From e637b774416775d09540070ceecf972c59070d90 Mon Sep 17 00:00:00 2001 From: Geert Uytterhoeven Date: Tue, 29 Sep 2026 14:25:56 +0200 Subject: [PATCH 0001/2102] firmware: arm_scmi: Update ARM_SCMI_HAVE_TRANSPORT rationale Not enabling any transports no longer breaks the build. Fixes: c0397c85b53d0bc6 ("firmware: arm_scmi: Use WARN_ON() to check configured transports") Signed-off-by: Geert Uytterhoeven Link: https://patch.msgid.link/48c4bed8036dcb55f554f513ce2ae61807c5677d.1790684637.git.geert+renesas@glider.be Signed-off-by: Sudeep Holla --- drivers/firmware/arm_scmi/transports/Kconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/firmware/arm_scmi/transports/Kconfig b/drivers/firmware/arm_scmi/transports/Kconfig index 0e34fbf2505323..6ba0dcb86204d7 100644 --- a/drivers/firmware/arm_scmi/transports/Kconfig +++ b/drivers/firmware/arm_scmi/transports/Kconfig @@ -5,7 +5,7 @@ config ARM_SCMI_HAVE_TRANSPORT bool help This declares whether at least one SCMI transport has been configured. - Used to trigger a build bug when trying to build SCMI without any + Used to trigger a runtime warning when enabling SCMI without any configured transport. config ARM_SCMI_HAVE_SHMEM From 3b0c8dd5a8d57dd143f31e7a042ad5737663b312 Mon Sep 17 00:00:00 2001 From: Sudeep Holla Date: Mon, 5 Oct 2026 10:53:10 +0100 Subject: [PATCH 0002/2102] firmware: arm_scmi: Avoid protocol devices in exclusive raw mode Since standard protocol devices are created without a driver request, rejecting SCMI driver registration is no longer enough to prevent them from appearing when raw mode is enabled without coexistence. When raw-mode debugfs setup succeeds, scmi_probe() returns success before protocol enumeration, so it does not normally create those devices. That early return is not sufficient: scmi_device_create() is exported and can be called later. Skip protocol-device creation in exclusive raw mode, including named non-transport requests. Keep named transport devices so raw mode can still set up its channels. Share the raw-mode condition and transport name check with the existing bus paths. Cc: Hans de Goede Fixes: aac4e67d6eb9 ("firmware: arm_scmi: Always create devices for standard protocols") Reviewed-by: Hans de Goede Tested-by: Peng Fan #i.MX95 EVK Link: https://patch.msgid.link/20261005-scmi_bus_fixes-v3-1-d9bada32ed38@kernel.org Signed-off-by: Sudeep Holla --- drivers/firmware/arm_scmi/bus.c | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/drivers/firmware/arm_scmi/bus.c b/drivers/firmware/arm_scmi/bus.c index 25197197db8e1a..f2e2ed56bc326f 100644 --- a/drivers/firmware/arm_scmi/bus.c +++ b/drivers/firmware/arm_scmi/bus.c @@ -36,6 +36,12 @@ struct scmi_requested_dev { /* Track globally the SCMI SystemPower protocol device. */ static struct scmi_device *scmi_syspower_registered; +static bool scmi_raw_mode_only(void) +{ + return IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT) && + !IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT_COEX); +} + /** * scmi_protocol_device_request - Helper to request a device * @@ -60,8 +66,7 @@ static int scmi_protocol_device_request(const struct scmi_device_id *id_table) pr_debug("Requesting SCMI device (%s) for protocol %x\n", id_table->name, id_table->protocol_id); - if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT) && - !IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT_COEX)) { + if (scmi_raw_mode_only()) { pr_warn("SCMI Raw mode active. Rejecting '%s'/0x%02X\n", id_table->name, id_table->protocol_id); return -EINVAL; @@ -210,12 +215,17 @@ scmi_protocol_table_unregister(const struct scmi_device_id *id_table) scmi_protocol_device_unrequest(entry); } -static bool scmi_device_is_transport(const struct scmi_device *scmi_dev) +static bool scmi_device_name_is_transport(const char *name) { - return !strncmp(scmi_dev->name, SCMI_TRANSPORT_DEVNAME_PREFIX, + return !strncmp(name, SCMI_TRANSPORT_DEVNAME_PREFIX, strlen(SCMI_TRANSPORT_DEVNAME_PREFIX)); } +static bool scmi_device_is_transport(const struct scmi_device *scmi_dev) +{ + return scmi_device_name_is_transport(scmi_dev->name); +} + static int __scmi_dev_match_by_id_table(struct scmi_device *scmi_dev, const struct scmi_device_id *id_table, bool skip_transport) @@ -591,6 +601,11 @@ struct scmi_device *scmi_device_create(struct fwnode_handle *fwnode, struct scmi_requested_dev *rdev; struct scmi_device *sdev, *scmi_dev = NULL; + /* Exclusive raw mode still needs transport devices for its channels. */ + if (scmi_raw_mode_only() && + (!name || !scmi_device_name_is_transport(name))) + return NULL; + if (name) return _scmi_device_create(fwnode, parent, protocol, name); From 00e30413150952ba36bda9e691da332a03672ec9 Mon Sep 17 00:00:00 2001 From: Sudeep Holla Date: Mon, 5 Oct 2026 10:53:11 +0100 Subject: [PATCH 0003/2102] firmware: arm_scmi: Skip requests for standard protocol devices The SCMI core creates devices for the standard protocol IDs during protocol enumeration, without waiting for an SCMI driver request. Recording a request for one of these devices also rejects a second driver registering the same protocol/name pair. When the first driver unregisters, unrequesting that pair destroys the core-created device. No other driver can be bound to it at that point, but removing it also removes the device that a later driver could bind to or use for module autoloading. Skip request tracking for standard devices. Keep request tracking and rollback for nonstandard devices unchanged. Reviewed-by: Hans de Goede Tested-by: Peng Fan #i.MX95 EVK Link: https://patch.msgid.link/20261005-scmi_bus_fixes-v3-2-d9bada32ed38@kernel.org Signed-off-by: Sudeep Holla --- drivers/firmware/arm_scmi/bus.c | 77 ++++++++++++++++++--------------- 1 file changed, 41 insertions(+), 36 deletions(-) diff --git a/drivers/firmware/arm_scmi/bus.c b/drivers/firmware/arm_scmi/bus.c index f2e2ed56bc326f..ed5bed545030e0 100644 --- a/drivers/firmware/arm_scmi/bus.c +++ b/drivers/firmware/arm_scmi/bus.c @@ -186,12 +186,44 @@ static void scmi_protocol_device_unrequest(const struct scmi_device_id *id_table } } +/* Standard protocols table */ +static const struct scmi_device_id scmi_std_id_table[] = { + { SCMI_PROTOCOL_POWER, "genpd" }, + { SCMI_PROTOCOL_SYSTEM, "syspower" }, + { SCMI_PROTOCOL_PERF, "perf" }, + { SCMI_PROTOCOL_PERF, "cpufreq" }, + { SCMI_PROTOCOL_CLOCK, "clocks" }, + { SCMI_PROTOCOL_SENSOR, "hwmon" }, + { SCMI_PROTOCOL_SENSOR, "iiodev" }, + { SCMI_PROTOCOL_RESET, "reset" }, + { SCMI_PROTOCOL_VOLTAGE, "regulator" }, + { SCMI_PROTOCOL_POWERCAP, "powercap" }, + { SCMI_PROTOCOL_PINCTRL, "pinctrl" }, + { SCMI_PROTOCOL_PINCTRL, "pinctrl-imx" }, + { }, +}; + +static bool scmi_device_id_in_std_id_table(const struct scmi_device_id *id) +{ + for (int i = 0; scmi_std_id_table[i].name[0]; i++) { + if (scmi_std_id_table[i].protocol_id == id->protocol_id && + !strcmp(scmi_std_id_table[i].name, id->name)) + return true; + } + + return false; +} + static int scmi_protocol_table_register(const struct scmi_device_id *id_table) { const struct scmi_device_id *entry; int ret; for (entry = id_table; entry->name[0]; entry++) { + /* Skip standard devices as they are created unconditionally */ + if (scmi_device_id_in_std_id_table(entry)) + continue; + ret = scmi_protocol_device_request(entry); if (ret) goto err_unrequest; @@ -200,8 +232,11 @@ static int scmi_protocol_table_register(const struct scmi_device_id *id_table) return 0; err_unrequest: - while (entry != id_table) - scmi_protocol_device_unrequest(--entry); + while (entry != id_table) { + --entry; + if (!scmi_device_id_in_std_id_table(entry)) + scmi_protocol_device_unrequest(entry); + } return ret; } @@ -211,8 +246,10 @@ scmi_protocol_table_unregister(const struct scmi_device_id *id_table) { const struct scmi_device_id *entry; - for (entry = id_table; entry->name[0]; entry++) - scmi_protocol_device_unrequest(entry); + for (entry = id_table; entry->name[0]; entry++) { + if (!scmi_device_id_in_std_id_table(entry)) + scmi_protocol_device_unrequest(entry); + } } static bool scmi_device_name_is_transport(const char *name) @@ -542,34 +579,6 @@ _scmi_device_create(struct fwnode_handle *fwnode, struct device *parent, return sdev; } -/* Standard protocols table */ -static const struct scmi_device_id scmi_std_id_table[] = { - { SCMI_PROTOCOL_POWER, "genpd" }, - { SCMI_PROTOCOL_SYSTEM, "syspower" }, - { SCMI_PROTOCOL_PERF, "perf" }, - { SCMI_PROTOCOL_PERF, "cpufreq" }, - { SCMI_PROTOCOL_CLOCK, "clocks" }, - { SCMI_PROTOCOL_SENSOR, "hwmon" }, - { SCMI_PROTOCOL_SENSOR, "iiodev" }, - { SCMI_PROTOCOL_RESET, "reset" }, - { SCMI_PROTOCOL_VOLTAGE, "regulator" }, - { SCMI_PROTOCOL_POWERCAP, "powercap" }, - { SCMI_PROTOCOL_PINCTRL, "pinctrl" }, - { SCMI_PROTOCOL_PINCTRL, "pinctrl-imx" }, - { }, -}; - -static bool scmi_device_id_in_std_id_table(const struct scmi_device_id *id) -{ - for (int i = 0; scmi_std_id_table[i].name[0]; i++) { - if (scmi_std_id_table[i].protocol_id == id->protocol_id && - !strcmp(scmi_std_id_table[i].name, id->name)) - return true; - } - - return false; -} - /** * scmi_device_create - A method to create one or more SCMI devices * @@ -634,10 +643,6 @@ struct scmi_device *scmi_device_create(struct fwnode_handle *fwnode, /* Walk the list of requested devices for protocol and create them */ list_for_each_entry(rdev, phead, node) { - /* Standard proto matches already have their dev created above */ - if (scmi_device_id_in_std_id_table(rdev->id_table)) - continue; - sdev = _scmi_device_create(fwnode, parent, rdev->id_table->protocol_id, rdev->id_table->name); From 5ac351938cae58c5cd1b356f9d0aae2e243c11ad Mon Sep 17 00:00:00 2001 From: "Rob Herring (Arm)" Date: Mon, 5 Oct 2026 16:05:06 -0500 Subject: [PATCH 0004/2102] arm64: dts: arm: corstone1000-a320: Fix GIC redistributor region size The Arm Corstone1000-A320 has a GICv4 which means the redistributor region should be 4x256KB rather than 512KB. This issue didn't become apparent as SMP was disabled as a work-around in early versions of the FVP. Fixes: 87599f1843d3 ("arm64: dts: arm/corstone1000: Add corstone-1000-a320") Reviewed-by: Liviu Dudau Signed-off-by: Rob Herring (Arm) Link: https://patch.msgid.link/20261005210506.2118052-2-robh@kernel.org Signed-off-by: Sudeep Holla --- arch/arm64/boot/dts/arm/corstone1000-a320.dtsi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/arm/corstone1000-a320.dtsi b/arch/arm64/boot/dts/arm/corstone1000-a320.dtsi index f0937914350c5d..f895a024fc9208 100644 --- a/arch/arm64/boot/dts/arm/corstone1000-a320.dtsi +++ b/arch/arm64/boot/dts/arm/corstone1000-a320.dtsi @@ -73,7 +73,7 @@ #size-cells = <1>; interrupt-controller; reg = <0x1c000000 0x10000>, - <0x1c040000 0x80000>; + <0x1c040000 0x100000>; interrupts = ; }; From 685e05f664d64882b466394bbcdae5bfd3e688c4 Mon Sep 17 00:00:00 2001 From: Sudeep Holla Date: Mon, 5 Oct 2026 10:53:12 +0100 Subject: [PATCH 0005/2102] pinctrl: imx: Match the standard SCMI pinctrl device Use the standard "pinctrl" SCMI device name instead of the i.MX-specific "pinctrl-imx" name. Standard devices no longer have exclusive request tracking, so the i.MX and generic pinctrl drivers can register for the same protocol/name pair. Their probe checks select the appropriate driver for the platform. This solves the issue that occurs when both "pinmux" and "pinmux-imx" devices that share the same fwnode as only the first device registered is assigned as the owner of the fwnode. If this owner device fails to probe (e.g., its driver is blocklisted or missing), it never reaches the driver_bound() stage and the system skips cleaning up its supplier links. Even if a alternative device binds successfully, the system still looks to the broken original owner. As a result, all dependent hardware components (I2C, SPI, UART, USB, MMC, PCIe) defer probing forever, halting the boot process. Note that the solution doesn't support same fwnode being shared by multiple devices and associated fw_devlink feature. Cc: Pengutronix Kernel Team Cc: NXP S32 Linux Team Reported-by: Peng Fan Closes: https://lore.kernel.org/all/20260928-driver-core-v1-1-0846bb8e0f32@nxp.com Reviewed-by: Peng Fan Tested-by: Peng Fan #i.MX95 EVK Acked-by: Linus Walleij Link: https://patch.msgid.link/20261005-scmi_bus_fixes-v3-3-d9bada32ed38@kernel.org Signed-off-by: Sudeep Holla --- drivers/firmware/arm_scmi/bus.c | 1 - drivers/pinctrl/freescale/pinctrl-imx-scmi.c | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/firmware/arm_scmi/bus.c b/drivers/firmware/arm_scmi/bus.c index ed5bed545030e0..eef47d2054cd1e 100644 --- a/drivers/firmware/arm_scmi/bus.c +++ b/drivers/firmware/arm_scmi/bus.c @@ -199,7 +199,6 @@ static const struct scmi_device_id scmi_std_id_table[] = { { SCMI_PROTOCOL_VOLTAGE, "regulator" }, { SCMI_PROTOCOL_POWERCAP, "powercap" }, { SCMI_PROTOCOL_PINCTRL, "pinctrl" }, - { SCMI_PROTOCOL_PINCTRL, "pinctrl-imx" }, { }, }; diff --git a/drivers/pinctrl/freescale/pinctrl-imx-scmi.c b/drivers/pinctrl/freescale/pinctrl-imx-scmi.c index 613552e3507039..b259a526ccc16d 100644 --- a/drivers/pinctrl/freescale/pinctrl-imx-scmi.c +++ b/drivers/pinctrl/freescale/pinctrl-imx-scmi.c @@ -354,7 +354,7 @@ static int scmi_pinctrl_imx_probe(struct scmi_device *sdev) } static const struct scmi_device_id scmi_id_table[] = { - { SCMI_PROTOCOL_PINCTRL, "pinctrl-imx" }, + { SCMI_PROTOCOL_PINCTRL, "pinctrl" }, { } }; MODULE_DEVICE_TABLE(scmi, scmi_id_table); From 59d22f7a4dfe9979045391082ad7c8492cb1ad70 Mon Sep 17 00:00:00 2001 From: Sudeep Holla Date: Mon, 5 Oct 2026 10:53:13 +0100 Subject: [PATCH 0006/2102] firmware: arm_scmi: Skip unused performance-domain devices The SCMI performance-domain driver uses the named "perf" device only when its firmware node declares #power-domain-cells. Otherwise its probe returns without registering a provider, while the same SCMI protocol may still be needed by the separate "cpufreq" device. Do not create the "perf" device when the provider property is absent. This avoids an unnecessary device claiming the protocol fwnode and leaves cpufreq creation unchanged. Update the device-creation contract to document that an intentionally omitted named device returns NULL. Reviewed-by: Hans de Goede Tested-by: Peng Fan #i.MX95 EVK Link: https://patch.msgid.link/20261005-scmi_bus_fixes-v3-4-d9bada32ed38@kernel.org Signed-off-by: Sudeep Holla --- drivers/firmware/arm_scmi/bus.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/drivers/firmware/arm_scmi/bus.c b/drivers/firmware/arm_scmi/bus.c index eef47d2054cd1e..7613ea2893ef92 100644 --- a/drivers/firmware/arm_scmi/bus.c +++ b/drivers/firmware/arm_scmi/bus.c @@ -570,6 +570,11 @@ _scmi_device_create(struct fwnode_handle *fwnode, struct device *parent, { struct scmi_device *sdev; + /* The perf device is only needed when it provides power domains. */ + if (protocol == SCMI_PROTOCOL_PERF && !strcmp(name, "perf") && + !fwnode_property_present(fwnode, "#power-domain-cells")) + return NULL; + sdev = __scmi_device_create(fwnode, parent, protocol, name); if (!sdev) pr_err("(%pfwf) Failed to create device - protocol 0x%x (%s)\n", @@ -596,10 +601,8 @@ _scmi_device_create(struct fwnode_handle *fwnode, struct device *parent, * * Return: The created device (or one of them if @name was NOT provided and * multiple devices were created) or NULL if no device was created; - * note that NULL indicates an error ONLY in case a specific @name - * was provided: when @name param was not provided, a number of devices - * could have been potentially created for a whole protocol, unless no - * device was found to have been requested for that specific protocol. + * note that NULL can also indicate that a named device is not needed + * for this fwnode, or that no device was requested when @name is NULL. */ struct scmi_device *scmi_device_create(struct fwnode_handle *fwnode, struct device *parent, int protocol, From 1df7f369075d7e8f7794981995a5103f1963bab7 Mon Sep 17 00:00:00 2001 From: Joonhoe Kim <26rote@gmail.com> Date: Wed, 7 Oct 2026 21:40:01 +0900 Subject: [PATCH 0007/2102] pinctrl: qcom: kaanapali: add the I2C strong pull-up bit The Kaanapali TLMM has the I2C pull-up control in bit 13 of the pin config register, like SM8550, SM8650 and X1E80100, but the driver does not describe it, so "bias-pull-up = <2200>" cannot select the strong pull-up. The downstream kernel sets it on the camera CCI pins (config 0x2007). On a Lenovo TB323FU tablet, with only the weak pull-up every CCI transfer on the two sensor buses times out; with bit 13 set the sensors answer and their chip IDs read correctly. Fixes: 35ff9c6b318a ("pinctrl: qcom: add the tlmm driver for Kaanapali platforms") Assisted-by: LLM Signed-off-by: Joonhoe Kim <26rote@gmail.com> Link: https://patch.msgid.link/20261007124001.1724-1-26rote@gmail.com Signed-off-by: Bartosz Golaszewski --- drivers/pinctrl/qcom/pinctrl-kaanapali.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/pinctrl/qcom/pinctrl-kaanapali.c b/drivers/pinctrl/qcom/pinctrl-kaanapali.c index e95ac064b84ce8..e9351e29d38ed9 100644 --- a/drivers/pinctrl/qcom/pinctrl-kaanapali.c +++ b/drivers/pinctrl/qcom/pinctrl-kaanapali.c @@ -37,6 +37,7 @@ .mux_bit = 2, \ .pull_bit = 0, \ .drv_bit = 6, \ + .i2c_pull_bit = 13, \ .egpio_enable = 12, \ .egpio_present = 11, \ .oe_bit = 9, \ From d36e0b560483991bc63b7b766f82396e1bf7ec33 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 09:03:09 -0700 Subject: [PATCH 0008/2102] assoc_array: correct the documentation of get_key_chunk()'s level argument assoc_array.rst says the level passed to get_key_chunk() will be a multiple of ASSOC_ARRAY_KEY_CHUNK_SIZE, and asks for the chunk starting at that bit. assoc_array_walk() after a shortcut, and both insertion paths, pass the level of a node, which is any multiple of ASSOC_ARRAY_LEVEL_STEP. Each then shifts the chunk it gets back right by level & ASSOC_ARRAY_KEY_CHUNK_MASK, so what it wants is the chunk that contains that bit. The keyring code copes, because keyring_get_key_chunk() divides the level by ASSOC_ARRAY_KEY_CHUNK_SIZE before using it. An implementation written to the documentation does not: one that returns a one-word key for level 0 and nothing for any other level files leaves under the wrong slot the first time a node is split, and a later insertion hits the BUG_ON() after found_slot_for_multiple_occupancy in assoc_array_insert_into_terminal_node(). Say what the code expects. get_object_key_chunk() is documented as "the previous function", so this covers it too. Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- Documentation/core-api/assoc_array.rst | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Documentation/core-api/assoc_array.rst b/Documentation/core-api/assoc_array.rst index 19d89f92bf8da8..c5ada1bff06fa2 100644 --- a/Documentation/core-api/assoc_array.rst +++ b/Documentation/core-api/assoc_array.rst @@ -123,10 +123,12 @@ This points to a number of methods, all of which need to be provided: unsigned long (*get_key_chunk)(const void *index_key, int level); - This should return a chunk of caller-supplied index key starting at the - *bit* position given by the level argument. The level argument will be a - multiple of ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` and the function should return - ``ASSOC_ARRAY_KEY_CHUNK_SIZE bits``. No error is possible. + This should return the ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` bits of + caller-supplied index key that contain the *bit* position given by the + level argument, starting at level rounded down to a multiple of + ``ASSOC_ARRAY_KEY_CHUNK_SIZE``. The level is often that of a node, which + is a multiple of ``ASSOC_ARRAY_LEVEL_STEP``, so the function has to do the + rounding. No error is possible. 2. Get a chunk of an object's index key:: From 2a62c32760a8fbf464a7388853d19bc62c5cc423 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 09:03:19 -0700 Subject: [PATCH 0009/2102] assoc_array: don't lose objects when a shortcut is split on a word boundary When assoc_array_insert_mid_shortcut() splits a shortcut at level diff, the new shortcut in front of the split, new_s0, gets the first round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE) bits of the old shortcut's index key, and the bits from diff onwards are then cleared from its last word: blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK); new_s0->index_key[keylen - 1] &= ~blank; When diff is a multiple of ASSOC_ARRAY_KEY_CHUNK_SIZE, the shift is 0, blank is all ones, and the whole last word is cleared, although all of it lies below diff. A walk then compares the key it is looking for against that zeroed word, takes the shortcut to point elsewhere, and every object below it can no longer be found. assoc_array_insert_into_terminal_node() trims a new shortcut's key the same way, and only when the level is not a multiple of the chunk size. Do the same here. Found by a userspace build of the array with a test that inserts, in order, string keys whose first word is their length and the rest their bytes. The 102nd key split a shortcut at bit 256, and 76 of the keys already in the array could no longer be found; AddressSanitizer also reported assoc_array_walk() reading a word past the end of a shortcut's index key. With this change the test passes, and AddressSanitizer and UndefinedBehaviorSanitizer report nothing. Fixes: 3cb989501c26 ("Add a generic associative array implementation.") Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index b6c9723e12ced5..20ef69e0378017 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -865,9 +865,11 @@ static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit, memcpy(new_s0->index_key, shortcut->index_key, flex_array_size(new_s0, index_key, keylen)); - blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK); - pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank); - new_s0->index_key[keylen - 1] &= ~blank; + if (diff & ASSOC_ARRAY_KEY_CHUNK_MASK) { + blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK); + pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank); + new_s0->index_key[keylen - 1] &= ~blank; + } } else { pr_devel("no pre-shortcut\n"); edit->set[0].to = assoc_array_node_to_ptr(new_n0); From 20b436c1ae8d37032f888c725915729830dc52f2 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 09:56:16 -0700 Subject: [PATCH 0010/2102] assoc_array: don't lose objects when a root shortcut is split at level 4 assoc_array_insert_mid_shortcut() takes level, the level of the node holding the shortcut as assoc_array_walk() reports it, and adds ASSOC_ARRAY_LEVEL_STEP to get the level of a node in that shortcut's place. If the new key first differs from the shortcut no further in than that, no shortcut is made in front of the split, and new_n0 takes the old shortcut's place directly. A shortcut at the root is held by no node. assoc_array_walk() reports level 0 for it, and whatever takes its place is the root, which is read at level 0. So when the new key first differs from a root shortcut in bits 4-7, diff is 4, no shortcut is made in front, and new_n0, whose slots are indexed by bits 4-7, becomes the root and is indexed by bits 0-3. Objects already in the array can no longer be found, and the new one lands in a slot its key does not select. Eighteen keys are enough: seventeen that agree on bits 0-7 make the root a shortcut, and one that agrees with them on bits 0-3 only splits it. Three of the eighteen objects can then not be found, and inserting one of those keys again adds a second object instead of replacing it. Only add the step for a shortcut that hangs from a node. A root shortcut split at level 4 then gets a shortcut in front of the split that ends at level 4, as assoc_array_insert_into_terminal_node() already makes when the leaves of a full root node first differ there. Found by a userspace test that builds a shortcut ending at every level and splits it at every level inside it, from the root and from a node: every split of a root shortcut at level 4 failed, and nothing else did. Fixes: 3cb989501c26 ("Add a generic associative array implementation.") Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index 20ef69e0378017..5611da338e1c8d 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -843,7 +843,8 @@ static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit, * zero length - otherwise we just connect the new node directly to the * parent. */ - level += ASSOC_ARRAY_LEVEL_STEP; + if (shortcut->back_pointer) + level += ASSOC_ARRAY_LEVEL_STEP; if (diff > level) { pr_devel("pre-shortcut %d...%d\n", level, diff); keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); From a624a7ce7d85b514d949b6c7a049f43ac96f3257 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 10:25:12 -0700 Subject: [PATCH 0011/2102] assoc_array: move in-place insertion into a function of its own assoc_array_insert_into_terminal_node() is over 300 lines and does four jobs, joined by gotos: putting the new leaf in place of a matching one or in a free slot, working out the segment of each leaf, splitting the node, and replacing the node with a shortcut. The last two share the function's tail, which installs the replacement where the node was. Move the jobs into functions of their own, one per commit, starting with the two cases that need no new node: assoc_array_insert_in_node(). No functional change. Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 68 ++++++++++++++++++++++++++++++----------------- 1 file changed, 43 insertions(+), 25 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index 5611da338e1c8d..11b92b6bb8e1cb 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -470,33 +470,17 @@ static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit) } /* - * Handle insertion into a terminal node. + * Insert into a terminal node without changing its shape, if that can be + * done: in place of a leaf with the same index key, or in a free slot. */ -static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, - const struct assoc_array_ops *ops, - const void *index_key, - struct assoc_array_walk_result *result) +static bool assoc_array_insert_in_node(struct assoc_array_edit *edit, + const struct assoc_array_ops *ops, + const void *index_key, + struct assoc_array_node *node) { - struct assoc_array_shortcut *shortcut, *new_s0; - struct assoc_array_node *node, *new_n0, *new_n1, *side; struct assoc_array_ptr *ptr; - unsigned long dissimilarity, base_seg, blank; - size_t keylen; - bool have_meta; - int level, diff; - int slot, next_slot, free_slot, i, j; - - node = result->terminal_node.node; - level = result->terminal_node.level; - edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; - - pr_devel("-->%s()\n", __func__); + int free_slot, i; - /* We arrived at a node which doesn't have an onward node or shortcut - * pointer that we have to follow. This means that (a) the leaf we - * want must go here (either by insertion or replacement) or (b) we - * need to split this node and insert in one of the fragments. - */ free_slot = -1; /* Firstly, we have to check the leaves in this node to see if there's @@ -514,7 +498,6 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, pr_devel("replace in slot %d\n", i); edit->leaf_p = &node->slots[i]; edit->dead_leaf = node->slots[i]; - pr_devel("<--%s() = ok [replace]\n", __func__); return true; } } @@ -526,7 +509,42 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, pr_devel("insert in free slot %d\n", free_slot); edit->leaf_p = &node->slots[free_slot]; edit->adjust_count_on = node; - pr_devel("<--%s() = ok [insert]\n", __func__); + return true; + } + + return false; +} + +/* + * Handle insertion into a terminal node. + */ +static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, + const struct assoc_array_ops *ops, + const void *index_key, + struct assoc_array_walk_result *result) +{ + struct assoc_array_shortcut *shortcut, *new_s0; + struct assoc_array_node *node, *new_n0, *new_n1, *side; + struct assoc_array_ptr *ptr; + unsigned long dissimilarity, base_seg, blank; + size_t keylen; + bool have_meta; + int level, diff; + int slot, next_slot, free_slot, i, j; + + node = result->terminal_node.node; + level = result->terminal_node.level; + edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; + + pr_devel("-->%s()\n", __func__); + + /* We arrived at a node which doesn't have an onward node or shortcut + * pointer that we have to follow. This means that (a) the leaf we + * want must go here (either by insertion or replacement) or (b) we + * need to split this node and insert in one of the fragments. + */ + if (assoc_array_insert_in_node(edit, ops, index_key, node)) { + pr_devel("<--%s() = ok [in node]\n", __func__); return true; } From 1159eaf9acb3de1417fb86b382b5e41b46eb17a4 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 10:25:12 -0700 Subject: [PATCH 0012/2102] assoc_array: fill the segment cache in one place The loop that records the segment of each leaf in a full node is written out twice in assoc_array_insert_into_terminal_node(): for the node at its own level, and again at the far end of a shortcut that replaces it. Make it assoc_array_fill_segment_cache(). The second copy did not look for metadata pointers, because that path is only taken for a node holding nothing but leaves, so the function finds none there. The new key's segment is still set by each caller, from the walk the first time and from the key the second. No functional change. Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 56 +++++++++++++++++++++++++++++------------------ 1 file changed, 35 insertions(+), 21 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index 11b92b6bb8e1cb..38af851326e54f 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -515,6 +515,38 @@ static bool assoc_array_insert_in_node(struct assoc_array_edit *edit, return false; } +/* + * Fill in the edit script's segment cache for a full node: the segment at + * this level of each leaf's index key, or 0xff for a metadata pointer. + * The new key's segment, in the last entry, is left to the caller. Returns + * true if there are any metadata pointers. + */ +static bool assoc_array_fill_segment_cache(struct assoc_array_edit *edit, + const struct assoc_array_ops *ops, + const struct assoc_array_node *node, + int level) +{ + struct assoc_array_ptr *ptr; + unsigned long base_seg; + bool have_meta; + int i; + + have_meta = false; + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { + ptr = node->slots[i]; + if (assoc_array_ptr_is_meta(ptr)) { + edit->segment_cache[i] = 0xff; + have_meta = true; + continue; + } + base_seg = ops->get_object_key_chunk( + assoc_array_ptr_to_leaf(ptr), level); + base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; + edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; + } + return have_meta; +} + /* * Handle insertion into a terminal node. */ @@ -534,7 +566,6 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, node = result->terminal_node.node; level = result->terminal_node.level; - edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; pr_devel("-->%s()\n", __func__); @@ -566,19 +597,8 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, /* We need to find out how similar the leaves are. */ pr_devel("no spare slots\n"); - have_meta = false; - for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { - ptr = node->slots[i]; - if (assoc_array_ptr_is_meta(ptr)) { - edit->segment_cache[i] = 0xff; - have_meta = true; - continue; - } - base_seg = ops->get_object_key_chunk( - assoc_array_ptr_to_leaf(ptr), level); - base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; - edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; - } + have_meta = assoc_array_fill_segment_cache(edit, ops, node, level); + edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; if (have_meta) { pr_devel("have meta\n"); @@ -791,13 +811,7 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, /* This now reduces to a node splitting exercise for which we'll need * to regenerate the disparity table. */ - for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { - ptr = node->slots[i]; - base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr), - level); - base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; - edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; - } + assoc_array_fill_segment_cache(edit, ops, node, level); base_seg = ops->get_key_chunk(index_key, level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; From 3c99a07bc82b051771ce0eb69274aceb9abf1eb7 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 10:25:12 -0700 Subject: [PATCH 0013/2102] assoc_array: move node splitting into a function of its own Move the code after the do_split_node label into assoc_array_split_node(), which both the split path and the shortcut path still reach through that label. It sets new_n1's back pointer itself, which both paths did before jumping there, and it no longer sets new_n1's parent slot to -1 first: it always sets the real one. No functional change. Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 194 +++++++++++++++++++++++++--------------------- 1 file changed, 104 insertions(+), 90 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index 38af851326e54f..690446b468f1cf 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -547,6 +547,106 @@ static bool assoc_array_fill_segment_cache(struct assoc_array_edit *edit, return have_meta; } +/* + * Split a full node into new_n0, which takes its place, and new_n1, below + * new_n0 in the slot of a segment that at least two of the leaves share, + * the new one included. The caller has filled in the segment cache and + * set new_n0's back pointer and parent slot. + */ +static void assoc_array_split_node(struct assoc_array_edit *edit, + struct assoc_array_node *node, + struct assoc_array_node *new_n0, + struct assoc_array_node *new_n1) +{ + struct assoc_array_shortcut *shortcut; + struct assoc_array_node *side; + struct assoc_array_ptr *ptr; + int slot, next_slot, free_slot, i, j; + + pr_devel("split node\n"); + + new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); + new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; + new_n1->nr_leaves_on_branch = 0; + + /* Begin by finding two matching leaves. There have to be at least two + * that match - even if there are meta pointers - because any leaf that + * would match a slot with a meta pointer in it must be somewhere + * behind that meta pointer and cannot be here. Further, given N + * remaining leaf slots, we now have N+1 leaves to go in them. + */ + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { + slot = edit->segment_cache[i]; + if (slot != 0xff) + for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++) + if (edit->segment_cache[j] == slot) + goto found_slot_for_multiple_occupancy; + } +found_slot_for_multiple_occupancy: + pr_devel("same slot: %x %x [%02x]\n", i, j, slot); + BUG_ON(i >= ASSOC_ARRAY_FAN_OUT); + BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1); + BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT); + + new_n1->parent_slot = slot; + + /* Metadata pointers cannot change slot */ + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) + if (assoc_array_ptr_is_meta(node->slots[i])) + new_n0->slots[i] = node->slots[i]; + else + new_n0->slots[i] = NULL; + BUG_ON(new_n0->slots[slot] != NULL); + new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1); + + /* Filter the leaf pointers between the new nodes */ + free_slot = -1; + next_slot = 0; + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { + if (assoc_array_ptr_is_meta(node->slots[i])) + continue; + if (edit->segment_cache[i] == slot) { + new_n1->slots[next_slot++] = node->slots[i]; + new_n1->nr_leaves_on_branch++; + } else { + do { + free_slot++; + } while (new_n0->slots[free_slot] != NULL); + new_n0->slots[free_slot] = node->slots[i]; + } + } + + pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot); + + if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) { + do { + free_slot++; + } while (new_n0->slots[free_slot] != NULL); + edit->leaf_p = &new_n0->slots[free_slot]; + edit->adjust_count_on = new_n0; + } else { + edit->leaf_p = &new_n1->slots[next_slot++]; + edit->adjust_count_on = new_n1; + } + + BUG_ON(next_slot <= 1); + + edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0); + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { + if (edit->segment_cache[i] == 0xff) { + ptr = node->slots[i]; + BUG_ON(assoc_array_ptr_is_leaf(ptr)); + if (assoc_array_ptr_is_node(ptr)) { + side = assoc_array_ptr_to_node(ptr); + edit->set_backpointers[i] = &side->back_pointer; + } else { + shortcut = assoc_array_ptr_to_shortcut(ptr); + edit->set_backpointers[i] = &shortcut->back_pointer; + } + } + } +} + /* * Handle insertion into a terminal node. */ @@ -555,14 +655,14 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, const void *index_key, struct assoc_array_walk_result *result) { - struct assoc_array_shortcut *shortcut, *new_s0; - struct assoc_array_node *node, *new_n0, *new_n1, *side; + struct assoc_array_shortcut *new_s0; + struct assoc_array_node *node, *new_n0, *new_n1; struct assoc_array_ptr *ptr; unsigned long dissimilarity, base_seg, blank; size_t keylen; bool have_meta; int level, diff; - int slot, next_slot, free_slot, i, j; + int i; node = result->terminal_node.node; level = result->terminal_node.level; @@ -632,8 +732,6 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, } split_node: - pr_devel("split node\n"); - /* We need to split the current node. The node must contain anything * from a single leaf (in the one leaf case, this leaf will cluster * with the new leaf) and the rest meta-pointers, to all leaves, some @@ -652,91 +750,9 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, edit->set[0].to = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; - new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); - new_n1->parent_slot = -1; /* Need to calculate this */ do_split_node: - pr_devel("do_split_node\n"); - - new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; - new_n1->nr_leaves_on_branch = 0; - - /* Begin by finding two matching leaves. There have to be at least two - * that match - even if there are meta pointers - because any leaf that - * would match a slot with a meta pointer in it must be somewhere - * behind that meta pointer and cannot be here. Further, given N - * remaining leaf slots, we now have N+1 leaves to go in them. - */ - for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { - slot = edit->segment_cache[i]; - if (slot != 0xff) - for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++) - if (edit->segment_cache[j] == slot) - goto found_slot_for_multiple_occupancy; - } -found_slot_for_multiple_occupancy: - pr_devel("same slot: %x %x [%02x]\n", i, j, slot); - BUG_ON(i >= ASSOC_ARRAY_FAN_OUT); - BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1); - BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT); - - new_n1->parent_slot = slot; - - /* Metadata pointers cannot change slot */ - for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) - if (assoc_array_ptr_is_meta(node->slots[i])) - new_n0->slots[i] = node->slots[i]; - else - new_n0->slots[i] = NULL; - BUG_ON(new_n0->slots[slot] != NULL); - new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1); - - /* Filter the leaf pointers between the new nodes */ - free_slot = -1; - next_slot = 0; - for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { - if (assoc_array_ptr_is_meta(node->slots[i])) - continue; - if (edit->segment_cache[i] == slot) { - new_n1->slots[next_slot++] = node->slots[i]; - new_n1->nr_leaves_on_branch++; - } else { - do { - free_slot++; - } while (new_n0->slots[free_slot] != NULL); - new_n0->slots[free_slot] = node->slots[i]; - } - } - - pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot); - - if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) { - do { - free_slot++; - } while (new_n0->slots[free_slot] != NULL); - edit->leaf_p = &new_n0->slots[free_slot]; - edit->adjust_count_on = new_n0; - } else { - edit->leaf_p = &new_n1->slots[next_slot++]; - edit->adjust_count_on = new_n1; - } - - BUG_ON(next_slot <= 1); - - edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0); - for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { - if (edit->segment_cache[i] == 0xff) { - ptr = node->slots[i]; - BUG_ON(assoc_array_ptr_is_leaf(ptr)); - if (assoc_array_ptr_is_node(ptr)) { - side = assoc_array_ptr_to_node(ptr); - edit->set_backpointers[i] = &side->back_pointer; - } else { - shortcut = assoc_array_ptr_to_shortcut(ptr); - edit->set_backpointers[i] = &shortcut->back_pointer; - } - } - } + assoc_array_split_node(edit, node, new_n0, new_n1); ptr = node->back_pointer; if (!ptr) @@ -791,8 +807,6 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, new_s0->next_node = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); new_n0->parent_slot = 0; - new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); - new_n1->parent_slot = -1; /* Need to calculate this */ new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK; pr_devel("skip_to_level = %d [diff %d]\n", level, diff); From fdc6124c55dd0c5aa8e3ec30e6425b4d423ada24 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 10:25:12 -0700 Subject: [PATCH 0014/2102] assoc_array: move shortcut creation into a function of its own Move the code after the all_leaves_cluster_together label into assoc_array_insert_shortcut(), which returns the new shortcut, or NULL when it cannot allocate one. The caller installs it and jumps to do_split_node as before. No functional change. Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 146 ++++++++++++++++++++++++++-------------------- 1 file changed, 82 insertions(+), 64 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index 690446b468f1cf..7f9afbcd40d710 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -647,6 +647,84 @@ static void assoc_array_split_node(struct assoc_array_edit *edit, } } +/* + * All the leaves, new and old, want to cluster together in this node in the + * same slot, so we have to replace this node with a shortcut to skip over + * the identical parts of the key, leading to new_n0. The caller then splits + * the leaves between new_n0 and new_n1 at the shortcut's far end, for which + * this fills in the segment cache. + */ +static struct assoc_array_shortcut * +assoc_array_insert_shortcut(struct assoc_array_edit *edit, + const struct assoc_array_ops *ops, + const void *index_key, + struct assoc_array_node *node, int level, + struct assoc_array_node *new_n0) +{ + struct assoc_array_shortcut *new_s0; + unsigned long base_seg, blank; + size_t keylen; + int diff, i; + + /* Firstly we need to work out where the leaves start diverging as a + * bit position into their keys so that we know how big the shortcut + * needs to be. + * + * We only need to make a single pass of N of the N+1 leaves because if + * any keys differ between themselves at bit X then at least one of + * them must also differ with the base key at bit X or before. + */ + pr_devel("all leaves cluster together\n"); + diff = INT_MAX; + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { + int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]), + index_key); + if (x < diff) { + BUG_ON(x < 0); + diff = x; + } + } + BUG_ON(diff == INT_MAX); + BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP); + + keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); + keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; + + new_s0 = kzalloc_flex(*new_s0, index_key, keylen); + if (!new_s0) + return NULL; + edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0); + + new_s0->back_pointer = node->back_pointer; + new_s0->parent_slot = node->parent_slot; + new_s0->next_node = assoc_array_node_to_ptr(new_n0); + new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); + new_n0->parent_slot = 0; + + new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK; + pr_devel("skip_to_level = %d [diff %d]\n", level, diff); + BUG_ON(level <= 0); + + for (i = 0; i < keylen; i++) + new_s0->index_key[i] = + ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE); + + if (level & ASSOC_ARRAY_KEY_CHUNK_MASK) { + blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK); + pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank); + new_s0->index_key[keylen - 1] &= ~blank; + } + + /* This now reduces to a node splitting exercise for which we'll need + * to regenerate the disparity table. + */ + assoc_array_fill_segment_cache(edit, ops, node, level); + base_seg = ops->get_key_chunk(index_key, level); + base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; + edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK; + return new_s0; +} + /* * Handle insertion into a terminal node. */ @@ -658,10 +736,9 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, struct assoc_array_shortcut *new_s0; struct assoc_array_node *node, *new_n0, *new_n1; struct assoc_array_ptr *ptr; - unsigned long dissimilarity, base_seg, blank; - size_t keylen; + unsigned long dissimilarity, base_seg; bool have_meta; - int level, diff; + int level; int i; node = result->terminal_node.node; @@ -766,70 +843,11 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, return true; all_leaves_cluster_together: - /* All the leaves, new and old, want to cluster together in this node - * in the same slot, so we have to replace this node with a shortcut to - * skip over the identical parts of the key and then place a pair of - * nodes, one inside the other, at the end of the shortcut and - * distribute the keys between them. - * - * Firstly we need to work out where the leaves start diverging as a - * bit position into their keys so that we know how big the shortcut - * needs to be. - * - * We only need to make a single pass of N of the N+1 leaves because if - * any keys differ between themselves at bit X then at least one of - * them must also differ with the base key at bit X or before. - */ - pr_devel("all leaves cluster together\n"); - diff = INT_MAX; - for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { - int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]), - index_key); - if (x < diff) { - BUG_ON(x < 0); - diff = x; - } - } - BUG_ON(diff == INT_MAX); - BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP); - - keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); - keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; - - new_s0 = kzalloc_flex(*new_s0, index_key, keylen); + new_s0 = assoc_array_insert_shortcut(edit, ops, index_key, + node, level, new_n0); if (!new_s0) return false; - edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0); - edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); - new_s0->back_pointer = node->back_pointer; - new_s0->parent_slot = node->parent_slot; - new_s0->next_node = assoc_array_node_to_ptr(new_n0); - new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); - new_n0->parent_slot = 0; - - new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK; - pr_devel("skip_to_level = %d [diff %d]\n", level, diff); - BUG_ON(level <= 0); - - for (i = 0; i < keylen; i++) - new_s0->index_key[i] = - ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE); - - if (level & ASSOC_ARRAY_KEY_CHUNK_MASK) { - blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK); - pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank); - new_s0->index_key[keylen - 1] &= ~blank; - } - - /* This now reduces to a node splitting exercise for which we'll need - * to regenerate the disparity table. - */ - assoc_array_fill_segment_cache(edit, ops, node, level); - - base_seg = ops->get_key_chunk(index_key, level); - base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; - edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK; goto do_split_node; } From c47aee71e14dd28d39fce95af83166d7a28a5f2b Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 10:25:12 -0700 Subject: [PATCH 0015/2102] assoc_array: choose between splitting a node and a shortcut without gotos With its jobs in functions, assoc_array_insert_into_terminal_node() comes down to one decision: replace the node with a shortcut when every leaf in it and the new key share one segment, or split it otherwise. Write that as an if and an else, in place of the labels split_node, do_split_node and all_leaves_cluster_together. Each branch now works out where its replacement goes from that replacement's own back pointer and parent slot, with assoc_array_parent_link(), rather than both using the node's. The two are the same today. None of the new functions is recursive, and gcc inlines all of them into assoc_array_insert(), whose stack frame is 240 bytes after this series against 224 before it, on an x86-64 defconfig. No functional change. Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 127 ++++++++++++++++++++++------------------------ 1 file changed, 61 insertions(+), 66 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index 7f9afbcd40d710..8bfdb0d5bc9a25 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -469,6 +469,21 @@ static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit) return true; } +/* + * The pointer that leads to a node or shortcut with the given back pointer + * and parent slot: the root, a slot in a node, or a shortcut's next node. + */ +static struct assoc_array_ptr **assoc_array_parent_link(struct assoc_array *array, + struct assoc_array_ptr *back_pointer, + int parent_slot) +{ + if (!back_pointer) + return &array->root; + if (assoc_array_ptr_is_node(back_pointer)) + return &assoc_array_ptr_to_node(back_pointer)->slots[parent_slot]; + return &assoc_array_ptr_to_shortcut(back_pointer)->next_node; +} + /* * Insert into a terminal node without changing its shape, if that can be * done: in place of a leaf with the same index key, or in a free slot. @@ -547,6 +562,20 @@ static bool assoc_array_fill_segment_cache(struct assoc_array_edit *edit, return have_meta; } +/* + * Whether the leaves of a full node and the new key all share one segment, + * so that splitting the node cannot make room. + */ +static bool assoc_array_all_one_segment(const struct assoc_array_edit *edit) +{ + int i; + + for (i = 1; i < ASSOC_ARRAY_FAN_OUT + 1; i++) + if (edit->segment_cache[i] != edit->segment_cache[0]) + return false; + return true; +} + /* * Split a full node into new_n0, which takes its place, and new_n1, below * new_n0 in the slot of a segment that at least two of the leaves share, @@ -735,11 +764,8 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, { struct assoc_array_shortcut *new_s0; struct assoc_array_node *node, *new_n0, *new_n1; - struct assoc_array_ptr *ptr; - unsigned long dissimilarity, base_seg; bool have_meta; int level; - int i; node = result->terminal_node.node; level = result->terminal_node.level; @@ -777,78 +803,47 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, have_meta = assoc_array_fill_segment_cache(edit, ops, node, level); edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; - if (have_meta) { - pr_devel("have meta\n"); - goto split_node; - } - - /* The node contains only leaves */ - dissimilarity = 0; - base_seg = edit->segment_cache[0]; - for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++) - dissimilarity |= edit->segment_cache[i] ^ base_seg; - - pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity); - - if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) { - /* The old leaves all cluster in the same slot. We will need - * to insert a shortcut if the new node wants to cluster with them. + if (!have_meta && assoc_array_all_one_segment(edit)) { + /* The node only contains leaves and all the leaves cluster in + * the same slot, so we need to insert a shortcut to skip the + * common portion of the key and split the node at the + * shortcut's far end. */ - if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0) - goto all_leaves_cluster_together; - - /* Otherwise all the old leaves cluster in the same slot, but - * the new leaf wants to go into a different slot - so we - * create a new node (n0) to hold the new leaf and a pointer to - * a new node (n1) holding all the old leaves. + new_s0 = assoc_array_insert_shortcut(edit, ops, index_key, + node, level, new_n0); + if (!new_s0) + return false; + edit->set[0].ptr = assoc_array_parent_link(edit->array, + new_s0->back_pointer, + new_s0->parent_slot); + edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); + } else { + /* We need to split the current node. The node must contain + * anything from a single leaf (in the one leaf case, this leaf + * will cluster with the new leaf) and the rest meta-pointers, + * to all leaves, some of which may cluster. + * + * We need to expel at least two leaves out of a set consisting + * of the leaves in the node and the new leaf. The current meta + * pointers can just be copied as they shouldn't cluster with + * any of the leaves. If all the old leaves cluster in one slot + * and the new leaf does not, they all go and the new leaf stays. * - * This can be done by falling through to the node splitting - * path. + * We need a new node (n0) to replace the current one and a new + * node to take the expelled nodes (n1). */ - pr_devel("present leaves cluster but not new leaf\n"); + new_n0->back_pointer = node->back_pointer; + new_n0->parent_slot = node->parent_slot; + edit->set[0].ptr = assoc_array_parent_link(edit->array, + new_n0->back_pointer, + new_n0->parent_slot); + edit->set[0].to = assoc_array_node_to_ptr(new_n0); } -split_node: - /* We need to split the current node. The node must contain anything - * from a single leaf (in the one leaf case, this leaf will cluster - * with the new leaf) and the rest meta-pointers, to all leaves, some - * of which may cluster. - * - * It won't contain the case in which all the current leaves plus the - * new leaves want to cluster in the same slot. - * - * We need to expel at least two leaves out of a set consisting of the - * leaves in the node and the new leaf. The current meta pointers can - * just be copied as they shouldn't cluster with any of the leaves. - * - * We need a new node (n0) to replace the current one and a new node to - * take the expelled nodes (n1). - */ - edit->set[0].to = assoc_array_node_to_ptr(new_n0); - new_n0->back_pointer = node->back_pointer; - new_n0->parent_slot = node->parent_slot; - -do_split_node: assoc_array_split_node(edit, node, new_n0, new_n1); - - ptr = node->back_pointer; - if (!ptr) - edit->set[0].ptr = &edit->array->root; - else if (assoc_array_ptr_is_node(ptr)) - edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot]; - else - edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node; edit->excised_meta[0] = assoc_array_node_to_ptr(node); pr_devel("<--%s() = ok [split node]\n", __func__); return true; - -all_leaves_cluster_together: - new_s0 = assoc_array_insert_shortcut(edit, ops, index_key, - node, level, new_n0); - if (!new_s0) - return false; - edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); - goto do_split_node; } /* From 48691075b0adc590a6831390723e3603dfca76fc Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 10:25:24 -0700 Subject: [PATCH 0016/2102] assoc_array: don't chain a new shortcut onto an existing one When a full node's leaves and the new key all share the node's segment, assoc_array_insert_into_terminal_node() replaces the node with a shortcut to a pair of new nodes. If the node is itself the target of a shortcut, the new shortcut is installed as that shortcut's next node, and a shortcut leading to a shortcut is something nothing expects: assoc_array_walk() indexes the second one as a node, and assoc_array_apply_edit() hits the BUG_ON() in the loop that adjusts nr_leaves_on_branch, on that same insertion. Deletion gets a node there. When the subtree below a shortcut shrinks enough, assoc_array_delete() collapses it into one node below the shortcut, and the leaves it collects can all share that node's segment. The next key that shares it too takes this path. Eighteen insertions and a deletion are enough: sixteen keys that agree on bits 0-11, one that leaves them at bit 8 and is deleted again, and one more that agrees with the sixteen. Have the new shortcut replace the one in front of the node as well. assoc_array_insert_shortcut() gives it that shortcut's back pointer and parent slot, so the caller installs it where that one was, and excises the old shortcut along with the node, which takes a second entry in excised_meta[]. The new shortcut's index key comes from the new key up to the new skip level, so it covers what the old one did. Found by a userspace test doing random insertions and deletions on keys that share long prefixes; a targeted case builds a shortcut, deletes down to the collapse and inserts one more key. Fixes: 3cb989501c26 ("Add a generic associative array implementation.") Reported-by: Ollrogge Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- include/linux/assoc_array_priv.h | 2 +- lib/assoc_array.c | 24 ++++++++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/include/linux/assoc_array_priv.h b/include/linux/assoc_array_priv.h index dca733ef675038..37a9f76e1505b6 100644 --- a/include/linux/assoc_array_priv.h +++ b/include/linux/assoc_array_priv.h @@ -80,7 +80,7 @@ struct assoc_array_edit { struct assoc_array_ptr **leaf_p; struct assoc_array_ptr *dead_leaf; struct assoc_array_ptr *new_meta[3]; - struct assoc_array_ptr *excised_meta[1]; + struct assoc_array_ptr *excised_meta[2]; struct assoc_array_ptr *excised_subtree; struct assoc_array_ptr **set_backpointers[ASSOC_ARRAY_FAN_OUT]; struct assoc_array_ptr *set_backpointers_to; diff --git a/lib/assoc_array.c b/lib/assoc_array.c index 8bfdb0d5bc9a25..834c33e3ddd4db 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -679,9 +679,10 @@ static void assoc_array_split_node(struct assoc_array_edit *edit, /* * All the leaves, new and old, want to cluster together in this node in the * same slot, so we have to replace this node with a shortcut to skip over - * the identical parts of the key, leading to new_n0. The caller then splits - * the leaves between new_n0 and new_n1 at the shortcut's far end, for which - * this fills in the segment cache. + * the identical parts of the key, leading to new_n0. If the node is the + * target of a shortcut, the new one replaces that shortcut as well. The + * caller then splits the leaves between new_n0 and new_n1 at the shortcut's + * far end, for which this fills in the segment cache. */ static struct assoc_array_shortcut * assoc_array_insert_shortcut(struct assoc_array_edit *edit, @@ -726,6 +727,20 @@ assoc_array_insert_shortcut(struct assoc_array_edit *edit, new_s0->back_pointer = node->back_pointer; new_s0->parent_slot = node->parent_slot; + + /* A shortcut has to lead to a node, so a node at the end of a shortcut + * is replaced together with that shortcut. The new one holds the index + * key from the root, so it covers what the old one did. + */ + if (node->back_pointer && + assoc_array_ptr_is_shortcut(node->back_pointer)) { + struct assoc_array_shortcut *above = + assoc_array_ptr_to_shortcut(node->back_pointer); + + new_s0->back_pointer = above->back_pointer; + new_s0->parent_slot = above->parent_slot; + edit->excised_meta[1] = node->back_pointer; + } new_s0->next_node = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); new_n0->parent_slot = 0; @@ -807,7 +822,8 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, /* The node only contains leaves and all the leaves cluster in * the same slot, so we need to insert a shortcut to skip the * common portion of the key and split the node at the - * shortcut's far end. + * shortcut's far end. The shortcut goes wherever its back + * pointer says, which may be further up than the node. */ new_s0 = assoc_array_insert_shortcut(edit, ops, index_key, node, level, new_n0); From 8afff2e4b90978b8203f9e3898995dcf86821b49 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 11:24:04 -0700 Subject: [PATCH 0017/2102] assoc_array: keep gc's cleanup out of the live tree on allocation failure assoc_array_gc() builds a copy of the tree. Where the copy reaches a shortcut, it allocates the copy of the shortcut with kmalloc_flex(), fills it with memcpy(), links it into the new tree, and only then allocates the copy of the node after it. The memcpy() leaves the new shortcut's next_node pointing at the old tree's node, so if that second allocation fails, the cleanup, assoc_array_destroy_subtree() on the new tree, follows the new shortcut into the old tree, and the BUG_ON() on the old node's back pointer fires. Allocate the node first, and the shortcut once the node exists, freeing the node again if the shortcut cannot be allocated. A copied shortcut is then only linked into the new tree when the copy of its node is there to follow it. Nothing else changes: with no allocation failing, the trees gc builds are the same as before. Found by a userspace test that makes each allocation of each operation fail in turn. Fixes: 3cb989501c26 ("Add a generic associative array implementation.") Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index 834c33e3ddd4db..3a7cddb1290b05 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -1560,16 +1560,25 @@ int assoc_array_gc(struct assoc_array *array, cursor = array->root; descend: - /* If this point is a shortcut, then we need to duplicate it and - * advance the target cursor. + /* The node at this position is duplicated, and so is the shortcut in + * front of it if there is one. The node is allocated first: the copy + * of the shortcut starts out pointing at the old node, and must not be + * in the new tree if the node cannot be allocated, or the cleanup + * would follow it into the old tree. */ + new_n = kzalloc_obj(struct assoc_array_node); + if (!new_n) + goto enomem; + if (assoc_array_ptr_is_shortcut(cursor)) { shortcut = assoc_array_ptr_to_shortcut(cursor); keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s = kmalloc_flex(*new_s, index_key, keylen); - if (!new_s) + if (!new_s) { + kfree(new_n); goto enomem; + } pr_devel("dup shortcut %p -> %p\n", shortcut, new_s); memcpy(new_s, shortcut, struct_size(new_s, index_key, keylen)); new_s->back_pointer = new_parent; @@ -1579,11 +1588,7 @@ int assoc_array_gc(struct assoc_array *array, cursor = shortcut->next_node; } - /* Duplicate the node at this position */ node = assoc_array_ptr_to_node(cursor); - new_n = kzalloc_obj(struct assoc_array_node); - if (!new_n) - goto enomem; pr_devel("dup node %p -> %p\n", node, new_n); new_n->back_pointer = new_parent; new_n->parent_slot = node->parent_slot; From 0fb34ebd3330382e61adde030416e9b77fe0f5d2 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 11:35:17 -0700 Subject: [PATCH 0018/2102] assoc_array: move gc's folding into a function of its own assoc_array_gc() is close to 300 lines with eleven gotos. It copies the tree depth first, without recursion, and packs each node's copy on the way back up; the copying, the walk and the packing are all written out in one function, joined by five labels. Start taking it apart with the folding of children into a finished copy, the code after the retry_compress label, which becomes assoc_array_gc_fold() and keeps its label and its goto. No functional change. Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 172 +++++++++++++++++++++++++--------------------- 1 file changed, 93 insertions(+), 79 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index 3a7cddb1290b05..0dfc2efb4fda0c 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -1503,6 +1503,97 @@ void assoc_array_cancel_edit(struct assoc_array_edit *edit) kfree(edit); } +/* + * Fold the children of a finished copy into it where their leaves fit in + * its free slots, and count its leaves. Returns the number of free slots + * left. + */ +static int assoc_array_gc_fold(struct assoc_array_node *new_n) +{ + struct assoc_array_ptr *ptr; + bool retained; + int slot, nr_free, next_slot, i; + +retry_compress: + pr_devel("-- compress node %p --\n", new_n); + + /* Count up the number of empty slots in this node and work out the + * subtree leaf count. + */ + new_n->nr_leaves_on_branch = 0; + nr_free = 0; + for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { + ptr = new_n->slots[slot]; + if (!ptr) + nr_free++; + else if (assoc_array_ptr_is_leaf(ptr)) + new_n->nr_leaves_on_branch++; + } + pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch); + + /* See what we can fold in */ + retained = false; + next_slot = 0; + for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { + struct assoc_array_shortcut *s; + struct assoc_array_node *child; + + ptr = new_n->slots[slot]; + if (!ptr || assoc_array_ptr_is_leaf(ptr)) + continue; + + s = NULL; + if (assoc_array_ptr_is_shortcut(ptr)) { + s = assoc_array_ptr_to_shortcut(ptr); + ptr = s->next_node; + } + + child = assoc_array_ptr_to_node(ptr); + new_n->nr_leaves_on_branch += child->nr_leaves_on_branch; + + if (child->nr_leaves_on_branch <= nr_free + 1) { + /* Fold the child node into this one */ + pr_devel("[%d] fold node %lu/%d [nx %d]\n", + slot, child->nr_leaves_on_branch, nr_free + 1, + next_slot); + + /* We would already have reaped an intervening shortcut + * on the way back up the tree. + */ + BUG_ON(s); + + new_n->slots[slot] = NULL; + nr_free++; + if (slot < next_slot) + next_slot = slot; + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { + struct assoc_array_ptr *p = child->slots[i]; + if (!p) + continue; + BUG_ON(assoc_array_ptr_is_meta(p)); + while (new_n->slots[next_slot]) + next_slot++; + BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT); + new_n->slots[next_slot++] = p; + nr_free--; + } + kfree(child); + } else { + pr_devel("[%d] retain node %lu/%d [nx %d]\n", + slot, child->nr_leaves_on_branch, nr_free + 1, + next_slot); + retained = true; + } + } + + if (retained && new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) { + pr_devel("internal nodes remain despite enough space, retrying\n"); + goto retry_compress; + } + pr_devel("after: %lu\n", new_n->nr_leaves_on_branch); + return nr_free; +} + /** * assoc_array_gc - Garbage collect an associative array. * @array: The array to clean. @@ -1538,8 +1629,7 @@ int assoc_array_gc(struct assoc_array *array, struct assoc_array_ptr *cursor, *ptr; struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp; unsigned long nr_leaves_on_tree; - bool retained; - int keylen, slot, nr_free, next_slot, i; + int keylen, slot, nr_free; pr_devel("-->%s()\n", __func__); @@ -1618,83 +1708,7 @@ int assoc_array_gc(struct assoc_array *array, goto descend; } -retry_compress: - pr_devel("-- compress node %p --\n", new_n); - - /* Count up the number of empty slots in this node and work out the - * subtree leaf count. - */ - new_n->nr_leaves_on_branch = 0; - nr_free = 0; - for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { - ptr = new_n->slots[slot]; - if (!ptr) - nr_free++; - else if (assoc_array_ptr_is_leaf(ptr)) - new_n->nr_leaves_on_branch++; - } - pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch); - - /* See what we can fold in */ - retained = false; - next_slot = 0; - for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { - struct assoc_array_shortcut *s; - struct assoc_array_node *child; - - ptr = new_n->slots[slot]; - if (!ptr || assoc_array_ptr_is_leaf(ptr)) - continue; - - s = NULL; - if (assoc_array_ptr_is_shortcut(ptr)) { - s = assoc_array_ptr_to_shortcut(ptr); - ptr = s->next_node; - } - - child = assoc_array_ptr_to_node(ptr); - new_n->nr_leaves_on_branch += child->nr_leaves_on_branch; - - if (child->nr_leaves_on_branch <= nr_free + 1) { - /* Fold the child node into this one */ - pr_devel("[%d] fold node %lu/%d [nx %d]\n", - slot, child->nr_leaves_on_branch, nr_free + 1, - next_slot); - - /* We would already have reaped an intervening shortcut - * on the way back up the tree. - */ - BUG_ON(s); - - new_n->slots[slot] = NULL; - nr_free++; - if (slot < next_slot) - next_slot = slot; - for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { - struct assoc_array_ptr *p = child->slots[i]; - if (!p) - continue; - BUG_ON(assoc_array_ptr_is_meta(p)); - while (new_n->slots[next_slot]) - next_slot++; - BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT); - new_n->slots[next_slot++] = p; - nr_free--; - } - kfree(child); - } else { - pr_devel("[%d] retain node %lu/%d [nx %d]\n", - slot, child->nr_leaves_on_branch, nr_free + 1, - next_slot); - retained = true; - } - } - - if (retained && new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) { - pr_devel("internal nodes remain despite enough space, retrying\n"); - goto retry_compress; - } - pr_devel("after: %lu\n", new_n->nr_leaves_on_branch); + nr_free = assoc_array_gc_fold(new_n); nr_leaves_on_tree = new_n->nr_leaves_on_branch; From f2c159a4cd1722a816bf8f08539ec0ec1e1cabde Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 11:35:18 -0700 Subject: [PATCH 0019/2102] assoc_array: replace the labels in gc's tree walk with a loop assoc_array_gc() walks the old tree depth first, without recursion, building the copy as it goes. Its position is a handful of locals, and its moves are labels: descend copies a node and the shortcut in front of it, continue_node goes on through the node's slots, the code after the fold removes a node holding nothing but a shortcut or a shortcut in front of a small node, and ascend_old_tree climbs back up. Keep the walk and its order, but give the position a structure, struct assoc_array_gc_walk, and each move a function: assoc_array_gc_copy(), assoc_array_gc_next(), assoc_array_gc_pack() and assoc_array_gc_ascend(). assoc_array_gc() becomes a loop that copies a subtree, then finds the next one, packing and climbing past the nodes that are done. Finishing is one test now: after packing, a copy has no parent exactly when it is the whole tree. That covers all four ways the old code finished: the three gotos to gc_complete, and the climb out of a node below a root shortcut that is kept, which now stops at the packing. The copy is made in one place, so gcc inlines all of it into assoc_array_gc(), which has no recursion: its stack frame is 152 bytes, against 128 before, on an x86-64 defconfig. No functional change. Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 380 +++++++++++++++++++++++++++------------------- 1 file changed, 226 insertions(+), 154 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index 0dfc2efb4fda0c..879a6d12ec3d91 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -1503,6 +1503,105 @@ void assoc_array_cancel_edit(struct assoc_array_edit *edit) kfree(edit); } +/* + * Where assoc_array_gc() has got to. It copies the tree depth first without + * recursion: on reaching a subtree it copies it and carries on there, and on + * finishing a node it climbs back up the old tree to the node above. + */ +struct assoc_array_gc_walk { + struct assoc_array_node *node; /* The node being copied */ + struct assoc_array_node *new_n; /* Its copy */ + int slot; /* The next slot of node to look at */ + struct assoc_array_ptr *new_root; /* The root of the copy */ + unsigned long nr_leaves_on_tree; + bool (*iterator)(void *object, void *iterator_data); + void *iterator_data; +}; + +/* + * Copy the node at cursor, and the shortcut in front of it if there is one, + * into the new tree at *link, below the copy of the node being worked on, + * and work on that node next. + */ +static bool assoc_array_gc_copy(struct assoc_array_gc_walk *w, + struct assoc_array_ptr *cursor, + struct assoc_array_ptr **link) +{ + struct assoc_array_shortcut *shortcut, *new_s; + struct assoc_array_node *new_n; + struct assoc_array_ptr *new_parent; + int keylen; + + new_parent = w->new_n ? assoc_array_node_to_ptr(w->new_n) : NULL; + + /* The node at this position is duplicated, and so is the shortcut in + * front of it if there is one. The node is allocated first: the copy + * of the shortcut starts out pointing at the old node, and must not be + * in the new tree if the node cannot be allocated, or the cleanup + * would follow it into the old tree. + */ + new_n = kzalloc_obj(struct assoc_array_node); + if (!new_n) + return false; + + if (assoc_array_ptr_is_shortcut(cursor)) { + shortcut = assoc_array_ptr_to_shortcut(cursor); + keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); + keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; + new_s = kmalloc_flex(*new_s, index_key, keylen); + if (!new_s) { + kfree(new_n); + return false; + } + pr_devel("dup shortcut %p -> %p\n", shortcut, new_s); + memcpy(new_s, shortcut, struct_size(new_s, index_key, keylen)); + new_s->back_pointer = new_parent; + new_s->parent_slot = shortcut->parent_slot; + *link = new_parent = assoc_array_shortcut_to_ptr(new_s); + link = &new_s->next_node; + cursor = shortcut->next_node; + } + + w->node = assoc_array_ptr_to_node(cursor); + pr_devel("dup node %p -> %p\n", w->node, new_n); + new_n->back_pointer = new_parent; + new_n->parent_slot = w->node->parent_slot; + *link = assoc_array_node_to_ptr(new_n); + w->new_n = new_n; + w->slot = 0; + return true; +} + +/* + * Carry on through the slots of the node being copied, putting the leaves + * the iterator keeps into the copy, as far as the next pointer to a subtree. + * Returns that pointer, with w->slot at it, or NULL when the node is done. + */ +static struct assoc_array_ptr *assoc_array_gc_next(struct assoc_array_gc_walk *w) +{ + struct assoc_array_ptr *ptr; + + /* Filter across any leaves and gc any subtrees */ + for (; w->slot < ASSOC_ARRAY_FAN_OUT; w->slot++) { + ptr = w->node->slots[w->slot]; + if (!ptr) + continue; + + if (assoc_array_ptr_is_leaf(ptr)) { + if (w->iterator(assoc_array_ptr_to_leaf(ptr), + w->iterator_data)) + /* The iterator will have done any reference + * counting on the object for us. + */ + w->new_n->slots[w->slot] = ptr; + continue; + } + + return ptr; + } + return NULL; +} + /* * Fold the children of a finished copy into it where their leaves fit in * its free slots, and count its leaves. Returns the number of free slots @@ -1594,123 +1693,21 @@ static int assoc_array_gc_fold(struct assoc_array_node *new_n) return nr_free; } -/** - * assoc_array_gc - Garbage collect an associative array. - * @array: The array to clean. - * @ops: The operations to use. - * @iterator: A callback function to pass judgement on each object. - * @iterator_data: Private data for the callback function. - * - * Collect garbage from an associative array and pack down the internal tree to - * save memory. - * - * The iterator function is asked to pass judgement upon each object in the - * array. If it returns false, the object is discard and if it returns true, - * the object is kept. If it returns true, it must increment the object's - * usage count (or whatever it needs to do to retain it) before returning. - * - * This function returns 0 if successful or -ENOMEM if out of memory. In the - * latter case, the array is not changed. - * - * The caller should lock against other modifications and must continue to hold - * the lock until assoc_array_apply_edit() has been called. - * - * Accesses to the tree may take place concurrently with this function, - * provided they hold the RCU read lock. +/* + * The copy of the node being worked on is finished: fold its children into + * it, then remove it if all it holds is a shortcut, or remove the shortcut + * in front of it if it is small. Returns what is then the copy's parent, or + * NULL if it is at the root, when the whole tree has been copied. */ -int assoc_array_gc(struct assoc_array *array, - const struct assoc_array_ops *ops, - bool (*iterator)(void *object, void *iterator_data), - void *iterator_data) +static struct assoc_array_ptr *assoc_array_gc_pack(struct assoc_array_gc_walk *w) { - struct assoc_array_shortcut *shortcut, *new_s; - struct assoc_array_node *node, *new_n; - struct assoc_array_edit *edit; - struct assoc_array_ptr *cursor, *ptr; - struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp; - unsigned long nr_leaves_on_tree; - int keylen, slot, nr_free; - - pr_devel("-->%s()\n", __func__); - - if (!array->root) - return 0; - - edit = kzalloc_obj(struct assoc_array_edit); - if (!edit) - return -ENOMEM; - edit->array = array; - edit->ops = ops; - edit->ops_for_excised_subtree = ops; - edit->set[0].ptr = &array->root; - edit->excised_subtree = array->root; - - new_root = new_parent = NULL; - new_ptr_pp = &new_root; - cursor = array->root; - -descend: - /* The node at this position is duplicated, and so is the shortcut in - * front of it if there is one. The node is allocated first: the copy - * of the shortcut starts out pointing at the old node, and must not be - * in the new tree if the node cannot be allocated, or the cleanup - * would follow it into the old tree. - */ - new_n = kzalloc_obj(struct assoc_array_node); - if (!new_n) - goto enomem; - - if (assoc_array_ptr_is_shortcut(cursor)) { - shortcut = assoc_array_ptr_to_shortcut(cursor); - keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); - keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; - new_s = kmalloc_flex(*new_s, index_key, keylen); - if (!new_s) { - kfree(new_n); - goto enomem; - } - pr_devel("dup shortcut %p -> %p\n", shortcut, new_s); - memcpy(new_s, shortcut, struct_size(new_s, index_key, keylen)); - new_s->back_pointer = new_parent; - new_s->parent_slot = shortcut->parent_slot; - *new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s); - new_ptr_pp = &new_s->next_node; - cursor = shortcut->next_node; - } - - node = assoc_array_ptr_to_node(cursor); - pr_devel("dup node %p -> %p\n", node, new_n); - new_n->back_pointer = new_parent; - new_n->parent_slot = node->parent_slot; - *new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n); - new_ptr_pp = NULL; - slot = 0; - -continue_node: - /* Filter across any leaves and gc any subtrees */ - for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { - ptr = node->slots[slot]; - if (!ptr) - continue; - - if (assoc_array_ptr_is_leaf(ptr)) { - if (iterator(assoc_array_ptr_to_leaf(ptr), - iterator_data)) - /* The iterator will have done any reference - * counting on the object for us. - */ - new_n->slots[slot] = ptr; - continue; - } - - new_ptr_pp = &new_n->slots[slot]; - cursor = ptr; - goto descend; - } + struct assoc_array_shortcut *new_s; + struct assoc_array_node *new_n = w->new_n; + struct assoc_array_ptr *ptr, *new_parent; + int nr_free, slot; nr_free = assoc_array_gc_fold(new_n); - - nr_leaves_on_tree = new_n->nr_leaves_on_branch; + w->nr_leaves_on_tree = new_n->nr_leaves_on_branch; /* Excise this node if it is singly occupied by a shortcut */ if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) { @@ -1728,8 +1725,8 @@ int assoc_array_gc(struct assoc_array *array, if (!new_parent) { new_s->back_pointer = NULL; new_s->parent_slot = 0; - new_root = ptr; - goto gc_complete; + w->new_root = ptr; + return NULL; } if (assoc_array_ptr_is_shortcut(new_parent)) { @@ -1745,16 +1742,15 @@ int assoc_array_gc(struct assoc_array *array, if (!new_parent) { new_s->back_pointer = NULL; new_s->parent_slot = 0; - new_root = ptr; - goto gc_complete; + w->new_root = ptr; + return NULL; } } new_s->back_pointer = new_parent; new_s->parent_slot = slot; - new_n = assoc_array_ptr_to_node(new_parent); - new_n->slots[slot] = ptr; - goto ascend_old_tree; + assoc_array_ptr_to_node(new_parent)->slots[slot] = ptr; + return new_parent; } } @@ -1763,59 +1759,135 @@ int assoc_array_gc(struct assoc_array *array, */ ptr = new_n->back_pointer; if (!ptr) - goto gc_complete; + return NULL; - if (assoc_array_ptr_is_shortcut(ptr)) { - new_s = assoc_array_ptr_to_shortcut(ptr); - new_parent = new_s->back_pointer; - slot = new_s->parent_slot; + if (!assoc_array_ptr_is_shortcut(ptr)) + return ptr; + + new_s = assoc_array_ptr_to_shortcut(ptr); + new_parent = new_s->back_pointer; + slot = new_s->parent_slot; + + if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) { + pr_devel("excise shortcut\n"); + new_n->back_pointer = new_parent; + new_n->parent_slot = slot; + kfree(new_s); + if (!new_parent) { + w->new_root = assoc_array_node_to_ptr(new_n); + return NULL; + } - if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) { - struct assoc_array_node *n; + assoc_array_ptr_to_node(new_parent)->slots[slot] = + assoc_array_node_to_ptr(new_n); + } + return new_parent; +} - pr_devel("excise shortcut\n"); - new_n->back_pointer = new_parent; - new_n->parent_slot = slot; - kfree(new_s); - if (!new_parent) { - new_root = assoc_array_node_to_ptr(new_n); - goto gc_complete; - } +/* + * Go back up from the node just finished to the node above it, whose copy is + * parent, and on to that node's next slot. + */ +static void assoc_array_gc_ascend(struct assoc_array_gc_walk *w, + struct assoc_array_ptr *parent) +{ + struct assoc_array_shortcut *shortcut; + struct assoc_array_ptr *ptr, *cursor; + int slot; - n = assoc_array_ptr_to_node(new_parent); - n->slots[slot] = assoc_array_node_to_ptr(new_n); - } - } else { - new_parent = ptr; - } - new_n = assoc_array_ptr_to_node(new_parent); + w->new_n = assoc_array_ptr_to_node(parent); -ascend_old_tree: - ptr = node->back_pointer; + ptr = w->node->back_pointer; if (assoc_array_ptr_is_shortcut(ptr)) { shortcut = assoc_array_ptr_to_shortcut(ptr); slot = shortcut->parent_slot; cursor = shortcut->back_pointer; - if (!cursor) - goto gc_complete; } else { - slot = node->parent_slot; + slot = w->node->parent_slot; cursor = ptr; } BUG_ON(!cursor); - node = assoc_array_ptr_to_node(cursor); - slot++; - goto continue_node; + w->node = assoc_array_ptr_to_node(cursor); + w->slot = slot + 1; +} + +/** + * assoc_array_gc - Garbage collect an associative array. + * @array: The array to clean. + * @ops: The operations to use. + * @iterator: A callback function to pass judgement on each object. + * @iterator_data: Private data for the callback function. + * + * Collect garbage from an associative array and pack down the internal tree to + * save memory. + * + * The iterator function is asked to pass judgement upon each object in the + * array. If it returns false, the object is discard and if it returns true, + * the object is kept. If it returns true, it must increment the object's + * usage count (or whatever it needs to do to retain it) before returning. + * + * This function returns 0 if successful or -ENOMEM if out of memory. In the + * latter case, the array is not changed. + * + * The caller should lock against other modifications and must continue to hold + * the lock until assoc_array_apply_edit() has been called. + * + * Accesses to the tree may take place concurrently with this function, + * provided they hold the RCU read lock. + */ +int assoc_array_gc(struct assoc_array *array, + const struct assoc_array_ops *ops, + bool (*iterator)(void *object, void *iterator_data), + void *iterator_data) +{ + struct assoc_array_gc_walk w = { + .iterator = iterator, + .iterator_data = iterator_data, + }; + struct assoc_array_edit *edit; + struct assoc_array_ptr *ptr, *parent, **link; + + pr_devel("-->%s()\n", __func__); + + if (!array->root) + return 0; + + edit = kzalloc_obj(struct assoc_array_edit); + if (!edit) + return -ENOMEM; + edit->array = array; + edit->ops = ops; + edit->ops_for_excised_subtree = ops; + edit->set[0].ptr = &array->root; + edit->excised_subtree = array->root; + + ptr = array->root; + link = &w.new_root; + for (;;) { + if (!assoc_array_gc_copy(&w, ptr, link)) + goto enomem; + + /* Find the next subtree to copy: further on in this node, or, + * when it is done, in the nodes above it. + */ + while (!(ptr = assoc_array_gc_next(&w))) { + parent = assoc_array_gc_pack(&w); + if (!parent) + goto copied; + assoc_array_gc_ascend(&w, parent); + } + link = &w.new_n->slots[w.slot]; + } -gc_complete: - edit->set[0].to = new_root; +copied: + edit->set[0].to = w.new_root; assoc_array_apply_edit(edit); - array->nr_leaves_on_tree = nr_leaves_on_tree; + array->nr_leaves_on_tree = w.nr_leaves_on_tree; return 0; enomem: pr_devel("enomem\n"); - assoc_array_destroy_subtree(new_root, edit->ops); + assoc_array_destroy_subtree(w.new_root, edit->ops); kfree(edit); return -ENOMEM; } From 4a5db94ad9b763d3b9d5dc0cad2241f5b9dd4f22 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 11:44:59 -0700 Subject: [PATCH 0020/2102] assoc_array: move deletion's collapse into a function of its own assoc_array_delete() is 177 lines: it finds the leaf, clears it, and then spends some 90 lines collapsing the subtree around it into one node, with two labels of its own inside an if. Move the collapse into assoc_array_delete_collapse(), which returns false when it cannot allocate the node; the caller cancels the edit as before. No functional change. Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 199 ++++++++++++++++++++++++---------------------- 1 file changed, 106 insertions(+), 93 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index 879a6d12ec3d91..fad5514aed16eb 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -1133,6 +1133,107 @@ static int assoc_array_delete_collapse_iterator(const void *leaf, return 0; } +/* + * Deleting a leaf from node leaves its subtree with FAN_OUT or fewer leaves: + * collapse the subtree into one new node, together with as much of the tree + * above it as also fits. Returns false if the new node cannot be allocated. + */ +static bool assoc_array_delete_collapse(struct assoc_array_edit *edit, + struct assoc_array_node *node) +{ + struct assoc_array_delete_collapse_context collapse; + struct assoc_array_node *parent, *grandparent, *new_n0; + struct assoc_array_ptr *ptr; + bool has_meta; + int i; + + /* First of all, we need to know if this node has metadata so + * that we don't try collapsing if all the leaves are already + * here. + */ + has_meta = false; + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { + ptr = node->slots[i]; + if (assoc_array_ptr_is_meta(ptr)) { + has_meta = true; + break; + } + } + + pr_devel("leaves: %ld [m=%d]\n", + node->nr_leaves_on_branch - 1, has_meta); + + /* Look further up the tree to see if we can collapse this node + * into a more proximal node too. + */ + parent = node; +collapse_up: + pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch); + + ptr = parent->back_pointer; + if (!ptr) + goto do_collapse; + if (assoc_array_ptr_is_shortcut(ptr)) { + struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr); + ptr = s->back_pointer; + if (!ptr) + goto do_collapse; + } + + grandparent = assoc_array_ptr_to_node(ptr); + if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { + parent = grandparent; + goto collapse_up; + } + +do_collapse: + /* There's no point collapsing if the original node has no meta + * pointers to discard and if we didn't merge into one of that + * node's ancestry. + */ + if (has_meta || parent != node) { + node = parent; + + /* Create a new node to collapse into */ + new_n0 = kzalloc_obj(struct assoc_array_node); + if (!new_n0) + return false; + edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); + + new_n0->back_pointer = node->back_pointer; + new_n0->parent_slot = node->parent_slot; + new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; + edit->adjust_count_on = new_n0; + + collapse.node = new_n0; + collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf); + collapse.slot = 0; + assoc_array_subtree_iterate(assoc_array_node_to_ptr(node), + node->back_pointer, + assoc_array_delete_collapse_iterator, + &collapse); + pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch); + BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1); + + if (!node->back_pointer) { + edit->set[1].ptr = &edit->array->root; + } else if (assoc_array_ptr_is_leaf(node->back_pointer)) { + BUG(); + } else if (assoc_array_ptr_is_node(node->back_pointer)) { + struct assoc_array_node *p = + assoc_array_ptr_to_node(node->back_pointer); + edit->set[1].ptr = &p->slots[node->parent_slot]; + } else if (assoc_array_ptr_is_shortcut(node->back_pointer)) { + struct assoc_array_shortcut *s = + assoc_array_ptr_to_shortcut(node->back_pointer); + edit->set[1].ptr = &s->next_node; + } + edit->set[1].to = assoc_array_node_to_ptr(new_n0); + edit->excised_subtree = assoc_array_node_to_ptr(node); + } + return true; +} + /** * assoc_array_delete - Script deletion of an object from an associative array * @array: The array to search. @@ -1156,13 +1257,11 @@ struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, const struct assoc_array_ops *ops, const void *index_key) { - struct assoc_array_delete_collapse_context collapse; struct assoc_array_walk_result result; - struct assoc_array_node *node, *new_n0; + struct assoc_array_node *node; struct assoc_array_edit *edit; struct assoc_array_ptr *ptr; - bool has_meta; - int slot, i; + int slot; pr_devel("-->%s()\n", __func__); @@ -1231,95 +1330,9 @@ struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, * We could also try and collapse in partially filled subtrees to take * up space in this node. */ - if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { - struct assoc_array_node *parent, *grandparent; - struct assoc_array_ptr *ptr; - - /* First of all, we need to know if this node has metadata so - * that we don't try collapsing if all the leaves are already - * here. - */ - has_meta = false; - for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { - ptr = node->slots[i]; - if (assoc_array_ptr_is_meta(ptr)) { - has_meta = true; - break; - } - } - - pr_devel("leaves: %ld [m=%d]\n", - node->nr_leaves_on_branch - 1, has_meta); - - /* Look further up the tree to see if we can collapse this node - * into a more proximal node too. - */ - parent = node; - collapse_up: - pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch); - - ptr = parent->back_pointer; - if (!ptr) - goto do_collapse; - if (assoc_array_ptr_is_shortcut(ptr)) { - struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr); - ptr = s->back_pointer; - if (!ptr) - goto do_collapse; - } - - grandparent = assoc_array_ptr_to_node(ptr); - if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { - parent = grandparent; - goto collapse_up; - } - - do_collapse: - /* There's no point collapsing if the original node has no meta - * pointers to discard and if we didn't merge into one of that - * node's ancestry. - */ - if (has_meta || parent != node) { - node = parent; - - /* Create a new node to collapse into */ - new_n0 = kzalloc_obj(struct assoc_array_node); - if (!new_n0) - goto enomem; - edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); - - new_n0->back_pointer = node->back_pointer; - new_n0->parent_slot = node->parent_slot; - new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; - edit->adjust_count_on = new_n0; - - collapse.node = new_n0; - collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf); - collapse.slot = 0; - assoc_array_subtree_iterate(assoc_array_node_to_ptr(node), - node->back_pointer, - assoc_array_delete_collapse_iterator, - &collapse); - pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch); - BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1); - - if (!node->back_pointer) { - edit->set[1].ptr = &array->root; - } else if (assoc_array_ptr_is_leaf(node->back_pointer)) { - BUG(); - } else if (assoc_array_ptr_is_node(node->back_pointer)) { - struct assoc_array_node *p = - assoc_array_ptr_to_node(node->back_pointer); - edit->set[1].ptr = &p->slots[node->parent_slot]; - } else if (assoc_array_ptr_is_shortcut(node->back_pointer)) { - struct assoc_array_shortcut *s = - assoc_array_ptr_to_shortcut(node->back_pointer); - edit->set[1].ptr = &s->next_node; - } - edit->set[1].to = assoc_array_node_to_ptr(new_n0); - edit->excised_subtree = assoc_array_node_to_ptr(node); - } - } + if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1 && + !assoc_array_delete_collapse(edit, node)) + goto enomem; return edit; From 2dafc9bc491da8146bf293a93ae21fd68755e370 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 11:44:59 -0700 Subject: [PATCH 0021/2102] assoc_array: find and collapse in deletion without gotos Finding the leaf to delete is a switch whose one useful case falls through into the cases that give up, and is left by a goto to found_leaf. Make it an if, and a loop that stops at the leaf. The climb to the highest node the collapse can merge into is two labels, collapse_up and do_collapse. Make it a for loop that stops at the root or at a node with too many leaves. The new node's place is found with assoc_array_parent_link(), keeping the check against a leaf as a back pointer as a BUG_ON(), and the cleanup after a failed allocation moves to the one place that needs it. There is no recursion, and assoc_array_delete()'s stack frame is 160 bytes against 176 before, on an x86-64 defconfig. No functional change. Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 72 ++++++++++++++++++----------------------------- 1 file changed, 27 insertions(+), 45 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index fad5514aed16eb..d3bc426f17af6f 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -1166,27 +1166,20 @@ static bool assoc_array_delete_collapse(struct assoc_array_edit *edit, /* Look further up the tree to see if we can collapse this node * into a more proximal node too. */ - parent = node; -collapse_up: - pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch); + for (parent = node;; parent = grandparent) { + pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch); - ptr = parent->back_pointer; - if (!ptr) - goto do_collapse; - if (assoc_array_ptr_is_shortcut(ptr)) { - struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr); - ptr = s->back_pointer; + ptr = parent->back_pointer; + if (ptr && assoc_array_ptr_is_shortcut(ptr)) + ptr = assoc_array_ptr_to_shortcut(ptr)->back_pointer; if (!ptr) - goto do_collapse; - } + break; - grandparent = assoc_array_ptr_to_node(ptr); - if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { - parent = grandparent; - goto collapse_up; + grandparent = assoc_array_ptr_to_node(ptr); + if (grandparent->nr_leaves_on_branch > ASSOC_ARRAY_FAN_OUT + 1) + break; } -do_collapse: /* There's no point collapsing if the original node has no meta * pointers to discard and if we didn't merge into one of that * node's ancestry. @@ -1215,19 +1208,11 @@ static bool assoc_array_delete_collapse(struct assoc_array_edit *edit, pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch); BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1); - if (!node->back_pointer) { - edit->set[1].ptr = &edit->array->root; - } else if (assoc_array_ptr_is_leaf(node->back_pointer)) { - BUG(); - } else if (assoc_array_ptr_is_node(node->back_pointer)) { - struct assoc_array_node *p = - assoc_array_ptr_to_node(node->back_pointer); - edit->set[1].ptr = &p->slots[node->parent_slot]; - } else if (assoc_array_ptr_is_shortcut(node->back_pointer)) { - struct assoc_array_shortcut *s = - assoc_array_ptr_to_shortcut(node->back_pointer); - edit->set[1].ptr = &s->next_node; - } + BUG_ON(node->back_pointer && + assoc_array_ptr_is_leaf(node->back_pointer)); + edit->set[1].ptr = assoc_array_parent_link(edit->array, + node->back_pointer, + node->parent_slot); edit->set[1].to = assoc_array_node_to_ptr(new_n0); edit->excised_subtree = assoc_array_node_to_ptr(node); } @@ -1272,8 +1257,10 @@ struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, edit->ops = ops; edit->adjust_count_by = -1; - switch (assoc_array_walk(array, ops, index_key, &result)) { - case assoc_array_walk_found_terminal_node: + node = NULL; + slot = ASSOC_ARRAY_FAN_OUT; + if (assoc_array_walk(array, ops, index_key, &result) == + assoc_array_walk_found_terminal_node) { /* We found a node that should contain the leaf we've been * asked to remove - *if* it's in the tree. */ @@ -1286,18 +1273,15 @@ struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, assoc_array_ptr_is_leaf(ptr) && ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) - goto found_leaf; + break; } - fallthrough; - case assoc_array_walk_tree_empty: - case assoc_array_walk_found_wrong_shortcut: - default: + } + if (slot == ASSOC_ARRAY_FAN_OUT) { assoc_array_cancel_edit(edit); pr_devel("not found\n"); return NULL; } -found_leaf: BUG_ON(array->nr_leaves_on_tree <= 0); /* In the simplest form of deletion we just clear the slot and release @@ -1331,16 +1315,14 @@ struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, * up space in this node. */ if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1 && - !assoc_array_delete_collapse(edit, node)) - goto enomem; + !assoc_array_delete_collapse(edit, node)) { + /* Clean up after an out of memory error */ + pr_devel("enomem\n"); + assoc_array_cancel_edit(edit); + return ERR_PTR(-ENOMEM); + } return edit; - -enomem: - /* Clean up after an out of memory error */ - pr_devel("enomem\n"); - assoc_array_cancel_edit(edit); - return ERR_PTR(-ENOMEM); } /** From bbab563c51315a1c6dbf6e801e4237b6d2b8b81e Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 11 Oct 2026 11:44:59 -0700 Subject: [PATCH 0022/2102] assoc_array: use assoc_array_parent_link() when splitting a shortcut assoc_array_insert_mid_shortcut() works out by hand which pointer leads to the shortcut it splits: the same cases as assoc_array_parent_link(), with a BUG() for a shortcut behind anything but a node. Use the function, and keep the check as a BUG_ON(). No functional change. Assisted-by: LLM Signed-off-by: Linus Torvalds Tested-by: David Howells Reviewed-by: David Howells --- lib/assoc_array.c | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/lib/assoc_array.c b/lib/assoc_array.c index d3bc426f17af6f..f19888ec3e0931 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -870,7 +870,7 @@ static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut, *new_s0, *new_s1; - struct assoc_array_node *node, *new_n0, *side; + struct assoc_array_node *new_n0, *side; unsigned long sc_segments, dissimilarity, blank; size_t keylen; int level, sc_level, diff; @@ -896,14 +896,11 @@ static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit, diff += sc_level & ~ASSOC_ARRAY_KEY_CHUNK_MASK; pr_devel("diff=%d\n", diff); - if (!shortcut->back_pointer) { - edit->set[0].ptr = &edit->array->root; - } else if (assoc_array_ptr_is_node(shortcut->back_pointer)) { - node = assoc_array_ptr_to_node(shortcut->back_pointer); - edit->set[0].ptr = &node->slots[shortcut->parent_slot]; - } else { - BUG(); - } + BUG_ON(shortcut->back_pointer && + !assoc_array_ptr_is_node(shortcut->back_pointer)); + edit->set[0].ptr = assoc_array_parent_link(edit->array, + shortcut->back_pointer, + shortcut->parent_slot); edit->excised_meta[0] = assoc_array_shortcut_to_ptr(shortcut); From 16ca2aea66b12c898df8d1a3a138ccc3025fe38d Mon Sep 17 00:00:00 2001 From: Geert Uytterhoeven Date: Fri, 16 Oct 2026 10:03:54 +0200 Subject: [PATCH 0023/2102] firmware: arm_scmi: Fix grammar s/thing/things/ Fix grammar in the help text for the ARM_SCMI_RAW_MODE_SUPPORT_COEX symbol. Signed-off-by: Geert Uytterhoeven Link: https://patch.msgid.link/5128072dc75dbf239dff6c967a88060a4d64b3c0.1792137751.git.geert+renesas@glider.be Signed-off-by: Sudeep Holla --- drivers/firmware/arm_scmi/Kconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/firmware/arm_scmi/Kconfig b/drivers/firmware/arm_scmi/Kconfig index 783c24a20e2919..9f6241efd5923f 100644 --- a/drivers/firmware/arm_scmi/Kconfig +++ b/drivers/firmware/arm_scmi/Kconfig @@ -52,7 +52,7 @@ config ARM_SCMI_RAW_MODE_SUPPORT_COEX Allow SCMI Raw transmission mode to coexist with normal SCMI stack. This will allow regular SCMI drivers to register with the core and - operate normally, thing which could make an SCMI test suite using the + operate normally, things which could make an SCMI test suite using the SCMI Raw mode support unreliable. If unsure, say N. config ARM_SCMI_DEBUG_COUNTERS From 8ab2e426762d199ce8b799d029edafbfb981f5c6 Mon Sep 17 00:00:00 2001 From: David Cemin Date: Tue, 20 Oct 2026 15:09:01 -0700 Subject: [PATCH 0024/2102] firmware: arm_ffa: Compare notify_id when looking up notifier callbacks The notifier callbacks are kept in a hash table keyed by notification ID, but struct notifier_cb_info does not store the ID and none of the lookup helpers compare it. hash_for_each_possible() walks the whole bucket, so any two IDs that hash to the same bucket are treated as the same registration. With the 64-bucket table, hash_32() maps IDs 2 and 36 to the same bucket. A driver that requests notifications sequentially therefore fails at the 37th request: ARM FF-A: Failed to register callback for 36 - -22 because update_notifier_cb() finds the node registered for ID 2 and rejects the new registration as a duplicate. The same lookup is used on the delivery path, so a notification for a colliding ID can also be dispatched to the callback registered for the other ID. Store the notification ID in the node and compare it in all three lookup helpers. This was found on an arm64 laptop whose embedded controller partition declares 38 notifications: the EC driver failed to probe and every EC event (AC, battery, lid, hotkeys) was lost. Fixes: e0573444edbf ("firmware: arm_ffa: Add interfaces to request notification callbacks") Fixes: c10debfe7f02 ("firmware: arm_ffa: Add support for {un,}registration of framework notifications") Signed-off-by: David Cemin Link: https://patch.msgid.link/20261020220902.611138-1-dcemin@nvidia.com Signed-off-by: Sudeep Holla --- drivers/firmware/arm_ffa/driver.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/drivers/firmware/arm_ffa/driver.c b/drivers/firmware/arm_ffa/driver.c index 28abc808fd32d2..ae8cc3a2ba2e7a 100644 --- a/drivers/firmware/arm_ffa/driver.c +++ b/drivers/firmware/arm_ffa/driver.c @@ -1223,6 +1223,7 @@ struct notifier_cb_info { ffa_fwk_notifier_cb fwk_cb; ffa_notifier_cb cb; void *cb_data; + u16 notify_id; }; static int @@ -1302,7 +1303,8 @@ notifier_hnode_get_by_vmid(u16 notify_id, int vmid) struct notifier_cb_info *node; hash_for_each_possible(drv_info->notifier_hash, node, hnode, notify_id) - if (node->fwk_cb && vmid == node->dev->vm_id) + if (node->notify_id == notify_id && node->fwk_cb && + vmid == node->dev->vm_id) return node; return NULL; @@ -1317,7 +1319,8 @@ notifier_hnode_get_by_vmid_uuid(u16 notify_id, int vmid, const uuid_t *uuid) return notifier_hnode_get_by_vmid(notify_id, vmid); hash_for_each_possible(drv_info->notifier_hash, node, hnode, notify_id) - if (node->fwk_cb && vmid == node->dev->vm_id && + if (node->notify_id == notify_id && node->fwk_cb && + vmid == node->dev->vm_id && uuid_equal(&node->dev->uuid, uuid)) return node; @@ -1330,7 +1333,8 @@ notifier_hnode_get_by_type(u16 notify_id, enum notify_type type) struct notifier_cb_info *node; hash_for_each_possible(drv_info->notifier_hash, node, hnode, notify_id) - if (node->cb && type == ffa_notify_type_get(node->dev->vm_id)) + if (node->notify_id == notify_id && node->cb && + type == ffa_notify_type_get(node->dev->vm_id)) return node; return NULL; @@ -1422,6 +1426,7 @@ static int __ffa_notify_request(struct ffa_device *dev, bool is_per_vcpu, cb_info->dev = dev; cb_info->cb_data = cb_data; + cb_info->notify_id = notify_id; if (is_framework) cb_info->fwk_cb = cb; else From 6cc03818814aa98c3584a346b82165f1b561f2b7 Mon Sep 17 00:00:00 2001 From: Julian Braha Date: Tue, 20 Oct 2026 23:28:16 +0100 Subject: [PATCH 0025/2102] firmware: smccc: Provide stubs for HAVE_ARM_SMCCC_DISCOVERY=n Add fallbacks for callers to avoid needing #ifdef guards when HAVE_ARM_SMCCC_DISCOVERY is disabled (32-bit arm). Fixes: 35727af2b15d ("irqchip/gicv3: Workaround for NVIDIA erratum T241-FABRIC-4") Suggested-by: Marc Zyngier Signed-off-by: Julian Braha Reviewed-by: Marc Zyngier Link: https://patch.msgid.link/20261020222817.1231643-2-julianbraha@gmail.com Signed-off-by: Sudeep Holla --- include/linux/arm-smccc.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/include/linux/arm-smccc.h b/include/linux/arm-smccc.h index 4de81848fe2eec..75f9d3f1723b58 100644 --- a/include/linux/arm-smccc.h +++ b/include/linux/arm-smccc.h @@ -324,6 +324,7 @@ enum arm_smccc_conduit { SMCCC_CONDUIT_HVC, }; +#ifdef CONFIG_HAVE_ARM_SMCCC_DISCOVERY /** * arm_smccc_1_1_get_conduit() * @@ -363,6 +364,12 @@ s32 arm_smccc_get_soc_id_version(void); * When ARM_SMCCC_ARCH_SOC_ID is not present, returns SMCCC_RET_NOT_SUPPORTED. */ s32 arm_smccc_get_soc_id_revision(void); +#else /* CONFIG_HAVE_ARM_SMCCC_DISCOVERY */ +#define arm_smccc_1_1_get_conduit() SMCCC_CONDUIT_NONE +#define arm_smccc_get_version() 0 +#define arm_smccc_get_soc_id_version() SMCCC_RET_NOT_SUPPORTED +#define arm_smccc_get_soc_id_revision() SMCCC_RET_NOT_SUPPORTED +#endif /* CONFIG_HAVE_ARM_SMCCC_DISCOVERY */ #ifndef __ASSEMBLY__ From 40b097fdfd00516ba9a568ccc10e9f166358ddca Mon Sep 17 00:00:00 2001 From: Julian Braha Date: Tue, 20 Oct 2026 23:28:17 +0100 Subject: [PATCH 0026/2102] irqchip/gic-v3: Select HAVE_ARM_SMCCC_DISCOVERY only on arm64 ARM_PSCI_FW is always enabled for arm64, and the GICv3 driver only uses HAVE_ARM_SMCCC_DISCOVERY to identify the NVIDIA T241, which is arm64 anyway. For ARM_GIC_V3, let's only select HAVE_ARM_SMCCC_DISCOVERY on arm64. Fixes: 35727af2b15d ("irqchip/gicv3: Workaround for NVIDIA erratum T241-FABRIC-4") Suggested-by: Marc Zyngier Reviewed-by: Marc Zyngier Acked-by: Thomas Gleixner Signed-off-by: Julian Braha Link: https://patch.msgid.link/20261020222817.1231643-3-julianbraha@gmail.com Signed-off-by: Sudeep Holla --- drivers/irqchip/Kconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/irqchip/Kconfig b/drivers/irqchip/Kconfig index 20b77fbc51ee03..dae023fed7d6ad 100644 --- a/drivers/irqchip/Kconfig +++ b/drivers/irqchip/Kconfig @@ -37,7 +37,7 @@ config ARM_GIC_V3 bool select IRQ_DOMAIN_HIERARCHY select GENERIC_IRQ_EFFECTIVE_AFF_MASK if SMP - select HAVE_ARM_SMCCC_DISCOVERY + select HAVE_ARM_SMCCC_DISCOVERY if ARM64 select IRQ_MSI_IOMMU config ARM_GIC_ITS_PARENT From 7f73b4cb4b3afff60577e5ddc532fd026b55d4e5 Mon Sep 17 00:00:00 2001 From: Sudeep Holla Date: Mon, 26 Oct 2026 10:55:10 +0000 Subject: [PATCH 0027/2102] firmware: arm_scmi: Drop redundant ACPI configuration guard Commit 98b9bfb659a9 ("ACPI: bus: Use acpi/acpi_bus.h without CONFIG_ACPI") makes the ACPI bus helpers and their stubs available through linux/acpi.h for all configurations. Drop the local CONFIG_ACPI conditional around scmi_acpi_device_hid(). ACPI_COMPANION() returns NULL when ACPI is disabled, so the existing "unknown" fallback preserves the current behavior. Fixes: 17b3cdaa7ab4 ("firmware: arm_scmi: Fall back to ACPI HID when "compatible" is absent") Link: https://patch.msgid.link/20261026105510.1778073-1-sudeep.holla@kernel.org Signed-off-by: Sudeep Holla --- drivers/firmware/arm_scmi/driver.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/drivers/firmware/arm_scmi/driver.c b/drivers/firmware/arm_scmi/driver.c index 599d77abc4a984..97985be0f9cff0 100644 --- a/drivers/firmware/arm_scmi/driver.c +++ b/drivers/firmware/arm_scmi/driver.c @@ -3107,11 +3107,7 @@ static void scmi_debugfs_common_cleanup(void *d) static const char *scmi_acpi_device_hid(struct acpi_device *adev) { -#ifdef CONFIG_ACPI return adev ? acpi_device_hid(adev) : "unknown"; -#else - return "unknown"; -#endif } static struct scmi_debug_info *scmi_debugfs_common_setup(struct scmi_info *info) From 24934cb6b8cd925b7c86ad818929c272a360ec53 Mon Sep 17 00:00:00 2001 From: LiuJunyuan <2058432396@qq.com> Date: Wed, 21 Oct 2026 15:50:05 +0800 Subject: [PATCH 0028/2102] staging: vme_user: delete driver The staging VME userspace drivers are orphaned and Greg KH requested a patch to remove them instead of continuing to fix staging-only issues. Remove the driver, its documentation, Kconfig and Makefile entries, the VME MAINTAINERS section, and stale VME options from the powerpc 86xx config. Signed-off-by: LiuJunyuan <2058432396@qq.com> Link: https://patch.msgid.link/tencent_6DFC9819B65A274390D9E2A01B3C1C9D160A@qq.com Signed-off-by: Greg Kroah-Hartman --- Documentation/driver-api/index.rst | 1 - Documentation/driver-api/vme.rst | 297 --- MAINTAINERS | 7 - arch/powerpc/configs/86xx-hw.config | 2 - drivers/staging/Kconfig | 2 - drivers/staging/Makefile | 1 - drivers/staging/vme_user/Kconfig | 53 - drivers/staging/vme_user/Makefile | 9 - drivers/staging/vme_user/vme.c | 1977 ------------------ drivers/staging/vme_user/vme.h | 190 -- drivers/staging/vme_user/vme_bridge.h | 190 -- drivers/staging/vme_user/vme_fake.c | 1308 ------------ drivers/staging/vme_user/vme_tsi148.c | 2643 ------------------------- drivers/staging/vme_user/vme_tsi148.h | 1392 ------------- drivers/staging/vme_user/vme_user.c | 812 -------- drivers/staging/vme_user/vme_user.h | 47 - 16 files changed, 8931 deletions(-) delete mode 100644 Documentation/driver-api/vme.rst delete mode 100644 drivers/staging/vme_user/Kconfig delete mode 100644 drivers/staging/vme_user/Makefile delete mode 100644 drivers/staging/vme_user/vme.c delete mode 100644 drivers/staging/vme_user/vme.h delete mode 100644 drivers/staging/vme_user/vme_bridge.h delete mode 100644 drivers/staging/vme_user/vme_fake.c delete mode 100644 drivers/staging/vme_user/vme_tsi148.c delete mode 100644 drivers/staging/vme_user/vme_tsi148.h delete mode 100644 drivers/staging/vme_user/vme_user.c delete mode 100644 drivers/staging/vme_user/vme_user.h diff --git a/Documentation/driver-api/index.rst b/Documentation/driver-api/index.rst index aaf5d76ed074ed..f92448a3de0cd3 100644 --- a/Documentation/driver-api/index.rst +++ b/Documentation/driver-api/index.rst @@ -67,7 +67,6 @@ Bus-level documentation slimbus usb/index virtio/index - vme w1 xillybus diff --git a/Documentation/driver-api/vme.rst b/Documentation/driver-api/vme.rst deleted file mode 100644 index 7111999abc14ce..00000000000000 --- a/Documentation/driver-api/vme.rst +++ /dev/null @@ -1,297 +0,0 @@ -VME Device Drivers -================== - -Driver registration -------------------- - -As with other subsystems within the Linux kernel, VME device drivers register -with the VME subsystem, typically called from the devices init routine. This is -achieved via a call to :c:func:`vme_register_driver`. - -A pointer to a structure of type :c:type:`struct vme_driver ` must -be provided to the registration function. Along with the maximum number of -devices your driver is able to support. - -At the minimum, the '.name', '.match' and '.probe' elements of -:c:type:`struct vme_driver ` should be correctly set. The '.name' -element is a pointer to a string holding the device driver's name. - -The '.match' function allows control over which VME devices should be registered -with the driver. The match function should return 1 if a device should be -probed and 0 otherwise. This example match function (from vme_user.c) limits -the number of devices probed to one: - -.. code-block:: c - - #define USER_BUS_MAX 1 - ... - static int vme_user_match(struct vme_dev *vdev) - { - if (vdev->id.num >= USER_BUS_MAX) - return 0; - return 1; - } - -The '.probe' element should contain a pointer to the probe routine. The -probe routine is passed a :c:type:`struct vme_dev ` pointer as an -argument. - -Here, the 'num' field refers to the sequential device ID for this specific -driver. The bridge number (or bus number) can be accessed using -dev->bridge->num. - -A function is also provided to unregister the driver from the VME core called -:c:func:`vme_unregister_driver` and should usually be called from the device -driver's exit routine. - - -Resource management -------------------- - -Once a driver has registered with the VME core the provided match routine will -be called the number of times specified during the registration. If a match -succeeds, a non-zero value should be returned. A zero return value indicates -failure. For all successful matches, the probe routine of the corresponding -driver is called. The probe routine is passed a pointer to the devices -device structure. This pointer should be saved, it will be required for -requesting VME resources. - -The driver can request ownership of one or more master windows -(:c:func:`vme_master_request`), slave windows (:c:func:`vme_slave_request`) -and/or dma channels (:c:func:`vme_dma_request`). Rather than allowing the device -driver to request a specific window or DMA channel (which may be used by a -different driver) the API allows a resource to be assigned based on the required -attributes of the driver in question. For slave windows these attributes are -split into the VME address spaces that need to be accessed in 'aspace' and VME -bus cycle types required in 'cycle'. Master windows add a further set of -attributes in 'width' specifying the required data transfer widths. These -attributes are defined as bitmasks and as such any combination of the -attributes can be requested for a single window, the core will assign a window -that meets the requirements, returning a pointer of type vme_resource that -should be used to identify the allocated resource when it is used. For DMA -controllers, the request function requires the potential direction of any -transfers to be provided in the route attributes. This is typically VME-to-MEM -and/or MEM-to-VME, though some hardware can support VME-to-VME and MEM-to-MEM -transfers as well as test pattern generation. If an unallocated window fitting -the requirements can not be found a NULL pointer will be returned. - -Functions are also provided to free window allocations once they are no longer -required. These functions (:c:func:`vme_master_free`, :c:func:`vme_slave_free` -and :c:func:`vme_dma_free`) should be passed the pointer to the resource -provided during resource allocation. - - -Master windows --------------- - -Master windows provide access from the local processor[s] out onto the VME bus. -The number of windows available and the available access modes is dependent on -the underlying chipset. A window must be configured before it can be used. - - -Master window configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Once a master window has been assigned :c:func:`vme_master_set` can be used to -configure it and :c:func:`vme_master_get` to retrieve the current settings. The -address spaces, transfer widths and cycle types are the same as described -under resource management, however some of the options are mutually exclusive. -For example, only one address space may be specified. - - -Master window access -~~~~~~~~~~~~~~~~~~~~ - -The function :c:func:`vme_master_read` can be used to read from and -:c:func:`vme_master_write` used to write to configured master windows. - -In addition to simple reads and writes, :c:func:`vme_master_rmw` is provided to -do a read-modify-write transaction. Parts of a VME window can also be mapped -into user space memory using :c:func:`vme_master_mmap_prepare`. - - -Slave windows -------------- - -Slave windows provide devices on the VME bus access into mapped portions of the -local memory. The number of windows available and the access modes that can be -used is dependent on the underlying chipset. A window must be configured before -it can be used. - - -Slave window configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Once a slave window has been assigned :c:func:`vme_slave_set` can be used to -configure it and :c:func:`vme_slave_get` to retrieve the current settings. - -The address spaces, transfer widths and cycle types are the same as described -under resource management, however some of the options are mutually exclusive. -For example, only one address space may be specified. - - -Slave window buffer allocation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Functions are provided to allow the user to allocate -(:c:func:`vme_alloc_consistent`) and free (:c:func:`vme_free_consistent`) -contiguous buffers which will be accessible by the VME bridge. These functions -do not have to be used, other methods can be used to allocate a buffer, though -care must be taken to ensure that they are contiguous and accessible by the VME -bridge. - - -Slave window access -~~~~~~~~~~~~~~~~~~~ - -Slave windows map local memory onto the VME bus, the standard methods for -accessing memory should be used. - - -DMA channels ------------- - -The VME DMA transfer provides the ability to run link-list DMA transfers. The -API introduces the concept of DMA lists. Each DMA list is a link-list which can -be passed to a DMA controller. Multiple lists can be created, extended, -executed, reused and destroyed. - - -List Management -~~~~~~~~~~~~~~~ - -The function :c:func:`vme_new_dma_list` is provided to create and -:c:func:`vme_dma_list_free` to destroy DMA lists. Execution of a list will not -automatically destroy the list, thus enabling a list to be reused for repetitive -tasks. - - -List Population -~~~~~~~~~~~~~~~ - -An item can be added to a list using :c:func:`vme_dma_list_add` (the source and -destination attributes need to be created before calling this function, this is -covered under "Transfer Attributes"). - -.. note:: - - The detailed attributes of the transfers source and destination - are not checked until an entry is added to a DMA list, the request - for a DMA channel purely checks the directions in which the - controller is expected to transfer data. As a result it is - possible for this call to return an error, for example if the - source or destination is in an unsupported VME address space. - -Transfer Attributes -~~~~~~~~~~~~~~~~~~~ - -The attributes for the source and destination are handled separately from adding -an item to a list. This is due to the diverse attributes required for each type -of source and destination. There are functions to create attributes for PCI, VME -and pattern sources and destinations (where appropriate): - - - PCI source or destination: :c:func:`vme_dma_pci_attribute` - - VME source or destination: :c:func:`vme_dma_vme_attribute` - - Pattern source: :c:func:`vme_dma_pattern_attribute` - -The function :c:func:`vme_dma_free_attribute` should be used to free an -attribute. - - -List Execution -~~~~~~~~~~~~~~ - -The function :c:func:`vme_dma_list_exec` queues a list for execution and will -return once the list has been executed. - - -Interrupts ----------- - -The VME API provides functions to attach and detach callbacks to specific VME -level and status ID combinations and for the generation of VME interrupts with -specific VME level and status IDs. - - -Attaching Interrupt Handlers -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The function :c:func:`vme_irq_request` can be used to attach and -:c:func:`vme_irq_free` to free a specific VME level and status ID combination. -Any given combination can only be assigned a single callback function. A void -pointer parameter is provided, the value of which is passed to the callback -function, the use of this pointer is user undefined. The callback parameters are -as follows. Care must be taken in writing a callback function, callback -functions run in interrupt context: - -.. code-block:: c - - void callback(int level, int statid, void *priv); - - -Interrupt Generation -~~~~~~~~~~~~~~~~~~~~ - -The function :c:func:`vme_irq_generate` can be used to generate a VME interrupt -at a given VME level and VME status ID. - - -Location monitors ------------------ - -The VME API provides the following functionality to configure the location -monitor. - - -Location Monitor Management -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The function :c:func:`vme_lm_request` is provided to request the use of a block -of location monitors and :c:func:`vme_lm_free` to free them after they are no -longer required. Each block may provide a number of location monitors, -monitoring adjacent locations. The function :c:func:`vme_lm_count` can be used -to determine how many locations are provided. - - -Location Monitor Configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Once a bank of location monitors has been allocated, the function -:c:func:`vme_lm_set` is provided to configure the location and mode of the -location monitor. The function :c:func:`vme_lm_get` can be used to retrieve -existing settings. - - -Location Monitor Use -~~~~~~~~~~~~~~~~~~~~ - -The function :c:func:`vme_lm_attach` enables a callback to be attached and -:c:func:`vme_lm_detach` allows on to be detached from each location monitor -location. Each location monitor can monitor a number of adjacent locations. The -callback function is declared as follows. - -.. code-block:: c - - void callback(void *data); - - -Slot Detection --------------- - -The function :c:func:`vme_slot_num` returns the slot ID of the provided bridge. - - -Bus Detection -------------- - -The function :c:func:`vme_bus_num` returns the bus ID of the provided bridge. - - -VME API -------- - -.. kernel-doc:: drivers/staging/vme_user/vme.h - :internal: - -.. kernel-doc:: drivers/staging/vme_user/vme.c - :export: diff --git a/MAINTAINERS b/MAINTAINERS index 03649f08c7c75b..da8cf5fcf90892 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -29783,13 +29783,6 @@ F: mm/vmalloc.c F: mm/vmalloc.h F: lib/test_vmalloc.c -VME SUBSYSTEM -L: linux-kernel@vger.kernel.org -S: Orphan -T: git git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/char-misc.git -F: Documentation/driver-api/vme.rst -F: drivers/staging/vme_user/ - VMWARE BALLOON DRIVER M: Jerrin Shaji George R: Broadcom internal kernel review list diff --git a/arch/powerpc/configs/86xx-hw.config b/arch/powerpc/configs/86xx-hw.config index 07f30ab881e59d..eb3ebf90888872 100644 --- a/arch/powerpc/configs/86xx-hw.config +++ b/arch/powerpc/configs/86xx-hw.config @@ -91,8 +91,6 @@ CONFIG_USB_OHCI_HCD=y CONFIG_USB_STORAGE=y CONFIG_USB=y CONFIG_VITESSE_PHY=y -CONFIG_VME_BUS=y -CONFIG_VME_TSI148=y CONFIG_WATCHDOG=y # CONFIG_YENTA_O2 is not set # CONFIG_YENTA_RICOH is not set diff --git a/drivers/staging/Kconfig b/drivers/staging/Kconfig index 46b460bfb4361a..7c57f362f1b7e7 100644 --- a/drivers/staging/Kconfig +++ b/drivers/staging/Kconfig @@ -44,6 +44,4 @@ source "drivers/staging/vc04_services/Kconfig" source "drivers/staging/axis-fifo/Kconfig" -source "drivers/staging/vme_user/Kconfig" - endif # STAGING diff --git a/drivers/staging/Makefile b/drivers/staging/Makefile index 7e2e7a7e773ad2..f827853ad8a6b1 100644 --- a/drivers/staging/Makefile +++ b/drivers/staging/Makefile @@ -3,7 +3,6 @@ obj-y += media/ obj-$(CONFIG_OCTEON_ETHERNET) += octeon/ -obj-$(CONFIG_VME_BUS) += vme_user/ obj-$(CONFIG_IIO) += iio/ obj-$(CONFIG_FB_SM750) += sm750fb/ obj-$(CONFIG_MFD_NVEC) += nvec/ diff --git a/drivers/staging/vme_user/Kconfig b/drivers/staging/vme_user/Kconfig deleted file mode 100644 index 8e5df6ce36e8f9..00000000000000 --- a/drivers/staging/vme_user/Kconfig +++ /dev/null @@ -1,53 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0 -menuconfig VME_BUS - bool "VME bridge support" - depends on PCI - help - Enable support for VME (VersaModular Eurocard bus) bridge modules. - The bridge allows connecting VME devices to systems with existing - interfaces (like USB or PCI) by means of translating VME protocol - operations. - - Note that this only enables the bridge framework. You'll also - likely want to enable driver for specific bridge device you have - to actually use it. If unsure, say N. - -if VME_BUS - -comment "VME Bridge Drivers" - -config VME_TSI148 - tristate "Tundra TSI148 VME bridge support" - depends on HAS_DMA - help - If you say Y here you get support for the Tundra TSI148 VME-to-PCI/X - bridge chip (and pin-compatible clones). - - TSI148 is a high-performant, 2eSST and VME64-compliant VME-to-PCI/X - interconnect bridge with support for PCI and PCI-X bus interface. - It is primarily used in industrial and embedded systems. - - To compile this driver as a module, say M - the module will be - called vme_tsi148. If unsure, say N. - -config VME_FAKE - tristate "Fake" - help - If you say Y here you get support for the fake VME bridge. This - provides a virtualised VME Bus for devices with no VME bridge. This - is mainly useful for VME development (in the absence of VME - hardware). - -comment "VME Device Drivers" - -config VME_USER - tristate "VME user space access driver" - help - If you say Y here you want to be able to access a limited number of - VME windows in a manner at least semi-compatible with the interface - provided with the original driver at . - - To compile this driver as a module, choose M here. The module will - be called vme_user. If unsure, say N. - -endif diff --git a/drivers/staging/vme_user/Makefile b/drivers/staging/vme_user/Makefile deleted file mode 100644 index 8dcc6938ce5c56..00000000000000 --- a/drivers/staging/vme_user/Makefile +++ /dev/null @@ -1,9 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0 -# -# Makefile for the VME device drivers. -# - -obj-$(CONFIG_VME_BUS) += vme.o -obj-$(CONFIG_VME_USER) += vme_user.o -obj-$(CONFIG_VME_TSI148) += vme_tsi148.o -obj-$(CONFIG_VME_FAKE) += vme_fake.o diff --git a/drivers/staging/vme_user/vme.c b/drivers/staging/vme_user/vme.c deleted file mode 100644 index d38c792eb89056..00000000000000 --- a/drivers/staging/vme_user/vme.c +++ /dev/null @@ -1,1977 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -/* - * VME Bridge Framework - * - * Author: Martyn Welch - * Copyright 2008 GE Intelligent Platforms Embedded Systems, Inc. - * - * Based on work by Tom Armistead and Ajit Prem - * Copyright 2004 Motorola Inc. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "vme.h" -#include "vme_bridge.h" - -/* Bitmask and list of registered buses both protected by common mutex */ -static unsigned int vme_bus_numbers; -static LIST_HEAD(vme_bus_list); -static DEFINE_MUTEX(vme_buses_lock); - -static int __init vme_init(void); - -static struct vme_dev *dev_to_vme_dev(struct device *dev) -{ - return container_of(dev, struct vme_dev, dev); -} - -/* - * Find the bridge that the resource is associated with. - */ -static struct vme_bridge *find_bridge(struct vme_resource *resource) -{ - /* Get list to search */ - switch (resource->type) { - case VME_MASTER: - return list_entry(resource->entry, struct vme_master_resource, - list)->parent; - case VME_SLAVE: - return list_entry(resource->entry, struct vme_slave_resource, - list)->parent; - case VME_DMA: - return list_entry(resource->entry, struct vme_dma_resource, - list)->parent; - case VME_LM: - return list_entry(resource->entry, struct vme_lm_resource, - list)->parent; - default: - return NULL; - } -} - -/** - * vme_alloc_consistent - Allocate contiguous memory. - * @resource: Pointer to VME resource. - * @size: Size of allocation required. - * @dma: Pointer to variable to store physical address of allocation. - * - * Allocate a contiguous block of memory for use by the driver. This is used to - * create the buffers for the slave windows. - * - * Return: Virtual address of allocation on success, NULL on failure. - */ -void *vme_alloc_consistent(struct vme_resource *resource, size_t size, - dma_addr_t *dma) -{ - struct vme_bridge *bridge = find_bridge(resource); - - if (!bridge->alloc_consistent) { - dev_err(bridge->parent, - "alloc_consistent not supported by bridge %s\n", - bridge->name); - return NULL; - } - - return bridge->alloc_consistent(bridge->parent, size, dma); -} -EXPORT_SYMBOL(vme_alloc_consistent); - -/** - * vme_free_consistent - Free previously allocated memory. - * @resource: Pointer to VME resource. - * @size: Size of allocation to free. - * @vaddr: Virtual address of allocation. - * @dma: Physical address of allocation. - * - * Free previously allocated block of contiguous memory. - */ -void vme_free_consistent(struct vme_resource *resource, size_t size, - void *vaddr, dma_addr_t dma) -{ - struct vme_bridge *bridge = find_bridge(resource); - - if (!bridge->free_consistent) { - dev_err(bridge->parent, - "free_consistent not supported by bridge %s\n", - bridge->name); - return; - } - - bridge->free_consistent(bridge->parent, size, vaddr, dma); -} -EXPORT_SYMBOL(vme_free_consistent); - -/** - * vme_get_size - Helper function returning size of a VME window - * @resource: Pointer to VME slave or master resource. - * - * Determine the size of the VME window provided. This is a helper - * function, wrappering the call to vme_master_get or vme_slave_get - * depending on the type of window resource handed to it. - * - * Return: Size of the window on success, zero on failure. - */ -size_t vme_get_size(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - int enabled, retval; - unsigned long long base, size; - dma_addr_t buf_base; - u32 aspace, cycle, dwidth; - - switch (resource->type) { - case VME_MASTER: - retval = vme_master_get(resource, &enabled, &base, &size, - &aspace, &cycle, &dwidth); - if (retval) - return 0; - - return size; - case VME_SLAVE: - retval = vme_slave_get(resource, &enabled, &base, &size, - &buf_base, &aspace, &cycle); - if (retval) - return 0; - - return size; - case VME_DMA: - return 0; - default: - dev_err(bridge->parent, "Unknown resource type\n"); - return 0; - } -} -EXPORT_SYMBOL(vme_get_size); - -int vme_check_window(struct vme_bridge *bridge, u32 aspace, - unsigned long long vme_base, unsigned long long size) -{ - int retval = 0; - - if (vme_base + size < size) - return -EINVAL; - - switch (aspace) { - case VME_A16: - if (vme_base + size > VME_A16_MAX) - retval = -EFAULT; - break; - case VME_A24: - if (vme_base + size > VME_A24_MAX) - retval = -EFAULT; - break; - case VME_A32: - if (vme_base + size > VME_A32_MAX) - retval = -EFAULT; - break; - case VME_A64: - /* The VME_A64_MAX limit is actually U64_MAX + 1 */ - break; - case VME_CRCSR: - if (vme_base + size > VME_CRCSR_MAX) - retval = -EFAULT; - break; - case VME_USER1: - case VME_USER2: - case VME_USER3: - case VME_USER4: - /* User Defined */ - break; - default: - dev_err(bridge->parent, "Invalid address space\n"); - retval = -EINVAL; - break; - } - - return retval; -} -EXPORT_SYMBOL(vme_check_window); - -static u32 vme_get_aspace(int am) -{ - switch (am) { - case 0x29: - case 0x2D: - return VME_A16; - case 0x38: - case 0x39: - case 0x3A: - case 0x3B: - case 0x3C: - case 0x3D: - case 0x3E: - case 0x3F: - return VME_A24; - case 0x8: - case 0x9: - case 0xA: - case 0xB: - case 0xC: - case 0xD: - case 0xE: - case 0xF: - return VME_A32; - case 0x0: - case 0x1: - case 0x3: - return VME_A64; - } - - return 0; -} - -/** - * vme_slave_request - Request a VME slave window resource. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @address: Required VME address space. - * @cycle: Required VME data transfer cycle type. - * - * Request use of a VME window resource capable of being set for the requested - * address space and data transfer cycle. - * - * Return: Pointer to VME resource on success, NULL on failure. - */ -struct vme_resource *vme_slave_request(struct vme_dev *vdev, u32 address, - u32 cycle) -{ - struct vme_bridge *bridge; - struct vme_slave_resource *allocated_image = NULL; - struct vme_slave_resource *slave_image; - struct vme_resource *resource = NULL; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - goto err_bus; - } - - /* Loop through slave resources */ - list_for_each_entry(slave_image, &bridge->slave_resources, list) { - if (!slave_image) { - dev_err(bridge->parent, - "Registered NULL Slave resource\n"); - continue; - } - - /* Find an unlocked and compatible image */ - mutex_lock(&slave_image->mtx); - if (((slave_image->address_attr & address) == address) && - ((slave_image->cycle_attr & cycle) == cycle) && - !slave_image->locked) { - slave_image->locked = 1; - mutex_unlock(&slave_image->mtx); - allocated_image = slave_image; - break; - } - mutex_unlock(&slave_image->mtx); - } - - /* No free image */ - if (!allocated_image) - goto err_image; - - resource = kmalloc_obj(*resource); - if (!resource) - goto err_alloc; - - resource->type = VME_SLAVE; - resource->entry = &allocated_image->list; - - return resource; - -err_alloc: - /* Unlock image */ - mutex_lock(&allocated_image->mtx); - allocated_image->locked = 0; - mutex_unlock(&allocated_image->mtx); -err_image: -err_bus: - return NULL; -} -EXPORT_SYMBOL(vme_slave_request); - -/** - * vme_slave_set - Set VME slave window configuration. - * @resource: Pointer to VME slave resource. - * @enabled: State to which the window should be configured. - * @vme_base: Base address for the window. - * @size: Size of the VME window. - * @buf_base: Based address of buffer used to provide VME slave window storage. - * @aspace: VME address space for the VME window. - * @cycle: VME data transfer cycle type for the VME window. - * - * Set configuration for provided VME slave window. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device, if an invalid resource has been provided or invalid - * attributes are provided. Hardware specific errors may also be - * returned. - */ -int vme_slave_set(struct vme_resource *resource, int enabled, - unsigned long long vme_base, unsigned long long size, - dma_addr_t buf_base, u32 aspace, u32 cycle) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_slave_resource *image; - int retval; - - if (resource->type != VME_SLAVE) { - dev_err(bridge->parent, "Not a slave resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_slave_resource, list); - - if (!bridge->slave_set) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - if (!(((image->address_attr & aspace) == aspace) && - ((image->cycle_attr & cycle) == cycle))) { - dev_err(bridge->parent, "Invalid attributes\n"); - return -EINVAL; - } - - retval = vme_check_window(bridge, aspace, vme_base, size); - if (retval) - return retval; - - return bridge->slave_set(image, enabled, vme_base, size, buf_base, - aspace, cycle); -} -EXPORT_SYMBOL(vme_slave_set); - -/** - * vme_slave_get - Retrieve VME slave window configuration. - * @resource: Pointer to VME slave resource. - * @enabled: Pointer to variable for storing state. - * @vme_base: Pointer to variable for storing window base address. - * @size: Pointer to variable for storing window size. - * @buf_base: Pointer to variable for storing slave buffer base address. - * @aspace: Pointer to variable for storing VME address space. - * @cycle: Pointer to variable for storing VME data transfer cycle type. - * - * Return configuration for provided VME slave window. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device or if an invalid resource has been provided. - */ -int vme_slave_get(struct vme_resource *resource, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - dma_addr_t *buf_base, u32 *aspace, u32 *cycle) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_slave_resource *image; - - if (resource->type != VME_SLAVE) { - dev_err(bridge->parent, "Not a slave resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_slave_resource, list); - - if (!bridge->slave_get) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->slave_get(image, enabled, vme_base, size, buf_base, - aspace, cycle); -} -EXPORT_SYMBOL(vme_slave_get); - -/** - * vme_slave_free - Free VME slave window - * @resource: Pointer to VME slave resource. - * - * Free the provided slave resource so that it may be reallocated. - */ -void vme_slave_free(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_slave_resource *slave_image; - - if (resource->type != VME_SLAVE) { - dev_err(bridge->parent, "Not a slave resource\n"); - return; - } - - slave_image = list_entry(resource->entry, struct vme_slave_resource, - list); - - /* Unlock image */ - mutex_lock(&slave_image->mtx); - if (!slave_image->locked) - dev_err(bridge->parent, "Image is already free\n"); - - slave_image->locked = 0; - mutex_unlock(&slave_image->mtx); - - /* Free up resource memory */ - kfree(resource); -} -EXPORT_SYMBOL(vme_slave_free); - -/** - * vme_master_request - Request a VME master window resource. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @address: Required VME address space. - * @cycle: Required VME data transfer cycle type. - * @dwidth: Required VME data transfer width. - * - * Request use of a VME window resource capable of being set for the requested - * address space, data transfer cycle and width. - * - * Return: Pointer to VME resource on success, NULL on failure. - */ -struct vme_resource *vme_master_request(struct vme_dev *vdev, u32 address, - u32 cycle, u32 dwidth) -{ - struct vme_bridge *bridge; - struct vme_master_resource *allocated_image = NULL; - struct vme_master_resource *master_image; - struct vme_resource *resource = NULL; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - goto err_bus; - } - - /* Loop through master resources */ - list_for_each_entry(master_image, &bridge->master_resources, list) { - if (!master_image) { - dev_warn(bridge->parent, - "Registered NULL master resource\n"); - continue; - } - - /* Find an unlocked and compatible image */ - spin_lock(&master_image->lock); - if (((master_image->address_attr & address) == address) && - ((master_image->cycle_attr & cycle) == cycle) && - ((master_image->width_attr & dwidth) == dwidth) && - !master_image->locked) { - master_image->locked = 1; - spin_unlock(&master_image->lock); - allocated_image = master_image; - break; - } - spin_unlock(&master_image->lock); - } - - /* Check to see if we found a resource */ - if (!allocated_image) { - dev_err(&vdev->dev, "Can't find a suitable resource\n"); - goto err_image; - } - - resource = kmalloc_obj(*resource); - if (!resource) - goto err_alloc; - - resource->type = VME_MASTER; - resource->entry = &allocated_image->list; - - return resource; - -err_alloc: - /* Unlock image */ - spin_lock(&allocated_image->lock); - allocated_image->locked = 0; - spin_unlock(&allocated_image->lock); -err_image: -err_bus: - return NULL; -} -EXPORT_SYMBOL(vme_master_request); - -/** - * vme_master_set - Set VME master window configuration. - * @resource: Pointer to VME master resource. - * @enabled: State to which the window should be configured. - * @vme_base: Base address for the window. - * @size: Size of the VME window. - * @aspace: VME address space for the VME window. - * @cycle: VME data transfer cycle type for the VME window. - * @dwidth: VME data transfer width for the VME window. - * - * Set configuration for provided VME master window. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device, if an invalid resource has been provided or invalid - * attributes are provided. Hardware specific errors may also be - * returned. - */ -int vme_master_set(struct vme_resource *resource, int enabled, - unsigned long long vme_base, unsigned long long size, - u32 aspace, u32 cycle, u32 dwidth) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - int retval; - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - - if (!bridge->master_set) { - dev_warn(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - if (!(((image->address_attr & aspace) == aspace) && - ((image->cycle_attr & cycle) == cycle) && - ((image->width_attr & dwidth) == dwidth))) { - dev_warn(bridge->parent, "Invalid attributes\n"); - return -EINVAL; - } - - retval = vme_check_window(bridge, aspace, vme_base, size); - if (retval) - return retval; - - return bridge->master_set(image, enabled, vme_base, size, aspace, - cycle, dwidth); -} -EXPORT_SYMBOL(vme_master_set); - -/** - * vme_master_get - Retrieve VME master window configuration. - * @resource: Pointer to VME master resource. - * @enabled: Pointer to variable for storing state. - * @vme_base: Pointer to variable for storing window base address. - * @size: Pointer to variable for storing window size. - * @aspace: Pointer to variable for storing VME address space. - * @cycle: Pointer to variable for storing VME data transfer cycle type. - * @dwidth: Pointer to variable for storing VME data transfer width. - * - * Return configuration for provided VME master window. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device or if an invalid resource has been provided. - */ -int vme_master_get(struct vme_resource *resource, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - - if (!bridge->master_get) { - dev_warn(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->master_get(image, enabled, vme_base, size, aspace, - cycle, dwidth); -} -EXPORT_SYMBOL(vme_master_get); - -/** - * vme_master_read - Read data from VME space into a buffer. - * @resource: Pointer to VME master resource. - * @buf: Pointer to buffer where data should be transferred. - * @count: Number of bytes to transfer. - * @offset: Offset into VME master window at which to start transfer. - * - * Perform read of count bytes of data from location on VME bus which maps into - * the VME master window at offset to buf. - * - * Return: Number of bytes read, -EINVAL if resource is not a VME master - * resource or read operation is not supported. -EFAULT returned if - * invalid offset is provided. Hardware specific errors may also be - * returned. - */ -ssize_t vme_master_read(struct vme_resource *resource, void *buf, size_t count, - loff_t offset) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - size_t length; - - if (!bridge->master_read) { - dev_warn(bridge->parent, - "Reading from resource not supported\n"); - return -EINVAL; - } - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - - length = vme_get_size(resource); - - if (offset > length) { - dev_warn(bridge->parent, "Invalid Offset\n"); - return -EFAULT; - } - - if ((offset + count) > length) - count = length - offset; - - return bridge->master_read(image, buf, count, offset); -} -EXPORT_SYMBOL(vme_master_read); - -/** - * vme_master_write - Write data out to VME space from a buffer. - * @resource: Pointer to VME master resource. - * @buf: Pointer to buffer holding data to transfer. - * @count: Number of bytes to transfer. - * @offset: Offset into VME master window at which to start transfer. - * - * Perform write of count bytes of data from buf to location on VME bus which - * maps into the VME master window at offset. - * - * Return: Number of bytes written, -EINVAL if resource is not a VME master - * resource or write operation is not supported. -EFAULT returned if - * invalid offset is provided. Hardware specific errors may also be - * returned. - */ -ssize_t vme_master_write(struct vme_resource *resource, void *buf, - size_t count, loff_t offset) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - size_t length; - - if (!bridge->master_write) { - dev_warn(bridge->parent, "Writing to resource not supported\n"); - return -EINVAL; - } - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - - length = vme_get_size(resource); - - if (offset > length) { - dev_warn(bridge->parent, "Invalid Offset\n"); - return -EFAULT; - } - - if ((offset + count) > length) - count = length - offset; - - return bridge->master_write(image, buf, count, offset); -} -EXPORT_SYMBOL(vme_master_write); - -/** - * vme_master_rmw - Perform read-modify-write cycle. - * @resource: Pointer to VME master resource. - * @mask: Bits to be compared and swapped in operation. - * @compare: Bits to be compared with data read from offset. - * @swap: Bits to be swapped in data read from offset. - * @offset: Offset into VME master window at which to perform operation. - * - * Perform read-modify-write cycle on provided location: - * - Location on VME bus is read. - * - Bits selected by mask are compared with compare. - * - Where a selected bit matches that in compare and are selected in swap, - * the bit is swapped. - * - Result written back to location on VME bus. - * - * Return: Bytes written on success, -EINVAL if resource is not a VME master - * resource or RMW operation is not supported. Hardware specific - * errors may also be returned. - */ -unsigned int vme_master_rmw(struct vme_resource *resource, unsigned int mask, - unsigned int compare, unsigned int swap, loff_t offset) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - - if (!bridge->master_rmw) { - dev_warn(bridge->parent, "Writing to resource not supported\n"); - return -EINVAL; - } - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - - return bridge->master_rmw(image, mask, compare, swap, offset); -} -EXPORT_SYMBOL(vme_master_rmw); - -/** - * vme_master_mmap_prepare - Mmap region of VME master window. - * @resource: Pointer to VME master resource. - * @desc: Pointer to descriptor of user mapping. - * - * Memory map a region of the VME master window into user space. - * - * Return: Zero on success, -EINVAL if resource is not a VME master - * resource or -EFAULT if map exceeds window size. Other generic mmap - * errors may also be returned. - */ -int vme_master_mmap_prepare(struct vme_resource *resource, - struct vm_area_desc *desc) -{ - const unsigned long vma_size = vma_desc_size(desc); - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - phys_addr_t phys_addr; - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - phys_addr = image->bus_resource.start + (desc->pgoff << PAGE_SHIFT); - - if (phys_addr + vma_size > image->bus_resource.end + 1) { - dev_err(bridge->parent, "Map size cannot exceed the window size\n"); - return -EFAULT; - } - - desc->page_prot = pgprot_noncached(desc->page_prot); - mmap_action_simple_ioremap(desc, phys_addr, vma_size); - return 0; -} -EXPORT_SYMBOL(vme_master_mmap_prepare); - -/** - * vme_master_free - Free VME master window - * @resource: Pointer to VME master resource. - * - * Free the provided master resource so that it may be reallocated. - */ -void vme_master_free(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *master_image; - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return; - } - - master_image = list_entry(resource->entry, struct vme_master_resource, - list); - - /* Unlock image */ - spin_lock(&master_image->lock); - if (!master_image->locked) - dev_err(bridge->parent, "Image is already free\n"); - - master_image->locked = 0; - spin_unlock(&master_image->lock); - - /* Free up resource memory */ - kfree(resource); -} -EXPORT_SYMBOL(vme_master_free); - -/** - * vme_dma_request - Request a DMA controller. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @route: Required src/destination combination. - * - * Request a VME DMA controller with capability to perform transfers between - * requested source/destination combination. - * - * Return: Pointer to VME DMA resource on success, NULL on failure. - */ -struct vme_resource *vme_dma_request(struct vme_dev *vdev, u32 route) -{ - struct vme_bridge *bridge; - struct vme_dma_resource *allocated_ctrlr = NULL; - struct vme_dma_resource *dma_ctrlr; - struct vme_resource *resource = NULL; - - /* XXX Not checking resource attributes */ - dev_err(&vdev->dev, "No VME resource Attribute tests done\n"); - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - goto err_bus; - } - - /* Loop through DMA resources */ - list_for_each_entry(dma_ctrlr, &bridge->dma_resources, list) { - if (!dma_ctrlr) { - dev_err(bridge->parent, - "Registered NULL DMA resource\n"); - continue; - } - - /* Find an unlocked and compatible controller */ - mutex_lock(&dma_ctrlr->mtx); - if (((dma_ctrlr->route_attr & route) == route) && - !dma_ctrlr->locked) { - dma_ctrlr->locked = 1; - mutex_unlock(&dma_ctrlr->mtx); - allocated_ctrlr = dma_ctrlr; - break; - } - mutex_unlock(&dma_ctrlr->mtx); - } - - /* Check to see if we found a resource */ - if (!allocated_ctrlr) - goto err_ctrlr; - - resource = kmalloc_obj(*resource); - if (!resource) - goto err_alloc; - - resource->type = VME_DMA; - resource->entry = &allocated_ctrlr->list; - - return resource; - -err_alloc: - /* Unlock image */ - mutex_lock(&allocated_ctrlr->mtx); - allocated_ctrlr->locked = 0; - mutex_unlock(&allocated_ctrlr->mtx); -err_ctrlr: -err_bus: - return NULL; -} -EXPORT_SYMBOL(vme_dma_request); - -/** - * vme_new_dma_list - Create new VME DMA list. - * @resource: Pointer to VME DMA resource. - * - * Create a new VME DMA list. It is the responsibility of the user to free - * the list once it is no longer required with vme_dma_list_free(). - * - * Return: Pointer to new VME DMA list, NULL on allocation failure or invalid - * VME DMA resource. - */ -struct vme_dma_list *vme_new_dma_list(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_dma_list *dma_list; - - if (resource->type != VME_DMA) { - dev_err(bridge->parent, "Not a DMA resource\n"); - return NULL; - } - - dma_list = kmalloc_obj(*dma_list); - if (!dma_list) - return NULL; - - INIT_LIST_HEAD(&dma_list->entries); - dma_list->parent = list_entry(resource->entry, - struct vme_dma_resource, - list); - mutex_init(&dma_list->mtx); - - return dma_list; -} -EXPORT_SYMBOL(vme_new_dma_list); - -/** - * vme_dma_pattern_attribute - Create "Pattern" type VME DMA list attribute. - * @pattern: Value to use used as pattern - * @type: Type of pattern to be written. - * - * Create VME DMA list attribute for pattern generation. It is the - * responsibility of the user to free used attributes using - * vme_dma_free_attribute(). - * - * Return: Pointer to VME DMA attribute, NULL on failure. - */ -struct vme_dma_attr *vme_dma_pattern_attribute(u32 pattern, u32 type) -{ - struct vme_dma_attr *attributes; - struct vme_dma_pattern *pattern_attr; - - attributes = kmalloc_obj(*attributes); - if (!attributes) - goto err_attr; - - pattern_attr = kmalloc_obj(*pattern_attr); - if (!pattern_attr) - goto err_pat; - - attributes->type = VME_DMA_PATTERN; - attributes->private = (void *)pattern_attr; - - pattern_attr->pattern = pattern; - pattern_attr->type = type; - - return attributes; - -err_pat: - kfree(attributes); -err_attr: - return NULL; -} -EXPORT_SYMBOL(vme_dma_pattern_attribute); - -/** - * vme_dma_pci_attribute - Create "PCI" type VME DMA list attribute. - * @address: PCI base address for DMA transfer. - * - * Create VME DMA list attribute pointing to a location on PCI for DMA - * transfers. It is the responsibility of the user to free used attributes - * using vme_dma_free_attribute(). - * - * Return: Pointer to VME DMA attribute, NULL on failure. - */ -struct vme_dma_attr *vme_dma_pci_attribute(dma_addr_t address) -{ - struct vme_dma_attr *attributes; - struct vme_dma_pci *pci_attr; - - /* XXX Run some sanity checks here */ - - attributes = kmalloc_obj(*attributes); - if (!attributes) - goto err_attr; - - pci_attr = kmalloc_obj(*pci_attr); - if (!pci_attr) - goto err_pci; - - attributes->type = VME_DMA_PCI; - attributes->private = (void *)pci_attr; - - pci_attr->address = address; - - return attributes; - -err_pci: - kfree(attributes); -err_attr: - return NULL; -} -EXPORT_SYMBOL(vme_dma_pci_attribute); - -/** - * vme_dma_vme_attribute - Create "VME" type VME DMA list attribute. - * @address: VME base address for DMA transfer. - * @aspace: VME address space to use for DMA transfer. - * @cycle: VME bus cycle to use for DMA transfer. - * @dwidth: VME data width to use for DMA transfer. - * - * Create VME DMA list attribute pointing to a location on the VME bus for DMA - * transfers. It is the responsibility of the user to free used attributes - * using vme_dma_free_attribute(). - * - * Return: Pointer to VME DMA attribute, NULL on failure. - */ -struct vme_dma_attr *vme_dma_vme_attribute(unsigned long long address, - u32 aspace, u32 cycle, u32 dwidth) -{ - struct vme_dma_attr *attributes; - struct vme_dma_vme *vme_attr; - - attributes = kmalloc_obj(*attributes); - if (!attributes) - goto err_attr; - - vme_attr = kmalloc_obj(*vme_attr); - if (!vme_attr) - goto err_vme; - - attributes->type = VME_DMA_VME; - attributes->private = (void *)vme_attr; - - vme_attr->address = address; - vme_attr->aspace = aspace; - vme_attr->cycle = cycle; - vme_attr->dwidth = dwidth; - - return attributes; - -err_vme: - kfree(attributes); -err_attr: - return NULL; -} -EXPORT_SYMBOL(vme_dma_vme_attribute); - -/** - * vme_dma_free_attribute - Free DMA list attribute. - * @attributes: Pointer to DMA list attribute. - * - * Free VME DMA list attribute. VME DMA list attributes can be safely freed - * once vme_dma_list_add() has returned. - */ -void vme_dma_free_attribute(struct vme_dma_attr *attributes) -{ - kfree(attributes->private); - kfree(attributes); -} -EXPORT_SYMBOL(vme_dma_free_attribute); - -/** - * vme_dma_list_add - Add entry to a VME DMA list. - * @list: Pointer to VME list. - * @src: Pointer to DMA list attribute to use as source. - * @dest: Pointer to DMA list attribute to use as destination. - * @count: Number of bytes to transfer. - * - * Add an entry to the provided VME DMA list. Entry requires pointers to source - * and destination DMA attributes and a count. - * - * Please note, the attributes supported as source and destinations for - * transfers are hardware dependent. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device or if the link list has already been submitted for execution. - * Hardware specific errors also possible. - */ -int vme_dma_list_add(struct vme_dma_list *list, struct vme_dma_attr *src, - struct vme_dma_attr *dest, size_t count) -{ - struct vme_bridge *bridge = list->parent->parent; - int retval; - - if (!bridge->dma_list_add) { - dev_warn(bridge->parent, - "Link List DMA generation not supported\n"); - return -EINVAL; - } - - if (!mutex_trylock(&list->mtx)) { - dev_err(bridge->parent, "Link List already submitted\n"); - return -EINVAL; - } - - retval = bridge->dma_list_add(list, src, dest, count); - - mutex_unlock(&list->mtx); - - return retval; -} -EXPORT_SYMBOL(vme_dma_list_add); - -/** - * vme_dma_list_exec - Queue a VME DMA list for execution. - * @list: Pointer to VME list. - * - * Queue the provided VME DMA list for execution. The call will return once the - * list has been executed. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device. Hardware specific errors also possible. - */ -int vme_dma_list_exec(struct vme_dma_list *list) -{ - struct vme_bridge *bridge = list->parent->parent; - int retval; - - if (!bridge->dma_list_exec) { - dev_err(bridge->parent, - "Link List DMA execution not supported\n"); - return -EINVAL; - } - - mutex_lock(&list->mtx); - - retval = bridge->dma_list_exec(list); - - mutex_unlock(&list->mtx); - - return retval; -} -EXPORT_SYMBOL(vme_dma_list_exec); - -/** - * vme_dma_list_free - Free a VME DMA list. - * @list: Pointer to VME list. - * - * Free the provided DMA list and all its entries. - * - * Return: Zero on success, -EINVAL on invalid VME resource, -EBUSY if resource - * is still in use. Hardware specific errors also possible. - */ -int vme_dma_list_free(struct vme_dma_list *list) -{ - struct vme_bridge *bridge = list->parent->parent; - int retval; - - if (!bridge->dma_list_empty) { - dev_warn(bridge->parent, - "Emptying of Link Lists not supported\n"); - return -EINVAL; - } - - if (!mutex_trylock(&list->mtx)) { - dev_err(bridge->parent, "Link List in use\n"); - return -EBUSY; - } - - /* - * Empty out all of the entries from the DMA list. We need to go to the - * low level driver as DMA entries are driver specific. - */ - retval = bridge->dma_list_empty(list); - if (retval) { - dev_err(bridge->parent, "Unable to empty link-list entries\n"); - mutex_unlock(&list->mtx); - return retval; - } - mutex_unlock(&list->mtx); - kfree(list); - - return retval; -} -EXPORT_SYMBOL(vme_dma_list_free); - -/** - * vme_dma_free - Free a VME DMA resource. - * @resource: Pointer to VME DMA resource. - * - * Free the provided DMA resource so that it may be reallocated. - * - * Return: Zero on success, -EINVAL on invalid VME resource, -EBUSY if resource - * is still active. - */ -int vme_dma_free(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_dma_resource *ctrlr; - - if (resource->type != VME_DMA) { - dev_err(bridge->parent, "Not a DMA resource\n"); - return -EINVAL; - } - - ctrlr = list_entry(resource->entry, struct vme_dma_resource, list); - - if (!mutex_trylock(&ctrlr->mtx)) { - dev_err(bridge->parent, "Resource busy, can't free\n"); - return -EBUSY; - } - - if (!(list_empty(&ctrlr->pending) && list_empty(&ctrlr->running))) { - dev_warn(bridge->parent, - "Resource still processing transfers\n"); - mutex_unlock(&ctrlr->mtx); - return -EBUSY; - } - - ctrlr->locked = 0; - - mutex_unlock(&ctrlr->mtx); - - kfree(resource); - - return 0; -} -EXPORT_SYMBOL(vme_dma_free); - -void vme_bus_error_handler(struct vme_bridge *bridge, - unsigned long long address, int am) -{ - struct vme_error_handler *handler; - int handler_triggered = 0; - u32 aspace = vme_get_aspace(am); - - list_for_each_entry(handler, &bridge->vme_error_handlers, list) { - if ((aspace == handler->aspace) && - (address >= handler->start) && - (address < handler->end)) { - if (!handler->num_errors) - handler->first_error = address; - if (handler->num_errors != UINT_MAX) - handler->num_errors++; - handler_triggered = 1; - } - } - - if (!handler_triggered) - dev_err(bridge->parent, - "Unhandled VME access error at address 0x%llx\n", - address); -} -EXPORT_SYMBOL(vme_bus_error_handler); - -struct vme_error_handler *vme_register_error_handler(struct vme_bridge *bridge, u32 aspace, - unsigned long long address, size_t len) -{ - struct vme_error_handler *handler; - - handler = kmalloc_obj(*handler, GFP_ATOMIC); - if (!handler) - return NULL; - - handler->aspace = aspace; - handler->start = address; - handler->end = address + len; - handler->num_errors = 0; - handler->first_error = 0; - list_add_tail(&handler->list, &bridge->vme_error_handlers); - - return handler; -} -EXPORT_SYMBOL(vme_register_error_handler); - -void vme_unregister_error_handler(struct vme_error_handler *handler) -{ - list_del(&handler->list); - kfree(handler); -} -EXPORT_SYMBOL(vme_unregister_error_handler); - -void vme_irq_handler(struct vme_bridge *bridge, int level, int statid) -{ - void (*call)(int level, int statid, void *priv_data); - void *priv_data; - - call = bridge->irq[level - 1].callback[statid].func; - priv_data = bridge->irq[level - 1].callback[statid].priv_data; - if (call) - call(level, statid, priv_data); - else - dev_warn(bridge->parent, - "Spurious VME interrupt, level:%x, vector:%x\n", level, - statid); -} -EXPORT_SYMBOL(vme_irq_handler); - -/** - * vme_irq_request - Request a specific VME interrupt. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @level: Interrupt priority being requested. - * @statid: Interrupt vector being requested. - * @callback: Pointer to callback function called when VME interrupt/vector - * received. - * @priv_data: Generic pointer that will be passed to the callback function. - * - * Request callback to be attached as a handler for VME interrupts with provided - * level and statid. - * - * Return: Zero on success, -EINVAL on invalid vme device, level or if the - * function is not supported, -EBUSY if the level/statid combination is - * already in use. Hardware specific errors also possible. - */ -int vme_irq_request(struct vme_dev *vdev, int level, int statid, - void (*callback)(int level, int statid, void *priv_data), - void *priv_data) -{ - struct vme_bridge *bridge; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - return -EINVAL; - } - - if ((level < 1) || (level > 7)) { - dev_err(bridge->parent, "Invalid interrupt level\n"); - return -EINVAL; - } - - if (!bridge->irq_set) { - dev_err(bridge->parent, - "Configuring interrupts not supported\n"); - return -EINVAL; - } - - mutex_lock(&bridge->irq_mtx); - - if (bridge->irq[level - 1].callback[statid].func) { - mutex_unlock(&bridge->irq_mtx); - dev_warn(bridge->parent, "VME Interrupt already taken\n"); - return -EBUSY; - } - - bridge->irq[level - 1].count++; - bridge->irq[level - 1].callback[statid].priv_data = priv_data; - bridge->irq[level - 1].callback[statid].func = callback; - - /* Enable IRQ level */ - bridge->irq_set(bridge, level, 1, 1); - - mutex_unlock(&bridge->irq_mtx); - - return 0; -} -EXPORT_SYMBOL(vme_irq_request); - -/** - * vme_irq_free - Free a VME interrupt. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @level: Interrupt priority of interrupt being freed. - * @statid: Interrupt vector of interrupt being freed. - * - * Remove previously attached callback from VME interrupt priority/vector. - */ -void vme_irq_free(struct vme_dev *vdev, int level, int statid) -{ - struct vme_bridge *bridge; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - return; - } - - if ((level < 1) || (level > 7)) { - dev_err(bridge->parent, "Invalid interrupt level\n"); - return; - } - - if (!bridge->irq_set) { - dev_err(bridge->parent, - "Configuring interrupts not supported\n"); - return; - } - - mutex_lock(&bridge->irq_mtx); - - bridge->irq[level - 1].count--; - - /* Disable IRQ level if no more interrupts attached at this level*/ - if (!bridge->irq[level - 1].count) - bridge->irq_set(bridge, level, 0, 1); - - bridge->irq[level - 1].callback[statid].func = NULL; - bridge->irq[level - 1].callback[statid].priv_data = NULL; - - mutex_unlock(&bridge->irq_mtx); -} -EXPORT_SYMBOL(vme_irq_free); - -/** - * vme_irq_generate - Generate VME interrupt. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @level: Interrupt priority at which to assert the interrupt. - * @statid: Interrupt vector to associate with the interrupt. - * - * Generate a VME interrupt of the provided level and with the provided - * statid. - * - * Return: Zero on success, -EINVAL on invalid vme device, level or if the - * function is not supported. Hardware specific errors also possible. - */ -int vme_irq_generate(struct vme_dev *vdev, int level, int statid) -{ - struct vme_bridge *bridge; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - return -EINVAL; - } - - if ((level < 1) || (level > 7)) { - dev_warn(bridge->parent, "Invalid interrupt level\n"); - return -EINVAL; - } - - if (!bridge->irq_generate) { - dev_warn(bridge->parent, - "Interrupt generation not supported\n"); - return -EINVAL; - } - - return bridge->irq_generate(bridge, level, statid); -} -EXPORT_SYMBOL(vme_irq_generate); - -/** - * vme_lm_request - Request a VME location monitor - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * - * Allocate a location monitor resource to the driver. A location monitor - * allows the driver to monitor accesses to a contiguous number of - * addresses on the VME bus. - * - * Return: Pointer to a VME resource on success or NULL on failure. - */ -struct vme_resource *vme_lm_request(struct vme_dev *vdev) -{ - struct vme_bridge *bridge; - struct vme_lm_resource *allocated_lm = NULL; - struct vme_lm_resource *lm; - struct vme_resource *resource = NULL; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - goto err_bus; - } - - /* Loop through LM resources */ - list_for_each_entry(lm, &bridge->lm_resources, list) { - if (!lm) { - dev_err(bridge->parent, - "Registered NULL Location Monitor resource\n"); - continue; - } - - /* Find an unlocked controller */ - mutex_lock(&lm->mtx); - if (!lm->locked) { - lm->locked = 1; - mutex_unlock(&lm->mtx); - allocated_lm = lm; - break; - } - mutex_unlock(&lm->mtx); - } - - /* Check to see if we found a resource */ - if (!allocated_lm) - goto err_lm; - - resource = kmalloc_obj(*resource); - if (!resource) - goto err_alloc; - - resource->type = VME_LM; - resource->entry = &allocated_lm->list; - - return resource; - -err_alloc: - /* Unlock image */ - mutex_lock(&allocated_lm->mtx); - allocated_lm->locked = 0; - mutex_unlock(&allocated_lm->mtx); -err_lm: -err_bus: - return NULL; -} -EXPORT_SYMBOL(vme_lm_request); - -/** - * vme_lm_count - Determine number of VME Addresses monitored - * @resource: Pointer to VME location monitor resource. - * - * The number of contiguous addresses monitored is hardware dependent. - * Return the number of contiguous addresses monitored by the - * location monitor. - * - * Return: Count of addresses monitored or -EINVAL when provided with an - * invalid location monitor resource. - */ -int vme_lm_count(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return -EINVAL; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - return lm->monitors; -} -EXPORT_SYMBOL(vme_lm_count); - -/** - * vme_lm_set - Configure location monitor - * @resource: Pointer to VME location monitor resource. - * @lm_base: Base address to monitor. - * @aspace: VME address space to monitor. - * @cycle: VME bus cycle type to monitor. - * - * Set the base address, address space and cycle type of accesses to be - * monitored by the location monitor. - * - * Return: Zero on success, -EINVAL when provided with an invalid location - * monitor resource or function is not supported. Hardware specific - * errors may also be returned. - */ -int vme_lm_set(struct vme_resource *resource, unsigned long long lm_base, - u32 aspace, u32 cycle) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return -EINVAL; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - if (!bridge->lm_set) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->lm_set(lm, lm_base, aspace, cycle); -} -EXPORT_SYMBOL(vme_lm_set); - -/** - * vme_lm_get - Retrieve location monitor settings - * @resource: Pointer to VME location monitor resource. - * @lm_base: Pointer used to output the base address monitored. - * @aspace: Pointer used to output the address space monitored. - * @cycle: Pointer used to output the VME bus cycle type monitored. - * - * Retrieve the base address, address space and cycle type of accesses to - * be monitored by the location monitor. - * - * Return: Zero on success, -EINVAL when provided with an invalid location - * monitor resource or function is not supported. Hardware specific - * errors may also be returned. - */ -int vme_lm_get(struct vme_resource *resource, unsigned long long *lm_base, - u32 *aspace, u32 *cycle) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return -EINVAL; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - if (!bridge->lm_get) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->lm_get(lm, lm_base, aspace, cycle); -} -EXPORT_SYMBOL(vme_lm_get); - -/** - * vme_lm_attach - Provide callback for location monitor address - * @resource: Pointer to VME location monitor resource. - * @monitor: Offset to which callback should be attached. - * @callback: Pointer to callback function called when triggered. - * @data: Generic pointer that will be passed to the callback function. - * - * Attach a callback to the specified offset into the location monitors - * monitored addresses. A generic pointer is provided to allow data to be - * passed to the callback when called. - * - * Return: Zero on success, -EINVAL when provided with an invalid location - * monitor resource or function is not supported. Hardware specific - * errors may also be returned. - */ -int vme_lm_attach(struct vme_resource *resource, int monitor, - void (*callback)(void *), void *data) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return -EINVAL; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - if (!bridge->lm_attach) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->lm_attach(lm, monitor, callback, data); -} -EXPORT_SYMBOL(vme_lm_attach); - -/** - * vme_lm_detach - Remove callback for location monitor address - * @resource: Pointer to VME location monitor resource. - * @monitor: Offset to which callback should be removed. - * - * Remove the callback associated with the specified offset into the - * location monitors monitored addresses. - * - * Return: Zero on success, -EINVAL when provided with an invalid location - * monitor resource or function is not supported. Hardware specific - * errors may also be returned. - */ -int vme_lm_detach(struct vme_resource *resource, int monitor) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return -EINVAL; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - if (!bridge->lm_detach) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->lm_detach(lm, monitor); -} -EXPORT_SYMBOL(vme_lm_detach); - -/** - * vme_lm_free - Free allocated VME location monitor - * @resource: Pointer to VME location monitor resource. - * - * Free allocation of a VME location monitor. - * - * WARNING: This function currently expects that any callbacks that have - * been attached to the location monitor have been removed. - * - * Return: Zero on success, -EINVAL when provided with an invalid location - * monitor resource. - */ -void vme_lm_free(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - mutex_lock(&lm->mtx); - - /* XXX - * Check to see that there aren't any callbacks still attached, if - * there are we should probably be detaching them! - */ - - lm->locked = 0; - - mutex_unlock(&lm->mtx); - - kfree(resource); -} -EXPORT_SYMBOL(vme_lm_free); - -/** - * vme_slot_num - Retrieve slot ID - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * - * Retrieve the slot ID associated with the provided VME device. - * - * Return: The slot ID on success, -EINVAL if VME bridge cannot be determined - * or the function is not supported. Hardware specific errors may also - * be returned. - */ -int vme_slot_num(struct vme_dev *vdev) -{ - struct vme_bridge *bridge; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - return -EINVAL; - } - - if (!bridge->slot_get) { - dev_warn(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->slot_get(bridge); -} -EXPORT_SYMBOL(vme_slot_num); - -/** - * vme_bus_num - Retrieve bus number - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * - * Retrieve the bus enumeration associated with the provided VME device. - * - * Return: The bus number on success, -EINVAL if VME bridge cannot be - * determined. - */ -int vme_bus_num(struct vme_dev *vdev) -{ - struct vme_bridge *bridge; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - return -EINVAL; - } - - return bridge->num; -} -EXPORT_SYMBOL(vme_bus_num); - -/* - Bridge Registration --------------------------------------------------- */ - -static void vme_dev_release(struct device *dev) -{ - kfree(dev_to_vme_dev(dev)); -} - -/* Common bridge initialization */ -struct vme_bridge *vme_init_bridge(struct vme_bridge *bridge) -{ - INIT_LIST_HEAD(&bridge->vme_error_handlers); - INIT_LIST_HEAD(&bridge->master_resources); - INIT_LIST_HEAD(&bridge->slave_resources); - INIT_LIST_HEAD(&bridge->dma_resources); - INIT_LIST_HEAD(&bridge->lm_resources); - mutex_init(&bridge->irq_mtx); - - return bridge; -} -EXPORT_SYMBOL(vme_init_bridge); - -int vme_register_bridge(struct vme_bridge *bridge) -{ - int i; - int ret = -1; - - mutex_lock(&vme_buses_lock); - for (i = 0; i < sizeof(vme_bus_numbers) * 8; i++) { - if (!(vme_bus_numbers & (1 << i))) { - vme_bus_numbers |= (1 << i); - bridge->num = i; - INIT_LIST_HEAD(&bridge->devices); - list_add_tail(&bridge->bus_list, &vme_bus_list); - ret = 0; - break; - } - } - mutex_unlock(&vme_buses_lock); - - return ret; -} -EXPORT_SYMBOL(vme_register_bridge); - -void vme_unregister_bridge(struct vme_bridge *bridge) -{ - struct vme_dev *vdev; - struct vme_dev *tmp; - - mutex_lock(&vme_buses_lock); - vme_bus_numbers &= ~(1 << bridge->num); - list_for_each_entry_safe(vdev, tmp, &bridge->devices, bridge_list) { - list_del(&vdev->drv_list); - list_del(&vdev->bridge_list); - device_unregister(&vdev->dev); - } - list_del(&bridge->bus_list); - mutex_unlock(&vme_buses_lock); -} -EXPORT_SYMBOL(vme_unregister_bridge); - -/* - Driver Registration --------------------------------------------------- */ - -static int __vme_register_driver_bus(struct vme_driver *drv, - struct vme_bridge *bridge, - unsigned int ndevs) -{ - int err; - unsigned int i; - struct vme_dev *vdev; - struct vme_dev *tmp; - - for (i = 0; i < ndevs; i++) { - vdev = kzalloc_obj(*vdev); - if (!vdev) { - err = -ENOMEM; - goto err_devalloc; - } - vdev->num = i; - vdev->bridge = bridge; - vdev->dev.platform_data = drv; - vdev->dev.release = vme_dev_release; - vdev->dev.parent = bridge->parent; - vdev->dev.bus = &vme_bus_type; - dev_set_name(&vdev->dev, "%s.%u-%u", drv->name, bridge->num, - vdev->num); - - err = device_register(&vdev->dev); - if (err) - goto err_reg; - - if (vdev->dev.platform_data) { - list_add_tail(&vdev->drv_list, &drv->devices); - list_add_tail(&vdev->bridge_list, &bridge->devices); - } else { - device_unregister(&vdev->dev); - } - } - return 0; - -err_reg: - put_device(&vdev->dev); -err_devalloc: - list_for_each_entry_safe(vdev, tmp, &drv->devices, drv_list) { - list_del(&vdev->drv_list); - list_del(&vdev->bridge_list); - device_unregister(&vdev->dev); - } - return err; -} - -static int __vme_register_driver(struct vme_driver *drv, unsigned int ndevs) -{ - struct vme_bridge *bridge; - int err = 0; - - mutex_lock(&vme_buses_lock); - list_for_each_entry(bridge, &vme_bus_list, bus_list) { - /* - * This cannot cause trouble as we already have vme_buses_lock - * and if the bridge is removed, it will have to go through - * vme_unregister_bridge() to do it (which calls remove() on - * the bridge which in turn tries to acquire vme_buses_lock and - * will have to wait). - */ - err = __vme_register_driver_bus(drv, bridge, ndevs); - if (err) - break; - } - mutex_unlock(&vme_buses_lock); - return err; -} - -/** - * vme_register_driver - Register a VME driver - * @drv: Pointer to VME driver structure to register. - * @ndevs: Maximum number of devices to allow to be enumerated. - * - * Register a VME device driver with the VME subsystem. - * - * Return: Zero on success, error value on registration failure. - */ -int vme_register_driver(struct vme_driver *drv, unsigned int ndevs) -{ - int err; - - drv->driver.name = drv->name; - drv->driver.bus = &vme_bus_type; - INIT_LIST_HEAD(&drv->devices); - - err = driver_register(&drv->driver); - if (err) - return err; - - err = __vme_register_driver(drv, ndevs); - if (err) - driver_unregister(&drv->driver); - - return err; -} -EXPORT_SYMBOL(vme_register_driver); - -/** - * vme_unregister_driver - Unregister a VME driver - * @drv: Pointer to VME driver structure to unregister. - * - * Unregister a VME device driver from the VME subsystem. - */ -void vme_unregister_driver(struct vme_driver *drv) -{ - struct vme_dev *dev, *dev_tmp; - - mutex_lock(&vme_buses_lock); - list_for_each_entry_safe(dev, dev_tmp, &drv->devices, drv_list) { - list_del(&dev->drv_list); - list_del(&dev->bridge_list); - device_unregister(&dev->dev); - } - mutex_unlock(&vme_buses_lock); - - driver_unregister(&drv->driver); -} -EXPORT_SYMBOL(vme_unregister_driver); - -/* - Bus Registration ------------------------------------------------------ */ - -static int vme_bus_match(struct device *dev, const struct device_driver *drv) -{ - const struct vme_driver *vme_drv; - - vme_drv = container_of(drv, struct vme_driver, driver); - - if (dev->platform_data == vme_drv) { - struct vme_dev *vdev = dev_to_vme_dev(dev); - - if (vme_drv->match && vme_drv->match(vdev)) - return 1; - - dev->platform_data = NULL; - } - return 0; -} - -static int vme_bus_probe(struct device *dev) -{ - struct vme_driver *driver; - struct vme_dev *vdev = dev_to_vme_dev(dev); - - driver = dev->platform_data; - if (driver->probe) - return driver->probe(vdev); - - return -ENODEV; -} - -static void vme_bus_remove(struct device *dev) -{ - struct vme_driver *driver; - struct vme_dev *vdev = dev_to_vme_dev(dev); - - driver = dev->platform_data; - if (driver->remove) - driver->remove(vdev); -} - -const struct bus_type vme_bus_type = { - .name = "vme", - .match = vme_bus_match, - .probe = vme_bus_probe, - .remove = vme_bus_remove, -}; -EXPORT_SYMBOL(vme_bus_type); - -static int __init vme_init(void) -{ - return bus_register(&vme_bus_type); -} -subsys_initcall(vme_init); diff --git a/drivers/staging/vme_user/vme.h b/drivers/staging/vme_user/vme.h deleted file mode 100644 index b6413605ea49c3..00000000000000 --- a/drivers/staging/vme_user/vme.h +++ /dev/null @@ -1,190 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 */ -#ifndef _VME_H_ -#define _VME_H_ - -#include - -/* Resource Type */ -enum vme_resource_type { - VME_MASTER, - VME_SLAVE, - VME_DMA, - VME_LM -}; - -/* VME Address Spaces */ -#define VME_A16 0x1 -#define VME_A24 0x2 -#define VME_A32 0x4 -#define VME_A64 0x8 -#define VME_CRCSR 0x10 -#define VME_USER1 0x20 -#define VME_USER2 0x40 -#define VME_USER3 0x80 -#define VME_USER4 0x100 - -#define VME_A16_MAX 0x10000ULL -#define VME_A24_MAX 0x1000000ULL -#define VME_A32_MAX 0x100000000ULL -#define VME_A64_MAX 0x10000000000000000ULL -#define VME_CRCSR_MAX 0x1000000ULL - -/* VME Cycle Types */ -#define VME_SCT 0x1 -#define VME_BLT 0x2 -#define VME_MBLT 0x4 -#define VME_2eVME 0x8 -#define VME_2eSST 0x10 -#define VME_2eSSTB 0x20 - -#define VME_2eSST160 0x100 -#define VME_2eSST267 0x200 -#define VME_2eSST320 0x400 - -#define VME_SUPER 0x1000 -#define VME_USER 0x2000 -#define VME_PROG 0x4000 -#define VME_DATA 0x8000 - -/* VME Data Widths */ -#define VME_D8 0x1 -#define VME_D16 0x2 -#define VME_D32 0x4 -#define VME_D64 0x8 - -/* Arbitration Scheduling Modes */ -#define VME_R_ROBIN_MODE 0x1 -#define VME_PRIORITY_MODE 0x2 - -#define VME_DMA_PATTERN BIT(0) -#define VME_DMA_PCI BIT(1) -#define VME_DMA_VME BIT(2) - -#define VME_DMA_PATTERN_BYTE BIT(0) -#define VME_DMA_PATTERN_WORD BIT(1) -#define VME_DMA_PATTERN_INCREMENT BIT(2) - -#define VME_DMA_VME_TO_MEM BIT(0) -#define VME_DMA_MEM_TO_VME BIT(1) -#define VME_DMA_VME_TO_VME BIT(2) -#define VME_DMA_MEM_TO_MEM BIT(3) -#define VME_DMA_PATTERN_TO_VME BIT(4) -#define VME_DMA_PATTERN_TO_MEM BIT(5) - -struct vme_dma_attr { - u32 type; - void *private; -}; - -struct vme_resource { - enum vme_resource_type type; - struct list_head *entry; -}; - -extern const struct bus_type vme_bus_type; - -/* Number of VME interrupt vectors */ -#define VME_NUM_STATUSID 256 - -/* VME_MAX_BRIDGES comes from the type of vme_bus_numbers */ -#define VME_MAX_BRIDGES (sizeof(unsigned int) * 8) -#define VME_MAX_SLOTS 32 - -#define VME_SLOT_CURRENT -1 -#define VME_SLOT_ALL -2 - -/** - * struct vme_dev - Structure representing a VME device - * @num: The device number - * @bridge: Pointer to the bridge device this device is on - * @dev: Internal device structure - * @drv_list: List of devices (per driver) - * @bridge_list: List of devices (per bridge) - */ -struct vme_dev { - int num; - struct vme_bridge *bridge; - struct device dev; - struct list_head drv_list; - struct list_head bridge_list; -}; - -/** - * struct vme_driver - Structure representing a VME driver - * @name: Driver name, should be unique among VME drivers and usually the same - * as the module name. - * @match: Callback used to determine whether probe should be run. - * @probe: Callback for device binding, called when new device is detected. - * @remove: Callback, called on device removal. - * @driver: Underlying generic device driver structure. - * @devices: List of VME devices (struct vme_dev) associated with this driver. - */ -struct vme_driver { - const char *name; - int (*match)(struct vme_dev *vdev); - int (*probe)(struct vme_dev *vdev); - void (*remove)(struct vme_dev *vdev); - struct device_driver driver; - struct list_head devices; -}; - -void *vme_alloc_consistent(struct vme_resource *resource, size_t size, dma_addr_t *dma); -void vme_free_consistent(struct vme_resource *resource, size_t size, void *vaddr, dma_addr_t dma); - -size_t vme_get_size(struct vme_resource *resource); -int vme_check_window(struct vme_bridge *bridge, u32 aspace, - unsigned long long vme_base, unsigned long long size); - -struct vme_resource *vme_slave_request(struct vme_dev *vdev, u32 address, u32 cycle); -int vme_slave_set(struct vme_resource *resource, int enabled, unsigned long long vme_base, - unsigned long long size, dma_addr_t buf_base, u32 aspace, u32 cycle); -int vme_slave_get(struct vme_resource *resource, int *enabled, unsigned long long *vme_base, - unsigned long long *size, dma_addr_t *buf_base, u32 *aspace, u32 *cycle); -void vme_slave_free(struct vme_resource *resource); - -struct vme_resource *vme_master_request(struct vme_dev *vdev, u32 address, u32 cycle, u32 dwidth); -int vme_master_set(struct vme_resource *resource, int enabled, unsigned long long vme_base, - unsigned long long size, u32 aspace, u32 cycle, u32 dwidth); -int vme_master_get(struct vme_resource *resource, int *enabled, unsigned long long *vme_base, - unsigned long long *size, u32 *aspace, u32 *cycle, u32 *dwidth); -ssize_t vme_master_read(struct vme_resource *resource, void *buf, size_t count, loff_t offset); -ssize_t vme_master_write(struct vme_resource *resource, void *buf, size_t count, loff_t offset); -unsigned int vme_master_rmw(struct vme_resource *resource, unsigned int mask, unsigned int compare, - unsigned int swap, loff_t offset); -int vme_master_mmap_prepare(struct vme_resource *resource, struct vm_area_desc *desc); -void vme_master_free(struct vme_resource *resource); - -struct vme_resource *vme_dma_request(struct vme_dev *vdev, u32 route); -struct vme_dma_list *vme_new_dma_list(struct vme_resource *resource); -struct vme_dma_attr *vme_dma_pattern_attribute(u32 pattern, u32 type); -struct vme_dma_attr *vme_dma_pci_attribute(dma_addr_t address); -struct vme_dma_attr *vme_dma_vme_attribute(unsigned long long address, - u32 aspace, u32 cycle, u32 dwidth); -void vme_dma_free_attribute(struct vme_dma_attr *attributes); -int vme_dma_list_add(struct vme_dma_list *list, struct vme_dma_attr *src, - struct vme_dma_attr *dest, size_t count); -int vme_dma_list_exec(struct vme_dma_list *list); -int vme_dma_list_free(struct vme_dma_list *list); -int vme_dma_free(struct vme_resource *resource); - -int vme_irq_request(struct vme_dev *vdev, int level, int statid, - void (*callback)(int level, int statid, void *priv_data), void *priv_data); -void vme_irq_free(struct vme_dev *vdev, int level, int statid); -int vme_irq_generate(struct vme_dev *vdev, int level, int statid); - -struct vme_resource *vme_lm_request(struct vme_dev *vdev); -int vme_lm_count(struct vme_resource *resource); -int vme_lm_set(struct vme_resource *resource, unsigned long long lm_base, u32 aspace, u32 cycle); -int vme_lm_get(struct vme_resource *resource, unsigned long long *lm_base, u32 *aspace, u32 *cycle); -int vme_lm_attach(struct vme_resource *resource, int monitor, void (*callback)(void *), void *data); -int vme_lm_detach(struct vme_resource *resource, int monitor); -void vme_lm_free(struct vme_resource *resource); - -int vme_slot_num(struct vme_dev *vdev); -int vme_bus_num(struct vme_dev *vdev); - -int vme_register_driver(struct vme_driver *drv, unsigned int ndevs); -void vme_unregister_driver(struct vme_driver *drv); - -#endif /* _VME_H_ */ - diff --git a/drivers/staging/vme_user/vme_bridge.h b/drivers/staging/vme_user/vme_bridge.h deleted file mode 100644 index 92b0baa793d73d..00000000000000 --- a/drivers/staging/vme_user/vme_bridge.h +++ /dev/null @@ -1,190 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 */ -#ifndef _VME_BRIDGE_H_ -#define _VME_BRIDGE_H_ - -#include "vme.h" - -#define VME_CRCSR_BUF_SIZE (508 * 1024) -/* - * Resource structures - */ -struct vme_master_resource { - struct list_head list; - struct vme_bridge *parent; - /* - * We are likely to need to access the VME bus in interrupt context, so - * protect master routines with a spinlock rather than a mutex. - */ - spinlock_t lock; - int locked; - int number; - u32 address_attr; - u32 cycle_attr; - u32 width_attr; - struct resource bus_resource; - void __iomem *kern_base; -}; - -struct vme_slave_resource { - struct list_head list; - struct vme_bridge *parent; - struct mutex mtx; - int locked; - int number; - u32 address_attr; - u32 cycle_attr; -}; - -struct vme_dma_pattern { - u32 pattern; - u32 type; -}; - -struct vme_dma_pci { - dma_addr_t address; -}; - -struct vme_dma_vme { - unsigned long long address; - u32 aspace; - u32 cycle; - u32 dwidth; -}; - -struct vme_dma_list { - struct list_head list; - struct vme_dma_resource *parent; - struct list_head entries; - struct mutex mtx; -}; - -struct vme_dma_resource { - struct list_head list; - struct vme_bridge *parent; - struct mutex mtx; - int locked; - int number; - struct list_head pending; - struct list_head running; - u32 route_attr; -}; - -struct vme_lm_resource { - struct list_head list; - struct vme_bridge *parent; - struct mutex mtx; - int locked; - int number; - int monitors; -}; - -struct vme_error_handler { - struct list_head list; - unsigned long long start; /* Beginning of error window */ - unsigned long long end; /* End of error window */ - unsigned long long first_error; /* Address of the first error */ - u32 aspace; /* Address space of error window*/ - unsigned int num_errors; /* Number of errors */ -}; - -struct vme_callback { - void (*func)(int level, int statid, void *priv_data); - void *priv_data; -}; - -struct vme_irq { - int count; - struct vme_callback callback[VME_NUM_STATUSID]; -}; - -/* Allow 16 characters for name (including null character) */ -#define VMENAMSIZ 16 - -/* This structure stores all the information about one bridge - * The structure should be dynamically allocated by the driver and one instance - * of the structure should be present for each VME chip present in the system. - */ -struct vme_bridge { - char name[VMENAMSIZ]; - int num; - struct list_head master_resources; - struct list_head slave_resources; - struct list_head dma_resources; - struct list_head lm_resources; - - /* List for registered errors handlers */ - struct list_head vme_error_handlers; - /* List of devices on this bridge */ - struct list_head devices; - - /* Bridge Info - XXX Move to private structure? */ - struct device *parent; /* Parent device (eg. pdev->dev for PCI) */ - void *driver_priv; /* Private pointer for the bridge driver */ - struct list_head bus_list; /* list of VME buses */ - - /* Interrupt callbacks */ - struct vme_irq irq[7]; - /* Locking for VME irq callback configuration */ - struct mutex irq_mtx; - - /* Slave Functions */ - int (*slave_get)(struct vme_slave_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - dma_addr_t *buf_base, u32 *aspace, u32 *cycle); - int (*slave_set)(struct vme_slave_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - dma_addr_t buf_base, u32 aspace, u32 cycle); - - /* Master Functions */ - int (*master_get)(struct vme_master_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth); - int (*master_set)(struct vme_master_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - u32 aspace, u32 cycle, u32 dwidth); - ssize_t (*master_read)(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset); - ssize_t (*master_write)(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset); - unsigned int (*master_rmw)(struct vme_master_resource *image, - unsigned int mask, unsigned int compare, - unsigned int swap, loff_t offset); - - /* DMA Functions */ - int (*dma_list_add)(struct vme_dma_list *list, struct vme_dma_attr *src, - struct vme_dma_attr *dest, size_t count); - int (*dma_list_exec)(struct vme_dma_list *list); - int (*dma_list_empty)(struct vme_dma_list *list); - - /* Interrupt Functions */ - void (*irq_set)(struct vme_bridge *bridge, int level, int state, int sync); - int (*irq_generate)(struct vme_bridge *bridge, int level, int statid); - - /* Location monitor functions */ - int (*lm_set)(struct vme_lm_resource *lm, unsigned long long lm_base, - u32 aspace, u32 cycle); - int (*lm_get)(struct vme_lm_resource *lm, unsigned long long *lm_base, - u32 *aspace, u32 *cycle); - int (*lm_attach)(struct vme_lm_resource *lm, int monitor, - void (*callback)(void *), void *data); - int (*lm_detach)(struct vme_lm_resource *lm, int monitor); - - /* CR/CSR space functions */ - int (*slot_get)(struct vme_bridge *bridge); - - /* Bridge parent interface */ - void *(*alloc_consistent)(struct device *dev, size_t size, dma_addr_t *dma); - void (*free_consistent)(struct device *dev, size_t size, void *vaddr, dma_addr_t dma); -}; - -void vme_bus_error_handler(struct vme_bridge *bridge, unsigned long long address, int am); -void vme_irq_handler(struct vme_bridge *bridge, int level, int statid); - -struct vme_bridge *vme_init_bridge(struct vme_bridge *bridge); -int vme_register_bridge(struct vme_bridge *bridge); -void vme_unregister_bridge(struct vme_bridge *bridge); -struct vme_error_handler *vme_register_error_handler(struct vme_bridge *bridge, u32 aspace, - unsigned long long address, size_t len); -void vme_unregister_error_handler(struct vme_error_handler *handler); - -#endif /* _VME_BRIDGE_H_ */ diff --git a/drivers/staging/vme_user/vme_fake.c b/drivers/staging/vme_user/vme_fake.c deleted file mode 100644 index 434cf760ade6c8..00000000000000 --- a/drivers/staging/vme_user/vme_fake.c +++ /dev/null @@ -1,1308 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -/* - * Fake VME bridge support. - * - * This drive provides a fake VME bridge chip, this enables debugging of the - * VME framework in the absence of a VME system. - * - * This driver has to do a number of things in software that would be driven - * by hardware if it was available, it will also result in extra overhead at - * times when compared with driving actual hardware. - * - * Author: Martyn Welch - * Copyright (c) 2014 Martyn Welch - * - * Based on vme_tsi148.c: - * - * Author: Martyn Welch - * Copyright 2008 GE Intelligent Platforms Embedded Systems, Inc. - * - * Based on work by Tom Armistead and Ajit Prem - * Copyright 2004 Motorola Inc. - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "vme.h" -#include "vme_bridge.h" - -/* - * Define the number of each that the fake driver supports. - */ -#define FAKE_MAX_MASTER 8 /* Max Master Windows */ -#define FAKE_MAX_SLAVE 8 /* Max Slave Windows */ - -/* Structures to hold information normally held in device registers */ -struct fake_slave_window { - int enabled; - unsigned long long vme_base; - unsigned long long size; - void *buf_base; - u32 aspace; - u32 cycle; -}; - -struct fake_master_window { - int enabled; - unsigned long long vme_base; - unsigned long long size; - u32 aspace; - u32 cycle; - u32 dwidth; -}; - -/* Structure used to hold driver specific information */ -struct fake_driver { - struct vme_bridge *parent; - struct fake_slave_window slaves[FAKE_MAX_SLAVE]; - struct fake_master_window masters[FAKE_MAX_MASTER]; - u32 lm_enabled; - unsigned long long lm_base; - u32 lm_aspace; - u32 lm_cycle; - void (*lm_callback[4])(void *); - void *lm_data[4]; - struct tasklet_struct int_tasklet; - int int_level; - int int_statid; - void *crcsr_kernel; - dma_addr_t crcsr_bus; - /* Only one VME interrupt can be generated at a time, provide locking */ - struct mutex vme_int; -}; - -/* Module parameter */ -static u32 geoid; - -static const char driver_name[] = "vme_fake"; - -static struct vme_bridge *exit_pointer; - -static struct device *vme_root; - -/* - * Calling VME bus interrupt callback if provided. - */ -static void fake_VIRQ_tasklet(unsigned long data) -{ - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = (struct vme_bridge *)data; - bridge = fake_bridge->driver_priv; - - vme_irq_handler(fake_bridge, bridge->int_level, bridge->int_statid); -} - -/* - * Configure VME interrupt - */ -static void fake_irq_set(struct vme_bridge *fake_bridge, int level, - int state, int sync) -{ - /* Nothing to do */ -} - -static void *fake_pci_to_ptr(dma_addr_t addr) -{ - return (void *)(uintptr_t)addr; -} - -static dma_addr_t fake_ptr_to_pci(void *addr) -{ - return (dma_addr_t)(uintptr_t)addr; -} - -/* - * Generate a VME bus interrupt at the requested level & vector. Wait for - * interrupt to be acked. - */ -static int fake_irq_generate(struct vme_bridge *fake_bridge, int level, - int statid) -{ - struct fake_driver *bridge; - - bridge = fake_bridge->driver_priv; - - mutex_lock(&bridge->vme_int); - - bridge->int_level = level; - - bridge->int_statid = statid; - - /* - * Schedule tasklet to run VME handler to emulate normal VME interrupt - * handler behaviour. - */ - tasklet_schedule(&bridge->int_tasklet); - - mutex_unlock(&bridge->vme_int); - - return 0; -} - -/* - * Initialize a slave window with the requested attributes. - */ -static int fake_slave_set(struct vme_slave_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - dma_addr_t buf_base, u32 aspace, u32 cycle) -{ - unsigned int i, granularity = 0; - unsigned long long vme_bound; - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = image->parent; - bridge = fake_bridge->driver_priv; - - i = image->number; - - switch (aspace) { - case VME_A16: - granularity = 0x10; - break; - case VME_A24: - granularity = 0x1000; - break; - case VME_A32: - granularity = 0x10000; - break; - case VME_A64: - granularity = 0x10000; - break; - case VME_CRCSR: - case VME_USER1: - case VME_USER2: - case VME_USER3: - case VME_USER4: - default: - pr_err("Invalid address space\n"); - return -EINVAL; - } - - /* - * Bound address is a valid address for the window, adjust - * accordingly - */ - vme_bound = vme_base + size - granularity; - - if (vme_base & (granularity - 1)) { - pr_err("Invalid VME base alignment\n"); - return -EINVAL; - } - if (vme_bound & (granularity - 1)) { - pr_err("Invalid VME bound alignment\n"); - return -EINVAL; - } - - mutex_lock(&image->mtx); - - bridge->slaves[i].enabled = enabled; - bridge->slaves[i].vme_base = vme_base; - bridge->slaves[i].size = size; - bridge->slaves[i].buf_base = fake_pci_to_ptr(buf_base); - bridge->slaves[i].aspace = aspace; - bridge->slaves[i].cycle = cycle; - - mutex_unlock(&image->mtx); - - return 0; -} - -/* - * Get slave window configuration. - */ -static int fake_slave_get(struct vme_slave_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - dma_addr_t *buf_base, u32 *aspace, u32 *cycle) -{ - unsigned int i; - struct fake_driver *bridge; - - bridge = image->parent->driver_priv; - - i = image->number; - - mutex_lock(&image->mtx); - - *enabled = bridge->slaves[i].enabled; - *vme_base = bridge->slaves[i].vme_base; - *size = bridge->slaves[i].size; - *buf_base = fake_ptr_to_pci(bridge->slaves[i].buf_base); - *aspace = bridge->slaves[i].aspace; - *cycle = bridge->slaves[i].cycle; - - mutex_unlock(&image->mtx); - - return 0; -} - -/* - * Set the attributes of an outbound window. - */ -static int fake_master_set(struct vme_master_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - u32 aspace, u32 cycle, u32 dwidth) -{ - int retval = 0; - unsigned int i; - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = image->parent; - - bridge = fake_bridge->driver_priv; - - /* Verify input data */ - if (vme_base & 0xFFFF) { - pr_err("Invalid VME Window alignment\n"); - retval = -EINVAL; - goto err_window; - } - - if (size & 0xFFFF) { - pr_err("Invalid size alignment\n"); - retval = -EINVAL; - goto err_window; - } - - if ((size == 0) && (enabled != 0)) { - pr_err("Size must be non-zero for enabled windows\n"); - retval = -EINVAL; - goto err_window; - } - - /* Setup data width */ - switch (dwidth) { - case VME_D8: - case VME_D16: - case VME_D32: - break; - default: - pr_err("Invalid data width\n"); - retval = -EINVAL; - goto err_dwidth; - } - - /* Setup address space */ - switch (aspace) { - case VME_A16: - case VME_A24: - case VME_A32: - case VME_A64: - case VME_CRCSR: - case VME_USER1: - case VME_USER2: - case VME_USER3: - case VME_USER4: - break; - default: - pr_err("Invalid address space\n"); - retval = -EINVAL; - goto err_aspace; - } - - spin_lock(&image->lock); - - i = image->number; - - bridge->masters[i].enabled = enabled; - bridge->masters[i].vme_base = vme_base; - bridge->masters[i].size = size; - bridge->masters[i].aspace = aspace; - bridge->masters[i].cycle = cycle; - bridge->masters[i].dwidth = dwidth; - - spin_unlock(&image->lock); - - return 0; - -err_aspace: -err_dwidth: -err_window: - return retval; -} - -/* - * Set the attributes of an outbound window. - */ -static int __fake_master_get(struct vme_master_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth) -{ - unsigned int i; - struct fake_driver *bridge; - - bridge = image->parent->driver_priv; - - i = image->number; - - *enabled = bridge->masters[i].enabled; - *vme_base = bridge->masters[i].vme_base; - *size = bridge->masters[i].size; - *aspace = bridge->masters[i].aspace; - *cycle = bridge->masters[i].cycle; - *dwidth = bridge->masters[i].dwidth; - - return 0; -} - -static int fake_master_get(struct vme_master_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth) -{ - int retval; - - spin_lock(&image->lock); - - retval = __fake_master_get(image, enabled, vme_base, size, aspace, - cycle, dwidth); - - spin_unlock(&image->lock); - - return retval; -} - -static void fake_lm_check(struct fake_driver *bridge, unsigned long long addr, - u32 aspace, u32 cycle) -{ - struct vme_bridge *fake_bridge; - unsigned long long lm_base; - u32 lm_aspace, lm_cycle; - int i; - struct vme_lm_resource *lm; - struct list_head *pos = NULL, *n; - - /* Get vme_bridge */ - fake_bridge = bridge->parent; - - /* Loop through each location monitor resource */ - list_for_each_safe(pos, n, &fake_bridge->lm_resources) { - lm = list_entry(pos, struct vme_lm_resource, list); - - /* If disabled, we're done */ - if (bridge->lm_enabled == 0) - return; - - lm_base = bridge->lm_base; - lm_aspace = bridge->lm_aspace; - lm_cycle = bridge->lm_cycle; - - /* First make sure that the cycle and address space match */ - if ((lm_aspace == aspace) && (lm_cycle == cycle)) { - for (i = 0; i < lm->monitors; i++) { - /* Each location monitor covers 8 bytes */ - if (((lm_base + (8 * i)) <= addr) && - ((lm_base + (8 * i) + 8) > addr)) { - if (bridge->lm_callback[i]) - bridge->lm_callback[i](bridge->lm_data[i]); - } - } - } - } -} - -static noinline_for_stack u8 fake_vmeread8(struct fake_driver *bridge, - unsigned long long addr, - u32 aspace, u32 cycle) -{ - u8 retval = 0xff; - int i; - unsigned long long start, end, offset; - u8 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - if ((addr >= start) && (addr < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u8 *)(bridge->slaves[i].buf_base + offset); - retval = *loc; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); - - return retval; -} - -static noinline_for_stack u16 fake_vmeread16(struct fake_driver *bridge, - unsigned long long addr, - u32 aspace, u32 cycle) -{ - u16 retval = 0xffff; - int i; - unsigned long long start, end, offset; - u16 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if ((addr >= start) && ((addr + 1) < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u16 *)(bridge->slaves[i].buf_base + offset); - retval = *loc; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); - - return retval; -} - -static noinline_for_stack u32 fake_vmeread32(struct fake_driver *bridge, - unsigned long long addr, - u32 aspace, u32 cycle) -{ - u32 retval = 0xffffffff; - int i; - unsigned long long start, end, offset; - u32 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if ((addr >= start) && ((addr + 3) < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u32 *)(bridge->slaves[i].buf_base + offset); - retval = *loc; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); - - return retval; -} - -static ssize_t fake_master_read(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset) -{ - int retval; - u32 aspace, cycle, dwidth; - struct vme_bridge *fake_bridge; - struct fake_driver *priv; - int i; - unsigned long long addr; - unsigned int done = 0; - unsigned int count32; - - fake_bridge = image->parent; - - priv = fake_bridge->driver_priv; - - i = image->number; - - addr = (unsigned long long)priv->masters[i].vme_base + offset; - aspace = priv->masters[i].aspace; - cycle = priv->masters[i].cycle; - dwidth = priv->masters[i].dwidth; - - spin_lock(&image->lock); - - /* The following code handles VME address alignment. We cannot use - * memcpy_xxx here because it may cut data transfers in to 8-bit - * cycles when D16 or D32 cycles are required on the VME bus. - * On the other hand, the bridge itself assures that the maximum data - * cycle configured for the transfer is used and splits it - * automatically for non-aligned addresses, so we don't want the - * overhead of needlessly forcing small transfers for the entire cycle. - */ - if (addr & 0x1) { - *(u8 *)buf = fake_vmeread8(priv, addr, aspace, cycle); - done += 1; - if (done == count) - goto out; - } - if ((dwidth == VME_D16) || (dwidth == VME_D32)) { - if ((addr + done) & 0x2) { - if ((count - done) < 2) { - *(u8 *)(buf + done) = fake_vmeread8(priv, - addr + done, aspace, cycle); - done += 1; - goto out; - } else { - *(u16 *)(buf + done) = fake_vmeread16(priv, - addr + done, aspace, cycle); - done += 2; - } - } - } - - if (dwidth == VME_D32) { - count32 = (count - done) & ~0x3; - while (done < count32) { - *(u32 *)(buf + done) = fake_vmeread32(priv, addr + done, - aspace, cycle); - done += 4; - } - } else if (dwidth == VME_D16) { - count32 = (count - done) & ~0x3; - while (done < count32) { - *(u16 *)(buf + done) = fake_vmeread16(priv, addr + done, - aspace, cycle); - done += 2; - } - } else if (dwidth == VME_D8) { - count32 = (count - done); - while (done < count32) { - *(u8 *)(buf + done) = fake_vmeread8(priv, addr + done, - aspace, cycle); - done += 1; - } - } - - if ((dwidth == VME_D16) || (dwidth == VME_D32)) { - if ((count - done) & 0x2) { - *(u16 *)(buf + done) = fake_vmeread16(priv, addr + done, - aspace, cycle); - done += 2; - } - } - if ((count - done) & 0x1) { - *(u8 *)(buf + done) = fake_vmeread8(priv, addr + done, aspace, - cycle); - done += 1; - } - -out: - retval = count; - - spin_unlock(&image->lock); - - return retval; -} - -static noinline_for_stack void fake_vmewrite8(struct fake_driver *bridge, - u8 *buf, unsigned long long addr, - u32 aspace, u32 cycle) -{ - int i; - unsigned long long start, end, offset; - u8 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if ((addr >= start) && (addr < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u8 *)((void *)bridge->slaves[i].buf_base + offset); - *loc = *buf; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); -} - -static noinline_for_stack void fake_vmewrite16(struct fake_driver *bridge, - u16 *buf, unsigned long long addr, - u32 aspace, u32 cycle) -{ - int i; - unsigned long long start, end, offset; - u16 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if ((addr >= start) && ((addr + 1) < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u16 *)((void *)bridge->slaves[i].buf_base + offset); - *loc = *buf; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); -} - -static noinline_for_stack void fake_vmewrite32(struct fake_driver *bridge, - u32 *buf, unsigned long long addr, - u32 aspace, u32 cycle) -{ - int i; - unsigned long long start, end, offset; - u32 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if ((addr >= start) && ((addr + 3) < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u32 *)((void *)bridge->slaves[i].buf_base + offset); - *loc = *buf; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); -} - -static ssize_t fake_master_write(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset) -{ - int retval = 0; - u32 aspace, cycle, dwidth; - unsigned long long addr; - int i; - unsigned int done = 0; - unsigned int count32; - - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = image->parent; - - bridge = fake_bridge->driver_priv; - - i = image->number; - - addr = bridge->masters[i].vme_base + offset; - aspace = bridge->masters[i].aspace; - cycle = bridge->masters[i].cycle; - dwidth = bridge->masters[i].dwidth; - - spin_lock(&image->lock); - - /* Here we apply for the same strategy we do in master_read - * function in order to assure the correct cycles. - */ - if (addr & 0x1) { - fake_vmewrite8(bridge, (u8 *)buf, addr, aspace, cycle); - done += 1; - if (done == count) - goto out; - } - - if ((dwidth == VME_D16) || (dwidth == VME_D32)) { - if ((addr + done) & 0x2) { - if ((count - done) < 2) { - fake_vmewrite8(bridge, (u8 *)(buf + done), - addr + done, aspace, cycle); - done += 1; - goto out; - } else { - fake_vmewrite16(bridge, (u16 *)(buf + done), - addr + done, aspace, cycle); - done += 2; - } - } - } - - if (dwidth == VME_D32) { - count32 = (count - done) & ~0x3; - while (done < count32) { - fake_vmewrite32(bridge, (u32 *)(buf + done), - addr + done, aspace, cycle); - done += 4; - } - } else if (dwidth == VME_D16) { - count32 = (count - done) & ~0x3; - while (done < count32) { - fake_vmewrite16(bridge, (u16 *)(buf + done), - addr + done, aspace, cycle); - done += 2; - } - } else if (dwidth == VME_D8) { - count32 = (count - done); - while (done < count32) { - fake_vmewrite8(bridge, (u8 *)(buf + done), addr + done, - aspace, cycle); - done += 1; - } - } - - if ((dwidth == VME_D16) || (dwidth == VME_D32)) { - if ((count - done) & 0x2) { - fake_vmewrite16(bridge, (u16 *)(buf + done), - addr + done, aspace, cycle); - done += 2; - } - } - - if ((count - done) & 0x1) { - fake_vmewrite8(bridge, (u8 *)(buf + done), addr + done, aspace, - cycle); - done += 1; - } - -out: - retval = count; - - spin_unlock(&image->lock); - - return retval; -} - -/* - * Perform an RMW cycle on the VME bus. - * - * Requires a previously configured master window, returns final value. - */ -static unsigned int fake_master_rmw(struct vme_master_resource *image, - unsigned int mask, unsigned int compare, - unsigned int swap, loff_t offset) -{ - u32 tmp, base; - u32 aspace, cycle; - int i; - struct fake_driver *bridge; - - bridge = image->parent->driver_priv; - - /* Find the PCI address that maps to the desired VME address */ - i = image->number; - - base = bridge->masters[i].vme_base; - aspace = bridge->masters[i].aspace; - cycle = bridge->masters[i].cycle; - - /* Lock image */ - spin_lock(&image->lock); - - /* Read existing value */ - tmp = fake_vmeread32(bridge, base + offset, aspace, cycle); - - /* Perform check */ - if ((tmp && mask) == (compare && mask)) { - tmp = tmp | (mask | swap); - tmp = tmp & (~mask | swap); - - /* Write back */ - fake_vmewrite32(bridge, &tmp, base + offset, aspace, cycle); - } - - /* Unlock image */ - spin_unlock(&image->lock); - - return tmp; -} - -/* - * All 4 location monitors reside at the same base - this is therefore a - * system wide configuration. - * - * This does not enable the LM monitor - that should be done when the first - * callback is attached and disabled when the last callback is removed. - */ -static int fake_lm_set(struct vme_lm_resource *lm, unsigned long long lm_base, - u32 aspace, u32 cycle) -{ - int i; - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = lm->parent; - - bridge = fake_bridge->driver_priv; - - mutex_lock(&lm->mtx); - - /* If we already have a callback attached, we can't move it! */ - for (i = 0; i < lm->monitors; i++) { - if (bridge->lm_callback[i]) { - mutex_unlock(&lm->mtx); - pr_err("Location monitor callback attached, can't reset\n"); - return -EBUSY; - } - } - - switch (aspace) { - case VME_A16: - case VME_A24: - case VME_A32: - case VME_A64: - break; - default: - mutex_unlock(&lm->mtx); - pr_err("Invalid address space\n"); - return -EINVAL; - } - - bridge->lm_base = lm_base; - bridge->lm_aspace = aspace; - bridge->lm_cycle = cycle; - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* Get configuration of the callback monitor and return whether it is enabled - * or disabled. - */ -static int fake_lm_get(struct vme_lm_resource *lm, - unsigned long long *lm_base, - u32 *aspace, u32 *cycle) -{ - struct fake_driver *bridge; - - bridge = lm->parent->driver_priv; - - mutex_lock(&lm->mtx); - - *lm_base = bridge->lm_base; - *aspace = bridge->lm_aspace; - *cycle = bridge->lm_cycle; - - mutex_unlock(&lm->mtx); - - return bridge->lm_enabled; -} - -/* - * Attach a callback to a specific location monitor. - * - * Callback will be passed the monitor triggered. - */ -static int fake_lm_attach(struct vme_lm_resource *lm, int monitor, - void (*callback)(void *), void *data) -{ - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = lm->parent; - - bridge = fake_bridge->driver_priv; - - mutex_lock(&lm->mtx); - - /* Ensure that the location monitor is configured - need PGM or DATA */ - if (bridge->lm_cycle == 0) { - mutex_unlock(&lm->mtx); - pr_err("Location monitor not properly configured\n"); - return -EINVAL; - } - - /* Check that a callback isn't already attached */ - if (bridge->lm_callback[monitor]) { - mutex_unlock(&lm->mtx); - pr_err("Existing callback attached\n"); - return -EBUSY; - } - - /* Attach callback */ - bridge->lm_callback[monitor] = callback; - bridge->lm_data[monitor] = data; - - /* Ensure that global Location Monitor Enable set */ - bridge->lm_enabled = 1; - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* - * Detach a callback function forn a specific location monitor. - */ -static int fake_lm_detach(struct vme_lm_resource *lm, int monitor) -{ - u32 tmp; - int i; - struct fake_driver *bridge; - - bridge = lm->parent->driver_priv; - - mutex_lock(&lm->mtx); - - /* Detach callback */ - bridge->lm_callback[monitor] = NULL; - bridge->lm_data[monitor] = NULL; - - /* If all location monitors disabled, disable global Location Monitor */ - tmp = 0; - for (i = 0; i < lm->monitors; i++) { - if (bridge->lm_callback[i]) - tmp = 1; - } - - if (tmp == 0) - bridge->lm_enabled = 0; - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* - * Determine Geographical Addressing - */ -static int fake_slot_get(struct vme_bridge *fake_bridge) -{ - return geoid; -} - -static void *fake_alloc_consistent(struct device *parent, size_t size, - dma_addr_t *dma) -{ - void *alloc = kmalloc(size, GFP_KERNEL); - - if (alloc) - *dma = fake_ptr_to_pci(alloc); - - return alloc; -} - -static void fake_free_consistent(struct device *parent, size_t size, - void *vaddr, dma_addr_t dma) -{ - kfree(vaddr); -} - -/* - * Configure CR/CSR space - * - * Access to the CR/CSR can be configured at power-up. The location of the - * CR/CSR registers in the CR/CSR address space is determined by the boards - * Geographic address. - * - * Each board has a 512kB window, with the highest 4kB being used for the - * boards registers, this means there is a fix length 508kB window which must - * be mapped onto PCI memory. - */ -static int fake_crcsr_init(struct vme_bridge *fake_bridge) -{ - u32 vstat; - struct fake_driver *bridge; - - bridge = fake_bridge->driver_priv; - - /* Allocate mem for CR/CSR image */ - bridge->crcsr_kernel = kzalloc(VME_CRCSR_BUF_SIZE, GFP_KERNEL); - bridge->crcsr_bus = fake_ptr_to_pci(bridge->crcsr_kernel); - if (!bridge->crcsr_kernel) - return -ENOMEM; - - vstat = fake_slot_get(fake_bridge); - - pr_info("CR/CSR Offset: %d\n", vstat); - - return 0; -} - -static void fake_crcsr_exit(struct vme_bridge *fake_bridge) -{ - struct fake_driver *bridge; - - bridge = fake_bridge->driver_priv; - - kfree(bridge->crcsr_kernel); -} - -static int __init fake_init(void) -{ - int retval, i; - struct list_head *pos = NULL, *n; - struct vme_bridge *fake_bridge; - struct fake_driver *fake_device; - struct vme_master_resource *master_image; - struct vme_slave_resource *slave_image; - struct vme_lm_resource *lm; - - if (geoid >= VME_MAX_SLOTS) { - pr_err("VME geographical address must be between 0 and %d (exclusive), but got %d\n", - VME_MAX_SLOTS, geoid); - return -EINVAL; - } - - /* We need a fake parent device */ - vme_root = root_device_register("vme"); - if (IS_ERR(vme_root)) - return PTR_ERR(vme_root); - - /* If we want to support more than one bridge at some point, we need to - * dynamically allocate this so we get one per device. - */ - fake_bridge = kzalloc_obj(*fake_bridge); - if (!fake_bridge) { - retval = -ENOMEM; - goto err_struct; - } - - fake_device = kzalloc_obj(*fake_device); - if (!fake_device) { - retval = -ENOMEM; - goto err_driver; - } - - fake_bridge->driver_priv = fake_device; - - fake_bridge->parent = vme_root; - - fake_device->parent = fake_bridge; - - /* Initialize wait queues & mutual exclusion flags */ - mutex_init(&fake_device->vme_int); - mutex_init(&fake_bridge->irq_mtx); - tasklet_init(&fake_device->int_tasklet, fake_VIRQ_tasklet, - (unsigned long)fake_bridge); - - strscpy(fake_bridge->name, driver_name, sizeof(fake_bridge->name)); - - /* Add master windows to list */ - INIT_LIST_HEAD(&fake_bridge->master_resources); - for (i = 0; i < FAKE_MAX_MASTER; i++) { - master_image = kmalloc_obj(*master_image); - if (!master_image) { - retval = -ENOMEM; - goto err_master; - } - master_image->parent = fake_bridge; - spin_lock_init(&master_image->lock); - master_image->locked = 0; - master_image->number = i; - master_image->address_attr = VME_A16 | VME_A24 | VME_A32 | - VME_A64; - master_image->cycle_attr = VME_SCT | VME_BLT | VME_MBLT | - VME_2eVME | VME_2eSST | VME_2eSSTB | VME_2eSST160 | - VME_2eSST267 | VME_2eSST320 | VME_SUPER | VME_USER | - VME_PROG | VME_DATA; - master_image->width_attr = VME_D16 | VME_D32; - memset(&master_image->bus_resource, 0, - sizeof(struct resource)); - master_image->kern_base = NULL; - list_add_tail(&master_image->list, - &fake_bridge->master_resources); - } - - /* Add slave windows to list */ - INIT_LIST_HEAD(&fake_bridge->slave_resources); - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - slave_image = kmalloc_obj(*slave_image); - if (!slave_image) { - retval = -ENOMEM; - goto err_slave; - } - slave_image->parent = fake_bridge; - mutex_init(&slave_image->mtx); - slave_image->locked = 0; - slave_image->number = i; - slave_image->address_attr = VME_A16 | VME_A24 | VME_A32 | - VME_A64 | VME_CRCSR | VME_USER1 | VME_USER2 | - VME_USER3 | VME_USER4; - slave_image->cycle_attr = VME_SCT | VME_BLT | VME_MBLT | - VME_2eVME | VME_2eSST | VME_2eSSTB | VME_2eSST160 | - VME_2eSST267 | VME_2eSST320 | VME_SUPER | VME_USER | - VME_PROG | VME_DATA; - list_add_tail(&slave_image->list, - &fake_bridge->slave_resources); - } - - /* Add location monitor to list */ - INIT_LIST_HEAD(&fake_bridge->lm_resources); - lm = kmalloc_obj(*lm); - if (!lm) { - retval = -ENOMEM; - goto err_lm; - } - lm->parent = fake_bridge; - mutex_init(&lm->mtx); - lm->locked = 0; - lm->number = 1; - lm->monitors = 4; - list_add_tail(&lm->list, &fake_bridge->lm_resources); - - fake_bridge->slave_get = fake_slave_get; - fake_bridge->slave_set = fake_slave_set; - fake_bridge->master_get = fake_master_get; - fake_bridge->master_set = fake_master_set; - fake_bridge->master_read = fake_master_read; - fake_bridge->master_write = fake_master_write; - fake_bridge->master_rmw = fake_master_rmw; - fake_bridge->irq_set = fake_irq_set; - fake_bridge->irq_generate = fake_irq_generate; - fake_bridge->lm_set = fake_lm_set; - fake_bridge->lm_get = fake_lm_get; - fake_bridge->lm_attach = fake_lm_attach; - fake_bridge->lm_detach = fake_lm_detach; - fake_bridge->slot_get = fake_slot_get; - fake_bridge->alloc_consistent = fake_alloc_consistent; - fake_bridge->free_consistent = fake_free_consistent; - - pr_info("Board is%s the VME system controller\n", - (geoid == 1) ? "" : " not"); - - pr_info("VME geographical address is set to %d\n", geoid); - - retval = fake_crcsr_init(fake_bridge); - if (retval) { - pr_err("CR/CSR configuration failed.\n"); - goto err_crcsr; - } - - retval = vme_register_bridge(fake_bridge); - if (retval != 0) { - pr_err("Chip Registration failed.\n"); - goto err_reg; - } - - exit_pointer = fake_bridge; - - return 0; - -err_reg: - fake_crcsr_exit(fake_bridge); -err_crcsr: -err_lm: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &fake_bridge->lm_resources) { - lm = list_entry(pos, struct vme_lm_resource, list); - list_del(pos); - kfree(lm); - } -err_slave: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &fake_bridge->slave_resources) { - slave_image = list_entry(pos, struct vme_slave_resource, list); - list_del(pos); - kfree(slave_image); - } -err_master: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &fake_bridge->master_resources) { - master_image = list_entry(pos, struct vme_master_resource, - list); - list_del(pos); - kfree(master_image); - } - - kfree(fake_device); -err_driver: - kfree(fake_bridge); -err_struct: - root_device_unregister(vme_root); - - return retval; -} - -static void __exit fake_exit(void) -{ - struct list_head *pos = NULL; - struct list_head *tmplist; - struct vme_lm_resource *lm; - struct vme_master_resource *master_image; - struct vme_slave_resource *slave_image; - int i; - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = exit_pointer; - - bridge = fake_bridge->driver_priv; - - pr_debug("Driver is being unloaded.\n"); - - /* - * Shutdown all inbound and outbound windows. - */ - for (i = 0; i < FAKE_MAX_MASTER; i++) - bridge->masters[i].enabled = 0; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) - bridge->slaves[i].enabled = 0; - - /* - * Shutdown Location monitor. - */ - bridge->lm_enabled = 0; - - vme_unregister_bridge(fake_bridge); - - fake_crcsr_exit(fake_bridge); - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &fake_bridge->lm_resources) { - lm = list_entry(pos, struct vme_lm_resource, list); - list_del(pos); - kfree(lm); - } - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &fake_bridge->slave_resources) { - slave_image = list_entry(pos, struct vme_slave_resource, list); - list_del(pos); - kfree(slave_image); - } - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &fake_bridge->master_resources) { - master_image = list_entry(pos, struct vme_master_resource, - list); - list_del(pos); - kfree(master_image); - } - - kfree(fake_bridge->driver_priv); - - kfree(fake_bridge); - - root_device_unregister(vme_root); -} - -MODULE_PARM_DESC(geoid, "Set geographical addressing"); -module_param(geoid, uint, 0); - -MODULE_DESCRIPTION("Fake VME bridge driver"); -MODULE_LICENSE("GPL"); - -module_init(fake_init); -module_exit(fake_exit); diff --git a/drivers/staging/vme_user/vme_tsi148.c b/drivers/staging/vme_user/vme_tsi148.c deleted file mode 100644 index 9447c00bc013d7..00000000000000 --- a/drivers/staging/vme_user/vme_tsi148.c +++ /dev/null @@ -1,2643 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -/* - * Support for the Tundra TSI148 VME-PCI Bridge Chip - * - * Author: Martyn Welch - * Copyright 2008 GE Intelligent Platforms Embedded Systems, Inc. - * - * Based on work by Tom Armistead and Ajit Prem - * Copyright 2004 Motorola Inc. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "vme.h" -#include "vme_bridge.h" -#include "vme_tsi148.h" - -static int tsi148_probe(struct pci_dev *, const struct pci_device_id *); -static void tsi148_remove(struct pci_dev *); - -/* Module parameter */ -static bool err_chk; -static u32 geoid; - -static const char driver_name[] = "vme_tsi148"; - -static const struct pci_device_id tsi148_ids[] = { - { PCI_DEVICE(PCI_VENDOR_ID_TUNDRA, PCI_DEVICE_ID_TUNDRA_TSI148) }, - { }, -}; - -MODULE_DEVICE_TABLE(pci, tsi148_ids); - -static struct pci_driver tsi148_driver = { - .name = driver_name, - .id_table = tsi148_ids, - .probe = tsi148_probe, - .remove = tsi148_remove, -}; - -static void reg_join(unsigned int high, unsigned int low, - unsigned long long *variable) -{ - *variable = (unsigned long long)high << 32; - *variable |= (unsigned long long)low; -} - -static void reg_split(unsigned long long variable, unsigned int *high, - unsigned int *low) -{ - *low = (unsigned int)variable & 0xFFFFFFFF; - *high = (unsigned int)(variable >> 32); -} - -/* - * Wakes up DMA queue. - */ -static u32 tsi148_DMA_irqhandler(struct tsi148_driver *bridge, - int channel_mask) -{ - u32 serviced = 0; - - if (channel_mask & TSI148_LCSR_INTS_DMA0S) { - wake_up(&bridge->dma_queue[0]); - serviced |= TSI148_LCSR_INTC_DMA0C; - } - if (channel_mask & TSI148_LCSR_INTS_DMA1S) { - wake_up(&bridge->dma_queue[1]); - serviced |= TSI148_LCSR_INTC_DMA1C; - } - - return serviced; -} - -/* - * Wake up location monitor queue - */ -static u32 tsi148_LM_irqhandler(struct tsi148_driver *bridge, u32 stat) -{ - int i; - u32 serviced = 0; - - for (i = 0; i < 4; i++) { - if (stat & TSI148_LCSR_INTS_LMS[i]) { - /* We only enable interrupts if the callback is set */ - bridge->lm_callback[i](bridge->lm_data[i]); - serviced |= TSI148_LCSR_INTC_LMC[i]; - } - } - - return serviced; -} - -/* - * Wake up mail box queue. - * - * XXX This functionality is not exposed up though API. - */ -static u32 tsi148_MB_irqhandler(struct vme_bridge *tsi148_bridge, u32 stat) -{ - int i; - u32 val; - u32 serviced = 0; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - for (i = 0; i < 4; i++) { - if (stat & TSI148_LCSR_INTS_MBS[i]) { - val = ioread32be(bridge->base + TSI148_GCSR_MBOX[i]); - dev_err(tsi148_bridge->parent, "VME Mailbox %d received: 0x%x\n", - i, val); - serviced |= TSI148_LCSR_INTC_MBC[i]; - } - } - - return serviced; -} - -/* - * Display error & status message when PERR (PCI) exception interrupt occurs. - */ -static u32 tsi148_PERR_irqhandler(struct vme_bridge *tsi148_bridge) -{ - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - dev_err(tsi148_bridge->parent, "PCI Exception at address: 0x%08x:%08x, attributes: %08x\n", - ioread32be(bridge->base + TSI148_LCSR_EDPAU), - ioread32be(bridge->base + TSI148_LCSR_EDPAL), - ioread32be(bridge->base + TSI148_LCSR_EDPAT)); - - dev_err(tsi148_bridge->parent, "PCI-X attribute reg: %08x, PCI-X split completion reg: %08x\n", - ioread32be(bridge->base + TSI148_LCSR_EDPXA), - ioread32be(bridge->base + TSI148_LCSR_EDPXS)); - - iowrite32be(TSI148_LCSR_EDPAT_EDPCL, bridge->base + TSI148_LCSR_EDPAT); - - return TSI148_LCSR_INTC_PERRC; -} - -/* - * Save address and status when VME error interrupt occurs. - */ -static u32 tsi148_VERR_irqhandler(struct vme_bridge *tsi148_bridge) -{ - unsigned int error_addr_high, error_addr_low; - unsigned long long error_addr; - u32 error_attrib; - int error_am; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - error_addr_high = ioread32be(bridge->base + TSI148_LCSR_VEAU); - error_addr_low = ioread32be(bridge->base + TSI148_LCSR_VEAL); - error_attrib = ioread32be(bridge->base + TSI148_LCSR_VEAT); - error_am = (error_attrib & TSI148_LCSR_VEAT_AM_M) >> 8; - - reg_join(error_addr_high, error_addr_low, &error_addr); - - /* Check for exception register overflow (we have lost error data) */ - if (error_attrib & TSI148_LCSR_VEAT_VEOF) - dev_err(tsi148_bridge->parent, "VME Bus Exception Overflow Occurred\n"); - - if (err_chk) - vme_bus_error_handler(tsi148_bridge, error_addr, error_am); - else - dev_err(tsi148_bridge->parent, - "VME Bus Error at address: 0x%llx, attributes: %08x\n", - error_addr, error_attrib); - - /* Clear Status */ - iowrite32be(TSI148_LCSR_VEAT_VESCL, bridge->base + TSI148_LCSR_VEAT); - - return TSI148_LCSR_INTC_VERRC; -} - -/* - * Wake up IACK queue. - */ -static u32 tsi148_IACK_irqhandler(struct tsi148_driver *bridge) -{ - wake_up(&bridge->iack_queue); - - return TSI148_LCSR_INTC_IACKC; -} - -/* - * Calling VME bus interrupt callback if provided. - */ -static u32 tsi148_VIRQ_irqhandler(struct vme_bridge *tsi148_bridge, - u32 stat) -{ - int vec, i, serviced = 0; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - for (i = 7; i > 0; i--) { - if (stat & (1 << i)) { - /* - * Note: Even though the registers are defined as - * 32-bits in the spec, we only want to issue 8-bit - * IACK cycles on the bus, read from offset 3. - */ - vec = ioread8(bridge->base + TSI148_LCSR_VIACK[i] + 3); - - vme_irq_handler(tsi148_bridge, i, vec); - - serviced |= (1 << i); - } - } - - return serviced; -} - -/* - * Top level interrupt handler. Clears appropriate interrupt status bits and - * then calls appropriate sub handler(s). - */ -static irqreturn_t tsi148_irqhandler(int irq, void *ptr) -{ - u32 stat, enable, serviced = 0; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - tsi148_bridge = ptr; - - bridge = tsi148_bridge->driver_priv; - - /* Determine which interrupts are unmasked and set */ - enable = ioread32be(bridge->base + TSI148_LCSR_INTEO); - stat = ioread32be(bridge->base + TSI148_LCSR_INTS); - - /* Only look at unmasked interrupts */ - stat &= enable; - - if (unlikely(!stat)) - return IRQ_NONE; - - /* Call subhandlers as appropriate */ - /* DMA irqs */ - if (stat & (TSI148_LCSR_INTS_DMA1S | TSI148_LCSR_INTS_DMA0S)) - serviced |= tsi148_DMA_irqhandler(bridge, stat); - - /* Location monitor irqs */ - if (stat & (TSI148_LCSR_INTS_LM3S | TSI148_LCSR_INTS_LM2S | - TSI148_LCSR_INTS_LM1S | TSI148_LCSR_INTS_LM0S)) - serviced |= tsi148_LM_irqhandler(bridge, stat); - - /* Mail box irqs */ - if (stat & (TSI148_LCSR_INTS_MB3S | TSI148_LCSR_INTS_MB2S | - TSI148_LCSR_INTS_MB1S | TSI148_LCSR_INTS_MB0S)) - serviced |= tsi148_MB_irqhandler(tsi148_bridge, stat); - - /* PCI bus error */ - if (stat & TSI148_LCSR_INTS_PERRS) - serviced |= tsi148_PERR_irqhandler(tsi148_bridge); - - /* VME bus error */ - if (stat & TSI148_LCSR_INTS_VERRS) - serviced |= tsi148_VERR_irqhandler(tsi148_bridge); - - /* IACK irq */ - if (stat & TSI148_LCSR_INTS_IACKS) - serviced |= tsi148_IACK_irqhandler(bridge); - - /* VME bus irqs */ - if (stat & (TSI148_LCSR_INTS_IRQ7S | TSI148_LCSR_INTS_IRQ6S | - TSI148_LCSR_INTS_IRQ5S | TSI148_LCSR_INTS_IRQ4S | - TSI148_LCSR_INTS_IRQ3S | TSI148_LCSR_INTS_IRQ2S | - TSI148_LCSR_INTS_IRQ1S)) - serviced |= tsi148_VIRQ_irqhandler(tsi148_bridge, stat); - - /* Clear serviced interrupts */ - iowrite32be(serviced, bridge->base + TSI148_LCSR_INTC); - - return IRQ_HANDLED; -} - -static int tsi148_irq_init(struct vme_bridge *tsi148_bridge) -{ - int result; - unsigned int tmp; - struct pci_dev *pdev; - struct tsi148_driver *bridge; - - pdev = to_pci_dev(tsi148_bridge->parent); - - bridge = tsi148_bridge->driver_priv; - - result = request_irq(pdev->irq, - tsi148_irqhandler, - IRQF_SHARED, - driver_name, tsi148_bridge); - if (result) { - dev_err(tsi148_bridge->parent, "Can't get assigned pci irq vector %02X\n", - pdev->irq); - return result; - } - - /* Enable and unmask interrupts */ - tmp = TSI148_LCSR_INTEO_DMA1EO | TSI148_LCSR_INTEO_DMA0EO | - TSI148_LCSR_INTEO_MB3EO | TSI148_LCSR_INTEO_MB2EO | - TSI148_LCSR_INTEO_MB1EO | TSI148_LCSR_INTEO_MB0EO | - TSI148_LCSR_INTEO_PERREO | TSI148_LCSR_INTEO_VERREO | - TSI148_LCSR_INTEO_IACKEO; - - /* This leaves the following interrupts masked. - * TSI148_LCSR_INTEO_VIEEO - * TSI148_LCSR_INTEO_SYSFLEO - * TSI148_LCSR_INTEO_ACFLEO - */ - - /* Don't enable Location Monitor interrupts here - they will be - * enabled when the location monitors are properly configured and - * a callback has been attached. - * TSI148_LCSR_INTEO_LM0EO - * TSI148_LCSR_INTEO_LM1EO - * TSI148_LCSR_INTEO_LM2EO - * TSI148_LCSR_INTEO_LM3EO - */ - - /* Don't enable VME interrupts until we add a handler, else the board - * will respond to it and we don't want that unless it knows how to - * properly deal with it. - * TSI148_LCSR_INTEO_IRQ7EO - * TSI148_LCSR_INTEO_IRQ6EO - * TSI148_LCSR_INTEO_IRQ5EO - * TSI148_LCSR_INTEO_IRQ4EO - * TSI148_LCSR_INTEO_IRQ3EO - * TSI148_LCSR_INTEO_IRQ2EO - * TSI148_LCSR_INTEO_IRQ1EO - */ - - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO); - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN); - - return 0; -} - -static void tsi148_irq_exit(struct vme_bridge *tsi148_bridge, - struct pci_dev *pdev) -{ - struct tsi148_driver *bridge = tsi148_bridge->driver_priv; - - /* Turn off interrupts */ - iowrite32be(0x0, bridge->base + TSI148_LCSR_INTEO); - iowrite32be(0x0, bridge->base + TSI148_LCSR_INTEN); - - /* Clear all interrupts */ - iowrite32be(0xFFFFFFFF, bridge->base + TSI148_LCSR_INTC); - - /* Detach interrupt handler */ - free_irq(pdev->irq, tsi148_bridge); -} - -/* - * Check to see if an IACk has been received, return true (1) or false (0). - */ -static int tsi148_iack_received(struct tsi148_driver *bridge) -{ - u32 tmp; - - tmp = ioread32be(bridge->base + TSI148_LCSR_VICR); - - if (tmp & TSI148_LCSR_VICR_IRQS) - return 0; - else - return 1; -} - -/* - * Configure VME interrupt - */ -static void tsi148_irq_set(struct vme_bridge *tsi148_bridge, int level, - int state, int sync) -{ - struct pci_dev *pdev; - u32 tmp; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - /* We need to do the ordering differently for enabling and disabling */ - if (state == 0) { - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEN); - tmp &= ~TSI148_LCSR_INTEN_IRQEN[level - 1]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN); - - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO); - tmp &= ~TSI148_LCSR_INTEO_IRQEO[level - 1]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO); - - if (sync != 0) { - pdev = to_pci_dev(tsi148_bridge->parent); - synchronize_irq(pdev->irq); - } - } else { - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO); - tmp |= TSI148_LCSR_INTEO_IRQEO[level - 1]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO); - - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEN); - tmp |= TSI148_LCSR_INTEN_IRQEN[level - 1]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN); - } -} - -/* - * Generate a VME bus interrupt at the requested level & vector. Wait for - * interrupt to be acked. - */ -static int tsi148_irq_generate(struct vme_bridge *tsi148_bridge, int level, - int statid) -{ - u32 tmp; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - mutex_lock(&bridge->vme_int); - - /* Read VICR register */ - tmp = ioread32be(bridge->base + TSI148_LCSR_VICR); - - /* Set Status/ID */ - tmp = (tmp & ~TSI148_LCSR_VICR_STID_M) | - (statid & TSI148_LCSR_VICR_STID_M); - iowrite32be(tmp, bridge->base + TSI148_LCSR_VICR); - - /* Assert VMEbus IRQ */ - tmp = tmp | TSI148_LCSR_VICR_IRQL[level]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_VICR); - - /* XXX Consider implementing a timeout? */ - wait_event_interruptible(bridge->iack_queue, - tsi148_iack_received(bridge)); - - mutex_unlock(&bridge->vme_int); - - return 0; -} - -/* - * Initialize a slave window with the requested attributes. - */ -static int tsi148_slave_set(struct vme_slave_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - dma_addr_t pci_base, u32 aspace, u32 cycle) -{ - unsigned int i, addr = 0, granularity = 0; - unsigned int temp_ctl = 0; - unsigned int vme_base_low, vme_base_high; - unsigned int vme_bound_low, vme_bound_high; - unsigned int pci_offset_low, pci_offset_high; - unsigned long long vme_bound, pci_offset; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - tsi148_bridge = image->parent; - bridge = tsi148_bridge->driver_priv; - - i = image->number; - - switch (aspace) { - case VME_A16: - granularity = 0x10; - addr |= TSI148_LCSR_ITAT_AS_A16; - break; - case VME_A24: - granularity = 0x1000; - addr |= TSI148_LCSR_ITAT_AS_A24; - break; - case VME_A32: - granularity = 0x10000; - addr |= TSI148_LCSR_ITAT_AS_A32; - break; - case VME_A64: - granularity = 0x10000; - addr |= TSI148_LCSR_ITAT_AS_A64; - break; - default: - dev_err(tsi148_bridge->parent, "Invalid address space\n"); - return -EINVAL; - } - - /* Convert 64-bit variables to 2x 32-bit variables */ - reg_split(vme_base, &vme_base_high, &vme_base_low); - - /* - * Bound address is a valid address for the window, adjust - * accordingly - */ - vme_bound = vme_base + size - granularity; - reg_split(vme_bound, &vme_bound_high, &vme_bound_low); - pci_offset = (unsigned long long)pci_base - vme_base; - reg_split(pci_offset, &pci_offset_high, &pci_offset_low); - - if (vme_base_low & (granularity - 1)) { - dev_err(tsi148_bridge->parent, "Invalid VME base alignment\n"); - return -EINVAL; - } - if (vme_bound_low & (granularity - 1)) { - dev_err(tsi148_bridge->parent, "Invalid VME bound alignment\n"); - return -EINVAL; - } - if (pci_offset_low & (granularity - 1)) { - dev_err(tsi148_bridge->parent, "Invalid PCI Offset alignment\n"); - return -EINVAL; - } - - /* Disable while we are mucking around */ - temp_ctl = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - temp_ctl &= ~TSI148_LCSR_ITAT_EN; - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - - /* Setup mapping */ - iowrite32be(vme_base_high, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITSAU); - iowrite32be(vme_base_low, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITSAL); - iowrite32be(vme_bound_high, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITEAU); - iowrite32be(vme_bound_low, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITEAL); - iowrite32be(pci_offset_high, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITOFU); - iowrite32be(pci_offset_low, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITOFL); - - /* Setup 2eSST speeds */ - temp_ctl &= ~TSI148_LCSR_ITAT_2eSSTM_M; - switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) { - case VME_2eSST160: - temp_ctl |= TSI148_LCSR_ITAT_2eSSTM_160; - break; - case VME_2eSST267: - temp_ctl |= TSI148_LCSR_ITAT_2eSSTM_267; - break; - case VME_2eSST320: - temp_ctl |= TSI148_LCSR_ITAT_2eSSTM_320; - break; - } - - /* Setup cycle types */ - temp_ctl &= ~(0x1F << 7); - if (cycle & VME_BLT) - temp_ctl |= TSI148_LCSR_ITAT_BLT; - if (cycle & VME_MBLT) - temp_ctl |= TSI148_LCSR_ITAT_MBLT; - if (cycle & VME_2eVME) - temp_ctl |= TSI148_LCSR_ITAT_2eVME; - if (cycle & VME_2eSST) - temp_ctl |= TSI148_LCSR_ITAT_2eSST; - if (cycle & VME_2eSSTB) - temp_ctl |= TSI148_LCSR_ITAT_2eSSTB; - - /* Setup address space */ - temp_ctl &= ~TSI148_LCSR_ITAT_AS_M; - temp_ctl |= addr; - - temp_ctl &= ~0xF; - if (cycle & VME_SUPER) - temp_ctl |= TSI148_LCSR_ITAT_SUPR; - if (cycle & VME_USER) - temp_ctl |= TSI148_LCSR_ITAT_NPRIV; - if (cycle & VME_PROG) - temp_ctl |= TSI148_LCSR_ITAT_PGM; - if (cycle & VME_DATA) - temp_ctl |= TSI148_LCSR_ITAT_DATA; - - /* Write ctl reg without enable */ - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - - if (enabled) - temp_ctl |= TSI148_LCSR_ITAT_EN; - - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - - return 0; -} - -/* - * Get slave window configuration. - */ -static int tsi148_slave_get(struct vme_slave_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - dma_addr_t *pci_base, u32 *aspace, u32 *cycle) -{ - unsigned int i, granularity = 0, ctl = 0; - unsigned int vme_base_low, vme_base_high; - unsigned int vme_bound_low, vme_bound_high; - unsigned int pci_offset_low, pci_offset_high; - unsigned long long vme_bound, pci_offset; - struct tsi148_driver *bridge; - - bridge = image->parent->driver_priv; - - i = image->number; - - /* Read registers */ - ctl = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - - vme_base_high = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITSAU); - vme_base_low = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITSAL); - vme_bound_high = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITEAU); - vme_bound_low = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITEAL); - pci_offset_high = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITOFU); - pci_offset_low = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITOFL); - - /* Convert 64-bit variables to 2x 32-bit variables */ - reg_join(vme_base_high, vme_base_low, vme_base); - reg_join(vme_bound_high, vme_bound_low, &vme_bound); - reg_join(pci_offset_high, pci_offset_low, &pci_offset); - - *pci_base = (dma_addr_t)(*vme_base + pci_offset); - - *enabled = 0; - *aspace = 0; - *cycle = 0; - - if (ctl & TSI148_LCSR_ITAT_EN) - *enabled = 1; - - if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A16) { - granularity = 0x10; - *aspace |= VME_A16; - } - if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A24) { - granularity = 0x1000; - *aspace |= VME_A24; - } - if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A32) { - granularity = 0x10000; - *aspace |= VME_A32; - } - if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A64) { - granularity = 0x10000; - *aspace |= VME_A64; - } - - /* Need granularity before we set the size */ - *size = (unsigned long long)((vme_bound - *vme_base) + granularity); - - if ((ctl & TSI148_LCSR_ITAT_2eSSTM_M) == TSI148_LCSR_ITAT_2eSSTM_160) - *cycle |= VME_2eSST160; - if ((ctl & TSI148_LCSR_ITAT_2eSSTM_M) == TSI148_LCSR_ITAT_2eSSTM_267) - *cycle |= VME_2eSST267; - if ((ctl & TSI148_LCSR_ITAT_2eSSTM_M) == TSI148_LCSR_ITAT_2eSSTM_320) - *cycle |= VME_2eSST320; - - if (ctl & TSI148_LCSR_ITAT_BLT) - *cycle |= VME_BLT; - if (ctl & TSI148_LCSR_ITAT_MBLT) - *cycle |= VME_MBLT; - if (ctl & TSI148_LCSR_ITAT_2eVME) - *cycle |= VME_2eVME; - if (ctl & TSI148_LCSR_ITAT_2eSST) - *cycle |= VME_2eSST; - if (ctl & TSI148_LCSR_ITAT_2eSSTB) - *cycle |= VME_2eSSTB; - - if (ctl & TSI148_LCSR_ITAT_SUPR) - *cycle |= VME_SUPER; - if (ctl & TSI148_LCSR_ITAT_NPRIV) - *cycle |= VME_USER; - if (ctl & TSI148_LCSR_ITAT_PGM) - *cycle |= VME_PROG; - if (ctl & TSI148_LCSR_ITAT_DATA) - *cycle |= VME_DATA; - - return 0; -} - -/* - * Allocate and map PCI Resource - */ -static int tsi148_alloc_resource(struct vme_master_resource *image, - unsigned long long size) -{ - unsigned long long existing_size; - int retval = 0; - struct pci_dev *pdev; - struct vme_bridge *tsi148_bridge; - - tsi148_bridge = image->parent; - - pdev = to_pci_dev(tsi148_bridge->parent); - - existing_size = (unsigned long long)(image->bus_resource.end - - image->bus_resource.start); - - /* If the existing size is OK, return */ - if ((size != 0) && (existing_size == (size - 1))) - return 0; - - if (existing_size != 0) { - iounmap(image->kern_base); - image->kern_base = NULL; - kfree(image->bus_resource.name); - release_resource(&image->bus_resource); - memset(&image->bus_resource, 0, sizeof(image->bus_resource)); - } - - /* Exit here if size is zero */ - if (size == 0) - return 0; - - if (!image->bus_resource.name) { - image->bus_resource.name = kmalloc(VMENAMSIZ + 3, GFP_ATOMIC); - if (!image->bus_resource.name) { - retval = -ENOMEM; - goto err_name; - } - } - - sprintf((char *)image->bus_resource.name, "%s.%d", tsi148_bridge->name, - image->number); - - image->bus_resource.start = 0; - image->bus_resource.end = (unsigned long)size; - image->bus_resource.flags = IORESOURCE_MEM; - - retval = pci_bus_alloc_resource(pdev->bus, &image->bus_resource, - size, 0x10000, PCIBIOS_MIN_MEM, - 0, NULL, NULL); - if (retval) { - dev_err(tsi148_bridge->parent, "Failed to allocate mem resource for window %d size 0x%lx start 0x%lx\n", - image->number, (unsigned long)size, - (unsigned long)image->bus_resource.start); - goto err_resource; - } - - image->kern_base = ioremap(image->bus_resource.start, size); - if (!image->kern_base) { - dev_err(tsi148_bridge->parent, "Failed to remap resource\n"); - retval = -ENOMEM; - goto err_remap; - } - - return 0; - -err_remap: - release_resource(&image->bus_resource); -err_resource: - kfree(image->bus_resource.name); - memset(&image->bus_resource, 0, sizeof(image->bus_resource)); -err_name: - return retval; -} - -/* - * Free and unmap PCI Resource - */ -static void tsi148_free_resource(struct vme_master_resource *image) -{ - iounmap(image->kern_base); - image->kern_base = NULL; - release_resource(&image->bus_resource); - kfree(image->bus_resource.name); - memset(&image->bus_resource, 0, sizeof(image->bus_resource)); -} - -/* - * Set the attributes of an outbound window. - */ -static int tsi148_master_set(struct vme_master_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - u32 aspace, u32 cycle, u32 dwidth) -{ - int retval = 0; - unsigned int i; - unsigned int temp_ctl = 0; - unsigned int pci_base_low, pci_base_high; - unsigned int pci_bound_low, pci_bound_high; - unsigned int vme_offset_low, vme_offset_high; - unsigned long long pci_bound, vme_offset, pci_base; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - struct pci_bus_region region; - struct pci_dev *pdev; - - tsi148_bridge = image->parent; - - bridge = tsi148_bridge->driver_priv; - - pdev = to_pci_dev(tsi148_bridge->parent); - - /* Verify input data */ - if (vme_base & 0xFFFF) { - dev_err(tsi148_bridge->parent, "Invalid VME Window alignment\n"); - retval = -EINVAL; - goto err_window; - } - - if ((size == 0) && (enabled != 0)) { - dev_err(tsi148_bridge->parent, "Size must be non-zero for enabled windows\n"); - retval = -EINVAL; - goto err_window; - } - - spin_lock(&image->lock); - - /* Let's allocate the resource here rather than further up the stack as - * it avoids pushing loads of bus dependent stuff up the stack. If size - * is zero, any existing resource will be freed. - */ - retval = tsi148_alloc_resource(image, size); - if (retval) { - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Unable to allocate memory for resource\n"); - goto err_res; - } - - if (size == 0) { - pci_base = 0; - pci_bound = 0; - vme_offset = 0; - } else { - pcibios_resource_to_bus(pdev->bus, ®ion, - &image->bus_resource); - pci_base = region.start; - - /* - * Bound address is a valid address for the window, adjust - * according to window granularity. - */ - pci_bound = pci_base + (size - 0x10000); - vme_offset = vme_base - pci_base; - } - - /* Convert 64-bit variables to 2x 32-bit variables */ - reg_split(pci_base, &pci_base_high, &pci_base_low); - reg_split(pci_bound, &pci_bound_high, &pci_bound_low); - reg_split(vme_offset, &vme_offset_high, &vme_offset_low); - - if (pci_base_low & 0xFFFF) { - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Invalid PCI base alignment\n"); - retval = -EINVAL; - goto err_gran; - } - if (pci_bound_low & 0xFFFF) { - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Invalid PCI bound alignment\n"); - retval = -EINVAL; - goto err_gran; - } - if (vme_offset_low & 0xFFFF) { - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Invalid VME Offset alignment\n"); - retval = -EINVAL; - goto err_gran; - } - - i = image->number; - - /* Disable while we are mucking around */ - temp_ctl = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - temp_ctl &= ~TSI148_LCSR_OTAT_EN; - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - - /* Setup 2eSST speeds */ - temp_ctl &= ~TSI148_LCSR_OTAT_2eSSTM_M; - switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) { - case VME_2eSST160: - temp_ctl |= TSI148_LCSR_OTAT_2eSSTM_160; - break; - case VME_2eSST267: - temp_ctl |= TSI148_LCSR_OTAT_2eSSTM_267; - break; - case VME_2eSST320: - temp_ctl |= TSI148_LCSR_OTAT_2eSSTM_320; - break; - } - - /* Setup cycle types */ - if (cycle & VME_BLT) { - temp_ctl &= ~TSI148_LCSR_OTAT_TM_M; - temp_ctl |= TSI148_LCSR_OTAT_TM_BLT; - } - if (cycle & VME_MBLT) { - temp_ctl &= ~TSI148_LCSR_OTAT_TM_M; - temp_ctl |= TSI148_LCSR_OTAT_TM_MBLT; - } - if (cycle & VME_2eVME) { - temp_ctl &= ~TSI148_LCSR_OTAT_TM_M; - temp_ctl |= TSI148_LCSR_OTAT_TM_2eVME; - } - if (cycle & VME_2eSST) { - temp_ctl &= ~TSI148_LCSR_OTAT_TM_M; - temp_ctl |= TSI148_LCSR_OTAT_TM_2eSST; - } - if (cycle & VME_2eSSTB) { - dev_warn(tsi148_bridge->parent, "Currently not setting Broadcast Select Registers\n"); - temp_ctl &= ~TSI148_LCSR_OTAT_TM_M; - temp_ctl |= TSI148_LCSR_OTAT_TM_2eSSTB; - } - - /* Setup data width */ - temp_ctl &= ~TSI148_LCSR_OTAT_DBW_M; - switch (dwidth) { - case VME_D16: - temp_ctl |= TSI148_LCSR_OTAT_DBW_16; - break; - case VME_D32: - temp_ctl |= TSI148_LCSR_OTAT_DBW_32; - break; - default: - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Invalid data width\n"); - retval = -EINVAL; - goto err_dwidth; - } - - /* Setup address space */ - temp_ctl &= ~TSI148_LCSR_OTAT_AMODE_M; - switch (aspace) { - case VME_A16: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_A16; - break; - case VME_A24: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_A24; - break; - case VME_A32: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_A32; - break; - case VME_A64: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_A64; - break; - case VME_CRCSR: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_CRCSR; - break; - case VME_USER1: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER1; - break; - case VME_USER2: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER2; - break; - case VME_USER3: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER3; - break; - case VME_USER4: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER4; - break; - default: - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Invalid address space\n"); - retval = -EINVAL; - goto err_aspace; - } - - temp_ctl &= ~(3 << 4); - if (cycle & VME_SUPER) - temp_ctl |= TSI148_LCSR_OTAT_SUP; - if (cycle & VME_PROG) - temp_ctl |= TSI148_LCSR_OTAT_PGM; - - /* Setup mapping */ - iowrite32be(pci_base_high, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAU); - iowrite32be(pci_base_low, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAL); - iowrite32be(pci_bound_high, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTEAU); - iowrite32be(pci_bound_low, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTEAL); - iowrite32be(vme_offset_high, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTOFU); - iowrite32be(vme_offset_low, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTOFL); - - /* Write ctl reg without enable */ - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - - if (enabled) - temp_ctl |= TSI148_LCSR_OTAT_EN; - - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - - spin_unlock(&image->lock); - return 0; - -err_aspace: -err_dwidth: -err_gran: - tsi148_free_resource(image); -err_res: -err_window: - return retval; -} - -/* - * Set the attributes of an outbound window. - * - * XXX Not parsing prefetch information. - */ -static int __tsi148_master_get(struct vme_master_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth) -{ - unsigned int i, ctl; - unsigned int pci_base_low, pci_base_high; - unsigned int pci_bound_low, pci_bound_high; - unsigned int vme_offset_low, vme_offset_high; - - unsigned long long pci_base, pci_bound, vme_offset; - struct tsi148_driver *bridge; - - bridge = image->parent->driver_priv; - - i = image->number; - - ctl = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - - pci_base_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAU); - pci_base_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAL); - pci_bound_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTEAU); - pci_bound_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTEAL); - vme_offset_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTOFU); - vme_offset_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTOFL); - - /* Convert 64-bit variables to 2x 32-bit variables */ - reg_join(pci_base_high, pci_base_low, &pci_base); - reg_join(pci_bound_high, pci_bound_low, &pci_bound); - reg_join(vme_offset_high, vme_offset_low, &vme_offset); - - *vme_base = pci_base + vme_offset; - *size = (unsigned long long)(pci_bound - pci_base) + 0x10000; - - *enabled = 0; - *aspace = 0; - *cycle = 0; - *dwidth = 0; - - if (ctl & TSI148_LCSR_OTAT_EN) - *enabled = 1; - - /* Setup address space */ - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A16) - *aspace |= VME_A16; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A24) - *aspace |= VME_A24; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A32) - *aspace |= VME_A32; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A64) - *aspace |= VME_A64; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_CRCSR) - *aspace |= VME_CRCSR; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER1) - *aspace |= VME_USER1; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER2) - *aspace |= VME_USER2; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER3) - *aspace |= VME_USER3; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER4) - *aspace |= VME_USER4; - - /* Setup 2eSST speeds */ - if ((ctl & TSI148_LCSR_OTAT_2eSSTM_M) == TSI148_LCSR_OTAT_2eSSTM_160) - *cycle |= VME_2eSST160; - if ((ctl & TSI148_LCSR_OTAT_2eSSTM_M) == TSI148_LCSR_OTAT_2eSSTM_267) - *cycle |= VME_2eSST267; - if ((ctl & TSI148_LCSR_OTAT_2eSSTM_M) == TSI148_LCSR_OTAT_2eSSTM_320) - *cycle |= VME_2eSST320; - - /* Setup cycle types */ - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_SCT) - *cycle |= VME_SCT; - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_BLT) - *cycle |= VME_BLT; - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_MBLT) - *cycle |= VME_MBLT; - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_2eVME) - *cycle |= VME_2eVME; - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_2eSST) - *cycle |= VME_2eSST; - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_2eSSTB) - *cycle |= VME_2eSSTB; - - if (ctl & TSI148_LCSR_OTAT_SUP) - *cycle |= VME_SUPER; - else - *cycle |= VME_USER; - - if (ctl & TSI148_LCSR_OTAT_PGM) - *cycle |= VME_PROG; - else - *cycle |= VME_DATA; - - /* Setup data width */ - if ((ctl & TSI148_LCSR_OTAT_DBW_M) == TSI148_LCSR_OTAT_DBW_16) - *dwidth = VME_D16; - if ((ctl & TSI148_LCSR_OTAT_DBW_M) == TSI148_LCSR_OTAT_DBW_32) - *dwidth = VME_D32; - - return 0; -} - -static int tsi148_master_get(struct vme_master_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth) -{ - int retval; - - spin_lock(&image->lock); - - retval = __tsi148_master_get(image, enabled, vme_base, size, aspace, - cycle, dwidth); - - spin_unlock(&image->lock); - - return retval; -} - -static ssize_t tsi148_master_read(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset) -{ - int retval, enabled; - unsigned long long vme_base, size; - u32 aspace, cycle, dwidth; - struct vme_error_handler *handler = NULL; - struct vme_bridge *tsi148_bridge; - void __iomem *addr = image->kern_base + offset; - unsigned int done = 0; - unsigned int count32; - - tsi148_bridge = image->parent; - - spin_lock(&image->lock); - - if (err_chk) { - __tsi148_master_get(image, &enabled, &vme_base, &size, &aspace, - &cycle, &dwidth); - handler = vme_register_error_handler(tsi148_bridge, aspace, - vme_base + offset, count); - if (!handler) { - spin_unlock(&image->lock); - return -ENOMEM; - } - } - - /* The following code handles VME address alignment. We cannot use - * memcpy_xxx here because it may cut data transfers in to 8-bit - * cycles when D16 or D32 cycles are required on the VME bus. - * On the other hand, the bridge itself assures that the maximum data - * cycle configured for the transfer is used and splits it - * automatically for non-aligned addresses, so we don't want the - * overhead of needlessly forcing small transfers for the entire cycle. - */ - if ((uintptr_t)addr & 0x1) { - *(u8 *)buf = ioread8(addr); - done += 1; - if (done == count) - goto out; - } - if ((uintptr_t)(addr + done) & 0x2) { - if ((count - done) < 2) { - *(u8 *)(buf + done) = ioread8(addr + done); - done += 1; - goto out; - } else { - *(u16 *)(buf + done) = ioread16(addr + done); - done += 2; - } - } - - count32 = (count - done) & ~0x3; - while (done < count32) { - *(u32 *)(buf + done) = ioread32(addr + done); - done += 4; - } - - if ((count - done) & 0x2) { - *(u16 *)(buf + done) = ioread16(addr + done); - done += 2; - } - if ((count - done) & 0x1) { - *(u8 *)(buf + done) = ioread8(addr + done); - done += 1; - } - -out: - retval = count; - - if (err_chk) { - if (handler->num_errors) { - dev_err(image->parent->parent, - "First VME read error detected an at address 0x%llx\n", - handler->first_error); - retval = handler->first_error - (vme_base + offset); - } - vme_unregister_error_handler(handler); - } - - spin_unlock(&image->lock); - - return retval; -} - -static ssize_t tsi148_master_write(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset) -{ - int retval = 0, enabled; - unsigned long long vme_base, size; - u32 aspace, cycle, dwidth; - void __iomem *addr = image->kern_base + offset; - unsigned int done = 0; - unsigned int count32; - - struct vme_error_handler *handler = NULL; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - tsi148_bridge = image->parent; - - bridge = tsi148_bridge->driver_priv; - - spin_lock(&image->lock); - - if (err_chk) { - __tsi148_master_get(image, &enabled, &vme_base, &size, &aspace, - &cycle, &dwidth); - handler = vme_register_error_handler(tsi148_bridge, aspace, - vme_base + offset, count); - if (!handler) { - spin_unlock(&image->lock); - return -ENOMEM; - } - } - - /* Here we apply for the same strategy we do in master_read - * function in order to assure the correct cycles. - */ - if ((uintptr_t)addr & 0x1) { - iowrite8(*(u8 *)buf, addr); - done += 1; - if (done == count) - goto out; - } - if ((uintptr_t)(addr + done) & 0x2) { - if ((count - done) < 2) { - iowrite8(*(u8 *)(buf + done), addr + done); - done += 1; - goto out; - } else { - iowrite16(*(u16 *)(buf + done), addr + done); - done += 2; - } - } - - count32 = (count - done) & ~0x3; - while (done < count32) { - iowrite32(*(u32 *)(buf + done), addr + done); - done += 4; - } - - if ((count - done) & 0x2) { - iowrite16(*(u16 *)(buf + done), addr + done); - done += 2; - } - if ((count - done) & 0x1) { - iowrite8(*(u8 *)(buf + done), addr + done); - done += 1; - } - -out: - retval = count; - - /* - * Writes are posted. We need to do a read on the VME bus to flush out - * all of the writes before we check for errors. We can't guarantee - * that reading the data we have just written is safe. It is believed - * that there isn't any read, write re-ordering, so we can read any - * location in VME space, so lets read the Device ID from the tsi148's - * own registers as mapped into CR/CSR space. - * - * We check for saved errors in the written address range/space. - */ - - if (err_chk) { - ioread16(bridge->flush_image->kern_base + 0x7F000); - - if (handler->num_errors) { - dev_warn(tsi148_bridge->parent, - "First VME write error detected an at address 0x%llx\n", - handler->first_error); - retval = handler->first_error - (vme_base + offset); - } - vme_unregister_error_handler(handler); - } - - spin_unlock(&image->lock); - - return retval; -} - -/* - * Perform an RMW cycle on the VME bus. - * - * Requires a previously configured master window, returns final value. - */ -static unsigned int tsi148_master_rmw(struct vme_master_resource *image, unsigned int mask, - unsigned int compare, unsigned int swap, loff_t offset) -{ - unsigned long long pci_addr; - unsigned int pci_addr_high, pci_addr_low; - u32 tmp, result; - int i; - struct tsi148_driver *bridge; - - bridge = image->parent->driver_priv; - - /* Find the PCI address that maps to the desired VME address */ - i = image->number; - - /* Locking as we can only do one of these at a time */ - mutex_lock(&bridge->vme_rmw); - - /* Lock image */ - spin_lock(&image->lock); - - pci_addr_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAU); - pci_addr_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAL); - - reg_join(pci_addr_high, pci_addr_low, &pci_addr); - reg_split(pci_addr + offset, &pci_addr_high, &pci_addr_low); - - /* Configure registers */ - iowrite32be(mask, bridge->base + TSI148_LCSR_RMWEN); - iowrite32be(compare, bridge->base + TSI148_LCSR_RMWC); - iowrite32be(swap, bridge->base + TSI148_LCSR_RMWS); - iowrite32be(pci_addr_high, bridge->base + TSI148_LCSR_RMWAU); - iowrite32be(pci_addr_low, bridge->base + TSI148_LCSR_RMWAL); - - /* Enable RMW */ - tmp = ioread32be(bridge->base + TSI148_LCSR_VMCTRL); - tmp |= TSI148_LCSR_VMCTRL_RMWEN; - iowrite32be(tmp, bridge->base + TSI148_LCSR_VMCTRL); - - /* Kick process off with a read to the required address. */ - result = ioread32be(image->kern_base + offset); - - /* Disable RMW */ - tmp = ioread32be(bridge->base + TSI148_LCSR_VMCTRL); - tmp &= ~TSI148_LCSR_VMCTRL_RMWEN; - iowrite32be(tmp, bridge->base + TSI148_LCSR_VMCTRL); - - spin_unlock(&image->lock); - - mutex_unlock(&bridge->vme_rmw); - - return result; -} - -static int tsi148_dma_set_vme_src_attributes(struct device *dev, __be32 *attr, - u32 aspace, u32 cycle, u32 dwidth) -{ - u32 val; - - val = be32_to_cpu(*attr); - - /* Setup 2eSST speeds */ - switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) { - case VME_2eSST160: - val |= TSI148_LCSR_DSAT_2eSSTM_160; - break; - case VME_2eSST267: - val |= TSI148_LCSR_DSAT_2eSSTM_267; - break; - case VME_2eSST320: - val |= TSI148_LCSR_DSAT_2eSSTM_320; - break; - } - - /* Setup cycle types */ - if (cycle & VME_SCT) - val |= TSI148_LCSR_DSAT_TM_SCT; - - if (cycle & VME_BLT) - val |= TSI148_LCSR_DSAT_TM_BLT; - - if (cycle & VME_MBLT) - val |= TSI148_LCSR_DSAT_TM_MBLT; - - if (cycle & VME_2eVME) - val |= TSI148_LCSR_DSAT_TM_2eVME; - - if (cycle & VME_2eSST) - val |= TSI148_LCSR_DSAT_TM_2eSST; - - if (cycle & VME_2eSSTB) { - dev_err(dev, "Currently not setting Broadcast Select Registers\n"); - val |= TSI148_LCSR_DSAT_TM_2eSSTB; - } - - /* Setup data width */ - switch (dwidth) { - case VME_D16: - val |= TSI148_LCSR_DSAT_DBW_16; - break; - case VME_D32: - val |= TSI148_LCSR_DSAT_DBW_32; - break; - default: - dev_err(dev, "Invalid data width\n"); - return -EINVAL; - } - - /* Setup address space */ - switch (aspace) { - case VME_A16: - val |= TSI148_LCSR_DSAT_AMODE_A16; - break; - case VME_A24: - val |= TSI148_LCSR_DSAT_AMODE_A24; - break; - case VME_A32: - val |= TSI148_LCSR_DSAT_AMODE_A32; - break; - case VME_A64: - val |= TSI148_LCSR_DSAT_AMODE_A64; - break; - case VME_CRCSR: - val |= TSI148_LCSR_DSAT_AMODE_CRCSR; - break; - case VME_USER1: - val |= TSI148_LCSR_DSAT_AMODE_USER1; - break; - case VME_USER2: - val |= TSI148_LCSR_DSAT_AMODE_USER2; - break; - case VME_USER3: - val |= TSI148_LCSR_DSAT_AMODE_USER3; - break; - case VME_USER4: - val |= TSI148_LCSR_DSAT_AMODE_USER4; - break; - default: - dev_err(dev, "Invalid address space\n"); - return -EINVAL; - } - - if (cycle & VME_SUPER) - val |= TSI148_LCSR_DSAT_SUP; - if (cycle & VME_PROG) - val |= TSI148_LCSR_DSAT_PGM; - - *attr = cpu_to_be32(val); - - return 0; -} - -static int tsi148_dma_set_vme_dest_attributes(struct device *dev, __be32 *attr, - u32 aspace, u32 cycle, u32 dwidth) -{ - u32 val; - - val = be32_to_cpu(*attr); - - /* Setup 2eSST speeds */ - switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) { - case VME_2eSST160: - val |= TSI148_LCSR_DDAT_2eSSTM_160; - break; - case VME_2eSST267: - val |= TSI148_LCSR_DDAT_2eSSTM_267; - break; - case VME_2eSST320: - val |= TSI148_LCSR_DDAT_2eSSTM_320; - break; - } - - /* Setup cycle types */ - if (cycle & VME_SCT) - val |= TSI148_LCSR_DDAT_TM_SCT; - - if (cycle & VME_BLT) - val |= TSI148_LCSR_DDAT_TM_BLT; - - if (cycle & VME_MBLT) - val |= TSI148_LCSR_DDAT_TM_MBLT; - - if (cycle & VME_2eVME) - val |= TSI148_LCSR_DDAT_TM_2eVME; - - if (cycle & VME_2eSST) - val |= TSI148_LCSR_DDAT_TM_2eSST; - - if (cycle & VME_2eSSTB) { - dev_err(dev, "Currently not setting Broadcast Select Registers\n"); - val |= TSI148_LCSR_DDAT_TM_2eSSTB; - } - - /* Setup data width */ - switch (dwidth) { - case VME_D16: - val |= TSI148_LCSR_DDAT_DBW_16; - break; - case VME_D32: - val |= TSI148_LCSR_DDAT_DBW_32; - break; - default: - dev_err(dev, "Invalid data width\n"); - return -EINVAL; - } - - /* Setup address space */ - switch (aspace) { - case VME_A16: - val |= TSI148_LCSR_DDAT_AMODE_A16; - break; - case VME_A24: - val |= TSI148_LCSR_DDAT_AMODE_A24; - break; - case VME_A32: - val |= TSI148_LCSR_DDAT_AMODE_A32; - break; - case VME_A64: - val |= TSI148_LCSR_DDAT_AMODE_A64; - break; - case VME_CRCSR: - val |= TSI148_LCSR_DDAT_AMODE_CRCSR; - break; - case VME_USER1: - val |= TSI148_LCSR_DDAT_AMODE_USER1; - break; - case VME_USER2: - val |= TSI148_LCSR_DDAT_AMODE_USER2; - break; - case VME_USER3: - val |= TSI148_LCSR_DDAT_AMODE_USER3; - break; - case VME_USER4: - val |= TSI148_LCSR_DDAT_AMODE_USER4; - break; - default: - dev_err(dev, "Invalid address space\n"); - return -EINVAL; - } - - if (cycle & VME_SUPER) - val |= TSI148_LCSR_DDAT_SUP; - if (cycle & VME_PROG) - val |= TSI148_LCSR_DDAT_PGM; - - *attr = cpu_to_be32(val); - - return 0; -} - -/* - * Add a link list descriptor to the list - * - * Note: DMA engine expects the DMA descriptor to be big endian. - */ -static int tsi148_dma_list_add(struct vme_dma_list *list, struct vme_dma_attr *src, - struct vme_dma_attr *dest, size_t count) -{ - struct tsi148_dma_entry *entry, *prev; - u32 address_high, address_low, val; - struct vme_dma_pattern *pattern_attr; - struct vme_dma_pci *pci_attr; - struct vme_dma_vme *vme_attr; - int retval = 0; - struct vme_bridge *tsi148_bridge; - - tsi148_bridge = list->parent->parent; - - /* Descriptor must be aligned on 64-bit boundaries */ - entry = kmalloc_obj(*entry); - if (!entry) { - retval = -ENOMEM; - goto err_mem; - } - - /* Test descriptor alignment */ - if ((unsigned long)&entry->descriptor & 0x7) { - dev_err(tsi148_bridge->parent, "Descriptor not aligned to 8 byte boundary as required: %p\n", - &entry->descriptor); - retval = -EINVAL; - goto err_align; - } - - /* Given we are going to fill out the structure, we probably don't - * need to zero it, but better safe than sorry for now. - */ - memset(&entry->descriptor, 0, sizeof(entry->descriptor)); - - /* Fill out source part */ - switch (src->type) { - case VME_DMA_PATTERN: - pattern_attr = src->private; - - entry->descriptor.dsal = cpu_to_be32(pattern_attr->pattern); - - val = TSI148_LCSR_DSAT_TYP_PAT; - - /* Default behaviour is 32 bit pattern */ - if (pattern_attr->type & VME_DMA_PATTERN_BYTE) - val |= TSI148_LCSR_DSAT_PSZ; - - /* It seems that the default behaviour is to increment */ - if ((pattern_attr->type & VME_DMA_PATTERN_INCREMENT) == 0) - val |= TSI148_LCSR_DSAT_NIN; - entry->descriptor.dsat = cpu_to_be32(val); - break; - case VME_DMA_PCI: - pci_attr = src->private; - - reg_split((unsigned long long)pci_attr->address, &address_high, &address_low); - entry->descriptor.dsau = cpu_to_be32(address_high); - entry->descriptor.dsal = cpu_to_be32(address_low); - entry->descriptor.dsat = cpu_to_be32(TSI148_LCSR_DSAT_TYP_PCI); - break; - case VME_DMA_VME: - vme_attr = src->private; - - reg_split((unsigned long long)vme_attr->address, &address_high, &address_low); - entry->descriptor.dsau = cpu_to_be32(address_high); - entry->descriptor.dsal = cpu_to_be32(address_low); - entry->descriptor.dsat = cpu_to_be32(TSI148_LCSR_DSAT_TYP_VME); - - retval = tsi148_dma_set_vme_src_attributes(tsi148_bridge->parent, - &entry->descriptor.dsat, - vme_attr->aspace, - vme_attr->cycle, - vme_attr->dwidth); - if (retval < 0) - goto err_source; - break; - default: - dev_err(tsi148_bridge->parent, "Invalid source type\n"); - retval = -EINVAL; - goto err_source; - } - - /* Assume last link - this will be over-written by adding another */ - entry->descriptor.dnlau = cpu_to_be32(0); - entry->descriptor.dnlal = cpu_to_be32(TSI148_LCSR_DNLAL_LLA); - - /* Fill out destination part */ - switch (dest->type) { - case VME_DMA_PCI: - pci_attr = dest->private; - - reg_split((unsigned long long)pci_attr->address, &address_high, - &address_low); - entry->descriptor.ddau = cpu_to_be32(address_high); - entry->descriptor.ddal = cpu_to_be32(address_low); - entry->descriptor.ddat = cpu_to_be32(TSI148_LCSR_DDAT_TYP_PCI); - break; - case VME_DMA_VME: - vme_attr = dest->private; - - reg_split((unsigned long long)vme_attr->address, &address_high, - &address_low); - entry->descriptor.ddau = cpu_to_be32(address_high); - entry->descriptor.ddal = cpu_to_be32(address_low); - entry->descriptor.ddat = cpu_to_be32(TSI148_LCSR_DDAT_TYP_VME); - - retval = tsi148_dma_set_vme_dest_attributes(tsi148_bridge->parent, - &entry->descriptor.ddat, - vme_attr->aspace, - vme_attr->cycle, - vme_attr->dwidth); - if (retval < 0) - goto err_dest; - break; - default: - dev_err(tsi148_bridge->parent, "Invalid destination type\n"); - retval = -EINVAL; - goto err_dest; - } - - /* Fill out count */ - entry->descriptor.dcnt = cpu_to_be32((u32)count); - - /* Add to list */ - list_add_tail(&entry->list, &list->entries); - - entry->dma_handle = dma_map_single(tsi148_bridge->parent, - &entry->descriptor, - sizeof(entry->descriptor), - DMA_TO_DEVICE); - if (dma_mapping_error(tsi148_bridge->parent, entry->dma_handle)) { - dev_err(tsi148_bridge->parent, "DMA mapping error\n"); - retval = -EINVAL; - goto err_dma; - } - - /* Fill out previous descriptors "Next Address" */ - if (entry->list.prev != &list->entries) { - reg_split((unsigned long long)entry->dma_handle, &address_high, - &address_low); - prev = list_entry(entry->list.prev, struct tsi148_dma_entry, - list); - prev->descriptor.dnlau = cpu_to_be32(address_high); - prev->descriptor.dnlal = cpu_to_be32(address_low); - } - - return 0; - -err_dma: - list_del(&entry->list); -err_dest: -err_source: -err_align: - kfree(entry); -err_mem: - return retval; -} - -/* - * Check to see if the provided DMA channel is busy. - */ -static int tsi148_dma_busy(struct vme_bridge *tsi148_bridge, int channel) -{ - u32 tmp; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - tmp = ioread32be(bridge->base + TSI148_LCSR_DMA[channel] + - TSI148_LCSR_OFFSET_DSTA); - - if (tmp & TSI148_LCSR_DSTA_BSY) - return 0; - else - return 1; -} - -/* - * Execute a previously generated link list - * - * XXX Need to provide control register configuration. - */ -static int tsi148_dma_list_exec(struct vme_dma_list *list) -{ - struct vme_dma_resource *ctrlr; - int channel, retval; - struct tsi148_dma_entry *entry; - u32 bus_addr_high, bus_addr_low; - u32 val, dctlreg = 0; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - ctrlr = list->parent; - - tsi148_bridge = ctrlr->parent; - - bridge = tsi148_bridge->driver_priv; - - mutex_lock(&ctrlr->mtx); - - channel = ctrlr->number; - - if (!list_empty(&ctrlr->running)) { - /* - * XXX We have an active DMA transfer and currently haven't - * sorted out the mechanism for "pending" DMA transfers. - * Return busy. - */ - /* Need to add to pending here */ - mutex_unlock(&ctrlr->mtx); - return -EBUSY; - } - - list_add(&list->list, &ctrlr->running); - - /* Get first bus address and write into registers */ - entry = list_first_entry(&list->entries, struct tsi148_dma_entry, - list); - - mutex_unlock(&ctrlr->mtx); - - reg_split(entry->dma_handle, &bus_addr_high, &bus_addr_low); - - iowrite32be(bus_addr_high, bridge->base + - TSI148_LCSR_DMA[channel] + TSI148_LCSR_OFFSET_DNLAU); - iowrite32be(bus_addr_low, bridge->base + - TSI148_LCSR_DMA[channel] + TSI148_LCSR_OFFSET_DNLAL); - - dctlreg = ioread32be(bridge->base + TSI148_LCSR_DMA[channel] + - TSI148_LCSR_OFFSET_DCTL); - - /* Start the operation */ - iowrite32be(dctlreg | TSI148_LCSR_DCTL_DGO, bridge->base + - TSI148_LCSR_DMA[channel] + TSI148_LCSR_OFFSET_DCTL); - - retval = wait_event_interruptible(bridge->dma_queue[channel], - tsi148_dma_busy(ctrlr->parent, channel)); - - if (retval) { - iowrite32be(dctlreg | TSI148_LCSR_DCTL_ABT, bridge->base + - TSI148_LCSR_DMA[channel] + TSI148_LCSR_OFFSET_DCTL); - /* Wait for the operation to abort */ - wait_event(bridge->dma_queue[channel], - tsi148_dma_busy(ctrlr->parent, channel)); - retval = -EINTR; - goto exit; - } - - /* - * Read status register, this register is valid until we kick off a - * new transfer. - */ - val = ioread32be(bridge->base + TSI148_LCSR_DMA[channel] + - TSI148_LCSR_OFFSET_DSTA); - - if (val & TSI148_LCSR_DSTA_VBE) { - dev_err(tsi148_bridge->parent, "DMA Error. DSTA=%08X\n", val); - retval = -EIO; - } - -exit: - /* Remove list from running list */ - mutex_lock(&ctrlr->mtx); - list_del(&list->list); - mutex_unlock(&ctrlr->mtx); - - return retval; -} - -/* - * Clean up a previously generated link list - * - * We have a separate function, don't assume that the chain can't be reused. - */ -static int tsi148_dma_list_empty(struct vme_dma_list *list) -{ - struct list_head *pos, *temp; - struct tsi148_dma_entry *entry; - - struct vme_bridge *tsi148_bridge = list->parent->parent; - - /* detach and free each entry */ - list_for_each_safe(pos, temp, &list->entries) { - list_del(pos); - entry = list_entry(pos, struct tsi148_dma_entry, list); - - dma_unmap_single(tsi148_bridge->parent, entry->dma_handle, - sizeof(struct tsi148_dma_descriptor), DMA_TO_DEVICE); - kfree(entry); - } - - return 0; -} - -/* - * All 4 location monitors reside at the same base - this is therefore a - * system wide configuration. - * - * This does not enable the LM monitor - that should be done when the first - * callback is attached and disabled when the last callback is removed. - */ -static int tsi148_lm_set(struct vme_lm_resource *lm, unsigned long long lm_base, - u32 aspace, u32 cycle) -{ - u32 lm_base_high, lm_base_low, lm_ctl = 0; - int i; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - tsi148_bridge = lm->parent; - - bridge = tsi148_bridge->driver_priv; - - mutex_lock(&lm->mtx); - - /* If we already have a callback attached, we can't move it! */ - for (i = 0; i < lm->monitors; i++) { - if (bridge->lm_callback[i]) { - mutex_unlock(&lm->mtx); - dev_err(tsi148_bridge->parent, "Location monitor callback attached, can't reset\n"); - return -EBUSY; - } - } - - switch (aspace) { - case VME_A16: - lm_ctl |= TSI148_LCSR_LMAT_AS_A16; - break; - case VME_A24: - lm_ctl |= TSI148_LCSR_LMAT_AS_A24; - break; - case VME_A32: - lm_ctl |= TSI148_LCSR_LMAT_AS_A32; - break; - case VME_A64: - lm_ctl |= TSI148_LCSR_LMAT_AS_A64; - break; - default: - mutex_unlock(&lm->mtx); - dev_err(tsi148_bridge->parent, "Invalid address space\n"); - return -EINVAL; - } - - if (cycle & VME_SUPER) - lm_ctl |= TSI148_LCSR_LMAT_SUPR; - if (cycle & VME_USER) - lm_ctl |= TSI148_LCSR_LMAT_NPRIV; - if (cycle & VME_PROG) - lm_ctl |= TSI148_LCSR_LMAT_PGM; - if (cycle & VME_DATA) - lm_ctl |= TSI148_LCSR_LMAT_DATA; - - reg_split(lm_base, &lm_base_high, &lm_base_low); - - iowrite32be(lm_base_high, bridge->base + TSI148_LCSR_LMBAU); - iowrite32be(lm_base_low, bridge->base + TSI148_LCSR_LMBAL); - iowrite32be(lm_ctl, bridge->base + TSI148_LCSR_LMAT); - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* Get configuration of the callback monitor and return whether it is enabled - * or disabled. - */ -static int tsi148_lm_get(struct vme_lm_resource *lm, - unsigned long long *lm_base, u32 *aspace, u32 *cycle) -{ - u32 lm_base_high, lm_base_low, lm_ctl, enabled = 0; - struct tsi148_driver *bridge; - - bridge = lm->parent->driver_priv; - - mutex_lock(&lm->mtx); - - lm_base_high = ioread32be(bridge->base + TSI148_LCSR_LMBAU); - lm_base_low = ioread32be(bridge->base + TSI148_LCSR_LMBAL); - lm_ctl = ioread32be(bridge->base + TSI148_LCSR_LMAT); - - reg_join(lm_base_high, lm_base_low, lm_base); - - if (lm_ctl & TSI148_LCSR_LMAT_EN) - enabled = 1; - - if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A16) - *aspace |= VME_A16; - - if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A24) - *aspace |= VME_A24; - - if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A32) - *aspace |= VME_A32; - - if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A64) - *aspace |= VME_A64; - - if (lm_ctl & TSI148_LCSR_LMAT_SUPR) - *cycle |= VME_SUPER; - if (lm_ctl & TSI148_LCSR_LMAT_NPRIV) - *cycle |= VME_USER; - if (lm_ctl & TSI148_LCSR_LMAT_PGM) - *cycle |= VME_PROG; - if (lm_ctl & TSI148_LCSR_LMAT_DATA) - *cycle |= VME_DATA; - - mutex_unlock(&lm->mtx); - - return enabled; -} - -/* - * Attach a callback to a specific location monitor. - * - * Callback will be passed the monitor triggered. - */ -static int tsi148_lm_attach(struct vme_lm_resource *lm, int monitor, - void (*callback)(void *), void *data) -{ - u32 lm_ctl, tmp; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - tsi148_bridge = lm->parent; - - bridge = tsi148_bridge->driver_priv; - - mutex_lock(&lm->mtx); - - /* Ensure that the location monitor is configured - need PGM or DATA */ - lm_ctl = ioread32be(bridge->base + TSI148_LCSR_LMAT); - if ((lm_ctl & (TSI148_LCSR_LMAT_PGM | TSI148_LCSR_LMAT_DATA)) == 0) { - mutex_unlock(&lm->mtx); - dev_err(tsi148_bridge->parent, "Location monitor not properly configured\n"); - return -EINVAL; - } - - /* Check that a callback isn't already attached */ - if (bridge->lm_callback[monitor]) { - mutex_unlock(&lm->mtx); - dev_err(tsi148_bridge->parent, "Existing callback attached\n"); - return -EBUSY; - } - - /* Attach callback */ - bridge->lm_callback[monitor] = callback; - bridge->lm_data[monitor] = data; - - /* Enable Location Monitor interrupt */ - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEN); - tmp |= TSI148_LCSR_INTEN_LMEN[monitor]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN); - - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO); - tmp |= TSI148_LCSR_INTEO_LMEO[monitor]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO); - - /* Ensure that global Location Monitor Enable set */ - if ((lm_ctl & TSI148_LCSR_LMAT_EN) == 0) { - lm_ctl |= TSI148_LCSR_LMAT_EN; - iowrite32be(lm_ctl, bridge->base + TSI148_LCSR_LMAT); - } - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* - * Detach a callback function forn a specific location monitor. - */ -static int tsi148_lm_detach(struct vme_lm_resource *lm, int monitor) -{ - u32 lm_en, tmp; - struct tsi148_driver *bridge; - - bridge = lm->parent->driver_priv; - - mutex_lock(&lm->mtx); - - /* Disable Location Monitor and ensure previous interrupts are clear */ - lm_en = ioread32be(bridge->base + TSI148_LCSR_INTEN); - lm_en &= ~TSI148_LCSR_INTEN_LMEN[monitor]; - iowrite32be(lm_en, bridge->base + TSI148_LCSR_INTEN); - - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO); - tmp &= ~TSI148_LCSR_INTEO_LMEO[monitor]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO); - - iowrite32be(TSI148_LCSR_INTC_LMC[monitor], - bridge->base + TSI148_LCSR_INTC); - - /* Detach callback */ - bridge->lm_callback[monitor] = NULL; - bridge->lm_data[monitor] = NULL; - - /* If all location monitors disabled, disable global Location Monitor */ - if ((lm_en & (TSI148_LCSR_INTS_LM0S | TSI148_LCSR_INTS_LM1S | - TSI148_LCSR_INTS_LM2S | TSI148_LCSR_INTS_LM3S)) == 0) { - tmp = ioread32be(bridge->base + TSI148_LCSR_LMAT); - tmp &= ~TSI148_LCSR_LMAT_EN; - iowrite32be(tmp, bridge->base + TSI148_LCSR_LMAT); - } - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* - * Determine Geographical Addressing - */ -static int tsi148_slot_get(struct vme_bridge *tsi148_bridge) -{ - u32 slot = 0; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - if (!geoid) { - slot = ioread32be(bridge->base + TSI148_LCSR_VSTAT); - slot = slot & TSI148_LCSR_VSTAT_GA_M; - } else { - slot = geoid; - } - - return (int)slot; -} - -static void *tsi148_alloc_consistent(struct device *parent, size_t size, - dma_addr_t *dma) -{ - struct pci_dev *pdev; - - /* Find pci_dev container of dev */ - pdev = to_pci_dev(parent); - - return dma_alloc_coherent(&pdev->dev, size, dma, GFP_KERNEL); -} - -static void tsi148_free_consistent(struct device *parent, size_t size, - void *vaddr, dma_addr_t dma) -{ - struct pci_dev *pdev; - - /* Find pci_dev container of dev */ - pdev = to_pci_dev(parent); - - dma_free_coherent(&pdev->dev, size, vaddr, dma); -} - -/* - * Configure CR/CSR space - * - * Access to the CR/CSR can be configured at power-up. The location of the - * CR/CSR registers in the CR/CSR address space is determined by the boards - * Auto-ID or Geographic address. This function ensures that the window is - * enabled at an offset consistent with the boards geopgraphic address. - * - * Each board has a 512kB window, with the highest 4kB being used for the - * boards registers, this means there is a fix length 508kB window which must - * be mapped onto PCI memory. - */ -static int tsi148_crcsr_init(struct vme_bridge *tsi148_bridge, - struct pci_dev *pdev) -{ - u32 cbar, crat, vstat; - u32 crcsr_bus_high, crcsr_bus_low; - int retval; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - /* Allocate mem for CR/CSR image */ - bridge->crcsr_kernel = dma_alloc_coherent(&pdev->dev, - VME_CRCSR_BUF_SIZE, - &bridge->crcsr_bus, GFP_KERNEL); - if (!bridge->crcsr_kernel) { - dev_err(tsi148_bridge->parent, "Failed to allocate memory for CR/CSR image\n"); - return -ENOMEM; - } - - reg_split(bridge->crcsr_bus, &crcsr_bus_high, &crcsr_bus_low); - - iowrite32be(crcsr_bus_high, bridge->base + TSI148_LCSR_CROU); - iowrite32be(crcsr_bus_low, bridge->base + TSI148_LCSR_CROL); - - /* Ensure that the CR/CSR is configured at the correct offset */ - cbar = ioread32be(bridge->base + TSI148_CBAR); - cbar = (cbar & TSI148_CRCSR_CBAR_M) >> 3; - - vstat = tsi148_slot_get(tsi148_bridge); - - if (cbar != vstat) { - cbar = vstat; - dev_info(tsi148_bridge->parent, "Setting CR/CSR offset\n"); - iowrite32be(cbar << 3, bridge->base + TSI148_CBAR); - } - dev_info(tsi148_bridge->parent, "CR/CSR Offset: %d\n", cbar); - - crat = ioread32be(bridge->base + TSI148_LCSR_CRAT); - if (crat & TSI148_LCSR_CRAT_EN) { - dev_info(tsi148_bridge->parent, "CR/CSR already enabled\n"); - } else { - dev_info(tsi148_bridge->parent, "Enabling CR/CSR space\n"); - iowrite32be(crat | TSI148_LCSR_CRAT_EN, bridge->base + TSI148_LCSR_CRAT); - } - - /* If we want flushed, error-checked writes, set up a window - * over the CR/CSR registers. We read from here to safely flush - * through VME writes. - */ - if (err_chk) { - retval = tsi148_master_set(bridge->flush_image, 1, (vstat * 0x80000), - 0x80000, VME_CRCSR, VME_SCT, VME_D16); - if (retval) - dev_err(tsi148_bridge->parent, "Configuring flush image failed\n"); - } - - return 0; -} - -static void tsi148_crcsr_exit(struct vme_bridge *tsi148_bridge, - struct pci_dev *pdev) -{ - u32 crat; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - /* Turn off CR/CSR space */ - crat = ioread32be(bridge->base + TSI148_LCSR_CRAT); - iowrite32be(crat & ~TSI148_LCSR_CRAT_EN, - bridge->base + TSI148_LCSR_CRAT); - - /* Free image */ - iowrite32be(0, bridge->base + TSI148_LCSR_CROU); - iowrite32be(0, bridge->base + TSI148_LCSR_CROL); - - dma_free_coherent(&pdev->dev, VME_CRCSR_BUF_SIZE, - bridge->crcsr_kernel, bridge->crcsr_bus); -} - -static int tsi148_probe(struct pci_dev *pdev, const struct pci_device_id *id) -{ - int retval, i, master_num; - u32 data; - struct list_head *pos = NULL, *n; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *tsi148_device; - struct vme_master_resource *master_image; - struct vme_slave_resource *slave_image; - struct vme_dma_resource *dma_ctrlr; - struct vme_lm_resource *lm; - - if (geoid >= VME_MAX_SLOTS) { - dev_err(&pdev->dev, "VME geographical address must be between 0 and %d (exclusive), but got %d\n", - VME_MAX_SLOTS, geoid); - return -EINVAL; - } - - /* If we want to support more than one of each bridge, we need to - * dynamically generate this so we get one per device - */ - tsi148_bridge = kzalloc_obj(*tsi148_bridge); - if (!tsi148_bridge) { - retval = -ENOMEM; - goto err_struct; - } - vme_init_bridge(tsi148_bridge); - - tsi148_device = kzalloc_obj(*tsi148_device); - if (!tsi148_device) { - retval = -ENOMEM; - goto err_driver; - } - - tsi148_bridge->driver_priv = tsi148_device; - - /* Enable the device */ - retval = pci_enable_device(pdev); - if (retval) { - dev_err(&pdev->dev, "Unable to enable device\n"); - goto err_enable; - } - - /* Map Registers */ - retval = pci_request_regions(pdev, driver_name); - if (retval) { - dev_err(&pdev->dev, "Unable to reserve resources\n"); - goto err_resource; - } - - /* map registers in BAR 0 */ - tsi148_device->base = ioremap(pci_resource_start(pdev, 0), - 4096); - if (!tsi148_device->base) { - dev_err(&pdev->dev, "Unable to remap CRG region\n"); - retval = -EIO; - goto err_remap; - } - - /* Check to see if the mapping worked out */ - data = ioread32(tsi148_device->base + TSI148_PCFS_ID) & 0x0000FFFF; - if (data != PCI_VENDOR_ID_TUNDRA) { - dev_err(&pdev->dev, "CRG region check failed\n"); - retval = -EIO; - goto err_test; - } - - /* Initialize wait queues & mutual exclusion flags */ - init_waitqueue_head(&tsi148_device->dma_queue[0]); - init_waitqueue_head(&tsi148_device->dma_queue[1]); - init_waitqueue_head(&tsi148_device->iack_queue); - mutex_init(&tsi148_device->vme_int); - mutex_init(&tsi148_device->vme_rmw); - - tsi148_bridge->parent = &pdev->dev; - strscpy(tsi148_bridge->name, driver_name, VMENAMSIZ); - - /* Setup IRQ */ - retval = tsi148_irq_init(tsi148_bridge); - if (retval != 0) { - dev_err(&pdev->dev, "Chip Initialization failed.\n"); - goto err_irq; - } - - /* If we are going to flush writes, we need to read from the VME bus. - * We need to do this safely, thus we read the devices own CR/CSR - * register. To do this we must set up a window in CR/CSR space and - * hence have one less master window resource available. - */ - master_num = TSI148_MAX_MASTER; - if (err_chk) { - master_num--; - - tsi148_device->flush_image = kmalloc_obj(*tsi148_device->flush_image); - if (!tsi148_device->flush_image) { - retval = -ENOMEM; - goto err_master; - } - tsi148_device->flush_image->parent = tsi148_bridge; - spin_lock_init(&tsi148_device->flush_image->lock); - tsi148_device->flush_image->locked = 1; - tsi148_device->flush_image->number = master_num; - memset(&tsi148_device->flush_image->bus_resource, 0, - sizeof(tsi148_device->flush_image->bus_resource)); - tsi148_device->flush_image->kern_base = NULL; - } - - /* Add master windows to list */ - for (i = 0; i < master_num; i++) { - master_image = kmalloc_obj(*master_image); - if (!master_image) { - retval = -ENOMEM; - goto err_master; - } - master_image->parent = tsi148_bridge; - spin_lock_init(&master_image->lock); - master_image->locked = 0; - master_image->number = i; - master_image->address_attr = VME_A16 | VME_A24 | VME_A32 | - VME_A64 | VME_CRCSR | VME_USER1 | VME_USER2 | - VME_USER3 | VME_USER4; - master_image->cycle_attr = VME_SCT | VME_BLT | VME_MBLT | - VME_2eVME | VME_2eSST | VME_2eSSTB | VME_2eSST160 | - VME_2eSST267 | VME_2eSST320 | VME_SUPER | VME_USER | - VME_PROG | VME_DATA; - master_image->width_attr = VME_D16 | VME_D32; - memset(&master_image->bus_resource, 0, - sizeof(master_image->bus_resource)); - master_image->kern_base = NULL; - list_add_tail(&master_image->list, - &tsi148_bridge->master_resources); - } - - /* Add slave windows to list */ - for (i = 0; i < TSI148_MAX_SLAVE; i++) { - slave_image = kmalloc_obj(*slave_image); - if (!slave_image) { - retval = -ENOMEM; - goto err_slave; - } - slave_image->parent = tsi148_bridge; - mutex_init(&slave_image->mtx); - slave_image->locked = 0; - slave_image->number = i; - slave_image->address_attr = VME_A16 | VME_A24 | VME_A32 | - VME_A64; - slave_image->cycle_attr = VME_SCT | VME_BLT | VME_MBLT | - VME_2eVME | VME_2eSST | VME_2eSSTB | VME_2eSST160 | - VME_2eSST267 | VME_2eSST320 | VME_SUPER | VME_USER | - VME_PROG | VME_DATA; - list_add_tail(&slave_image->list, - &tsi148_bridge->slave_resources); - } - - /* Add dma engines to list */ - for (i = 0; i < TSI148_MAX_DMA; i++) { - dma_ctrlr = kmalloc_obj(*dma_ctrlr); - if (!dma_ctrlr) { - retval = -ENOMEM; - goto err_dma; - } - dma_ctrlr->parent = tsi148_bridge; - mutex_init(&dma_ctrlr->mtx); - dma_ctrlr->locked = 0; - dma_ctrlr->number = i; - dma_ctrlr->route_attr = VME_DMA_VME_TO_MEM | - VME_DMA_MEM_TO_VME | VME_DMA_VME_TO_VME | - VME_DMA_MEM_TO_MEM | VME_DMA_PATTERN_TO_VME | - VME_DMA_PATTERN_TO_MEM; - INIT_LIST_HEAD(&dma_ctrlr->pending); - INIT_LIST_HEAD(&dma_ctrlr->running); - list_add_tail(&dma_ctrlr->list, - &tsi148_bridge->dma_resources); - } - - /* Add location monitor to list */ - lm = kmalloc_obj(*lm); - if (!lm) { - retval = -ENOMEM; - goto err_lm; - } - lm->parent = tsi148_bridge; - mutex_init(&lm->mtx); - lm->locked = 0; - lm->number = 1; - lm->monitors = 4; - list_add_tail(&lm->list, &tsi148_bridge->lm_resources); - - tsi148_bridge->slave_get = tsi148_slave_get; - tsi148_bridge->slave_set = tsi148_slave_set; - tsi148_bridge->master_get = tsi148_master_get; - tsi148_bridge->master_set = tsi148_master_set; - tsi148_bridge->master_read = tsi148_master_read; - tsi148_bridge->master_write = tsi148_master_write; - tsi148_bridge->master_rmw = tsi148_master_rmw; - tsi148_bridge->dma_list_add = tsi148_dma_list_add; - tsi148_bridge->dma_list_exec = tsi148_dma_list_exec; - tsi148_bridge->dma_list_empty = tsi148_dma_list_empty; - tsi148_bridge->irq_set = tsi148_irq_set; - tsi148_bridge->irq_generate = tsi148_irq_generate; - tsi148_bridge->lm_set = tsi148_lm_set; - tsi148_bridge->lm_get = tsi148_lm_get; - tsi148_bridge->lm_attach = tsi148_lm_attach; - tsi148_bridge->lm_detach = tsi148_lm_detach; - tsi148_bridge->slot_get = tsi148_slot_get; - tsi148_bridge->alloc_consistent = tsi148_alloc_consistent; - tsi148_bridge->free_consistent = tsi148_free_consistent; - - data = ioread32be(tsi148_device->base + TSI148_LCSR_VSTAT); - dev_info(&pdev->dev, "Board is%s the VME system controller\n", - (data & TSI148_LCSR_VSTAT_SCONS) ? "" : " not"); - if (!geoid) - dev_info(&pdev->dev, "VME geographical address is %d\n", - data & TSI148_LCSR_VSTAT_GA_M); - else - dev_info(&pdev->dev, "VME geographical address is set to %d\n", - geoid); - - dev_info(&pdev->dev, "VME Write and flush and error check is %s\n", - str_enabled_disabled(err_chk)); - - retval = tsi148_crcsr_init(tsi148_bridge, pdev); - if (retval) { - dev_err(&pdev->dev, "CR/CSR configuration failed.\n"); - goto err_crcsr; - } - - retval = vme_register_bridge(tsi148_bridge); - if (retval != 0) { - dev_err(&pdev->dev, "Chip Registration failed.\n"); - goto err_reg; - } - - pci_set_drvdata(pdev, tsi148_bridge); - - /* Clear VME bus "board fail", and "power-up reset" lines */ - data = ioread32be(tsi148_device->base + TSI148_LCSR_VSTAT); - data &= ~TSI148_LCSR_VSTAT_BRDFL; - data |= TSI148_LCSR_VSTAT_CPURST; - iowrite32be(data, tsi148_device->base + TSI148_LCSR_VSTAT); - - return 0; - -err_reg: - tsi148_crcsr_exit(tsi148_bridge, pdev); -err_crcsr: -err_lm: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &tsi148_bridge->lm_resources) { - lm = list_entry(pos, struct vme_lm_resource, list); - list_del(pos); - kfree(lm); - } -err_dma: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &tsi148_bridge->dma_resources) { - dma_ctrlr = list_entry(pos, struct vme_dma_resource, list); - list_del(pos); - kfree(dma_ctrlr); - } -err_slave: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &tsi148_bridge->slave_resources) { - slave_image = list_entry(pos, struct vme_slave_resource, list); - list_del(pos); - kfree(slave_image); - } -err_master: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &tsi148_bridge->master_resources) { - master_image = list_entry(pos, struct vme_master_resource, list); - list_del(pos); - kfree(master_image); - } - - tsi148_irq_exit(tsi148_bridge, pdev); -err_irq: -err_test: - iounmap(tsi148_device->base); -err_remap: - pci_release_regions(pdev); -err_resource: - pci_disable_device(pdev); -err_enable: - kfree(tsi148_device); -err_driver: - kfree(tsi148_bridge); -err_struct: - return retval; -} - -static void tsi148_remove(struct pci_dev *pdev) -{ - struct list_head *pos = NULL; - struct list_head *tmplist; - struct vme_lm_resource *lm; - struct vme_master_resource *master_image; - struct vme_slave_resource *slave_image; - struct vme_dma_resource *dma_ctrlr; - int i; - struct tsi148_driver *bridge; - struct vme_bridge *tsi148_bridge = pci_get_drvdata(pdev); - - bridge = tsi148_bridge->driver_priv; - - dev_dbg(&pdev->dev, "Driver is being unloaded.\n"); - - /* - * Shutdown all inbound and outbound windows. - */ - for (i = 0; i < 8; i++) { - iowrite32be(0, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - iowrite32be(0, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - } - - /* - * Shutdown Location monitor. - */ - iowrite32be(0, bridge->base + TSI148_LCSR_LMAT); - - /* - * Shutdown CRG map. - */ - iowrite32be(0, bridge->base + TSI148_LCSR_CSRAT); - - /* - * Clear error status. - */ - iowrite32be(0xFFFFFFFF, bridge->base + TSI148_LCSR_EDPAT); - iowrite32be(0xFFFFFFFF, bridge->base + TSI148_LCSR_VEAT); - iowrite32be(0x07000700, bridge->base + TSI148_LCSR_PSTAT); - - /* - * Remove VIRQ interrupt (if any) - */ - if (ioread32be(bridge->base + TSI148_LCSR_VICR) & 0x800) - iowrite32be(0x8000, bridge->base + TSI148_LCSR_VICR); - - /* - * Map all Interrupts to PCI INTA - */ - iowrite32be(0x0, bridge->base + TSI148_LCSR_INTM1); - iowrite32be(0x0, bridge->base + TSI148_LCSR_INTM2); - - tsi148_irq_exit(tsi148_bridge, pdev); - - vme_unregister_bridge(tsi148_bridge); - - tsi148_crcsr_exit(tsi148_bridge, pdev); - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &tsi148_bridge->lm_resources) { - lm = list_entry(pos, struct vme_lm_resource, list); - list_del(pos); - kfree(lm); - } - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &tsi148_bridge->dma_resources) { - dma_ctrlr = list_entry(pos, struct vme_dma_resource, list); - list_del(pos); - kfree(dma_ctrlr); - } - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &tsi148_bridge->slave_resources) { - slave_image = list_entry(pos, struct vme_slave_resource, list); - list_del(pos); - kfree(slave_image); - } - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &tsi148_bridge->master_resources) { - master_image = list_entry(pos, struct vme_master_resource, list); - list_del(pos); - kfree(master_image); - } - - iounmap(bridge->base); - - pci_release_regions(pdev); - - pci_disable_device(pdev); - - kfree(tsi148_bridge->driver_priv); - - kfree(tsi148_bridge); -} - -module_pci_driver(tsi148_driver); - -MODULE_PARM_DESC(err_chk, "Check for VME errors on reads and writes"); -module_param(err_chk, bool, 0); - -MODULE_PARM_DESC(geoid, "Override geographical addressing"); -module_param(geoid, uint, 0); - -MODULE_DESCRIPTION("VME driver for the Tundra Tempe VME bridge"); -MODULE_LICENSE("GPL"); diff --git a/drivers/staging/vme_user/vme_tsi148.h b/drivers/staging/vme_user/vme_tsi148.h deleted file mode 100644 index f73ac92320bbf2..00000000000000 --- a/drivers/staging/vme_user/vme_tsi148.h +++ /dev/null @@ -1,1392 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-or-later */ -/* - * tsi148.h - * - * Support for the Tundra TSI148 VME Bridge chip - * - * Author: Tom Armistead - * Updated and maintained by Ajit Prem - * Copyright 2004 Motorola Inc. - */ - -#ifndef TSI148_H -#define TSI148_H - -#ifndef PCI_VENDOR_ID_TUNDRA -#define PCI_VENDOR_ID_TUNDRA 0x10e3 -#endif - -#ifndef PCI_DEVICE_ID_TUNDRA_TSI148 -#define PCI_DEVICE_ID_TUNDRA_TSI148 0x148 -#endif - -/* - * Define the number of each that the Tsi148 supports. - */ -#define TSI148_MAX_MASTER 8 /* Max Master Windows */ -#define TSI148_MAX_SLAVE 8 /* Max Slave Windows */ -#define TSI148_MAX_DMA 2 /* Max DMA Controllers */ -#define TSI148_MAX_MAILBOX 4 /* Max Mail Box registers */ -#define TSI148_MAX_SEMAPHORE 8 /* Max Semaphores */ - -/* Structure used to hold driver specific information */ -struct tsi148_driver { - void __iomem *base; /* Base Address of device registers */ - wait_queue_head_t dma_queue[2]; - wait_queue_head_t iack_queue; - void (*lm_callback[4])(void *); /* Called in interrupt handler */ - void *lm_data[4]; - void *crcsr_kernel; - dma_addr_t crcsr_bus; - struct vme_master_resource *flush_image; - struct mutex vme_rmw; /* Only one RMW cycle at a time */ - struct mutex vme_int; /* - * Only one VME interrupt can be - * generated at a time, provide locking - */ -}; - -/* - * Layout of a DMAC Linked-List Descriptor - * - * Note: This structure is accessed via the chip and therefore must be - * correctly laid out - It must also be aligned on 64-bit boundaries. - */ -struct tsi148_dma_descriptor { - __be32 dsau; /* Source Address */ - __be32 dsal; - __be32 ddau; /* Destination Address */ - __be32 ddal; - __be32 dsat; /* Source attributes */ - __be32 ddat; /* Destination attributes */ - __be32 dnlau; /* Next link address */ - __be32 dnlal; - __be32 dcnt; /* Byte count */ - __be32 ddbs; /* 2eSST Broadcast select */ -}; - -struct tsi148_dma_entry { - /* - * The descriptor needs to be aligned on a 64-bit boundary, we increase - * the chance of this by putting it first in the structure. - */ - struct tsi148_dma_descriptor descriptor; - struct list_head list; - dma_addr_t dma_handle; -}; - -/* - * TSI148 ASIC register structure overlays and bit field definitions. - * - * Note: Tsi148 Register Group (CRG) consists of the following - * combination of registers: - * PCFS - PCI Configuration Space Registers - * LCSR - Local Control and Status Registers - * GCSR - Global Control and Status Registers - * CR/CSR - Subset of Configuration ROM / - * Control and Status Registers - */ - -/* - * Command/Status Registers (CRG + $004) - */ -#define TSI148_PCFS_ID 0x0 -#define TSI148_PCFS_CSR 0x4 -#define TSI148_PCFS_CLASS 0x8 -#define TSI148_PCFS_MISC0 0xC -#define TSI148_PCFS_MBARL 0x10 -#define TSI148_PCFS_MBARU 0x14 -#define TSI148_PCFS_SUBID 0x28 -#define TSI148_PCFS_CAPP 0x34 -#define TSI148_PCFS_MISC1 0x3C -#define TSI148_PCFS_XCAPP 0x40 -#define TSI148_PCFS_XSTAT 0x44 - -/* - * LCSR definitions - */ - -/* - * Outbound Translations - */ -#define TSI148_LCSR_OT0_OTSAU 0x100 -#define TSI148_LCSR_OT0_OTSAL 0x104 -#define TSI148_LCSR_OT0_OTEAU 0x108 -#define TSI148_LCSR_OT0_OTEAL 0x10C -#define TSI148_LCSR_OT0_OTOFU 0x110 -#define TSI148_LCSR_OT0_OTOFL 0x114 -#define TSI148_LCSR_OT0_OTBS 0x118 -#define TSI148_LCSR_OT0_OTAT 0x11C - -#define TSI148_LCSR_OT1_OTSAU 0x120 -#define TSI148_LCSR_OT1_OTSAL 0x124 -#define TSI148_LCSR_OT1_OTEAU 0x128 -#define TSI148_LCSR_OT1_OTEAL 0x12C -#define TSI148_LCSR_OT1_OTOFU 0x130 -#define TSI148_LCSR_OT1_OTOFL 0x134 -#define TSI148_LCSR_OT1_OTBS 0x138 -#define TSI148_LCSR_OT1_OTAT 0x13C - -#define TSI148_LCSR_OT2_OTSAU 0x140 -#define TSI148_LCSR_OT2_OTSAL 0x144 -#define TSI148_LCSR_OT2_OTEAU 0x148 -#define TSI148_LCSR_OT2_OTEAL 0x14C -#define TSI148_LCSR_OT2_OTOFU 0x150 -#define TSI148_LCSR_OT2_OTOFL 0x154 -#define TSI148_LCSR_OT2_OTBS 0x158 -#define TSI148_LCSR_OT2_OTAT 0x15C - -#define TSI148_LCSR_OT3_OTSAU 0x160 -#define TSI148_LCSR_OT3_OTSAL 0x164 -#define TSI148_LCSR_OT3_OTEAU 0x168 -#define TSI148_LCSR_OT3_OTEAL 0x16C -#define TSI148_LCSR_OT3_OTOFU 0x170 -#define TSI148_LCSR_OT3_OTOFL 0x174 -#define TSI148_LCSR_OT3_OTBS 0x178 -#define TSI148_LCSR_OT3_OTAT 0x17C - -#define TSI148_LCSR_OT4_OTSAU 0x180 -#define TSI148_LCSR_OT4_OTSAL 0x184 -#define TSI148_LCSR_OT4_OTEAU 0x188 -#define TSI148_LCSR_OT4_OTEAL 0x18C -#define TSI148_LCSR_OT4_OTOFU 0x190 -#define TSI148_LCSR_OT4_OTOFL 0x194 -#define TSI148_LCSR_OT4_OTBS 0x198 -#define TSI148_LCSR_OT4_OTAT 0x19C - -#define TSI148_LCSR_OT5_OTSAU 0x1A0 -#define TSI148_LCSR_OT5_OTSAL 0x1A4 -#define TSI148_LCSR_OT5_OTEAU 0x1A8 -#define TSI148_LCSR_OT5_OTEAL 0x1AC -#define TSI148_LCSR_OT5_OTOFU 0x1B0 -#define TSI148_LCSR_OT5_OTOFL 0x1B4 -#define TSI148_LCSR_OT5_OTBS 0x1B8 -#define TSI148_LCSR_OT5_OTAT 0x1BC - -#define TSI148_LCSR_OT6_OTSAU 0x1C0 -#define TSI148_LCSR_OT6_OTSAL 0x1C4 -#define TSI148_LCSR_OT6_OTEAU 0x1C8 -#define TSI148_LCSR_OT6_OTEAL 0x1CC -#define TSI148_LCSR_OT6_OTOFU 0x1D0 -#define TSI148_LCSR_OT6_OTOFL 0x1D4 -#define TSI148_LCSR_OT6_OTBS 0x1D8 -#define TSI148_LCSR_OT6_OTAT 0x1DC - -#define TSI148_LCSR_OT7_OTSAU 0x1E0 -#define TSI148_LCSR_OT7_OTSAL 0x1E4 -#define TSI148_LCSR_OT7_OTEAU 0x1E8 -#define TSI148_LCSR_OT7_OTEAL 0x1EC -#define TSI148_LCSR_OT7_OTOFU 0x1F0 -#define TSI148_LCSR_OT7_OTOFL 0x1F4 -#define TSI148_LCSR_OT7_OTBS 0x1F8 -#define TSI148_LCSR_OT7_OTAT 0x1FC - -#define TSI148_LCSR_OT0 0x100 -#define TSI148_LCSR_OT1 0x120 -#define TSI148_LCSR_OT2 0x140 -#define TSI148_LCSR_OT3 0x160 -#define TSI148_LCSR_OT4 0x180 -#define TSI148_LCSR_OT5 0x1A0 -#define TSI148_LCSR_OT6 0x1C0 -#define TSI148_LCSR_OT7 0x1E0 - -static const int TSI148_LCSR_OT[8] = { TSI148_LCSR_OT0, TSI148_LCSR_OT1, - TSI148_LCSR_OT2, TSI148_LCSR_OT3, - TSI148_LCSR_OT4, TSI148_LCSR_OT5, - TSI148_LCSR_OT6, TSI148_LCSR_OT7 }; - -#define TSI148_LCSR_OFFSET_OTSAU 0x0 -#define TSI148_LCSR_OFFSET_OTSAL 0x4 -#define TSI148_LCSR_OFFSET_OTEAU 0x8 -#define TSI148_LCSR_OFFSET_OTEAL 0xC -#define TSI148_LCSR_OFFSET_OTOFU 0x10 -#define TSI148_LCSR_OFFSET_OTOFL 0x14 -#define TSI148_LCSR_OFFSET_OTBS 0x18 -#define TSI148_LCSR_OFFSET_OTAT 0x1C - -/* - * VMEbus interrupt ack - * offset 0x200 - */ -#define TSI148_LCSR_VIACK1 0x204 -#define TSI148_LCSR_VIACK2 0x208 -#define TSI148_LCSR_VIACK3 0x20C -#define TSI148_LCSR_VIACK4 0x210 -#define TSI148_LCSR_VIACK5 0x214 -#define TSI148_LCSR_VIACK6 0x218 -#define TSI148_LCSR_VIACK7 0x21C - -static const int TSI148_LCSR_VIACK[8] = { 0, TSI148_LCSR_VIACK1, - TSI148_LCSR_VIACK2, TSI148_LCSR_VIACK3, - TSI148_LCSR_VIACK4, TSI148_LCSR_VIACK5, - TSI148_LCSR_VIACK6, TSI148_LCSR_VIACK7 }; - -/* - * RMW - * offset 0x220 - */ -#define TSI148_LCSR_RMWAU 0x220 -#define TSI148_LCSR_RMWAL 0x224 -#define TSI148_LCSR_RMWEN 0x228 -#define TSI148_LCSR_RMWC 0x22C -#define TSI148_LCSR_RMWS 0x230 - -/* - * VMEbus control - * offset 0x234 - */ -#define TSI148_LCSR_VMCTRL 0x234 -#define TSI148_LCSR_VCTRL 0x238 -#define TSI148_LCSR_VSTAT 0x23C - -/* - * PCI status - * offset 0x240 - */ -#define TSI148_LCSR_PSTAT 0x240 - -/* - * VME filter. - * offset 0x250 - */ -#define TSI148_LCSR_VMEFL 0x250 - -/* - * VME exception. - * offset 0x260 - */ -#define TSI148_LCSR_VEAU 0x260 -#define TSI148_LCSR_VEAL 0x264 -#define TSI148_LCSR_VEAT 0x268 - -/* - * PCI error - * offset 0x270 - */ -#define TSI148_LCSR_EDPAU 0x270 -#define TSI148_LCSR_EDPAL 0x274 -#define TSI148_LCSR_EDPXA 0x278 -#define TSI148_LCSR_EDPXS 0x27C -#define TSI148_LCSR_EDPAT 0x280 - -/* - * Inbound Translations - * offset 0x300 - */ -#define TSI148_LCSR_IT0_ITSAU 0x300 -#define TSI148_LCSR_IT0_ITSAL 0x304 -#define TSI148_LCSR_IT0_ITEAU 0x308 -#define TSI148_LCSR_IT0_ITEAL 0x30C -#define TSI148_LCSR_IT0_ITOFU 0x310 -#define TSI148_LCSR_IT0_ITOFL 0x314 -#define TSI148_LCSR_IT0_ITAT 0x318 - -#define TSI148_LCSR_IT1_ITSAU 0x320 -#define TSI148_LCSR_IT1_ITSAL 0x324 -#define TSI148_LCSR_IT1_ITEAU 0x328 -#define TSI148_LCSR_IT1_ITEAL 0x32C -#define TSI148_LCSR_IT1_ITOFU 0x330 -#define TSI148_LCSR_IT1_ITOFL 0x334 -#define TSI148_LCSR_IT1_ITAT 0x338 - -#define TSI148_LCSR_IT2_ITSAU 0x340 -#define TSI148_LCSR_IT2_ITSAL 0x344 -#define TSI148_LCSR_IT2_ITEAU 0x348 -#define TSI148_LCSR_IT2_ITEAL 0x34C -#define TSI148_LCSR_IT2_ITOFU 0x350 -#define TSI148_LCSR_IT2_ITOFL 0x354 -#define TSI148_LCSR_IT2_ITAT 0x358 - -#define TSI148_LCSR_IT3_ITSAU 0x360 -#define TSI148_LCSR_IT3_ITSAL 0x364 -#define TSI148_LCSR_IT3_ITEAU 0x368 -#define TSI148_LCSR_IT3_ITEAL 0x36C -#define TSI148_LCSR_IT3_ITOFU 0x370 -#define TSI148_LCSR_IT3_ITOFL 0x374 -#define TSI148_LCSR_IT3_ITAT 0x378 - -#define TSI148_LCSR_IT4_ITSAU 0x380 -#define TSI148_LCSR_IT4_ITSAL 0x384 -#define TSI148_LCSR_IT4_ITEAU 0x388 -#define TSI148_LCSR_IT4_ITEAL 0x38C -#define TSI148_LCSR_IT4_ITOFU 0x390 -#define TSI148_LCSR_IT4_ITOFL 0x394 -#define TSI148_LCSR_IT4_ITAT 0x398 - -#define TSI148_LCSR_IT5_ITSAU 0x3A0 -#define TSI148_LCSR_IT5_ITSAL 0x3A4 -#define TSI148_LCSR_IT5_ITEAU 0x3A8 -#define TSI148_LCSR_IT5_ITEAL 0x3AC -#define TSI148_LCSR_IT5_ITOFU 0x3B0 -#define TSI148_LCSR_IT5_ITOFL 0x3B4 -#define TSI148_LCSR_IT5_ITAT 0x3B8 - -#define TSI148_LCSR_IT6_ITSAU 0x3C0 -#define TSI148_LCSR_IT6_ITSAL 0x3C4 -#define TSI148_LCSR_IT6_ITEAU 0x3C8 -#define TSI148_LCSR_IT6_ITEAL 0x3CC -#define TSI148_LCSR_IT6_ITOFU 0x3D0 -#define TSI148_LCSR_IT6_ITOFL 0x3D4 -#define TSI148_LCSR_IT6_ITAT 0x3D8 - -#define TSI148_LCSR_IT7_ITSAU 0x3E0 -#define TSI148_LCSR_IT7_ITSAL 0x3E4 -#define TSI148_LCSR_IT7_ITEAU 0x3E8 -#define TSI148_LCSR_IT7_ITEAL 0x3EC -#define TSI148_LCSR_IT7_ITOFU 0x3F0 -#define TSI148_LCSR_IT7_ITOFL 0x3F4 -#define TSI148_LCSR_IT7_ITAT 0x3F8 - -#define TSI148_LCSR_IT0 0x300 -#define TSI148_LCSR_IT1 0x320 -#define TSI148_LCSR_IT2 0x340 -#define TSI148_LCSR_IT3 0x360 -#define TSI148_LCSR_IT4 0x380 -#define TSI148_LCSR_IT5 0x3A0 -#define TSI148_LCSR_IT6 0x3C0 -#define TSI148_LCSR_IT7 0x3E0 - -static const int TSI148_LCSR_IT[8] = { TSI148_LCSR_IT0, TSI148_LCSR_IT1, - TSI148_LCSR_IT2, TSI148_LCSR_IT3, - TSI148_LCSR_IT4, TSI148_LCSR_IT5, - TSI148_LCSR_IT6, TSI148_LCSR_IT7 }; - -#define TSI148_LCSR_OFFSET_ITSAU 0x0 -#define TSI148_LCSR_OFFSET_ITSAL 0x4 -#define TSI148_LCSR_OFFSET_ITEAU 0x8 -#define TSI148_LCSR_OFFSET_ITEAL 0xC -#define TSI148_LCSR_OFFSET_ITOFU 0x10 -#define TSI148_LCSR_OFFSET_ITOFL 0x14 -#define TSI148_LCSR_OFFSET_ITAT 0x18 - -/* - * Inbound Translation GCSR - * offset 0x400 - */ -#define TSI148_LCSR_GBAU 0x400 -#define TSI148_LCSR_GBAL 0x404 -#define TSI148_LCSR_GCSRAT 0x408 - -/* - * Inbound Translation CRG - * offset 0x40C - */ -#define TSI148_LCSR_CBAU 0x40C -#define TSI148_LCSR_CBAL 0x410 -#define TSI148_LCSR_CSRAT 0x414 - -/* - * Inbound Translation CR/CSR - * CRG - * offset 0x418 - */ -#define TSI148_LCSR_CROU 0x418 -#define TSI148_LCSR_CROL 0x41C -#define TSI148_LCSR_CRAT 0x420 - -/* - * Inbound Translation Location Monitor - * offset 0x424 - */ -#define TSI148_LCSR_LMBAU 0x424 -#define TSI148_LCSR_LMBAL 0x428 -#define TSI148_LCSR_LMAT 0x42C - -/* - * VMEbus Interrupt Control. - * offset 0x430 - */ -#define TSI148_LCSR_BCU 0x430 -#define TSI148_LCSR_BCL 0x434 -#define TSI148_LCSR_BPGTR 0x438 -#define TSI148_LCSR_BPCTR 0x43C -#define TSI148_LCSR_VICR 0x440 - -/* - * Local Bus Interrupt Control. - * offset 0x448 - */ -#define TSI148_LCSR_INTEN 0x448 -#define TSI148_LCSR_INTEO 0x44C -#define TSI148_LCSR_INTS 0x450 -#define TSI148_LCSR_INTC 0x454 -#define TSI148_LCSR_INTM1 0x458 -#define TSI148_LCSR_INTM2 0x45C - -/* - * DMA Controllers - * offset 0x500 - */ -#define TSI148_LCSR_DCTL0 0x500 -#define TSI148_LCSR_DSTA0 0x504 -#define TSI148_LCSR_DCSAU0 0x508 -#define TSI148_LCSR_DCSAL0 0x50C -#define TSI148_LCSR_DCDAU0 0x510 -#define TSI148_LCSR_DCDAL0 0x514 -#define TSI148_LCSR_DCLAU0 0x518 -#define TSI148_LCSR_DCLAL0 0x51C -#define TSI148_LCSR_DSAU0 0x520 -#define TSI148_LCSR_DSAL0 0x524 -#define TSI148_LCSR_DDAU0 0x528 -#define TSI148_LCSR_DDAL0 0x52C -#define TSI148_LCSR_DSAT0 0x530 -#define TSI148_LCSR_DDAT0 0x534 -#define TSI148_LCSR_DNLAU0 0x538 -#define TSI148_LCSR_DNLAL0 0x53C -#define TSI148_LCSR_DCNT0 0x540 -#define TSI148_LCSR_DDBS0 0x544 - -#define TSI148_LCSR_DCTL1 0x580 -#define TSI148_LCSR_DSTA1 0x584 -#define TSI148_LCSR_DCSAU1 0x588 -#define TSI148_LCSR_DCSAL1 0x58C -#define TSI148_LCSR_DCDAU1 0x590 -#define TSI148_LCSR_DCDAL1 0x594 -#define TSI148_LCSR_DCLAU1 0x598 -#define TSI148_LCSR_DCLAL1 0x59C -#define TSI148_LCSR_DSAU1 0x5A0 -#define TSI148_LCSR_DSAL1 0x5A4 -#define TSI148_LCSR_DDAU1 0x5A8 -#define TSI148_LCSR_DDAL1 0x5AC -#define TSI148_LCSR_DSAT1 0x5B0 -#define TSI148_LCSR_DDAT1 0x5B4 -#define TSI148_LCSR_DNLAU1 0x5B8 -#define TSI148_LCSR_DNLAL1 0x5BC -#define TSI148_LCSR_DCNT1 0x5C0 -#define TSI148_LCSR_DDBS1 0x5C4 - -#define TSI148_LCSR_DMA0 0x500 -#define TSI148_LCSR_DMA1 0x580 - -static const int TSI148_LCSR_DMA[TSI148_MAX_DMA] = { TSI148_LCSR_DMA0, - TSI148_LCSR_DMA1 }; - -#define TSI148_LCSR_OFFSET_DCTL 0x0 -#define TSI148_LCSR_OFFSET_DSTA 0x4 -#define TSI148_LCSR_OFFSET_DCSAU 0x8 -#define TSI148_LCSR_OFFSET_DCSAL 0xC -#define TSI148_LCSR_OFFSET_DCDAU 0x10 -#define TSI148_LCSR_OFFSET_DCDAL 0x14 -#define TSI148_LCSR_OFFSET_DCLAU 0x18 -#define TSI148_LCSR_OFFSET_DCLAL 0x1C -#define TSI148_LCSR_OFFSET_DSAU 0x20 -#define TSI148_LCSR_OFFSET_DSAL 0x24 -#define TSI148_LCSR_OFFSET_DDAU 0x28 -#define TSI148_LCSR_OFFSET_DDAL 0x2C -#define TSI148_LCSR_OFFSET_DSAT 0x30 -#define TSI148_LCSR_OFFSET_DDAT 0x34 -#define TSI148_LCSR_OFFSET_DNLAU 0x38 -#define TSI148_LCSR_OFFSET_DNLAL 0x3C -#define TSI148_LCSR_OFFSET_DCNT 0x40 -#define TSI148_LCSR_OFFSET_DDBS 0x44 - -/* - * GCSR Register Group - */ - -/* - * GCSR CRG - * offset 0x00 0x600 - DEVI/VENI - * offset 0x04 0x604 - CTRL/GA/REVID - * offset 0x08 0x608 - Semaphore3/2/1/0 - * offset 0x0C 0x60C - Seamphore7/6/5/4 - */ -#define TSI148_GCSR_ID 0x600 -#define TSI148_GCSR_CSR 0x604 -#define TSI148_GCSR_SEMA0 0x608 -#define TSI148_GCSR_SEMA1 0x60C - -/* - * Mail Box - * GCSR CRG - * offset 0x10 0x610 - Mailbox0 - */ -#define TSI148_GCSR_MBOX0 0x610 -#define TSI148_GCSR_MBOX1 0x614 -#define TSI148_GCSR_MBOX2 0x618 -#define TSI148_GCSR_MBOX3 0x61C - -static const int TSI148_GCSR_MBOX[4] = { TSI148_GCSR_MBOX0, - TSI148_GCSR_MBOX1, - TSI148_GCSR_MBOX2, - TSI148_GCSR_MBOX3 }; - -/* - * CR/CSR - */ - -/* - * CR/CSR CRG - * offset 0x7FFF4 0xFF4 - CSRBCR - * offset 0x7FFF8 0xFF8 - CSRBSR - * offset 0x7FFFC 0xFFC - CBAR - */ -#define TSI148_CSRBCR 0xFF4 -#define TSI148_CSRBSR 0xFF8 -#define TSI148_CBAR 0xFFC - -/* - * TSI148 Register Bit Definitions - */ - -/* - * PFCS Register Set - */ -#define TSI148_PCFS_CMMD_SERR BIT(8) /* SERR_L out pin ssys err */ -#define TSI148_PCFS_CMMD_PERR BIT(6) /* PERR_L out pin parity */ -#define TSI148_PCFS_CMMD_MSTR BIT(2) /* PCI bus master */ -#define TSI148_PCFS_CMMD_MEMSP BIT(1) /* PCI mem space access */ -#define TSI148_PCFS_CMMD_IOSP BIT(0) /* PCI I/O space enable */ - -#define TSI148_PCFS_STAT_RCPVE BIT(15) /* Detected Parity Error */ -#define TSI148_PCFS_STAT_SIGSE BIT(14) /* Signalled System Error */ -#define TSI148_PCFS_STAT_RCVMA BIT(13) /* Received Master Abort */ -#define TSI148_PCFS_STAT_RCVTA BIT(12) /* Received Target Abort */ -#define TSI148_PCFS_STAT_SIGTA BIT(11) /* Signalled Target Abort */ -#define TSI148_PCFS_STAT_SELTIM (3 << 9) /* DELSEL Timing */ -#define TSI148_PCFS_STAT_DPAR BIT(8) /* Data Parity Err Reported */ -#define TSI148_PCFS_STAT_FAST BIT(7) /* Fast back-to-back Cap */ -#define TSI148_PCFS_STAT_P66M BIT(5) /* 66 MHz Capable */ -#define TSI148_PCFS_STAT_CAPL BIT(4) /* Capab List - address $34 */ - -/* - * Revision ID/Class Code Registers (CRG +$008) - */ -#define TSI148_PCFS_CLAS_M (0xFF << 24) /* Class ID */ -#define TSI148_PCFS_SUBCLAS_M (0xFF << 16) /* Sub-Class ID */ -#define TSI148_PCFS_PROGIF_M (0xFF << 8) /* Sub-Class ID */ -#define TSI148_PCFS_REVID_M (0xFF << 0) /* Rev ID */ - -/* - * Cache Line Size/ Master Latency Timer/ Header Type Registers (CRG + $00C) - */ -#define TSI148_PCFS_HEAD_M (0xFF << 16) /* Master Lat Timer */ -#define TSI148_PCFS_MLAT_M (0xFF << 8) /* Master Lat Timer */ -#define TSI148_PCFS_CLSZ_M (0xFF << 0) /* Cache Line Size */ - -/* - * Memory Base Address Lower Reg (CRG + $010) - */ -#define TSI148_PCFS_MBARL_BASEL_M (0xFFFFF << 12) /* Base Addr Lower Mask */ -#define TSI148_PCFS_MBARL_PRE BIT(3) /* Prefetch */ -#define TSI148_PCFS_MBARL_MTYPE_M (3 << 1) /* Memory Type Mask */ -#define TSI148_PCFS_MBARL_IOMEM BIT(0) /* I/O Space Indicator */ - -/* - * Message Signaled Interrupt Capabilities Register (CRG + $040) - */ -#define TSI148_PCFS_MSICAP_64BAC BIT(7) /* 64-bit Address Capable */ -#define TSI148_PCFS_MSICAP_MME_M (7 << 4) /* Multiple Msg Enable Mask */ -#define TSI148_PCFS_MSICAP_MMC_M (7 << 1) /* Multiple Msg Capable Mask */ -#define TSI148_PCFS_MSICAP_MSIEN BIT(0) /* Msg signaled INT Enable */ - -/* - * Message Address Lower Register (CRG +$044) - */ -#define TSI148_PCFS_MSIAL_M (0x3FFFFFFF << 2) /* Mask */ - -/* - * Message Data Register (CRG + 4C) - */ -#define TSI148_PCFS_MSIMD_M (0xFFFF << 0) /* Mask */ - -/* - * PCI-X Capabilities Register (CRG + $050) - */ -#define TSI148_PCFS_PCIXCAP_MOST_M (7 << 4) /* Max outstanding Split Tran */ -#define TSI148_PCFS_PCIXCAP_MMRBC_M (3 << 2) /* Max Mem Read byte cnt */ -#define TSI148_PCFS_PCIXCAP_ERO BIT(1) /* Enable Relaxed Ordering */ -#define TSI148_PCFS_PCIXCAP_DPERE BIT(0) /* Data Parity Recover Enable */ - -/* - * PCI-X Status Register (CRG +$054) - */ -#define TSI148_PCFS_PCIXSTAT_RSCEM BIT(29) /* Received Split Comp Error */ -#define TSI148_PCFS_PCIXSTAT_DMCRS_M (7 << 26) /* max Cumulative Read Size */ -#define TSI148_PCFS_PCIXSTAT_DMOST_M (7 << 23) /* max outstanding Split Trans */ -#define TSI148_PCFS_PCIXSTAT_DMMRC_M (3 << 21) /* max mem read byte count */ -#define TSI148_PCFS_PCIXSTAT_DC BIT(20) /* Device Complexity */ -#define TSI148_PCFS_PCIXSTAT_USC BIT(19) /* Unexpected Split comp */ -#define TSI148_PCFS_PCIXSTAT_SCD BIT(18) /* Split completion discard */ -#define TSI148_PCFS_PCIXSTAT_133C BIT(17) /* 133MHz capable */ -#define TSI148_PCFS_PCIXSTAT_64D BIT(16) /* 64 bit device */ -#define TSI148_PCFS_PCIXSTAT_BN_M (0xFF << 8) /* Bus number */ -#define TSI148_PCFS_PCIXSTAT_DN_M (0x1F << 3) /* Device number */ -#define TSI148_PCFS_PCIXSTAT_FN_M (7 << 0) /* Function Number */ - -/* - * LCSR Registers - */ - -/* - * Outbound Translation Starting Address Lower - */ -#define TSI148_LCSR_OTSAL_M (0xFFFF << 16) /* Mask */ - -/* - * Outbound Translation Ending Address Lower - */ -#define TSI148_LCSR_OTEAL_M (0xFFFF << 16) /* Mask */ - -/* - * Outbound Translation Offset Lower - */ -#define TSI148_LCSR_OTOFFL_M (0xFFFF << 16) /* Mask */ - -/* - * Outbound Translation 2eSST Broadcast Select - */ -#define TSI148_LCSR_OTBS_M (0xFFFFF << 0) /* Mask */ - -/* - * Outbound Translation Attribute - */ -#define TSI148_LCSR_OTAT_EN BIT(31) /* Window Enable */ -#define TSI148_LCSR_OTAT_MRPFD BIT(18) /* Prefetch Disable */ - -#define TSI148_LCSR_OTAT_PFS_M (3 << 16) /* Prefetch Size Mask */ -#define TSI148_LCSR_OTAT_PFS_2 (0 << 16) /* 2 Cache Lines P Size */ -#define TSI148_LCSR_OTAT_PFS_4 BIT(16) /* 4 Cache Lines P Size */ -#define TSI148_LCSR_OTAT_PFS_8 (2 << 16) /* 8 Cache Lines P Size */ -#define TSI148_LCSR_OTAT_PFS_16 (3 << 16) /* 16 Cache Lines P Size */ - -#define TSI148_LCSR_OTAT_2eSSTM_M (7 << 11) /* 2eSST Xfer Rate Mask */ -#define TSI148_LCSR_OTAT_2eSSTM_160 (0 << 11) /* 160MB/s 2eSST Xfer Rate */ -#define TSI148_LCSR_OTAT_2eSSTM_267 BIT(11) /* 267MB/s 2eSST Xfer Rate */ -#define TSI148_LCSR_OTAT_2eSSTM_320 (2 << 11) /* 320MB/s 2eSST Xfer Rate */ - -#define TSI148_LCSR_OTAT_TM_M (7 << 8) /* Xfer Protocol Mask */ -#define TSI148_LCSR_OTAT_TM_SCT (0 << 8) /* SCT Xfer Protocol */ -#define TSI148_LCSR_OTAT_TM_BLT BIT(8) /* BLT Xfer Protocol */ -#define TSI148_LCSR_OTAT_TM_MBLT (2 << 8) /* MBLT Xfer Protocol */ -#define TSI148_LCSR_OTAT_TM_2eVME (3 << 8) /* 2eVME Xfer Protocol */ -#define TSI148_LCSR_OTAT_TM_2eSST (4 << 8) /* 2eSST Xfer Protocol */ -#define TSI148_LCSR_OTAT_TM_2eSSTB (5 << 8) /* 2eSST Bcast Xfer Protocol */ - -#define TSI148_LCSR_OTAT_DBW_M (3 << 6) /* Max Data Width */ -#define TSI148_LCSR_OTAT_DBW_16 (0 << 6) /* 16-bit Data Width */ -#define TSI148_LCSR_OTAT_DBW_32 BIT(6) /* 32-bit Data Width */ - -#define TSI148_LCSR_OTAT_SUP BIT(5) /* Supervisory Access */ -#define TSI148_LCSR_OTAT_PGM BIT(4) /* Program Access */ - -#define TSI148_LCSR_OTAT_AMODE_M (0xf << 0) /* Address Mode Mask */ -#define TSI148_LCSR_OTAT_AMODE_A16 (0 << 0) /* A16 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_A24 BIT(0) /* A24 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_A32 (2 << 0) /* A32 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_A64 (4 << 0) /* A32 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_CRCSR (5 << 0) /* CR/CSR Address Space */ -#define TSI148_LCSR_OTAT_AMODE_USER1 (8 << 0) /* User1 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_USER2 (9 << 0) /* User2 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_USER3 (10 << 0) /* User3 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_USER4 (11 << 0) /* User4 Address Space */ - -/* - * VME Master Control Register CRG+$234 - */ -#define TSI148_LCSR_VMCTRL_VSA BIT(27) /* VMEbus Stop Ack */ -#define TSI148_LCSR_VMCTRL_VS BIT(26) /* VMEbus Stop */ -#define TSI148_LCSR_VMCTRL_DHB BIT(25) /* Device Has Bus */ -#define TSI148_LCSR_VMCTRL_DWB BIT(24) /* Device Wants Bus */ - -#define TSI148_LCSR_VMCTRL_RMWEN BIT(20) /* RMW Enable */ - -#define TSI148_LCSR_VMCTRL_ATO_M (7 << 16) /* Master Access Time-out Mask */ -#define TSI148_LCSR_VMCTRL_ATO_32 (0 << 16) /* 32 us */ -#define TSI148_LCSR_VMCTRL_ATO_128 BIT(16) /* 128 us */ -#define TSI148_LCSR_VMCTRL_ATO_512 (2 << 16) /* 512 us */ -#define TSI148_LCSR_VMCTRL_ATO_2M (3 << 16) /* 2 ms */ -#define TSI148_LCSR_VMCTRL_ATO_8M (4 << 16) /* 8 ms */ -#define TSI148_LCSR_VMCTRL_ATO_32M (5 << 16) /* 32 ms */ -#define TSI148_LCSR_VMCTRL_ATO_128M (6 << 16) /* 128 ms */ -#define TSI148_LCSR_VMCTRL_ATO_DIS (7 << 16) /* Disabled */ - -#define TSI148_LCSR_VMCTRL_VTOFF_M (7 << 12) /* VMEbus Master Time off */ -#define TSI148_LCSR_VMCTRL_VTOFF_0 (0 << 12) /* 0us */ -#define TSI148_LCSR_VMCTRL_VTOFF_1 BIT(12) /* 1us */ -#define TSI148_LCSR_VMCTRL_VTOFF_2 (2 << 12) /* 2us */ -#define TSI148_LCSR_VMCTRL_VTOFF_4 (3 << 12) /* 4us */ -#define TSI148_LCSR_VMCTRL_VTOFF_8 (4 << 12) /* 8us */ -#define TSI148_LCSR_VMCTRL_VTOFF_16 (5 << 12) /* 16us */ -#define TSI148_LCSR_VMCTRL_VTOFF_32 (6 << 12) /* 32us */ -#define TSI148_LCSR_VMCTRL_VTOFF_64 (7 << 12) /* 64us */ - -#define TSI148_LCSR_VMCTRL_VTON_M (7 << 8) /* VMEbus Master Time On */ -#define TSI148_LCSR_VMCTRL_VTON_4 (0 << 8) /* 8us */ -#define TSI148_LCSR_VMCTRL_VTON_8 BIT(8) /* 8us */ -#define TSI148_LCSR_VMCTRL_VTON_16 (2 << 8) /* 16us */ -#define TSI148_LCSR_VMCTRL_VTON_32 (3 << 8) /* 32us */ -#define TSI148_LCSR_VMCTRL_VTON_64 (4 << 8) /* 64us */ -#define TSI148_LCSR_VMCTRL_VTON_128 (5 << 8) /* 128us */ -#define TSI148_LCSR_VMCTRL_VTON_256 (6 << 8) /* 256us */ -#define TSI148_LCSR_VMCTRL_VTON_512 (7 << 8) /* 512us */ - -#define TSI148_LCSR_VMCTRL_VREL_M (3 << 3) /* VMEbus Master Rel Mode Mask - */ -#define TSI148_LCSR_VMCTRL_VREL_T_D (0 << 3) /* Time on or Done */ -#define TSI148_LCSR_VMCTRL_VREL_T_R_D BIT(3) /* Time on and REQ or Done */ -#define TSI148_LCSR_VMCTRL_VREL_T_B_D (2 << 3) /* Time on and BCLR or Done */ -#define TSI148_LCSR_VMCTRL_VREL_T_D_R (3 << 3) /* Time on or Done and REQ */ - -#define TSI148_LCSR_VMCTRL_VFAIR BIT(2) /* VMEbus Master Fair Mode */ -#define TSI148_LCSR_VMCTRL_VREQL_M (3 << 0) /* VMEbus Master Req Level Mask - */ - -/* - * VMEbus Control Register CRG+$238 - */ -#define TSI148_LCSR_VCTRL_LRE BIT(31) /* Late Retry Enable */ - -#define TSI148_LCSR_VCTRL_DLT_M (0xF << 24) /* Deadlock Timer */ -#define TSI148_LCSR_VCTRL_DLT_OFF (0 << 24) /* Deadlock Timer Off */ -#define TSI148_LCSR_VCTRL_DLT_16 BIT(24) /* 16 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_32 (2 << 24) /* 32 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_64 (3 << 24) /* 64 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_128 (4 << 24) /* 128 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_256 (5 << 24) /* 256 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_512 (6 << 24) /* 512 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_1024 (7 << 24) /* 1024 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_2048 (8 << 24) /* 2048 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_4096 (9 << 24) /* 4096 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_8192 (0xA << 24) /* 8192 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_16384 (0xB << 24) /* 16384 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_32768 (0xC << 24) /* 32768 VCLKS */ - -#define TSI148_LCSR_VCTRL_NERBB BIT(20) /* No Early Release of Bus Busy */ - -#define TSI148_LCSR_VCTRL_SRESET BIT(17) /* System Reset */ -#define TSI148_LCSR_VCTRL_LRESET BIT(16) /* Local Reset */ - -#define TSI148_LCSR_VCTRL_SFAILAI BIT(15) /* SYSFAIL Auto Slot ID */ -#define TSI148_LCSR_VCTRL_BID_M (0x1F << 8) /* Broadcast ID Mask */ - -#define TSI148_LCSR_VCTRL_ATOEN BIT(7) /* Arbiter Time-out Enable */ -#define TSI148_LCSR_VCTRL_ROBIN BIT(6) /* VMEbus Round Robin */ - -#define TSI148_LCSR_VCTRL_GTO_M (7 << 0) /* VMEbus Global Time-out Mask*/ -#define TSI148_LCSR_VCTRL_GTO_8 (0 << 0) /* 8 us */ -#define TSI148_LCSR_VCTRL_GTO_16 BIT(0) /* 16 us */ -#define TSI148_LCSR_VCTRL_GTO_32 (2 << 0) /* 32 us */ -#define TSI148_LCSR_VCTRL_GTO_64 (3 << 0) /* 64 us */ -#define TSI148_LCSR_VCTRL_GTO_128 (4 << 0) /* 128 us */ -#define TSI148_LCSR_VCTRL_GTO_256 (5 << 0) /* 256 us */ -#define TSI148_LCSR_VCTRL_GTO_512 (6 << 0) /* 512 us */ -#define TSI148_LCSR_VCTRL_GTO_DIS (7 << 0) /* Disabled */ - -/* - * VMEbus Status Register CRG + $23C - */ -#define TSI148_LCSR_VSTAT_CPURST BIT(15) /* Clear power up reset */ -#define TSI148_LCSR_VSTAT_BRDFL BIT(14) /* Board fail */ -#define TSI148_LCSR_VSTAT_PURSTS BIT(12) /* Power up reset status */ -#define TSI148_LCSR_VSTAT_BDFAILS BIT(11) /* Board Fail Status */ -#define TSI148_LCSR_VSTAT_SYSFAILS BIT(10) /* System Fail Status */ -#define TSI148_LCSR_VSTAT_ACFAILS BIT(9) /* AC fail status */ -#define TSI148_LCSR_VSTAT_SCONS BIT(8) /* System Cont Status */ -#define TSI148_LCSR_VSTAT_GAP BIT(5) /* Geographic Addr Parity */ -#define TSI148_LCSR_VSTAT_GA_M (0x1F << 0) /* Geographic Addr Mask */ - -/* - * PCI Configuration Status Register CRG+$240 - */ -#define TSI148_LCSR_PSTAT_REQ64S BIT(6) /* Request 64 status set */ -#define TSI148_LCSR_PSTAT_M66ENS BIT(5) /* M66ENS 66Mhz enable */ -#define TSI148_LCSR_PSTAT_FRAMES BIT(4) /* Frame Status */ -#define TSI148_LCSR_PSTAT_IRDYS BIT(3) /* IRDY status */ -#define TSI148_LCSR_PSTAT_DEVSELS BIT(2) /* DEVL status */ -#define TSI148_LCSR_PSTAT_STOPS BIT(1) /* STOP status */ -#define TSI148_LCSR_PSTAT_TRDYS BIT(0) /* TRDY status */ - -/* - * VMEbus Exception Attributes Register CRG + $268 - */ -#define TSI148_LCSR_VEAT_VES BIT(31) /* Status */ -#define TSI148_LCSR_VEAT_VEOF BIT(30) /* Overflow */ -#define TSI148_LCSR_VEAT_VESCL BIT(29) /* Status Clear */ -#define TSI148_LCSR_VEAT_2EOT BIT(21) /* 2e Odd Termination */ -#define TSI148_LCSR_VEAT_2EST BIT(20) /* 2e Slave terminated */ -#define TSI148_LCSR_VEAT_BERR BIT(19) /* Bus Error */ -#define TSI148_LCSR_VEAT_LWORD BIT(18) /* LWORD_ signal state */ -#define TSI148_LCSR_VEAT_WRITE BIT(17) /* WRITE_ signal state */ -#define TSI148_LCSR_VEAT_IACK BIT(16) /* IACK_ signal state */ -#define TSI148_LCSR_VEAT_DS1 BIT(15) /* DS1_ signal state */ -#define TSI148_LCSR_VEAT_DS0 BIT(14) /* DS0_ signal state */ -#define TSI148_LCSR_VEAT_AM_M (0x3F << 8) /* Address Mode Mask */ -#define TSI148_LCSR_VEAT_XAM_M (0xFF << 0) /* Master AMode Mask */ - -/* - * VMEbus PCI Error Diagnostics PCI/X Attributes Register CRG + $280 - */ -#define TSI148_LCSR_EDPAT_EDPCL BIT(29) - -/* - * Inbound Translation Starting Address Lower - */ -#define TSI148_LCSR_ITSAL6432_M (0xFFFF << 16) /* Mask */ -#define TSI148_LCSR_ITSAL24_M (0x00FFF << 12) /* Mask */ -#define TSI148_LCSR_ITSAL16_M (0x0000FFF << 4) /* Mask */ - -/* - * Inbound Translation Ending Address Lower - */ -#define TSI148_LCSR_ITEAL6432_M (0xFFFF << 16) /* Mask */ -#define TSI148_LCSR_ITEAL24_M (0x00FFF << 12) /* Mask */ -#define TSI148_LCSR_ITEAL16_M (0x0000FFF << 4) /* Mask */ - -/* - * Inbound Translation Offset Lower - */ -#define TSI148_LCSR_ITOFFL6432_M (0xFFFF << 16) /* Mask */ -#define TSI148_LCSR_ITOFFL24_M (0xFFFFF << 12) /* Mask */ -#define TSI148_LCSR_ITOFFL16_M (0xFFFFFFF << 4) /* Mask */ - -/* - * Inbound Translation Attribute - */ -#define TSI148_LCSR_ITAT_EN BIT(31) /* Window Enable */ -#define TSI148_LCSR_ITAT_TH BIT(18) /* Prefetch Threshold */ - -#define TSI148_LCSR_ITAT_VFS_M (3 << 16) /* Virtual FIFO Size Mask */ -#define TSI148_LCSR_ITAT_VFS_64 (0 << 16) /* 64 bytes Virtual FIFO Size */ -#define TSI148_LCSR_ITAT_VFS_128 BIT(16) /* 128 bytes Virtual FIFO Sz */ -#define TSI148_LCSR_ITAT_VFS_256 (2 << 16) /* 256 bytes Virtual FIFO Sz */ -#define TSI148_LCSR_ITAT_VFS_512 (3 << 16) /* 512 bytes Virtual FIFO Sz */ - -#define TSI148_LCSR_ITAT_2eSSTM_M (7 << 12) /* 2eSST Xfer Rate Mask */ -#define TSI148_LCSR_ITAT_2eSSTM_160 (0 << 12) /* 160MB/s 2eSST Xfer Rate */ -#define TSI148_LCSR_ITAT_2eSSTM_267 BIT(12) /* 267MB/s 2eSST Xfer Rate */ -#define TSI148_LCSR_ITAT_2eSSTM_320 (2 << 12) /* 320MB/s 2eSST Xfer Rate */ - -#define TSI148_LCSR_ITAT_2eSSTB BIT(11) /* 2eSST Bcast Xfer Protocol */ -#define TSI148_LCSR_ITAT_2eSST BIT(10) /* 2eSST Xfer Protocol */ -#define TSI148_LCSR_ITAT_2eVME BIT(9) /* 2eVME Xfer Protocol */ -#define TSI148_LCSR_ITAT_MBLT BIT(8) /* MBLT Xfer Protocol */ -#define TSI148_LCSR_ITAT_BLT BIT(7) /* BLT Xfer Protocol */ - -#define TSI148_LCSR_ITAT_AS_M (7 << 4) /* Address Space Mask */ -#define TSI148_LCSR_ITAT_AS_A16 (0 << 4) /* A16 Address Space */ -#define TSI148_LCSR_ITAT_AS_A24 BIT(4) /* A24 Address Space */ -#define TSI148_LCSR_ITAT_AS_A32 (2 << 4) /* A32 Address Space */ -#define TSI148_LCSR_ITAT_AS_A64 (4 << 4) /* A64 Address Space */ - -#define TSI148_LCSR_ITAT_SUPR BIT(3) /* Supervisor Access */ -#define TSI148_LCSR_ITAT_NPRIV BIT(2) /* Non-Priv (User) Access */ -#define TSI148_LCSR_ITAT_PGM BIT(1) /* Program Access */ -#define TSI148_LCSR_ITAT_DATA BIT(0) /* Data Access */ - -/* - * GCSR Base Address Lower Address CRG +$404 - */ -#define TSI148_LCSR_GBAL_M (0x7FFFFFF << 5) /* Mask */ - -/* - * GCSR Attribute Register CRG + $408 - */ -#define TSI148_LCSR_GCSRAT_EN BIT(7) /* Enable access to GCSR */ - -#define TSI148_LCSR_GCSRAT_AS_M (7 << 4) /* Address Space Mask */ -#define TSI148_LCSR_GCSRAT_AS_A16 (0 << 4) /* Address Space 16 */ -#define TSI148_LCSR_GCSRAT_AS_A24 BIT(4) /* Address Space 24 */ -#define TSI148_LCSR_GCSRAT_AS_A32 (2 << 4) /* Address Space 32 */ -#define TSI148_LCSR_GCSRAT_AS_A64 (4 << 4) /* Address Space 64 */ - -#define TSI148_LCSR_GCSRAT_SUPR BIT(3) /* Sup set -GCSR decoder */ -#define TSI148_LCSR_GCSRAT_NPRIV BIT(2) /* Non-Privliged set - CGSR */ -#define TSI148_LCSR_GCSRAT_PGM BIT(1) /* Program set - GCSR decoder */ -#define TSI148_LCSR_GCSRAT_DATA BIT(0) /* DATA set GCSR decoder */ - -/* - * CRG Base Address Lower Address CRG + $410 - */ -#define TSI148_LCSR_CBAL_M (0xFFFFF << 12) - -/* - * CRG Attribute Register CRG + $414 - */ -#define TSI148_LCSR_CRGAT_EN BIT(7) /* Enable PRG Access */ - -#define TSI148_LCSR_CRGAT_AS_M (7 << 4) /* Address Space */ -#define TSI148_LCSR_CRGAT_AS_A16 (0 << 4) /* Address Space 16 */ -#define TSI148_LCSR_CRGAT_AS_A24 BIT(4) /* Address Space 24 */ -#define TSI148_LCSR_CRGAT_AS_A32 (2 << 4) /* Address Space 32 */ -#define TSI148_LCSR_CRGAT_AS_A64 (4 << 4) /* Address Space 64 */ - -#define TSI148_LCSR_CRGAT_SUPR BIT(3) /* Supervisor Access */ -#define TSI148_LCSR_CRGAT_NPRIV BIT(2) /* Non-Privliged(User) Access */ -#define TSI148_LCSR_CRGAT_PGM BIT(1) /* Program Access */ -#define TSI148_LCSR_CRGAT_DATA BIT(0) /* Data Access */ - -/* - * CR/CSR Offset Lower Register CRG + $41C - */ -#define TSI148_LCSR_CROL_M (0x1FFF << 19) /* Mask */ - -/* - * CR/CSR Attribute register CRG + $420 - */ -#define TSI148_LCSR_CRAT_EN BIT(7) /* Enable access to CR/CSR */ - -/* - * Location Monitor base address lower register CRG + $428 - */ -#define TSI148_LCSR_LMBAL_M (0x7FFFFFF << 5) /* Mask */ - -/* - * Location Monitor Attribute Register CRG + $42C - */ -#define TSI148_LCSR_LMAT_EN BIT(7) /* Enable Location Monitor */ - -#define TSI148_LCSR_LMAT_AS_M (7 << 4) /* Address Space MASK */ -#define TSI148_LCSR_LMAT_AS_A16 (0 << 4) /* A16 */ -#define TSI148_LCSR_LMAT_AS_A24 BIT(4) /* A24 */ -#define TSI148_LCSR_LMAT_AS_A32 (2 << 4) /* A32 */ -#define TSI148_LCSR_LMAT_AS_A64 (4 << 4) /* A64 */ - -#define TSI148_LCSR_LMAT_SUPR BIT(3) /* Supervisor Access */ -#define TSI148_LCSR_LMAT_NPRIV BIT(2) /* Non-Priv (User) Access */ -#define TSI148_LCSR_LMAT_PGM BIT(1) /* Program Access */ -#define TSI148_LCSR_LMAT_DATA BIT(0) /* Data Access */ - -/* - * Broadcast Pulse Generator Timer Register CRG + $438 - */ -#define TSI148_LCSR_BPGTR_BPGT_M (0xFFFF << 0) /* Mask */ - -/* - * Broadcast Programmable Clock Timer Register CRG + $43C - */ -#define TSI148_LCSR_BPCTR_BPCT_M (0xFFFFFF << 0) /* Mask */ - -/* - * VMEbus Interrupt Control Register CRG + $43C - */ -#define TSI148_LCSR_VICR_CNTS_M (3 << 22) /* Cntr Source MASK */ -#define TSI148_LCSR_VICR_CNTS_DIS BIT(22) /* Cntr Disable */ -#define TSI148_LCSR_VICR_CNTS_IRQ1 (2 << 22) /* IRQ1 to Cntr */ -#define TSI148_LCSR_VICR_CNTS_IRQ2 (3 << 22) /* IRQ2 to Cntr */ - -#define TSI148_LCSR_VICR_EDGIS_M (3 << 20) /* Edge interrupt MASK */ -#define TSI148_LCSR_VICR_EDGIS_DIS BIT(20) /* Edge interrupt Disable */ -#define TSI148_LCSR_VICR_EDGIS_IRQ1 (2 << 20) /* IRQ1 to Edge */ -#define TSI148_LCSR_VICR_EDGIS_IRQ2 (3 << 20) /* IRQ2 to Edge */ - -#define TSI148_LCSR_VICR_IRQIF_M (3 << 18) /* IRQ1* Function MASK */ -#define TSI148_LCSR_VICR_IRQIF_NORM BIT(18) /* Normal */ -#define TSI148_LCSR_VICR_IRQIF_PULSE (2 << 18) /* Pulse Generator */ -#define TSI148_LCSR_VICR_IRQIF_PROG (3 << 18) /* Programmable Clock */ -#define TSI148_LCSR_VICR_IRQIF_1U (4 << 18) /* 1us Clock */ - -#define TSI148_LCSR_VICR_IRQ2F_M (3 << 16) /* IRQ2* Function MASK */ -#define TSI148_LCSR_VICR_IRQ2F_NORM BIT(16) /* Normal */ -#define TSI148_LCSR_VICR_IRQ2F_PULSE (2 << 16) /* Pulse Generator */ -#define TSI148_LCSR_VICR_IRQ2F_PROG (3 << 16) /* Programmable Clock */ -#define TSI148_LCSR_VICR_IRQ2F_1U (4 << 16) /* 1us Clock */ - -#define TSI148_LCSR_VICR_BIP BIT(15) /* Broadcast Interrupt Pulse */ - -#define TSI148_LCSR_VICR_IRQC BIT(12) /* VMEbus IRQ Clear */ -#define TSI148_LCSR_VICR_IRQS BIT(11) /* VMEbus IRQ Status */ - -#define TSI148_LCSR_VICR_IRQL_M (7 << 8) /* VMEbus SW IRQ Level Mask */ -#define TSI148_LCSR_VICR_IRQL_1 BIT(8) /* VMEbus SW IRQ Level 1 */ -#define TSI148_LCSR_VICR_IRQL_2 (2 << 8) /* VMEbus SW IRQ Level 2 */ -#define TSI148_LCSR_VICR_IRQL_3 (3 << 8) /* VMEbus SW IRQ Level 3 */ -#define TSI148_LCSR_VICR_IRQL_4 (4 << 8) /* VMEbus SW IRQ Level 4 */ -#define TSI148_LCSR_VICR_IRQL_5 (5 << 8) /* VMEbus SW IRQ Level 5 */ -#define TSI148_LCSR_VICR_IRQL_6 (6 << 8) /* VMEbus SW IRQ Level 6 */ -#define TSI148_LCSR_VICR_IRQL_7 (7 << 8) /* VMEbus SW IRQ Level 7 */ - -static const int TSI148_LCSR_VICR_IRQL[8] = { 0, TSI148_LCSR_VICR_IRQL_1, - TSI148_LCSR_VICR_IRQL_2, TSI148_LCSR_VICR_IRQL_3, - TSI148_LCSR_VICR_IRQL_4, TSI148_LCSR_VICR_IRQL_5, - TSI148_LCSR_VICR_IRQL_6, TSI148_LCSR_VICR_IRQL_7 }; - -#define TSI148_LCSR_VICR_STID_M (0xFF << 0) /* Status/ID Mask */ - -/* - * Interrupt Enable Register CRG + $440 - */ -#define TSI148_LCSR_INTEN_DMA1EN BIT(25) /* DMAC 1 */ -#define TSI148_LCSR_INTEN_DMA0EN BIT(24) /* DMAC 0 */ -#define TSI148_LCSR_INTEN_LM3EN BIT(23) /* Location Monitor 3 */ -#define TSI148_LCSR_INTEN_LM2EN BIT(22) /* Location Monitor 2 */ -#define TSI148_LCSR_INTEN_LM1EN BIT(21) /* Location Monitor 1 */ -#define TSI148_LCSR_INTEN_LM0EN BIT(20) /* Location Monitor 0 */ -#define TSI148_LCSR_INTEN_MB3EN BIT(19) /* Mail Box 3 */ -#define TSI148_LCSR_INTEN_MB2EN BIT(18) /* Mail Box 2 */ -#define TSI148_LCSR_INTEN_MB1EN BIT(17) /* Mail Box 1 */ -#define TSI148_LCSR_INTEN_MB0EN BIT(16) /* Mail Box 0 */ -#define TSI148_LCSR_INTEN_PERREN BIT(13) /* PCI/X Error */ -#define TSI148_LCSR_INTEN_VERREN BIT(12) /* VMEbus Error */ -#define TSI148_LCSR_INTEN_VIEEN BIT(11) /* VMEbus IRQ Edge */ -#define TSI148_LCSR_INTEN_IACKEN BIT(10) /* IACK */ -#define TSI148_LCSR_INTEN_SYSFLEN BIT(9) /* System Fail */ -#define TSI148_LCSR_INTEN_ACFLEN BIT(8) /* AC Fail */ -#define TSI148_LCSR_INTEN_IRQ7EN BIT(7) /* IRQ7 */ -#define TSI148_LCSR_INTEN_IRQ6EN BIT(6) /* IRQ6 */ -#define TSI148_LCSR_INTEN_IRQ5EN BIT(5) /* IRQ5 */ -#define TSI148_LCSR_INTEN_IRQ4EN BIT(4) /* IRQ4 */ -#define TSI148_LCSR_INTEN_IRQ3EN BIT(3) /* IRQ3 */ -#define TSI148_LCSR_INTEN_IRQ2EN BIT(2) /* IRQ2 */ -#define TSI148_LCSR_INTEN_IRQ1EN BIT(1) /* IRQ1 */ - -static const int TSI148_LCSR_INTEN_LMEN[4] = { TSI148_LCSR_INTEN_LM0EN, - TSI148_LCSR_INTEN_LM1EN, - TSI148_LCSR_INTEN_LM2EN, - TSI148_LCSR_INTEN_LM3EN }; - -static const int TSI148_LCSR_INTEN_IRQEN[7] = { TSI148_LCSR_INTEN_IRQ1EN, - TSI148_LCSR_INTEN_IRQ2EN, - TSI148_LCSR_INTEN_IRQ3EN, - TSI148_LCSR_INTEN_IRQ4EN, - TSI148_LCSR_INTEN_IRQ5EN, - TSI148_LCSR_INTEN_IRQ6EN, - TSI148_LCSR_INTEN_IRQ7EN }; - -/* - * Interrupt Enable Out Register CRG + $444 - */ -#define TSI148_LCSR_INTEO_DMA1EO BIT(25) /* DMAC 1 */ -#define TSI148_LCSR_INTEO_DMA0EO BIT(24) /* DMAC 0 */ -#define TSI148_LCSR_INTEO_LM3EO BIT(23) /* Loc Monitor 3 */ -#define TSI148_LCSR_INTEO_LM2EO BIT(22) /* Loc Monitor 2 */ -#define TSI148_LCSR_INTEO_LM1EO BIT(21) /* Loc Monitor 1 */ -#define TSI148_LCSR_INTEO_LM0EO BIT(20) /* Location Monitor 0 */ -#define TSI148_LCSR_INTEO_MB3EO BIT(19) /* Mail Box 3 */ -#define TSI148_LCSR_INTEO_MB2EO BIT(18) /* Mail Box 2 */ -#define TSI148_LCSR_INTEO_MB1EO BIT(17) /* Mail Box 1 */ -#define TSI148_LCSR_INTEO_MB0EO BIT(16) /* Mail Box 0 */ -#define TSI148_LCSR_INTEO_PERREO BIT(13) /* PCI/X Error */ -#define TSI148_LCSR_INTEO_VERREO BIT(12) /* VMEbus Error */ -#define TSI148_LCSR_INTEO_VIEEO BIT(11) /* VMEbus IRQ Edge */ -#define TSI148_LCSR_INTEO_IACKEO BIT(10) /* IACK */ -#define TSI148_LCSR_INTEO_SYSFLEO BIT(9) /* System Fail */ -#define TSI148_LCSR_INTEO_ACFLEO BIT(8) /* AC Fail */ -#define TSI148_LCSR_INTEO_IRQ7EO BIT(7) /* IRQ7 */ -#define TSI148_LCSR_INTEO_IRQ6EO BIT(6) /* IRQ6 */ -#define TSI148_LCSR_INTEO_IRQ5EO BIT(5) /* IRQ5 */ -#define TSI148_LCSR_INTEO_IRQ4EO BIT(4) /* IRQ4 */ -#define TSI148_LCSR_INTEO_IRQ3EO BIT(3) /* IRQ3 */ -#define TSI148_LCSR_INTEO_IRQ2EO BIT(2) /* IRQ2 */ -#define TSI148_LCSR_INTEO_IRQ1EO BIT(1) /* IRQ1 */ - -static const int TSI148_LCSR_INTEO_LMEO[4] = { TSI148_LCSR_INTEO_LM0EO, - TSI148_LCSR_INTEO_LM1EO, - TSI148_LCSR_INTEO_LM2EO, - TSI148_LCSR_INTEO_LM3EO }; - -static const int TSI148_LCSR_INTEO_IRQEO[7] = { TSI148_LCSR_INTEO_IRQ1EO, - TSI148_LCSR_INTEO_IRQ2EO, - TSI148_LCSR_INTEO_IRQ3EO, - TSI148_LCSR_INTEO_IRQ4EO, - TSI148_LCSR_INTEO_IRQ5EO, - TSI148_LCSR_INTEO_IRQ6EO, - TSI148_LCSR_INTEO_IRQ7EO }; - -/* - * Interrupt Status Register CRG + $448 - */ -#define TSI148_LCSR_INTS_DMA1S BIT(25) /* DMA 1 */ -#define TSI148_LCSR_INTS_DMA0S BIT(24) /* DMA 0 */ -#define TSI148_LCSR_INTS_LM3S BIT(23) /* Location Monitor 3 */ -#define TSI148_LCSR_INTS_LM2S BIT(22) /* Location Monitor 2 */ -#define TSI148_LCSR_INTS_LM1S BIT(21) /* Location Monitor 1 */ -#define TSI148_LCSR_INTS_LM0S BIT(20) /* Location Monitor 0 */ -#define TSI148_LCSR_INTS_MB3S BIT(19) /* Mail Box 3 */ -#define TSI148_LCSR_INTS_MB2S BIT(18) /* Mail Box 2 */ -#define TSI148_LCSR_INTS_MB1S BIT(17) /* Mail Box 1 */ -#define TSI148_LCSR_INTS_MB0S BIT(16) /* Mail Box 0 */ -#define TSI148_LCSR_INTS_PERRS BIT(13) /* PCI/X Error */ -#define TSI148_LCSR_INTS_VERRS BIT(12) /* VMEbus Error */ -#define TSI148_LCSR_INTS_VIES BIT(11) /* VMEbus IRQ Edge */ -#define TSI148_LCSR_INTS_IACKS BIT(10) /* IACK */ -#define TSI148_LCSR_INTS_SYSFLS BIT(9) /* System Fail */ -#define TSI148_LCSR_INTS_ACFLS BIT(8) /* AC Fail */ -#define TSI148_LCSR_INTS_IRQ7S BIT(7) /* IRQ7 */ -#define TSI148_LCSR_INTS_IRQ6S BIT(6) /* IRQ6 */ -#define TSI148_LCSR_INTS_IRQ5S BIT(5) /* IRQ5 */ -#define TSI148_LCSR_INTS_IRQ4S BIT(4) /* IRQ4 */ -#define TSI148_LCSR_INTS_IRQ3S BIT(3) /* IRQ3 */ -#define TSI148_LCSR_INTS_IRQ2S BIT(2) /* IRQ2 */ -#define TSI148_LCSR_INTS_IRQ1S BIT(1) /* IRQ1 */ - -static const int TSI148_LCSR_INTS_LMS[4] = { TSI148_LCSR_INTS_LM0S, - TSI148_LCSR_INTS_LM1S, - TSI148_LCSR_INTS_LM2S, - TSI148_LCSR_INTS_LM3S }; - -static const int TSI148_LCSR_INTS_MBS[4] = { TSI148_LCSR_INTS_MB0S, - TSI148_LCSR_INTS_MB1S, - TSI148_LCSR_INTS_MB2S, - TSI148_LCSR_INTS_MB3S }; - -/* - * Interrupt Clear Register CRG + $44C - */ -#define TSI148_LCSR_INTC_DMA1C BIT(25) /* DMA 1 */ -#define TSI148_LCSR_INTC_DMA0C BIT(24) /* DMA 0 */ -#define TSI148_LCSR_INTC_LM3C BIT(23) /* Location Monitor 3 */ -#define TSI148_LCSR_INTC_LM2C BIT(22) /* Location Monitor 2 */ -#define TSI148_LCSR_INTC_LM1C BIT(21) /* Location Monitor 1 */ -#define TSI148_LCSR_INTC_LM0C BIT(20) /* Location Monitor 0 */ -#define TSI148_LCSR_INTC_MB3C BIT(19) /* Mail Box 3 */ -#define TSI148_LCSR_INTC_MB2C BIT(18) /* Mail Box 2 */ -#define TSI148_LCSR_INTC_MB1C BIT(17) /* Mail Box 1 */ -#define TSI148_LCSR_INTC_MB0C BIT(16) /* Mail Box 0 */ -#define TSI148_LCSR_INTC_PERRC BIT(13) /* VMEbus Error */ -#define TSI148_LCSR_INTC_VERRC BIT(12) /* VMEbus Access Time-out */ -#define TSI148_LCSR_INTC_VIEC BIT(11) /* VMEbus IRQ Edge */ -#define TSI148_LCSR_INTC_IACKC BIT(10) /* IACK */ -#define TSI148_LCSR_INTC_SYSFLC BIT(9) /* System Fail */ -#define TSI148_LCSR_INTC_ACFLC BIT(8) /* AC Fail */ - -static const int TSI148_LCSR_INTC_LMC[4] = { TSI148_LCSR_INTC_LM0C, - TSI148_LCSR_INTC_LM1C, - TSI148_LCSR_INTC_LM2C, - TSI148_LCSR_INTC_LM3C }; - -static const int TSI148_LCSR_INTC_MBC[4] = { TSI148_LCSR_INTC_MB0C, - TSI148_LCSR_INTC_MB1C, - TSI148_LCSR_INTC_MB2C, - TSI148_LCSR_INTC_MB3C }; - -/* - * Interrupt Map Register 1 CRG + $458 - */ -#define TSI148_LCSR_INTM1_DMA1M_M (3 << 18) /* DMA 1 */ -#define TSI148_LCSR_INTM1_DMA0M_M (3 << 16) /* DMA 0 */ -#define TSI148_LCSR_INTM1_LM3M_M (3 << 14) /* Location Monitor 3 */ -#define TSI148_LCSR_INTM1_LM2M_M (3 << 12) /* Location Monitor 2 */ -#define TSI148_LCSR_INTM1_LM1M_M (3 << 10) /* Location Monitor 1 */ -#define TSI148_LCSR_INTM1_LM0M_M (3 << 8) /* Location Monitor 0 */ -#define TSI148_LCSR_INTM1_MB3M_M (3 << 6) /* Mail Box 3 */ -#define TSI148_LCSR_INTM1_MB2M_M (3 << 4) /* Mail Box 2 */ -#define TSI148_LCSR_INTM1_MB1M_M (3 << 2) /* Mail Box 1 */ -#define TSI148_LCSR_INTM1_MB0M_M (3 << 0) /* Mail Box 0 */ - -/* - * Interrupt Map Register 2 CRG + $45C - */ -#define TSI148_LCSR_INTM2_PERRM_M (3 << 26) /* PCI Bus Error */ -#define TSI148_LCSR_INTM2_VERRM_M (3 << 24) /* VMEbus Error */ -#define TSI148_LCSR_INTM2_VIEM_M (3 << 22) /* VMEbus IRQ Edge */ -#define TSI148_LCSR_INTM2_IACKM_M (3 << 20) /* IACK */ -#define TSI148_LCSR_INTM2_SYSFLM_M (3 << 18) /* System Fail */ -#define TSI148_LCSR_INTM2_ACFLM_M (3 << 16) /* AC Fail */ -#define TSI148_LCSR_INTM2_IRQ7M_M (3 << 14) /* IRQ7 */ -#define TSI148_LCSR_INTM2_IRQ6M_M (3 << 12) /* IRQ6 */ -#define TSI148_LCSR_INTM2_IRQ5M_M (3 << 10) /* IRQ5 */ -#define TSI148_LCSR_INTM2_IRQ4M_M (3 << 8) /* IRQ4 */ -#define TSI148_LCSR_INTM2_IRQ3M_M (3 << 6) /* IRQ3 */ -#define TSI148_LCSR_INTM2_IRQ2M_M (3 << 4) /* IRQ2 */ -#define TSI148_LCSR_INTM2_IRQ1M_M (3 << 2) /* IRQ1 */ - -/* - * DMA Control (0-1) Registers CRG + $500 - */ -#define TSI148_LCSR_DCTL_ABT BIT(27) /* Abort */ -#define TSI148_LCSR_DCTL_PAU BIT(26) /* Pause */ -#define TSI148_LCSR_DCTL_DGO BIT(25) /* DMA Go */ - -#define TSI148_LCSR_DCTL_MOD BIT(23) /* Mode */ - -#define TSI148_LCSR_DCTL_VBKS_M (7 << 12) /* VMEbus block Size MASK */ -#define TSI148_LCSR_DCTL_VBKS_32 (0 << 12) /* VMEbus block Size 32 */ -#define TSI148_LCSR_DCTL_VBKS_64 BIT(12) /* VMEbus block Size 64 */ -#define TSI148_LCSR_DCTL_VBKS_128 (2 << 12) /* VMEbus block Size 128 */ -#define TSI148_LCSR_DCTL_VBKS_256 (3 << 12) /* VMEbus block Size 256 */ -#define TSI148_LCSR_DCTL_VBKS_512 (4 << 12) /* VMEbus block Size 512 */ -#define TSI148_LCSR_DCTL_VBKS_1024 (5 << 12) /* VMEbus block Size 1024 */ -#define TSI148_LCSR_DCTL_VBKS_2048 (6 << 12) /* VMEbus block Size 2048 */ -#define TSI148_LCSR_DCTL_VBKS_4096 (7 << 12) /* VMEbus block Size 4096 */ - -#define TSI148_LCSR_DCTL_VBOT_M (7 << 8) /* VMEbus back-off MASK */ -#define TSI148_LCSR_DCTL_VBOT_0 (0 << 8) /* VMEbus back-off 0us */ -#define TSI148_LCSR_DCTL_VBOT_1 BIT(8) /* VMEbus back-off 1us */ -#define TSI148_LCSR_DCTL_VBOT_2 (2 << 8) /* VMEbus back-off 2us */ -#define TSI148_LCSR_DCTL_VBOT_4 (3 << 8) /* VMEbus back-off 4us */ -#define TSI148_LCSR_DCTL_VBOT_8 (4 << 8) /* VMEbus back-off 8us */ -#define TSI148_LCSR_DCTL_VBOT_16 (5 << 8) /* VMEbus back-off 16us */ -#define TSI148_LCSR_DCTL_VBOT_32 (6 << 8) /* VMEbus back-off 32us */ -#define TSI148_LCSR_DCTL_VBOT_64 (7 << 8) /* VMEbus back-off 64us */ - -#define TSI148_LCSR_DCTL_PBKS_M (7 << 4) /* PCI block size MASK */ -#define TSI148_LCSR_DCTL_PBKS_32 (0 << 4) /* PCI block size 32 bytes */ -#define TSI148_LCSR_DCTL_PBKS_64 BIT(4) /* PCI block size 64 bytes */ -#define TSI148_LCSR_DCTL_PBKS_128 (2 << 4) /* PCI block size 128 bytes */ -#define TSI148_LCSR_DCTL_PBKS_256 (3 << 4) /* PCI block size 256 bytes */ -#define TSI148_LCSR_DCTL_PBKS_512 (4 << 4) /* PCI block size 512 bytes */ -#define TSI148_LCSR_DCTL_PBKS_1024 (5 << 4) /* PCI block size 1024 bytes */ -#define TSI148_LCSR_DCTL_PBKS_2048 (6 << 4) /* PCI block size 2048 bytes */ -#define TSI148_LCSR_DCTL_PBKS_4096 (7 << 4) /* PCI block size 4096 bytes */ - -#define TSI148_LCSR_DCTL_PBOT_M (7 << 0) /* PCI back off MASK */ -#define TSI148_LCSR_DCTL_PBOT_0 (0 << 0) /* PCI back off 0us */ -#define TSI148_LCSR_DCTL_PBOT_1 BIT(0) /* PCI back off 1us */ -#define TSI148_LCSR_DCTL_PBOT_2 (2 << 0) /* PCI back off 2us */ -#define TSI148_LCSR_DCTL_PBOT_4 (3 << 0) /* PCI back off 3us */ -#define TSI148_LCSR_DCTL_PBOT_8 (4 << 0) /* PCI back off 4us */ -#define TSI148_LCSR_DCTL_PBOT_16 (5 << 0) /* PCI back off 8us */ -#define TSI148_LCSR_DCTL_PBOT_32 (6 << 0) /* PCI back off 16us */ -#define TSI148_LCSR_DCTL_PBOT_64 (7 << 0) /* PCI back off 32us */ - -/* - * DMA Status Registers (0-1) CRG + $504 - */ -#define TSI148_LCSR_DSTA_SMA BIT(31) /* PCI Signalled Master Abt */ -#define TSI148_LCSR_DSTA_RTA BIT(30) /* PCI Received Target Abt */ -#define TSI148_LCSR_DSTA_MRC BIT(29) /* PCI Max Retry Count */ -#define TSI148_LCSR_DSTA_VBE BIT(28) /* VMEbus error */ -#define TSI148_LCSR_DSTA_ABT BIT(27) /* Abort */ -#define TSI148_LCSR_DSTA_PAU BIT(26) /* Pause */ -#define TSI148_LCSR_DSTA_DON BIT(25) /* Done */ -#define TSI148_LCSR_DSTA_BSY BIT(24) /* Busy */ - -/* - * DMA Current Link Address Lower (0-1) - */ -#define TSI148_LCSR_DCLAL_M (0x3FFFFFF << 6) /* Mask */ - -/* - * DMA Source Attribute (0-1) Reg - */ -#define TSI148_LCSR_DSAT_TYP_M (3 << 28) /* Source Bus Type */ -#define TSI148_LCSR_DSAT_TYP_PCI (0 << 28) /* PCI Bus */ -#define TSI148_LCSR_DSAT_TYP_VME BIT(28) /* VMEbus */ -#define TSI148_LCSR_DSAT_TYP_PAT (2 << 28) /* Data Pattern */ - -#define TSI148_LCSR_DSAT_PSZ BIT(25) /* Pattern Size */ -#define TSI148_LCSR_DSAT_NIN BIT(24) /* No Increment */ - -#define TSI148_LCSR_DSAT_2eSSTM_M (3 << 11) /* 2eSST Trans Rate Mask */ -#define TSI148_LCSR_DSAT_2eSSTM_160 (0 << 11) /* 160 MB/s */ -#define TSI148_LCSR_DSAT_2eSSTM_267 BIT(11) /* 267 MB/s */ -#define TSI148_LCSR_DSAT_2eSSTM_320 (2 << 11) /* 320 MB/s */ - -#define TSI148_LCSR_DSAT_TM_M (7 << 8) /* Bus Transfer Protocol Mask */ -#define TSI148_LCSR_DSAT_TM_SCT (0 << 8) /* SCT */ -#define TSI148_LCSR_DSAT_TM_BLT BIT(8) /* BLT */ -#define TSI148_LCSR_DSAT_TM_MBLT (2 << 8) /* MBLT */ -#define TSI148_LCSR_DSAT_TM_2eVME (3 << 8) /* 2eVME */ -#define TSI148_LCSR_DSAT_TM_2eSST (4 << 8) /* 2eSST */ -#define TSI148_LCSR_DSAT_TM_2eSSTB (5 << 8) /* 2eSST Broadcast */ - -#define TSI148_LCSR_DSAT_DBW_M (3 << 6) /* Max Data Width MASK */ -#define TSI148_LCSR_DSAT_DBW_16 (0 << 6) /* 16 Bits */ -#define TSI148_LCSR_DSAT_DBW_32 BIT(6) /* 32 Bits */ - -#define TSI148_LCSR_DSAT_SUP BIT(5) /* Supervisory Mode */ -#define TSI148_LCSR_DSAT_PGM BIT(4) /* Program Mode */ - -#define TSI148_LCSR_DSAT_AMODE_M (0xf << 0) /* Address Space Mask */ -#define TSI148_LCSR_DSAT_AMODE_A16 (0 << 0) /* A16 */ -#define TSI148_LCSR_DSAT_AMODE_A24 BIT(0) /* A24 */ -#define TSI148_LCSR_DSAT_AMODE_A32 (2 << 0) /* A32 */ -#define TSI148_LCSR_DSAT_AMODE_A64 (4 << 0) /* A64 */ -#define TSI148_LCSR_DSAT_AMODE_CRCSR (5 << 0) /* CR/CSR */ -#define TSI148_LCSR_DSAT_AMODE_USER1 (8 << 0) /* User1 */ -#define TSI148_LCSR_DSAT_AMODE_USER2 (9 << 0) /* User2 */ -#define TSI148_LCSR_DSAT_AMODE_USER3 (0xa << 0) /* User3 */ -#define TSI148_LCSR_DSAT_AMODE_USER4 (0xb << 0) /* User4 */ - -/* - * DMA Destination Attribute Registers (0-1) - */ -#define TSI148_LCSR_DDAT_TYP_PCI (0 << 28) /* Destination PCI Bus */ -#define TSI148_LCSR_DDAT_TYP_VME BIT(28) /* Destination VMEbus */ - -#define TSI148_LCSR_DDAT_2eSSTM_M (3 << 11) /* 2eSST Transfer Rate Mask */ -#define TSI148_LCSR_DDAT_2eSSTM_160 (0 << 11) /* 160 MB/s */ -#define TSI148_LCSR_DDAT_2eSSTM_267 BIT(11) /* 267 MB/s */ -#define TSI148_LCSR_DDAT_2eSSTM_320 (2 << 11) /* 320 MB/s */ - -#define TSI148_LCSR_DDAT_TM_M (7 << 8) /* Bus Transfer Protocol Mask */ -#define TSI148_LCSR_DDAT_TM_SCT (0 << 8) /* SCT */ -#define TSI148_LCSR_DDAT_TM_BLT BIT(8) /* BLT */ -#define TSI148_LCSR_DDAT_TM_MBLT (2 << 8) /* MBLT */ -#define TSI148_LCSR_DDAT_TM_2eVME (3 << 8) /* 2eVME */ -#define TSI148_LCSR_DDAT_TM_2eSST (4 << 8) /* 2eSST */ -#define TSI148_LCSR_DDAT_TM_2eSSTB (5 << 8) /* 2eSST Broadcast */ - -#define TSI148_LCSR_DDAT_DBW_M (3 << 6) /* Max Data Width MASK */ -#define TSI148_LCSR_DDAT_DBW_16 (0 << 6) /* 16 Bits */ -#define TSI148_LCSR_DDAT_DBW_32 BIT(6) /* 32 Bits */ - -#define TSI148_LCSR_DDAT_SUP BIT(5) /* Supervisory/User Access */ -#define TSI148_LCSR_DDAT_PGM BIT(4) /* Program/Data Access */ - -#define TSI148_LCSR_DDAT_AMODE_M (0xf << 0) /* Address Space Mask */ -#define TSI148_LCSR_DDAT_AMODE_A16 (0 << 0) /* A16 */ -#define TSI148_LCSR_DDAT_AMODE_A24 BIT(0) /* A24 */ -#define TSI148_LCSR_DDAT_AMODE_A32 (2 << 0) /* A32 */ -#define TSI148_LCSR_DDAT_AMODE_A64 (4 << 0) /* A64 */ -#define TSI148_LCSR_DDAT_AMODE_CRCSR (5 << 0) /* CRC/SR */ -#define TSI148_LCSR_DDAT_AMODE_USER1 (8 << 0) /* User1 */ -#define TSI148_LCSR_DDAT_AMODE_USER2 (9 << 0) /* User2 */ -#define TSI148_LCSR_DDAT_AMODE_USER3 (0xa << 0) /* User3 */ -#define TSI148_LCSR_DDAT_AMODE_USER4 (0xb << 0) /* User4 */ - -/* - * DMA Next Link Address Lower - */ -#define TSI148_LCSR_DNLAL_DNLAL_M (0x3FFFFFF << 6) /* Address Mask */ -#define TSI148_LCSR_DNLAL_LLA BIT(0) /* Last Link Address Indicator */ - -/* - * DMA 2eSST Broadcast Select - */ -#define TSI148_LCSR_DBS_M (0x1FFFFF << 0) /* Mask */ - -/* - * GCSR Register Group - */ - -/* - * GCSR Control and Status Register CRG + $604 - */ -#define TSI148_GCSR_GCTRL_LRST BIT(15) /* Local Reset */ -#define TSI148_GCSR_GCTRL_SFAILEN BIT(14) /* System Fail enable */ -#define TSI148_GCSR_GCTRL_BDFAILS BIT(13) /* Board Fail Status */ -#define TSI148_GCSR_GCTRL_SCON BIT(12) /* System Controller */ -#define TSI148_GCSR_GCTRL_MEN BIT(11) /* Module Enable (READY) */ - -#define TSI148_GCSR_GCTRL_LMI3S BIT(7) /* Loc Monitor 3 Int Status */ -#define TSI148_GCSR_GCTRL_LMI2S BIT(6) /* Loc Monitor 2 Int Status */ -#define TSI148_GCSR_GCTRL_LMI1S BIT(5) /* Loc Monitor 1 Int Status */ -#define TSI148_GCSR_GCTRL_LMI0S BIT(4) /* Loc Monitor 0 Int Status */ -#define TSI148_GCSR_GCTRL_MBI3S BIT(3) /* Mail box 3 Int Status */ -#define TSI148_GCSR_GCTRL_MBI2S BIT(2) /* Mail box 2 Int Status */ -#define TSI148_GCSR_GCTRL_MBI1S BIT(1) /* Mail box 1 Int Status */ -#define TSI148_GCSR_GCTRL_MBI0S BIT(0) /* Mail box 0 Int Status */ - -#define TSI148_GCSR_GAP BIT(5) /* Geographic Addr Parity */ -#define TSI148_GCSR_GA_M (0x1F << 0) /* Geographic Address Mask */ - -/* - * CR/CSR Register Group - */ - -/* - * CR/CSR Bit Clear Register CRG + $FF4 - */ -#define TSI148_CRCSR_CSRBCR_LRSTC BIT(7) /* Local Reset Clear */ -#define TSI148_CRCSR_CSRBCR_SFAILC BIT(6) /* System Fail Enable Clear */ -#define TSI148_CRCSR_CSRBCR_BDFAILS BIT(5) /* Board Fail Status */ -#define TSI148_CRCSR_CSRBCR_MENC BIT(4) /* Module Enable Clear */ -#define TSI148_CRCSR_CSRBCR_BERRSC BIT(3) /* Bus Error Status Clear */ - -/* - * CR/CSR Bit Set Register CRG+$FF8 - */ -#define TSI148_CRCSR_CSRBSR_LISTS BIT(7) /* Local Reset Clear */ -#define TSI148_CRCSR_CSRBSR_SFAILS BIT(6) /* System Fail Enable Clear */ -#define TSI148_CRCSR_CSRBSR_BDFAILS BIT(5) /* Board Fail Status */ -#define TSI148_CRCSR_CSRBSR_MENS BIT(4) /* Module Enable Clear */ -#define TSI148_CRCSR_CSRBSR_BERRS BIT(3) /* Bus Error Status Clear */ - -/* - * CR/CSR Base Address Register CRG + FFC - */ -#define TSI148_CRCSR_CBAR_M (0x1F << 3) /* Mask */ - -#endif /* TSI148_H */ diff --git a/drivers/staging/vme_user/vme_user.c b/drivers/staging/vme_user/vme_user.c deleted file mode 100644 index a472a38ef613a6..00000000000000 --- a/drivers/staging/vme_user/vme_user.c +++ /dev/null @@ -1,812 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0+ -/* - * VMEbus User access driver - * - * Author: Martyn Welch - * Copyright 2008 GE Intelligent Platforms Embedded Systems, Inc. - * - * Based on work by: - * Tom Armistead and Ajit Prem - * Copyright 2004 Motorola Inc. - */ - -#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "vme.h" -#include "vme_user.h" - -#define DRIVER_NAME "vme_user" - -static int bus[VME_USER_BUS_MAX]; -static unsigned int bus_num; - -/* Currently Documentation/admin-guide/devices.rst defines the - * following for VME: - * - * 221 char VME bus - * 0 = /dev/bus/vme/m0 First master image - * 1 = /dev/bus/vme/m1 Second master image - * 2 = /dev/bus/vme/m2 Third master image - * 3 = /dev/bus/vme/m3 Fourth master image - * 4 = /dev/bus/vme/s0 First slave image - * 5 = /dev/bus/vme/s1 Second slave image - * 6 = /dev/bus/vme/s2 Third slave image - * 7 = /dev/bus/vme/s3 Fourth slave image - * 8 = /dev/bus/vme/ctl Control - * - * It is expected that all VME bus drivers will use the - * same interface. For interface documentation see - * http://www.vmelinux.org/. - * - * However the VME driver at http://www.vmelinux.org/ is rather old and doesn't - * even support the tsi148 chipset (which has 8 master and 8 slave windows). - * We'll run with this for now as far as possible, however it probably makes - * sense to get rid of the old mappings and just do everything dynamically. - * - * So for now, we'll restrict the driver to providing 4 masters and 4 slaves as - * defined above and try to support at least some of the interface from - * http://www.vmelinux.org/ as an alternative the driver can be written - * providing a saner interface later. - * - * The vmelinux.org driver never supported slave images, the devices reserved - * for slaves were repurposed to support all 8 master images on the UniverseII! - * We shall support 4 masters and 4 slaves with this driver. - */ -#define VME_MAJOR 221 /* VME Major Device Number */ -#define VME_DEVS 9 /* Number of dev entries */ - -#define MASTER_MINOR 0 -#define MASTER_MAX 3 -#define SLAVE_MINOR 4 -#define SLAVE_MAX 7 -#define CONTROL_MINOR 8 - -#define PCI_BUF_SIZE 0x20000 /* Size of one slave image buffer */ - -/* - * Structure to handle image related parameters. - */ -struct image_desc { - void *kern_buf; /* Buffer address in kernel space */ - dma_addr_t pci_buf; /* Buffer address in PCI address space */ - unsigned long long size_buf; /* Buffer size */ - struct mutex mutex; /* Mutex for locking image */ - struct device *device; /* Sysfs device */ - struct vme_resource *resource; /* VME resource */ - int mmap_count; /* Number of current mmap's */ -}; - -static struct image_desc image[VME_DEVS]; - -static struct cdev *vme_user_cdev; /* Character device */ -static struct vme_dev *vme_user_bridge; /* Pointer to user device */ - -static const struct class vme_user_sysfs_class = { - .name = DRIVER_NAME, -}; - -static const int type[VME_DEVS] = { MASTER_MINOR, MASTER_MINOR, - MASTER_MINOR, MASTER_MINOR, - SLAVE_MINOR, SLAVE_MINOR, - SLAVE_MINOR, SLAVE_MINOR, - CONTROL_MINOR - }; - -struct vme_user_vma_priv { - unsigned int minor; - refcount_t refcnt; -}; - -static ssize_t resource_to_user(int minor, char __user *buf, size_t count, - loff_t *ppos) -{ - ssize_t copied = 0; - - if (count > image[minor].size_buf) - count = image[minor].size_buf; - - copied = vme_master_read(image[minor].resource, image[minor].kern_buf, - count, *ppos); - if (copied < 0) - return (int)copied; - - if (copy_to_user(buf, image[minor].kern_buf, (unsigned long)copied)) - return -EFAULT; - - return copied; -} - -static ssize_t resource_from_user(unsigned int minor, const char __user *buf, - size_t count, loff_t *ppos) -{ - if (count > image[minor].size_buf) - count = image[minor].size_buf; - - if (copy_from_user(image[minor].kern_buf, buf, (unsigned long)count)) - return -EFAULT; - - return vme_master_write(image[minor].resource, image[minor].kern_buf, - count, *ppos); -} - -static ssize_t buffer_to_user(unsigned int minor, char __user *buf, - size_t count, loff_t *ppos) -{ - void *image_ptr; - - /* - * The slave window (image_size) can exceed the fixed kern_buf - * (size_buf == PCI_BUF_SIZE), so bound the copy to kern_buf. - * *ppos is >= 0 here (checked by the caller), so the - * subtraction below cannot wrap. - */ - if (*ppos >= image[minor].size_buf) - return 0; - if (count > image[minor].size_buf - *ppos) - count = image[minor].size_buf - *ppos; - - image_ptr = image[minor].kern_buf + *ppos; - if (copy_to_user(buf, image_ptr, (unsigned long)count)) - return -EFAULT; - - return count; -} - -static ssize_t buffer_from_user(unsigned int minor, const char __user *buf, - size_t count, loff_t *ppos) -{ - void *image_ptr; - - /* - * The slave window (image_size) can exceed the fixed kern_buf - * (size_buf == PCI_BUF_SIZE), so bound the copy to kern_buf. - * *ppos is >= 0 here (checked by the caller), so the - * subtraction below cannot wrap. - */ - if (*ppos >= image[minor].size_buf) - return 0; - if (count > image[minor].size_buf - *ppos) - count = image[minor].size_buf - *ppos; - - image_ptr = image[minor].kern_buf + *ppos; - if (copy_from_user(image_ptr, buf, (unsigned long)count)) - return -EFAULT; - - return count; -} - -static ssize_t vme_user_read(struct file *file, char __user *buf, size_t count, - loff_t *ppos) -{ - unsigned int minor = iminor(file_inode(file)); - ssize_t retval; - size_t image_size; - - if (minor == CONTROL_MINOR) - return 0; - - mutex_lock(&image[minor].mutex); - - /* XXX Do we *really* want this helper - we can use vme_*_get ? */ - image_size = vme_get_size(image[minor].resource); - - /* Ensure we are starting at a valid location */ - if ((*ppos < 0) || (*ppos > (image_size - 1))) { - mutex_unlock(&image[minor].mutex); - return 0; - } - - /* Ensure not reading past end of the image */ - if (*ppos + count > image_size) - count = image_size - *ppos; - - switch (type[minor]) { - case MASTER_MINOR: - retval = resource_to_user(minor, buf, count, ppos); - break; - case SLAVE_MINOR: - retval = buffer_to_user(minor, buf, count, ppos); - break; - default: - retval = -EINVAL; - } - - mutex_unlock(&image[minor].mutex); - if (retval > 0) - *ppos += retval; - - return retval; -} - -static ssize_t vme_user_write(struct file *file, const char __user *buf, - size_t count, loff_t *ppos) -{ - unsigned int minor = iminor(file_inode(file)); - ssize_t retval; - size_t image_size; - - if (minor == CONTROL_MINOR) - return 0; - - mutex_lock(&image[minor].mutex); - - image_size = vme_get_size(image[minor].resource); - - /* Ensure we are starting at a valid location */ - if ((*ppos < 0) || (*ppos > (image_size - 1))) { - mutex_unlock(&image[minor].mutex); - return 0; - } - - /* Ensure not reading past end of the image */ - if (*ppos + count > image_size) - count = image_size - *ppos; - - switch (type[minor]) { - case MASTER_MINOR: - retval = resource_from_user(minor, buf, count, ppos); - break; - case SLAVE_MINOR: - retval = buffer_from_user(minor, buf, count, ppos); - break; - default: - retval = -EINVAL; - } - - mutex_unlock(&image[minor].mutex); - - if (retval > 0) - *ppos += retval; - - return retval; -} - -static loff_t vme_user_llseek(struct file *file, loff_t off, int whence) -{ - unsigned int minor = iminor(file_inode(file)); - size_t image_size; - loff_t res; - - switch (type[minor]) { - case MASTER_MINOR: - case SLAVE_MINOR: - mutex_lock(&image[minor].mutex); - image_size = vme_get_size(image[minor].resource); - res = fixed_size_llseek(file, off, whence, image_size); - mutex_unlock(&image[minor].mutex); - return res; - } - - return -EINVAL; -} - -/* - * The ioctls provided by the old VME access method (the one at vmelinux.org) - * are most certainly wrong as the effectively push the registers layout - * through to user space. Given that the VME core can handle multiple bridges, - * with different register layouts this is most certainly not the way to go. - * - * We aren't using the structures defined in the Motorola driver either - these - * are also quite low level, however we should use the definitions that have - * already been defined. - */ -static int vme_user_ioctl(struct inode *inode, struct file *file, - unsigned int cmd, unsigned long arg) -{ - struct vme_master master; - struct vme_slave slave; - struct vme_irq_id irq_req; - unsigned long copied; - unsigned int minor = iminor(inode); - int retval; - dma_addr_t pci_addr; - void __user *argp = (void __user *)arg; - - switch (type[minor]) { - case CONTROL_MINOR: - switch (cmd) { - case VME_IRQ_GEN: - copied = copy_from_user(&irq_req, argp, - sizeof(irq_req)); - if (copied) { - pr_warn("Partial copy from userspace\n"); - return -EFAULT; - } - - return vme_irq_generate(vme_user_bridge, - irq_req.level, - irq_req.statid); - } - break; - case MASTER_MINOR: - switch (cmd) { - case VME_GET_MASTER: - memset(&master, 0, sizeof(master)); - - /* XXX We do not want to push aspace, cycle and width - * to userspace as they are - */ - retval = vme_master_get(image[minor].resource, - &master.enable, - &master.vme_addr, - &master.size, &master.aspace, - &master.cycle, &master.dwidth); - - copied = copy_to_user(argp, &master, - sizeof(master)); - if (copied) { - pr_warn("Partial copy to userspace\n"); - return -EFAULT; - } - - return retval; - - case VME_SET_MASTER: - - if (image[minor].mmap_count != 0) { - pr_warn("Can't adjust mapped window\n"); - return -EPERM; - } - - copied = copy_from_user(&master, argp, sizeof(master)); - if (copied) { - pr_warn("Partial copy from userspace\n"); - return -EFAULT; - } - - /* XXX We do not want to push aspace, cycle and width - * to userspace as they are - */ - return vme_master_set(image[minor].resource, - master.enable, master.vme_addr, master.size, - master.aspace, master.cycle, master.dwidth); - - break; - } - break; - case SLAVE_MINOR: - switch (cmd) { - case VME_GET_SLAVE: - memset(&slave, 0, sizeof(slave)); - - /* XXX We do not want to push aspace, cycle and width - * to userspace as they are - */ - retval = vme_slave_get(image[minor].resource, - &slave.enable, &slave.vme_addr, - &slave.size, &pci_addr, - &slave.aspace, &slave.cycle); - - copied = copy_to_user(argp, &slave, - sizeof(slave)); - if (copied) { - pr_warn("Partial copy to userspace\n"); - return -EFAULT; - } - - return retval; - - case VME_SET_SLAVE: - - copied = copy_from_user(&slave, argp, sizeof(slave)); - if (copied) { - pr_warn("Partial copy from userspace\n"); - return -EFAULT; - } - - /* XXX We do not want to push aspace, cycle and width - * to userspace as they are - */ - return vme_slave_set(image[minor].resource, - slave.enable, slave.vme_addr, slave.size, - image[minor].pci_buf, slave.aspace, - slave.cycle); - - break; - } - break; - } - - return -EINVAL; -} - -static long -vme_user_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg) -{ - int ret; - struct inode *inode = file_inode(file); - unsigned int minor = iminor(inode); - - mutex_lock(&image[minor].mutex); - ret = vme_user_ioctl(inode, file, cmd, arg); - mutex_unlock(&image[minor].mutex); - - return ret; -} - -static void vme_user_vm_open(struct vm_area_struct *vma) -{ - struct vme_user_vma_priv *vma_priv = vma->vm_private_data; - - refcount_inc(&vma_priv->refcnt); -} - -static void vme_user_vm_close(struct vm_area_struct *vma) -{ - struct vme_user_vma_priv *vma_priv = vma->vm_private_data; - unsigned int minor = vma_priv->minor; - - if (!refcount_dec_and_test(&vma_priv->refcnt)) - return; - - mutex_lock(&image[minor].mutex); - image[minor].mmap_count--; - mutex_unlock(&image[minor].mutex); - - kfree(vma_priv); -} - -static int vme_user_vm_mapped(unsigned long start, unsigned long end, pgoff_t pgoff, - const struct file *file, void **vm_private_data) -{ - const unsigned int minor = iminor(file_inode(file)); - struct vme_user_vma_priv *vma_priv; - - mutex_lock(&image[minor].mutex); - - vma_priv = kmalloc_obj(*vma_priv); - if (!vma_priv) { - mutex_unlock(&image[minor].mutex); - return -ENOMEM; - } - - vma_priv->minor = minor; - refcount_set(&vma_priv->refcnt, 1); - *vm_private_data = vma_priv; - image[minor].mmap_count++; - - mutex_unlock(&image[minor].mutex); - return 0; -} - -static const struct vm_operations_struct vme_user_vm_ops = { - .mapped = vme_user_vm_mapped, - .open = vme_user_vm_open, - .close = vme_user_vm_close, -}; - -static int vme_user_master_mmap_prepare(unsigned int minor, - struct vm_area_desc *desc) -{ - int err; - - mutex_lock(&image[minor].mutex); - - err = vme_master_mmap_prepare(image[minor].resource, desc); - if (!err) - desc->vm_ops = &vme_user_vm_ops; - - mutex_unlock(&image[minor].mutex); - return err; -} - -static int vme_user_mmap_prepare(struct vm_area_desc *desc) -{ - const struct file *file = desc->file; - const unsigned int minor = iminor(file_inode(file)); - - if (type[minor] == MASTER_MINOR) - return vme_user_master_mmap_prepare(minor, desc); - - return -ENODEV; -} - -static const struct file_operations vme_user_fops = { - .read = vme_user_read, - .write = vme_user_write, - .llseek = vme_user_llseek, - .unlocked_ioctl = vme_user_unlocked_ioctl, - .compat_ioctl = compat_ptr_ioctl, - .mmap_prepare = vme_user_mmap_prepare, -}; - -static int vme_user_match(struct vme_dev *vdev) -{ - int i; - - int cur_bus = vme_bus_num(vdev); - int cur_slot = vme_slot_num(vdev); - - for (i = 0; i < bus_num; i++) - if ((cur_bus == bus[i]) && (cur_slot == vdev->num)) - return 1; - - return 0; -} - -/* - * In this simple access driver, the old behaviour is being preserved as much - * as practical. We will therefore reserve the buffers and request the images - * here so that we don't have to do it later. - */ -static int vme_user_probe(struct vme_dev *vdev) -{ - int i, err; - char *name; - - /* Save pointer to the bridge device */ - if (vme_user_bridge) { - dev_err(&vdev->dev, "Driver can only be loaded for 1 device\n"); - err = -EINVAL; - goto err_dev; - } - vme_user_bridge = vdev; - - /* Initialise descriptors */ - for (i = 0; i < VME_DEVS; i++) { - image[i].kern_buf = NULL; - image[i].pci_buf = 0; - mutex_init(&image[i].mutex); - image[i].device = NULL; - image[i].resource = NULL; - } - - /* Assign major and minor numbers for the driver */ - err = register_chrdev_region(MKDEV(VME_MAJOR, 0), VME_DEVS, DRIVER_NAME); - if (err) { - dev_warn(&vdev->dev, "Error getting Major Number %d for driver.\n", - VME_MAJOR); - goto err_region; - } - - /* Register the driver as a char device */ - vme_user_cdev = cdev_alloc(); - if (!vme_user_cdev) { - err = -ENOMEM; - goto err_char; - } - vme_user_cdev->ops = &vme_user_fops; - vme_user_cdev->owner = THIS_MODULE; - err = cdev_add(vme_user_cdev, MKDEV(VME_MAJOR, 0), VME_DEVS); - if (err) - goto err_class; - - /* Request slave resources and allocate buffers (128kB wide) */ - for (i = SLAVE_MINOR; i < (SLAVE_MAX + 1); i++) { - /* XXX Need to properly request attributes */ - /* For ca91cx42 bridge there are only two slave windows - * supporting A16 addressing, so we request A24 supported - * by all windows. - */ - image[i].resource = vme_slave_request(vme_user_bridge, - VME_A24, VME_SCT); - if (!image[i].resource) { - dev_warn(&vdev->dev, - "Unable to allocate slave resource\n"); - err = -ENOMEM; - goto err_slave; - } - image[i].size_buf = PCI_BUF_SIZE; - image[i].kern_buf = vme_alloc_consistent(image[i].resource, - image[i].size_buf, - &image[i].pci_buf); - if (!image[i].kern_buf) { - dev_warn(&vdev->dev, - "Unable to allocate memory for buffer\n"); - image[i].pci_buf = 0; - vme_slave_free(image[i].resource); - err = -ENOMEM; - goto err_slave; - } - } - - /* - * Request master resources allocate page sized buffers for small - * reads and writes - */ - for (i = MASTER_MINOR; i < (MASTER_MAX + 1); i++) { - /* XXX Need to properly request attributes */ - image[i].resource = vme_master_request(vme_user_bridge, - VME_A32, VME_SCT, - VME_D32); - if (!image[i].resource) { - dev_warn(&vdev->dev, - "Unable to allocate master resource\n"); - err = -ENOMEM; - goto err_master; - } - image[i].size_buf = PCI_BUF_SIZE; - image[i].kern_buf = kmalloc(image[i].size_buf, GFP_KERNEL); - if (!image[i].kern_buf) { - err = -ENOMEM; - vme_master_free(image[i].resource); - goto err_master; - } - } - - /* Create sysfs entries - on udev systems this creates the dev files */ - err = class_register(&vme_user_sysfs_class); - if (err) { - dev_err(&vdev->dev, "Error creating vme_user class.\n"); - goto err_master; - } - - /* Add sysfs Entries */ - for (i = 0; i < VME_DEVS; i++) { - int num; - - switch (type[i]) { - case MASTER_MINOR: - name = "bus/vme/m%d"; - break; - case CONTROL_MINOR: - name = "bus/vme/ctl"; - break; - case SLAVE_MINOR: - name = "bus/vme/s%d"; - break; - default: - err = -EINVAL; - goto err_sysfs; - } - - num = (type[i] == SLAVE_MINOR) ? i - (MASTER_MAX + 1) : i; - image[i].device = device_create(&vme_user_sysfs_class, NULL, - MKDEV(VME_MAJOR, i), NULL, - name, num); - if (IS_ERR(image[i].device)) { - dev_info(&vdev->dev, "Error creating sysfs device\n"); - err = PTR_ERR(image[i].device); - goto err_sysfs; - } - } - - return 0; - -err_sysfs: - while (i > 0) { - i--; - device_destroy(&vme_user_sysfs_class, MKDEV(VME_MAJOR, i)); - } - class_unregister(&vme_user_sysfs_class); - - /* Ensure counter set correctly to unalloc all master windows */ - i = MASTER_MAX + 1; -err_master: - while (i > MASTER_MINOR) { - i--; - kfree(image[i].kern_buf); - vme_master_free(image[i].resource); - } - - /* - * Ensure counter set correctly to unalloc all slave windows and buffers - */ - i = SLAVE_MAX + 1; -err_slave: - while (i > SLAVE_MINOR) { - i--; - vme_free_consistent(image[i].resource, image[i].size_buf, - image[i].kern_buf, image[i].pci_buf); - vme_slave_free(image[i].resource); - } -err_class: - cdev_del(vme_user_cdev); -err_char: - unregister_chrdev_region(MKDEV(VME_MAJOR, 0), VME_DEVS); -err_region: -err_dev: - return err; -} - -static void vme_user_remove(struct vme_dev *vdev) -{ - int i; - - /* Remove sysfs Entries */ - for (i = 0; i < VME_DEVS; i++) { - mutex_destroy(&image[i].mutex); - device_destroy(&vme_user_sysfs_class, MKDEV(VME_MAJOR, i)); - } - class_unregister(&vme_user_sysfs_class); - - for (i = MASTER_MINOR; i < (MASTER_MAX + 1); i++) { - kfree(image[i].kern_buf); - vme_master_free(image[i].resource); - } - - for (i = SLAVE_MINOR; i < (SLAVE_MAX + 1); i++) { - vme_slave_set(image[i].resource, 0, 0, 0, 0, VME_A32, 0); - vme_free_consistent(image[i].resource, image[i].size_buf, - image[i].kern_buf, image[i].pci_buf); - vme_slave_free(image[i].resource); - } - - /* Unregister device driver */ - cdev_del(vme_user_cdev); - - /* Unregister the major and minor device numbers */ - unregister_chrdev_region(MKDEV(VME_MAJOR, 0), VME_DEVS); -} - -static struct vme_driver vme_user_driver = { - .name = DRIVER_NAME, - .match = vme_user_match, - .probe = vme_user_probe, - .remove = vme_user_remove, -}; - -static int __init vme_user_init(void) -{ - int retval = 0; - - pr_info("VME User Space Access Driver\n"); - - if (bus_num == 0) { - pr_err("No cards, skipping registration\n"); - retval = -ENODEV; - goto err_nocard; - } - - /* Let's start by supporting one bus, we can support more than one - * in future revisions if that ever becomes necessary. - */ - if (bus_num > VME_USER_BUS_MAX) { - pr_err("Driver only able to handle %d buses\n", - VME_USER_BUS_MAX); - bus_num = VME_USER_BUS_MAX; - } - - /* - * Here we just register the maximum number of devices we can and - * leave vme_user_match() to allow only 1 to go through to probe(). - * This way, if we later want to allow multiple user access devices, - * we just change the code in vme_user_match(). - */ - retval = vme_register_driver(&vme_user_driver, VME_MAX_SLOTS); - if (retval) - goto err_reg; - - return retval; - -err_reg: -err_nocard: - return retval; -} - -static void __exit vme_user_exit(void) -{ - vme_unregister_driver(&vme_user_driver); -} - -MODULE_PARM_DESC(bus, "Enumeration of VMEbus to which the driver is connected"); -module_param_array(bus, int, &bus_num, 0000); - -MODULE_DESCRIPTION("VME User Space Access Driver"); -MODULE_AUTHOR("Martyn Welch "); -MODULE_LICENSE("GPL"); - -module_init(vme_user_init); -module_exit(vme_user_exit); diff --git a/drivers/staging/vme_user/vme_user.h b/drivers/staging/vme_user/vme_user.h deleted file mode 100644 index 9e010974351dce..00000000000000 --- a/drivers/staging/vme_user/vme_user.h +++ /dev/null @@ -1,47 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 */ -#ifndef _VME_USER_H_ -#define _VME_USER_H_ - -#define VME_USER_BUS_MAX 1 - -/* - * VMEbus Master Window Configuration Structure - */ -struct vme_master { - __u32 enable; /* State of Window */ - __u64 vme_addr; /* Starting Address on the VMEbus */ - __u64 size; /* Window Size */ - __u32 aspace; /* Address Space */ - __u32 cycle; /* Cycle properties */ - __u32 dwidth; /* Maximum Data Width */ -} __packed; - -/* - * IOCTL Commands and structures - */ - -/* Magic number for use in ioctls */ -#define VME_IOC_MAGIC 0xAE - -/* VMEbus Slave Window Configuration Structure */ -struct vme_slave { - __u32 enable; /* State of Window */ - __u64 vme_addr; /* Starting Address on the VMEbus */ - __u64 size; /* Window Size */ - __u32 aspace; /* Address Space */ - __u32 cycle; /* Cycle properties */ -} __packed; - -struct vme_irq_id { - __u8 level; - __u8 statid; -}; - -#define VME_GET_SLAVE _IOR(VME_IOC_MAGIC, 1, struct vme_slave) -#define VME_SET_SLAVE _IOW(VME_IOC_MAGIC, 2, struct vme_slave) -#define VME_GET_MASTER _IOR(VME_IOC_MAGIC, 3, struct vme_master) -#define VME_SET_MASTER _IOW(VME_IOC_MAGIC, 4, struct vme_master) -#define VME_IRQ_GEN _IOW(VME_IOC_MAGIC, 5, struct vme_irq_id) - -#endif /* _VME_USER_H_ */ - From 6569d814fa49384e3e0f4f41947ecfabf2eb93c8 Mon Sep 17 00:00:00 2001 From: Dmitry Antipov Date: Thu, 22 Oct 2026 08:44:52 +0300 Subject: [PATCH 0029/2102] HID: roccat: use atomic_t for device status flag In roccat_disconnect(), per-device 'exist' status flag is cleared with 'devices_lock' locked but both roccat_read() and roccat_poll() checks this flag unlocked. To avoid data races, convert the flag to atomic_t and introduce the convenient roccat_device_available() wrapper. Signed-off-by: Dmitry Antipov Link: https://patch.msgid.link/20261022054454.238343-2-dmantipov@yandex.ru Signed-off-by: Benjamin Tissoires --- drivers/hid/hid-roccat.c | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/drivers/hid/hid-roccat.c b/drivers/hid/hid-roccat.c index b3e69c79c4b438..c76929c0456e94 100644 --- a/drivers/hid/hid-roccat.c +++ b/drivers/hid/hid-roccat.c @@ -40,7 +40,7 @@ struct roccat_device { unsigned int minor; int report_size; int open; - int exist; + atomic_t exist; wait_queue_head_t wait; struct device *dev; struct hid_device *hid; @@ -70,6 +70,11 @@ static struct roccat_device *devices[ROCCAT_MAX_DEVICES]; /* protects modifications of devices array */ static DEFINE_MUTEX(devices_lock); +static bool roccat_device_available(struct roccat_device *device) +{ + return atomic_read(&device->exist); +} + static void roccat_free_device(struct roccat_device *device) { int i; @@ -105,7 +110,7 @@ static ssize_t roccat_read(struct file *file, char __user *buffer, retval = -ERESTARTSYS; break; } - if (!device->exist) { + if (!roccat_device_available(device)) { retval = -EIO; break; } @@ -149,7 +154,7 @@ static __poll_t roccat_poll(struct file *file, poll_table *wait) poll_wait(file, &reader->device->wait, wait); if (reader->cbuf_start != reader->device->cbuf_end) return EPOLLIN | EPOLLRDNORM; - if (!reader->device->exist) + if (!roccat_device_available(reader->device)) return EPOLLERR | EPOLLHUP; return 0; } @@ -226,7 +231,7 @@ static int roccat_release(struct inode *inode, struct file *file) if (!--device->open) { /* removing last reader */ - if (device->exist) { + if (roccat_device_available(device)) { hid_hw_power(device->hid, PM_HINT_NORMAL); hid_hw_close(device->hid); } else { @@ -345,7 +350,7 @@ int roccat_connect(const struct class *klass, struct hid_device *hid, int report mutex_init(&device->cbuf_lock); device->minor = minor; device->hid = hid; - device->exist = 1; + atomic_set(&device->exist, 1); device->cbuf_end = 0; device->report_size = report_size; @@ -364,7 +369,7 @@ void roccat_disconnect(int minor) mutex_lock(&devices_lock); device = devices[minor]; - device->exist = 0; /* TODO exist maybe not needed */ + atomic_set(&device->exist, 0); device_destroy(device->dev->class, MKDEV(roccat_major, minor)); From be90794d15c6b22861cacebaca2380cbff855157 Mon Sep 17 00:00:00 2001 From: Dmitry Antipov Date: Thu, 22 Oct 2026 08:44:53 +0300 Subject: [PATCH 0030/2102] HID: roccat: use kref to manage device instances Use kref to manage 'struct roccat_device' instances and fix both memory leaks and UaF-triggering races between roccat_open()/roccat_release() and roccat_connect()/roccat_disconnect() pairs. To avoid the scenario when opened device is disconnected and its slot indexed by minor number is reused by another device, release the slot in roccat_free_device() rather than in roccat_disconnect(). This way, there is a time frame when disconnected device may still occupy the slot; to reject such a device, add extra roccat_device_available() checks to roccat_open() and roccat_ioctl(). Add extra WARN_ON() device check to roccat_disconnect() and a few debugging quirks to roccat_free_device() as well. Reported-by: syzbot+d632e93ffcd1452bc61e@syzkaller.appspotmail.com Reported-by: syzbot+c492a9e154f81127551f@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=d632e93ffcd1452bc61e Closes: https://syzkaller.appspot.com/bug?extid=c492a9e154f81127551f Link: https://sashiko.dev/#/patchset/20260902094551.200587-1-dmantipov@yandex.ru?part=2 Signed-off-by: Dmitry Antipov Link: https://patch.msgid.link/20261022054454.238343-3-dmantipov@yandex.ru Signed-off-by: Benjamin Tissoires --- drivers/hid/hid-roccat.c | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/drivers/hid/hid-roccat.c b/drivers/hid/hid-roccat.c index c76929c0456e94..5cc523635445d0 100644 --- a/drivers/hid/hid-roccat.c +++ b/drivers/hid/hid-roccat.c @@ -40,6 +40,7 @@ struct roccat_device { unsigned int minor; int report_size; int open; + struct kref ref; atomic_t exist; wait_queue_head_t wait; struct device *dev; @@ -75,12 +76,20 @@ static bool roccat_device_available(struct roccat_device *device) return atomic_read(&device->exist); } -static void roccat_free_device(struct roccat_device *device) +static void roccat_free_device(struct kref *ref) { + struct roccat_device *device; int i; + WARN_ON(!mutex_is_locked(&devices_lock)); + + device = container_of(ref, struct roccat_device, ref); for (i = 0; i < ROCCAT_CBUF_SIZE; i++) kfree(device->cbuf[i].value); + + devices[device->minor] = NULL; + mutex_destroy(&device->readers_lock); + mutex_destroy(&device->cbuf_lock); kfree(device); } @@ -174,7 +183,7 @@ static int roccat_open(struct inode *inode, struct file *file) device = devices[minor]; - if (!device) { + if (!device || !roccat_device_available(device)) { pr_emerg("roccat device with minor %d doesn't exist\n", minor); error = -ENODEV; goto exit_err_devices; @@ -196,6 +205,7 @@ static int roccat_open(struct inode *inode, struct file *file) --device->open; goto exit_err_readers; } + kref_get(&device->ref); } reader->device = device; @@ -234,9 +244,8 @@ static int roccat_release(struct inode *inode, struct file *file) if (roccat_device_available(device)) { hid_hw_power(device->hid, PM_HINT_NORMAL); hid_hw_close(device->hid); - } else { - roccat_free_device(device); } + kref_put(&device->ref, roccat_free_device); } mutex_unlock(&devices_lock); @@ -348,6 +357,7 @@ int roccat_connect(const struct class *klass, struct hid_device *hid, int report INIT_LIST_HEAD(&device->readers); mutex_init(&device->readers_lock); mutex_init(&device->cbuf_lock); + kref_init(&device->ref); device->minor = minor; device->hid = hid; atomic_set(&device->exist, 1); @@ -369,19 +379,19 @@ void roccat_disconnect(int minor) mutex_lock(&devices_lock); device = devices[minor]; - atomic_set(&device->exist, 0); - - device_destroy(device->dev->class, MKDEV(roccat_major, minor)); + if (WARN_ON(!device)) + goto out; - devices[minor] = NULL; + if (!WARN_ON(!atomic_cmpxchg(&device->exist, 1, 0))) + device_destroy(device->dev->class, MKDEV(roccat_major, minor)); if (device->open) { hid_hw_close(device->hid); wake_up_interruptible(&device->wait); - } else { - roccat_free_device(device); } + kref_put(&device->ref, roccat_free_device); +out: mutex_unlock(&devices_lock); } EXPORT_SYMBOL_GPL(roccat_disconnect); @@ -396,7 +406,7 @@ static long roccat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) mutex_lock(&devices_lock); device = devices[minor]; - if (!device) { + if (!device || !roccat_device_available(device)) { retval = -ENODEV; goto out; } From 8343dd786b4725c69e4352afc5a24dd796aadbcf Mon Sep 17 00:00:00 2001 From: Dmitry Antipov Date: Thu, 22 Oct 2026 08:44:54 +0300 Subject: [PATCH 0031/2102] HID: roccat: avoid unlocked report buffer access in roccat_poll() Since roccat_read() and roccat_report_event() uses per-device report buffer holding 'cbuf_lock', grab the same mutex in roccat_poll() to avoid race against them. Signed-off-by: Dmitry Antipov Link: https://patch.msgid.link/20261022054454.238343-4-dmantipov@yandex.ru Signed-off-by: Benjamin Tissoires --- drivers/hid/hid-roccat.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/drivers/hid/hid-roccat.c b/drivers/hid/hid-roccat.c index 5cc523635445d0..4ed8822fec20c0 100644 --- a/drivers/hid/hid-roccat.c +++ b/drivers/hid/hid-roccat.c @@ -160,12 +160,18 @@ static ssize_t roccat_read(struct file *file, char __user *buffer, static __poll_t roccat_poll(struct file *file, poll_table *wait) { struct roccat_reader *reader = file->private_data; + bool avail; + poll_wait(file, &reader->device->wait, wait); - if (reader->cbuf_start != reader->device->cbuf_end) - return EPOLLIN | EPOLLRDNORM; + if (!roccat_device_available(reader->device)) return EPOLLERR | EPOLLHUP; - return 0; + + mutex_lock(&reader->device->cbuf_lock); + avail = (reader->cbuf_start != reader->device->cbuf_end); + mutex_unlock(&reader->device->cbuf_lock); + + return avail ? EPOLLIN | EPOLLRDNORM : 0; } static int roccat_open(struct inode *inode, struct file *file) From 8dbf66b011135422a28ee32da1d6aacbe08ddd7a Mon Sep 17 00:00:00 2001 From: Shashikirana H K Date: Tue, 13 Oct 2026 06:46:32 +0000 Subject: [PATCH 0032/2102] HID: vivaldi: Extract feature report value directly in vivaldi_feature_mapping() Currently vivaldi_feature_mapping() passes the raw buffer returned by hid_hw_raw_request() to hid_report_raw_event() with the descriptor-declared report_len just to populate field->value[usage->usage_index]. Since vivaldi_feature_mapping() already has the target report, field, and usage in hand, and nothing else consumes field->value[] for this report, verify that hid_hw_raw_request() returns the expected report_len, ensure usage->usage_index is within field->report_count, and extract the value directly using hid_field_extract(). Also use __free(kfree) to simplify buffer cleanup. Suggested-by: Dmitry Torokhov Fixes: 33bbe04a15f2 ("HID: google: extract Vivaldi hid feature mapping for use in hid-hammer") Cc: Tzung-Bi Shih Cc: Sean O'Brien Signed-off-by: Shashikirana H K Link: https://patch.msgid.link/20261013-upstream-vivaldi-fix-v2-1-ecc20329d24c@chromium.org Signed-off-by: Benjamin Tissoires --- drivers/hid/hid-vivaldi-common.c | 72 ++++++++++++-------------------- 1 file changed, 26 insertions(+), 46 deletions(-) diff --git a/drivers/hid/hid-vivaldi-common.c b/drivers/hid/hid-vivaldi-common.c index b12bb5cc091aa3..1359a107e63bd0 100644 --- a/drivers/hid/hid-vivaldi-common.c +++ b/drivers/hid/hid-vivaldi-common.c @@ -5,11 +5,13 @@ * Copyright (C) 2022 Google, Inc */ +#include #include #include #include #include #include +#include #include #include "hid-vivaldi-common.h" @@ -33,13 +35,14 @@ void vivaldi_feature_mapping(struct hid_device *hdev, { struct vivaldi_data *data = hid_get_drvdata(hdev); struct hid_report *report = field->report; - u8 *report_data, *buf; - u32 report_len; unsigned int fn_key; + unsigned int offset; + u32 report_len; int ret; if (field->logical != HID_USAGE_FN_ROW_PHYSMAP || - (usage->hid & HID_USAGE_PAGE) != HID_UP_ORDINAL) + (usage->hid & HID_USAGE_PAGE) != HID_UP_ORDINAL || + usage->usage_index >= field->report_count) return; fn_key = usage->hid & HID_USAGE; @@ -49,54 +52,31 @@ void vivaldi_feature_mapping(struct hid_device *hdev, if (fn_key > data->num_function_row_keys) data->num_function_row_keys = fn_key; - report_data = buf = hid_alloc_report_buf(report, GFP_KERNEL); - if (!report_data) + u8 *buf __free(kfree) = hid_alloc_report_buf(report, GFP_KERNEL); + if (!buf) return; - report_len = hid_report_len(report); - if (!report->id) { - /* - * hid_hw_raw_request() will stuff report ID (which will be 0) - * into the first byte of the buffer even for unnumbered - * reports, so we need to account for this to avoid getting - * -EOVERFLOW in return. - * Note that hid_alloc_report_buf() adds 7 bytes to the size - * so we can safely say that we have space for an extra byte. - */ - report_len++; - } - - ret = hid_hw_raw_request(hdev, report->id, report_data, - report_len, HID_FEATURE_REPORT, - HID_REQ_GET_REPORT); - if (ret < 0) { - dev_warn(&hdev->dev, "failed to fetch feature %d\n", - field->report->id); - goto out; - } - - if (!report->id) { - /* - * Undo the damage from hid_hw_raw_request() for unnumbered - * reports. - */ - report_data++; - report_len--; - } - - ret = hid_report_raw_event(hdev, HID_FEATURE_REPORT, report_data, - report_len, report_len, 0); - if (ret) { - dev_warn(&hdev->dev, "failed to report feature %d\n", - field->report->id); - goto out; + /* + * hid_hw_raw_request() will stuff report ID (which will be 0) + * into the first byte of the buffer even for unnumbered + * reports, so we need to account for this to avoid getting + * -EOVERFLOW in return. + * Note that hid_alloc_report_buf() adds 7 bytes to the size + * so we can safely say that we have space for an extra byte. + */ + report_len = hid_report_len(report) + !report->id; + + ret = hid_hw_raw_request(hdev, report->id, buf, report_len, + HID_FEATURE_REPORT, HID_REQ_GET_REPORT); + if (ret != report_len) { + dev_warn(&hdev->dev, "failed to fetch feature %d: %d\n", + report->id, ret); + return; } + offset = field->report_offset + usage->usage_index * field->report_size; data->function_row_physmap[fn_key - MIN_FN_ROW_KEY] = - field->value[usage->usage_index]; - -out: - kfree(buf); + hid_field_extract(hdev, buf + 1, offset, field->report_size); } EXPORT_SYMBOL_GPL(vivaldi_feature_mapping); From 720806515cb6921ab05caaa6f470f7054b56385e Mon Sep 17 00:00:00 2001 From: Zhengping Jiang Date: Thu, 15 Oct 2026 06:42:23 +0000 Subject: [PATCH 0033/2102] HID: vivaldi: avoid redundant feature report reads per usage vivaldi_feature_mapping() is invoked by report_features() in ascending usage_index order for each usage in the top-row physical keymap field. Because fetching the feature report at usage_index == 0 already reads the entire report from hardware, calling hid_hw_raw_request() again for subsequent usages redundantly reads the same report N times (e.g., 12 sequential BLE GATT reads taking ~2s on Vivaldi BLE keyboards). Bail out immediately when usage->usage_index != 0, fetch the feature report once at usage_index == 0, and iterate over all usages in the field to populate data->function_row_physmap[]. Fixes: 33bbe04a15f2 ("HID: google: extract Vivaldi hid feature mapping for use in hid-hammer") Signed-off-by: Zhengping Jiang Link: https://patch.msgid.link/20261015064223.1939367-1-jiangzp@google.com Signed-off-by: Benjamin Tissoires --- drivers/hid/hid-vivaldi-common.c | 33 +++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/drivers/hid/hid-vivaldi-common.c b/drivers/hid/hid-vivaldi-common.c index 1359a107e63bd0..973393d0935615 100644 --- a/drivers/hid/hid-vivaldi-common.c +++ b/drivers/hid/hid-vivaldi-common.c @@ -39,19 +39,11 @@ void vivaldi_feature_mapping(struct hid_device *hdev, unsigned int offset; u32 report_len; int ret; + int i; - if (field->logical != HID_USAGE_FN_ROW_PHYSMAP || - (usage->hid & HID_USAGE_PAGE) != HID_UP_ORDINAL || - usage->usage_index >= field->report_count) + if (field->logical != HID_USAGE_FN_ROW_PHYSMAP || usage->usage_index) return; - fn_key = usage->hid & HID_USAGE; - if (fn_key < MIN_FN_ROW_KEY || fn_key > MAX_FN_ROW_KEY) - return; - - if (fn_key > data->num_function_row_keys) - data->num_function_row_keys = fn_key; - u8 *buf __free(kfree) = hid_alloc_report_buf(report, GFP_KERNEL); if (!buf) return; @@ -74,9 +66,24 @@ void vivaldi_feature_mapping(struct hid_device *hdev, return; } - offset = field->report_offset + usage->usage_index * field->report_size; - data->function_row_physmap[fn_key - MIN_FN_ROW_KEY] = - hid_field_extract(hdev, buf + 1, offset, field->report_size); + for (i = 0; i < field->maxusage && i < field->report_count; i++) { + usage = &field->usage[i]; + + if ((usage->hid & HID_USAGE_PAGE) != HID_UP_ORDINAL) + continue; + + fn_key = usage->hid & HID_USAGE; + if (fn_key < MIN_FN_ROW_KEY || fn_key > MAX_FN_ROW_KEY) + continue; + + if (fn_key > data->num_function_row_keys) + data->num_function_row_keys = fn_key; + + offset = field->report_offset + i * field->report_size; + data->function_row_physmap[fn_key - MIN_FN_ROW_KEY] = + hid_field_extract(hdev, buf + 1, offset, + field->report_size); + } } EXPORT_SYMBOL_GPL(vivaldi_feature_mapping); From 3baf579ba76613f65b03f43a2f2642340e5fb717 Mon Sep 17 00:00:00 2001 From: Sudeep Holla Date: Wed, 28 Oct 2026 13:05:00 +0000 Subject: [PATCH 0034/2102] firmware: arm_scmi: imx: Track copied syslog words The MISC syslog iterator records the number of returned words plus firmware-reported remaining words in the caller's size output. The debugfs consumer uses that value to dump its fixed-size buffer. A malformed or inconsistent response can therefore make it read beyond the copied data and allocation. Return the accumulated number of words copied into the caller's buffer instead. The generic iterator bounds this count to the initial buffer capacity before processing each response. Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-67e325a9-473e-450a-a2a0-bf4c0c720624 Fixes: 4fa62e80c7db ("firmware: arm_scmi: imx: Support getting syslog of MISC protocol") Reviewed-by: Peng Fan Link: https://patch.msgid.link/20261028130502.2999676-1-sudeep.holla@kernel.org Signed-off-by: Sudeep Holla --- drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c b/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c index 637973fb45e650..0c708b2dd4967b 100644 --- a/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c +++ b/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c @@ -438,7 +438,7 @@ static int iter_misc_syslog_update_state(struct scmi_iterator_state *st, st->num_returned = RETURNED(r->numlogflags); st->num_remaining = REMAINING(r->numlogflags); - *p->size = st->num_returned + st->num_remaining; + *p->size = st->desc_index + st->num_returned; return 0; } From 4e3652a0ac715ba7387b072b72eaff76e761aaf9 Mon Sep 17 00:00:00 2001 From: Sudeep Holla Date: Wed, 28 Oct 2026 13:05:01 +0000 Subject: [PATCH 0035/2102] firmware: arm_scmi: imx: Validate MISC control response size scmi_imx_misc_ctrl_get() uses @num to report the number of values returned by firmware, but it did not retain the caller's value as the capacity of @val. A response with more values than the caller allocated was copied into @val unchecked. For example, the MQS regmap callback supplies storage for one value. Retain the input capacity and reject responses exceeding it before copying, then update @num only after a successful copy. Document the in/out @num contract of the exported helper. Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-6897b44a-57fb-4964-95f8-447d0ce526e4 Fixes: 61c9f03e22fc ("firmware: arm_scmi: Add initial support for i.MX MISC protocol") Reviewed-by: Peng Fan Link: https://patch.msgid.link/20261028130502.2999676-2-sudeep.holla@kernel.org Signed-off-by: Sudeep Holla --- .../firmware/arm_scmi/vendors/imx/imx-sm-misc.c | 16 ++++++++++++---- include/linux/firmware/imx/sm.h | 6 ++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c b/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c index 0c708b2dd4967b..f00f7acba845a0 100644 --- a/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c +++ b/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c @@ -273,10 +273,16 @@ static int scmi_imx_misc_ctrl_get(const struct scmi_protocol_handle *ph, { struct scmi_imx_misc_ctrl_get_out *out; struct scmi_xfer *t; + u32 num_values, max_values; int ret, i; int max_msg_size = ph->hops->get_max_msg_size(ph); int max_num = (max_msg_size - sizeof(*out)) / sizeof(__le32); + if (!num || !val || !*num) + return -EINVAL; + + max_values = *num; + ret = scmi_imx_misc_ctrl_validate_id(ph, ctrl_id); if (ret) return ret; @@ -290,16 +296,18 @@ static int scmi_imx_misc_ctrl_get(const struct scmi_protocol_handle *ph, ret = ph->xops->do_xfer(ph, t); if (!ret) { out = t->rx.buf; - *num = le32_to_cpu(out->num); + num_values = le32_to_cpu(out->num); - if (*num >= max_num || - *num * sizeof(__le32) > t->rx.len - sizeof(__le32)) { + if (num_values > max_values || num_values >= max_num || + num_values * sizeof(__le32) > t->rx.len - sizeof(__le32)) { ph->xops->xfer_put(ph, t); return -EINVAL; } - for (i = 0; i < *num; i++) + for (i = 0; i < num_values; i++) val[i] = le32_to_cpu(out->val[i]); + + *num = num_values; } ph->xops->xfer_put(ph, t); diff --git a/include/linux/firmware/imx/sm.h b/include/linux/firmware/imx/sm.h index ba5d93bd6158f4..0aec7da0ae784d 100644 --- a/include/linux/firmware/imx/sm.h +++ b/include/linux/firmware/imx/sm.h @@ -29,6 +29,12 @@ #define SCMI_IMX952_CTRL_BYPASS_AUDMIX 8U /* WAKE AUDMIX */ #if IS_ENABLED(CONFIG_IMX_SCMI_MISC_DRV) +/** + * scmi_imx_misc_ctrl_get() - Read an i.MX MISC control + * @id: Control identifier + * @num: On entry, capacity of @val in words; on return, words read + * @val: Buffer for the control value + */ int scmi_imx_misc_ctrl_get(u32 id, u32 *num, u32 *val); int scmi_imx_misc_ctrl_set(u32 id, u32 val); #else From b9bb2eb88037a3823e7abd096b54d0a07d428f90 Mon Sep 17 00:00:00 2001 From: Sudeep Holla Date: Wed, 28 Oct 2026 13:05:02 +0000 Subject: [PATCH 0036/2102] firmware: arm_scmi: Unregister notifier on enable failure scmi_notifier_register() adds the caller's notifier block before enabling the corresponding event at the platform. If enablement fails, the caller receives an error and can free its notifier block. A concurrent registration can retain and later enable the handler, leaving the failed caller's block in its notification chain. Event delivery can then dereference the freed block. Remove the notifier block before dropping the handler reference when event enablement fails. Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-c3c9437c-ba1a-4db6-837f-cb0950d89018 Fixes: e7c215f358a3 ("firmware: arm_scmi: Add notification callbacks-registration") Reviewed-by: Peng Fan Link: https://patch.msgid.link/20261028130502.2999676-3-sudeep.holla@kernel.org Signed-off-by: Sudeep Holla --- drivers/firmware/arm_scmi/notify.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/firmware/arm_scmi/notify.c b/drivers/firmware/arm_scmi/notify.c index fb60fb07c0ed19..e5de0d29c34608 100644 --- a/drivers/firmware/arm_scmi/notify.c +++ b/drivers/firmware/arm_scmi/notify.c @@ -1395,8 +1395,10 @@ static int scmi_notifier_register(const struct scmi_handle *handle, /* Enable events for not pending handlers */ if (!IS_HNDL_PENDING(hndl)) { ret = scmi_event_handler_enable_events(hndl); - if (ret) + if (ret) { + blocking_notifier_chain_unregister(&hndl->chain, nb); scmi_put_handler(ni, hndl); + } } return ret; From 38b6268eae651de1ca31c48b912a55ae3e706b94 Mon Sep 17 00:00:00 2001 From: Sudeep Holla Date: Wed, 28 Oct 2026 15:32:03 +0000 Subject: [PATCH 0037/2102] firmware: arm_scmi: Free mailbox state on mapping failure mailbox_chan_setup() allocates its private state from the SCMI base device before mapping the shared-memory area. If mapping fails while setting up an optional RX channel, the core ignores the RX failure and keeps the base device bound, retaining that devres allocation. Release the private mailbox state before returning the mapping error. Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-fda9bcb5-8255-4157-bbf7-d720bbd86605 Fixes: 1ebc28e9357c ("firmware: arm_scmi: Introduce setup_shmem_iomap") Link: https://patch.msgid.link/20261028153203.3305067-1-sudeep.holla@kernel.org Signed-off-by: Sudeep Holla --- drivers/firmware/arm_scmi/transports/mailbox.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/firmware/arm_scmi/transports/mailbox.c b/drivers/firmware/arm_scmi/transports/mailbox.c index 56af2cb0f42473..49c472e2ba2742 100644 --- a/drivers/firmware/arm_scmi/transports/mailbox.c +++ b/drivers/firmware/arm_scmi/transports/mailbox.c @@ -206,8 +206,11 @@ static int mailbox_chan_setup(struct scmi_chan_info *cinfo, struct device *dev, smbox->shmem = core->shmem->setup_iomap(cinfo, dev, tx, NULL, &smbox->io_ops); - if (IS_ERR(smbox->shmem)) - return PTR_ERR(smbox->shmem); + if (IS_ERR(smbox->shmem)) { + ret = PTR_ERR(smbox->shmem); + devm_kfree(dev, smbox); + return ret; + } cl = &smbox->cl; cl->dev = cdev; From 2fad8d241a6833d0c7aeafa0ab596e83c7b4ec9c Mon Sep 17 00:00:00 2001 From: Radhey Shyam Pandey Date: Mon, 28 Sep 2026 17:30:13 +0530 Subject: [PATCH 0038/2102] usb: dwc3: xilinx: fix system suspend and resume PHY handling System suspend and resume error paths do not handle PHY and clock resources correctly. Suspend calls phy_exit() without first powering off the PHY and ignores failures, while resume can leave clocks enabled if PHY reinitialization fails. Propagate errors to the PM core and unwind resources to ensure a consistent state on suspend and resume failures. Fixes: d6edcdc1ef06 ("usb: dwc3: xilinx: fix usb3 non-wakeup source resume failure") Cc: stable Assisted-by: Claude:claude-opus-5 Signed-off-by: Radhey Shyam Pandey Acked-by: Thinh Nguyen Link: https://patch.msgid.link/20260928120015.3152461-2-radhey.shyam.pandey@amd.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/dwc3-xilinx.c | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/drivers/usb/dwc3/dwc3-xilinx.c b/drivers/usb/dwc3/dwc3-xilinx.c index b832505e1b0428..8c63e02575f1bd 100644 --- a/drivers/usb/dwc3/dwc3-xilinx.c +++ b/drivers/usb/dwc3/dwc3-xilinx.c @@ -383,13 +383,26 @@ static int __maybe_unused dwc3_xlnx_runtime_idle(struct device *dev) static int __maybe_unused dwc3_xlnx_suspend(struct device *dev) { struct dwc3_xlnx *priv_data = dev_get_drvdata(dev); + int ret; - phy_exit(priv_data->usb3_phy); + ret = phy_power_off(priv_data->usb3_phy); + if (ret < 0) + return ret; + + ret = phy_exit(priv_data->usb3_phy); + if (ret < 0) + goto err_phy_power_on; /* Disable the clocks */ clk_bulk_disable(priv_data->num_clocks, priv_data->clks); return 0; + +err_phy_power_on: + if (phy_power_on(priv_data->usb3_phy)) + dev_err(dev, "failed to restore PHY power after suspend error\n"); + + return ret; } static int __maybe_unused dwc3_xlnx_resume(struct device *dev) @@ -403,15 +416,20 @@ static int __maybe_unused dwc3_xlnx_resume(struct device *dev) ret = phy_init(priv_data->usb3_phy); if (ret < 0) - return ret; + goto err_clk_disable; ret = phy_power_on(priv_data->usb3_phy); if (ret < 0) { phy_exit(priv_data->usb3_phy); - return ret; + goto err_clk_disable; } return 0; + +err_clk_disable: + clk_bulk_disable(priv_data->num_clocks, priv_data->clks); + + return ret; } static const struct dev_pm_ops dwc3_xlnx_dev_pm_ops = { From f33f0dd2eb014bffda02ecfd182de3ddab058596 Mon Sep 17 00:00:00 2001 From: Radhey Shyam Pandey Date: Mon, 28 Sep 2026 17:30:14 +0530 Subject: [PATCH 0039/2102] usb: dwc3: xilinx: re-assert resets on ZynqMP init error paths If reset deassert or PHY setup fails partway through dwc3_xlnx_init_zynqmp(), re-assert the resets that were already released before unwinding the PHY. Only undo the reset cycle the function actually performed. The cycle is skipped when no usb3-phy is present, because asserting the core resets can break a USB3 configuration that is live but missing from the device tree, so the error path skips it for the same reason. Asserting an already asserted reset is harmless, so one block covers however far the deasserts progressed. Save the ZynqMP reset handles in driver private data so later probe teardown can re-assert released resets. Fixes: 84770f028fab ("usb: dwc3: Add driver for Xilinx platforms") Cc: stable Assisted-by: Claude:claude-opus-5 Signed-off-by: Radhey Shyam Pandey Acked-by: Thinh Nguyen Link: https://patch.msgid.link/20260928120015.3152461-3-radhey.shyam.pandey@amd.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/dwc3-xilinx.c | 55 ++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 19 deletions(-) diff --git a/drivers/usb/dwc3/dwc3-xilinx.c b/drivers/usb/dwc3/dwc3-xilinx.c index 8c63e02575f1bd..d2315573b3d3dc 100644 --- a/drivers/usb/dwc3/dwc3-xilinx.c +++ b/drivers/usb/dwc3/dwc3-xilinx.c @@ -48,6 +48,9 @@ struct dwc3_xlnx { void __iomem *regs; int (*pltfm_init)(struct dwc3_xlnx *data); struct phy *usb3_phy; + struct reset_control *usb_crst; + struct reset_control *usb_hibrst; + struct reset_control *usb_apbrst; }; static void dwc3_xlnx_mask_phy_rst(struct dwc3_xlnx *priv_data, bool mask) @@ -112,7 +115,6 @@ static int dwc3_xlnx_init_versal(struct dwc3_xlnx *priv_data) static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) { struct device *dev = priv_data->dev; - struct reset_control *crst, *hibrst, *apbrst; struct gpio_desc *reset_gpio; int ret = 0; @@ -124,25 +126,25 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) goto err; } - crst = devm_reset_control_get_exclusive(dev, "usb_crst"); - if (IS_ERR(crst)) { - ret = PTR_ERR(crst); + priv_data->usb_crst = devm_reset_control_get_exclusive(dev, "usb_crst"); + if (IS_ERR(priv_data->usb_crst)) { + ret = PTR_ERR(priv_data->usb_crst); dev_err_probe(dev, ret, "failed to get core reset signal\n"); goto err; } - hibrst = devm_reset_control_get_exclusive(dev, "usb_hibrst"); - if (IS_ERR(hibrst)) { - ret = PTR_ERR(hibrst); + priv_data->usb_hibrst = devm_reset_control_get_exclusive(dev, "usb_hibrst"); + if (IS_ERR(priv_data->usb_hibrst)) { + ret = PTR_ERR(priv_data->usb_hibrst); dev_err_probe(dev, ret, "failed to get hibernation reset signal\n"); goto err; } - apbrst = devm_reset_control_get_exclusive(dev, "usb_apbrst"); - if (IS_ERR(apbrst)) { - ret = PTR_ERR(apbrst); + priv_data->usb_apbrst = devm_reset_control_get_exclusive(dev, "usb_apbrst"); + if (IS_ERR(priv_data->usb_apbrst)) { + ret = PTR_ERR(priv_data->usb_apbrst); dev_err_probe(dev, ret, "failed to get APB reset signal\n"); goto err; @@ -156,19 +158,19 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) * absent. */ if (priv_data->usb3_phy) { - ret = reset_control_assert(crst); + ret = reset_control_assert(priv_data->usb_crst); if (ret < 0) { dev_err(dev, "Failed to assert core reset\n"); goto err; } - ret = reset_control_assert(hibrst); + ret = reset_control_assert(priv_data->usb_hibrst); if (ret < 0) { dev_err(dev, "Failed to assert hibernation reset\n"); goto err; } - ret = reset_control_assert(apbrst); + ret = reset_control_assert(priv_data->usb_apbrst); if (ret < 0) { dev_err(dev, "Failed to assert APB reset\n"); goto err; @@ -179,7 +181,7 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) if (ret < 0) goto err; - ret = reset_control_deassert(apbrst); + ret = reset_control_deassert(priv_data->usb_apbrst); if (ret < 0) { dev_err(dev, "Failed to release APB reset\n"); goto err_phy_exit; @@ -195,21 +197,21 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) writel(PIPE_CLK_DESELECT, priv_data->regs + XLNX_USB_FPD_PIPE_CLK); } - ret = reset_control_deassert(crst); + ret = reset_control_deassert(priv_data->usb_crst); if (ret < 0) { dev_err(dev, "Failed to release core reset\n"); - goto err_phy_exit; + goto err_reset_assert; } - ret = reset_control_deassert(hibrst); + ret = reset_control_deassert(priv_data->usb_hibrst); if (ret < 0) { dev_err(dev, "Failed to release hibernation reset\n"); - goto err_phy_exit; + goto err_reset_assert; } ret = phy_power_on(priv_data->usb3_phy); if (ret < 0) - goto err_phy_exit; + goto err_reset_assert; /* ulpi reset via gpio-modepin or gpio-framework driver */ reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH); @@ -230,6 +232,21 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) err_phy_power_off: phy_power_off(priv_data->usb3_phy); +err_reset_assert: + /* + * Undo only the reset cycle performed above. That cycle is skipped + * when there is no usb3-phy. The deasserts stay unconditional so a + * core the bootloader left in reset still comes up, but they are + * deliberately not paired with an assert here: resetting a USB3 + * configuration that is live but missing from the device tree could + * break it. Asserting an already asserted reset is harmless, so one + * block covers however far the cycle's deasserts got. + */ + if (priv_data->usb3_phy) { + reset_control_assert(priv_data->usb_hibrst); + reset_control_assert(priv_data->usb_crst); + reset_control_assert(priv_data->usb_apbrst); + } err_phy_exit: phy_exit(priv_data->usb3_phy); err: From 6c6508e742b47539224eb18cb23f7ed5d401dcb6 Mon Sep 17 00:00:00 2001 From: Radhey Shyam Pandey Date: Mon, 28 Sep 2026 17:30:15 +0530 Subject: [PATCH 0040/2102] usb: dwc3: xilinx: unwind ZynqMP platform init on probe failure and remove dwc3_xlnx_init_zynqmp() leaves the controller out of reset with the PHY powered on, but nothing undoes that if probe fails later or when the driver is removed. The resets stay deasserted and the PHY stays on with no driver bound. Register the teardown with devm_add_action_or_reset() once init has completed, so it runs on probe failure without the driver having to track how far init progressed. The teardown only undoes the reset cycle init performed, so it carries the same usb3-phy guard: with no PHY the resets were never asserted, and asserting them could break a USB3 configuration that is live but missing from the device tree. The resets have to be asserted while the clocks are still running, so both the probe error path and remove() run the teardown explicitly before gating the clocks rather than leaving it to devres, which would otherwise run it afterwards. devm_release_action() unlinks the action before calling it, so devres cannot run it a second time. Running it from remove() also covers .shutdown, which shares dwc3_xlnx_remove(): device_shutdown() does not call devres_release_all(), so a teardown left to devres would never run there. Fixes: 84770f028fab ("usb: dwc3: Add driver for Xilinx platforms") Cc: stable Suggested-by: Philipp Zabel Assisted-by: Claude:claude-opus-5 Signed-off-by: Radhey Shyam Pandey Acked-by: Thinh Nguyen Link: https://patch.msgid.link/20260928120015.3152461-4-radhey.shyam.pandey@amd.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/dwc3-xilinx.c | 44 +++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/drivers/usb/dwc3/dwc3-xilinx.c b/drivers/usb/dwc3/dwc3-xilinx.c index d2315573b3d3dc..475bc19a1746b4 100644 --- a/drivers/usb/dwc3/dwc3-xilinx.c +++ b/drivers/usb/dwc3/dwc3-xilinx.c @@ -112,6 +112,39 @@ static int dwc3_xlnx_init_versal(struct dwc3_xlnx *priv_data) return 0; } +static void dwc3_xlnx_zynqmp_teardown(void *data) +{ + struct dwc3_xlnx *priv_data = data; + + phy_power_off(priv_data->usb3_phy); + + /* + * Undo only the reset cycle init performed. As on the init error + * path, the unconditional deasserts are not paired with an assert + * here: with no usb3-phy, resetting the core could break a USB3 + * configuration that is live but missing from the device tree. + */ + if (priv_data->usb3_phy) { + reset_control_assert(priv_data->usb_hibrst); + reset_control_assert(priv_data->usb_crst); + reset_control_assert(priv_data->usb_apbrst); + } + + phy_exit(priv_data->usb3_phy); +} + +/* + * Run the platform teardown explicitly, so the resets are asserted while the + * clocks are still running. devm_release_action() unlinks the action before + * calling it, so devres will not run it a second time. + */ +static void dwc3_xlnx_release_teardown(struct device *dev, + struct dwc3_xlnx *priv_data) +{ + if (devm_is_action_added(dev, dwc3_xlnx_zynqmp_teardown, priv_data)) + devm_release_action(dev, dwc3_xlnx_zynqmp_teardown, priv_data); +} + static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) { struct device *dev = priv_data->dev; @@ -228,7 +261,8 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) dwc3_xlnx_set_coherency(priv_data, XLNX_USB_TRAFFIC_ROUTE_CONFIG); - return 0; + return devm_add_action_or_reset(dev, dwc3_xlnx_zynqmp_teardown, + priv_data); err_phy_power_off: phy_power_off(priv_data->usb3_phy); @@ -355,6 +389,7 @@ static int dwc3_xlnx_probe(struct platform_device *pdev) pm_runtime_set_suspended(dev); err_clk_put: + dwc3_xlnx_release_teardown(dev, priv_data); clk_bulk_disable_unprepare(priv_data->num_clocks, priv_data->clks); return ret; @@ -367,6 +402,13 @@ static void dwc3_xlnx_remove(struct platform_device *pdev) of_platform_depopulate(dev); + /* + * This is also what makes .shutdown behave the same as .remove: + * device_shutdown() does not call devres_release_all(), so a teardown + * left to devres would never run on the shutdown path. + */ + dwc3_xlnx_release_teardown(dev, priv_data); + clk_bulk_disable_unprepare(priv_data->num_clocks, priv_data->clks); priv_data->num_clocks = 0; From 688bee95b42395f5d127cbd7523d52b218ae5f8f Mon Sep 17 00:00:00 2001 From: Thinh Nguyen Date: Sat, 3 Oct 2026 02:18:05 +0000 Subject: [PATCH 0041/2102] MAINTAINERS: take over dwc2 maintainership Minas is stepping down as the DWC2 maintainer. Thank you Minas for your years of work maintaining this driver. I'm taking over DWC2 maintenance in addition to DWC3 so that both DesignWare USB DRD drivers share a single point of contact. Also drop the stale tree entry pointing at balbi/usb.git, which is no longer where dwc2 patches are picked up. This matches the DWC3 entry, which does not list a tree either. Signed-off-by: Thinh Nguyen Link: https://patch.msgid.link/c2a97d0eafcbaa9509edce5b7b2648d6f9d80863.1790993820.git.Thinh.Nguyen@synopsys.com Signed-off-by: Greg Kroah-Hartman --- MAINTAINERS | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index 748ce4d1c6a260..f292eef1197c9a 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -7555,10 +7555,9 @@ F: drivers/dma/dw-edma/ F: include/linux/dma/edma.h DESIGNWARE USB2 DRD IP DRIVER -M: Minas Harutyunyan +M: Thinh Nguyen L: linux-usb@vger.kernel.org S: Maintained -T: git git://git.kernel.org/pub/scm/linux/kernel/git/balbi/usb.git F: drivers/usb/dwc2/ DESIGNWARE USB3 DRD IP DRIVER From 5b4b83c2ffe8740f6f3e54ea4d4962a62c063ef1 Mon Sep 17 00:00:00 2001 From: Uttkarsh Aggarwal Date: Tue, 29 Sep 2026 14:59:39 +0530 Subject: [PATCH 0042/2102] usb: typec: ucsi: Set ucsi->connector before enabling notifications In ucsi_init(), ucsi->connector is assigned only after the UCSI_SET_NOTIFICATION_ENABLE command completes. But once that command is sent, the PPM is free to raise a connector change notification at any time, which is handled through: ucsi_notify_common() -> ucsi_connector_change() ucsi_connector_change() indexes into ucsi->connector to get the connector and schedule its work item. If this notification arrives before ucsi_init() reaches the "ucsi->connector = connector;" line, ucsi->connector is still NULL and the driver crashes dereferencing it. Fix this by setting ucsi->connector right after the connectors are registered, before notifications are enabled, so it is always valid by the time a connector change event can be delivered. Also clear ucsi->connector in the err_unregister path so it isn't left pointing at freed memory if a later step in ucsi_init() fails. Fixes: 0482c34ec6f8 ("usb: ucsi: Fix ucsi->connector race") Cc: stable Signed-off-by: Uttkarsh Aggarwal Reviewed-by: Peter Chen Reviewed-by: Heikki Krogerus Link: https://patch.msgid.link/20260929092939.1806907-1-uttkarsh.aggarwal@oss.qualcomm.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/typec/ucsi/ucsi.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/drivers/usb/typec/ucsi/ucsi.c b/drivers/usb/typec/ucsi/ucsi.c index 5aab8ab9f0132d..2f9adf4f8bdebd 100644 --- a/drivers/usb/typec/ucsi/ucsi.c +++ b/drivers/usb/typec/ucsi/ucsi.c @@ -2134,6 +2134,14 @@ static int ucsi_init(struct ucsi *ucsi) goto err_unregister; } + /* + * Set ucsi->connector before enabling notifications. A connector + * change event can be handled as soon as the notifications are + * enabled below, and ucsi_connector_change() indexes into + * ucsi->connector, so it must not be NULL at that point. + */ + ucsi->connector = connector; + /* Enable all supported notifications */ ntfy = ucsi_get_supported_notifications(ucsi); command = UCSI_SET_NOTIFICATION_ENABLE | ntfy; @@ -2141,7 +2149,6 @@ static int ucsi_init(struct ucsi *ucsi) if (ret < 0) goto err_unregister; - ucsi->connector = connector; ucsi->ntfy = ntfy; mutex_lock(&ucsi->ppm_lock); @@ -2155,6 +2162,7 @@ static int ucsi_init(struct ucsi *ucsi) return 0; err_unregister: + ucsi->connector = NULL; for (con = connector; con->port; con++) ucsi_unregister_port(con); for (i = 0; i < ucsi->cap.num_connectors; i++) From ea6cf69ad03c8d85138830c0d2c3b946b5ae231d Mon Sep 17 00:00:00 2001 From: Brian Ellis Date: Tue, 13 Oct 2026 14:57:03 -0600 Subject: [PATCH 0043/2102] usb: gadget: u_serial: fix NULL deref in gs_close() after failed open gs_close() opens with struct gs_port *port = tty->driver_data; ... spin_lock_irq(&port->port_lock); and never checks port. gs_open() assigns tty->driver_data only on the port.count 0 -> 1 edge, so any failure earlier in gs_open() leaves it NULL, and tty_open() calls tty_release(), and hence ->close(), when ->open() fails. syzbot hit exactly this on arm64. Fault injection failed the kfifo_alloc() of the write buffer in gs_open(): __kfifo_alloc_node+0x10c/0x208 lib/kfifo.c:44 gs_open+0x144/0x514 drivers/usb/gadget/function/u_serial.c:636 tty_open+0x404/0x89c drivers/tty/tty_io.c:2137 and the tty core's close of the failed open then took port_lock through the NULL port: BUG: unable to handle kernel paging request in gs_close KASAN: null-ptr-deref in range [0x00000000000003a0-0x00000000000003a7] Call trace: spin_lock_irq include/linux/spinlock.h:372 [inline] gs_close+0xac/0x65c drivers/usb/gadget/function/u_serial.c:698 tty_release+0x2c4/0xffc drivers/tty/tty_io.c:1745 tty_open+0x46c/0x89c drivers/tty/tty_io.c:2146 Return early instead. There is nothing to release when the open never got far enough to claim the port. Unlike the check reverted by commit f6c7bc4a6823 ("Revert "usb: gadget: u_serial: Add null pointer check in gs_start_io""), this is not hiding a race: the tty core calls ->close() for an ->open() that failed by design, so driver_data is legitimately unset on that path. Fixes: c1dca562be8a ("usb gadget: split out serial core") Reported-by: syzbot+782b2f1063e38ba8fa6e@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=782b2f1063e38ba8fa6e Cc: stable Assisted-by: LLM Signed-off-by: Brian Ellis Link: https://patch.msgid.link/20261013-u_serial-gs-close-null-v4-1-9ea038501994@gotenna.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/u_serial.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/usb/gadget/function/u_serial.c b/drivers/usb/gadget/function/u_serial.c index cdd1dfc666c4f6..892d2673e9b052 100644 --- a/drivers/usb/gadget/function/u_serial.c +++ b/drivers/usb/gadget/function/u_serial.c @@ -695,6 +695,9 @@ static void gs_close(struct tty_struct *tty, struct file *file) struct gs_port *port = tty->driver_data; struct gserial *gser; + if (!port) + return; + spin_lock_irq(&port->port_lock); if (port->port.count != 1) { From fafd23d61494461256d374f67c121f2712e1af2f Mon Sep 17 00:00:00 2001 From: Olivier Kaloudoff Date: Wed, 14 Oct 2026 18:57:41 +0200 Subject: [PATCH 0044/2102] usb: uas: ignore UAS for ASMT135x bridges (174c:55aa) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ASMedia chip detection in uas_use_uas_driver() assumes that every device with idVendor/idProduct 174c:5106 or 174c:55aa reporting a config.MaxPower of 0 is an ASM1153 with working UAS. ASMT135x bridges (iProduct "ASMT135x") share the same 174c:55aa id and also report MaxPower == 0, so they take the "ASM1153, do nothing" path — but their UAS implementation is broken: - The first READ(16) issued by sd probing times out after 30 s; enumeration only completes after a uas_eh_abort_handler plus a full uas_eh_host_reset_handler cycle: scsi 3:0:0:0: Direct-Access ASMT ASMT135x 0 PQ: 0 ANSI: 6 sd 3:0:0:0: [sdb] tag#26 uas_eh_abort_handler 0 uas-tag 1 inflight: CMD IN sd 3:0:0:0: [sdb] tag#26 CDB: Read(16) 88 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 scsi host3: uas_eh_host_reset_handler start usb 6-2: reset SuperSpeed USB device number 2 using xhci_hcd scsi host3: uas_eh_host_reset_handler success - Under concurrent load the bridge stalls: all inflight commands (20+ UAS tags in the captured incident, mixed READ(16)/WRITE(16)) hit the 30 s UAS timeout in the same event, forcing repeated abort/reset cycles and eventually a USB disconnect. Writes dropped mid-flight during these resets returned zeros to the filesystem (observed as XFS metadata corruption on the mounted volume). - Sequential-write throughput is ~45 MiB/s under UAS versus ~136 MiB/s after disabling UAS (usb-storage BOT mode), which is fully stable: several tens of GiB written without a single error. - Bulk reads of healthy LBA ranges do work under UAS (~190 MiB/s, no errors); the failure pattern is command-timeout at enumeration and under queue depth / write load, not a broken transfer path. Since 174c:55aa is shared across several ASMedia bridges and enclosure rebrandings, distinguish the ASMT135x by its product string — the same approach used for the HIKSEMI MD202 check a few lines below. The product strings of working bridges using the same id ("ASM1053E", "ASM1153", "ASM1153E", "ASM1351", vendor rebrands such as "YZWY_TECH") do not contain "ASMT135", so the match is safe. Verified on an ORICO enclosure (iManufacturer "ASMT", iProduct "ASMT135x", bcdDevice 1.00) attached through an Alpine Ridge TB3 dock: with the equivalent usb-storage quirks parameter (174c:55aa:u) the device is completely stable. Signed-off-by: Olivier Kaloudoff Cc: stable Acked-by: Alan Stern Link: https://patch.msgid.link/20261014165741.35758-1-olivier.kaloudoff@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/storage/uas-detect.h | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/drivers/usb/storage/uas-detect.h b/drivers/usb/storage/uas-detect.h index 4d3b49e5b87a9d..523a17cf0a3c10 100644 --- a/drivers/usb/storage/uas-detect.h +++ b/drivers/usb/storage/uas-detect.h @@ -78,6 +78,8 @@ static int uas_use_uas_driver(struct usb_interface *intf, * ASM1051 - with broken (*) uas support * ASM1053 - with working uas support, but problems with large xfers * ASM1153 - with working uas support + * ASMT135x - broken uas support, shares the ASM1153 MaxPower == 0 + * signature, identify it by its product string * * Devices with these chips re-use a number of device-ids over the * entire line, so the device-id is useless to determine if we're @@ -99,7 +101,11 @@ static int uas_use_uas_driver(struct usb_interface *intf, (le16_to_cpu(udev->descriptor.idProduct) == 0x5106 || le16_to_cpu(udev->descriptor.idProduct) == 0x55aa)) { if (udev->actconfig->desc.bMaxPower == 0) { - /* ASM1153, do nothing */ + if (udev->product && strstr(udev->product, "ASMT135")) { + /* ASMT135x, broken uas */ + flags |= US_FL_IGNORE_UAS; + } + /* else ASM1153, do nothing */ } else if (udev->speed < USB_SPEED_SUPER) { /* No streams info, assume ASM1051 */ flags |= US_FL_IGNORE_UAS; From fdaca138694111153f96c7d76877734b9dbf0e01 Mon Sep 17 00:00:00 2001 From: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Date: Fri, 16 Oct 2026 15:27:50 +0800 Subject: [PATCH 0045/2102] usb: usbtest: prevent divide by zero in simple_io() with zero length A divide error oops was observed in simple_io(): usbtest 1-1:1.0: TEST 3: write/1 0..0 bytes 16307 times Oops: divide error: 0000 [#1] SMP KASAN RIP: 0010:simple_io+0x2c4/0x540 drivers/usb/misc/usbtest.c:497 The variable-length tests (test 3 and test 4) compute the next URB size with "len %= max", where max is the original urb->transfer_buffer_length. However, when a zero-length transfer is requested (param->length == 0), simple_alloc_urb() still returns a valid URB with transfer_buffer_length set to 0. On the first vary update, "len %= max" divides by zero and the kernel oopses. Commit 564e69893c63 ("USB: usbtest: prevent a divide by zero bug") added the equivalent zero check to alloc_sglist(), which covers the scatterlist tests (test 7/8), but the single-URB variable-length path in simple_io() was left unprotected. Fix this by returning -EINVAL early from simple_io() when vary is requested but max is zero, so the divide by zero never occurs. Zero-length transfers without vary remain valid for the other callers of simple_io(). Cc: stable Co-developed-by: Bin Yu Signed-off-by: Bin Yu Co-developed-by: Cheng Wen Signed-off-by: Cheng Wen Signed-off-by: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Reviewed-by: Alan Stern Link: https://patch.msgid.link/20261016072750.34256-1-25031212351@stu.xidian.edu.cn Signed-off-by: Greg Kroah-Hartman --- drivers/usb/misc/usbtest.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/usb/misc/usbtest.c b/drivers/usb/misc/usbtest.c index 8759df49be2873..e2f5e6be353acb 100644 --- a/drivers/usb/misc/usbtest.c +++ b/drivers/usb/misc/usbtest.c @@ -466,6 +466,9 @@ static int simple_io( int retval = 0; unsigned long expire; + if (vary && !max) + return -EINVAL; + urb->context = &completion; while (retval == 0 && iterations-- > 0) { init_completion(&completion); From bc9dd21ec61acd152d9e7c12cb07db37c63ad41a Mon Sep 17 00:00:00 2001 From: Johan Hovold Date: Mon, 19 Oct 2026 14:37:55 +0200 Subject: [PATCH 0046/2102] USB: cdc-acm: fix NULL-deref on hangup Make sure to take a reference to the port tty when processing carrier detect changes to avoid dereferencing a NULL pointer when the port is being hung up. Fixes: 3b563b901eef ("usb: cdc-acm: add PPS support") Cc: stable Cc: Dan Drown Signed-off-by: Johan Hovold Link: https://patch.msgid.link/20261019123755.2008384-1-johan@kernel.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/class/cdc-acm.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/drivers/usb/class/cdc-acm.c b/drivers/usb/class/cdc-acm.c index 489575d40bd148..666969ffd19449 100644 --- a/drivers/usb/class/cdc-acm.c +++ b/drivers/usb/class/cdc-acm.c @@ -294,6 +294,7 @@ static void acm_process_notification(struct acm *acm, unsigned char *buf) unsigned long flags; struct usb_cdc_notification *dr = (struct usb_cdc_notification *)buf; unsigned char *data = buf + sizeof(struct usb_cdc_notification); + struct tty_struct *tty; switch (dr->bNotificationType) { case USB_CDC_NOTIFY_NETWORK_CONNECTION: @@ -320,12 +321,17 @@ static void acm_process_notification(struct acm *acm, unsigned char *buf) difference = acm->ctrlin ^ newctrl; - if ((difference & USB_CDC_SERIAL_STATE_DCD) && acm->port.tty) { - struct tty_ldisc *ld = tty_ldisc_ref(acm->port.tty); - if (ld) { - if (ld->ops->dcd_change) - ld->ops->dcd_change(acm->port.tty, newctrl & USB_CDC_SERIAL_STATE_DCD); - tty_ldisc_deref(ld); + if (difference & USB_CDC_SERIAL_STATE_DCD) { + tty = tty_port_tty_get(&acm->port); + if (tty) { + struct tty_ldisc *ld = tty_ldisc_ref(tty); + + if (ld) { + if (ld->ops->dcd_change) + ld->ops->dcd_change(tty, newctrl & USB_CDC_SERIAL_STATE_DCD); + tty_ldisc_deref(ld); + } + tty_kref_put(tty); } } From 450fa94d7ae9fc91c3df525f5d1322bf8fecf7b2 Mon Sep 17 00:00:00 2001 From: Yu Zhang Date: Tue, 20 Oct 2026 12:30:50 +1000 Subject: [PATCH 0047/2102] usb: gadget: f_mass_storage: take filesem in nofua store to fix backing-file UAF fsg_store_nofua() syncs the LUN's backing file when switching from async to sync mode: if (!nofua && curlun->nofua) fsg_lun_fsync_sub(curlun); fsg_lun_fsync_sub() dereferences curlun->filp (vfs_fsync(filp)). Unlike every other store that touches the backing file -- fsg_store_ro() and fsg_store_cdrom() (down_read), fsg_store_file() (down_write) -- fsg_store_nofua() holds no filesem while doing so. A concurrent close of the backing file runs under down_write(filesem) and does fput(curlun->filp) in fsg_lun_close() (fsg_store_file() with an empty path, the SCSI START_STOP eject in do_start_stop(), or forced_eject), so it can free the file while fsg_store_nofua() is dereferencing it: BUG: KASAN: slab-use-after-free in vfs_fsync+0x20/0xe0 vfs_fsync+0x20/0xe0 fsg_lun_fsync_sub+0xa0/0xd0 fsg_store_nofua+0x138/0x160 configfs_write_iter+0x1a7/0x250 vfs_write+0x5df/0x940 Allocated by task 3459: fsg_store_file+0x150/0x1f0 configfs_write_iter+0x1a7/0x250 Freed by task 3459: __fput+0x456/0x6c0 __fput_deferred+0x10d/0x330 fsg_store_file+0x9e/0x1f0 configfs_write_iter+0x1a7/0x250 Hold filesem for read around the fsync in fsg_store_nofua() so the backing file cannot be closed underneath it. The lock is only needed when the fsync actually runs, so it is taken only in that branch. Reproduced on a mass_storage gadget over dummy_hcd by writing lun.N/nofua (1 then 0) from one task while another task rewrites and clears lun.N/file. Cc: stable Signed-off-by: Yu Zhang Acked-by: Alan Stern Link: https://patch.msgid.link/20261020023050.87701-1-yuz08559@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_mass_storage.c | 8 ++++++-- drivers/usb/gadget/function/storage_common.c | 7 +++++-- drivers/usb/gadget/function/storage_common.h | 3 ++- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/drivers/usb/gadget/function/f_mass_storage.c b/drivers/usb/gadget/function/f_mass_storage.c index e3c9b7ab9f39ba..52314a00d8e64f 100644 --- a/drivers/usb/gadget/function/f_mass_storage.c +++ b/drivers/usb/gadget/function/f_mass_storage.c @@ -2669,8 +2669,9 @@ static ssize_t nofua_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct fsg_lun *curlun = fsg_lun_from_dev(dev); + struct rw_semaphore *filesem = dev_get_drvdata(dev); - return fsg_store_nofua(curlun, buf, count); + return fsg_store_nofua(curlun, filesem, buf, count); } static ssize_t file_store(struct device *dev, struct device_attribute *attr, @@ -3248,7 +3249,10 @@ static ssize_t fsg_lun_opts_nofua_show(struct config_item *item, char *page) static ssize_t fsg_lun_opts_nofua_store(struct config_item *item, const char *page, size_t len) { - return fsg_store_nofua(to_fsg_lun_opts(item)->lun, page, len); + struct fsg_lun_opts *opts = to_fsg_lun_opts(item); + struct fsg_opts *fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent); + + return fsg_store_nofua(opts->lun, &fsg_opts->common->filesem, page, len); } CONFIGFS_ATTR(fsg_lun_opts_, nofua); diff --git a/drivers/usb/gadget/function/storage_common.c b/drivers/usb/gadget/function/storage_common.c index 75831f2c7abeb0..51a70f2abe574a 100644 --- a/drivers/usb/gadget/function/storage_common.c +++ b/drivers/usb/gadget/function/storage_common.c @@ -415,7 +415,8 @@ ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem, } EXPORT_SYMBOL_GPL(fsg_store_ro); -ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count) +ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem, + const char *buf, size_t count) { bool nofua; int ret; @@ -425,8 +426,10 @@ ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count) return ret; /* Sync data when switching from async mode to sync */ - if (!nofua && curlun->nofua) + if (!nofua && curlun->nofua) { + guard(rwsem_read)(filesem); fsg_lun_fsync_sub(curlun); + } curlun->nofua = nofua; diff --git a/drivers/usb/gadget/function/storage_common.h b/drivers/usb/gadget/function/storage_common.h index e73a30cc553fc4..e66b753d7cbd98 100644 --- a/drivers/usb/gadget/function/storage_common.h +++ b/drivers/usb/gadget/function/storage_common.h @@ -245,7 +245,8 @@ ssize_t fsg_show_cdrom(struct fsg_lun *curlun, char *buf); ssize_t fsg_show_removable(struct fsg_lun *curlun, char *buf); ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem, const char *buf, size_t count); -ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count); +ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem, + const char *buf, size_t count); ssize_t fsg_store_file(struct fsg_lun *curlun, struct rw_semaphore *filesem, const char *buf, size_t count); ssize_t fsg_store_cdrom(struct fsg_lun *curlun, struct rw_semaphore *filesem, From d8090de52e0a8f1761ced4fc31d52a3e289e341c Mon Sep 17 00:00:00 2001 From: Thinh Nguyen Date: Wed, 21 Oct 2026 00:47:17 +0000 Subject: [PATCH 0048/2102] usb: dwc3: trace: Restore request name assignment The commit 0a06917432a7 ("usb: dwc3: Log dwc3 address in traces") removed the __assign_str(name) call from dwc3_log_request. The name field still exists in the trace event, but nothing fills it in, so the endpoint name printed for these events is leftover garbage from the ring buffer. Put the __assign_str() call back so the endpoint name is logged again. Fixes: 0a06917432a7 ("usb: dwc3: Log dwc3 address in traces") Cc: stable Signed-off-by: Thinh Nguyen Link: https://patch.msgid.link/8bd045b136bfef8ce5de79f1fa2f09db639f0707.1792543567.git.Thinh.Nguyen@synopsys.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/trace.h | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/usb/dwc3/trace.h b/drivers/usb/dwc3/trace.h index 5253da23d8b003..0caaa0b396d1c4 100644 --- a/drivers/usb/dwc3/trace.h +++ b/drivers/usb/dwc3/trace.h @@ -141,6 +141,7 @@ DECLARE_EVENT_CLASS(dwc3_log_request, ), TP_fast_assign( __entry->base_address = req->dep->dwc->xhci_resources[0].start; + __assign_str(name); __entry->req = req; __entry->actual = req->request.actual; __entry->length = req->request.length; From 2022b10726be78849626ea3fa33038ee96a54e46 Mon Sep 17 00:00:00 2001 From: Chaz Bailey Date: Fri, 16 Oct 2026 13:20:45 +0100 Subject: [PATCH 0049/2102] usb: typec: nb7vpq904m: Set client data in probe to avoid crash on remove nb7vpq904m_probe() allocates struct nb7vpq904m, but client data is not set during probe. In nb7vpq904m_remove(), i2c_get_clientdata(client) returns NULL, leading to a NULL pointer dereference when accessing nb7->retimer or nb7->sw. Set client data upon successful allocation in probe. Fixes: 88d8f3ac9c67 ("usb: typec: add support for the nb7vpq904m Type-C Linear Redriver") Cc: stable Signed-off-by: Chaz Bailey Reviewed-by: Krishna Kurapati Reviewed-by: Heikki Krogerus Link: https://patch.msgid.link/20261016122045.187862-1-charles.s.bailey@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/typec/mux/nb7vpq904m.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/usb/typec/mux/nb7vpq904m.c b/drivers/usb/typec/mux/nb7vpq904m.c index d1fa26ff442c27..52e3c9db35a72d 100644 --- a/drivers/usb/typec/mux/nb7vpq904m.c +++ b/drivers/usb/typec/mux/nb7vpq904m.c @@ -396,6 +396,7 @@ static int nb7vpq904m_probe(struct i2c_client *client) return -ENOMEM; nb7->client = client; + i2c_set_clientdata(client, nb7); nb7->regmap = devm_regmap_init_i2c(client, &nb7_regmap); if (IS_ERR(nb7->regmap)) { From 89aaaa26f6985d55676fc5c90440f279733fa132 Mon Sep 17 00:00:00 2001 From: Joonhoe Kim <26rote@gmail.com> Date: Fri, 23 Oct 2026 01:51:43 +0900 Subject: [PATCH 0050/2102] usb: typec: mux: fsa4480: Keep the USB 2.0 switch on in DP-only modes DisplayPort pin assignments C and E give all four SuperSpeed lanes to DisplayPort, but the USB 2.0 D+/D- pair is not part of the pin assignment and stays available. The FSA4480 sits on that pair, and in these modes the driver turns its USB switch off, so a USB 2.0 hub or device behind a DisplayPort sink is disconnected as soon as the DisplayPort mode is set. Configure the USB switch the same way in all DisplayPort modes. Fixes: c7054c31c1c9 ("usb: typec: fsa4480: rework mux & switch setup to handle more states") Cc: stable Signed-off-by: Joonhoe Kim <26rote@gmail.com> Reviewed-by: Konrad Dybcio Acked-by: Heikki Krogerus Link: https://patch.msgid.link/20261022165143.1327-1-26rote@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/typec/mux/fsa4480.c | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/drivers/usb/typec/mux/fsa4480.c b/drivers/usb/typec/mux/fsa4480.c index bea0c1deec94d5..e05ab3c10c8110 100644 --- a/drivers/usb/typec/mux/fsa4480.c +++ b/drivers/usb/typec/mux/fsa4480.c @@ -93,16 +93,9 @@ static int fsa4480_set(struct fsa4480 *fsa) sel = FSA4480_SEL_USB; } else if (fsa->svid) { switch (fsa->mode) { - /* DP Only */ case TYPEC_DP_STATE_C: - case TYPEC_DP_STATE_E: - enable |= FSA4480_ENABLE_SBU; - if (reverse) - sel = FSA4480_SEL_SBU_REVERSE; - break; - - /* DP + USB */ case TYPEC_DP_STATE_D: + case TYPEC_DP_STATE_E: case TYPEC_DP_STATE_F: enable |= FSA4480_ENABLE_USB | FSA4480_ENABLE_SBU; sel = FSA4480_SEL_USB; From 7cfb037005c04b9dee5b0c4626e56e2eddeef157 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=20Ahmet=20Memi=C5=9F?= Date: Sat, 24 Oct 2026 20:44:41 +0300 Subject: [PATCH 0051/2102] usb: typec: ucsi: debugfs: Fix GET commands on UCSI < 2.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since the debugfs response buffer grew to 24 bytes, every GET command fails with -EINVAL on UCSI < 2.0, where the data length is limited to 16 bytes. Clamp the length to UCSI_MAX_DATA_LENGTH(). Fixes: d9dc19910321 ("usb: typec: ucsi: Fix debugfs response truncation beyond 16 bytes") Cc: stable Signed-off-by: Ali Ahmet Memiş Reviewed-by: Heikki Krogerus Link: https://patch.msgid.link/20261024174441.878903-1-aliamemis@disroot.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/typec/ucsi/debugfs.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/usb/typec/ucsi/debugfs.c b/drivers/usb/typec/ucsi/debugfs.c index 77a0dd75edd3c3..3cffd3778c67e4 100644 --- a/drivers/usb/typec/ucsi/debugfs.c +++ b/drivers/usb/typec/ucsi/debugfs.c @@ -60,7 +60,8 @@ static int ucsi_cmd(void *data, u64 val) case UCSI_GET_LPM_PPM_INFO: ret = ucsi_send_command(ucsi, val, &ucsi->debugfs->response, - sizeof(ucsi->debugfs->response)); + min(sizeof(ucsi->debugfs->response), + UCSI_MAX_DATA_LENGTH(ucsi))); break; default: ret = -EOPNOTSUPP; From 3ee1e1c3fca6fb5d0abbe0fc91539951ffa60aa7 Mon Sep 17 00:00:00 2001 From: Ihor Urazov Date: Mon, 26 Oct 2026 01:47:52 +0200 Subject: [PATCH 0052/2102] usb: typec: ucsi: acpi: Assume UCSI 1.0 on HP ZBook 8 G2i 14 The HP ZBook 8 G2i 14 (board 8ED9) exposes a working UCSI ACPI PPM, but its UCSI VERSION field reads zero until the first command completes. ucsi_register() rejects a zero version with -ENODEV, so no Type-C ports are registered. The firmware's _DSM READ function (2) is a stub. The mailbox VERSION field is written only by the EC response handler, after a command completes, after which it reads 0x0100 (UCSI 1.0). The mailbox is 48 bytes with 16-byte MESSAGE_IN/MESSAGE_OUT fields, the UCSI 1.x layout, and _DSM function 5 is not implemented. Add a DMI-specific read_version for this board that substitutes the version the firmware itself reports, UCSI 1.0, only when VERSION reads zero. A non-zero firmware version is used as is. The same firmware defect on the HP ZBook Fury G1i 16 was discussed in "[RFC PATCH] usb: typec: ucsi: acpi: bootstrap PPM on HP systems with empty _DSM func 2" [1]. The defect was reported to HP as case 5166176673. Tested on an HP ZBook 8 G2i 14 with BIOS Y70 01.02.08, from a fresh boot where VERSION reads zero: three connectors register, the PD contract and alternate modes of a Thunderbolt dock are reported, and its DisplayPort output stays up across the PPM reset in ucsi_init(). Dock unplug/replug and s2idle suspend/resume update the connector state without errors. Link: https://lore.kernel.org/linux-usb/f3M_fpjtt8FxDqGKcA84vqXmRbKzCBfpCrIK4-jCWvIscER51zkD8qD8FYpz75qZw51rMDRSkUyYlrBvLvdM8CGRY2l8TFVvr4MC1LdTzbc=@interstellar.eu/ [1] Fixes: c1b0bc2dabfa ("usb: typec: Add support for UCSI interface") Cc: stable Cc: Francesco Orro Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Ihor Urazov Reviewed-by: Heikki Krogerus Reviewed-by: Huang Wei Link: https://patch.msgid.link/20261026-ucsi-hp-zbook-8-g2i-v1-1-91002e9ef073@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/typec/ucsi/ucsi_acpi.c | 35 ++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/drivers/usb/typec/ucsi/ucsi_acpi.c b/drivers/usb/typec/ucsi/ucsi_acpi.c index 5697ccc24ec3fc..2421a92ecb0e4e 100644 --- a/drivers/usb/typec/ucsi/ucsi_acpi.c +++ b/drivers/usb/typec/ucsi/ucsi_acpi.c @@ -148,6 +148,34 @@ static const struct ucsi_operations ucsi_acer_ops = { .async_control = ucsi_acpi_async_control }; +static int ucsi_hp_read_version(struct ucsi *ucsi, u16 *version) +{ + struct ucsi_acpi *ua = ucsi_get_drvdata(ucsi); + int ret; + + ret = ucsi_acpi_read_version(ucsi, version); + if (ret) + return ret; + + /* Firmware fills in VERSION (1.0) only after the first command completes */ + if (!*version) { + dev_warn(ua->dev, "UCSI version is zero, assuming 1.0\n"); + *version = UCSI_VERSION_1_0; + } + + return 0; +} + +static const struct ucsi_operations ucsi_hp_ops = { + .read_version = ucsi_hp_read_version, + .read_cci = ucsi_acpi_read_cci, + .poll_cci = ucsi_acpi_poll_cci, + .read_message_in = ucsi_acpi_read_message_in, + .write_message_out = ucsi_acpi_write_message_out, + .sync_control = ucsi_sync_control_common, + .async_control = ucsi_acpi_async_control +}; + static int ucsi_gram_sync_control(struct ucsi *ucsi, u64 command, u32 *cci, void *val, size_t len, void *msg_out, size_t msg_out_size) @@ -196,6 +224,13 @@ static const struct dmi_system_id ucsi_acpi_quirks[] = { }, .driver_data = (void *)&ucsi_acer_ops, }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "HP"), + DMI_MATCH(DMI_BOARD_NAME, "8ED9"), + }, + .driver_data = (void *)&ucsi_hp_ops, + }, { .matches = { DMI_MATCH(DMI_SYS_VENDOR, "LG Electronics"), From 5eb11b1647b0534b3a61a21473d77ebf4ffbed7c Mon Sep 17 00:00:00 2001 From: Thinh Nguyen Date: Wed, 21 Oct 2026 00:37:51 +0000 Subject: [PATCH 0053/2102] usb: dwc3: gadget: Reject requests to a disabled endpoint __dwc3_gadget_ep_disable() releases the lock while giving back requests, and DWC3_EP_ENABLED is only cleared afterward. A function driver can queue a new request in this window, and the driver would start a transfer on an endpoint that is already disabled in hardware. Clear DWC3_EP_ENABLED before giving back the requests, and reject requests queued to an endpoint that is not enabled. Fixes: 72246da40f37 ("usb: Introduce DesignWare USB3 DRD Driver") Cc: stable Signed-off-by: Thinh Nguyen Link: https://patch.msgid.link/4ceab6aa5d6af0e4780f9d3a964fd5d8168a0a02.1792542945.git.Thinh.Nguyen@synopsys.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/gadget.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/drivers/usb/dwc3/gadget.c b/drivers/usb/dwc3/gadget.c index ee837235630ad9..eb6666b7bb989b 100644 --- a/drivers/usb/dwc3/gadget.c +++ b/drivers/usb/dwc3/gadget.c @@ -1084,6 +1084,8 @@ static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep) reg &= ~DWC3_DALEPENA_EP(dep->number); dwc3_writel(dwc, DWC3_DALEPENA, reg); + dep->flags &= ~DWC3_EP_ENABLED; + dwc3_remove_requests(dwc, dep, -ESHUTDOWN); dep->stream_capable = false; @@ -1990,7 +1992,8 @@ static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req) { struct dwc3 *dwc = dep->dwc; - if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) { + if (!(dep->flags & DWC3_EP_ENABLED) || !dep->endpoint.desc || + !dwc->pullups_connected || !dwc->connected) { dev_dbg(dwc->dev, "%s: can't queue to disabled endpoint\n", dep->name); return -ESHUTDOWN; From af91c6322e633504aa45de278f5d520f39d127be Mon Sep 17 00:00:00 2001 From: Thinh Nguyen Date: Wed, 21 Oct 2026 00:37:56 +0000 Subject: [PATCH 0054/2102] usb: dwc3: gadget: Track a timed out End Transfer If an End Transfer command with CMDIOC times out, the driver clears the resource index but keeps DWC3_EP_TRANSFER_STARTED without setting DWC3_EP_END_TRANSFER_PENDING. The command is still outstanding, but a later stop issues another End Transfer with resource index 0, and the next Start Transfer fails with "No Resource". Mark the timed out End Transfer as pending so that no other command is issued to the endpoint until it completes. For any other failure, there is no outstanding command, so clear DWC3_EP_TRANSFER_STARTED. Fixes: e192cc7b5239 ("usb: dwc3: gadget: move cmd_endtransfer to extra function") Cc: stable Reported-by: Selvarasu Ganesan Closes: https://lore.kernel.org/linux-usb/3fdda532-8181-48e9-b58d-cad7289408e7@samsung.com/ Signed-off-by: Thinh Nguyen Link: https://patch.msgid.link/5815c41a7e7923edb114741f29697cf0161f523c.1792542945.git.Thinh.Nguyen@synopsys.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/gadget.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/usb/dwc3/gadget.c b/drivers/usb/dwc3/gadget.c index eb6666b7bb989b..df5407e757884e 100644 --- a/drivers/usb/dwc3/gadget.c +++ b/drivers/usb/dwc3/gadget.c @@ -1798,9 +1798,9 @@ static int __dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool int dep->resource_index = 0; - if (!interrupt) + if (!interrupt || (ret && ret != -ETIMEDOUT)) dep->flags &= ~DWC3_EP_TRANSFER_STARTED; - else if (!ret) + else dep->flags |= DWC3_EP_END_TRANSFER_PENDING; dep->flags &= ~DWC3_EP_DELAY_STOP; From f2bd20f92a7dc68980a6098397503067192ce63a Mon Sep 17 00:00:00 2001 From: Thinh Nguyen Date: Wed, 21 Oct 2026 00:38:02 +0000 Subject: [PATCH 0055/2102] usb: dwc3: gadget: Clear delayed stop on End Transfer completion When an End Transfer command times out outside of the SETUP phase, the driver sets DWC3_EP_DELAY_STOP to retry it on the next SETUP phase. If the command completes in the meantime, the flag is left set. Requests queued to the endpoint are then deferred, and the retry may end a transfer that is started later. Clear DWC3_EP_DELAY_STOP when the End Transfer command completes. Fixes: 4db0fbb60136 ("usb: dwc3: gadget: Don't delay End Transfer on delayed_status") Cc: stable Signed-off-by: Thinh Nguyen Link: https://patch.msgid.link/c28a9660f7b6bfa626077ddcfbadd50e6b503f86.1792542945.git.Thinh.Nguyen@synopsys.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/gadget.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/usb/dwc3/gadget.c b/drivers/usb/dwc3/gadget.c index df5407e757884e..4de3b81cb6781d 100644 --- a/drivers/usb/dwc3/gadget.c +++ b/drivers/usb/dwc3/gadget.c @@ -3875,6 +3875,7 @@ static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep, if (dep->stream_capable) dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM; + dep->flags &= ~DWC3_EP_DELAY_STOP; dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING; dep->flags &= ~DWC3_EP_TRANSFER_STARTED; dwc3_gadget_ep_cleanup_cancelled_requests(dep); From e616d91e02881983e5dadf6980c4aa08123800b3 Mon Sep 17 00:00:00 2001 From: Thinh Nguyen Date: Wed, 21 Oct 2026 00:38:07 +0000 Subject: [PATCH 0056/2102] usb: dwc3: gadget: Issue no-op Start Transfer only for stream endpoints The function driver may re-enable an endpoint before the End Transfer command issued on ep disable completes. The no-op Start Transfer issued on ep enable then fails with "No Resource". Only stream endpoints need the no-op Start Transfer to initiate a stream. Other bulk and interrupt endpoints start their transfer when a request is queued. Skip it for those endpoints, and move it to a helper to be reused. Fixes: a97ea994605e ("usb: dwc3: gadget: offset Start Transfer latency for bulk EPs") Cc: stable Reported-by: Selvarasu Ganesan Closes: https://lore.kernel.org/linux-usb/20260227121236.963-1-selvarasu.g@samsung.com/ Signed-off-by: Thinh Nguyen Link: https://patch.msgid.link/227e97e30d26a017c92d7008a8633c01f955d088.1792542945.git.Thinh.Nguyen@synopsys.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/gadget.c | 97 ++++++++++++++++++++------------------- 1 file changed, 50 insertions(+), 47 deletions(-) diff --git a/drivers/usb/dwc3/gadget.c b/drivers/usb/dwc3/gadget.c index 4de3b81cb6781d..e68584f20fbdea 100644 --- a/drivers/usb/dwc3/gadget.c +++ b/drivers/usb/dwc3/gadget.c @@ -906,6 +906,54 @@ static int dwc3_gadget_resize_tx_fifos(struct dwc3_ep *dep) return 0; } +static int dwc3_gadget_ep_start_noop_transfer(struct dwc3_ep *dep) +{ + struct dwc3_gadget_ep_cmd_params params; + struct dwc3 *dwc = dep->dwc; + struct dwc3_trb *trb; + dma_addr_t trb_dma; + u32 cmd; + int ret; + + memset(¶ms, 0, sizeof(params)); + trb = &dep->trb_pool[0]; + trb_dma = dwc3_trb_dma_offset(dep, trb); + + params.param0 = upper_32_bits(trb_dma); + params.param1 = lower_32_bits(trb_dma); + + cmd = DWC3_DEPCMD_STARTTRANSFER; + + ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms); + if (ret < 0) + return ret; + + /* + * For streams, at start, there maybe a race where the host primes the + * endpoint before the function driver queues a request to initiate a + * stream. In that case, the controller will not see the prime to + * generate the ERDY and start stream. To workaround this, issue a + * no-op TRB as normal, but end it immediately. As a result, when the + * function driver queues the request, the next START_TRANSFER command + * will cause the controller to generate an ERDY to initiate the + * stream. + */ + dwc3_stop_active_transfer(dep, false, true); + + /* + * All stream eps will reinitiate stream on NoStream rejection. + * + * However, if the controller is capable of TXF_FLUSH_BYPASS, then IN + * direction endpoints will automatically restart the stream without + * the driver initiation. + */ + if (!dep->direction || + !(dwc->hwparams.hwparams9 & DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS)) + dep->flags |= DWC3_EP_FORCE_RESTART_STREAM; + + return 0; +} + /** * __dwc3_gadget_ep_enable - initializes a hw endpoint * @dep: endpoint to be initialized @@ -971,55 +1019,10 @@ static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action) * Issue StartTransfer here with no-op TRB so we can always rely on No * Response Update Transfer command. */ - if (usb_endpoint_xfer_bulk(desc) || - usb_endpoint_xfer_int(desc)) { - struct dwc3_gadget_ep_cmd_params params; - struct dwc3_trb *trb; - dma_addr_t trb_dma; - u32 cmd; - - memset(¶ms, 0, sizeof(params)); - trb = &dep->trb_pool[0]; - trb_dma = dwc3_trb_dma_offset(dep, trb); - - params.param0 = upper_32_bits(trb_dma); - params.param1 = lower_32_bits(trb_dma); - - cmd = DWC3_DEPCMD_STARTTRANSFER; - - ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms); + if (dep->stream_capable) { + ret = dwc3_gadget_ep_start_noop_transfer(dep); if (ret < 0) return ret; - - if (dep->stream_capable) { - /* - * For streams, at start, there maybe a race where the - * host primes the endpoint before the function driver - * queues a request to initiate a stream. In that case, - * the controller will not see the prime to generate the - * ERDY and start stream. To workaround this, issue a - * no-op TRB as normal, but end it immediately. As a - * result, when the function driver queues the request, - * the next START_TRANSFER command will cause the - * controller to generate an ERDY to initiate the - * stream. - */ - dwc3_stop_active_transfer(dep, false, true); - - /* - * All stream eps will reinitiate stream on NoStream - * rejection. - * - * However, if the controller is capable of - * TXF_FLUSH_BYPASS, then IN direction endpoints will - * automatically restart the stream without the driver - * initiation. - */ - if (!dep->direction || - !(dwc->hwparams.hwparams9 & - DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS)) - dep->flags |= DWC3_EP_FORCE_RESTART_STREAM; - } } out: From 1338410c21a5710b7ba88057034d35367ba0f054 Mon Sep 17 00:00:00 2001 From: Thinh Nguyen Date: Wed, 21 Oct 2026 00:38:13 +0000 Subject: [PATCH 0057/2102] usb: dwc3: gadget: Wait for End Transfer completion on ep disable The End Transfer command on ep disable is issued without interrupt, and the endpoint flags are cleared right after a fixed delay. The command may not have completed by then. If the function driver re-enables the endpoint and queues a request, the next Start Transfer fails with "No Resource". Issue the End Transfer command with interrupt on ep disable, and keep DWC3_EP_END_TRANSFER_PENDING and DWC3_EP_TRANSFER_STARTED until the command completes. Defer the no-op Start Transfer of a stream endpoint re-enabled in the meantime to the command completion. Fixes: c5353b225df9 ("usb: dwc3: gadget: don't enable interrupt when disabling endpoint") Cc: stable Reported-by: Selvarasu Ganesan Closes: https://lore.kernel.org/linux-usb/20260227121236.963-1-selvarasu.g@samsung.com/ Signed-off-by: Thinh Nguyen Link: https://patch.msgid.link/24fa8adeb0222dab415c8c2799405188440bad4b.1792542945.git.Thinh.Nguyen@synopsys.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/core.h | 4 +++- drivers/usb/dwc3/ep0.c | 2 +- drivers/usb/dwc3/gadget.c | 42 ++++++++++++++++++++++++++++++++------- 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/drivers/usb/dwc3/core.h b/drivers/usb/dwc3/core.h index f3dabb37f806b6..267c922ca11bb6 100644 --- a/drivers/usb/dwc3/core.h +++ b/drivers/usb/dwc3/core.h @@ -771,6 +771,7 @@ struct dwc3_ep { #define DWC3_EP_TXFIFO_RESIZED BIT(12) #define DWC3_EP_DELAY_STOP BIT(13) #define DWC3_EP_RESOURCE_ALLOCATED BIT(14) +#define DWC3_EP_PENDING_NOOP_START BIT(15) /* This last one is specific to EP0 */ #define DWC3_EP0_DIR_IN BIT(31) @@ -1695,7 +1696,8 @@ int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned int cmd, int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd, u32 param); void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc); -void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status); +void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status, + bool interrupt); #else static inline int dwc3_gadget_init(struct dwc3 *dwc) { return 0; } diff --git a/drivers/usb/dwc3/ep0.c b/drivers/usb/dwc3/ep0.c index 46a34c4a046b40..cf5a47b71efc81 100644 --- a/drivers/usb/dwc3/ep0.c +++ b/drivers/usb/dwc3/ep0.c @@ -315,7 +315,7 @@ void dwc3_ep0_out_start(struct dwc3 *dwc) if (dwc->connected) dwc3_stop_active_transfer(dwc3_ep, false, true); else - dwc3_remove_requests(dwc, dwc3_ep, -ESHUTDOWN); + dwc3_remove_requests(dwc, dwc3_ep, -ESHUTDOWN, false); } } diff --git a/drivers/usb/dwc3/gadget.c b/drivers/usb/dwc3/gadget.c index e68584f20fbdea..e531adc02a4010 100644 --- a/drivers/usb/dwc3/gadget.c +++ b/drivers/usb/dwc3/gadget.c @@ -1020,9 +1020,14 @@ static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action) * Response Update Transfer command. */ if (dep->stream_capable) { - ret = dwc3_gadget_ep_start_noop_transfer(dep); - if (ret < 0) - return ret; + if (dep->flags & (DWC3_EP_END_TRANSFER_PENDING | + DWC3_EP_DELAY_STOP)) { + dep->flags |= DWC3_EP_PENDING_NOOP_START; + } else { + ret = dwc3_gadget_ep_start_noop_transfer(dep); + if (ret < 0) + return ret; + } } out: @@ -1031,16 +1036,21 @@ static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action) return 0; } -void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status) +void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status, + bool interrupt) { struct dwc3_request *req; - dwc3_stop_active_transfer(dep, false, false); + dwc3_stop_active_transfer(dep, false, interrupt); /* If endxfer is delayed, avoid unmapping requests */ if (dep->flags & DWC3_EP_DELAY_STOP) return; + /* Give the controller time to stop accessing the request buffers */ + if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) + mdelay(1); + /* - giveback all requests to gadget driver */ while (!list_empty(&dep->started_list)) { req = next_request(&dep->started_list); @@ -1089,7 +1099,7 @@ static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep) dep->flags &= ~DWC3_EP_ENABLED; - dwc3_remove_requests(dwc, dep, -ESHUTDOWN); + dwc3_remove_requests(dwc, dep, -ESHUTDOWN, true); dep->stream_capable = false; dep->type = 0; @@ -1101,6 +1111,15 @@ static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep) */ if (dep->flags & DWC3_EP_DELAY_STOP) mask |= (DWC3_EP_DELAY_STOP | DWC3_EP_TRANSFER_STARTED); + + /* + * The End Transfer command is still in progress. Do not clear the + * flags, so that the ep is only rearmed once the command completes. + */ + if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) + mask |= (DWC3_EP_END_TRANSFER_PENDING | + DWC3_EP_TRANSFER_STARTED); + dep->flags &= mask; /* Clear out the ep descriptors for non-ep0 */ @@ -2553,7 +2572,7 @@ static void dwc3_stop_active_transfers(struct dwc3 *dwc) if (!dep) continue; - dwc3_remove_requests(dwc, dep, -ESHUTDOWN); + dwc3_remove_requests(dwc, dep, -ESHUTDOWN, false); } } @@ -3901,7 +3920,16 @@ static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep, dwc3_ep0_send_delayed_status(dwc); } + if (dep->flags & DWC3_EP_PENDING_NOOP_START) { + dep->flags &= ~DWC3_EP_PENDING_NOOP_START; + + if (!(dep->flags & DWC3_EP_DELAY_START) && + (dep->flags & DWC3_EP_ENABLED)) + dwc3_gadget_ep_start_noop_transfer(dep); + } + if ((dep->flags & DWC3_EP_DELAY_START) && + (dep->flags & DWC3_EP_ENABLED) && !usb_endpoint_xfer_isoc(dep->endpoint.desc)) __dwc3_gadget_kick_transfer(dep); From 7c9bc134e5b3315e0456cda9e8e59c752309ea78 Mon Sep 17 00:00:00 2001 From: Thinh Nguyen Date: Wed, 21 Oct 2026 00:38:19 +0000 Subject: [PATCH 0058/2102] usb: dwc3: gadget: Reset endpoint flags on controller start The flags of a disabled endpoint may be preserved while its End Transfer command is pending. If the command never completes, the stale flags persist across a soft disconnect or an error recovery, and the endpoint can't be used again. Reset the flags of all non-control endpoints when starting the controller. Fixes: 76bff31c7fba ("usb: dwc3: gadget: Do not clear ep delayed stop flag during ep disable") Cc: stable Signed-off-by: Thinh Nguyen Link: https://patch.msgid.link/21cd189962b9d32a4f9df381df4947d35341d5a9.1792542945.git.Thinh.Nguyen@synopsys.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/gadget.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/drivers/usb/dwc3/gadget.c b/drivers/usb/dwc3/gadget.c index e531adc02a4010..a8f12e583a0f4a 100644 --- a/drivers/usb/dwc3/gadget.c +++ b/drivers/usb/dwc3/gadget.c @@ -2972,6 +2972,7 @@ static int __dwc3_gadget_start(struct dwc3 *dwc) { struct dwc3_ep *dep; int ret = 0; + u32 epnum; u32 reg; /* @@ -3029,6 +3030,15 @@ static int __dwc3_gadget_start(struct dwc3 *dwc) return ret; } + for (epnum = 2; epnum < dwc->num_eps; epnum++) { + dep = dwc->eps[epnum]; + if (!dep) + continue; + + dep->flags &= (DWC3_EP_TXFIFO_RESIZED | + DWC3_EP_RESOURCE_ALLOCATED); + } + dep = dwc->eps[0]; dep->flags = 0; ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT); From 61575534fb05d52d36979f38976ece74649f091a Mon Sep 17 00:00:00 2001 From: Thinh Nguyen Date: Wed, 21 Oct 2026 00:38:24 +0000 Subject: [PATCH 0059/2102] usb: dwc3: gadget: Recover from End Transfer timeout If the End Transfer command times out, the endpoint resource is never released and every subsequent Start Transfer to the endpoint fails with "No Resource". Schedule an error recovery to reset the controller. Signed-off-by: Thinh Nguyen Cc: stable Link: https://patch.msgid.link/7523e9a11303a33acd0b92a092fb0e8218d509d2.1792542945.git.Thinh.Nguyen@synopsys.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/gadget.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/drivers/usb/dwc3/gadget.c b/drivers/usb/dwc3/gadget.c index a8f12e583a0f4a..a76f669a796c2e 100644 --- a/drivers/usb/dwc3/gadget.c +++ b/drivers/usb/dwc3/gadget.c @@ -1775,6 +1775,8 @@ static int __dwc3_gadget_get_frame(struct dwc3 *dwc) return DWC3_DSTS_SOFFN(reg); } +static void dwc3_schedule_err_recovery(struct dwc3 *dwc); + /** * __dwc3_stop_active_transfer - stop the current active transfer * @dep: isoc endpoint @@ -1818,6 +1820,9 @@ static int __dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool int dev_err_ratelimited(dep->dwc->dev, "end transfer failed: %d\n", ret); + if (ret == -ETIMEDOUT && dep->dwc->err_state == DWC3_ERR_NONE) + dwc3_schedule_err_recovery(dep->dwc); + dep->resource_index = 0; if (!interrupt || (ret && ret != -ETIMEDOUT)) From 03e3c33fe074ba57ae4457894fe5b6a90e3be6ee Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:24:52 +0100 Subject: [PATCH 0060/2102] thunderbolt: stream: Undo more if the start fails If the receive buffers cannot be allocated or mapped, tbstream_dev_start() stops and frees the rings, but - leaves the DMA paths through the XDomain connection enabled, with the hop IDs of rings which no longer exist; - does not release the frame array and the pages which tbstream_dev_alloc_rx_buffers() had allocated and mapped before it failed. Fixes: 6db21d817b43 ("thunderbolt: Add support for USB4STREAM") Cc: stable Cc: Andreas Noever Cc: Mika Westerberg Cc: Yehezkel Bernat Cc: Alan Borzeszkowski Signed-off-by: Josef Bacik Acked-by: Mika Westerberg (Intel) Link: https://patch.msgid.link/2026102751-nibble-synapse-d406@gregkh Signed-off-by: Greg Kroah-Hartman --- drivers/thunderbolt/stream.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/thunderbolt/stream.c b/drivers/thunderbolt/stream.c index 4f9a57b77bfa28..c9e1987a69242d 100644 --- a/drivers/thunderbolt/stream.c +++ b/drivers/thunderbolt/stream.c @@ -683,6 +683,12 @@ static int tbstream_dev_start(struct tbstream_dev *sdev) err_stop: tb_ring_stop(sdev->rx_ring.ring); tb_ring_stop(sdev->tx_ring.ring); + tb_xdomain_disable_paths(xd, sdev->out_hopid, + sdev->tx_ring.ring->hop, + sdev->in_hopid, + sdev->rx_ring.ring->hop); + if (sdev->rx_ring.frames) + tbstream_ring_free(&sdev->rx_ring); err_free_rx: tb_ring_free(sdev->rx_ring.ring); err_free_tx_buffers: From 1981b53c2b52a00f0f4b9eb87183c9aedc8dac5d Mon Sep 17 00:00:00 2001 From: Krystian Kaniewski Date: Thu, 22 Oct 2026 11:13:59 +0200 Subject: [PATCH 0061/2102] usb: gadget: u_serial: pin ports while TTYs are installed A slab-use-after-free can occur when gserial_free_line() frees struct gs_port while it is still reachable through an installed TTY. The port->port.count value tracks successful opens, but it is zero before gs_open() and again after gs_close(), before TTY cleanup has finished. Teardown can therefore free gs_port while tty_init_dev() or release_tty() still accesses its tty_port. Manage gs_port lifetime with tty_port references. Take a reference in gs_install(), drop it in gs_cleanup(), and move the final free to gs_port_destruct(). Unregister the TTY device before dropping the owner reference. Keep each minor reserved until the old port is destroyed so an installed TTY for one generation cannot overlap a replacement at the same minor. Publish the new port before device registration so the cdev and add uevent never expose a TTY before gs_install() can pin it. Since commit 8df07fe93573 ("tty: fix saved termios reset race"), u_serial registration no longer frees saved termios. On registration failure, unpublish the port before dropping its owner reference. Check in gs_open() that the installed port is still the published generation. Track failures after a successful install so close callbacks issued by the TTY core do not decrement port->port.count for opens that never incremented it. Fixes: 19b10a8828a6 ("usb: gadget: allocate & giveback serial ports instead hard code them") Assisted-by: Gemini:gemini-3.8-flash syzbot Reported-by: syzbot+fe63e4d633540f230624@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=fe63e4d633540f230624 Link: https://syzkaller.appspot.com/ai_job?id=ec789387-2e7b-4a8f-a7a1-a47bf7fa57f5 Cc: stable Signed-off-by: Krystian Kaniewski Tested-by: syzbot@syzkaller.appspotmail.com Tested-by: Mehmet Fide Reported-by: syzbot+bca09f5d8b843bbf7571@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=bca09f5d8b843bbf7571 Link: https://patch.msgid.link/20261022091359.1187468-1-krystianmkaniewski@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/u_serial.c | 167 ++++++++++++++++++++----- 1 file changed, 134 insertions(+), 33 deletions(-) diff --git a/drivers/usb/gadget/function/u_serial.c b/drivers/usb/gadget/function/u_serial.c index 892d2673e9b052..0a304f508bc384 100644 --- a/drivers/usb/gadget/function/u_serial.c +++ b/drivers/usb/gadget/function/u_serial.c @@ -70,10 +70,28 @@ * gserial->ioport == usb_ep->driver_data ... gs_port * gs_port->port_usb ... gserial * - * gs_port <---> tty_struct ... links will be null when the TTY file - * isn't opened; managed by gs_open()/gs_close() - * gserial->port_tty ... tty_struct - * tty_struct->driver_data ... gserial + * gs_port <---> tty_struct: + * tty->driver_data refers to gs_port from install through cleanup, + * pinning the port via tty_port reference counting. + * gs_port->port.tty exists only while the port is open. + * + * Each entry in ports[] is guarded by ports[i].lock and models three states: + * - Free: !port && !reserved + * - Published: port && reserved + * - Retiring: !port && reserved + * + * A minor remains reserved until gs_port_destruct() runs upon final tty_port + * release, preventing minor reuse while cleanup of the installed TTY is still + * underway. The owner reference is retained through device unregister so the + * destructor releases the reservation only after device teardown is complete. + * + * open_close_failures tracks failed gs_open() calls where port->port.count + * was not incremented. The TTY core calls gs_close() on open failure to tear + * down the tty; tracking failures as aggregate credits allows gs_close() to + * consume a credit and exit without decrementing port->port.count. Credits + * are aggregate rather than paired with individual files (another gs_close() + * can consume a failed open's credit before that file's own close runs). + * It is protected by tty_lock. */ /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the @@ -128,6 +146,7 @@ struct gs_port { wait_queue_head_t close_wait; bool suspended; /* port suspended */ bool start_delayed; /* delay start when suspended */ + unsigned int open_close_failures; /* protected by tty_lock */ struct async_icount icount; /* REVISIT this state ... */ @@ -135,8 +154,9 @@ struct gs_port { }; static struct portmaster { - struct mutex lock; /* protect open/close */ + struct mutex lock; /* protect open/close and port slot */ struct gs_port *port; + bool reserved; } ports[MAX_U_SERIAL_PORTS]; #define GS_CLOSE_TIMEOUT 15 /* seconds */ @@ -603,22 +623,60 @@ static int gserial_wakeup_host(struct gserial *gser) /* TTY Driver */ +static int gs_install(struct tty_driver *driver, struct tty_struct *tty) +{ + struct gs_port *port; + struct tty_port *tport; + int ret; + + mutex_lock(&ports[tty->index].lock); + port = ports[tty->index].port; + if (!port) { + mutex_unlock(&ports[tty->index].lock); + return -ENODEV; + } + + tport = tty_port_get(&port->port); + if (!tport) { + mutex_unlock(&ports[tty->index].lock); + return -ENODEV; + } + + ret = tty_port_install(tport, driver, tty); + if (ret) { + mutex_unlock(&ports[tty->index].lock); + tty_port_put(tport); + return ret; + } + + tty->driver_data = port; + mutex_unlock(&ports[tty->index].lock); + + return 0; +} + +static void gs_cleanup(struct tty_struct *tty) +{ + tty_port_put(tty->port); +} + /* - * gs_open sets up the link between a gs_port and its associated TTY. - * That link is broken *only* by TTY close(), and all driver methods - * know that. + * gs_open associates an open TTY with its gs_port. + * + * There are two TTY-to-port relationships: port->port.tty exists from the + * first successful open until final close, while tty->driver_data is assigned + * during gs_install() and remains valid through gs_cleanup(). */ static int gs_open(struct tty_struct *tty, struct file *file) { int port_num = tty->index; - struct gs_port *port; + struct gs_port *port = tty->driver_data; int status = 0; mutex_lock(&ports[port_num].lock); - port = ports[port_num].port; - if (!port) { + if (ports[port_num].port != port) { status = -ENODEV; - goto out; + goto fail_unlock; } spin_lock_irq(&port->port_lock); @@ -638,7 +696,7 @@ static int gs_open(struct tty_struct *tty, struct file *file) if (status) { pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n", port_num, tty, file); - goto out; + goto fail_unlock; } spin_lock_irq(&port->port_lock); @@ -648,7 +706,6 @@ static int gs_open(struct tty_struct *tty, struct file *file) if (port->port.count++) goto exit_unlock_port; - tty->driver_data = port; port->port.tty = tty; /* if connected, start the I/O stream */ @@ -672,7 +729,11 @@ static int gs_open(struct tty_struct *tty, struct file *file) exit_unlock_port: spin_unlock_irq(&port->port_lock); -out: + mutex_unlock(&ports[port_num].lock); + return status; + +fail_unlock: + port->open_close_failures++; mutex_unlock(&ports[port_num].lock); return status; } @@ -698,6 +759,11 @@ static void gs_close(struct tty_struct *tty, struct file *file) if (!port) return; + if (port->open_close_failures > 0) { + port->open_close_failures--; + return; + } + spin_lock_irq(&port->port_lock); if (port->port.count != 1) { @@ -912,8 +978,10 @@ static int gs_get_icount(struct tty_struct *tty, } static const struct tty_operations gs_tty_ops = { + .install = gs_install, .open = gs_open, .close = gs_close, + .cleanup = gs_cleanup, .write = gs_write, .put_char = gs_put_char, .flush_chars = gs_flush_chars, @@ -1206,14 +1274,41 @@ static void gs_console_exit(struct gs_port *port) #endif -static int +static void gs_port_destruct(struct tty_port *tport) +{ + struct gs_port *port = container_of(tport, struct gs_port, port); + unsigned int port_num = port->port_num; + + mutex_lock(&ports[port_num].lock); + if (WARN_ON(ports[port_num].port)) + ports[port_num].port = NULL; + WARN_ON(!ports[port_num].reserved); + if (gs_tty_driver) + gs_tty_driver->ports[port_num] = NULL; + ports[port_num].reserved = false; + mutex_unlock(&ports[port_num].lock); + + kfifo_free(&port->port_write_buf); + kfree(port); +} + +static const struct tty_port_operations gs_port_ops = { + .destruct = gs_port_destruct, +}; + +static struct gs_port * gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) { struct gs_port *port; int ret = 0; mutex_lock(&ports[port_num].lock); - if (ports[port_num].port) { + if (WARN_ON_ONCE(ports[port_num].port && !ports[port_num].reserved)) { + ret = -EBUSY; + goto out; + } + + if (ports[port_num].reserved) { ret = -EBUSY; goto out; } @@ -1225,6 +1320,7 @@ gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) } tty_port_init(&port->port); + port->port.ops = &gs_port_ops; spin_lock_init(&port->port_lock); init_waitqueue_head(&port->drain_wait); init_waitqueue_head(&port->close_wait); @@ -1238,10 +1334,14 @@ gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) port->port_num = port_num; port->port_line_coding = *coding; + ports[port_num].reserved = true; ports[port_num].port = port; + mutex_unlock(&ports[port_num].lock); + return port; + out: mutex_unlock(&ports[port_num].lock); - return ret; + return ERR_PTR(ret); } static int gs_closed(struct gs_port *port) @@ -1261,8 +1361,7 @@ static void gserial_free_port(struct gs_port *port) /* wait for old opens to finish */ wait_event(port->close_wait, gs_closed(port)); WARN_ON(port->port_usb != NULL); - tty_port_destroy(&port->port); - kfree(port); + tty_port_put(&port->port); } void gserial_free_line(unsigned char port_num) @@ -1279,15 +1378,15 @@ void gserial_free_line(unsigned char port_num) ports[port_num].port = NULL; mutex_unlock(&ports[port_num].lock); - gserial_free_port(port); tty_unregister_device(gs_tty_driver, port_num); + gserial_free_port(port); } EXPORT_SYMBOL_GPL(gserial_free_line); int gserial_alloc_line_no_console(unsigned char *line_num) { struct usb_cdc_line_coding coding; - struct gs_port *port; + struct gs_port *port = ERR_PTR(-EBUSY); struct device *tty_dev; int ret; int port_num; @@ -1298,19 +1397,20 @@ int gserial_alloc_line_no_console(unsigned char *line_num) coding.bDataBits = USB_CDC_1_STOP_BITS; for (port_num = 0; port_num < MAX_U_SERIAL_PORTS; port_num++) { - ret = gs_port_alloc(port_num, &coding); - if (ret == -EBUSY) - continue; - if (ret) + port = gs_port_alloc(port_num, &coding); + if (IS_ERR(port)) { + ret = PTR_ERR(port); + if (ret == -EBUSY) + continue; return ret; + } break; } - if (ret) - return ret; + if (IS_ERR(port)) + return PTR_ERR(port); /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */ - port = ports[port_num].port; tty_dev = tty_port_register_device(&port->port, gs_tty_driver, port_num, NULL); if (IS_ERR(tty_dev)) { @@ -1319,14 +1419,15 @@ int gserial_alloc_line_no_console(unsigned char *line_num) ret = PTR_ERR(tty_dev); mutex_lock(&ports[port_num].lock); + WARN_ON(ports[port_num].port != port); ports[port_num].port = NULL; mutex_unlock(&ports[port_num].lock); - gserial_free_port(port); - goto err; + tty_port_put(&port->port); + return ret; } + *line_num = port_num; -err: - return ret; + return 0; } EXPORT_SYMBOL_GPL(gserial_alloc_line_no_console); From 78a8d6537f1de34770e460edee360b556ef40427 Mon Sep 17 00:00:00 2001 From: Sonali Pradhan Date: Wed, 28 Oct 2026 07:48:21 +0000 Subject: [PATCH 0062/2102] usb: gadget: f_midi: fix UAF race during IN request handling f_midi_disable() drains and frees pre-allocated IN requests from in_req_fifo without holding midi->transmit_lock. If f_midi_transmit() runs concurrently on the workqueue, f_midi_do_transmit() can peek a request from in_req_fifo and write into its buffer while f_midi_disable() frees it, leading to a use-after-free. Additionally, when usb_ep_queue() fails in f_midi_do_transmit() (such as with -ESHUTDOWN when the endpoint is disabled concurrently), it resets req->length = 0 and returns active instead of the error code, causing the do-while loop in f_midi_transmit() to keep spinning under midi->transmit_lock until the substream is drained. Fix this by acquiring midi->transmit_lock in f_midi_disable() while releasing IN requests from in_req_fifo, and returning the error code from f_midi_do_transmit() when usb_ep_queue() fails so f_midi_transmit() aborts immediately and drops active substreams. Fixes: e1e3d7ec5da3 ("usb: gadget: f_midi: pre-allocate IN requests") Cc: stable Signed-off-by: Sonali Pradhan Link: https://patch.msgid.link/20261028074821.579450-1-sonalipradhan@google.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_midi.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/usb/gadget/function/f_midi.c b/drivers/usb/gadget/function/f_midi.c index 63fb6ee70a3d65..48cda34399e818 100644 --- a/drivers/usb/gadget/function/f_midi.c +++ b/drivers/usb/gadget/function/f_midi.c @@ -420,6 +420,7 @@ static void f_midi_disable(struct usb_function *f) struct f_midi *midi = func_to_midi(f); struct usb_composite_dev *cdev = f->config->cdev; struct usb_request *req = NULL; + unsigned long flags; DBG(cdev, "disable\n"); @@ -431,8 +432,10 @@ static void f_midi_disable(struct usb_function *f) usb_ep_disable(midi->out_ep); /* release IN requests */ + spin_lock_irqsave(&midi->transmit_lock, flags); while (kfifo_get(&midi->in_req_fifo, &req)) free_ep_req(midi->in_ep, req); + spin_unlock_irqrestore(&midi->transmit_lock, flags); f_midi_drop_out_substreams(midi); } @@ -661,6 +664,7 @@ static int f_midi_do_transmit(struct f_midi *midi, struct usb_ep *ep) ERROR(midi, "%s failed to queue req: %d\n", midi->in_ep->name, err); req->length = 0; /* Re-use request next time. */ + return err; } else { /* Upon success, put request at the back of the queue. */ kfifo_skip(&midi->in_req_fifo); From 78585f90feb3bbaf3b1c642294c8c47e451dc3cf Mon Sep 17 00:00:00 2001 From: Cosmin Tanislav Date: Mon, 17 Aug 2026 22:26:38 +0300 Subject: [PATCH 0063/2102] usb: gadget: f_ncm: restart the TX timer if the TX freelist is empty ncm_wrap_ntb() aggregates datagrams into a pending NTB, which is sent either when it becomes full, or after 300us since the NTB was started, using ndo_start_xmit() (eth_start_xmit()). ndo_start_xmit() returns NETDEV_TX_BUSY when the TX freelist is empty. For regular packets this is fine since the networking core will requeue them, but for timer-flushed packets there is no logic to handle this situation, and HRTIMER_NORESTART is returned from ncm_tx_timeout() without checking eth_start_xmit()'s return value. Under sustained TX saturation the request freelist is empty most of the time. Since the timer is never restarted, small packets keep getting accumulated into the NTB, until either TX_MAX_NUM_DPE packets are stored or NTB_DEFAULT_IN_SIZE is reached, which is an unknown amount of time. Check the return value of ndo_start_xmit() and restart the timer after another 300us. Cc: stable Fixes: 6d3865f9d41f ("usb: gadget: NCM: Add transmit multi-frame.") Signed-off-by: Cosmin Tanislav Tested-by: Vladyslav Tymoshchuk Tested-by: Leonardo Costa Reported-by: Hiago De Franco Closes: https://lore.kernel.org/all/20231204183751.64202-1-hiagofranco@gmail.com/ Link: https://patch.msgid.link/20260817192638.437798-1-cosmin-gabriel.tanislav.xa@renesas.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_ncm.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/usb/gadget/function/f_ncm.c b/drivers/usb/gadget/function/f_ncm.c index 500c9c19c78b4f..ab6da3ef87836c 100644 --- a/drivers/usb/gadget/function/f_ncm.c +++ b/drivers/usb/gadget/function/f_ncm.c @@ -1148,6 +1148,7 @@ static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data) { struct f_ncm *ncm = container_of(data, struct f_ncm, task_timer); struct net_device *netdev = READ_ONCE(ncm->netdev); + netdev_tx_t ret; if (netdev) { /* XXX This allowance of a NULL skb argument to ndo_start_xmit @@ -1158,7 +1159,11 @@ static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data) * * This will call directly into u_ether's eth_start_xmit() */ - netdev->netdev_ops->ndo_start_xmit(NULL, netdev); + ret = netdev->netdev_ops->ndo_start_xmit(NULL, netdev); + if (ret == NETDEV_TX_BUSY) { + hrtimer_forward_now(data, TX_TIMEOUT_NSECS); + return HRTIMER_RESTART; + } } return HRTIMER_NORESTART; } From ca783a2d55b3361493917ad4a3573715ba902503 Mon Sep 17 00:00:00 2001 From: Hui Peng Date: Wed, 30 Sep 2026 07:52:47 +0000 Subject: [PATCH 0064/2102] USB: serial: garmin_gps: validate packet data length in nat_receive() In nat_receive() (called from garmin_write() when userspace writes to /dev/ttyUSBn in MODE_NATIVE mode), while garmin_data_p->insize is less than GARMIN_PKTHDR_LENGTH (12), the loop copies up to 12 bytes into garmin_data_p->inbuffer. Once garmin_data_p->insize reaches GARMIN_PKTHDR_LENGTH, nat_receive() computes the total packet size as: len = GARMIN_PKTHDR_LENGTH + getDataLength(garmin_data_p->inbuffer); Because getDataLength() returns a signed int from __le32_to_cpup(), a 12-byte header with a negative 32-bit length field (such as 0xfffffff5, i.e., -11) causes len to underflow to a small positive value (12 + (-11) = 1) without any bounds check at that point. Then garmin_data_p->insize >= len (12 >= 1) evaluates to true and nat_receive() calls garmin_write_bulk(port, inbuffer, 1, 0), which allocates a 1-byte slab buffer via kmemdup() and immediately reads 4 bytes from it in getLayerId(buffer) (and again in garmin_write_bulk_callback() when the URB completes): BUG: KASAN: slab-out-of-bounds in garmin_write_bulk.constprop.0+0x3eb/0x500 Read of size 4 at addr ffff888002cc0ba0 by task init/1 Call Trace: dump_stack_lvl+0x70/0xa0 print_report+0x153/0x4c6 kasan_report+0xf1/0x120 garmin_write_bulk.constprop.0+0x3eb/0x500 garmin_write+0x60f/0x1450 serial_write+0x123/0x200 n_tty_write+0x8ea/0xeb0 file_tty_write.isra.0+0x44f/0x7a0 vfs_write+0x671/0xd20 Validate the unsigned 32-bit data length (dlen >= GPS_IN_BUFSIZ - GARMIN_PKTHDR_LENGTH, matching the existing len >= GPS_IN_BUFSIZ bound) in nat_receive() as soon as the 12-byte header is present, resetting insize and returning -EINVPKT on invalid lengths so garmin_write_bulk() is only ever called with a full valid packet header (12 <= len < GPS_IN_BUFSIZ). Tested in QEMU against Linux 7.3.0-rc3 by emulating a Garmin USB GPS device (091e:0003) via dummy_hcd + raw-gadget, switching /dev/ttyUSB0 to MODE_NATIVE via PRIV_PKTID_SET_MODE, and writing a 12-byte native packet with data length 0xfffffff5: on the unfixed kernel this triggers KASAN slab-out-of-bounds reads in garmin_write_bulk() and garmin_write_bulk_callback(), whereas on the fixed kernel nat_receive() rejects the packet with -EINVPKT and 0 KASAN faults. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Hui Peng [ johan: move comment and dev_dbg(); add comment about redundant check ] Signed-off-by: Johan Hovold --- drivers/usb/serial/garmin_gps.c | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/drivers/usb/serial/garmin_gps.c b/drivers/usb/serial/garmin_gps.c index 8020149f5658dc..40df6f14e045c1 100644 --- a/drivers/usb/serial/garmin_gps.c +++ b/drivers/usb/serial/garmin_gps.c @@ -746,11 +746,7 @@ static int nat_receive(struct garmin_data *garmin_data_p, len = GARMIN_PKTHDR_LENGTH; if (len >= GPS_IN_BUFSIZ) { - /* seems to be an invalid packet, ignore rest - of input */ - dev_dbg(&garmin_data_p->port->dev, - "%s - packet size too large: %d\n", - __func__, len); + /* should never end up here given the dlen check below */ garmin_data_p->insize = 0; count = 0; result = -EINVPKT; @@ -769,8 +765,17 @@ static int nat_receive(struct garmin_data *garmin_data_p, /* do we have a complete packet ? */ if (garmin_data_p->insize >= GARMIN_PKTHDR_LENGTH) { - len = GARMIN_PKTHDR_LENGTH+ - getDataLength(garmin_data_p->inbuffer); + u32 dlen = getDataLength(garmin_data_p->inbuffer); + + if (dlen >= GPS_IN_BUFSIZ - GARMIN_PKTHDR_LENGTH) { + /* invalid packet, ignore rest of input */ + dev_dbg(&garmin_data_p->port->dev, "%s - invalid length: %u\n", + __func__, dlen); + garmin_data_p->insize = 0; + result = -EINVPKT; + break; + } + len = GARMIN_PKTHDR_LENGTH + dlen; if (garmin_data_p->insize >= len) { garmin_write_bulk(garmin_data_p->port, garmin_data_p->inbuffer, From a3d43b39032cc5565a5693a10c581844342372cd Mon Sep 17 00:00:00 2001 From: Tristan Madani Date: Mon, 19 Oct 2026 10:38:49 +0000 Subject: [PATCH 0065/2102] USB: serial: sierra: validate URB length in instat callback sierra_instat_callback() reads request fields and one byte past the usb_ctrlrequest header without first checking that urb->actual_length is large enough. A short USB interrupt transfer could cause an out-of-bounds read. Add two length checks matching the pattern already present in the option driver (option_instat_callback): one for the request header before accessing bRequestType, and one for the line-state data byte inside the serial-state notification handler. Use dev_err() since failing these checks causes the interrupt URB not to be resubmitted. Fixes: 033a3fb980b041 ("USB: Sierra Wireless driver update") Cc: stable@vger.kernel.org Signed-off-by: Tristan Madani [ johan: use sizeof(*req_pkt) consistently ] Signed-off-by: Johan Hovold --- drivers/usb/serial/sierra.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/drivers/usb/serial/sierra.c b/drivers/usb/serial/sierra.c index f2cc7f364d2040..c6aa5dfe468b1a 100644 --- a/drivers/usb/serial/sierra.c +++ b/drivers/usb/serial/sierra.c @@ -575,12 +575,24 @@ static void sierra_instat_callback(struct urb *urb) __func__); return; } + if (urb->actual_length < sizeof(*req_pkt)) { + dev_err(&port->dev, "%s: short transfer\n", + __func__); + return; + } if ((req_pkt->bRequestType == 0xA1) && (req_pkt->bRequest == 0x20)) { int old_dcd_state; - unsigned char signals = *((unsigned char *) - urb->transfer_buffer + - sizeof(struct usb_ctrlrequest)); + unsigned char signals; + + if (urb->actual_length < sizeof(*req_pkt) + 1) { + dev_err(&port->dev, + "%s: short interrupt transfer\n", + __func__); + return; + } + signals = *((unsigned char *)urb->transfer_buffer + + sizeof(*req_pkt)); dev_dbg(&port->dev, "%s: signal x%x\n", __func__, signals); From 0e0b1fcfb80c0490bda7f7eb633ebb5e431c2e16 Mon Sep 17 00:00:00 2001 From: Johan Hovold Date: Mon, 19 Oct 2026 14:34:12 +0200 Subject: [PATCH 0066/2102] USB: serial: upd78f0730: fix NULL-deref on hangup The port tty pointer is cleared on hangup before deasserting the modem control signals and should not be used in the dtr_rts() callback. Factor out a new upd78f0730_port_tiocmset() helper that can be used in upd78f0730_dtr_rts() to avoid dereferencing a NULL-pointer on hangup (e.g. on disconnect). This issue was flagged by an LLM. Fixes: ea534e0b4047 ("USB: serial: add uPD78F0730 USB to Serial Adaptor Driver") Cc: stable@vger.kernel.org # 4.11 Cc: Maksim Salau Signed-off-by: Johan Hovold --- drivers/usb/serial/upd78f0730.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/drivers/usb/serial/upd78f0730.c b/drivers/usb/serial/upd78f0730.c index 78c4d3c19a8ec4..f2189b994ed7b1 100644 --- a/drivers/usb/serial/upd78f0730.c +++ b/drivers/usb/serial/upd78f0730.c @@ -201,10 +201,9 @@ static int upd78f0730_tiocmget(struct tty_struct *tty) return res; } -static int upd78f0730_tiocmset(struct tty_struct *tty, +static int upd78f0730_port_tiocmset(struct usb_serial_port *port, unsigned int set, unsigned int clear) { - struct usb_serial_port *port = tty->driver_data; struct upd78f0730_port_private *private; struct upd78f0730_set_dtr_rts request; struct device *dev = &port->dev; @@ -238,6 +237,13 @@ static int upd78f0730_tiocmset(struct tty_struct *tty, return res; } +static int upd78f0730_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) +{ + struct usb_serial_port *port = tty->driver_data; + + return upd78f0730_port_tiocmset(port, set, clear); +} + static int upd78f0730_break_ctl(struct tty_struct *tty, int break_state) { struct upd78f0730_port_private *private; @@ -267,7 +273,6 @@ static int upd78f0730_break_ctl(struct tty_struct *tty, int break_state) static void upd78f0730_dtr_rts(struct usb_serial_port *port, int on) { - struct tty_struct *tty = port->port.tty; unsigned int set = 0; unsigned int clear = 0; @@ -276,7 +281,7 @@ static void upd78f0730_dtr_rts(struct usb_serial_port *port, int on) else clear = TIOCM_DTR | TIOCM_RTS; - upd78f0730_tiocmset(tty, set, clear); + upd78f0730_port_tiocmset(port, set, clear); } static speed_t upd78f0730_get_baud_rate(struct tty_struct *tty) From ae22e9b6412e5dc99e1cf8bd13c6176d44c7d42e Mon Sep 17 00:00:00 2001 From: Johan Hovold Date: Fri, 23 Oct 2026 14:15:19 +0200 Subject: [PATCH 0067/2102] USB: serial: io_edgeport: fix NULL-deref on early status The driver submits the interrupt-in URB during probe or on first port open, which on completion may submit the bulk-in URB before all ports have been opened and their waitqueues have been initialised. If a (malicious) device sends a status message for a port that has not yet been opened this may lead to a NULL-pointer dereference in the bulk-in completion handler when attempting to wakeup blocked tasks. Move waitqueue initialisation from open() to port_probe() to address this. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Reported-by: syzbot+763813d65c7e18c1b6d5@syzkaller.appspotmail.com Link: https://lore.kernel.org/6a8818d8.ae6ddae5.3da009.0031.GAE@google.com Cc: stable@vger.kernel.org Signed-off-by: Johan Hovold --- drivers/usb/serial/io_edgeport.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/drivers/usb/serial/io_edgeport.c b/drivers/usb/serial/io_edgeport.c index eaa8f00716c87d..cdf41e86ba448b 100644 --- a/drivers/usb/serial/io_edgeport.c +++ b/drivers/usb/serial/io_edgeport.c @@ -877,11 +877,6 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) } } - /* initialize our wait queues */ - init_waitqueue_head(&edge_port->wait_open); - init_waitqueue_head(&edge_port->wait_chase); - init_waitqueue_head(&edge_port->wait_command); - /* initialize our port settings */ edge_port->txCredits = 0; /* Can't send any data yet */ /* Must always set this bit to enable ints! */ @@ -2965,6 +2960,11 @@ static int edge_port_probe(struct usb_serial_port *port) return -ENOMEM; spin_lock_init(&edge_port->ep_lock); + + init_waitqueue_head(&edge_port->wait_open); + init_waitqueue_head(&edge_port->wait_chase); + init_waitqueue_head(&edge_port->wait_command); + edge_port->port = port; usb_set_serial_port_data(port, edge_port); From 839ff5fa30995c40cd5fba15fd976ad63416738a Mon Sep 17 00:00:00 2001 From: Johan Hovold Date: Fri, 23 Oct 2026 14:15:20 +0200 Subject: [PATCH 0068/2102] USB: serial: io_edgeport: fix potential close() use-after-free Add the missing open check on write() and locking when updating the port status during close() to prevent a racing interrupt completion handler from trying to submit more data for the port while its write URB and FIFO are being deallocated. This issue was flagged by Sashiko when reviewing a related fix. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Link: https://sashiko.dev/#/patchset/20260714101316.823942-1-shpark061104%40gmail.com?part=1 Signed-off-by: Johan Hovold --- drivers/usb/serial/io_edgeport.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/usb/serial/io_edgeport.c b/drivers/usb/serial/io_edgeport.c index cdf41e86ba448b..a5011fa91ee70c 100644 --- a/drivers/usb/serial/io_edgeport.c +++ b/drivers/usb/serial/io_edgeport.c @@ -1085,7 +1085,9 @@ static void edge_close(struct usb_serial_port *port) /* port->close = true; */ edge_port->closePending = false; + spin_lock_irq(&edge_port->ep_lock); edge_port->open = false; + spin_unlock_irq(&edge_port->ep_lock); edge_port->openPending = false; usb_kill_urb(edge_port->write_urb); @@ -1127,6 +1129,12 @@ static int edge_write(struct tty_struct *tty, struct usb_serial_port *port, spin_lock_irqsave(&edge_port->ep_lock, flags); + /* avoid accessing freed fifo if tty_wakeup() races with close() */ + if (!edge_port->open) { + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + return 0; + } + /* calculate number of bytes to put in fifo */ copySize = min_t(unsigned int, count, (edge_port->txCredits - fifo->count)); From a0403880a0a638f189e5187068244d9fd5bc8d4d Mon Sep 17 00:00:00 2001 From: Johan Hovold Date: Fri, 23 Oct 2026 14:15:21 +0200 Subject: [PATCH 0069/2102] USB: serial: io_edgeport: fix potential NULL-deref at open Do not mark the port as open until after the write FIFO has been allocated and initialised to prevent a racing interrupt completion from attempting to send stale data and dereference the FIFO buffer pointer. Note that the open flag defaults to false and is cleared on close() so there is no need to reinitialise it on every open(). Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Signed-off-by: Johan Hovold --- drivers/usb/serial/io_edgeport.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/drivers/usb/serial/io_edgeport.c b/drivers/usb/serial/io_edgeport.c index a5011fa91ee70c..e8e641e9a1974e 100644 --- a/drivers/usb/serial/io_edgeport.c +++ b/drivers/usb/serial/io_edgeport.c @@ -885,9 +885,7 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) /* send a open port command */ edge_port->openPending = true; - edge_port->open = false; response = send_iosp_ext_cmd(edge_port, IOSP_CMD_OPEN_PORT, 0); - if (response < 0) { dev_err(dev, "%s - error sending open port command\n", __func__); edge_port->openPending = false; @@ -897,8 +895,7 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) /* now wait for the port to be completely opened */ wait_event_timeout(edge_port->wait_open, !edge_port->openPending, OPEN_TIMEOUT); - - if (!edge_port->open) { + if (edge_port->openPending) { /* open timed out */ dev_dbg(dev, "%s - open timeout\n", __func__); edge_port->openPending = false; @@ -926,6 +923,10 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) return -ENOMEM; } + spin_lock_irq(&edge_port->ep_lock); + edge_port->open = true; + spin_unlock_irq(&edge_port->ep_lock); + dev_dbg(dev, "%s - Initialize TX fifo to %d bytes\n", __func__, edge_port->maxTxCredits); @@ -1818,7 +1819,6 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, /* we have completed the open */ edge_port->openPending = false; - edge_port->open = true; wake_up(&edge_port->wait_open); return; } From febadc65a4ef8d08a12e76d6ec50834d72cc0e59 Mon Sep 17 00:00:00 2001 From: Johan Hovold Date: Fri, 23 Oct 2026 14:15:22 +0200 Subject: [PATCH 0070/2102] USB: serial: io_edgeport: move initial termios update to open() Explicitly update the terminal settings on open() instead of doing so from the interrupt completion handler when receiving an open command response, which in theory can be received after a failed open attempt. Note that this will be used to fix a FIFO corruption issue and also allows for switching to synchronous commands. Cc: stable@vger.kernel.org Signed-off-by: Johan Hovold --- drivers/usb/serial/io_edgeport.c | 64 +++++--------------------------- 1 file changed, 10 insertions(+), 54 deletions(-) diff --git a/drivers/usb/serial/io_edgeport.c b/drivers/usb/serial/io_edgeport.c index e8e641e9a1974e..cdcff02c435bff 100644 --- a/drivers/usb/serial/io_edgeport.c +++ b/drivers/usb/serial/io_edgeport.c @@ -281,8 +281,7 @@ static void handle_new_lsr(struct edgeport_port *edge_port, __u8 lsrData, static int send_iosp_ext_cmd(struct edgeport_port *edge_port, __u8 command, __u8 param); static int calc_baud_rate_divisor(struct device *dev, int baud_rate, int *divisor); -static void change_port_settings(struct tty_struct *tty, - struct edgeport_port *edge_port, +static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, const struct ktermios *old_termios); static int send_cmd_write_uart_register(struct edgeport_port *edge_port, __u8 regNum, __u8 regValue); @@ -923,6 +922,9 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) return -ENOMEM; } + if (tty) + edge_set_termios(tty, port, NULL); + spin_lock_irq(&edge_port->ep_lock); edge_port->open = true; spin_unlock_irq(&edge_port->ep_lock); @@ -1443,30 +1445,6 @@ static void edge_unthrottle(struct tty_struct *tty) } -/***************************************************************************** - * SerialSetTermios - * this function is called by the tty driver when it wants to change - * the termios structure - *****************************************************************************/ -static void edge_set_termios(struct tty_struct *tty, - struct usb_serial_port *port, - const struct ktermios *old_termios) -{ - struct edgeport_port *edge_port = usb_get_serial_port_data(port); - - if (edge_port == NULL) - return; - - if (!edge_port->open) { - dev_dbg(&port->dev, "%s - port not opened\n", __func__); - return; - } - - /* change the port settings to the new ones specified */ - change_port_settings(tty, edge_port, old_termios); -} - - /***************************************************************************** * get_lsr_info - get line status register info * @@ -1756,7 +1734,6 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, { struct usb_serial_port *port; struct edgeport_port *edge_port; - struct tty_struct *tty; struct device *dev; __u8 code = edge_serial->rxStatusCode; @@ -1808,15 +1785,6 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, __func__, edge_serial->rxPort, byte2, edge_port->txCredits); handle_new_msr(edge_port, byte2); - /* send the current line settings to the port so we are - in sync with any further termios calls */ - tty = tty_port_tty_get(&edge_port->port->port); - if (tty) { - change_port_settings(tty, - edge_port, &tty->termios); - tty_kref_put(tty); - } - /* we have completed the open */ edge_port->openPending = false; wake_up(&edge_port->wait_open); @@ -2328,18 +2296,12 @@ static int send_cmd_write_uart_register(struct edgeport_port *edge_port, } -/***************************************************************************** - * change_port_settings - * This routine is called to set the UART on the device to match the - * specified new settings. - *****************************************************************************/ - -static void change_port_settings(struct tty_struct *tty, - struct edgeport_port *edge_port, const struct ktermios *old_termios) +static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, + const struct ktermios *old_termios) { - struct device *dev = &edge_port->port->dev; - struct edgeport_serial *edge_serial = - usb_get_serial_data(edge_port->port->serial); + struct edgeport_serial *edge_serial = usb_get_serial_data(port->serial); + struct edgeport_port *edge_port = usb_get_serial_port_data(port); + struct device *dev = &port->dev; int baud; unsigned cflag; __u8 mask = 0xff; @@ -2350,12 +2312,6 @@ static void change_port_settings(struct tty_struct *tty, __u8 txFlow; int status; - if (!edge_port->open && - !edge_port->openPending) { - dev_dbg(dev, "%s - port not opened\n", __func__); - return; - } - cflag = tty->termios.c_cflag; switch (cflag & CSIZE) { @@ -2489,7 +2445,7 @@ static void change_port_settings(struct tty_struct *tty, dev_dbg(dev, "%s - baud rate = %d\n", __func__, baud); status = send_cmd_write_baud_rate(edge_port, baud); - if (status == -1) { + if (status == -1 && old_termios) { /* Speed change was not possible - put back the old speed */ baud = tty_termios_baud_rate(old_termios); tty_encode_baud_rate(tty, baud, baud); From 270f76c3b88c9cc3d6ca58c5c0c0f34c2373b27c Mon Sep 17 00:00:00 2001 From: Johan Hovold Date: Fri, 23 Oct 2026 14:15:23 +0200 Subject: [PATCH 0071/2102] USB: serial: io_edgeport: fix potential fifo corruption The device buffer size is determined during open() and the driver allocates a TX FIFO of corresponding size. Add the missing sanity check to prevent memory corruption in case a malicious device sends a second open response with a different buffer size. This issue was flagged by Sashiko when reviewing a related fix. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Link: https://sashiko.dev/#/patchset/20260714101316.823942-1-shpark061104%40gmail.com?part=1 Signed-off-by: Johan Hovold --- drivers/usb/serial/io_edgeport.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/drivers/usb/serial/io_edgeport.c b/drivers/usb/serial/io_edgeport.c index cdcff02c435bff..b8fbcc8908d14e 100644 --- a/drivers/usb/serial/io_edgeport.c +++ b/drivers/usb/serial/io_edgeport.c @@ -877,13 +877,17 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) } /* initialize our port settings */ + spin_lock_irq(&edge_port->ep_lock); edge_port->txCredits = 0; /* Can't send any data yet */ + edge_port->maxTxCredits = 0; + edge_port->openPending = true; + spin_unlock_irq(&edge_port->ep_lock); + /* Must always set this bit to enable ints! */ edge_port->shadowMCR = MCR_MASTER_IE; edge_port->chaseResponsePending = false; /* send a open port command */ - edge_port->openPending = true; response = send_iosp_ext_cmd(edge_port, IOSP_CMD_OPEN_PORT, 0); if (response < 0) { dev_err(dev, "%s - error sending open port command\n", __func__); @@ -1736,6 +1740,7 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, struct edgeport_port *edge_port; struct device *dev; __u8 code = edge_serial->rxStatusCode; + unsigned long flags; /* switch the port pointer to the one being currently talked about */ if (edge_serial->rxPort >= edge_serial->serial->num_ports) @@ -1779,6 +1784,12 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, } if (code == IOSP_STATUS_OPEN_RSP) { + spin_lock_irqsave(&edge_port->ep_lock, flags); + /* reject stray open responses to avoid FIFO corruption */ + if (!edge_port->openPending) { + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + return; + } edge_port->txCredits = GET_TX_BUFFER_SIZE(byte3); edge_port->maxTxCredits = edge_port->txCredits; dev_dbg(dev, "%s - Port %u Open Response Initial MSR = %02x TxBufferSize = %d\n", @@ -1787,6 +1798,8 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, /* we have completed the open */ edge_port->openPending = false; + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + wake_up(&edge_port->wait_open); return; } From 50613e6380db7a904ef15c60ed0c436baf308f0a Mon Sep 17 00:00:00 2001 From: Johan Hovold Date: Fri, 23 Oct 2026 14:15:24 +0200 Subject: [PATCH 0072/2102] USB: serial: io_edgeport: fix potential use-after-free on disconnect The driver submits command URBs asynchronously but fails to stop them on disconnect, something which could lead to a use-after-free when accessing driver data in the completion handler after a port has been unbound. Add an URB anchor to track and kill outstanding command URBs on disconnect. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Signed-off-by: Johan Hovold --- drivers/usb/serial/io_edgeport.c | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/drivers/usb/serial/io_edgeport.c b/drivers/usb/serial/io_edgeport.c index b8fbcc8908d14e..0fe7495c47f487 100644 --- a/drivers/usb/serial/io_edgeport.c +++ b/drivers/usb/serial/io_edgeport.c @@ -225,6 +225,7 @@ struct edgeport_serial { __u8 rxStatusParam; /* the receive status parameter */ __s16 rxBytesRemaining; /* the number of port bytes left to read */ struct usb_serial *serial; /* loop back to the owner of this object */ + struct usb_anchor cmd_anchor; }; /* baud rate information */ @@ -261,9 +262,6 @@ static const struct divisor_table_entry divisor_table[] = { { 230400, 1}, }; -/* Number of outstanding Command Write Urbs */ -static atomic_t CmdUrbs = ATOMIC_INIT(0); - /* function prototypes */ @@ -776,11 +774,6 @@ static void edge_bulk_out_cmd_callback(struct urb *urb) struct device *dev = &urb->dev->dev; int status = urb->status; - atomic_dec(&CmdUrbs); - dev_dbg(dev, "%s - FREE URB %p (outstanding %d)\n", __func__, urb, - atomic_read(&CmdUrbs)); - - /* clean up the transfer buffer */ kfree(urb->transfer_buffer); @@ -2127,24 +2120,21 @@ static int write_cmd_usb(struct edgeport_port *edge_port, if (!urb) return -ENOMEM; - atomic_inc(&CmdUrbs); - dev_dbg(dev, "%s - ALLOCATE URB %p (outstanding %d)\n", - __func__, urb, atomic_read(&CmdUrbs)); - usb_fill_bulk_urb(urb, edge_serial->serial->dev, usb_sndbulkpipe(edge_serial->serial->dev, edge_serial->bulk_out_endpoint), buffer, length, edge_bulk_out_cmd_callback, edge_port); edge_port->commandPending = true; + usb_anchor_urb(urb, &edge_serial->cmd_anchor); status = usb_submit_urb(urb, GFP_ATOMIC); if (status) { /* something went wrong */ dev_err(dev, "%s - usb_submit_urb(write command) failed, status = %d\n", __func__, status); + usb_unanchor_urb(urb); usb_free_urb(urb); - atomic_dec(&CmdUrbs); return status; } @@ -2696,6 +2686,7 @@ static int edge_startup(struct usb_serial *serial) spin_lock_init(&edge_serial->es_lock); edge_serial->serial = serial; + init_usb_anchor(&edge_serial->cmd_anchor); usb_set_serial_data(serial, edge_serial); /* get the name for the device from the device */ @@ -2900,6 +2891,8 @@ static void edge_disconnect(struct usb_serial *serial) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); + usb_kill_anchored_urbs(&edge_serial->cmd_anchor); + if (edge_serial->is_epic) { usb_kill_urb(edge_serial->interrupt_read_urb); usb_kill_urb(edge_serial->read_urb); From 6e4629504d7e5a22dd26f3b262f0a0f80e3cad6a Mon Sep 17 00:00:00 2001 From: Johan Hovold Date: Fri, 23 Oct 2026 14:15:25 +0200 Subject: [PATCH 0073/2102] USB: serial: io_edgeport: serialise MCR accesses Add a mutex to serialise modem control register updates to prevent concurrent tasks from interfering with each other. Note that the register updates are currently asynchronous so a task may read back a value which has not yet taken effect. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Signed-off-by: Johan Hovold --- drivers/usb/serial/io_edgeport.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/drivers/usb/serial/io_edgeport.c b/drivers/usb/serial/io_edgeport.c index 0fe7495c47f487..0fd68faa8427c0 100644 --- a/drivers/usb/serial/io_edgeport.c +++ b/drivers/usb/serial/io_edgeport.c @@ -168,6 +168,7 @@ struct edgeport_port { struct urb *write_urb; /* write URB for this port */ bool write_in_progress; /* 'true' while a write URB is outstanding */ spinlock_t ep_lock; + struct mutex mutex; __u8 shadowLCR; /* last LCR value received */ __u8 shadowMCR; /* last MCR value received */ @@ -877,7 +878,10 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) spin_unlock_irq(&edge_port->ep_lock); /* Must always set this bit to enable ints! */ + mutex_lock(&edge_port->mutex); edge_port->shadowMCR = MCR_MASTER_IE; + mutex_unlock(&edge_port->mutex); + edge_port->chaseResponsePending = false; /* send a open port command */ @@ -1398,9 +1402,11 @@ static void edge_throttle(struct tty_struct *tty) /* if we are implementing RTS/CTS, toggle that line */ if (C_CRTSCTS(tty)) { + mutex_lock(&edge_port->mutex); edge_port->shadowMCR &= ~MCR_RTS; status = send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); if (status != 0) return; } @@ -1435,9 +1441,11 @@ static void edge_unthrottle(struct tty_struct *tty) } /* if we are implementing RTS/CTS, toggle that line */ if (C_CRTSCTS(tty)) { + mutex_lock(&edge_port->mutex); edge_port->shadowMCR |= MCR_RTS; send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); } } @@ -1478,6 +1486,7 @@ static int edge_tiocmset(struct tty_struct *tty, struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int mcr; + mutex_lock(&edge_port->mutex); mcr = edge_port->shadowMCR; if (set & TIOCM_RTS) mcr |= MCR_RTS; @@ -1496,6 +1505,7 @@ static int edge_tiocmset(struct tty_struct *tty, edge_port->shadowMCR = mcr; send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); return 0; } @@ -1509,6 +1519,7 @@ static int edge_tiocmget(struct tty_struct *tty) unsigned int mcr; msr = edge_port->shadowMSR; + mutex_lock(&edge_port->mutex); mcr = edge_port->shadowMCR; result = ((mcr & MCR_DTR) ? TIOCM_DTR: 0) /* 0x002 */ | ((mcr & MCR_RTS) ? TIOCM_RTS: 0) /* 0x004 */ @@ -1516,6 +1527,7 @@ static int edge_tiocmget(struct tty_struct *tty) | ((msr & EDGEPORT_MSR_CD) ? TIOCM_CAR: 0) /* 0x040 */ | ((msr & EDGEPORT_MSR_RI) ? TIOCM_RI: 0) /* 0x080 */ | ((msr & EDGEPORT_MSR_DSR) ? TIOCM_DSR: 0); /* 0x100 */ + mutex_unlock(&edge_port->mutex); return result; } @@ -2430,12 +2442,14 @@ static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *por return; /* set up the MCR register and send it to the EdgePort */ + mutex_lock(&edge_port->mutex); edge_port->shadowMCR = MCR_MASTER_IE; if (cflag & CBAUD) edge_port->shadowMCR |= (MCR_DTR | MCR_RTS); status = send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); if (status != 0) return; @@ -2930,6 +2944,7 @@ static int edge_port_probe(struct usb_serial_port *port) return -ENOMEM; spin_lock_init(&edge_port->ep_lock); + mutex_init(&edge_port->mutex); init_waitqueue_head(&edge_port->wait_open); init_waitqueue_head(&edge_port->wait_chase); From f184ae84a5d19554d980a918a9c8baaef87ac301 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:31:26 +0100 Subject: [PATCH 0074/2102] USB: serial: oti6858: fix the teardown order in close The driver passes a baton around: the completion handler of the interrupt urb either resubmits the urb, submits the read urb or schedules one of the two delayed works, and the works and the bulk completion handlers submit the interrupt urb again. oti6858_close() cancels the works first and kills the urbs afterwards. An interrupt urb that completes in between schedules a work again: oti6858_close() cancel_delayed_work_sync(setup) cancel_delayed_work_sync(write) oti6858_read_int_callback() schedule_delayed_work(setup) usb_kill_urb(interrupt_in_urb) /* not in flight */ setup_line() usb_submit_urb(interrupt_in_urb) The port is now closed with the baton still going round. The next open fails because the interrupt urb is already submitted, and if the device is unplugged, oti6858_port_remove() frees the private data while a work may be pending or running. Poison the interrupt urb first: that waits for the handler and makes all further submissions fail, so nothing schedules the works any more. Then cancel the works, after which only the bulk urbs are left, kill those, and make the interrupt urb usable again for the next open. Don't print an error for the submissions that fail with -EPERM in this window, as oti6858_read_bulk_callback() already does. Fixes: 49cdee0ed0fc ("USB: oti6858 usb-serial driver (in Nokia CA-42 cable)") Cc: stable Cc: Johan Hovold Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Signed-off-by: Johan Hovold --- drivers/usb/serial/oti6858.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/drivers/usb/serial/oti6858.c b/drivers/usb/serial/oti6858.c index c6364e8ff71f95..005fe19c3cd4f1 100644 --- a/drivers/usb/serial/oti6858.c +++ b/drivers/usb/serial/oti6858.c @@ -248,7 +248,7 @@ static void setup_line(struct work_struct *work) dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__); result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL); - if (result != 0) { + if (result != 0 && result != -EPERM) { dev_err(&port->dev, "%s(): usb_submit_urb() failed with error %d\n", __func__, result); } @@ -300,7 +300,7 @@ static void send_data(struct work_struct *work) dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__); result = usb_submit_urb(port->interrupt_in_urb, GFP_NOIO); - if (result != 0) { + if (result != 0 && result != -EPERM) { dev_err(&port->dev, "%s(): usb_submit_urb() failed with error %d\n", __func__, result); } @@ -561,6 +561,13 @@ static void oti6858_close(struct usb_serial_port *port) dev_dbg(&port->dev, "%s(): after buf_clear()\n", __func__); + /* + * The interrupt urb schedules the works, and the works and the bulk + * urbs resubmit the interrupt urb: keep it from being submitted until + * all of them are gone. + */ + usb_poison_urb(port->interrupt_in_urb); + /* cancel scheduled setup */ cancel_delayed_work_sync(&priv->delayed_setup_work); cancel_delayed_work_sync(&priv->delayed_write_work); @@ -569,7 +576,8 @@ static void oti6858_close(struct usb_serial_port *port) dev_dbg(&port->dev, "%s(): shutting down urbs\n", __func__); usb_kill_urb(port->write_urb); usb_kill_urb(port->read_urb); - usb_kill_urb(port->interrupt_in_urb); + + usb_unpoison_urb(port->interrupt_in_urb); } static int oti6858_tiocmset(struct tty_struct *tty, @@ -826,7 +834,7 @@ static void oti6858_write_bulk_callback(struct urb *urb) /* schedule the interrupt urb if we are still open */ dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__); result = usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC); - if (result != 0) { + if (result != 0 && result != -EPERM) { dev_err(&port->dev, "%s(): failed submitting int urb," " error %d\n", __func__, result); } From ab89a9dab02d9553eb0cc27fd3e4a4998acbc8e9 Mon Sep 17 00:00:00 2001 From: Johan Hovold Date: Thu, 29 Oct 2026 11:18:28 +0100 Subject: [PATCH 0075/2102] USB: serial: garmin_gps: fix deadlock on reset request The garmin_gps driver has a reset feature that is supposed to reset the device when writing a private reset request packet. The reset is however done synchronously from the write() callback (and without holding the required device lock) which leads to a deadlock in the line discipline when hanging up the port as part of disconnect. Switch to using the asynchronous reset interface while dropping the redundant and synchronous stopping of the interrupt urb (write() callbacks are supposed to be atomic and USB core, USB serial core and the driver itself will unlink and kill all URBs during disconnect). Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Reported-by: Josef Bacik Link: https://lore.kernel.org/2026102733-prayer-drainer-56f3@gregkh Cc: stable@vger.kernel.org Reviewed-by: Greg Kroah-Hartman Signed-off-by: Johan Hovold --- drivers/usb/serial/garmin_gps.c | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/drivers/usb/serial/garmin_gps.c b/drivers/usb/serial/garmin_gps.c index 40df6f14e045c1..a7c18a8fdf59c6 100644 --- a/drivers/usb/serial/garmin_gps.c +++ b/drivers/usb/serial/garmin_gps.c @@ -823,10 +823,9 @@ static void priv_status_resp(struct usb_serial_port *port) * Garmin specific driver functions ******************************************************************************/ -static int process_resetdev_request(struct usb_serial_port *port) +static void process_resetdev_request(struct usb_serial_port *port) { unsigned long flags; - int status; struct garmin_data *garmin_data_p = usb_get_serial_port_data(port); spin_lock_irqsave(&garmin_data_p->lock, flags); @@ -835,13 +834,8 @@ static int process_resetdev_request(struct usb_serial_port *port) garmin_data_p->serial_num = 0; spin_unlock_irqrestore(&garmin_data_p->lock, flags); - usb_kill_urb(port->interrupt_in_urb); - dev_dbg(&port->dev, "%s - usb_reset_device\n", __func__); - status = usb_reset_device(port->serial->dev); - if (status) - dev_dbg(&port->dev, "%s - usb_reset_device failed: %d\n", - __func__, status); - return status; + dev_dbg(&port->dev, "%s - usb_queue_reset_device\n", __func__); + usb_queue_reset_device(port->serial->interface); } From 6895dbdc19d927a2872bd4f111e1911874d5dce4 Mon Sep 17 00:00:00 2001 From: Yiyu Zhou Date: Thu, 29 Oct 2026 22:43:24 +0200 Subject: [PATCH 0076/2102] xhci: give back TDs and clean up ep0 after disconnect Fix a regression in v7.3 introduced by the commits in the Fixes tags. Those patches avoid endpoint recovery and rapid state changes after the root port link is lost. This caused a regression in device enumeration. It turns out that a subset of USB HID devices briefly disconnect during enumeration. USB core manages to resuscitate these devices without reallocating them, and thus continue using the same udev, xhci vdev and default control endpoint (ep0) of the device. xhci didn't give back or clean up halted TDs behind disconnected ports as it assumed that the disconnect cancels all URBs, and drops and frees all endpoints. This is not the case, so cancel and give back TDs on halted endpoint behind disconnected ports, make sure ep0 is cleared and in a proper state to continue working even after a link error or disconnect is detected. Also prevent new URBs until device is reset. One issue related to the TDs not being given back was seen on a PFU HHKB Professional HYBRID Type-S keyboard (04fe:0021). It drops off the bus about 300 ms after its first enumeration, while usbhid is still probing its third interface. The probe runs in hub_wq, so the disconnect is not handled until the probe returns. On a root port the HID descriptor request and its four retries in hid_get_class_descriptor() each wait for the full 5 second USB_CTRL_GET_TIMEOUT: [57685.006036] usb 3-2: new full-speed USB device number 24 using xhci_hcd ... [57685.291304] hid-generic 0003:04FE:0021.0017: input,hidraw1: USB HID v1.11 Keyboard [PFU Limited HHKB-Hybrid] on usb-0000:00:14.0-2/input1 [57711.221083] usbhid 3-2:1.2: can't add hid device: -110 [57711.221613] usbhid 3-2:1.2: probe with driver usbhid failed with error -110 [57711.221842] usb 3-2: USB disconnect, device number 24 [mn: merge EP_DROP_PENDING and link_inactive checks in xhci_urb_enqueue(), return TDs and clean up ep0 on disconnect, rewrite commit message] Fixes: 042aad8d0db6 ("xhci: prevent endpoint recovery after roothub disconnect") Fixes: 7e0ef4332ed9 ("xhci: avoid xHC endpoint changes after disconnect or link error.") Cc: stable Closes: https://lore.kernel.org/all/20261010071811.20483-1-yiyu@yiyuzhou.io/ Closes: https://lore.kernel.org/linux-usb/4MjB9K-2SoiA85WbI9iEig@dsine.de/ Tested-by: Yiyu Zhou Tested-by: Dennis Wissel Signed-off-by: Yiyu Zhou Co-developed-by: Mathias Nyman Signed-off-by: Mathias Nyman Link: https://patch.msgid.link/20261029204324.658845-2-mathias.nyman@linux.intel.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/host/xhci-ring.c | 73 ++++++++++++++++++++++++++++++------ drivers/usb/host/xhci.c | 13 ++++--- 2 files changed, 69 insertions(+), 17 deletions(-) diff --git a/drivers/usb/host/xhci-ring.c b/drivers/usb/host/xhci-ring.c index c23434001e9cbf..a1fa188680f586 100644 --- a/drivers/usb/host/xhci-ring.c +++ b/drivers/usb/host/xhci-ring.c @@ -65,6 +65,7 @@ static int queue_command(struct xhci_hcd *xhci, struct xhci_command *cmd, u32 field1, u32 field2, u32 field3, u32 field4, bool command_must_succeed); +static void xhci_kill_endpoint_urbs(struct xhci_hcd *xhci, int slot_id, int ep_index); /* * Returns zero if the TRB isn't in this segment, otherwise it returns the DMA @@ -962,6 +963,24 @@ static void xhci_giveback_invalidated_tds(struct xhci_hcd *xhci, struct xhci_vir } } +static void xhci_cancel_ring_tds(struct xhci_hcd *xhci, struct xhci_virt_ep *ep, + struct xhci_ring *ring, int td_status) +{ + struct xhci_td *tmp_td; + struct xhci_td *td; + + /* Add all TDs on ring to cancelled td list */ + list_for_each_entry_safe(td, tmp_td, &ring->td_list, td_list) { + if (list_empty(&td->cancelled_td_list)) { + list_add_tail(&td->cancelled_td_list, + &ep->cancelled_td_list); + td->cancel_status = TD_DIRTY; + if (!td->status) + td->status = td_status; + } + } +} + static int xhci_reset_halted_ep(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, enum xhci_ep_reset_type reset_type) { @@ -993,25 +1012,53 @@ static int xhci_handle_halted_endpoint(struct xhci_hcd *xhci, { struct xhci_port *rhub_port = ep->vdev->rhub_port; unsigned int slot_id = ep->vdev->slot_id; + bool disconnected = false; + struct xhci_ring *ring; int err; - /* - * Avoid resetting endpoint if link is inactive or device disconnected. - * Can cause host hang. - * Device will be reset to recover an inactive link, so don't do anything - */ + /* link is inactive or device disconnected */ if (rhub_port->link_inactive || !rhub_port->connected) { ep->ep_state |= EP_DROP_PENDING; - return -ENODEV; + disconnected = true; + if (!td && ep->ep_index != 0) { + xhci_kill_endpoint_urbs(xhci, slot_id, ep->ep_index); + return -ENODEV; + } } - /* add td to cancelled list and let reset ep handler take care of it */ - if (reset_type == EP_HARD_RESET) { - ep->ep_state |= EP_HARD_CLEAR_TOGGLE; + /* Add halted td to cancelled list and let reset ep handler take care of it */ + if (reset_type == EP_HARD_RESET || disconnected) { if (td && list_empty(&td->cancelled_td_list)) { list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list); td->cancel_status = TD_HALTED; + if (disconnected && !td->status) + td->status = -EPROTO; + } + } + + /* + * Avoid resetting non-ep0 endpoints if link is inactive or device + * disconnected. Can cause host hang. + * Endpoints other than ep0 won't restart before the device is reset or + * the endpoint is dropped, so cancel all TDs, and give back non-ep0 TDs + * now instead of letting them time out. Ep0 can survive a short device + * disconnect during enumeration so reset ep0 normally and clean it up. + */ + if (disconnected) { + ring = td ? xhci_urb_to_transfer_ring(xhci, td->urb) : ep->ring; + xhci_cancel_ring_tds(xhci, ep, ring, -ESHUTDOWN); + if (ep->ep_index != 0) { + xhci_dbg(xhci, "Not resetting ep %u slot %u after disconnect\n", + ep->ep_index, slot_id); + + xhci_process_cancelled_tds(xhci, ep); + xhci_kill_endpoint_urbs(xhci, slot_id, ep->ep_index); + return -ENODEV; } + /* hard-reset a halted disconnected ep0 */ + xhci_dbg(xhci, "Reset and clean up ep0 slot %u after disconnect\n", + slot_id); + reset_type = EP_HARD_RESET; } if (ep->ep_state & EP_HALTED) { @@ -1020,6 +1067,9 @@ static int xhci_handle_halted_endpoint(struct xhci_hcd *xhci, return 0; } + if (reset_type == EP_HARD_RESET) + ep->ep_state |= EP_HARD_CLEAR_TOGGLE; + err = xhci_reset_halted_ep(xhci, slot_id, ep->ep_index, reset_type); if (err) return err; @@ -1070,8 +1120,9 @@ static int xhci_invalidate_cancelled_tds(struct xhci_hcd *xhci, struct xhci_virt continue; } - /* device disconnected or link error, ep will be dropped */ - if (ep->ep_state & EP_DROP_PENDING) { + /* device disconnected or link error, non-ep0 endpoints will be dropped */ + if (ep->ep_state & EP_DROP_PENDING && ep->ep_index != 0) { + td_to_noop(xhci, ep, td, false); td->cancel_status = TD_CLEARED; continue; } diff --git a/drivers/usb/host/xhci.c b/drivers/usb/host/xhci.c index 30ac1bc4559b74..b50a582be1fbfa 100644 --- a/drivers/usb/host/xhci.c +++ b/drivers/usb/host/xhci.c @@ -1665,12 +1665,6 @@ static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flag goto free_priv; } - if (xhci->devs[slot_id]->rhub_port->link_inactive) { - xhci_dbg(xhci, "Can't queue urb, port error, link inactive\n"); - ret = -ENODEV; - goto free_priv; - } - if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for non-responsive xHCI host.\n", urb->ep->desc.bEndpointAddress, urb); @@ -1680,6 +1674,13 @@ static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flag ep_state = &xhci->devs[slot_id]->eps[ep_index].ep_state; + if (xhci->devs[slot_id]->rhub_port->link_inactive || + *ep_state & EP_DROP_PENDING) { + xhci_dbg(xhci, "Can't queue urb, port disconnect or link inactive\n"); + ret = -ENODEV; + goto free_priv; + } + if (*ep_state & (EP_GETTING_STREAMS | EP_GETTING_NO_STREAMS)) { xhci_warn(xhci, "WARN: Can't enqueue URB, ep in streams transition state %x\n", *ep_state); From 6036663be30a411b895d4ce9ba4625abbec5943b Mon Sep 17 00:00:00 2001 From: Connor Abbott Date: Thu, 29 Oct 2026 19:02:30 -0400 Subject: [PATCH 0077/2102] drm/msm: Fix GMEM_BASE on a8xx This was missed during initial bringup because GMEM_BASE is not used anymore for textures on a8xx. However other things such as mesh shading still use the GMEM aperture. Fix it to match the value programmed into the registers. Fixes: 288a93200892 ("drm/msm/adreno: Introduce A8x GPU Support") Signed-off-by: Connor Abbott Reviewed-by: Konrad Dybcio Patchwork: https://patchwork.freedesktop.org/patch/764371/ Message-ID: <20261029-drm-msm-gmem-base-fix-v2-1-26b338471b46@gmail.com> Signed-off-by: Rob Clark --- drivers/gpu/drm/msm/adreno/adreno_gpu.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/msm/adreno/adreno_gpu.c b/drivers/gpu/drm/msm/adreno/adreno_gpu.c index dadfe4c6943841..f7882bb8028d86 100644 --- a/drivers/gpu/drm/msm/adreno/adreno_gpu.c +++ b/drivers/gpu/drm/msm/adreno/adreno_gpu.c @@ -382,7 +382,9 @@ int adreno_get_param(struct msm_gpu *gpu, struct msm_context *ctx, *value = adreno_gpu->gmem; return 0; case MSM_PARAM_GMEM_BASE: - if (adreno_gpu->info->family >= ADRENO_6XX_GEN3) + if (adreno_gpu->info->family >= ADRENO_8XX_GEN1) + *value = SZ_64M; + else if (adreno_gpu->info->family >= ADRENO_6XX_GEN3) *value = 0; else *value = 0x100000; From d1eb0afa9140c740ff29985f9b89b1926b1b502d Mon Sep 17 00:00:00 2001 From: Sergei Kuznetsov Date: Fri, 23 Oct 2026 19:13:14 +0700 Subject: [PATCH 0078/2102] Input: xpad - add GameSir G7 Pro support Add the GameSir G7 Pro (0x3537:0x109c) in Xbox mode, connected through its 2.4G dongle. The controller uses the GIP protocol and was already bound through the GameSir vendor match, but showed up as "Generic X-Box pad" and its Share button was not reported. Set MAP_SHARE_BUTTON so the Share button is reported as KEY_RECORD. Signed-off-by: Sergei Kuznetsov Link: https://patch.msgid.link/20261023121314.8024-1-kernel@phnx47.net Cc: stable@vger.kernel.org Signed-off-by: Dmitry Torokhov --- drivers/input/joystick/xpad.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/input/joystick/xpad.c b/drivers/input/joystick/xpad.c index d2eb48d98fead7..53fd3b562f4140 100644 --- a/drivers/input/joystick/xpad.c +++ b/drivers/input/joystick/xpad.c @@ -409,6 +409,7 @@ static const struct xpad_device { { 0x3537, 0x100f, "GameSir Nova 2 Lite", 0, XTYPE_XBOX360 }, { 0x3537, 0x1010, "GameSir G7 SE", 0, XTYPE_XBOXONE }, { 0x3537, 0x1040, "GameSir Nova Lite", 0, XTYPE_XBOX360 }, + { 0x3537, 0x109c, "GameSir G7 Pro", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x3651, 0x1000, "CRKD SG", 0, XTYPE_XBOX360 }, { 0x366c, 0x0005, "ByoWave Proteus Controller", MAP_SHARE_BUTTON, XTYPE_XBOXONE, FLAG_DELAY_INIT }, { 0x3767, 0x0101, "Fanatec Speedster 3 Forceshock Wheel", 0, XTYPE_XBOX }, From d0c8bd5d18a492d64d05482f4b1700e14df7ff84 Mon Sep 17 00:00:00 2001 From: Jiale Yao Date: Fri, 25 Sep 2026 22:09:54 +0800 Subject: [PATCH 0079/2102] iio: gyro: bmg160: reject duplicate event disable The IIO core does not filter duplicate writes to the event enable attribute. bmg160_write_event_config() already ignores repeated enable requests, but a repeated disable request still calls bmg160_set_power_state(data, false), dropping a runtime PM reference that was not acquired for this request. This can underflow the runtime PM usage count and trigger a "Runtime PM usage count underflow" warning. Return early when the requested state already matches ev_enable_state. Fixes: 22b46c45fb9b ("iio:gyro:bmg160 Gyro Sensor driver") Signed-off-by: Jiale Yao Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/gyro/bmg160_core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/iio/gyro/bmg160_core.c b/drivers/iio/gyro/bmg160_core.c index b007f46d3fd624..0958b7d31a9281 100644 --- a/drivers/iio/gyro/bmg160_core.c +++ b/drivers/iio/gyro/bmg160_core.c @@ -761,7 +761,7 @@ static int bmg160_write_event_config(struct iio_dev *indio_dev, struct bmg160_data *data = iio_priv(indio_dev); int ret; - if (state && data->ev_enable_state) + if (state == data->ev_enable_state) return 0; mutex_lock(&data->mutex); From 9a60b35fe45801d45454e1efe90569c9cc6ea736 Mon Sep 17 00:00:00 2001 From: Jiale Yao Date: Fri, 25 Sep 2026 22:10:05 +0800 Subject: [PATCH 0080/2102] iio: imu: kmx61: reject duplicate event disable The IIO core does not filter duplicate writes to the event enable attribute. kmx61_write_event_config() already ignores repeated enable requests, but a repeated disable request still calls kmx61_set_power_state(data, false, KMX61_ACC), dropping a runtime PM reference that was not acquired for this request. This can underflow the runtime PM usage count and trigger a "Runtime PM usage count underflow" warning. Return early when the requested state already matches ev_enable_state. Fixes: fd3ae7a9f21c ("iio: imu: kmx61: Add support for any motion trigger") Signed-off-by: Jiale Yao Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/imu/kmx61.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/iio/imu/kmx61.c b/drivers/iio/imu/kmx61.c index c288437d53eae5..a4962b88ef58c7 100644 --- a/drivers/iio/imu/kmx61.c +++ b/drivers/iio/imu/kmx61.c @@ -939,7 +939,7 @@ static int kmx61_write_event_config(struct iio_dev *indio_dev, struct kmx61_data *data = kmx61_get_data(indio_dev); int ret = 0; - if (state && data->ev_enable_state) + if (state == data->ev_enable_state) return 0; guard(mutex)(&data->lock); From a107ee273c65414bfcf680b0bf1e9cf3c3365ce1 Mon Sep 17 00:00:00 2001 From: Alexis Bouzigues Date: Wed, 7 Oct 2026 09:34:16 -0500 Subject: [PATCH 0081/2102] iio: accel: adxl345: select IIO_BUFFER and IIO_KFIFO_BUF MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since the addition of FIFO watermark support, adxl345_core.c calls devm_iio_kfifo_buffer_setup() and iio_push_to_buffers(), but the ADXL345 Kconfig entry does not select IIO_BUFFER and IIO_KFIFO_BUF. Building with CONFIG_ADXL345_I2C=y and CONFIG_IIO_BUFFER=n fails to link: ld: drivers/iio/accel/adxl345_core.o: in function `adxl345_irq_handler': adxl345_core.c:(.text+0x145c): undefined reference to `iio_push_to_buffers' ld: drivers/iio/accel/adxl345_core.o: in function `adxl345_core_probe': adxl345_core.c:(.text+0x1db6): undefined reference to `devm_iio_kfifo_buffer_setup_ext' Add the missing selects on the hidden ADXL345 core symbol, as done for ADXL367, ADXL372 and ADXL380, so both the I2C and SPI front-ends are covered. Fixes: cf04212d1fe7 ("iio: accel: adxl345: add FIFO with watermark events") Signed-off-by: Alexis Bouzigues Tested-by: Joshua Crofts Reviewed-by: Joshua Crofts Reviewed-by: Nuno Sá Signed-off-by: Jonathan Cameron --- drivers/iio/accel/Kconfig | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/iio/accel/Kconfig b/drivers/iio/accel/Kconfig index 141ac984247cdd..dc560e1df64894 100644 --- a/drivers/iio/accel/Kconfig +++ b/drivers/iio/accel/Kconfig @@ -62,6 +62,8 @@ config ADXL313_SPI config ADXL345 tristate + select IIO_BUFFER + select IIO_KFIFO_BUF config ADXL345_I2C tristate "Analog Devices ADXL345 3-Axis Digital Accelerometer I2C Driver" From bfa3b177d839bb303d0187335115b572a2644920 Mon Sep 17 00:00:00 2001 From: Myeonghun Pak Date: Thu, 15 Oct 2026 22:47:35 -0400 Subject: [PATCH 0082/2102] iio: proximity: hx9023s: Allocate trigger before requesting IRQ An IRQ handler that already read trigger_enabled can poll data->trig after buffer disable. Detaching the virtual IRQ does not join this physical IRQ, and trigger deselection can drop the consumer reference. Devres may then free the trigger before joining the handler. Allocate the trigger before requesting the IRQ so devres joins the handler before dropping the allocation reference. This issue was identified as part of our ongoing research while reviewing kernel code. Fixes: 60df548277b7 ("iio: proximity: Add driver support for TYHX's HX9023S capacitive proximity sensor") Co-developed-by: Ijae Kim Signed-off-by: Ijae Kim Signed-off-by: Myeonghun Pak Reviewed-by: Joshua Crofts Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/proximity/hx9023s.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/drivers/iio/proximity/hx9023s.c b/drivers/iio/proximity/hx9023s.c index 0199a6351a4674..2a6da557f22ed0 100644 --- a/drivers/iio/proximity/hx9023s.c +++ b/drivers/iio/proximity/hx9023s.c @@ -1133,14 +1133,6 @@ static int hx9023s_probe(struct i2c_client *client) return dev_err_probe(dev, ret, "reg config failed\n"); if (client->irq) { - ret = devm_request_threaded_irq(dev, client->irq, - hx9023s_irq_handler, - hx9023s_irq_thread_handler, - IRQF_ONESHOT, - "hx9023s_event", indio_dev); - if (ret) - return ret; - data->trig = devm_iio_trigger_alloc(dev, "%s-dev%d", indio_dev->name, iio_device_id(indio_dev)); @@ -1150,6 +1142,14 @@ static int hx9023s_probe(struct i2c_client *client) data->trig->ops = &hx9023s_trigger_ops; iio_trigger_set_drvdata(data->trig, indio_dev); + ret = devm_request_threaded_irq(dev, client->irq, + hx9023s_irq_handler, + hx9023s_irq_thread_handler, + IRQF_ONESHOT, + "hx9023s_event", indio_dev); + if (ret) + return ret; + ret = devm_iio_trigger_register(dev, data->trig); if (ret) return dev_err_probe(dev, ret, From e5f7a6684a23d9b20184a81b4ebded3b3504ccdc Mon Sep 17 00:00:00 2001 From: Arnav Kapoor Date: Sun, 11 Oct 2026 10:26:17 +0530 Subject: [PATCH 0083/2102] iio: imu: inv_mpu6050: fix magnetometer scale of Y and Z axes inv_mpu_magn_get_scale() returns st->magn_raw_to_gauss[chan->address], where magn_raw_to_gauss[] holds one coefficient per axis, computed in inv_magn_init() from the per-axis factory sensitivity adjustment values (ASAX, ASAY, ASAZ) of the AK8975/AK8963 magnetometer. However INV_MPU9X50_MAGN_CHAN() never sets .address, so it is 0 for all three magnetometer channels. As a result the Y and Z channels report the scale computed from the X axis adjustment value, and userspace scales the Y and Z readings with the wrong per-axis calibration. Set .address to the axis index (0 for X, 1 for Y, 2 for Z) in the channel macro, matching the order used to fill magn_raw_to_gauss[]. Fixes: b1392de06184 ("iio: imu: inv_mpu6050: add MPU925x magnetometer support") Signed-off-by: Arnav Kapoor Acked-by: Jean-Baptiste Maneyrol Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/imu/inv_mpu6050/inv_mpu_core.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c b/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c index 38c3f3b398d4f8..1614f49be66c88 100644 --- a/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c +++ b/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c @@ -1576,6 +1576,8 @@ static const unsigned long inv_mpu_scan_masks[] = { .type = IIO_MAGN, \ .modified = 1, \ .channel2 = _chan2, \ + /* index of the axis in magn_raw_to_gauss[] */ \ + .address = (_chan2) - IIO_MOD_X, \ .info_mask_separate = BIT(IIO_CHAN_INFO_SCALE) | \ BIT(IIO_CHAN_INFO_RAW), \ .scan_index = _index, \ From 3a5e2ca34cadd9d5993064884aa5b9c4f6d71dff Mon Sep 17 00:00:00 2001 From: Arnav Kapoor Date: Sun, 11 Oct 2026 10:27:04 +0530 Subject: [PATCH 0084/2102] iio: imu: inv_mpu6050: fix swapped accel and gyro startup times struct inv_mpu6050_hw declares startup_time as { accel, gyro }, but every entry of hw_info[] initializes it positionally as { *_GYRO_STARTUP_TIME, *_ACCEL_STARTUP_TIME }, so the two values are swapped for all chips. inv_mpu6050_switch_engine() waits for startup_time.gyro after enabling the gyroscope, so it waits for the accelerometer startup time instead, e.g. 20 ms instead of 60 ms on MPU6050 and 20 ms instead of 100 ms on ICM20602, and the first gyroscope samples can be read before the sensor has settled. Enabling only the accelerometer waits longer than needed. Use designated initializers, so each value is assigned to the member it is named after. Fixes: e46a36d92da0 ("Add startup time for each chip using inv_mpu6050 driver") Signed-off-by: Arnav Kapoor Acked-by: Jean-Baptiste Maneyrol Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/imu/inv_mpu6050/inv_mpu_core.c | 95 +++++++++++++++++----- 1 file changed, 76 insertions(+), 19 deletions(-) diff --git a/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c b/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c index 1614f49be66c88..7265a3c3de0582 100644 --- a/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c +++ b/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c @@ -150,7 +150,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6500_WHOAMI_VALUE, @@ -159,7 +162,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6515_WHOAMI_VALUE, @@ -168,7 +174,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6880_WHOAMI_VALUE, @@ -177,7 +186,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4096, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6000_WHOAMI_VALUE, @@ -186,7 +198,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9150_WHOAMI_VALUE, @@ -195,7 +210,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9250_WHOAMI_VALUE, @@ -204,7 +222,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9255_WHOAMI_VALUE, @@ -213,7 +234,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20608_WHOAMI_VALUE, @@ -222,7 +246,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20608D_WHOAMI_VALUE, @@ -231,7 +258,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20609_WHOAMI_VALUE, @@ -240,7 +270,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20689_WHOAMI_VALUE, @@ -249,7 +282,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20600_WHOAMI_VALUE, @@ -258,7 +294,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1008, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20602_GYRO_STARTUP_TIME, INV_ICM20602_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20602_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20602_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20602_WHOAMI_VALUE, @@ -267,7 +306,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1008, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20602_GYRO_STARTUP_TIME, INV_ICM20602_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20602_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20602_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20690_WHOAMI_VALUE, @@ -276,7 +318,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20690_GYRO_STARTUP_TIME, INV_ICM20690_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20690_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20690_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20380_WHOAMI_VALUE, .name = "IAM20380", @@ -284,7 +329,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680_WHOAMI_VALUE, @@ -293,7 +341,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680HP_WHOAMI_VALUE, @@ -302,7 +353,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680HT_WHOAMI_VALUE, @@ -311,7 +365,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, }; From 043ececf147863fbd253687aa0b9edcac358a711 Mon Sep 17 00:00:00 2001 From: Arnav Kapoor Date: Tue, 6 Oct 2026 10:22:41 +0530 Subject: [PATCH 0085/2102] iio: common: scmi_sensors: fix truncating 64-bit divisions do_div() divides a 64-bit dividend by a 32-bit divisor: the divisor is stored in a uint32_t on all architectures. The driver passes 64-bit divisors to it in several places, so they are silently truncated: - scmi_iio_set_odr_val() divides by uHz, which exceeds 32 bits for sampling frequencies above ~4294 Hz. - convert_ns_to_freq() divides by interval_ns, which exceeds 32 bits for update intervals of ~4.29 s and above. If its low 32 bits happen to be zero, this is a division by zero. - scmi_iio_get_odr_val(), scmi_iio_convert_interval_to_ns(), scmi_iio_sensor_update_cb() and scmi_iio_get_raw_available() divide by int_pow(10, n), which returns u64 and exceeds 32 bits for n >= 10. The SCMI exponent fields allow values down to -16. Truncation results in wrong sampling frequency, timestamp and raw_available values being reported to userspace. Use div64_u64() and div64_u64_rem(), which take a 64-bit divisor. Fixes: f774117c96f9 ("iio/scmi: Adding support for IIO SCMI Based Sensors") Reported-by: kernel test robot Closes: https://lore.kernel.org/oe-kbuild-all/202606040245.XfmRpBhA-lkp@intel.com/ Signed-off-by: Arnav Kapoor Reviewed-by: Andy Shevchenko Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/common/scmi_sensors/scmi_iio.c | 27 +++++++++++----------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/drivers/iio/common/scmi_sensors/scmi_iio.c b/drivers/iio/common/scmi_sensors/scmi_iio.c index 442b40ef27cf51..659a2f888ac909 100644 --- a/drivers/iio/common/scmi_sensors/scmi_iio.c +++ b/drivers/iio/common/scmi_sensors/scmi_iio.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -70,8 +71,7 @@ static int scmi_iio_sensor_update_cb(struct notifier_block *nb, */ tstamp_scale = sensor->sensor_info->tstamp_scale + 9; if (tstamp_scale < 0) { - do_div(time, int_pow(10, abs(tstamp_scale))); - time_ns = time; + time_ns = div64_u64(time, int_pow(10, abs(tstamp_scale))); } else { time_ns = time * int_pow(10, tstamp_scale); } @@ -162,7 +162,7 @@ static int scmi_iio_set_odr_val(struct iio_dev *iio_dev, int val, int val2) mult = scnprintf(buf, sizeof(buf), "%llu", sf) - 1; sec = int_pow(10, mult) * MICROHZ_PER_HZ; - do_div(sec, uHz); + sec = div64_u64(sec, uHz); if (sec == 0) { dev_err(&iio_dev->dev, "Trying to set invalid sensor update value for sensor %s", @@ -237,13 +237,10 @@ static int scmi_iio_read_avail(struct iio_dev *iio_dev, static void convert_ns_to_freq(u64 interval_ns, u64 *hz, u64 *uhz) { - u64 rem, freq; + u64 rem; - freq = NSEC_PER_SEC; - rem = do_div(freq, interval_ns); - *hz = freq; - *uhz = rem * 1000000UL; - do_div(*uhz, interval_ns); + *hz = div64_u64_rem(HZ_PER_GHZ, interval_ns, &rem); + *uhz = div64_u64(rem * MICROHZ_PER_HZ, interval_ns); } static int scmi_iio_get_odr_val(struct iio_dev *iio_dev, int *val, int *val2) @@ -269,7 +266,8 @@ static int scmi_iio_get_odr_val(struct iio_dev *iio_dev, int *val, int *val2) mult = SCMI_SENS_CFG_GET_UPDATE_EXP(sensor_config); if (mult < 0) { sensor_interval_mult = int_pow(10, abs(mult)); - do_div(sensor_update_interval, sensor_interval_mult); + sensor_update_interval = div64_u64(sensor_update_interval, + sensor_interval_mult); } else { sensor_interval_mult = int_pow(10, mult); sensor_update_interval = @@ -395,9 +393,9 @@ static ssize_t scmi_iio_get_raw_available(struct iio_dev *iio_dev, */ exponent = exponent - scale; if (exponent < 0) { - rem = do_div(resolution, - int_pow(10, abs(exponent)) - ); + resolution = div64_u64_rem(resolution, + int_pow(10, abs(exponent)), + &rem); len = sysfs_emit(buf, "[%lld %llu.%llu %lld]\n", min_range, resolution, rem, max_range); @@ -491,7 +489,8 @@ static u64 scmi_iio_convert_interval_to_ns(u32 val) mult = SCMI_SENS_INTVL_GET_EXP(val); if (mult < 0) { sensor_interval_mult = int_pow(10, abs(mult)); - do_div(sensor_update_interval, sensor_interval_mult); + sensor_update_interval = div64_u64(sensor_update_interval, + sensor_interval_mult); } else { sensor_interval_mult = int_pow(10, mult); sensor_update_interval = From 6bcabc30b89f31e2925647d1ffa5a0e4b7919829 Mon Sep 17 00:00:00 2001 From: Alexander Sarmanow Date: Mon, 12 Oct 2026 16:43:15 +0200 Subject: [PATCH 0086/2102] iio: light: vcnl4035: Fix reversed ALS mode bit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit According to the datasheet (table 2) the ALS_SD bit behaves the opposite way the current ALS mode defines are set, writing 0 powers the sensor and writing 1 shuts it down. The current driver thinks the ALS is up while it's actually shut down and it's down when the systems powers it up. Fixes: 55707294c4eb ("iio: light: Add support for vishay vcnl4035") Cc: stable@vger.kernel.org Signed-off-by: Alexander Sarmanow Reviewed-by: Nuno Sá Signed-off-by: Jonathan Cameron --- drivers/iio/light/vcnl4035.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/iio/light/vcnl4035.c b/drivers/iio/light/vcnl4035.c index ce1bd42b0c7ca7..f1cc75245001c7 100644 --- a/drivers/iio/light/vcnl4035.c +++ b/drivers/iio/light/vcnl4035.c @@ -44,8 +44,8 @@ #define VCNL4035_DEV_ID_MASK GENMASK(7, 0) /* Default values */ -#define VCNL4035_MODE_ALS_ENABLE BIT(0) -#define VCNL4035_MODE_ALS_DISABLE 0x00 +#define VCNL4035_MODE_ALS_ENABLE 0x00 +#define VCNL4035_MODE_ALS_DISABLE BIT(0) #define VCNL4035_MODE_ALS_INT_ENABLE BIT(1) #define VCNL4035_MODE_ALS_INT_DISABLE 0 #define VCNL4035_DEV_ID_VAL 0x80 From 0cb3fc8987038a26ac0f581bfa26b16daf6ca6a7 Mon Sep 17 00:00:00 2001 From: Nikhil Gautam Date: Mon, 12 Oct 2026 17:15:53 +0530 Subject: [PATCH 0087/2102] iio: atlas-ezo: Fix humidity channel read support The atlas_ezo_read_raw() function rejects channels that are not of type IIO_CONCENTRATION, preventing the relative humidity channel from reading raw and scale values. Remove the early channel type check to allow both concentration and relative humidity channels to reach the mask-specific handling. Fixes: dc3ebfcaa51f ("iio: chemical: atlas-ezo-sensor: add humidity sensor support") Signed-off-by: Nikhil Gautam Reviewed-by: Joshua Crofts Reviewed-by: Matt Ranostay Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/chemical/atlas-ezo-sensor.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/drivers/iio/chemical/atlas-ezo-sensor.c b/drivers/iio/chemical/atlas-ezo-sensor.c index 298b2fe48a19c5..abe26ba212f598 100644 --- a/drivers/iio/chemical/atlas-ezo-sensor.c +++ b/drivers/iio/chemical/atlas-ezo-sensor.c @@ -116,9 +116,6 @@ static int atlas_ezo_read_raw(struct iio_dev *indio_dev, struct atlas_ezo_data *data = iio_priv(indio_dev); struct i2c_client *client = data->client; - if (chan->type != IIO_CONCENTRATION) - return -EINVAL; - switch (mask) { case IIO_CHAN_INFO_RAW: { int ret; From dd53f1841ecfa2da152cbc31038a5f125b2b9e57 Mon Sep 17 00:00:00 2001 From: Yu-Hsiang Tseng Date: Mon, 12 Oct 2026 15:41:44 +0800 Subject: [PATCH 0088/2102] iio: acpi: Accept comma separated values in ROTM strings The ROTM method of the MXC6655 accelerometer on the Higole F9B, an Alder Lake-N handheld (AMI BIOS F9D_16G_P800217, DMI strings are all "Default string"), separates the values with a comma and a space: Method (ROTM, 0, NotSerialized) { Name (SBUF, Package (0x03) { "-1, 0, 0", "0, 1, 0", "0, 0, 1" }) Return (SBUF) } iio_read_acpi_mount_matrix() only accepts the space separated form used in Microsoft's example ("0 1 0"). It rejects this matrix and mxc4005 falls back to the identity matrix: mxc4005 i2c-MXC6655:00: Incorrect ACPI mount matrix string format mxc4005 i2c-MXC6655:00: mounting matrix not found: using identity... With the X axis not inverted, iio-sensor-proxy reports left-up when the device is held right-up and vice versa, so the desktop turns the picture upside down whenever the handheld is held in landscape. It is not the only BIOS written this way. The BOSC0200 on the AYANEO Air Plus uses commas in its ROMS method as well, with a space before one of them, and its ROMK method has "1, 0,0": Method (ROMS, 0, NotSerialized) { Name (SBUF, Package (0x03) { "-1, 0, 0", "0, -1 , 0", "0, 0, -1" }) Return (SBUF) } The kernel's sscanf() does not support '%*[', so there is no clean way to take both separators in a single format string. That leaves either a second sscanf() call with a comma format, or normalizing the separator first. Do the latter: turn the commas into spaces before parsing, so the existing "%d %d %d" format, which already takes any amount of white space around the values, keeps working unchanged. The strings live in the buffer acpi_evaluate_object() allocated for us, so they can be modified in place. With this change in_accel_mount_matrix on the Higole F9B reads "-1, 0, 0; 0, 1, 0; 0, 0, 1" and, with no udev hwdb override, the desktop rotates correctly in all four orientations. The AYANEO Air Plus was not tested; systemd's hwdb has an entry for it, which iio-sensor-proxy prefers over the kernel's matrix. Link: https://github.com/hhd-dev/hwinfo/blob/d9508123bee46ae3a59dc24826030ef51ea95058/devices/ayaneo_airplus/acpi/decoded/dsdt.dsl Cc: stable@vger.kernel.org # 6.10.x Signed-off-by: Yu-Hsiang Tseng Reviewed-by: Andy Shevchenko Signed-off-by: Jonathan Cameron --- drivers/iio/industrialio-acpi.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/drivers/iio/industrialio-acpi.c b/drivers/iio/industrialio-acpi.c index d67a4384379988..c77926f6db6215 100644 --- a/drivers/iio/industrialio-acpi.c +++ b/drivers/iio/industrialio-acpi.c @@ -6,6 +6,7 @@ #include #include #include +#include /** * iio_read_acpi_mount_matrix() - Read accelerometer mount matrix info from ACPI @@ -63,6 +64,14 @@ bool iio_read_acpi_mount_matrix(struct device *dev, } str = elements[i].string.pointer; + /* + * Microsoft's example separates the values with spaces, "0 1 0". + * Some BIOSes use commas instead, with or without spaces around + * them: "0, 1, 0", "0, -1 , 0", "1, 0,0". The string lives in + * the buffer allocated for us above, so turn the commas into + * spaces in place before parsing. + */ + strreplace(str, ',', ' '); if (sscanf(str, "%d %d %d", &val[0], &val[1], &val[2]) != 3) { dev_err(dev, "Incorrect ACPI mount matrix string format\n"); goto out_free_buffer; From 38e05cf38df705b7fa9e8ada931589fa96816f09 Mon Sep 17 00:00:00 2001 From: Shashank Mohan Jain Date: Mon, 12 Oct 2026 10:30:54 +0530 Subject: [PATCH 0089/2102] iio: magnetometer: mmc35240: leave cache-only mode before the cache sync mmc35240_resume() marks the register cache dirty and calls regcache_sync_region() while the regmap is still in cache-only mode. It calls regcache_cache_only(false) only after the sync. This ordering has been wrong since the resume support was added; it happened to work until regmap started rejecting a sync in cache-only mode. Since commit afc8e3ee8307 ("regcache: Validate cache_only state in regcache_sync_region()") a sync in cache-only mode is refused with a WARN and -EINVAL. Every resume now gives WARNING: drivers/base/regmap/regcache.c:536 at regcache_sync_region+0x1a4/0x1c0 ... mmc35240_resume+0x30/0x70 dpm_run_callback+0x7d/0x1c0 device_resume+0x175/0x270 ... mmc35240 1-0030: Failed to restore control registers and the control registers are not written. If the chip lost its state during suspend, it runs with the reset value of CTRL1 while the cache, and with it the sampling frequency attribute, still has the configured value. Writing the same frequency again does not repair this, because regmap_update_bits() finds no difference to the cache. Leave cache-only mode first, then mark the cache dirty and sync it. Reproduced in qemu with the driver bound to an i2c-stub device: set in_magn_sampling_frequency to 25 (CTRL1 = 0x02), clear CTRL0 and CTRL1 of the stub behind the driver's back to emulate the power loss, and run a suspend/resume cycle with "devices" in /sys/power/pm_test. Without this change CTRL1 is still 0x00 after resume and the warning is printed. With it, and also with the regcache commit reverted, CTRL1 is 0x02 again and there is no warning. Not tested on real hardware. Fixes: 553a776b7908 ("iio: magnetometer: mmc35240: Add PM sleep support") Signed-off-by: Shashank Mohan Jain Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/magnetometer/mmc35240.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/iio/magnetometer/mmc35240.c b/drivers/iio/magnetometer/mmc35240.c index 6f40cba4b1ba74..7f028d7f1f1e3d 100644 --- a/drivers/iio/magnetometer/mmc35240.c +++ b/drivers/iio/magnetometer/mmc35240.c @@ -532,14 +532,13 @@ static int mmc35240_resume(struct device *dev) struct mmc35240_data *data = iio_priv(indio_dev); int ret; + regcache_cache_only(data->regmap, false); regcache_mark_dirty(data->regmap); ret = regcache_sync_region(data->regmap, MMC35240_REG_CTRL0, MMC35240_REG_CTRL1); if (ret < 0) dev_err(dev, "Failed to restore control registers\n"); - regcache_cache_only(data->regmap, false); - return 0; } From c794a0a82fb189d98c635c5791c67c672ad80eb8 Mon Sep 17 00:00:00 2001 From: Shashank Mohan Jain Date: Mon, 12 Oct 2026 10:30:55 +0530 Subject: [PATCH 0090/2102] iio: magnetometer: mmc5633: leave cache-only mode before the cache sync mmc5633_resume() marks the register cache dirty and calls regcache_sync_region() while the regmap is still in cache-only mode. It calls regcache_cache_only(false) only after the sync. This ordering has been wrong since the driver was added; it happened to work until regmap started rejecting a sync in cache-only mode. Since commit afc8e3ee8307 ("regcache: Validate cache_only state in regcache_sync_region()") a sync in cache-only mode is refused with a WARN and -EINVAL. Every resume now gives WARNING: drivers/base/regmap/regcache.c:536 at regcache_sync_region+0x1a4/0x1c0 ... mmc5633_resume+0x2d/0x70 dpm_run_callback+0x7d/0x1c0 device_resume+0x175/0x270 ... mmc5633_i2c 1-0030: Failed to restore control registers and the control registers are not written. If the chip lost its state during suspend, it runs with the reset value of CTRL1 while the cache, and with it the sampling frequency attribute, still has the configured value. Writing the same frequency again does not repair this, because regmap_update_bits() finds no difference to the cache. Leave cache-only mode first, then mark the cache dirty and sync it. Reproduced in qemu with the I2C driver bound to an i2c-stub device: set in_magn_sampling_frequency to 3.5 (CTRL1 = 0x02), clear CTRL0 and CTRL1 of the stub behind the driver's back to emulate the power loss, and run a suspend/resume cycle with "devices" in /sys/power/pm_test. Without this change CTRL1 is still 0x00 after resume and the warning is printed. With it, and also with the regcache commit reverted, CTRL1 is 0x02 again and there is no warning. Not tested on real hardware. Fixes: 6e5f6bf2e3f0 ("iio: magnetometer: Add mmc5633 sensor") Signed-off-by: Shashank Mohan Jain Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/magnetometer/mmc5633.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/iio/magnetometer/mmc5633.c b/drivers/iio/magnetometer/mmc5633.c index f4dae7ba1335b2..b651f01e1b5d98 100644 --- a/drivers/iio/magnetometer/mmc5633.c +++ b/drivers/iio/magnetometer/mmc5633.c @@ -499,13 +499,12 @@ static int mmc5633_resume(struct device *dev) struct regmap *regmap = dev_get_regmap(dev, NULL); int ret; + regcache_cache_only(regmap, false); regcache_mark_dirty(regmap); ret = regcache_sync_region(regmap, MMC5633_REG_CTRL0, MMC5633_REG_CTRL1); if (ret) dev_err(dev, "Failed to restore control registers\n"); - regcache_cache_only(regmap, false); - return 0; } From ef5c183a863bb69bf019a2d2ae0e1bfdaebe6222 Mon Sep 17 00:00:00 2001 From: Viral Patel Date: Wed, 14 Oct 2026 23:07:36 +0530 Subject: [PATCH 0091/2102] iio: magnetometer: tlv493d: fix magnetic field scale The TLV493D-A1B6 datasheet specifies a magnetic resolution of 98 uT/LSB (0.098 mT/LSB). IIO reports magnetic field in Gauss (1 mT = 10 G), so the scale should be 0.98 G/LSB. The driver currently reports 98/1000 = 0.098 G/LSB, which under-reports the magnetic field by a factor of 10. The comment also gives the resolution as 0.0098 mT (9.8 uT), mixing up units. Correct the scale value and the comment. Fixes: 106511d280c7 ("iio: magnetometer: add support for Infineon TLV493D 3D Magentic sensor") Signed-off-by: Viral Patel Reviewed-by: Joshua Crofts Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/magnetometer/tlv493d.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/iio/magnetometer/tlv493d.c b/drivers/iio/magnetometer/tlv493d.c index 03415cc2c9b3ee..234e3ce63ff784 100644 --- a/drivers/iio/magnetometer/tlv493d.c +++ b/drivers/iio/magnetometer/tlv493d.c @@ -299,11 +299,11 @@ static int tlv493d_read_raw(struct iio_dev *indio_dev, switch (chan->type) { case IIO_MAGN: /* - * Magnetic field scale: 0.0098 mTesla (i.e. 9.8 µT) - * Magnetic field in Gauss: mT * 10 = 0.098. + * Magnetic field scale: 0.098 mTesla (i.e. 98 µT) per LSB. + * In Gauss (1 mT = 10 G): 0.98 G per LSB. */ *val = 98; - *val2 = 1000; + *val2 = 100; return IIO_VAL_FRACTIONAL; case IIO_TEMP: /* From 0f8945d5da179594ed7ba058eeb363964438d2d7 Mon Sep 17 00:00:00 2001 From: Arnav Kapoor Date: Sun, 11 Oct 2026 10:24:08 +0530 Subject: [PATCH 0092/2102] iio: common: cros_ec_sensors: use sensor_scale union member for CALIBSCALE The IIO_CHAN_INFO_CALIBSCALE read and write paths send MOTIONSENSE_CMD_SENSOR_SCALE, but set the flags through the sensor_offset member of the request union, while the scale values in the write path are filled through sensor_scale. This only works because the sensor_offset and sensor_scale structs of struct ec_params_motion_sense happen to place flags at the same offset. Use the sensor_scale member that matches the command, so all fields of the request are set through the same struct. No functional change. Fixes: ed1f2e85da79 ("iio: cros_ec: Add calibscale for 3d MEMS") Signed-off-by: Arnav Kapoor Reviewed-by: Joshua Crofts Reviewed-by: Tzung-Bi Shih Signed-off-by: Jonathan Cameron --- drivers/iio/common/cros_ec_sensors/cros_ec_sensors.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/drivers/iio/common/cros_ec_sensors/cros_ec_sensors.c b/drivers/iio/common/cros_ec_sensors/cros_ec_sensors.c index 551b86236abcca..2839714f5bc8e5 100644 --- a/drivers/iio/common/cros_ec_sensors/cros_ec_sensors.c +++ b/drivers/iio/common/cros_ec_sensors/cros_ec_sensors.c @@ -70,7 +70,7 @@ static int cros_ec_sensors_read(struct iio_dev *indio_dev, break; case IIO_CHAN_INFO_CALIBSCALE: st->core.param.cmd = MOTIONSENSE_CMD_SENSOR_SCALE; - st->core.param.sensor_offset.flags = 0; + st->core.param.sensor_scale.flags = 0; ret = cros_ec_motion_send_host_cmd(&st->core, 0); if (ret == -EPROTO || ret == -EOPNOTSUPP) { @@ -178,8 +178,7 @@ static int cros_ec_sensors_write(struct iio_dev *indio_dev, /* Send to EC for each axis, even if not complete */ st->core.param.cmd = MOTIONSENSE_CMD_SENSOR_SCALE; - st->core.param.sensor_offset.flags = - MOTION_SENSE_SET_OFFSET; + st->core.param.sensor_scale.flags = MOTION_SENSE_SET_OFFSET; for (i = CROS_EC_SENSOR_X; i < CROS_EC_SENSOR_MAX_AXIS; i++) st->core.param.sensor_scale.scale[i] = st->core.calib[i].scale; From 4e9f192f997dc56f309090233352d62edbea42ce Mon Sep 17 00:00:00 2001 From: Alexis Bouzigues Date: Tue, 6 Oct 2026 19:08:58 -0500 Subject: [PATCH 0093/2102] iio: accel: adxl313: add missing buffer selections in Kconfig MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The FIFO support added to the ADXL313 core uses devm_iio_kfifo_buffer_setup() and iio_push_to_buffers(), but its Kconfig entry does not select the required buffer support. Enabling either frontend without IIO_BUFFER or IIO_KFIFO_BUF causes undefined references to devm_iio_kfifo_buffer_setup_ext() and iio_push_to_buffers(). Select IIO_BUFFER and IIO_KFIFO_BUF from the shared ADXL313 core symbol so both the I2C and SPI frontends have the required dependencies. Fixes: ff8093fa6ba4 ("iio: accel: adxl313: add buffered FIFO watermark with interrupt handling") Cc: stable@vger.kernel.org Signed-off-by: Alexis Bouzigues Tested-by: Joshua Crofts Reviewed-by: Joshua Crofts Reviewed-by: Nuno Sá Signed-off-by: Jonathan Cameron --- drivers/iio/accel/Kconfig | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/iio/accel/Kconfig b/drivers/iio/accel/Kconfig index dc560e1df64894..c6fce69ac4703c 100644 --- a/drivers/iio/accel/Kconfig +++ b/drivers/iio/accel/Kconfig @@ -33,6 +33,8 @@ config ADIS16209 config ADXL313 tristate + select IIO_BUFFER + select IIO_KFIFO_BUF config ADXL313_I2C tristate "Analog Devices ADXL313 3-Axis Digital Accelerometer I2C Driver" From 9253a88b28d4ff6b70c015838e516fc385047dd5 Mon Sep 17 00:00:00 2001 From: Arka Mondal Date: Wed, 7 Oct 2026 00:32:09 +0900 Subject: [PATCH 0094/2102] dt-bindings: iio: dac: adi,ad5758: Fix the 4 mA to 20 mA current range MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit adi,range-microamp gives the 4 mA to 20 mA range as <4 24000>. The values are in microamps, so this reads as 4 uA to 24 mA. The original text binding described <4 24000> as the "4 mA to 20 mA current range", and the data sheet (Rev. B, Table 32) confirms range code 1010 is 4 mA to 20 mA. Replace it with <4000 20000>. No in-tree device tree uses this binding, so nothing in the tree changes. A device tree that still has the old value no longer validates. Fixes: 777baca07ef1 ("dt-bindings: iio: dac: Add docs for AD5758 DAC") Signed-off-by: Arka Mondal Reviewed-by: Nuno Sá Acked-by: Conor Dooley Signed-off-by: Jonathan Cameron --- Documentation/devicetree/bindings/iio/dac/adi,ad5758.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/iio/dac/adi,ad5758.yaml b/Documentation/devicetree/bindings/iio/dac/adi,ad5758.yaml index 5121685337b5ed..a0f2649129e0f2 100644 --- a/Documentation/devicetree/bindings/iio/dac/adi,ad5758.yaml +++ b/Documentation/devicetree/bindings/iio/dac/adi,ad5758.yaml @@ -66,8 +66,8 @@ properties: - const: 0 - enum: [20000, 24000] - items: - - const: 4 - - const: 24000 + - const: 4000 + - const: 20000 - items: - const: -20000 - const: 20000 From a6cae12024949f19b0b0a7296ea4bc52be2d5b38 Mon Sep 17 00:00:00 2001 From: Arka Mondal Date: Wed, 7 Oct 2026 00:32:10 +0900 Subject: [PATCH 0095/2102] iio: dac: ad5758: Fix the 4 mA to 20 mA current range MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Range code 1010 selects 4 mA to 20 mA (data sheet Rev. B, Table 32), but the driver describes it as 4 uA to 24 mA. With the reported scale and offset, userspace converts raw code 0 to about 0 mA instead of 4 mA, and full scale to about 23 mA instead of 20 mA. Describe the range as 4000 to 20000 uA and rename the enum entry to match. A device tree that still has <4 24000> no longer matches any entry in the table, so probe fails with "range invalid". Fixes: 28d1a7ac2a0d ("iio: dac: Add AD5758 support") Signed-off-by: Arka Mondal Reviewed-by: Nuno Sá Signed-off-by: Jonathan Cameron --- drivers/iio/dac/ad5758.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/iio/dac/ad5758.c b/drivers/iio/dac/ad5758.c index 1e21ad2a050dbe..4c15447ccb6bfb 100644 --- a/drivers/iio/dac/ad5758.c +++ b/drivers/iio/dac/ad5758.c @@ -141,7 +141,7 @@ enum ad5758_output_range { AD5758_RANGE_PLUSMINUS_10V, AD5758_RANGE_0mA_20mA = 8, AD5758_RANGE_0mA_24mA, - AD5758_RANGE_4mA_24mA, + AD5758_RANGE_4mA_20mA, AD5758_RANGE_PLUSMINUS_20mA, AD5758_RANGE_PLUSMINUS_24mA, AD5758_RANGE_MINUS_1mA_PLUS_22mA, @@ -164,7 +164,7 @@ static const struct ad5758_range ad5758_voltage_range[] = { static const struct ad5758_range ad5758_current_range[] = { { AD5758_RANGE_0mA_20mA, 0, 20000}, { AD5758_RANGE_0mA_24mA, 0, 24000 }, - { AD5758_RANGE_4mA_24mA, 4, 24000 }, + { AD5758_RANGE_4mA_20mA, 4000, 20000 }, { AD5758_RANGE_PLUSMINUS_20mA, -20000, 20000 }, { AD5758_RANGE_PLUSMINUS_24mA, -24000, 24000 }, { AD5758_RANGE_MINUS_1mA_PLUS_22mA, -1000, 22000 }, From dff701806ab6252f6a0fccba880c47cd09602625 Mon Sep 17 00:00:00 2001 From: Karl Mehltretter Date: Tue, 6 Oct 2026 05:41:47 +0200 Subject: [PATCH 0096/2102] iio: trigger: Return an error when the trigger has no free irq iio_trigger_attach_poll_func() prints an error when all CONFIG_IIO_CONSUMERS_PER_TRIGGER irqs of the trigger are in use, but returns 0. The buffer of the extra consumer is enabled without a poll function. Disabling that buffer calls clear_bit() with a negative bit number and drops a module reference for the second time. On arm and arm64 the clear_bit() goes about 512 MB past the pool bitmap. That is an oops if the address is not mapped, and a bit cleared in unrelated memory if it is. Return the error from iio_trigger_get_irq(). Fixes: 995438233579 ("iio: Fix error handling in iio_trigger_attach_poll_func") Cc: stable@vger.kernel.org Signed-off-by: Karl Mehltretter Reviewed-by: Joshua Crofts Signed-off-by: Jonathan Cameron --- drivers/iio/industrialio-trigger.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/iio/industrialio-trigger.c b/drivers/iio/industrialio-trigger.c index 76926fee0f84d9..fc4651490d4243 100644 --- a/drivers/iio/industrialio-trigger.c +++ b/drivers/iio/industrialio-trigger.c @@ -293,6 +293,7 @@ int iio_trigger_attach_poll_func(struct iio_trigger *trig, if (pf->irq < 0) { pr_err("Could not find an available irq for trigger %s, CONFIG_IIO_CONSUMERS_PER_TRIGGER=%d limit might be exceeded\n", trig->name, CONFIG_IIO_CONSUMERS_PER_TRIGGER); + ret = pf->irq; goto out_put_module; } From 0a570feeca37d85fbfd6b4f6e3d9f33e1461c634 Mon Sep 17 00:00:00 2001 From: Vidhu Sarwal Date: Mon, 28 Sep 2026 19:54:50 +0530 Subject: [PATCH 0097/2102] iio: humidity: am2315: fix negative temperature decoding The AM2315/AM2320 report temperature as a sign-magnitude value, with bit 15 as the sign and bits 14-0 as the magnitude. am2315_read_data() stores the raw value directly in an s16, causing negative temperatures to be interpreted as two's complement. Both the read_raw and the triggered buffer paths are affected. Decode the sign bit before storing the temperature value. Positive readings are unaffected. Fixes: 366a3270c1c5 ("iio: humidity: Add support for AM2315") Signed-off-by: Vidhu Sarwal Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/humidity/am2315.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/drivers/iio/humidity/am2315.c b/drivers/iio/humidity/am2315.c index 5c7582f3a4f94f..8cf7e4e176a971 100644 --- a/drivers/iio/humidity/am2315.c +++ b/drivers/iio/humidity/am2315.c @@ -123,6 +123,7 @@ static int am2315_read_data(struct am2315_data *data, */ u8 rx_buf[8]; u16 crc; + u16 temp_raw; /* First wake up the device. */ am2315_ping(data->client); @@ -154,8 +155,15 @@ static int am2315_read_data(struct am2315_data *data, sensor_data->hum_data = (rx_buf[AM2315_HUM_OFFSET] << 8) | rx_buf[AM2315_HUM_OFFSET + 1]; - sensor_data->temp_data = (rx_buf[AM2315_TEMP_OFFSET] << 8) | - rx_buf[AM2315_TEMP_OFFSET + 1]; + + /* + * Temperature is sign-magnitude, not two's complement: + * bit 15 is the sign, bits 14-0 are the magnitude (x0.1 degC). + */ + temp_raw = (rx_buf[AM2315_TEMP_OFFSET] << 8) | + rx_buf[AM2315_TEMP_OFFSET + 1]; + sensor_data->temp_data = (temp_raw & 0x8000) ? + -(temp_raw & 0x7fff) : temp_raw; return ret; From 4d4e75b3074bc29525c963a81c19471528f29a45 Mon Sep 17 00:00:00 2001 From: Salah Triki Date: Thu, 17 Sep 2026 12:01:20 +0100 Subject: [PATCH 0098/2102] iio: temperature: mlx90614: Fix dual channel probe condition check In mlx90614_probe_num_ir_sensors(), the check on chip_info->dual_channel is inverted. Currently, if dual_channel is true (MLX90614), the function returns 0 immediately without checking op_eeprom_config1. This forces all MLX90614 devices to be registered as single sensor (num_channels = 2), making the second object temperature channel inaccessible. Conversely, if dual_channel is false (MLX90615), the function skips the early return and performs an unnecessary SMBus read on EEPROM CONFIG1 even though MLX90615 does not support dual channel operation. Fix this by negating the condition so that single-channel chips return early with 0, while dual-channel capable chips (MLX90614) proceed to read the EEPROM configuration register to detect whether 1 or 2 object channels are present. Fixes: 3d5ead238bc8 ("iio: mlx90614: Factor our register IO and constants into model specific descriptor") Signed-off-by: Salah Triki Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/temperature/mlx90614.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/iio/temperature/mlx90614.c b/drivers/iio/temperature/mlx90614.c index 27d6ab5f5d7a46..4f79da1f905ed4 100644 --- a/drivers/iio/temperature/mlx90614.c +++ b/drivers/iio/temperature/mlx90614.c @@ -565,7 +565,7 @@ static int mlx90614_probe_num_ir_sensors(struct i2c_client *client) const struct mlx_chip_info *chip_info = data->chip_info; s32 ret; - if (chip_info->dual_channel) + if (!chip_info->dual_channel) return 0; ret = i2c_smbus_read_word_data(client, chip_info->op_eeprom_config1); From 6ec0623a7c77bc2c383e9971d7b0c9df3ec988fb Mon Sep 17 00:00:00 2001 From: Billy Tsai Date: Mon, 5 Oct 2026 18:22:53 +0800 Subject: [PATCH 0099/2102] dt-bindings: iio: adc: Add syscon property for multi-SCU SoCs The ADC's reference-voltage trimming data lives in a System Control Unit (SCU) register. SoCs with a single SCU instance let the driver locate it without any additional information, but SoCs such as AST2700 that expose more than one SCU node need an explicit phandle to disambiguate which one holds the trimming data. Add an "aspeed,trim-syscon" phandle property, and require it for the AST2700 compatibles since they are the first multi-SCU SoCs supported by this driver. Reviewed-by: Krzysztof Kozlowski Signed-off-by: Billy Tsai Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- .../bindings/iio/adc/aspeed,ast2600-adc.yaml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml b/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml index 249101b55cf4e7..140d7034e2196e 100644 --- a/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml +++ b/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml @@ -67,6 +67,11 @@ properties: description: Inform the driver that last channel will be used to sensor battery. + aspeed,trim-syscon: + $ref: /schemas/types.yaml#/definitions/phandle + description: + Phandle to the SCU holding the ADC's reference-voltage trimming data. + required: - compatible - reg @@ -74,6 +79,18 @@ required: - resets - "#io-channel-cells" +allOf: + - if: + properties: + compatible: + contains: + enum: + - aspeed,ast2700-adc0 + - aspeed,ast2700-adc1 + then: + required: + - aspeed,trim-syscon + additionalProperties: false examples: From 4e7007317fdf83b5201f39afff5adfa0292fc707 Mon Sep 17 00:00:00 2001 From: Billy Tsai Date: Mon, 5 Oct 2026 18:22:54 +0800 Subject: [PATCH 0100/2102] iio: adc: aspeed: Use syscon phandle for trimming data when available aspeed_adc_set_trim_data() locates the SCU holding the ADC's reference-voltage trimming data with of_find_node_by_name(NULL, "syscon"), a global search that matches the first device-tree node named "syscon" regardless of which SCU instance it actually is. On AST2700, which splits its SCU into "syscon0" (soc0) and "syscon1" (soc1), both nodes share the same node name "syscon" and only differ by label and unit address, so the lookup always resolves to syscon0 even though the ADC's trimming data lives in syscon1. Use the new "aspeed,trim-syscon" phandle property when present to look up the correct regmap directly, falling back to the old global by-name search when the property is absent so existing device trees keep working. Fixes: 9d8b88ffb773 ("iio: adc: aspeed: Add AST2700 ADC support") Signed-off-by: Billy Tsai Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/adc/aspeed_adc.c | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/drivers/iio/adc/aspeed_adc.c b/drivers/iio/adc/aspeed_adc.c index 452c30cf04f284..085fdaffb9cd0c 100644 --- a/drivers/iio/adc/aspeed_adc.c +++ b/drivers/iio/adc/aspeed_adc.c @@ -201,18 +201,29 @@ static const struct iio_chan_spec aspeed_adc_iio_bat_channels[] = { static int aspeed_adc_set_trim_data(struct iio_dev *indio_dev) { - struct device_node *syscon; + struct device_node *np, *syscon; struct regmap *scu; u32 scu_otp, trimming_val; struct aspeed_adc_data *data = iio_priv(indio_dev); + const char *propname = "aspeed,trim-syscon"; - syscon = of_find_node_by_name(NULL, "syscon"); - if (syscon == NULL) { - dev_warn(data->dev, "Couldn't find syscon node\n"); - return -EOPNOTSUPP; + np = dev_of_node(data->dev); + if (of_property_present(np, propname)) { + scu = syscon_regmap_lookup_by_phandle(np, propname); + } else { + /* + * No "aspeed,trim-syscon" phandle: either a single-SCU SoC, + * or a DTB predating the property. Fall back to the old + * global by-name lookup for backward compatibility. + */ + syscon = of_find_node_by_name(NULL, "syscon"); + if (!syscon) { + dev_warn(data->dev, "Couldn't find syscon node\n"); + return -EOPNOTSUPP; + } + scu = syscon_node_to_regmap(syscon); + of_node_put(syscon); } - scu = syscon_node_to_regmap(syscon); - of_node_put(syscon); if (IS_ERR(scu)) { dev_warn(data->dev, "Failed to get syscon regmap\n"); return -EOPNOTSUPP; From bd63c89aac5672f40cdc123a856493b628fc1abb Mon Sep 17 00:00:00 2001 From: Jan Remes Date: Thu, 22 Oct 2026 20:56:40 +0200 Subject: [PATCH 0101/2102] iio: light: tsl2591: don't divide by zero The TSL2591 has two raw light channels - CH0 and CH1. The algorithm for calculating illumination from the raw channels requires division by CH0 (which can be zero) and by "counts per lux" (CPL) value which is also zero for (gain = LOW, integration time <= 400 ms). Furthermore, the algorithm assumes CH0 > CH1, which can be violated in almost complete darkness. As a result, reading from 'in_illuminance_input' results in division-by-zero whenever CH0 is 0 (complete darkness) or whenever the parameters result in CPL being zero. This results in kernel oops on x86_64 and in reading the value as 0 on arm64. Fix that by: - reporting CH0 <= CH1 as zero (catches also CH0 = 0) - updating the lux algorithm to only do the division at the end Fixes: 2335f0d7c790 ("iio: light: Added AMS tsl2591 driver implementation") Cc: stable@vger.kernel.org Reported-by: Martin Triska Reviewed-by: Andy Shevchenko Signed-off-by: Jan Remes Signed-off-by: Jonathan Cameron --- drivers/iio/light/tsl2591.c | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/drivers/iio/light/tsl2591.c b/drivers/iio/light/tsl2591.c index ef3ed9635a1ef8..f56d31404c253f 100644 --- a/drivers/iio/light/tsl2591.c +++ b/drivers/iio/light/tsl2591.c @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -362,6 +363,10 @@ static int tsl2591_wait_adc_complete(struct tsl2591_chip *chip) * Scale values to get more representative value of lux i.e. * lux = ((C0DATA - C1DATA) * (1000 - ((C1DATA * 1000) / C0DATA))) / CPL * + * CPL is not computed on its own: at 1x gain it is below 1 for integration + * times under 500 ms, so the division by LUX DF is folded into the final + * division instead. + * * Channel 0 = IR + Visible * Channel 1 = IR only */ @@ -373,8 +378,10 @@ static int tsl2591_read_channel_data(struct iio_dev *indio_dev, struct tsl2591_als_settings *settings = &chip->als_settings; struct i2c_client *client = chip->client; u8 als_data[TSL2591_NUM_DATA_REGISTERS]; - int counts_per_lux, int_time_fval, gain_multi, lux; + int int_time_fval, gain_multi; u16 als_ch0, als_ch1; + u64 lux; + u32 rem; int ret; ret = tsl2591_wait_adc_complete(chip); @@ -410,23 +417,28 @@ static int tsl2591_read_channel_data(struct iio_dev *indio_dev, return gain_multi; } - int_time_fval = TSL2591_FVAL_TO_MSEC(settings->als_int_time); - /* Calculate counts per lux value */ - counts_per_lux = (int_time_fval * gain_multi) / TSL2591_LUX_COEFFICIENT; + /* No visible light, this also catches C0DATA == 0 */ + if (als_ch0 <= als_ch1) { + *val = 0; + *val2 = 0; + break; + } - dev_dbg(&client->dev, "Counts Per Lux: %d\n", counts_per_lux); + int_time_fval = TSL2591_FVAL_TO_MSEC(settings->als_int_time); /* Calculate lux value */ - lux = ((als_ch0 - als_ch1) * - (1000 - ((als_ch1 * 1000) / als_ch0))) / counts_per_lux; + lux = (u64)(als_ch0 - als_ch1) * + (1000 - ((als_ch1 * 1000) / als_ch0)) * + TSL2591_LUX_COEFFICIENT; + lux = div_u64(lux, int_time_fval * gain_multi); - dev_dbg(&client->dev, "Raw lux calculation: %d\n", lux); + dev_dbg(&client->dev, "Raw lux calculation: %llu\n", lux); /* Divide by 1000 to get real lux value before scaling */ - *val = lux / 1000; + *val = div_u64_rem(lux, 1000, &rem); /* Get the decimal part of lux reading */ - *val2 = (lux - (*val * 1000)) * 1000; + *val2 = rem * 1000; break; default: From 7b5f54280f8e6ef07664f6705dd005feefbe87d1 Mon Sep 17 00:00:00 2001 From: Arnav Kapoor Date: Sat, 24 Oct 2026 00:56:51 +0530 Subject: [PATCH 0102/2102] iio: proximity: sx9324: fix out-of-bounds read of scan period table The scan period of the SX9324 is selected by the 5 bit wide SX9324_REG_GNRL_CTRL0_SCANPERIOD field, so it has 32 possible values. sx9324_scan_period_table[] however only has 16 entries, it was copied over from the SX9310 driver where the field is only 4 bits wide. sx9324_wait_for_sample() indexes the table with the raw field value, so all the codes from 16 to 31 read past the end of the array. The default value of the register is SX9324_REG_GNRL_CTRL0_SCANPERIOD_100MS (0x16, i.e. 22), so the out-of-bounds read happens with the default configuration of the device. It is only avoided when the device has an interrupt line, as the wait is only done in the polling case. The value read is then used as the duration of an msleep() call, so the sensor is polled with a completely random delay. Fill the table with the scan periods of all 32 codes, which are the periods documented for the corresponding sx9324_samp_freq_table[] entries, and add a static assertion to keep both tables in sync. Fixes: 4c18a890dff8 ("iio:proximity:sx9324: Add SX9324 support") Cc: stable@vger.kernel.org Signed-off-by: Arnav Kapoor Reviewed-by: Andy Shevchenko Signed-off-by: Jonathan Cameron --- drivers/iio/proximity/sx9324.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/drivers/iio/proximity/sx9324.c b/drivers/iio/proximity/sx9324.c index 255a36976ac41f..1c8ba28c030acc 100644 --- a/drivers/iio/proximity/sx9324.c +++ b/drivers/iio/proximity/sx9324.c @@ -279,11 +279,20 @@ static const struct { { 0, 250000 }, /* 11111: 4 s */ }; +/* + * The scan period of the SX9324 is selected by the 5-bit wide + * SX9324_REG_GNRL_CTRL0_SCANPERIOD field. The values below are the scan + * periods in ms of the corresponding sx9324_samp_freq_table[] entries. + */ static const unsigned int sx9324_scan_period_table[] = { - 2, 15, 30, 45, 60, 90, 120, 200, - 400, 600, 800, 1000, 2000, 3000, 4000, 5000, + 1, 2, 4, 6, 8, 10, 14, 18, /* 0x00 - 0x07 */ + 22, 26, 30, 34, 38, 42, 46, 50, /* 0x08 - 0x0f */ + 56, 62, 68, 74, 80, 90, 100, 200, /* 0x10 - 0x17 */ + 300, 400, 600, 800, 1000, 2000, 3000, 4000, /* 0x18 - 0x1f */ }; +static_assert(ARRAY_SIZE(sx9324_scan_period_table) == ARRAY_SIZE(sx9324_samp_freq_table)); + static const struct regmap_range sx9324_writable_reg_ranges[] = { /* * To set COMPSTAT for compensation, even if datasheet says register is From 3785dffc7c68751a8429ae6dd75804c14a5a7c7a Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Maneyrol Date: Tue, 20 Oct 2026 17:26:00 +0200 Subject: [PATCH 0103/2102] iio: inv_sensors: prevent timestamps going back in time in transitions Ensure when computing first timestamp and when applying odr change, that the next timestamp will not be lower than the previous one. This way there is no risk to have a timestamp going back in time, meaning being lower than the previous one. It already can never happen without a transition because we are generating timestamps by adding the period to the last timestamp. Fixes: 0ecc363ccea7 ("iio: make invensense timestamp module generic") Cc: stable@vger.kernel.org Signed-off-by: Jean-Baptiste Maneyrol Signed-off-by: Jonathan Cameron --- .../common/inv_sensors/inv_sensors_timestamp.c | 16 ++++++++++++---- include/linux/iio/common/inv_sensors_timestamp.h | 3 ++- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c b/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c index 8c9e81a77e6887..9040da80f0c73a 100644 --- a/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c +++ b/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c @@ -133,10 +133,15 @@ void inv_sensors_timestamp_interrupt(struct inv_sensors_timestamp *ts, return; /* no previous data, compute theoretical value from interrupt */ - if (ts->timestamp == 0) { + if (!ts->init) { /* elapsed time: sensor period * sensor samples number */ interval = (s64)ts->period * (s64)sample_nb; - ts->timestamp = timestamp - interval; + delta = timestamp - interval; + /* prevent next timestamp to be lower than the last one */ + if ((delta + ts->period) > ts->timestamp) + ts->timestamp = delta; + ts->init = true; + } /* update delta timestamps and estimated period */ @@ -184,7 +189,7 @@ void inv_sensors_timestamp_apply_odr(struct inv_sensors_timestamp *ts, u32 fifo_period, size_t fifo_nb, unsigned int fifo_no) { - s64 interval; + s64 interval, timestamp; u32 fifo_mult; if (ts->new_mult == 0) @@ -207,7 +212,10 @@ void inv_sensors_timestamp_apply_odr(struct inv_sensors_timestamp *ts, fifo_period = fifo_mult * ts->chip_period.val; /* computes time interval between interrupt and this sample */ interval = (s64)(fifo_nb - fifo_no) * (s64)fifo_period; - ts->timestamp = ts->it.up - interval; + timestamp = ts->it.up - interval; + /* prevent next timestamp to be lower than current one */ + if ((timestamp + ts->period) > ts->timestamp) + ts->timestamp = timestamp; } } EXPORT_SYMBOL_NS_GPL(inv_sensors_timestamp_apply_odr, "IIO_INV_SENSORS_TIMESTAMP"); diff --git a/include/linux/iio/common/inv_sensors_timestamp.h b/include/linux/iio/common/inv_sensors_timestamp.h index 4f08204ede3b45..91690778ae88b8 100644 --- a/include/linux/iio/common/inv_sensors_timestamp.h +++ b/include/linux/iio/common/inv_sensors_timestamp.h @@ -66,6 +66,7 @@ struct inv_sensors_timestamp { u32 new_mult; u32 period; struct inv_sensors_timestamp_acc chip_period; + bool init; }; void inv_sensors_timestamp_init(struct inv_sensors_timestamp *ts, @@ -94,7 +95,7 @@ static inline void inv_sensors_timestamp_reset(struct inv_sensors_timestamp *ts) ts->it = interval_init; ts->delta = interval_init; ts->delta_counter = 0; - ts->timestamp = 0; + ts->init = false; } #endif From 0d695709ed380f1bc9303a91f57525d33766a07e Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Maneyrol Date: Tue, 20 Oct 2026 18:28:47 +0200 Subject: [PATCH 0104/2102] iio: inv_sensors: do not compute period estimation when updating odr When odr is updated, the delta between the interrupts will change and it will lead to a bad period estimation. Avoid this by preventing the period estimation in this case. Fixes: 82bd09ce4fd3 ("iio: inv_sensors: improve period measurement by using a longer delay") Cc: stable@vger.kernel.org Signed-off-by: Jean-Baptiste Maneyrol Signed-off-by: Jonathan Cameron --- drivers/iio/common/inv_sensors/inv_sensors_timestamp.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c b/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c index 9040da80f0c73a..b3a784d3e67d74 100644 --- a/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c +++ b/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c @@ -147,6 +147,12 @@ void inv_sensors_timestamp_interrupt(struct inv_sensors_timestamp *ts, /* update delta timestamps and estimated period */ it = &ts->delta; ts->delta_counter += sample_nb; + /* reset in case of odr change */ + if (ts->new_mult) { + it->lo = 0; + it->up = 0; + ts->delta_counter = 0; + } delta = timestamp - it->up; delta_threshold = INV_SENSORS_TIMESTAMP_MIN(INV_SENSORS_MIN_IT_DELTA, ts->chip.jitter); if (delta >= delta_threshold) { @@ -166,7 +172,7 @@ void inv_sensors_timestamp_interrupt(struct inv_sensors_timestamp *ts, it->lo = it->up; it->up = timestamp; delta = it->up - it->lo; - if (it->lo != 0) { + if (it->lo != 0 && !ts->new_mult) { /* compute period and check validity */ period = div_s64(delta, sample_nb); valid = inv_validate_period(ts, period); From 4a141623442888458d147f4e61fe47411c0e4e17 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Maneyrol Date: Mon, 19 Oct 2026 15:37:33 +0200 Subject: [PATCH 0105/2102] iio: imu: inv_icm42600: fix parsing of all FIFO frames for odr change For getting all odr change events, we need to parse all FIFO frames in each iio device. Fix this correctly by sending effectively all frames to all iio devices. Previously only batches of frames containing a matching sensor event were sent to the corresponding iio device. Fixes: f670d4d34773 ("iio: imu: inv_icm42600: fix odr change not caught in certain cases") Cc: stable@vger.kernel.org Signed-off-by: Jean-Baptiste Maneyrol Signed-off-by: Jonathan Cameron --- .../imu/inv_icm42600/inv_icm42600_buffer.c | 24 ++++++++----------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c b/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c index 2bf9fc29d7d296..5bff2a3a44bcf5 100644 --- a/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c +++ b/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c @@ -532,22 +532,20 @@ int inv_icm42600_buffer_fifo_parse(struct inv_icm42600_state *st) ts = &gyro_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.watermark.eff_gyro, st->timestamp.gyro); - ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); - if (ret) - return ret; } + ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); + if (ret) + return ret; + /* handle accelerometer timestamp and FIFO data parsing */ if (st->fifo.nb.accel > 0) { ts = &accel_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.watermark.eff_accel, st->timestamp.accel); - ret = inv_icm42600_accel_parse_fifo(st->indio_accel); - if (ret) - return ret; } - return 0; + return inv_icm42600_accel_parse_fifo(st->indio_accel); } int inv_icm42600_buffer_hwfifo_flush(struct inv_icm42600_state *st, @@ -572,20 +570,18 @@ int inv_icm42600_buffer_hwfifo_flush(struct inv_icm42600_state *st, if (st->fifo.nb.gyro > 0) { ts = &gyro_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.nb.gyro, gyro_ts); - ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); - if (ret) - return ret; } + ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); + if (ret) + return ret; + if (st->fifo.nb.accel > 0) { ts = &accel_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.nb.accel, accel_ts); - ret = inv_icm42600_accel_parse_fifo(st->indio_accel); - if (ret) - return ret; } - return 0; + return inv_icm42600_accel_parse_fifo(st->indio_accel); } int inv_icm42600_buffer_init(struct inv_icm42600_state *st) From 1e50a03490120f1978c323741013457bc5c4582c Mon Sep 17 00:00:00 2001 From: Arnav Kapoor Date: Sat, 24 Oct 2026 00:28:34 +0530 Subject: [PATCH 0106/2102] iio: adc: mcp3564: reject devices without match data When the chip can't be identified from its ID registers, the driver falls back to spi_get_device_match_data() and dereferences the result unconditionally. That returns NULL for a device bound through driver_override whose name isn't in the id table, causing an oops. Return -ENODATA in that case. Fixes: 33ec3e5fc1ea ("iio: adc: adding support for MCP3564 ADC") Reviewed-by: Andy Shevchenko Signed-off-by: Arnav Kapoor Signed-off-by: Jonathan Cameron --- drivers/iio/adc/mcp3564.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/iio/adc/mcp3564.c b/drivers/iio/adc/mcp3564.c index 259ac4ebdedf1d..91796a47e412e4 100644 --- a/drivers/iio/adc/mcp3564.c +++ b/drivers/iio/adc/mcp3564.c @@ -1204,6 +1204,9 @@ static int mcp3564_config(struct iio_dev *indio_dev, bool *use_internal_vref_att * try using fallback compatible in device tree to deal with some newer part number. */ adc->chip_info = spi_get_device_match_data(adc->spi); + if (!adc->chip_info) + return -ENODATA; + adc->have_vref = adc->chip_info->have_vref; } else { adc->chip_info = &mcp3564_chip_infos_tbl[ids]; From 0516c565878687e1b4952edf32b4a069ca13e9ad Mon Sep 17 00:00:00 2001 From: David Carlier Date: Sun, 25 Oct 2026 21:18:56 +0000 Subject: [PATCH 0107/2102] iio: dac: mcp47feb02: reject out-of-range raw values mcp47feb02_write_raw() writes the user supplied raw value to the DAC register without checking it against the chip resolution. The parts are 8, 10 or 12 bit, and the bits above the resolution are not implemented, so writing 300 to out_voltage0_raw on an 8-bit part sets the output to code 44 instead of failing, and -1 is written as 0xffff. The out-of-range value is also cached in dac_data, so it is written back on resume and stored to EEPROM by store_eeprom. Return -EINVAL for values outside [0, 2^resolution - 1]. Fixes: bf394cc80369 ("iio: dac: adding support for Microchip MCP47FEB02") Reviewed-by: Joshua Crofts Reviewed-by: Andy Shevchenko Signed-off-by: David Carlier Signed-off-by: Jonathan Cameron --- drivers/iio/dac/mcp47feb02-core.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/iio/dac/mcp47feb02-core.c b/drivers/iio/dac/mcp47feb02-core.c index 88bffbab08541f..b5a2ac4a2e6731 100644 --- a/drivers/iio/dac/mcp47feb02-core.c +++ b/drivers/iio/dac/mcp47feb02-core.c @@ -696,6 +696,9 @@ static int mcp47feb02_write_raw(struct iio_dev *indio_dev, struct iio_chan_spec switch (mask) { case IIO_CHAN_INFO_RAW: + if (val < 0 || val > GENMASK(data->chip_features->resolution - 1, 0)) + return -EINVAL; + ret = regmap_write(data->regmap, REG_ADDR(ch->address), val); if (ret) return ret; From d252425c1533bfacd5940faa3371af82196bff5b Mon Sep 17 00:00:00 2001 From: Arnav Kapoor Date: Mon, 26 Oct 2026 03:42:38 +0530 Subject: [PATCH 0108/2102] iio: proximity: sx9360: fix sampling frequency write and available range GNRL_CTRL1/2 hold the scan period in units of 8192 / FOSC, but sx9360_set_samp_freq() computes freq * 8192 / FOSC and mis-scales val2, which is in micro units. Any integer frequency then programs a period of 0, and fractional parts above ~0.26 Hz overflow the int, writing 0x10 to GNRL_CTRL1 outside the SCANPERIOD field. Compute FOSC / (freq * 8192), rounded to the closest value, and reject frequencies outside the 1..2047 period range. The available range doesn't match the limits in the comments next to it either: 4 MHz / 8192 is 488.28125 Hz, not 448.28125 Hz, 4 MHz / (8192 * 2047) is 0.238535 Hz, and (max - min) / 2047 is 0.238419 Hz. Use those values. Fixes: 1cdb4c47f7f5 ("iio:proximity:sx9360: Add sx9360 support") Signed-off-by: Arnav Kapoor Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/proximity/sx9360.c | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/drivers/iio/proximity/sx9360.c b/drivers/iio/proximity/sx9360.c index ed83d809ecf5ec..2a9b37df8f6228 100644 --- a/drivers/iio/proximity/sx9360.c +++ b/drivers/iio/proximity/sx9360.c @@ -14,10 +14,12 @@ #include #include #include +#include #include #include #include #include +#include #include @@ -43,6 +45,7 @@ #define SX9360_REG_GNRL_CTRL1_SCANPERIOD_MASK GENMASK(2, 0) #define SX9360_REG_GNRL_CTRL2 0x12 #define SX9360_REG_GNRL_CTRL2_PERIOD_102MS 0x32 +#define SX9360_REG_GNRL_SCANPERIOD_MAX GENMASK(10, 0) #define SX9360_REG_GNRL_REG_2_PERIOD_MS(_r) \ (((_r) * 8192) / (SX9360_FOSC_HZ / 1000)) #define SX9360_REG_GNRL_FREQ_2_REG(_f) (((_f) * 8192) / SX9360_FOSC_HZ) @@ -182,9 +185,9 @@ static const struct { int val; int val2; } sx9360_samp_freq_interval[] = { - { 0, 281250 }, /* 4MHz / (8192 * 2047) */ - { 0, 281250 }, - { 448, 281250 }, /* 4MHz / 8192 */ + { 0, 238535 }, /* 4MHz / (8192 * 2047) */ + { 0, 238419 }, + { 488, 281250 }, /* 4MHz / 8192 */ }; static const struct regmap_range sx9360_writable_reg_ranges[] = { @@ -383,11 +386,25 @@ static int sx9360_read_avail(struct iio_dev *indio_dev, static int sx9360_set_samp_freq(struct sx_common_data *data, int val, int val2) { - int reg; + unsigned int period_ticks; + u64 freq_uHz; __be16 buf; - reg = val * 8192 / SX9360_FOSC_HZ + val2 * 8192 / (SX9360_FOSC_MHZ); - buf = cpu_to_be16(reg); + if (val < 0 || val2 < 0) + return -EINVAL; + + freq_uHz = (u64)val * MICROHZ_PER_HZ + val2; + if (!freq_uHz) + return -EINVAL; + + /* The register holds the scan period in ticks of 8192 FOSC cycles. */ + period_ticks = DIV64_U64_ROUND_CLOSEST((u64)SX9360_FOSC_HZ * MICROHZ_PER_HZ, + freq_uHz * 8192); + if (!period_ticks || period_ticks > SX9360_REG_GNRL_SCANPERIOD_MAX) + return -EINVAL; + + buf = cpu_to_be16(period_ticks); + guard(mutex)(&data->mutex); return regmap_bulk_write(data->regmap, SX9360_REG_GNRL_CTRL1, &buf, From 098a4c37dc8815ea941866179220394e4d182c67 Mon Sep 17 00:00:00 2001 From: "Baek Kyu, Kim" Date: Sun, 25 Oct 2026 23:13:51 +0900 Subject: [PATCH 0109/2102] iio: dac: mcp4725: Update the cached DAC value only on success mcp4725_write_raw() updates dac_value even if mcp4725_set_value() rejects the requested value or reports an I2C transfer error. After writing 1000, a rejected write of 4096 returns -EINVAL without an I2C transfer, but out_voltage0_raw reports 4096. A later powerdown exit sends 00 00 instead of the 03 e8 frame for the last successful value. The EEPROM store path uses the same cache. Return the setter error before updating dac_value. This keeps the last successful software value for readback, powerdown exit and EEPROM writes. Fixes: cf35ad61aca2 ("iio: add mcp4725 I2C DAC driver") Signed-off-by: Baek Kyu, Kim Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/dac/mcp4725.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/iio/dac/mcp4725.c b/drivers/iio/dac/mcp4725.c index 3fa7acc69aeb6b..94d51af83042ff 100644 --- a/drivers/iio/dac/mcp4725.c +++ b/drivers/iio/dac/mcp4725.c @@ -356,6 +356,8 @@ static int mcp4725_write_raw(struct iio_dev *indio_dev, switch (mask) { case IIO_CHAN_INFO_RAW: ret = mcp4725_set_value(indio_dev, val); + if (ret) + return ret; data->dac_value = val; break; default: From b8ed9165906597b69a46fabf39ab41690721ebe8 Mon Sep 17 00:00:00 2001 From: Arnav Kapoor Date: Sat, 24 Oct 2026 23:26:53 +0530 Subject: [PATCH 0110/2102] iio: proximity: sx9500: ignore event config writes that don't change state sx9500_write_event_config() adjusts the channel and close/far user counts on every write, even when the event is already in the requested state. Writing 0 to a disabled event and then 1 leaves the counts at 0, so the channel and its interrupts stay off while the event reads as enabled. As channel_users[] is shared with raw reads, those can then wait forever for a conversion. Writing 1 twice and then 0 has the opposite effect. Return early when the state doesn't change, as sx_common_write_event_config() does. Fixes: 4193c0f1d863 ("iio: driver for Semtech SX9500 proximity solution") Signed-off-by: Arnav Kapoor Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/proximity/sx9500.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/iio/proximity/sx9500.c b/drivers/iio/proximity/sx9500.c index dadce9b442271f..26522b6c5a2d6e 100644 --- a/drivers/iio/proximity/sx9500.c +++ b/drivers/iio/proximity/sx9500.c @@ -548,6 +548,12 @@ static int sx9500_write_event_config(struct iio_dev *indio_dev, mutex_lock(&data->mutex); + /* The user counts must only change when the state does. */ + if (data->event_enabled[chan->channel] == state) { + ret = 0; + goto out_unlock; + } + if (state) { ret = sx9500_inc_chan_users(data, chan->channel); if (ret < 0) From f3fc8718af9189aad13a2ad7f5b256475bb14b21 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:19:19 +0100 Subject: [PATCH 0111/2102] iio: sx9310: use the data of the I2C table sx9310_check_whoami() takes the chip information from device_get_match_data(), which only looks at the OF and ACPI tables, and dereferences it. For a client which was bound through the i2c_device_id table, for instance one created with echo sx9310 0x28 > /sys/bus/i2c/devices/i2c-1/new_device it returns NULL, and the kernel oopses as soon as something at that address answers the read of the WHOAMI register. The I2C table has the same pointers. Use i2c_get_match_data(), which falls back to it. Fixes: 21fd3b1373f6 ("iio: proximity: sx9310: Convert enum->pointer for match data table") Cc: stable Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Signed-off-by: Jonathan Cameron --- drivers/iio/proximity/sx9310.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/iio/proximity/sx9310.c b/drivers/iio/proximity/sx9310.c index 79ba46d8a0aaeb..2585b9c6fb6938 100644 --- a/drivers/iio/proximity/sx9310.c +++ b/drivers/iio/proximity/sx9310.c @@ -891,7 +891,7 @@ static int sx9310_check_whoami(struct device *dev, if (ret) return ret; - ddata = device_get_match_data(dev); + ddata = i2c_get_match_data(data->client); if (ddata->whoami != whoami) return -ENODEV; From e6dfbd84b833ed595a5236b027357e917de28260 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:19:11 +0100 Subject: [PATCH 0112/2102] iio: addac: ad74413r: fix the values of set_multiple MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ad74413r_gpio_set_multiple() walks over the lines in the mask and looks up the new value of each with if (*bits & offset) offset is the number of the line, not a bit mask. Line 0 is always driven low, line 1 gets the value meant for line 0, line 2 the one meant for line 1, and line 3 is driven high if either of these two is. Test the bit which belongs to the line. Fixes: fea251b6a5db ("iio: addac: add AD74413R driver") Cc: stable Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Reviewed-by: Nuno Sá Signed-off-by: Jonathan Cameron --- drivers/iio/addac/ad74413r.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/iio/addac/ad74413r.c b/drivers/iio/addac/ad74413r.c index 2e5a58e48a89aa..20db890d958b4f 100644 --- a/drivers/iio/addac/ad74413r.c +++ b/drivers/iio/addac/ad74413r.c @@ -312,7 +312,7 @@ static int ad74413r_gpio_set_multiple(struct gpio_chip *chip, return ret; real_mask |= BIT(real_offset); - if (*bits & offset) + if (test_bit(offset, bits)) real_bits |= BIT(real_offset); } From 594157b4f3f64db5833dee679194c33a5968f92e Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:19:10 +0100 Subject: [PATCH 0113/2102] iio: adc: ad7923: add the AD7927 to the SPI ID table MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The binding describes the AD7927 as compatible = "adi,ad7927", "adi,ad7928"; The OF match takes the second string. The modalias of the SPI device is made from the first one, "ad7927", which is not in the spi_device_id table: spi_get_device_id() returns NULL and ad7923_probe() dereferences it for the chip information. The module is not loaded automatically either, as the uevent of an SPI device says "spi:ad7927". Add the name, with the data of the AD7928. Fixes: 1140f96cd4af ("dt-bindings: iio: adc: ad7923: adjust documentation") Cc: stable Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Reviewed-by: Nuno Sá Signed-off-by: Jonathan Cameron --- drivers/iio/adc/ad7923.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/iio/adc/ad7923.c b/drivers/iio/adc/ad7923.c index 44e014da97222b..69fafb4aa4ea06 100644 --- a/drivers/iio/adc/ad7923.c +++ b/drivers/iio/adc/ad7923.c @@ -366,6 +366,7 @@ static const struct spi_device_id ad7923_id[] = { { .name = "ad7924", .driver_data = AD7924 }, { .name = "ad7908", .driver_data = AD7908 }, { .name = "ad7918", .driver_data = AD7918 }, + { .name = "ad7927", .driver_data = AD7928 }, { .name = "ad7928", .driver_data = AD7928 }, { } }; From 905b5d93b795b0e2311a8c855c1cdd97c9cc2989 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:19:09 +0100 Subject: [PATCH 0114/2102] iio: adc: check the result of ad_sd_init() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ad_sd_init() asks for the optional "rdy" GPIO and returns the error if that fails, for instance -EPROBE_DEFER. The binding of the AD7780 describes such a GPIO. ad7780, ad7791, ad7793 and max11205 ignore the result. The function has then returned before it set the driver data of the IIO device, which devm_ad_sd_setup_buffer_and_trigger() dereferences a few lines further down in these probe functions, and sigma_delta->rdy_gpiod holds an ERR_PTR() which ad_sigma_delta_clear_pending_event() takes for a GPIO. Return the error, as the other users of the library do. Fixes: a87ef09b1fdf ("iio: adc: ad_sigma_delta: Add support for reading irq status using a GPIO") Cc: stable Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Reviewed-by: Nuno Sá Signed-off-by: Jonathan Cameron --- drivers/iio/adc/ad7780.c | 4 +++- drivers/iio/adc/ad7791.c | 4 +++- drivers/iio/adc/ad7793.c | 4 +++- drivers/iio/adc/max11205.c | 4 +++- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/drivers/iio/adc/ad7780.c b/drivers/iio/adc/ad7780.c index 1cfad70320feb5..c1428f30241c8f 100644 --- a/drivers/iio/adc/ad7780.c +++ b/drivers/iio/adc/ad7780.c @@ -311,7 +311,9 @@ static int ad7780_probe(struct spi_device *spi) st = iio_priv(indio_dev); st->gain = 1; - ad_sd_init(&st->sd, indio_dev, spi, &ad7780_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7780_sigma_delta_info); + if (ret) + return ret; st->chip_info = &ad7780_chip_info_tbl[spi_get_device_id(spi)->driver_data]; diff --git a/drivers/iio/adc/ad7791.c b/drivers/iio/adc/ad7791.c index c2688307bbba18..10aa40ca35e7b2 100644 --- a/drivers/iio/adc/ad7791.c +++ b/drivers/iio/adc/ad7791.c @@ -435,7 +435,9 @@ static int ad7791_probe(struct spi_device *spi) return ret; st->info = &ad7791_chip_infos[spi_get_device_id(spi)->driver_data]; - ad_sd_init(&st->sd, indio_dev, spi, &ad7791_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7791_sigma_delta_info); + if (ret) + return ret; indio_dev->name = spi_get_device_id(spi)->name; indio_dev->modes = INDIO_DIRECT_MODE; diff --git a/drivers/iio/adc/ad7793.c b/drivers/iio/adc/ad7793.c index b0f44c144f20e7..937c8b09ad4534 100644 --- a/drivers/iio/adc/ad7793.c +++ b/drivers/iio/adc/ad7793.c @@ -796,7 +796,9 @@ static int ad7793_probe(struct spi_device *spi) st = iio_priv(indio_dev); - ad_sd_init(&st->sd, indio_dev, spi, &ad7793_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7793_sigma_delta_info); + if (ret) + return ret; if (pdata->refsel != AD7793_REFSEL_INTERNAL) { ret = devm_regulator_get_enable_read_voltage(dev, "refin"); diff --git a/drivers/iio/adc/max11205.c b/drivers/iio/adc/max11205.c index 53ac2f4f383e92..e46e90400bdcb4 100644 --- a/drivers/iio/adc/max11205.c +++ b/drivers/iio/adc/max11205.c @@ -114,7 +114,9 @@ static int max11205_probe(struct spi_device *spi) st = iio_priv(indio_dev); - ad_sd_init(&st->sd, indio_dev, spi, &max11205_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &max11205_sigma_delta_info); + if (ret) + return ret; st->chip_info = spi_get_device_match_data(spi); if (!st->chip_info) From 4c56180167ea4d419a0578545bf62110494b563d Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:19:08 +0100 Subject: [PATCH 0115/2102] iio: accel: adxl380: don't stay in standby on -EINVAL MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit adxl380_set_act_inact_threshold() puts the sensor into standby, writes the threshold and switches the measurement on again. A threshold above 8191 is refused in between, and the sensor stays in standby: no samples and no events until the next write that succeeds. adxl380_set_range() has the same problem and a worse one. It rescales both thresholds for the new range. If one no longer fits it returns -EINVAL with the sensor in standby, the new range in the chip, the old one in st->range and rescaled thresholds in the driver's state: from the next successful write on the samples are reported with the wrong scale. Switch the measurement on again if the threshold is refused. In adxl380_set_range() see whether the thresholds fit before anything is changed. Fixes: df36de13677a ("iio: accel: add ADXL380 driver") Cc: stable Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Reviewed-by: Nuno Sá Signed-off-by: Jonathan Cameron --- drivers/iio/accel/adxl380.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/drivers/iio/accel/adxl380.c b/drivers/iio/accel/adxl380.c index 8518ee23e11490..03b140303520d7 100644 --- a/drivers/iio/accel/adxl380.c +++ b/drivers/iio/accel/adxl380.c @@ -334,8 +334,11 @@ static int adxl380_set_act_inact_threshold(struct iio_dev *indio_dev, return ret; ret = adxl380_write_act_inact_threshold(st, act, th); - if (ret) + if (ret) { + /* Leave standby also if the value was refused */ + adxl380_set_measure_en(st, true); return ret; + } return adxl380_set_measure_en(st, true); } @@ -698,6 +701,12 @@ static int adxl380_set_range(struct adxl380_state *st, u8 range) guard(mutex)(&st->lock); + /* The thresholds are rescaled: see that they fit before any change */ + if (mult_frac(max(st->act_threshold, st->inact_threshold), + adxl380_range_scale_factor_tbl[st->range], + adxl380_range_scale_factor_tbl[range]) > ADXL380_THRESH_MAX) + return -EINVAL; + ret = adxl380_set_measure_en(st, false); if (ret) return ret; From c83cc7d7ed204245ec50d974aefcfcc66e910cd5 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 27 Oct 2026 18:58:39 +0800 Subject: [PATCH 0116/2102] iio: light: hid-sensor-als: Don't read past the end of short fields Reports are not guaranteed to be 4 bytes. On color ALS sensors there are fields that can be shorter than 4 bytes: 16-bit illuminance, color temperature and chromaticity x/y. I don't have such a sensor right now, but I have emulated one in firmware. With this patch, no garbage data is read from the next report: before: 05dc02bc 05dc02bc 190005dc 0ce41900 00000ce4 after: 000002bc 000002bc 000005dc 00001900 00000ce4 Same fix as commit ad02ca57e44e ("iio: hid-sensor-prox: Add support for 16-bit report size"). Fixes: ed5514c925a0 ("iio: hid-sensors: Added ALS") Signed-off-by: Daniel Schaefer Signed-off-by: Jonathan Cameron --- drivers/iio/light/hid-sensor-als.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/drivers/iio/light/hid-sensor-als.c b/drivers/iio/light/hid-sensor-als.c index 929343e42d8345..00dfc2037c1975 100644 --- a/drivers/iio/light/hid-sensor-als.c +++ b/drivers/iio/light/hid-sensor-als.c @@ -267,7 +267,21 @@ static int als_capture_sample(struct hid_sensor_hub_device *hsdev, struct iio_dev *indio_dev = platform_get_drvdata(priv); struct als_state *als_state = iio_priv(indio_dev); int ret = -EINVAL; - u32 sample_data = *(u32 *)raw_data; + u32 sample_data; + + switch (raw_len) { + case 1: + sample_data = *(u8 *)raw_data; + break; + case 2: + sample_data = *(u16 *)raw_data; + break; + default: + if (raw_len < sizeof(u32)) + return -EINVAL; + sample_data = *(u32 *)raw_data; + break; + } switch (usage_id) { case HID_USAGE_SENSOR_LIGHT_ILLUM: From 25d15b4192b9ae45be61670b5424721f5a0e0cf2 Mon Sep 17 00:00:00 2001 From: Loic Poulain Date: Sun, 1 Nov 2026 11:09:02 +0800 Subject: [PATCH 0117/2102] iio: adc: qcom-spmi-adc5-gen3: Reuse IIO device ID for ADC_TM aux device adc5_gen3_add_aux_tm_device() never sets the auxiliary device id, so every ADC5 Gen3 instance with at least one qcom,adc-tm channel tries to register the same device name. With ADC_TM channels on more than one PMIC, the second instance to probe fails: sysfs: cannot create duplicate filename '/bus/auxiliary/devices/qcom_spmi_adc5_gen3.adc5_tm_gen3.0' ... auxiliary qcom_spmi_adc5_gen3.adc5_tm_gen3.0: adding auxiliary device failed!: -17 qcom-spmi-adc5-gen3 c400000.spmi:pmic@8:adc@7200: error -EEXIST: Failed to add auxiliary TM device The ADC probe then fails as a whole, so that PMIC loses both its IIO channels and its thermal zones. This shows up on Nord, which has thermistor channels on two PMAU0102 PMICs. Each ADC instance already has a unique IIO device ID. Use it as the auxiliary device id instead of allocating one from a separate driver-wide IDA, which removes the custom ID allocation and release handling. The ADC_TM driver matches on the device name only, so the instance number does not affect binding. Fixes: baff45179e90 ("iio: adc: Add support for QCOM PMIC5 Gen3 ADC") Signed-off-by: Loic Poulain Signed-off-by: Shawn Guo Signed-off-by: Jonathan Cameron --- drivers/iio/adc/qcom-spmi-adc5-gen3.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/iio/adc/qcom-spmi-adc5-gen3.c b/drivers/iio/adc/qcom-spmi-adc5-gen3.c index c68c6c5f6aca09..a23eb5c9096d76 100644 --- a/drivers/iio/adc/qcom-spmi-adc5-gen3.c +++ b/drivers/iio/adc/qcom-spmi-adc5-gen3.c @@ -610,7 +610,7 @@ static void adc5_gen3_delete_aux(void *data) static void adc5_gen3_aux_device_release(struct device *dev) {} -static int adc5_gen3_add_aux_tm_device(struct adc5_chip *adc) +static int adc5_gen3_add_aux_tm_device(struct adc5_chip *adc, int id) { struct tm5_aux_dev_wrapper *aux_device; int i, ret, i_tm = 0; @@ -620,6 +620,7 @@ static int adc5_gen3_add_aux_tm_device(struct adc5_chip *adc) return -ENOMEM; aux_device->aux_dev.name = "adc5_tm_gen3"; + aux_device->aux_dev.id = id; aux_device->aux_dev.dev.parent = adc->dev; aux_device->aux_dev.dev.release = adc5_gen3_aux_device_release; @@ -799,7 +800,7 @@ static int adc5_gen3_probe(struct platform_device *pdev) return ret; if (adc->n_tm_channels > 0) { - ret = adc5_gen3_add_aux_tm_device(adc); + ret = adc5_gen3_add_aux_tm_device(adc, iio_device_id(indio_dev)); if (ret) dev_err_probe(dev, ret, "Failed to add auxiliary TM device\n"); From fd7334314f63a3a2a4927f209b2ca0e33d111840 Mon Sep 17 00:00:00 2001 From: Guangshuo Li Date: Sat, 31 Oct 2026 21:05:38 +0800 Subject: [PATCH 0118/2102] iio: accel: kxsd9: Fix potential use-after-free on removal Unregistering an IIO device with an active triggered buffer detaches its poll function. Freeing the poll function first can therefore make iio_device_unregister() access freed memory. Unregister the device before cleaning up the triggered buffer. This issue was found by our static analysis tool under development. Fixes: 0427a106a98a ("iio: accel: kxsd9: Add triggered buffer handling") Signed-off-by: Guangshuo Li Reviewed-by: Joshua Crofts Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/accel/kxsd9.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/iio/accel/kxsd9.c b/drivers/iio/accel/kxsd9.c index 7ac885d94d7f45..27adcdd312014e 100644 --- a/drivers/iio/accel/kxsd9.c +++ b/drivers/iio/accel/kxsd9.c @@ -478,8 +478,8 @@ void kxsd9_common_remove(struct device *dev) struct iio_dev *indio_dev = dev_get_drvdata(dev); struct kxsd9_state *st = iio_priv(indio_dev); - iio_triggered_buffer_cleanup(indio_dev); iio_device_unregister(indio_dev); + iio_triggered_buffer_cleanup(indio_dev); pm_runtime_get_sync(dev); pm_runtime_put_noidle(dev); pm_runtime_disable(dev); From c293f0db308fe76a0a9b0f6674cd2dea149b03aa Mon Sep 17 00:00:00 2001 From: Andrea Amer Date: Mon, 26 Oct 2026 11:57:38 +0100 Subject: [PATCH 0119/2102] iio: afe: rescale: expose offset if rescaler or source has one A rescale channel advertises IIO_CHAN_INFO_OFFSET only when its own offset is non-zero. A child rescale therefore hides a source offset, and consumers apply raw * scale and drop it, even though rescale_read_raw() folds the source offset in. Expose the attribute when either the rescaler or the source channel provides an offset. Fixes: a29c3283653b ("iio: afe: rescale: add offset support") Signed-off-by: Andrea Amer Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/afe/iio-rescale.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/iio/afe/iio-rescale.c b/drivers/iio/afe/iio-rescale.c index 3a6a09ffa5267d..c01292a15a29d0 100644 --- a/drivers/iio/afe/iio-rescale.c +++ b/drivers/iio/afe/iio-rescale.c @@ -303,7 +303,8 @@ static int rescale_configure_channel(struct device *dev, chan->info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE); - if (rescale->offset) + if (rescale->offset || + iio_channel_has_info(schan, IIO_CHAN_INFO_OFFSET)) chan->info_mask_separate |= BIT(IIO_CHAN_INFO_OFFSET); /* From 6c067677192f054bbfa815caf04f536bb8dcdee2 Mon Sep 17 00:00:00 2001 From: Oleg Keri Date: Fri, 9 Oct 2026 10:26:39 +0200 Subject: [PATCH 0120/2102] soundwire: qcom: disable the interrupt before gating the clock swrm_runtime_suspend() gates hclk straight after the ClockStopNow broadcast, while the interrupt thread that completed it is still clearing the status and CLK_STOP_FINISHED is about to fire. Both touch registers with the clock going away; on x1e80100 and glymur hclk is the SoundWire clock itself. The next clock-stop exit then fails at random (bus clash, parity errors, AUTO_ENUM_FAILED) and one side of the speakers stays detached until reboot. Disable the interrupt before gating the clock and enable it again once the clock is back. Fixes: 74e79da9fd46 ("soundwire: qcom: add runtime pm support") Signed-off-by: Oleg Keri Reviewed-by: Dmitry Baryshkov Link: https://patch.msgid.link/20261009082639.22662-1-okerixx@gmail.com Signed-off-by: Vinod Koul --- drivers/soundwire/qcom.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/soundwire/qcom.c b/drivers/soundwire/qcom.c index 6e0c5fb10efad4..147e55b7a600b9 100644 --- a/drivers/soundwire/qcom.c +++ b/drivers/soundwire/qcom.c @@ -1801,6 +1801,7 @@ static int __maybe_unused swrm_runtime_resume(struct device *dev) } clk_prepare_enable(ctrl->hclk); + enable_irq(ctrl->irq); if (ctrl->clock_stop_not_supported) { reinit_completion(&ctrl->enumeration); @@ -1887,6 +1888,7 @@ static int __maybe_unused swrm_runtime_suspend(struct device *dev) } } + disable_irq(ctrl->irq); clk_disable_unprepare(ctrl->hclk); usleep_range(300, 305); From c5f343c189aa30285e7c73dbf2f185720467794b Mon Sep 17 00:00:00 2001 From: Myeonghun Pak Date: Wed, 14 Oct 2026 20:28:52 -0400 Subject: [PATCH 0121/2102] memory: tegra: Shut down Tegra210 EMC timers before teardown The training and refresh timers can outlive the EMC state on removal or probe failure after clock attachment, causing use-after-free. Shut down both timers before detaching the clock provider and releasing the timing tables to wait for callbacks and prevent rearming. Initialize them before clock attachment, since set_rate() can start training. Fixes: 10de21148f7d ("memory: tegra: Add EMC scaling support code for Tegra210") Co-developed-by: Ijae Kim Signed-off-by: Ijae Kim Signed-off-by: Myeonghun Pak Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-47538f77-fb50-4a06-b49b-92dbee8b538b Link: https://patch.msgid.link/20261015002852.2159841-1-mhun512@gmail.com Signed-off-by: Krzysztof Kozlowski --- drivers/memory/tegra/tegra210-emc-core.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/drivers/memory/tegra/tegra210-emc-core.c b/drivers/memory/tegra/tegra210-emc-core.c index e8d4cd8fdec26b..044ec6f1bc321c 100644 --- a/drivers/memory/tegra/tegra210-emc-core.c +++ b/drivers/memory/tegra/tegra210-emc-core.c @@ -1946,12 +1946,6 @@ static int tegra210_emc_probe(struct platform_device *pdev) config->same_freq = true; } - err = tegra210_clk_emc_attach(emc->clk, &emc->provider); - if (err < 0) { - dev_err(&pdev->dev, "failed to attach to EMC clock: %d\n", err); - goto release; - } - emc->clkchange_delay = 100; emc->training_interval = 100; dev_set_drvdata(emc->dev, emc); @@ -1963,6 +1957,12 @@ static int tegra210_emc_probe(struct platform_device *pdev) timer_setup(&emc->training, tegra210_emc_train, 0); + err = tegra210_clk_emc_attach(emc->clk, &emc->provider); + if (err < 0) { + dev_err(&pdev->dev, "failed to attach to EMC clock: %d\n", err); + goto release; + } + tegra210_emc_debugfs_init(emc); cd = devm_thermal_of_child_cooling_device_register(emc->dev, np, "emc", emc, @@ -1978,6 +1978,8 @@ static int tegra210_emc_probe(struct platform_device *pdev) detach: debugfs_remove_recursive(emc->debugfs.root); + timer_shutdown_sync(&emc->training); + timer_shutdown_sync(&emc->refresh_timer); tegra210_clk_emc_detach(emc->clk); release: of_reserved_mem_device_release(emc->dev); @@ -1990,6 +1992,8 @@ static void tegra210_emc_remove(struct platform_device *pdev) struct tegra210_emc *emc = platform_get_drvdata(pdev); debugfs_remove_recursive(emc->debugfs.root); + timer_shutdown_sync(&emc->training); + timer_shutdown_sync(&emc->refresh_timer); tegra210_clk_emc_detach(emc->clk); of_reserved_mem_device_release(emc->dev); } From a94cfeb60dc1a9f1e73718d3ba2f9e70834a6b90 Mon Sep 17 00:00:00 2001 From: Runyu Xiao Date: Fri, 9 Oct 2026 14:01:55 +0800 Subject: [PATCH 0122/2102] memory: fsl_ifc: guard optional NAND IRQ cleanup The IFC device tree binding permits a controller to provide only the common interrupt. In that configuration, irq_of_parse_and_map() returns 0 for the optional NAND IRQ and probe skips request_irq(), but both the probe unwind and remove paths still call free_irq() unconditionally. Guard the NAND IRQ cleanup with a check for a non-zero IRQ. Fixes: 721c0705906e ("powerpc/mpc85xx: Update interrupt handling for IFC controller") Fixes: 3e25f800afb8 ("memory: fsl_ifc: populate child devices without relying on simple-bus") Cc: stable@vger.kernel.org Signed-off-by: Runyu Xiao Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-1bbccb12-0e0d-40df-bddb-e6251bc0409b Link: https://patch.msgid.link/20261009060155.1162262-1-runyu.xiao@seu.edu.cn Co-developed-by: Krzysztof Kozlowski Signed-off-by: Krzysztof Kozlowski --- drivers/memory/fsl_ifc.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/memory/fsl_ifc.c b/drivers/memory/fsl_ifc.c index e89e0c6cc4bccc..6dcc317d95d42d 100644 --- a/drivers/memory/fsl_ifc.c +++ b/drivers/memory/fsl_ifc.c @@ -89,7 +89,8 @@ static void fsl_ifc_ctrl_remove(struct platform_device *dev) struct fsl_ifc_ctrl *ctrl = dev_get_drvdata(&dev->dev); of_platform_depopulate(&dev->dev); - free_irq(ctrl->nand_irq, ctrl); + if (ctrl->nand_irq) + free_irq(ctrl->nand_irq, ctrl); free_irq(ctrl->irq, ctrl); irq_dispose_mapping(ctrl->nand_irq); @@ -292,7 +293,8 @@ static int fsl_ifc_ctrl_probe(struct platform_device *dev) return 0; err_free_nandirq: - free_irq(fsl_ifc_ctrl_dev->nand_irq, fsl_ifc_ctrl_dev); + if (fsl_ifc_ctrl_dev->nand_irq) + free_irq(fsl_ifc_ctrl_dev->nand_irq, fsl_ifc_ctrl_dev); err_free_irq: free_irq(fsl_ifc_ctrl_dev->irq, fsl_ifc_ctrl_dev); err_unmap_nandirq: From 21250426a8469d3bc43c2f0c69ed5497ee9ff7d4 Mon Sep 17 00:00:00 2001 From: Selby Mashiki Date: Sun, 25 Oct 2026 21:03:22 +0200 Subject: [PATCH 0123/2102] memory: tegra: fix device_node leak in tegra186_mc_probe_device() tegra186_mc_probe_device() iterates over the "interconnects" phandles using of_parse_phandle_with_args(), which increments the reference count of args.np on each successful call, but never drops the reference with of_node_put(args.np). Call of_node_put(args.np) at the end of each loop iteration. Fixes: fe3b082a6eb8 ("memory: tegra: Add SID override programming for MC clients") Signed-off-by: Selby Mashiki Link: https://patch.msgid.link/20261025190322.449324-1-mashikiselby@gmail.com Signed-off-by: Krzysztof Kozlowski --- drivers/memory/tegra/tegra186.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/memory/tegra/tegra186.c b/drivers/memory/tegra/tegra186.c index 442edb2b033e24..0df5b56586e896 100644 --- a/drivers/memory/tegra/tegra186.c +++ b/drivers/memory/tegra/tegra186.c @@ -146,6 +146,7 @@ static int tegra186_mc_probe_device(struct tegra_mc *mc, struct device *dev) } } + of_node_put(args.np); index++; } #endif From c3cc990de568e949bf6a3cc93c8950bc1bd58dc1 Mon Sep 17 00:00:00 2001 From: Krzysztof Kozlowski Date: Fri, 30 Oct 2026 16:24:06 +0100 Subject: [PATCH 0124/2102] memory: atmel-ebi: Disable SMC clock on probe failure Unprepare and drop the SMC clock reference, if probe fails to avoid resource leakage e.g. during probe deferral. There is no remove() callback, presumably on purpose so only error paths are handled. Cc: stable@vger.kernel.org Fixes: 87108dc78eb8 ("memory: atmel-ebi: Enable the SMC clock if specified") Reported-by: Wentao Liang Closes: https://lore.kernel.org/all/20260917101623.2146392-1-vulab@iscas.ac.cn/ Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-8e236c81-01b2-4274-a213-11c3f31acfc2 Signed-off-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261030152405.281376-2-krzysztof.kozlowski@oss.qualcomm.com Signed-off-by: Krzysztof Kozlowski --- drivers/memory/atmel-ebi.c | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/drivers/memory/atmel-ebi.c b/drivers/memory/atmel-ebi.c index 1e8e8aba2542da..7dc2f7add1b1d3 100644 --- a/drivers/memory/atmel-ebi.c +++ b/drivers/memory/atmel-ebi.c @@ -562,7 +562,7 @@ static int atmel_ebi_probe(struct platform_device *pdev) } ret = clk_prepare_enable(ebi->smc.clk); if (ret) - return ret; + goto err_put_clk; /* * The sama5d3 does not provide an EBICSA register and thus does need @@ -572,14 +572,16 @@ static int atmel_ebi_probe(struct platform_device *pdev) ebi->regmap = syscon_regmap_lookup_by_phandle(np, ebi->caps->regmap_name); - if (IS_ERR(ebi->regmap)) - return PTR_ERR(ebi->regmap); + if (IS_ERR(ebi->regmap)) { + ret = PTR_ERR(ebi->regmap); + goto err_disable_clk; + } } ret = of_property_read_u32(np, "#address-cells", &val); if (ret) { dev_err(dev, "missing #address-cells property\n"); - return ret; + goto err_disable_clk; } reg_cells = val; @@ -587,7 +589,7 @@ static int atmel_ebi_probe(struct platform_device *pdev) ret = of_property_read_u32(np, "#size-cells", &val); if (ret) { dev_err(dev, "missing #address-cells property\n"); - return ret; + goto err_disable_clk; } reg_cells += val; @@ -603,11 +605,22 @@ static int atmel_ebi_probe(struct platform_device *pdev) ret = atmel_ebi_dev_disable(ebi, child); if (ret) - return ret; + goto err_disable_clk; } } - return of_platform_populate(np, NULL, NULL, dev); + ret = of_platform_populate(np, NULL, NULL, dev); + if (ret) + goto err_disable_clk; + + return 0; + +err_disable_clk: + clk_disable_unprepare(ebi->smc.clk); +err_put_clk: + clk_put(ebi->smc.clk); + + return ret; } static __maybe_unused int atmel_ebi_resume(struct device *dev) From 8ca80811c3ba01691b424f4fef4db8960955df4f Mon Sep 17 00:00:00 2001 From: Geert Uytterhoeven Date: Tue, 13 Oct 2026 10:38:39 +0200 Subject: [PATCH 0125/2102] perf/renesas: Remove remaining RISCV_ALTERNATIVE references As riscv always selects RISCV_ALTERNATIVE, the option was removed. However, a few references were left, making it impossible to enable RZ/Five support (ARCH_R9A07G043). Fix this by removing all remaining references. Fixes: b924210f542e13c7 ("riscv: remove RISCV_ALTERNATIVE Kconfig option") Signed-off-by: Geert Uytterhoeven Reviewed-by: Jisheng Zhang Reviewed-by: Lad Prabhakar Link: https://patch.msgid.link/fe117dd44728fe7c96f3e4b3ec88c6ca83c5da9b.1791880574.git.geert+renesas@glider.be --- drivers/perf/Kconfig | 2 +- drivers/soc/renesas/Kconfig | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/perf/Kconfig b/drivers/perf/Kconfig index 245e7bb763b994..8cef4bdef76aec 100644 --- a/drivers/perf/Kconfig +++ b/drivers/perf/Kconfig @@ -117,7 +117,7 @@ config STARFIVE_STARLINK_PMU config ANDES_CUSTOM_PMU bool "Andes custom PMU support" - depends on ARCH_RENESAS && RISCV_ALTERNATIVE && RISCV_PMU_SBI + depends on ARCH_RENESAS && RISCV_PMU_SBI default y help The Andes cores implement the PMU overflow extension very diff --git a/drivers/soc/renesas/Kconfig b/drivers/soc/renesas/Kconfig index a63df28df3b5e7..0b6876ef6dca22 100644 --- a/drivers/soc/renesas/Kconfig +++ b/drivers/soc/renesas/Kconfig @@ -461,7 +461,6 @@ config ARCH_R9A07G043 bool "RISC-V Platform support for R9A07G043F (RZ/Five)" depends on NONPORTABLE depends on !DMA_DIRECT_REMAP - depends on RISCV_ALTERNATIVE depends on !RISCV_ISA_ZICBOM depends on RISCV_SBI select ARCH_RZG2L From 56e8ad28ebd79702b40efbef17b8895c68b84bd9 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Wed, 28 Oct 2026 14:13:19 +0100 Subject: [PATCH 0126/2102] efi/libstub: zboot: Round up image size to section alignment Oliver reports that some arm64 EFI boot images have a SizeOfImage field in the PE header that is set to a value that is not a round multiple of the image's section alignment, which violates the PE/COFF spec. This turns out to be a problem in the zboot linker script, and so it affects compressed EFI zboot images for all architectures, not only arm64. Uncompressed arm64 images built with an EFI stub are fine, as those are rounded up to 64k already. So fix this by bumping the zboot _end marker to the next 4k boundary . Reported-by: Oliver Smith-Denny Signed-off-by: Ard Biesheuvel --- drivers/firmware/efi/libstub/zboot.lds | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/firmware/efi/libstub/zboot.lds b/drivers/firmware/efi/libstub/zboot.lds index 367907eb7d8698..a785c012374970 100644 --- a/drivers/firmware/efi/libstub/zboot.lds +++ b/drivers/firmware/efi/libstub/zboot.lds @@ -45,7 +45,7 @@ SECTIONS .bss : { *(.bss* .init.bss*) - _end = ALIGN(512); + _end = ALIGN(4096); . = _end; } From aa0c00a516faac6683c7fb0a4f1032f471f910f7 Mon Sep 17 00:00:00 2001 From: NeilBrown Date: Wed, 21 Oct 2026 19:56:57 +1100 Subject: [PATCH 0127/2102] fuse: Use d_alloc_trylock() in fuse_direntplus_link() fuse uses the results of readdir to prime the dcache. Using d_alloc_parallel() can block if there is a concurrent lookup. Blocking in that case is pointless as the lookup will add info to the dcache and there is no value in the readdir waiting to see if it should add the info too. Also this call to d_alloc_parallel() is made while the parent directory is locked. A proposed change to locking will lock the parent later, after d_alloc_parallel(). This means it won't be safe to wait in d_alloc_parallel() while holding the directory lock. So change to use d_alloc_trylock(), which doesn't require full_name_hash and d_lookup to be called first. If d_alloc_trylock() fails with -EWOULDBLOCK or for any other reason, the consequence is only that fuse_force_forget() is called, which is required to keep the lookup count on the node consistent between client and server. It does not cause the readdir to fail. Signed-off-by: NeilBrown Signed-off-by: Miklos Szeredi --- fs/fuse/readdir.c | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/fs/fuse/readdir.c b/fs/fuse/readdir.c index 1f6cf565477f78..295cbd645653da 100644 --- a/fs/fuse/readdir.c +++ b/fs/fuse/readdir.c @@ -11,6 +11,7 @@ #include #include #include +#include static bool fuse_use_readdirplus(struct inode *dir, struct dir_context *ctx) { @@ -195,14 +196,11 @@ static int fuse_direntplus_link(struct file *file, fc = get_fuse_conn(dir); epoch = atomic_read(&fc->epoch); - name.hash = full_name_hash(parent, name.name, name.len); - dentry = d_lookup(parent, &name); - if (!dentry) { retry: - dentry = d_alloc_parallel(parent, &name); - if (IS_ERR(dentry)) - return PTR_ERR(dentry); - } + dentry = d_alloc_trylock(parent, &name); + if (IS_ERR(dentry)) + return PTR_ERR(dentry); + if (!d_in_lookup(dentry)) { struct fuse_inode *fi; inode = d_inode(dentry); From 41fb0e8f340f5b883b67786549a48ff60bcecca0 Mon Sep 17 00:00:00 2001 From: Artem Utkin Date: Mon, 26 Oct 2026 17:09:14 +0100 Subject: [PATCH 0128/2102] ARM: dts: samsung: exynos4412-p4note: allow powering off the wifi card sdhci_3 serving BCM4334 was missing cap-power-off-card. On my N8000 this resulted in the following messages after sleeping: [305.759883] PM: suspend entry (deep) [306.514698] brcmfmac: brcmf_ops_sdio_suspend: Failed to set pm_flags 1 [306.671504] brcmfmac: brcmf_sdio_htclk: HT Avail request error: -110 [307.127267] PM: suspend exit The regression was triggered by commit 8c3170628a9c ("wifi: brcmfmac: keep power during suspend if board requires it"). Midas already has a fix in commit 2ff147fdfa99 ("ARM: dts: samsung: exynos4412-midas: turn off SDIO WLAN chip during system suspend"). exynos4412-p4note.dtsi does not include exynos4412-midas.dtsi, so p4note did not automatically inherit the Midas fix. Fixes: 8c3170628a9c ("wifi: brcmfmac: keep power during suspend if board requires it") Cc: stable@vger.kernel.org Signed-off-by: Artem Utkin Link: https://patch.msgid.link/20261026-exynos4412-p4note-brcmfmac-v2-1-14b372972163@gmail.com Signed-off-by: Krzysztof Kozlowski --- arch/arm/boot/dts/samsung/exynos4412-p4note.dtsi | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm/boot/dts/samsung/exynos4412-p4note.dtsi b/arch/arm/boot/dts/samsung/exynos4412-p4note.dtsi index 8d52aa13b862f1..03b514a82b8a7b 100644 --- a/arch/arm/boot/dts/samsung/exynos4412-p4note.dtsi +++ b/arch/arm/boot/dts/samsung/exynos4412-p4note.dtsi @@ -1232,6 +1232,7 @@ #address-cells = <1>; #size-cells = <0>; non-removable; + cap-power-off-card; bus-width = <4>; mmc-pwrseq = <&wlan_pwrseq>; From f1ae606eb404bca2498b9ad69b923073655556e4 Mon Sep 17 00:00:00 2001 From: JaeGwon Go Date: Thu, 29 Oct 2026 17:18:34 +0900 Subject: [PATCH 0129/2102] thunderbolt: Send header-only XDomain properties changed response Commit 19813551701d ("thunderbolt: xdomain: Avoid potential stack OOB read") turned struct tb_xdp_properties_changed_response into a union of struct tb_xdp_error_response and struct tb_xdp_header, so that tb_xdp_handle_error() can safely read the error field of a received response. tb_xdp_properties_changed_response() still sends sizeof(res), so since that commit the response Linux sends is 36 bytes instead of 32: it carries the zeroed error field, and its XDomain length field says 6 dwords instead of 5. The other responses changed by that commit are not affected, because their non-error members are already larger than struct tb_xdp_error_response. macOS sends this response as the header only. macOS 27.2 (26B123) keeps re-sending PROPERTIES_CHANGED_REQUEST when it gets the longer response: after link-up it repeats the request every 1.5 s, ten times, and then resets the link, about 15 seconds after it came up. thunderbolt-net logs in and passes traffic before the reset. The same host stayed connected to the same Mac for about 23 hours while the Mac ran macOS 27.0.1, so the change in behavior came with macOS 27.2. Send only the header again, as before that commit. The union stays, so a received response still has room for the error field. Linux requesters accept the shorter response: tb_xdomain_match() requires only frame.size >= response_size / 4, and tb_xdp_handle_error() reads the error field only when the type is ERROR_RESPONSE. Tested on an ASMedia ASM4242 USB4 host running an Ubuntu 7.0.0-38 kernel, connected to a Mac17,6 running macOS 27.2. With this change macOS stops re-sending after the first answers, and tracing shows an 8-dword response with length 5, the same as the response macOS sends. The link has stayed up for over 1.5 hours, about 80 minutes of which carried a multi-gigabyte transfer every few minutes. Not tested: a Linux peer, the error response path, and macOS releases other than 27.2. The analysis, the fix and the tests were done with an AI coding assistant. Fixes: 19813551701d ("thunderbolt: xdomain: Avoid potential stack OOB read") Cc: stable@vger.kernel.org Signed-off-by: JaeGwon Go Signed-off-by: Mika Westerberg --- drivers/thunderbolt/xdomain.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/thunderbolt/xdomain.c b/drivers/thunderbolt/xdomain.c index b187a60663f513..563a8b65c8543a 100644 --- a/drivers/thunderbolt/xdomain.c +++ b/drivers/thunderbolt/xdomain.c @@ -509,8 +509,8 @@ tb_xdp_properties_changed_response(struct tb_ctl *ctl, u64 route, u8 sequence) memset(&res, 0, sizeof(res)); tb_xdp_fill_header(&res.hdr, route, sequence, - PROPERTIES_CHANGED_RESPONSE, sizeof(res)); - return __tb_xdomain_response(ctl, &res, sizeof(res), + PROPERTIES_CHANGED_RESPONSE, sizeof(res.hdr)); + return __tb_xdomain_response(ctl, &res.hdr, sizeof(res.hdr), TB_CFG_PKG_XDOMAIN_RESP); } From 78d082e4eb600de4a28e36db89cc528712b2e928 Mon Sep 17 00:00:00 2001 From: Marek Szyprowski Date: Mon, 2 Nov 2026 13:58:25 +0100 Subject: [PATCH 0130/2102] ARM: dts: samsung: exynos4210-universal_c210: fix BCM4330 Bluetooth GPIOs BT_REG_ON (BT_EN) line of the BCM4330 WLAN/BT combo chip is connected to the XMMC1CMD pad (GPK1[1]), while the XMDMADDR_4 pad (GPE1[4]) is connected to BT_RST (BT_nRST). The Bluetooth node however used GPE1[4] as shutdown-gpios and left the real BT_REG_ON line undriven, so it was kept low by the default SoC pull-down. This worked only by accident: the internal regulators of the BCM4330 are enabled when either WL_REG_ON or BT_REG_ON is high, so the Bluetooth core was powered via WL_REG_ON driven by the SDIO WLAN power sequence, while toggling GPE1[4] only released it from reset. Once 'cap-power-off-card' was added to the SDIO node, the MMC core started to power off the WLAN part (asserting WL_REG_ON low) whenever it was idle, what cut off the Bluetooth power as well and resulted in HCI command timeouts. Fix this by using GPK1[1] as shutdown-gpios and describing GPE1[4] as active-low reset-gpios. While touching this, move the GPE1[4] pin configuration to the pinctrl_0 node, as GPE1 bank belongs to that pin controller, what fixes the following error: samsung-pinctrl 11000000.pinctrl: does not have pin group gpe1-4 Fixes: 4e7787929854 ("ARM: dts: exynos: Enable Bluetooth support for Universal C210 board") Cc: stable@vger.kernel.org Signed-off-by: Marek Szyprowski Link: https://patch.msgid.link/20261102125826.3111447-1-m.szyprowski@samsung.com Signed-off-by: Krzysztof Kozlowski --- .../boot/dts/samsung/exynos4210-universal_c210.dts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/arch/arm/boot/dts/samsung/exynos4210-universal_c210.dts b/arch/arm/boot/dts/samsung/exynos4210-universal_c210.dts index 744039068e8f31..79c0c27d9377bb 100644 --- a/arch/arm/boot/dts/samsung/exynos4210-universal_c210.dts +++ b/arch/arm/boot/dts/samsung/exynos4210-universal_c210.dts @@ -537,7 +537,7 @@ &pinctrl_1 { bt_shutdown: bt-shutdown-pins { - samsung,pins = "gpe1-4"; + samsung,pins = "gpk1-1"; samsung,pin-function = ; samsung,pin-pud = ; }; @@ -572,6 +572,12 @@ samsung,pin-pud = ; samsung,pin-drv = ; }; + + bt_reset: bt-reset-pins { + samsung,pins = "gpe1-4"; + samsung,pin-function = ; + samsung,pin-pud = ; + }; }; &pwm { @@ -641,9 +647,10 @@ max-speed = <3000000>; - pinctrl-0 = <&bt_shutdown &bt_device_wakeup &bt_host_wakeup>; + pinctrl-0 = <&bt_shutdown &bt_reset &bt_device_wakeup &bt_host_wakeup>; pinctrl-names = "default"; - shutdown-gpios = <&gpe1 4 GPIO_ACTIVE_HIGH>; + shutdown-gpios = <&gpk1 1 GPIO_ACTIVE_HIGH>; + reset-gpios = <&gpe1 4 GPIO_ACTIVE_LOW>; device-wakeup-gpios = <&gpx3 1 GPIO_ACTIVE_HIGH>; host-wakeup-gpios = <&gpx2 6 GPIO_ACTIVE_HIGH>; }; From a6b33da67ef16a4bdf359d4e76870b1ba1a1360a Mon Sep 17 00:00:00 2001 From: Marek Szyprowski Date: Mon, 2 Nov 2026 13:58:10 +0100 Subject: [PATCH 0131/2102] ARM: dts: samsung: exynos4210-trats: fix BCM4330 Bluetooth GPIOs According to the board schematic, BT_REG_ON (BT_EN) line of the BCM4330 WLAN/BT combo chip is connected to GPL0[4], while GPL1[0] is connected to BT_RST (BT_nRST). The Bluetooth node however used GPL1[0] as shutdown-gpios and left the real BT_REG_ON line undriven, so it was kept low by the default SoC pull-down. This worked only by accident: the internal regulators of the BCM4330 are enabled when either WL_REG_ON or BT_REG_ON is high, so the Bluetooth core was powered via WL_REG_ON driven by the SDIO WLAN power sequence, while toggling GPL1[0] only released it from reset. Once 'cap-power-off-card' was added to the SDIO node, the MMC core started to power off the WLAN part (asserting WL_REG_ON low) whenever it was idle, what cut off the Bluetooth power as well and resulted in HCI command timeouts: Bluetooth: hci0: Opcode 0x0c03 failed: -110 Fix this by using GPL0[4] as shutdown-gpios and describing GPL1[0] as active-low reset-gpios, together with the respective pin configuration. Fixes: 132e900a47b8 ("ARM: dts: exynos: Enable Bluetooth support for Trats board") Cc: stable@vger.kernel.org Signed-off-by: Marek Szyprowski Link: https://patch.msgid.link/20261102125811.3111427-1-m.szyprowski@samsung.com Signed-off-by: Krzysztof Kozlowski --- arch/arm/boot/dts/samsung/exynos4210-trats.dts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/arch/arm/boot/dts/samsung/exynos4210-trats.dts b/arch/arm/boot/dts/samsung/exynos4210-trats.dts index 20fe148387fc23..ae4327770799a3 100644 --- a/arch/arm/boot/dts/samsung/exynos4210-trats.dts +++ b/arch/arm/boot/dts/samsung/exynos4210-trats.dts @@ -469,6 +469,12 @@ &pinctrl_1 { bt_shutdown: bt-shutdown-pins { + samsung,pins = "gpl0-4"; + samsung,pin-function = ; + samsung,pin-pud = ; + }; + + bt_reset: bt-reset-pins { samsung,pins = "gpl1-0"; samsung,pin-function = ; samsung,pin-pud = ; @@ -548,9 +554,10 @@ max-speed = <3000000>; - pinctrl-0 = <&bt_shutdown &bt_device_wakeup &bt_host_wakeup>; + pinctrl-0 = <&bt_shutdown &bt_reset &bt_device_wakeup &bt_host_wakeup>; pinctrl-names = "default"; - shutdown-gpios = <&gpl1 0 GPIO_ACTIVE_HIGH>; + shutdown-gpios = <&gpl0 4 GPIO_ACTIVE_HIGH>; + reset-gpios = <&gpl1 0 GPIO_ACTIVE_LOW>; device-wakeup-gpios = <&gpx3 1 GPIO_ACTIVE_HIGH>; host-wakeup-gpios = <&gpx2 6 GPIO_ACTIVE_HIGH>; }; From 996a59519af2ef3d8f47479685616bb2278c6cfa Mon Sep 17 00:00:00 2001 From: Sun Yuechi Date: Wed, 21 Oct 2026 22:58:14 -0700 Subject: [PATCH 0132/2102] PCI: Ignore Immediate Readiness on Samsung PM9D3a NVMe The Samsung PM9D3a [144d:a80e] (MZWL63T8HFLT-00B07, firmware LDD5702Q) advertises Immediate Readiness, so pcie_flr() doesn't wait after FLR, but the drive returns ~0 for up to 6 ms. The config restore runs about 1 ms after the FLR, so the BARs and Command register are lost and neither vfio-pci nor a rebound nvme driver can reach the device: pci 0008:01:00.0: reset via flr pci 0008:01:00.0: restore config 0x10: 0xffffffff -> 0x10010004 nvme 0008:01:00.0: error -ENODEV: probe failed Ignore Immediate Readiness on this device too, so pcie_flr() waits. Fixes: 10baa9b4df40 ("PCI: Drop unnecessary retries when restoring BARs") Signed-off-by: Sun Yuechi Signed-off-by: Bjorn Helgaas Link: https://patch.msgid.link/20261022055814.2566044-1-sunyuechi@iscas.ac.cn --- drivers/pci/quirks.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/pci/quirks.c b/drivers/pci/quirks.c index 7f1f47ea2ee415..4a02fc80755da8 100644 --- a/drivers/pci/quirks.c +++ b/drivers/pci/quirks.c @@ -5789,6 +5789,7 @@ static void quirk_no_imm_ready(struct pci_dev *dev) } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SAMSUNG, 0xa80c, quirk_no_imm_ready); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SAMSUNG, 0xa80d, quirk_no_imm_ready); +DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SAMSUNG, 0xa80e, quirk_no_imm_ready); static void quirk_no_ext_tags(struct pci_dev *pdev) { From c72dcaeaabd60e164e7324f80ccb037e879eefdd Mon Sep 17 00:00:00 2001 From: Maximilian Czirr Date: Wed, 7 Oct 2026 02:01:07 +0200 Subject: [PATCH 0133/2102] iio: hid-sensor: Fix scale for magnetic north heading hid_sensor_format_scale() applies the HID unit exponent only when the usage and unit match an entry in unit_conversion[]. Rotation-from-north support uses HID_USAGE_SENSOR_ORIENT_COMP_MAGN_NORTH, but that usage has no entry in the conversion table. As a result, the unit exponent is ignored and the heading can be exposed with a scale of 1 instead of the scale specified by the HID descriptor. Add a unitless conversion entry so the HID unit exponent is applied to the magnetic north heading. A sensor reporting an exponent of -5 then correctly exposes a scale of 0.00001 instead of 1. Fixes: abea9c62c32f ("iio: hid-sensor-magn-3d: Add support for rotation from north") Cc: stable@vger.kernel.org Signed-off-by: Maximilian Czirr Acked-by: Srinivas Pandruvada Signed-off-by: Jonathan Cameron --- drivers/iio/common/hid-sensors/hid-sensor-attributes.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/iio/common/hid-sensors/hid-sensor-attributes.c b/drivers/iio/common/hid-sensors/hid-sensor-attributes.c index 9e7c26e37880aa..26f8554d18a57d 100644 --- a/drivers/iio/common/hid-sensors/hid-sensor-attributes.c +++ b/drivers/iio/common/hid-sensors/hid-sensor-attributes.c @@ -38,6 +38,8 @@ static const struct { {HID_USAGE_SENSOR_COMPASS_3D, 0, 0, 1000000}, {HID_USAGE_SENSOR_COMPASS_3D, HID_USAGE_SENSOR_UNITS_GAUSS, 1, 0}, + {HID_USAGE_SENSOR_ORIENT_COMP_MAGN_NORTH, 0, 1, 0}, + {HID_USAGE_SENSOR_INCLINOMETER_3D, 0, 0, 17453293}, {HID_USAGE_SENSOR_INCLINOMETER_3D, HID_USAGE_SENSOR_UNITS_DEGREES, 0, 17453293}, From 289ea23b7bdeea303d3ac16a0f24a684cb48bdca Mon Sep 17 00:00:00 2001 From: Wang Haoran Date: Fri, 23 Oct 2026 15:33:49 +0800 Subject: [PATCH 0134/2102] IB/usnic: fix wild pointer dereference in usnic_ib_qp_grp_dump_rows() While auditing list_first_entry() users we found that usnic_ib_qp_grp_dump_rows() calls list_first_entry() on qp_grp->flows_lst without checking whether the list is empty. list_first_entry() never returns NULL: on an empty list head->next == head, so container_of() yields a bogus non-NULL pointer derived from the list head address. The function then dereferences it twice through "default_flow->flow->flow_id", which reads a garbage pointer out of the enclosing structure and dereferences that in turn, almost certainly causing a kernel oops. The empty-list state is reachable on a normal path: transitioning a QP group to IB_QPS_RESET via usnic_ib_qp_grp_modify() calls release_and_remove_all_flows(), which empties flows_lst, while disable_qp_grp() only disables the hardware queues and does not release the VNIC resources, so res->owner still points at the qp_grp. A later usnic_ib_create_qp() on the same VF unconditionally dumps the whole VF via usnic_ib_log_vf() -> usnic_vnic_dump(), which invokes this callback for every res->owner != NULL - including the reset qp_grp with an empty flows_lst. The existing "if (obj)" guard does not help because obj (the qp_grp itself) is non-NULL; nothing checks the flow list. Fix it by switching to list_first_entry_or_null() and printing "N/A" for the flow ID column when the qp_grp has no flow, mirroring the existing all-"N/A" formatting used for a NULL obj. This was found by code audit; we do not have Cisco usNIC hardware to reproduce it, but the triggering sequence (create QP, modify to RESET, create another QP on the same VF) is a plain libibverbs flow. Fixes: 256d6a6ac52e ("IB/usnic: Port over usnic_ib_qp_grp.[hc] to new usnic_fwd.h") Reported-by: Wang Haoran Reported-by: Li Ximo Signed-off-by: Wang Haoran Link: https://patch.msgid.link/20261023073349.1287022-1-lixicaicai@gmail.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/usnic/usnic_ib_qp_grp.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/drivers/infiniband/hw/usnic/usnic_ib_qp_grp.c b/drivers/infiniband/hw/usnic/usnic_ib_qp_grp.c index a7327c7a746577..6f6aaea06edead 100644 --- a/drivers/infiniband/hw/usnic/usnic_ib_qp_grp.c +++ b/drivers/infiniband/hw/usnic/usnic_ib_qp_grp.c @@ -78,8 +78,17 @@ int usnic_ib_qp_grp_dump_rows(void *obj, char *buf, int buf_sz) struct usnic_ib_qp_grp *qp_grp = obj; struct usnic_ib_qp_grp_flow *default_flow; if (obj) { - default_flow = list_first_entry(&qp_grp->flows_lst, - struct usnic_ib_qp_grp_flow, link); + default_flow = list_first_entry_or_null(&qp_grp->flows_lst, + struct usnic_ib_qp_grp_flow, + link); + if (!default_flow) + return scnprintf(buf, buf_sz, + "|%d\t|%s\t|%d\t|%hu\t|N/A", + qp_grp->ibqp.qp_num, + usnic_ib_qp_grp_state_to_string( + qp_grp->state), + qp_grp->owner_pid, + usnic_vnic_get_index(qp_grp->vf->vnic)); return scnprintf(buf, buf_sz, "|%d\t|%s\t|%d\t|%hu\t|%d", qp_grp->ibqp.qp_num, usnic_ib_qp_grp_state_to_string( From 82d46dedf750addfad5480f79165cacb81c89650 Mon Sep 17 00:00:00 2001 From: Yehyeong Lee Date: Sun, 25 Oct 2026 10:37:46 +0900 Subject: [PATCH 0135/2102] RDMA/srpt: bound the indirect descriptor table to the IU srpt_get_desc_tbl() takes the number of INDIRECT descriptors from idb->table_desc.len, which the initiator controls, and checks it only against data_out_desc_cnt + data_in_desc_cnt, two more initiator fields. Both are u8, so the pair admits up to 510 descriptors, and nothing compares the table against the receive IU it has to live in. srpt_alloc_rw_ctxs() then walks idb->desc_list for that many entries. With the default srp_max_req_size of 8276 the table fits as long as the additional CDB is short, but ADDITIONAL CDB LENGTH is an initiator field too, and at its maximum of 252 bytes 510 descriptors end at 48 + 252 + 20 + 510 * 16 = 8480, which is past the end of the object. BUG: KASAN: slab-out-of-bounds in srpt_alloc_rw_ctxs+0x631/0x870 Read of size 4 at addr ffff888002d6a05c by task kunit_try_catch/43 CPU: 0 UID: 0 PID: 43 Comm: kunit_try_catch Tainted: G N 7.3.0-12378-g6fba331225f5-dirty #1 PREEMPT(lazy) Tainted: [N]=TEST Call Trace: dump_stack_lvl+0x3f/0x50 print_report+0xcd/0x620 ? alloc_pages_node_noprof+0xa2/0x140 ? srpt_alloc_rw_ctxs+0x631/0x870 kasan_report+0xde/0x110 ? srpt_alloc_rw_ctxs+0x631/0x870 srpt_alloc_rw_ctxs+0x631/0x870 srpt_test_parse+0x114/0x580 ? __pfx_srpt_test_ctx_common.constprop.0+0x10/0x10 ? __pfx_srpt_test_parse+0x10/0x10 ? srpt_test_ctx_init.constprop.0+0x4cb/0x6c0 srpt_test_run.constprop.0+0xc1/0xa60 ? pick_task_fair+0x126/0x1950 ? __pfx_srpt_test_run.constprop.0+0x10/0x10 ? update_curr.constprop.0+0x4a/0x390 ? __set_cpus_allowed_ptr+0x181/0x240 ? __pfx_read_tsc+0x10/0x10 ? ktime_get_ts64+0x192/0x250 kunit_try_run_case+0x1ca/0x4b0 ? __pfx_kunit_try_run_case+0x10/0x10 ? kthread_affine_node+0x24b/0x370 ? __pfx_kthread_affine_node+0x10/0x10 ? __pfx_kunit_try_run_case+0x10/0x10 ? __pfx_kunit_generic_run_threadfn_adapter+0x10/0x10 kunit_generic_run_threadfn_adapter+0x7b/0xe0 kthread+0x36e/0x500 ? __pfx_kthread+0x10/0x10 ret_from_fork+0x34d/0x620 ? __pfx_ret_from_fork+0x10/0x10 ? __switch_to+0x22/0xdd0 ? __pfx_kthread+0x10/0x10 ret_from_fork_asm+0x19/0x30 Allocated by task 43: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 __kasan_slab_alloc+0x6e/0x70 kmem_cache_alloc_noprof+0xfc/0x2b0 srpt_test_ctx_common.constprop.0+0x46f/0x9b0 srpt_test_ctx_init.constprop.0+0x30/0x6c0 srpt_test_run.constprop.0+0xb6/0xa60 kunit_try_run_case+0x1ca/0x4b0 kunit_generic_run_threadfn_adapter+0x7b/0xe0 kthread+0x36e/0x500 ret_from_fork+0x34d/0x620 ret_from_fork_asm+0x19/0x30 The buggy address belongs to the object at ffff888002d68000 which belongs to the cache srpt-kunit-iu of size 8276 The buggy address is located 8 bytes to the right of allocated 8276-byte region [ffff888002d68000, ffff888002d6a054) The KUnit harness that forces this is not part of this patch. A table_desc.len below one descriptor is the other way in. It gives nbufs zero, which the count check admits and a span check cannot catch either, since an empty table fits in any IU. srpt_alloc_rw_ctxs() then returns success with n_rw_ctx zero, no scatterlist is chained, and srpt_write_pending() reaches ib_post_send() with an empty work request list. rvt_post_send() evaluates !wr->next before the loop that tests wr against NULL, so an rdmavt device faults there whenever its send queue is idle. Reject a table that does not fit by comparing the span it occupies against byte_len, and reject an empty one. The span is the table offset plus struct_size(idb, desc_list, nbufs), and nbufs is at most 510 once the existing count check has passed, so it cannot saturate. The header always lies inside the allocated buffer, since the largest offset srpt_get_desc_buf() can return is 48 + 252 and the header is 20 bytes, so it ends at 320 while srp_max_req_size is at least MIN_MAX_REQ_SIZE, which is 996. It does not always lie inside the bytes the initiator actually sent, which is why the span starts at the table offset and covers the header as well. Fixes: a42d985bd5b2 ("ib_srpt: Initial SRP Target merge for v3.3-rc1") Cc: stable@vger.kernel.org Signed-off-by: Yehyeong Lee Link: https://patch.msgid.link/20261025013748.3755639-2-yhlee@isslab.korea.ac.kr Reviewed-by: Bart Van Assche Signed-off-by: Leon Romanovsky --- drivers/infiniband/ulp/srpt/ib_srpt.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/drivers/infiniband/ulp/srpt/ib_srpt.c b/drivers/infiniband/ulp/srpt/ib_srpt.c index 43c3ff1ad8e7ed..40d796840befc5 100644 --- a/drivers/infiniband/ulp/srpt/ib_srpt.c +++ b/drivers/infiniband/ulp/srpt/ib_srpt.c @@ -1117,6 +1117,7 @@ static int srpt_get_desc_tbl(struct srpt_recv_ioctx *recv_ioctx, struct srp_indirect_buf *idb = srpt_get_desc_buf(srp_cmd); int nbufs = be32_to_cpu(idb->table_desc.len) / sizeof(struct srp_direct_buf); + size_t desc_off = (uintptr_t)idb - (uintptr_t)srp_cmd; if (nbufs > (srp_cmd->data_out_desc_cnt + srp_cmd->data_in_desc_cnt)) { @@ -1128,6 +1129,18 @@ static int srpt_get_desc_tbl(struct srpt_recv_ioctx *recv_ioctx, return -EINVAL; } + if (nbufs == 0) { + pr_err("received SRP_CMD with an empty indirect descriptor table\n"); + return -EINVAL; + } + + if (desc_off + struct_size(idb, desc_list, nbufs) > + recv_ioctx->byte_len) { + pr_err("received SRP_CMD indirect table (%d descriptors) that does not fit the %d-byte IU\n", + nbufs, recv_ioctx->byte_len); + return -EINVAL; + } + *data_len = be32_to_cpu(idb->len); return srpt_alloc_rw_ctxs(ioctx, idb->desc_list, nbufs, sg, sg_cnt); From 252fc17ff4fbc2c6ead5e2f9404c9d0c490f0965 Mon Sep 17 00:00:00 2001 From: Yehyeong Lee Date: Sun, 25 Oct 2026 10:37:47 +0900 Subject: [PATCH 0136/2102] RDMA/srpt: reject zero-length buffer descriptors srpt_alloc_rw_ctxs() takes each buffer descriptor length straight from the wire and hands it to target_alloc_sgl(), which has no length check of its own. For the single descriptor of a DIRECT request, and for the last descriptor of an INDIRECT table, chainable is false, so a zero length makes sgl_alloc_order() compute nalloc zero. kmalloc_objs() answers that with ZERO_SIZE_PTR, which is not NULL, so the allocation looks like it succeeded and sg_init_table(sgl, 0) runs. That reaches sg_init_marker(), which does sg_mark_end(&sgl[nents - 1]) with nents unsigned, so the index is 4294967295 rather than minus one and the read modify write of page_link lands far outside any allocation. Oops: general protection fault, probably for non-canonical address 0xdffffc03fffffffe: 0000 [#1] KASAN PTI KASAN: probably user-memory-access in range [0x0000001ffffffff0-0x0000001ffffffff7] CPU: 0 UID: 0 PID: 43 Comm: kunit_try_catch Tainted: G N 7.3.0-12378-g6fba331225f5-dirty #1 PREEMPT(lazy) Tainted: [N]=TEST RIP: 0010:sgl_alloc_order+0xb6/0x370 Code: ef 01 4c 89 e2 49 89 c4 31 f6 49 c1 e7 05 48 89 c7 e8 ae e0 cb ff 4d 01 e7 48 b8 00 00 00 00 00 fc ff df 4c 89 fa 48 c1 ea 03 <80> 3c 02 00 0f 85 6b 02 00 00 49 bc 00 00 00 00 00 fc ff df 49 8b RSP: 0000:ffff888002d4fa38 EFLAGS: 00010202 RAX: dffffc0000000000 RBX: 0000000000001000 RCX: 0000000000000000 RDX: 00000003fffffffe RSI: 0000000000000000 RDI: 0000000000000010 RBP: 0000000000000000 R08: ffff888002b158a0 R09: 0000000000000000 R10: 0000000000000010 R11: 0000000000000037 R12: 0000000000000010 R13: ffff888002d6803c R14: 0000000000000000 R15: 0000001ffffffff0 FS: 0000000000000000(0000) GS:0000000000000000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: ffff88802f1c8000 CR3: 000000002e458000 CR4: 00000000000006f0 Call Trace: target_alloc_sgl+0x2b/0x70 srpt_alloc_rw_ctxs+0x2ef/0x870 srpt_test_parse+0x114/0x580 ? __pfx_srpt_test_parse+0x10/0x10 ? srpt_test_ctx_init_direct+0x17d/0x280 srpt_direct_len0_test+0xa4/0x280 ? __pfx_srpt_direct_len0_test+0x10/0x10 ? __set_cpus_allowed_ptr+0x181/0x240 ? __pfx_read_tsc+0x10/0x10 ? ktime_get_ts64+0x192/0x250 kunit_try_run_case+0x1ca/0x4b0 ? __pfx_kunit_try_run_case+0x10/0x10 ? kthread_affine_node+0x24b/0x370 ? __pfx_kthread_affine_node+0x10/0x10 ? __pfx_kunit_try_run_case+0x10/0x10 ? __pfx_kunit_generic_run_threadfn_adapter+0x10/0x10 kunit_generic_run_threadfn_adapter+0x7b/0xe0 kthread+0x36e/0x500 ? __pfx_kthread+0x10/0x10 ret_from_fork+0x34d/0x620 ? __pfx_ret_from_fork+0x10/0x10 ? __switch_to+0x22/0xdd0 ? __pfx_kthread+0x10/0x10 ret_from_fork_asm+0x19/0x30 The KUnit harness that forces this is not part of this patch. A zero length descriptor elsewhere in a table is chainable, so one entry is allocated and that write does not happen, but the entry count comes back zero and the mapping in rdma_rw_ctx_init() then refuses it. The target core never hands the same allocator a zero length. Its own call in transport_generic_new_cmd() sits behind a cmd->data_length test. Reject a descriptor whose length is zero. The existing unwind label covers the first iteration, where its loop body does not run because nothing has been allocated yet. Fixes: b99f8e4d7bcd ("IB/srpt: convert to the generic RDMA READ/WRITE API") Cc: stable@vger.kernel.org Signed-off-by: Yehyeong Lee Link: https://patch.msgid.link/20261025013748.3755639-3-yhlee@isslab.korea.ac.kr Reviewed-by: Bart Van Assche Signed-off-by: Leon Romanovsky --- drivers/infiniband/ulp/srpt/ib_srpt.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/infiniband/ulp/srpt/ib_srpt.c b/drivers/infiniband/ulp/srpt/ib_srpt.c index 40d796840befc5..dfcecbe3a47c75 100644 --- a/drivers/infiniband/ulp/srpt/ib_srpt.c +++ b/drivers/infiniband/ulp/srpt/ib_srpt.c @@ -979,6 +979,12 @@ static int srpt_alloc_rw_ctxs(struct srpt_send_ioctx *ioctx, u32 size = be32_to_cpu(db->len); u32 rkey = be32_to_cpu(db->key); + if (size == 0) { + pr_err("received SRP_CMD buffer descriptor with zero length\n"); + ret = -EINVAL; + goto unwind; + } + ret = target_alloc_sgl(&ctx->sg, &ctx->nents, size, false, i < nbufs - 1); if (ret) From 013eb66a8ef25ef531bf41d79815948ab4938571 Mon Sep 17 00:00:00 2001 From: Yehyeong Lee Date: Sun, 25 Oct 2026 10:37:48 +0900 Subject: [PATCH 0137/2102] RDMA/srpt: widen the indirect RDMA context counters srpt_send_ioctx::n_rdma and ::n_rw_ctx are u8, and neither of the values stored in them is bounded by 255. n_rw_ctx counts the INDIRECT descriptors a command carries, and the count guard in srpt_get_desc_tbl() admits data_out_desc_cnt plus data_in_desc_cnt, so up to 510. At 256 descriptors n_rw_ctx wraps to zero, and srpt_release_cmd() frees the contexts only when it is non-zero, so every scatterlist and RDMA context the command allocated leaks. n_rdma is not a descriptor count at all. It is the sum of the rdma_rw_ctx_init() return values, which is the number of work requests each context needs, accumulated by ioctx->n_rdma += ret. A handful of descriptors for large transfers can pass 255 on their own, with no unusual descriptor count involved. A wrapped n_rdma is then handed to atomic_sub_return(ioctx->n_rdma, &ch->sq_wr_avail) and tested by WARN_ON(ioctx->n_rdma <= 0), so the send queue work request accounting drifts too. Make both counters int, the type the values they accumulate already have. Fixes: b99f8e4d7bcd ("IB/srpt: convert to the generic RDMA READ/WRITE API") Cc: stable@vger.kernel.org Reviewed-by: Bart Van Assche Signed-off-by: Yehyeong Lee Link: https://patch.msgid.link/20261025013748.3755639-4-yhlee@isslab.korea.ac.kr Signed-off-by: Leon Romanovsky --- drivers/infiniband/ulp/srpt/ib_srpt.c | 2 +- drivers/infiniband/ulp/srpt/ib_srpt.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/infiniband/ulp/srpt/ib_srpt.c b/drivers/infiniband/ulp/srpt/ib_srpt.c index dfcecbe3a47c75..a2af0882eff5ad 100644 --- a/drivers/infiniband/ulp/srpt/ib_srpt.c +++ b/drivers/infiniband/ulp/srpt/ib_srpt.c @@ -959,7 +959,7 @@ static int srpt_alloc_rw_ctxs(struct srpt_send_ioctx *ioctx, struct srpt_rdma_ch *ch = ioctx->ch; struct scatterlist *prev = NULL; unsigned prev_nents; - u8 n_rdma, n_rw_ctx; + int n_rdma, n_rw_ctx; int ret, i; if (nbufs == 1) { diff --git a/drivers/infiniband/ulp/srpt/ib_srpt.h b/drivers/infiniband/ulp/srpt/ib_srpt.h index 506c11b843593b..d9061aa65c1a89 100644 --- a/drivers/infiniband/ulp/srpt/ib_srpt.h +++ b/drivers/infiniband/ulp/srpt/ib_srpt.h @@ -223,8 +223,8 @@ struct srpt_send_ioctx { struct ib_cqe rdma_cqe; enum srpt_command_state state; struct se_cmd cmd; - u8 n_rdma; - u8 n_rw_ctx; + int n_rdma; + int n_rw_ctx; bool queue_status_only; u8 sense_data[TRANSPORT_SENSE_BUFFER]; }; From 0246639e79a4132b68cb41ba28e41333d7c742d0 Mon Sep 17 00:00:00 2001 From: Serhat Kumral Date: Fri, 23 Oct 2026 22:23:48 +0300 Subject: [PATCH 0138/2102] RDMA/mthca: Fix off-by-one in mthca_map_user_db() db_tab->page[] has uarc_size / MTHCA_ICM_PAGE_SIZE elements, so valid doorbell indices are in the range [0, uarc_size / 8 - 1]. Allowing index == uarc_size / 8 results in an out-of-bounds access at db_tab->page[npages]. Use '>=' instead of '>' in the bounds check. Fixes: 56483ec1b702 ("[PATCH] IB uverbs: add mthca user doorbell record support") Signed-off-by: Serhat Kumral Link: https://patch.msgid.link/20261023192348.11070-1-serhatkumral1@gmail.com Reviewed-by: Chenguang Zhao Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/mthca/mthca_memfree.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/infiniband/hw/mthca/mthca_memfree.c b/drivers/infiniband/hw/mthca/mthca_memfree.c index 9c5eb03f354ded..39d82dc73807e4 100644 --- a/drivers/infiniband/hw/mthca/mthca_memfree.c +++ b/drivers/infiniband/hw/mthca/mthca_memfree.c @@ -453,7 +453,7 @@ int mthca_map_user_db(struct mthca_dev *dev, struct mthca_uar *uar, if (!mthca_is_memfree(dev)) return 0; - if (index < 0 || index > dev->uar_table.uarc_size / 8) + if (index < 0 || index >= dev->uar_table.uarc_size / 8) return -EINVAL; mutex_lock(&db_tab->mutex); From a78ee2e05f7c7dd09e58ea615960105f78dc3c75 Mon Sep 17 00:00:00 2001 From: Krzysztof Kozlowski Date: Sun, 1 Nov 2026 13:08:39 +0100 Subject: [PATCH 0139/2102] memory: fsl_ifc: Clear fsl_ifc_ctrl_dev on probe failure and removal Global fsl_ifc_ctrl_dev is allocated with devm_kzalloc(), so it is freed when probe fails or when the device is unbound, but the exported global pointer is never reset. Subsequent calls to fsl_ifc_find() or probing of fsl_ifc_nand would then pass the NULL check and dereference freed memory. Issue is mostly theoretical, because there are no users/calls to fsl_ifc_find(). Rework the logic, so the global fsl_ifc_ctrl_dev is assigned only after device state is properly initialized in probe(), except requesting interrupts. This makes sure that early call to fsl_ifc_find() will not use the device driver while it is not fully initialized. Clear the global pointer on exit and error paths, to fix the possible use-after-free. Reported-by: Reid Downing Closes: https://lore.kernel.org/all/20261025170833.1316443-1-skibletz@gmail.com/ Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-72f58ab4-9f9d-4b00-949c-00929918a3b3 Fixes: 8e0d09b1232d ("memory: fsl_ifc: fix leak of private memory on probe failure") Fixes: a20cbdeffce2 ("powerpc/fsl: Add support for Integrated Flash Controller") Cc: stable@vger.kernel.org Signed-off-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261101120838.36227-2-krzysztof.kozlowski@oss.qualcomm.com Signed-off-by: Krzysztof Kozlowski --- drivers/memory/fsl_ifc.c | 73 +++++++++++++++++++++------------------- 1 file changed, 38 insertions(+), 35 deletions(-) diff --git a/drivers/memory/fsl_ifc.c b/drivers/memory/fsl_ifc.c index 6dcc317d95d42d..83991c05a6a5c5 100644 --- a/drivers/memory/fsl_ifc.c +++ b/drivers/memory/fsl_ifc.c @@ -92,6 +92,7 @@ static void fsl_ifc_ctrl_remove(struct platform_device *dev) if (ctrl->nand_irq) free_irq(ctrl->nand_irq, ctrl); free_irq(ctrl->irq, ctrl); + fsl_ifc_ctrl_dev = NULL; irq_dispose_mapping(ctrl->nand_irq); irq_dispose_mapping(ctrl->irq); @@ -205,82 +206,82 @@ static int fsl_ifc_ctrl_probe(struct platform_device *dev) int ret = 0; int version, banks; void __iomem *addr; + struct fsl_ifc_ctrl *ctrl; dev_info(&dev->dev, "Freescale Integrated Flash Controller\n"); - fsl_ifc_ctrl_dev = devm_kzalloc(&dev->dev, sizeof(*fsl_ifc_ctrl_dev), - GFP_KERNEL); - if (!fsl_ifc_ctrl_dev) + ctrl = devm_kzalloc(&dev->dev, sizeof(*ctrl), GFP_KERNEL); + if (!ctrl) return -ENOMEM; - dev_set_drvdata(&dev->dev, fsl_ifc_ctrl_dev); + dev_set_drvdata(&dev->dev, ctrl); /* IOMAP the entire IFC region */ - fsl_ifc_ctrl_dev->gregs = of_iomap(dev->dev.of_node, 0); - if (!fsl_ifc_ctrl_dev->gregs) { + ctrl->gregs = of_iomap(dev->dev.of_node, 0); + if (!ctrl->gregs) { dev_err(&dev->dev, "failed to get memory region\n"); return -ENODEV; } if (of_property_read_bool(dev->dev.of_node, "little-endian")) { - fsl_ifc_ctrl_dev->little_endian = true; + ctrl->little_endian = true; dev_dbg(&dev->dev, "IFC REGISTERS are LITTLE endian\n"); } else { - fsl_ifc_ctrl_dev->little_endian = false; + ctrl->little_endian = false; dev_dbg(&dev->dev, "IFC REGISTERS are BIG endian\n"); } - version = ifc_in32(&fsl_ifc_ctrl_dev->gregs->ifc_rev) & - FSL_IFC_VERSION_MASK; + version = ifc_in32(&ctrl->gregs->ifc_rev) & FSL_IFC_VERSION_MASK; banks = (version == FSL_IFC_VERSION_1_0_0) ? 4 : 8; dev_info(&dev->dev, "IFC version %d.%d, %d banks\n", version >> 24, (version >> 16) & 0xf, banks); - fsl_ifc_ctrl_dev->version = version; - fsl_ifc_ctrl_dev->banks = banks; + ctrl->version = version; + ctrl->banks = banks; - addr = fsl_ifc_ctrl_dev->gregs; + addr = ctrl->gregs; if (version >= FSL_IFC_VERSION_2_0_0) addr += PGOFFSET_64K; else addr += PGOFFSET_4K; - fsl_ifc_ctrl_dev->rregs = addr; + ctrl->rregs = addr; /* get the Controller level irq */ - fsl_ifc_ctrl_dev->irq = irq_of_parse_and_map(dev->dev.of_node, 0); - if (fsl_ifc_ctrl_dev->irq == 0) { + ctrl->irq = irq_of_parse_and_map(dev->dev.of_node, 0); + if (ctrl->irq == 0) { dev_err(&dev->dev, "failed to get irq resource for IFC\n"); ret = -ENODEV; goto err; } /* get the nand machine irq */ - fsl_ifc_ctrl_dev->nand_irq = - irq_of_parse_and_map(dev->dev.of_node, 1); + ctrl->nand_irq = irq_of_parse_and_map(dev->dev.of_node, 1); - fsl_ifc_ctrl_dev->dev = &dev->dev; + ctrl->dev = &dev->dev; - ret = fsl_ifc_ctrl_init(fsl_ifc_ctrl_dev); + ret = fsl_ifc_ctrl_init(ctrl); if (ret < 0) goto err_unmap_nandirq; - init_waitqueue_head(&fsl_ifc_ctrl_dev->nand_wait); + init_waitqueue_head(&ctrl->nand_wait); - ret = request_irq(fsl_ifc_ctrl_dev->irq, fsl_ifc_ctrl_irq, IRQF_SHARED, - "fsl-ifc", fsl_ifc_ctrl_dev); + fsl_ifc_ctrl_dev = ctrl; + + ret = request_irq(ctrl->irq, fsl_ifc_ctrl_irq, IRQF_SHARED, + "fsl-ifc", ctrl); if (ret != 0) { dev_err(&dev->dev, "failed to install irq (%d)\n", - fsl_ifc_ctrl_dev->irq); - goto err_unmap_nandirq; + ctrl->irq); + goto err_clear_global; } - if (fsl_ifc_ctrl_dev->nand_irq) { - ret = request_irq(fsl_ifc_ctrl_dev->nand_irq, fsl_ifc_nand_irq, - 0, "fsl-ifc-nand", fsl_ifc_ctrl_dev); + if (ctrl->nand_irq) { + ret = request_irq(ctrl->nand_irq, fsl_ifc_nand_irq, 0, + "fsl-ifc-nand", ctrl); if (ret != 0) { dev_err(&dev->dev, "failed to install irq (%d)\n", - fsl_ifc_ctrl_dev->nand_irq); + ctrl->nand_irq); goto err_free_irq; } } @@ -293,15 +294,17 @@ static int fsl_ifc_ctrl_probe(struct platform_device *dev) return 0; err_free_nandirq: - if (fsl_ifc_ctrl_dev->nand_irq) - free_irq(fsl_ifc_ctrl_dev->nand_irq, fsl_ifc_ctrl_dev); + if (ctrl->nand_irq) + free_irq(ctrl->nand_irq, ctrl); err_free_irq: - free_irq(fsl_ifc_ctrl_dev->irq, fsl_ifc_ctrl_dev); + free_irq(ctrl->irq, ctrl); +err_clear_global: + fsl_ifc_ctrl_dev = NULL; err_unmap_nandirq: - irq_dispose_mapping(fsl_ifc_ctrl_dev->nand_irq); - irq_dispose_mapping(fsl_ifc_ctrl_dev->irq); + irq_dispose_mapping(ctrl->nand_irq); + irq_dispose_mapping(ctrl->irq); err: - iounmap(fsl_ifc_ctrl_dev->gregs); + iounmap(ctrl->gregs); return ret; } From 861bebd1fac5f5a25c11e40aec3c3291542045d1 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Mon, 21 Sep 2026 08:29:55 +0100 Subject: [PATCH 0140/2102] irqchip/gic-v4: Clear the domain and fwnode pointers after freeing them The GICv4 allocation and teardown paths free their irq domains and fwnodes but leave the pointers set, and the allocation error paths test those pointers before removing them. struct its_vm and struct its_vpe are embedded in KVM's per-VM and per-vCPU state, so nothing re-zeroes them between two attempts, and an error path taken after an earlier one already freed the domain calls irq_domain_remove() on freed memory. Reaching this takes two allocation failures, one to leave the stale pointer behind and one to send the next attempt down the error path. Fixes: 7de5c0af9c7c ("irqchip/gic-v4: Add per-VM VPE domain creation") Fixes: 6d31b6ff985d ("irqchip/gic-v4.1: Add VSGI allocation/teardown") Reviewed-by: Yuan Yao Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20260921072958.2918477-2-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- drivers/irqchip/irq-gic-v4.c | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/drivers/irqchip/irq-gic-v4.c b/drivers/irqchip/irq-gic-v4.c index 8455b4a5fbb0d5..754839e409f884 100644 --- a/drivers/irqchip/irq-gic-v4.c +++ b/drivers/irqchip/irq-gic-v4.c @@ -147,10 +147,14 @@ static int its_alloc_vcpu_sgis(struct its_vpe *vpe, int idx) return 0; err: - if (vpe->sgi_domain) + if (vpe->sgi_domain) { irq_domain_remove(vpe->sgi_domain); - if (vpe->fwnode) + vpe->sgi_domain = NULL; + } + if (vpe->fwnode) { irq_domain_free_fwnode(vpe->fwnode); + vpe->fwnode = NULL; + } kfree(name); return -ENOMEM; } @@ -191,10 +195,14 @@ int its_alloc_vcpu_irqs(struct its_vm *vm) return 0; err: - if (vm->domain) + if (vm->domain) { irq_domain_remove(vm->domain); - if (vm->fwnode) + vm->domain = NULL; + } + if (vm->fwnode) { irq_domain_free_fwnode(vm->fwnode); + vm->fwnode = NULL; + } return -ENOMEM; } @@ -215,6 +223,8 @@ static void its_free_sgi_irqs(struct its_vm *vm) irq_domain_free_irqs(irq, 16); irq_domain_remove(vm->vpes[i]->sgi_domain); irq_domain_free_fwnode(vm->vpes[i]->fwnode); + vm->vpes[i]->sgi_domain = NULL; + vm->vpes[i]->fwnode = NULL; } } @@ -224,6 +234,8 @@ void its_free_vcpu_irqs(struct its_vm *vm) irq_domain_free_irqs(vm->vpes[0]->irq, vm->nr_vpes); irq_domain_remove(vm->domain); irq_domain_free_fwnode(vm->fwnode); + vm->domain = NULL; + vm->fwnode = NULL; } static int its_send_vpe_cmd(struct its_vpe *vpe, struct its_cmd_info *info) From fd86d69c951765e24e89a162c53dfe33a8aba976 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Mon, 21 Sep 2026 08:29:56 +0100 Subject: [PATCH 0141/2102] irqchip/gic-v4: Unwind what its_alloc_vcpu_irqs() allocated on failure A failure in the its_alloc_vcpu_sgis() loop leaves behind both the SGI domains created for the vPEs below the failing index and the vPE irqs allocated before the loop, since irq_domain_remove() frees neither. Each leaked vPE takes its ITS state with it, a vpe_id and an LPI pending table. Free both from a second label before the existing unwind. With the freed pointers now cleared, its_free_sgi_irqs() can skip a vPE with no SGI domain and be reused there. The check has to precede the lookup: irq_find_mapping(NULL, 0) falls back to irq_default_domain, and the live irq it returns would then be freed. Fixes: 6d31b6ff985d ("irqchip/gic-v4.1: Add VSGI allocation/teardown") Reviewed-by: Yuan Yao Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20260921072958.2918477-3-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- drivers/irqchip/irq-gic-v4.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/drivers/irqchip/irq-gic-v4.c b/drivers/irqchip/irq-gic-v4.c index 754839e409f884..f707a3cb281aa6 100644 --- a/drivers/irqchip/irq-gic-v4.c +++ b/drivers/irqchip/irq-gic-v4.c @@ -159,6 +159,8 @@ static int its_alloc_vcpu_sgis(struct its_vpe *vpe, int idx) return -ENOMEM; } +static void its_free_sgi_irqs(struct its_vm *vm); + int its_alloc_vcpu_irqs(struct its_vm *vm) { int vpe_base_irq, i; @@ -189,11 +191,14 @@ int its_alloc_vcpu_irqs(struct its_vm *vm) vm->vpes[i]->irq = vpe_base_irq + i; ret = its_alloc_vcpu_sgis(vm->vpes[i], i); if (ret) - goto err; + goto err_free_irqs; } return 0; +err_free_irqs: + its_free_sgi_irqs(vm); + irq_domain_free_irqs(vpe_base_irq, vm->nr_vpes); err: if (vm->domain) { irq_domain_remove(vm->domain); @@ -215,8 +220,13 @@ static void its_free_sgi_irqs(struct its_vm *vm) return; for (i = 0; i < vm->nr_vpes; i++) { - unsigned int irq = irq_find_mapping(vm->vpes[i]->sgi_domain, 0); + unsigned int irq; + + /* irq_find_mapping() falls back to the default domain on NULL. */ + if (!vm->vpes[i]->sgi_domain) + continue; + irq = irq_find_mapping(vm->vpes[i]->sgi_domain, 0); if (WARN_ON(!irq)) continue; From e3e068a457cebe2e475535685c325d5ca305f44a Mon Sep 17 00:00:00 2001 From: Kunihiko Hayashi Date: Fri, 2 Oct 2026 17:41:42 +0900 Subject: [PATCH 0142/2102] reset: scmi: Set the device for the reset controller SCMI reset driver does not set rcdev.dev when registering its reset controller. If rcdev.of_node is not available, the reset core tries to obtain the firmware node from rcdev.dev. However, rcdev.dev is also NULL, causing a NULL pointer dereference. Set rcdev.dev to the SCMI device. Signed-off-by: Kunihiko Hayashi Reviewed-by: Sudeep Holla Fixes: c8ae9c2da1cc ("reset: Add support for resets provided by SCMI") Signed-off-by: Philipp Zabel --- drivers/reset/reset-scmi.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/reset/reset-scmi.c b/drivers/reset/reset-scmi.c index 4335811e0cfaa5..0fdf593b09e24a 100644 --- a/drivers/reset/reset-scmi.c +++ b/drivers/reset/reset-scmi.c @@ -107,6 +107,7 @@ static int scmi_reset_probe(struct scmi_device *sdev) data->rcdev.ops = &scmi_reset_ops; data->rcdev.owner = THIS_MODULE; + data->rcdev.dev = dev; data->rcdev.of_node = np; data->rcdev.nr_resets = reset_ops->num_domains_get(ph); data->ph = ph; From 7100185bdc1162eb2eca1dd20a036314e27f1561 Mon Sep 17 00:00:00 2001 From: Colton Lewis Date: Tue, 27 Oct 2026 18:06:09 +0000 Subject: [PATCH 0143/2102] irqchip/gic-v4: Use a separate lockdep class for vPE doorbell IRQs By default, init_desc() assigns the shared irq_desc_lock_class lockdep key to desc->lock for every struct irq_desc. Device drivers that register an IRQ affinity notifier establish a lock dependency chain of &irq_desc_lock_class --> &pool->lock --> &p->pi_lock --> &rq->__lock when irq_set_affinity_locked() calls schedule_work() while holding desc->lock. On GICv4 systems, scheduling out a KVM vCPU calls kvm_sched_out() -> kvm_arch_vcpu_put() -> vgic_v3_put() -> vgic_v4_put() -> its_make_vpe_non_resident() -> irq_set_vcpu_affinity() while holding the scheduler runqueue lock (&rq->__lock). Acquiring the vPE doorbell IRQ's desc->lock establishes &rq->__lock --> &irq_desc_lock_class, triggering a lockdep circular locking splat: WARNING: possible circular locking dependency detected ------------------------------------------------------ VCPU-0/109705 is trying to acquire lock: ffff0001e41e4cc8 (&irq_desc_lock_class){-.-.}-{2:2}, at: __irq_get_desc_lock+0x5c/0xb0 but task is already holding lock: ffff00dad15fd260 (&rq->__lock){-.-.}-{2:2}, at: __schedule+0x23c/0x1850 which lock already depends on the new lock. Chain exists of: &irq_desc_lock_class --> &p->pi_lock --> &rq->__lock Possible unsafe locking scenario: CPU0 CPU1 ---- ---- lock(&rq->__lock); lock(&p->pi_lock); lock(&rq->__lock); lock(&irq_desc_lock_class); GICv4 vPE doorbell IRQs are internal to KVM and GICv4, set IRQ_NO_BALANCING, and never register an affinity notifier or queue work under desc->lock. However, under forced IRQ threading (threadirqs or CONFIG_PREEMPT_RT), request_irq() creates an IRQ thread for the doorbell handler, causing irq_set_affinity() -> irq_set_thread_affinity() in vgic_v4_load() to call wake_up_process() under desc->lock and establish a real desc->lock --> &p->pi_lock --> &rq->__lock dependency on the vPE doorbell IRQ itself. Mark vPE doorbell IRQs with irq_set_nothread() so they are never force-threaded, and assign them a dedicated lockdep class in its_alloc_vcpu_irqs() via irq_set_lockdep_class(). Fixes: 8e01d9a396e6 ("KVM: arm64: vgic-v4: Move the GICv4 residency flow to be driven by vcpu_load/put") Signed-off-by: Colton Lewis Link: https://patch.msgid.link/20261027180610.2840837-1-coltonlewis@google.com Signed-off-by: Marc Zyngier --- drivers/irqchip/irq-gic-v4.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/drivers/irqchip/irq-gic-v4.c b/drivers/irqchip/irq-gic-v4.c index f707a3cb281aa6..019aa0ded1bf95 100644 --- a/drivers/irqchip/irq-gic-v4.c +++ b/drivers/irqchip/irq-gic-v4.c @@ -163,6 +163,8 @@ static void its_free_sgi_irqs(struct its_vm *vm); int its_alloc_vcpu_irqs(struct its_vm *vm) { + static struct lock_class_key vpe_irq_lock_class; + static struct lock_class_key vpe_irq_request_class; int vpe_base_irq, i; vm->fwnode = irq_domain_alloc_named_id_fwnode("GICv4-vpe", @@ -189,6 +191,9 @@ int its_alloc_vcpu_irqs(struct its_vm *vm) for (i = 0; i < vm->nr_vpes; i++) { int ret; vm->vpes[i]->irq = vpe_base_irq + i; + irq_set_lockdep_class(vm->vpes[i]->irq, &vpe_irq_lock_class, + &vpe_irq_request_class); + irq_set_nothread(vm->vpes[i]->irq); ret = its_alloc_vcpu_sgis(vm->vpes[i], i); if (ret) goto err_free_irqs; From 9f63ac1e31c370d5ed9d49caec4faa469d0007fc Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Mon, 21 Sep 2026 08:29:57 +0100 Subject: [PATCH 0144/2102] KVM: arm64: vgic: Tear down what vgic_init() created when it fails Once kvm_vgic_dist_init() has succeeded, every later failure in vgic_init() returns with the SPI array still allocated. A failure after vgic_v4_init() has also succeeded, which means only kvm_vgic_setup_default_irq_routing(), leaves the vPE array behind as well. A failed vgic_init() leaves kvm_arch_vcpu_precreate() admitting new vCPUs, so a retry of KVM_DEV_ARM_VGIC_CTRL_INIT reaches vgic_v4_init()'s early return with an array that no longer covers every vCPU, and vgic_v3_load()'s WARN_ON(vgic_v4_load()) fires on the first one it misses. Release each on the paths that can reach it, so the ioctl is all or nothing and a retry starts from scratch. vgic_v4_init() unwinds its own state on every error return, so its failure leaves only the SPI array to free. dist->nr_spis stays frozen, since the SPI count cannot change once vgic_init() has supplied it. Fixes: 180ae7b11823 ("KVM: arm/arm64: Enable irqchip routing") Fixes: 74fe55dc9ab7 ("KVM: arm/arm64: GICv4: Add init/teardown of the per-VM vPE irq domain") Reported-by: Sashiko Closes: https://lore.kernel.org/all/20260807105558.73D701F000E9@smtp.kernel.org/ Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20260921072958.2918477-4-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/vgic/vgic-init.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/arch/arm64/kvm/vgic/vgic-init.c b/arch/arm64/kvm/vgic/vgic-init.c index c9991e24cb6b74..7050e274b74200 100644 --- a/arch/arm64/kvm/vgic/vgic-init.c +++ b/arch/arm64/kvm/vgic/vgic-init.c @@ -519,7 +519,7 @@ int vgic_init(struct kvm *kvm) if (vgic_supports_direct_irqs(kvm)) { ret = vgic_v4_init(kvm); if (ret) - return ret; + goto out_free_spis; } } else { if (!dist->nr_spis) @@ -534,17 +534,24 @@ int vgic_init(struct kvm *kvm) kvm_vgic_vcpu_reset(vcpu); ret = kvm_vgic_setup_default_irq_routing(kvm); - if (ret) { - if (vgic_is_v5(kvm)) - vgic_v5_teardown(kvm); - - return ret; - } + if (ret) + goto out_teardown; vgic_debug_init(kvm); dist->initialized = true; return 0; + +out_teardown: + if (vgic_is_v5(kvm)) + vgic_v5_teardown(kvm); + else + vgic_v4_teardown(kvm); +out_free_spis: + kfree(dist->spis); + dist->spis = NULL; + + return ret; } static void kvm_vgic_dist_destroy(struct kvm *kvm) From 1ad8b8b8827e72b7d5907ee47c43ca0e2506b4f5 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Mon, 21 Sep 2026 08:29:58 +0100 Subject: [PATCH 0145/2102] KVM: arm64: vgic-v4: Restore nr_vpes before freeing the vPE resources vgic_v4_init() truncates its_vm.nr_vpes to the failing index to bound vgic_v4_teardown()'s free_irq() loop, but its_free_vcpu_irqs() reads the same field: the vPE irqs and the v4.1 SGI domains at or above that index are never freed, each one leaking a vpe_id and an LPI pending table. Restore the count from online_vcpus before that call. This depends on the previous patch: a failed vgic_init() keeps admitting vCPUs, so without that patch's teardown the vPE array outlives the failure while online_vcpus grows past the size it was allocated with. Fixes: bdb2d2ccac65 ("KVM: arm/arm64: GICv4: Add doorbell interrupt handling") Reported-by: Sashiko Closes: https://lore.kernel.org/all/20260820130616.1A7241F000E9@smtp.kernel.org/ Suggested-by: Marc Zyngier Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20260921072958.2918477-5-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/vgic/vgic-v4.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/arm64/kvm/vgic/vgic-v4.c b/arch/arm64/kvm/vgic/vgic-v4.c index ed236f083f0d7f..30e1de3fc7d9d6 100644 --- a/arch/arm64/kvm/vgic/vgic-v4.c +++ b/arch/arm64/kvm/vgic/vgic-v4.c @@ -333,6 +333,9 @@ void vgic_v4_teardown(struct kvm *kvm) free_irq(irq, vcpu); } + /* Make sure we free all VM-wide, per-CPU resources */ + its_vm->nr_vpes = atomic_read(&kvm->online_vcpus); + its_free_vcpu_irqs(its_vm); kfree(its_vm->vpes); its_vm->nr_vpes = 0; From 5f54835d94db2e896ec27415b9de2e81cb56009a Mon Sep 17 00:00:00 2001 From: Sascha Bischoff Date: Fri, 4 Sep 2026 17:44:20 +0000 Subject: [PATCH 0146/2102] KVM: arm64: vgic: Serialise CTRL_INIT against vCPU creation vgic_init() compares created_vcpus with online_vcpus to detect a vCPU being created. However, CTRL_INIT only holds config_lock, while admission of new vCPUs and updates to created_vcpus are protected by kvm->lock. A concurrent KVM_CREATE_VCPU can therefore increment created_vcpus after vgic_init() checks the counters, then block on config_lock before publishing the new vCPU. For a GICv4 VM, vgic_v4_init() consequently sizes its vPE array using a stale online_vcpus value, leaving no vPE entry for the new vCPU once its creation completes. The upcoming GICv5 IRS support would hit the same issue when sizing its doorbell domain. Hold kvm->lock around CTRL_INIT. The existing counter check detects a vCPU creation already in progress, while the lock prevents a new one from starting until initialisation has completed. Fixes: f00327731131 ("KVM: arm64: Use config_lock to protect vgic state") Reported-by: Sashiko Link: https://lore.kernel.org/r/20260807124506.ED85C1F000E9@smtp.kernel.org Signed-off-by: Sascha Bischoff Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Link: https://patch.msgid.link/20260904174419.76057-1-sascha.bischoff@arm.com Signed-off-by: Marc Zyngier --- arch/arm64/kvm/vgic/vgic-kvm-device.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/arch/arm64/kvm/vgic/vgic-kvm-device.c b/arch/arm64/kvm/vgic/vgic-kvm-device.c index 1c205cb1361fd5..f8869dabd3657d 100644 --- a/arch/arm64/kvm/vgic/vgic-kvm-device.c +++ b/arch/arm64/kvm/vgic/vgic-kvm-device.c @@ -280,9 +280,11 @@ static int vgic_set_common_attr(struct kvm_device *dev, case KVM_DEV_ARM_VGIC_GRP_CTRL: { switch (attr->attr) { case KVM_DEV_ARM_VGIC_CTRL_INIT: + mutex_lock(&dev->kvm->lock); mutex_lock(&dev->kvm->arch.config_lock); r = vgic_init(dev->kvm); mutex_unlock(&dev->kvm->arch.config_lock); + mutex_unlock(&dev->kvm->lock); return r; case KVM_DEV_ARM_VGIC_SAVE_PENDING_TABLES: /* From e1024ed9c3823fbc4b1e65f351088f0bf999b887 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Wed, 28 Oct 2026 17:33:18 +0000 Subject: [PATCH 0147/2102] KVM: arm64: vgic-its: Clear an unqueued LPI before dropping its lock DISCARD reads which vCPU's AP list holds the LPI, drops the irq lock to pause that vCPU, and takes the lock again to clear the pending state. When no list holds the LPI there's nothing to pause, yet the lock is still dropped. In between, vgic_queue_irq_unlock() can list the LPI (for an MSI that had already made it pending, or a GICR_INVLPIR write enabling it while latched) and its vCPU can load it into a list register. The guest then takes an LPI it has discarded. Clear an LPI that no list holds before dropping the lock. Fixes: e99ff76f4a02b ("KVM: arm64: vgic-its: Remove the pending state of a discarded LPI") Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261028173319.1807811-2-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/vgic/vgic-its.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/arch/arm64/kvm/vgic/vgic-its.c b/arch/arm64/kvm/vgic/vgic-its.c index 7e9b265b1f521c..a8f103009143f1 100644 --- a/arch/arm64/kvm/vgic/vgic-its.c +++ b/arch/arm64/kvm/vgic/vgic-its.c @@ -842,22 +842,24 @@ static int vgic_its_cmd_handle_discard(struct kvm *kvm, struct vgic_its *its, * Only an LPI on a vCPU's AP list can be in its list registers, * which the exit path folds back, and that exit moves the LPI * to its target vCPU if the target has changed: pause both. + * Clear an LPI on no AP list before dropping the lock, so that + * nothing can put it in a list register first. */ scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) { vcpu = irq->vcpu; target = irq->target_vcpu; + if (!vcpu) + irq->pending_latch = false; } if (vcpu) { if (target != vcpu) kvm_pause_vcpu(target); kvm_pause_vcpu(vcpu); - } - scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) - irq->pending_latch = false; + scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) + irq->pending_latch = false; - if (vcpu) { kvm_resume_vcpu(vcpu); if (target != vcpu) kvm_resume_vcpu(target); From 147ce65112bc7255d5e2d3b12aaa23dc9ce44371 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Wed, 28 Oct 2026 17:33:19 +0000 Subject: [PATCH 0148/2102] KVM: arm64: vgic-its: Remove the pending state of a cleared LPI CLEAR removes the pending state of an LPI (IHI 0069H.b 5.3.3). Since commit e99ff76f4a02b ("KVM: arm64: vgic-its: Remove the pending state of a discarded LPI"), DISCARD does that under the irq lock, after pausing the vCPUs whose list registers can hold the LPI. CLEAR does neither. An LPI pending in a running vCPU's list register is folded back on exit, so the guest takes it after the CLEAR. pending_latch also shares a word with on_lr, so a racing CLEAR can restore on_lr after the exit path has cleared it under the lock, and trip the WARN_ON() in vgic_v3_compute_lr() when the LPI is next queued. Move DISCARD's pause and clear into a helper and use it for CLEAR too, after checking, as DISCARD does, that the event's collection is mapped. CLEAR on an unmapped collection is a command error. Without the check, the helper could be handed an LPI that has no target vCPU to pause. Fixes: df9f58fbea9bc ("KVM: arm64: vgic-its: Implement ITS command queue command handlers") Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261028173319.1807811-3-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/vgic/vgic-its.c | 67 ++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 32 deletions(-) diff --git a/arch/arm64/kvm/vgic/vgic-its.c b/arch/arm64/kvm/vgic/vgic-its.c index a8f103009143f1..f122584f1e7f5c 100644 --- a/arch/arm64/kvm/vgic/vgic-its.c +++ b/arch/arm64/kvm/vgic/vgic-its.c @@ -817,6 +817,38 @@ static u64 its_cmd_mask_field(u64 *its_cmd, int word, int shift, int size) #define its_cmd_get_target_addr(cmd) its_cmd_mask_field(cmd, 2, 16, 32) #define its_cmd_get_validbit(cmd) its_cmd_mask_field(cmd, 2, 63, 1) +/* + * Only an LPI on a vCPU's AP list can be in its list registers, which the + * exit path folds back, and that exit moves the LPI to its target vCPU if + * the target has changed: pause both. Clear an LPI on no AP list before + * dropping the lock, so that nothing can put it in a list register first. + * Must be called with the its_lock mutex held. + */ +static void vgic_its_clear_pending(struct vgic_irq *irq) +{ + struct kvm_vcpu *vcpu, *target; + + scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) { + vcpu = irq->vcpu; + target = irq->target_vcpu; + if (!vcpu) + irq->pending_latch = false; + } + + if (vcpu) { + if (target != vcpu) + kvm_pause_vcpu(target); + kvm_pause_vcpu(vcpu); + + scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) + irq->pending_latch = false; + + kvm_resume_vcpu(vcpu); + if (target != vcpu) + kvm_resume_vcpu(target); + } +} + /* * The DISCARD command frees an Interrupt Translation Table Entry (ITTE). * Must be called with the its_lock mutex held. @@ -833,38 +865,9 @@ static int vgic_its_cmd_handle_discard(struct kvm *kvm, struct vgic_its *its, struct its_device *device = find_its_device(its, device_id); int ite_esz = vgic_its_get_abi(its)->ite_esz; gpa_t gpa = device->itt_addr + ite->event_id * ite_esz; - struct vgic_irq *irq = ite->irq; - struct kvm_vcpu *vcpu, *target; vgic_its_invalidate_cache(its); - - /* - * Only an LPI on a vCPU's AP list can be in its list registers, - * which the exit path folds back, and that exit moves the LPI - * to its target vCPU if the target has changed: pause both. - * Clear an LPI on no AP list before dropping the lock, so that - * nothing can put it in a list register first. - */ - scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) { - vcpu = irq->vcpu; - target = irq->target_vcpu; - if (!vcpu) - irq->pending_latch = false; - } - - if (vcpu) { - if (target != vcpu) - kvm_pause_vcpu(target); - kvm_pause_vcpu(vcpu); - - scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) - irq->pending_latch = false; - - kvm_resume_vcpu(vcpu); - if (target != vcpu) - kvm_resume_vcpu(target); - } - + vgic_its_clear_pending(ite->irq); its_free_ite(kvm, ite); return vgic_its_write_entry_lock(its, gpa, 0ULL, ite); @@ -1309,10 +1312,10 @@ static int vgic_its_cmd_handle_clear(struct kvm *kvm, struct vgic_its *its, ite = find_ite(its, device_id, event_id); - if (!ite) + if (!ite || !its_is_collection_mapped(ite->collection)) return E_ITS_CLEAR_UNMAPPED_INTERRUPT; - ite->irq->pending_latch = false; + vgic_its_clear_pending(ite->irq); if (ite->irq->hw) return irq_set_irqchip_state(ite->irq->host_irq, From 61d4f8c3d02cf936cfb91f7b72516b17febf74d3 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Mon, 2 Nov 2026 08:29:33 +0000 Subject: [PATCH 0149/2102] KVM: arm64: vgic-its: Update GITS_CTLR.Enabled under its_lock A GITS_CTLR write that disables the ITS clears its->enabled and invalidates the translation cache under cmd_lock, while an MSI injection tests the enable bit and populates the cache under its_lock. An injection that passed the test before the disable can cache its translation after the invalidation, and the cached path then injects the LPI from the disabled ITS on every later MSI for that event. Take its_lock around the store and the invalidation, so that it serializes the store against the test. Nest it under cmd_lock, as the command handlers do. Fixes: 86a7dae884f38 ("KVM: arm/arm64: vgic-its: Check the LPI translation cache on MSI injection") Reported-by: Hyunwoo Kim Link: https://lore.kernel.org/ah6Lsi4MfKUU6wBR@v4bel/ Suggested-by: Oliver Upton Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261102082933.2673799-1-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/vgic/vgic-its.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/arm64/kvm/vgic/vgic-its.c b/arch/arm64/kvm/vgic/vgic-its.c index f122584f1e7f5c..5ce485485a1178 100644 --- a/arch/arm64/kvm/vgic/vgic-its.c +++ b/arch/arm64/kvm/vgic/vgic-its.c @@ -1805,9 +1805,12 @@ static void vgic_mmio_write_its_ctlr(struct kvm *kvm, struct vgic_its *its, !(its->cbaser & GITS_CBASER_VALID))) goto out; + /* vgic_its_resolve_lpi() tests the enable bit and caches under its_lock. */ + mutex_lock(&its->its_lock); its->enabled = !!(val & GITS_CTLR_ENABLE); if (!its->enabled) vgic_its_invalidate_cache(its); + mutex_unlock(&its->its_lock); /* * Try to process any pending commands. This function bails out early From 1995650e0a5eb29f624e9b3e4afe487541bfd3cf Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Wed, 28 Oct 2026 10:13:17 +0000 Subject: [PATCH 0150/2102] KVM: arm64: vgic-v4: Don't allocate vPEs for a GICv2 VM KVM can run a GICv2 VM on a GICv4.0 host whose CPU interface supports legacy operation. Such a VM has no LPIs and never uses vPEs, so vgic_supports_direct_irqs() is false for it and kvm_vgic_dist_destroy() never tears them down. However, userspace can still create an ITS for it. Once the vgic is initialised, vgic_its_create() calls vgic_v4_init(), which allocates the vPEs and requests a doorbell IRQ for each vCPU. They're then never freed, and each doorbell handler stays registered with a vCPU that's freed with the VM. Only allocate vPEs for a GICv3 VM. Fixes: 74fe55dc9ab77 ("KVM: arm/arm64: GICv4: Add init/teardown of the per-VM vPE irq domain") Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261028101318.2170928-2-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/vgic/vgic-v4.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/arm64/kvm/vgic/vgic-v4.c b/arch/arm64/kvm/vgic/vgic-v4.c index 30e1de3fc7d9d6..dbeb6cd8859956 100644 --- a/arch/arm64/kvm/vgic/vgic-v4.c +++ b/arch/arm64/kvm/vgic/vgic-v4.c @@ -248,7 +248,7 @@ int vgic_v4_init(struct kvm *kvm) lockdep_assert_held(&kvm->arch.config_lock); - if (!kvm_vgic_global_state.has_gicv4) + if (!kvm_vgic_global_state.has_gicv4 || dist->vgic_model != KVM_DEV_TYPE_ARM_VGIC_V3) return 0; /* Nothing to see here... move along. */ if (dist->its_vm.vpes) From 6ade9467e37149d62ec704d1a03d52f334906f13 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Wed, 28 Oct 2026 10:13:18 +0000 Subject: [PATCH 0151/2102] KVM: arm64: vgic-v4: Don't allocate vPEs when userspace clears nASSGIcap Since commit c652887a92887 ("KVM: arm64: vgic-v3: Allow userspace to write GICD_TYPER2.nASSGIcap"), userspace can disable vPE allocation for a VM on a GICv4.1 host with vSGIs by clearing nASSGIcap before the vgic is initialised. vgic_init() then skips vgic_v4_init(), and kvm_vgic_dist_destroy() skips vgic_v4_teardown(). vgic_its_create() still calls vgic_v4_init() for an ITS created after the vgic is initialised, though, and vgic_v4_init() allocates the vPEs and requests a doorbell IRQ for each vCPU. Destroying the VM leaks them, and leaves each doorbell handler registered with a vCPU that's about to be freed. Move the part of vgic_supports_direct_msis() that doesn't depend on the ITS into vgic_supports_vpes(), together with vgic_v4_init()'s GICv3 check. Gate vgic_v4_init() on it rather than on vgic_supports_direct_irqs(), which reads has_its before vgic_its_create() sets it. vgic_supports_direct_msis() returns what it did before, since vgic_has_its() is already false for a non-GICv3 VM. Fixes: c652887a92887 ("KVM: arm64: vgic-v3: Allow userspace to write GICD_TYPER2.nASSGIcap") Suggested-by: Oliver Upton Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261028101318.2170928-3-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/vgic/vgic-mmio-v3.c | 9 +++++++-- arch/arm64/kvm/vgic/vgic-v4.c | 2 +- arch/arm64/kvm/vgic/vgic.h | 1 + 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/arch/arm64/kvm/vgic/vgic-mmio-v3.c b/arch/arm64/kvm/vgic/vgic-mmio-v3.c index f9ff553bbbf164..273edcc0d519b0 100644 --- a/arch/arm64/kvm/vgic/vgic-mmio-v3.c +++ b/arch/arm64/kvm/vgic/vgic-mmio-v3.c @@ -45,7 +45,7 @@ bool vgic_has_its(struct kvm *kvm) return dist->its_model && dist->its_model == dist->vgic_model; } -bool vgic_supports_direct_msis(struct kvm *kvm) +bool vgic_supports_vpes(struct kvm *kvm) { /* * Deliberately conflate vLPI and vSGI support on GICv4.1 hardware, @@ -55,7 +55,12 @@ bool vgic_supports_direct_msis(struct kvm *kvm) if (system_supports_direct_sgis() && !vgic_supports_direct_sgis(kvm)) return false; - return kvm_vgic_global_state.has_gicv4 && vgic_has_its(kvm); + return kvm_vgic_global_state.has_gicv4 && vgic_is_v3(kvm); +} + +bool vgic_supports_direct_msis(struct kvm *kvm) +{ + return vgic_supports_vpes(kvm) && vgic_has_its(kvm); } bool system_supports_direct_sgis(void) diff --git a/arch/arm64/kvm/vgic/vgic-v4.c b/arch/arm64/kvm/vgic/vgic-v4.c index dbeb6cd8859956..1b7623f098e2f2 100644 --- a/arch/arm64/kvm/vgic/vgic-v4.c +++ b/arch/arm64/kvm/vgic/vgic-v4.c @@ -248,7 +248,7 @@ int vgic_v4_init(struct kvm *kvm) lockdep_assert_held(&kvm->arch.config_lock); - if (!kvm_vgic_global_state.has_gicv4 || dist->vgic_model != KVM_DEV_TYPE_ARM_VGIC_V3) + if (!vgic_supports_vpes(kvm)) return 0; /* Nothing to see here... move along. */ if (dist->its_vm.vpes) diff --git a/arch/arm64/kvm/vgic/vgic.h b/arch/arm64/kvm/vgic/vgic.h index 97fc3bdf520e5b..71c481ddd98d61 100644 --- a/arch/arm64/kvm/vgic/vgic.h +++ b/arch/arm64/kvm/vgic/vgic.h @@ -521,6 +521,7 @@ static inline bool vgic_host_has_gicv5(void) } bool system_supports_direct_sgis(void); +bool vgic_supports_vpes(struct kvm *kvm); bool vgic_supports_direct_msis(struct kvm *kvm); bool vgic_supports_direct_sgis(struct kvm *kvm); From bf9c9ed5204fe8155bfff96a737faaae6afe07d8 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Mon, 26 Oct 2026 09:28:01 +0000 Subject: [PATCH 0152/2102] KVM: arm64: vgic: Don't forward LPIs to a redistributor with LPIs disabled Clearing GICR_CTLR.EnableLPIs retires the LPIs on the target vCPU's ap_list, then invalidates the ITS translation caches. However, an MSI that hits the translation cache can still queue an LPI to that vCPU after the retire, and so can an INVALL that enables an LPI already pending. vgic_target_oracle() only checks that the distributor is enabled, so the LPI goes on the ap_list and the vCPU takes it with EnableLPIs clear. Make the oracle also return NULL for an LPI whose redistributor has LPIs disabled. vgic_queue_irq_unlock() rechecks it under the ap_list lock, which the retire takes after clearing EnableLPIs, so either the retire finds the LPI or the queueing reads EnableLPIs clear. The disable path pauses the vCPU after clearing EnableLPIs, and with this change the prune on that vCPU's exit would take its pending LPIs off the ap_list before the retire walks it. Pause the vCPU before clearing EnableLPIs, so that the retire still clears their pending state. Fixes: 0e4e82f154e38 ("KVM: arm64: vgic-its: Enable ITS emulation as a virtual MSI controller") Suggested-by: Oliver Upton Link: https://lore.kernel.org/r/asf87i2RDh-WksL-@kernel.org Signed-off-by: Fuad Tabba Reviewed-by: Oliver Upton Link: https://patch.msgid.link/20261026092802.2636798-2-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/vgic/vgic-mmio-v3.c | 29 ++++++++++++++++------------- arch/arm64/kvm/vgic/vgic.c | 12 ++++++++---- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/arch/arm64/kvm/vgic/vgic-mmio-v3.c b/arch/arm64/kvm/vgic/vgic-mmio-v3.c index 273edcc0d519b0..02292f8e0b4312 100644 --- a/arch/arm64/kvm/vgic/vgic-mmio-v3.c +++ b/arch/arm64/kvm/vgic/vgic-mmio-v3.c @@ -295,28 +295,31 @@ static void vgic_mmio_write_v3r_ctlr(struct kvm_vcpu *vcpu, return; if (!(val & GICR_CTLR_ENABLE_LPIS)) { - /* - * Don't disable if RWP is set, as there already an - * ongoing disable. Funky guest... - */ - ctlr = atomic_cmpxchg_acquire(&vgic_cpu->ctlr, - GICR_CTLR_ENABLE_LPIS, - GICR_CTLR_RWP); - if (ctlr != GICR_CTLR_ENABLE_LPIS) - return; - /* * Yes, disabling LPIs is painful, since it can be done from * a *remote* vcpu! So let's not take any chance, and make * sure that the target vCPU has written their LRs back to the * irq structures, and release any reference they would have. + * Pause it before its LPIs read as disabled, so that the exit's + * prune leaves them for vgic_flush_pending_lpis() to retire. * * If it hurts, don't do it. */ kvm_pause_vcpu(vcpu); - vgic_flush_pending_lpis(vcpu); - vgic_its_invalidate_all_caches(vcpu->kvm); - atomic_set_release(&vgic_cpu->ctlr, 0); + + /* + * Don't disable if RWP is set, as there already an + * ongoing disable. Funky guest... + */ + ctlr = atomic_cmpxchg_acquire(&vgic_cpu->ctlr, + GICR_CTLR_ENABLE_LPIS, + GICR_CTLR_RWP); + if (ctlr == GICR_CTLR_ENABLE_LPIS) { + vgic_flush_pending_lpis(vcpu); + vgic_its_invalidate_all_caches(vcpu->kvm); + atomic_set_release(&vgic_cpu->ctlr, 0); + } + kvm_resume_vcpu(vcpu); } else { ctlr = atomic_cmpxchg_acquire(&vgic_cpu->ctlr, 0, diff --git a/arch/arm64/kvm/vgic/vgic.c b/arch/arm64/kvm/vgic/vgic.c index bea848c93a990d..fe09ada3226253 100644 --- a/arch/arm64/kvm/vgic/vgic.c +++ b/arch/arm64/kvm/vgic/vgic.c @@ -285,14 +285,18 @@ struct kvm_vcpu *vgic_target_oracle(struct vgic_irq *irq) * If the IRQ is not active but enabled and pending, we should direct * it to its configured target VCPU. * If the distributor is disabled, pending interrupts shouldn't be - * forwarded. + * forwarded, nor should LPIs whose redistributor has them disabled. */ if (irq->enabled && irq_is_pending(irq)) { - if (unlikely(irq->target_vcpu && - !irq->target_vcpu->kvm->arch.vgic.enabled)) + struct kvm_vcpu *vcpu = irq->target_vcpu; + + if (unlikely(vcpu && !vcpu->kvm->arch.vgic.enabled)) + return NULL; + + if (unlikely(vcpu && irq_is_lpi(vcpu->kvm, irq->intid) && !vgic_lpis_enabled(vcpu))) return NULL; - return irq->target_vcpu; + return vcpu; } /* If neither active nor pending and enabled, then this IRQ should not From b4c9f30194a421b069bcfef18ccbee004c97b9f2 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Mon, 26 Oct 2026 09:28:02 +0000 Subject: [PATCH 0153/2102] KVM: arm64: vgic-v3: Don't drop a pending LPI mapped with LPIs disabled When an LPI is mapped, or restored with the ITS tables, vgic_v3_lpi_sync_pending_status() moves its bit in the target redistributor's pending table into the LPI's pending latch. Enabling LPIs on that redistributor resets the latch of every LPI that targets it from the table (its_sync_lpi_pending_table()), which no longer has the bit. So an LPI mapped while its redistributor has LPIs disabled loses its pending state, and the guest never takes it. While the redistributor has LPIs disabled, copy the bit into the latch rather than move it, so that enabling LPIs reads it again from the table. It's still copied into the latch, since saving the pending tables would otherwise write the empty latch over the bit. Fixes: 06bd5359549d7 ("KVM: arm64: vgic-its: Read config and pending bit in add_lpi()") Signed-off-by: Fuad Tabba Reviewed-by: Oliver Upton Link: https://patch.msgid.link/20261026092802.2636798-3-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/vgic/vgic-v3.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/arch/arm64/kvm/vgic/vgic-v3.c b/arch/arm64/kvm/vgic/vgic-v3.c index 346bacb3198f22..65b77fb35be37d 100644 --- a/arch/arm64/kvm/vgic/vgic-v3.c +++ b/arch/arm64/kvm/vgic/vgic-v3.c @@ -552,7 +552,8 @@ int vgic_v3_lpi_sync_pending_status(struct kvm *kvm, struct vgic_irq *irq) irq->pending_latch = status; vgic_queue_irq_unlock(vcpu->kvm, irq, flags); - if (status) { + /* Enabling LPIs resets the latch from the table: leave the bit for it */ + if (status && vgic_lpis_enabled(vcpu)) { /* clear consumed data */ val &= ~(1 << bit_nr); ret = vgic_write_guest_lock(kvm, ptr, &val, 1); From 6e4aea4c279c1be2707e5f1d8f94a3afc408b591 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Thu, 1 Oct 2026 08:10:58 +0100 Subject: [PATCH 0154/2102] KVM: arm64: selftests: Add MOVI and MOVALL commands to the ITS library Add its_send_movi_cmd() and its_send_movall_cmd() for a test that moves a pending LPI. MOVALL takes both redistributors as processor numbers, as its_send_mapc_cmd() and its_send_sync_cmd() do, and the new its_encode_target2() puts the second one in RDbase2, in the command's fourth doubleword. Assisted-by: LLM Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261001071100.190013-2-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- .../selftests/kvm/include/arm64/gic_v3_its.h | 2 ++ .../selftests/kvm/lib/arm64/gic_v3_its.c | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/tools/testing/selftests/kvm/include/arm64/gic_v3_its.h b/tools/testing/selftests/kvm/include/arm64/gic_v3_its.h index a43a407e2d5c13..e30a658fbd1c3c 100644 --- a/tools/testing/selftests/kvm/include/arm64/gic_v3_its.h +++ b/tools/testing/selftests/kvm/include/arm64/gic_v3_its.h @@ -14,6 +14,8 @@ void its_send_mapc_cmd(void *cmdq_base, u32 vcpu_id, u32 collection_id, bool val void its_send_mapti_cmd(void *cmdq_base, u32 device_id, u32 event_id, u32 collection_id, u32 intid); void its_send_invall_cmd(void *cmdq_base, u32 collection_id); +void its_send_movi_cmd(void *cmdq_base, u32 device_id, u32 event_id, u32 collection_id); +void its_send_movall_cmd(void *cmdq_base, u32 from_vcpu, u32 to_vcpu); void its_send_sync_cmd(void *cmdq_base, u32 vcpu_id); #endif // __SELFTESTS_GIC_V3_ITS_H__ diff --git a/tools/testing/selftests/kvm/lib/arm64/gic_v3_its.c b/tools/testing/selftests/kvm/lib/arm64/gic_v3_its.c index 1188b578121dd3..811d858f5def65 100644 --- a/tools/testing/selftests/kvm/lib/arm64/gic_v3_its.c +++ b/tools/testing/selftests/kvm/lib/arm64/gic_v3_its.c @@ -159,6 +159,11 @@ static void its_encode_target(struct its_cmd_block *cmd, u64 target_addr) its_mask_encode(&cmd->raw_cmd[2], target_addr >> 16, 51, 16); } +static void its_encode_target2(struct its_cmd_block *cmd, u64 target_addr) +{ + its_mask_encode(&cmd->raw_cmd[3], target_addr >> 16, 51, 16); +} + static void its_encode_collection(struct its_cmd_block *cmd, u16 col) { its_mask_encode(&cmd->raw_cmd[2], col, 15, 0); @@ -253,6 +258,29 @@ void its_send_invall_cmd(void *cmdq_base, u32 collection_id) its_send_cmd(cmdq_base, &cmd); } +void its_send_movi_cmd(void *cmdq_base, u32 device_id, u32 event_id, u32 collection_id) +{ + struct its_cmd_block cmd = {}; + + its_encode_cmd(&cmd, GITS_CMD_MOVI); + its_encode_devid(&cmd, device_id); + its_encode_event_id(&cmd, event_id); + its_encode_collection(&cmd, collection_id); + + its_send_cmd(cmdq_base, &cmd); +} + +void its_send_movall_cmd(void *cmdq_base, u32 from_vcpu, u32 to_vcpu) +{ + struct its_cmd_block cmd = {}; + + its_encode_cmd(&cmd, GITS_CMD_MOVALL); + its_encode_target(&cmd, procnum_to_rdbase(from_vcpu)); + its_encode_target2(&cmd, procnum_to_rdbase(to_vcpu)); + + its_send_cmd(cmdq_base, &cmd); +} + void its_send_sync_cmd(void *cmdq_base, u32 vcpu_id) { struct its_cmd_block cmd = {}; From 0edd1f549a1d543fce3e0f6b5c87d182575cb267 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Thu, 1 Oct 2026 08:10:59 +0100 Subject: [PATCH 0155/2102] KVM: arm64: selftests: Build a VM per test in vgic_lpi_stress vgic_lpi_stress runs its one test, the stress test, in a VM built from the command-line configuration. Build the VM per test instead, from the test's own configuration, guest code and IRQ handler, so that other ITS tests can go in the same file. The command-line configuration becomes the stress test's own (stress_args), and each run destroys its thread barrier so the next test can initialise it again. The guest's wait for the stop request moves to guest_wait_for_stop(), for the other tests to share. No functional change intended. Suggested-by: Marc Zyngier Assisted-by: LLM Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261001071100.190013-3-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- .../selftests/kvm/arm64/vgic_lpi_stress.c | 64 ++++++++++++------- 1 file changed, 41 insertions(+), 23 deletions(-) diff --git a/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c b/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c index 45a87ba5a737af..fc24e375315a6b 100644 --- a/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c +++ b/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c @@ -28,7 +28,7 @@ static struct kvm_vm *vm; static struct kvm_vcpu **vcpus; static int its_fd; -static struct test_data { +struct test_data { bool request_vcpus_stop; u32 nr_cpus; u32 nr_devices; @@ -42,7 +42,11 @@ static struct test_data { gpa_t lpi_prop_table; gpa_t lpi_pend_tables; -} test_data = { +}; + +static struct test_data test_data; + +static struct test_data stress_args = { .nr_cpus = 1, .nr_devices = 1, .nr_event_ids = 16, @@ -123,13 +127,8 @@ static void guest_setup_gic(void) its_send_sync_cmd(test_data.cmdq_base_va, cpuid); } -static void guest_code(size_t nr_lpis) +static void guest_wait_for_stop(void) { - guest_setup_gic(); - local_irq_enable(); - - GUEST_SYNC(0); - /* * Don't use WFI here to avoid blocking the vCPU thread indefinitely and * never getting the stop signal. @@ -140,6 +139,16 @@ static void guest_code(size_t nr_lpis) GUEST_DONE(); } +static void guest_stress_code(size_t nr_lpis) +{ + guest_setup_gic(); + local_irq_enable(); + + GUEST_SYNC(0); + + guest_wait_for_stop(); +} + static void setup_memslot(void) { gpa_t gpa_base; @@ -294,7 +303,7 @@ static void report_stats(struct timespec delta) pr_info("Rate: %.2f LPIs/sec\n", nr_lpis / time); } -static void run_test(void) +static void run_stress_test(void) { u32 nr_devices = test_data.nr_devices; u32 nr_vcpus = test_data.nr_cpus; @@ -326,10 +335,12 @@ static void run_test(void) for (i = 0; i < nr_vcpus; i++) kvm_pthread_join(vcpu_threads[i], NULL); + pthread_barrier_destroy(&test_setup_barrier); + report_stats(delta); } -static void setup_vm(void) +static void setup_vm(void *guest_code, handler_fn irq_handler) { int i; @@ -342,7 +353,7 @@ static void setup_vm(void) for (i = 0; i < test_data.nr_cpus; i++) vcpu_init_descriptor_tables(vcpus[i]); - vm_install_exception_handler(vm, VECTOR_IRQ_CURRENT, guest_irq_handler); + vm_install_exception_handler(vm, VECTOR_IRQ_CURRENT, irq_handler); setup_memslot(); @@ -358,12 +369,23 @@ static void destroy_vm(void) free(vcpus); } +static void test_lpi_stress(void) +{ + test_data = stress_args; + + setup_vm(guest_stress_code, guest_irq_handler); + + run_stress_test(); + + destroy_vm(); +} + static void pr_usage(const char *name) { pr_info("%s [-v NR_VCPUS] [-d NR_DEVICES] [-e NR_EVENTS] [-i ITERS] -h\n", name); - pr_info(" -v:\tnumber of vCPUs (default: %u)\n", test_data.nr_cpus); - pr_info(" -d:\tnumber of devices (default: %u)\n", test_data.nr_devices); - pr_info(" -e:\tnumber of event IDs per device (default: %u)\n", test_data.nr_event_ids); + pr_info(" -v:\tnumber of vCPUs (default: %u)\n", stress_args.nr_cpus); + pr_info(" -d:\tnumber of devices (default: %u)\n", stress_args.nr_devices); + pr_info(" -e:\tnumber of event IDs per device (default: %u)\n", stress_args.nr_event_ids); pr_info(" -i:\tnumber of iterations (default: %lu)\n", nr_iterations); } @@ -377,13 +399,13 @@ int main(int argc, char **argv) while ((c = getopt(argc, argv, "hv:d:e:i:")) != -1) { switch (c) { case 'v': - test_data.nr_cpus = atoi(optarg); + stress_args.nr_cpus = atoi(optarg); break; case 'd': - test_data.nr_devices = atoi(optarg); + stress_args.nr_devices = atoi(optarg); break; case 'e': - test_data.nr_event_ids = atoi(optarg); + stress_args.nr_event_ids = atoi(optarg); break; case 'i': nr_iterations = strtoul(optarg, NULL, 0); @@ -395,16 +417,12 @@ int main(int argc, char **argv) } } - nr_threads = test_data.nr_cpus + test_data.nr_devices; + nr_threads = stress_args.nr_cpus + stress_args.nr_devices; if (nr_threads > get_nprocs()) pr_info("WARNING: running %u threads on %d CPUs; performance is degraded.\n", nr_threads, get_nprocs()); - setup_vm(); - - run_test(); - - destroy_vm(); + test_lpi_stress(); return 0; } From b5d08dcf25e7a22a7f52d9806c6c6db0c3354a0b Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Thu, 1 Oct 2026 08:11:00 +0100 Subject: [PATCH 0156/2102] KVM: arm64: selftests: Test MOVI and MOVALL on a pending LPI MOVI and MOVALL move the pending state of LPIs between redistributors, so a test of either has to make its LPI pending before the move. Add one to vgic_lpi_stress. vCPU0 and vCPU1 keep IRQs masked while LPI A is signalled to vCPU0 and LPI B to vCPU1, and each waits until ICC_HPPIR1_EL1 shows its LPI pending at the CPU interface. vCPU1 then moves A to vCPU2, with MOVI or with MAPC and MOVALL of vCPU0's collection. Once unmasked, A must be taken on vCPU2 only and B on vCPU1 only. KVM retargets A at the MAPC already, so the MOVALL case catches a MOVALL that moves too much: without commit 751f4641560b ("KVM: arm64: vgic-its: Fix MOVALL handling of source redistributor"), B goes to vCPU2 as well. vCPU1 issues the commands, so its own ITS accesses, which exit to KVM, move a wrongly retargeted B off it before it unmasks. Both cases run after the stress test, so a kernel that fails them still gets the stress run, and the command-line options still configure only the stress test. Assisted-by: LLM Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261001071100.190013-4-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- .../selftests/kvm/arm64/vgic_lpi_stress.c | 196 +++++++++++++++++- 1 file changed, 195 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c b/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c index fc24e375315a6b..71edefc5aca445 100644 --- a/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c +++ b/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 /* - * vgic_lpi_stress - Stress test for KVM's ITS emulation + * vgic_lpi_stress - Tests for KVM's ITS emulation * * Copyright (c) 2024 Google LLC */ @@ -28,11 +28,17 @@ static struct kvm_vm *vm; static struct kvm_vcpu **vcpus; static int its_fd; +enum move_cmd { + MOVE_MOVI, + MOVE_MAPC_MOVALL, +}; + struct test_data { bool request_vcpus_stop; u32 nr_cpus; u32 nr_devices; u32 nr_event_ids; + enum move_cmd move_cmd; gpa_t device_table; gpa_t collection_table; @@ -380,6 +386,191 @@ static void test_lpi_stress(void) destroy_vm(); } +/* + * Pending move: A is pending at vCPU0's CPU interface and B at vCPU1's, both + * vCPUs with IRQs masked, when vCPU1 moves A to vCPU2. Once unmasked, A must + * be taken on vCPU2 only, and B on vCPU1 only. + */ +#define MOVE_NR_VCPUS 3 +#define MOVE_NR_LPIS 2 +#define MOVE_DEVICE 0 + +/* guest_setup_its_mappings() maps event N to vCPU N's collection */ +#define LPI_A 0 +#define LPI_B 1 +#define SRC_VCPU 0 +#define B_VCPU 1 +#define DST_VCPU 2 + +static atomic_uint lpi_taken[MOVE_NR_VCPUS][MOVE_NR_LPIS]; +static atomic_bool lpi_a_pending, lpi_a_moved, vcpu_unmasked[MOVE_NR_VCPUS]; + +static void guest_count_irq_handler(struct ex_regs *regs) +{ + u32 intid = gic_get_and_ack_irq(); + + if (intid == IAR_SPURIOUS) + return; + + GUEST_ASSERT(intid >= GIC_LPI_OFFSET && intid < GIC_LPI_OFFSET + MOVE_NR_LPIS); + atomic_fetch_add(&lpi_taken[guest_get_vcpuid()][intid - GIC_LPI_OFFSET], 1); + gic_set_eoi(intid); +} + +/* HPPIR shows an LPI pending at this CPU interface even with IRQs masked */ +static bool guest_lpi_pending(u32 lpi) +{ + return (read_sysreg_s(SYS_ICC_HPPIR1_EL1) & GENMASK(23, 0)) == GIC_LPI_OFFSET + lpi; +} + +static void guest_wait_pending(u32 lpi) +{ + while (!guest_lpi_pending(lpi)) + cpu_relax(); +} + +/* An LPI still pending here is taken before the host is told to check */ +static void guest_unmask(u32 lpi) +{ + local_irq_enable(); + + while (guest_lpi_pending(lpi)) + cpu_relax(); + + atomic_store(&vcpu_unmasked[guest_get_vcpuid()], true); +} + +static void guest_move_lpi_a(void) +{ + void *cmdq = test_data.cmdq_base_va; + + if (test_data.move_cmd == MOVE_MOVI) { + its_send_movi_cmd(cmdq, MOVE_DEVICE, LPI_A, DST_VCPU); + } else { + its_send_mapc_cmd(cmdq, DST_VCPU, SRC_VCPU, true); + /* The GICv3 spec's MAPC description requires this SYNC before MOVALL */ + its_send_sync_cmd(cmdq, SRC_VCPU); + its_send_movall_cmd(cmdq, SRC_VCPU, DST_VCPU); + } + + /* Complete the move at both redistributors before vCPU0 unmasks */ + its_send_sync_cmd(cmdq, SRC_VCPU); + its_send_sync_cmd(cmdq, DST_VCPU); +} + +static void guest_pending_move_code(void) +{ + u32 cpuid = guest_get_vcpuid(); + + guest_setup_gic(); + + if (cpuid == DST_VCPU) + local_irq_enable(); + + GUEST_SYNC(0); + + if (cpuid == SRC_VCPU) { + guest_wait_pending(LPI_A); + atomic_store(&lpi_a_pending, true); + + while (!atomic_load(&lpi_a_moved)) + cpu_relax(); + guest_unmask(LPI_A); + } else if (cpuid == B_VCPU) { + guest_wait_pending(LPI_B); + + while (!atomic_load(&lpi_a_pending)) + cpu_relax(); + guest_move_lpi_a(); + atomic_store(&lpi_a_moved, true); + guest_unmask(LPI_B); + } + + guest_wait_for_stop(); +} + +static unsigned int nr_lpis_taken(atomic_uint (*taken)[MOVE_NR_LPIS]) +{ + unsigned int nr = 0; + int vcpu, lpi; + + for (vcpu = 0; vcpu < MOVE_NR_VCPUS; vcpu++) + for (lpi = 0; lpi < MOVE_NR_LPIS; lpi++) + nr += atomic_load(&taken[vcpu][lpi]); + + return nr; +} + +static bool pending_move_done(atomic_uint (*taken)[MOVE_NR_LPIS], atomic_bool *unmasked) +{ + return nr_lpis_taken(taken) >= MOVE_NR_LPIS && + atomic_load(&unmasked[SRC_VCPU]) && atomic_load(&unmasked[B_VCPU]); +} + +static void check_lpi_taken(atomic_uint (*taken)[MOVE_NR_LPIS], int lpi, int want_vcpu) +{ + const char *cmd = test_data.move_cmd == MOVE_MOVI ? "MOVI" : "MAPC+MOVALL"; + unsigned int nr[MOVE_NR_VCPUS]; + bool ok = true; + int vcpu; + + for (vcpu = 0; vcpu < MOVE_NR_VCPUS; vcpu++) { + nr[vcpu] = atomic_load(&taken[vcpu][lpi]); + ok &= nr[vcpu] == (vcpu == want_vcpu); + } + + TEST_ASSERT(ok, "%s: LPI %c taken %u/%u/%u times on vCPU0/1/2, expected once on vCPU%d", + cmd, 'A' + lpi, nr[0], nr[1], nr[2], want_vcpu); +} + +static void run_pending_move_test(void) +{ + atomic_uint (*taken)[MOVE_NR_LPIS] = addr_gva2hva(vm, (gva_t)lpi_taken); + atomic_bool *unmasked = addr_gva2hva(vm, (gva_t)vcpu_unmasked); + pthread_t vcpu_threads[MOVE_NR_VCPUS]; + int i; + + pthread_barrier_init(&test_setup_barrier, NULL, MOVE_NR_VCPUS + 1); + + for (i = 0; i < MOVE_NR_VCPUS; i++) + kvm_pthread_create(&vcpu_threads[i], NULL, vcpu_worker_thread, vcpus[i]); + + pthread_barrier_wait(&test_setup_barrier); + + signal_lpi(MOVE_DEVICE, LPI_A); + signal_lpi(MOVE_DEVICE, LPI_B); + + for (i = 0; i < 10000 && !pending_move_done(taken, unmasked); i++) + usleep(1000); + + /* Check first: a vCPU still waiting for its LPI never sees the stop */ + check_lpi_taken(taken, LPI_A, DST_VCPU); + check_lpi_taken(taken, LPI_B, B_VCPU); + + write_guest_global(vm, test_data.request_vcpus_stop, true); + + for (i = 0; i < MOVE_NR_VCPUS; i++) + kvm_pthread_join(vcpu_threads[i], NULL); + + pthread_barrier_destroy(&test_setup_barrier); +} + +static void test_pending_move(enum move_cmd move_cmd) +{ + test_data = (struct test_data) { + .nr_cpus = MOVE_NR_VCPUS, + .nr_devices = 1, + .nr_event_ids = MOVE_NR_LPIS, + .move_cmd = move_cmd, + }; + + setup_vm(guest_pending_move_code, guest_count_irq_handler); + + run_pending_move_test(); + + destroy_vm(); +} + static void pr_usage(const char *name) { pr_info("%s [-v NR_VCPUS] [-d NR_DEVICES] [-e NR_EVENTS] [-i ITERS] -h\n", name); @@ -424,5 +615,8 @@ int main(int argc, char **argv) test_lpi_stress(); + test_pending_move(MOVE_MOVI); + test_pending_move(MOVE_MAPC_MOVALL); + return 0; } From 168cae7e87463c34758db2b51537937a29b753f1 Mon Sep 17 00:00:00 2001 From: Hung-Chun Tseng Date: Wed, 21 Oct 2026 21:21:30 +0800 Subject: [PATCH 0157/2102] reset: spacemit: Fix the RCPU2 PWM reset registers Every entry in k1_rcpu2_resets[] uses RCPU2_PWM9_CLK_RST, so asserting or deasserting the reset of any RCPU2 PWM from 0 to 8 acts on PWM9 instead. Each PWM has its own register, RCPU2_PWMn_CLK_RST at offset 4 * n, as k1-syscon.h already defines. On a Milk-V Jupiter running the vendor kernel, which uses RCPU2 PWM2 for the fan, the RCPU2 registers read: 0x00: 0x4 0x04: 0x4 0x08: 0x1 0x0c: 0x4 ... 0x24: 0x4 Only PWM2's register has its reset deasserted, which matches one register per PWM. Use the matching register for each reset. No in-tree device tree uses the RCPU2 PWMs yet, so this has no effect on current boards, but it would break the first one that does. Build-tested only (riscv defconfig, W=1); the fix could not be tested at runtime, as mainline has no RCPU2 PWM node to exercise it. Fixes: c479d7cf06c3 ("reset: spacemit: add support for SpacemiT CCU resets") Signed-off-by: Hung-Chun Tseng Reviewed-by: Yixun Lan Reviewed-by: Troy Mitchell Reviewed-by: Philipp Zabel Signed-off-by: Philipp Zabel --- drivers/reset/spacemit/reset-spacemit-k1.c | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/drivers/reset/spacemit/reset-spacemit-k1.c b/drivers/reset/spacemit/reset-spacemit-k1.c index 8f3b5329ea5f62..dbd783c138b1b1 100644 --- a/drivers/reset/spacemit/reset-spacemit-k1.c +++ b/drivers/reset/spacemit/reset-spacemit-k1.c @@ -154,15 +154,15 @@ static const struct ccu_reset_controller_data k1_rcpu_reset_data = { }; static const struct ccu_reset_data k1_rcpu2_resets[] = { - [RESET_RCPU2_PWM0] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM1] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM2] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM3] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM4] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM5] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM6] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM7] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM8] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM0] = RESET_DATA(RCPU2_PWM0_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM1] = RESET_DATA(RCPU2_PWM1_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM2] = RESET_DATA(RCPU2_PWM2_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM3] = RESET_DATA(RCPU2_PWM3_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM4] = RESET_DATA(RCPU2_PWM4_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM5] = RESET_DATA(RCPU2_PWM5_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM6] = RESET_DATA(RCPU2_PWM6_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM7] = RESET_DATA(RCPU2_PWM7_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM8] = RESET_DATA(RCPU2_PWM8_CLK_RST, BIT(2), BIT(0)), [RESET_RCPU2_PWM9] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), }; From 192a20f6e105e679c48e98c66af6336d37095f09 Mon Sep 17 00:00:00 2001 From: Wei-Lin Chang Date: Thu, 29 Oct 2026 15:37:28 -0700 Subject: [PATCH 0158/2102] KVM: arm64: nv: Don't advertise FEAT_LPA2 for guest stage-1 There is no FEAT_LPA2 support for NV guests as of now, but we missed limiting it for the non-stage-2 granule size fields (TGRAN4, TGRAN16) in ID_AA64MMFR0_EL1. Add the sanitisation. Fixes: 9f75b6d447d7 ("KVM: arm64: nv: Filter out unsupported features from ID regs") Signed-off-by: Wei-Lin Chang Cc: stable@vger.kernel.org Signed-off-by: Oliver Upton Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Link: https://patch.msgid.link/20261029223732.103785-2-oupton@kernel.org Signed-off-by: Marc Zyngier --- arch/arm64/kvm/nested.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/arch/arm64/kvm/nested.c b/arch/arm64/kvm/nested.c index 4d83281a7a28b4..cd0dabcf3f81c5 100644 --- a/arch/arm64/kvm/nested.c +++ b/arch/arm64/kvm/nested.c @@ -1875,6 +1875,17 @@ u64 limit_nv_id_reg(struct kvm *kvm, u32 reg, u64 val) /* Hide CNTPOFF if present */ val = ID_REG_LIMIT_FIELD_ENUM(val, ID_AA64MMFR0_EL1, ECV, IMP); + /* NV does not support FEAT_LPA2. */ + if (SYS_FIELD_GET(ID_AA64MMFR0_EL1, TGRAN4, val) == ID_AA64MMFR0_EL1_TGRAN4_52_BIT) { + val &= ~ID_AA64MMFR0_EL1_TGRAN4; + val |= SYS_FIELD_PREP_ENUM(ID_AA64MMFR0_EL1, TGRAN4, IMP); + } + + if (SYS_FIELD_GET(ID_AA64MMFR0_EL1, TGRAN16, val) == ID_AA64MMFR0_EL1_TGRAN16_52_BIT) { + val &= ~ID_AA64MMFR0_EL1_TGRAN16; + val |= SYS_FIELD_PREP_ENUM(ID_AA64MMFR0_EL1, TGRAN16, IMP); + } + /* Disallow unsupported S2 page sizes */ switch (PAGE_SIZE) { case SZ_64K: From 2942baff3a951e0805d0ce9608f318e21c7e3744 Mon Sep 17 00:00:00 2001 From: Wei-Lin Chang Date: Thu, 29 Oct 2026 15:37:29 -0700 Subject: [PATCH 0159/2102] arm64: sysreg: Add TCR_EL2 to sysreg infrastructure Convert TCR_EL2 to the sysreg infrastructure with data extracted from Registers.json of the BSD licenced AARCHMRS (AARCHMRS_OPENSOURCE_A_profile_FAT-2026-06). There are two formats of TCR_EL2 based on whether the effective value of HCR_EL2.E2H is 0 or 1. For the E2H == 1 case, prefix the macros with "VHE_". For the E2H == 0 case, the macros are left unprefixed. Reviewed-by: Mark Brown Signed-off-by: Wei-Lin Chang Signed-off-by: Oliver Upton Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Link: https://patch.msgid.link/20261029223732.103785-3-oupton@kernel.org Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/kvm_arm.h | 13 ---- arch/arm64/include/asm/sysreg.h | 1 - arch/arm64/tools/sysreg | 125 +++++++++++++++++++++++++++++++ 3 files changed, 125 insertions(+), 14 deletions(-) diff --git a/arch/arm64/include/asm/kvm_arm.h b/arch/arm64/include/asm/kvm_arm.h index ba0062849be908..3e1c9e31028e91 100644 --- a/arch/arm64/include/asm/kvm_arm.h +++ b/arch/arm64/include/asm/kvm_arm.h @@ -45,19 +45,6 @@ #define MPAMHCR_HOST_FLAGS 0 /* TCR_EL2 Registers bits */ -#define TCR_EL2_DS (1UL << 32) -#define TCR_EL2_RES1 ((1U << 31) | (1 << 23)) -#define TCR_EL2_HPD (1 << 24) -#define TCR_EL2_HA (1 << 21) -#define TCR_EL2_TBI (1 << 20) -#define TCR_EL2_PS_SHIFT 16 -#define TCR_EL2_PS_MASK (7 << TCR_EL2_PS_SHIFT) -#define TCR_EL2_PS_40B (2 << TCR_EL2_PS_SHIFT) -#define TCR_EL2_TG0_MASK TCR_TG0_MASK -#define TCR_EL2_SH0_MASK TCR_SH0_MASK -#define TCR_EL2_ORGN0_MASK TCR_ORGN0_MASK -#define TCR_EL2_IRGN0_MASK TCR_IRGN0_MASK -#define TCR_EL2_T0SZ_MASK 0x3f #define TCR_EL2_MASK (TCR_EL2_TG0_MASK | TCR_EL2_SH0_MASK | \ TCR_EL2_ORGN0_MASK | TCR_EL2_IRGN0_MASK) diff --git a/arch/arm64/include/asm/sysreg.h b/arch/arm64/include/asm/sysreg.h index e3b60ee0302301..7cba1216efd2e7 100644 --- a/arch/arm64/include/asm/sysreg.h +++ b/arch/arm64/include/asm/sysreg.h @@ -510,7 +510,6 @@ #define SYS_TTBR0_EL2 sys_reg(3, 4, 2, 0, 0) #define SYS_TTBR1_EL2 sys_reg(3, 4, 2, 0, 1) -#define SYS_TCR_EL2 sys_reg(3, 4, 2, 0, 2) #define SYS_VTTBR_EL2 sys_reg(3, 4, 2, 1, 0) #define SYS_HAFGRTR_EL2 sys_reg(3, 4, 3, 1, 6) diff --git a/arch/arm64/tools/sysreg b/arch/arm64/tools/sysreg index 997c62ab72e686..28d319e63d8f10 100644 --- a/arch/arm64/tools/sysreg +++ b/arch/arm64/tools/sysreg @@ -5604,6 +5604,131 @@ Res0 6 Field 5:0 T0SZ EndSysreg +Sysreg TCR_EL2 3 4 2 0 2 +Prefix VHE +Res0 63:62 +Field 61 MTX1 +Field 60 MTX0 +Field 59 DS +Field 58 TCMA1 +Field 57 TCMA0 +Field 56 E0PD1 +Field 55 E0PD0 +Field 54 NFD1 +Field 53 NFD0 +Field 52 TBID1 +Field 51 TBID0 +Field 50 HWU162 +Field 49 HWU161 +Field 48 HWU160 +Field 47 HWU159 +Field 46 HWU062 +Field 45 HWU061 +Field 44 HWU060 +Field 43 HWU059 +Field 42 HPD1 +Field 41 HPD0 +Field 40 HD +Field 39 HA +Field 38 TBI1 +Field 37 TBI0 +Field 36 AS +Res0 35 +Field 34:32 IPS +Enum 31:30 TG1 + 0b01 16K + 0b10 4K + 0b11 64K +EndEnum +Enum 29:28 SH1 + 0b00 NONE + 0b10 OUTER + 0b11 INNER +EndEnum +Enum 27:26 ORGN1 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Enum 25:24 IRGN1 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Field 23 EPD1 +Field 22 A1 +Field 21:16 T1SZ +Enum 15:14 TG0 + 0b00 4K + 0b01 64K + 0b10 16K +EndEnum +Enum 13:12 SH0 + 0b00 NONE + 0b10 OUTER + 0b11 INNER +EndEnum +Enum 11:10 ORGN0 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Enum 9:8 IRGN0 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Field 7 EPD0 +Res0 6 +Field 5:0 T0SZ +EndPrefix +Res0 63:34 +Field 33 MTX +Field 32 DS +Res1 31 +Field 30 TCMA +Field 29 TBID +Field 28 HWU62 +Field 27 HWU61 +Field 26 HWU60 +Field 25 HWU59 +Field 24 HPD +Res1 23 +Field 22 HD +Field 21 HA +Field 20 TBI +Res0 19 +Field 18:16 PS +Enum 15:14 TG0 + 0b00 4K + 0b01 64K + 0b10 16K +EndEnum +Enum 13:12 SH0 + 0b00 NONE + 0b10 OUTER + 0b11 INNER +EndEnum +Enum 11:10 ORGN0 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Enum 9:8 IRGN0 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Res0 7:6 +Field 5:0 T0SZ +EndSysreg + Sysreg TCR_EL12 3 5 2 0 2 Mapping TCR_EL1 EndSysreg From 81755e75f86c490bc9296f6cec0cd221edecaa27 Mon Sep 17 00:00:00 2001 From: Marc Zyngier Date: Thu, 29 Oct 2026 15:37:30 -0700 Subject: [PATCH 0160/2102] KVM: arm64: Reset TCR_EL2 according to guest's E2H mode Previously vCPU TCR_EL2's reset value didn't consider TCR_EL2's different formats based on the value of HCR_EL2.E2H. It always resets to the E2H == 0 version. This didn't cause any problem because the bits set in the E2H == 0 version (TCR_EL2_RES1) all reset to UNKNOWN for E2H == 1 per the architecture. Still, it's better to fix it. Choose the correct reset value by checking KVM_ARM_VCPU_HAS_EL2_E2H0. Signed-off-by: Wei-Lin Chang Reviewed-by: Joey Gouly Signed-off-by: Oliver Upton Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Link: https://patch.msgid.link/20261029223732.103785-4-oupton@kernel.org Signed-off-by: Marc Zyngier --- arch/arm64/kvm/sys_regs.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/arch/arm64/kvm/sys_regs.c b/arch/arm64/kvm/sys_regs.c index 850eba167aad6a..601eb06a2c877a 100644 --- a/arch/arm64/kvm/sys_regs.c +++ b/arch/arm64/kvm/sys_regs.c @@ -3275,6 +3275,14 @@ static u64 reset_mdcr(struct kvm_vcpu *vcpu, const struct sys_reg_desc *r) return vcpu->kvm->arch.nr_pmu_counters; } +static u64 reset_tcr_el2(struct kvm_vcpu *vcpu, const struct sys_reg_desc *r) +{ + __vcpu_assign_sys_reg(vcpu, r->reg, + vcpu_has_feature(vcpu, KVM_ARM_VCPU_HAS_EL2_E2H0) ? + TCR_EL2_RES1 : VHE_TCR_EL2_RES1); + return __vcpu_sys_reg(vcpu, r->reg); +} + /* * Architected system registers. * Important: Must be sorted ascending by Op0, Op1, CRn, CRm, Op2 @@ -3853,7 +3861,7 @@ static const struct sys_reg_desc sys_reg_descs[] = { EL2_REG(TTBR0_EL2, access_rw, reset_val, 0), EL2_REG(TTBR1_EL2, access_rw, reset_val, 0), - EL2_REG(TCR_EL2, access_rw, reset_val, TCR_EL2_RES1), + EL2_REG(TCR_EL2, access_rw, reset_tcr_el2, 0), EL2_REG_FILTERED(TCR2_EL2, access_rw, reset_val, TCR2_EL2_RES1, tcr2_el2_visibility), EL2_REG_VNCR(VTTBR_EL2, reset_val, 0), From 388faffbd371fd367d39535ad2aa07fbbd745c08 Mon Sep 17 00:00:00 2001 From: Wei-Lin Chang Date: Thu, 29 Oct 2026 15:37:31 -0700 Subject: [PATCH 0161/2102] KVM: arm64: Convert TCR_EL2 to config-driven sanitisation Feature dependencies of the fields in TCR_EL2 are extracted from Registers.json of the BSD licenced AARCHMRS (AARCHMRS_OPENSOURCE_A_profile_FAT-2026-06). Places where we slightly deviate from the above: - Stick to the ARM ARM M.c requirement for TCR_EL2.TCMA*, which only depends on FEAT_MTE2. This avoids updating ID_AA64PFR2_EL1 with new VMTE* definitions that we don't know the meaning of, as they aren't present in the ARM ARM yet. - Ignore TCR_EL2.DS's requirement of needing the effective value of TCR2_EL2.D128 be 0. This requires runtime detection of TCR2_EL2.D128 and we don't have D128 support yet. - TCR_EL2.AS is dependent on FEAT_ASID16, this information is missing from the json. Signed-off-by: Wei-Lin Chang Reviewed-by: Joey Gouly Signed-off-by: Oliver Upton Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Link: https://patch.msgid.link/20261029223732.103785-5-oupton@kernel.org Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/kvm_host.h | 2 +- arch/arm64/kvm/config.c | 112 ++++++++++++++++++++++++++++++ arch/arm64/kvm/nested.c | 4 ++ 3 files changed, 117 insertions(+), 1 deletion(-) diff --git a/arch/arm64/include/asm/kvm_host.h b/arch/arm64/include/asm/kvm_host.h index 97332ffcb1300e..4cf2f74239471d 100644 --- a/arch/arm64/include/asm/kvm_host.h +++ b/arch/arm64/include/asm/kvm_host.h @@ -600,7 +600,6 @@ enum vcpu_sysreg { HACR_EL2, /* Hypervisor Auxiliary Control Register */ TTBR0_EL2, /* Translation Table Base Register 0 (EL2) */ TTBR1_EL2, /* Translation Table Base Register 1 (EL2) */ - TCR_EL2, /* Translation Control Register (EL2) */ PIRE0_EL2, /* Permission Indirection Register 0 (EL2) */ PIR_EL2, /* Permission Indirection Register 1 (EL2) */ POR_EL2, /* Permission Overlay Register 2 (EL2) */ @@ -625,6 +624,7 @@ enum vcpu_sysreg { /* Anything from this can be RES0/RES1 sanitised */ MARKER(__SANITISED_REG_START__), SCTLR_EL2, /* System Control Register (EL2) */ + TCR_EL2, /* Translation Control Register (EL2) */ TCR2_EL2, /* Extended Translation Control Register (EL2) */ SCTLR2_EL2, /* System Control Register 2 (EL2) */ MDCR_EL2, /* Monitor Debug Configuration Register (EL2) */ diff --git a/arch/arm64/kvm/config.c b/arch/arm64/kvm/config.c index adaf26ab93b857..e295435a30b870 100644 --- a/arch/arm64/kvm/config.c +++ b/arch/arm64/kvm/config.c @@ -219,7 +219,9 @@ struct reg_feat_map_desc { #define FEAT_CPA2 ID_AA64ISAR3_EL1, CPA, CPA2 #define FEAT_ASID2 ID_AA64MMFR4_EL1, ASID2, IMP #define FEAT_MEC ID_AA64MMFR3_EL1, MEC, IMP +#define FEAT_HAF ID_AA64MMFR1_EL1, HAFDBS, AF #define FEAT_HAFT ID_AA64MMFR1_EL1, HAFDBS, HAFT +#define FEAT_HAFDBS ID_AA64MMFR1_EL1, HAFDBS, DBM #define FEAT_HDBSS ID_AA64MMFR1_EL1, HAFDBS, HDBSS #define FEAT_HPDS ID_AA64MMFR1_EL1, HPDS, IMP #define FEAT_HPDS2 ID_AA64MMFR1_EL1, HPDS, HPDS2 @@ -232,6 +234,10 @@ struct reg_feat_map_desc { #define FEAT_MixedEndEL0 ID_AA64MMFR0_EL1, BIGENDEL0, IMP #define FEAT_MTE_ASYNC ID_AA64PFR1_EL1, MTE_frac, ASYNC #define FEAT_MTE_STORE_ONLY ID_AA64PFR2_EL1, MTESTOREONLY, IMP +#define FEAT_MTE_CANONICAL_TAGS ID_AA64PFR1_EL1, MTEX, MTE4 +#define FEAT_MTE_NO_ADDRESS_TAGS ID_AA64PFR1_EL1, MTEX, MTE4 +#define FEAT_E0PD ID_AA64MMFR2_EL1, E0PD, IMP +#define FEAT_SVE ID_AA64PFR0_EL1, SVE, IMP #define FEAT_PAN ID_AA64MMFR1_EL1, PAN, IMP #define FEAT_PAN3 ID_AA64MMFR1_EL1, PAN, PAN3 #define FEAT_SSBS ID_AA64PFR1_EL1, SSBS, IMP @@ -244,6 +250,19 @@ struct reg_feat_map_desc { #define FEAT_GCIE ID_AA64PFR2_EL1, GCIE, IMP #define FEAT_NV3 ID_AA64MMFR4_EL1, NV_frac, NV3 +static bool feat_asid16(struct kvm *kvm) +{ + return kvm_has_feat_enum(kvm, ID_AA64MMFR0_EL1, ASIDBITS, 16); +} + +static bool feat_mte_no_addr_tags_or_canonical_tags(struct kvm *kvm) +{ + bool no_addr_tags = kvm_has_feat(kvm, FEAT_MTE_NO_ADDRESS_TAGS); + bool canonical_tags = kvm_has_feat(kvm, FEAT_MTE_CANONICAL_TAGS); + + return no_addr_tags || canonical_tags; +} + static bool not_feat_aa64el3(struct kvm *kvm) { return !kvm_has_feat(kvm, FEAT_AA64EL3); @@ -1080,6 +1099,91 @@ static const struct reg_bits_to_feat_map sctlr2_feat_map[] = { static const DECLARE_FEAT_MAP(sctlr2_desc, SCTLR2_EL1, sctlr2_feat_map, FEAT_SCTLR2); +static const struct reg_bits_to_feat_map vhe_tcr_el2_feat_map[] = { + NEEDS_FEAT(VHE_TCR_EL2_MTX1 | + VHE_TCR_EL2_MTX0, + feat_mte_no_addr_tags_or_canonical_tags), + NEEDS_FEAT(VHE_TCR_EL2_DS, feat_lpa2), + NEEDS_FEAT(VHE_TCR_EL2_TCMA1 | + VHE_TCR_EL2_TCMA0, + FEAT_MTE2), + NEEDS_FEAT(VHE_TCR_EL2_E0PD1 | + VHE_TCR_EL2_E0PD0, + FEAT_E0PD), + NEEDS_FEAT(VHE_TCR_EL2_NFD1 | + VHE_TCR_EL2_NFD0, + FEAT_SVE), + NEEDS_FEAT(VHE_TCR_EL2_TBID1 | + VHE_TCR_EL2_TBID0, + feat_pauth), + NEEDS_FEAT(VHE_TCR_EL2_HWU162 | + VHE_TCR_EL2_HWU161 | + VHE_TCR_EL2_HWU160 | + VHE_TCR_EL2_HWU159 | + VHE_TCR_EL2_HWU062 | + VHE_TCR_EL2_HWU061 | + VHE_TCR_EL2_HWU060 | + VHE_TCR_EL2_HWU059, + FEAT_HPDS2), + NEEDS_FEAT(VHE_TCR_EL2_HPD1 | + VHE_TCR_EL2_HPD0, + FEAT_HPDS), + NEEDS_FEAT(VHE_TCR_EL2_HD, FEAT_HAFDBS), + NEEDS_FEAT(VHE_TCR_EL2_HA, FEAT_HAF), + NEEDS_FEAT(VHE_TCR_EL2_AS, feat_asid16), + NEEDS_FEAT(VHE_TCR_EL2_TBI1 | + VHE_TCR_EL2_TBI0 | + VHE_TCR_EL2_IPS | + VHE_TCR_EL2_TG1 | + VHE_TCR_EL2_SH1 | + VHE_TCR_EL2_ORGN1 | + VHE_TCR_EL2_IRGN1 | + VHE_TCR_EL2_EPD1 | + VHE_TCR_EL2_A1 | + VHE_TCR_EL2_T1SZ | + VHE_TCR_EL2_TG0 | + VHE_TCR_EL2_SH0 | + VHE_TCR_EL2_ORGN0 | + VHE_TCR_EL2_IRGN0 | + VHE_TCR_EL2_EPD0 | + VHE_TCR_EL2_T0SZ, + FEAT_AA64EL2), + FORCE_RES0(VHE_TCR_EL2_RES0), + FORCE_RES1(VHE_TCR_EL2_RES1), +}; + +static const DECLARE_FEAT_MAP(vhe_tcr_el2_desc, VHE_TCR_EL2, + vhe_tcr_el2_feat_map, FEAT_AA64EL2); + +static const struct reg_bits_to_feat_map tcr_el2_feat_map[] = { + NEEDS_FEAT(TCR_EL2_MTX, + feat_mte_no_addr_tags_or_canonical_tags), + NEEDS_FEAT(TCR_EL2_DS, feat_lpa2), + NEEDS_FEAT(TCR_EL2_TCMA, FEAT_MTE2), + NEEDS_FEAT(TCR_EL2_TBID, feat_pauth), + NEEDS_FEAT(TCR_EL2_HWU62 | + TCR_EL2_HWU61 | + TCR_EL2_HWU60 | + TCR_EL2_HWU59, + FEAT_HPDS2), + NEEDS_FEAT(TCR_EL2_HPD, FEAT_HPDS), + NEEDS_FEAT(TCR_EL2_HD, FEAT_HAFDBS), + NEEDS_FEAT(TCR_EL2_HA, FEAT_HAF), + NEEDS_FEAT(TCR_EL2_TBI | + TCR_EL2_PS | + TCR_EL2_TG0 | + TCR_EL2_SH0 | + TCR_EL2_ORGN0 | + TCR_EL2_IRGN0 | + TCR_EL2_T0SZ, + FEAT_AA64EL2), + FORCE_RES0(TCR_EL2_RES0), + FORCE_RES1(TCR_EL2_RES1), +}; + +static const DECLARE_FEAT_MAP(tcr_el2_desc, TCR_EL2, + tcr_el2_feat_map, FEAT_AA64EL2); + static const struct reg_bits_to_feat_map tcr2_el2_feat_map[] = { NEEDS_FEAT_FLAG(TCR2_EL2_FNG1 | TCR2_EL2_FNG0 | @@ -1442,6 +1546,8 @@ void __init check_feature_map(void) check_reg_desc(&hcr_desc); check_reg_desc(&nvhcr_desc); check_reg_desc(&sctlr2_desc); + check_reg_desc(&vhe_tcr_el2_desc); + check_reg_desc(&tcr_el2_desc); check_reg_desc(&tcr2_el2_desc); check_reg_desc(&sctlr_el1_desc); check_reg_desc(&sctlr_el2_desc); @@ -1689,6 +1795,12 @@ struct resx get_reg_fixed_bits(struct kvm *kvm, enum vcpu_sysreg reg) case SCTLR2_EL2: resx = compute_reg_resx_bits(kvm, &sctlr2_desc, 0, 0); break; + case TCR_EL2: + if (kvm_has_feat(kvm, FEAT_E2H0)) + resx = compute_reg_resx_bits(kvm, &tcr_el2_desc, 0, 0); + else + resx = compute_reg_resx_bits(kvm, &vhe_tcr_el2_desc, 0, 0); + break; case TCR2_EL2: resx = compute_reg_resx_bits(kvm, &tcr2_el2_desc, 0, 0); break; diff --git a/arch/arm64/kvm/nested.c b/arch/arm64/kvm/nested.c index cd0dabcf3f81c5..78fa433774c6eb 100644 --- a/arch/arm64/kvm/nested.c +++ b/arch/arm64/kvm/nested.c @@ -2101,6 +2101,10 @@ int kvm_init_nv_sysregs(struct kvm_vcpu *vcpu) resx = get_reg_fixed_bits(kvm, HFGITR2_EL2); set_sysreg_masks(kvm, HFGITR2_EL2, resx); + /* TCR_EL2 */ + resx = get_reg_fixed_bits(kvm, TCR_EL2); + set_sysreg_masks(kvm, TCR_EL2, resx); + /* TCR2_EL2 */ resx = get_reg_fixed_bits(kvm, TCR2_EL2); set_sysreg_masks(kvm, TCR2_EL2, resx); From 361564a8d4305100ee4140ff7b345d1bf2c1a1b2 Mon Sep 17 00:00:00 2001 From: Oliver Upton Date: Thu, 29 Oct 2026 15:37:32 -0700 Subject: [PATCH 0162/2102] KVM: arm64: nv: Correctly compute the effective TCR_EL1 for nVHE TCR_EL2 It would appear that nVHE hypervisor support has a few warts which shouldn't come as a surprise. Several fields in TCR_EL2 for features supported in the VM (TCR_EL2.HA for example) are not correctly propagated to the effective value of TCR_EL1. Forward fields in bulk from nVHE TCR_EL2 to the effective TCR_EL1, relying on config-based sanitisation to enforce the RESx behavior of unsupported features. Deal with the slightly annoying case where the E2H==0 bitfield names are not annotated by TTBR like they are in E2H==1. Cc: stable@vger.kernel.org # v6.18+ Fixes: d5bbb76f4474 ("KVM: arm64: nv: Expose hardware access flag management to NV guests") Fixes: 3606e0b2e462 ("KVM: arm64: nv: Add non-VHE-EL2->EL1 translation helpers") Signed-off-by: Oliver Upton Reviewed-by: Wei-Lin Chang Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Link: https://patch.msgid.link/20261029223732.103785-6-oupton@kernel.org Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/kvm_nested.h | 38 ++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/arch/arm64/include/asm/kvm_nested.h b/arch/arm64/include/asm/kvm_nested.h index 0f899addafa8b4..27ec73da02c601 100644 --- a/arch/arm64/include/asm/kvm_nested.h +++ b/arch/arm64/include/asm/kvm_nested.h @@ -20,16 +20,36 @@ static inline u64 tcr_el2_ps_to_tcr_el1_ips(u64 tcr_el2) return (u64)FIELD_GET(TCR_EL2_PS_MASK, tcr_el2) << TCR_IPS_SHIFT; } -static inline u64 translate_tcr_el2_to_tcr_el1(u64 tcr) +#define __xlate_tcr_nvhe_to_vhe(nfld, vfld, nvhe, vhe) \ + FIELD_MODIFY(VHE_TCR_EL2_##vfld, vhe, FIELD_GET(TCR_EL2_##nfld, *(nvhe))) + +#define __xlate_tcr_nvhe_to_vhe_field(fld, nvhe, vhe) \ + __xlate_tcr_nvhe_to_vhe(fld, fld, nvhe, vhe) + +static inline u64 translate_tcr_el2_to_tcr_el1(u64 nvhe) { - return TCR_EPD1_MASK | /* disable TTBR1_EL1 */ - ((tcr & TCR_EL2_DS) ? TCR_DS : 0) | - ((tcr & TCR_EL2_TBI) ? TCR_TBI0 : 0) | - tcr_el2_ps_to_tcr_el1_ips(tcr) | - (tcr & TCR_EL2_TG0_MASK) | - (tcr & TCR_EL2_ORGN0_MASK) | - (tcr & TCR_EL2_IRGN0_MASK) | - (tcr & TCR_EL2_T0SZ_MASK); + u64 vhe = VHE_TCR_EL2_EPD1 | /* disable TTBR1_EL1 */ + tcr_el2_ps_to_tcr_el1_ips(nvhe); + + __xlate_tcr_nvhe_to_vhe(MTX, MTX0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(TCMA, TCMA0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(TBID, TBID0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(HWU62, HWU062, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(HWU61, HWU061, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(HWU60, HWU060, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(HWU59, HWU059, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(HPD, HPD0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(TBI, TBI0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( DS, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( HA, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( HD, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( TG0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( SH0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( ORGN0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( IRGN0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( T0SZ, &nvhe, &vhe); + + return vhe; } static inline u64 translate_cptr_el2_to_cpacr_el1(u64 cptr_el2) From 0e24f9db2ebedc271add0c5dbf2821b8f8a0ab06 Mon Sep 17 00:00:00 2001 From: Xuheng Li Date: Wed, 28 Oct 2026 23:02:10 +0000 Subject: [PATCH 0163/2102] KVM: arm64: Add an ISB after mapping a hyp fixmap slot fixmap_map_slot() installs a valid PTE for the CPU's fixmap slot (or the fixblock slot) and issues a DSB ISHST before returning the slot's VA, which the caller then accesses. It does not issue an ISB. The DSB guarantees that the PTE write has completed, but without a context synchronization event the architecture does not guarantee that a later access on the same CPU uses the new entry: its translation may have been performed speculatively while the slot was still invalid, in which case the access takes a translation fault. At EL2 that fault ends in hyp_panic(). The clear side, fixmap_clear_slot(), already ends with an ISB. A litmus test of the same shape (map the slot, DSB ISHST, load through it) faulted on a Cortex-A72 in 2 out of 100M runs. Arm's herd7 model with -variant vmsa also allows the fault, and forbids it once the ISB is added. Add the missing ISB. This covers both hyp_fixmap_map() and hyp_fixblock_map(), which share fixmap_map_slot(). Fixes: aa6948f82f0b ("KVM: arm64: Add per-cpu fixmap infrastructure at EL2") Cc: stable@vger.kernel.org Signed-off-by: Xuheng Li Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Reviewed-by: Oliver Upton Link: https://patch.msgid.link/20261028-fixmap-isb-v1-1-6c9f0f9cb810@cs.columbia.edu Signed-off-by: Marc Zyngier --- arch/arm64/kvm/hyp/nvhe/mm.c | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm64/kvm/hyp/nvhe/mm.c b/arch/arm64/kvm/hyp/nvhe/mm.c index b95d98cfe57df9..83b74c5223c385 100644 --- a/arch/arm64/kvm/hyp/nvhe/mm.c +++ b/arch/arm64/kvm/hyp/nvhe/mm.c @@ -316,6 +316,7 @@ static void *fixmap_map_slot(struct hyp_fixmap_slot *slot, phys_addr_t phys) pte |= kvm_phys_to_pte(phys) | KVM_PTE_VALID; WRITE_ONCE(*ptep, pte); dsb(ishst); + isb(); return (void *)slot->addr; } From a511905b3c0d6e73afcc4016b2eddc159703060e Mon Sep 17 00:00:00 2001 From: Vincent Donnefort Date: Mon, 26 Oct 2026 16:39:35 +0000 Subject: [PATCH 0164/2102] KVM: arm64: Make __vgic_v3_init_lrs HVC always available The __vgic_v3_init_lrs hypercall only resets the vGIC LRs. Those registers are expected to be 0 when the host is running. As a consequence, it is completely safe to make it available at all times, even when pKVM is enabled and the host was deprivileged. Fixes: 057bed206f70 ("KVM: arm64: Disable privileged hypercalls after pKVM finalisation") Tested-by: Fuad Tabba Reviewed-by: Fuad Tabba Signed-off-by: Vincent Donnefort Link: https://patch.msgid.link/20261026163937.963087-2-vdonnefort@google.com Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/kvm_asm.h | 2 +- arch/arm64/kvm/hyp/nvhe/hyp-main.c | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/arch/arm64/include/asm/kvm_asm.h b/arch/arm64/include/asm/kvm_asm.h index abda476e023deb..8c585478938ee7 100644 --- a/arch/arm64/include/asm/kvm_asm.h +++ b/arch/arm64/include/asm/kvm_asm.h @@ -60,7 +60,6 @@ enum __kvm_host_smccc_func { __KVM_HOST_SMCCC_FUNC___pkvm_create_private_mapping, __KVM_HOST_SMCCC_FUNC___pkvm_cpu_set_vector, __KVM_HOST_SMCCC_FUNC___kvm_enable_ssbs, - __KVM_HOST_SMCCC_FUNC___vgic_v3_init_lrs, __KVM_HOST_SMCCC_FUNC___vgic_v3_get_gic_config, __KVM_HOST_SMCCC_FUNC___pkvm_hyp_alloc_selftest, __KVM_HOST_SMCCC_FUNC___vgic_v5_make_resident, @@ -91,6 +90,7 @@ enum __kvm_host_smccc_func { __KVM_HOST_SMCCC_FUNC___tracing_reset, __KVM_HOST_SMCCC_FUNC___tracing_enable_event, __KVM_HOST_SMCCC_FUNC___tracing_write_event, + __KVM_HOST_SMCCC_FUNC___vgic_v3_init_lrs, __KVM_HOST_SMCCC_FUNC___vgic_v3_save_aprs, __KVM_HOST_SMCCC_FUNC___vgic_v3_restore_vmcr_aprs, __KVM_HOST_SMCCC_FUNC___pkvm_hyp_topup, diff --git a/arch/arm64/kvm/hyp/nvhe/hyp-main.c b/arch/arm64/kvm/hyp/nvhe/hyp-main.c index 179d7c8277b883..0e1c05fd9ed1de 100644 --- a/arch/arm64/kvm/hyp/nvhe/hyp-main.c +++ b/arch/arm64/kvm/hyp/nvhe/hyp-main.c @@ -1197,7 +1197,8 @@ DEFINE_KVM_HOST_HCALL0(u64, __vgic_v3_get_gic_config) DEFINE_KVM_HOST_HCALL0(void, __vgic_v3_init_lrs) { - __vgic_v3_init_lrs(); + if (hyp_gicv3_nr_lr) + __vgic_v3_init_lrs(); } DEFINE_KVM_HOST_HCALL(void, __vgic_v3_save_aprs, @@ -1547,7 +1548,6 @@ static const hcall_t host_hcall[] = { HANDLE_FUNC(__pkvm_create_private_mapping), HANDLE_FUNC(__pkvm_cpu_set_vector), HANDLE_FUNC(__kvm_enable_ssbs), - HANDLE_FUNC(__vgic_v3_init_lrs), HANDLE_FUNC(__vgic_v3_get_gic_config), HANDLE_FUNC(__pkvm_hyp_alloc_selftest), HANDLE_FUNC(__pkvm_prot_finalize), @@ -1569,6 +1569,7 @@ static const hcall_t host_hcall[] = { HANDLE_FUNC(__tracing_reset), HANDLE_FUNC(__tracing_enable_event), HANDLE_FUNC(__tracing_write_event), + HANDLE_FUNC(__vgic_v3_init_lrs), HANDLE_FUNC(__vgic_v3_save_aprs), HANDLE_FUNC(__vgic_v3_restore_vmcr_aprs), HANDLE_FUNC(__vgic_v5_make_resident), From 91e496a1e474d56e296f3997ed2a34185e9a1c0c Mon Sep 17 00:00:00 2001 From: Vincent Donnefort Date: Mon, 26 Oct 2026 16:39:36 +0000 Subject: [PATCH 0165/2102] KVM: arm64: pkvm: Fix missing reset of GICv3 LRs The vGIC LRs are architecturally UNKNOWN when the CPU boots or resumes. However, in protected mode, only the used ones are reset, because the HVC __vgic_v3_init_lrs() is never called: * During boot, vgic_present is only set in init_subsystems(), after cpu_hyp_init() was called. * During CPU hotplug, kvm_arch_enable_virtualization_cpu() never calls it either because kvm_hyp_initialized is always set. * During CPU resume, no notifier is registered for pKVM. If left uninitialised, those registers may inject spurious interrupts or worse, if EOI is set, livelock the vCPU, since no one is in position to clear it. First, return the error of __hyp_reset_vectors(). On an error, we know the hypervisor doesn't allow a reset. Only re-init what the host has access to, no matter the KVM configuration, which is the vGIC LRs. Then, cpu_hyp_init() is only called from init_subsystems() and kvm_arch_enable_virtualization_cpu(). Remove the kvm_hyp_initialized gate. It is possible because when pKVM is enabled, a CPU may already be initialised but then cpu_hyp_reset() simply returns an error, so we know we can skip the full init, while for the other modes, we know for sure it is never initialised when it hits this path. Finally, enable the PM notifiers for pKVM, it is now safe to do so. It will ensure the host properly configures the vGIC LRs regardless of the KVM configuration. Fixes: fa8c3d65538a ("KVM: arm64: Keep nVHE EL2 vector installed") Tested-by: Fuad Tabba Reviewed-by: Fuad Tabba Signed-off-by: Vincent Donnefort Link: https://patch.msgid.link/20261026163937.963087-3-vdonnefort@google.com Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/virt.h | 2 +- arch/arm64/kvm/arm.c | 50 +++++++++++++++++++---------------- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/arch/arm64/include/asm/virt.h b/arch/arm64/include/asm/virt.h index b546703c3ab9a8..a5bde8cc5df51a 100644 --- a/arch/arm64/include/asm/virt.h +++ b/arch/arm64/include/asm/virt.h @@ -83,7 +83,7 @@ extern u32 __boot_cpu_mode[2]; #define ARM64_VECTOR_TABLE_LEN SZ_2K void __hyp_set_vectors(phys_addr_t phys_vector_base); -void __hyp_reset_vectors(void); +int __hyp_reset_vectors(void); bool is_kvm_arm_initialised(void); DECLARE_STATIC_KEY_FALSE(kvm_protected_mode_initialized); diff --git a/arch/arm64/kvm/arm.c b/arch/arm64/kvm/arm.c index 157bf4b8120201..4602aeb795a0fb 100644 --- a/arch/arm64/kvm/arm.c +++ b/arch/arm64/kvm/arm.c @@ -2457,10 +2457,12 @@ static void cpu_init_hyp_mode(void) } } -static void cpu_hyp_reset(void) +static int cpu_hyp_reset(void) { if (!is_kernel_in_hyp_mode()) - __hyp_reset_vectors(); + return __hyp_reset_vectors() ? -EPERM : 0; + + return 0; } /* @@ -2511,32 +2513,38 @@ static void cpu_hyp_init_features(void) kvm_timer_init_vhe(); kvm_debug_init_vhe(); } - - if (vgic_present) - kvm_vgic_init_cpu_hardware(); } static void cpu_hyp_reinit(void) { - cpu_hyp_reset(); - cpu_hyp_init_context(); - cpu_hyp_init_features(); + if (!cpu_hyp_reset()) { + cpu_hyp_init_context(); + cpu_hyp_init_features(); + } else if (WARN_ON(!__this_cpu_read(kvm_hyp_initialized))) { + return; + } + + /* + * Even if the hypervisor didn't allow resetting the vectors we can + * reset the LRs. + */ + if (vgic_present) + kvm_vgic_init_cpu_hardware(); } static void cpu_hyp_init(void *discard) { - if (!__this_cpu_read(kvm_hyp_initialized)) { - cpu_hyp_reinit(); - __this_cpu_write(kvm_hyp_initialized, 1); - } + cpu_hyp_reinit(); + __this_cpu_write(kvm_hyp_initialized, 1); } static void cpu_hyp_uninit(void *discard) { - if (!is_protected_kvm_enabled() && __this_cpu_read(kvm_hyp_initialized)) { - cpu_hyp_reset(); + if (!__this_cpu_read(kvm_hyp_initialized)) + return; + + if (!cpu_hyp_reset()) __this_cpu_write(kvm_hyp_initialized, 0); - } } int kvm_arch_enable_virtualization_cpu(void) @@ -2564,8 +2572,7 @@ void kvm_arch_disable_virtualization_cpu(void) kvm_timer_cpu_down(); kvm_vgic_cpu_down(); - if (!is_protected_kvm_enabled()) - cpu_hyp_uninit(NULL); + cpu_hyp_uninit(NULL); } #ifdef CONFIG_CPU_PM @@ -2608,13 +2615,11 @@ static struct notifier_block hyp_init_cpu_pm_nb = { static void __init hyp_cpu_pm_init(void) { - if (!is_protected_kvm_enabled()) - cpu_pm_register_notifier(&hyp_init_cpu_pm_nb); + cpu_pm_register_notifier(&hyp_init_cpu_pm_nb); } static void __init hyp_cpu_pm_exit(void) { - if (!is_protected_kvm_enabled()) - cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb); + cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb); } #else static inline void __init hyp_cpu_pm_init(void) @@ -2737,8 +2742,7 @@ static int __init init_subsystems(void) if (err) hyp_cpu_pm_exit(); - if (err || !is_protected_kvm_enabled()) - on_each_cpu(cpu_hyp_uninit, NULL, 1); + on_each_cpu(cpu_hyp_uninit, NULL, 1); return err; } From 5fe9e7dbc78e3ade118a8f64952b7ed84e502afa Mon Sep 17 00:00:00 2001 From: Vincent Donnefort Date: Mon, 26 Oct 2026 16:39:37 +0000 Subject: [PATCH 0166/2102] KVM: arm64: pkvm: Reset GICv3 LRs in the hypervisor After the host is deprivileged, pKVM can't trust the host for resetting the vGIC LRs whose value is architecturally UNKNOWN when the CPU boots or resumes. Add a blanket cover in the CPU_ON/CPU_SUSPEND path. Fixes: 1025c8c0c6ac ("KVM: arm64: Wrap the host with a stage 2") Tested-by: Fuad Tabba Reviewed-by: Fuad Tabba Signed-off-by: Vincent Donnefort Link: https://patch.msgid.link/20261026163937.963087-4-vdonnefort@google.com Signed-off-by: Marc Zyngier --- arch/arm64/kvm/hyp/nvhe/psci-relay.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/arch/arm64/kvm/hyp/nvhe/psci-relay.c b/arch/arm64/kvm/hyp/nvhe/psci-relay.c index e20db999e3288b..2863b4b90ea877 100644 --- a/arch/arm64/kvm/hyp/nvhe/psci-relay.c +++ b/arch/arm64/kvm/hyp/nvhe/psci-relay.c @@ -213,6 +213,10 @@ static void __noreturn __kvm_host_psci_cpu_entry(unsigned long pc, unsigned long write_sysreg_el1(INIT_SCTLR_EL1_MMU_OFF, SYS_SCTLR); write_sysreg(INIT_PSTATE_EL1, SPSR_EL2); + /* We can't trust the host to reset the LRs */ + if (hyp_gicv3_nr_lr) + __vgic_v3_init_lrs(); + trace_hyp_exit(host_ctxt, HYP_REASON_PSCI); __host_enter(host_ctxt); } From 9e29ea628848d29eea948200c4357f530b0e1768 Mon Sep 17 00:00:00 2001 From: Vincent Donnefort Date: Wed, 28 Oct 2026 15:31:50 +0000 Subject: [PATCH 0167/2102] KVM: arm64: Synchronise kvm_host_data before host deprivileging When protected mode is enabled, the host is populating and reading the hypervisor copy of kvm_host_data until it is deprivileged. This is an issue for nr_event_counters which is only used by the host to populate mdcr_el2. After deprivileging, it is reading an uninitialised value and sets HPMN to 0, preventing programmable event counters from counting a non-protected guest. Before the host is entirely deprivileged, copy the entire kvm_host_data content from the hypervisor copy to the host-accessible one. Fixes: 2417218f2f23 ("KVM: arm64: Get rid of __kvm_get_mdcr_el2() and related warts") Signed-off-by: Vincent Donnefort Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261028153152.1740044-2-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/pkvm.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/arch/arm64/kvm/pkvm.c b/arch/arm64/kvm/pkvm.c index 016997288fd233..fd0a0f26dffe74 100644 --- a/arch/arm64/kvm/pkvm.c +++ b/arch/arm64/kvm/pkvm.c @@ -316,6 +316,12 @@ static void __init _kvm_host_prot_finalize(void *arg) { int *err = arg; + /* + * After __pkvm_prot_finalize, access to the hypervisor copy of + * kvm_host_data is lost. Save it into the host-accessible version. + */ + *this_cpu_ptr(&kvm_host_data) = *this_cpu_ptr_nvhe_sym(kvm_host_data); + if (WARN_ON(kvm_call_hyp_nvhe(__pkvm_prot_finalize))) WRITE_ONCE(*err, -EINVAL); } From 8ee90ca40b10cc040544fdccf24b20115f46aa7d Mon Sep 17 00:00:00 2001 From: Oliver Upton Date: Wed, 28 Oct 2026 15:31:51 +0000 Subject: [PATCH 0168/2102] KVM: arm64: Pass the PMU events to the hyp vCPU of non-protected guests Before every run, the host records in vcpu->arch.pmu.events which perf counters to disable and enable around guest entry, and __pmu_switch_to_guest() applies them at EL2. Since commit be66e67f1750 ("KVM: arm64: Use the pKVM hyp vCPU structure in handle___kvm_vcpu_run()"), protected mode runs the hyp vCPU instead, and flush_hyp_vcpu() never copies the events into it. So the counters backing a non-protected guest's PMU are never enabled, and every counter the guest reads stays at 0, the cycle counter included. The host's counters that exclude guests keep counting the guest as well. Copy the events into the hyp vCPU of a non-protected guest on every run. The events only exist with CONFIG_HW_PERF_EVENTS, so the copy is built under it. Like mdcr_el2, they're host-controlled and never reach a protected guest. [Fuad: non-protected copy only, tested on the hyp vCPU, under CONFIG_HW_PERF_EVENTS, new message] Fixes: be66e67f1750 ("KVM: arm64: Use the pKVM hyp vCPU structure in handle___kvm_vcpu_run()") Link: https://lore.kernel.org/all/20240305184840.636212-2-oliver.upton@linux.dev/ Signed-off-by: Oliver Upton Tested-by: Vincent Donnefort Reviewed-by: Vincent Donnefort Co-developed-by: Fuad Tabba Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261028153152.1740044-3-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/hyp/nvhe/hyp-main.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/arch/arm64/kvm/hyp/nvhe/hyp-main.c b/arch/arm64/kvm/hyp/nvhe/hyp-main.c index 0e1c05fd9ed1de..0c023ee0cf42a8 100644 --- a/arch/arm64/kvm/hyp/nvhe/hyp-main.c +++ b/arch/arm64/kvm/hyp/nvhe/hyp-main.c @@ -690,6 +690,16 @@ static void sync_debug_state(struct pkvm_hyp_vcpu *hyp_vcpu) host_vcpu->arch.external_debug_state = hyp_vcpu->vcpu.arch.external_debug_state; } +#ifdef CONFIG_HW_PERF_EVENTS +static void flush_pmu_state(struct pkvm_hyp_vcpu *hyp_vcpu) +{ + if (!pkvm_hyp_vcpu_is_protected(hyp_vcpu)) + hyp_vcpu->vcpu.arch.pmu.events = hyp_vcpu->host_vcpu->arch.pmu.events; +} +#else +static void flush_pmu_state(struct pkvm_hyp_vcpu *hyp_vcpu) {} +#endif + static void flush_hyp_vcpu(struct pkvm_hyp_vcpu *hyp_vcpu) { struct kvm_vcpu *host_vcpu = hyp_vcpu->host_vcpu; @@ -699,6 +709,7 @@ static void flush_hyp_vcpu(struct pkvm_hyp_vcpu *hyp_vcpu) fpsimd_sve_flush(); flush_debug_state(hyp_vcpu); + flush_pmu_state(hyp_vcpu); /* * If we deal with a non-protected guest and the state is potentially From a7dd36f7e381025bdf01d8665bf37167368754c4 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Wed, 28 Oct 2026 15:31:52 +0000 Subject: [PATCH 0169/2102] KVM: arm64: Disable host PMU counters for protected guests A protected guest has no PMU, and EL2 clears MDCR_EL2.HPME for it. However, __pkvm_vcpu_load() sets HPMN to cover every event counter, so HPME has no effect and the counters the host has enabled keep counting the guest. Clear PMCR_EL0.E in the world switch while a protected guest runs, which stops them all. Gate this on system_supports_pmuv3(), as __activate_traps_common() does for PMUSERENR_EL0. Side channels are outside pKVM's threat model, so this is hardening rather than a fix. Reported-by: Oculytic Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261028153152.1740044-4-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/hyp/nvhe/switch.c | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/arch/arm64/kvm/hyp/nvhe/switch.c b/arch/arm64/kvm/hyp/nvhe/switch.c index 89fb9dd351ad5d..c23fbd4ef2860c 100644 --- a/arch/arm64/kvm/hyp/nvhe/switch.c +++ b/arch/arm64/kvm/hyp/nvhe/switch.c @@ -175,6 +175,26 @@ static void __pmu_switch_to_host(struct kvm_vcpu *vcpu) #define __pmu_switch_to_host(v) do {} while (0) #endif +static u64 __pmu_stop_host_counters(struct kvm_vcpu *vcpu) +{ + u64 pmcr; + + if (!vcpu_is_protected(vcpu) || !system_supports_pmuv3()) + return 0; + + pmcr = read_sysreg(pmcr_el0); + if (pmcr & ARMV8_PMU_PMCR_E) + write_sysreg(pmcr & ~ARMV8_PMU_PMCR_E, pmcr_el0); + + return pmcr; +} + +static void __pmu_restore_host_counters(u64 pmcr) +{ + if (pmcr & ARMV8_PMU_PMCR_E) + write_sysreg(pmcr, pmcr_el0); +} + /* * Handler for protected VM MSR, MRS or System instruction execution in AArch64. * @@ -283,6 +303,7 @@ int __kvm_vcpu_run(struct kvm_vcpu *vcpu) struct kvm_s2_mmu *mmu; bool pmu_switch_needed; u64 exit_code; + u64 host_pmcr; /* * Having IRQs masked via PMR when entering the guest means the GIC @@ -300,6 +321,7 @@ int __kvm_vcpu_run(struct kvm_vcpu *vcpu) guest_ctxt = &vcpu->arch.ctxt; pmu_switch_needed = __pmu_switch_to_guest(vcpu); + host_pmcr = __pmu_stop_host_counters(vcpu); __sysreg_save_state_nvhe(host_ctxt); /* @@ -384,6 +406,8 @@ int __kvm_vcpu_run(struct kvm_vcpu *vcpu) if (pmu_switch_needed) __pmu_switch_to_host(vcpu); + __pmu_restore_host_counters(host_pmcr); + /* Returning to host will clear PSR.I, remask PMR if needed */ if (system_uses_irq_prio_masking()) gic_write_pmr(GIC_PRIO_IRQOFF); From cadcd8d70f331044d12aa6a9644f8253cd2bf29a Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Tue, 20 Oct 2026 08:43:11 +0100 Subject: [PATCH 0170/2102] KVM: arm64: Ensure TLBs and I-cache are private to each vCPU in pKVM All vCPUs of a VM share its VMID, so KVM flushes a physical CPU's TLBs and I-cache for the VM whenever a different vCPU of that VM is loaded there. pKVM guests, protected or not, run on the hypervisor's stage-2 and VMID, and the host doesn't flush for them. Nothing at EL2 flushes instead, so a vCPU can hit TLB and I-cache entries that another vCPU of the same VM left on that CPU. Track at EL2 the last vCPU of each VM loaded on each CPU, and flush when it changes. EL2 can't allocate per-CPU memory for each VM, as the host does, so use one per-CPU array indexed by the VM's table entry. Reset the entry's slot on every CPU when a VM reserves it, so that a new VM starts with no last vCPU, whether the entry is unused or was left by a VM that was torn down. Fixes: fce886a602073 ("KVM: arm64: Plumb the pKVM MMU in KVM") Signed-off-by: Fuad Tabba Reviewed-by: Joey Gouly Reviewed-by: Vincent Donnefort Link: https://patch.msgid.link/20261020074311.1873316-1-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/hyp/nvhe/pkvm.c | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/arch/arm64/kvm/hyp/nvhe/pkvm.c b/arch/arm64/kvm/hyp/nvhe/pkvm.c index fc0475f0877d19..6442200cd40bab 100644 --- a/arch/arm64/kvm/hyp/nvhe/pkvm.c +++ b/arch/arm64/kvm/hyp/nvhe/pkvm.c @@ -38,6 +38,9 @@ unsigned int kvm_host_sve_max_vl; */ static DEFINE_PER_CPU(struct pkvm_hyp_vcpu *, loaded_hyp_vcpu); +/* Per VM table entry, the vcpu_idx of the last vCPU of that VM loaded on this CPU. */ +static DEFINE_PER_CPU(unsigned int, last_vcpu_ran[KVM_MAX_PVMS]); + /* * The PKVM_HCR_EL2_HOST_{PVM,NPVM} bits of this value come from the host on * each entry, and a protected vCPU's TWI and TWE at vCPU load. @@ -271,6 +274,7 @@ struct pkvm_hyp_vcpu *pkvm_load_hyp_vcpu(pkvm_handle_t handle, { struct pkvm_hyp_vcpu *hyp_vcpu = NULL; struct pkvm_hyp_vm *hyp_vm; + unsigned int *last_ran; /* Cannot load a new vcpu without putting the old one first. */ if (__this_cpu_read(loaded_hyp_vcpu)) @@ -300,8 +304,18 @@ struct pkvm_hyp_vcpu *pkvm_load_hyp_vcpu(pkvm_handle_t handle, unlock: hyp_spin_unlock(&vm_table_lock); - if (hyp_vcpu) - __this_cpu_write(loaded_hyp_vcpu, hyp_vcpu); + if (!hyp_vcpu) + return NULL; + + __this_cpu_write(loaded_hyp_vcpu, hyp_vcpu); + + /* TLBs and I-cache are private to each vCPU, see vcpu_prepare_mmu(). */ + last_ran = this_cpu_ptr(&last_vcpu_ran[vm_handle_to_idx(handle)]); + if (*last_ran != vcpu_idx) { + __kvm_flush_cpu_context(hyp_vcpu->vcpu.arch.hw_mmu); + *last_ran = vcpu_idx; + } + return hyp_vcpu; } @@ -668,6 +682,7 @@ static int find_free_vm_table_entry(void) */ static int allocate_vm_table_entry(void) { + unsigned int cpu; int idx; hyp_assert_lock_held(&vm_table_lock); @@ -686,6 +701,9 @@ static int allocate_vm_table_entry(void) vm_table[idx] = RESERVED_ENTRY; + for (cpu = 0; cpu < hyp_nr_cpus; cpu++) + per_cpu(last_vcpu_ran[idx], cpu) = UINT_MAX; + return idx; } From 699edee85fb9f4403b5bc939f3f84374f841b33b Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Sun, 25 Oct 2026 07:51:34 +0000 Subject: [PATCH 0171/2102] arm64: Add override for ID_AA64ISAR1_EL1.LS64 Accesses to ACCDATA_EL1, which FEAT_LS64_ACCDATA adds, trap to EL3 unless firmware sets SCR_EL3.ADEn. Once KVM context-switches the register for its guests, a host whose firmware leaves the bit clear can't run them. Add an override for ID_AA64ISAR1_EL1.LS64, with an arm64.nols64 alias, so that the feature can be disabled on such a host and for its guests. id_aa64isar1.ls64=2 disables only FEAT_LS64_ACCDATA and above. Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Acked-by: Catalin Marinas Link: https://patch.msgid.link/20261025075138.2919734-2-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- Documentation/admin-guide/kernel-parameters.txt | 3 +++ arch/arm64/kernel/pi/idreg-override.c | 2 ++ 2 files changed, 5 insertions(+) diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt index 0b3c140babd944..695d7063d6f358 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -564,6 +564,9 @@ Kernel parameters arm64.nohaft [ARM64] Unconditionally disable Hardware managed Access Flag for Table descriptors support + arm64.nols64 [ARM64] Unconditionally disable 64-byte Load/Store + instructions support + arm64.nomops [ARM64] Unconditionally disable Memory Copy and Memory Set instructions support diff --git a/arch/arm64/kernel/pi/idreg-override.c b/arch/arm64/kernel/pi/idreg-override.c index acaf56234973b9..2f132b44ef27db 100644 --- a/arch/arm64/kernel/pi/idreg-override.c +++ b/arch/arm64/kernel/pi/idreg-override.c @@ -174,6 +174,7 @@ static const struct ftr_set_desc isar1 __prel64_initconst = { .name = "id_aa64isar1", .override = &id_aa64isar1_override, .fields = { + FIELD("ls64", ID_AA64ISAR1_EL1_LS64_SHIFT, NULL), FIELD("gpi", ID_AA64ISAR1_EL1_GPI_SHIFT, NULL), FIELD("gpa", ID_AA64ISAR1_EL1_GPA_SHIFT, NULL), FIELD("api", ID_AA64ISAR1_EL1_API_SHIFT, NULL), @@ -254,6 +255,7 @@ static const struct { "id_aa64isar1.gpi=0 id_aa64isar1.gpa=0 " "id_aa64isar1.api=0 id_aa64isar1.apa=0 " "id_aa64isar2.gpa3=0 id_aa64isar2.apa3=0" }, + { "arm64.nols64", "id_aa64isar1.ls64=0" }, { "arm64.nomops", "id_aa64isar2.mops=0" }, { "arm64.nowfxt", "id_aa64isar2.wfxt=0" }, { "arm64.nomte", "id_aa64pfr1.mte=0" }, From 8b5bcf2e799c24906b813f4a63081e68721a026b Mon Sep 17 00:00:00 2001 From: Marc Zyngier Date: Sun, 25 Oct 2026 07:51:35 +0000 Subject: [PATCH 0172/2102] KVM: arm64: Add ACCDATA_EL1 to the sysreg array Make ACCDATA_EL1 a first-class citizen, and add it to the sysreg array. Visibility is conditioned on the feature being enabled. Link: https://lore.kernel.org/r/20240815125959.2097734-4-maz@kernel.org [Fuad: rebased] Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Reviewed-by: Yuan Yao Link: https://patch.msgid.link/20261025075138.2919734-3-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/kvm_host.h | 3 +++ arch/arm64/kvm/sys_regs.c | 12 +++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/arch/arm64/include/asm/kvm_host.h b/arch/arm64/include/asm/kvm_host.h index 97332ffcb1300e..f83962b6d0b3e1 100644 --- a/arch/arm64/include/asm/kvm_host.h +++ b/arch/arm64/include/asm/kvm_host.h @@ -582,6 +582,9 @@ enum vcpu_sysreg { GCR_EL1, /* Tag Control Register */ TFSRE0_EL1, /* Tag Fault Status Register (EL0) */ + /* Random stuff */ + ACCDATA_EL1, /* Accelerator Data */ + POR_EL0, /* Permission Overlay Register 0 (EL0) */ /* FP/SIMD/SVE */ diff --git a/arch/arm64/kvm/sys_regs.c b/arch/arm64/kvm/sys_regs.c index 850eba167aad6a..e5ed7de6fb4f85 100644 --- a/arch/arm64/kvm/sys_regs.c +++ b/arch/arm64/kvm/sys_regs.c @@ -2914,6 +2914,15 @@ static unsigned int sve_el2_visibility(const struct kvm_vcpu *vcpu, return __el2_visibility(vcpu, rd, sve_visibility); } +static unsigned int accdata_visibility(const struct kvm_vcpu *vcpu, + const struct sys_reg_desc *rd) +{ + if (kvm_has_feat(vcpu->kvm, ID_AA64ISAR1_EL1, LS64, LS64_ACCDATA)) + return 0; + + return REG_HIDDEN; +} + static unsigned int vncr_el2_visibility(const struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd) { @@ -3601,7 +3610,8 @@ static const struct sys_reg_desc sys_reg_descs[] = { { SYS_DESC(SYS_CONTEXTIDR_EL1), access_vm_reg, reset_val, CONTEXTIDR_EL1, 0 }, { SYS_DESC(SYS_TPIDR_EL1), NULL, reset_unknown, TPIDR_EL1 }, - { SYS_DESC(SYS_ACCDATA_EL1), undef_access }, + { SYS_DESC(SYS_ACCDATA_EL1), undef_access, reset_val, ACCDATA_EL1, 0, + .visibility = accdata_visibility}, { SYS_DESC(SYS_SCXTNUM_EL1), undef_access }, From c122ea1564b41326d8c09c64005d38ec2fa6dd8f Mon Sep 17 00:00:00 2001 From: Marc Zyngier Date: Sun, 25 Oct 2026 07:51:36 +0000 Subject: [PATCH 0173/2102] KVM: arm64: Add context-switch of ACCDATA_EL1 Add ACCDATA_EL1 save/restore as part of the EL0 context. This is conditioned on the guest's view of ID_AA64ISAR1_EL1.LS64 reporting that this register is supported. [Fuad: rebased; switch ACCDATA_EL1 for guests only, as the host never uses it; gate it on a new ARM64_HAS_LS64_ACCDATA capability, since in pKVM the host controls a non-protected guest's ID registers, and an EL2 access to ACCDATA_EL1 on a CPU without the feature is UNDEFINED] Fixes: 58ce78667a641 ("arm64: Add support for FEAT_{LS64, LS64_V}") Link: https://lore.kernel.org/r/20240815125959.2097734-5-maz@kernel.org Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Reviewed-by: Yuan Yao Acked-by: Catalin Marinas Link: https://patch.msgid.link/20261025075138.2919734-4-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kernel/cpufeature.c | 7 +++++++ arch/arm64/kvm/hyp/include/hyp/sysreg-sr.h | 23 ++++++++++++++++++++++ arch/arm64/tools/cpucaps | 1 + 3 files changed, 31 insertions(+) diff --git a/arch/arm64/kernel/cpufeature.c b/arch/arm64/kernel/cpufeature.c index 34c5c03c0c9b4f..5f99633b5c94b7 100644 --- a/arch/arm64/kernel/cpufeature.c +++ b/arch/arm64/kernel/cpufeature.c @@ -3075,6 +3075,13 @@ static const struct arm64_cpu_capabilities arm64_features[] = { .cpu_enable = cpu_enable_ls64_v, ARM64_CPUID_FIELDS(ID_AA64ISAR1_EL1, LS64, LS64_V) }, + { + .desc = "LS64_ACCDATA", + .capability = ARM64_HAS_LS64_ACCDATA, + .type = ARM64_CPUCAP_SYSTEM_FEATURE, + .matches = has_cpuid_feature, + ARM64_CPUID_FIELDS(ID_AA64ISAR1_EL1, LS64, LS64_ACCDATA) + }, #ifdef CONFIG_ARM64_LSUI { .desc = "Unprivileged Load Store Instructions (LSUI)", diff --git a/arch/arm64/kvm/hyp/include/hyp/sysreg-sr.h b/arch/arm64/kvm/hyp/include/hyp/sysreg-sr.h index c382848d319479..4a008c8a696ba1 100644 --- a/arch/arm64/kvm/hyp/include/hyp/sysreg-sr.h +++ b/arch/arm64/kvm/hyp/include/hyp/sysreg-sr.h @@ -17,6 +17,7 @@ #include static inline bool ctxt_has_s1poe(struct kvm_cpu_context *ctxt); +static inline bool ctxt_has_accdata(struct kvm_cpu_context *ctxt); static inline struct kvm_vcpu *ctxt_to_vcpu(struct kvm_cpu_context *ctxt) { @@ -67,6 +68,13 @@ static inline void __sysreg_save_user_state(struct kvm_cpu_context *ctxt) { ctxt_sys_reg(ctxt, TPIDR_EL0) = read_sysreg(tpidr_el0); ctxt_sys_reg(ctxt, TPIDRRO_EL0) = read_sysreg(tpidrro_el0); + + /* + * Despite the appearances, ACCDATA_EL1 is part of the EL0 + * context, as it can only be used using ST64BV0. + */ + if (ctxt_has_accdata(ctxt)) + ctxt_sys_reg(ctxt, ACCDATA_EL1) = read_sysreg_s(SYS_ACCDATA_EL1); } static inline bool ctxt_has_mte(struct kvm_cpu_context *ctxt) @@ -131,6 +139,18 @@ static inline bool ctxt_has_sctlr2(struct kvm_cpu_context *ctxt) return kvm_has_sctlr2(kern_hyp_va(vcpu->kvm)); } +static inline bool ctxt_has_accdata(struct kvm_cpu_context *ctxt) +{ + struct kvm_vcpu *vcpu; + + /* The host never uses ACCDATA_EL1 */ + if (!cpus_have_final_cap(ARM64_HAS_LS64_ACCDATA) || !ctxt_is_guest(ctxt)) + return false; + + vcpu = ctxt_to_vcpu(ctxt); + return kvm_has_feat(kern_hyp_va(vcpu->kvm), ID_AA64ISAR1_EL1, LS64, LS64_ACCDATA); +} + static inline void __sysreg_save_el1_state(struct kvm_cpu_context *ctxt) { ctxt_sys_reg(ctxt, SCTLR_EL1) = read_sysreg_el1(SYS_SCTLR); @@ -210,6 +230,9 @@ static inline void __sysreg_restore_user_state(struct kvm_cpu_context *ctxt) { write_sysreg(ctxt_sys_reg(ctxt, TPIDR_EL0), tpidr_el0); write_sysreg(ctxt_sys_reg(ctxt, TPIDRRO_EL0), tpidrro_el0); + + if (ctxt_has_accdata(ctxt)) + write_sysreg_s(ctxt_sys_reg(ctxt, ACCDATA_EL1), SYS_ACCDATA_EL1); } static inline void __sysreg_restore_el1_state(struct kvm_cpu_context *ctxt, diff --git a/arch/arm64/tools/cpucaps b/arch/arm64/tools/cpucaps index 20cc185649f9af..51f5683374b0f4 100644 --- a/arch/arm64/tools/cpucaps +++ b/arch/arm64/tools/cpucaps @@ -49,6 +49,7 @@ HAS_LPA2 HAS_LSE_ATOMICS HAS_LS64 HAS_LS64_V +HAS_LS64_ACCDATA HAS_LSUI HAS_MOPS HAS_NESTED_VIRT From e2412d6a90a4b39e3fc464eeab8637a7f4eccc10 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Sun, 25 Oct 2026 07:51:37 +0000 Subject: [PATCH 0174/2102] KVM: arm64: Enable ST64BV0 for guests with FEAT_LS64_ACCDATA Since commit 58ce78667a641 ("arm64: Add support for FEAT_{LS64, LS64_V}"), a guest sees the host's ID_AA64ISAR1_EL1.LS64, but KVM only enables the FEAT_LS64 and FEAT_LS64_V instructions in HCRX_EL2. On a host with FEAT_LS64_ACCDATA, a guest's ST64BV0 therefore traps and hits the WARN_ON_ONCE() in handle_other(). Set HCRX_EL2.EnAS0 when the guest has FEAT_LS64_ACCDATA, now that ACCDATA_EL1 is context-switched. Fixes: 58ce78667a641 ("arm64: Add support for FEAT_{LS64, LS64_V}") Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Reviewed-by: Yuan Yao Link: https://patch.msgid.link/20261025075138.2919734-5-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/kvm_emulate.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/arm64/include/asm/kvm_emulate.h b/arch/arm64/include/asm/kvm_emulate.h index 334211b8b2ee49..2d7c82cfb8a40d 100644 --- a/arch/arm64/include/asm/kvm_emulate.h +++ b/arch/arm64/include/asm/kvm_emulate.h @@ -740,6 +740,9 @@ static inline void vcpu_set_hcrx(struct kvm_vcpu *vcpu) if (kvm_has_feat(kvm, ID_AA64ISAR1_EL1, LS64, LS64_V)) vcpu->arch.hcrx_el2 |= HCRX_EL2_EnASR; + if (kvm_has_feat(kvm, ID_AA64ISAR1_EL1, LS64, LS64_ACCDATA)) + vcpu->arch.hcrx_el2 |= HCRX_EL2_EnAS0; + /* * NV3 is a host-specific extension, and we always use * it when present and that the guest uses NV. It may From b7bb9e9425dd7772cba9ac4392e982f541cccfac Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Sun, 25 Oct 2026 07:51:38 +0000 Subject: [PATCH 0175/2102] KVM: arm64: selftests: Add ACCDATA_EL1 to get-reg-list KVM exposes ACCDATA_EL1 to userspace when the guest has FEAT_LS64_ACCDATA. Add it to get-reg-list, conditioned on ID_AA64ISAR1_EL1.LS64, so that the test still passes on hosts that implement the feature. Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261025075138.2919734-6-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- tools/testing/selftests/kvm/arm64/get-reg-list.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/testing/selftests/kvm/arm64/get-reg-list.c b/tools/testing/selftests/kvm/arm64/get-reg-list.c index 533994687b5d82..912590f9b0c2bc 100644 --- a/tools/testing/selftests/kvm/arm64/get-reg-list.c +++ b/tools/testing/selftests/kvm/arm64/get-reg-list.c @@ -49,6 +49,7 @@ static struct feature_id_reg feat_id_regs[] = { REG_FEAT(POR_EL1, ID_AA64MMFR3_EL1, S1POE, IMP), REG_FEAT(POR_EL0, ID_AA64MMFR3_EL1, S1POE, IMP), REG_FEAT(POR_EL2, ID_AA64MMFR3_EL1, S1POE, IMP), + REG_FEAT(ACCDATA_EL1, ID_AA64ISAR1_EL1, LS64, LS64_ACCDATA), REG_FEAT(HCRX_EL2, ID_AA64MMFR1_EL1, HCX, IMP), REG_FEAT(HFGRTR_EL2, ID_AA64MMFR0_EL1, FGT, IMP), REG_FEAT(HFGWTR_EL2, ID_AA64MMFR0_EL1, FGT, IMP), @@ -517,6 +518,7 @@ static __u64 base_regs[] = { ARM64_SYS_REG(3, 0, 12, 1, 1), /* DISR_EL1 */ ARM64_SYS_REG(3, 0, 13, 0, 1), /* CONTEXTIDR_EL1 */ ARM64_SYS_REG(3, 0, 13, 0, 4), /* TPIDR_EL1 */ + ARM64_SYS_REG(3, 0, 13, 0, 5), /* ACCDATA_EL1 */ ARM64_SYS_REG(3, 0, 14, 1, 0), /* CNTKCTL_EL1 */ ARM64_SYS_REG(3, 2, 0, 0, 0), /* CSSELR_EL1 */ ARM64_SYS_REG(3, 3, 10, 2, 4), /* POR_EL0 */ From 2c77a4a3040da8095e052849e2a0a05f598c8601 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Mon, 2 Nov 2026 07:58:42 +0000 Subject: [PATCH 0176/2102] KVM: arm64: Clear the VM's feature bitmap when kvm_setup_vcpu() fails KVM_ARM_VCPU_INIT records the requested features in the VM-wide bitmap before kvm_setup_vcpu() runs, and leaves them there when setup fails (e.g., HAS_EL2_E2H0 on a host without FEAT_NV1). The PMU attributes read that bitmap before the vCPU is initialized, so after such a failure with PMU_V3 requested, KVM_SET_DEVICE_ATTR on the PMU group no longer returns -ENODEV. Until an INIT has succeeded, every INIT that gets past the feature checks rewrites the bitmap. After that, kvm_vcpu_init_changed() requires the requested features to match it, so the copy is a no-op. Clear the bitmap on failure while KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED is clear. Fixes: 427733579744e ("KVM: arm64: Select default PMU in KVM_ARM_VCPU_INIT handler") Suggested-by: Oliver Upton Reviewed-by: Lorenzo Stoakes (ARM) Signed-off-by: Fuad Tabba Reviewed-by: Suzuki K Poulose Link: https://patch.msgid.link/20261102075843.2556018-2-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/arm.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/arch/arm64/kvm/arm.c b/arch/arm64/kvm/arm.c index 157bf4b8120201..3e91e01b032c42 100644 --- a/arch/arm64/kvm/arm.c +++ b/arch/arm64/kvm/arm.c @@ -1856,8 +1856,13 @@ static int __kvm_vcpu_set_target(struct kvm_vcpu *vcpu, bitmap_copy(kvm->arch.vcpu_features, &features, KVM_VCPU_MAX_FEATURES); ret = kvm_setup_vcpu(vcpu); - if (ret) + if (ret) { + /* Clear the bitmap if setup fails on the first vCPU to be initialized. */ + if (!test_bit(KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED, &kvm->arch.flags)) + bitmap_zero(kvm->arch.vcpu_features, KVM_VCPU_MAX_FEATURES); + goto out_unlock; + } /* Now we know what it is, we can reset it. */ kvm_reset_vcpu(vcpu); From 4d3361e4d60a46781c8697ee1ab9532f625163f1 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Mon, 2 Nov 2026 07:58:43 +0000 Subject: [PATCH 0177/2102] KVM: arm64: Clear the default PMU when kvm_setup_vcpu() fails Under KVM_ARM_VCPU_PMU_V3_STRICT, the VM has no PMU until userspace selects one, and initializing the PMU fails with -ENXIO until then. However, without STRICT, kvm_setup_vcpu() selects the default PMU before it prepares the vCPU for nested virtualization, and leaves it set when that preparation fails. After a retry with STRICT, initializing the PMU succeeds and the guest gets the PMU of the CPU the failed INIT ran on. Drop the PMU and its number of counters along with the VM's feature bitmap. While KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED is clear, no vCPU has been initialized and the PMU attributes return -ENODEV, so only such a failure can have set them. Once the flag is set, every INIT has the features of the first one that succeeded, which either selected a PMU or had none to select, so kvm_setup_vcpu() doesn't select another. Fixes: ad220e275c398 ("KVM: arm64: Add KVM_ARM_VCPU_PMU_V3_STRICT vCPU feature") Signed-off-by: Fuad Tabba Reviewed-by: Suzuki K Poulose Link: https://patch.msgid.link/20261102075843.2556018-3-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/arm.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/arch/arm64/kvm/arm.c b/arch/arm64/kvm/arm.c index 3e91e01b032c42..65194e02cdbc25 100644 --- a/arch/arm64/kvm/arm.c +++ b/arch/arm64/kvm/arm.c @@ -1857,9 +1857,12 @@ static int __kvm_vcpu_set_target(struct kvm_vcpu *vcpu, ret = kvm_setup_vcpu(vcpu); if (ret) { - /* Clear the bitmap if setup fails on the first vCPU to be initialized. */ - if (!test_bit(KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED, &kvm->arch.flags)) + /* Clear the bitmap and PMU if setup fails on the first vCPU to be initialized. */ + if (!test_bit(KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED, &kvm->arch.flags)) { bitmap_zero(kvm->arch.vcpu_features, KVM_VCPU_MAX_FEATURES); + kvm->arch.arm_pmu = NULL; + kvm->arch.nr_pmu_counters = 0; + } goto out_unlock; } From 0e086eebb3f38c392789dde6f0731f6555d793c5 Mon Sep 17 00:00:00 2001 From: Matthias Goergens Date: Fri, 30 Oct 2026 16:33:51 +0800 Subject: [PATCH 0178/2102] Documentation/process: Add a maintainer entry profile for KVM/arm64 KVM/arm64 has no P: entry in MAINTAINERS, so nothing tells a contributor that the kvmarm tree is used for integration only, or what the maintainers expect patches to be based on. Marc Zyngier said a profile would help. Add one covering the trees, the base for patches, the submit checklist, key cycle dates and review cadence, and point the KVM/arm64 entry at it. Link: https://lore.kernel.org/all/875wzu4vuv.wl-maz@kernel.org/ Link: https://lore.kernel.org/all/87tsnb2dtq.wl-maz@kernel.org/ Signed-off-by: Matthias Goergens Acked-by: Zenghui Yu Link: https://patch.msgid.link/20261030083351.3040604-1-matthias.goergens@gmail.com Signed-off-by: Marc Zyngier --- .../process/maintainer-kvm-arm64.rst | 181 ++++++++++++++++++ MAINTAINERS | 2 + 2 files changed, 183 insertions(+) create mode 100644 Documentation/process/maintainer-kvm-arm64.rst diff --git a/Documentation/process/maintainer-kvm-arm64.rst b/Documentation/process/maintainer-kvm-arm64.rst new file mode 100644 index 00000000000000..ffb73cee06aef7 --- /dev/null +++ b/Documentation/process/maintainer-kvm-arm64.rst @@ -0,0 +1,181 @@ +.. SPDX-License-Identifier: GPL-2.0 + +KVM/arm64 +========= + +This document describes how KVM/arm64 (``arch/arm64/kvm/`` and the other +files listed under "KERNEL VIRTUAL MACHINE FOR ARM64 (KVM/arm64)" in +MAINTAINERS) is maintained. It supplements +Documentation/process/submitting-patches.rst. + +Overview +-------- + +The maintainers, reviewers and mailing lists for KVM/arm64 are listed in its +MAINTAINERS entry. + +Trees +~~~~~ + +The KVM/arm64 tree is:: + + git://git.kernel.org/pub/scm/linux/kernel/git/kvmarm/kvmarm.git + +This tree is used for integration only: no development happens in it, and +most patches should not be based on it (see `Base for patches`_). Its +branches are: + +``next`` + Changes queued for the next merge window. linux-next merges this branch. + +``fixes`` + Fixes for the release currently in its -rc phase. linux-next merges this + branch too. + +``master`` + Follows the -rc tags in Linus Torvalds' tree. + +Changes leave the tree as signed tags, which are pulled into the main KVM tree +(``git://git.kernel.org/pub/scm/virt/kvm/kvm.git``) and from there reach Linus +Torvalds. + +Topic branches are managed by the maintainers in their private trees, and only +the result of integrating them is pushed out. The exception is shared +branches, which are published when necessary. Where a series also touches +code maintained elsewhere, most often the arm64 architecture code, the +maintainers may set up a shared stable branch, based on an -rc tag, that both +trees merge. Say in the cover letter which parts of a series touch other +subsystems. + +Base for patches +~~~~~~~~~~~~~~~~ + +Base your patches on a tag published in Linus Torvalds' tree, preferably -rc1 +to -rc3. If you rely on something merged later, for example a fix merged in +-rc4, say why in the cover letter. Patches based on linux-next are +discouraged. + +Do not base patches on ``kvmarm/next`` either: it is rebuilt regularly, so a +commit on it is generally the wrong base. If your series conflicts with work +queued there, leave the conflict for the maintainers to see, as it is a sign +that something needs a closer look. A proposed resolution is welcome. The +exception is a series that strictly continues one that has already been +queued. + +If your series depends on something else that is not yet in mainline, such as +another series under review, say so in the cover letter and name exactly what +it applies on top of. + +Use ``git format-patch --base`` so that the base commit is recorded in the +patches. + +Submit Checklist Addendum +------------------------- + +Recipients and threading +~~~~~~~~~~~~~~~~~~~~~~~~ + +Send the whole series to all of the maintainers and reviewers listed for +KVM/arm64, not a selection of them. Post each new version as a new thread, +not as a reply to the previous version, with a cover letter for anything +longer than a single patch. + +Subject lines +~~~~~~~~~~~~~ + +Changes to KVM/arm64 use the ``KVM: arm64:`` prefix, often followed by a +sub-topic such as ``nv:`` or ``vgic:``. Selftest changes use ``KVM: arm64: +selftests:`` or ``KVM: selftests:``. +``git log --oneline`` on the files you touch shows what is in use. The text +after the prefixes starts with a capital letter, for example ``KVM: arm64: nv: +Fix life cycle of the nested_mmus array``. + +Architecture references +~~~~~~~~~~~~~~~~~~~~~~~ + +KVM/arm64 code tracks the Arm Architecture Reference Manual (the "Arm ARM", +document DDI0487) closely. Where a change depends on architected behaviour, +explain why the change is needed and cite the Arm ARM in the commit message +or in a comment. Where the rule has an identifier, such as ``R_QXXPC``, quote +that: identifiers stay the same across revisions of the document, while +section numbers do not. Otherwise give the revision along with the section, +for example ``DDI0487L.a D24.2.70``. The same applies to other architecture +documents. + +Testing +~~~~~~~ + +Say in the cover letter how the series was tested: which tests, and on which +hardware or model. The KVM selftests (``tools/testing/selftests/kvm/``) and +kvm-unit-tests are the usual test suites. Put selftest changes in patches of +their own, separate from the KVM changes and usually at the end of the series. + +KVM/arm64 can run in several modes, which are described under +``kvm-arm.mode=`` in Documentation/admin-guide/kernel-parameters.txt. Test +the modes your change can affect. + +If a patch aims to improve performance, describe exactly how you measured it, +in enough detail for others to reproduce the results. Measurements made on a +software model such as QEMU or the Arm FVP say nothing about performance on +hardware. + +New tests are encouraged, particularly for nested virtualisation, where +coverage is poor. Depending on the change, selftests may not be enough; the +maintainers may ask for testing with a VMM, for example. + +Userspace API +~~~~~~~~~~~~~ + +Document changes to the userspace API, usually in +Documentation/virt/kvm/api.rst or in the files under +Documentation/virt/kvm/devices/ and Documentation/virt/kvm/arm/. + +Fixes +~~~~~ + +Add a ``Fixes:`` tag for bug fixes. If the fix should go to stable kernels, +add ``Cc: stable@vger.kernel.org``; the maintainers may add it when applying +if the bug calls for it. + +Key Cycle Dates +--------------- + +Changes for the next merge window are queued on ``next``. New features are +usually not merged once -rc6 has been published; from then on, only fixes are +queued. This is not a hard rule, but posting a feature just before -rc6 +guarantees nothing. + +Fixes for the current release are queued on ``fixes`` and sent upstream at +intervals that depend on how severe the bugs are. There is no cut-off for +fixes, but the maintainers may defer a low-priority fix to the next merge +window. + +Review Cadence +-------------- + +Unless the maintainers ask for a new version sooner, allow at least a week +between versions of a series, and only post a new version once there has +been enough review to justify it. Posting more often delays review rather +than speeding it up. + +Pinging a series that has had no response is fine. + +Answer reviews from bots such as Sashiko as you would any other review, even +if only to say that a finding is wrong. Pre-existing problems that a bot +points out, and that are unrelated to the series, need not be fixed in its +initial posting. + +Applied patches are normally acknowledged in reply to the posting, naming the +branch (``next`` or ``fixes``) and the commits. The maintainers try not to +change the commit IDs of applied patches, but the IDs of merge commits almost +always change. + +Minor problems are often fixed up by the maintainers when applying; ask if +you are unsure whether to resend. + +Security issues +--------------- + +Bugs that let a guest attack its host, or a nested guest attack its guest +hypervisor, should be reported as described in +Documentation/process/security-bugs.rst. diff --git a/MAINTAINERS b/MAINTAINERS index 93abbb315065de..936bdb8b96350c 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -14623,7 +14623,9 @@ R: Zenghui Yu L: linux-arm-kernel@lists.infradead.org (moderated for non-subscribers) L: kvmarm@lists.linux.dev S: Maintained +P: Documentation/process/maintainer-kvm-arm64.rst T: git git://git.kernel.org/pub/scm/linux/kernel/git/kvmarm/kvmarm.git +F: Documentation/process/maintainer-kvm-arm64.rst F: Documentation/virt/kvm/arm/ F: Documentation/virt/kvm/devices/arm* F: arch/arm64/include/asm/kvm* From 36b225a9b1c41a71d80e2cc17b3f0fcde4bd598e Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 3 Nov 2026 12:44:12 +0100 Subject: [PATCH 0179/2102] KVM: arm64: Don't livelock when AT can't resolve a fault IPA When a stage-2 permission fault doesn't report its IPA in HPFAR_EL2, __get_fault_info() recovers it with an AT S1E1R/S1E1A on FAR_EL2. If that fails, kvm_hyp_handle_memory_fault() goes straight back to the guest, on the assumption that the replayed access will either succeed or take a fault that the slow path can handle. That assumption doesn't hold when the AT fails because its stage-1 walk takes a stage-2 fault on one of the guest's page-table pages, while the guest still holds a cached translation for the faulting VA. The guest doesn't walk its page tables, so it never takes the S1PTW fault that would let the slow path fix things up. It takes the same permission fault again, the AT fails again, and the vCPU livelocks in the world switch. This was observed on Apple M2, which has no hardware Access flag management at stage 2, and no DIC, so execute permission is granted lazily and the first instruction fetch from a page takes a permission fault. With DAMON_STAT enabled (CONFIG_DAMON_STAT_ENABLED_DEFAULT=y), kdamond keeps sampling guest memory, and damon_pmdp_mkold() ages a whole PMD at a time through mmu_notifier_clear_young(). With THP-backed guest memory, kvm_age_gfn() therefore clears the stage-2 AF of 32MB of guest pages at once, without TLB invalidation. When that covers both freshly loaded code and the page-table page that maps it, the first instruction fetch from that code livelocks, and the vCPU only ever recovers when its thread happens to be moved to another CPU. In all 52 instrumented occurrences, the AT reported a stage-2 Access flag fault on a stage-1 table walk (PAR_EL1.{S,PTW} = {1,1}, FST = Access flag fault, level 3), while an AT S12E1R on the same VA succeeded. With DAMON_STAT disabled, the AT didn't fail once in 210 boots. Nothing in this is specific to nested virtualisation, nor to instruction fetches: a write to a read-only memslot hit it too. A stage-1 fault can lead to the same livelock. A guest that ages its own page tables without invalidating the TLB, as MGLRU does through ptep_test_and_clear_young(), can keep using a cached translation while the descriptor in memory has its Access flag clear. If such an access takes a stage-2 permission fault (lazy execute permission, or dirty logging), the AT reports a stage-1 Access flag fault (PAR_EL1.S = 0), which the guest never takes either, as it doesn't walk its page tables. This hasn't been observed, but it is why the invalidation below is done whenever the AT fails, rather than only when PAR_EL1.PTW reports a stage-2 fault on the walk. A guest that merely races with its own page-table updates isn't harmed by it: at worst, it takes a translation fault that it was allowed to take anyway. Invalidate this VMID's TLB entries on the local CPU before replaying the access, so that the guest has to walk its page tables and takes the fault that the AT ran into: either a stage-2 fault on the page-table page, with a valid HPFAR_EL2, which the slow path resolves, or a stage-1 fault, which the guest resolves itself. In all instrumented cases, the next exit was an S1PTW Access flag fault on the page-table page. This only happens when the AT fails, so the cost is negligible. With this change, an EL2 UEFI guest that livelocked in 27 out of 210 boots didn't hang once in 420 boots. Cc: stable@vger.kernel.org Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Signed-off-by: Ard Biesheuvel Link: https://patch.msgid.link/20261103114411.3642140-2-ardb+git@google.com Signed-off-by: Marc Zyngier --- arch/arm64/kvm/hyp/include/hyp/switch.h | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/arch/arm64/kvm/hyp/include/hyp/switch.h b/arch/arm64/kvm/hyp/include/hyp/switch.h index e0c55644224cb2..6b2ca89e83260c 100644 --- a/arch/arm64/kvm/hyp/include/hyp/switch.h +++ b/arch/arm64/kvm/hyp/include/hyp/switch.h @@ -843,8 +843,22 @@ static inline bool kvm_hyp_handle_cp15_32(struct kvm_vcpu *vcpu, u64 *exit_code) static inline bool kvm_hyp_handle_memory_fault(struct kvm_vcpu *vcpu, u64 *exit_code) { - if (!__populate_fault_info(vcpu)) + if (!__populate_fault_info(vcpu)) { + /* + * The AT couldn't resolve the IPA, typically because its + * stage-1 walk took a stage-2 fault, such as an Access flag + * fault on an aged page-table page. If the guest still has a + * cached translation for the VA, it won't take that fault + * itself, and would replay the same permission fault forever. + * Drop this VMID's TLB entries on this CPU, so that the replay + * walks the page tables and faults with a valid HPFAR_EL2. + */ + dsb(nsh); /* ensure that AT completed before issuing the TLBI */ + __tlbi(vmalls12e1); + dsb(nsh); + isb(); return true; + } return false; } From cbf47fe57a568f178ac55176d98a13caba1d8598 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Wed, 21 Oct 2026 12:06:57 +0100 Subject: [PATCH 0180/2102] KVM: arm64: Clear the whole hugetlb folio when sanitising MTE tags sanitise_mte_tags() clears the tags of the pages about to be mapped at stage-2 before marking them tagged. For a hugetlb folio the flag covers every page in the folio, but the loop only covers the mapping being installed. Stage-2 maps a folio in pieces for the contiguous hugetlb sizes, and for any size under dirty logging. The first fault then marks the whole folio after clearing only its own piece, and the rest keeps its previous owner's tags for the guest to read. Clear the whole folio, as mte_sync_tags() does. Fixes: 25c17c4b55def ("hugetlb: arm64: add mte support") Reviewed-by: Lorenzo Stoakes (ARM) Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Reviewed-by: Catalin Marinas Link: https://patch.msgid.link/20261021110700.493315-2-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/mmu.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/arch/arm64/kvm/mmu.c b/arch/arm64/kvm/mmu.c index 1db10d8d6db737..7ddbcb66547548 100644 --- a/arch/arm64/kvm/mmu.c +++ b/arch/arm64/kvm/mmu.c @@ -1617,10 +1617,10 @@ static void sanitise_mte_tags(struct kvm *kvm, kvm_pfn_t pfn, } if (folio_test_hugetlb(folio)) { - /* Hugetlb has MTE flags set on head page only */ + /* A hugetlb folio is marked tagged as a whole, so clear every page */ if (folio_try_hugetlb_mte_tagging(folio)) { - for (i = 0; i < nr_pages; i++, page++) - mte_clear_page_tags(page_address(page)); + for (i = 0; i < folio_nr_pages(folio); i++) + mte_clear_page_tags(page_address(folio_page(folio, i))); folio_set_hugetlb_mte_tagged(folio); } return; From 62b9e1f75a3c39cfc38b3950bbad017ac5f95bcc Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Wed, 21 Oct 2026 12:06:58 +0100 Subject: [PATCH 0181/2102] KVM: arm64: Clear the whole hugetlb folio when storing MTE tags When KVM_ARM_MTE_COPY_TAGS copies tags into a page, it marks the page as tagged. For a hugetlb folio the flag covers every page in the folio. If the folio wasn't tagged yet, its other pages are marked as tagged with their previous owner's tags still in place. The stage-2 fault path then maps them into the guest without clearing them. The ioctl's read side also copies them out to the VMM. Clear the whole folio on its first tagging, before copying in this page's tags. Fixes: 25c17c4b55def ("hugetlb: arm64: add mte support") Reviewed-by: Lorenzo Stoakes (ARM) Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Reviewed-by: Catalin Marinas Link: https://patch.msgid.link/20261021110700.493315-3-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/guest.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/arch/arm64/kvm/guest.c b/arch/arm64/kvm/guest.c index 878ea4500c5c55..5ba8eb743029ab 100644 --- a/arch/arm64/kvm/guest.c +++ b/arch/arm64/kvm/guest.c @@ -1029,6 +1029,7 @@ int kvm_vm_ioctl_mte_copy_tags(struct kvm *kvm, void *maddr; unsigned long num_tags; struct folio *folio; + unsigned long i; if (!page) { ret = -EFAULT; @@ -1059,12 +1060,14 @@ int kvm_vm_ioctl_mte_copy_tags(struct kvm *kvm, /* * Only locking to serialise with a concurrent * __set_ptes() in the VMM but still overriding the - * tags, hence ignoring the return value. + * tags. A hugetlb folio is marked tagged as a whole, + * so its first tagging clears every page. */ - if (folio_test_hugetlb(folio)) - folio_try_hugetlb_mte_tagging(folio); - else + if (!folio_test_hugetlb(folio)) try_page_mte_tagging(page); + else if (folio_try_hugetlb_mte_tagging(folio)) + for (i = 0; i < folio_nr_pages(folio); i++) + mte_clear_page_tags(page_address(folio_page(folio, i))); num_tags = mte_copy_tags_from_user(maddr, tags, MTE_GRANULES_PER_PAGE); From 249e053eaacb2959794a5ee3d27737063f4e3dad Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Wed, 21 Oct 2026 12:06:59 +0100 Subject: [PATCH 0182/2102] KVM: arm64: Sanitise MTE tags when a permission fault installs a mapping The stage-2 fault path sanitises MTE tags only on translation faults, as a permission fault normally just relaxes an existing leaf. However, when the page is backed by a THP, a permission fault at page granule installs a block whose other pages may never have been mapped or sanitised. Once dirty logging is off, a guest write to a page mapped read-only during logging installs the block, and the guest can read the tags those pages' previous owners left. Sanitise whenever the fault path calls kvm_pgtable_stage2_map() rather than relaxing permissions. If the VMM replaces the VMA after the guest takes a permission fault but before vma_lookup(), that path would map and sanitise memory from the new VMA without checking it. Run the VM_MTE_ALLOWED check in kvm_s2_fault_compute_prot() on permission faults too. Fixes: ea7fc1bb1cd1b ("KVM: arm64: Introduce MTE VM feature") Reviewed-by: Lorenzo Stoakes (ARM) Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Reviewed-by: Catalin Marinas Link: https://patch.msgid.link/20261021110700.493315-4-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/mmu.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/arch/arm64/kvm/mmu.c b/arch/arm64/kvm/mmu.c index 7ddbcb66547548..5e46b5bfe099ce 100644 --- a/arch/arm64/kvm/mmu.c +++ b/arch/arm64/kvm/mmu.c @@ -2129,7 +2129,7 @@ static int kvm_s2_fault_compute_prot(const struct kvm_s2_fault_desc *s2fd, if (s2fd->nested) *prot = adjust_nested_exec_perms(kvm, s2fd->nested, *prot); - if (!kvm_s2_fault_is_perm(s2fd) && !s2vi->map_non_cacheable && kvm_has_mte(kvm)) { + if (!s2vi->map_non_cacheable && kvm_has_mte(kvm)) { /* Check the VMM hasn't introduced a new disallowed VMA */ if (!s2vi->mte_allowed) return -EFAULT; @@ -2195,9 +2195,6 @@ static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd, canonical_ipa = ALIGN_DOWN(canonical_ipa, mapping_size); } - if (!perm_fault_granule && !s2vi->map_non_cacheable && kvm_has_mte(kvm)) - sanitise_mte_tags(kvm, pfn, mapping_size); - /* * Under the premise of getting a FSC_PERM fault, we just need to relax * permissions only if mapping_size equals perm_fault_granule. Otherwise, @@ -2212,6 +2209,9 @@ static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd, ret = KVM_PGT_FN(kvm_pgtable_stage2_relax_perms)(pgt, gfn_to_gpa(gfn), prot, flags); } else { + if (!s2vi->map_non_cacheable && kvm_has_mte(kvm)) + sanitise_mte_tags(kvm, pfn, mapping_size); + ret = KVM_PGT_FN(kvm_pgtable_stage2_map)(pgt, gfn_to_gpa(gfn), mapping_size, __pfn_to_phys(pfn), prot, memcache, flags); From da9f24dc43361b1cdcbba2fee7b90f4706819fa7 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Wed, 21 Oct 2026 12:07:00 +0100 Subject: [PATCH 0183/2102] arm64: mte: Add mte_clear_folio_tags() mte_sync_tags(), sanitise_mte_tags() and kvm_vm_ioctl_mte_copy_tags() each open-code the loop that clears the tags of every page in a hugetlb folio. Add mte_clear_folio_tags() and use it in all three. kvm_vm_ioctl_mte_copy_tags() then tests for hugetlb first, as it does where it sets the tagged flag below. No functional change intended. Suggested-by: Lorenzo Stoakes (ARM) Signed-off-by: Fuad Tabba Reviewed-by: Catalin Marinas Reviewed-by: Lorenzo Stoakes (ARM) Link: https://patch.msgid.link/20261021110700.493315-5-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/mte.h | 4 ++++ arch/arm64/kernel/mte.c | 15 ++++++++++----- arch/arm64/kvm/guest.c | 10 +++++----- arch/arm64/kvm/mmu.c | 3 +-- 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/arch/arm64/include/asm/mte.h b/arch/arm64/include/asm/mte.h index 83f3b05fc78490..45ae6cabd5f1da 100644 --- a/arch/arm64/include/asm/mte.h +++ b/arch/arm64/include/asm/mte.h @@ -94,6 +94,7 @@ static inline bool try_page_mte_tagging(struct page *page) } void mte_zero_clear_page_tags(void *addr); +void mte_clear_folio_tags(struct folio *folio); void mte_sync_tags(pte_t pte, unsigned int nr_pages); void mte_copy_page_tags(void *kto, const void *kfrom); void mte_thread_init_user(void); @@ -126,6 +127,9 @@ static inline bool try_page_mte_tagging(struct page *page) static inline void mte_zero_clear_page_tags(void *addr) { } +static inline void mte_clear_folio_tags(struct folio *folio) +{ +} static inline void mte_sync_tags(pte_t pte, unsigned int nr_pages) { } diff --git a/arch/arm64/kernel/mte.c b/arch/arm64/kernel/mte.c index 31f5c6b0510e72..850bcee21e7709 100644 --- a/arch/arm64/kernel/mte.c +++ b/arch/arm64/kernel/mte.c @@ -36,6 +36,14 @@ DEFINE_STATIC_KEY_FALSE(mte_async_or_asymm_mode); EXPORT_SYMBOL_GPL(mte_async_or_asymm_mode); #endif +void mte_clear_folio_tags(struct folio *folio) +{ + unsigned long i; + + for (i = 0; i < folio_nr_pages(folio); i++) + mte_clear_page_tags(page_address(folio_page(folio, i))); +} + void mte_sync_tags(pte_t pte, unsigned int nr_pages) { struct page *page = pte_page(pte); @@ -43,12 +51,9 @@ void mte_sync_tags(pte_t pte, unsigned int nr_pages) unsigned long i; if (folio_test_hugetlb(folio)) { - unsigned long nr = folio_nr_pages(folio); - - /* Hugetlb MTE flags are set for head page only */ + /* A hugetlb folio is marked tagged as a whole, so clear every page */ if (folio_try_hugetlb_mte_tagging(folio)) { - for (i = 0; i < nr; i++, page++) - mte_clear_page_tags(page_address(page)); + mte_clear_folio_tags(folio); folio_set_hugetlb_mte_tagged(folio); } diff --git a/arch/arm64/kvm/guest.c b/arch/arm64/kvm/guest.c index 5ba8eb743029ab..ba4570c52a9162 100644 --- a/arch/arm64/kvm/guest.c +++ b/arch/arm64/kvm/guest.c @@ -1029,7 +1029,6 @@ int kvm_vm_ioctl_mte_copy_tags(struct kvm *kvm, void *maddr; unsigned long num_tags; struct folio *folio; - unsigned long i; if (!page) { ret = -EFAULT; @@ -1063,11 +1062,12 @@ int kvm_vm_ioctl_mte_copy_tags(struct kvm *kvm, * tags. A hugetlb folio is marked tagged as a whole, * so its first tagging clears every page. */ - if (!folio_test_hugetlb(folio)) + if (folio_test_hugetlb(folio)) { + if (folio_try_hugetlb_mte_tagging(folio)) + mte_clear_folio_tags(folio); + } else { try_page_mte_tagging(page); - else if (folio_try_hugetlb_mte_tagging(folio)) - for (i = 0; i < folio_nr_pages(folio); i++) - mte_clear_page_tags(page_address(folio_page(folio, i))); + } num_tags = mte_copy_tags_from_user(maddr, tags, MTE_GRANULES_PER_PAGE); diff --git a/arch/arm64/kvm/mmu.c b/arch/arm64/kvm/mmu.c index 5e46b5bfe099ce..155a3083c735e2 100644 --- a/arch/arm64/kvm/mmu.c +++ b/arch/arm64/kvm/mmu.c @@ -1619,8 +1619,7 @@ static void sanitise_mte_tags(struct kvm *kvm, kvm_pfn_t pfn, if (folio_test_hugetlb(folio)) { /* A hugetlb folio is marked tagged as a whole, so clear every page */ if (folio_try_hugetlb_mte_tagging(folio)) { - for (i = 0; i < folio_nr_pages(folio); i++) - mte_clear_page_tags(page_address(folio_page(folio, i))); + mte_clear_folio_tags(folio); folio_set_hugetlb_mte_tagged(folio); } return; From 98b2eab9345c502cb13ef2e347ab5a6c288db482 Mon Sep 17 00:00:00 2001 From: Wei-Lin Chang Date: Thu, 29 Oct 2026 17:52:37 +0000 Subject: [PATCH 0184/2102] KVM: arm64: Fix dirty logging detection in ring-only mode When checking whether a memslot has dirty logging enabled, the KVM_MEM_LOG_DIRTY_PAGES flag is the source of truth. Previously in memslot_is_logging() we were testing the dirty bitmap only and did not consider dirty ring. With the ring and no bitmap, a logged memslot can still get block mappings, so guest writes to most of a block are never logged and a migration can copy stale memory. Fix this by using kvm_slot_dirty_track_enabled() instead which checks KVM_MEM_LOG_DIRTY_PAGES, within memslot_is_logging(). Fixes: 9cb1096f8590 ("KVM: arm64: Enable ring-based dirty memory tracking") Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Signed-off-by: Wei-Lin Chang Cc: stable@vger.kernel.org Reviewed-by: Leonardo Bras Reviewed-by: Gavin Shan Link: https://patch.msgid.link/20261029175238.3214788-2-weilin.chang@arm.com Signed-off-by: Marc Zyngier --- arch/arm64/kvm/mmu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/arm64/kvm/mmu.c b/arch/arm64/kvm/mmu.c index 155a3083c735e2..178455d0c08516 100644 --- a/arch/arm64/kvm/mmu.c +++ b/arch/arm64/kvm/mmu.c @@ -176,7 +176,7 @@ static int kvm_mmu_split_huge_pages(struct kvm *kvm, phys_addr_t addr, static bool memslot_is_logging(struct kvm_memory_slot *memslot) { - return memslot->dirty_bitmap && !(memslot->flags & KVM_MEM_READONLY); + return kvm_slot_dirty_track_enabled(memslot) && !(memslot->flags & KVM_MEM_READONLY); } static int pkvm_flush_remote_tlbs(struct kvm *kvm) From 4bc0c9cd84767a978046c3b2a73dc932bdb8d9f9 Mon Sep 17 00:00:00 2001 From: Wei-Lin Chang Date: Thu, 29 Oct 2026 17:52:38 +0000 Subject: [PATCH 0185/2102] KVM: arm64: Remove stale remark on canonical IPA alignment Commit 3b8ce2b5132ae ("KVM: arm64: Use a variable for the canonical IPA in kvm_s2_fault_map()") created a variable to store the canonical IPA, instead of calculating it when needed. It moved the aligning just before mark_page_dirty_in_slot() to an earlier place but did not update the comment. Remove the stale part of the comment. Signed-off-by: Wei-Lin Chang Reviewed-by: Leonardo Bras Reviewed-by: Gavin Shan Reviewed-by: Fuad Tabba Link: https://patch.msgid.link/20261029175238.3214788-3-weilin.chang@arm.com Signed-off-by: Marc Zyngier --- arch/arm64/kvm/mmu.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/arch/arm64/kvm/mmu.c b/arch/arm64/kvm/mmu.c index 178455d0c08516..86aa0b6fa8b571 100644 --- a/arch/arm64/kvm/mmu.c +++ b/arch/arm64/kvm/mmu.c @@ -2231,11 +2231,7 @@ static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd, kvm_fault_unlock(kvm); kfree(mapping); - /* - * Mark the page dirty only if the fault is handled successfully, - * making sure we adjust the canonical IPA if the mapping size has - * been updated (via a THP upgrade, for example). - */ + /* Mark the page dirty only if the fault is handled successfully. */ if (writable && !ret) mark_page_dirty_in_slot(kvm, s2fd->memslot, gpa_to_gfn(canonical_ipa)); From 756cfa339d1b117676107049f650dad5414d6ec4 Mon Sep 17 00:00:00 2001 From: Selvin Xavier Date: Wed, 28 Oct 2026 04:33:58 -0700 Subject: [PATCH 0186/2102] RDMA/bnxt_re: Clear stale RCFW resp pointer when wait ends If the wait ends with ERR_DEVICE_DETACHED, bnxt_qplib_map_rc() returns 0 for destroy-type opcodes, so the caller sees a synthetic success without a CREQ. is_waiter_alive and resp are left set, resp keeps pointing at the caller's stack, and a late CREQ is copied into a dead frame. After the wait, take hwq->lock and, if the slot still holds this command's response buffer, clear is_waiter_alive and resp. This also covers the timeout case, where it is only defensive since is_waiter_alive was already cleared there. Return success without checking evnt->status when the slot still holds the buffer, since no completion was processed. Also reset the slot in the completion handler, in the same critical section that clears is_in_used, so that a second CREQ for the same cookie cannot be copied into the caller's buffer. With this, resp == evnt under the lock means no completion was processed. Clear crsqe->resp when __send_message_no_waiter() takes a slot as well, so a stale waiter can never match an internal command's slot by its own response buffer pointer. Fixes: 3022cc151197 ("RDMA/bnxt_re: Avoid the command wait if firmware is inactive") Fixes: 691eb7c6110f ("RDMA/bnxt_re: handle command completions after driver detect a timedout") Signed-off-by: Selvin Xavier Link: https://patch.msgid.link/20261028113404.33289-2-selvin.xavier@broadcom.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/bnxt_re/qplib_rcfw.c | 26 ++++++++++++++-------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c index 34d8aa12265de2..707687a8f30117 100644 --- a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c +++ b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c @@ -255,6 +255,7 @@ static void __send_message_no_waiter(struct bnxt_qplib_rcfw *rcfw, */ crsqe->is_internal_cmd = true; crsqe->is_waiter_alive = false; + crsqe->resp = NULL; crsqe->is_in_used = true; crsqe->req_size = __get_cmdq_base_cmd_size(msg->req, msg->req_sz); @@ -487,6 +488,7 @@ static int __bnxt_qplib_rcfw_send_message(struct bnxt_qplib_rcfw *rcfw, { struct creq_qp_event *evnt = (struct creq_qp_event *)msg->resp; struct bnxt_qplib_crsqe *crsqe; + bool pending; u16 cookie; int rc; u8 opcode; @@ -511,15 +513,21 @@ static int __bnxt_qplib_rcfw_send_message(struct bnxt_qplib_rcfw *rcfw, else rc = __poll_for_resp(rcfw, cookie); - if (rc) { - spin_lock_bh(&rcfw->cmdq.hwq.lock); - crsqe = &rcfw->crsqe_tbl[cookie]; + spin_lock_bh(&rcfw->cmdq.hwq.lock); + crsqe = &rcfw->crsqe_tbl[cookie]; + pending = false; + if (crsqe->resp == evnt) { + pending = true; crsqe->is_waiter_alive = false; - if (rc == -ENODEV) - set_bit(FIRMWARE_STALL_DETECTED, &rcfw->cmdq.flags); - spin_unlock_bh(&rcfw->cmdq.hwq.lock); - return -ETIMEDOUT; + crsqe->resp = NULL; } + if (rc == -ENODEV) + set_bit(FIRMWARE_STALL_DETECTED, &rcfw->cmdq.flags); + spin_unlock_bh(&rcfw->cmdq.hwq.lock); + if (rc) + return -ETIMEDOUT; + if (pending) + return 0; if (evnt->status) { /* failed with status */ @@ -703,8 +711,8 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw, is_waiter_alive = crsqe->is_waiter_alive; crsqe->req_size = 0; - if (!is_waiter_alive) - crsqe->resp = NULL; + crsqe->resp = NULL; + crsqe->is_waiter_alive = false; crsqe->is_in_used = false; From 5ea08e2dcf736a7c81cd3c33683a76cc66de10be Mon Sep 17 00:00:00 2001 From: Selvin Xavier Date: Wed, 28 Oct 2026 04:33:59 -0700 Subject: [PATCH 0187/2102] RDMA/bnxt_re: Honor a completion that races with a wait timeout If the wait helper gives up (timeout or firmware stall) and the CREQ tasklet processes the command before the waiter takes hwq->lock, the response is already copied into the caller's buffer and is_in_used is clear. The waiter still returns -ETIMEDOUT and may set FIRMWARE_STALL_DETECTED, and for CREATE_AH the handler skips destroy_timedout_ah() because the waiter was alive, so the AH leaks in firmware. Under the lock, if the slot no longer holds this command's response buffer, a completion was delivered. Use its status instead of failing. To keep that check valid, never reuse a cookie slot that is still in use: __send_message() returns -EAGAIN and __send_message_no_waiter() drops the internal command. A slot stays in use only while its completion is outstanding. If that completion never arrives, the cause is a PCI error or firmware still processing the command, so there is no point in posting more commands. Continuing to return -EAGAIN until firmware completes the command in order is intended; otherwise recovery is initiated. An internal destroy_ah dropped for the same reason leaks the AH in firmware; this is accepted and the comment in bnxt_qplib_service_creq() is updated to say so. Fixes: 691eb7c6110f ("RDMA/bnxt_re: handle command completions after driver detect a timedout") Signed-off-by: Selvin Xavier Link: https://patch.msgid.link/20261028113404.33289-3-selvin.xavier@broadcom.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/bnxt_re/qplib_rcfw.c | 31 ++++++++++++++++++---- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c index 707687a8f30117..1676262468004d 100644 --- a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c +++ b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c @@ -223,7 +223,7 @@ static int __block_for_resp(struct bnxt_qplib_rcfw *rcfw, u16 cookie) * Current design of this function is - * user must hold the completion queue hwq->lock. * user must have used existing completion and free the resources. - * this function will not check queue full condition. + * the command is dropped if the cookie slot is in use or the queue is full. * this function will explicitly set is_waiter_alive=false. * current use case is - send destroy_ah if create_ah is return * after waiter of create_ah is lost. It can be extended for other @@ -245,9 +245,17 @@ static void __send_message_no_waiter(struct bnxt_qplib_rcfw *rcfw, u8 *preq; cookie = cmdq->seq_num & RCFW_MAX_COOKIE_VALUE; - __set_cmdq_base_cookie(msg->req, msg->req_sz, cpu_to_le16(cookie)); crsqe = &rcfw->crsqe_tbl[cookie]; + if (crsqe->is_in_used || + bnxt_qplib_get_cmd_slots(msg->req) >= HWQ_FREE_SLOTS(hwq)) { + dev_warn_ratelimited(&rcfw->pdev->dev, + "CMDQ cookie %#x busy or CMDQ full, dropping internal command\n", + cookie); + return; + } + __set_cmdq_base_cookie(msg->req, msg->req_sz, cpu_to_le16(cookie)); + /* Set cmd_size in terms of 16B slots in req. */ bsize = bnxt_qplib_set_cmd_slots(msg->req); /* GET_CMD_SIZE would return number of slots in either case of tlv @@ -314,6 +322,12 @@ static int __send_message(struct bnxt_qplib_rcfw *rcfw, spin_unlock_bh(&hwq->lock); return -EAGAIN; } + if (crsqe->is_in_used) { + dev_info_ratelimited(&pdev->dev, + "CMDQ cookie %#x still in use\n", cookie); + spin_unlock_bh(&hwq->lock); + return -EAGAIN; + } if (msg->block) cookie |= RCFW_CMD_IS_BLOCKING; __set_cmdq_base_cookie(msg->req, msg->req_sz, cpu_to_le16(cookie)); @@ -520,6 +534,11 @@ static int __bnxt_qplib_rcfw_send_message(struct bnxt_qplib_rcfw *rcfw, pending = true; crsqe->is_waiter_alive = false; crsqe->resp = NULL; + } else if (rc) { + /* The completion was processed after the wait gave up but + * before the lock was taken. The response is valid. + */ + rc = 0; } if (rc == -ENODEV) set_bit(FIRMWARE_STALL_DETECTED, &rcfw->cmdq.flags); @@ -726,9 +745,11 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw, * so let's destroy the same address vector since it is * no more used in stack. We don't care about completion * in __send_message_no_waiter. - * If destroy_ah is failued by firmware, there will be AH - * resource leak and relatively not critical + unlikely - * scenario. Current design is not to handle such case. + * If destroy_ah is failed by firmware, or is dropped locally + * because the cookie slot is in use or the CMDQ is full, + * there will be AH resource leak and relatively not + * critical + unlikely scenario. Current design is not to + * handle such case. */ if (!is_waiter_alive && !qp_event->status && qp_event->event == CREQ_QP_EVENT_EVENT_CREATE_AH) From 02df984377d14381cdddb3d94bfc263486590d5b Mon Sep 17 00:00:00 2001 From: Selvin Xavier Date: Wed, 28 Oct 2026 04:34:00 -0700 Subject: [PATCH 0188/2102] RDMA/bnxt_re: Do not treat CQ error notification as a command completion creq_cq_error_notification has the same type as creq_qp_event, and its cq_err_reason (1-6) sits where creq_qp_event carries the cookie. With no case for the event in bnxt_qplib_process_qp_event(), it is handled as a completion for cookie 1-6 and can corrupt an outstanding command. Handle the event explicitly and do not touch crsqe_tbl. The event is intentionally not reported to the stack for now; that will be handled in a later series. Fixes: 1ac5a4047975 ("RDMA/bnxt_re: Add bnxt_re RoCE driver") Signed-off-by: Selvin Xavier Link: https://patch.msgid.link/20261028113404.33289-4-selvin.xavier@broadcom.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/bnxt_re/qplib_rcfw.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c index 1676262468004d..da6c7779ff873a 100644 --- a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c +++ b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c @@ -647,6 +647,7 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw, struct creq_qp_event *qp_event, u32 *num_wait) { + struct creq_cq_error_notification *cq_err_event; struct creq_qp_error_notification *err_event; struct bnxt_qplib_hwq *hwq = &rcfw->cmdq.hwq; struct bnxt_qplib_crsqe *crsqe; @@ -661,6 +662,13 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw, pdev = rcfw->pdev; print_hex_dump_bytes("event: ", DUMP_PREFIX_OFFSET, qp_event, sizeof(*qp_event)); switch (qp_event->event) { + case CREQ_QP_EVENT_EVENT_CQ_ERROR_NOTIFICATION: + cq_err_event = (struct creq_cq_error_notification *)qp_event; + dev_dbg(&pdev->dev, + "Received CQ error notification cqid 0x%x, reason 0x%x\n", + le32_to_cpu(cq_err_event->xid), + cq_err_event->cq_err_reason); + break; case CREQ_QP_EVENT_EVENT_QP_ERROR_NOTIFICATION: err_event = (struct creq_qp_error_notification *)qp_event; qp_id = le32_to_cpu(err_event->xid); From fbe33b99673d25cdddb6a019b0b237a3bc39054e Mon Sep 17 00:00:00 2001 From: Saravanan Vajravel Date: Wed, 28 Oct 2026 04:34:01 -0700 Subject: [PATCH 0189/2102] RDMA/bnxt_re: Drop RCFW completions for cookies with no outstanding command A duplicate CREQ completion for an idle cookie slot is processed as a command response. It can decrement timeout_send a second time and, for CREATE_AH, send a spurious DESTROY_AH. Log and drop such completions. Fixes: 691eb7c6110f ("RDMA/bnxt_re: handle command completions after driver detect a timedout") Signed-off-by: Saravanan Vajravel Signed-off-by: Selvin Xavier Link: https://patch.msgid.link/20261028113404.33289-5-selvin.xavier@broadcom.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/bnxt_re/qplib_rcfw.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c index da6c7779ff873a..7278e85a8a409d 100644 --- a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c +++ b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c @@ -718,6 +718,14 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw, return rc; } + if (!crsqe->is_in_used) { + dev_warn_ratelimited(&pdev->dev, + "event %#x for cookie %#x with no outstanding command\n", + qp_event->event, cookie); + spin_unlock(&hwq->lock); + return rc; + } + if (crsqe->is_internal_cmd && !qp_event->status) atomic_dec(&rcfw->timeout_send); From f7da2c5c60017d2c2bf3453d5aed68a3551e9e99 Mon Sep 17 00:00:00 2001 From: Selvin Xavier Date: Wed, 28 Oct 2026 04:34:02 -0700 Subject: [PATCH 0190/2102] RDMA/bnxt_re: Reset cqe pointer each poll_cq iteration In bnxt_re_poll_cq(), cqe advances for every polled CQE, but budget is decremented only for completions reported to the caller. Skipped CQEs (looped-back QP1 receive, shadow-QP completions, unknown opcode) leave cqe ahead of where budget implies, so the next poll can write past the end of cq->cql[]. cql[] is only scratch space, so reset cqe to the start of the array on each iteration of the outer loop. Fixes: 1ac5a4047975 ("RDMA/bnxt_re: Add bnxt_re RoCE driver") Signed-off-by: Selvin Xavier Link: https://patch.msgid.link/20261028113404.33289-6-selvin.xavier@broadcom.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/bnxt_re/ib_verbs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/infiniband/hw/bnxt_re/ib_verbs.c b/drivers/infiniband/hw/bnxt_re/ib_verbs.c index ac15372376a236..796ea795c5b753 100644 --- a/drivers/infiniband/hw/bnxt_re/ib_verbs.c +++ b/drivers/infiniband/hw/bnxt_re/ib_verbs.c @@ -4328,8 +4328,8 @@ int bnxt_re_poll_cq(struct ib_cq *ib_cq, int num_entries, struct ib_wc *wc) ibdev_err(&cq->rdev->ibdev, "POLL CQ : no CQL to use"); goto exit; } - cqe = &cq->cql[0]; while (budget) { + cqe = &cq->cql[0]; lib_qp = NULL; ncqe = bnxt_qplib_poll_cq(&cq->qplib_cq, cqe, budget, &lib_qp); if (lib_qp) { From 6be33e5725ee7f0db72577104daaeb569f5938bb Mon Sep 17 00:00:00 2001 From: Selvin Xavier Date: Wed, 28 Oct 2026 04:34:03 -0700 Subject: [PATCH 0191/2102] RDMA/bnxt_re: Remove shared page mmap entry on alloc_ucontext failure The uverbs core does not call dealloc_ucontext() when alloc_ucontext() fails. If bnxt_re_alloc_ucontext() fails after inserting the shared page mmap entry, the entry is leaked. Remove it in the failure path. Fixes: 24ce94782c48 ("RDMA/bnxt_re: Use the common mmap helper functions") Signed-off-by: Selvin Xavier Link: https://patch.msgid.link/20261028113404.33289-7-selvin.xavier@broadcom.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/bnxt_re/ib_verbs.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/infiniband/hw/bnxt_re/ib_verbs.c b/drivers/infiniband/hw/bnxt_re/ib_verbs.c index 796ea795c5b753..1ca481806578e6 100644 --- a/drivers/infiniband/hw/bnxt_re/ib_verbs.c +++ b/drivers/infiniband/hw/bnxt_re/ib_verbs.c @@ -4909,6 +4909,8 @@ int bnxt_re_alloc_ucontext(struct ib_ucontext *ctx, struct ib_udata *udata) return 0; cfail: + rdma_user_mmap_entry_remove(uctx->shpage_mmap); + uctx->shpage_mmap = NULL; free_page((unsigned long)uctx->shpg); uctx->shpg = NULL; fail: From ac39883b95322df170461d980953b0fcbf993332 Mon Sep 17 00:00:00 2001 From: Selvin Xavier Date: Wed, 28 Oct 2026 04:34:04 -0700 Subject: [PATCH 0192/2102] RDMA/bnxt_re: Bound FRMR page list by max_num_sg bnxt_re_set_page() checks against frpl->max_pg_ptrs, which is rounded up to a power of two, while mr->pages[] is allocated with max_num_sg entries. For a non-power-of-two max_num_sg, ib_sg_to_pages() can write past the end of mr->pages[]. Track the allocated size in mr->max_pages and bound against it. Also reject max_num_sg of 0. Fixes: 1ac5a4047975 ("RDMA/bnxt_re: Add bnxt_re RoCE driver") Signed-off-by: Selvin Xavier Link: https://patch.msgid.link/20261028113404.33289-8-selvin.xavier@broadcom.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/bnxt_re/ib_verbs.c | 5 +++-- drivers/infiniband/hw/bnxt_re/ib_verbs.h | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/infiniband/hw/bnxt_re/ib_verbs.c b/drivers/infiniband/hw/bnxt_re/ib_verbs.c index 1ca481806578e6..811f59f02f7584 100644 --- a/drivers/infiniband/hw/bnxt_re/ib_verbs.c +++ b/drivers/infiniband/hw/bnxt_re/ib_verbs.c @@ -4555,7 +4555,7 @@ static int bnxt_re_set_page(struct ib_mr *ib_mr, u64 addr) { struct bnxt_re_mr *mr = container_of(ib_mr, struct bnxt_re_mr, ib_mr); - if (unlikely(mr->npages == mr->qplib_frpl.max_pg_ptrs)) + if (unlikely(mr->npages == mr->max_pages)) return -ENOMEM; mr->pages[mr->npages++] = addr; @@ -4584,7 +4584,7 @@ struct ib_mr *bnxt_re_alloc_mr(struct ib_pd *ib_pd, enum ib_mr_type type, ibdev_dbg(&rdev->ibdev, "MR type 0x%x not supported", type); return ERR_PTR(-EINVAL); } - if (max_num_sg > MAX_PBL_LVL_1_PGS) + if (!max_num_sg || max_num_sg > MAX_PBL_LVL_1_PGS) return ERR_PTR(-EINVAL); mr = kzalloc_obj(*mr); @@ -4603,6 +4603,7 @@ struct ib_mr *bnxt_re_alloc_mr(struct ib_pd *ib_pd, enum ib_mr_type type, mr->ib_mr.lkey = mr->qplib_mr.lkey; mr->ib_mr.rkey = mr->ib_mr.lkey; + mr->max_pages = max_num_sg; mr->pages = kzalloc_objs(u64, max_num_sg); if (!mr->pages) { rc = -ENOMEM; diff --git a/drivers/infiniband/hw/bnxt_re/ib_verbs.h b/drivers/infiniband/hw/bnxt_re/ib_verbs.h index b7b33f6acf9109..d12cadaef10c56 100644 --- a/drivers/infiniband/hw/bnxt_re/ib_verbs.h +++ b/drivers/infiniband/hw/bnxt_re/ib_verbs.h @@ -124,6 +124,7 @@ struct bnxt_re_mr { struct ib_umem *ib_umem; struct bnxt_qplib_mrw qplib_mr; u32 npages; + u32 max_pages; u64 *pages; struct bnxt_qplib_frpl qplib_frpl; }; From d706625c62b45135ffd6f40b669081c4896dde6f Mon Sep 17 00:00:00 2001 From: Jacob Moroni Date: Thu, 22 Oct 2026 21:06:49 +0000 Subject: [PATCH 0193/2102] RDMA/irdma: Fix FRWR logic for PAGE_SIZE > 4K The HW only supports 1G, 2M, and 4K page sizes, but some ULPs pass PAGE_SIZE to ib_map_mr_sg(), and PAGE_SIZE can be some multiple of 4K (64K arm kernels, etc.). The HW can still support these scenarios, but we must force it to use 4K pages. The max_fast_reg_page_list_len and page_cnt during MR allocation must also be scaled to accommodate for the additional PBLEs that will be used when ib_sg_to_pages() ends up producing more pages than what would have otherwise been required with the original page size. It is worth noting that this change avoids this over-allocation/cracking in the off chance that a 1G or 2M PAGE_SIZE is ever used; it's only applicable when PAGE_SIZE is some power of 2 multiple of 4K that is not currently supported by HW. This was discovered by encountering SMMU faults when running kernel NFS/RDMA on a 64K kernel, which was due to the page list holding PAGE_SIZE entries while the WQE was indicating 4K, so HW was translating every access after the first 4K incorrectly. Fixes: b48c24c2d710 ("RDMA/irdma: Implement device supported verb APIs") Tested-by: Leah Li Signed-off-by: Jacob Moroni Link: https://patch.msgid.link/20261022210650.1182000-2-jmoroni@google.com Acked-by: Tatyana Nikolova Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/irdma/ctrl.c | 4 +++- drivers/infiniband/hw/irdma/defs.h | 1 + drivers/infiniband/hw/irdma/verbs.c | 36 +++++++++++++++++++++++++++-- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/drivers/infiniband/hw/irdma/ctrl.c b/drivers/infiniband/hw/irdma/ctrl.c index 1c2ad5773b9f7d..ef8627f070ce76 100644 --- a/drivers/infiniband/hw/irdma/ctrl.c +++ b/drivers/infiniband/hw/irdma/ctrl.c @@ -1703,8 +1703,10 @@ int irdma_sc_mr_fast_register(struct irdma_sc_qp *qp, page_size = IRDMA_PAGE_SIZE_1G; else if (info->page_size == 0x200000) page_size = IRDMA_PAGE_SIZE_2M; - else + else if (info->page_size == 0x1000) page_size = IRDMA_PAGE_SIZE_4K; + else + return -EINVAL; sq_info.wr_id = info->wr_id; sq_info.signaled = info->signaled; diff --git a/drivers/infiniband/hw/irdma/defs.h b/drivers/infiniband/hw/irdma/defs.h index d6a3152959dde6..eb91796648842e 100644 --- a/drivers/infiniband/hw/irdma/defs.h +++ b/drivers/infiniband/hw/irdma/defs.h @@ -159,6 +159,7 @@ enum irdma_protocol_used { #define IRDMA_HW_PAGE_SIZE 4096 #define IRDMA_HW_PAGE_SHIFT 12 +#define IRDMA_HW_PAGES_PER_PAGE (PAGE_SIZE >> IRDMA_HW_PAGE_SHIFT) #define IRDMA_CQE_QTYPE_RQ 0 #define IRDMA_CQE_QTYPE_SQ 1 diff --git a/drivers/infiniband/hw/irdma/verbs.c b/drivers/infiniband/hw/irdma/verbs.c index c91c55917de919..9443e9732c4a3b 100644 --- a/drivers/infiniband/hw/irdma/verbs.c +++ b/drivers/infiniband/hw/irdma/verbs.c @@ -2,6 +2,21 @@ /* Copyright (c) 2015 - 2021 Intel Corporation */ #include "main.h" +/** + * irdma_fmr_pages_per_page() - HW pages needed per PAGE_SIZE page in an FRWR. + * @dev: sc device + * + * If PAGE_SIZE is one of the HW supported page sizes, then it can be directly + * used. Otherwise, we need to break PAGE_SIZE into multiple HW (4K) pages. + */ +static u32 irdma_fmr_pages_per_page(struct irdma_sc_dev *dev) +{ + if (PAGE_SIZE & dev->hw_attrs.page_size_cap) + return 1; + + return IRDMA_HW_PAGES_PER_PAGE; +} + /** * irdma_query_device - get device attributes * @ibdev: device pointer from stack @@ -58,7 +73,8 @@ static int irdma_query_device(struct ib_device *ibdev, props->max_mcast_grp = rf->max_mcg; props->max_mcast_qp_attach = IRDMA_MAX_MGS_PER_CTX; props->max_total_mcast_qp_attach = rf->max_qp * IRDMA_MAX_MGS_PER_CTX; - props->max_fast_reg_page_list_len = IRDMA_MAX_PAGES_PER_FMR; + props->max_fast_reg_page_list_len = + IRDMA_MAX_PAGES_PER_FMR / irdma_fmr_pages_per_page(&rf->sc_dev); props->max_srq = rf->max_srq - rf->used_srqs; props->max_srq_wr = IRDMA_MAX_SRQ_WRS; props->max_srq_sge = hw_attrs->uk_attrs.max_hw_wq_frags; @@ -3208,12 +3224,16 @@ static struct ib_mr *irdma_alloc_mr(struct ib_pd *pd, enum ib_mr_type mr_type, u32 max_num_sg) { struct irdma_device *iwdev = to_iwdev(pd->device); + u32 pages_per_page = irdma_fmr_pages_per_page(&iwdev->rf->sc_dev); struct irdma_pble_alloc *palloc; struct irdma_pbl *iwpbl; struct irdma_mr *iwmr; u32 stag; int err_code; + if (max_num_sg > IRDMA_MAX_PAGES_PER_FMR / pages_per_page) + return ERR_PTR(-EINVAL); + iwmr = kzalloc_obj(*iwmr); if (!iwmr) return ERR_PTR(-ENOMEM); @@ -3233,7 +3253,12 @@ static struct ib_mr *irdma_alloc_mr(struct ib_pd *pd, enum ib_mr_type mr_type, iwpbl->iwmr = iwmr; iwmr->type = IRDMA_MEMREG_TYPE_MEM; palloc = &iwpbl->pble_alloc; - iwmr->page_cnt = max_num_sg; + /* Some ULPs pass PAGE_SIZE to ib_map_mr_sg() but PAGE_SIZE can be some + * multiple of 4K that the HW does not natively support. We can work + * around this by cracking the larger page into multiple 4K pages, but + * page_cnt needs to be scaled. + */ + iwmr->page_cnt = max_num_sg * pages_per_page; /* Use system PAGE_SIZE as the sg page sizes are unknown at this point */ iwmr->len = max_num_sg * PAGE_SIZE; err_code = irdma_get_pble(iwdev->rf->pble_rsrc, palloc, iwmr->page_cnt, @@ -3297,8 +3322,15 @@ static int irdma_set_page(struct ib_mr *ibmr, u64 addr) static int irdma_map_mr_sg(struct ib_mr *ibmr, struct scatterlist *sg, int sg_nents, unsigned int *sg_offset) { + struct irdma_device *iwdev = to_iwdev(ibmr->device); struct irdma_mr *iwmr = to_iwmr(ibmr); + /* HW only supports 4K, 2M and 1G pages, but some ULPs pass PAGE_SIZE + * which can be some multiple of 4K that we do not support, so force 4K. + */ + if (!(ibmr->page_size & iwdev->rf->sc_dev.hw_attrs.page_size_cap)) + ibmr->page_size = SZ_4K; + iwmr->npages = 0; return ib_sg_to_pages(ibmr, sg, sg_nents, sg_offset, irdma_set_page); From cefc2270e42baed46d64d7d79fa23172bbad9533 Mon Sep 17 00:00:00 2001 From: Jacob Moroni Date: Thu, 22 Oct 2026 21:06:50 +0000 Subject: [PATCH 0194/2102] RDMA/irdma: Fix paged PBLE and virtual AEQ for PAGE_SIZE > 4K HMC page descriptors and the virtual AEQ PBL always assume 4K HW pages, but irdma_map_vm_page_list() returns one DMA address per PAGE_SIZE page and irdma_pble_get_paged_mem() sizes the chunk as PAGE_SIZE * pg_cnt. This breaks when PAGE_SIZE is greater than 4K. For example, with a 64K PAGE_SIZE, the second HW page points to vaddr+64K whereas the driver assumes it to be at vaddr+4096, etc. It also ends up using an incorrect chunk size which causes each paged chunk to claim 16x more PBL entries than what actually exist. Fix these issues by taking into account the potential difference between the HW page size (4K) and the system PAGE_SIZE during allocation and mapping (so on a 64K kernel, each page ends up populating 16 PDs, etc.). Fixes: 44d9e52977a1 ("RDMA/irdma: Implement device initialization definitions") Fixes: 915cc7ac0f8e ("RDMA/irdma: Add miscellaneous utility definitions") Tested-by: Leah Li Signed-off-by: Jacob Moroni Link: https://patch.msgid.link/20261022210650.1182000-3-jmoroni@google.com Acked-by: Tatyana Nikolova Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/irdma/hw.c | 4 ++-- drivers/infiniband/hw/irdma/utils.c | 22 +++++++++++++--------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/drivers/infiniband/hw/irdma/hw.c b/drivers/infiniband/hw/irdma/hw.c index fbb8fb47d0d167..1d57b3c9f4906b 100644 --- a/drivers/infiniband/hw/irdma/hw.c +++ b/drivers/infiniband/hw/irdma/hw.c @@ -700,7 +700,7 @@ static void irdma_destroy_cqp(struct irdma_pci_f *rf) static void irdma_destroy_virt_aeq(struct irdma_pci_f *rf) { struct irdma_aeq *aeq = &rf->aeq; - u32 pg_cnt = DIV_ROUND_UP(aeq->mem.size, PAGE_SIZE); + u32 pg_cnt = DIV_ROUND_UP(aeq->mem.size, IRDMA_HW_PAGE_SIZE); dma_addr_t *pg_arr = (dma_addr_t *)aeq->palloc.level1.addr; irdma_unmap_vm_page_list(&rf->hw, pg_arr, pg_cnt); @@ -1479,7 +1479,7 @@ static int irdma_create_virt_aeq(struct irdma_pci_f *rf, u32 size) if (!aeq->mem.va) return -ENOMEM; - pg_cnt = DIV_ROUND_UP(aeq->mem.size, PAGE_SIZE); + pg_cnt = DIV_ROUND_UP(aeq->mem.size, IRDMA_HW_PAGE_SIZE); status = irdma_get_pble(rf->pble_rsrc, &aeq->palloc, pg_cnt, true); if (status) { vfree(aeq->mem.va); diff --git a/drivers/infiniband/hw/irdma/utils.c b/drivers/infiniband/hw/irdma/utils.c index 290ad02ed65754..3efc4125bb59cc 100644 --- a/drivers/infiniband/hw/irdma/utils.c +++ b/drivers/infiniband/hw/irdma/utils.c @@ -2199,20 +2199,24 @@ int irdma_map_vm_page_list(struct irdma_hw *hw, void *va, dma_addr_t *pg_dma, u32 pg_cnt) { struct page *vm_page; - int i; + dma_addr_t dma; + u32 i, j; u8 *addr; addr = (u8 *)(uintptr_t)va; - for (i = 0; i < pg_cnt; i++) { + for (i = 0; i < pg_cnt; i += IRDMA_HW_PAGES_PER_PAGE) { vm_page = vmalloc_to_page(addr); if (!vm_page) goto err; - pg_dma[i] = dma_map_page(hw->device, vm_page, 0, PAGE_SIZE, - DMA_BIDIRECTIONAL); - if (dma_mapping_error(hw->device, pg_dma[i])) + dma = dma_map_page(hw->device, vm_page, 0, PAGE_SIZE, + DMA_BIDIRECTIONAL); + if (dma_mapping_error(hw->device, dma)) goto err; + for (j = 0; j < IRDMA_HW_PAGES_PER_PAGE && i + j < pg_cnt; j++) + pg_dma[i + j] = dma + j * IRDMA_HW_PAGE_SIZE; + addr += PAGE_SIZE; } @@ -2225,9 +2229,9 @@ int irdma_map_vm_page_list(struct irdma_hw *hw, void *va, dma_addr_t *pg_dma, void irdma_unmap_vm_page_list(struct irdma_hw *hw, dma_addr_t *pg_dma, u32 pg_cnt) { - int i; + u32 i; - for (i = 0; i < pg_cnt; i++) + for (i = 0; i < pg_cnt; i += IRDMA_HW_PAGES_PER_PAGE) dma_unmap_page(hw->device, pg_dma[i], PAGE_SIZE, DMA_BIDIRECTIONAL); } @@ -2254,7 +2258,7 @@ void irdma_pble_free_paged_mem(struct irdma_chunk *chunk) /** * irdma_pble_get_paged_mem -allocate paged memory for pbles * @chunk: chunk to add for paged memory - * @pg_cnt: number of pages needed + * @pg_cnt: number of HW (4K) pages needed */ int irdma_pble_get_paged_mem(struct irdma_chunk *chunk, u32 pg_cnt) { @@ -2265,7 +2269,7 @@ int irdma_pble_get_paged_mem(struct irdma_chunk *chunk, u32 pg_cnt) if (!chunk->dmainfo.dmaaddrs) return -ENOMEM; - size = PAGE_SIZE * pg_cnt; + size = pg_cnt * IRDMA_HW_PAGE_SIZE; va = vmalloc(size); if (!va) goto err; From 0353b51965883cf70dad162908e07395f242000f Mon Sep 17 00:00:00 2001 From: "Jiri Slaby (SUSE)" Date: Tue, 3 Nov 2026 12:16:37 +0100 Subject: [PATCH 0195/2102] serial: 8250_exar: check priv->gpio properly priv->gpio is set by platform_device_register_full(), which returns error-encoded pointers on failure, not NULL. Sashiko reported: > Does __xr17v35x_register_gpio() return an ERR_PTR if > platform_device_register_full() fails? > > If it does, we might be storing an error pointer directly into > priv->gpio in xr17v35x_register_gpio() without validating it with > IS_ERR(). Because the error is ignored, the device probe > successfully continues. Before commit 1145d1a0703f ("serial: 8250_exar: use platform_device_register_full()"), __xr17v35x_register_gpio() returned NULL on any failure (platform_device_alloc(), device_add_software_node() or platform_device_add() failing were all turned into a NULL return). The plain truthy check in xr17v35x_unregister_gpio() matched that convention. That commit switched registration to platform_device_register_full(), which reports failure as an ERR_PTR() instead of NULL, but the unregister check was never updated to match. As a result, a failed registration left an error pointer in priv->gpio, and unbind would tear it down as if it were a real platform_device, dereferencing the encoded error value in device_remove_software_node() and platform_device_unregister(). Use IS_ERR_OR_NULL() instead, so both the unset (non-EXAR vendor, priv->gpio never assigned) and failed-registration (ERR_PTR) cases are skipped. Fixes: 1145d1a0703f ("serial: 8250_exar: use platform_device_register_full()") Signed-off-by: Jiri Slaby (SUSE) Cc: stable@vger.kernel.org Assisted-by: LLM Link: https://lore.kernel.org/all/sashiko-outbox-170895@kernel.org/ Link: https://patch.msgid.link/28c09cf858795491f66667781bf79fb6a603f159.1793704520.git.jirislaby@kernel.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/serial/8250/8250_exar.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/tty/serial/8250/8250_exar.c b/drivers/tty/serial/8250/8250_exar.c index 57847c5bd2fcf6..b1e20fd4cfd281 100644 --- a/drivers/tty/serial/8250/8250_exar.c +++ b/drivers/tty/serial/8250/8250_exar.c @@ -1181,7 +1181,7 @@ static int xr17v35x_register_gpio(struct exar8250 *priv, struct pci_dev *pcidev, static void xr17v35x_unregister_gpio(struct exar8250 *priv) { - if (priv->gpio) { + if (!IS_ERR_OR_NULL(priv->gpio)) { __xr17v35x_unregister_gpio(priv->gpio); priv->gpio = NULL; } From 93db7f4e32e2d5f6c63e724452814bccb5bd6773 Mon Sep 17 00:00:00 2001 From: "Jiri Slaby (SUSE)" Date: Tue, 3 Nov 2026 12:16:38 +0100 Subject: [PATCH 0196/2102] serial: 8250_hp300: reorder HPDCA code To have less ifdefs (code is now under one) and no forward declarations. Signed-off-by: Jiri Slaby (SUSE) Link: https://patch.msgid.link/f4dbbb45248771baa130e56bcb0b1916cd909256.1793704520.git.jirislaby@kernel.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/serial/8250/8250_hp300.c | 62 ++++++++++++---------------- 1 file changed, 26 insertions(+), 36 deletions(-) diff --git a/drivers/tty/serial/8250/8250_hp300.c b/drivers/tty/serial/8250/8250_hp300.c index e9599c5c2feada..68ce5972c296b3 100644 --- a/drivers/tty/serial/8250/8250_hp300.c +++ b/drivers/tty/serial/8250/8250_hp300.c @@ -34,29 +34,6 @@ struct hp300_port { static struct hp300_port *hp300_ports; #endif -#ifdef CONFIG_HPDCA - -static int hpdca_init_one(struct dio_dev *d, - const struct dio_device_id *ent); -static void hpdca_remove_one(struct dio_dev *d); - -static struct dio_device_id hpdca_dio_tbl[] = { - { DIO_ID_DCA0 }, - { DIO_ID_DCA0REM }, - { DIO_ID_DCA1 }, - { DIO_ID_DCA1REM }, - { 0 } -}; - -static struct dio_driver hpdca_driver = { - .name = "hpdca", - .id_table = hpdca_dio_tbl, - .probe = hpdca_init_one, - .remove = hpdca_remove_one, -}; - -#endif - static unsigned int num_ports; extern int hp300_uart_scode; @@ -197,6 +174,32 @@ static int hpdca_init_one(struct dio_dev *d, return 0; } + +static void hpdca_remove_one(struct dio_dev *d) +{ + struct uart_8250_port *uport = dio_get_drvdata(d); + + if (d->resource.start) { + /* Disable board-interrupts */ + out_8(d->resource.start + DIO_VIRADDRBASE + DCA_IC, 0); + } + serial8250_unregister_port(uport); +} + +static struct dio_device_id hpdca_dio_tbl[] = { + { DIO_ID_DCA0 }, + { DIO_ID_DCA0REM }, + { DIO_ID_DCA1 }, + { DIO_ID_DCA1REM }, + { 0 } +}; + +static struct dio_driver hpdca_driver = { + .name = "hpdca", + .id_table = hpdca_dio_tbl, + .probe = hpdca_init_one, + .remove = hpdca_remove_one, +}; #endif static int __init hp300_8250_init(void) @@ -280,19 +283,6 @@ static int __init hp300_8250_init(void) return 0; } -#ifdef CONFIG_HPDCA -static void hpdca_remove_one(struct dio_dev *d) -{ - struct uart_8250_port *uport = dio_get_drvdata(d); - - if (d->resource.start) { - /* Disable board-interrupts */ - out_8(d->resource.start + DIO_VIRADDRBASE + DCA_IC, 0); - } - serial8250_unregister_port(uport); -} -#endif - static void __exit hp300_8250_exit(void) { #ifdef CONFIG_HPAPCI From 895dc0eaa2779ff46a0b2a20b5ce9eb0b1125cb2 Mon Sep 17 00:00:00 2001 From: "Jiri Slaby (SUSE)" Date: Tue, 3 Nov 2026 12:16:39 +0100 Subject: [PATCH 0197/2102] tty: fix misapplied compat_ptr() in tty_compat_ioctl() Since commit f0193d3ea73b below, `cmd` was converted with compat_ptr(), while `arg` was passed to ld->ops->ioctl() unmodified. Fix it so `cmd` stays `cmd` and `arg` gets converted through compat_ptr() as intended. Notes: 2) compat_ptr() did nothing to `cmd`, provided it is uint, 1) compat_ptr() is no-op everywhere (was different on s390 before 8e0b986c59c6 ("s390: Remove compat support")), 3) `arg` might not have been chopped correctly until 8e0b986c59c6. But I am not sure why noone noticed all those (7) years (from f0193d3ea73b to 8e0b986c59c6)? Fixes: f0193d3ea73b ("change semantics of ldisc ->compat_ioctl()") Signed-off-by: Jiri Slaby (SUSE) Cc: stable@vger.kernel.org # applicable from 4.20 to 6.18 incl Assisted-by: LLM Link: https://patch.msgid.link/63e9d84a1e8e23852423206cf3f8907aafc88f17.1793704520.git.jirislaby@kernel.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/tty_io.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/tty/tty_io.c b/drivers/tty/tty_io.c index 1a6c8a1bc764a3..150052f6d9dbf2 100644 --- a/drivers/tty/tty_io.c +++ b/drivers/tty/tty_io.c @@ -2969,8 +2969,7 @@ static long tty_compat_ioctl(struct file *file, unsigned int cmd, if (ld->ops->compat_ioctl) retval = ld->ops->compat_ioctl(tty, cmd, arg); if (retval == -ENOIOCTLCMD && ld->ops->ioctl) - retval = ld->ops->ioctl(tty, (unsigned long)compat_ptr(cmd), - arg); + retval = ld->ops->ioctl(tty, cmd, (unsigned long)compat_ptr(arg)); tty_ldisc_deref(ld); return retval; From 5d1d814408c1c8e797031eac8ddd40de1a9e8e93 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Tue, 27 Oct 2026 12:06:27 +0100 Subject: [PATCH 0198/2102] vt: serialise the producers of the flip buffer Typing on a virtual console while the console replies to an escape sequence can make the kernel write past the end of a buffer. A user who can write to the foreground console can cause this on purpose if they can also inject key events, through /dev/uinput or by writing to the /dev/input/event* node of a keyboard. Input for a tty goes through the flip buffer of its port. A driver inserts the data with tty_insert_flip_*() and then calls tty_flip_buffer_push() to pass it on to the line discipline. The insert functions take no lock: they check that the current struct tty_buffer has room, copy the data to offset ->used, and then advance ->used. So a flip buffer supports only one producer at a time, and a driver that has several must serialise them. Four functions feed the flip buffer of a virtual console: - put_queue(), puts_queue() and fn_send_intr() insert typed characters and breaks for the keyboard handler. They run under kbd_event_lock. - respond_string() inserts the reply when a program writes an escape sequence that requests one, such as a cursor position report. It runs under the console lock. The keyboard handler gets its events from the input layer and feeds the foreground console. Key events that a program writes to /dev/uinput or to an event node reach it in the same way as typed keys. The keyboard handler and respond_string() share no lock, so they can interleave: keyboard handler respond_string() ================ ================ room check passes room check passes memcpy() to offset used used += len memcpy() to offset used used += len /* used > size of the buffer */ The room check subtracts ->used from the size, and both are unsigned. Once ->used exceeds the size, the result wraps, so the check always passes, and each later insert lands further past the buffer. Reproduced as root, with keys from a uinput keyboard and cursor position reports on the same console: KFENCE reported an out-of-bounds write 1,024 bytes past the buffer in under 10 s. Fix this by taking port->lock, with interrupts disabled, around the insert and the push in these four functions. kbd_keycode() already takes port->lock under kbd_event_lock, so this lock ordering is not new. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable Cc: Jiri Slaby Cc: Nicolas Pitre Cc: Kees Cook Cc: Joshua Rogers Cc: Chris Mason Cc: Helge Deller Cc: Thomas Zimmermann Cc: Mingyu Wang <25181214217@stu.xidian.edu.cn> Cc: Randy Dunlap Cc: Ronan Pigott Cc: Liav Mordouch Signed-off-by: Chris Mason Signed-off-by: Greg Kroah-Hartman Link: https://patch.msgid.link/20261027-tty-llm-v1-1-99b0202ae546@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/vt/keyboard.c | 6 ++++++ drivers/tty/vt/vt.c | 2 ++ 2 files changed, 8 insertions(+) diff --git a/drivers/tty/vt/keyboard.c b/drivers/tty/vt/keyboard.c index ef4a19aeb3ce88..f4b742e091fbdb 100644 --- a/drivers/tty/vt/keyboard.c +++ b/drivers/tty/vt/keyboard.c @@ -322,15 +322,20 @@ int kbd_rate(struct kbd_repeat *rpt) /* * Helper Functions. + * + * A flip buffer allows one producer at a time, and respond_string() in vt.c + * feeds the same one under the console lock. So take the lock of the port. */ static void put_queue(struct vc_data *vc, int ch) { + guard(spinlock_irqsave)(&vc->port.lock); tty_insert_flip_char(&vc->port, ch, 0); tty_flip_buffer_push(&vc->port); } static void puts_queue(struct vc_data *vc, const char *cp) { + guard(spinlock_irqsave)(&vc->port.lock); tty_insert_flip_string(&vc->port, cp, strlen(cp)); tty_flip_buffer_push(&vc->port); } @@ -587,6 +592,7 @@ static void fn_inc_console(struct vc_data *vc) static void fn_send_intr(struct vc_data *vc) { + guard(spinlock_irqsave)(&vc->port.lock); tty_insert_flip_char(&vc->port, 0, TTY_BREAK); tty_flip_buffer_push(&vc->port); } diff --git a/drivers/tty/vt/vt.c b/drivers/tty/vt/vt.c index 7dbc0072a40a95..6a6eb8b2a6dece 100644 --- a/drivers/tty/vt/vt.c +++ b/drivers/tty/vt/vt.c @@ -1971,6 +1971,8 @@ static void csi_m(struct vc_data *vc) static void respond_string(const char *p, size_t len, struct tty_port *port) { + /* The keyboard handler feeds the same flip buffer. */ + guard(spinlock_irqsave)(&port->lock); tty_insert_flip_string(port, p, len); tty_flip_buffer_push(port); } From 84da8238f7bd3025fc16da32c4cd9992c95a783b Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 12:06:28 +0100 Subject: [PATCH 0199/2102] serial: core: respect runtime PM when sending x_char MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit __uart_start() calls the start_tx operation only if the port is runtime active. Otherwise it asks for a resume, and serial_port_runtime_resume() starts the transmitter. uart_send_xchar() calls start_tx at once, under the port lock, whatever the state of the device. With 8250_omap, serial8250_start_tx() then calls pm_runtime_get_sync() for a suspended device: that sleeps, and omap8250_runtime_resume() takes the port lock again. A tcflow(TCIOFF) on an idle port is enough, if autosuspend has been enabled. It was allowed as long as that driver used pm_runtime_irq_safe(). Share the part of __uart_start() that deals with runtime PM. A stopped transmission still does not hold up an XON or XOFF character. Let a pending x_char count as work for serial_port_runtime_resume(), and keep the port from being suspended with it. Fixes: 8700a7ea5519 ("serial: 8250_omap: Drop pm_runtime_irq_safe()") Cc: stable Cc: Jiri Slaby Cc: Hugo Villeneuve Cc: Johan Hovold Cc: Karl Mehltretter Cc: John Ogness Cc: "Uwe Kleine-König (The Capable Hub)" Cc: Tony Lindgren Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Link: https://patch.msgid.link/20261027-tty-llm-v1-2-99b0202ae546@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/serial/serial_core.c | 25 +++++++++++++++---------- drivers/tty/serial/serial_port.c | 4 ++-- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/drivers/tty/serial/serial_core.c b/drivers/tty/serial/serial_core.c index c0deec0e6af41d..b06d2649be343a 100644 --- a/drivers/tty/serial/serial_core.c +++ b/drivers/tty/serial/serial_core.c @@ -135,17 +135,11 @@ static void uart_stop(struct tty_struct *tty) uart_port_unlock_deref(port, flags); } -static void __uart_start(struct uart_state *state) +static void uart_port_start_tx(struct uart_port *port) { - struct uart_port *port = state->uart_port; - struct serial_port_device *port_dev; + struct serial_port_device *port_dev = port->port_dev; int err; - if (!port || port->flags & UPF_DEAD || uart_tx_stopped(port)) - return; - - port_dev = port->port_dev; - /* Increment the runtime PM usage count for the active check below */ err = pm_runtime_get(&port_dev->dev); if (err < 0 && err != -EINPROGRESS) { @@ -164,6 +158,16 @@ static void __uart_start(struct uart_state *state) pm_runtime_put_autosuspend(&port_dev->dev); } +static void __uart_start(struct uart_state *state) +{ + struct uart_port *port = state->uart_port; + + if (!port || port->flags & UPF_DEAD || uart_tx_stopped(port)) + return; + + uart_port_start_tx(port); +} + static void uart_start(struct tty_struct *tty) { struct uart_state *state = tty->driver_data; @@ -718,8 +722,9 @@ static void uart_send_xchar(struct tty_struct *tty, u8 ch) else { guard(uart_port_lock_irqsave)(port); port->x_char = ch; - if (ch) - port->ops->start_tx(port); + /* It goes out even if the transmission is stopped */ + if (ch && !(port->flags & UPF_DEAD)) + uart_port_start_tx(port); } uart_port_deref(port); } diff --git a/drivers/tty/serial/serial_port.c b/drivers/tty/serial/serial_port.c index 2fc48cd63f6cff..f2f7cdd3a54c9a 100644 --- a/drivers/tty/serial/serial_port.c +++ b/drivers/tty/serial/serial_port.c @@ -23,8 +23,8 @@ /* Only considers pending TX for now. Caller must take care of locking */ static int __serial_port_busy(struct uart_port *port) { - return !uart_tx_stopped(port) && - !kfifo_is_empty(&port->state->port.xmit_fifo); + return port->x_char || (!uart_tx_stopped(port) && + !kfifo_is_empty(&port->state->port.xmit_fifo)); } static int serial_port_runtime_resume(struct device *dev) From 08daebfd63e9054e097eb2653eff9381de43a422 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 12:06:42 +0100 Subject: [PATCH 0200/2102] serial: 8250_lpss: don't divide by 0 above 6.25 Mbaud MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit byt_set_termios() derives the clock of the UART from the baud rate in the termios, which nobody has looked at yet: fuart = baud * 16; ... fuart *= rounddown_pow_of_two(fref / fuart); ... p->uartclk = fuart; fref is 100 MHz. For a baud rate above 6250000, which BOTHER allows, fref / fuart is 0, and rounddown_pow_of_two(0) shifts 1UL by -1. On x86 that is 1UL << 63, the product with a multiple of 16 is 0, and so is uartclk. serial8250_get_baud_rate() then passes 0 for both limits, uart_get_baud_rate() finds no rate which fits, WARNs and returns 0, and uart_get_divisor() or dw8250_get_divisor() divide by 16 * 0. Everybody who may open the tty can oops the kernel with one TCSETS2. Don't ask for more than fref. The limits are those of a 100 MHz clock then, and uart_get_baud_rate() falls back to the old rate as for any other rate that the port cannot do. 8250_mid, which has the same formula, treats this case separately. Fixes: 21947ba654a6 ("serial: 8250_pci: replace switch-case by formula") Cc: stable Cc: "Ilpo Järvinen" Cc: Andy Shevchenko Cc: Jiri Slaby Cc: Heikki Krogerus Cc: Peter Hurley Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Link: https://patch.msgid.link/20261027-tty-llm-v1-16-99b0202ae546@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/serial/8250/8250_lpss.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/tty/serial/8250/8250_lpss.c b/drivers/tty/serial/8250/8250_lpss.c index f1b4b975571a0b..7e88f2b793b5ad 100644 --- a/drivers/tty/serial/8250/8250_lpss.c +++ b/drivers/tty/serial/8250/8250_lpss.c @@ -83,6 +83,9 @@ static void byt_set_termios(struct uart_port *p, struct ktermios *termios, /* Gracefully handle the B0 case: fall back to B9600 */ fuart = fuart ? fuart : 9600 * 16; + /* Fuart <= Fref: leave it to the core to refuse a higher baud rate */ + fuart = min(fuart, fref); + /* Get Fuart closer to Fref */ fuart *= rounddown_pow_of_two(fref / fuart); From 899e3c6e30ff34cf7a260b806fdedb56749e36e9 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 12:06:43 +0100 Subject: [PATCH 0201/2102] serial: 8250_mxpcie: handle hangup during break Ending a software break on a Moxa PCIe port in RS-485 2-wire mode dereferences a NULL tty pointer if the port was hung up while the break was being sent. send_break() calls ->break_ctl(tty, -1), sleeps for the break duration and then calls ->break_ctl(tty, 0), without excluding a concurrent hangup. A hangup (a modem DCD drop, or the session leader exiting while another process of the session is in TCSBRK/TCSBRKP) runs uart_hangup(), which shuts the port down and clears port->state->port.tty. The second call still reaches mxpcie8250_software_break_ctl() through uart_break_ctl(), which then does: struct tty_struct *tty = port->state->port.tty; ... baud = tty_get_baud_rate(tty); with tty == NULL. The bug was found by code inspection and has not been reproduced. Fix by taking a reference to the port's tty with tty_port_tty_get() and only restoring the divisor when a tty is still attached; a hung up port is shut down, and the next open programs the divisor again through set_termios(). Fixes: ade78d3d253c ("serial: 8250_mxpcie: add break support for RS485 using MUEx50 features") Cc: stable Cc: Jiri Slaby Cc: Crescent Hsieh Cc: Andy Shevchenko Cc: Linmao Li Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Link: https://patch.msgid.link/20261027-tty-llm-v1-17-99b0202ae546@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/serial/8250/8250_mxpcie.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/drivers/tty/serial/8250/8250_mxpcie.c b/drivers/tty/serial/8250/8250_mxpcie.c index 4935a5d1c1a3fc..b3418c1ccb0538 100644 --- a/drivers/tty/serial/8250/8250_mxpcie.c +++ b/drivers/tty/serial/8250/8250_mxpcie.c @@ -412,7 +412,7 @@ static int mxpcie8250_handle_irq(struct uart_port *port) static void mxpcie8250_software_break_ctl(struct uart_port *port, int break_state) { struct uart_8250_port *up = up_to_u8250p(port); - struct tty_struct *tty = port->state->port.tty; + struct tty_struct *tty; unsigned int baud, quot; u8 sfr, tx_byte = 0x01; @@ -439,9 +439,14 @@ static void mxpcie8250_software_break_ctl(struct uart_port *port, int break_stat serial_out(up, UART_FCR, UART_FCR_CLEAR_XMIT); - baud = tty_get_baud_rate(tty); - quot = uart_get_divisor(port, baud); - serial8250_do_set_divisor(port, baud, quot); + /* A hangup during the break detaches the tty */ + tty = tty_port_tty_get(&port->state->port); + if (tty) { + baud = tty_get_baud_rate(tty); + quot = uart_get_divisor(port, baud); + serial8250_do_set_divisor(port, baud, quot); + tty_kref_put(tty); + } serial_out(up, UART_LCR, up->lcr); } } From 0f0664a63efdfd70d1c555080781f4e8464445aa Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 12:06:44 +0100 Subject: [PATCH 0202/2102] serial: fsl_lpuart: fix tty ref of wakeup event To report a wakeup event, lpuart_resume_noirq() gets the tty with tty_port_tty_get() and never puts it: each wakeup by the UART leaks a reference, and the tty is not freed when it is closed. With no_console_suspend, the function also gets there for a console which is not open. Then tty_port_tty_get() returns NULL, which is dereferenced. Fixes: 18bdfccf3c30 ("tty: serial: fsl_lpuart: Add missing wakeup event reporting") Cc: stable Cc: Jiri Slaby Cc: Frank Li Cc: Peng Fan Cc: Shitalkumar Gandhi Cc: Sherry Sun Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Link: https://patch.msgid.link/20261027-tty-llm-v1-18-99b0202ae546@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/serial/fsl_lpuart.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/drivers/tty/serial/fsl_lpuart.c b/drivers/tty/serial/fsl_lpuart.c index c8575c9652035e..e54b4c44db4296 100644 --- a/drivers/tty/serial/fsl_lpuart.c +++ b/drivers/tty/serial/fsl_lpuart.c @@ -3113,8 +3113,14 @@ static int lpuart_resume_noirq(struct device *dev) /* check whether lpuart wakeup was triggered */ wake_active = stat & (UARTSTAT_RDRF | UARTSTAT_RXEDGIF); - if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq))) - pm_wakeup_event(tty_port_tty_get(port)->dev, 0); + if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq))) { + struct tty_struct *tty = tty_port_tty_get(port); + + if (tty) { + pm_wakeup_event(tty->dev, 0); + tty_kref_put(tty); + } + } } } From 6d7fbd5a28d092ab61ec0092cf1e085d2bb9ed7e Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 12:06:45 +0100 Subject: [PATCH 0203/2102] serial: imx: fix the tty reference of the wakeup event To report a wakeup event, imx_uart_enable_wakeup() gets the tty with tty_port_tty_get() and never puts it: each wakeup by the UART leaks a reference, and the tty is not freed when it is closed. Fixes: 0cfadf4bcd28 ("tty: serial: imx: Add missing wakeup event reporting") Cc: stable Cc: Jiri Slaby Cc: Frank Li Cc: Sascha Hauer Cc: Pengutronix Kernel Team Cc: Fabio Estevam Cc: Robin Gong Cc: Petr Mladek Cc: John Ogness Cc: Pan Chuang Cc: Karl Mehltretter Cc: Sherry Sun Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Link: https://patch.msgid.link/20261027-tty-llm-v1-19-99b0202ae546@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/serial/imx.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/drivers/tty/serial/imx.c b/drivers/tty/serial/imx.c index 986fefb45c6322..18892fc4a35b0c 100644 --- a/drivers/tty/serial/imx.c +++ b/drivers/tty/serial/imx.c @@ -2742,8 +2742,14 @@ static void imx_uart_enable_wakeup(struct imx_port *sport, bool on) imx_uart_writel(sport, ucr1, UCR1); } - if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq))) - pm_wakeup_event(tty_port_tty_get(port)->dev, 0); + if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq))) { + struct tty_struct *tty = tty_port_tty_get(port); + + if (tty) { + pm_wakeup_event(tty->dev, 0); + tty_kref_put(tty); + } + } uart_port_unlock_irq(&sport->port); } From 859f7c56709b161a72b629b6f2f1384dcd374404 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 12:06:46 +0100 Subject: [PATCH 0204/2102] serial: rda: free the interrupt on shutdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit rda_uart_startup() requests the interrupt, and nothing ever frees it. It is not shared, so once the port has been closed, the next startup fails with -EBUSY and the port cannot be opened any more. Free it in rda_uart_shutdown(). Fixes: c10b13325ced ("tty: serial: Add RDA8810PL UART driver") Cc: stable Cc: Jiri Slaby Cc: Arnd Bergmann Cc: "Andreas Färber" Cc: Olof Johansson Signed-off-by: Josef Bacik Reviewed-by: Manivannan Sadhasivam Signed-off-by: Greg Kroah-Hartman Link: https://patch.msgid.link/20261027-tty-llm-v1-20-99b0202ae546@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/serial/rda-uart.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/tty/serial/rda-uart.c b/drivers/tty/serial/rda-uart.c index 87fa30d6868784..9c1785771cbb69 100644 --- a/drivers/tty/serial/rda-uart.c +++ b/drivers/tty/serial/rda-uart.c @@ -471,6 +471,8 @@ static void rda_uart_shutdown(struct uart_port *port) rda_uart_write(port, val, RDA_UART_CTRL); uart_port_unlock_irqrestore(port, flags); + + free_irq(port->irq, port); } static const char *rda_uart_type(struct uart_port *port) From 7ada442f5ef77f8d53f608a0141a5e88a888ca9f Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 12:06:47 +0100 Subject: [PATCH 0205/2102] serial: samsung: don't leak the tty on an RX IRQ s3c24xx_serial_rx_chars_dma() starts by taking a reference to the tty. If the interrupt is not a receive timeout, it switches the port from PIO back to DMA and leaves through the "finish" label, which does not drop the reference. A port with RX DMA changes to PIO on every receive timeout, that is at the end of every burst of data, and comes back this way when the next burst starts. So each burst takes a reference which is never dropped, and the tty structure is not freed when the port is closed for the last time. Drop the reference on both paths. Fixes: b543c301c2c5 ("serial: samsung: add DMA support for RX") Cc: stable Cc: Krzysztof Kozlowski Cc: Peter Griffin Cc: Alim Akhtar Cc: Jiri Slaby Cc: Robert Baldyga Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Link: https://patch.msgid.link/20261027-tty-llm-v1-21-99b0202ae546@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/serial/samsung_tty.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/drivers/tty/serial/samsung_tty.c b/drivers/tty/serial/samsung_tty.c index 640f85e2d636b1..c9a870a8d15518 100644 --- a/drivers/tty/serial/samsung_tty.c +++ b/drivers/tty/serial/samsung_tty.c @@ -736,14 +736,13 @@ static irqreturn_t s3c24xx_serial_rx_chars_dma(struct s3c24xx_uart_port *ourport s3c24xx_serial_rx_drain_fifo(ourport); - if (tty) { + if (tty) tty_flip_buffer_push(t); - tty_kref_put(tty); - } wr_regl(port, S3C2410_UTRSTAT, S3C2410_UTRSTAT_TIMEOUT); finish: + tty_kref_put(tty); uart_port_unlock(port); return IRQ_HANDLED; From eedf2cf3505c1562a2fb24f8b997056f023d242b Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 12:06:48 +0100 Subject: [PATCH 0206/2102] serial: samsung: put the previous baud clock s3c24xx_serial_getclk() returns the best baud clock with the reference which clk_get() has taken. s3c24xx_serial_set_termios() stores it in ourport->baudclk and disables the clock which was there before, but does not put it. clk_get() hands out a new handle on every call, so the new clock never equals the old one, and every call of ->set_termios() leaks a handle: a struct clk and a copy of the connection name. Whoever has the port open can repeat that at will with tcsetattr(). Put the old clock when it is replaced, and the new one in case it is not stored. Fixes: 5f5a7a5578c5 ("serial: samsung: switch to clkdev based clock lookup") Cc: stable Cc: Krzysztof Kozlowski Cc: Peter Griffin Cc: Alim Akhtar Cc: Jiri Slaby Cc: Kukjin Kim Cc: Thomas Abraham Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Link: https://patch.msgid.link/20261027-tty-llm-v1-22-99b0202ae546@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/tty/serial/samsung_tty.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/tty/serial/samsung_tty.c b/drivers/tty/serial/samsung_tty.c index c9a870a8d15518..f437f7363fd3dc 100644 --- a/drivers/tty/serial/samsung_tty.c +++ b/drivers/tty/serial/samsung_tty.c @@ -1501,11 +1501,14 @@ static void s3c24xx_serial_set_termios(struct uart_port *port, if (!IS_ERR(ourport->baudclk)) { clk_disable_unprepare(ourport->baudclk); + clk_put(ourport->baudclk); ourport->baudclk = ERR_PTR(-EINVAL); } ourport->baudclk = clk; ourport->baudclk_rate = clk ? clk_get_rate(clk) : 0; + } else { + clk_put(clk); } if (ourport->info->has_divslot) { From a7ff66ebcb81abf65967513cc51788e5bdb32a92 Mon Sep 17 00:00:00 2001 From: Jacob Moroni Date: Thu, 29 Oct 2026 13:27:40 +0000 Subject: [PATCH 0207/2102] RDMA/mlx4: Fix stale umem and MTT state after rereg_mr failures During rereg_mr, the umem is released in various failure cases but mmr->umem was left pointing to a freed umem, so it could end up getting double-freed when the MR is finally deregistered, or cause a UAF in ib_umem_check_rereg() if another rereg_mr attempt is made. Fix this by setting mmr->umem to NULL after ib_umem_release(). Additionally, when mlx4_mr_rereg_mem_write() fails, mtt.order is left set but with an invalid offset, so during dereg, mlx4_mtt_cleanup() ends up freeing an MTT range that was never allocated. Fix this by resetting mtt.order to -1 in that path. Fixes: 9376932d0c26 ("IB/mlx4_ib: Add support for user MR re-registration") Signed-off-by: Jacob Moroni Link: https://patch.msgid.link/20261029132740.1169950-1-jmoroni@google.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/mlx4/mr.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/infiniband/hw/mlx4/mr.c b/drivers/infiniband/hw/mlx4/mr.c index a6b4abce1bfef0..e7f524c28f1e07 100644 --- a/drivers/infiniband/hw/mlx4/mr.c +++ b/drivers/infiniband/hw/mlx4/mr.c @@ -268,6 +268,8 @@ struct ib_mr *mlx4_ib_rereg_user_mr(struct ib_mr *mr, int flags, u64 start, *pmpt_entry); if (err) { ib_umem_release(mmr->umem); + mmr->mmr.mtt.order = -1; + mmr->umem = NULL; goto release_mpt_entry; } mmr->mmr.iova = virt_addr; @@ -277,6 +279,7 @@ struct ib_mr *mlx4_ib_rereg_user_mr(struct ib_mr *mr, int flags, u64 start, if (err) { mlx4_mr_rereg_mem_cleanup(dev->dev, &mmr->mmr); ib_umem_release(mmr->umem); + mmr->umem = NULL; goto release_mpt_entry; } } From 6b5c8236e3008f7795ce558a9235c38f829a94a4 Mon Sep 17 00:00:00 2001 From: Jacob Moroni Date: Thu, 29 Oct 2026 13:31:21 +0000 Subject: [PATCH 0208/2102] RDMA/irdma: Do not allow rereg_mr to revive defunct MRs An MR can become "defunct" if a previous rereg_mr happened to fail in between deregistering the old MR in HW and reregistering it (e.g., due to ib_umem_get_va() failing in the IB_MR_REREG_TRANS case). In this case, the MR is left in a state where the umem may have already been released. If rereg_mr then runs again, but without IB_MR_REREG_TRANS, it will end up reregistering the MR with stale translation info. Fix this by rejecting any attempt to reregister an MR that has previously failed during rereg_mr after the point where the MR has been deregistered in HW. Fixes: 5ac388db27c4 ("RDMA/irdma: Add support to re-register a memory region") Signed-off-by: Jacob Moroni Link: https://patch.msgid.link/20261029133121.1204636-1-jmoroni@google.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/irdma/verbs.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/infiniband/hw/irdma/verbs.c b/drivers/infiniband/hw/irdma/verbs.c index 9443e9732c4a3b..bea2019892f3bc 100644 --- a/drivers/infiniband/hw/irdma/verbs.c +++ b/drivers/infiniband/hw/irdma/verbs.c @@ -3905,6 +3905,9 @@ static struct ib_mr *irdma_rereg_user_mr(struct ib_mr *ib_mr, int flags, if (ret) return ERR_PTR(ret); + if (!iwmr->is_hwreg) + return ERR_PTR(-EINVAL); + ret = irdma_hwdereg_mr(ib_mr); if (ret) return ERR_PTR(ret); From ab5389ccf8bcd312a620f974ef94c174067ac1c8 Mon Sep 17 00:00:00 2001 From: Jacob Moroni Date: Thu, 29 Oct 2026 13:53:06 +0000 Subject: [PATCH 0209/2102] RDMA/irdma: Do not change mr->pd in driver during rereg_mr Previously, IB_MR_REREG_PD would cause the driver to set iwmr->ibmr.pd to the new PD before reregistering with HW because irdma_hwreg_mr() retrieves the PD from there. ib_uverbs_rereg_mr() only moves the PD usecnt from the old PD to the new one and updates mr->pd itself after the driver's rereg_user_mr() call succeeds. So, if the rereg_user_mr() call fails, the MR is left pointing at a PD that does not account for it while the old PD keeps the reference, which means the old PD can never be deallocated, while the new PD can be deallocated even though the MR still points at it. Fix this by removing the PD update from the driver and just letting the core handle it. This required plumbing the PD as an argument through a few functions. This works because the core passes the PD unconditionally and provides the current PD if IB_MR_REREG_PD is not set. Fixes: 5ac388db27c4 ("RDMA/irdma: Add support to re-register a memory region") Signed-off-by: Jacob Moroni Link: https://patch.msgid.link/20261029135306.1372393-1-jmoroni@google.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/irdma/verbs.c | 34 ++++++++++++----------------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/drivers/infiniband/hw/irdma/verbs.c b/drivers/infiniband/hw/irdma/verbs.c index bea2019892f3bc..9cc1b65eea2672 100644 --- a/drivers/infiniband/hw/irdma/verbs.c +++ b/drivers/infiniband/hw/irdma/verbs.c @@ -3340,14 +3340,14 @@ static int irdma_map_mr_sg(struct ib_mr *ibmr, struct scatterlist *sg, * irdma_hwreg_mr - send cqp command for memory registration * @iwdev: irdma device * @iwmr: irdma mr pointer + * @pd: protection domain to register the MR with * @access: access for MR */ static int irdma_hwreg_mr(struct irdma_device *iwdev, struct irdma_mr *iwmr, - u16 access) + struct ib_pd *pd, u16 access) { struct irdma_pbl *iwpbl = &iwmr->iwpbl; struct irdma_reg_ns_stag_info *stag_info; - struct ib_pd *pd = iwmr->ibmr.pd; struct irdma_pd *iwpd = to_iwpd(pd); struct irdma_pble_alloc *palloc = &iwpbl->pble_alloc; struct irdma_cqp_request *cqp_request; @@ -3401,8 +3401,8 @@ static int irdma_hwreg_mr(struct irdma_device *iwdev, struct irdma_mr *iwmr, return ret; } -static int irdma_reg_user_mr_type_mem(struct irdma_mr *iwmr, int access, - bool create_stag) +static int irdma_reg_user_mr_type_mem(struct irdma_mr *iwmr, struct ib_pd *pd, + int access, bool create_stag) { struct irdma_device *iwdev = to_iwdev(iwmr->ibmr.device); struct irdma_pbl *iwpbl = &iwmr->iwpbl; @@ -3447,7 +3447,7 @@ static int irdma_reg_user_mr_type_mem(struct irdma_mr *iwmr, int access, iwmr->ibmr.lkey = stag; } - err = irdma_hwreg_mr(iwdev, iwmr, access); + err = irdma_hwreg_mr(iwdev, iwmr, pd, access); if (err) goto err_hwreg; @@ -3678,7 +3678,7 @@ static struct ib_mr *irdma_reg_user_mr(struct ib_pd *pd, u64 start, u64 len, goto error; break; case IRDMA_MEMREG_TYPE_MEM: - err = irdma_reg_user_mr_type_mem(iwmr, access, true); + err = irdma_reg_user_mr_type_mem(iwmr, pd, access, true); if (err) goto error; @@ -3758,7 +3758,7 @@ static struct ib_mr *irdma_reg_user_mr_dmabuf(struct ib_pd *pd, u64 start, goto err_release; } - err = irdma_reg_user_mr_type_mem(iwmr, access, true); + err = irdma_reg_user_mr_type_mem(iwmr, pd, access, true); if (err) goto err_iwmr; @@ -3826,6 +3826,7 @@ static int irdma_hwdereg_mr(struct ib_mr *ib_mr) /* * irdma_rereg_mr_trans - Re-register a user MR for a change translation. * @iwmr: ptr of iwmr + * @pd: protection domain to register the MR with * @start: virtual start address * @len: length of mr * @virt: virtual address @@ -3833,11 +3834,10 @@ static int irdma_hwdereg_mr(struct ib_mr *ib_mr) * Re-register a user memory region when a change translation is requested. * Re-register a new region while reusing the stag from the original registration. */ -static int irdma_rereg_mr_trans(struct irdma_mr *iwmr, u64 start, u64 len, - u64 virt) +static int irdma_rereg_mr_trans(struct irdma_mr *iwmr, struct ib_pd *pd, + u64 start, u64 len, u64 virt) { struct irdma_pbl *iwpbl = &iwmr->iwpbl; - struct ib_pd *pd = iwmr->ibmr.pd; struct ib_umem *region; int err; @@ -3847,11 +3847,10 @@ static int irdma_rereg_mr_trans(struct irdma_mr *iwmr, u64 start, u64 len, iwmr->region = region; iwmr->ibmr.iova = virt; - iwmr->ibmr.pd = pd; iwmr->len = region->length; iwpbl->user_base = virt; - err = irdma_reg_user_mr_type_mem(iwmr, iwmr->access, false); + err = irdma_reg_user_mr_type_mem(iwmr, pd, iwmr->access, false); if (err) goto err; @@ -3915,11 +3914,6 @@ static struct ib_mr *irdma_rereg_user_mr(struct ib_mr *ib_mr, int flags, if (flags & IB_MR_REREG_ACCESS) iwmr->access = new_access; - if (flags & IB_MR_REREG_PD) { - iwmr->ibmr.pd = new_pd; - iwmr->ibmr.device = new_pd->device; - } - if (flags & IB_MR_REREG_TRANS) { if (iwpbl->pbl_allocated) { irdma_free_pble(iwdev->rf->pble_rsrc, @@ -3932,9 +3926,9 @@ static struct ib_mr *irdma_rereg_user_mr(struct ib_mr *ib_mr, int flags, iwmr->region = NULL; } - ret = irdma_rereg_mr_trans(iwmr, start, len, virt); + ret = irdma_rereg_mr_trans(iwmr, new_pd, start, len, virt); } else { - ret = irdma_hwreg_mr(iwdev, iwmr, iwmr->access); + ret = irdma_hwreg_mr(iwdev, iwmr, new_pd, iwmr->access); } return ret ? ERR_PTR(ret) : NULL; @@ -3983,7 +3977,7 @@ struct ib_mr *irdma_reg_phys_mr(struct ib_pd *pd, u64 addr, u64 size, int access iwmr->pgaddrmem[0] = addr; iwmr->len = size; iwmr->page_size = SZ_4K; - ret = irdma_hwreg_mr(iwdev, iwmr, access); + ret = irdma_hwreg_mr(iwdev, iwmr, pd, access); if (ret) { irdma_free_stag(iwdev, stag); goto err; From 09436ffe8f1b396c6446eda12798e46f82fed48c Mon Sep 17 00:00:00 2001 From: Marc Zyngier Date: Mon, 26 Oct 2026 08:23:04 +0000 Subject: [PATCH 0210/2102] arm64: Add return value to mte_disable_tco_entry() In order to provide adequate levels of synchronisation when clearing TCO, update mte_disable_tco_entry() to indicate whether it has actually done something. Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Reviewed-by: Catalin Marinas Link: https://patch.msgid.link/20261026082305.2515705-2-maz@kernel.org Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/mte.h | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/arch/arm64/include/asm/mte.h b/arch/arm64/include/asm/mte.h index 83f3b05fc78490..f20c5aa4112b25 100644 --- a/arch/arm64/include/asm/mte.h +++ b/arch/arm64/include/asm/mte.h @@ -222,10 +222,10 @@ static inline bool folio_try_hugetlb_mte_tagging(struct folio *folio) } #endif -static inline void mte_disable_tco_entry(struct task_struct *task) +static inline bool mte_disable_tco_entry(struct task_struct *task) { if (!system_supports_mte()) - return; + return false; /* * Re-enable tag checking (TCO set on exception entry). This is only @@ -238,8 +238,12 @@ static inline void mte_disable_tco_entry(struct task_struct *task) * expensive. */ if (kasan_hw_tags_enabled() || - (task->thread.sctlr_user & (1UL << SCTLR_EL1_TCF0_SHIFT))) + (task->thread.sctlr_user & (1UL << SCTLR_EL1_TCF0_SHIFT))) { asm volatile(SET_PSTATE_TCO(0)); + return true; + } + + return false; } #ifdef CONFIG_KASAN_HW_TAGS From 491fe17530d662a7e6c6b4d139d950dfa0e3a210 Mon Sep 17 00:00:00 2001 From: Marc Zyngier Date: Mon, 26 Oct 2026 08:23:05 +0000 Subject: [PATCH 0211/2102] KVM: arm64: Reenable MTE tag checking on exit from guest when running VHE Once we're back from running a guest, it is important to set TCO to zero so that MTE is functional again. Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Reviewed-by: Catalin Marinas Link: https://patch.msgid.link/20261026082305.2515705-3-maz@kernel.org Signed-off-by: Marc Zyngier --- arch/arm64/kvm/hyp/vhe/switch.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/arch/arm64/kvm/hyp/vhe/switch.c b/arch/arm64/kvm/hyp/vhe/switch.c index 3f2390a13173bd..5f7a46c4f516de 100644 --- a/arch/arm64/kvm/hyp/vhe/switch.c +++ b/arch/arm64/kvm/hyp/vhe/switch.c @@ -193,6 +193,13 @@ static void __deactivate_traps(struct kvm_vcpu *vcpu) if (!arm64_kernel_unmapped_at_el0()) host_vectors = __this_cpu_read(this_cpu_vector); write_sysreg(host_vectors, vbar_el1); + + /* + * We're now able to take MTE exceptions, make sure the VBAR_EL2 is + * set to the correct value. + */ + if (mte_disable_tco_entry(current)) + isb(); } NOKPROBE_SYMBOL(__deactivate_traps); From 687a1e161457b267963f8334fd143896515cec25 Mon Sep 17 00:00:00 2001 From: Abhijit Gangurde Date: Fri, 30 Oct 2026 13:54:02 +0530 Subject: [PATCH 0212/2102] RDMA/ionic: Use a linear QID space when udma_shift is zero Firmware reports udma_shift as the log2 of the number of queues in a queue group. A value of zero means the queues are not striped across two UDMAs, so the QID space is linear and the device has one UDMA. The interleaved bitid/qid transform treats bit 0 as the UDMA selector when the group shift is zero. QID 1 then becomes bitid 1 << half_qid_shift, and freeing that QID releases the wrong allocator index. Skip the transform and select one UDMA so QP and CQ allocation uses the QID directly. Fixes: e8521822c733 ("RDMA/ionic: Register device ops for control path") Reported-by: Keith Lucas Link: https://lore.kernel.org/r/20261021161651.4020222-1-haakon.bugge@oracle.com Cc: stable@vger.kernel.org # 6.18 Signed-off-by: Abhijit Gangurde Link: https://patch.msgid.link/20261030082402.841751-1-abhijit.gangurde@amd.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/ionic/ionic_lif_cfg.c | 2 +- drivers/infiniband/hw/ionic/ionic_res.h | 23 ++++++++++++++------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/drivers/infiniband/hw/ionic/ionic_lif_cfg.c b/drivers/infiniband/hw/ionic/ionic_lif_cfg.c index 66cee57442e7a3..a3ee86b560379f 100644 --- a/drivers/infiniband/hw/ionic/ionic_lif_cfg.c +++ b/drivers/infiniband/hw/ionic/ionic_lif_cfg.c @@ -84,7 +84,7 @@ void ionic_fill_lif_cfg(struct ionic_lif *lif, struct ionic_lif_cfg *cfg) cfg->cq_qtype = ident->rdma.cq_qtype.qtype; cfg->eq_qtype = ident->rdma.eq_qtype.qtype; cfg->udma_qgrp_shift = ident->rdma.udma_shift; - cfg->udma_count = 2; + cfg->udma_count = cfg->udma_qgrp_shift ? 2 : 1; cfg->max_stride = ident->rdma.max_stride; cfg->rcq_sign_bit = ident->rdma.rcq_sign_bit; diff --git a/drivers/infiniband/hw/ionic/ionic_res.h b/drivers/infiniband/hw/ionic/ionic_res.h index 46c8c584bd9a1c..c480865dced526 100644 --- a/drivers/infiniband/hw/ionic/ionic_res.h +++ b/drivers/infiniband/hw/ionic/ionic_res.h @@ -125,10 +125,14 @@ static inline void ionic_resid_put(struct ionic_resid_bits *resid, int id) static inline u32 ionic_bitid_to_qid(u32 bitid, u8 qgrp_shift, u8 half_qid_shift) { - u32 udma_bit = - (bitid & BIT(half_qid_shift)) >> (half_qid_shift - qgrp_shift); - u32 grp_bits = (bitid & GENMASK(half_qid_shift - 1, qgrp_shift)) << 1; - u32 idx_bits = bitid & (BIT(qgrp_shift) - 1); + u32 udma_bit, grp_bits, idx_bits; + + if (!qgrp_shift) + return bitid; + + udma_bit = (bitid & BIT(half_qid_shift)) >> (half_qid_shift - qgrp_shift); + grp_bits = (bitid & GENMASK(half_qid_shift - 1, qgrp_shift)) << 1; + idx_bits = bitid & (BIT(qgrp_shift) - 1); return grp_bits | udma_bit | idx_bits; } @@ -145,9 +149,14 @@ static inline u32 ionic_bitid_to_qid(u32 bitid, u8 qgrp_shift, */ static inline u32 ionic_qid_to_bitid(u32 qid, u8 qgrp_shift, u8 half_qid_shift) { - u32 udma_bit = (qid & BIT(qgrp_shift)) << (half_qid_shift - qgrp_shift); - u32 grp_bits = (qid & GENMASK(half_qid_shift, qgrp_shift + 1)) >> 1; - u32 idx_bits = qid & (BIT(qgrp_shift) - 1); + u32 udma_bit, grp_bits, idx_bits; + + if (!qgrp_shift) + return qid; + + udma_bit = (qid & BIT(qgrp_shift)) << (half_qid_shift - qgrp_shift); + grp_bits = (qid & GENMASK(half_qid_shift, qgrp_shift + 1)) >> 1; + idx_bits = qid & (BIT(qgrp_shift) - 1); return udma_bit | grp_bits | idx_bits; } From 51f7c4a7d311930868041634bc041633b94d68c1 Mon Sep 17 00:00:00 2001 From: Marc Zyngier Date: Mon, 26 Oct 2026 08:26:33 +0000 Subject: [PATCH 0213/2102] KVM: arm64: Don't let a guest overwrite HCRX_EL2.MCE2 FEAT_MOPS is fun. CPUs are allowed to implement any of two ways to perform the memory copy, and the hypervisor is in charge of hiding the difference between implementation when the vcpu migrates from one to another. This is unhelpfully signalled with an exception, which KVM diligently handles. Today, we don't really make a good job of it in the sense that if L1 also has the trap bit set, we don't forward the trap as the architecture would require us to do. But there is no good reason to forward this to the L1 guest if L2 generates the "I'm on the wrong implementation". KVM can fix it up in place and return to L2 directly, as if the physical CPU was able to implement both options. Conversely, allowing L1 to clear HCRX_EL2.MCE2 is counter-productive, and violates the abstraction that KVM aims to give. Implement this behaviour by never allowing the guest's view of HCRX_EL2.MCE2 to make it into the HW, and document that KVM is in charge of the A/B handling. Reviewed-by: Oliver Upton Reviewed-by: Fuad Tabba Link: https://patch.msgid.link/20261026082633.2515820-1-maz@kernel.org Signed-off-by: Marc Zyngier --- arch/arm64/kvm/hyp/include/hyp/switch.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/arch/arm64/kvm/hyp/include/hyp/switch.h b/arch/arm64/kvm/hyp/include/hyp/switch.h index e0c55644224cb2..ec33819e67c0c5 100644 --- a/arch/arm64/kvm/hyp/include/hyp/switch.h +++ b/arch/arm64/kvm/hyp/include/hyp/switch.h @@ -330,7 +330,7 @@ static inline void __deactivate_traps_mpam(void) * Just like for HCR_EL2, we can't let the guest mess with some of the * basics we rely on in HCRX_EL2. However, the major difference is that * HCRX_EL2 only affects EL1, and never EL2 (sudden outburst of sanity, I - * guess). So it is always the guest inflicting it on its own guestx. + * guess). So it is always the guest inflicting it on its own guest. * * Things we don't want to let the guest control are: * @@ -339,10 +339,14 @@ static inline void __deactivate_traps_mpam(void) * - PTTWI: Similarly, it is for us to decide whether Reduced Coherency for * the PTW is a thing. It really isn't. * + * - MCE2: FEAT_MOPS generated exceptions for Option-{A,B} interoperability + * are always handled on the host and not forwarded to a guest hypervisor + * in order to give the (poor) illusion of a homogeneous system. + * * - EnIDCP128: We don't allow IMPDEF sysregs -- full stop. */ #define NV_HCRX_GUEST_EXCLUDE (HCRX_EL2_TMEA | HCRX_EL2_PTTWI | \ - HCRX_EL2_EnIDCP128) + HCRX_EL2_MCE2 | HCRX_EL2_EnIDCP128) static inline void __activate_traps_common(struct kvm_vcpu *vcpu) { From 9d447709895d3977e207dd1bc01a30f5c0f76156 Mon Sep 17 00:00:00 2001 From: Will Deacon Date: Tue, 3 Nov 2026 13:35:39 +0000 Subject: [PATCH 0214/2102] KVM: arm64: Use S1E1A when Stage-1 PIE is supported On a system with stage-1 PIE, a guest can try to execute from an execute-only mapping at stage-1 but trigger a permission fault at stage-2 if the stage-2 mapping is execute-never. In this case, the EL2 permission fault handler will attempt to translate the faulting VA using an AT S1E1R operation, which will fail due to the lack of read permission at stage-1. We will then return to the guest and take the exact same fault the next time around. Similarly to commit 55f4b215fb60 ("KVM: arm64: use `at s1e1a` for POE"), use the S1E1A operation to bypass stage-1 permission checks when obtaining the IPA for a stage-2 permission fault. Like FEAT_S1POE, FEAT_S1PIE implies FEAT_ATS1A, so extend the existing AT invocation in __translate_far_to_hpfar() to use the permission-bypassing variant when S1PIE is implemented. Cc: Marc Zyngier Cc: Oliver Upton Cc: Fuad Tabba Cc: Joey Gouly Cc: Steffen Eiden Cc: Ard Biesheuvel Signed-off-by: Will Deacon Link: https://patch.msgid.link/20261103133540.29566-1-will@kernel.org Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/cpufeature.h | 5 +++++ arch/arm64/kvm/hyp/include/hyp/fault.h | 5 +++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/arch/arm64/include/asm/cpufeature.h b/arch/arm64/include/asm/cpufeature.h index e3c8a1493dc8d9..7d7b8eb7f72fb1 100644 --- a/arch/arm64/include/asm/cpufeature.h +++ b/arch/arm64/include/asm/cpufeature.h @@ -872,6 +872,11 @@ static inline bool system_supports_lpa2(void) return cpus_have_final_cap(ARM64_HAS_LPA2); } +static inline bool system_supports_pie(void) +{ + return alternative_has_cap_unlikely(ARM64_HAS_S1PIE); +} + static inline bool system_supports_poe(void) { return alternative_has_cap_unlikely(ARM64_HAS_S1POE); diff --git a/arch/arm64/kvm/hyp/include/hyp/fault.h b/arch/arm64/kvm/hyp/include/hyp/fault.h index fc573fc767b0e7..741ea12be07df8 100644 --- a/arch/arm64/kvm/hyp/include/hyp/fault.h +++ b/arch/arm64/kvm/hyp/include/hyp/fault.h @@ -38,8 +38,9 @@ static inline bool __translate_far_to_hpfar(u64 far, u64 *hpfar) * saved the guest context yet, and we may return early... */ par = read_sysreg_par(); - ret = system_supports_poe() ? __kvm_at(OP_AT_S1E1A, far) : - __kvm_at(OP_AT_S1E1R, far); + ret = system_supports_poe() || system_supports_pie() ? + __kvm_at(OP_AT_S1E1A, far) : + __kvm_at(OP_AT_S1E1R, far); if (!ret) tmp = read_sysreg_par(); else From 8cf5406b86249af4c95956cc9ea0805375fa2033 Mon Sep 17 00:00:00 2001 From: Nikolaos Gkarlis Date: Sun, 1 Nov 2026 15:15:20 +0100 Subject: [PATCH 0215/2102] RDMA/nldev: Reply to RDMA_NLDEV_CMD_PORT_GET with its own command nldev_port_get_doit() replies with RDMA_NLDEV_CMD_GET, while the dump replies with RDMA_NLDEV_CMD_PORT_GET. Use RDMA_NLDEV_CMD_PORT_GET for both. Fixes: c3f66f7b0052 ("RDMA/netlink: Implement nldev port doit callback") Assisted-by: LLM Signed-off-by: Nikolaos Gkarlis Link: https://patch.msgid.link/20261101141521.2426198-2-nickgarlis@gmail.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/core/nldev.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/infiniband/core/nldev.c b/drivers/infiniband/core/nldev.c index 849a5db54e1cb0..0602e4d38aa5a0 100644 --- a/drivers/infiniband/core/nldev.c +++ b/drivers/infiniband/core/nldev.c @@ -1304,7 +1304,8 @@ static int nldev_port_get_doit(struct sk_buff *skb, struct nlmsghdr *nlh, } nlh = nlmsg_put(msg, NETLINK_CB(skb).portid, nlh->nlmsg_seq, - RDMA_NL_GET_TYPE(RDMA_NL_NLDEV, RDMA_NLDEV_CMD_GET), + RDMA_NL_GET_TYPE(RDMA_NL_NLDEV, + RDMA_NLDEV_CMD_PORT_GET), 0, 0); if (!nlh) { err = -EMSGSIZE; From f3980f8abd2d111c7a9057130e7fa926ae908b0f Mon Sep 17 00:00:00 2001 From: Nikolaos Gkarlis Date: Sun, 1 Nov 2026 15:15:21 +0100 Subject: [PATCH 0216/2102] RDMA/nldev: Reply to RDMA_NLDEV_CMD_STAT_DEL with its own command nldev_stat_del_doit() replies with RDMA_NLDEV_CMD_STAT_SET. Use RDMA_NLDEV_CMD_STAT_DEL. Fixes: b389327df905 ("RDMA/nldev: Allow counter manual mode configration through RDMA netlink") Assisted-by: LLM Signed-off-by: Nikolaos Gkarlis Link: https://patch.msgid.link/20261101141521.2426198-3-nickgarlis@gmail.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/core/nldev.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/infiniband/core/nldev.c b/drivers/infiniband/core/nldev.c index 0602e4d38aa5a0..953406531cd54e 100644 --- a/drivers/infiniband/core/nldev.c +++ b/drivers/infiniband/core/nldev.c @@ -2316,7 +2316,7 @@ static int nldev_stat_del_doit(struct sk_buff *skb, struct nlmsghdr *nlh, } nlh = nlmsg_put(msg, NETLINK_CB(skb).portid, nlh->nlmsg_seq, RDMA_NL_GET_TYPE(RDMA_NL_NLDEV, - RDMA_NLDEV_CMD_STAT_SET), + RDMA_NLDEV_CMD_STAT_DEL), 0, 0); if (!nlh) { ret = -EMSGSIZE; From a70672b9b3ac7d8945f67cd199c1bb680d5d5f64 Mon Sep 17 00:00:00 2001 From: Deep Shah Date: Mon, 2 Nov 2026 06:44:37 +0000 Subject: [PATCH 0217/2102] RDMA/siw: Fix use-after-free in siw_mem_id2obj() siw_mem_id2obj() finds a siw_mem with xa_load() under rcu_read_lock() and then takes a reference with kref_get_unless_zero(). This is only safe if the object stays allocated until RCU readers are done with it. siw_free_mem() frees it with kfree() as soon as the last reference is dropped, so a lookup that races with the final put reads freed memory. This happens when an MR is deregistered while an incoming RDMA WRITE looks up its STag: BUG: KASAN: slab-use-after-free in siw_mem_id2obj+0xe5/0x310 Read of size 4 at addr ff110001042aed88 by task repro-rcu2/90 Call Trace: siw_mem_id2obj+0xe5/0x310 siw_proc_write+0x282/0x430 siw_tcp_rx_data+0x12e/0xbf0 __tcp_read_sock+0x12c/0x440 siw_qp_llp_data_ready+0x147/0x260 Allocated by task 89: siw_mr_add_mem+0xb2/0x2a0 siw_reg_user_mr+0x19f/0x380 ib_uverbs_reg_mr+0x2a7/0x4c0 Freed by task 89: kfree+0x301/0x530 siw_dereg_mr+0x31/0x50 ib_dereg_mr_user+0xb9/0x200 Free siw_mem with kfree_rcu(). A lookup that loses the race then sees a zero refcount and fails. The umem or PBL is still released at the last put, since a failed lookup never touches it. Fixes: 2251334dcac9 ("rdma/siw: application buffer management") Cc: stable@vger.kernel.org Signed-off-by: Deep Shah Link: https://patch.msgid.link/20261102064437.23976-1-deepshah146@gmail.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/sw/siw/siw.h | 1 + drivers/infiniband/sw/siw/siw_mem.c | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/infiniband/sw/siw/siw.h b/drivers/infiniband/sw/siw/siw.h index dbc998248b1e9f..4ec9c2ac75e7b4 100644 --- a/drivers/infiniband/sw/siw/siw.h +++ b/drivers/infiniband/sw/siw/siw.h @@ -157,6 +157,7 @@ struct siw_mem { void *mem_obj; }; struct ib_pd *pd; + struct rcu_head rcu; }; struct siw_mr { diff --git a/drivers/infiniband/sw/siw/siw_mem.c b/drivers/infiniband/sw/siw/siw_mem.c index 2a08817d3cce08..be70dc9c8f813d 100644 --- a/drivers/infiniband/sw/siw/siw_mem.c +++ b/drivers/infiniband/sw/siw/siw_mem.c @@ -115,7 +115,7 @@ void siw_free_mem(struct kref *ref) else kfree(mem->pbl); } - kfree(mem); + kfree_rcu(mem, rcu); } /* From 9191c2c1a76a759ac97be72481fdd4f9e920c902 Mon Sep 17 00:00:00 2001 From: Miklos Szeredi Date: Mon, 2 Nov 2026 15:11:04 +0100 Subject: [PATCH 0218/2102] fuse: fix possible UAF in fuse_direntplus_link() In fuse_direntplus_link() a use-after-free occurs on struct fuse_inode when linking a newly allocated in-lookup dentry during FUSE_READDIRPLUS processing fails inside d_splice_alias(). When d_in_lookup(dentry) is true, fuse_iget() returns an inode with an incremented reference count and fi->nlookup, which is then passed to d_splice_alias(). Inside d_splice_alias_ops(), if the directory inode has an existing alias and splicing fails with -ELOOP in d_ancestor() or -ESTALE in __d_unalias(), the function drops the alias reference via dput(new) and unconditionally consumes the caller's inode reference via iput(inode) before returning the error pointer. If the existing alias is concurrently unhashed and dropped, iput(inode) drops the final inode reference and evicts the inode immediately via fuse_evict_inode(), sending a FUSE_FORGET request for fi->nlookup and freeing struct fuse_inode via RCU. Because fuse_direntplus_link() subsequently checks !IS_ERR(inode) outside an RCU read-side critical section, it dereferences the freed inode to acquire fi->lock and decrement fi->nlookup, and its caller parse_dirplusfile() then invokes fuse_force_forget() on the error return, issuing a duplicate FUSE_FORGET request to the server. Fixes: b8bd342d50cb ("fuse: nlookup missing decrement in fuse_direntplus_link") Cc: stable@vger.kernel.org #v6.6+ Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-0a00a32c-3732-46fe-9cdb-3c67a11903cc Signed-off-by: Miklos Szeredi --- fs/fuse/readdir.c | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/fs/fuse/readdir.c b/fs/fuse/readdir.c index 295cbd645653da..f4f9590f8ae534 100644 --- a/fs/fuse/readdir.c +++ b/fs/fuse/readdir.c @@ -236,9 +236,13 @@ static int fuse_direntplus_link(struct file *file, inode = fuse_iget(dir->i_sb, o->nodeid, o->generation, &o->attr, ATTR_TIMEOUT(o), attr_version, evict_ctr); - if (!inode) - inode = ERR_PTR(-ENOMEM); + if (!inode) { + d_lookup_done(dentry); + dput(dentry); + return -ENOMEM; + } + ihold(inode); /* d_splice_alias() eats a reference */ alias = d_splice_alias(inode, dentry); d_lookup_done(dentry); if (alias) { @@ -246,15 +250,15 @@ static int fuse_direntplus_link(struct file *file, dentry = alias; } if (IS_ERR(dentry)) { - if (!IS_ERR(inode)) { - struct fuse_inode *fi = get_fuse_inode(inode); + struct fuse_inode *fi = get_fuse_inode(inode); - spin_lock(&fi->lock); - fi->nlookup--; - spin_unlock(&fi->lock); - } + spin_lock(&fi->lock); + fi->nlookup--; + spin_unlock(&fi->lock); + iput(inode); return PTR_ERR(dentry); } + iput(inode); } if (fc->readdirplus_auto) set_bit(FUSE_I_INIT_RDPLUS, &get_fuse_inode(inode)->state); From 9b82a8aed794c8775a38142579686cf383f7f26b Mon Sep 17 00:00:00 2001 From: Miklos Szeredi Date: Tue, 3 Nov 2026 13:11:43 +0100 Subject: [PATCH 0219/2102] fuse: zero the partial EOF page in copy_file_range() In __fuse_copy_file_range() extending a destination file across a hole via copy_file_range() fails to zero the tail of a partial EOF folio when the destination offset starts on a page beyond the old i_size. Commit 34b5c4a6e4fb ("fuse: zero the partial EOF page when extending a file") already fixed several cases of this bug but missed the copy_file_range() case. Signed-off-by: Miklos Szeredi --- fs/fuse/file.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/fs/fuse/file.c b/fs/fuse/file.c index d5e1cb53d86a6b..f09a0a348a1f5e 100644 --- a/fs/fuse/file.c +++ b/fs/fuse/file.c @@ -2999,6 +2999,7 @@ static ssize_t __fuse_copy_file_range(struct file *file_in, loff_t pos_in, struct fuse_write_out outarg; struct fuse_copy_file_range_out outarg_64; u64 bytes_copied; + loff_t old_size; ssize_t err; /* mark unstable when write-back is not used, and file_out gets * extended */ @@ -3023,6 +3024,14 @@ static ssize_t __fuse_copy_file_range(struct file *file_in, loff_t pos_in, if (err) goto out; + /* + * Copying to an offset past EOF extends the file over a hole. Drop the + * cache over the newly exposed range before the new size is published. + */ + old_size = i_size_read(inode_out); + if (pos_out > old_size) + truncate_pagecache_range(inode_out, old_size, pos_out - 1); + /* * Write out dirty pages in the destination file before sending the COPY * request to userspace. After the request is completed, drop the From 9ea515bbfb8c02c621af02410dd2e5234130126d Mon Sep 17 00:00:00 2001 From: Miklos Szeredi Date: Tue, 3 Nov 2026 13:18:36 +0100 Subject: [PATCH 0220/2102] selftests/fuse: test post-EOF page zeroing on copy_file_range() Extend the test for the case of copy_file_range() extending the file over a hole. Fixes: 60dbcce1567f ("selftests/fuse: test post-EOF page zeroing when a file is extended") Signed-off-by: Miklos Szeredi --- .../filesystems/fuse/write_extend_eof_test.c | 143 +++++++++++++++--- 1 file changed, 125 insertions(+), 18 deletions(-) diff --git a/tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c b/tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c index ca6ce6eca382ef..d6d5de8dac275a 100644 --- a/tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c +++ b/tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c @@ -25,24 +25,46 @@ #include #include #include +#include #include #include #include "../../kselftest_harness.h" #define FUSE_ROOT_ID 1 -#define FILE_INO 2 +#define FILE_INO 2 /* "file", the file being extended */ +#define SRC_INO 3 /* "src", copy_file_range() source */ #define MAX_WRITE (128 * 1024) #define BACKING_SIZE (4 * 1024 * 1024) #define POLLUTE 0xee +/* Called directly: the libc wrapper needs off64_t and a recent enough glibc. */ +static ssize_t sys_copy_file_range(int fd_in, int64_t *off_in, int fd_out, + int64_t *off_out, size_t len, + unsigned int flags) +{ + return syscall(__NR_copy_file_range, fd_in, off_in, fd_out, off_out, + len, flags); +} + +/* Per-file server state. */ +struct backing_file { + unsigned char data[BACKING_SIZE]; /* authoritative bytes */ + uint64_t size; +}; + /* Server-side state, shared with the responder thread. */ struct server { int fd; - unsigned char backing[BACKING_SIZE]; /* authoritative bytes */ - uint64_t size; + unsigned int copy_ops; /* FUSE_COPY_FILE_RANGE* seen */ + struct backing_file file[2]; /* FILE_INO, SRC_INO */ }; +static struct backing_file *lookup_file(struct server *s, uint64_t nodeid) +{ + return &s->file[nodeid == SRC_INO]; +} + static void reply(int fd, uint64_t unique, int error, void *data, size_t len) { struct fuse_out_header oh = { @@ -109,17 +131,22 @@ static void *server_thread(void *arg) out.attr_valid = 3600; fill_attr(&out.attr, ih->nodeid, root ? (S_IFDIR | 0755) : (S_IFREG | 0644), - root ? 0 : s->size); + root ? 0 : lookup_file(s, ih->nodeid)->size); reply(s->fd, ih->unique, 0, &out, sizeof(out)); break; } case FUSE_LOOKUP: { + const char *name = (const char *)(ih + 1); struct fuse_entry_out out = {0}; + uint64_t nodeid; - out.nodeid = FILE_INO; + /* Every name exists; "src" is the second file. */ + nodeid = strcmp(name, "src") ? FILE_INO : SRC_INO; + out.nodeid = nodeid; out.attr_valid = 3600; out.entry_valid = 3600; - fill_attr(&out.attr, FILE_INO, S_IFREG | 0644, s->size); + fill_attr(&out.attr, nodeid, S_IFREG | 0644, + lookup_file(s, nodeid)->size); reply(s->fd, ih->unique, 0, &out, sizeof(out)); break; } @@ -134,6 +161,7 @@ static void *server_thread(void *arg) } case FUSE_READ: { struct fuse_read_in *in = (void *)(ih + 1); + struct backing_file *f = lookup_file(s, ih->nodeid); uint64_t off = in->offset; uint32_t size = in->size; @@ -141,11 +169,12 @@ static void *server_thread(void *arg) size = 0; else if (off + size > BACKING_SIZE) size = BACKING_SIZE - off; - reply(s->fd, ih->unique, 0, s->backing + off, size); + reply(s->fd, ih->unique, 0, f->data + off, size); break; } case FUSE_WRITE: { struct fuse_write_in *in = (void *)(ih + 1); + struct backing_file *f = lookup_file(s, ih->nodeid); struct fuse_write_out out = {0}; uint64_t off = in->offset; uint32_t size = in->size; @@ -155,9 +184,9 @@ static void *server_thread(void *arg) if (off + c > BACKING_SIZE) c = BACKING_SIZE - off; - memcpy(s->backing + off, in + 1, c); - if (off + c > s->size) - s->size = off + c; + memcpy(f->data + off, in + 1, c); + if (off + c > f->size) + f->size = off + c; } out.size = size; reply(s->fd, ih->unique, 0, &out, sizeof(out)); @@ -165,32 +194,70 @@ static void *server_thread(void *arg) } case FUSE_SETATTR: { struct fuse_setattr_in *in = (void *)(ih + 1); + struct backing_file *f = lookup_file(s, ih->nodeid); struct fuse_attr_out out = {0}; if ((in->valid & FATTR_SIZE) && in->size <= BACKING_SIZE) { - if (in->size > s->size) - memset(s->backing + s->size, 0, - in->size - s->size); - s->size = in->size; + if (in->size > f->size) + memset(f->data + f->size, 0, + in->size - f->size); + f->size = in->size; } out.attr_valid = 3600; - fill_attr(&out.attr, ih->nodeid, S_IFREG | 0644, s->size); + fill_attr(&out.attr, ih->nodeid, S_IFREG | 0644, f->size); reply(s->fd, ih->unique, 0, &out, sizeof(out)); break; } case FUSE_FALLOCATE: { struct fuse_fallocate_in *in = (void *)(ih + 1); + struct backing_file *f = lookup_file(s, ih->nodeid); uint64_t end = in->offset + in->length; /* Only plain (size-extending) fallocate is used here. */ if (!(in->mode & FALLOC_FL_KEEP_SIZE) && - end <= BACKING_SIZE && end > s->size) { - memset(s->backing + s->size, 0, end - s->size); - s->size = end; + end <= BACKING_SIZE && end > f->size) { + memset(f->data + f->size, 0, end - f->size); + f->size = end; } reply(s->fd, ih->unique, 0, NULL, 0); break; } + case FUSE_COPY_FILE_RANGE: + case FUSE_COPY_FILE_RANGE_64: { + struct fuse_copy_file_range_in *in = (void *)(ih + 1); + struct backing_file *src = lookup_file(s, ih->nodeid); + struct backing_file *dst; + struct fuse_copy_file_range_out out64 = {0}; + struct fuse_write_out out = {0}; + uint64_t off_in = in->off_in; + uint64_t off_out = in->off_out; + uint64_t len = in->len; + + dst = lookup_file(s, in->nodeid_out); + s->copy_ops++; + if (off_in >= BACKING_SIZE || off_out >= BACKING_SIZE) { + len = 0; + } else { + if (off_in + len > BACKING_SIZE) + len = BACKING_SIZE - off_in; + if (off_out + len > BACKING_SIZE) + len = BACKING_SIZE - off_out; + /* The hole left behind stays zero. */ + memmove(dst->data + off_out, src->data + off_in, + len); + if (off_out + len > dst->size) + dst->size = off_out + len; + } + if (ih->opcode == FUSE_COPY_FILE_RANGE) { + out.size = len; + reply(s->fd, ih->unique, 0, &out, sizeof(out)); + } else { + out64.bytes_copied = len; + reply(s->fd, ih->unique, 0, &out64, + sizeof(out64)); + } + break; + } case FUSE_FLUSH: case FUSE_RELEASE: case FUSE_RELEASEDIR: @@ -337,6 +404,46 @@ TEST_F(fuse, fallocate_extend) assert_tail_zeroed(_metadata, self); } +/* + * Extend via copy_file_range() landing on a page strictly past the old EOF + * page, so neither the copied range nor the flush of either file touches the + * old EOF folio. The source has to be a separate file: copying within one + * file would flush it from the source offset on, and writeback zeroes the + * post-EOF tail on the way out, hiding the bug. + */ +TEST_F(fuse, copy_file_range_extend) +{ + int64_t off_in = 0; + int64_t off_out; + char path[128]; + char *buf; + ssize_t ret; + int src; + + pollute_eof_tail(_metadata, self); + off_out = 5 * self->page; + + snprintf(path, sizeof(path), "%s/src", self->dir); + src = open(path, O_RDWR | O_CREAT | O_TRUNC, 0644); + ASSERT_GE(src, 0); + + buf = malloc(self->page); + ASSERT_NE(NULL, buf); + memset(buf, 'C', self->page); + ASSERT_EQ(self->page, pwrite(src, buf, self->page, 0)); + free(buf); + + ret = sys_copy_file_range(src, &off_in, self->fd, &off_out, + self->page, 0); + ASSERT_EQ(self->page, ret); + close(src); + + /* A splice fallback would extend via the write path instead. */ + ASSERT_NE(0u, self->srv->copy_ops); + + assert_tail_zeroed(_metadata, self); +} + /* A write landing inside the old EOF page must not clobber its own data. */ TEST_F(fuse, extend_into_eof_page_preserves_data) { From 2b2bb55990cf1d9dbd59ee326d545798061fce97 Mon Sep 17 00:00:00 2001 From: James Houghton Date: Mon, 26 Oct 2026 21:52:17 +0000 Subject: [PATCH 0221/2102] scsi: bsg: Don't copy sense data to user memory when canceled scsi_bsg_uring_task_cb() copies the sense data to the submitter's response_addr with copy_to_user(). It runs as io_uring task work, but io_uring may also run it with tw.cancel set from other contexts when the submitting task can't run it: from a kworker when the submitting task has exited (io_tctx_fallback_work()), or from io_cancel_local_task_work() when a DEFER_TASKRUN ring is torn down. In a kworker, current->mm is NULL, and the copy does not reliably fail: the user half of the address space belongs to whatever mm happens to be lazily loaded, if any, so up to max_response_len bytes of sense data may be written into an unrelated process. Don't copy the sense data when the task work is canceled, and complete the command with -ECANCELED. Fixes: 7b6d3255e7f8 ("scsi: bsg: add io_uring passthrough handler") Signed-off-by: James Houghton Reviewed-by: Jens Axboe Link: https://patch.msgid.link/20261026215226.3713941-2-jthoughton@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/scsi_bsg.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/drivers/scsi/scsi_bsg.c b/drivers/scsi/scsi_bsg.c index e4a65d7a237422..3cf1caad02f70b 100644 --- a/drivers/scsi/scsi_bsg.c +++ b/drivers/scsi/scsi_bsg.c @@ -43,9 +43,17 @@ static void scsi_bsg_uring_task_cb(struct io_tw_req tw_req, io_tw_token_t tw) if (pdu->bio) ret = blk_rq_unmap_user(pdu->bio); + /* + * If the request is being canceled, e.g. because the submitting task + * has exited, this may run from a kworker or in a different task, so + * don't copy the sense data to the submitter's address. + */ + if (unlikely(tw.cancel)) + ret = -ECANCELED; + if (scsi_status_is_check_condition(scmd->result)) { driver_status = DRIVER_SENSE; - if (pdu->response_addr) + if (pdu->response_addr && !tw.cancel) sense_len_wr = min_t(unsigned int, pdu->max_response_len, scmd->sense_len); } From 6da1bc55c060bec3163b0e6077f3ac9641f8100c Mon Sep 17 00:00:00 2001 From: Stanley Jhu Date: Thu, 29 Oct 2026 15:08:30 +0800 Subject: [PATCH 0222/2102] scsi: ufs: core: Keep clock-gating hold on failed W-LUN runtime resume 1. __ufshcd_wl_suspend() takes one ufshcd_hold() reference and sets hba->clk_gating.is_suspended while the UFS device W-LUN enters RPM_SUSPENDED. 2. Since commit eef1d74bf88f ("PM: runtime: Only set runtime_error on suspend callback failures"), a failed runtime resume (for example START STOP UNIT completing with an error) leaves the W-LUN in RPM_SUSPENDED with power.runtime_error == 0, while __ufshcd_wl_resume() already clears hba->clk_gating.is_suspended and calls ufshcd_release(). 3. The next W-LUN runtime resume runs __ufshcd_wl_resume() again without an intervening suspend and calls ufshcd_release() a second time, dropping a reference it does not own and underflowing hba->clk_gating.active_reqs on UFSHCD_CAP_CLK_GATING hosts. Keep hba->clk_gating.is_suspended and the suspend hold across a failed W-LUN runtime resume, so the hold stays paired with the W-LUN RPM_SUSPENDED state and the next successful resume releases it. Fixes: eef1d74bf88f ("PM: runtime: Only set runtime_error on suspend callback failures") Cc: stable@vger.kernel.org # v7.3+ Signed-off-by: Stanley Jhu Reviewed-by: Brian Norris Reviewed-by: Peter Wang Link: https://patch.msgid.link/20261029040002.2100002-1-stanleyjhu@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/core/ufshcd.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/drivers/ufs/core/ufshcd.c b/drivers/ufs/core/ufshcd.c index fd52deb72d21c4..4f0301d2a5d4cf 100644 --- a/drivers/ufs/core/ufshcd.c +++ b/drivers/ufs/core/ufshcd.c @@ -10651,8 +10651,14 @@ static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op) out: if (ret) ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret); - hba->clk_gating.is_suspended = false; - ufshcd_release(hba); + /* + * A failed runtime resume leaves the W-LUN RPM_SUSPENDED, so keep + * is_suspended and the suspend hold for the next resume. + */ + if (!ret || pm_op != UFS_RUNTIME_PM) { + hba->clk_gating.is_suspended = false; + ufshcd_release(hba); + } hba->pm_op_in_progress = false; return ret; } From 807b09be9c8f234ce758bcf43101f34e0a036b83 Mon Sep 17 00:00:00 2001 From: Yunhui Cui Date: Thu, 22 Oct 2026 16:32:12 +0800 Subject: [PATCH 0223/2102] riscv: Fix SR_SUM leakage across context switches __switch_to() saves the sstatus value of prev and restores the SR_SUM bit of next with csrs. However, csrs only sets bits. If prev has SR_SUM set and next has SR_SUM clear in its saved state, the old SR_SUM bit remains set in sstatus. This lets next run with user memory access enabled even though its saved SR_SUM state is clear. Use csrrc to save the sstatus value of prev and clear SR_SUM from the live CSR before restoring the saved SR_SUM state of next. This keeps prev's SR_SUM state intact, while preventing it from leaking to next. Fixes: 788aa64c01f1 ("riscv: save the SR_SUM status over switches") Cc: stable@vger.kernel.org Signed-off-by: Yunhui Cui Reviewed-by: Jisheng Zhang Reviewed-by: Andy Chiu Reviewed-by: Yicong Yang Link: https://patch.msgid.link/20261022083212.84721-1-cuiyunhui@bytedance.com Signed-off-by: Paul Walmsley --- arch/riscv/kernel/entry.S | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/arch/riscv/kernel/entry.S b/arch/riscv/kernel/entry.S index 61b7a77166971d..628b85e3915a7e 100644 --- a/arch/riscv/kernel/entry.S +++ b/arch/riscv/kernel/entry.S @@ -443,15 +443,15 @@ SYM_FUNC_START(__switch_to) REG_S s10, TASK_THREAD_S10_RA(a3) REG_S s11, TASK_THREAD_S11_RA(a3) - /* save the user space access flag */ - csrr s0, CSR_STATUS + /* Save and clear the user space access flag. */ + li s1, SR_SUM + csrrc s0, CSR_STATUS, s1 REG_S s0, TASK_THREAD_SUM_RA(a3) /* Save the kernel shadow call stack pointer */ scs_save_current /* Restore context from next->thread */ REG_L s0, TASK_THREAD_SUM_RA(a4) - li s1, SR_SUM and s0, s0, s1 csrs CSR_STATUS, s0 REG_L ra, TASK_THREAD_RA_RA(a4) From 0d0c6a49d80669176f721403916df0b1e32afeef Mon Sep 17 00:00:00 2001 From: Michael Ellerman Date: Thu, 29 Oct 2026 23:07:12 +1100 Subject: [PATCH 0224/2102] riscv: defconfig: Disable COMPAT_BRK COMPAT_BRK defaults to y, which disables brk (heap) randomisation by default (ie. randomize_va_space=1 by default) for compatibility with "ancient" binaries, in particular libc5 based binaries. libc5 predates RISC-V, so there can't be any libc5 binaries for RISC-V. COMPAT_BRK was introduced in 2008, commit 32a932332c8b ("brk randomization: introduce CONFIG_COMPAT_BRK"). But even then the only non-libc5 binaries mentioned as being broken were ~5 year old versions of emacs (see commit c1d171a00294 ("x86: randomize brk")). Distro kernels for riscv64 also disable it, including Debian, Fedora, openSUSE and Ubuntu. So even if there were riscv binaries out there that rely on it, no mainstream distro would support them. Most other architectures already disable COMPAT_BRK in their primary defconfigs, including arm64, x86_64, powerpc, s390, loongarch and sparc64, as do the riscv nommu defconfigs. It is also disabled in kernel/configs/hardening.config. So disable COMPAT_BRK in the riscv defconfig so that brk is randomised by default, matching distro and other arch configs. Signed-off-by: Michael Ellerman Link: https://patch.msgid.link/20261029-compat-brk-v1-1-5b2cf86eb453@kernel.org Signed-off-by: Paul Walmsley --- arch/riscv/configs/defconfig | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/riscv/configs/defconfig b/arch/riscv/configs/defconfig index 04ae305d5511bb..933cbf2735eca5 100644 --- a/arch/riscv/configs/defconfig +++ b/arch/riscv/configs/defconfig @@ -52,6 +52,7 @@ CONFIG_JUMP_LABEL=y CONFIG_MODULES=y CONFIG_MODULE_UNLOAD=y CONFIG_BLK_DEV_THROTTLING=y +# CONFIG_COMPAT_BRK is not set CONFIG_SPARSEMEM_MANUAL=y CONFIG_NET=y CONFIG_PACKET=y From 784118478160751016b3bc437d009890fa20f3f7 Mon Sep 17 00:00:00 2001 From: Saad Anjum Date: Mon, 5 Oct 2026 11:06:41 +0500 Subject: [PATCH 0225/2102] pinctrl: mediatek: common-v2: Fix of_iomap() error check of_iomap() returns NULL on failure, never an error pointer, so the IS_ERR() check in mtk_build_eint() can never be true. The check was carried over from the previous devm_platform_ioremap_resource_byname() call, which does return an error pointer, when the EINT registers were switched to being mapped with of_iomap() to support multiple bases. If mapping one of the EINT register ranges fails, for example because the device tree node lists more "reg-names" than "reg" entries so that of_address_to_resource() fails, or because ioremap() itself fails, the NULL pointer is stored in hw->eint->base[] and probing continues. mtk_eint_do_init() then calls mtk_eint_hw_init(), which writes to eint->base[i] + regs->dom_en, causing a NULL pointer dereference instead of a clean probe failure. Check for NULL and return -ENOMEM instead. The existing error path already skips NULL entries when unmapping, so any ranges mapped before the failure are still released. Fixes: 3ef9f710efcb ("pinctrl: mediatek: Add EINT support for multiple addresses") Signed-off-by: Saad Anjum Signed-off-by: Linus Walleij --- drivers/pinctrl/mediatek/pinctrl-mtk-common-v2.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/pinctrl/mediatek/pinctrl-mtk-common-v2.c b/drivers/pinctrl/mediatek/pinctrl-mtk-common-v2.c index faa6dbf0f6356f..bf9d20b5921338 100644 --- a/drivers/pinctrl/mediatek/pinctrl-mtk-common-v2.c +++ b/drivers/pinctrl/mediatek/pinctrl-mtk-common-v2.c @@ -398,8 +398,8 @@ int mtk_build_eint(struct mtk_pinctrl *hw, struct platform_device *pdev) for (i = hw->soc->nbase_names, j = 0; i < count_reg_names; i++, j++) { hw->eint->base[j] = of_iomap(np, i); - if (IS_ERR(hw->eint->base[j])) { - ret = PTR_ERR(hw->eint->base[j]); + if (!hw->eint->base[j]) { + ret = -ENOMEM; goto err_free_eint; } } From d432e5d3dbd98589029905e898bfe7005be69b68 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:43:28 +0100 Subject: [PATCH 0226/2102] comedi: fix endless recursion in comedi_event() When comedi_event() was split into a wrapper which takes a reference on the running command and _comedi_event(), which does the work, the wrapper ended up calling itself: if (comedi_get_is_subdevice_running(s)) { comedi_event(dev, s); comedi_put_is_subdevice_running(s); } As long as the command is running every level takes another reference and recurses, until the stack is used up. Most drivers go through comedi_handle_events(), which calls _comedi_event(). usbdux, usbduxfast and usbduxsigma cannot use that and call comedi_event() from their URB completion handlers, i.e. for every completed URB of a running acquisition. Fixes: 51495254fda4 ("comedi: Use reference count for asynchronous command functions") Cc: stable Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261027-llm-char-misc-comedi-v1-1-1899771ee15b@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/comedi/comedi_fops.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/comedi/comedi_fops.c b/drivers/comedi/comedi_fops.c index 05d14839c5a6a1..68eddf853465b7 100644 --- a/drivers/comedi/comedi_fops.c +++ b/drivers/comedi/comedi_fops.c @@ -3495,7 +3495,7 @@ void _comedi_event(struct comedi_device *dev, struct comedi_subdevice *s) void comedi_event(struct comedi_device *dev, struct comedi_subdevice *s) { if (comedi_get_is_subdevice_running(s)) { - comedi_event(dev, s); + _comedi_event(dev, s); comedi_put_is_subdevice_running(s); } } From ade85ceef46892425a08f3ee52ca06729ee4922e Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:43:29 +0100 Subject: [PATCH 0227/2102] comedi: addi_apci_1500: fix clearing of the gate enable INSN_CONFIG_SET_GATE_SRC reads the mode register of the counter/timer, is meant to clear the External Gate Enable bit, sets it again if the external gate was asked for, and writes the register back. The mask lacks its '~': all the bits but EGE are cleared instead. So - the external gate can be enabled but never be disabled again, and - the instruction wipes the mode (continuous or single cycle, external output, count and trigger enables, retrigger, duty cycle) which INSN_CONFIG_SET_COUNTER_MODE has programmed: the timer silently falls back to a single cycle pulse. With the right mask, the instruction only changes the gate bit. An application which sets the gate source after the counter mode now keeps the mode it has asked for. Fixes: a8c66b684efa ("staging: comedi: addi_apci_1500: rewrite the subdevice support functions") Cc: stable Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261027-llm-char-misc-comedi-v1-2-1899771ee15b@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/comedi/drivers/addi_apci_1500.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/comedi/drivers/addi_apci_1500.c b/drivers/comedi/drivers/addi_apci_1500.c index a203e27888e2f6..3d65aef565b318 100644 --- a/drivers/comedi/drivers/addi_apci_1500.c +++ b/drivers/comedi/drivers/addi_apci_1500.c @@ -696,7 +696,7 @@ static int apci1500_timer_insn_config(struct comedi_device *dev, return -EINVAL; val = z8536_read(dev, Z8536_CT_MODE_REG(chan)); - val &= Z8536_CT_MODE_EGE; + val &= ~Z8536_CT_MODE_EGE; if (data[1] == 1) val |= Z8536_CT_MODE_EGE; else if (data[1] > 1) From 5a0c88567a5ebbe24ecb7828e200f63ed972718f Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:43:30 +0100 Subject: [PATCH 0228/2102] comedi: ni_660x: don't poll without a DMA channel A counter command owns a MITE DMA channel from ni_660x_cmd() to ni_660x_cancel(). A command does not only end by COMEDI_CANCEL: when the reader is too slow mite_sync_input_dma() sets COMEDI_CB_OVERFLOW, and counter errors set COMEDI_CB_ERROR, and comedi_handle_events() then calls ->cancel() from the interrupt handler. That releases the channel and clears counter->mite_chan, but s->busy stays set until the owner has read the rest of the data and seen the end of the acquisition. do_poll_ioctl() only looks at s->busy, so a COMEDI_POLL in that state ends in mite_sync_dma(NULL, s), which dereferences the channel. Test the channel like ni_pcidio_poll() and ni_sync_ai_dma() do. The pointer only changes under dev->mutex, which the ioctl holds, or in the interrupt handler under interrupt_lock, which is taken here. Fixes: 894db1197347 ("Staging: Comedi: ni_600x: Added support for comedi_poll.") Cc: stable Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261027-llm-char-misc-comedi-v1-3-1899771ee15b@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/comedi/drivers/ni_660x.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/comedi/drivers/ni_660x.c b/drivers/comedi/drivers/ni_660x.c index 5508cdb1b0bacd..9238475dda07d2 100644 --- a/drivers/comedi/drivers/ni_660x.c +++ b/drivers/comedi/drivers/ni_660x.c @@ -459,7 +459,8 @@ static int ni_660x_input_poll(struct comedi_device *dev, /* lock to avoid race with comedi_poll */ spin_lock_irqsave(&devpriv->interrupt_lock, flags); - mite_sync_dma(counter->mite_chan, s); + if (counter->mite_chan) + mite_sync_dma(counter->mite_chan, s); spin_unlock_irqrestore(&devpriv->interrupt_lock, flags); return comedi_buf_read_n_available(s); } From ec214735bb113be747454812035b83010892e0d2 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:43:31 +0100 Subject: [PATCH 0229/2102] comedi: ni_tio: Fix overflow of the clock period ni_tio_set_clock_src() stores the period of the clock source, which the user passes in nanoseconds, in picoseconds: counter->clock_period_ps = period_ns * 1000; period_ns is an unsigned int, so that the product is computed in 32 bits, although clock_period_ps is a u64. It wraps for periods above 4294967 ns, that is for external clocks slower than 233 Hz. INSN_CONFIG_GET_CLOCK_SRC then reports a wrong period, and ni_tio_set_sync_mode() decides on a wrong one: 4294968 ns become 704 ps, which is below the limit of 25 ns under which the alternate synchronization mode for fast clocks is switched on. The multiplication was done in 64 bits until the constant pico_per_nano, a uint64_t, was replaced by a literal. Widen again. Fixes: 3e90b1c7ebe9 ("staging: comedi: ni_tio: tidy up ni_tio_set_clock_src() and helpers") Cc: stable Signed-off-by: Josef Bacik Reviewed-by: Ian Abbott Link: https://patch.msgid.link/20261027-llm-char-misc-comedi-v1-4-1899771ee15b@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/comedi/drivers/ni_tio.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/comedi/drivers/ni_tio.c b/drivers/comedi/drivers/ni_tio.c index c3a909abcfa71b..b7ab70f34275e8 100644 --- a/drivers/comedi/drivers/ni_tio.c +++ b/drivers/comedi/drivers/ni_tio.c @@ -800,7 +800,7 @@ static int ni_tio_set_clock_src(struct ni_gpct *counter, GI_PRESCALE_X2(counter_dev->variant) | GI_PRESCALE_X8(counter_dev->variant), bits); } - counter->clock_period_ps = period_ns * 1000; + counter->clock_period_ps = (u64)period_ns * 1000; ni_tio_set_sync_mode(counter); return 0; } From 92fa93505576188acc22c5de1999db9a1c70c09b Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:43:32 +0100 Subject: [PATCH 0230/2102] comedi: vmk80xx: report failed transfers of the K8061 For the K8061 board vmk80xx_read_packet() and vmk80xx_write_packet() call vmk80xx_do_bulk_msg(), which ignores the result of its two bulk transfers, and return 0. After a timeout, a stall or an unplug the instruction handlers therefore go on and hand the old content of usb_rx_buf to user space as a fresh sample (analog and digital inputs, counters, PWM and output read-back), and writes to the outputs are reported as done. All callers check the result already, because the K8055 branch of the two functions returns that of usb_interrupt_msg(). Return the error of the bulk transfers as well, and don't wait for an answer to a command that could not be sent. Fixes: 985cafccbf9b ("Staging: Comedi: vmk80xx: Add k8061 support") Cc: stable Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261027-llm-char-misc-comedi-v1-5-1899771ee15b@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/comedi/drivers/vmk80xx.c | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/drivers/comedi/drivers/vmk80xx.c b/drivers/comedi/drivers/vmk80xx.c index 84dce5184a77ae..ddb12b48c8a493 100644 --- a/drivers/comedi/drivers/vmk80xx.c +++ b/drivers/comedi/drivers/vmk80xx.c @@ -151,7 +151,7 @@ struct vmk80xx_private { enum vmk80xx_model model; }; -static void vmk80xx_do_bulk_msg(struct comedi_device *dev) +static int vmk80xx_do_bulk_msg(struct comedi_device *dev) { struct vmk80xx_private *devpriv = dev->private; struct usb_device *usb = comedi_to_usb_dev(dev); @@ -161,6 +161,7 @@ static void vmk80xx_do_bulk_msg(struct comedi_device *dev) unsigned int rx_pipe; size_t tx_size; size_t rx_size; + int ret; tx_addr = devpriv->ep_tx->bEndpointAddress; rx_addr = devpriv->ep_rx->bEndpointAddress; @@ -169,11 +170,13 @@ static void vmk80xx_do_bulk_msg(struct comedi_device *dev) tx_size = usb_endpoint_maxp(devpriv->ep_tx); rx_size = usb_endpoint_maxp(devpriv->ep_rx); - usb_bulk_msg(usb, tx_pipe, devpriv->usb_tx_buf, tx_size, NULL, - PACKET_TIMEOUT); + ret = usb_bulk_msg(usb, tx_pipe, devpriv->usb_tx_buf, tx_size, NULL, + PACKET_TIMEOUT); + if (ret) + return ret; - usb_bulk_msg(usb, rx_pipe, devpriv->usb_rx_buf, rx_size, NULL, - PACKET_TIMEOUT); + return usb_bulk_msg(usb, rx_pipe, devpriv->usb_rx_buf, rx_size, NULL, + PACKET_TIMEOUT); } static int vmk80xx_read_packet(struct comedi_device *dev) @@ -183,10 +186,8 @@ static int vmk80xx_read_packet(struct comedi_device *dev) struct usb_endpoint_descriptor *ep; unsigned int pipe; - if (devpriv->model == VMK8061_MODEL) { - vmk80xx_do_bulk_msg(dev); - return 0; - } + if (devpriv->model == VMK8061_MODEL) + return vmk80xx_do_bulk_msg(dev); ep = devpriv->ep_rx; pipe = usb_rcvintpipe(usb, ep->bEndpointAddress); @@ -204,10 +205,8 @@ static int vmk80xx_write_packet(struct comedi_device *dev, int cmd) devpriv->usb_tx_buf[0] = cmd; - if (devpriv->model == VMK8061_MODEL) { - vmk80xx_do_bulk_msg(dev); - return 0; - } + if (devpriv->model == VMK8061_MODEL) + return vmk80xx_do_bulk_msg(dev); ep = devpriv->ep_tx; pipe = usb_sndintpipe(usb, ep->bEndpointAddress); From 824a27d391cf934d3232e8e2dabee221fc4e18ae Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:58:16 +0100 Subject: [PATCH 0231/2102] misc: vmw_vmci: wait for callbacks in event unsubscribe event_deliver() calls the callbacks of the subscribers inside an RCU read side critical section. vmci_event_unsubscribe() used to call synchronize_rcu() before it freed the subscription. This did more than to protect the struct vmci_subscription: when the function returned, no callback was running any more, and its callers rely on that. vmci_transport_free_resources() unsubscribes from VMCI_EVENT_QP_PEER_DETACH and frees the struct vmci_transport, which is the callback data, a few lines later: CPU0 CPU1 event_deliver() rcu_read_lock() vmci_transport_peer_detach_cb() vmci_event_unsubscribe() list_del_rcu(&s->node) kvfree_rcu_mightsleep(s) kfree(transport) spin_lock_bh(&trans->lock) The event is sent when the peer of the queue pair detaches, so the other end of a vsock connection chooses the time. vmci_transport_exit() and vmci_guest_remove_device() unsubscribe callbacks which are gone with their module. kvfree_rcu_mightsleep() only waits for a grace period if it cannot allocate memory. Bring the synchronize_rcu() back. The cleanup work of the vmci transport now waits for one grace period per socket again. Fixes: 6da3f33770e0 ("misc: vmw_vmci: Switch to kvfree_rcu() API") Cc: stable Cc: Bryan Tan Cc: Vishnu Dasa Cc: Broadcom internal kernel review list Cc: Arnd Bergmann Signed-off-by: Josef Bacik Link: https://patch.msgid.link/2026102715-escapable-quaintly-8530@gregkh Signed-off-by: Greg Kroah-Hartman --- drivers/misc/vmw_vmci/vmci_event.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/misc/vmw_vmci/vmci_event.c b/drivers/misc/vmw_vmci/vmci_event.c index c3ef3b98c432e0..57d3a63678acd9 100644 --- a/drivers/misc/vmw_vmci/vmci_event.c +++ b/drivers/misc/vmw_vmci/vmci_event.c @@ -213,7 +213,12 @@ int vmci_event_unsubscribe(u32 sub_id) if (!s) return VMCI_ERROR_NOT_FOUND; - kvfree_rcu_mightsleep(s); + /* + * Wait for event_deliver(): the caller is going to free what the + * callback works on. + */ + synchronize_rcu(); + kfree(s); return VMCI_SUCCESS; } From a36b3db60466d44eefcc5c252ce927c043429922 Mon Sep 17 00:00:00 2001 From: Guangshuo Li Date: Tue, 27 Oct 2026 23:09:21 +0800 Subject: [PATCH 0232/2102] misc: bcm-vk: fix DMA allocation memory leak bcm_vk_dma_alloc() leaks dma->pages and pinned user-page references when page pinning or coherent SG allocation fails. DMA mapping failures can also leave the SG list and earlier mappings unreleased, as bcm_vk_sg_alloc() skips the partially initialized slot. This issue was found by our static analysis tool under development. Fixes: 111d746bb476 ("misc: bcm-vk: add VK messaging support") Cc: stable@vger.kernel.org Signed-off-by: Guangshuo Li Link: https://patch.msgid.link/20261027150921.137189-1-lgs201920130244@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/misc/bcm-vk/bcm_vk_sg.c | 43 +++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/drivers/misc/bcm-vk/bcm_vk_sg.c b/drivers/misc/bcm-vk/bcm_vk_sg.c index 8662bb8651293c..b237a5332b7f0a 100644 --- a/drivers/misc/bcm-vk/bcm_vk_sg.c +++ b/drivers/misc/bcm-vk/bcm_vk_sg.c @@ -78,7 +78,8 @@ static int bcm_vk_dma_alloc(struct device *dev, dma->nr_pages = (err >= 0) ? err : 0; dev_err(dev, "get_user_pages_fast, err=%d [%d]\n", err, dma->nr_pages); - return err < 0 ? err : -EINVAL; + err = err < 0 ? err : -EINVAL; + goto err_pages; } /* Max size of sg list is 1 per mapped page + fields at start */ @@ -90,8 +91,10 @@ static int bcm_vk_dma_alloc(struct device *dev, dma->sglen, &dma->handle, GFP_KERNEL); - if (!dma->sglist) - return -ENOMEM; + if (!dma->sglist) { + err = -ENOMEM; + goto err_pages; + } dma->sglist[SGLIST_NUM_SG] = 0; dma->sglist[SGLIST_TOTALSIZE] = vkdata->size; @@ -108,8 +111,8 @@ static int bcm_vk_dma_alloc(struct device *dev, dma->direction); transfer_size = size; if (unlikely(dma_mapping_error(dev, sg_addr))) { - __free_page(dma->pages[0]); - return -EIO; + err = -EIO; + goto err_sglist; } for (i = 1; i < dma->nr_pages; i++) { @@ -121,8 +124,8 @@ static int bcm_vk_dma_alloc(struct device *dev, size, dma->direction); if (unlikely(dma_mapping_error(dev, addr))) { - __free_page(dma->pages[i]); - return -EIO; + err = -EIO; + goto err_unmap; } /* @@ -167,6 +170,32 @@ static int bcm_vk_dma_alloc(struct device *dev, #endif return 0; + +err_unmap: + /* + * Unmap completed SG entries and the in-progress DMA range, + * which has not been written to the SG list yet. + */ + sgdata = (struct _vk_data *)&dma->sglist[SGLIST_VKDATA_START]; + for (i = 0; i < dma->sglist[SGLIST_NUM_SG]; i++) { + size = sgdata[i].size; + addr = get_unaligned(&sgdata[i].address); + dma_unmap_page(dev, addr, size, dma->direction); + } + dma_unmap_page(dev, sg_addr, transfer_size, dma->direction); + +err_sglist: + dma_free_coherent(dev, dma->sglen, dma->sglist, dma->handle); + +err_pages: + for (i = 0; i < dma->nr_pages; i++) + put_page(dma->pages[i]); + kfree(dma->pages); + dma->pages = NULL; + dma->sglist = NULL; + dma->sglen = 0; + dma->nr_pages = 0; + return err; } int bcm_vk_sg_alloc(struct device *dev, From 8599e08648c0b4913ea7b202511f1294d176e793 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:04:34 +0100 Subject: [PATCH 0233/2102] w1: use the bus mutex for the "rw" file Commit b02f8bede217 ("W1: split master mutex to avoid deadlocks.") gave the bus a mutex of its own, because the lock which protects the list of slaves is held while a slave is removed, which waits for the sysfs callbacks of the slave, so these must not take it. It converted all the slave drivers, but not the "rw" file of the default family in w1.c, which still takes the mutex of the master to talk on the bus. That has two consequences: - A deadlock. w1_process() holds the mutex of the master while it searches the bus and detaches the slaves which have gone: w1_process() read() of .../rw mutex_lock(&dev->mutex) kernfs active reference w1_search_process() rw_read() w1_slave_detach() mutex_lock(&master->mutex) w1_unref_slave() waits device_unregister() waits for the reference The file is readable for everybody. - The accesses through this file are not serialised with those of the slave drivers, which take bus_mutex, so that two transactions can get mixed up on the wire. Take bus_mutex here as well. It also excludes the search, which takes it for every pass. Fixes: b02f8bede217 ("W1: split master mutex to avoid deadlocks.") Cc: stable Signed-off-by: Josef Bacik Reviewed-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261027-llm-char-misc-w1-v1-1-d2e6bfafb6a4@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/w1/w1.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/w1/w1.c b/drivers/w1/w1.c index c1694664278929..fe7b73d2a5536b 100644 --- a/drivers/w1/w1.c +++ b/drivers/w1/w1.c @@ -116,7 +116,7 @@ static ssize_t rw_write(struct file *filp, struct kobject *kobj, { struct w1_slave *sl = kobj_to_w1_slave(kobj); - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); if (w1_reset_select_slave(sl)) { count = 0; goto out_up; @@ -125,7 +125,7 @@ static ssize_t rw_write(struct file *filp, struct kobject *kobj, w1_write_block(sl->master, buf, count); out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -135,9 +135,9 @@ static ssize_t rw_read(struct file *filp, struct kobject *kobj, { struct w1_slave *sl = kobj_to_w1_slave(kobj); - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); w1_read_block(sl->master, buf, count); - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } From dfc57752ec53c3cc6105656d3037fb2f5e80e9cc Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:04:35 +0100 Subject: [PATCH 0234/2102] w1: remove the master's files before taking its locks __w1_remove_master_device() calls w1_destroy_master_attributes() with both the mutex of the master and list_mutex held. Removing the files waits for the callbacks which are running, and nearly all of them take one of these two locks: __w1_remove_master_device() read() of .../w1_master_slaves mutex_lock(&dev->mutex) kernfs active reference mutex_lock(&dev->list_mutex) w1_master_attribute_show_slaves() w1_destroy_master_attributes() mutex_lock(&md->list_mutex) sysfs_remove_group() waits waits for the reference The files are readable for everybody, and a bus master goes away when, for instance, a DS2490 USB adapter is unplugged. Remove the files first, before the locks are taken. That has to be done before the slaves are detached and not afterwards: as long as the files exist, a write to w1_master_add could attach a new slave behind the back of this function, which would then wait for the reference count of the master for ever. And it is done before the thread is stopped, because a write to w1_master_search wakes the thread up. Fixes: c30c9b15187e ("W1: fix deadlocks and remove w1_control_thread") Cc: stable Signed-off-by: Josef Bacik Reviewed-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261027-llm-char-misc-w1-v1-2-d2e6bfafb6a4@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/w1/w1_int.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/drivers/w1/w1_int.c b/drivers/w1/w1_int.c index 19a0ea28e9f39a..3fcc9ee567278a 100644 --- a/drivers/w1/w1_int.c +++ b/drivers/w1/w1_int.c @@ -176,6 +176,13 @@ void __w1_remove_master_device(struct w1_master *dev) mutex_unlock(&w1_mlock); set_bit(W1_ABORT_SEARCH, &dev->flags); + + /* + * This waits for the callbacks, which take the locks below. One of + * them wakes the thread up. + */ + w1_destroy_master_attributes(dev); + kthread_stop(dev->thread); mutex_lock(&dev->mutex); @@ -185,7 +192,6 @@ void __w1_remove_master_device(struct w1_master *dev) w1_slave_detach(sl); mutex_lock(&dev->list_mutex); } - w1_destroy_master_attributes(dev); mutex_unlock(&dev->list_mutex); mutex_unlock(&dev->mutex); atomic_dec(&dev->refcnt); From e4f673632fa8292a2922bcfbb39519b08016b382 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:04:36 +0100 Subject: [PATCH 0235/2102] w1: ds2482: set the strong pull-up with its byte The eight channels of a DS2482-800 are eight independent 1-wire masters for the w1 core, but share one I2C device. Each bus operation consists of several I2C transfers: select the channel, send the command, poll the status, set the read pointer, read the result. access_lock keeps the operations of the channels apart. ds2482_w1_set_pullup() polls the status, writes the configuration and polls again without the lock. Polling sets the read pointer of the device to the status register. In the middle of a read on another channel, after that one has set the pointer to the data register, this makes the read return the status instead of the data. The cached copy of the pointer in pdev->read_prt can go wrong as well. The lock alone is not enough. The strong pull-up is a setting of the whole chip which is used up by the next byte. If an operation of another channel gets in before the byte it was meant for, that channel gets the pull-up, and the sensor converts without power. So only note the request in ds2482_w1_set_pullup(), and write the configuration in ds2482_w1_write_byte(), under the lock and after the channel has been selected. The w1 core calls the former right before the latter, under the bus mutex of the channel. Fixes: 9c95bb6f25ff ("w1: ds2482: Added 1-Wire pull-up support to the driver") Cc: stable Signed-off-by: Josef Bacik Reviewed-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261027-llm-char-misc-w1-v1-3-d2e6bfafb6a4@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/w1/masters/ds2482.c | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/drivers/w1/masters/ds2482.c b/drivers/w1/masters/ds2482.c index cbd11bc6127493..5498bb04f7cecb 100644 --- a/drivers/w1/masters/ds2482.c +++ b/drivers/w1/masters/ds2482.c @@ -103,6 +103,7 @@ struct ds2482_data; struct ds2482_w1_chan { struct ds2482_data *pdev; u8 channel; + bool spu; /* strong pullup after the next byte */ struct w1_bus_master w1_bm; }; @@ -336,6 +337,19 @@ static void ds2482_w1_write_byte(void *data, u8 byte) if (pdev->w1_count > 1) ds2482_set_channel(pdev, pchan->channel); + if (pchan->spu) { + pchan->spu = false; + /* the wait above and this one are crucial, otherwise devices + * might not be powered long enough, causing e.g. a w1_therm + * sensor to provide wrong conversion results + */ + /* note: it seems like both SPU and APU have to be set! */ + ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG, + ds2482_calculate_config(DS2482_REG_CFG_SPU | + DS2482_REG_CFG_APU)); + ds2482_wait_1wire_idle(pdev); + } + /* Send the write byte command */ ds2482_send_cmd_data(pdev, DS2482_CMD_1WIRE_WRITE_BYTE, byte); @@ -420,27 +434,19 @@ static u8 ds2482_w1_reset_bus(void *data) static u8 ds2482_w1_set_pullup(void *data, int delay) { struct ds2482_w1_chan *pchan = data; - struct ds2482_data *pdev = pchan->pdev; - u8 retval = 1; /* if delay is non-zero activate the pullup, * the strong pullup will be automatically deactivated * by the master, so do not explicitly deactive it + * + * The setting is used up by the next byte on any channel of the chip: + * ds2482_w1_write_byte() makes it, in one go with the byte. */ - if (delay) { - /* both waits are crucial, otherwise devices might not be - * powered long enough, causing e.g. a w1_therm sensor to - * provide wrong conversion results - */ - ds2482_wait_1wire_idle(pdev); - /* note: it seems like both SPU and APU have to be set! */ - retval = ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG, - ds2482_calculate_config(DS2482_REG_CFG_SPU | - DS2482_REG_CFG_APU)); - ds2482_wait_1wire_idle(pdev); - } + if (!delay) + return 1; - return retval; + pchan->spu = true; + return 0; } From 5bc51235d0ad4a4991e38f4e9dc3440738296850 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:04:37 +0100 Subject: [PATCH 0236/2102] w1: ds28e04: use the bus mutex to talk on the bus Since commit b02f8bede217 ("W1: split master mutex to avoid deadlocks.") the slave drivers serialise their accesses to the bus with bus_mutex. This driver, which was merged shortly afterwards, takes the mutex of the master in the callbacks of its eeprom and pio files instead. That mutex is held while a slave which has disappeared from the bus is removed, which waits for the sysfs callbacks of the slave to return. A callback which is waiting for the mutex at that moment never does: both tasks are stuck, and with them the thread of the bus master. Besides, it does not keep the other slave drivers off the bus, so that two transactions can get mixed up on the wire. Fixes: fbf7f7b4e2ae ("w1: Add 1-wire slave device driver for DS28E04-100") Cc: stable Signed-off-by: Josef Bacik Reviewed-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261027-llm-char-misc-w1-v1-4-d2e6bfafb6a4@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/w1/slaves/w1_ds28e04.c | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/drivers/w1/slaves/w1_ds28e04.c b/drivers/w1/slaves/w1_ds28e04.c index 3b3c0789e1adf3..30fb8415b659e0 100644 --- a/drivers/w1/slaves/w1_ds28e04.c +++ b/drivers/w1/slaves/w1_ds28e04.c @@ -123,7 +123,7 @@ static ssize_t eeprom_read(struct file *filp, struct kobject *kobj, if (count == 0) return 0; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); if (w1_enable_crccheck) { min_page = (off >> W1_PAGE_BITS); @@ -140,7 +140,7 @@ static ssize_t eeprom_read(struct file *filp, struct kobject *kobj, } out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -253,7 +253,7 @@ static ssize_t eeprom_write(struct file *filp, struct kobject *kobj, } } - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* Can only write data to one page at a time */ idx = 0; @@ -271,7 +271,7 @@ static ssize_t eeprom_write(struct file *filp, struct kobject *kobj, } out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -290,9 +290,9 @@ static ssize_t pio_read(struct file *filp, struct kobject *kobj, if (off != 0 || count != 1 || buf == NULL) return -EINVAL; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); ret = w1_f1C_read(sl, W1_1C_REG_LOGIC_STATE, count, buf); - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return ret; } @@ -310,11 +310,11 @@ static ssize_t pio_write(struct file *filp, struct kobject *kobj, if (off != 0 || count != 1 || buf == NULL) return -EINVAL; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* Write the PIO data */ if (w1_reset_select_slave(sl)) { - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return -1; } @@ -328,7 +328,7 @@ static ssize_t pio_write(struct file *filp, struct kobject *kobj, w1_read_block(sl->master, &ack, sizeof(ack)); - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); /* check for acknowledgement */ if (ack != 0xAA) From a2e52ccce044e13d2695bb1bbdc07942727f28dd Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:04:38 +0100 Subject: [PATCH 0237/2102] w1: ds2805: use the bus mutex to talk on the bus Since commit b02f8bede217 ("W1: split master mutex to avoid deadlocks.") the slave drivers serialise their accesses to the bus with bus_mutex. This driver takes the mutex of the master in the callbacks of its eeprom file instead. That mutex is held while a slave which has disappeared from the bus is removed, which waits for the sysfs callbacks of the slave to return. A callback which is waiting for the mutex at that moment never does: both tasks are stuck, and with them the thread of the bus master. Besides, it does not keep the other slave drivers off the bus, so that two transactions can get mixed up on the wire. Fixes: f6887531c0c6 ("drivers: w1: Add 1w slave driver for DS28E05 EEPROM") Cc: stable Signed-off-by: Josef Bacik Reviewed-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261027-llm-char-misc-w1-v1-5-d2e6bfafb6a4@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/w1/slaves/w1_ds2805.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/w1/slaves/w1_ds2805.c b/drivers/w1/slaves/w1_ds2805.c index 9c86b7985d0bd6..bfcc02ecbdb9b7 100644 --- a/drivers/w1/slaves/w1_ds2805.c +++ b/drivers/w1/slaves/w1_ds2805.c @@ -102,7 +102,7 @@ static ssize_t w1_f0d_read_bin(struct file *filp, struct kobject *kobj, if (count == 0) return 0; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* read directly from the EEPROM in chunks of W1_F0D_READ_MAXLEN */ while (todo > 0) { @@ -123,7 +123,7 @@ static ssize_t w1_f0d_read_bin(struct file *filp, struct kobject *kobj, off += W1_F0D_READ_MAXLEN; } - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -211,7 +211,7 @@ static ssize_t w1_f0d_write_bin(struct file *filp, struct kobject *kobj, if (count == 0) return 0; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* Can only write data in blocks of the size of the scratchpad */ addr = off; @@ -256,7 +256,7 @@ static ssize_t w1_f0d_write_bin(struct file *filp, struct kobject *kobj, } out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } From 847fa880a3e1b2fdbbf72d89e830566108457637 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:04:39 +0100 Subject: [PATCH 0238/2102] w1: netlink: drop the slave after the bus is unlocked w1_process_cb() executes the commands of a netlink message with bus_mutex held, and drops the reference to the slave which the message was addressed to before it unlocks the mutex. If the slave has been detached in the meantime, this is the last reference, and w1_unref_slave() tears the slave down on the spot. That waits - in device_unregister(), for the sysfs callbacks of the slave which are running, and - in w1_therm_remove_slave(), for the readers which have taken a reference to the family data, and both kinds take bus_mutex to talk to the slave. Whoever is waiting for the mutex at that moment is never going to finish, and neither is the thread of the bus master. Unlock the bus first. The reference keeps the slave, and with it the master, alive until then. Fixes: d3a8a9dbb903 ("w1: hold bus_mutex in netlink and search") Cc: stable Signed-off-by: Josef Bacik Reviewed-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261027-llm-char-misc-w1-v1-6-d2e6bfafb6a4@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/w1/w1_netlink.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/drivers/w1/w1_netlink.c b/drivers/w1/w1_netlink.c index e6b59d92107661..40fbb96a793e99 100644 --- a/drivers/w1/w1_netlink.c +++ b/drivers/w1/w1_netlink.c @@ -478,15 +478,17 @@ static void w1_process_cb(struct w1_master *dev, struct w1_async_cmd *async_cmd) if (!cmd || err) w1_netlink_queue_status(node->block, node->msg, cmd, err); + dev->priv = NULL; + mutex_unlock(&dev->bus_mutex); + /* ref taken in w1_search_slave or w1_search_master_id when building - * the block + * the block. If it is the last one, the slave is removed, which waits + * for users of the bus. */ if (sl) w1_unref_slave(sl); else atomic_dec(&dev->refcnt); - dev->priv = NULL; - mutex_unlock(&dev->bus_mutex); mutex_lock(&dev->list_mutex); list_del(&async_cmd->async_entry); From 7ef382cb0ae0b2d6df4fbc5c822cd80394308839 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:04:40 +0100 Subject: [PATCH 0239/2102] w1: don't hold list_mutex while a slave is torn down When the last reference to a slave is dropped, w1_unref_slave() holds list_mutex of the master until the slave has been freed. In between it calls the ->remove_slave() callback of the family driver and device_unregister(). Both wait for others: for the sysfs callbacks which are running, and in the case of w1_therm also for the file therm_bulk_read of the master and for everybody who is talking to the sensor. None of those can therefore take list_mutex, although the callbacks of therm_bulk_read walk the list which it protects. The mutex is only needed to make the decrement of the reference count and the removal from the list one step for w1_search_slave() and w1_slave_search_device(), which look the slave up in the list and, in the first case, take a reference. Once the slave is off the list, nobody can find it any more. Drop the mutex at that point. The callers which hold the mutex of the master, which serialises attaching and detaching, are not affected. The one which does not is w1_process_cb(), when it drops the last reference to a slave which has been detached while a netlink command for it was queued. Somebody who attaches a slave with the same ID through sysfs or netlink at that very moment used to wait until the old device was gone. Now the registration of the new device may fail because the name is still in use. This is a preparation for "w1: w1_therm: lock the list of slaves for the bulk read". Cc: stable Signed-off-by: Josef Bacik Reviewed-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261027-llm-char-misc-w1-v1-7-d2e6bfafb6a4@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/w1/w1.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/drivers/w1/w1.c b/drivers/w1/w1.c index fe7b73d2a5536b..4eb785c643c928 100644 --- a/drivers/w1/w1.c +++ b/drivers/w1/w1.c @@ -781,16 +781,24 @@ int w1_unref_slave(struct w1_slave *sl) { struct w1_master *dev = sl->master; int refcnt; + + /* + * Once it is off the list nobody can find the slave and take a new + * reference. The lock must not be held any longer than that: the rest + * waits for sysfs callbacks and for users of the family data. + */ mutex_lock(&dev->list_mutex); refcnt = atomic_sub_return(1, &sl->refcnt); + if (refcnt == 0) + list_del(&sl->w1_slave_entry); + mutex_unlock(&dev->list_mutex); + if (refcnt == 0) { struct w1_netlink_msg msg; dev_dbg(&sl->dev, "%s: detaching %s [%p].\n", __func__, sl->name, sl); - list_del(&sl->w1_slave_entry); - memset(&msg, 0, sizeof(msg)); memcpy(msg.id.id, &sl->reg_num, sizeof(msg.id)); msg.type = W1_SLAVE_REMOVE; @@ -804,7 +812,6 @@ int w1_unref_slave(struct w1_slave *sl) kfree(sl); } atomic_dec(&dev->refcnt); - mutex_unlock(&dev->list_mutex); return refcnt; } From 1e46334d38e0217f5d255dc6fd63243593052f8e Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:04:41 +0100 Subject: [PATCH 0240/2102] w1: w1_therm: lock the list of slaves for the bulk read The callbacks of the file therm_bulk_read walk the list of the slaves of the master, trigger_bulk_read() three times and therm_bulk_read_show() once, without the list_mutex which protects it. In the meantime the thread of the master may find out that a sensor has gone: write to therm_bulk_read w1_process() trigger_bulk_read() w1_slave_detach() list_for_each_entry(sl, ...) w1_unref_slave() bulk_read_slave(sl) list_del() w1_therm_remove_slave() kfree(sl->family_data) kfree(sl) SLAVE_CONVERT_TRIGGERED(sl) = 1 The walk reads, and writes to, memory which has been freed, and follows the poisoned list pointers. Take list_mutex around each of the four walks. No pointer to a slave is kept from one walk to the next. This could not be done as long as w1_unref_slave() held the mutex while it waited, in w1_therm_remove_slave(), for these very callbacks and for the readers of the sensor, who need the bus_mutex which trigger_bulk_read() holds around its second walk. Now nothing is waited for with list_mutex held, and none of the other mutexes of the subsystem is taken under it, so it can be nested inside bus_mutex. Fixes: 57c76221d5af ("w1_therm: adding bulk read support to trigger multiple conversion on bus") Cc: stable Signed-off-by: Josef Bacik Reviewed-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261027-llm-char-misc-w1-v1-8-d2e6bfafb6a4@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/w1/slaves/w1_therm.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/w1/slaves/w1_therm.c b/drivers/w1/slaves/w1_therm.c index d96b224e221503..6db0b534b3383c 100644 --- a/drivers/w1/slaves/w1_therm.c +++ b/drivers/w1/slaves/w1_therm.c @@ -1495,6 +1495,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) * and compute duration of conversion for these devices * so we can apply a strong pullup if required */ + mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { if (!sl->family_data) goto error; @@ -1508,6 +1509,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) w1_strong_pullup)); } } + mutex_unlock(&dev_master->list_mutex); /* * t_conv is the max conversion time required on the bus @@ -1534,11 +1536,13 @@ static int trigger_bulk_read(struct w1_master *dev_master) w1_write_8(dev_master, W1_CONVERT_TEMP); /* set a flag to instruct that converT pending */ + mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { if (bulk_read_support(sl)) SLAVE_CONVERT_TRIGGERED(sl) = -1; } + mutex_unlock(&dev_master->list_mutex); if (strong_pullup) { /* some device need pullup */ sleep_rem = msleep_interruptible(t_conv); @@ -1564,10 +1568,12 @@ static int trigger_bulk_read(struct w1_master *dev_master) mutex_unlock(&dev_master->bus_mutex); set_flag: /* set a flag to register convsersion is done */ + mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { if (bulk_read_support(sl)) SLAVE_CONVERT_TRIGGERED(sl) = 1; } + mutex_unlock(&dev_master->list_mutex); error: return ret; } @@ -1932,6 +1938,7 @@ static ssize_t therm_bulk_read_show(struct device *device, struct w1_slave *sl = NULL; int ret = 0; + mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { if (sl->family_data) { if (bulk_read_support(sl)) { @@ -1946,6 +1953,7 @@ static ssize_t therm_bulk_read_show(struct device *device, } } show_result: + mutex_unlock(&dev_master->list_mutex); return sprintf(buf, "%d\n", ret); } From c0eadd2e06e52563cae2b80491e56eb9712eb727 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:04:42 +0100 Subject: [PATCH 0241/2102] w1: w1_therm: leave the slaves of other families alone The file therm_bulk_read belongs to the bus master. Its callbacks walk all the slaves of the bus and look at sl->family_data as if every slave were a temperature sensor. A 1-wire bus can carry other devices too: - The family data of a slave which is driven by another driver, such as w1_ds2433, w1_ds250x, w1_ds28e04 or w1_ds28e17, is a structure of that driver. bulk_read_support() takes whatever is at the offset of specific_functions for a pointer and dereferences it, and if the result happens not to be 0, the callbacks write the state of the conversion into that foreign structure. - For a slave without family data, which is the case for most of the other drivers and for the default family, trigger_bulk_read() gives up with -ENODEV. A single serial number chip on the bus is enough to make the bulk read unusable for all the sensors. Only look at the slaves whose family is one of ours. A bulk conversion now works on a bus with other devices. Fixes: 57c76221d5af ("w1_therm: adding bulk read support to trigger multiple conversion on bus") Cc: stable Signed-off-by: Josef Bacik Reviewed-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261027-llm-char-misc-w1-v1-9-d2e6bfafb6a4@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/w1/slaves/w1_therm.c | 37 ++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/drivers/w1/slaves/w1_therm.c b/drivers/w1/slaves/w1_therm.c index 6db0b534b3383c..d8751b29f4205a 100644 --- a/drivers/w1/slaves/w1_therm.c +++ b/drivers/w1/slaves/w1_therm.c @@ -906,6 +906,19 @@ static inline bool bulk_read_support(struct w1_slave *sl) return false; /* No device family */ } +/** + * bulk_read_slave() - check if a slave of the bus takes part in a bulk read + * @sl: any slave on the list of the master + * + * The family data of the slaves of other families is none of our business. + * + * Return: true if it is one of our devices and supports bulk read + */ +static bool bulk_read_slave(struct w1_slave *sl) +{ + return device_family(sl) && sl->family_data && bulk_read_support(sl); +} + /** * conversion_time() - get the Tconv for the slave * @sl: device to get the conversion time @@ -1497,9 +1510,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) */ mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (!sl->family_data) - goto error; - if (bulk_read_support(sl)) { + if (bulk_read_slave(sl)) { int t_cur = conversion_time(sl); t_conv = max(t_cur, t_conv); @@ -1539,7 +1550,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (bulk_read_support(sl)) + if (bulk_read_slave(sl)) SLAVE_CONVERT_TRIGGERED(sl) = -1; } mutex_unlock(&dev_master->list_mutex); @@ -1570,7 +1581,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) /* set a flag to register convsersion is done */ mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (bulk_read_support(sl)) + if (bulk_read_slave(sl)) SLAVE_CONVERT_TRIGGERED(sl) = 1; } mutex_unlock(&dev_master->list_mutex); @@ -1940,16 +1951,14 @@ static ssize_t therm_bulk_read_show(struct device *device, mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (sl->family_data) { - if (bulk_read_support(sl)) { - if (SLAVE_CONVERT_TRIGGERED(sl) == -1) { - ret = -1; - goto show_result; - } - if (SLAVE_CONVERT_TRIGGERED(sl) == 1) - /* continue to check other slaves */ - ret = 1; + if (bulk_read_slave(sl)) { + if (SLAVE_CONVERT_TRIGGERED(sl) == -1) { + ret = -1; + goto show_result; } + if (SLAVE_CONVERT_TRIGGERED(sl) == 1) + /* continue to check other slaves */ + ret = 1; } } show_result: From 2022f170e5655c40b93ed98629f7d0adb98cea49 Mon Sep 17 00:00:00 2001 From: Jiale Yao Date: Wed, 28 Oct 2026 12:48:24 +0800 Subject: [PATCH 0242/2102] misc: ibmvmc: initialize HMC state before device registration misc_register() exposes the IBM VMC device before the HMC state and spinlocks are initialized. A userspace operation racing module initialization can therefore access an HMC through an uninitialized spinlock. Initialize all HMC state before registering the misc device. Fixes: 0eca353e7ae7 ("misc: IBM Virtual Management Channel Driver (VMC)") Cc: stable Signed-off-by: Jiale Yao Link: https://patch.msgid.link/20261028044828.96177-5-yaojiale02@163.com Signed-off-by: Greg Kroah-Hartman --- drivers/misc/ibmvmc.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/drivers/misc/ibmvmc.c b/drivers/misc/ibmvmc.c index 6afef0788b9095..d03aeb8dea8fd4 100644 --- a/drivers/misc/ibmvmc.c +++ b/drivers/misc/ibmvmc.c @@ -2366,14 +2366,6 @@ static int __init ibmvmc_module_init(void) ibmvmc.state = ibmvmc_state_initial; pr_info("ibmvmc: version %s\n", IBMVMC_DRIVER_VERSION); - rc = misc_register(&ibmvmc_miscdev); - if (rc) { - pr_err("ibmvmc: misc registration failed\n"); - goto misc_register_failed; - } - pr_info("ibmvmc: node %d:%d\n", MISC_MAJOR, - ibmvmc_miscdev.minor); - /* Initialize data structures */ memset(hmcs, 0, sizeof(struct ibmvmc_hmc) * MAX_HMCS); for (i = 0; i < MAX_HMCS; i++) { @@ -2383,6 +2375,14 @@ static int __init ibmvmc_module_init(void) hmcs[i].queue_outbound_msgs[j] = VMC_INVALID_BUFFER_ID; } + rc = misc_register(&ibmvmc_miscdev); + if (rc) { + pr_err("ibmvmc: misc registration failed\n"); + goto misc_register_failed; + } + pr_info("ibmvmc: node %d:%d\n", MISC_MAJOR, + ibmvmc_miscdev.minor); + /* Sanity check module parms */ ibmvmc_scrub_module_parms(); From ff9de8571f05e8f62f9cbe29f38e0aedda9389cf Mon Sep 17 00:00:00 2001 From: Alice Ryhl Date: Wed, 28 Oct 2026 09:46:45 +0000 Subject: [PATCH 0243/2102] rust_binder: push BR_TRANSACTION_COMPLETE before BR_FAILED_REPLY When building a reply fails in Thread::reply_inner(), BR_FAILED_REPLY is delivered to the caller before BR_TRANSACTION_COMPLETE is pushed to the replying thread's work list. In a nested transaction, the caller can wake up upon receiving BR_FAILED_REPLY and send an outer reply to the replying thread before BR_TRANSACTION_COMPLETE is queued. This causes the outer BR_REPLY to arrive ahead of BR_TRANSACTION_COMPLETE, which is not legal. This leads to userspace tripping on an assertion. Thus, push BR_TRANSACTION_COMPLETE in Thread::reply_inner() before delivering BR_FAILED_REPLY to the caller. As a nice side effect, this lets us remove the now-unused BR_TRANSACTION_COMPLETE error path in Thread::transaction(). Cc: stable Fixes: eafedbc7c050 ("rust_binder: add Rust Binder driver") Signed-off-by: Alice Ryhl Link: https://patch.msgid.link/20261028-binder-reply-fail-v1-1-8b71d4daaf1d@google.com Signed-off-by: Greg Kroah-Hartman --- drivers/android/binder/error.rs | 1 - drivers/android/binder/thread.rs | 33 +++++++++++++------------------- 2 files changed, 13 insertions(+), 21 deletions(-) diff --git a/drivers/android/binder/error.rs b/drivers/android/binder/error.rs index 89077c5baeaf96..acf0aa09c555e5 100644 --- a/drivers/android/binder/error.rs +++ b/drivers/android/binder/error.rs @@ -114,7 +114,6 @@ impl fmt::Debug for BinderError { BR_DEAD_REPLY => f.pad("BR_DEAD_REPLY"), BR_FROZEN_REPLY => f.pad("BR_FROZEN_REPLY"), BR_TRANSACTION_PENDING_FROZEN => f.pad("BR_TRANSACTION_PENDING_FROZEN"), - BR_TRANSACTION_COMPLETE => f.pad("BR_TRANSACTION_COMPLETE"), _ => match self.source.as_ref() { Some(source) => source.fmt(f), None => self.reply.fmt(f), diff --git a/drivers/android/binder/thread.rs b/drivers/android/binder/thread.rs index f5965e838a962a..4ce6fc53320311 100644 --- a/drivers/android/binder/thread.rs +++ b/drivers/android/binder/thread.rs @@ -1332,20 +1332,16 @@ impl Thread { self.transaction_inner(&mut info) }; - // This runs when return work is passed to the caller. This is not - // always the same as the transaction failing, as reply errors are - // delivered to the remote process. + // This runs when a transaction fails with an error returned to the caller. if let Err(err) = ret { self.push_return_work(err.reply); - if err.reply != BR_TRANSACTION_COMPLETE { - info.reply = err.reply; - info.error_line = Some(err.line); - if let Some(source) = err.source { - info.errno = Some(source); - - self.inner.lock().extended_error = - ExtendedError::new(info.debug_id as u32, err.reply, source.to_errno()); - } + info.reply = err.reply; + info.error_line = Some(err.line); + if let Some(source) = err.source { + info.errno = Some(source); + + self.inner.lock().extended_error = + ExtendedError::new(info.debug_id as u32, err.reply, source.to_errno()); } } @@ -1450,7 +1446,7 @@ impl Thread { info.to_pid = orig.from.process.task.pid(); // We need to complete the transaction even if we cannot complete building the reply. - let out = (|| -> BinderResult<_> { + if let Err(err) = (|| -> BinderResult<_> { let completion = DTRWrap::arc_try_new(DeliverCode::new( BR_TRANSACTION_COMPLETE, self.process.task.pid(), @@ -1471,11 +1467,10 @@ impl Thread { } orig.from.deliver_reply(Ok(reply), &orig, None); Ok(()) - })() - .map_err(|mut err| { + })() { // At this point we only return `BR_TRANSACTION_COMPLETE` to the caller, and we must let // the sender know that the transaction has completed (with an error in this case). - + self.push_return_work(BR_TRANSACTION_COMPLETE); let param = err.source.as_ref().map_or(0, |e| e.to_errno()); let ee = ExtendedError::new(info.debug_id as u32, err.reply, param); orig.from @@ -1483,11 +1478,9 @@ impl Thread { info.reply = BR_FAILED_REPLY; info.errno = err.source; info.error_line = Some(err.line); - err.reply = BR_TRANSACTION_COMPLETE; - err - }); + } - out + Ok(()) } fn oneway_transaction_inner(self: &Arc, info: &mut TransactionInfo) -> BinderResult { From 1115120f89f5c22bf49f7423cf158a04a474dd93 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:27:40 +0100 Subject: [PATCH 0244/2102] mei: lb: read the MTU once mei_cldev_mtu() returns 0 if the client is not connected. A link reset disconnects all clients at any time, from the reset work. mei_lb_push_payload_v2() asks for the MTU to allocate the request buffer and asks again for every chunk. If the reset comes in between, chunk_size = min(payload_size - sent_data, 0 - sizeof(*req)); makes the chunk the whole rest of the payload, and the memcpy() behind it writes over the end of the buffer. If the reset comes before the first call, kzalloc(0) returns ZERO_SIZE_PTR, which passes the NULL check and is dereferenced. An MTU not bigger than the request header has the same effect as 0. Read the MTU once and refuse one which leaves no room for payload. If the client has gone, sending the chunk fails. Fixes: 773a43b8627f ("mei: lb: add late binding version 2") Cc: stable Cc: Alexander Usyskin Cc: Arnd Bergmann Signed-off-by: Josef Bacik Acked-by: Alexander Usyskin Link: https://patch.msgid.link/2026102739-boil-startup-145b@gregkh Signed-off-by: Greg Kroah-Hartman --- drivers/misc/mei/mei_lb.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/drivers/misc/mei/mei_lb.c b/drivers/misc/mei/mei_lb.c index 9fa69acf28d5b0..ffaf5be3b6059b 100644 --- a/drivers/misc/mei/mei_lb.c +++ b/drivers/misc/mei/mei_lb.c @@ -312,16 +312,24 @@ static int mei_lb_push_payload_v2(struct device *dev, struct mei_cl_device *clde size_t chunk_size; size_t req_size; ssize_t bytes; + size_t mtu; int ret; - struct mei_lb2_req *req __free(kfree) = kzalloc(mei_cldev_mtu(cldev), GFP_KERNEL); + /* The MTU turns into 0 when a link reset disconnects the client */ + mtu = mei_cldev_mtu(cldev); + if (mtu <= sizeof(struct mei_lb2_req)) { + dev_err(dev, "MTU is too small: %zu\n", mtu); + return -EMSGSIZE; + } + + struct mei_lb2_req *req __free(kfree) = kzalloc(mtu, GFP_KERNEL); if (!req) return -ENOMEM; first_chunk = MEI_LB2_FLAG_FST_CHUNK; last_chunk = 0; do { - chunk_size = min(payload_size - sent_data, mei_cldev_mtu(cldev) - sizeof(*req)); + chunk_size = min(payload_size - sent_data, mtu - sizeof(*req)); req_size = struct_size(req, payload, chunk_size); if (sent_data + chunk_size == payload_size) From 73383d06da9a1ded4c85845407cb4029aeecca39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antonio=20V=C3=A1zquez=20Blanco?= Date: Thu, 29 Oct 2026 09:48:59 +0100 Subject: [PATCH 0245/2102] mei: me: add ice lake point LP iTouch DID MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the device ID for the Intel Precise Touch & Stylus (iTouch) function on Ice Lake Point LP. It appears as PCI device 8086:34e4, next to the regular MEI function at 8086:34e0, on Microsoft Surface Pro 7 and Surface Laptop 3. Without this entry mei_me does not bind, the touch controller is unreachable, and neither the touchscreen nor the pen work. Users currently work around this by binding the device by hand at boot: echo "8086 34e4 ffffffff ffffffff 0 0 9" > \ /sys/bus/pci/drivers/mei_me/new_id where the trailing 9 is the mei_me_cfgs[] index of MEI_ME_PCH12_CFG. That is fragile by construction, since the index is positional and any reordering of the config array silently changes which config the device gets. This ID was first reported in June 2020, together with Sunrise Point's 0x9d3e, in "mei: me: Add itouch device IDs for SPT / ICP" [1]. That submission was declined over the server platform ID conflict, and the Sunrise Point half was subsequently added in commit 372a829862e5 ("mei: me: add MEI device for SPT with ITPS capability"). Ice Lake Point was never added. Use MEI_ME_PCH12_SPS_ITOUCH_CFG, so that the device is reported with the correct kind and the SPS firmware exclusion applies. Note this is not the config the manual new_id workaround above selects: it reports kind "itouch" rather than "mei", and it does not set up a DMA ring. Link: https://lore.kernel.org/all/20200601155954.764558-1-dorian.stoll@tmsp.io/ [1] Cc: stable Signed-off-by: Antonio Vázquez Blanco Acked-by: Alexander Usyskin Link: https://patch.msgid.link/20261029084859.4537-1-antoniovazquezblanco@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/misc/mei/hw-me-regs.h | 1 + drivers/misc/mei/pci-me.c | 1 + 2 files changed, 2 insertions(+) diff --git a/drivers/misc/mei/hw-me-regs.h b/drivers/misc/mei/hw-me-regs.h index b9a67629496bab..3972f9504f12f7 100644 --- a/drivers/misc/mei/hw-me-regs.h +++ b/drivers/misc/mei/hw-me-regs.h @@ -94,6 +94,7 @@ #define PCI_DEVICE_ID_INTEL_MEI_CDF 0x18D3 /* Cedar Fork */ #define PCI_DEVICE_ID_INTEL_MEI_ICP_LP 0x34E0 /* Ice Lake Point LP */ +#define PCI_DEVICE_ID_INTEL_MEI_ICP_LP_3 0x34E4 /* Ice Lake Point LP 3 (iTouch) */ #define PCI_DEVICE_ID_INTEL_MEI_ICP_N 0x38E0 /* Ice Lake Point N */ #define PCI_DEVICE_ID_INTEL_MEI_JSP_N 0x4DE0 /* Jasper Lake Point N */ diff --git a/drivers/misc/mei/pci-me.c b/drivers/misc/mei/pci-me.c index 790a4647811b70..cfdef9531ab1db 100644 --- a/drivers/misc/mei/pci-me.c +++ b/drivers/misc/mei/pci-me.c @@ -98,6 +98,7 @@ static const struct pci_device_id mei_me_pci_tbl[] = { { PCI_DEVICE_DATA(INTEL, MEI_CMP_H_3, MEI_ME_PCH8_ITOUCH_CFG) }, { PCI_DEVICE_DATA(INTEL, MEI_ICP_LP, MEI_ME_PCH12_CFG) }, + { PCI_DEVICE_DATA(INTEL, MEI_ICP_LP_3, MEI_ME_PCH12_SPS_ITOUCH_CFG) }, { PCI_DEVICE_DATA(INTEL, MEI_ICP_N, MEI_ME_PCH12_CFG) }, { PCI_DEVICE_DATA(INTEL, MEI_TGP_LP, MEI_ME_PCH15_CFG) }, From fa0858523f07f8dd71d89b221f4422c3b8096d90 Mon Sep 17 00:00:00 2001 From: Ian Abbott Date: Tue, 3 Nov 2026 17:36:10 +0000 Subject: [PATCH 0246/2102] comedi: comedi_bond: Fix leak of opened device references bonding_attach() calls do_dev_config() to open other comedi devices specified by the user and tries to make use of them as part of the 'bonding' device. If it successfully opens the other device but cannot use it (either because it does not any subdevices of a type the 'bonding' device can use, or because of some error that occurs while dealing with its subdevices) then it is left in the open state and the fact that it is open does not get recorded by the 'bonding' device, so the reference to the opened device gets lost. Fix it by closing the opened device if it could not be bound to the 'bonding' device. To match previous behavior, if the opened device is unsuitable then ignore it (after closing it). The opened devices recorded by the 'bonding' device will eventually get closed by bonding_detach() even if bonding_attach() returns an error. Fixes: 3cf840f65ad5 ("Staging: comedi: add comedi_bond driver") Cc: stable Reported-by: Wentao Liang Link: https://lore.kernel.org/lkml/20261103063301.1025860-1-vulab@iscas.ac.cn Signed-off-by: Ian Abbott Link: https://patch.msgid.link/20261103173610.89687-1-abbotti@mev.co.uk Signed-off-by: Greg Kroah-Hartman --- drivers/comedi/drivers/comedi_bond.c | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/drivers/comedi/drivers/comedi_bond.c b/drivers/comedi/drivers/comedi_bond.c index a10cfbd04c7286..3764ece90f826d 100644 --- a/drivers/comedi/drivers/comedi_bond.c +++ b/drivers/comedi/drivers/comedi_bond.c @@ -184,7 +184,9 @@ static int do_dev_config(struct comedi_device *dev, struct comedi_devconfig *it) char file[sizeof("/dev/comediXXXXXX")]; int minor = it->options[i]; struct comedi_device *d; - int sdev = -1, nchans; + int sdev = -1; + int nchans; + int nope = 1; struct bonded_device *bdev; struct bonded_device **devs; @@ -223,11 +225,14 @@ static int do_dev_config(struct comedi_device *dev, struct comedi_devconfig *it) dev_err(dev->class_dev, "comedi_get_n_channels() returned %d on minor %u subdev %d!\n", nchans, minor, sdev); - return -EINVAL; + nope = -EINVAL; + break; } bdev = kmalloc_obj(*bdev); - if (!bdev) - return -ENOMEM; + if (!bdev) { + nope = -ENOMEM; + break; + } bdev->dev = d; bdev->minor = minor; @@ -248,14 +253,23 @@ static int do_dev_config(struct comedi_device *dev, struct comedi_devconfig *it) dev_err(dev->class_dev, "Could not allocate memory. Out of memory?\n"); kfree(bdev); - return -ENOMEM; + nope = -ENOMEM; + break; } devpriv->devs = devs; devpriv->devs[devpriv->ndevs++] = bdev; + nope = 0; /* keeps the device open */ /* Append dev:subdev to devpriv->name */ seq_buf_printf(&s, "%u:%u ", bdev->minor, bdev->subdev); } + + if (nope) { + /* Opened device cannot be used, so close it. */ + comedi_close_from(d, dev->minor); + if (nope < 0) + return nope; + } } if (!devpriv->nchans) { From 90d95fbc1bcc8464f6d8c6891c62bad4c0dc2d58 Mon Sep 17 00:00:00 2001 From: Jaeyeong Lee Date: Wed, 4 Nov 2026 08:50:33 +0000 Subject: [PATCH 0247/2102] RDMA/rtrs: Register client event handler after capability check rtrs_clt_ib_dev_init() registers dev->event_handler before checking IB_DEVICE_MEM_MGT_EXTENSIONS. If the device does not provide that capability, init returns -ENOTSUPP and rtrs_ib_dev_find_or_add() frees dev through out_free_pd without calling the deinit callback. The embedded event handler therefore remains on the IB device's list after its storage has been freed. A later IB event walks the dangling list entry and accesses freed memory. The issue was found by static analysis. A focused out-of-tree test module on an x86_64 QEMU/KASAN kernel temporarily cleared only IB_DEVICE_MEM_MGT_EXTENSIONS on a SIW device, exercised the real rtrs_clt_ib_dev_init() callback through rtrs_ib_dev_find_or_add(), restored the capabilities, and dispatched IB_EVENT_DEVICE_FATAL. KASAN reported an 8-byte slab-use-after-free read in ib_dispatch_event_clients(), with both the allocation and free originating in rtrs_ib_dev_find_or_add(). Move the capability check before event handler registration. The check is a prerequisite for successful client initialization. Registration cannot fail and init returns success immediately afterwards, so every installed handler is now owned by a successfully initialized device and is removed by the existing deinit callback. Fixes: 667db86bcbe8 ("RDMA/rtrs: Register ib event handler") Cc: stable@vger.kernel.org Signed-off-by: Jaeyeong Lee Link: https://patch.msgid.link/179378222423.73361.3247716499619173751@jaeyeong.cc Acked-by: Jack Wang Signed-off-by: Leon Romanovsky --- drivers/infiniband/ulp/rtrs/rtrs-clt.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/infiniband/ulp/rtrs/rtrs-clt.c b/drivers/infiniband/ulp/rtrs/rtrs-clt.c index bf3a0377da3ff4..85eaa2bdb4704a 100644 --- a/drivers/infiniband/ulp/rtrs/rtrs-clt.c +++ b/drivers/infiniband/ulp/rtrs/rtrs-clt.c @@ -3191,16 +3191,16 @@ void rtrs_clt_ib_event_handler(struct ib_event_handler *handler, static int rtrs_clt_ib_dev_init(struct rtrs_ib_dev *dev) { - INIT_IB_EVENT_HANDLER(&dev->event_handler, dev->ib_dev, - rtrs_clt_ib_event_handler); - ib_register_event_handler(&dev->event_handler); - if (!(dev->ib_dev->attrs.device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS)) { pr_err("Memory registrations not supported.\n"); return -ENOTSUPP; } + INIT_IB_EVENT_HANDLER(&dev->event_handler, dev->ib_dev, + rtrs_clt_ib_event_handler); + ib_register_event_handler(&dev->event_handler); + return 0; } From b8320a8b5650096873ae8c0377b8fa1226b15fe0 Mon Sep 17 00:00:00 2001 From: Jacob Riff Date: Fri, 30 Oct 2026 20:24:00 -0700 Subject: [PATCH 0248/2102] usb: typec: ucsi: retry init only while the PPM is not ready Commit 254261381538 ("usb: typec: ucsi: retry init when the PPM answers early commands incorrectly") makes ucsi_init_work() retry ucsi_init() on -ENODEV and -EINVAL, a hundred times over ten seconds, to cover a PPM that is not ready to answer commands correctly for a short window during boot. It catches more than that. ucsi_register_port() also fails with -ENODEV when no USB role switch is available, and logs that at error level, so every retry runs it again and logs it again. Where a machine without a usable role switch used to log ucsi_acpi USBC000:00: error -ENODEV: con1: failed to get usb role switch ucsi_acpi USBC000:00: error -ENODEV: PPM init failed it now logs a hundred and one copies of the first line, followed by "PPM init failed, stop trying", on every boot, and the retries can never succeed there. Have ucsi_init() report the two not-ready cases as -EAGAIN instead: GET_CAPABILITY reporting zero connectors, and the PPM rejecting a standard command (-EINVAL from ucsi_read_error(), the only -EINVAL expected once the PPM reset has succeeded). Retry only -EAGAIN and, as before that commit, -EPROBE_DEFER. Every other error is reported once and init stops, as it did before. Also give -EAGAIN its own budget. The hundred retries over ten seconds belong to the USB role switch wait. On the machine the retry was written for, every observed failure recovered on the first or second retry, so ten retries over one second is plenty. A PPM that permanently rejects a command now logs "possible UCSI driver bug" up to eleven times in that second, on hardware where init already failed before. Fixes: 254261381538 ("usb: typec: ucsi: retry init when the PPM answers early commands incorrectly") Reported-by: Linus Torvalds Closes: https://lore.kernel.org/r/CAHk-=wjGk9rBTphk1OAwcqGAE1__KJgMr3B-8X4hKFPX8Wm=BQ@mail.gmail.com Signed-off-by: Jacob Riff Link: https://patch.msgid.link/20261031032400.38349-1-jacob@riff.dk Signed-off-by: Greg Kroah-Hartman --- drivers/usb/typec/ucsi/ucsi.c | 37 +++++++++++++++++++++++++---------- drivers/usb/typec/ucsi/ucsi.h | 1 + 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/drivers/usb/typec/ucsi/ucsi.c b/drivers/usb/typec/ucsi/ucsi.c index 2f9adf4f8bdebd..9e453d216c169b 100644 --- a/drivers/usb/typec/ucsi/ucsi.c +++ b/drivers/usb/typec/ucsi/ucsi.c @@ -2106,7 +2106,7 @@ static int ucsi_init(struct ucsi *ucsi) goto err_reset; if (!ucsi->cap.num_connectors) { - ret = -ENODEV; + ret = -EAGAIN; goto err_reset; } /* Check if reserved bit set. This is out of spec but happens in buggy FW */ @@ -2172,6 +2172,16 @@ static int ucsi_init(struct ucsi *ucsi) err_reset: memset(&ucsi->cap, 0, sizeof(ucsi->cap)); ucsi_reset_ppm(ucsi); + + /* + * The only -EINVAL expected on this path is ucsi_read_error()'s: + * the PPM rejected a standard command. Some PPMs do that, or + * report zero connectors above, for a short while after boot + * before they are ready. Report both as -EAGAIN so that + * ucsi_init_work() can retry them, and only them. + */ + if (ret == -EINVAL) + ret = -EAGAIN; err: return ret; } @@ -2249,16 +2259,23 @@ static void ucsi_init_work(struct work_struct *work) } /* - * On some platforms the PPM is not ready to answer commands - * correctly for a short window during boot: standard commands are - * rejected or GET_CAPABILITY reports zero connectors, seen as - * -EINVAL or -ENODEV from ucsi_init(), and a retry moments later - * succeeds (observed on Lenovo ThinkPad X1 Carbon Gen 14, where - * this affects roughly half of all boots). Retry those like the - * USB role switch wait instead of giving up on the first attempt. + * -EPROBE_DEFER: the USB role switch is not registered yet. Wait + * up to ten seconds for it. + * + * -EAGAIN: the PPM is not ready to answer commands correctly yet. + * On some platforms that lasts for a short window during boot + * (observed on Lenovo ThinkPad X1 Carbon Gen 14, where it affects + * roughly half of all boots and a retry moments later succeeds). + * One second is plenty for that. + * + * Anything else is not going to change with a retry, so report it + * once and stop. */ - if (ret == -EPROBE_DEFER || ret == -ENODEV || ret == -EINVAL) { - if (ucsi->work_count++ < UCSI_ROLE_SWITCH_WAIT_COUNT) { + if (ret == -EPROBE_DEFER || ret == -EAGAIN) { + int limit = ret == -EPROBE_DEFER ? UCSI_ROLE_SWITCH_WAIT_COUNT : + UCSI_PPM_READY_WAIT_COUNT; + + if (ucsi->work_count++ < limit) { dev_dbg(ucsi->dev, "PPM init failed (%pe), retrying\n", ERR_PTR(ret)); queue_delayed_work(system_dfl_long_wq, &ucsi->work, diff --git a/drivers/usb/typec/ucsi/ucsi.h b/drivers/usb/typec/ucsi/ucsi.h index 1996f04ed5e68d..140d34e90c7c4c 100644 --- a/drivers/usb/typec/ucsi/ucsi.h +++ b/drivers/usb/typec/ucsi/ucsi.h @@ -491,6 +491,7 @@ struct ucsi { #define UCSI_ROLE_SWITCH_RETRY_PER_HZ 10 #define UCSI_ROLE_SWITCH_INTERVAL (HZ / UCSI_ROLE_SWITCH_RETRY_PER_HZ) #define UCSI_ROLE_SWITCH_WAIT_COUNT (10 * UCSI_ROLE_SWITCH_RETRY_PER_HZ) +#define UCSI_PPM_READY_WAIT_COUNT (1 * UCSI_ROLE_SWITCH_RETRY_PER_HZ) /* PPM Communication lock */ struct mutex ppm_lock; From b889ea1f6dbeab953a3b1e752cc1d4fda2c46927 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Mon, 2 Nov 2026 07:20:58 +0000 Subject: [PATCH 0249/2102] bpf, sockmap: Write sg.start when recvmsg() faults __sk_msg_recvmsg() copies an sk_msg to the user buffer and starts at sg.start. After a full copy of an element it calls put_page(), unless an skb owns the page. It handles 0 copied bytes as a fault. It writes the new sg.start after the loop, but not when copy_page_to_iter() faults. element 0: length 0, put_page() 1: fault here 2: not copied sg.start ^ today ^ this patch Each subsequent call copies 0 bytes from element 0 and returns -EFAULT. The user cannot read the rest of the data. sk_msg_free() starts at sg.start too. It calls put_page() for element 0 again and can free a page in use. Write sg.start in the fault path too. The commit in the Fixes tag removed this write. Do not write it for MSG_PEEK, which changes no element. Fixes: c9c89dcd872e ("bpf, sockmap: Fix partial copy_page_to_iter so progress can still be made") Signed-off-by: Josef Bacik Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Link: https://patch.msgid.link/20261102072112.4160195-2-alexei.starovoitov@gmail.com --- net/core/skmsg.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/net/core/skmsg.c b/net/core/skmsg.c index df385a5a961e83..f03519468ad106 100644 --- a/net/core/skmsg.c +++ b/net/core/skmsg.c @@ -443,6 +443,9 @@ int __sk_msg_recvmsg(struct sock *sk, struct sk_psock *psock, struct msghdr *msg if (copy) copy = copy_page_to_iter(page, sge->offset, copy, iter); if (!copy) { + /* The elements in front of i are used up */ + if (!peek) + msg_rx->sg.start = i; copied = copied ? copied : -EFAULT; goto out; } From 436c4cfa071e1b48aae94dcd73b69ef6fca2eba3 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Mon, 2 Nov 2026 07:20:59 +0000 Subject: [PATCH 0250/2102] bpf, sockmap: Don't let an SK_DROP verdict stick The verdict of an sk_msg prog is valid for one message, or for the bytes that bpf_msg_apply_bytes() requests. These bytes can come from many sendmsg() calls. Thus tcp_bpf_send_verdict() keeps the verdict in psock->eval and runs the prog only when psock->eval is __SK_NONE. The code that resets psock->eval is after the switch statement, but the __SK_DROP branch returns before that code. Then sendmsg() drops all subsequent messages with -EACCES and does not run the prog. Reset psock->eval when apply_bytes is 0, as the __SK_REDIRECT branch does. Fixes: 4f738adba30a ("bpf: create tcp_bpf_ulp allowing BPF to monitor socket TX/RX data") Signed-off-by: Josef Bacik Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Reviewed-by: John Fastabend Link: https://patch.msgid.link/20261102072112.4160195-3-alexei.starovoitov@gmail.com --- net/ipv4/tcp_bpf.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index 8cf63a9e7fed15..d90bcc911b36b9 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -509,6 +509,9 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, default: sk_msg_free(sk, msg); sk_msg_apply_bytes(psock, tosend); + /* The verdict holds for apply_bytes, not for ever */ + if (!psock->apply_bytes) + psock->eval = __SK_NONE; *copied -= (tosend + delta); return -EACCES; } From f4c044966d6c896c46ea0fd929df3b7c06529ef8 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Mon, 2 Nov 2026 07:21:00 +0000 Subject: [PATCH 0251/2102] bpf, sockmap: Don't let an SK_PASS verdict cover the next message tcp_bpf_send_verdict() keeps the verdict of the sk_msg prog in psock->eval and runs the prog only when eval is __SK_NONE. For __SK_PASS it resets eval only after tcp_bpf_push() returns 0. But the push can release the socket lock in sk_stream_wait_memory(), and it can fail. Then another tcp_bpf_sendmsg() sends its message and does not run the prog. With bpf_msg_apply_bytes() the verdict covers apply_bytes bytes. After a failed push, apply_bytes still includes the sent bytes. Thus the verdict covers more bytes than the prog requested. Reset eval before the push when apply_bytes is 0. If this push fails, the prog now runs for the rest of the message. The same already occurs when a message does not fit into one sk_msg. When the push fails, subtract the sent bytes from apply_bytes. When apply_bytes is not 0, eval stays __SK_PASS during the push, and the prog does not run for another message, as today. The verdict must still cover the bytes that a failed push does not send. But such a message also lowers apply_bytes. Thus, if apply_bytes is 0 after the subtraction, end the verdict, as after a push that returns 0. Fixes: 4f738adba30a ("bpf: create tcp_bpf_ulp allowing BPF to monitor socket TX/RX data") Signed-off-by: Alexei Starovoitov Reviewed-by: John Fastabend Link: https://patch.msgid.link/20261102072112.4160195-4-alexei.starovoitov@gmail.com --- net/ipv4/tcp_bpf.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index d90bcc911b36b9..b016aa419fb2d0 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -457,8 +457,22 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, switch (psock->eval) { case __SK_PASS: + /* The push may sleep without the socket lock, and it may fail */ + if (!psock->apply_bytes) + psock->eval = __SK_NONE; + origsize = msg->sg.size; ret = tcp_bpf_push(sk, msg, tosend, flags, true); if (unlikely(ret)) { + /* A part of it may have gone out */ + sk_msg_apply_bytes(psock, origsize - msg->sg.size); + /* Another sender can use up the rest during the push */ + if (!psock->apply_bytes) { + psock->eval = __SK_NONE; + if (psock->sk_redir) { + sock_put(psock->sk_redir); + psock->sk_redir = NULL; + } + } *copied -= sk_msg_free(sk, msg); break; } From fa84be67b5bc2999c6962e18c5deee2e90483bfb Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Mon, 2 Nov 2026 07:21:01 +0000 Subject: [PATCH 0252/2102] bpf, sockmap: Subtract all dropped bytes from the return value When an sk_msg prog returns SK_DROP, tcp_bpf_send_verdict() frees the full message. It then subtracts tosend bytes from *copied, the return value of sendmsg(). But tosend is the number of bytes that the verdict applies to. After bpf_msg_apply_bytes() tosend can be less than the message size. Then sendmsg() reports dropped bytes as sent. Subtract the number of bytes that sk_msg_free() frees. After an error the SK_PASS branch already does this. The SK_REDIRECT branch does the same if the message is not the cork. Nothing changes when tosend is equal to the message size. Otherwise sendmsg() now returns -EACCES if it sends nothing. Fixes: ca70b8baf2bd ("tcp_bpf: Fix the sk_mem_uncharge logic in tcp_bpf_sendmsg") Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Reviewed-by: John Fastabend Link: https://patch.msgid.link/20261102072112.4160195-5-alexei.starovoitov@gmail.com --- net/ipv4/tcp_bpf.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index b016aa419fb2d0..36d1bf46353a9c 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -521,12 +521,12 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, break; case __SK_DROP: default: - sk_msg_free(sk, msg); + /* All of it is thrown away, not only tosend bytes */ + *copied -= sk_msg_free(sk, msg) + delta; sk_msg_apply_bytes(psock, tosend); /* The verdict holds for apply_bytes, not for ever */ if (!psock->apply_bytes) psock->eval = __SK_NONE; - *copied -= (tosend + delta); return -EACCES; } From 51e0f3d60be57379329b4933a1d63bbdbeb8b99e Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Mon, 2 Nov 2026 07:21:02 +0000 Subject: [PATCH 0253/2102] bpf, sockmap: Clear the resume state of a stopped psock sk_psock_backlog() passes the skbs of psock->ingress_skb to the socket of the psock. When the socket has no room, the function saves the length and offset of the remaining data in psock->work_state. A later run continues at this offset and clears the state when the skb is complete. sk_psock_skb_state() saves and clears the state, but only while SK_PSOCK_TX_ENABLED is set. sk_psock_backlog() does not test this flag for each skb. If the socket closes during the loop, sk_psock_stop() clears the flag. The loop continues, but the state of the completed skb stays. The loop uses this state for all subsequent skbs and sends only part of their data. A closing socket may lose the end of a stream, but not the middle. The state belongs to the skb at the head of ingress_skb. Always clear the state when this skb is complete. A stopped psock still saves no new state. Fixes: 3b4f14b79428 ("bpf, sockmap: fix duplicated data transmission") Signed-off-by: Josef Bacik Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Reviewed-by: John Fastabend Link: https://patch.msgid.link/20261102072112.4160195-6-alexei.starovoitov@gmail.com --- net/core/skmsg.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/net/core/skmsg.c b/net/core/skmsg.c index f03519468ad106..a5d498982848f9 100644 --- a/net/core/skmsg.c +++ b/net/core/skmsg.c @@ -664,7 +664,8 @@ static void sk_psock_skb_state(struct sk_psock *psock, int len, int off) { spin_lock_bh(&psock->ingress_lock); - if (sk_psock_test_state(psock, SK_PSOCK_TX_ENABLED)) { + /* No new state once the psock is stopped, but never keep an old one */ + if (!len || sk_psock_test_state(psock, SK_PSOCK_TX_ENABLED)) { state->len = len; state->off = off; } From 7c036a39ba293186832436f2e6d2798f397f6fa7 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Mon, 2 Nov 2026 07:21:03 +0000 Subject: [PATCH 0254/2102] bpf, sockmap: Give no progs to a TCP listener A psock with a verdict prog replaces sk_data_ready and sk_write_space of its socket. It saves the old callbacks, and the new callbacks call them. sock_map_link() does this to a TCP listener too. Its new sk_data_ready cannot read and does not call the old one. Thus it does not wake accept(). sk_clone() copies the new callbacks to each child, but not the psock. tcp_bpf_clone() restores only sk_prot. Without a psock the child loses data or does not wake its reader. If it gets a psock, the psock saves the copies as the old callbacks. Then sk_psock_verdict_data_ready() calls itself until the stack overflows. sk_psock_write_space() calls itself too, without end. Give no progs to a TCP listener, as before the first commit below. A listener receives and sends no data. It stays in the map and keeps its own callbacks. Add this exception to map_sockmap.rst. A listener no longer gets -EBUSY from a second map with progs of the same kind. Since the second commit below, a socket keeps its psock when TCP unhashes it. sock_map_link() does not see the state that the socket gets later. Do not depend on TCP to keep such a socket out of TCP_LISTEN. Set both callbacks in tcp_bpf_clone() to the TCP defaults. Fixes: 0c48eefae712 ("sock_map: Lift socket state restriction for datagram sockets") Fixes: b8b8315e39ff ("bpf, sockmap: Remove unhash handler for BPF sockmap usage") Signed-off-by: Chris Mason Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Reviewed-by: John Fastabend Link: https://patch.msgid.link/20261102072112.4160195-7-alexei.starovoitov@gmail.com --- Documentation/bpf/map_sockmap.rst | 4 +++- net/core/sock_map.c | 9 +++++++++ net/ipv4/tcp_bpf.c | 15 +++++++++++++-- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/Documentation/bpf/map_sockmap.rst b/Documentation/bpf/map_sockmap.rst index 2d630686a00baa..eb466b86df1707 100644 --- a/Documentation/bpf/map_sockmap.rst +++ b/Documentation/bpf/map_sockmap.rst @@ -33,7 +33,9 @@ of ``__SK_DROP``, ``__SK_PASS``, or ``__SK_REDIRECT``. When a socket is inserted into one of these maps, its socket callbacks are replaced and a ``struct sk_psock`` is attached to it. Additionally, this -``sk_psock`` inherits the programs that are attached to the map. +``sk_psock`` inherits the programs that are attached to the map. A TCP listener +is an exception. It gets a ``struct sk_psock``, but it keeps its callbacks and +inherits no programs. A sock object may be in multiple maps, but can only inherit a single parse or verdict program. If adding a sock object to a map would result diff --git a/net/core/sock_map.c b/net/core/sock_map.c index efe49551caba9e..282c6a4b2b05fe 100644 --- a/net/core/sock_map.c +++ b/net/core/sock_map.c @@ -228,6 +228,14 @@ static int sock_map_link(struct bpf_map *map, struct sock *sk) struct sk_psock *psock; int ret; + /* + * A listener receives no data. With the callbacks of a verdict program + * or a parser it would no longer wake accept(), and its children would + * copy them. + */ + if (sk_is_tcp(sk) && sk->sk_state == TCP_LISTEN) + goto no_progs; + stream_verdict = READ_ONCE(progs->stream_verdict); if (stream_verdict) { stream_verdict = bpf_prog_inc_not_zero(stream_verdict); @@ -262,6 +270,7 @@ static int sock_map_link(struct bpf_map *map, struct sock *sk) } } +no_progs: psock = sock_map_psock_get_checked(sk); if (IS_ERR(psock)) { ret = PTR_ERR(psock); diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index 36d1bf46353a9c..fd443350f9b81a 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -785,7 +785,18 @@ void tcp_bpf_clone(const struct sock *sk, struct sock *newsk) { struct proto *prot = newsk->sk_prot; - if (is_insidevar(prot, tcp_bpf_prots)) - newsk->sk_prot = sk->sk_prot_creator; + if (!is_insidevar(prot, tcp_bpf_prots)) + return; + + newsk->sk_prot = sk->sk_prot_creator; + /* + * sock_map_link() gives a listener no programs, but a socket which got + * them in another state and listens now has the psock's sk_data_ready + * and sk_write_space, and sock_copy() has copied them. + * sk_psock_init() refuses a socket that has sk_user_data or a ULP, so + * what the psock replaced were the defaults of a TCP socket. + */ + newsk->sk_data_ready = sock_def_readable; + newsk->sk_write_space = sk_stream_write_space; } #endif /* CONFIG_BPF_SYSCALL */ From 4aeaad1c536ef640539aaafe728a8a4b096603f4 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Mon, 2 Nov 2026 07:21:04 +0000 Subject: [PATCH 0255/2102] bpf, sockmap: Check the target of an egress redirect before each send tcp_sendmsg_locked() expects a caller that has the socket open. It uses sk->sk_socket and the wait queue sk->sk_wq. For an egress redirect of an sk_msg prog the sender calls it on the target without a reference to the target's file. Both pointers are NULL before accept() and after close(). close() can occur while the sender sleeps. Then the kernel crashes. Fail the redirect when the target has no struct socket, or when the sender has to wait for the connection. The error is EINVAL. After close() it is EPIPE, as today. sk_stream_wait_connect() calls remove_wait_queue() without a test of SOCK_DEAD. sk_stream_wait_memory() has this test, but it can still use sk_wq after the sleep. This patch does not change that. The target can change while the sender sleeps there. Thus do both checks before each call of tcp_sendmsg_locked(). Clear MSG_FASTOPEN, so that the sender does not call the connect code of the target, which uses both pointers. Today the sender can send before accept() and waits in SYN_SENT. send() with MSG_FASTOPEN sends the data. Today it fails with EISCONN. When the redirect of a cork fails, send() returns success and the kernel drops the data, as today. The Fixes tags are for the two checks and for MSG_FASTOPEN, in this order. Fixes: 4f738adba30a ("bpf: create tcp_bpf_ulp allowing BPF to monitor socket TX/RX data") Fixes: b8b8315e39ff ("bpf, sockmap: Remove unhash handler for BPF sockmap usage") Fixes: c5c37af6ecad ("tcp: Convert do_tcp_sendpages() to use MSG_SPLICE_PAGES") Signed-off-by: Chris Mason Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Reviewed-by: John Fastabend Link: https://patch.msgid.link/20261102072112.4160195-8-alexei.starovoitov@gmail.com --- net/ipv4/tcp_bpf.c | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index fd443350f9b81a..ef2e15de0fe3b3 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -88,6 +88,24 @@ static int bpf_tcp_ingress(struct sock *sk, struct sk_psock *psock, return ret; } +/* + * The target of a redirect belongs to somebody else. A child that nobody has + * accepted yet, and an orphan, have no struct socket and no wait queue. + * tcp_sendmsg_locked() needs both. See sendmsg_locked() in skbuff.c. + * The sender holds no reference to the file of the target, which can be closed + * whenever tcp_sendmsg_locked() sleeps. sk_stream_wait_connect() and + * inet_wait_for_connect() go back to the wait queue when they wake up, so the + * sender must not wait for a connect. + */ +static bool tcp_bpf_redir_allowed(const struct sock *sk) +{ + if (!sk->sk_socket) + return false; + if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) + return tcp_passive_fastopen(sk); + return true; +} + static int tcp_bpf_push(struct sock *sk, struct sk_msg *msg, u32 apply_bytes, int flags, bool uncharge) { @@ -109,6 +127,10 @@ static int tcp_bpf_push(struct sock *sk, struct sk_msg *msg, u32 apply_bytes, page = sg_page(sge); retry: + /* Only a redirect sends data which is not charged to sk */ + if (!uncharge && unlikely(!tcp_bpf_redir_allowed(sk))) + return sock_flag(sk, SOCK_DEAD) ? -EPIPE : -EINVAL; + msghdr.msg_flags = flags | MSG_SPLICE_PAGES; has_tx_ulp = tls_sw_has_ctx_tx(sk); if (has_tx_ulp) @@ -555,7 +577,7 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size) int flags; /* Don't let internal flags through */ - flags = (msg->msg_flags & ~MSG_SENDPAGE_DECRYPTED); + flags = (msg->msg_flags & ~(MSG_SENDPAGE_DECRYPTED | MSG_FASTOPEN)); flags |= MSG_NO_SHARED_FRAGS; psock = sk_psock_get(sk); From 430775a30b1f2d3998d2201b74be0e8e502dedbf Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Mon, 2 Nov 2026 07:21:05 +0000 Subject: [PATCH 0256/2102] net: Leave sk_stream_wait_memory() once the socket is dead When an sk_msg prog redirects data to the egress of another socket, the sender calls tcp_sendmsg_locked() on that socket. The sender holds a reference to the sock, but not to its file. Thus __tcp_close() can call sock_orphan() while the sender sleeps in sk_stream_wait_memory(). sock_orphan() sets SOCK_DEAD and sets sk_wq to NULL. After the sleep the loop continues and does not test SOCK_DEAD. The subsequent sk_set_bit() can dereference the NULL sk_wq. The tests of sk_err and sk_shutdown do not always stop the sender. sock_error() clears sk_err, and __tcp_close() can call tcp_disconnect(), which clears sk_shutdown. The sender then adds data to the write queue of the dead socket, and inet_sock_destruct() warns. Leave the loop with -EPIPE when the socket is dead after the sleep. The function already tests SOCK_DEAD before remove_wait_queue() for the same reason. A caller that has the socket open never sees SOCK_DEAD. Fixes: 4f738adba30a ("bpf: create tcp_bpf_ulp allowing BPF to monitor socket TX/RX data") Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Link: https://patch.msgid.link/20261102072112.4160195-9-alexei.starovoitov@gmail.com --- net/core/stream.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/net/core/stream.c b/net/core/stream.c index cb255e2a3a5dd7..334124d683a7a0 100644 --- a/net/core/stream.c +++ b/net/core/stream.c @@ -150,7 +150,11 @@ int sk_stream_wait_memory(struct sock *sk, long *timeo_p) (sk_stream_memory_free(sk) && !vm_wait), &wait); sk->sk_write_pending--; - if (ret < 0) + /* + * A sender which sockmap has redirected to sk does not keep it + * open. A dead socket has no sk_wq. + */ + if (ret < 0 || sock_flag(sk, SOCK_DEAD)) goto do_error; if (vm_wait) { From 9f5763e6287a7a35a807c527874e7033ba3038cc Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Mon, 2 Nov 2026 07:21:06 +0000 Subject: [PATCH 0257/2102] bpf, sockmap: Check the TCP state in recvmsg() With an sk_skb verdict prog, tcp_bpf_recvmsg_parser() copies data from the psock. Then it calls __tcp_cleanup_rbuf() to calculate the receive window and to send an ACK. The window and the ACK need a connection on the socket. But tcp_disconnect() keeps the socket in the sockmap and the data on the psock. For a TCP socket sock_map_redirect_allowed() rejects only TCP_LISTEN. Thus the psock can also get data after tcp_disconnect(). __tcp_select_window() divides by icsk_ack.rcv_mss, which can be 0 in TCP_CLOSE. In TCP_SYN_SENT the new peer can get an ACK with the sequence numbers of the old connection. Call __tcp_cleanup_rbuf() only when tcp_can_send_ack() returns true. recvmsg() returns the data as before. Move tcp_can_send_ack() from MPTCP to tcp.h. It also returns false for a fastopen child in TCP_SYN_RECV. From its peer the child has only the SYN data, and the SYN-ACK acknowledges it. Fixes: e5c6de5fa025 ("bpf, sockmap: Incorrectly handling copied_seq") Signed-off-by: Chris Mason Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Acked-by: Matthieu Baerts (NGI0) Link: https://patch.msgid.link/20261102072112.4160195-10-alexei.starovoitov@gmail.com --- include/net/tcp.h | 6 ++++++ net/ipv4/tcp_bpf.c | 3 ++- net/mptcp/protocol.c | 6 ------ 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/include/net/tcp.h b/include/net/tcp.h index 3560adddf82154..23a22d70718eae 100644 --- a/include/net/tcp.h +++ b/include/net/tcp.h @@ -1845,6 +1845,12 @@ static inline void tcp_adjust_rcv_ssthresh(struct sock *sk) void tcp_cleanup_rbuf(struct sock *sk, int copied); void __tcp_cleanup_rbuf(struct sock *sk, int copied); +/* Is the socket in a state in which TCP may send an ACK? */ +static inline bool tcp_can_send_ack(const struct sock *sk) +{ + return !((1 << inet_sk_state_load(sk)) & + (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_TIME_WAIT | TCPF_CLOSE | TCPF_LISTEN)); +} /* We provision sk_rcvbuf around 200% of sk_rcvlowat. * If 87.5 % (7/8) of the space has been consumed, we want to override diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index ef2e15de0fe3b3..3d703f1517d882 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -343,7 +343,8 @@ static int tcp_bpf_recvmsg_parser(struct sock *sk, if (!peek) WRITE_ONCE(tcp->copied_seq, seq); tcp_rcv_space_adjust(sk); - if (copied > 0) + /* Data on the psock outlives the connection that it came in on */ + if (copied > 0 && tcp_can_send_ack(sk)) __tcp_cleanup_rbuf(sk, copied); unlock: diff --git a/net/mptcp/protocol.c b/net/mptcp/protocol.c index 7a22e9388e0e9a..d62cfbf2d490c2 100644 --- a/net/mptcp/protocol.c +++ b/net/mptcp/protocol.c @@ -619,12 +619,6 @@ static void mptcp_set_timeout(struct sock *sk) __mptcp_set_timeout(sk, tout); } -static inline bool tcp_can_send_ack(const struct sock *ssk) -{ - return !((1 << inet_sk_state_load(ssk)) & - (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_TIME_WAIT | TCPF_CLOSE | TCPF_LISTEN)); -} - void __mptcp_subflow_send_ack(struct sock *ssk) { if (tcp_can_send_ack(ssk)) From 12c45473dfe7b5438d253e67bc7bdf2bb98e3108 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Mon, 2 Nov 2026 07:21:07 +0000 Subject: [PATCH 0258/2102] bpf, sockmap: Reset the copy position when corking sk_msg_memcopy_from_iter() writes to the copy position: byte sg.copybreak after the offset of element sg.curr. Both tcp_bpf_push() and sk_msg_xfer() remove bytes from the front of an element. They increase its offset, but they do not change sg.copybreak when the element is sg.curr. tcp_bpf_send_verdict() can send a part of a message and keep the rest as the cork. tcp_bpf_sendmsg() appends new data to it. If sk_msg_alloc() then extends element sg.curr, the peer can get memory that nobody wrote: old offset offset end of data offset + sg.copybreak | removed | rest | not written | new data Move sk_msg_reset_curr() from filter.c to skmsg.h. Call it when a message becomes the cork, as the helpers that change a message do. It sets the copy position to the end of the data. Without removed bytes it changes nothing. Fixes: 91843d540a13 ("bpf: sockmap, add msg_cork_bytes() helper") Signed-off-by: Chris Mason Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Link: https://patch.msgid.link/20261102072112.4160195-11-alexei.starovoitov@gmail.com --- include/linux/skmsg.h | 19 +++++++++++++++++++ net/core/filter.c | 14 -------------- net/ipv4/tcp_bpf.c | 5 +++++ 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/include/linux/skmsg.h b/include/linux/skmsg.h index d5e35f24738d5c..f0e27b4b929f10 100644 --- a/include/linux/skmsg.h +++ b/include/linux/skmsg.h @@ -196,6 +196,25 @@ static inline void sk_msg_init(struct sk_msg *msg) sg_init_marker(msg->sg.data, NR_MSG_FRAG_IDS); } +/* + * sk_msg_memcopy_from_iter() writes to byte sg.copybreak of element sg.curr, + * counted from the offset of that element. Point both past the last byte of + * the message, after something other than a copy has changed its elements. + */ +static inline void sk_msg_reset_curr(struct sk_msg *msg) +{ + if (!msg->sg.size) { + msg->sg.curr = msg->sg.start; + msg->sg.copybreak = 0; + } else { + u32 i = msg->sg.end; + + sk_msg_iter_var_prev(i); + msg->sg.curr = i; + msg->sg.copybreak = msg->sg.data[i].length; + } +} + static inline void sk_msg_xfer(struct sk_msg *dst, struct sk_msg *src, int which, u32 size) { diff --git a/net/core/filter.c b/net/core/filter.c index 9245009d9f1ebc..50c0cda778db83 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -2677,20 +2677,6 @@ BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg *, msg, u32, bytes) return 0; } -static void sk_msg_reset_curr(struct sk_msg *msg) -{ - if (!msg->sg.size) { - msg->sg.curr = msg->sg.start; - msg->sg.copybreak = 0; - } else { - u32 i = msg->sg.end; - - sk_msg_iter_var_prev(i); - msg->sg.curr = i; - msg->sg.copybreak = msg->sg.data[i].length; - } -} - static bool sk_msg_elem_is_copy(const struct sk_msg *msg, u32 i) { return test_bit(i, msg->sg.copy); diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index 3d703f1517d882..d534974c33f817 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -469,6 +469,11 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, return -ENOMEM; } } + /* + * A push or a redirect may have taken bytes off the front of + * element sg.curr. The next sendmsg() appends to the cork. + */ + sk_msg_reset_curr(msg); memcpy(psock->cork, msg, sizeof(*msg)); return 0; } From a912358996f8f9ac16690c358b05bbcfc59f7666 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Mon, 2 Nov 2026 07:21:08 +0000 Subject: [PATCH 0259/2102] bpf, sockmap: Don't copy 0 bytes into a full cork psock->cork is a ring. sk_msg_memcopy_from_iter() writes at sg.curr. sk_msg_alloc() adds room at sg.end, where a full ring has a spare element. When only a part of the data fits, tcp_bpf_sendmsg() copies this part and flushes the cork. If nothing fits, it copies 0 bytes. This copy writes nothing, but it moves sg.curr to sg.end and returns -ENOSPC. Thus sendmsg() fails without a flush. sg.curr stays at sg.end, and from there a copy moves it past the spare element. Then a copy can skip the first new element, and the peer gets memory that nobody wrote. Skip the copy when sk_msg_alloc() adds nothing, as tls_sw_sendmsg_locked() does. This pass of the loop flushes the cork. The flush empties the element at sg.curr, thus the copy in the next pass starts at the first new element. Now sendmsg() on a full cork does not fail with ENOSPC. The prog runs on less data than it wants to cork, as it does when a part fits. The first Fixes tag is for the -ENOSPC without a flush. The commit in the second tag added the spare element. Since then sg.curr can move past it. Fixes: 604326b41a6f ("bpf, sockmap: convert to generic sk_msg interface") Fixes: 031097d9e079 ("net: skmsg: fix TLS 1.3 crash with full sk_msg") Signed-off-by: Chris Mason Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Link: https://patch.msgid.link/20261102072112.4160195-12-alexei.starovoitov@gmail.com --- net/ipv4/tcp_bpf.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index d534974c33f817..d8e29b09818c20 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -619,8 +619,15 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size) copy = msg_tx->sg.size - osize; } - ret = sk_msg_memcopy_from_iter(sk, &msg->msg_iter, msg_tx, - copy); + /* + * copy is 0 if the ring of the cork was full already and its + * last element could not be extended. Flush the cork below, + * and let the next pass take the data. + */ + ret = 0; + if (copy) + ret = sk_msg_memcopy_from_iter(sk, &msg->msg_iter, + msg_tx, copy); if (ret < 0) { sk_msg_trim(sk, msg_tx, osize); err = ret; From e4c2fe0b9a6206420cc71e1ba4675238b43cb18f Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Mon, 2 Nov 2026 07:21:09 +0000 Subject: [PATCH 0260/2102] bpf, sockmap: Clear the redirect target before the sk_msg prog runs bpf_msg_redirect_{map,hash}() store the target in msg->sk_redir, without a reference. After the prog has run, sk_psock_msg_verdict() makes SK_PASS a redirect if this field is set. But tcp_bpf_send_verdict() runs the prog again on a cork, and on the rest of a partly sent message. Nothing clears the field between runs. Thus SK_PASS without a new target is a redirect to the old target. If that sock is already free, this is a use after free. Clear msg->sk_redir before each run, as the skb verdict paths do with skb_bpf_redirect_clear(). Only SK_PASS without a target changes. It now sends the data on psock->sk. Then sendmsg() can return another value. A redirect that applies to more bytes uses psock->sk_redir, with its own reference. The counts msg->apply_bytes and msg->cork_bytes stay as today. Fixes: e5cd3abcb31a ("bpf: sockmap, refactor sockmap routines to work with hashmap") Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Link: https://patch.msgid.link/20261102072112.4160195-13-alexei.starovoitov@gmail.com --- net/core/skmsg.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/net/core/skmsg.c b/net/core/skmsg.c index a5d498982848f9..8a3b8536c0c218 100644 --- a/net/core/skmsg.c +++ b/net/core/skmsg.c @@ -936,6 +936,13 @@ int sk_psock_msg_verdict(struct sock *sk, struct sk_psock *psock, sk_msg_compute_data_pointers(msg); msg->sk = sk; + /* + * The prog may have run on this sk_msg before: it is a cork, or the + * rest of a message of which only a part was sent. The target of that + * run is not the target of this run, and the sk_msg holds no reference + * to it. + */ + msg->sk_redir = NULL; ret = bpf_prog_run_pin_on_cpu(prog, msg); msg->sk = NULL; ret = sk_psock_map_verd(ret, msg->sk_redir); From 815cfc482e631f713d18944d4e81c1d41fe91fcb Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Mon, 2 Nov 2026 07:21:10 +0000 Subject: [PATCH 0261/2102] bpf, sockmap: Check that the redirected message is the cork In tcp_bpf_send_verdict(), msg is psock->cork or the sk_msg on the stack of tcp_bpf_sendmsg(). If psock->cork is not NULL, the SK_REDIRECT branch sets it to NULL before release_sock() and calls kfree(msg) after the redirect. Thus the branch assumes that a cork is msg. This is not true after release_sock(), because a second sender on the same socket can make a cork. The first sender can run the branch again, and then psock->cork is not its msg. Nobody sends or frees the cork of the second sender. kfree() gets the sk_msg on the stack, and the kernel crashes. Compare psock->cork with msg. Nothing changes for one sender, because psock->cork is then NULL or msg. The other branches do not change, and a cork is still not safe for two senders on one socket. Fixes: 4f738adba30a ("bpf: create tcp_bpf_ulp allowing BPF to monitor socket TX/RX data") Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Link: https://patch.msgid.link/20261102072112.4160195-14-alexei.starovoitov@gmail.com --- net/ipv4/tcp_bpf.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index d8e29b09818c20..b1071b0960cf58 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -517,7 +517,11 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, psock->eval = __SK_NONE; psock->sk_redir = NULL; } - if (psock->cork) { + /* + * Another thread can make a cork while this one sends msg + * without the socket lock. Leave that cork alone. + */ + if (psock->cork == msg) { cork = true; psock->cork = NULL; } From 13c41b87e4a7f587cfec463c7b02bdbb543caa80 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Mon, 2 Nov 2026 07:21:11 +0000 Subject: [PATCH 0262/2102] bpf, sockmap: Keep the rest of the cork after a redirect After bpf_msg_apply_bytes() a verdict can apply to a part of the message. Then tcp_bpf_send_verdict() sends this part and goes to more_data, and the sk_msg prog runs on the rest. The SK_REDIRECT branch does not go there if the message is the cork. It removes the cork from the psock before it releases the socket lock. After the redirect it frees the cork together with the rest. Thus the rest is lost, and sendmsg() reports it as sent. If bytes remain after the redirect, put the cork back into the psock. Then the prog runs on the rest, as after SK_PASS. If the new verdict is SK_DROP or the push fails, sendmsg() now returns a smaller value or the error. msg->cork_bytes keeps its value, thus the rest can stay in the cork. If the psock has a new cork after lock_sock(), the kernel still frees the rest. If the redirect of a cork fails, sendmsg() still returns success and frees it. Fixes: 4f738adba30a ("bpf: create tcp_bpf_ulp allowing BPF to monitor socket TX/RX data") Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Link: https://patch.msgid.link/20261102072112.4160195-15-alexei.starovoitov@gmail.com --- net/ipv4/tcp_bpf.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index b1071b0960cf58..788ce08eef4d7a 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -544,6 +544,14 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, if (!cork) *copied -= free; } + /* + * The verdict was for tosend bytes. The rest goes back, unless + * another thread made a new cork while the lock was released. + */ + if (cork && msg->sg.size && !psock->cork) { + psock->cork = msg; + cork = false; + } if (cork) { sk_msg_free(sk, msg); kfree(msg); From 0048086bd3616b2b3b1b0f122f6268360769a756 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Mon, 2 Nov 2026 07:21:12 +0000 Subject: [PATCH 0263/2102] bpf, sockmap: Clear the end mark of elements added by push and pop The elements of an sk_msg are in a ring of scatterlist slots. A free slot can have the end mark, because sk_msg_init() marks the last slot of the ring. Also, sg_init_table() in tcp_bpf_push() marks each emptied slot. Thus sk_msg_alloc() and sk_msg_page_add() clear the mark of a new element. bpf_msg_push_data() and bpf_msg_pop_data() fill a free slot with sg_set_page(), which keeps the mark. Then the sk_msg can have an end mark before its last element. bpf_tcp_ingress() copies the mark. Since the commit below, __sk_msg_recvmsg() stops at the mark and frees the sk_msg. The data after the mark is lost, and its pages and memory charge leak. Clear the mark after the two sg_set_page() calls that can fill a free slot. A free slot keeps its mark, as today. tcp_bpf_push() does not read the mark, thus SK_PASS and egress redirect do not change. Fixes: 9974d37ea75f ("skmsg: Fix invalid last sg check in sk_msg_recvmsg()") Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Link: https://patch.msgid.link/20261102072112.4160195-16-alexei.starovoitov@gmail.com --- net/core/filter.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/net/core/filter.c b/net/core/filter.c index 50c0cda778db83..d68b5215040506 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -2995,6 +2995,8 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, msg->sg.size += len; sk_msg_clear_elem_copy(msg, new); sg_set_page(&msg->sg.data[new], page, len + copy, 0); + /* A free slot can have the end mark */ + sg_unmark_end(&msg->sg.data[new]); if (rsge.length) { get_page(sg_page(&rsge)); sk_msg_iter_var_next(new); @@ -3128,6 +3130,7 @@ BPF_CALL_4(bpf_msg_pop_data, struct sk_msg *, msg, u32, start, sg_set_page(nsge, sg_page(sge), b, sge->offset + pop + a); + sg_unmark_end(nsge); sk_msg_set_elem_copy(msg, i, sge_copy); } else { struct page *page, *orig; From 4e8d36054e2e2838681fa5dba9ac67a81af12386 Mon Sep 17 00:00:00 2001 From: Geert Uytterhoeven Date: Wed, 14 Oct 2026 12:20:39 +0200 Subject: [PATCH 0264/2102] riscv: RISCV_ISA_SV48 and RISCV_ISA_SV57 should depend on MMU These options are irreleant for nommu systems. Fixes: 36de74049ec8cb1a ("riscv: introduce RISCV_ISA_SV48 and RISCV_ISA_SV57") Signed-off-by: Geert Uytterhoeven Reviewed-by: Jisheng Zhang Link: https://patch.msgid.link/1b1ca4208d725ae0bb834a61636e48728d79cf80.1791973171.git.geert+renesas@glider.be Signed-off-by: Paul Walmsley --- arch/riscv/Kconfig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/arch/riscv/Kconfig b/arch/riscv/Kconfig index e7891a2a89da6a..d2db8f40c61671 100644 --- a/arch/riscv/Kconfig +++ b/arch/riscv/Kconfig @@ -602,7 +602,7 @@ config RISCV_ISA_SSQOSID config RISCV_ISA_SV48 bool "Page-Based 48-bit Virtual-Memory System" - depends on 64BIT + depends on 64BIT && MMU default y help Add support for the Page-Based 48-bit Virtual-Memory System. @@ -614,7 +614,7 @@ config RISCV_ISA_SV48 config RISCV_ISA_SV57 bool "Page-Based 57-bit Virtual-Memory System" - depends on 64BIT + depends on 64BIT && MMU default y help Add support for the Page-Based 57-bit Virtual-Memory System. From e0167a473b3e0f6388bcbf13ce2afcafe1b44b0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20L=C3=A9ger?= Date: Mon, 2 Nov 2026 15:58:11 +0100 Subject: [PATCH 0265/2102] riscv: kgdb: Fix potential missing local_irq_restore() call MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If kgdb_handle_exception() returns an error, local irqs are not reenabled. Fix this by factoring out the kgdb exception handling to a function and call it between local_irq_save()/local_irq_restore() so that the error handling flow is simple. Signed-off-by: Clément Léger Link: https://patch.msgid.link/20261102145812.36939-1-clement.leger@linux.dev Signed-off-by: Paul Walmsley --- arch/riscv/kernel/kgdb.c | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/arch/riscv/kernel/kgdb.c b/arch/riscv/kernel/kgdb.c index 0bf629204c76a4..b833408494f933 100644 --- a/arch/riscv/kernel/kgdb.c +++ b/arch/riscv/kernel/kgdb.c @@ -319,13 +319,28 @@ static int kgdb_riscv_kgdbbreak(unsigned long addr) return kgdb_has_hit_break(addr); } +static int kgdb_riscv_handle(struct die_args *args, unsigned long cmd, + int type) +{ + struct pt_regs *regs = args->regs; + + if (kgdb_handle_exception(type == KGDB_SW_SINGLE_STEP ? 0 : 1, + args->signr, cmd, regs)) + return NOTIFY_DONE; + + if (type == KGDB_COMPILED_BREAK) + regs->epc += 4; + + return NOTIFY_STOP; +} + static int kgdb_riscv_notify(struct notifier_block *self, unsigned long cmd, void *ptr) { struct die_args *args = (struct die_args *)ptr; struct pt_regs *regs = args->regs; unsigned long flags; - int type; + int type, ret; if (user_mode(regs)) return NOTIFY_DONE; @@ -335,17 +350,10 @@ static int kgdb_riscv_notify(struct notifier_block *self, unsigned long cmd, return NOTIFY_DONE; local_irq_save(flags); - - if (kgdb_handle_exception(type == KGDB_SW_SINGLE_STEP ? 0 : 1, - args->signr, cmd, regs)) - return NOTIFY_DONE; - - if (type == KGDB_COMPILED_BREAK) - regs->epc += 4; - + ret = kgdb_riscv_handle(args, cmd, type); local_irq_restore(flags); - return NOTIFY_STOP; + return ret; } static struct notifier_block kgdb_notifier = { From 94196cd3413fba6cf6d1f71d6de401e56caaf29b Mon Sep 17 00:00:00 2001 From: Dmitry Bogdanov Date: Tue, 27 Oct 2026 21:01:22 +0300 Subject: [PATCH 0266/2102] scsi: Revert "scsi: target: iscsi: Fix hang for aborted WRITE_PENDING commands" This reverts commit d5869dae5080e976d4b03cc33eb7ceb527f242bf as it introduces double completion of the command and other issues. Signed-off-by: Dmitry Bogdanov Reviewed-by: Laurence Oberman Tested-by: Laurence Oberman Link: https://patch.msgid.link/20261027180123.13163-2-d.bogdanov@yadro.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/target/iscsi/iscsi_target.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/drivers/target/iscsi/iscsi_target.c b/drivers/target/iscsi/iscsi_target.c index 124ff269b8e759..62ada3a52210ea 100644 --- a/drivers/target/iscsi/iscsi_target.c +++ b/drivers/target/iscsi/iscsi_target.c @@ -1533,10 +1533,8 @@ __iscsit_check_dataout_hdr(struct iscsit_conn *conn, void *buf, */ if (se_cmd->transport_state & CMD_T_ABORTED) { if (hdr->flags & ISCSI_FLAG_CMD_FINAL && - --cmd->outstanding_r2ts < 1) { + --cmd->outstanding_r2ts < 1) iscsit_stop_dataout_timer(cmd); - target_complete_cmd(se_cmd, SAM_STAT_TASK_ABORTED); - } return iscsit_dump_data_payload(conn, payload_length, 1); } From cae8db99f3956e6446827ae4a9605a1ed815772b Mon Sep 17 00:00:00 2001 From: Dmitry Bogdanov Date: Tue, 27 Oct 2026 21:01:23 +0300 Subject: [PATCH 0267/2102] scsi: target: iscsi: Fix hanging WRITE_PENDING commands When Data comes for an aborted WRITE command in WRITE_PENDING state it is silently received and the command does not pass to the target. That leads to hanging of other session with LUN_RESET aborting that command. Pass the aborted WRITE commands when all Data has been gathered. Signed-off-by: Dmitry Bogdanov Reviewed-by: Laurence Oberman Tested-by: Laurence Oberman Link: https://patch.msgid.link/20261027180123.13163-3-d.bogdanov@yadro.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/target/iscsi/iscsi_target.c | 17 ----------------- drivers/target/iscsi/iscsi_target_erl1.c | 8 -------- 2 files changed, 25 deletions(-) diff --git a/drivers/target/iscsi/iscsi_target.c b/drivers/target/iscsi/iscsi_target.c index 62ada3a52210ea..03d618cd767218 100644 --- a/drivers/target/iscsi/iscsi_target.c +++ b/drivers/target/iscsi/iscsi_target.c @@ -1518,23 +1518,6 @@ __iscsit_check_dataout_hdr(struct iscsit_conn *conn, void *buf, if (hdr->flags & ISCSI_FLAG_CMD_FINAL) iscsit_stop_dataout_timer(cmd); - return iscsit_dump_data_payload(conn, payload_length, 1); - } - } else { - /* - * For the normal solicited data path: - * - * Check for a delayed TASK_ABORTED status and dump any - * incoming data out payload if one exists. Also, when the - * ISCSI_FLAG_CMD_FINAL is set to denote the end of the current - * data out sequence, we decrement outstanding_r2ts. Once - * outstanding_r2ts reaches zero, go ahead and send the delayed - * TASK_ABORTED status. - */ - if (se_cmd->transport_state & CMD_T_ABORTED) { - if (hdr->flags & ISCSI_FLAG_CMD_FINAL && - --cmd->outstanding_r2ts < 1) - iscsit_stop_dataout_timer(cmd); return iscsit_dump_data_payload(conn, payload_length, 1); } diff --git a/drivers/target/iscsi/iscsi_target_erl1.c b/drivers/target/iscsi/iscsi_target_erl1.c index d8ca06e697d63f..44b851e4a602d8 100644 --- a/drivers/target/iscsi/iscsi_target_erl1.c +++ b/drivers/target/iscsi/iscsi_target_erl1.c @@ -908,8 +908,6 @@ int iscsit_execute_cmd(struct iscsit_cmd *cmd, int ooo) return 0; } spin_unlock_bh(&cmd->istate_lock); - if (cmd->se_cmd.transport_state & CMD_T_ABORTED) - return 0; return transport_send_check_condition_and_sense(se_cmd, cmd->sense_reason, 0); } @@ -927,9 +925,6 @@ int iscsit_execute_cmd(struct iscsit_cmd *cmd, int ooo) if (!(cmd->cmd_flags & ICF_NON_IMMEDIATE_UNSOLICITED_DATA)) { - if (cmd->se_cmd.transport_state & CMD_T_ABORTED) - return 0; - iscsit_set_dataout_sequence_values(cmd); conn->conn_transport->iscsit_get_dataout(conn, cmd, false); } @@ -942,9 +937,6 @@ int iscsit_execute_cmd(struct iscsit_cmd *cmd, int ooo) if ((cmd->data_direction == DMA_TO_DEVICE) && !(cmd->cmd_flags & ICF_NON_IMMEDIATE_UNSOLICITED_DATA)) { - if (cmd->se_cmd.transport_state & CMD_T_ABORTED) - return 0; - iscsit_set_unsolicited_dataout(cmd); } return target_submit(&cmd->se_cmd); From ebf5cab0dd223a36a09742a91be4fea97e46c816 Mon Sep 17 00:00:00 2001 From: Stanley Jhu Date: Thu, 29 Oct 2026 15:08:36 +0800 Subject: [PATCH 0268/2102] scsi: ufs: core: Restore jiffies conversion of device management timeouts Before commit 08b12cda6c44 ("scsi: ufs: core: Switch to scsi_get_internal_cmd()"), ufshcd_wait_for_dev_cmd() converted the millisecond timeout with msecs_to_jiffies() before waiting for the command. That commit moved the timeout to the block layer and assigns the millisecond value to rq->timeout as is, but rq->timeout is in jiffies. A 1500 ms query timeout (QUERY_REQ_TIMEOUT_DEFAULT) becomes 6 s with CONFIG_HZ=250 and 15 s with CONFIG_HZ=100, and NOP_OUT_TIMEOUT and ADVANCED_RPMB_REQ_TIMEOUT grow the same way. Restore the conversion with msecs_to_jiffies(). Fixes: 08b12cda6c44 ("scsi: ufs: core: Switch to scsi_get_internal_cmd()") Cc: stable@vger.kernel.org # v6.19+ Signed-off-by: Stanley Jhu Reviewed-by: Bart Van Assche Reviewed-by: Peter Wang Link: https://patch.msgid.link/20261029040003.2100003-2-stanleyjhu@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/core/ufshcd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/ufs/core/ufshcd.c b/drivers/ufs/core/ufshcd.c index 4f0301d2a5d4cf..b85b88e4c30861 100644 --- a/drivers/ufs/core/ufshcd.c +++ b/drivers/ufs/core/ufshcd.c @@ -3390,7 +3390,7 @@ static int ufshcd_issue_dev_cmd(struct ufs_hba *hba, struct scsi_cmnd *cmd, struct request *rq = scsi_cmd_to_rq(cmd); blk_status_t sts; - rq->timeout = timeout; + rq->timeout = msecs_to_jiffies(timeout); sts = blk_execute_rq(rq, true); if (sts != BLK_STS_OK) return blk_status_to_errno(sts); From cbab12e5b4a7f49d5add4301de275351269cd431 Mon Sep 17 00:00:00 2001 From: Stanley Jhu Date: Thu, 29 Oct 2026 15:08:37 +0800 Subject: [PATCH 0269/2102] scsi: ufs: core: Introduce ufshcd_rpm_resume_and_get() helper ufshcd_clkscale_enable_store() and ufshcd_auto_hibern8_update() resume the UFS device W-LUN with ufshcd_rpm_get_sync() and ignore its return value. For clkscale_enable: 1. The W-LUN is runtime suspended and clock scaling is disabled. 2. User space writes 1 to clkscale_enable. 3. ufshcd_clkscale_enable_store() calls ufshcd_rpm_get_sync(). 4. The W-LUN runtime resume fails and the W-LUN stays suspended. 5. ufshcd_rpm_get_sync() returns a negative errno, which is ignored. 6. ufshcd_clkscale_enable_store() enables clock scaling and resumes devfreq while the W-LUN is still suspended. For auto_hibern8: 1. The W-LUN starts a runtime suspend. 2. User space writes a new value to auto_hibern8. 3. ufshcd_auto_hibern8_update() sees that the W-LUN is not yet suspended and calls ufshcd_rpm_get_sync(). 4. ufshcd_rpm_get_sync() waits for the runtime suspend to finish and then runs the W-LUN runtime resume. 5. The W-LUN runtime resume fails and the W-LUN stays suspended. 6. ufshcd_rpm_get_sync() returns a negative errno, which is ignored. 7. ufshcd_auto_hibern8_update() writes REG_AUTO_HIBERNATE_IDLE_TIMER while the W-LUN is still suspended. Add ufshcd_rpm_resume_and_get() wrapping pm_runtime_resume_and_get() so failed resumes drop the usage reference automatically, and return early in ufshcd_clkscale_enable_store() and ufshcd_auto_hibern8_update() when it fails. Fixes: b294ff3e3449 ("scsi: ufs: core: Enable power management for wlun") Cc: stable@vger.kernel.org Signed-off-by: Stanley Jhu Reviewed-by: Bart Van Assche Reviewed-by: Peter Wang Link: https://patch.msgid.link/20261029040003.2100003-3-stanleyjhu@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/core/ufshcd-priv.h | 5 +++++ drivers/ufs/core/ufshcd.c | 7 +++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/drivers/ufs/core/ufshcd-priv.h b/drivers/ufs/core/ufshcd-priv.h index e55c2a02c1f506..99f654b79035fc 100644 --- a/drivers/ufs/core/ufshcd-priv.h +++ b/drivers/ufs/core/ufshcd-priv.h @@ -388,6 +388,11 @@ static inline int ufshcd_rpm_get_sync(struct ufs_hba *hba) return pm_runtime_get_sync(&hba->ufs_device_wlun->sdev_gendev); } +static inline int ufshcd_rpm_resume_and_get(struct ufs_hba *hba) +{ + return pm_runtime_resume_and_get(&hba->ufs_device_wlun->sdev_gendev); +} + static inline int ufshcd_rpm_get_if_active(struct ufs_hba *hba) { return pm_runtime_get_if_active(&hba->ufs_device_wlun->sdev_gendev); diff --git a/drivers/ufs/core/ufshcd.c b/drivers/ufs/core/ufshcd.c index b85b88e4c30861..9cb009a6acbe89 100644 --- a/drivers/ufs/core/ufshcd.c +++ b/drivers/ufs/core/ufshcd.c @@ -1864,7 +1864,9 @@ static ssize_t ufshcd_clkscale_enable_store(struct device *dev, if (value == hba->clk_scaling.is_enabled) goto out; - ufshcd_rpm_get_sync(hba); + err = ufshcd_rpm_resume_and_get(hba); + if (err) + goto out; ufshcd_hold(hba); hba->clk_scaling.is_enabled = value; @@ -4792,7 +4794,8 @@ void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit) WRITE_ONCE(hba->ahit, ahit); if (!pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) { - ufshcd_rpm_get_sync(hba); + if (ufshcd_rpm_resume_and_get(hba)) + return; ufshcd_hold(hba); /* * Serialize with the host driver's AHIT control. Skip the From 93891d1c486efcef2267c32e6e73ca2fd243704e Mon Sep 17 00:00:00 2001 From: Stanley Jhu Date: Thu, 29 Oct 2026 15:08:38 +0800 Subject: [PATCH 0270/2102] scsi: ufs: sysfs: Propagate runtime PM resume errors All 14 ufshcd_rpm_get_sync() callers in ufs-sysfs.c resume the UFS device W-LUN and ignore the return value. For example, for a UFS descriptor read: 1. The W-LUN is runtime suspended. 2. User space reads a UFS descriptor attribute in sysfs. 3. ufs_sysfs_read_desc_param() calls ufshcd_rpm_get_sync(). 4. The W-LUN runtime resume fails and the W-LUN stays suspended. 5. ufshcd_rpm_get_sync() returns a negative errno, which is ignored. 6. ufs_sysfs_read_desc_param() sends a query UPIU while the W-LUN is still suspended. The other sysfs callers follow the same sequence. They send other query UPIUs, or read a host register in ufshcd_read_hci_reg(). Switch all 14 sysfs callers to ufshcd_rpm_resume_and_get() and return the error after releasing any held buffer and hba->host_sem. Fixes: aef80fd1da32 ("scsi: ufs: sysfs: Resume the proper SCSI device") Fixes: b9d104465a6c ("scsi: ufs: Prepare to add HCI capabilities sysfs") Fixes: 600edc6620a4 ("scsi: ufs: sysfs: Make max_number_of_rtt read-write") Fixes: 6c4148ce7cc1 ("scsi: ufs: wb: Add explicit flush sysfs attribute") Fixes: 500d4b742e0c ("scsi: ufs: core: Add WB buffer resize support") Fixes: ae7795a8c258 ("scsi: ufs: core: Add HID support") Fixes: 1fd2e77b8897 ("scsi: ufs: core: Add device level exception support") Cc: stable@vger.kernel.org # needs "scsi: ufs: core: Introduce ufshcd_rpm_resume_and_get() helper" Signed-off-by: Stanley Jhu Reviewed-by: Bart Van Assche Reviewed-by: Peter Wang Link: https://patch.msgid.link/20261029040003.2100003-4-stanleyjhu@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/core/ufs-sysfs.c | 67 ++++++++++++++++++++++++++++-------- 1 file changed, 53 insertions(+), 14 deletions(-) diff --git a/drivers/ufs/core/ufs-sysfs.c b/drivers/ufs/core/ufs-sysfs.c index cf49ad0258e140..19b62cf52410bb 100644 --- a/drivers/ufs/core/ufs-sysfs.c +++ b/drivers/ufs/core/ufs-sysfs.c @@ -250,13 +250,19 @@ EXPORT_SYMBOL_GPL(ufshcd_us_to_ahit); static int ufshcd_read_hci_reg(struct ufs_hba *hba, u32 *val, unsigned int reg) { + int ret; + down(&hba->host_sem); if (!ufshcd_is_user_access_allowed(hba)) { up(&hba->host_sem); return -EBUSY; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) { + up(&hba->host_sem); + return ret; + } ufshcd_hold(hba); *val = ufshcd_readl(hba, reg); ufshcd_release(hba); @@ -350,7 +356,9 @@ static ssize_t wb_on_store(struct device *dev, struct device_attribute *attr, goto out; } - ufshcd_rpm_get_sync(hba); + res = ufshcd_rpm_resume_and_get(hba); + if (res) + goto out; res = ufshcd_wb_toggle(hba, wb_enable); ufshcd_rpm_put_sync(hba); out: @@ -421,7 +429,9 @@ static ssize_t enable_wb_buf_flush_store(struct device *dev, goto out; } - ufshcd_rpm_get_sync(hba); + res = ufshcd_rpm_resume_and_get(hba); + if (res) + goto out; res = ufshcd_wb_toggle_buf_flush(hba, enable_wb_buf_flush); ufshcd_rpm_put_sync(hba); @@ -490,7 +500,9 @@ static ssize_t wb_resize_enable_store(struct device *dev, goto out; } - ufshcd_rpm_get_sync(hba); + res = ufshcd_rpm_resume_and_get(hba); + if (res) + goto out; res = ufshcd_wb_set_resize_en(hba, mode); ufshcd_rpm_put_sync(hba); @@ -598,7 +610,9 @@ static ssize_t device_lvl_exception_id_show(struct device *dev, if (hba->dev_info.wspecversion < 0x410) return -EOPNOTSUPP; - ufshcd_rpm_get_sync(hba); + err = ufshcd_rpm_resume_and_get(hba); + if (err) + return err; err = ufshcd_query_attr_qword(hba, UPIU_QUERY_OPCODE_READ_ATTR, QUERY_ATTR_IDN_DEV_LVL_EXCEPTION_ID, 0, 0, &exception_id); @@ -1101,7 +1115,9 @@ static ssize_t ufs_sysfs_read_desc_param(struct ufs_hba *hba, goto out; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) + goto out; ret = ufshcd_read_desc_param(hba, desc_id, desc_index, param_offset, desc_buf, param_size); ufshcd_rpm_put_sync(hba); @@ -1482,7 +1498,12 @@ static ssize_t _name##_show(struct device *dev, \ up(&hba->host_sem); \ return -ENOMEM; \ } \ - ufshcd_rpm_get_sync(hba); \ + ret = ufshcd_rpm_resume_and_get(hba); \ + if (ret) { \ + kfree(desc_buf); \ + up(&hba->host_sem); \ + return ret; \ + } \ ret = ufshcd_query_descriptor_retry(hba, \ UPIU_QUERY_OPCODE_READ_DESC, QUERY_DESC_IDN_DEVICE, \ 0, 0, desc_buf, &desc_len); \ @@ -1548,7 +1569,9 @@ static ssize_t _name##_show(struct device *dev, \ } \ if (ufshcd_is_wb_flags(QUERY_FLAG_IDN##_uname)) \ index = ufshcd_wb_get_query_index(hba); \ - ufshcd_rpm_get_sync(hba); \ + ret = ufshcd_rpm_resume_and_get(hba); \ + if (ret) \ + goto out; \ ret = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG, \ QUERY_FLAG_IDN##_uname, index, &flag); \ ufshcd_rpm_put_sync(hba); \ @@ -1608,7 +1631,9 @@ static ssize_t max_number_of_rtt_show(struct device *dev, return -EBUSY; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) + goto out; ret = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR, QUERY_ATTR_IDN_MAX_NUM_OF_RTT, 0, 0, &rtt); ufshcd_rpm_put_sync(hba); @@ -1648,7 +1673,9 @@ static ssize_t max_number_of_rtt_store(struct device *dev, goto out; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) + goto out; memflags = memalloc_noio_save(); shost_for_each_device(sdev, hba->host) @@ -1700,7 +1727,11 @@ static int wb_read_resize_attrs(struct ufs_hba *hba, } index = ufshcd_wb_get_query_index(hba); - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) { + up(&hba->host_sem); + return ret; + } ret = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR, idn, index, 0, attr_val); ufshcd_rpm_put_sync(hba); @@ -1760,7 +1791,9 @@ static ssize_t _name##_show(struct device *dev, \ } \ if (ufshcd_is_wb_attrs(QUERY_ATTR_IDN##_uname)) \ index = ufshcd_wb_get_query_index(hba); \ - ufshcd_rpm_get_sync(hba); \ + ret = ufshcd_rpm_resume_and_get(hba); \ + if (ret) \ + goto out; \ if (ufshcd_is_qword_attr(QUERY_ATTR_IDN##_uname)) \ ret = ufshcd_query_attr_qword(hba, \ UPIU_QUERY_OPCODE_READ_ATTR, \ @@ -1848,7 +1881,11 @@ static int hid_query_attr(struct ufs_hba *hba, enum query_opcode opcode, return -EBUSY; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) { + up(&hba->host_sem); + return ret; + } ret = ufshcd_query_attr(hba, opcode, idn, 0, 0, attr_val); ufshcd_rpm_put_sync(hba); @@ -2121,7 +2158,9 @@ static ssize_t dyn_cap_needed_attribute_show(struct device *dev, goto out; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) + goto out; ret = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR, QUERY_ATTR_IDN_DYN_CAP_NEEDED, lun, 0, &value); ufshcd_rpm_put_sync(hba); From 2b8541edf7c43f0294c45d2e687bbc1288292f4e Mon Sep 17 00:00:00 2001 From: Stanley Jhu Date: Thu, 29 Oct 2026 15:08:39 +0800 Subject: [PATCH 0271/2102] scsi: ufs: bsg: Abort ufs_bsg_request() when runtime resume fails ufs_bsg_request() resumes the UFS device W-LUN with ufshcd_rpm_get_sync() and ignores its return value: 1. The W-LUN is runtime suspended. 2. User space submits a BSG request. 3. ufs_bsg_request() calls ufshcd_rpm_get_sync(). 4. The W-LUN runtime resume fails and the W-LUN stays suspended. 5. ufshcd_rpm_get_sync() returns a negative errno, which is ignored. 6. ufs_bsg_request() dispatches the BSG command while the W-LUN is still suspended. Use ufshcd_rpm_resume_and_get() and jump to out_complete on error so the BSG job is completed via bsg_job_done() with the failure code without dropping an unacquired runtime PM reference. Fixes: b294ff3e3449 ("scsi: ufs: core: Enable power management for wlun") Cc: stable@vger.kernel.org # needs "scsi: ufs: core: Introduce ufshcd_rpm_resume_and_get() helper" Signed-off-by: Stanley Jhu Reviewed-by: Bart Van Assche Reviewed-by: Peter Wang Link: https://patch.msgid.link/20261029040003.2100003-5-stanleyjhu@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/core/ufs_bsg.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/ufs/core/ufs_bsg.c b/drivers/ufs/core/ufs_bsg.c index baf6ae917d36e4..8df1a2c6abf6a7 100644 --- a/drivers/ufs/core/ufs_bsg.c +++ b/drivers/ufs/core/ufs_bsg.c @@ -150,7 +150,9 @@ static int ufs_bsg_request(struct bsg_job *job) goto out_complete; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) + goto out_complete; msgcode = bsg_request->msgcode; switch (msgcode) { From 9eb89611d95914e47cec62826e4000396df0f953 Mon Sep 17 00:00:00 2001 From: Stanley Jhu Date: Thu, 29 Oct 2026 15:08:40 +0800 Subject: [PATCH 0272/2102] scsi: ufs: hwmon, debugfs: Propagate runtime PM resume errors ufs_hwmon_read(), ufs_hwmon_write(), and ufs_debugfs_get_user_access() resume the UFS device W-LUN with ufshcd_rpm_get_sync() and ignore its return value. For example, for a hwmon temperature read: 1. The W-LUN is runtime suspended. 2. User space reads temp1_input of the UFS hwmon device. 3. ufs_hwmon_read() calls ufshcd_rpm_get_sync(). 4. The W-LUN runtime resume fails and the W-LUN stays suspended. 5. ufshcd_rpm_get_sync() returns a negative errno, which is ignored. 6. ufs_hwmon_read() sends an attribute query UPIU while the W-LUN is still suspended. ufs_hwmon_write() and the debugfs writers that use ufs_debugfs_get_user_access() (exception_event_mask and tx_eq_ctrl) follow the same sequence. Convert all three call sites to ufshcd_rpm_resume_and_get() and release hba->host_sem before returning the error, ahead of __acquire(ufs_debugfs) in ufs_debugfs_get_user_access(). Fixes: b294ff3e3449 ("scsi: ufs: core: Enable power management for wlun") Fixes: e88e2d32200a ("scsi: ufs: core: Probe for temperature notification support") Fixes: adbabdcf0db0 ("scsi: ufs: core: Add support to retrain TX Equalization via debugfs") Cc: stable@vger.kernel.org # needs "scsi: ufs: core: Introduce ufshcd_rpm_resume_and_get() helper" Signed-off-by: Stanley Jhu Reviewed-by: Bart Van Assche Reviewed-by: Peter Wang Link: https://patch.msgid.link/20261029040003.2100003-6-stanleyjhu@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/core/ufs-debugfs.c | 8 +++++++- drivers/ufs/core/ufs-hwmon.c | 12 ++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/drivers/ufs/core/ufs-debugfs.c b/drivers/ufs/core/ufs-debugfs.c index 9f83628f3e2cfd..44a1a969232428 100644 --- a/drivers/ufs/core/ufs-debugfs.c +++ b/drivers/ufs/core/ufs-debugfs.c @@ -70,12 +70,18 @@ token_context_lock(ufs_debugfs); static int ufs_debugfs_get_user_access(struct ufs_hba *hba) __cond_acquires(0, ufs_debugfs) { + int err; + down(&hba->host_sem); if (!ufshcd_is_user_access_allowed(hba)) { up(&hba->host_sem); return -EBUSY; } - ufshcd_rpm_get_sync(hba); + err = ufshcd_rpm_resume_and_get(hba); + if (err) { + up(&hba->host_sem); + return err; + } __acquire(ufs_debugfs); return 0; } diff --git a/drivers/ufs/core/ufs-hwmon.c b/drivers/ufs/core/ufs-hwmon.c index aa0b60a0ee8a77..2b9673d925737a 100644 --- a/drivers/ufs/core/ufs-hwmon.c +++ b/drivers/ufs/core/ufs-hwmon.c @@ -61,7 +61,11 @@ static int ufs_hwmon_read(struct device *dev, enum hwmon_sensor_types type, u32 return -EBUSY; } - ufshcd_rpm_get_sync(hba); + err = ufshcd_rpm_resume_and_get(hba); + if (err) { + up(&hba->host_sem); + return err; + } switch (attr) { case hwmon_temp_enable: @@ -113,7 +117,11 @@ static int ufs_hwmon_write(struct device *dev, enum hwmon_sensor_types type, u32 return -EBUSY; } - ufshcd_rpm_get_sync(hba); + err = ufshcd_rpm_resume_and_get(hba); + if (err) { + up(&hba->host_sem); + return err; + } if (val == 1) err = ufshcd_update_ee_usr_mask(hba, MASK_EE_URGENT_TEMP, 0); From c84374cf4d2cb0c6efff91f7a37e85656cbbd593 Mon Sep 17 00:00:00 2001 From: Shawn Lin Date: Thu, 29 Oct 2026 15:24:55 +0800 Subject: [PATCH 0273/2102] scsi: ufs: rockchip: Improve RX noise immunity Program VND_RX_SAVE_DET_CTRL for each RX lane to raise the receiver's tolerance against short transients on the incoming signal, as recommended by the Rockchip PHY team. Signed-off-by: Shawn Lin Link: https://patch.msgid.link/20261029151030.1.I61cd43e660b146e49d4380a754e936270e5fb6a1@changeid Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/host/ufs-rockchip.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/ufs/host/ufs-rockchip.c b/drivers/ufs/host/ufs-rockchip.c index bac68f238e1c4f..87308c9b1070c1 100644 --- a/drivers/ufs/host/ufs-rockchip.c +++ b/drivers/ufs/host/ufs-rockchip.c @@ -82,6 +82,7 @@ static int ufs_rockchip_rk3576_phy_init(struct ufs_hba *hba) ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(VND_RX_LINERESET_PVALUE2, SEL_RX_LANE0 + i), 0x02); ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(VND_RX_LINERESET_OPTION, SEL_RX_LANE0 + i), 0xf6); ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(VND_RX_POWER_SAVING_CTRL, SEL_RX_LANE0 + i), 0x69); + ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(VND_RX_SAVE_DET_CTRL, SEL_RX_LANE0 + i), 0x18); } /* disable the mphy DME_SET cfg */ From 04feb5fd2c23894ebc2cdaf4a4cc38b8667b17ac Mon Sep 17 00:00:00 2001 From: Dongdong Hao Date: Wed, 4 Nov 2026 17:28:08 +0800 Subject: [PATCH 0274/2102] scsi: leapraid: Fix init_cmd_priv error handling leapraid_init_cmd_priv() ignores the return value of leapraid_internal_init_cmd_priv() and always returns success. If dma_pool_alloc() fails, io_tracker->chain remains NULL, but the SCSI midlayer considers the command successfully initialized. A subsequent I/O requiring more than LEAPRAID_SGL_INLINE_THRESHOLD DMA-mapped scatter-gather entries dereferences the NULL chain buffer while building the chained SGL, causing a kernel crash. Return the result of leapraid_internal_init_cmd_priv() so that allocation failures propagate to the SCSI midlayer and abort initialization of the affected request. Reviewed-by: Damien Le Moal Signed-off-by: Dongdong Hao Link: https://patch.msgid.link/20261104092808.206067-1-doubled@leap-io-kernel.com Fixes: 5597088c9e79 ("scsi: leapraid: Add new SCSI driver") Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/leapraid/leapraid_os.c | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/drivers/scsi/leapraid/leapraid_os.c b/drivers/scsi/leapraid/leapraid_os.c index da597eb99377eb..749e50366dbcf0 100644 --- a/drivers/scsi/leapraid/leapraid_os.c +++ b/drivers/scsi/leapraid/leapraid_os.c @@ -935,22 +935,16 @@ static int leapraid_init_cmd_priv(struct Scsi_Host *shost, struct scsi_cmnd *scmd) { struct leapraid_adapter *adapter = shost_priv(shost); - struct leapraid_io_req_tracker *io_tracker; - io_tracker = scsi_cmd_priv(scmd); - leapraid_internal_init_cmd_priv(adapter, io_tracker); - - return 0; + return leapraid_internal_init_cmd_priv(adapter, scsi_cmd_priv(scmd)); } static int leapraid_exit_cmd_priv(struct Scsi_Host *shost, struct scsi_cmnd *scmd) { struct leapraid_adapter *adapter = shost_priv(shost); - struct leapraid_io_req_tracker *io_tracker; - io_tracker = scsi_cmd_priv(scmd); - leapraid_internal_exit_cmd_priv(adapter, io_tracker); + leapraid_internal_exit_cmd_priv(adapter, scsi_cmd_priv(scmd)); return 0; } From 494f40ffabcdc8d9fa4012b2c972690f25a0a40f Mon Sep 17 00:00:00 2001 From: Marek Szyprowski Date: Mon, 26 Oct 2026 10:54:12 +0100 Subject: [PATCH 0275/2102] dma-coherent: serialize reserved memory pool initialization Multiple devices can share the same "shared-dma-pool" reserved memory region, in which case the dma_coherent_mem structure is created by the first device attached to it and stored in rmem->priv. To avoid the potential race, serialize the check and initialization of rmem->priv with a mutex. Fixes: 7bfa5ab6fa1b ("drivers: dma-coherent: add initialization from device tree") Cc: stable@vger.kernel.org Link: https://lore.kernel.org/r/20261026095423.966856-2-m.szyprowski@samsung.com Signed-off-by: Marek Szyprowski --- kernel/dma/coherent.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/kernel/dma/coherent.c b/kernel/dma/coherent.c index 4d0266893bcc99..ac62b6bd3d0d0e 100644 --- a/kernel/dma/coherent.c +++ b/kernel/dma/coherent.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -335,10 +336,18 @@ static phys_addr_t dma_reserved_default_memory_base __initdata; static phys_addr_t dma_reserved_default_memory_size __initdata; #endif +static DEFINE_MUTEX(rmem_dma_mutex); + static int rmem_dma_device_init(struct reserved_mem *rmem, struct device *dev) { - struct dma_coherent_mem *mem = rmem->priv; + struct dma_coherent_mem *mem; + /* + * Multiple devices can share the same pool and may be probed + * concurrently, so serialize the initialization of rmem->priv. + */ + guard(mutex)(&rmem_dma_mutex); + mem = rmem->priv; if (!mem) { mem = dma_init_coherent_memory(rmem->base, rmem->base, rmem->size, true); From 7ad92b81b415de806957b19828fc4777a9cf2216 Mon Sep 17 00:00:00 2001 From: Marek Szyprowski Date: Mon, 26 Oct 2026 10:54:13 +0100 Subject: [PATCH 0276/2102] dma: swiotlb: Serialize restricted DMA pool initialization Multiple devices can share the same restricted DMA pool, in which case the io_tlb_mem structure is allocated and initialized by the first device attached to it and stored in rmem->priv. To avoid the potential race, serialize the check and initialization of rmem->priv with a mutex. Fixes: 0b84e4f8b793 ("swiotlb: Add restricted DMA pool initialization") Closes: https://sashiko.dev/#/bug/linux-6fda7589-591d-4a68-b6e1-b1561f867319 Cc: stable@vger.kernel.org Link: https://lore.kernel.org/r/20261026095423.966856-3-m.szyprowski@samsung.com Signed-off-by: Marek Szyprowski --- kernel/dma/swiotlb.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/kernel/dma/swiotlb.c b/kernel/dma/swiotlb.c index 2c57b49ac7c063..db731f7891b769 100644 --- a/kernel/dma/swiotlb.c +++ b/kernel/dma/swiotlb.c @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -1986,10 +1987,12 @@ void swiotlb_free_from_pool(struct device *dev, swiotlb_release_slots(dev, tlb_addr, pool); } +static DEFINE_MUTEX(rmem_swiotlb_mutex); + static int rmem_swiotlb_device_init(struct reserved_mem *rmem, struct device *dev) { - struct io_tlb_mem *mem = rmem->priv; + struct io_tlb_mem *mem; unsigned long nslabs = rmem->size >> IO_TLB_SHIFT; /* Set Per-device io tlb area to one */ @@ -2003,8 +2006,10 @@ static int rmem_swiotlb_device_init(struct reserved_mem *rmem, /* * Since multiple devices can share the same pool, the private data, * io_tlb_mem struct, will be initialized by the first device attached - * to it. + * to it. Serialize this, as devices may be probed concurrently. */ + guard(mutex)(&rmem_swiotlb_mutex); + mem = rmem->priv; if (!mem) { struct io_tlb_pool *pool; From ca010d38da7bf05a4572a54c2c16d6d64a758c3a Mon Sep 17 00:00:00 2001 From: Marek Szyprowski Date: Mon, 26 Oct 2026 10:54:15 +0100 Subject: [PATCH 0277/2102] dma-pool: release CMA pages on atomic_pool_expand() error path atomic_pool_expand() may allocate the pool backing pages from CMA via dma_alloc_from_contiguous(), but the error path unconditionally frees them with __free_pages(). This hands CMA pages to the buddy allocator while leaving them marked as allocated in the CMA bitmap, permanently leaking CMA capacity on every failed expansion. Try dma_release_from_contiguous() first and fall back to __free_pages() only for pages that did not come from CMA, as the code did before CMA allocation was temporarily removed from the pool. Fixes: d7e673ec2c8e ("dma-pool: Only allocate from CMA when in same memory zone") Closes: https://sashiko.dev/#/bug/linux-fdfc6e83-15e4-4980-9818-691b034397e7 Cc: stable@vger.kernel.org Link: https://lore.kernel.org/r/20261026095423.966856-5-m.szyprowski@samsung.com Signed-off-by: Marek Szyprowski --- kernel/dma/pool.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/kernel/dma/pool.c b/kernel/dma/pool.c index 00f422a1e89666..381b3cb28368fc 100644 --- a/kernel/dma/pool.c +++ b/kernel/dma/pool.c @@ -152,7 +152,8 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size, dma_common_free_remap(addr, pool_size); free_page: #endif - if (!leak_pages) + if (!leak_pages && + !dma_release_from_contiguous(NULL, page, 1 << order)) __free_pages(page, order); out: return ret; From 5b4b87935bf9c6c81b603558c2e167fc27c22a1b Mon Sep 17 00:00:00 2001 From: Marek Szyprowski Date: Tue, 3 Nov 2026 16:50:15 +0100 Subject: [PATCH 0278/2102] dma: swiotlb: Round restricted DMA pool size down to IO_TLB_SEGSIZE All other paths creating a swiotlb pool ensure that nslabs is a multiple of IO_TLB_SEGSIZE, and the swiotlb code relies on that. Since commit 0b84e4f8b793 ("swiotlb: Add restricted DMA pool initialization") a restricted pool can have an arbitrary size taken from the device tree. If the pool size is not a multiple of IO_TLB_SEGSIZE, the last segment is partial and swiotlb_release_slots() reads mem->slots[index + nslabs], which is one past the end of the slots array when the freed buffer ends at the end of the pool: BUG: KASAN: slab-out-of-bounds in swiotlb_release_slots Read of size 2 Round the pool size down to a multiple of IO_TLB_SEGSIZE, wasting a bit of memory, and warn about it. Reported-by: Giorgi Kobakhia Closes: https://lore.kernel.org/all/20261026032007.1957949-1-gkobakhi@asu.edu/ Fixes: 0b84e4f8b793 ("swiotlb: Add restricted DMA pool initialization") CC: stable@vger.kernel.org Reviewed-by: Michael Kelley Link: https://lore.kernel.org/r/20261103155016.1107958-1-m.szyprowski@samsung.com Signed-off-by: Marek Szyprowski --- kernel/dma/swiotlb.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/kernel/dma/swiotlb.c b/kernel/dma/swiotlb.c index db731f7891b769..9b0bc272dd82f5 100644 --- a/kernel/dma/swiotlb.c +++ b/kernel/dma/swiotlb.c @@ -2012,6 +2012,19 @@ static int rmem_swiotlb_device_init(struct reserved_mem *rmem, mem = rmem->priv; if (!mem) { struct io_tlb_pool *pool; + unsigned long aligned_nslabs = ALIGN_DOWN(nslabs, IO_TLB_SEGSIZE); + + if (aligned_nslabs != nslabs) { + dev_warn(dev, "Restricted DMA pool size %zu is not a multiple of %lu, rounding down to %lu bytes\n", + (size_t)rmem->size, + (unsigned long)IO_TLB_SEGSIZE << IO_TLB_SHIFT, + aligned_nslabs << IO_TLB_SHIFT); + nslabs = aligned_nslabs; + } + if (!nslabs) { + dev_err(dev, "Restricted DMA pool is too small\n"); + return -EINVAL; + } mem = kzalloc_obj(*mem); if (!mem) @@ -2039,7 +2052,7 @@ static int rmem_swiotlb_device_init(struct reserved_mem *rmem, mem->cc_shared = true; ret = set_memory_decrypted((unsigned long)phys_to_virt(rmem->base), - rmem->size >> PAGE_SHIFT); + (nslabs << IO_TLB_SHIFT) >> PAGE_SHIFT); if (ret) { dev_err(dev, "Failed to decrypt restricted DMA pool\n"); kfree(pool->areas); From ff00e5c03e7efe88f7a50a8673b14e8f0d4b45bb Mon Sep 17 00:00:00 2001 From: "Baek Kyu, Kim" Date: Sat, 31 Oct 2026 17:18:04 +0900 Subject: [PATCH 0279/2102] pinctrl: realtek: Write the encoded slew rate value rtd_pconf_parse_conf() maps slew-rate arguments 1, 10, 20 and 30 to the two-bit field values 0, 1, 2 and 3. However, it shifts the original argument into the register value instead of using the computed encoding. After masking, these arguments write 1, 2, 0 and 2 respectively. In particular, the distinct 10 and 30 settings write the same field value. Use set_val when constructing the register value so that both individual pin and group configuration apply the existing conversion. Leave argument validation, field offsets, masks and regmap error handling unchanged. Fixes: dcc9334435b0 ("pinctrl: realtek: add support for slew rate, input voltage and high VIL") Signed-off-by: Baek Kyu, Kim Reviewed-by: Yu-Chun Lin Tested-by: Yu-Chun Lin Signed-off-by: Linus Walleij --- drivers/pinctrl/realtek/pinctrl-rtd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/pinctrl/realtek/pinctrl-rtd.c b/drivers/pinctrl/realtek/pinctrl-rtd.c index 60222339726b46..656c281c557ace 100644 --- a/drivers/pinctrl/realtek/pinctrl-rtd.c +++ b/drivers/pinctrl/realtek/pinctrl-rtd.c @@ -438,7 +438,7 @@ static int rtd_pconf_parse_conf(struct rtd_pinctrl *data, sr_off = config_desc->base_bit + config_desc->slew_rate_offset; reg_off = config_desc->reg_offset; mask = 0x3 << sr_off; - val = arg << sr_off; + val = set_val << sr_off; break; case PIN_CONFIG_INPUT_VOLTAGE_UV: From da984bd653ac005bd6230a97d6c1b0ceec112c9a Mon Sep 17 00:00:00 2001 From: Leon Romanovsky Date: Thu, 5 Nov 2026 04:55:51 -0500 Subject: [PATCH 0280/2102] RDMA: Rely on the generic Patchwork instance Drivers do not maintain separate patch states in Patchwork, so there is no need to specify the generic Patchwork instance for every entry. Rely on the generic instance instead. Link: https://patch.msgid.link/20261103-rdma-branches-v1-1-763c07cc14aa@nvidia.com Signed-off-by: Leon Romanovsky --- MAINTAINERS | 6 ------ 1 file changed, 6 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index 93abbb315065de..ececae18035249 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -1049,7 +1049,6 @@ R: Gal Pressman R: Yossi Leybovich L: linux-rdma@vger.kernel.org S: Supported -Q: https://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/hw/efa/ F: include/uapi/rdma/efa-abi.h @@ -14193,7 +14192,6 @@ L: linux-rdma@vger.kernel.org S: Supported W: http://www.openfabrics.org W: www.open-iscsi.org -Q: http://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/ulp/iser/ ISCSI EXTENSIONS FOR RDMA (ISER) TARGET @@ -17357,7 +17355,6 @@ M: Yishai Hadas L: linux-rdma@vger.kernel.org S: Supported W: https://www.nvidia.com/networking/ -Q: http://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/hw/mlx4/ F: include/linux/mlx4/ F: include/uapi/rdma/mlx4-abi.h @@ -17381,7 +17378,6 @@ M: Leon Romanovsky L: linux-rdma@vger.kernel.org S: Supported W: https://www.nvidia.com/networking/ -Q: http://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/hw/mlx5/ F: include/linux/mlx5/ F: include/uapi/rdma/mlx5-abi.h @@ -25165,7 +25161,6 @@ SCSI RDMA PROTOCOL (SRP) INITIATOR M: Bart Van Assche L: linux-rdma@vger.kernel.org S: Supported -Q: http://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/ulp/srp/ F: include/scsi/srp.h @@ -25174,7 +25169,6 @@ M: Bart Van Assche L: linux-rdma@vger.kernel.org L: target-devel@vger.kernel.org S: Supported -Q: http://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/ulp/srpt/ SCSI SG DRIVER From 8a659a44b80f074a7f99b39a840054b7363b5a94 Mon Sep 17 00:00:00 2001 From: Leon Romanovsky Date: Thu, 5 Nov 2026 04:55:51 -0500 Subject: [PATCH 0281/2102] RDMA: Add missing UAPI files Add the missing UAPI files to the relevant entries. Link: https://patch.msgid.link/20261103-rdma-branches-v1-2-763c07cc14aa@nvidia.com Signed-off-by: Leon Romanovsky --- MAINTAINERS | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index ececae18035249..d49552a5969225 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -11821,6 +11821,7 @@ M: Dennis Dalessandro L: linux-rdma@vger.kernel.org S: Supported F: drivers/infiniband/hw/hfi1 +F: include/uapi/rdma/hfi HFS FILESYSTEM M: Viacheslav Dubeyko @@ -12146,6 +12147,7 @@ L: linux-rdma@vger.kernel.org S: Maintained F: Documentation/devicetree/bindings/infiniband/hisilicon,hns-roce-v1.yaml F: drivers/infiniband/hw/hns/ +F: include/uapi/rdma/hns-abi.h HISILICON SAS Controller M: Xingui Yang @@ -23440,6 +23442,7 @@ M: Dennis Dalessandro L: linux-rdma@vger.kernel.org S: Supported F: drivers/infiniband/sw/rdmavt +F: include/uapi/rdma/rvt-abi.h RDS - RELIABLE DATAGRAM SOCKETS M: Allison Henderson @@ -29905,10 +29908,10 @@ F: arch/x86/kernel/cpu/vmware.c VMWARE PVRDMA DRIVER M: Bryan Tan M: Vishnu Dasa -R: Broadcom internal kernel review list L: linux-rdma@vger.kernel.org S: Supported F: drivers/infiniband/hw/vmw_pvrdma/ +F: include/uapi/rdma/vmw_pvrdma-abi.h VMWARE PVSCSI DRIVER M: Vishal Bhakta From 19c729c9be549276ccebcb2e2a19bc615d87ebc3 Mon Sep 17 00:00:00 2001 From: Leon Romanovsky Date: Thu, 5 Nov 2026 04:55:52 -0500 Subject: [PATCH 0282/2102] RDMA: Clean up the INFINIBAND subsystem entry The Infiniband subsystem has had a broader meaning for a long time. It represents the entire RDMA stack rather than just the InfiniBand transport. Reflect this in the subsystem name. While at it, point contributors at the correct base branch for their work, which is for-next rather than the default master branch. Link: https://patch.msgid.link/20261103-rdma-branches-v1-3-763c07cc14aa@nvidia.com Signed-off-by: Leon Romanovsky --- MAINTAINERS | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index d49552a5969225..54df71bd7d65fb 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -13111,14 +13111,14 @@ W: https://www.infineon.com/part/TLV493D-A1B6 F: Documentation/devicetree/bindings/iio/magnetometer/infineon,tlv493d-a1b6.yaml F: drivers/iio/magnetometer/tlv493d.c -INFINIBAND SUBSYSTEM +RDMA (INFINIBAND) SUBSYSTEM M: Jason Gunthorpe M: Leon Romanovsky L: linux-rdma@vger.kernel.org S: Supported W: https://github.com/linux-rdma/rdma-core Q: http://patchwork.kernel.org/project/linux-rdma/list/ -T: git git://git.kernel.org/pub/scm/linux/kernel/git/rdma/rdma.git +T: git git://git.kernel.org/pub/scm/linux/kernel/git/rdma/rdma.git for-next F: Documentation/devicetree/bindings/infiniband/ F: Documentation/infiniband/ F: drivers/infiniband/ From 9378a75946ba32fded743b9cdeda5b0543a5250d Mon Sep 17 00:00:00 2001 From: Leon Romanovsky Date: Thu, 5 Nov 2026 04:55:52 -0500 Subject: [PATCH 0283/2102] RDMA: Remove pointless links These links either no longer exist, point to stale tree, or provide no useful information. Remove them. Link: https://patch.msgid.link/20261103-rdma-branches-v1-4-763c07cc14aa@nvidia.com Signed-off-by: Leon Romanovsky --- MAINTAINERS | 3 --- 1 file changed, 3 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index 54df71bd7d65fb..6004ff7ed8af3b 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -14192,8 +14192,6 @@ M: Sagi Grimberg M: Max Gurtovoy L: linux-rdma@vger.kernel.org S: Supported -W: http://www.openfabrics.org -W: www.open-iscsi.org F: drivers/infiniband/ulp/iser/ ISCSI EXTENSIONS FOR RDMA (ISER) TARGET @@ -14201,7 +14199,6 @@ M: Sagi Grimberg L: linux-rdma@vger.kernel.org L: target-devel@vger.kernel.org S: Supported -T: git git://git.kernel.org/pub/scm/linux/kernel/git/nab/target-pending.git master F: drivers/infiniband/ulp/isert ISL28022 HARDWARE MONITORING DRIVER From f06482ceb314c8dc19f3d084b29c27af237556b5 Mon Sep 17 00:00:00 2001 From: Tzung-Bi Shih Date: Thu, 5 Nov 2026 00:20:37 +0800 Subject: [PATCH 0284/2102] reset: Fix reset_control leak when put after controller unregister After commit 8c91302a29bc ("reset: protect struct reset_control with its own mutex"), reset_control_put_internal() returns early if `rcdev` is NULL. When a reset controller is unregistered while consumers still hold reset_control handles, reset_controller_unregister() sets `rstc->rcdev` to NULL. When consumers later release their handles via reset_control_put(), the early return skips kref_put(), resulting in leaking resources. Call kref_put() in reset_control_put_internal() even if `rcdev` is NULL. Fixes: 8c91302a29bc ("reset: protect struct reset_control with its own mutex") Signed-off-by: Tzung-Bi Shih Reviewed-by: Philipp Zabel Reviewed-by: Bartosz Golaszewski Signed-off-by: Philipp Zabel --- drivers/reset/core.c | 47 ++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 13 deletions(-) diff --git a/drivers/reset/core.c b/drivers/reset/core.c index 38e189d04d09b2..f0ab09795ae1bd 100644 --- a/drivers/reset/core.c +++ b/drivers/reset/core.c @@ -160,6 +160,9 @@ int reset_controller_register(struct reset_controller_dev *rcdev) } EXPORT_SYMBOL_GPL(reset_controller_register); +static void __reset_control_release(struct kref *kref); +static void __reset_control_free(struct reset_control *rstc); + static void reset_controller_remove(struct reset_controller_dev *rcdev, struct reset_control *rstc) { @@ -185,11 +188,18 @@ void reset_controller_unregister(struct reset_controller_dev *rcdev) /* * Numb but don't free the remaining reset control handles that are * still held by consumers. + * + * Hold a temporary reference on rstc before clearing rstc->rcdev: + * once rstc->rcdev is NULL, a concurrent reset_control_put_internal() + * will not acquire rcdev->lock and could otherwise free rstc. */ list_for_each_entry_safe(rstc, pos, &rcdev->reset_control_head, list) { + kref_get(&rstc->refcnt); rcu_assign_pointer(rstc->rcdev, NULL); synchronize_srcu(&rstc->srcu); reset_controller_remove(rcdev, rstc); + if (kref_put(&rstc->refcnt, __reset_control_release)) + __reset_control_free(rstc); } } @@ -886,14 +896,16 @@ __reset_control_get_internal(struct reset_controller_dev *rcdev, return rstc; } +/* + * Detaches rstc from rcdev (if still attached) when refcnt reaches 0. + * If rstc is still attached, the caller must hold rcdev->lock. + */ static void __reset_control_release(struct kref *kref) { struct reset_control *rstc = container_of(kref, struct reset_control, refcnt); struct reset_controller_dev *rcdev; - lockdep_assert_held(&rstc->srcu); - rcdev = rcu_replace_pointer(rstc->rcdev, NULL, true); if (rcdev) { lockdep_assert_held(&rcdev->lock); @@ -903,6 +915,17 @@ static void __reset_control_release(struct kref *kref) mutex_destroy(&rstc->lock); } +/* + * Must be called outside the rstc->srcu read-side critical section after + * kref_put(..., __reset_control_release) returns true. + */ +static void __reset_control_free(struct reset_control *rstc) +{ + synchronize_srcu(&rstc->srcu); + cleanup_srcu_struct(&rstc->srcu); + kfree(rstc); +} + static void reset_control_put_internal(struct reset_control *rstc) { struct reset_controller_dev *rcdev; @@ -913,19 +936,17 @@ static void reset_control_put_internal(struct reset_control *rstc) scoped_guard(srcu, &rstc->srcu) { rcdev = srcu_dereference(rstc->rcdev, &rstc->srcu); - if (!rcdev) - /* Already released. */ - return; - - guard(mutex)(&rcdev->lock); - ret = kref_put(&rstc->refcnt, __reset_control_release); + if (rcdev) { + guard(mutex)(&rcdev->lock); + ret = kref_put(&rstc->refcnt, __reset_control_release); + } else { + /* Already detached from rcdev. */ + ret = kref_put(&rstc->refcnt, __reset_control_release); + } } - if (ret) { - synchronize_srcu(&rstc->srcu); - cleanup_srcu_struct(&rstc->srcu); - kfree(rstc); - } + if (ret) + __reset_control_free(rstc); } static void reset_gpio_aux_device_release(struct device *dev) From d1f583c1eab5e4432c7ad48a8abd27cffbc8a549 Mon Sep 17 00:00:00 2001 From: Tzung-Bi Shih Date: Thu, 5 Nov 2026 00:20:38 +0800 Subject: [PATCH 0285/2102] reset: Fix circular locking dependency in reset_controller_unregister() reset_control_acquire() and reset_control_put_internal() acquire `rcdev->lock` inside the `rstc->srcu` read-side critical section (`rstc->srcu` -> `rcdev->lock`). However, reset_controller_unregister() holds `rcdev->lock` while calling synchronize_srcu(&rstc->srcu) (`rcdev->lock` -> `rstc->srcu`), causing a lockdep circular locking dependency warning and a potential ABBA deadlock. Run synchronize_srcu() outside `rcdev->lock`. Fixes: 44a0acb2caca ("reset: protect struct reset_controller_dev with its own mutex") Signed-off-by: Tzung-Bi Shih Reviewed-by: Philipp Zabel Reviewed-by: Bartosz Golaszewski Signed-off-by: Philipp Zabel --- drivers/reset/core.c | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/drivers/reset/core.c b/drivers/reset/core.c index f0ab09795ae1bd..4a582721782f49 100644 --- a/drivers/reset/core.c +++ b/drivers/reset/core.c @@ -163,11 +163,15 @@ EXPORT_SYMBOL_GPL(reset_controller_register); static void __reset_control_release(struct kref *kref); static void __reset_control_free(struct reset_control *rstc); +/* + * Removes rstc from its list and drops the references on rcdev's owner module + * and device. The caller must ensure rstc->list access is serialized (e.g., + * by holding rcdev->lock or moving rstc to a private list) and that no + * operations on rcdev via rstc are in flight. + */ static void reset_controller_remove(struct reset_controller_dev *rcdev, struct reset_control *rstc) { - lockdep_assert_held(&rcdev->lock); - list_del(&rstc->list); module_put(rcdev->owner); put_device(rcdev->dev); @@ -180,6 +184,7 @@ static void reset_controller_remove(struct reset_controller_dev *rcdev, void reset_controller_unregister(struct reset_controller_dev *rcdev) { struct reset_control *rstc, *pos; + LIST_HEAD(reset_control_head); scoped_guard(mutex, &reset_list_mutex) list_del(&rcdev->list); @@ -196,13 +201,22 @@ void reset_controller_unregister(struct reset_controller_dev *rcdev) list_for_each_entry_safe(rstc, pos, &rcdev->reset_control_head, list) { kref_get(&rstc->refcnt); rcu_assign_pointer(rstc->rcdev, NULL); - synchronize_srcu(&rstc->srcu); - reset_controller_remove(rcdev, rstc); - if (kref_put(&rstc->refcnt, __reset_control_release)) - __reset_control_free(rstc); + list_move(&rstc->list, &reset_control_head); } } + /* + * Run synchronize_srcu() outside rcdev->lock to avoid a circular + * locking dependency with paths that acquire rcdev->lock inside + * the rstc->srcu read-side critical section. + */ + list_for_each_entry_safe(rstc, pos, &reset_control_head, list) { + synchronize_srcu(&rstc->srcu); + reset_controller_remove(rcdev, rstc); + if (kref_put(&rstc->refcnt, __reset_control_release)) + __reset_control_free(rstc); + } + mutex_destroy(&rcdev->lock); } EXPORT_SYMBOL_GPL(reset_controller_unregister); From f9bfe5af596a5ef6fc745c30bda41f9a109ed16d Mon Sep 17 00:00:00 2001 From: Rik van Riel Date: Wed, 4 Nov 2026 10:01:15 -0500 Subject: [PATCH 0286/2102] xfs: keep successful near rt allocations XFS realtime allocations first attempt to allocate space near where other parts of a file already are. If that allocation succeeds, it does not have to do a global search for free space. Unfortunately, a code cleanup a while ago causes xfs_rtallocate_rtg to unconditionally do the global search, even when the search for a nearby extent has succeeded. Fix it by running the global search only when the near search did not find available space. Found by noticing higher kernel CPU use and examining the profile. Fixes: fd048a1bb391d ("xfs: rework the rtalloc fallback handling") Cc: stable@vger.kernel.org # v6.12 Reported-by: Christian Andres Saide Signed-off-by: Rik van Riel Reviewed-by: Christoph Hellwig Reviewed-by: Carlos Maiolino Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_rtalloc.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/fs/xfs/xfs_rtalloc.c b/fs/xfs/xfs_rtalloc.c index 84efe5a8fb11d8..31d90828b4e9e2 100644 --- a/fs/xfs/xfs_rtalloc.c +++ b/fs/xfs/xfs_rtalloc.c @@ -1997,10 +1997,14 @@ xfs_rtallocate_rtg( if (error == -ENOSPC) { xfs_rtbuf_cache_relse(&args); error = 0; + start = 0; } } - if (!error) { + /* + * Global search, runs when the near search did not find space. + */ + if (!error && !start) { error = xfs_rtallocate_extent_size(&args, minlen, maxlen, &len, prod, &rtx); } From 25ef4be4b4b06c0d21378bf6bced2532216d4d56 Mon Sep 17 00:00:00 2001 From: Gautam Gala Date: Thu, 15 Oct 2026 12:48:21 +0200 Subject: [PATCH 0287/2102] KVM: s390: fix ESSA addressing exception injection in migration mode __do_essa() treated any negative return from dat_perform_essa() as the normal "no CBRL entry appended" case and returned 0, so a page-table walk failure silently dropped the addressing exception. Return -PGM_ADDRESSING on a walk failure and inject the program interrupt in __do_essa() for the -PGM_ADDRESSING return value. DAT_WALK_ANY is required in the dat_entry_walk() call so that a GFN backed by a large page (segment or region entry) does not return an error: the walk stops early but succeeds, leaving ptep as NULL, which is already handled by the existing "set exception state, return -1" path. Without DAT_WALK_ANY such addresses would fall through to the new error path and incorrectly inject PGM_ADDRESSING. Fixes: e38c884df921 ("KVM: s390: Switch to new gmap") Reported-by: Christian Borntraeger Suggested-by: Claudio Imbrenda Acked-by: Christian Borntraeger Signed-off-by: Gautam Gala Reviewed-by: Claudio Imbrenda Signed-off-by: Christian Borntraeger --- arch/s390/kvm/gmap/dat.c | 5 ++++- arch/s390/kvm/s390/priv.c | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/arch/s390/kvm/gmap/dat.c b/arch/s390/kvm/gmap/dat.c index ff80d02c9f5643..a2031aece4ed1e 100644 --- a/arch/s390/kvm/gmap/dat.c +++ b/arch/s390/kvm/gmap/dat.c @@ -1084,6 +1084,7 @@ int dat_set_prefix_notif_bit(union asce asce, gfn_t gfn) * * %1 if the page state has been altered and the page is to be added to the CBRL * * %0 if the page state has been altered, but the page is not to be added to the CBRL * * %-1 if the page state has not been altered and the page is not to be added to the CBRL + * * %PGM_ADDRESSING if the guest page-table walk failed */ int dat_perform_essa(union asce asce, gfn_t gfn, int orc, union essa_state *state, bool *dirty) { @@ -1092,7 +1093,9 @@ int dat_perform_essa(union asce asce, gfn_t gfn, int orc, union essa_state *stat union pte *ptep; int res = 0; - if (dat_entry_walk(NULL, gfn, asce, 0, TABLE_TYPE_PAGE_TABLE, &crstep, &ptep)) { + if (dat_entry_walk(NULL, gfn, asce, DAT_WALK_ANY, TABLE_TYPE_PAGE_TABLE, &crstep, &ptep)) + return PGM_ADDRESSING; + if (!ptep) { *state = (union essa_state) { .exception = 1 }; return -1; } diff --git a/arch/s390/kvm/s390/priv.c b/arch/s390/kvm/s390/priv.c index 856939acf012fd..b252c812dcbe7e 100644 --- a/arch/s390/kvm/s390/priv.c +++ b/arch/s390/kvm/s390/priv.c @@ -1169,6 +1169,8 @@ static inline int __do_essa(struct kvm_vcpu *vcpu, const int orc) entries = (vcpu->arch.sie_block->cbrlo & ~PAGE_MASK) >> 3; nappended = dat_perform_essa(vcpu->arch.gmap->asce, gfn, orc, &state, &dirtied); + if (nappended == PGM_ADDRESSING) + return kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING); vcpu->run->s.regs.gprs[r1] = state.val; if (nappended < 0) return 0; From a4ac406a32910b45159fce463032faac7acd3894 Mon Sep 17 00:00:00 2001 From: Gautam Gala Date: Tue, 20 Oct 2026 10:25:34 +0200 Subject: [PATCH 0288/2102] KVM: s390: pqap: fix AP status written to wrong half of GR1 The AP Queue Status Word (APQSW) occupies bit positions 32-63 of GR1, i.e. the low 32 bits of the 64-bit register, while the upper 32 bits are reserved. The no-hook fallback path in handle_pqap() synthesizes an APQSW and copies struct ap_queue_status directly into GPR1 using memcpy(). On big-endian s390 this places the APQSW in the upper 32 bits of the register rather than in the architecturally defined APQSW field. Use union ap_queue_status_reg and assign its value directly to GPR1. This places APQSW in the correct half of the register and aligns the fallback path with the register layout used by the AP infrastructure. Fixes: e5282de93105 ("s390: ap: kvm: add PQAP interception for AQIC") Reported-by: Christian Borntraeger Signed-off-by: Gautam Gala Reviewed-by: Christian Borntraeger Signed-off-by: Christian Borntraeger --- arch/s390/kvm/s390/priv.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/arch/s390/kvm/s390/priv.c b/arch/s390/kvm/s390/priv.c index b252c812dcbe7e..f22612a127c96b 100644 --- a/arch/s390/kvm/s390/priv.c +++ b/arch/s390/kvm/s390/priv.c @@ -593,7 +593,7 @@ EXPORT_SYMBOL_FOR_MODULES(kvm_s390_is_gpa_in_memslot, "vfio_ap"); */ static int handle_pqap(struct kvm_vcpu *vcpu) { - struct ap_queue_status status = {}; + union ap_queue_status_reg status = {}; crypto_hook pqap_hook; unsigned long reg0; int ret; @@ -662,8 +662,8 @@ static int handle_pqap(struct kvm_vcpu *vcpu) * No hook means no driver to enable the SIE CRYCB and no queues. * We send this response to the guest. */ - status.response_code = 0x01; - memcpy(&vcpu->run->s.regs.gprs[1], &status, sizeof(status)); + status.status.response_code = 0x01; + vcpu->run->s.regs.gprs[1] = status.value; kvm_s390_set_psw_cc(vcpu, 3); return 0; } From 997ca6555b9fc38a4048fcc477e5f3a26cbe4415 Mon Sep 17 00:00:00 2001 From: Selvin Xavier Date: Wed, 4 Nov 2026 12:02:44 -0800 Subject: [PATCH 0289/2102] RDMA/uverbs: Zero the QP attrs in ib_uverbs_query_qp ib_uverbs_query_qp() allocates qp_attr and qp_init_attr without zeroing and copies fields such as alt_ah_attr, path_mig_state and sq_draining to userspace. Drivers are not required to set every field in their query_qp() callback, so uninitialized kernel heap memory can leak. Allocate both structures zeroed. Fixes: 7ccc9a24e012 ("IB/uverbs: Support for query QP from userspace") Signed-off-by: Selvin Xavier Link: https://patch.msgid.link/20261104200244.52979-1-selvin.xavier@broadcom.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/core/uverbs_cmd.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/infiniband/core/uverbs_cmd.c b/drivers/infiniband/core/uverbs_cmd.c index aca7c6ab55cd81..54da98431f40cf 100644 --- a/drivers/infiniband/core/uverbs_cmd.c +++ b/drivers/infiniband/core/uverbs_cmd.c @@ -1668,8 +1668,8 @@ static int ib_uverbs_query_qp(struct uverbs_attr_bundle *attrs) if (ret) return ret; - attr = kmalloc_obj(*attr); - init_attr = kmalloc_obj(*init_attr); + attr = kzalloc_obj(*attr); + init_attr = kzalloc_obj(*init_attr); if (!attr || !init_attr) { ret = -ENOMEM; goto out; From 5933d2311e477e33c485c21e593d02f4190708ee Mon Sep 17 00:00:00 2001 From: Akhil P Oommen Date: Sat, 24 Oct 2026 16:00:07 +0530 Subject: [PATCH 0290/2102] drm/msm/a6xx: Check BX dependency vote index a6xx_gmu_rpmh_arc_index() returns a signed error value. Check the result before passing it to FIELD_MODIFY(), which rejects a compiler-propagated negative value as too large for the field. Fixes: 020b8eaa1db8 ("drm/msm/a6xx: Add BX rail support to GMU dependency votes") Cc: stable@vger.kernel.org Reported-by: kernel test robot Closes: https://lore.kernel.org/oe-kbuild-all/202610070334.bYvBJSpj-lkp@intel.com/ Signed-off-by: Akhil P Oommen Reviewed-by: Konrad Dybcio Patchwork: https://patchwork.freedesktop.org/patch/762791/ Message-ID: <20261024-assorted-fixes-oct-v1-1-2977f974ddb7@oss.qualcomm.com> Signed-off-by: Rob Clark --- drivers/gpu/drm/msm/adreno/a6xx_gmu.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gmu.c b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c index 662f09bec9d523..9e02d6f939af69 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gmu.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c @@ -1867,6 +1867,9 @@ static int a6xx_gmu_rpmh_dep_votes_init(struct device *dev, u32 *votes, * back to the highest BX corner if none is high enough. */ bx = a6xx_gmu_rpmh_arc_index(dev, gbx, gbx_count, gx[index], true); + if (bx < 0) + return bx; + FIELD_MODIFY(GMU_BX_MASK, &votes[i], bx); } From 575c09d24b6b3759c4a15e6130788ac3dd7ca509 Mon Sep 17 00:00:00 2001 From: Jie Zhang Date: Sat, 24 Oct 2026 16:00:08 +0530 Subject: [PATCH 0291/2102] drm/msm/a6xx: Fix GMU shutdown idle check GPUBUSYIGNAHB only indicates GPU hardware busy status and does not cover the whole GPU subsystem. Use CXGXCPUBUSYIGNAHB instead so GMU shutdown waits until CX/GX/CPU busy activity is cleared. Also, increase the timeout to 100ms to match the downstream driver. Fixes: 4b565ca5a2cb ("drm/msm: Add A6XX device support") Cc: stable@vger.kernel.org Signed-off-by: Jie Zhang Signed-off-by: Akhil P Oommen Reviewed-by: Konrad Dybcio Patchwork: https://patchwork.freedesktop.org/patch/762793/ Message-ID: <20261024-assorted-fixes-oct-v1-2-2977f974ddb7@oss.qualcomm.com> Signed-off-by: Rob Clark --- drivers/gpu/drm/msm/adreno/a6xx_gmu.c | 4 ++-- drivers/gpu/drm/msm/registers/adreno/a6xx_gmu.xml | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gmu.c b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c index 9e02d6f939af69..7e80670736a63f 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gmu.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c @@ -1461,8 +1461,8 @@ static void a6xx_gmu_shutdown(struct a6xx_gmu *gmu) ret = gmu_poll_timeout(gmu, REG_A6XX_GPU_GMU_AO_GPU_CX_BUSY_STATUS, val, - !(val & A6XX_GPU_GMU_AO_GPU_CX_BUSY_STATUS_GPUBUSYIGNAHB), - 100, 10000); + !(val & A6XX_GPU_GMU_AO_GPU_CX_BUSY_STATUS_CXGXCPUBUSYIGNAHB), + 100, 100000); /* * Let the user know we failed to slumber but don't worry too diff --git a/drivers/gpu/drm/msm/registers/adreno/a6xx_gmu.xml b/drivers/gpu/drm/msm/registers/adreno/a6xx_gmu.xml index b3082738c99d30..786fd7d2f67437 100644 --- a/drivers/gpu/drm/msm/registers/adreno/a6xx_gmu.xml +++ b/drivers/gpu/drm/msm/registers/adreno/a6xx_gmu.xml @@ -224,6 +224,7 @@ xsi:schemaLocation="https://gitlab.freedesktop.org/freedreno/ rules-fd.xsd"> + From 0989920b0904cc27ee79dbcdc384aef49298bde3 Mon Sep 17 00:00:00 2001 From: Jie Zhang Date: Sat, 24 Oct 2026 16:00:09 +0530 Subject: [PATCH 0292/2102] drm/msm/a6xx: Fix stale boot up BW vote An initial bus bandwidth is voted during boot to bring up the GMU. In GPUs where the GMU drives bandwidth scaling, this boot-time BW vote is redundant and can be removed. Fixes: 7047e655a567 ("drm/msm: adreno: find bandwidth index of OPP and set it along freq index") Cc: stable@vger.kernel.org Signed-off-by: Jie Zhang Signed-off-by: Akhil P Oommen Acked-by: Konrad Dybcio Patchwork: https://patchwork.freedesktop.org/patch/762796/ Message-ID: <20261024-assorted-fixes-oct-v1-3-2977f974ddb7@oss.qualcomm.com> Signed-off-by: Rob Clark --- drivers/gpu/drm/msm/adreno/a6xx_gmu.c | 16 +++++++++++++--- drivers/gpu/drm/msm/adreno/a6xx_gmu.h | 1 + drivers/gpu/drm/msm/adreno/a6xx_hfi.c | 2 +- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gmu.c b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c index 7e80670736a63f..991db3c9cd9680 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gmu.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c @@ -76,6 +76,13 @@ static irqreturn_t a6xx_hfi_irq(int irq, void *data) return IRQ_HANDLED; } +bool a6xx_gmu_scales_bw(struct a6xx_gmu *gmu) +{ + struct a6xx_gpu *a6xx_gpu = container_of(gmu, struct a6xx_gpu, gmu); + + return a6xx_gpu->base.info->a6xx->bcms && gmu->nr_gpu_bws > 1; +} + bool a6xx_gmu_sptprac_is_on(struct a6xx_gmu *gmu) { u32 val; @@ -169,7 +176,6 @@ void a6xx_gmu_set_freq(struct msm_gpu *gpu, struct dev_pm_opp *opp, bool suspended) { struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu); - const struct a6xx_info *info = adreno_gpu->info->a6xx; struct a6xx_gpu *a6xx_gpu = to_a6xx_gpu(adreno_gpu); struct a6xx_gmu *gmu = &a6xx_gpu->gmu; u32 perf_index; @@ -187,7 +193,7 @@ void a6xx_gmu_set_freq(struct msm_gpu *gpu, struct dev_pm_opp *opp, break; /* If enabled, find the corresponding DDR bandwidth index */ - if (info->bcms && gmu->nr_gpu_bws > 1) { + if (a6xx_gmu_scales_bw(gmu)) { unsigned int bw = dev_pm_opp_get_bw(opp, true, 0); for (bw_index = 0; bw_index < gmu->nr_gpu_bws - 1; bw_index++) { @@ -1393,6 +1399,10 @@ int a6xx_gmu_resume(struct a6xx_gpu *a6xx_gpu) /* Set the GPU to the current freq */ a6xx_gmu_set_initial_freq(gpu, gmu); + /* Clear the boot bus quota to allow GMU-driven BW scaling */ + if (a6xx_gmu_scales_bw(gmu)) + dev_pm_opp_set_opp(&gpu->pdev->dev, NULL); + return 0; disable_irq: @@ -1913,7 +1923,7 @@ static int a6xx_gmu_rpmh_votes_init(struct a6xx_gmu *gmu) gmu->gmu_freqs, gmu->nr_gmu_freqs, "cx.lvl", "mx.lvl"); /* Build the interconnect votes */ - if (info->bcms && gmu->nr_gpu_bws > 1) + if (a6xx_gmu_scales_bw(gmu)) ret |= a6xx_gmu_rpmh_bw_votes_init(adreno_gpu, info, gmu); return ret; diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gmu.h b/drivers/gpu/drm/msm/adreno/a6xx_gmu.h index d3f6cd8b97413d..b9e966e602e236 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gmu.h +++ b/drivers/gpu/drm/msm/adreno/a6xx_gmu.h @@ -239,6 +239,7 @@ bool a6xx_gmu_gx_is_on(struct adreno_gpu *adreno_gpu); bool a7xx_gmu_gx_is_on(struct adreno_gpu *adreno_gpu); bool a8xx_gmu_gx_is_on(struct adreno_gpu *adreno_gpu); bool a6xx_gmu_sptprac_is_on(struct a6xx_gmu *gmu); +bool a6xx_gmu_scales_bw(struct a6xx_gmu *gmu); void a6xx_sptprac_disable(struct a6xx_gmu *gmu); int a6xx_sptprac_enable(struct a6xx_gmu *gmu); diff --git a/drivers/gpu/drm/msm/adreno/a6xx_hfi.c b/drivers/gpu/drm/msm/adreno/a6xx_hfi.c index 6b34e704a70d0e..ac684d72d2b4ed 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_hfi.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_hfi.c @@ -810,7 +810,7 @@ static int a6xx_hfi_send_bw_table(struct a6xx_gmu *gmu) if (!msg) return -ENOMEM; - if (info->bcms && gmu->nr_gpu_bws > 1) + if (a6xx_gmu_scales_bw(gmu)) a6xx_generate_bw_table(info, gmu, msg); else if (adreno_is_a618(adreno_gpu)) a618_build_bw_table(msg); From 393dc23e41040a0ceba474135dc3f1fe23c2de59 Mon Sep 17 00:00:00 2001 From: Jie Zhang Date: Sat, 24 Oct 2026 16:00:10 +0530 Subject: [PATCH 0293/2102] drm/msm/devfreq: Record idle_time at GPU idle onset Setting df->idle_time in msm_devfreq_idle_work() means a cancelled idle_work leaves a stale timestamp, causing idle_time to accumulate across idle cycles and potentially trigger a spurious devfreq boost. Move the assignment to msm_devfreq_idle() so the timestamp always reflects the actual GPU idle onset. Fixes: 658f4c829688 ("drm/msm/devfreq: Add 1ms delay before clamping freq") Cc: stable@vger.kernel.org Signed-off-by: Jie Zhang Signed-off-by: Akhil P Oommen Reviewed-by: Konrad Dybcio Patchwork: https://patchwork.freedesktop.org/patch/762797/ Message-ID: <20261024-assorted-fixes-oct-v1-4-2977f974ddb7@oss.qualcomm.com> Signed-off-by: Rob Clark --- drivers/gpu/drm/msm/msm_gpu_devfreq.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/msm/msm_gpu_devfreq.c b/drivers/gpu/drm/msm/msm_gpu_devfreq.c index 2e1d5c3432728c..f3c664b20a1bad 100644 --- a/drivers/gpu/drm/msm/msm_gpu_devfreq.c +++ b/drivers/gpu/drm/msm/msm_gpu_devfreq.c @@ -357,7 +357,6 @@ static void msm_devfreq_idle_work(struct kthread_work *work) if (priv->gpu_clamp_to_idle) msm_devfreq_target(&gpu->pdev->dev, &target_freq, 0); - df->idle_time = ktime_get(); df->idle_freq = idle_freq; mutex_unlock(&df->devfreq->lock); @@ -370,6 +369,8 @@ void msm_devfreq_idle(struct msm_gpu *gpu) if (!has_devfreq(gpu)) return; + df->idle_time = ktime_get(); + msm_hrtimer_queue_work(&df->idle_work, ms_to_ktime(1), HRTIMER_MODE_REL); } From 3c3050df314ad790baa5aa719f2c266434bd4dce Mon Sep 17 00:00:00 2001 From: Jie Zhang Date: Sat, 24 Oct 2026 16:00:11 +0530 Subject: [PATCH 0294/2102] drm/msm: Fix sched_prio inversion within a ring Commit 38f922a563aa ("drm/sched: Reverse run-queue priority enumeration") reversed the values of each sched priority. But it didn't update msm_gpu_convert_priority() to match the new order. This results in incorrect sched priorities within a ring. To fix this, remove the inversion logic and add an offset of DRM_SCHED_PRIORITY_HIGH to keep the range within [HIGH..LOW], reserving KERNEL for internal submissions. Fixes: 38f922a563aa ("drm/sched: Reverse run-queue priority enumeration") Cc: stable@vger.kernel.org Signed-off-by: Jie Zhang Signed-off-by: Akhil P Oommen Acked-by: Konrad Dybcio Patchwork: https://patchwork.freedesktop.org/patch/762800/ Message-ID: <20261024-assorted-fixes-oct-v1-5-2977f974ddb7@oss.qualcomm.com> Signed-off-by: Rob Clark --- drivers/gpu/drm/msm/msm_gpu.h | 24 ++++++++++-------------- drivers/gpu/drm/msm/msm_submitqueue.c | 2 +- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/msm/msm_gpu.h b/drivers/gpu/drm/msm/msm_gpu.h index d27d54bdb7a71b..bc5b31eb1eca8e 100644 --- a/drivers/gpu/drm/msm/msm_gpu.h +++ b/drivers/gpu/drm/msm/msm_gpu.h @@ -522,17 +522,18 @@ msm_context_is_vmbind(struct msm_context *ctx) * @sched_prio: [out] the gpu scheduler priority level which the userspace * priority maps to * - * With drm/scheduler providing it's own level of prioritization, our total + * With drm/scheduler providing its own level of prioritization, our total * number of available priority levels is (nr_rings * NR_SCHED_PRIORITIES). - * Each ring is associated with it's own scheduler instance. However, our - * UABI is that lower numerical values are higher priority. So mapping the - * single userspace priority level into ring_nr and sched_prio takes some - * care. The userspace provided priority (when a submitqueue is created) - * is mapped to ring nr and scheduler priority as such: + * Each ring is associated with its own scheduler instance. Both the MSM + * UABI and drm/scheduler use lower-numeric = higher-priority, so the mapping + * from a single userspace priority level into ring_nr and sched_prio is: * * ring_nr = userspace_prio / NR_SCHED_PRIORITIES - * sched_prio = NR_SCHED_PRIORITIES - - * (userspace_prio % NR_SCHED_PRIORITIES) - 1 + * sched_prio = (userspace_prio % NR_SCHED_PRIORITIES) + DRM_SCHED_PRIORITY_HIGH + * + * The offset by DRM_SCHED_PRIORITY_HIGH keeps the range within [HIGH..LOW], + * intentionally excluding DRM_SCHED_PRIORITY_KERNEL which is reserved for + * kernel-internal submissions. * * This allows generations without preemption (nr_rings==1) to have some * amount of prioritization, and provides more priority levels for gens @@ -547,16 +548,11 @@ static inline int msm_gpu_convert_priority(struct msm_gpu *gpu, int prio, rn = div_u64_rem(prio, NR_SCHED_PRIORITIES, &sp); - /* invert sched priority to map to higher-numeric-is-higher- - * priority convention - */ - sp = NR_SCHED_PRIORITIES - sp - 1; - if (rn >= gpu->nr_rings) return -EINVAL; *ring_nr = rn; - *sched_prio = sp; + *sched_prio = sp + DRM_SCHED_PRIORITY_HIGH; return 0; } diff --git a/drivers/gpu/drm/msm/msm_submitqueue.c b/drivers/gpu/drm/msm/msm_submitqueue.c index d307cdd17d908f..8d550d281704e8 100644 --- a/drivers/gpu/drm/msm/msm_submitqueue.c +++ b/drivers/gpu/drm/msm/msm_submitqueue.c @@ -136,7 +136,7 @@ get_sched_entity(struct msm_context *ctx, struct msm_ringbuffer *ring, unsigned ring_nr, enum drm_sched_priority sched_prio) { static DEFINE_MUTEX(entity_lock); - unsigned idx = (ring_nr * NR_SCHED_PRIORITIES) + sched_prio; + unsigned idx = (ring_nr * NR_SCHED_PRIORITIES) + (sched_prio - DRM_SCHED_PRIORITY_HIGH); /* We should have already validated that the requested priority is * valid by the time we get here. From 034b2e10481fa8900668eacea00bdb2efe2bc125 Mon Sep 17 00:00:00 2001 From: Akhil P Oommen Date: Sat, 24 Oct 2026 16:00:12 +0530 Subject: [PATCH 0295/2102] drm/msm/a6xx: Reset preemption records across suspend The preemption records are initialised only once at probe time. On every resume, a6xx_preempt_hw_init() and a8xx_preempt_hw_init() refresh only a subset of the fields (rptr, wptr, rptr_addr, info, data, rbase). Whatever else the CP wrote into the record before the GPU was power-collapsed is left in place and gets consumed again by the CP on the next preemption, now carrying stale context state. To fix this, zero the whole preemption record on suspend and fully initialise every field in the hw_init path. Fixes: e7ae83da4a28 ("drm/msm/a6xx: Implement preemption for a7xx targets") Cc: stable@vger.kernel.org Signed-off-by: Akhil P Oommen Tested-by: Connor Abbott Patchwork: https://patchwork.freedesktop.org/patch/762801/ Message-ID: <20261024-assorted-fixes-oct-v1-6-2977f974ddb7@oss.qualcomm.com> Signed-off-by: Rob Clark --- drivers/gpu/drm/msm/adreno/a6xx_gpu.c | 2 ++ drivers/gpu/drm/msm/adreno/a6xx_gpu.h | 1 + drivers/gpu/drm/msm/adreno/a6xx_preempt.c | 37 +++++++++++++---------- drivers/gpu/drm/msm/adreno/a8xx_preempt.c | 11 +++++-- 4 files changed, 32 insertions(+), 19 deletions(-) diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gpu.c b/drivers/gpu/drm/msm/adreno/a6xx_gpu.c index 92e8c8abb86da5..3e4afaa5345fda 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gpu.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_gpu.c @@ -2248,6 +2248,7 @@ static int a6xx_gmu_pm_suspend(struct msm_gpu *gpu) for (i = 0; i < gpu->nr_rings; i++) a6xx_gpu->shadow[i] = 0; + a6xx_preempt_record_reset(gpu); gpu->suspend_count++; return 0; @@ -2287,6 +2288,7 @@ static int a6xx_pm_suspend(struct msm_gpu *gpu) for (i = 0; i < gpu->nr_rings; i++) a6xx_gpu->shadow[i] = 0; + a6xx_preempt_record_reset(gpu); gpu->suspend_count++; return 0; diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gpu.h b/drivers/gpu/drm/msm/adreno/a6xx_gpu.h index 79912a33e17cf2..62a19e22e23003 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gpu.h +++ b/drivers/gpu/drm/msm/adreno/a6xx_gpu.h @@ -305,6 +305,7 @@ void a6xx_preempt_hw_init(struct msm_gpu *gpu); void a6xx_preempt_trigger(struct msm_gpu *gpu); void a6xx_preempt_irq(struct msm_gpu *gpu); void a6xx_preempt_fini(struct msm_gpu *gpu); +void a6xx_preempt_record_reset(struct msm_gpu *gpu); void a6xx_emit_set_pseudo_reg(struct msm_ringbuffer *ring, struct a6xx_gpu *a6xx_gpu, struct msm_gpu_submitqueue *queue); int a6xx_preempt_submitqueue_setup(struct msm_gpu *gpu, diff --git a/drivers/gpu/drm/msm/adreno/a6xx_preempt.c b/drivers/gpu/drm/msm/adreno/a6xx_preempt.c index 1e599d4ddea1c8..df8d4f3e8d4c1a 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_preempt.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_preempt.c @@ -140,12 +140,17 @@ void a6xx_preempt_hw_init(struct msm_gpu *gpu) for (i = 0; i < gpu->nr_rings; i++) { struct a6xx_preempt_record *record_ptr = a6xx_gpu->preempt[i]; - record_ptr->wptr = 0; - record_ptr->rptr = 0; - record_ptr->rptr_addr = shadowptr(a6xx_gpu, gpu->rb[i]); + record_ptr->magic = A6XX_PREEMPT_RECORD_MAGIC; record_ptr->info = 0; + record_ptr->errno = 0; record_ptr->data = 0; + record_ptr->cntl = MSM_GPU_RB_CNTL_DEFAULT; + record_ptr->rptr = 0; + record_ptr->wptr = 0; + record_ptr->rptr_addr = shadowptr(a6xx_gpu, gpu->rb[i]); record_ptr->rbase = gpu->rb[i]->iova; + record_ptr->counter = 0; + record_ptr->bv_rptr_addr = rbmemptr(gpu->rb[i], bv_rptr); } /* Write a 0 to signal that we aren't switching pagetables */ @@ -163,6 +168,19 @@ void a6xx_preempt_hw_init(struct msm_gpu *gpu) a6xx_gpu->cur_ring = gpu->rb[0]; } +void a6xx_preempt_record_reset(struct msm_gpu *gpu) +{ + struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu); + struct a6xx_gpu *a6xx_gpu = to_a6xx_gpu(adreno_gpu); + int i; + + if (gpu->nr_rings == 1) + return; + + for (i = 0; i < gpu->nr_rings; i++) + memset(a6xx_gpu->preempt[i], 0, a6xx_gpu->preempt_bo[i]->size); +} + void a6xx_preempt_trigger(struct msm_gpu *gpu) { struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu); @@ -302,8 +320,6 @@ static int preempt_init_ring(struct a6xx_gpu *a6xx_gpu, a6xx_gpu->preempt_iova[ring->id] = iova; a6xx_gpu->preempt[ring->id] = ptr; - struct a6xx_preempt_record *record_ptr = ptr; - ptr = msm_gem_kernel_new(gpu->dev, PREEMPT_SMMU_INFO_SIZE, MSM_BO_WC | MSM_BO_MAP_PRIV | MSM_BO_GPU_READONLY, @@ -329,17 +345,6 @@ static int preempt_init_ring(struct a6xx_gpu *a6xx_gpu, smmu_info_ptr->asid = 0xdecafbad; smmu_info_ptr->context_idr = 0; - /* Set up the defaults on the preemption record */ - record_ptr->magic = A6XX_PREEMPT_RECORD_MAGIC; - record_ptr->info = 0; - record_ptr->data = 0; - record_ptr->rptr = 0; - record_ptr->wptr = 0; - record_ptr->cntl = MSM_GPU_RB_CNTL_DEFAULT; - record_ptr->rbase = ring->iova; - record_ptr->counter = 0; - record_ptr->bv_rptr_addr = rbmemptr(ring, bv_rptr); - return 0; } diff --git a/drivers/gpu/drm/msm/adreno/a8xx_preempt.c b/drivers/gpu/drm/msm/adreno/a8xx_preempt.c index 6cb53a0718018e..0e0503ed54a1d7 100644 --- a/drivers/gpu/drm/msm/adreno/a8xx_preempt.c +++ b/drivers/gpu/drm/msm/adreno/a8xx_preempt.c @@ -121,12 +121,17 @@ void a8xx_preempt_hw_init(struct msm_gpu *gpu) for (i = 0; i < gpu->nr_rings; i++) { struct a6xx_preempt_record *record_ptr = a6xx_gpu->preempt[i]; - record_ptr->wptr = 0; - record_ptr->rptr = 0; - record_ptr->rptr_addr = shadowptr(a6xx_gpu, gpu->rb[i]); + record_ptr->magic = A6XX_PREEMPT_RECORD_MAGIC; record_ptr->info = 0; + record_ptr->errno = 0; record_ptr->data = 0; + record_ptr->cntl = MSM_GPU_RB_CNTL_DEFAULT; + record_ptr->rptr = 0; + record_ptr->wptr = 0; + record_ptr->rptr_addr = shadowptr(a6xx_gpu, gpu->rb[i]); record_ptr->rbase = gpu->rb[i]->iova; + record_ptr->counter = 0; + record_ptr->bv_rptr_addr = rbmemptr(gpu->rb[i], bv_rptr); } /* Write a 0 to signal that we aren't switching pagetables */ From 1c3ce33b3d3449f0a05816c636136a91b32a3ee2 Mon Sep 17 00:00:00 2001 From: Akhil P Oommen Date: Sat, 24 Oct 2026 16:00:13 +0530 Subject: [PATCH 0296/2102] drm/msm/a6xx: Request CLX enable from secure world The CLX (Current Limit Extension) feature also requires the secure world to enable it via the GPU init regs SCM call. Without the QCOM_SCM_GPU_CLX_EN_REQ flag, the CLX tables sent to the GMU over HFI are not effective. Set QCOM_SCM_GPU_CLX_EN_REQ in the SCM request on GPUs that have a CLX table in their catalog entry. Fixes: 967e62fbeecc ("drm/msm/a6xx: Add HFI support for CLX feature") Signed-off-by: Akhil P Oommen Reviewed-by: Konrad Dybcio Patchwork: https://patchwork.freedesktop.org/patch/762804/ Message-ID: <20261024-assorted-fixes-oct-v1-7-2977f974ddb7@oss.qualcomm.com> Signed-off-by: Rob Clark --- drivers/gpu/drm/msm/adreno/a6xx_gmu.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gmu.c b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c index 991db3c9cd9680..a1561ca41a5b39 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gmu.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c @@ -1247,8 +1247,12 @@ static int a6xx_gmu_secure_init(struct a6xx_gpu *a6xx_gpu) goto done; } - ret = qcom_scm_gpu_init_regs(QCOM_SCM_GPU_ALWAYS_EN_REQ | - QCOM_SCM_GPU_TSENSE_EN_REQ); + u32 gpu_req = QCOM_SCM_GPU_ALWAYS_EN_REQ | QCOM_SCM_GPU_TSENSE_EN_REQ; + + if (adreno_gpu->info->a6xx->clx_tbl) + gpu_req |= QCOM_SCM_GPU_CLX_EN_REQ; + + ret = qcom_scm_gpu_init_regs(gpu_req); if (ret) { dev_warn_once(gpu->dev->dev, "SCM call failed\n"); From 487ba4c521ae900961e5daf4f43c325877b4b195 Mon Sep 17 00:00:00 2001 From: Akhil P Oommen Date: Sat, 24 Oct 2026 16:00:14 +0530 Subject: [PATCH 0297/2102] drm/msm/a8xx: Add AQE firmware to Adreno X2-90 GPU Update the catalog to add AQE firmware to the Adreno X2-90 GPU. Signed-off-by: Akhil P Oommen Reviewed-by: Konrad Dybcio Patchwork: https://patchwork.freedesktop.org/patch/762805/ Message-ID: <20261024-assorted-fixes-oct-v1-8-2977f974ddb7@oss.qualcomm.com> Signed-off-by: Rob Clark --- drivers/gpu/drm/msm/adreno/a8xx_catalog.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/gpu/drm/msm/adreno/a8xx_catalog.c b/drivers/gpu/drm/msm/adreno/a8xx_catalog.c index 55a805ab438cc1..775aca1964eefa 100644 --- a/drivers/gpu/drm/msm/adreno/a8xx_catalog.c +++ b/drivers/gpu/drm/msm/adreno/a8xx_catalog.c @@ -1582,6 +1582,7 @@ static const struct adreno_info a8xx_gpus[] = { .fw = { [ADRENO_FW_SQE] = "gen80100_sqe.fw", [ADRENO_FW_GMU] = "gen80100_gmu.bin", + [ADRENO_FW_AQE] = "gen80100_aqe.fw", }, .gmem = 21 * SZ_1M, .inactive_period = DRM_MSM_INACTIVE_PERIOD, From 11d0f2eb20e7b39e2b6670b8af236e9aea5e6c4f Mon Sep 17 00:00:00 2001 From: Rob Clark Date: Wed, 28 Oct 2026 17:16:00 -0700 Subject: [PATCH 0298/2102] drm/msm/adreno: Soften no-firmware message It isn't _necessarily_ an error, the driver will try again each time the device file is opened. But if you don't have GPU fw in the initrd, you end up seeing this error message at least once. Which seems to confuse users. So try to re-word it slightly. Signed-off-by: Rob Clark Reviewed-by: Dmitry Baryshkov Reviewed-by: Konrad Dybcio Reviewed-by: Hans de Goede Patchwork: https://patchwork.freedesktop.org/patch/763881/ Message-ID: <20261029001601.82269-1-robin.clark@oss.qualcomm.com> --- drivers/gpu/drm/msm/adreno/adreno_gpu.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/msm/adreno/adreno_gpu.c b/drivers/gpu/drm/msm/adreno/adreno_gpu.c index f7882bb8028d86..54f33747523170 100644 --- a/drivers/gpu/drm/msm/adreno/adreno_gpu.c +++ b/drivers/gpu/drm/msm/adreno/adreno_gpu.c @@ -560,7 +560,7 @@ adreno_request_fw(struct adreno_gpu *adreno_gpu, const char *fwname) adreno_gpu->fwloc = FW_LOCATION_NEW; goto out; } else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) { - DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n", + DRM_DEV_INFO(drm->dev, "failed to load %s: %d (will try again later)\n", newname, ret); fw = ERR_PTR(ret); goto out; @@ -580,7 +580,7 @@ adreno_request_fw(struct adreno_gpu *adreno_gpu, const char *fwname) adreno_gpu->fwloc = FW_LOCATION_LEGACY; goto out; } else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) { - DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n", + DRM_DEV_INFO(drm->dev, "failed to load %s: %d (will try again later)\n", fwname, ret); fw = ERR_PTR(ret); goto out; @@ -601,14 +601,14 @@ adreno_request_fw(struct adreno_gpu *adreno_gpu, const char *fwname) adreno_gpu->fwloc = FW_LOCATION_HELPER; goto out; } else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) { - DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n", + DRM_DEV_INFO(drm->dev, "failed to load %s: %d (will try again later)\n", newname, ret); fw = ERR_PTR(ret); goto out; } } - DRM_DEV_ERROR(drm->dev, "failed to load %s\n", fwname); + DRM_DEV_INFO(drm->dev, "failed to load %s (will try again later)\n", fwname); fw = ERR_PTR(-ENOENT); out: kfree(newname); From 4f0af27c3aef5a9480712cbac4bee14f7509ae5f Mon Sep 17 00:00:00 2001 From: Rob Clark Date: Mon, 2 Nov 2026 09:19:57 -0800 Subject: [PATCH 0299/2102] drm/msm/gem: Fix VM_BIND range check Use size_add() to guard against overflow. Reported-by: Konrad Dybcio Fixes: 3a3bef68a6c1 ("drm/msm: Fix missing VM_BIND offset/range validation") Reviewed-by: Dmitry Baryshkov Signed-off-by: Rob Clark Reviewed-by: Konrad Dybcio Patchwork: https://patchwork.freedesktop.org/patch/765329/ Message-ID: <20261102172001.508440-2-robin.clark@oss.qualcomm.com> --- drivers/gpu/drm/msm/msm_gem_vma.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/msm/msm_gem_vma.c b/drivers/gpu/drm/msm/msm_gem_vma.c index f687a629629d34..bd1c3ceeea51e5 100644 --- a/drivers/gpu/drm/msm/msm_gem_vma.c +++ b/drivers/gpu/drm/msm/msm_gem_vma.c @@ -1012,10 +1012,10 @@ lookup_op(struct msm_vm_bind_job *job, const struct drm_msm_vm_bind_op *op) if (invalid_alignment(op->iova)) ret = UERR(EINVAL, dev, "invalid address: %016llx\n", op->iova); - if (invalid_alignment(op->obj_offset)) + if (invalid_alignment(op->obj_offset) || (op->obj_offset > SIZE_MAX)) ret = UERR(EINVAL, dev, "invalid bo_offset: %016llx\n", op->obj_offset); - if (invalid_alignment(op->range)) + if (invalid_alignment(op->range) || (op->range > SIZE_MAX) || !op->range) ret = UERR(EINVAL, dev, "invalid range: %016llx\n", op->range); if (!drm_gpuvm_range_valid(job->vm, op->iova, op->range)) @@ -1118,7 +1118,7 @@ vm_bind_job_lookup_ops(struct msm_vm_bind_job *job, struct drm_msm_vm_bind *args op->obj = obj; cnt++; - if ((op->range + op->obj_offset) > obj->size) { + if (size_add(op->range, op->obj_offset) > obj->size) { ret = UERR(EINVAL, dev, "invalid range: %016llx + %016llx > %016zx\n", op->range, op->obj_offset, obj->size); goto out_unlock; From b3b44f7508c7f01273ba773595b7787883ceb4e0 Mon Sep 17 00:00:00 2001 From: Rob Clark Date: Mon, 2 Nov 2026 09:19:58 -0800 Subject: [PATCH 0300/2102] drm/msm/gem: Disallow nr_bos for VM_BIND contexts If using VM_BIND, it is invalid to attach BOs to a GEM_SUBMIT ioctl. Only the VM_BIND ioctl should be used for binding objects. Fixes: 2e6a8a1fe2b2 ("drm/msm: Add VM_BIND ioctl") Reviewed-by: Dmitry Baryshkov Signed-off-by: Rob Clark Reviewed-by: Konrad Dybcio Patchwork: https://patchwork.freedesktop.org/patch/765330/ Message-ID: <20261102172001.508440-3-robin.clark@oss.qualcomm.com> --- drivers/gpu/drm/msm/msm_gem_submit.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/msm/msm_gem_submit.c b/drivers/gpu/drm/msm/msm_gem_submit.c index 5862db05297a71..c03410c568a5a4 100644 --- a/drivers/gpu/drm/msm/msm_gem_submit.c +++ b/drivers/gpu/drm/msm/msm_gem_submit.c @@ -272,7 +272,7 @@ static int submit_lock_objects_vmbind(struct msm_gem_submit *submit) struct drm_exec *exec = &submit->exec; int ret = 0; - drm_exec_init(&submit->exec, flags, submit->nr_bos); + drm_exec_init(&submit->exec, flags, 0); submit->has_exec = true; drm_exec_until_all_locked (&submit->exec) { @@ -589,6 +589,9 @@ int msm_ioctl_gem_submit(struct drm_device *dev, void *data, return -EINVAL; } + if (msm_context_is_vmbind(ctx) && args->nr_bos) + return UERR(EINVAL, dev, "invalid nr_bos, must be zero for VM_BIND contexts"); + queue = msm_submitqueue_get(ctx, args->queueid); if (!queue) return -ENOENT; From 31708945d3647ad29f91def9d40dafa149ac66f1 Mon Sep 17 00:00:00 2001 From: Rob Clark Date: Mon, 2 Nov 2026 09:19:59 -0800 Subject: [PATCH 0301/2102] drm/msm/gem: Decrement loop idx if handle lookup fails In the out_unlock unlock loop, we should skip the op which still has the gem handle instead of gem obj ptr. Fixes: 2e6a8a1fe2b2 ("drm/msm: Add VM_BIND ioctl") Signed-off-by: Rob Clark Reviewed-by: Konrad Dybcio Patchwork: https://patchwork.freedesktop.org/patch/765328/ Message-ID: <20261102172001.508440-4-robin.clark@oss.qualcomm.com> --- drivers/gpu/drm/msm/msm_gem_vma.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/gpu/drm/msm/msm_gem_vma.c b/drivers/gpu/drm/msm/msm_gem_vma.c index bd1c3ceeea51e5..3177461d7ad092 100644 --- a/drivers/gpu/drm/msm/msm_gem_vma.c +++ b/drivers/gpu/drm/msm/msm_gem_vma.c @@ -1110,6 +1110,7 @@ vm_bind_job_lookup_ops(struct msm_vm_bind_job *job, struct drm_msm_vm_bind *args obj = idr_find(&file->object_idr, op->handle); if (!obj) { ret = UERR(EINVAL, dev, "invalid handle %u at index %u\n", op->handle, i); + i--; goto out_unlock; } From b22f5d783eadbebe90481db0c48cecf719e71dad Mon Sep 17 00:00:00 2001 From: Rob Clark Date: Mon, 2 Nov 2026 09:20:00 -0800 Subject: [PATCH 0302/2102] drm/msm/gem: Clear nr_ops in lookup_ops() failure path We've already dropped the references taken in the handle lookup loop, so we don't want to drop them again in msm_vma_job_free(). Signed-off-by: Rob Clark Fixes: 2e6a8a1fe2b2 ("drm/msm: Add VM_BIND ioctl") Patchwork: https://patchwork.freedesktop.org/patch/765324/ Message-ID: <20261102172001.508440-5-robin.clark@oss.qualcomm.com> --- drivers/gpu/drm/msm/msm_gem_vma.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/msm/msm_gem_vma.c b/drivers/gpu/drm/msm/msm_gem_vma.c index 3177461d7ad092..8b702422030afe 100644 --- a/drivers/gpu/drm/msm/msm_gem_vma.c +++ b/drivers/gpu/drm/msm/msm_gem_vma.c @@ -1088,7 +1088,6 @@ vm_bind_job_lookup_ops(struct msm_vm_bind_job *job, struct drm_msm_vm_bind *args } if (ret) { - job->nr_ops = 0; goto out; } @@ -1143,6 +1142,9 @@ vm_bind_job_lookup_ops(struct msm_vm_bind_job *job, struct drm_msm_vm_bind *args } } out: + if (ret) + job->nr_ops = 0; + return ret; } From 6e0bbda7b97bc8fa60ec2a3b43732f4033142109 Mon Sep 17 00:00:00 2001 From: Rob Clark Date: Wed, 4 Nov 2026 13:20:47 -0800 Subject: [PATCH 0303/2102] drm/msm/a8xx: Fix 1/2b alpha filtering precision Need to set b25 in TPL1_DBG_ECO_CNTL1 on all gen8. Reported-by: Danylo Piliaiev Signed-off-by: Rob Clark Reviewed-by: Akhil P Oommen Patchwork: https://patchwork.freedesktop.org/patch/766378/ Message-ID: <20261104212048.21010-1-robin.clark@oss.qualcomm.com> --- drivers/gpu/drm/msm/adreno/a8xx_catalog.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/msm/adreno/a8xx_catalog.c b/drivers/gpu/drm/msm/adreno/a8xx_catalog.c index 775aca1964eefa..529b9b53a72315 100644 --- a/drivers/gpu/drm/msm/adreno/a8xx_catalog.c +++ b/drivers/gpu/drm/msm/adreno/a8xx_catalog.c @@ -54,7 +54,7 @@ static const struct adreno_reglist_pipe a830_nonctxt_regs[] = { { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10000000, BIT(PIPE_NONE) }, /* Enable cubemap small miplevel optimization settings */ /* BIT(26): Disable final clamp for bicubic filtering */ - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x04000724, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x06000724, BIT(PIPE_NONE) }, /* Disable tag bank id hashing */ { REG_A6XX_UCHE_MODE_CNTL, 0x00080000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, @@ -328,7 +328,7 @@ static const struct adreno_reglist_pipe x285_nonctxt_regs[] = { { REG_A7XX_SP_READ_SEL, 0x0001ff00, BIT(PIPE_NONE) }, { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10000000, BIT(PIPE_NONE) }, /* BIT(26): Disable final clamp for bicubic filtering */ - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x04000720, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x06000720, BIT(PIPE_NONE) }, { REG_A6XX_UCHE_MODE_CNTL, 0x80080000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_CACHE_WAYS, 0x00000800, BIT(PIPE_NONE) }, @@ -470,7 +470,7 @@ static const struct adreno_reglist_pipe a810_nonctxt_regs[] = { { REG_A6XX_SP_PERFCTR_SHADER_MASK, 0x0000003f, BIT(PIPE_NONE) }, { REG_A7XX_SP_HLSQ_TIMEOUT_THRESHOLD_DP, 0x00000080, BIT(PIPE_NONE) }, { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10100000, BIT(PIPE_NONE) }, - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x04000724, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x06000724, BIT(PIPE_NONE) }, { REG_A6XX_UCHE_MODE_CNTL, 0x00020000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_CACHE_WAYS, 0x00000800, BIT(PIPE_NONE) }, @@ -825,7 +825,7 @@ static const struct adreno_reglist_pipe a840_nonctxt_regs[] = { { REG_A7XX_SP_READ_SEL, 0x0001ff00, BIT(PIPE_NONE) }, { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10100000, BIT(PIPE_NONE) }, /* BIT(26): Disable final clamp for bicubic filtering */ - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x04000720, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x06000720, BIT(PIPE_NONE) }, { REG_A6XX_UCHE_MODE_CNTL, 0x80080000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_CACHE_WAYS, 0x00000800, BIT(PIPE_NONE) }, @@ -1211,7 +1211,7 @@ static const struct adreno_reglist_pipe a845_nonctxt_regs[] = { { REG_A7XX_SP_READ_SEL, 0x0001ff00, BIT(PIPE_NONE) }, { REG_A8XX_SP_L0_PERF_TUNE, 0x00000024, BIT(PIPE_NONE) }, { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10100000, BIT(PIPE_NONE) }, - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x00000720, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x02000720, BIT(PIPE_NONE) }, { REG_A6XX_UCHE_MODE_CNTL, 0x80080000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_DBG_ECO_CNTL_0, BIT(31), BIT(PIPE_NONE) }, @@ -1270,7 +1270,7 @@ static const struct adreno_reglist_pipe a850_nonctxt_regs[] = { { REG_A7XX_SP_READ_SEL, 0x0001ff00, BIT(PIPE_NONE) }, { REG_A8XX_SP_L0_PERF_TUNE, 0x00000024, BIT(PIPE_NONE) }, { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10100000, BIT(PIPE_NONE) }, - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x00000720, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x02000720, BIT(PIPE_NONE) }, { REG_A6XX_UCHE_MODE_CNTL, 0x80080000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_DBG_ECO_CNTL_0, BIT(31), BIT(PIPE_NONE) }, From 1e59855738454b14021b64115f0090eafc7526ae Mon Sep 17 00:00:00 2001 From: Bart Van Assche Date: Mon, 26 Oct 2026 12:58:08 -0700 Subject: [PATCH 0304/2102] drm/msm: Fix a lock leak in msm_ioctl_gem_info_set_metadata() If krealloc() fails, msm_ioctl_gem_info_set_metadata() returns without unlocking the GEM object. Fix this by jumping to a new label that unlocks the GEM object before the buffer is freed. This bug has been detected by the Clang thread-safety analyzer. Fixes: 1c8c354098ea ("drm/msm: Add error handling for krealloc in metadata setup") Signed-off-by: Bart Van Assche Patchwork: https://patchwork.freedesktop.org/patch/763272/ Message-ID: <9671164f87138a0caf5c69b66129bbd6faf932f8.1793044688.git.bvanassche@acm.org> Signed-off-by: Rob Clark --- drivers/gpu/drm/msm/msm_drv.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/msm/msm_drv.c b/drivers/gpu/drm/msm/msm_drv.c index 5e8f3ce26b32c9..7ab808322be6f9 100644 --- a/drivers/gpu/drm/msm/msm_drv.c +++ b/drivers/gpu/drm/msm/msm_drv.c @@ -571,13 +571,14 @@ static int msm_ioctl_gem_info_set_metadata(struct drm_gem_object *obj, krealloc(msm_obj->metadata, metadata_size, GFP_KERNEL); if (!new_metadata) { ret = -ENOMEM; - goto out; + goto unlock; } msm_obj->metadata = new_metadata; msm_obj->metadata_size = metadata_size; memcpy(msm_obj->metadata, buf, metadata_size); +unlock: msm_gem_unlock(obj); out: From 7c739fe81758c076b298776357b88735d788901f Mon Sep 17 00:00:00 2001 From: Steffen Eiden Date: Tue, 3 Nov 2026 17:37:02 +0100 Subject: [PATCH 0305/2102] KVM: s390: arm64: Turn vcpu->arch.pause into a counter The s390 arm64 vcpu struct mirrors arm64's kvm_vcpu_arch. When commit e64309198eda2 ("KVM: arm64: Turn vcpu->arch.pause into a counter") changed the type of kvm_vcpu_arch.pause from bool to atomic_t, the merge into this tree missed the s390 copy, leaving it out of sync. Nothing on the s390 side accesses vcpu->arch.pause yet, so this has no functional effect. Align the type to keep the mirror identical to its arm64 counterpart. Fixes: e6c329180d1d ("KVM: s390: arm64: Introduce host definitions") Signed-off-by: Steffen Eiden Signed-off-by: Andreas Grapentin Reviewed-by: Andreas Grapentin Acked-by: Marc Zyngier Signed-off-by: Christian Borntraeger --- arch/s390/include/asm/kvm_host_arm64.h | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/arch/s390/include/asm/kvm_host_arm64.h b/arch/s390/include/asm/kvm_host_arm64.h index 82343e723ebf40..a3e40650d75d05 100644 --- a/arch/s390/include/asm/kvm_host_arm64.h +++ b/arch/s390/include/asm/kvm_host_arm64.h @@ -63,11 +63,10 @@ struct kvm_vcpu_arch { /* * Don't run the guest (internal implementation need). * - * Contrary to the flags above, this is set/cleared outside of - * a vcpu context, and thus cannot be mixed with the flags - * themselves (or the flag accesses need to be made atomic). + * Contrary to the flags above, this is updated outside of + * a vcpu context, and thus cannot be mixed with the flags. */ - bool pause; + atomic_t pause; /* vcpu power state */ struct kvm_mp_state mp_state; From 53c389953a747f590f83abaf1278f2d584ab49c3 Mon Sep 17 00:00:00 2001 From: Andreas Grapentin Date: Tue, 3 Nov 2026 17:37:03 +0100 Subject: [PATCH 0306/2102] KVM: s390: arm64: Declare enum vcpu_sysreg Forward-declare enum vcpu_sysreg in kvm_host_arm64.h. This should have been included in the first iteration of the header, since we will need it to talk about system registers. Since the definition of enum vcpu_sysreg is not shared yet, and not used on the s390 side, this should not cause any functional changes. Fixes: e6c329180d1d ("KVM: s390: arm64: Introduce host definitions") Signed-off-by: Andreas Grapentin Acked-by: Christian Borntraeger Reviewed-by: Steffen Eiden Acked-by: Marc Zyngier Signed-off-by: Christian Borntraeger --- arch/s390/include/asm/kvm_host_arm64.h | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/s390/include/asm/kvm_host_arm64.h b/arch/s390/include/asm/kvm_host_arm64.h index a3e40650d75d05..3e69724f17c907 100644 --- a/arch/s390/include/asm/kvm_host_arm64.h +++ b/arch/s390/include/asm/kvm_host_arm64.h @@ -8,6 +8,7 @@ #include #define vcpu_gp_regs(v) ((v)->arch.sae_block.gpr) +enum vcpu_sysreg; #include #include From 674feba7a0d39eb93e78f9e84bd5ec0c0072baa2 Mon Sep 17 00:00:00 2001 From: Andreas Grapentin Date: Tue, 3 Nov 2026 17:37:04 +0100 Subject: [PATCH 0307/2102] KVM: s390: arm64: Fix kvm_arm64 module naming consistency the module build for the kvm_arm64 module produced kvm-arm64.ko, fix the Makefile to produce kvm_arm64.ko instead, so the output file name matches the module name. Signed-off-by: Andreas Grapentin Fixes: 91b87e6eea4d0 ("KVM: s390: arm64: Integrate arm on s390") Acked-by: Christian Borntraeger Reviewed-by: Steffen Eiden Acked-by: Marc Zyngier Signed-off-by: Christian Borntraeger --- arch/s390/kvm/arm64/Makefile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/arch/s390/kvm/arm64/Makefile b/arch/s390/kvm/arm64/Makefile index 3f0fe5c9f0a17c..b48dc65b7aaab5 100644 --- a/arch/s390/kvm/arm64/Makefile +++ b/arch/s390/kvm/arm64/Makefile @@ -29,7 +29,7 @@ $(obj)/%-arm64.o: $(src)/%.c FORCE $(call if_changed_rule,cc_o_c) $(call cmd,force_checksrc) -# %-arm64.o stems don't match any kvm-arm64-y entry so Kbuild derives wrong +# %-arm64.o stems don't match any kvm_arm64-y entry so Kbuild derives wrong # KBUILD_MODNAME/KBUILD_MODFILE. Force include a generated header to override. KVM_ARM64_MODNAME_H := $(obj)/generated/kvm_arm64_modname.h ccflags-y += -include $(KVM_ARM64_MODNAME_H) @@ -48,7 +48,7 @@ define filechk_kvm_arm64_modname echo '#undef __KBUILD_MODNAME'; \ echo '#define __KBUILD_MODNAME $(KVM_DEV_NAME)'; \ echo '#undef KBUILD_MODFILE'; \ - echo '#define KBUILD_MODFILE "$(obj)/kvm-arm64"'; \ + echo '#define KBUILD_MODFILE "$(obj)/kvm_arm64"'; \ echo '#endif /* __KVM_ARM64_MODNAME_H */' endef @@ -60,7 +60,7 @@ $(addprefix $(obj)/,$(kvm-arm64-obj)): private part-of-builtin := y ifeq ($(CONFIG_KVM),m) -kvm-arm64-y = $(kvm-arm64-obj) +kvm_arm64-y = $(kvm-arm64-obj) else ifeq ($(CONFIG_KVM),y) @@ -86,7 +86,7 @@ $(obj)/kvm_symbol_list: $(obj)/kvm-unnamespaced.o FORCE # cmd_oc_o_o carries -DKBUILD_MODFILE so generate_builtin_ranges.awk # can attribute kvm-namespaced.o to kvm_arm64 via its .cmd file. -cmd_oc_o_o = $(cmd_objcopy) -DKBUILD_MODFILE='"$(obj)/kvm-arm64"' +cmd_oc_o_o = $(cmd_objcopy) -DKBUILD_MODFILE='"$(obj)/kvm_arm64"' define rule_oc_o_o $(call cmd,objcopy) @printf '%s\n' 'savedcmd_$@ := $(call make-cmd,oc_o_o)' > $(dot-target).cmd @@ -98,7 +98,7 @@ OBJCOPYFLAGS_kvm-namespaced.o := -O $(LD_BFD) --localize-symbols=$(obj)/kvm_symb $(obj)/kvm-namespaced.o: $(obj)/kvm-unnamespaced.o $(obj)/kvm_symbol_list FORCE $(call if_changed_rule,oc_o_o) -kvm-arm64-y = kvm-namespaced.o +kvm_arm64-y = kvm-namespaced.o targets += kvm-unnamespaced.o kvm_symbol_list kvm-namespaced.o @@ -106,5 +106,5 @@ endif clean-files += kvm-unnamespaced.o kvm_symbol_list kvm-namespaced.o -obj-$(CONFIG_KVM) += kvm-arm64.o +obj-$(CONFIG_KVM) += kvm_arm64.o From 62aef2c04e0e69a9b88affa74ff699ce5c4e8652 Mon Sep 17 00:00:00 2001 From: Sasha Levin Date: Wed, 14 Oct 2026 16:01:49 -0400 Subject: [PATCH 0308/2102] selftests: drivers/s390x: Select uvdevice tests using the target architecture The uvdevice Makefile decides whether to build its test from uname -m, which describes the build host. A cross build for s390 on another host therefore silently omits the test, while the non-s390 branch provides no-op build and installation targets but no emit_tests target. Select the test from the target ARCH when it is given and from the host's SUBARCH otherwise, accepting both the s390 and s390x spellings, and include lib.mk unconditionally so that other architectures build, install and emit an empty runlist. ARCH itself is left unset so that a native LLVM=1 build keeps using the compiler's native target. Drop the include path derived from tools/arch/$(ARCH): the test only needs asm/uvdevice.h from the installed kernel headers, and the path does not exist for the s390x spelling. Fixes: cbac924200b8 ("selftests: drivers/s390x: Add uvdevice tests") Signed-off-by: Sasha Levin Reviewed-by: Steffen Eiden Signed-off-by: Christian Borntraeger --- .../selftests/drivers/s390x/uvdevice/Makefile | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/tools/testing/selftests/drivers/s390x/uvdevice/Makefile b/tools/testing/selftests/drivers/s390x/uvdevice/Makefile index 755d164384c46f..586a9aa6fb1581 100644 --- a/tools/testing/selftests/drivers/s390x/uvdevice/Makefile +++ b/tools/testing/selftests/drivers/s390x/uvdevice/Makefile @@ -1,20 +1,13 @@ include ../../../../../build/Build.include -UNAME_M := $(shell uname -m) - -ifneq ($(UNAME_M),s390x) -nothing: -.PHONY: all clean run_tests install -.SILENT: -else +top_srcdir ?= ../../../../../.. +include $(top_srcdir)/scripts/subarch.include +ARCH_PROCESSED := $(or $(ARCH),$(SUBARCH)) +ifneq (,$(filter s390 s390x,$(ARCH_PROCESSED))) TEST_GEN_PROGS := test_uvdevice -top_srcdir ?= ../../../../../.. -LINUX_TOOL_ARCH_INCLUDE = $(top_srcdir)/tools/arch/$(ARCH)/include - -CFLAGS += -Wall -Werror -static $(KHDR_INCLUDES) -I$(LINUX_TOOL_ARCH_INCLUDE) +CFLAGS += -Wall -Werror -static $(KHDR_INCLUDES) +endif include ../../../lib.mk - -endif From 0f01f3156f260a5fbce3b4017e1f1ff93cb29465 Mon Sep 17 00:00:00 2001 From: Gerald Schaefer Date: Wed, 21 Oct 2026 14:04:26 +0200 Subject: [PATCH 0309/2102] s390/appldata: Fix error handling in appldata_generic_handler() appldata_generic_handler() always returns 0 after starting or stopping monitor recording. So "echo {0,1} > /proc/sys/appldata/{os,mem,net_sum}" returns success even when DIAG 0xDC failed. A failed start would keep ops->active as 0, so reading the sysctl later would correctly reflect this. A failed stop would falsely set ops->active to 0 and decrement module refcount. This would allow the data gathering module to be removed, and the data buffer to be freed, while z/VM monitor service is still collecting data from that buffer. Fix this by returning -EIO when appldata_diag() failed, and only set ops->active to 0 and decrement module refcount when it succeeded on stop path. Cc: stable@vger.kernel.org Signed-off-by: Gerald Schaefer Reviewed-by: Heiko Carstens Signed-off-by: Heiko Carstens Signed-off-by: Alexander Gordeev --- arch/s390/appldata/appldata_base.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/arch/s390/appldata/appldata_base.c b/arch/s390/appldata/appldata_base.c index 836c51da18f4b2..f10b2f040cc20d 100644 --- a/arch/s390/appldata/appldata_base.c +++ b/arch/s390/appldata/appldata_base.c @@ -360,21 +360,25 @@ appldata_generic_handler(const struct ctl_table *ctl, int write, pr_err("Starting the data collection for %s " "failed with rc=%d\n", ops->name, rc); module_put(ops->owner); + rc = -EIO; } else ops->active = 1; } else if (!active && (ops->active == 1)) { - ops->active = 0; rc = appldata_diag(ops->record_nr, APPLDATA_STOP_REC, (unsigned long) ops->data, ops->size, ops->mod_lvl); - if (rc != 0) + if (rc != 0) { pr_err("Stopping the data collection for %s " "failed with rc=%d\n", ops->name, rc); - module_put(ops->owner); + rc = -EIO; + } else { + ops->active = 0; + module_put(ops->owner); + } } mutex_unlock(&appldata_ops_mutex); module_put(ops->owner); - return 0; + return rc; } /*************************** /proc stuff *******************************/ From f3ebe20a4898708bd9617b7eeea0c8c4f66724cb Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Wed, 21 Oct 2026 10:56:43 +0200 Subject: [PATCH 0310/2102] s390/syscall: Set -ENOSYS return value before calling syscall_enter_from_user_mode_work() On s390 gpr2 contains both the system call return value and the system call number. With [1] it is expected to set gpr2 to -ENOSYS before calling syscall_enter_from_user_mode_work(), so that a skipped system call has a defined default return value, and not the system call number like today. To make that work and stay compatible with existing ptrace users, replace PIF_SYSCALL_RET_SET with PIF_SYSCALL_ENTRY. PIF_SYSCALL_ENTRY is set before syscall_enter_from_user_mode_work() is called and indicates that reads and writes to gpr2 via PTRACE_PEEKUSR, PTRACE_POKEUSR, PTRACE_GETREGSET, and PTRACE_SETREGSET are redirected to regs->int_code, which contains the system call number. gpr2, which contains the system call return value, can only be changed via syscall_set_return_value() (e.g. seccomp). After syscall_enter_from_user_mode_work() returns, PIF_SYSCALL_ENTRY is cleared and the code behaves as before. PIF_SYSCALL_RET_SET was introduced with [2]. The flag was set by syscall_set_return_value() and allowed seccomp to skip syscalls and inject a return value despite the gpr2 aliasing. Kernel seccomp and ptrace selftests, as well as strace selftests, show no difference with and without this change. [1] 05c033db7e9a ("entry, treewide: Make syscall_enter_from_user_mode[_work]() indicate syscall execution") [2] 56e62a737028 ("s390: convert to generic entry") Fixes: 05c033db7e9a ("entry, treewide: Make syscall_enter_from_user_mode[_work]() indicate syscall execution") Cc: stable@vger.kernel.org Acked-by: Alexander Gordeev Signed-off-by: Heiko Carstens Signed-off-by: Alexander Gordeev --- arch/s390/include/asm/ptrace.h | 4 ++-- arch/s390/include/asm/syscall.h | 1 - arch/s390/kernel/ptrace.c | 28 +++++++++++++++++++++++----- arch/s390/kernel/syscall.c | 20 +++++++++----------- 4 files changed, 34 insertions(+), 19 deletions(-) diff --git a/arch/s390/include/asm/ptrace.h b/arch/s390/include/asm/ptrace.h index 3e56ef8c268b79..d8f3a2dbe68940 100644 --- a/arch/s390/include/asm/ptrace.h +++ b/arch/s390/include/asm/ptrace.h @@ -15,14 +15,14 @@ #define PIF_SYSCALL 0 /* inside a system call */ #define PIF_PSW_ADDR_ADJUSTED 1 /* psw address has been adjusted */ -#define PIF_SYSCALL_RET_SET 2 /* return value was set via ptrace */ +#define PIF_SYSCALL_ENTRY 2 /* ptrace gpr2 access redirected to syscall nr */ #define PIF_FTRACE_FULL_REGS 3 /* all register contents valid (ftrace) */ #define PIF_WARN_TRAP_SKIPPED 4 /* __WARN_trap() was skipped */ #define PIF_PGM_CHECK 5 /* inside a program check */ #define _PIF_SYSCALL BIT(PIF_SYSCALL) #define _PIF_ADDR_PSW_ADJUSTED BIT(PIF_PSW_ADDR_ADJUSTED) -#define _PIF_SYSCALL_RET_SET BIT(PIF_SYSCALL_RET_SET) +#define _PIF_SYSCALL_ENTRY BIT(PIF_SYSCALL_ENTRY) #define _PIF_FTRACE_FULL_REGS BIT(PIF_FTRACE_FULL_REGS) #define _PIF_WARN_TRAP_SKIPPED BIT(PIF_WARN_TRAP_SKIPPED) #define _PIF_PGM_CHECK BIT(PIF_PGM_CHECK) diff --git a/arch/s390/include/asm/syscall.h b/arch/s390/include/asm/syscall.h index 5f310caad1fcec..47f66202977f7a 100644 --- a/arch/s390/include/asm/syscall.h +++ b/arch/s390/include/asm/syscall.h @@ -59,7 +59,6 @@ static inline void syscall_set_return_value(struct task_struct *task, struct pt_regs *regs, int error, long val) { - set_pt_regs_flag(regs, PIF_SYSCALL_RET_SET); regs->gprs[2] = error ? error : val; } diff --git a/arch/s390/kernel/ptrace.c b/arch/s390/kernel/ptrace.c index 5202f9a2d9390b..577fb2c3d5a8ea 100644 --- a/arch/s390/kernel/ptrace.c +++ b/arch/s390/kernel/ptrace.c @@ -204,15 +204,24 @@ static unsigned long __peek_user(struct task_struct *child, addr_t addr) addr_t offset, tmp; if (addr < offsetof(struct user, regs.acrs)) { - /* - * psw and gprs are stored on the stack - */ - tmp = *(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr); + struct pt_regs *regs = task_pt_regs(child); + + /* psw and gprs are on the stack. */ + tmp = *(addr_t *)((addr_t)®s->psw + addr); if (addr == offsetof(struct user, regs.psw.mask)) { /* Return a clean psw mask. */ tmp &= PSW_MASK_USER | PSW_MASK_RI; tmp |= PSW_USER_BITS; } + /* + * During system call entry gpr2 contains the return + * value. Redirect reads of gpr2 to int_code so that + * readers see the system call number. + */ + if (addr == offsetof(struct user, regs.gprs[2])) { + if (test_pt_regs_flag(regs, PIF_SYSCALL_ENTRY)) + tmp = syscall_get_nr(child, regs); + } } else if (addr < offsetof(struct user, regs.orig_gpr2)) { /* @@ -347,8 +356,17 @@ static int __poke_user(struct task_struct *child, addr_t addr, addr_t data) } if (addr == offsetof(struct user, regs.gprs[2])) { - if (test_pt_regs_flag(regs, PIF_SYSCALL)) + if (test_pt_regs_flag(regs, PIF_SYSCALL_ENTRY)) { + /* + * System call entry path: only change system + * call number in int_code, but leave gpr2 + * alone, which contains the return value. + */ syscall_set_nr(child, regs, data); + return 0; + } else if (test_pt_regs_flag(regs, PIF_SYSCALL)) { + syscall_set_nr(child, regs, data); + } } *(addr_t *)((addr_t) ®s->psw + addr) = data; } else if (addr < offsetof(struct user, regs.orig_gpr2)) { diff --git a/arch/s390/kernel/syscall.c b/arch/s390/kernel/syscall.c index bcc0b76bd868cd..a94bfcef2e8c6f 100644 --- a/arch/s390/kernel/syscall.c +++ b/arch/s390/kernel/syscall.c @@ -117,24 +117,22 @@ void noinstr __do_syscall(struct pt_regs *regs, unsigned long flags) regs->int_code &= ~0xffffUL; regs->int_code |= nr; } - regs->gprs[2] = nr; if (nr == __NR_restart_syscall && !(current->restart_block.arch_data & 1)) { regs->psw.addr = current->restart_block.arch_data; current->restart_block.arch_data = 1; } - - permit = syscall_enter_from_user_mode_work(regs, &nr); - /* - * In the s390 ptrace ABI, both the syscall number and the return value - * use gpr2. However, userspace puts the syscall number either in the - * svc instruction itself, or uses gpr1. To make at least skipping syscalls - * work, the ptrace code sets PIF_SYSCALL_RET_SET, which is checked here - * and if set, the syscall will be skipped. + * gpr2 is the return value register. Set it to -ENOSYS so that a + * skipped system call gets a defined default return value. + * Set PIF_SYSCALL_ENTRY so that ptrace reads and writes to gpr2 + * are redirected to the system call number in int_code. */ - if (unlikely(test_and_clear_pt_regs_flag(regs, PIF_SYSCALL_RET_SET) || !permit)) + syscall_set_return_value(current, regs, -ENOSYS, 0); + set_pt_regs_flag(regs, PIF_SYSCALL_ENTRY); + permit = syscall_enter_from_user_mode_work(regs, &nr); + clear_pt_regs_flag(regs, PIF_SYSCALL_ENTRY); + if (unlikely(!permit)) goto out; - regs->gprs[2] = -ENOSYS; if (likely(nr < NR_syscalls)) { nr = array_index_nospec(nr, NR_syscalls); regs->gprs[2] = sys_call_table[nr](regs); From 64ee7f863655e67f26947420516daba4e232675d Mon Sep 17 00:00:00 2001 From: Jiale Yao Date: Wed, 28 Oct 2026 12:48:25 +0800 Subject: [PATCH 0311/2102] s390/dcssblk: Initialize device semaphore before sysfs registration device_create_file() makes the add and remove attributes writable before the device list semaphore is initialized. A sysfs write racing module initialization can therefore acquire an uninitialized rwsem. Initialize the semaphore before registering the root device and its attributes. [hca@linux.ibm.com: Use DECLARE_RWSEM() instead of moving init_rwsem()] Cc: stable@vger.kernel.org Acked-by: Alexander Gordeev Signed-off-by: Jiale Yao Signed-off-by: Heiko Carstens Signed-off-by: Alexander Gordeev --- drivers/s390/block/dcssblk.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/s390/block/dcssblk.c b/drivers/s390/block/dcssblk.c index e5a02c2990d017..9b6b48431fbf0b 100644 --- a/drivers/s390/block/dcssblk.c +++ b/drivers/s390/block/dcssblk.c @@ -101,7 +101,7 @@ static DEVICE_ATTR(remove, S_IWUSR, NULL, dcssblk_remove_store); static struct device *dcssblk_root_dev; static LIST_HEAD(dcssblk_devices); -static struct rw_semaphore dcssblk_devices_sem; +static DECLARE_RWSEM(dcssblk_devices_sem); /* * release function for segment device. @@ -1026,7 +1026,6 @@ dcssblk_init(void) if (rc < 0) goto out_root; dcssblk_major = rc; - init_rwsem(&dcssblk_devices_sem); dcssblk_check_params(); return 0; From 3ec76ed5bea344db45f46daa1592901b53601580 Mon Sep 17 00:00:00 2001 From: Jacob Moroni Date: Fri, 30 Oct 2026 17:35:56 +0000 Subject: [PATCH 0312/2102] MAINTAINERS: Add Jacob Moroni as irdma co-maintainer Tatyana Nikolova is currently the only listed maintainer of the irdma driver. Add myself as a co-maintainer to help with patch review and ongoing maintenance. Signed-off-by: Jacob Moroni Link: https://patch.msgid.link/20261030173556.1873811-1-jmoroni@google.com Acked-by: Tatyana Nikolova Signed-off-by: Leon Romanovsky --- MAINTAINERS | 1 + 1 file changed, 1 insertion(+) diff --git a/MAINTAINERS b/MAINTAINERS index 6004ff7ed8af3b..475b69ef5c939e 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -13413,6 +13413,7 @@ F: include/linux/net/intel/ INTEL ETHERNET PROTOCOL DRIVER FOR RDMA M: Tatyana Nikolova +M: Jacob Moroni L: linux-rdma@vger.kernel.org S: Supported F: drivers/infiniband/hw/irdma/ From b5c11bf9759834731440806708143c40638dc2ff Mon Sep 17 00:00:00 2001 From: Dezhen Lu Date: Tue, 3 Nov 2026 15:28:04 +0100 Subject: [PATCH 0313/2102] RDMA/mlx5: Fix DevX umem page size truncation for pages >= 4G devx_umem_find_best_pgsize() computes the page size in an unsigned long but returns it as unsigned int, and devx_umem_reg_cmd_alloc() stores it in an unsigned int. When the DMA mapping of the umem is contiguous and aligned to 4 GiB or more, and the umem length is a multiple of that size, ib_umem_find_best_pgoff() selects a page size >= 2^32. Since the value is a power of two, the truncation turns it into 0 and the registration fails with -EINVAL. The umem log_page_size field is 5 bits wide on top of MLX5_ADAPTER_PAGE_SHIFT, so the command can encode these page sizes. Seen on two GH200 nodes (ConnectX-7, firmware 32.38.3056 and 32.43.1014) with a dma-buf exported from cudaMalloc memory: registering 4 GiB or 8 GiB umems at 4 GiB-aligned offsets of the dma-buf fails with EINVAL every time, while 2 GiB umems at the same offsets and ibv_reg_dmabuf_mr() of the same ranges succeed. Restricting the user pgsz_bitmap to <= 2 GiB makes all of them succeed. Other large physically contiguous buffers, such as a 16 GiB hugetlb page on an arm64 kernel with 64K base pages, should hit the same path. Use unsigned long for the page size, as commit f0c2427412b4 ("RDMA/mlx5: Fix page_size variable overflow") already did for the MR paths. The bug was found by an AI coding assistant (Claude Opus 5.5, Anthropic) during an audit of 32-bit truncations of page sizes and offsets in drivers/infiniband/core and drivers/infiniband/hw/mlx5. The assistant also wrote the reproducer and this patch. The reproducer was run on the GH200 nodes described above. Fixes: 7610ab57de56 ("RDMA/mlx5: Allow larger pages in DevX umem") Cc: stable@vger.kernel.org Signed-off-by: Dezhen Lu Link: https://patch.msgid.link/20261103142804.67210-1-dezhen.lu@student.uni-tuebingen.de Reviewed-by: Jason Gunthorpe Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/mlx5/devx.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/infiniband/hw/mlx5/devx.c b/drivers/infiniband/hw/mlx5/devx.c index fc6f793dcc6584..2277160d9a33be 100644 --- a/drivers/infiniband/hw/mlx5/devx.c +++ b/drivers/infiniband/hw/mlx5/devx.c @@ -2294,8 +2294,8 @@ static int devx_umem_get(struct mlx5_ib_dev *dev, struct ib_ucontext *ucontext, return 0; } -static unsigned int devx_umem_find_best_pgsize(struct ib_umem *umem, - unsigned long pgsz_bitmap) +static unsigned long devx_umem_find_best_pgsize(struct ib_umem *umem, + unsigned long pgsz_bitmap) { unsigned long page_size; @@ -2333,7 +2333,7 @@ static int devx_umem_reg_cmd_alloc(struct mlx5_ib_dev *dev, int access) { unsigned long pgsz_bitmap; - unsigned int page_size; + unsigned long page_size; __be64 *mtt; void *umem; int ret; From bb261776d1a29768b8fd84eb4f42d99dafa29c93 Mon Sep 17 00:00:00 2001 From: Mathias Nyman Date: Thu, 5 Nov 2026 19:51:02 +0200 Subject: [PATCH 0314/2102] xhci: keep port link_inactive and connected flags in sync when polled Update port 'link_inactive' and 'connected' flags even if xHC isn't generating port change events. xHC only generates port change events on port changes after old port change bits are cleared. Hub driver is often kept up to date by polling the port status. Sashiko reported a possible case where all port changes after a port reset take place before hub driver clears the reset change bit. This way the port can end up connected and fully running with link in u0 without a port event clearing the 'link_inactive' or setting the 'connected' flags. A protocol STALL in this state would set EP_DROP_PENDING, and prevent all future URBs for the endpoint. Fix this by also updating the flags during get_port_status(), when hub driver is polling the port state. Fixes: 6895dbdc19d9 ("xhci: give back TDs and clean up ep0 after disconnect") Link: https://lore.kernel.org/linux-usb/sashiko-outbox-190046@kernel.org/ Cc: stable Signed-off-by: Mathias Nyman Link: https://patch.msgid.link/20261105175106.241182-2-mathias.nyman@linux.intel.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/host/xhci-hub.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/usb/host/xhci-hub.c b/drivers/usb/host/xhci-hub.c index 470bafe1802be5..55430b673f1e94 100644 --- a/drivers/usb/host/xhci-hub.c +++ b/drivers/usb/host/xhci-hub.c @@ -1166,6 +1166,12 @@ static u32 xhci_get_port_status(struct usb_hcd *hcd, struct xhci_bus_state *bus_ if (portsc & PORT_RESET) status |= USB_PORT_STAT_RESET; + /* track connect and link error status when hub is polling */ + if (!(portsc & PORT_RESET)) { + port->link_inactive = (portsc & PORT_PLS_MASK) == XDEV_INACTIVE; + port->connected = !!(portsc & PORT_CONNECT); + } + /* USB2 and USB3 specific bits, including Port Link State */ if (hcd->speed >= HCD_USB3) xhci_get_usb3_port_status(port, &status, portsc); From 2f2fe3201029ffc215b46ac40a0a9587715bc43a Mon Sep 17 00:00:00 2001 From: Xu Rao Date: Thu, 5 Nov 2026 19:51:03 +0200 Subject: [PATCH 0315/2102] usb: xhci: disable the correct slot on alloc_dev failure xhci_alloc_dev() stores the Slot ID returned by the Enable Slot command in the local slot_id variable. udev->slot_id is updated only after xhci_alloc_virt_device() succeeds. If endpoint resource reservation or virtual device allocation fails before that update, the error path passes udev->slot_id to xhci_disable_and_free_slot(). During initial enumeration this is slot 0. When reallocating a device whose virtual device is missing or belongs to another usb_device, udev->slot_id may contain a stale Slot ID. The newly enabled slot can therefore remain active, or the wrong slot can be disabled. Pass slot_id, which identifies the slot enabled by this invocation. xhci_disable_and_free_slot() already handles a missing xhci->devs entry. Fixes: 3ffbba9511b4 ("USB: xhci: Allocate and address USB devices") Cc: stable@vger.kernel.org Signed-off-by: Xu Rao Reviewed-by: Niklas Neronin Signed-off-by: Mathias Nyman Link: https://patch.msgid.link/20261105175106.241182-3-mathias.nyman@linux.intel.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/host/xhci.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/usb/host/xhci.c b/drivers/usb/host/xhci.c index b50a582be1fbfa..94da0268b7b30f 100644 --- a/drivers/usb/host/xhci.c +++ b/drivers/usb/host/xhci.c @@ -4301,7 +4301,7 @@ int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev) return 1; disable_slot: - xhci_disable_and_free_slot(xhci, udev->slot_id); + xhci_disable_and_free_slot(xhci, slot_id); return 0; } From 5550405351199fe78f4a3cd606c07f5ad7220e1b Mon Sep 17 00:00:00 2001 From: Rishabh Jain Date: Thu, 5 Nov 2026 19:51:04 +0200 Subject: [PATCH 0316/2102] usb: pci-quirks: always assert xHCI OS ownership The xHCI ownership protocol requires the OS driver to assert the HC OS Owned semaphore before using the host controller, then wait for HC BIOS Owned to clear if firmware owns it. quirk_usb_handoff_xhci() currently asserts OS Owned only when BIOS Owned is already set. If firmware leaves BIOS Owned clear, Linux uses the xHC while both ownership semaphores remain clear. The timeout fallback also clears BIOS Owned using the original register value, which can clear OS Owned at the same time. On an AMD PROM21 xHCI controller (1022:43fc), this caused every S3 resume to terminate Controller Restore State with USBSTS 0x401. Linux then reset the host controller, both root hubs and the USB Bluetooth adapter. The controller entered resume ready and halted with USBSTS 0x1. Endpoint state, 100 ms save/restore delays, scratchpads, the DCBAA, device contexts and command, event and transfer rings were verified not to cause the restore error. Across four S3 cycles, asserting only HC OS Owned changed USBLEGSUP from 0x00000801 to 0x01000801 and eliminated the restore failure. Testing included the unmodified 7.1.8-ogc1.1.fc44.x86_64 distribution kernel using a test module that set the HC OS Owned semaphore. The same test was repeated after review with the same result. Clearing USBLEGCTLSTS was independently verified to be unnecessary. Always assert OS Owned for controllers using the standard xHCI handoff, and leave the existing TI/Renesas forced handoff unchanged. Keep OS Owned asserted after the standard handoff, including when forcing BIOS Owned clear after a timeout, to prevent firmware from reclaiming the controller during subsequent suspends. Fixes: 66d4eadd8d06 ("USB: xhci: BIOS handoff and HW initialization.") Cc: stable@vger.kernel.org Reviewed-by: Mario Limonciello (AMD) Tested-by: McKenna Fan Tested-by: Quinn Schive Tested-by: Bruno Filipe Tested-by: Maciej Zonski Signed-off-by: Rishabh Jain Signed-off-by: Mathias Nyman Link: https://patch.msgid.link/20261105175106.241182-4-mathias.nyman@linux.intel.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/host/pci-quirks.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/drivers/usb/host/pci-quirks.c b/drivers/usb/host/pci-quirks.c index f670e7aab98433..1dbfd697a58200 100644 --- a/drivers/usb/host/pci-quirks.c +++ b/drivers/usb/host/pci-quirks.c @@ -1195,10 +1195,11 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) && pdev->device == 0x0014)) { val = (val | XHCI_HC_OS_OWNED) & ~XHCI_HC_BIOS_OWNED; writel(val, base + ext_cap_offset); - } - - /* If the BIOS owns the HC, signal that the OS wants it, and wait */ - if (val & XHCI_HC_BIOS_OWNED) { + } else { + /* + * Perform the standard handoff and leave OS ownership set to + * keep the BIOS at bay during subsequent suspends. + */ writel(val | XHCI_HC_OS_OWNED, base + ext_cap_offset); /* Wait for 1 second with 10 microsecond polling interval */ @@ -1210,7 +1211,9 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) dev_warn(&pdev->dev, "xHCI BIOS handoff failed (BIOS bug ?) %08x\n", val); - writel(val & ~XHCI_HC_BIOS_OWNED, base + ext_cap_offset); + writel((val | XHCI_HC_OS_OWNED) & + ~XHCI_HC_BIOS_OWNED, + base + ext_cap_offset); } } From d1ec1859f3b8641e3e5c5953cc7dd8e63b54339f Mon Sep 17 00:00:00 2001 From: Niklas Neronin Date: Thu, 5 Nov 2026 19:51:05 +0200 Subject: [PATCH 0317/2102] usb: xhci: clear stale bandwidth data after hibernation Controllers using software managed bandwidth accounting maintain periodic endpoint bandwidth information in struct 'xhci_interval_bw_table'. Each root hub port owns a bandwidth table and a list of TT bandwidth domains, where each TT has its own bandwidth table. Virtual devices reference the bandwidth table of their current bandwidth domain through 'bw_table' or 'tt_info'. Historically, resume from S4 reinitialized the entire xHCI driver state, which implicitly cleared all bandwidth accounting data. After the hibernation resume path was optimized to preserve parts of the driver state, virtual devices and TT bandwidth information were freed and recreated, but the root hub bandwidth tables were left intact. As a result, stale bandwidth accounting data could remain in the root hub bandwidth tables across hibernation resume, leading to incorrect bandwidth calculations after devices were rediscovered. Fix this by resetting all bandwidth accounting data in xhci_rh_bw_cleanup() so that resume starts with a clean bandwidth state, and resetting the total active endpoints count. Fixes: 2a70e5dc0301 ("usb: xhci: optimize resuming from S4 (suspend-to-disk)") Reported-by: Harald Judt Link: https://bugzilla.kernel.org/show_bug.cgi?id=222071 Suggested-by: Lovekesh Solanki Tested-by: Harald Judt Cc: stable Signed-off-by: Niklas Neronin Signed-off-by: Mathias Nyman Link: https://patch.msgid.link/20261105175106.241182-5-mathias.nyman@linux.intel.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/host/xhci-mem.c | 16 +++++++++++++++- drivers/usb/host/xhci.c | 1 + 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/drivers/usb/host/xhci-mem.c b/drivers/usb/host/xhci-mem.c index af8d4b74c4ba0c..75577f441cddc5 100644 --- a/drivers/usb/host/xhci-mem.c +++ b/drivers/usb/host/xhci-mem.c @@ -1903,24 +1903,38 @@ EXPORT_SYMBOL_GPL(xhci_remove_secondary_interrupter); void xhci_rh_bw_cleanup(struct xhci_hcd *xhci) { struct xhci_root_port_bw_info *rh_bw; + struct xhci_interval_bw_table *bw_table; + struct xhci_interval_bw *interval_bw; struct xhci_tt_bw_info *tt_info, *tt_next; struct list_head *eps, *ep, *ep_next; for (int i = 0; i < xhci->max_ports; i++) { rh_bw = &xhci->rh_bw[i]; + rh_bw->num_active_tts = 0; /* Clear and free all TT bandwidth entries */ list_for_each_entry_safe(tt_info, tt_next, &rh_bw->tts, tt_list) { list_del(&tt_info->tt_list); kfree(tt_info); } + bw_table = &rh_bw->bw_table; + bw_table->interval0_esit_payload = 0; + bw_table->bw_used = 0; + bw_table->ss_bw_in = 0; + bw_table->ss_bw_out = 0; + /* Clear per-interval endpoint lists */ for (int j = 0; j < XHCI_MAX_INTERVAL; j++) { - eps = &rh_bw->bw_table.interval_bw[j].endpoints; + interval_bw = &bw_table->interval_bw[j]; + eps = &interval_bw->endpoints; + interval_bw->num_packets = 0; list_for_each_safe(ep, ep_next, eps) list_del_init(ep); + interval_bw->overhead[LS_OVERHEAD_TYPE] = 0; + interval_bw->overhead[FS_OVERHEAD_TYPE] = 0; + interval_bw->overhead[HS_OVERHEAD_TYPE] = 0; } } } diff --git a/drivers/usb/host/xhci.c b/drivers/usb/host/xhci.c index 94da0268b7b30f..a762dd010e8dea 100644 --- a/drivers/usb/host/xhci.c +++ b/drivers/usb/host/xhci.c @@ -1185,6 +1185,7 @@ int xhci_resume(struct xhci_hcd *xhci, bool power_lost, bool is_auto_resume) for (int i = xhci->max_slots; i > 0; i--) xhci_free_virt_devices_depth_first(xhci, i); + xhci->num_active_eps = 0; xhci_rh_bw_cleanup(xhci); xhci->cmd_ring_reserved_trbs = 0; From 3149e8b3237f58d4dd440fc64c45c93404c4b064 Mon Sep 17 00:00:00 2001 From: Niklas Neronin Date: Thu, 5 Nov 2026 19:51:06 +0200 Subject: [PATCH 0318/2102] usb: xhci: fix 'num_active_eps' accounting on allocation failure For controllers affected by XHCI_EP_LIMIT_QUIRK, endpoint resources for the default control endpoint are accounted before the virtual device is allocated. If xhci_alloc_virt_device() fails, the slot is disabled and cleanup is handled through the Disable Slot completion path. However, because no virtual device is installed in 'xhci->devs', the endpoint accounting is never released and 'num_active_eps' remains incremented. As a result, each allocation failure leaks one endpoint from the driver's accounting. Fix this by undoing the endpoint reservation when virtual device allocation fails. Signed-off-by: Niklas Neronin Signed-off-by: Mathias Nyman Link: https://patch.msgid.link/20261105175106.241182-6-mathias.nyman@linux.intel.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/host/xhci.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/drivers/usb/host/xhci.c b/drivers/usb/host/xhci.c index a762dd010e8dea..fc1b0a6b04297e 100644 --- a/drivers/usb/host/xhci.c +++ b/drivers/usb/host/xhci.c @@ -4280,6 +4280,11 @@ int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev) */ if (!xhci_alloc_virt_device(xhci, slot_id, udev, GFP_NOIO)) { xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n"); + if (xhci->quirks & XHCI_EP_LIMIT_QUIRK) { + spin_lock_irqsave(&xhci->lock, flags); + xhci->num_active_eps -= 1; + spin_unlock_irqrestore(&xhci->lock, flags); + } goto disable_slot; } vdev = xhci->devs[slot_id]; From 551bdd6fcaba4ffc98fd95c4d969d4470eae580f Mon Sep 17 00:00:00 2001 From: Nickolai Zeldovich Date: Sat, 17 Oct 2026 22:36:49 -0400 Subject: [PATCH 0319/2102] riscv: mm: Define PAGE_KERNEL_RO Kernel mappings that generic code creates read-only are writable on riscv. With HugeTLB vmemmap optimization (selected by riscv and on by default with CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP_DEFAULT_ON), the tail vmemmap pages of every optimized huge page are remapped to one shared page with PAGE_KERNEL_RO so that a stray write to a tail struct page faults. On riscv that remap keeps _PAGE_WRITE, so such a write silently changes the struct pages of every optimized huge page instead. early_memremap_ro() (EFI system and configuration tables), the firmware loader's vmap() of the loaded image, and acpi_os_ioremap() for EFI runtime code and NOMAP regions, which asks for a read-only mapping precisely to avoid a writable mapping of executable code, are affected the same way. riscv defines PAGE_KERNEL_READ but not PAGE_KERNEL_RO, so include/linux/pgtable.h falls back to "#define PAGE_KERNEL_RO PAGE_KERNEL". Define PAGE_KERNEL_RO as PAGE_KERNEL_READ. FIXMAP_PAGE_RO then follows from asm-generic/fixmap.h: early_memremap_ro() now passes 0xe3 instead of 0xe7 to __early_ioremap(). Tested on QEMU virt (riscv64, defconfig with CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP_DEFAULT_ON and CONFIG_PTDUMP_DEBUGFS, booted with hugepages=8): before, every vmemmap entry in /sys/kernel/debug/kernel_page_tables has W set; after, the 28K of tail vmemmap of each huge page is mapped R without W. Fixes: a3c7d6b642e4 ("riscv: mm: hugetlb: Enable ARCH_WANT_HUGETLB_PAGE_OPTIMIZE_VMEMMAP") Assisted-by: LLM Signed-off-by: Nickolai Zeldovich Acked-by: Muchun Song Reviewed-by: Jisheng Zhang Link: https://patch.msgid.link/20261018023649.798595-1-nickolai@csail.mit.edu Signed-off-by: Paul Walmsley --- arch/riscv/include/asm/pgtable.h | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/riscv/include/asm/pgtable.h b/arch/riscv/include/asm/pgtable.h index 2ebd5fa5adc58e..07ccacd51ab543 100644 --- a/arch/riscv/include/asm/pgtable.h +++ b/arch/riscv/include/asm/pgtable.h @@ -189,6 +189,7 @@ extern struct pt_alloc_ops pt_ops __meminitdata; #define PAGE_KERNEL __pgprot(_PAGE_KERNEL) #define PAGE_KERNEL_READ __pgprot(_PAGE_KERNEL & ~_PAGE_WRITE) +#define PAGE_KERNEL_RO PAGE_KERNEL_READ #define PAGE_KERNEL_EXEC __pgprot(_PAGE_KERNEL | _PAGE_EXEC) #define PAGE_KERNEL_READ_EXEC __pgprot((_PAGE_KERNEL & ~_PAGE_WRITE) \ | _PAGE_EXEC) From 043a2260b96ffc13121a1dd65282e67eb2e1d8a8 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 5 Nov 2026 19:16:44 +0100 Subject: [PATCH 0320/2102] mm/khugepaged: don't map folios that are not uptodate in MADV_COLLAPSE madvise(MADV_COLLAPSE) can map PMD-sized pagecache folios that are not uptodate. For example, shmem fallocate() can put such folios into the page cache. collapse_file() already refuses to proceed with folios that are not uptodate. Let's just do the same in try_collapse_pte_mapped_thp() and skip such folios, leaving handling to the page faults. Note that collapse_file() effectively clears shmem folios through shmem_get_folio(); let's keep this fix simple and simply let the page fault path deal with that. Fixes: 34488399fa08 ("mm/madvise: add file and shmem support to MADV_COLLAPSE") Reported-by: Chris Mason Cc: stable@vger.kernel.org Reviewed-by: Lorenzo Stoakes (ARM) Acked-by: Hugh Dickins Acked-by: Zi Yan Reviewed-by: Zach O'Keefe Reviewed-by: SJ Park Reviewed-by: Baolin Wang Reviewed-by: Lance Yang Reviewed-by: Kiryl Shutsemau (Meta) Link: https://patch.msgid.link/20261105-set_huge_pmd_uptodate-v1-1-a78d8a1b7117@kernel.org Reviewed-by: Pedro Falcato Signed-off-by: David Hildenbrand (Arm) --- mm/khugepaged.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mm/khugepaged.c b/mm/khugepaged.c index 4bbe319ef86fa3..964f78c3856ba3 100644 --- a/mm/khugepaged.c +++ b/mm/khugepaged.c @@ -1888,6 +1888,12 @@ static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsign goto drop_folio; } + /* Leave any uninitialized folios to the page fault path. */ + if (!folio_test_uptodate(folio)) { + result = SCAN_FAIL; + goto drop_folio; + } + result = find_pmd_or_thp_or_none(mm, haddr, &pmd); switch (result) { case SCAN_SUCCEED: From 51a08d499c3a2e69ff2509a8c67249b51a52f0c2 Mon Sep 17 00:00:00 2001 From: Guixin Liu Date: Fri, 6 Nov 2026 10:27:28 +0800 Subject: [PATCH 0321/2102] nvme-pci: remove write-only NVMEQ_DELETE_ERROR flag Commit fa46c6fb5d61b ("nvme/pci: move cqe check after device shutdown") removed the only reader of the NVMEQ_DELETE_ERROR flag, but left the flag and its two writes behind. Without a reader the flag carries no state, and nvme_del_cq_end() degenerates to a plain wrapper around nvme_del_queue_end(), which the SQ deletion path already uses directly. Remove the flag, its writes, and the now redundant wrapper. Signed-off-by: Guixin Liu Reviewed-by: Christoph Hellwig Reviewed-by: Nilay Shroff Signed-off-by: Keith Busch --- drivers/nvme/host/pci.c | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/drivers/nvme/host/pci.c b/drivers/nvme/host/pci.c index f8088d5aa724cd..f899015ae40012 100644 --- a/drivers/nvme/host/pci.c +++ b/drivers/nvme/host/pci.c @@ -390,7 +390,6 @@ struct nvme_queue { unsigned long flags; #define NVMEQ_ENABLED 0 #define NVMEQ_SQ_CMB 1 -#define NVMEQ_DELETE_ERROR 2 #define NVMEQ_POLLED 3 __le32 *dbbuf_sq_db; __le32 *dbbuf_cq_db; @@ -2459,8 +2458,6 @@ static int nvme_create_queue(struct nvme_queue *nvmeq, int qid, bool polled) int result; u16 vector = 0; - clear_bit(NVMEQ_DELETE_ERROR, &nvmeq->flags); - /* * A queue's vector matches the queue identifier unless the controller * has only one vector available. @@ -3322,18 +3319,6 @@ static enum rq_end_io_ret nvme_del_queue_end(struct request *req, return RQ_END_IO_NONE; } -static enum rq_end_io_ret nvme_del_cq_end(struct request *req, - blk_status_t error, - const struct io_comp_batch *iob) -{ - struct nvme_queue *nvmeq = req->end_io_data; - - if (error) - set_bit(NVMEQ_DELETE_ERROR, &nvmeq->flags); - - return nvme_del_queue_end(req, error, iob); -} - static int nvme_delete_queue(struct nvme_queue *nvmeq, u8 opcode) { struct request_queue *q = nvmeq->dev->ctrl.admin_q; @@ -3348,10 +3333,7 @@ static int nvme_delete_queue(struct nvme_queue *nvmeq, u8 opcode) return PTR_ERR(req); nvme_init_request(req, &cmd); - if (opcode == nvme_admin_delete_cq) - req->end_io = nvme_del_cq_end; - else - req->end_io = nvme_del_queue_end; + req->end_io = nvme_del_queue_end; req->end_io_data = nvmeq; init_completion(&nvmeq->delete_done); From 21e384dfa497f5bdb987e104652e3a11cda80e75 Mon Sep 17 00:00:00 2001 From: Guixin Liu Date: Fri, 6 Nov 2026 10:27:29 +0800 Subject: [PATCH 0322/2102] nvme-fc: remove dead seqno field in nvme_fc_queue The seqno field of struct nvme_fc_queue has never been referenced since it was introduced in commit e399441de9115 ("nvme-fabrics: Add host support for FC transport"). Drop it. Signed-off-by: Guixin Liu Reviewed-by: Christoph Hellwig Reviewed-by: Nilay Shroff Signed-off-by: Keith Busch --- drivers/nvme/host/fc.c | 1 - 1 file changed, 1 deletion(-) diff --git a/drivers/nvme/host/fc.c b/drivers/nvme/host/fc.c index 0b9ff50d26ff30..2cbd744ffd22ad 100644 --- a/drivers/nvme/host/fc.c +++ b/drivers/nvme/host/fc.c @@ -39,7 +39,6 @@ struct nvme_fc_queue { size_t cmnd_capsule_len; u32 qnum; u32 rqcnt; - u32 seqno; u64 connection_id; atomic_t csn; From 6e31e030e2004b94f663f7a8bef54e4db79d6db6 Mon Sep 17 00:00:00 2001 From: Guixin Liu Date: Fri, 6 Nov 2026 10:27:30 +0800 Subject: [PATCH 0323/2102] nvme-auth: remove dead entry field in nvme_dhchap_queue_context The entry list_head of struct nvme_dhchap_queue_context has never been used since it was introduced in commit f50fff73d620c ("nvme: implement In-Band authentication"). Drop it. Signed-off-by: Guixin Liu Reviewed-by: Christoph Hellwig Reviewed-by: Nilay Shroff Signed-off-by: Keith Busch --- drivers/nvme/host/auth.c | 1 - 1 file changed, 1 deletion(-) diff --git a/drivers/nvme/host/auth.c b/drivers/nvme/host/auth.c index 85f005a5efd0aa..9a3da74dec5aa8 100644 --- a/drivers/nvme/host/auth.c +++ b/drivers/nvme/host/auth.c @@ -19,7 +19,6 @@ static struct kmem_cache *nvme_chap_buf_cache; static mempool_t *nvme_chap_buf_pool; struct nvme_dhchap_queue_context { - struct list_head entry; struct work_struct auth_work; struct nvme_ctrl *ctrl; struct crypto_kpp *dh_tfm; From c621d47b7a454a105e7b873d61cd69dcf84d0451 Mon Sep 17 00:00:00 2001 From: Guixin Liu Date: Fri, 6 Nov 2026 10:27:31 +0800 Subject: [PATCH 0324/2102] nvme-fabrics: remove dead hostnqn already-assigned check The opts->host check in the NVMF_OPT_HOSTNQN handler can never fire: options are parsed into a freshly allocated struct, and opts->host is only assigned after the parsing loop completes. A duplicate hostnqn option is already silently overridden by the strscpy() into the local buffer. Remove the dead check. Signed-off-by: Guixin Liu Reviewed-by: Christoph Hellwig Reviewed-by: Nilay Shroff Signed-off-by: Keith Busch --- drivers/nvme/host/fabrics.c | 6 ------ 1 file changed, 6 deletions(-) diff --git a/drivers/nvme/host/fabrics.c b/drivers/nvme/host/fabrics.c index 3d7ad86c1955ff..c262538523fb61 100644 --- a/drivers/nvme/host/fabrics.c +++ b/drivers/nvme/host/fabrics.c @@ -872,12 +872,6 @@ static int nvmf_parse_options(struct nvmf_ctrl_options *opts, opts->fast_io_fail_tmo = token; break; case NVMF_OPT_HOSTNQN: - if (opts->host) { - pr_err("hostnqn already user-assigned: %s\n", - opts->host->nqn); - ret = -EADDRINUSE; - goto out; - } p = match_strdup(args); if (!p) { ret = -ENOMEM; From 9762c7ae1ee709f6dc3823d151391f89457b5492 Mon Sep 17 00:00:00 2001 From: Guixin Liu Date: Fri, 6 Nov 2026 10:27:32 +0800 Subject: [PATCH 0325/2102] nvme: drop unreachable "off" case in reconnect_delay_show() The "off" case was copied from fast_io_fail_tmo_show(), but unlike fast_io_fail_tmo, reconnect_delay is an unsigned int that the option parser bounds to positive values and that has no off state. The comparison can only trigger when the raw value 4294967295 is written through sysfs, which is not a meaningful delay. Drop the case and the matching sentence in the ABI documentation. Signed-off-by: Guixin Liu Reviewed-by: Christoph Hellwig Reviewed-by: Nilay Shroff Signed-off-by: Keith Busch --- Documentation/ABI/stable/sysfs-nvme | 3 +-- drivers/nvme/host/sysfs.c | 2 -- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/Documentation/ABI/stable/sysfs-nvme b/Documentation/ABI/stable/sysfs-nvme index 9291595f8102f7..1826df9161d24d 100644 --- a/Documentation/ABI/stable/sysfs-nvme +++ b/Documentation/ABI/stable/sysfs-nvme @@ -70,8 +70,7 @@ Description: fabrics controller. reconnect_delay: Shows or sets the reconnect delay in - seconds. Reading returns the delay value, or "off" if - disabled. + seconds. Reading returns the delay value. ctrl_loss_tmo: Shows or sets the controller loss timeout in seconds. Reading returns the timeout value, or "off" if diff --git a/drivers/nvme/host/sysfs.c b/drivers/nvme/host/sysfs.c index 10018c6356b62e..3724b5ce03a079 100644 --- a/drivers/nvme/host/sysfs.c +++ b/drivers/nvme/host/sysfs.c @@ -618,8 +618,6 @@ static ssize_t nvme_ctrl_reconnect_delay_show(struct device *dev, { struct nvme_ctrl *ctrl = dev_get_drvdata(dev); - if (ctrl->opts->reconnect_delay == -1) - return sysfs_emit(buf, "off\n"); return sysfs_emit(buf, "%d\n", ctrl->opts->reconnect_delay); } From f7a3f5f72b8b8c53972a6848290e8121e786b4c4 Mon Sep 17 00:00:00 2001 From: Guixin Liu Date: Fri, 6 Nov 2026 10:27:33 +0800 Subject: [PATCH 0326/2102] nvmet-fc: remove dead fields in nvmet_fc_ls_iod and nvmet_fc_tgt_queue The fcpreq field of struct nvmet_fc_ls_iod is only ever assigned NULL and never read, and the ninetypercent field of struct nvmet_fc_tgt_queue is never referenced as the 90% queue state is recomputed on demand. Drop both. Signed-off-by: Guixin Liu Reviewed-by: Christoph Hellwig Reviewed-by: Nilay Shroff Signed-off-by: Keith Busch --- drivers/nvme/target/fc.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/drivers/nvme/target/fc.c b/drivers/nvme/target/fc.c index 2b7dc3f03912d5..bccfbaea6dfcb9 100644 --- a/drivers/nvme/target/fc.c +++ b/drivers/nvme/target/fc.c @@ -27,7 +27,6 @@ struct nvmet_fc_tgt_assoc; struct nvmet_fc_ls_iod { /* for an LS RQST RCV */ struct nvmefc_ls_rsp *lsrsp; - struct nvmefc_tgt_fcp_req *fcpreq; /* only if RS */ struct list_head ls_rcv_list; /* tgtport->ls_rcv_list */ @@ -129,7 +128,6 @@ struct nvmet_fc_defer_fcp_req { }; struct nvmet_fc_tgt_queue { - bool ninetypercent; u16 qid; u16 sqsize; u16 ersp_ratio; @@ -2076,7 +2074,6 @@ nvmet_fc_rcv_ls_req(struct nvmet_fc_target_port *target_port, } iod->lsrsp = lsrsp; - iod->fcpreq = NULL; memcpy(iod->rqstbuf, lsreqbuf, lsreqbuf_len); iod->rqstdatalen = lsreqbuf_len; iod->hosthandle = hosthandle; From 16fc085d86144c7f6e1c9b70e9d9fe562f8d611e Mon Sep 17 00:00:00 2001 From: Guixin Liu Date: Fri, 6 Nov 2026 10:27:34 +0800 Subject: [PATCH 0327/2102] nvmet: remove unreachable "pcie" entry from the address family map The first entry of nvmet_addr_family[] is never matched: both the adrfam show and store handlers skip index 0, and the NVMF_ADDR_FAMILY_PCI type is matched by the "pci" entry further down the array. Drop the entry and start the iteration at index 0 so the map no longer needs an explanation for the skipped element. Signed-off-by: Guixin Liu Reviewed-by: Christoph Hellwig Reviewed-by: Nilay Shroff Signed-off-by: Keith Busch --- drivers/nvme/target/configfs.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/drivers/nvme/target/configfs.c b/drivers/nvme/target/configfs.c index bde94656e4b743..a9b53fba69b80d 100644 --- a/drivers/nvme/target/configfs.c +++ b/drivers/nvme/target/configfs.c @@ -42,7 +42,6 @@ static struct nvmet_type_name_map nvmet_transport[] = { }; static const struct nvmet_type_name_map nvmet_addr_family[] = { - { NVMF_ADDR_FAMILY_PCI, "pcie" }, { NVMF_ADDR_FAMILY_IP4, "ipv4" }, { NVMF_ADDR_FAMILY_IP6, "ipv6" }, { NVMF_ADDR_FAMILY_IB, "ib" }, @@ -68,7 +67,7 @@ static ssize_t nvmet_addr_adrfam_show(struct config_item *item, char *page) u8 adrfam = to_nvmet_port(item)->disc_addr.adrfam; int i; - for (i = 1; i < ARRAY_SIZE(nvmet_addr_family); i++) { + for (i = 0; i < ARRAY_SIZE(nvmet_addr_family); i++) { if (nvmet_addr_family[i].type == adrfam) return snprintf(page, PAGE_SIZE, "%s\n", nvmet_addr_family[i].name); @@ -86,7 +85,7 @@ static ssize_t nvmet_addr_adrfam_store(struct config_item *item, if (nvmet_is_port_enabled(port, __func__)) return -EACCES; - for (i = 1; i < ARRAY_SIZE(nvmet_addr_family); i++) { + for (i = 0; i < ARRAY_SIZE(nvmet_addr_family); i++) { if (sysfs_streq(page, nvmet_addr_family[i].name)) goto found; } From 2b7982b06cc877584942d82d071a28a2a9e83603 Mon Sep 17 00:00:00 2001 From: Guixin Liu Date: Fri, 6 Nov 2026 10:27:35 +0800 Subject: [PATCH 0328/2102] nvmet: passthru: remove unreachable break statements In the nvme_admin_set_features and nvme_admin_get_features handlers of nvmet_passthru_parse_cmd(), every path of the inner switch over the feature id returns, so the break statement following the switch can never be reached. Remove them. Signed-off-by: Guixin Liu Reviewed-by: Christoph Hellwig Reviewed-by: Nilay Shroff Signed-off-by: Keith Busch --- drivers/nvme/target/passthru.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/drivers/nvme/target/passthru.c b/drivers/nvme/target/passthru.c index 6b67880c7bb2fc..32ae4b6b59bf06 100644 --- a/drivers/nvme/target/passthru.c +++ b/drivers/nvme/target/passthru.c @@ -550,7 +550,6 @@ u16 nvmet_parse_passthru_admin_cmd(struct nvmet_req *req) default: return nvmet_passthru_get_set_features(req); } - break; case nvme_admin_get_features: switch (le32_to_cpu(req->cmd->features.fid)) { case NVME_FEAT_ASYNC_EVENT: @@ -564,7 +563,6 @@ u16 nvmet_parse_passthru_admin_cmd(struct nvmet_req *req) default: return nvmet_passthru_get_set_features(req); } - break; case nvme_admin_identify: switch (req->cmd->identify.cns) { case NVME_ID_CNS_CS_CTRL: From 66e3ef5dad6d22a79cb32b614d2a37a166a5437b Mon Sep 17 00:00:00 2001 From: Guixin Liu Date: Fri, 6 Nov 2026 10:27:36 +0800 Subject: [PATCH 0329/2102] nvmet-pci-epf: don't drain the never-populated SQ list nvmet_pci_epf_delete_sq() calls nvmet_pci_epf_drain_queue() on the submission queue, but IOD links are only ever added to the completion queue list, so the SQ list is always empty and the call is a no-op. Remove it. Signed-off-by: Guixin Liu Reviewed-by: Christoph Hellwig Reviewed-by: Nilay Shroff Signed-off-by: Keith Busch --- drivers/nvme/target/pci-epf.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/drivers/nvme/target/pci-epf.c b/drivers/nvme/target/pci-epf.c index cfc52454325ba7..7a08d9424d95dc 100644 --- a/drivers/nvme/target/pci-epf.c +++ b/drivers/nvme/target/pci-epf.c @@ -1432,8 +1432,6 @@ static u16 nvmet_pci_epf_delete_sq(struct nvmet_ctrl *tctrl, u16 sqid) destroy_workqueue(sq->iod_wq); sq->iod_wq = NULL; - nvmet_pci_epf_drain_queue(sq); - if (sq->nvme_sq.ctrl) nvmet_sq_destroy(&sq->nvme_sq); From 4a5aeebf1a00360bcc53c9e29fcd8d47aefa4c1d Mon Sep 17 00:00:00 2001 From: Yingjie Wang <1075151112@qq.com> Date: Fri, 6 Nov 2026 14:25:16 +0800 Subject: [PATCH 0330/2102] nvme: avoid wrapping admin_timeout and io_timeout NVME_ADMIN_TIMEOUT and NVME_IO_TIMEOUT multiply the admin_timeout and io_timeout module parameters by HZ in unsigned int arithmetic, and nvme_fw_act_work() does the same through secs_to_jiffies(). The parameters accept any unsigned int, so values above UINT_MAX / HZ wrap. With HZ=1000, io_timeout=4294968 becomes 704 jiffies, and a controller created afterwards times out I/O after 0.7 seconds instead of about 49.7 days. On 32-bit systems, results above MAX_JIFFY_OFFSET are also unsafe relative delays and can be treated as already expired. These large values are used in practice. AWS documents nvme_core.io_timeout=4294967295 for EBS volumes and says Amazon Linux uses it by default. With HZ=1000, the current code happens to wrap this setting to 4294966296 jiffies, which still behaves as a long timeout on 64-bit systems. Add nvme_timeout_to_jiffies(), which caps the seconds value so that the result fits the u32 timeout fields and stays within MAX_JIFFY_OFFSET for 32-bit timers, and use it for both macros and for the firmware activation wait. On 64-bit kernels every timeout that did not wrap is unchanged. Larger values saturate instead of being rejected so that the documented setting keeps a long timeout. Fixes: 8ae4e4477d8f ("nvme: update timeout module parameter type") Cc: stable@vger.kernel.org Signed-off-by: Yingjie Wang <1075151112@qq.com> Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/host/core.c | 2 +- drivers/nvme/host/nvme.h | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/drivers/nvme/host/core.c b/drivers/nvme/host/core.c index f4aa02869b7904..5b642b5aec1abc 100644 --- a/drivers/nvme/host/core.c +++ b/drivers/nvme/host/core.c @@ -4903,7 +4903,7 @@ static void nvme_fw_act_work(struct work_struct *work) if (ctrl->mtfa) fw_act_timeout = jiffies + msecs_to_jiffies(ctrl->mtfa * 100); else - fw_act_timeout = jiffies + secs_to_jiffies(admin_timeout); + fw_act_timeout = jiffies + NVME_ADMIN_TIMEOUT; nvme_quiesce_io_queues(ctrl); while (nvme_ctrl_pp_status(ctrl)) { diff --git a/drivers/nvme/host/nvme.h b/drivers/nvme/host/nvme.h index 8833a463f1c846..2543e52d6358a6 100644 --- a/drivers/nvme/host/nvme.h +++ b/drivers/nvme/host/nvme.h @@ -22,11 +22,20 @@ extern const struct pr_ops nvme_pr_ops; +/* Seconds to jiffies, capped for the u32 timeouts and timer delays */ +static inline unsigned int nvme_timeout_to_jiffies(unsigned int timeout) +{ + unsigned long max_secs; + + max_secs = min_t(unsigned long, UINT_MAX, MAX_JIFFY_OFFSET) / HZ; + return min_t(unsigned long, timeout, max_secs) * HZ; +} + extern unsigned int nvme_io_timeout; -#define NVME_IO_TIMEOUT (nvme_io_timeout * HZ) +#define NVME_IO_TIMEOUT nvme_timeout_to_jiffies(nvme_io_timeout) extern unsigned int admin_timeout; -#define NVME_ADMIN_TIMEOUT (admin_timeout * HZ) +#define NVME_ADMIN_TIMEOUT nvme_timeout_to_jiffies(admin_timeout) #define NVME_DEFAULT_KATO 5 From 1e1d36e7610fc2c2c425ea246caf8ea0380d5fd6 Mon Sep 17 00:00:00 2001 From: Kyle Smith Date: Thu, 5 Nov 2026 21:54:38 +0000 Subject: [PATCH 0331/2102] nvme: Fix potential gendisk leak in nvme_alloc_ns Multiple BUGs were seen after the following sequence: 1) ctrl A in subsys A allocs ns nvmeAcAn1 and ns_head nvmeAn1 and sets both as live 2) ctrl B in subsys A allocs ns nvmeAcBn1 under ns_head nvmeAn1, but is interrupted or stalled between nvme_init_ns_head and healthy return 3) the namespace is removed from subsystem, triggering rescan 4) nvmeAcAn1 completes nvme_ns_remove 5) nvmeAcBn1 allocation returns through an error pathway in nvme_alloc_ns In this sequence, when nvmeAcBn1 returns, it is the last path and has the responsibility of shutting down the live ns_head, but does not call nvme_mpath_shutdown_disk. Failure to call nvme_mpath_shutdown_disk leaves the gendisk active in sysfs/devfs while components around it are freed. The result is that a new nvme_ns_head with the same namespace number cannot be created in sysfs and freed memory can be accessed through remaining userspace files. Most observed panics were seen from paths utilizing nvme_find_path, such as nuse_show or blkdev_ioctl, though occasionally corruption of the dpm list was detected as well. Fix here is to simply keep ns_head cleanup the same as nvme_ns_remove. This ensures we don't break delayed removal and that we clean up the gendisk when appropriate. Signed-off-by: Kyle Smith Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/host/core.c | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/drivers/nvme/host/core.c b/drivers/nvme/host/core.c index 5b642b5aec1abc..f874a6e3b4b1d6 100644 --- a/drivers/nvme/host/core.c +++ b/drivers/nvme/host/core.c @@ -4378,24 +4378,16 @@ static void nvme_alloc_ns(struct nvme_ctrl *ctrl, struct nvme_ns_info *info) mutex_lock(&ctrl->subsys->lock); list_del_rcu(&ns->siblings); if (list_empty(&ns->head->list)) { - list_del_init(&ns->head->entry); - /* - * If multipath is not configured, we still create a namespace - * head (nshead), but head->disk is not initialized in that - * case. As a result, only a single reference to nshead is held - * (via kref_init()) when it is created. Therefore, ensure that - * we do not release the reference to nshead twice if head->disk - * is not present. - */ - if (ns->head->disk) - last_path = true; + if (!nvme_mpath_queue_if_no_path(ns->head)) + list_del_init(&ns->head->entry); + last_path = true; } mutex_unlock(&ctrl->subsys->lock); /* guarantee not available in head->list */ synchronize_srcu(&ns->head->srcu); if (last_path) - nvme_put_ns_head(ns->head); + nvme_mpath_remove_disk(ns->head); nvme_put_ns_head(ns->head); out_cleanup_disk: put_disk(disk); From fc991838ef25f1cab9ff34b55b39f16d95ed39b3 Mon Sep 17 00:00:00 2001 From: Qiliang Yuan Date: Tue, 3 Nov 2026 01:28:02 -0500 Subject: [PATCH 0332/2102] nvme: remove namespaces in parallel nvme_remove_namespaces() removes the namespaces of a controller one after another. Each removal waits for RCU grace periods in del_gendisk() for the namespace and for its multipath head, about 20 ms in all. Deleting a controller, such as disconnecting from a fabrics target, thus takes time proportional to its namespace count, over a second for 64 namespaces. Scanning had the same problem until commit 4e893ca81170 ("nvme_core: scan namespaces asynchronously") made it add namespaces in parallel. Remove the namespaces through an async domain the same way, and wait for all of them before returning. Each removal still waits about 20 ms, but the waits now overlap: a grace period is system-wide, so removals that wait at the same time are released by the same grace periods instead of each needing its own. Disconnect time from a target on the same host, over tcp to 127.0.0.1 and over nvme-loop, with 4 I/O queues, median of 3 runs on each of two boots per kernel: namespaces transport before after 8 tcp 170 / 171 ms 85 / 91 ms 32 tcp 628 / 628 ms 294 / 293 ms 64 tcp 1201 / 1308 ms 533 / 550 ms 64 loop 1988 / 1913 ms 1283 / 1200 ms Signed-off-by: Qiliang Yuan Reviewed-by: Nilay Shroff Reviewed-by: Christoph Hellwig Reviewed-by: Hannes Reinecke Reviewed-by: Daniel Wagner Signed-off-by: Keith Busch --- drivers/nvme/host/core.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/drivers/nvme/host/core.c b/drivers/nvme/host/core.c index f874a6e3b4b1d6..ed44d7882dd40b 100644 --- a/drivers/nvme/host/core.c +++ b/drivers/nvme/host/core.c @@ -4722,6 +4722,11 @@ static void nvme_scan_work(struct work_struct *work) #endif } +static void nvme_ns_remove_async(void *data, async_cookie_t cookie) +{ + nvme_ns_remove(data); +} + /* * This function iterates the namespace list unlocked to allow recovery from * controller failure. It is up to the caller to ensure the namespace list is @@ -4731,6 +4736,7 @@ void nvme_remove_namespaces(struct nvme_ctrl *ctrl) { struct nvme_ns *ns, *next; LIST_HEAD(ns_list); + ASYNC_DOMAIN(domain); /* * make sure to requeue I/O to all namespaces as these @@ -4764,8 +4770,13 @@ void nvme_remove_namespaces(struct nvme_ctrl *ctrl) list_splice_init_srcu(&ctrl->namespaces, &ns_list, &ctrl->srcu); mutex_unlock(&ctrl->namespaces_lock); + /* + * Remove the namespaces in parallel, as each removal waits for several + * RCU grace periods. + */ list_for_each_entry_safe(ns, next, &ns_list, list) - nvme_ns_remove(ns); + async_schedule_domain(nvme_ns_remove_async, ns, &domain); + async_synchronize_full_domain(&domain); } EXPORT_SYMBOL_GPL(nvme_remove_namespaces); From 9b657c565984f28976b1e471e3ce2f81cc269238 Mon Sep 17 00:00:00 2001 From: Yaohan Li Date: Thu, 5 Nov 2026 19:41:49 +0800 Subject: [PATCH 0333/2102] nvme: stop asynchronous event work before ANA teardown NVMe ANA work has several producers, including ANA AER completion, namespace scanning and failover processing. An AER completion can queue ana_work for an ANA notice and can separately queue async_event_work, which sends the AEN uevent and submits the next asynchronous event request. These work items access controller-owned state during asynchronous processing. This issue was investigated and the fix was developed with AI assistance (ZCode/GLM-4). Fixes: 0d0b660f214dc ("nvme: add ANA support") Cc: stable@vger.kernel.org Signed-off-by: Yaohan Li Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/host/core.c | 9 +++++++++ drivers/nvme/host/multipath.c | 7 +++++++ 2 files changed, 16 insertions(+) diff --git a/drivers/nvme/host/core.c b/drivers/nvme/host/core.c index ed44d7882dd40b..cd0df9b038063a 100644 --- a/drivers/nvme/host/core.c +++ b/drivers/nvme/host/core.c @@ -5198,6 +5198,15 @@ EXPORT_SYMBOL_GPL(nvme_start_ctrl); void nvme_uninit_ctrl(struct nvme_ctrl *ctrl) { nvme_stop_keep_alive(ctrl); + + /* + * An AER completion can queue async_event_work; drain it before the + * controller's final release. Note that ana_work has additional + * producers (namespace scanning via nvme_scan_work, and the failover + * path in nvme_failover_req), which is why nvme_mpath_uninit() + * separately cancels ana_work after this point. + */ + cancel_work_sync(&ctrl->async_event_work); nvme_hwmon_exit(ctrl); nvme_fault_inject_fini(&ctrl->fault_inject); dev_pm_qos_hide_latency_tolerance(ctrl->device); diff --git a/drivers/nvme/host/multipath.c b/drivers/nvme/host/multipath.c index ae8059366b57d4..27facdbb3d4c03 100644 --- a/drivers/nvme/host/multipath.c +++ b/drivers/nvme/host/multipath.c @@ -1608,6 +1608,13 @@ int nvme_mpath_init_identify(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) void nvme_mpath_uninit(struct nvme_ctrl *ctrl) { + /* + * ANA work can be queued by nvme_handle_aen_notice, nvme_scan_work, + * and nvme_failover_req. Drain remaining work before releasing the ANA + * resources. + */ + cancel_work_sync(&ctrl->ana_work); + kvfree(ctrl->ana_log_buf); ctrl->ana_log_buf = NULL; ctrl->ana_log_size = 0; From 82dd68297483afdc3be48e9d77f2dc4adb7a6941 Mon Sep 17 00:00:00 2001 From: Yuho Choi Date: Thu, 22 Oct 2026 00:58:18 -0400 Subject: [PATCH 0334/2102] nvme-pci: shut down the controller if disabling the HMB fails on suspend nvme_suspend() disables the host memory buffer before it moves the controller to a non-operational power state, as host memory access may not work in a system suspend state. It only treats a negative return from nvme_set_host_mem() as a failure, though. If the controller fails the Set Features command with an NVMe status, the HMB stays enabled and the controller is suspended with it in use. On resume, nvme_setup_host_mem() then tries to enable the buffer again. If the controller rejects that, the buffer is freed while the controller can still access it, and the reset that nvme_resume() falls back to is not scheduled, as the controller is still LIVE. Handle a positive status like the power state change below does: shut the controller down, so that it no longer accesses the buffer and is reset on resume. Fixes: e5ad96f388b7 ("nvme-pci: disable hmb on idle suspend") Assisted-by: LLM Signed-off-by: Yuho Choi Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/host/pci.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/nvme/host/pci.c b/drivers/nvme/host/pci.c index f899015ae40012..66496c4ba8048a 100644 --- a/drivers/nvme/host/pci.c +++ b/drivers/nvme/host/pci.c @@ -4211,6 +4211,14 @@ static int nvme_suspend(struct device *dev) ret = nvme_set_host_mem(ndev, 0); if (ret < 0) goto unfreeze; + if (ret) { + /* + * The controller may still access the HMB. Shut it + * down instead, which forces a reset on resume. + */ + ret = nvme_disable_prepare_reset(ndev, true); + goto unfreeze; + } } ret = nvme_get_power_state(ctrl, &ndev->last_ps); From 284894b212b5895047c4159525467510d707de5a Mon Sep 17 00:00:00 2001 From: Avi Weiss Date: Thu, 22 Oct 2026 10:19:34 +0300 Subject: [PATCH 0335/2102] nvme-tcp: wait for in-flight TLS handshake callback When nvme_tcp_start_tls() times out or is interrupted, tls_handshake_cancel() can return false after handshake_complete() marks the request completed, but before nvme_tcp_tls_done() finishes. Error cleanup can then release the queue while the callback still accesses it. Wait for queue->tls_complete when cancellation loses, before continuing cleanup. Preserve the original timeout or signal error. This follows the cancellation/completion synchronization used in SunRPC for: - commit d00e32f84ca1 ("sunrpc: wait for in-flight TLS handshake callback when cancel loses race") - commit a89dd5974588 ("SUNRPC: wait for in-flight client TLS handshake callback") Fixes: be8e82caa685 ("nvme-tcp: enable TLS handshake upcall") Signed-off-by: Avi Weiss Reviewed-by: Hannes Reinecke Signed-off-by: Keith Busch --- drivers/nvme/host/tcp.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/nvme/host/tcp.c b/drivers/nvme/host/tcp.c index 7ecc6c007f8d4f..2587db92a3a24e 100644 --- a/drivers/nvme/host/tcp.c +++ b/drivers/nvme/host/tcp.c @@ -1992,7 +1992,8 @@ static int nvme_tcp_start_tls(struct nvme_ctrl *nctrl, dev_err(nctrl->device, "queue %d: TLS handshake failed, error %d\n", qid, ret); - tls_handshake_cancel(queue->sock->sk); + if (!tls_handshake_cancel(queue->sock->sk)) + wait_for_completion(&queue->tls_complete); } else { if (queue->tls_err) { dev_err(nctrl->device, From f3c20e42ff5628b93ed0084154cf62082a2157b2 Mon Sep 17 00:00:00 2001 From: Andrew Stellman Date: Fri, 6 Nov 2026 08:43:13 -0500 Subject: [PATCH 0336/2102] nvmet: accept ANA group ID NVMET_MAX_ANAGRPS in configfs nvmet_ns_ana_grpid_store() accepts an ANA group ID in the range 1..NVMET_MAX_ANAGRPS, and nvmet_ana_groups_make_group() accepts 2..NVMET_MAX_ANAGRPS (group 1 is the default group). Both then pass the ID through array_index_nospec() with NVMET_MAX_ANAGRPS as the size. That helper treats the size as an exclusive upper bound, so the maximum valid ID, 128, is rewritten to 0. nvmet_ana_group_enabled[] is NVMET_MAX_ANAGRPS + 1 entries wide, so index 128 is a valid slot, and the controller advertises ANAGRPMAX = NVMET_MAX_ANAGRPS. NVMe Base Specification 2.4, section 8.1.1 (Asymmetric Namespace Access Reporting), "ANA Groups", defines a valid ANA Group Identifier as "a non-zero value that is less than or equal to ANAGRPMAX". There are two visible effects. Writing 128 to a namespace's ana_grpid succeeds but the namespace lands in the reserved group 0, which Identify Namespace then reports. Creating and removing ports/N/ana_groups/128 increments slot 0 on create but decrements slot 128 on release, leaving nvmet_ana_group_enabled[128] at 0xffffffff, so every subsequent ANA log page reports a group 128 with no namespaces in the Inaccessible state. Use NVMET_MAX_ANAGRPS + 1 as the array_index_nospec() bound at both sites, matching the array's actual size. A namespace assigned to group 128 now follows the same path as any other group: its ANA state is Inaccessible until ports/N/ana_groups/128 is created and configured, where before it was placed in group 0, whose ana_state entry is never set. That entry stays 0, which isn't a valid ANA state, so nvmet_check_ana_state() let I/O through. Fixes: 20dc66f2d76b ("nvme: prevent potential spectre v1 gadget") Signed-off-by: Andrew Stellman Signed-off-by: Keith Busch --- drivers/nvme/target/configfs.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/nvme/target/configfs.c b/drivers/nvme/target/configfs.c index a9b53fba69b80d..27c50fa533e70e 100644 --- a/drivers/nvme/target/configfs.c +++ b/drivers/nvme/target/configfs.c @@ -708,7 +708,7 @@ static ssize_t nvmet_ns_ana_grpid_store(struct config_item *item, down_write(&nvmet_ana_sem); oldgrpid = ns->anagrpid; - newgrpid = array_index_nospec(newgrpid, NVMET_MAX_ANAGRPS); + newgrpid = array_index_nospec(newgrpid, NVMET_MAX_ANAGRPS + 1); nvmet_ana_group_enabled[newgrpid]++; ns->anagrpid = newgrpid; nvmet_ana_group_enabled[oldgrpid]--; @@ -2085,7 +2085,7 @@ static struct config_group *nvmet_ana_groups_make_group( grp->grpid = grpid; down_write(&nvmet_ana_sem); - grpid = array_index_nospec(grpid, NVMET_MAX_ANAGRPS); + grpid = array_index_nospec(grpid, NVMET_MAX_ANAGRPS + 1); nvmet_ana_group_enabled[grpid]++; up_write(&nvmet_ana_sem); From ad606ae5635b68e324005aaa06421be752619dab Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Fri, 6 Nov 2026 23:00:19 +0800 Subject: [PATCH 0337/2102] nvmet: zero the entire Get Log Page transfer buffer Several fixed-size Get Log Page handlers copy only the log structure and leave the rest of the host buffer untouched. The transport buffers are not zeroed, so a host requesting more bytes than the structure receives stale kernel memory. Zero the entire transfer length before filling the buffer in the Supported Log Pages, Commands Supported and Effects, Supported Features, Endurance Group, Rotational Media Information and Reservation handlers. For the Error log, also clamp the ring walk to the requested length and propagate copy failures instead of completing with success. The Rotational Media Information handler now accepts a buffer larger than its fixed structure. Fixes: 11ad507784ed ("nvmet: add error log page cmd handler") Fixes: 83acb24e6de7 ("nvmet: implement supported log pages") Fixes: 0866bf0c3778 ("nvmet: add commands supported and effects log page") Fixes: e973c91727d4 ("nvmet: implement supported features log") Fixes: 266b652c65b4 ("nvmet: implement endurance groups") Fixes: 5fd075cdaf36 ("nvmet: implement rotational media information log") Fixes: 5a47c2080a73 ("nvmet: support reservation feature") Cc: stable@vger.kernel.org Signed-off-by: Shao Mingyin Signed-off-by: Keith Busch --- drivers/nvme/target/admin-cmd.c | 51 ++++++++++++++++++++++++++------- drivers/nvme/target/pr.c | 6 ++++ 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/drivers/nvme/target/admin-cmd.c b/drivers/nvme/target/admin-cmd.c index f12d8309864464..6732d6d078e35c 100644 --- a/drivers/nvme/target/admin-cmd.c +++ b/drivers/nvme/target/admin-cmd.c @@ -176,16 +176,35 @@ static void nvmet_execute_get_log_page_error(struct nvmet_req *req) { struct nvmet_ctrl *ctrl = req->sq->ctrl; unsigned long flags; - off_t offset = 0; + u32 offset = 0; + u32 len; u64 slot; u64 i; + u16 status = 0; + + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (status) { + nvmet_req_complete(req, status); + return; + } + + len = min_t(u32, req->transfer_len, + NVMET_ERROR_LOG_SLOTS * sizeof(struct nvme_error_slot)); spin_lock_irqsave(&ctrl->error_lock, flags); + + /* + * The NVMe base specification requires the most recent error to be + * the first log entry, so walk the ring backwards from the slot of + * the last error and stop at the end of the requested buffer. + */ slot = ctrl->err_counter % NVMET_ERROR_LOG_SLOTS; - for (i = 0; i < NVMET_ERROR_LOG_SLOTS; i++) { - if (nvmet_copy_to_sgl(req, offset, &ctrl->slots[slot], - sizeof(struct nvme_error_slot))) + for (i = 0; i < NVMET_ERROR_LOG_SLOTS && + offset + sizeof(struct nvme_error_slot) <= len; i++) { + status = nvmet_copy_to_sgl(req, offset, &ctrl->slots[slot], + sizeof(struct nvme_error_slot)); + if (status) break; if (slot == 0) @@ -195,7 +214,7 @@ static void nvmet_execute_get_log_page_error(struct nvmet_req *req) offset += sizeof(struct nvme_error_slot); } spin_unlock_irqrestore(&ctrl->error_lock, flags); - nvmet_req_complete(req, 0); + nvmet_req_complete(req, status); } static void nvmet_execute_get_supported_log_pages(struct nvmet_req *req) @@ -221,7 +240,9 @@ static void nvmet_execute_get_supported_log_pages(struct nvmet_req *req) logs->lids[NVME_LOG_RMI] = cpu_to_le32(NVME_LIDS_LSUPP); logs->lids[NVME_LOG_RESERVATION] = cpu_to_le32(NVME_LIDS_LSUPP); - status = nvmet_copy_to_sgl(req, 0, logs, sizeof(*logs)); + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (!status) + status = nvmet_copy_to_sgl(req, 0, logs, sizeof(*logs)); kfree(logs); out: nvmet_req_complete(req, status); @@ -303,7 +324,7 @@ static void nvmet_execute_get_log_page_rmi(struct nvmet_req *req) goto out; } - if (req->transfer_len != sizeof(*log)) { + if (req->transfer_len < sizeof(*log)) { status = NVME_SC_SGL_INVALID_DATA | NVME_STATUS_DNR; goto out; } @@ -321,7 +342,9 @@ static void nvmet_execute_get_log_page_rmi(struct nvmet_req *req) else log->numa = cpu_to_le16(1); - status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (!status) + status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); kfree(log); out: nvmet_req_complete(req, status); @@ -436,7 +459,9 @@ static void nvmet_execute_get_log_cmd_effects_ns(struct nvmet_req *req) goto free; } - status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (!status) + status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); free: kfree(log); out: @@ -527,7 +552,9 @@ static void nvmet_execute_get_log_page_endgrp(struct nvmet_req *req) put_unaligned_le64(host_writes, &log->hwc[0]); put_unaligned_le64(data_units_written, &log->duw[0]); copy: - status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (!status) + status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); kfree(log); out: nvmet_req_complete(req, status); @@ -610,7 +637,9 @@ static void nvmet_execute_get_log_page_features(struct nvmet_req *req) features->fis[NVME_FEAT_RESV_MASK] = cpu_to_le32(NVME_FIS_FSUPP | NVME_FIS_NSCPE); - status = nvmet_copy_to_sgl(req, 0, features, sizeof(*features)); + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (!status) + status = nvmet_copy_to_sgl(req, 0, features, sizeof(*features)); kfree(features); out: nvmet_req_complete(req, status); diff --git a/drivers/nvme/target/pr.c b/drivers/nvme/target/pr.c index 14eaa99f98fa32..b860cbe192cd29 100644 --- a/drivers/nvme/target/pr.c +++ b/drivers/nvme/target/pr.c @@ -99,6 +99,12 @@ void nvmet_execute_get_log_page_resv(struct nvmet_req *req) u64 cur_count; u64 next_count; + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (status) { + nvmet_req_complete(req, status); + return; + } + mutex_lock(&log_mgr->lock); if (!kfifo_get(&log_mgr->log_queue, &log)) goto out; From 687f3014afcd5826fa3d8f40b445f647b5a379b6 Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Fri, 6 Nov 2026 23:00:20 +0800 Subject: [PATCH 0338/2102] nvmet: zns: return the namespace lookup error for Identify nvmet_execute_identify_ns_zns() jumps to done when nvmet_req_find_ns() fails, and that label overwrites status with a successful copy of the zeroed identify data. An Identify with CNS 05h and CSI 02h for a missing NSID therefore completes with SUCCESS and zeroed data instead of Invalid Namespace. Return the lookup error instead. Fixes: aaf2e048af27 ("nvmet: add ZBD over ZNS backend support") Cc: stable@vger.kernel.org Signed-off-by: Shao Mingyin Signed-off-by: Keith Busch --- drivers/nvme/target/zns.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/nvme/target/zns.c b/drivers/nvme/target/zns.c index 92f5c1435582ec..cea05b4bc7409c 100644 --- a/drivers/nvme/target/zns.c +++ b/drivers/nvme/target/zns.c @@ -108,7 +108,7 @@ void nvmet_execute_identify_ns_zns(struct nvmet_req *req) status = nvmet_req_find_ns(req); if (status) - goto done; + goto out; if (nvmet_ns_revalidate(req->ns)) { mutex_lock(&req->ns->subsys->lock); @@ -140,7 +140,6 @@ void nvmet_execute_identify_ns_zns(struct nvmet_req *req) mar--; id_zns->mar = cpu_to_le32(mar); -done: status = nvmet_copy_to_sgl(req, 0, id_zns, sizeof(*id_zns)); out: kfree(id_zns); From 4d8996081dd19c177c44a83e74715ddf220e3452 Mon Sep 17 00:00:00 2001 From: Vineet Gupta Date: Thu, 5 Nov 2026 09:57:45 -0800 Subject: [PATCH 0339/2102] kbuild: move gcc's -Wconstant-logical-operand to W=2 GCC 17 adds -Wconstant-logical-operand to -Wall. It warns when an operand of && or || folds to a constant other than 0 or 1. Unlike clang's version, it also checks constant left operands and operators that come from a macro expansion. With CONFIG_WERROR=y, an x86 defconfig build fails in prepare0: arch/x86/include/asm/cpufeature.h:72:36: error: use of logical '&&' with constant operand '4194304' [-Werror=constant-logical-operand] The warning is meant to catch && written for &. Kernel history has no such catch. Of the 13 earlier kernel fixes for clang's version, only commit dd7fe5d9fd6a ("rtc: max31335: Fix comparison in max31335_volatile_reg()") fixed a bug that the warning found. Commit 394b52462020 ("drm/i915/gem: fix bitwise and logical AND mixup") fixed a & written for &&, which the warning cannot see. The other fixes rewrote correct code. In GCC's own tree, the warning found two sites since it was added, and both were false positives. Disable the warning for GCC unless W=2 is given. Keep clang's version, which skips macros and constant left operands. Suggested-by: Borislav Petkov Link: https://lore.kernel.org/all/20261104160722.1637541-1-vineet.gupta@linux.dev/ Signed-off-by: Vineet Gupta Cc: stable@vger.kernel.org Acked-by: Nick Desaulniers Reviewed-by: Nathan Chancellor Link: https://patch.msgid.link/20261105175748.3057520-1-vineet.gupta@linux.dev Signed-off-by: Nathan Chancellor --- scripts/Kconfig.toolchain | 3 +++ scripts/Makefile.warn | 1 + 2 files changed, 4 insertions(+) diff --git a/scripts/Kconfig.toolchain b/scripts/Kconfig.toolchain index 2acbd40a38f16f..1d68075f046912 100644 --- a/scripts/Kconfig.toolchain +++ b/scripts/Kconfig.toolchain @@ -233,6 +233,9 @@ config CC_OPT_WNO_FORMAT_OVERFLOW config CC_OPT_WNO_STRINGOP_TRUNCATION def_string "$(cc-option-str,-Wno-stringop-truncation)" +config CC_OPT_WNO_CONSTANT_LOGICAL_OPERAND + def_string "$(cc-option-str,-Wno-constant-logical-operand)" + config CC_HAS_COUNTED_BY bool # clang needs to be at least 20.1.0 to avoid potential crashes diff --git a/scripts/Makefile.warn b/scripts/Makefile.warn index 556fa249ca071a..03b677bdbb0af1 100644 --- a/scripts/Makefile.warn +++ b/scripts/Makefile.warn @@ -167,6 +167,7 @@ endif ifdef CONFIG_CC_IS_GCC KBUILD_CFLAGS += -Wno-maybe-uninitialized +KBUILD_CFLAGS += $(CONFIG_CC_OPT_WNO_CONSTANT_LOGICAL_OPERAND) endif endif From 2d6b75e0a6f2c779c87670283b0c2f6271ca5445 Mon Sep 17 00:00:00 2001 From: Arnaldo Carvalho de Melo Date: Sat, 7 Nov 2026 17:19:19 -0300 Subject: [PATCH 0340/2102] tools headers UAPI: Sync linux/if_addr.h with the kernel sources To pick up the changes in: commit ebff14be20c3f2c0 ("net: add AF_PACKET multicast dumps") That just rebuilds perf, silencing this build warning. This addresses this perf build warning: Warning: Kernel ABI header differences: diff -u tools/include/uapi/linux/if_addr.h include/uapi/linux/if_addr.h Please see tools/include/uapi/README for further details. Cc: Yuyang Huang Signed-off-by: Arnaldo Carvalho de Melo --- tools/include/uapi/linux/if_addr.h | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/include/uapi/linux/if_addr.h b/tools/include/uapi/linux/if_addr.h index 7fb630b7fe311a..0a1ad9ebb47bed 100644 --- a/tools/include/uapi/linux/if_addr.h +++ b/tools/include/uapi/linux/if_addr.h @@ -57,6 +57,7 @@ enum { #define IFA_F_NOPREFIXROUTE 0x200 #define IFA_F_MCAUTOJOIN 0x400 #define IFA_F_STABLE_PRIVACY 0x800 +#define IFA_F_GLOBAL 0x1000 struct ifa_cacheinfo { __u32 ifa_prefered; From 9313d37f8a515d2c06ef309c6b18d3fa47d71dc6 Mon Sep 17 00:00:00 2001 From: Arnaldo Carvalho de Melo Date: Sat, 7 Nov 2026 17:19:21 -0300 Subject: [PATCH 0341/2102] tools arch x86: Sync the cpufeatures.h copy with the kernel sources To pick up the changes in: commit 732cf7ec3224f05f ("x86/cpufeatures: Add Page modification logging") commit 1ee97d0f7b20e1f7 ("x86/cpufeatures: Add X86_FEATURE_RMPOPT feature flag") commit 228200f695c0f92c ("x86/CPU/AMD: Fix Zen5 TLB sizes reporting") commit ae1d2082d93bc046 ("x86/bugs: Adapt SRSO mitigation to Zen6") That just rebuilds perf, silencing this build warning. This addresses this perf build warning: Warning: Kernel ABI header differences: diff -u tools/arch/x86/include/asm/cpufeatures.h arch/x86/include/asm/cpufeatures.h Please see tools/include/uapi/README for further details. Cc: Ashish Kalra Cc: Borislav Petkov (AMD) Cc: Nikunj A Dadhania Signed-off-by: Arnaldo Carvalho de Melo --- tools/arch/x86/include/asm/cpufeatures.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tools/arch/x86/include/asm/cpufeatures.h b/tools/arch/x86/include/asm/cpufeatures.h index fe84cf4e97d35a..61930f0d457865 100644 --- a/tools/arch/x86/include/asm/cpufeatures.h +++ b/tools/arch/x86/include/asm/cpufeatures.h @@ -76,7 +76,7 @@ #define X86_FEATURE_K8 ( 3*32+ 4) /* Opteron, Athlon64 */ #define X86_FEATURE_ZEN5 ( 3*32+ 5) /* CPU based on Zen5 microarchitecture */ #define X86_FEATURE_ZEN6 ( 3*32+ 6) /* CPU based on Zen6 microarchitecture */ -/* Free ( 3*32+ 7) */ +#define X86_FEATURE_RMPOPT ( 3*32+ 7) /* Support for AMD RMPOPT instruction */ #define X86_FEATURE_CONSTANT_TSC ( 3*32+ 8) /* "constant_tsc" TSC ticks at a constant rate */ /* free: was #define X86_FEATURE_UP ( 3*32+ 9) * "up" SMP kernel running on UP */ #define X86_FEATURE_ART ( 3*32+10) /* "art" Always running timer (ART) */ @@ -238,6 +238,7 @@ // free: was #define X86_FEATURE_PVUNLOCK ( 8*32+20) /* PV unlock function */ #define X86_FEATURE_VCPUPREEMPT ( 8*32+21) /* PV vcpu_is_preempted function */ #define X86_FEATURE_TDX_GUEST ( 8*32+22) /* "tdx_guest" Intel Trust Domain Extensions Guest */ +#define X86_FEATURE_PML ( 8*32+23) /* AMD Page Modification logging */ /* Intel-defined CPU features, CPUID level 0x00000007:0 (EBX), word 9 */ #define X86_FEATURE_FSGSBASE ( 9*32+ 0) /* "fsgsbase" RDFSBASE, WRFSBASE, RDGSBASE, WRGSBASE instructions*/ @@ -430,6 +431,7 @@ #define X86_FEATURE_SUCCOR (17*32+ 1) /* "succor" Uncorrectable error containment and recovery */ #define X86_FEATURE_CPPC_PERF_PRIO (17*32+ 2) /* CPPC Floor Perf support */ #define X86_FEATURE_SMCA (17*32+ 3) /* "smca" Scalable MCA */ +#define X86_FEATURE_BTB_CTX_ISOLATION (17*32+ 4) /* AMD: Branch predictions contexts isolated */ /* Intel-defined CPU features, CPUID level 0x00000007:0 (EDX), word 18 */ #define X86_FEATURE_AVX512_4VNNIW (18*32+ 2) /* "avx512_4vnniw" AVX-512 Neural Network Instructions */ @@ -485,6 +487,8 @@ #define X86_FEATURE_AUTOIBRS (20*32+ 8) /* Automatic IBRS */ #define X86_FEATURE_NO_SMM_CTL_MSR (20*32+ 9) /* SMM_CTL MSR is not present */ +#define X86_FEATURE_L2_TLB_SIZE_X32 (20*32+14) /* L2 TLB sizes are encoded as multiples of 32 */ + #define X86_FEATURE_GP_ON_USER_CPUID (20*32+17) /* User CPUID faulting */ #define X86_FEATURE_PREFETCHI (20*32+20) /* Prefetch Data/Instruction to Cache Level */ From 55dc07f739ccda28373f1b5d29e2d3b8c574d57c Mon Sep 17 00:00:00 2001 From: Arnaldo Carvalho de Melo Date: Sat, 7 Nov 2026 17:19:22 -0300 Subject: [PATCH 0342/2102] tools arch x86: Sync the msr-index.h copy with the kernel sources To pick up the changes in: commit 15d974be0a3ba370 ("x86/sev: Initialize RMPOPT configuration MSRs") commit 46cff0be63379264 ("x86/mce: Add enumeration for Intel bitfix filter reset") commit c4fabb67a47f8103 ("perf/x86/intel: Support arch-PEBS based SIMD/eGPRs sampling") commit ac5cc691eb4a7b60 ("x86/thermal: Add bit definitions for Intel Directed Package Thermal Interrupt") That introduce these new entries in the string tables: $ tools/perf/trace/beauty/tracepoints/x86_msr.sh tools/arch/x86/include/asm > before.txt $ cp arch/x86/include/asm/msr-index.h tools/arch/x86/include/asm/msr-index.h $ tools/perf/trace/beauty/tracepoints/x86_msr.sh tools/arch/x86/include/asm > after.txt $ diff -u before.txt after.txt [0xc0010134 - x86_AMD_V_KVM_MSRs_offset] = "AMD64_GUEST_TSC_FREQ", [0xc0010136 - x86_AMD_V_KVM_MSRs_offset] = "AMD64_RMP_CFG", [0xc0010138 - x86_AMD_V_KVM_MSRs_offset] = "AMD64_SAVIC_CONTROL", + [0xc0010139 - x86_AMD_V_KVM_MSRs_offset] = "AMD64_RMPOPT_BASE", [0xc0010140 - x86_AMD_V_KVM_MSRs_offset] = "AMD64_OSVW_ID_LENGTH", [0xc0010141 - x86_AMD_V_KVM_MSRs_offset] = "AMD64_OSVW_STATUS", [0xc0010200 - x86_AMD_V_KVM_MSRs_offset] = "F15H_PERF_CTL", This addresses this perf build warning: Warning: Kernel ABI header differences: diff -u tools/arch/x86/include/asm/msr-index.h arch/x86/include/asm/msr-index.h Please see tools/include/uapi/README for further details. Cc: Ashish Kalra Cc: Dapeng Mi Cc: Ricardo Neri Cc: Tony Luck Signed-off-by: Arnaldo Carvalho de Melo --- tools/arch/x86/include/asm/msr-index.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tools/arch/x86/include/asm/msr-index.h b/tools/arch/x86/include/asm/msr-index.h index 9c26d4075c5f42..c0914829a925d5 100644 --- a/tools/arch/x86/include/asm/msr-index.h +++ b/tools/arch/x86/include/asm/msr-index.h @@ -114,6 +114,8 @@ #define MSR_IA32_CORE_CAPS_INTEGRITY_CAPS BIT(MSR_IA32_CORE_CAPS_INTEGRITY_CAPS_BIT) #define MSR_IA32_CORE_CAPS_SPLIT_LOCK_DETECT_BIT 5 #define MSR_IA32_CORE_CAPS_SPLIT_LOCK_DETECT BIT(MSR_IA32_CORE_CAPS_SPLIT_LOCK_DETECT_BIT) +#define MSR_IA32_CORE_CAPS_BFF_RESET_BIT 9 +#define MSR_IA32_CORE_CAPS_BFF_RESET BIT(MSR_IA32_CORE_CAPS_BFF_RESET_BIT) #define MSR_PKG_CST_CONFIG_CONTROL 0x000000e2 #define NHM_C3_AUTO_DEMOTE (1UL << 25) @@ -768,6 +770,9 @@ #define MSR_AMD64_SEG_RMP_ENABLED_BIT 0 #define MSR_AMD64_SEG_RMP_ENABLED BIT_ULL(MSR_AMD64_SEG_RMP_ENABLED_BIT) #define MSR_AMD64_RMP_SEGMENT_SHIFT(x) (((x) & GENMASK_ULL(13, 8)) >> 8) +#define MSR_AMD64_RMPOPT_BASE 0xc0010139 +#define MSR_AMD64_RMPOPT_ENABLE_BIT 0 +#define MSR_AMD64_RMPOPT_ENABLE BIT_ULL(MSR_AMD64_RMPOPT_ENABLE_BIT) #define MSR_SVSM_CAA 0xc001f000 @@ -1014,6 +1019,7 @@ #define THERM_INT_HIGH_ENABLE (1 << 0) #define THERM_INT_LOW_ENABLE (1 << 1) #define THERM_INT_PLN_ENABLE (1 << 24) +#define THERM_INT_DPTI_ENABLE (1 << 25) #define MSR_IA32_THERM_STATUS 0x0000019c @@ -1043,6 +1049,7 @@ #define PACKAGE_THERM_STATUS_PROCHOT (1 << 0) #define PACKAGE_THERM_STATUS_POWER_LIMIT (1 << 10) +#define PACKAGE_THERM_STATUS_DPTI_ACK (1 << 25) #define PACKAGE_THERM_STATUS_HFI_UPDATED (1 << 26) #define MSR_IA32_PACKAGE_THERM_INTERRUPT 0x000001b2 From 2b81439ec96197487bb43e3377dad207a0b7912f Mon Sep 17 00:00:00 2001 From: Arnaldo Carvalho de Melo Date: Sat, 7 Nov 2026 17:19:22 -0300 Subject: [PATCH 0343/2102] tools headers: Sync UAPI sound/asound.h with the kernel sources To pick up the changes in: commit 7a0b09d72d3710a6 ("ALSA: uapi: Add hwdep interface ID for caiaq devices") That don't result in changes to the string tables generated from this header. This addresses this perf build warning: Warning: Kernel ABI header differences: diff -u tools/perf/trace/beauty/include/uapi/sound/asound.h include/uapi/sound/asound.h Please see tools/include/uapi/README for further details. Cc: Niko Huuskonen Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/trace/beauty/include/uapi/sound/asound.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/perf/trace/beauty/include/uapi/sound/asound.h b/tools/perf/trace/beauty/include/uapi/sound/asound.h index c11da9656e3811..767c9627324592 100644 --- a/tools/perf/trace/beauty/include/uapi/sound/asound.h +++ b/tools/perf/trace/beauty/include/uapi/sound/asound.h @@ -99,9 +99,10 @@ enum { SNDRV_HWDEP_IFACE_LINE6, /* Line6 USB processors */ SNDRV_HWDEP_IFACE_FW_MOTU, /* MOTU FireWire series */ SNDRV_HWDEP_IFACE_FW_FIREFACE, /* RME Fireface series */ + SNDRV_HWDEP_IFACE_CAIAQ, /* Native Instruments caiaq USB devices */ /* Don't forget to change the following: */ - SNDRV_HWDEP_IFACE_LAST = SNDRV_HWDEP_IFACE_FW_FIREFACE + SNDRV_HWDEP_IFACE_LAST = SNDRV_HWDEP_IFACE_CAIAQ }; struct snd_hwdep_info { From a1c4ec661d5a941ed827919d412963f5813b93ee Mon Sep 17 00:00:00 2001 From: Arnaldo Carvalho de Melo Date: Wed, 4 Nov 2026 17:17:44 -0300 Subject: [PATCH 0344/2102] perf trace beauty: Split the KVM ioctl table by direction KVM_SET_MEMORY_ATTRIBUTES2 reuses ioctl number 0xd2 with _IOWR, while KVM_SET_MEMORY_ATTRIBUTES is _IOW at the same number. The KVM table is keyed only by _IOC_NR, so both map to the same index and the generated array fails to build with -Werror=override-init. Split it the way vhost_virtio_ioctl already does: _IO/_IOW entries stay in kvm_ioctl_cmds, _IOR/_IOWR move to kvm_ioctl_read_cmds, and the lookup picks the table from the _IOC_READ bit. Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/trace/beauty/ioctl.c | 6 ++++-- tools/perf/trace/beauty/kvm_ioctl.sh | 9 +++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/tools/perf/trace/beauty/ioctl.c b/tools/perf/trace/beauty/ioctl.c index e19eb6ea361d72..9817f319d09a00 100644 --- a/tools/perf/trace/beauty/ioctl.c +++ b/tools/perf/trace/beauty/ioctl.c @@ -81,9 +81,11 @@ static size_t ioctl__scnprintf_kvm_cmd(int nr, int dir, char *bf, size_t size) { #include "trace/beauty/generated/ioctl/kvm_ioctl_array.c" static DEFINE_STRARRAY(kvm_ioctl_cmds, ""); + static DEFINE_STRARRAY(kvm_ioctl_read_cmds, ""); + struct strarray *s = (dir & _IOC_READ) ? &strarray__kvm_ioctl_read_cmds : &strarray__kvm_ioctl_cmds; - if (nr < strarray__kvm_ioctl_cmds.nr_entries && strarray__kvm_ioctl_cmds.entries[nr] != NULL) - return scnprintf(bf, size, "KVM_%s", strarray__kvm_ioctl_cmds.entries[nr]); + if (nr < s->nr_entries && s->entries[nr] != NULL) + return scnprintf(bf, size, "KVM_%s", s->entries[nr]); return scnprintf(bf, size, "(%#x, %#x, %#x)", 0xAE, nr, dir); } diff --git a/tools/perf/trace/beauty/kvm_ioctl.sh b/tools/perf/trace/beauty/kvm_ioctl.sh index bd0efd45fa9db5..8a3fedc8fcbea6 100755 --- a/tools/perf/trace/beauty/kvm_ioctl.sh +++ b/tools/perf/trace/beauty/kvm_ioctl.sh @@ -6,6 +6,15 @@ printf "static const char *kvm_ioctl_cmds[] = {\n" regex='^#[[:space:]]*define[[:space:]]+KVM_(\w+)[[:space:]]+_IO[RW]*\([[:space:]]*KVMIO[[:space:]]*,[[:space:]]*(0x[[:xdigit:]]+).*' grep -E $regex ${header_dir}/kvm.h | \ + grep -E "_IO(W)?[[:space:]]*\(" | \ + sed -r "s/$regex/\2 \1/g" | \ + grep -E -v " ((ARM|PPC|S390)_|[GS]ET_(DEBUGREGS|PIT2|XSAVE|TSC_KHZ)|CREATE_SPAPR_TCE_64)" | \ + sort | xargs printf "\t[%s] = \"%s\",\n" +printf "};\n" + +printf "static const char *kvm_ioctl_read_cmds[] = {\n" +grep -E $regex ${header_dir}/kvm.h | \ + grep -E "_IO(W)?R[[:space:]]*\(" | \ sed -r "s/$regex/\2 \1/g" | \ grep -E -v " ((ARM|PPC|S390)_|[GS]ET_(DEBUGREGS|PIT2|XSAVE|TSC_KHZ)|CREATE_SPAPR_TCE_64)" | \ sort | xargs printf "\t[%s] = \"%s\",\n" From a9186becd8b33f4bac13bef5c6de5a1391182910 Mon Sep 17 00:00:00 2001 From: Arnaldo Carvalho de Melo Date: Sat, 7 Nov 2026 17:19:23 -0300 Subject: [PATCH 0345/2102] tools headers: Sync KVM headers with the kernel sources To pick up the changes in: commit dcde2f853ff46836 ("KVM: guest_memfd: Ensure pages are not in use before conversion") commit 799c9fadc639949b ("KVM: guest_memfd: Add base support for KVM_SET_MEMORY_ATTRIBUTES2") commit 0d7fbc059f33527c ("KVM: SVM: Add Page modification logging support") That introduce these new entries in the string tables: $ tools/perf/trace/beauty/kvm_ioctl.sh tools/include/uapi/linux > before.txt $ cp include/uapi/linux/kvm.h tools/include/uapi/linux/kvm.h $ tools/perf/trace/beauty/kvm_ioctl.sh tools/include/uapi/linux > after.txt $ diff -u before.txt after.txt [0xc8] = "XEN_HVM_GET_ATTR", [0xca] = "XEN_VCPU_GET_ATTR", [0xcc] = "GET_SREGS2", + [0xd2] = "SET_MEMORY_ATTRIBUTES2", [0xd4] = "CREATE_GUEST_MEMFD", [0xd5] = "PRE_FAULT_MEMORY", [0xe0] = "CREATE_DEVICE", This addresses these perf build warnings: Warning: Kernel ABI header differences: diff -u tools/include/uapi/linux/kvm.h include/uapi/linux/kvm.h diff -u tools/arch/x86/include/uapi/asm/svm.h arch/x86/include/uapi/asm/svm.h Please see tools/include/uapi/README for further details. Cc: Ackerley Tng Cc: Nikunj A Dadhania Signed-off-by: Arnaldo Carvalho de Melo --- tools/arch/x86/include/uapi/asm/svm.h | 2 ++ tools/include/uapi/linux/kvm.h | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/tools/arch/x86/include/uapi/asm/svm.h b/tools/arch/x86/include/uapi/asm/svm.h index 010a45c9f6147f..e8067618509215 100644 --- a/tools/arch/x86/include/uapi/asm/svm.h +++ b/tools/arch/x86/include/uapi/asm/svm.h @@ -101,6 +101,7 @@ #define SVM_EXIT_AVIC_INCOMPLETE_IPI 0x401 #define SVM_EXIT_AVIC_UNACCELERATED_ACCESS 0x402 #define SVM_EXIT_VMGEXIT 0x403 +#define SVM_EXIT_PML_FULL 0x407 /* SEV-ES software-defined VMGEXIT events */ #define SVM_VMGEXIT_MMIO_READ 0x80000001ull @@ -236,6 +237,7 @@ { SVM_EXIT_AVIC_INCOMPLETE_IPI, "avic_incomplete_ipi" }, \ { SVM_EXIT_AVIC_UNACCELERATED_ACCESS, "avic_unaccelerated_access" }, \ { SVM_EXIT_VMGEXIT, "vmgexit" }, \ + { SVM_EXIT_PML_FULL, "pml_full" }, \ { SVM_VMGEXIT_MMIO_READ, "vmgexit_mmio_read" }, \ { SVM_VMGEXIT_MMIO_WRITE, "vmgexit_mmio_write" }, \ { SVM_VMGEXIT_NMI_COMPLETE, "vmgexit_nmi_complete" }, \ diff --git a/tools/include/uapi/linux/kvm.h b/tools/include/uapi/linux/kvm.h index ac2d77d1496356..8dff2fc1972e97 100644 --- a/tools/include/uapi/linux/kvm.h +++ b/tools/include/uapi/linux/kvm.h @@ -999,6 +999,7 @@ struct kvm_enable_cap { #define KVM_CAP_S390_HPAGE_2G 249 #define KVM_CAP_PPC_COMPAT_CAPS 250 #define KVM_CAP_ARM_PMU_V3_STRICT 251 +#define KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES 252 struct kvm_irq_routing_irqchip { __u32 irqchip; @@ -1653,6 +1654,21 @@ struct kvm_memory_attributes { __u64 flags; }; +/* Available with KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES */ +#define KVM_SET_MEMORY_ATTRIBUTES2 _IOWR(KVMIO, 0xd2, struct kvm_memory_attributes2) + +struct kvm_memory_attributes2 { + union { + __u64 address; + __u64 offset; + }; + __u64 size; + __u64 attributes; + __u64 flags; + __u64 error_offset; + __u64 reserved[11]; +}; + #define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) #define KVM_CREATE_GUEST_MEMFD _IOWR(KVMIO, 0xd4, struct kvm_create_guest_memfd) From 810a0c269706e0ff92912adf3680065e32034f66 Mon Sep 17 00:00:00 2001 From: Arnaldo Carvalho de Melo Date: Wed, 4 Nov 2026 17:17:45 -0300 Subject: [PATCH 0346/2102] tools headers: Sync linux/gfp_types.h with the kernel sources To pick up the changes in: commit cbbed3c303f9ea63 ("mm: adjust out-dated document of __GFP_NOFAIL") commit ff566742e9cf59b0 ("mm: Move default_gfp() into gfp_types.h") commit f6c786a95e950931 ("mm: gfp_types: fix __GFP_ACCOUNT, GFP_KERNEL_ACCOUNT documentation") commit ff566742e9cf59b0 ("mm: Move default_gfp() into gfp_types.h") also moved __default_gfp()/default_gfp() out of include/linux/gfp.h, do the same in the tools/ copy of gfp.h, otherwise the two definitions collide with the ones now in gfp_types.h. That just rebuilds perf, silencing this build warning. This addresses this perf build warning: Warning: Kernel ABI header differences: diff -u tools/include/linux/gfp_types.h include/linux/gfp_types.h Please see tools/include/uapi/README for further details. Cc: Johannes Weiner Cc: Kees Cook Cc: Wei Yang Signed-off-by: Arnaldo Carvalho de Melo --- tools/include/linux/gfp.h | 4 ---- tools/include/linux/gfp_types.h | 11 ++++++++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/tools/include/linux/gfp.h b/tools/include/linux/gfp.h index 9e957b57b69451..6a10ff5f5be907 100644 --- a/tools/include/linux/gfp.h +++ b/tools/include/linux/gfp.h @@ -5,10 +5,6 @@ #include #include -/* Helper macro to avoid gfp flags if they are the default one */ -#define __default_gfp(a,...) a -#define default_gfp(...) __default_gfp(__VA_ARGS__ __VA_OPT__(,) GFP_KERNEL) - static inline bool gfpflags_allow_blocking(const gfp_t gfp_flags) { return !!(gfp_flags & __GFP_DIRECT_RECLAIM); diff --git a/tools/include/linux/gfp_types.h b/tools/include/linux/gfp_types.h index da47aa089f01c9..c1331bf0b2398c 100644 --- a/tools/include/linux/gfp_types.h +++ b/tools/include/linux/gfp_types.h @@ -134,7 +134,8 @@ enum { * %__GFP_THISNODE forces the allocation to be satisfied from the requested * node with no fallbacks or placement policy enforcements. * - * %__GFP_ACCOUNT causes the allocation to be accounted to kmemcg. + * %__GFP_ACCOUNT causes the allocation to be accounted to the active + * cgroup context. */ #define __GFP_RECLAIMABLE ((__force gfp_t)___GFP_RECLAIMABLE) #define __GFP_WRITE ((__force gfp_t)___GFP_WRITE) @@ -243,7 +244,7 @@ enum { * definitely preferable to use the flag rather than opencode endless * loop around allocator. * Allocating pages from the buddy with __GFP_NOFAIL and order > 1 is - * not supported. Please consider using kvmalloc() instead. + * discouraged. Please consider using kvmalloc() instead if possible. */ #define __GFP_IO ((__force gfp_t)___GFP_IO) #define __GFP_FS ((__force gfp_t)___GFP_FS) @@ -313,7 +314,7 @@ enum { * %ZONE_NORMAL or a lower zone for direct access but can direct reclaim. * * %GFP_KERNEL_ACCOUNT is the same as GFP_KERNEL, except the allocation is - * accounted to kmemcg. + * accounted to the active cgroup context. * * %GFP_NOWAIT is for kernel allocations that should not stall for direct * reclaim, start physical IO or use any filesystem callback. It is very @@ -381,4 +382,8 @@ enum { __GFP_NOMEMALLOC | __GFP_NOWARN) & ~__GFP_RECLAIM) #define GFP_TRANSHUGE (GFP_TRANSHUGE_LIGHT | __GFP_DIRECT_RECLAIM) +/* Helper macro to avoid gfp flags if they are the default one */ +#define __default_gfp(a,b,...) b +#define default_gfp(...) __default_gfp(,##__VA_ARGS__,GFP_KERNEL) + #endif /* __LINUX_GFP_TYPES_H */ From fe748877fe66561b354dcfb0cbb931c985abbc04 Mon Sep 17 00:00:00 2001 From: Arnaldo Carvalho de Melo Date: Sat, 7 Nov 2026 17:31:37 -0300 Subject: [PATCH 0347/2102] perf tools: Fix the sync-headers generated commit messages The script renders the kernel commits it picks up with --abbrev=12, while git here is configured with core.abbrev=16, so the commit ids come out shorter than everywhere else. Use 16 chars, the kernel asks for at least 12, and render them as 'commit ("subject")', the form checkpatch expects. Drop the '@@' hunk header from the beauty string table excerpts as well, checkpatch mistakes it for diff content in the generated commit message. Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/scripts/sync-headers.sh | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/tools/perf/scripts/sync-headers.sh b/tools/perf/scripts/sync-headers.sh index 01e2d108432f01..3ba94102e2799f 100755 --- a/tools/perf/scripts/sync-headers.sh +++ b/tools/perf/scripts/sync-headers.sh @@ -292,13 +292,13 @@ merge_pickup_commits() { git rev-list --no-walk=unsorted --stdin --min-parents=2 2>/dev/null } -# Render commit ids with FORMAT at the usual 12 chars, keeping their order. +# Render commit ids with FORMAT at the usual 16 chars, keeping their order. format_commits() { local format="$1" local ids="$2" [[ -n "$ids" ]] || return 0 - printf '%s\n' "$ids" | git log --no-walk=unsorted --abbrev=12 \ + printf '%s\n' "$ids" | git log --no-walk=unsorted --abbrev=16 \ --format="$format" --stdin 2>/dev/null } @@ -875,7 +875,7 @@ beauty_body_fragment() { printf ' $ diff -u before.txt after.txt\n' fi printf '\n' - diff -u "$before" "$after" | tail -n +3 | sed 's/^/ /' + diff -u "$before" "$after" | tail -n +3 | sed -e '/^@@ /d' -e 's/^/ /' printf '\n' } @@ -914,7 +914,7 @@ process_header() { local kernel_commits="" if [[ -n "$pickup_commits" ]]; then - kernel_commits=$(format_commits ' %h ("%s")' "$pickup_commits") + kernel_commits=$(format_commits ' commit %h ("%s")' "$pickup_commits") fi # A merge can bring content of its own; list it too, it is not the @@ -926,7 +926,7 @@ process_header() { if [[ -n "$kernel_commits" ]]; then kernel_commits+=$'\n' fi - kernel_commits+=$(format_commits ' %h ("%s")' "$merge_commits") + kernel_commits+=$(format_commits ' commit %h ("%s")' "$merge_commits") fi if [[ -n "$kernel_commits" ]]; then @@ -1235,10 +1235,10 @@ process_group() { echo "" echo " Kernel commits since last sync ($tools_path):" if [[ -n "$pickup_commits" ]]; then - format_commits ' %h ("%s")' "$pickup_commits" + format_commits ' commit %h ("%s")' "$pickup_commits" fi if [[ -n "$merge_commits" ]]; then - format_commits ' %h ("%s")' "$merge_commits" + format_commits ' commit %h ("%s")' "$merge_commits" fi local ccs ccs=$(format_commits 'Cc: %an <%ae>' "$pickup_commits" | sort -u) @@ -1290,7 +1290,7 @@ process_group() { warn "No previous sync commit found for $tools_path" fi if [[ -n "$pickup_commits" ]]; then - all_kernel_commits+=$(format_commits ' %h ("%s")' "$pickup_commits") + all_kernel_commits+=$(format_commits ' commit %h ("%s")' "$pickup_commits") all_kernel_commits+=$'\n' local ccs @@ -1306,7 +1306,7 @@ process_group() { merge_commits=$(merge_pickup_commits "$kernel_path" "$tools_path" \ "$sync_point") if [[ -n "$merge_commits" ]]; then - all_kernel_commits+=$(format_commits ' %h ("%s")' "$merge_commits") + all_kernel_commits+=$(format_commits ' commit %h ("%s")' "$merge_commits") all_kernel_commits+=$'\n' fi From a5399c1457abce20a7e7feeb0ca1f11296d8ab33 Mon Sep 17 00:00:00 2001 From: Dmitry Safonov Date: Tue, 3 Nov 2026 16:55:21 +0000 Subject: [PATCH 0348/2102] perf build: Override OUTPUT when building internal libraries After commit 1572ba36fbca9583 ("perf tests: Improvements to build-test performance"), building perf with OUTPUT on the command line fails: make -C tools/perf OUTPUT=/tmp/linux/perf/ ARCH=x86_64 LC_ALL=C \ CC=gcc HOSTCC=gcc LD=ld ... make[3]: *** No rule to make target '/tmp/linux/perf/libsubcmd/libsubcmd.a'. Stop. MAKEFLAGS propagates the command-line OUTPUT assignment to recursive makes. The library builds pass their output directories through $O, but the assignment to $OUTPUT in tools/scripts/Makefile.include cannot replace a command-line argument. This affects libapi, libperf, libsubcmd and libsymbol. With "unexport MAKEFLAGS" returned and added $(info) debug in libsubcmd Makefile produces: OUTPUT = /tmp/linux/perf/libsubcmd/ Without it, on current master it prints: OUTPUT = /tmp/linux/perf/ Pass OUTPUT explicitly to each library build, including the trailing slash required when constructing file names. This follows the existing libbpf build rule and preserves MAKEFLAGS and jobserver propagation. Fixes: 1572ba36fbca9583 ("perf tests: Improvements to build-test performance") Signed-off-by: Dmitry Safonov [ Fixed the copy'n'paste in the example, the OUTPUT path had a stray '/bld/' ] Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/Makefile.perf | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/perf/Makefile.perf b/tools/perf/Makefile.perf index b74b534e1153ff..4cc5bb3011da4d 100644 --- a/tools/perf/Makefile.perf +++ b/tools/perf/Makefile.perf @@ -798,7 +798,7 @@ $(patsubst perf-%,%.o,$(PROGRAMS)): $(wildcard */*.h) $(LIBAPI): FORCE | $(LIBAPI_OUTPUT) $(Q)$(MAKE) -C $(LIBAPI_DIR) O=$(LIBAPI_OUTPUT) \ - DESTDIR=$(LIBAPI_DESTDIR) prefix= subdir= \ + OUTPUT=$(LIBAPI_OUTPUT)/ DESTDIR=$(LIBAPI_DESTDIR) prefix= subdir= \ $@ install_headers $(LIBAPI)-clean: @@ -816,7 +816,7 @@ $(LIBBPF)-clean: $(LIBPERF): FORCE | $(LIBPERF_OUTPUT) $(Q)$(MAKE) -C $(LIBPERF_DIR) O=$(LIBPERF_OUTPUT) \ - DESTDIR=$(LIBPERF_DESTDIR) prefix= subdir= \ + OUTPUT=$(LIBPERF_OUTPUT)/ DESTDIR=$(LIBPERF_DESTDIR) prefix= subdir= \ $@ install_headers $(LIBPERF)-clean: @@ -825,7 +825,7 @@ $(LIBPERF)-clean: $(LIBSUBCMD): FORCE | $(LIBSUBCMD_OUTPUT) $(Q)$(MAKE) -C $(LIBSUBCMD_DIR) O=$(LIBSUBCMD_OUTPUT) \ - DESTDIR=$(LIBSUBCMD_DESTDIR) prefix= subdir= \ + OUTPUT=$(LIBSUBCMD_OUTPUT)/ DESTDIR=$(LIBSUBCMD_DESTDIR) prefix= subdir= \ $@ install_headers $(LIBSUBCMD)-clean: @@ -834,7 +834,7 @@ $(LIBSUBCMD)-clean: $(LIBSYMBOL): FORCE | $(LIBSYMBOL_OUTPUT) $(Q)$(MAKE) -C $(LIBSYMBOL_DIR) O=$(LIBSYMBOL_OUTPUT) \ - DESTDIR=$(LIBSYMBOL_DESTDIR) prefix= subdir= \ + OUTPUT=$(LIBSYMBOL_OUTPUT)/ DESTDIR=$(LIBSYMBOL_DESTDIR) prefix= subdir= \ $@ install_headers $(LIBSYMBOL)-clean: From 4c673fe9d9c3c1fd8f3c0b37f06c816e60f4bb43 Mon Sep 17 00:00:00 2001 From: Li RongQing Date: Sat, 31 Oct 2026 20:01:23 +0800 Subject: [PATCH 0349/2102] perf kvm: Fix arm64 VM-exit duration accounting Use kvm_exit as the start event and the following kvm_entry as the end event for arm64 VM-exit statistics. Keep decoding ret and esr_ec from the exit sample. Before this change, arm64 measured guest runtime as VM-exit time. Fixes: 1218838d68f5e9cc ("perf kvm: Add kvm-stat for arm64") Reviewed-by: Leo Yan Signed-off-by: Li RongQing Cc: Adrian Hunter Cc: Alexander Shishkin Cc: Ian Rogers Cc: Ingo Molnar Cc: James Clark Cc: Jiri Olsa Cc: Leo Yan Cc: Mark Rutland Cc: Namhyung Kim Cc: Peter Zijlstra Cc: Sergey Senozhatsky Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/util/kvm-stat-arch/kvm-stat-arm64.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tools/perf/util/kvm-stat-arch/kvm-stat-arm64.c b/tools/perf/util/kvm-stat-arch/kvm-stat-arm64.c index 018b0db0e6e7d2..ff853ef68aa5d3 100644 --- a/tools/perf/util/kvm-stat-arch/kvm-stat-arm64.c +++ b/tools/perf/util/kvm-stat-arch/kvm-stat-arm64.c @@ -36,13 +36,7 @@ static void event_get_key(struct perf_sample *sample, } static bool event_begin(struct perf_sample *sample, - struct event_key *key __maybe_unused) -{ - return evsel__name_is(sample->evsel, kvm_entry_trace(EM_AARCH64)); -} - -static bool event_end(struct perf_sample *sample, - struct event_key *key) + struct event_key *key) { if (evsel__name_is(sample->evsel, kvm_exit_trace(EM_AARCH64))) { event_get_key(sample, key); @@ -51,6 +45,12 @@ static bool event_end(struct perf_sample *sample, return false; } +static bool event_end(struct perf_sample *sample, + struct event_key *key __maybe_unused) +{ + return evsel__name_is(sample->evsel, kvm_entry_trace(EM_AARCH64)); +} + static const struct kvm_events_ops exit_events = { .is_begin_event = event_begin, .is_end_event = event_end, From a583680672ad8a3c010cfed0218042db0ffe336d Mon Sep 17 00:00:00 2001 From: Li RongQing Date: Wed, 4 Nov 2026 10:19:51 +0800 Subject: [PATCH 0350/2102] perf intel-pt: Free the old snapshot reference array after growing it Growing snapshot_refs allocates a new array and copies the old entries, then overwrites the only pointer to the old array. Snapshot recording with more than sixteen AUX mappings leaks that allocation on expansion. Free the old array after copying its entries. The reference buffers are still owned by the entries copied into the replacement array. Fixes: 90e457f7be087005 ("perf tools: Add Intel PT support") Reviewed-by: Adrian Hunter Signed-off-by: Li RongQing Cc: Adrian Hunter Cc: Alexander Shishkin Cc: Ian Rogers Cc: Ingo Molnar Cc: James Clark Cc: Jiri Olsa Cc: Mark Rutland Cc: Namhyung Kim Cc: Peter Zijlstra Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/arch/x86/util/intel-pt.c | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/perf/arch/x86/util/intel-pt.c b/tools/perf/arch/x86/util/intel-pt.c index a533114c0048cb..4c183ccf4e5b6d 100644 --- a/tools/perf/arch/x86/util/intel-pt.c +++ b/tools/perf/arch/x86/util/intel-pt.c @@ -941,6 +941,7 @@ static int intel_pt_alloc_snapshot_refs(struct intel_pt_recording *ptr, int idx) memcpy(refs, ptr->snapshot_refs, cnt * sz); + free(ptr->snapshot_refs); ptr->snapshot_refs = refs; ptr->snapshot_ref_cnt = new_cnt; From e48155a1bbf1a867d76241c66bac270aa0509dde Mon Sep 17 00:00:00 2001 From: Li RongQing Date: Wed, 4 Nov 2026 10:20:42 +0800 Subject: [PATCH 0351/2102] perf intel-bts: Free the old snapshot reference array after growing it The snapshot reference array grows when a mapping index exceeds its capacity. Its old entries are copied into a new allocation, but the old array is abandoned when snapshot_refs is replaced. Release the old array after copying it so expanding past sixteen mappings does not leak it. Fixes: d0170af7004dce9c ("perf tools: Add Intel BTS support") Reviewed-by: James Clark Signed-off-by: Li RongQing Cc: Adrian Hunter Cc: Alexander Shishkin Cc: Ian Rogers Cc: Ingo Molnar Cc: Jiri Olsa Cc: Mark Rutland Cc: Namhyung Kim Cc: Peter Zijlstra Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/arch/x86/util/intel-bts.c | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/perf/arch/x86/util/intel-bts.c b/tools/perf/arch/x86/util/intel-bts.c index d44d568a6d2108..9403681297c1da 100644 --- a/tools/perf/arch/x86/util/intel-bts.c +++ b/tools/perf/arch/x86/util/intel-bts.c @@ -299,6 +299,7 @@ static int intel_bts_alloc_snapshot_refs(struct intel_bts_recording *btsr, memcpy(refs, btsr->snapshot_refs, cnt * sz); + free(btsr->snapshot_refs); btsr->snapshot_refs = refs; btsr->snapshot_ref_cnt = new_cnt; From 1b0935ab5ac2e31ee0c2641d2b58b4af3db68a7a Mon Sep 17 00:00:00 2001 From: Leo Yan Date: Fri, 23 Oct 2026 14:20:24 +0100 Subject: [PATCH 0352/2102] perf treport: Initialize the subtitle in the constructor For Arm64 cross build without Textual, assignments outside __init__() trigger pylint warning: ************* Module treport python/treport.py:625:8: W0201: Attribute 'sub_title' defined outside __init__ (attribute-defined-outside-init) python/treport.py:629:12: W0201: Attribute 'sub_title' defined outside __init__ (attribute-defined-outside-init) python/treport.py:668:8: W0201: Attribute 'sub_title' defined outside __init__ (attribute-defined-outside-init) python/treport.py:675:8: W0201: Attribute 'sub_title' defined outside __init__ (attribute-defined-outside-init) ------------------------------------------------------------------ Your code has been rated at 9.91/10 (previous run: 9.91/10, +0.00) Move the initial subtitle assignment from on_mount() to ReportApp.__init__() so pylint can see the attribute initialization without resolving the Textual base class. Fixes: b379b70b7b7b41ff ("perf treport: Show the profile while it loads") Signed-off-by: Leo Yan Cc: Adrian Hunter Cc: Aishwarya TCV Cc: Alexander Shishkin Cc: Alice Rogers Cc: Ian Rogers Cc: James Clark Cc: Jiri Olsa Cc: Mark Rutland Cc: Namhyung Kim Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/python/treport.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/perf/python/treport.py b/tools/perf/python/treport.py index fb583786b17a57..202d70a923ecf8 100755 --- a/tools/perf/python/treport.py +++ b/tools/perf/python/treport.py @@ -602,6 +602,7 @@ def __init__(self, input_file: str, root: Optional[ProfileNode] = None): """ super().__init__() self.input_file = input_file + self.sub_title = input_file self.root = root if root else ProfileNode("root", parent=None) self.loaded = root is not None # Held when reading or changing the profile, which is built in a @@ -622,7 +623,6 @@ def compose(self) -> ComposeResult: def on_mount(self) -> None: """Start loading the profile unless it was given.""" - self.sub_title = self.input_file if self.loaded: self.update_views() else: From f88e617ea4590d80e4a144c69d6326c04fe2a357 Mon Sep 17 00:00:00 2001 From: Leo Yan Date: Fri, 23 Oct 2026 14:20:25 +0100 Subject: [PATCH 0353/2102] perf timechart: Initialize Textual attributes in constructors When Textual is unavailable, pylint cannot resolve the inherited virtual_size and sub_title attributes, which triggers pylint warnings and caused arm64 cross build failure: ************* Module ttimechart python/ttimechart.py:1086:8: W0201: Attribute 'virtual_size' defined outside __init__ (attribute-defined-outside-init) python/ttimechart.py:1422:12: W0201: Attribute 'sub_title' defined outside __init__ (attribute-defined-outside-init) python/ttimechart.py:1496:8: W0201: Attribute 'sub_title' defined outside __init__ (attribute-defined-outside-init) python/ttimechart.py:1510:8: W0201: Attribute 'sub_title' defined outside __init__ (attribute-defined-outside-init) Initialize both attributes in their respective constructors. Use Textual's default empty virtual size, with the actual geometry computed when the timeline mounts or resizes. Fixes: e7a72d6919804e5e ("perf timechart: Add an interactive --tui mode") Signed-off-by: Leo Yan Cc: Adrian Hunter Cc: Aishwarya TCV Cc: Alexander Shishkin Cc: Alice Rogers Cc: Ian Rogers Cc: James Clark Cc: Jiri Olsa Cc: Mark Rutland Cc: Namhyung Kim Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/python/ttimechart.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/perf/python/ttimechart.py b/tools/perf/python/ttimechart.py index d7ba0276a9fb4a..2ec7ad9fcc994e 100755 --- a/tools/perf/python/ttimechart.py +++ b/tools/perf/python/ttimechart.py @@ -1065,6 +1065,7 @@ def __init__(self, data: TimechartData, rows: List[Row], *pos_args, **kwargs) -> self.can_focus = True self.data = data self.rows = rows + self.virtual_size = Size(0, 0) self.cache: Dict[int, List[Cell]] = {} self.cache_key: Tuple[float, float, int, Optional[ThemeColors]] = (0.0, 0.0, 0, None) self.label_style = Style() @@ -1332,6 +1333,7 @@ def __init__(self, input_name: str, power_only: bool, tasks_only: bool, """ super().__init__() self.input_name = input_name + self.sub_title = input_name self.power_only = power_only self.tasks_only = tasks_only self.filters = filters From 0e263803702d7cdc182f3f9f81f721cdf7569664 Mon Sep 17 00:00:00 2001 From: Gu Bin Date: Wed, 4 Nov 2026 17:02:28 +0800 Subject: [PATCH 0354/2102] perf hist: Fix branch_info index for sample weight iter_add_next_branch_entry() is called once per branch and uses &bi[i] for the hist entry, but reads the weight from bi->flags.cycles (i.e. bi[0]) for every branch, so every entry is weighted with the first branch's cycle count. This is incorrect when the branch stack contains more than one entry with different cycle counts, as the weight of each hist entry fails to reflect the cycles of its own branch. Use bi[i].flags.cycles, as the surrounding code already does. Fixes: 0e332f033a8216fa ("perf tools: Add support for cycles, weight branch_info field") Reviewed-by: James Clark Signed-off-by: Gu Bin Cc: Andi Kleen Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/util/hist.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/perf/util/hist.c b/tools/perf/util/hist.c index e75a4fcce975a7..364754e9d12aa0 100644 --- a/tools/perf/util/hist.c +++ b/tools/perf/util/hist.c @@ -1055,7 +1055,7 @@ iter_add_next_branch_entry(struct hist_entry_iter *iter, struct addr_location *a * and not events sampled. Thus we use a pseudo period of 1. */ sample->period = 1; - sample->weight = bi->flags.cycles ? bi->flags.cycles : 1; + sample->weight = bi[i].flags.cycles ? bi[i].flags.cycles : 1; he = hists__add_entry(hists, al, iter->parent, &bi[i], NULL, NULL, sample, true); From a89a17e152c8e78795ba4b2a28583f1e727dd6f3 Mon Sep 17 00:00:00 2001 From: TAKANO Mitsuhiro Date: Tue, 3 Nov 2026 11:26:09 +0000 Subject: [PATCH 0355/2102] perf vendor events arm64 AmpereOneX: Deprecate BPU_FLUSH_MEM_FAULT The AmpereOne tables renamed event 0x121 from BPU_FLUSH_MEM_FAULT to GPC_FLUSH_MEM_FAULT, but the AmpereOneX tables that followed kept the old name in memory.json, so 'perf list' shows both names for that code. The old name has been in every release since v6.8, so scripts using it must keep working: mark the entry deprecated, as the x86 tables do, instead of deleting it. It still registers event=0x121. Fixes: 16438b652b464ef7 ("perf vendor events arm64 AmpereOneX: Add core PMU events and metrics") Suggested-by: Ian Rogers Link: https://lore.kernel.org/20261021224527.167637-1-takano32@gmail.com Link: https://lore.kernel.org/CAP-5=fX+2eRGCHcU43sqU=gi9iKvxqyS6ipwRSnvFcap3D+QzQ@mail.gmail.com Link: https://lore.kernel.org/42801873-8908-07a6-aed1-c7076c689e8e@os.amperecomputing.com Reviewed-by: James Clark Signed-off-by: TAKANO Mitsuhiro Acked-by: Ilkka Koskinen Signed-off-by: Arnaldo Carvalho de Melo --- .../perf/pmu-events/arch/arm64/ampere/ampereonex/memory.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/perf/pmu-events/arch/arm64/ampere/ampereonex/memory.json b/tools/perf/pmu-events/arch/arm64/ampere/ampereonex/memory.json index 6c06bc928415de..114f95e41e0d59 100644 --- a/tools/perf/pmu-events/arch/arm64/ampere/ampereonex/memory.json +++ b/tools/perf/pmu-events/arch/arm64/ampere/ampereonex/memory.json @@ -35,9 +35,10 @@ "ArchStdEvent": "MEM_ACCESS_CHECKED_WR" }, { - "PublicDescription": "Flushes due to memory hazards", + "PublicDescription": "This event is deprecated. Refer to new event GPC_FLUSH_MEM_FAULT Flushes due to memory hazards", "EventCode": "0x121", "EventName": "BPU_FLUSH_MEM_FAULT", - "BriefDescription": "Flushes due to memory hazards" + "BriefDescription": "This event is deprecated. Refer to new event GPC_FLUSH_MEM_FAULT", + "Deprecated": "1" } ] From 5a1325cf23a7338f532f808fe79fddadd745dda5 Mon Sep 17 00:00:00 2001 From: Ian Rogers Date: Tue, 3 Nov 2026 20:30:03 -0800 Subject: [PATCH 0356/2102] tools build: Add explicitly sequenced -lzstd to libbfd feature fallback Distributions like Fedora ship a statically compiled binutils libbfd that depends on zstd (along with libiberty and zlib) to decompress sections (e.g. undefined reference to 'ZSTD_decompress'). Commit 89d001d48ec792b9 ("tools build: Add zstd to the binutils library feature tests") added '|| $(BUILD_BFD) -lzstd' directly to test-libbfd.bin, test-libbfd-threadsafe.bin, and test-disassembler-four-args.bin. However, static libbfd requires '-liberty -lz -lzstd' together, and setting feature-libbfd=1 when extra libraries are needed causes callers (perf, bpftool) to link only '-lbfd -lopcodes' without '-lzstd'. Restore test-libbfd.bin to test only $(BUILD_BFD), add the test-libbfd-liberty-z-zstd.bin feature test and FEATURE_GROUP_MEMBERS-libbfd entry, and append the '-liberty -lz -lzstd' fallback to test-libbfd-threadsafe.bin, test-disassembler-four-args.bin, and test-disassembler-init-styled.bin. Fixes: 89d001d48ec792b9 ("tools build: Add zstd to the binutils library feature tests") Signed-off-by: Ian Rogers Signed-off-by: Arnaldo Carvalho de Melo --- tools/build/Makefile.feature | 3 ++- tools/build/feature/Makefile | 19 +++++++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/tools/build/Makefile.feature b/tools/build/Makefile.feature index 4d37d11f674c5b..c010049d972075 100644 --- a/tools/build/Makefile.feature +++ b/tools/build/Makefile.feature @@ -121,6 +121,7 @@ FEATURE_TESTS_EXTRA := \ libcheck \ libbfd-liberty \ libbfd-liberty-z \ + libbfd-liberty-z-zstd \ libopencsd \ llvm \ libbpf \ @@ -160,7 +161,7 @@ FEATURE_DISPLAY ?= \ # Declare group members of a feature to display the logical OR of the detection # result instead of each member result. # -FEATURE_GROUP_MEMBERS-libbfd = libbfd-liberty libbfd-liberty-z +FEATURE_GROUP_MEMBERS-libbfd = libbfd-liberty libbfd-liberty-z libbfd-liberty-z-zstd # # Declare list of feature dependency packages that provide pkg-config files. diff --git a/tools/build/feature/Makefile b/tools/build/feature/Makefile index 10340a5372242e..359da8b98bc5d1 100644 --- a/tools/build/feature/Makefile +++ b/tools/build/feature/Makefile @@ -20,6 +20,7 @@ FILES= \ test-reallocarray.bin \ test-libbfd-liberty.bin \ test-libbfd-liberty-z.bin \ + test-libbfd-liberty-z-zstd.bin \ test-cplus-demangle.bin \ test-cxa-demangle.bin \ test-libcap.bin \ @@ -249,18 +250,21 @@ $(OUTPUT)test-python-module.bin: $(BUILD) $(FLAGS_PYTHON_EMBED) $(OUTPUT)test-libbfd.bin: - $(BUILD_BFD) || $(BUILD_BFD) -lzstd + $(BUILD_BFD) $(OUTPUT)test-libbfd-threadsafe.bin: - $(BUILD_BFD) || $(BUILD_BFD) -lzstd || $(BUILD_BFD) -liberty || $(BUILD_BFD) -liberty -lz + $(BUILD_BFD) || $(BUILD_BFD) -liberty || $(BUILD_BFD) -liberty -lz || \ + $(BUILD_BFD) -liberty -lz -lzstd $(OUTPUT)test-disassembler-four-args.bin: - $(BUILD_BFD) -lopcodes || $(BUILD_BFD) -lopcodes -lzstd || $(BUILD_BFD) -lopcodes -liberty || \ - $(BUILD_BFD) -lopcodes -liberty -lz + $(BUILD_BFD) -lopcodes || $(BUILD_BFD) -lopcodes -liberty || \ + $(BUILD_BFD) -lopcodes -liberty -lz || \ + $(BUILD_BFD) -lopcodes -liberty -lz -lzstd $(OUTPUT)test-disassembler-init-styled.bin: - $(BUILD_BFD) -lopcodes || $(BUILD_BFD) -lopcodes -liberty || \ - $(BUILD_BFD) -lopcodes -liberty -lz + $(BUILD_BFD) -lopcodes || $(BUILD_BFD) -lopcodes -liberty || \ + $(BUILD_BFD) -lopcodes -liberty -lz || \ + $(BUILD_BFD) -lopcodes -liberty -lz -lzstd $(OUTPUT)test-reallocarray.bin: $(BUILD) @@ -271,6 +275,9 @@ $(OUTPUT)test-libbfd-liberty.bin: $(OUTPUT)test-libbfd-liberty-z.bin: $(CC) $(CFLAGS) -Wall -Werror -o $@ test-libbfd.c -DPACKAGE='"perf"' $(LDFLAGS) -lbfd -ldl -liberty -lz +$(OUTPUT)test-libbfd-liberty-z-zstd.bin: + $(CC) $(CFLAGS) -Wall -Werror -o $@ test-libbfd.c -DPACKAGE='"perf"' $(LDFLAGS) -lbfd -ldl -liberty -lz -lzstd + $(OUTPUT)test-cplus-demangle.bin: $(BUILD) -liberty From a794dc43e25679a0c2ba9019cf46e2b125c85c02 Mon Sep 17 00:00:00 2001 From: Ian Rogers Date: Tue, 3 Nov 2026 20:30:04 -0800 Subject: [PATCH 0357/2102] perf build: Add explicitly sequenced -lzstd to libbfd feature fallback Distributions like Fedora ship a statically compiled binutils libbfd that depends on zstd to decompress sections (e.g. undefined reference to 'ZSTD_decompress'). Since libbfd does not reliably distribute a .pc file for pkg-config, perf probes manual linker flag combinations in fallback chains (-lbfd -ldl -liberty -lz). Extend the testing cascade in tools/perf/Makefile.config to check libbfd-liberty-z-zstd and append '-lbfd -lopcodes -liberty -lz -lzstd' when detected. Signed-off-by: Ian Rogers Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/Makefile.config | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/perf/Makefile.config b/tools/perf/Makefile.config index b4764f69f47f4d..78423b0dcc73ac 100644 --- a/tools/perf/Makefile.config +++ b/tools/perf/Makefile.config @@ -896,6 +896,7 @@ ifdef BUILD_NONDISTRO $(call feature_check,libbfd-threadsafe) $(call feature_check,libbfd-liberty) $(call feature_check,libbfd-liberty-z) + $(call feature_check,libbfd-liberty-z-zstd) ifneq ($(feature-libbfd-threadsafe), 1) $(error binutils-dev(el) 2.42 or later is required for non-distro builds) @@ -909,6 +910,8 @@ ifdef BUILD_NONDISTRO EXTLIBS += -lbfd -lopcodes -liberty else ifeq ($(feature-libbfd-liberty-z), 1) EXTLIBS += -lbfd -lopcodes -liberty -lz + else ifeq ($(feature-libbfd-liberty-z-zstd), 1) + EXTLIBS += -lbfd -lopcodes -liberty -lz -lzstd endif CFLAGS += -DHAVE_LIBBFD_SUPPORT From 8e2287c5df7417a93457548087f45aa11dc2a140 Mon Sep 17 00:00:00 2001 From: James Clark Date: Fri, 6 Nov 2026 10:48:09 +0000 Subject: [PATCH 0358/2102] perf test probe_vfs_getname: Fix missing debuginfo detection skip_if_no_debuginfo() looks for the errors that 'perf probe' prints when there is no debuginfo in the output of add_probe_vfs_getname(). But since commit 92b664dcefab ("perf test probe_vfs_getname: Skip if no suitable line detected"), add_probe_vfs_getname() returns early without adding a probe if 'perf probe -L' doesn't find the line, which is also what happens when there is no debuginfo. The error from 'perf probe -L' is discarded, so the debuginfo errors are never found. This causes the debuginfo dependent subtests of the "perftool-testsuite_probe" test to fail instead of being skipped on kernels without debuginfo, because test_adding_kernel.sh calls skip_if_no_debuginfo() unconditionally. The other users only call it when add_probe_vfs_getname() returns 1, so they aren't affected. Fix it by doing a dry run of a probe that needs debuginfo instead. This works without libdw too, where 'perf probe -L' isn't available, and also avoids adding a real probe just to check for debuginfo. This fixes the "perftool-testsuite_probe" test: $ sudo perf test -vvv "perftool-testsuite_probe" ... -- [ FAIL ] -- perf_probe :: test_adding_kernel :: listing added probe :: perf probe -l (output regexp parsing) ... -- [ FAIL ] -- perf_probe :: test_adding_kernel :: wildcard adding support (command exitcode + output regexp parsing) ... -- [ FAIL ] -- perf_probe :: test_adding_kernel :: non-existing variable (output regexp parsing) ... ## [ FAIL ] ## perf_probe :: test_adding_kernel SUMMARY :: 3 failures found ... 189: perftool-testsuite_probe : FAILED! Fixes: 92b664dcefab71f4 ("perf test probe_vfs_getname: Skip if no suitable line detected") Signed-off-by: James Clark Cc: Adrian Hunter Cc: Alexander Shishkin Cc: Ian Rogers Cc: Ingo Molnar Cc: Jakub Brnak Cc: Jiri Olsa Cc: Leo Yan Cc: Mark Rutland Cc: Namhyung Kim Cc: Peter Zijlstra [ Added a shellcheck disable for add_probe_vfs_getname()'s now unused -v argument ] Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/tests/shell/lib/probe_vfs_getname.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tools/perf/tests/shell/lib/probe_vfs_getname.sh b/tools/perf/tests/shell/lib/probe_vfs_getname.sh index 57a59ae7d4ae3d..c7fee1f74bee16 100644 --- a/tools/perf/tests/shell/lib/probe_vfs_getname.sh +++ b/tools/perf/tests/shell/lib/probe_vfs_getname.sh @@ -27,6 +27,7 @@ cleanup_probe_vfs_getname() { trap cleanup_probe_vfs_getname exit trap 'exit 1' term int +# shellcheck disable=SC2120 # -v is for manual runs add_probe_vfs_getname() { add_probe_verbose=$1 if [ $had_vfs_getname -eq 1 ] ; then @@ -64,7 +65,11 @@ add_probe_vfs_getname() { } skip_if_no_debuginfo() { - add_probe_vfs_getname -v 2>&1 | grep -E -q "^(Failed to find the path for the kernel|Debuginfo-analysis is not supported)|(file has no debug information)" && return 2 + # Dry run a probe that needs debuginfo. + perf probe -n -v 'getname_flags $params' 2>&1 | grep -q \ + -e "^Failed to find the path for the kernel" \ + -e "^Debuginfo-analysis is not supported" \ + -e "file has no debug information" && return 2 return 1 } From f6d181fde135e5757c5c94409f510cf42874308b Mon Sep 17 00:00:00 2001 From: James Clark Date: Fri, 6 Nov 2026 10:48:10 +0000 Subject: [PATCH 0359/2102] perf test: Don't starve per-process tests with system-wide events Some tests intermittently fail when run in parallel, for example "Check branch stack sampling" fails with no branches recorded at all. The default event is cycles:P which there may only be 1 or 2 HW counters for on Intel because it's precise. System wide or per-core precise events hog the HW counter leaving other per-process tests with no samples. Rather than make all the tests that use default record commands run serially, just make the system wide ones use a software event which has the greatest possible compatibility. They don't need precise sampling or HW counters anyway. The per-process tests can be left alone as their events/processes never run concurrently on any one core. The LBR filter is another resource shared by all events on a CPU, and the system-wide LBR test uses different filters to the per-process branch stack test, so mark the LBR test as exclusive. This fixes the "Check branch stack sampling" test and other flakes when a system-wide record from another test runs at the same time, for example: $ sudo perf record -a -o /dev/null -- sleep 30 & $ sudo perf test -vvv "Check branch stack sampling" ... Testing user branch stack sampling ERROR: Branches missing ^brstack_bench\+[^ ]*/brstack_foo\+[^ ]*/IND_CALL/.*$ ... Testing user branch stack sampling [Failed] ... Testing branch stack filtering permutation (call,CALL|SYSCALL) Testing branch stack filtering [Failed empty script output] ... ---- end(-1) ---- 138: Check branch stack sampling : FAILED! Signed-off-by: James Clark Cc: Adrian Hunter Cc: Alexander Shishkin Cc: Ian Rogers Cc: Ingo Molnar Cc: Jakub Brnak Cc: Jiri Olsa Cc: Leo Yan Cc: Mark Rutland Cc: Namhyung Kim Cc: Peter Zijlstra Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/tests/shell/record.sh | 6 +++--- tools/perf/tests/shell/record_lbr.sh | 2 +- tools/perf/tests/shell/record_sideband.sh | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tools/perf/tests/shell/record.sh b/tools/perf/tests/shell/record.sh index 01dc3e22fa7381..e4789e2bcf4373 100755 --- a/tools/perf/tests/shell/record.sh +++ b/tools/perf/tests/shell/record.sh @@ -388,7 +388,7 @@ test_system_wide() { echo "Basic --system-wide mode test" local ret=0 perf_record_with_retry "${perfdata}" "check_system_wide" "perf test -w thloop" \ - -aB --synth=no || ret=$? + -aB --synth=no -e cpu-clock || ret=$? if [ $ret -eq 2 ]; then echo "System-wide record [Skipped not supported]" return @@ -471,7 +471,7 @@ test_cgroup() { echo "Cgroup sampling test" local ret=0 perf_record_with_retry "${perfdata}" "check_cgroup" "perf test -w thloop" \ - -aB --synth=cgroup --all-cgroups || ret=$? + -aB --synth=cgroup --all-cgroups -e cpu-clock || ret=$? if [ $ret -eq 2 ]; then echo "Cgroup sampling [Skipped not supported]" return @@ -491,7 +491,7 @@ test_uid() { echo "Uid sampling test" local ret=0 perf_record_with_retry "${perfdata}" "check_uid" "perf test -w thloop" \ - -aB --synth=no --uid "$(id -u)" || ret=$? + -aB --synth=no --uid "$(id -u)" -e cpu-clock || ret=$? if [ $ret -eq 2 ]; then local logfile="${PERF_RECORD_LOGS[${#PERF_RECORD_LOGS[@]}-1]}" if grep -q -E "libbpf.*EPERM|Access to performance monitoring" "$logfile" || \ diff --git a/tools/perf/tests/shell/record_lbr.sh b/tools/perf/tests/shell/record_lbr.sh index 8d51afeb437ba0..6b6af59db87131 100755 --- a/tools/perf/tests/shell/record_lbr.sh +++ b/tools/perf/tests/shell/record_lbr.sh @@ -1,6 +1,6 @@ #!/bin/bash # SPDX-License-Identifier: GPL-2.0 -# perf record LBR tests +# perf record LBR tests (exclusive) set -e diff --git a/tools/perf/tests/shell/record_sideband.sh b/tools/perf/tests/shell/record_sideband.sh index 2182551873be32..f16889e3fa9a75 100755 --- a/tools/perf/tests/shell/record_sideband.sh +++ b/tools/perf/tests/shell/record_sideband.sh @@ -22,7 +22,7 @@ trap trap_cleanup EXIT TERM INT can_cpu_wide() { - if ! perf record -o ${perfdata} -BN --no-bpf-event -C $1 true > /dev/null 2>&1 + if ! perf record -o ${perfdata} -BN --no-bpf-event -e cpu-clock -C $1 true > /dev/null 2>&1 then echo "record sideband test [Skipped cannot record cpu$1]" err=2 @@ -39,7 +39,7 @@ test_system_wide_tracking() can_cpu_wide 1 || return 0 # Record on CPU 0 a task running on CPU 1 - perf record -BN --no-bpf-event -o ${perfdata} -C 0 -- taskset --cpu-list 1 true + perf record -BN --no-bpf-event -e cpu-clock -o ${perfdata} -C 0 -- taskset --cpu-list 1 true # Should get MMAP events from CPU 1 mmap_cnt=`perf script -i ${perfdata} --show-mmap-events -C 1 2>/dev/null | grep MMAP | wc -l` From 82b4a28e758816365405e01d9ed09027d13ef77a Mon Sep 17 00:00:00 2001 From: Paul Moses Date: Fri, 30 Oct 2026 06:48:50 +0000 Subject: [PATCH 0360/2102] perf record: Reject CPU indices equal to the mask size record__mmap_cpu_mask_init() rejects CPU indices greater than nbits but accepts nbits itself. Valid indices end at nbits - 1. When nbits is a multiple of BITS_PER_LONG, __set_bit() accesses the word immediately past the bitmap allocation. User specified recording thread masks reach this write before they are intersected with the selected CPU mask. For example, an affinity mask containing CPU 64 overruns a bitmap allocated for 64 possible CPUs. ==40343==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x7bbab4000018 at pc 0x6195de57af45 bp 0x7ffe25545d20 sp 0x7ffe25545d18 READ of size 8 at 0x7bbab4000018 thread T0 Reject indices greater than or equal to nbits before setting a bit. Fixes: cbd7bfc7fd99acdd ("tools/perf: Fix out of bound access to cpu mask array") Signed-off-by: Paul Moses Acked-by: Namhyung Kim Cc: Adrian Hunter Cc: Alexander Shishkin Cc: Athira Rajeev Cc: Ian Rogers Cc: Ingo Molnar Cc: James Clark Cc: Jiri Olsa Cc: Mark Rutland Cc: Namhyung Kim Cc: Peter Zijlstra Cc: stable@vger.kernel.org Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/builtin-record.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/perf/builtin-record.c b/tools/perf/builtin-record.c index ad81458989b53c..0e98a613c37df9 100644 --- a/tools/perf/builtin-record.c +++ b/tools/perf/builtin-record.c @@ -3704,8 +3704,8 @@ static int record__mmap_cpu_mask_init(struct mmap_cpu_mask *mask, struct perf_cp return 0; perf_cpu_map__for_each_cpu_skip_any(cpu, idx, cpus) { - /* Return ENODEV is input cpu is greater than max cpu */ - if ((unsigned long)cpu.cpu > mask->nbits) + /* Return ENODEV if the CPU index is outside the mask. */ + if ((unsigned long)cpu.cpu >= mask->nbits) return -ENODEV; __set_bit(cpu.cpu, mask->bits); } From 1c264cb18f718bd30f9763de2f0fc65ecc0073fb Mon Sep 17 00:00:00 2001 From: Ian Rogers Date: Wed, 4 Nov 2026 20:48:41 -0800 Subject: [PATCH 0361/2102] perf jevents: Don't encode MSRs with no value Fixes the events mem_trans_retired.load_latency (EMR) and mem_inst_retired.latency_above_threshold_0 (NHM, WSM) that were having their ldlat= value encoded as python's None. Fixes: ffc606ada3d7d8b2 ("perf jevents: Add python converter script") Reported-by: kernel test robot Closes: https://lore.kernel.org/oe-lkp/202611050801.67bb4af4-lkp@intel.com Reviewed-by: Dapeng Mi Signed-off-by: Ian Rogers Acked-by: Namhyung Kim Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/pmu-events/jevents.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/perf/pmu-events/jevents.py b/tools/perf/pmu-events/jevents.py index 080e04b51b8c5e..e083f7495e67c5 100755 --- a/tools/perf/pmu-events/jevents.py +++ b/tools/perf/pmu-events/jevents.py @@ -396,7 +396,7 @@ def canonicalize_value(val: str) -> str: event += f',{value}{canonicalize_value(jd[key])}' if filter: event += f',{filter}' - if msr: + if msr and msrval: event += f',{msr}{msrval}' if self.desc and extra_desc: self.desc += extra_desc From 30bdadc9aa3a684cd634c7fa49740b1151e7b2e5 Mon Sep 17 00:00:00 2001 From: Kiwoong Kim Date: Fri, 6 Nov 2026 13:12:46 +0900 Subject: [PATCH 0362/2102] scsi: ufs: core: Skip ABORT TASK for device management commands In MCQ mode, ufshcd_mcq_abort() falls through to ufshcd_try_to_abort_task() for all timed-out commands. However, device management commands (query, NOP) use reserved requests and are not SCSI I/O commands. The ABORT TASK task management function is designed for SCSI I/O UPIUs and is not applicable to device management UPIUs. This is only reachable since device management commands were converted to scsi_get_internal_cmd(); before that, a timed-out query was handled by ufshcd_wait_for_dev_cmd() -> ufshcd_clear_cmd() and never reached ufshcd_try_to_abort_task(). Fix this by checking ufshcd_is_scsi_cmd() in ufshcd_try_to_abort_task(). For a reserved (device management) command, skip the TM path and call ufshcd_clear_cmd() directly. ufshcd_abort() now calls ufshcd_try_to_abort_task() for every request, so its separate reserved-request branch is removed. Fixes: 08b12cda6c44 ("scsi: ufs: core: Switch to scsi_get_internal_cmd()") Reported-by: Bart Van Assche Signed-off-by: Kiwoong Kim Reviewed-by: Bean Huo Reviewed-by: Bart Van Assche Link: https://patch.msgid.link/ab14d2f1414fa1a0a396f160abf8c27c404b4ec4.1793938245.git.kwmad.kim@samsung.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/core/ufshcd.c | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/drivers/ufs/core/ufshcd.c b/drivers/ufs/core/ufshcd.c index 9cb009a6acbe89..ddc953b45ce95d 100644 --- a/drivers/ufs/core/ufshcd.c +++ b/drivers/ufs/core/ufshcd.c @@ -8067,11 +8067,15 @@ static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap) * @hba: Pointer to adapter instance * @tag: Tag of the task to be aborted * - * Abort the pending command in device by sending UFS_ABORT_TASK task management - * command, and in host controller by clearing the door-bell register. There can - * be race between controller sending the command to the device while abort is - * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is - * really issued and then try to abort it. + * Abort the pending SCSI command in device by sending UFS_ABORT_TASK task + * management command, and in host controller by clearing the door-bell + * register. There can be race between controller sending the command to the + * device while abort is issued. To avoid that, first issue UFS_QUERY_TASK to + * check if the command is really issued and then try to abort it. + * + * Device management commands are not SCSI commands, so no task management + * function is issued for them; only the command is cleared in the host + * controller. * * Return: zero on success, non-zero on failure. */ @@ -8088,6 +8092,9 @@ int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag) lrbp = scsi_cmd_priv(cmd); + if (!ufshcd_is_scsi_cmd(cmd)) + goto clear_cmd; + for (poll_cnt = 100; poll_cnt; poll_cnt--) { err = ufshcd_issue_tm_cmd(hba, lrbp->lun, tag, UFS_QUERY_TASK, &resp); @@ -8133,6 +8140,7 @@ int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag) return err; } +clear_cmd: err = ufshcd_clear_cmd(hba, tag); if (err) dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n", @@ -8226,10 +8234,7 @@ static int ufshcd_abort(struct scsi_cmnd *cmd) goto release; } - if (blk_mq_is_reserved_rq(rq)) - err = ufshcd_clear_cmd(hba, tag); - else - err = ufshcd_try_to_abort_task(hba, tag); + err = ufshcd_try_to_abort_task(hba, tag); if (err) { dev_err(hba->dev, "%s: failed with err %d\n", __func__, err); ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs); From e510b597d8afca2e790e2b5429bc5e01e3386f65 Mon Sep 17 00:00:00 2001 From: Kiwoong Kim Date: Fri, 6 Nov 2026 13:12:47 +0900 Subject: [PATCH 0363/2102] scsi: ufs: mcq: Poll OCS after sq cleanup for device management commands Extend ufshcd_mcq_sq_cleanup() to poll the OCS field in the UTRD of a device management command after a successful SQ_CUS poll. UFSHCI does not specify the order between the OCS update and the SQ_CUS update, so OCS may still be stale when cleanup returns. Without this poll, a late response to a timed-out query can arrive while a retry is already in flight, leaving the host controller with two query contexts and raising IS.UTPES. Here is the timeline of an actual case I found with kernel 6.18: 1. The driver sent a query but the device didn't respond to it for a long time. [ 7384.156142] [4: kworker/u40:5:10671] exynos-ufs 38300000.ufs: ufshcd_mcq_sq_cleanup, hwq 0: cleanup return code (RTC) 0 [ 7384.156154] [4: kworker/u40:5:10671] exynos-ufs 38300000.ufs: ufshcd_query_flag: Sending flag query for idn 14 failed, err = -11 2. So after the query timed out, the driver did SQ cleanup. Then the host controller updated the CQ tail and raised IS.CQES. Unfortunately, complete() was called by the driver's ISR afterward. 3. The driver started to retry the query. In the meantime, it set OCS to 0xF. Then the driver didn't wait for completion due to the previous complete() call, and just checked OCS. [ 7384.156163] [4: kworker/u40:5:10671] exynos-ufs 38300000.ufs: ufshcd_query_flag: Sending flag query for idn 14 failed, err = 15 4. The driver retried the query again, but the device didn't return anything, so the query also timed out. [ 7385.660108] [3: kworker/u40:5:10671] exynos-ufs 38300000.ufs: ufshcd_query_flag: Sending flag query for idn 14 failed, err = -11 5. A few seconds later, the device returned the response of the first query, but since the host controller was holding two query contexts and couldn't handle it, it raised IS.UTPES. The same problem exists in the current code. If the query times out, the SCSI error handler calls ufshcd_abort() -> ufshcd_mcq_abort() -> ufshcd_mcq_sq_cleanup(), the request is finished, and the retry reuses the same reserved tag, struct scsi_cmnd and devman UCD. A late CQE for the first query then maps to the same tag and completes the retry by calling scsi_done() too early. The retry then returns the OCS of the first query and, if that OCS is OCS_SUCCESS, its response as well. Hence ufshcd_mcq_sq_cleanup() must not return until the CQE of the cleaned-up request has been processed. The poll is limited to device management commands because ufshcd_compl_one_cqe() copies the OCS from the CQE into the UTRD only for them. For SCSI commands, the OCS in the UTRD stays OCS_INVALID_COMMAND_STATUS, so polling it would always time out. The poll waits until OCS is no longer OCS_INVALID_COMMAND_STATUS or MCQ_POLL_US elapses. -ETIMEDOUT is returned only if OCS is still OCS_INVALID_COMMAND_STATUS after the poll. Any other value, such as OCS_ABORTED reported by the host controller for the cleaned-up request, means the cleanup has completed. The UFSHCI specification says "The host controller shall free up any resources associated to the nexus, and shall post a Completion Queue entry with OCS = ABORTED if clean up successful." Each poll iteration reaps the CQ with ufshcd_mcq_poll_cqe_lock() before reading the OCS, as ufshcd_clear_lu_cmds() does after ufshcd_clear_cmd(). This removes the dependency on interrupt delivery. Otherwise the OCS is only updated once the interrupt handler processes the CQE, and a delayed or lost interrupt would make the poll time out and escalate to a host reset although the request has already been cleaned up. The OCS is still read under hwq->cq_lock because the interrupt handler may reap the CQE between the reap and the read. ufshcd_compl_one_cqe() updates the OCS under that lock before it sets cmd->result and calls scsi_done(). Without the lock, cleanup could observe the new OCS and return while the completion is still running. The abort could then finish the command and a retry could reuse the same reserved request before the pending scsi_done() call, which would then complete the retry prematurely. Fixes: 8d7290348992 ("scsi: ufs: mcq: Add supporting functions for MCQ abort") Signed-off-by: Kiwoong Kim Reviewed-by: Bart Van Assche Reviewed-by: Bean Huo Link: https://patch.msgid.link/a1af44cd90dca0dd8a9a06d09a254a4e7e0861b2.1793938245.git.kwmad.kim@samsung.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/core/ufs-mcq.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/drivers/ufs/core/ufs-mcq.c b/drivers/ufs/core/ufs-mcq.c index 25e392f8ede2bf..005a7046247303 100644 --- a/drivers/ufs/core/ufs-mcq.c +++ b/drivers/ufs/core/ufs-mcq.c @@ -554,6 +554,23 @@ static int ufshcd_mcq_sq_start(struct ufs_hba *hba, struct ufs_hw_queue *hwq) return err; } +/* + * Reap the CQ directly so that progress does not depend on interrupt + * delivery. ufshcd_compl_one_cqe() updates the OCS under cq_lock before + * calling scsi_done(). Holding cq_lock while reading the OCS makes sure that + * the completion has finished once the updated OCS is observed, even if the + * CQE was reaped by the interrupt handler. + */ +static enum utp_ocs ufshcd_mcq_poll_ocs(struct ufs_hba *hba, + struct ufs_hw_queue *hwq, + struct ufshcd_lrb *lrbp) +{ + ufshcd_mcq_poll_cqe_lock(hba, hwq); + + guard(spinlock_irqsave)(&hwq->cq_lock); + return lrbp->utr_descriptor_ptr->header.ocs; +} + /** * ufshcd_mcq_sq_cleanup - Clean up submission queue resources * associated with the pending command. @@ -613,6 +630,23 @@ int ufshcd_mcq_sq_cleanup(struct ufs_hba *hba, int task_tag) __func__, id, FIELD_GET(SQ_ICU_ERR_CODE_MASK, readl(reg))); + /* + * For device management commands, there is no order guaranteed between + * OCS update and CUS update, which is why we need to wait here. SCSI + * commands are excluded because the OCS in their UTRD is not updated + * from the CQE. + */ + if (!err && blk_mq_is_reserved_rq(rq)) { + enum utp_ocs ocs; + + err = read_poll_timeout(ufshcd_mcq_poll_ocs, ocs, + ocs != OCS_INVALID_COMMAND_STATUS, 20, + MCQ_POLL_US, false, hba, hwq, lrbp); + if (err) + dev_err(hba->dev, "%s: OCS not updated. hwq=%d, tag=%d err=%d\n", + __func__, id, task_tag, err); + } + if (ufshcd_mcq_sq_start(hba, hwq)) err = -ETIMEDOUT; From b3da73f09499b34faf5c43c50e1d09e4286226de Mon Sep 17 00:00:00 2001 From: Joonhoe Kim <26rote@gmail.com> Date: Fri, 23 Oct 2026 01:50:06 +0900 Subject: [PATCH 0364/2102] scsi: ufs: qcom: Reprogram ESI after a host controller reset ufs_qcom_config_esi() returns early once the ESI interrupts are set up. ufshcd_config_mcq() also calls it after every host controller reset, which clears the ESI base address, the vector mask and ESI enable. After the error handler has reset the controller, the completions then arrive only on the legacy interrupt while mcq_esi_enabled stays set. Allocate the MSIs and request their interrupts only once, but program the ESI registers on every call. The MSI message is not cached for platform MSIs, so keep the one written at allocation. Fixes: 519b6274a777 ("scsi: ufs: qcom: Add MCQ ESI config vendor specific ops") Signed-off-by: Joonhoe Kim <26rote@gmail.com> Link: https://patch.msgid.link/20261022165006.1275-1-26rote@gmail.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/host/ufs-qcom.c | 12 +++++++++--- drivers/ufs/host/ufs-qcom.h | 2 ++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/drivers/ufs/host/ufs-qcom.c b/drivers/ufs/host/ufs-qcom.c index 27c87e62f8e98d..47fc785612adac 100644 --- a/drivers/ufs/host/ufs-qcom.c +++ b/drivers/ufs/host/ufs-qcom.c @@ -2413,7 +2413,9 @@ static void ufs_qcom_write_msi_msg(struct msi_desc *desc, struct msi_msg *msg) { struct device *dev = msi_desc_to_dev(desc); struct ufs_hba *hba = dev_get_drvdata(dev); + struct ufs_qcom_host *host = ufshcd_get_variant(hba); + host->esi_msg = *msg; ufshcd_mcq_config_esi(hba, msg); } @@ -2441,8 +2443,10 @@ static int ufs_qcom_config_esi(struct ufs_hba *hba) struct ufs_qcom_irq *qi; int nr_irqs, ret; - if (host->esi_enabled) - return 0; + if (host->esi_enabled) { + ufshcd_mcq_config_esi(hba, &host->esi_msg); + goto enable; + } /* * 1. We only handle CQs as of now. @@ -2480,12 +2484,14 @@ static int ufs_qcom_config_esi(struct ufs_hba *hba) } } + host->esi_enabled = true; + +enable: if (host->hw_ver.major >= 6) { ufshcd_rmwl(hba, ESI_VEC_MASK, FIELD_PREP(ESI_VEC_MASK, MAX_ESI_VEC - 1), REG_UFS_CFG3); } ufshcd_mcq_enable_esi(hba); - host->esi_enabled = true; return 0; } diff --git a/drivers/ufs/host/ufs-qcom.h b/drivers/ufs/host/ufs-qcom.h index 944b2e532a0962..d2647695abe3ab 100644 --- a/drivers/ufs/host/ufs-qcom.h +++ b/drivers/ufs/host/ufs-qcom.h @@ -5,6 +5,7 @@ #ifndef UFS_QCOM_H_ #define UFS_QCOM_H_ +#include #include #include #include @@ -360,6 +361,7 @@ struct ufs_qcom_host { u32 phy_gear; bool esi_enabled; + struct msi_msg esi_msg; u32 saved_tx_eq_g1_setting; u32 boot_spare_cfg; From fe5988e8708e1d42cb844bd9ac8f0a51388061fc Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Mon, 26 Oct 2026 19:49:55 +0800 Subject: [PATCH 0365/2102] scsi: target: Fix NULL pointer dereference in target_dev_alua_lu_gp_store() Writing "NULL" to the alua_lu_gp attribute clears the ALUA LU group association of a device. The attribute can be written again after the association has already been cleared. In that case lu_gp_mem->lu_gp and lu_gp_new are both NULL, but the code still calls __core_alua_attach_lu_gp_mem(), which dereferences the NULL lu_gp pointer: BUG: kernel NULL pointer dereference, address: 0000000000000000 ... __core_alua_attach_lu_gp_mem target_dev_alua_lu_gp_store Clearing an already cleared association is a no-op, so return early when there is no association left to clear. Fixes: c66ac9db8d4a ("[SCSI] target: Add LIO target core v4.0.0-rc6") Signed-off-by: Shao Mingyin Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261026194955694FnXGoQ352dstLk5HPBqCG@zte.com.cn Signed-off-by: Martin K. Petersen (Oracle) --- drivers/target/target_core_configfs.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/target/target_core_configfs.c b/drivers/target/target_core_configfs.c index 2b19a956007b73..430fc1eaeca5d7 100644 --- a/drivers/target/target_core_configfs.c +++ b/drivers/target/target_core_configfs.c @@ -2547,6 +2547,14 @@ static ssize_t target_dev_alua_lu_gp_store(struct config_item *item, spin_lock(&lu_gp_mem->lu_gp_mem_lock); lu_gp = lu_gp_mem->lu_gp; + if (!lu_gp && !lu_gp_new) { + /* + * The LU group association has already been cleared, so + * there is nothing left to do. + */ + spin_unlock(&lu_gp_mem->lu_gp_mem_lock); + return count; + } if (lu_gp) { /* * Clearing an existing lu_gp association, and replacing From c0bb6614132c64205a3c40c32dc1494c1bfeffe1 Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Mon, 26 Oct 2026 19:51:33 +0800 Subject: [PATCH 0366/2102] scsi: target: Fix NULL pointer dereference in core_alua_do_port_transition() core_alua_do_port_transition() assumes that the device has an ALUA LU group member and that the member is associated with an LU group. Neither is guaranteed: internal-use HBAs never allocate dev_alua_lu_gp_mem, and the association with an LU group is dropped when "NULL" is written to the device's alua_lu_gp attribute. The configfs path can reach the second case. After clearing the LU group association, writing the implicit ALUA access state of a target port group calls core_alua_do_port_transition(), which dereferences the NULL lu_gp in atomic_inc(&lu_gp->lu_gp_ref_cnt). Return -ENODEV when the device has no LU group association instead. Fixes: c66ac9db8d4a ("[SCSI] target: Add LIO target core v4.0.0-rc6") Signed-off-by: Shao Mingyin Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261026195133237y2UxJLoV1FK6aD1zrFbIU@zte.com.cn Signed-off-by: Martin K. Petersen (Oracle) --- drivers/target/target_core_alua.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/target/target_core_alua.c b/drivers/target/target_core_alua.c index 140154d93c4308..17386c96de1333 100644 --- a/drivers/target/target_core_alua.c +++ b/drivers/target/target_core_alua.c @@ -1081,8 +1081,15 @@ int core_alua_do_port_transition( return -EINVAL; local_lu_gp_mem = l_dev->dev_alua_lu_gp_mem; + if (!local_lu_gp_mem) + return -ENODEV; + spin_lock(&local_lu_gp_mem->lu_gp_mem_lock); lu_gp = local_lu_gp_mem->lu_gp; + if (!lu_gp) { + spin_unlock(&local_lu_gp_mem->lu_gp_mem_lock); + return -ENODEV; + } atomic_inc(&lu_gp->lu_gp_ref_cnt); spin_unlock(&local_lu_gp_mem->lu_gp_mem_lock); /* From 46846939d5f33c9333612662c52475f92e753407 Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Mon, 26 Oct 2026 19:54:09 +0800 Subject: [PATCH 0367/2102] scsi: rdac: Keep the error status when controller lookup fails initialize_controller() records SCSI_DH_RES_TEMP_UNAVAIL when get_controller() fails, but then overwrites it with SCSI_DH_OK unconditionally. It therefore reports success with h->ctlr == NULL and rdac_bus_attach() continues with check_ownership(), which dereferences h->ctlr: BUG: kernel NULL pointer dereference, address: 0000000000000000 ... check_ownership rdac_bus_attach get_controller() only fails when its GFP_ATOMIC allocation fails, so the crash happens exactly when memory is already scarce. Only report success after the controller was found and the device was added to its list. Fixes: 327825574132 ("scsi_dh_rdac: switch to scsi_execute_req_flags()") Signed-off-by: Shao Mingyin Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261026195409354OWEI2b6HO7swSphvv1FOc@zte.com.cn Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/device_handler/scsi_dh_rdac.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/scsi/device_handler/scsi_dh_rdac.c b/drivers/scsi/device_handler/scsi_dh_rdac.c index 742534c9938654..0986a6e2a6aee4 100644 --- a/drivers/scsi/device_handler/scsi_dh_rdac.c +++ b/drivers/scsi/device_handler/scsi_dh_rdac.c @@ -450,14 +450,14 @@ static int initialize_controller(struct scsi_device *sdev, spin_lock(&list_lock); h->ctlr = get_controller(index, array_name, array_id, sdev); - if (!h->ctlr) + if (!h->ctlr) { err = SCSI_DH_RES_TEMP_UNAVAIL; - else { + } else { h->sdev = sdev; list_add_rcu(&h->node, &h->ctlr->dh_list); + err = SCSI_DH_OK; } spin_unlock(&list_lock); - err = SCSI_DH_OK; } return err; } From 612293fb469c81408829e6325bae25725968986f Mon Sep 17 00:00:00 2001 From: Boyan Liu Date: Wed, 28 Oct 2026 14:16:51 +0800 Subject: [PATCH 0368/2102] scsi: sd_zbc: Cap zone report count by buffer size sd_zbc_report_zones() limits descriptor parsing to the requested zone count and the device-reported ZONE LIST LENGTH, but not to the number of descriptors that fit in the allocated report buffer. A malicious or malfunctioning device can report an oversized length and cause out-of-bounds reads while the descriptors are parsed: BUG: KASAN: slab-out-of-bounds in sd_zbc_report_zones (drivers/scsi/sd_zbc.c:256) Read of size 8 at addr ffff88802c8d2610 by task kworker/u8:2/37 Call Trace: sd_zbc_report_zones (drivers/scsi/sd_zbc.c:256) blk_revalidate_disk_zones (block/blk-zoned.c:2354) sd_zbc_revalidate_zones (drivers/scsi/sd_zbc.c:566) sd_revalidate_disk (drivers/scsi/sd.c:3898) sd_probe (drivers/scsi/sd.c:4101) Cap the descriptor count with min3() over the remaining requested zones, the device-reported count, and max_in_buf derived from buflen. This matches nvme_ns_report_zones() and preserves iteration over reports that require multiple commands. Use shared constants for the REPORT ZONES header and zone descriptor sizes. [mkp: define constants] Fixes: d41003513e61 ("block: rework zone reporting") Cc: stable@vger.kernel.org Reported-by: co+4a4f9998e2b4b490@bugs.sh Signed-off-by: Boyan Liu Link: https://patch.msgid.link/20261028061651.110435-1-yymhvert@gmail.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/sd_zbc.c | 9 +++++++-- include/scsi/scsi_proto.h | 3 +++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/drivers/scsi/sd_zbc.c b/drivers/scsi/sd_zbc.c index 8cbf171e6fabf1..06f4e3fcda1de9 100644 --- a/drivers/scsi/sd_zbc.c +++ b/drivers/scsi/sd_zbc.c @@ -222,7 +222,7 @@ int sd_zbc_report_zones(struct gendisk *disk, sector_t sector, { struct scsi_disk *sdkp = scsi_disk(disk); sector_t lba = sectors_to_logical(sdkp->device, sector); - unsigned int nr, i; + unsigned int nr, i, max_in_buf; unsigned char *buf; u64 zone_length, start_lba; size_t offset, buflen = 0; @@ -241,13 +241,18 @@ int sd_zbc_report_zones(struct gendisk *disk, sector_t sector, if (!buf) return -ENOMEM; + max_in_buf = (buflen - ZBC_REPORT_ZONES_HEADER_SIZE) / + ZBC_ZONE_DESCRIPTOR_SIZE; + while (zone_idx < nr_zones && lba < sdkp->capacity) { ret = sd_zbc_do_report_zones(sdkp, buf, buflen, lba, true); if (ret) goto out; offset = 0; - nr = min(nr_zones, get_unaligned_be32(&buf[0]) / 64); + nr = min3(nr_zones - zone_idx, + get_unaligned_be32(&buf[0]) / ZBC_ZONE_DESCRIPTOR_SIZE, + max_in_buf); if (!nr) break; diff --git a/include/scsi/scsi_proto.h b/include/scsi/scsi_proto.h index 9c7d31aa6bae59..0ee0cf3200d0ca 100644 --- a/include/scsi/scsi_proto.h +++ b/include/scsi/scsi_proto.h @@ -371,6 +371,9 @@ enum zbc_zone_reporting_options { #define ZBC_REPORT_ZONE_PARTIAL 0x80 +#define ZBC_REPORT_ZONES_HEADER_SIZE 64 +#define ZBC_ZONE_DESCRIPTOR_SIZE 64 + /* Zone types of REPORT ZONES zone descriptors */ enum zbc_zone_type { ZBC_ZONE_TYPE_CONV = 0x1, From 48d3b732e5ad3fffe74e033d9a3cf47ebaa314b0 Mon Sep 17 00:00:00 2001 From: Praneeth Balasubramanian Date: Thu, 29 Oct 2026 13:54:56 -0700 Subject: [PATCH 0369/2102] scsi: target: iscsi: Check for existing sessions only after authentication In the operational-negotiation path (CSG=1), iscsi_target_handle_csg_one() calls iscsi_target_check_for_existing_instances() before iscsi_conn_authenticated(). An initiator can therefore send a first Login PDU with CSG=1, TSIH=0 and no CHAP exchange, carrying the InitiatorName and ISID of an existing session. The target reinstates that session, which tears down the legitimate initiator's connection. Only afterwards does it reject the login with AUTH_FAILED. iscsi_check_for_session_reinstatement() matches on ISID, InitiatorName and SessionType only. The InitiatorName is not secret, and open-iscsi ISIDs are a fixed OUI followed by a small session counter. A remote peer with no credentials can thus repeatedly disconnect a CHAP-authenticated session and keep its I/O failing. The comment above iscsi_target_check_for_existing_instances() already states the intended invariant: NOTE: We check for existing sessions or connections AFTER the initiator has been successfully authenticated in order to protect against faked ISID/TSIH combinations. The security-negotiation path (CSG=0) honours this, calling the check only once authentication completes. Move the CSG=1 call below the authentication check so both paths behave the same. When authentication is not required, iscsi_conn_authenticated() returns true and behaviour is unchanged. Fixes: e48354ce078c ("iscsi-target: Add iSCSI fabric support for target v4.1") Cc: stable@vger.kernel.org Signed-off-by: Praneeth Balasubramanian Link: https://patch.msgid.link/20261029205456.1211532-1-praneethb2002@gmail.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/target/iscsi/iscsi_target_nego.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/target/iscsi/iscsi_target_nego.c b/drivers/target/iscsi/iscsi_target_nego.c index b03ed154ca34e9..ccd468e26fb925 100644 --- a/drivers/target/iscsi/iscsi_target_nego.c +++ b/drivers/target/iscsi/iscsi_target_nego.c @@ -982,9 +982,6 @@ static int iscsi_target_handle_csg_one(struct iscsit_conn *conn, struct iscsi_lo if (iscsi_target_check_first_request(conn, login) < 0) return -1; - if (iscsi_target_check_for_existing_instances(conn, login) < 0) - return -1; - ret = iscsi_encode_text_output( PHASE_OPERATIONAL|PHASE_DECLARATIVE, SENDER_TARGET, @@ -1008,6 +1005,9 @@ static int iscsi_target_handle_csg_one(struct iscsit_conn *conn, struct iscsi_lo return -1; } + if (iscsi_target_check_for_existing_instances(conn, login) < 0) + return -1; + if (!iscsi_check_negotiated_keys(conn->param_list)) if ((login_req->flags & ISCSI_FLAG_LOGIN_NEXT_STAGE3) && (login_req->flags & ISCSI_FLAG_LOGIN_TRANSIT)) From 08f08a6d49efc422258edba802faa4fc7677309e Mon Sep 17 00:00:00 2001 From: Ciro Iriarte Date: Sat, 31 Oct 2026 22:21:39 -0300 Subject: [PATCH 0370/2102] scsi: target: core: Parse APTPL res_type and res_scope as hex core_scsi3_update_aptpl_buf() saves the reservation holder's type and scope to the APTPL metadata file as zero-padded hex ("res_type=%02x", "res_scope=%02x"), but target_pr_res_aptpl_metadata_store() reads them back with "%d" tokens and match_int(), which parse with base 0. A leading zero selects octal, so match_token() parses only the "0" of "res_type=08", the trailing "8" makes the token not match, and the field is ignored as unknown. An Exclusive Access - All Registrants holder (type 0x8) is left with type 0 and the write fails with -EINVAL and Illegal PR type: 0x00 for reservation holder Userspace that restores APTPL state by writing the saved records back to pr/res_aptpl_metadata (rtslib-fb does this when it recreates a storage object) therefore loses every type 8 reservation across a target restart, and with rtslib the storage object creation fails. The other valid types (1, 3, 5, 6, 7) and scope 0 only work because their octal and decimal values coincide. Keep the on-disk format and parse both fields as hex. The valid type and scope values have the same hex and decimal representation, so records written in decimal by hand keep working. Fixes: c66ac9db8d4a ("[SCSI] target: Add LIO target core v4.0.0-rc6") Cc: stable@vger.kernel.org Signed-off-by: Ciro Iriarte Link: https://patch.msgid.link/ea903e6c-09b5-4a11-80e8-6e1387f39ef5@gmail.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/target/target_core_configfs.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/target/target_core_configfs.c b/drivers/target/target_core_configfs.c index 430fc1eaeca5d7..385b84bcbfb26e 100644 --- a/drivers/target/target_core_configfs.c +++ b/drivers/target/target_core_configfs.c @@ -2126,8 +2126,8 @@ static match_table_t tokens = { {Opt_initiator_sid, "initiator_sid=%s"}, {Opt_sa_res_key, "sa_res_key=%s"}, {Opt_res_holder, "res_holder=%d"}, - {Opt_res_type, "res_type=%d"}, - {Opt_res_scope, "res_scope=%d"}, + {Opt_res_type, "res_type=%x"}, + {Opt_res_scope, "res_scope=%x"}, {Opt_res_all_tg_pt, "res_all_tg_pt=%d"}, {Opt_mapped_lun, "mapped_lun=%u"}, {Opt_target_fabric, "target_fabric=%s"}, @@ -2229,13 +2229,13 @@ static ssize_t target_pr_res_aptpl_metadata_store(struct config_item *item, res_holder = arg; break; case Opt_res_type: - ret = match_int(args, &arg); + ret = match_hex(args, &arg); if (ret) goto out; type = (u8)arg; break; case Opt_res_scope: - ret = match_int(args, &arg); + ret = match_hex(args, &arg); if (ret) goto out; break; From e550f2b2b4aab4c5f12db89d04d8978ce4ed7b4e Mon Sep 17 00:00:00 2001 From: "Milan P. Gandhi" Date: Thu, 5 Nov 2026 17:54:01 +0530 Subject: [PATCH 0371/2102] scsi: mpi3mr: Validate reply frame size bounds Firmware provides reply_frame_size in dwords, which the driver multiplies by 4 to compute facts.reply_sz (u16). If the reported size exceeds U16_MAX / 4, the multiplication overflows u16 before assignment, causing under-allocated DMA reply buffers. Furthermore, several paths assume a minimal reply frame size: - logdata_entry_sz calculations underflow or hit zero when reply_sz <= 20 bytes, leading to zero-size allocations and divide-by-zero crashes. - Unsolicited status descriptors and fixed replies (such as struct mpi3_iounit_control_reply, 64 bytes) require at least 16 dwords. Validate reply_frame_size in mpi3mr_issue_iocfacts() to ensure it is within [16, U16_MAX / 4] dwords before processing facts data. Fixes: 824a156633df ("scsi: mpi3mr: Base driver code") Cc: stable@vger.kernel.org Signed-off-by: Milan P. Gandhi Link: https://patch.msgid.link/20261105122401.266559-1-mgandhi@redhat.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/mpi3mr/mpi3mr.h | 1 + drivers/scsi/mpi3mr/mpi3mr_fw.c | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/drivers/scsi/mpi3mr/mpi3mr.h b/drivers/scsi/mpi3mr/mpi3mr.h index d6e16707fd97c8..e78383df619c34 100644 --- a/drivers/scsi/mpi3mr/mpi3mr.h +++ b/drivers/scsi/mpi3mr/mpi3mr.h @@ -83,6 +83,7 @@ extern atomic64_t event_counter; #define MPI3MR_ADMIN_REPLY_Q_SIZE (8 * MPI3MR_PAGE_SIZE_4K) #define MPI3MR_ADMIN_REQ_FRAME_SZ 128 #define MPI3MR_ADMIN_REPLY_FRAME_SZ 16 +#define MPI3MR_MIN_REPLY_FRAME_SZ_DWORDS 16 /* 64 bytes */ /* Operational queue management definitions */ #define MPI3MR_OP_REQ_Q_QD 512 diff --git a/drivers/scsi/mpi3mr/mpi3mr_fw.c b/drivers/scsi/mpi3mr/mpi3mr_fw.c index f0d3cd398dd00c..60a92366e59049 100644 --- a/drivers/scsi/mpi3mr/mpi3mr_fw.c +++ b/drivers/scsi/mpi3mr/mpi3mr_fw.c @@ -3261,6 +3261,7 @@ static int mpi3mr_issue_iocfacts(struct mpi3mr_ioc *mrioc, struct mpi3_ioc_facts_data *facts_data) { struct mpi3_ioc_facts_request iocfacts_req; + u16 reply_frame_size; void *data = NULL; dma_addr_t data_dma; u32 data_len = sizeof(*facts_data); @@ -3318,6 +3319,23 @@ static int mpi3mr_issue_iocfacts(struct mpi3mr_ioc *mrioc, goto out_unlock; } memcpy(facts_data, (u8 *)data, data_len); + + reply_frame_size = le16_to_cpu(facts_data->reply_frame_size); + /* + * Validate reply_frame_size: + * - Must be at least 16 dwords (64 bytes) to accommodate fixed reply + * structures and avoid underflow/divide-by-zero in logdata sizing. + * - Must not exceed U16_MAX / 4 to prevent integer overflow. + */ + if (reply_frame_size < MPI3MR_MIN_REPLY_FRAME_SZ_DWORDS || + reply_frame_size > (U16_MAX / 4)) { + ioc_err(mrioc, "Invalid reply_frame_size %u (must be %u..%u dwords)\n", + reply_frame_size, MPI3MR_MIN_REPLY_FRAME_SZ_DWORDS, + (unsigned int)(U16_MAX / 4)); + retval = -EINVAL; + goto out_unlock; + } + mpi3mr_process_factsdata(mrioc, facts_data); out_unlock: mrioc->init_cmds.state = MPI3MR_CMD_NOTUSED; From b3249e446d47c65dc09611705ad4d0a7587405ac Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Fri, 6 Nov 2026 15:51:29 +0800 Subject: [PATCH 0372/2102] Input: goodix - reject a bak_ref length that cannot hold the checksum driver_num and sensor_num are taken from the touchscreen config. A config with driver_num 1 and sensor_num 0 yields a bak_ref length of 0, for which devm_kzalloc() returns ZERO_SIZE_PTR. That pointer passes the !ts->bak_ref check and the subsequent ts->bak_ref[ts->bak_ref_len - 1] = 1 writes before the allocation. Reject a length that leaves no room for the trailing checksum before allocating, and skip saving a bak_ref that was never allocated. Without the second check a rejected length leaves bak_ref NULL while bak_ref_len still holds the bogus value, and goodix_save_bak_ref() then writes through the same index on suspend. Fixes: 09182ed20c04 ("Input: goodix - add support for controllers without flash") Cc: stable@vger.kernel.org Signed-off-by: Liu Chao Link: https://patch.msgid.link/20261106075129.3106093-1-liuc63@xiaopeng.com Signed-off-by: Dmitry Torokhov --- drivers/input/touchscreen/goodix_fwupload.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/input/touchscreen/goodix_fwupload.c b/drivers/input/touchscreen/goodix_fwupload.c index 5ae9a109ba0d17..888da7538c065b 100644 --- a/drivers/input/touchscreen/goodix_fwupload.c +++ b/drivers/input/touchscreen/goodix_fwupload.c @@ -281,6 +281,8 @@ static int goodix_prepare_bak_ref(struct goodix_ts_data *ts) driver_num, sensor_num, have_key); ts->bak_ref_len = (driver_num * (sensor_num - 2) + 2) * 2; + if (ts->bak_ref_len < 2) + return -EINVAL; ts->bak_ref = devm_kzalloc(&ts->client->dev, ts->bak_ref_len, GFP_KERNEL); @@ -409,7 +411,7 @@ void goodix_save_bak_ref(struct goodix_ts_data *ts) int error; u8 val; - if (!ts->firmware_name) + if (!ts->firmware_name || !ts->bak_ref) return; error = goodix_i2c_read(ts->client, GOODIX_REG_STATUS, &val, 1); From f5f8cc539f8b2bd5324c03dfce8cca57284653e6 Mon Sep 17 00:00:00 2001 From: Wentao Liang Date: Sun, 8 Nov 2026 06:45:47 +0000 Subject: [PATCH 0373/2102] Input: cyapa - fix runtime PM leak in cyapa_update_rt_suspend_scanrate() pm_runtime_get_sync() unconditionally increments the runtime PM usage counter. If mutex_lock_interruptible() is interrupted, the function returns without dropping that reference, so the usage count stays elevated for as long as the driver is bound and the device can no longer be autosuspended. Drop the reference on the error path. Use pm_runtime_put_autosuspend() rather than the synchronous variant there: nothing has been done to the device on this path, so there is nothing to wait for, and with the 2 s autosuspend delay the driver configures the put only arms the autosuspend timer instead of suspending the device. Fixes: 672865080a8f ("Input: cyapa - add runtime power management support") Cc: stable@vger.kernel.org Signed-off-by: Wentao Liang Link: https://patch.msgid.link/1794120347.2701234.vulab@iscas.ac.cn Signed-off-by: Dmitry Torokhov --- drivers/input/mouse/cyapa.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/input/mouse/cyapa.c b/drivers/input/mouse/cyapa.c index a8e9b9ab9f84c1..737fc54539d933 100644 --- a/drivers/input/mouse/cyapa.c +++ b/drivers/input/mouse/cyapa.c @@ -900,8 +900,10 @@ static ssize_t cyapa_update_rt_suspend_scanrate(struct device *dev, pm_runtime_get_sync(dev); error = mutex_lock_interruptible(&cyapa->state_sync_lock); - if (error) + if (error) { + pm_runtime_put_autosuspend(dev); return error; + } cyapa->runtime_suspend_sleep_time = min_t(u16, time, 1000); cyapa->runtime_suspend_power_mode = From ff662d60374cd8858d1209f678f5f01b1b0be7c1 Mon Sep 17 00:00:00 2001 From: Andreas Grapentin Date: Thu, 5 Nov 2026 15:14:29 +0100 Subject: [PATCH 0374/2102] KVM: s390: arm64: Tolerate unused functions in extracted source Extracting static declared arm64 functions with no consumer on the s390 side into the generated sources causes compiler warnings when subsuming the generated sources from s390. This causes spurious compiler warnings that make it harder to extract larger, more cohesive portions of the arm64 source. Update the extraction logic to wrap the extracted source into diagnostic pragmas to disable -Wunused-function for the extracted block. This allows us to share more freely, and also opens up more paths for future code sharing with a separation of extraction and definition of consumers in separate commits. Obviously no functional change intended. Signed-off-by: Andreas Grapentin Reviewed-by: Steffen Eiden Acked-by: Christian Borntraeger Signed-off-by: Christian Borntraeger --- arch/s390/kvm/arm64/copy-arm64c.awk | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/arch/s390/kvm/arm64/copy-arm64c.awk b/arch/s390/kvm/arm64/copy-arm64c.awk index 640a7bcb7e23e2..a318be97c4191d 100644 --- a/arch/s390/kvm/arm64/copy-arm64c.awk +++ b/arch/s390/kvm/arm64/copy-arm64c.awk @@ -42,6 +42,9 @@ BEGIN { print "#endif /* __INCL_GEN_ARM_FILE */" print "#undef __INCL_GEN_ARM_FILE" print "" + print "__diag_push()" + print "__diag_ignore_all(\"-Wunused-function\", \"tolerate unused functions shared from arm64\")" + print "" file_header_done = 1 } @@ -78,5 +81,10 @@ copying { } END { - exit error || !found_marker || copying + ok = !error && found_marker && !copying + if (ok) { + print "" + print "__diag_pop()" + } + exit !ok } From 976311c5594a7a26047891f087ad59a804e02baa Mon Sep 17 00:00:00 2001 From: Guixin Liu Date: Mon, 9 Nov 2026 10:26:46 +0800 Subject: [PATCH 0375/2102] nvmet: use GFP_KERNEL for PR allocations nvmet_pr_update_reg_attr() and nvmet_pr_alloc_and_insert_pc_ref() allocate with GFP_ATOMIC, but both run in sleepable context: the PR command handlers execute from the transport workqueues and take the pr_sem semaphore, and the pc_ref allocation is reached from the connect and configfs paths. The latter function even passes GFP_KERNEL to the percpu_ref_init() in the same scope, so the GFP_ATOMIC only raises the failure rate for no reason. Switch both allocations to GFP_KERNEL. Fixes: 5a47c2080a73 ("nvmet: support reservation feature") Cc: stable@vger.kernel.org Reviewed-by: Hannes Reinecke Reviewed-by: Christoph Hellwig Reviewed-by: Nilay Shroff Signed-off-by: Guixin Liu Signed-off-by: Keith Busch --- drivers/nvme/target/pr.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/nvme/target/pr.c b/drivers/nvme/target/pr.c index b860cbe192cd29..8c818f24815bdf 100644 --- a/drivers/nvme/target/pr.c +++ b/drivers/nvme/target/pr.c @@ -341,7 +341,7 @@ static u16 nvmet_pr_update_reg_attr(struct nvmet_pr *pr, return NVME_SC_SUCCESS; } - new = kmalloc_obj(*new, GFP_ATOMIC); + new = kmalloc_obj(*new, GFP_KERNEL); if (!new) return NVME_SC_INTERNAL; @@ -1046,7 +1046,7 @@ static int nvmet_pr_alloc_and_insert_pc_ref(struct nvmet_ns *ns, struct nvmet_pr_per_ctrl_ref *pc_ref; int ret; - pc_ref = kmalloc_obj(*pc_ref, GFP_ATOMIC); + pc_ref = kmalloc_obj(*pc_ref, GFP_KERNEL); if (!pc_ref) return -ENOMEM; From f92fe8dea19c743eb9e4d998ae0384344dd40091 Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Thu, 5 Nov 2026 21:58:07 +0800 Subject: [PATCH 0376/2102] nvme: reject invalid reconnect_delay sysfs values nvme_ctrl_reconnect_delay_store() stores whatever kstrtou32() accepted into opts->reconnect_delay without validating it. The nvme-fabrics option parser refuses reconnect_delay values that are zero or negative, and the rest of the driver relies on that: nvme_ctrl_loss_tmo_store() computes opts->max_reconnects = DIV_ROUND_UP(ctrl_loss_tmo, opts->reconnect_delay); Writing 0 to reconnect_delay and then a positive value to ctrl_loss_tmo therefore divides by zero in the kernel. In addition, a value larger than INT_MAX is truncated to a negative int in the assignment and silently bypasses the checks done by the fabrics parser. Reject zero and values that do not fit into the signed int field. Fixes: 764075fdcb2f ("nvme: expose reconnect_delay and ctrl_loss_tmo via sysfs") Cc: stable@vger.kernel.org Signed-off-by: Shao Mingyin Signed-off-by: Keith Busch --- drivers/nvme/host/sysfs.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/nvme/host/sysfs.c b/drivers/nvme/host/sysfs.c index 3724b5ce03a079..9672ca3f74d2e8 100644 --- a/drivers/nvme/host/sysfs.c +++ b/drivers/nvme/host/sysfs.c @@ -632,6 +632,9 @@ static ssize_t nvme_ctrl_reconnect_delay_store(struct device *dev, if (err) return err; + if (!v || v > INT_MAX) + return -EINVAL; + ctrl->opts->reconnect_delay = v; return count; } From c1f4db7e869ce7dafd1811a75b392740985e1199 Mon Sep 17 00:00:00 2001 From: Ivan Verbovoy Date: Mon, 9 Nov 2026 19:15:55 +0200 Subject: [PATCH 0377/2102] Input: da7280 - do not advertise FF_GAIN The driver sets FF_GAIN in the device's force feedback capabilities but provides no set_gain() callback. input_ff_event() checks the capability bit, not the callback, before calling ff->set_gain(), so an EV_FF/FF_GAIN event written to the event node by any process with write access to it calls through a NULL pointer. The driver has no global gain to set: a constant effect carries its own level, and a periodic effect plays a pattern from the device's waveform memory. Drop FF_GAIN from the capabilities, so that input_ff_event() ignores such an event. Fixes: cd3f609823a5 ("Input: new da7280 haptic driver") Cc: stable@vger.kernel.org Signed-off-by: Ivan Verbovoy Link: https://patch.msgid.link/20261109-da7280-fixes-v1-1-09cc3650261c@gmail.com Signed-off-by: Dmitry Torokhov --- drivers/input/misc/da7280.c | 1 - 1 file changed, 1 deletion(-) diff --git a/drivers/input/misc/da7280.c b/drivers/input/misc/da7280.c index e607836efb500c..1a03f9586d3952 100644 --- a/drivers/input/misc/da7280.c +++ b/drivers/input/misc/da7280.c @@ -1226,7 +1226,6 @@ static int da7280_probe(struct i2c_client *client) input_set_capability(haptics->input_dev, EV_FF, FF_PERIODIC); input_set_capability(haptics->input_dev, EV_FF, FF_CUSTOM); input_set_capability(haptics->input_dev, EV_FF, FF_CONSTANT); - input_set_capability(haptics->input_dev, EV_FF, FF_GAIN); error = input_ff_create(haptics->input_dev, DA7280_FF_EFFECT_COUNT_MAX); From 82838789646f9f5881dd1c8b3a3c960ee2a28772 Mon Sep 17 00:00:00 2001 From: Paul Moses Date: Fri, 30 Oct 2026 06:59:28 +0000 Subject: [PATCH 0378/2102] perf record: Skip affinity for per-thread mmap buffers Per-thread mmap buffers use CPU -1 to mean any CPU. Combining --per-thread with --affinity=cpu passes this value to __set_bit() when constructing the reader affinity mask, causing an out-of-bounds bitmap access and SIGSEGV. Program received signal SIGSEGV, Segmentation fault. 0x0000555555f3488e in mmap.mmap () #0 0x0000555555f3488e in mmap.mmap () #1 0x0000555555e2f7bf in mmap_per_evsel (evlist=evlist@entry=0x7fffedcc1150, ops=ops@entry=0x7fffffffaf50, idx=idx@entry=0, mp=mp@entry=0x7fffffffaf70, cpu_idx=cpu_idx@entry=0, thread=thread@entry=0, _output=0x7fffffffaf08, _output_overwrite=0x7fffffffaf04, nr_mmaps=0x7fffffffaf0c) at evlist.c:598 #2 0x0000555555e2ef96 in mmap_per_thread (evlist=0x7fffedcc1150, ops=0x7fffffffaf50, mp=0x7fffffffaf70) at evlist.c:650 #3 perf_evlist__mmap_ops (evlist=0x7fffedcc1150, ops=0x7fffffffaf50, mp=0x7fffffffaf70) at evlist.c:748 #4 0x0000555555f2150d in evlist.mmap_ex () #5 0x0000555555db0b0a in record.open () #6 0x0000555555dadea7 in __cmd_record () #7 0x0000555555daca89 in cmd_record () #8 0x0000555555e27d53 in run_builtin () #9 0x0000555555e277cf in main () rip 0x555555f3488e 0x555555f3488e rax 0x7fffef9e9bd0 140737213537232 rbx 0x7fffedd249a0 140737183369632 rcx 0x3ffffffffffffff 288230376151711743 rdx 0x8000000000000000 -9223372036854775808 rsi 0x0 0 rdi 0x7fffef9e9bd0 140737213537232 0x555555f34876 : movswq 0x10(%rbx),%rcx 0x555555f3487b : mov 0xb8(%rbx),%rax 0x555555f34882 : mov $0x1,%edx 0x555555f34887 : shl %cl,%rdx 0x555555f3488a : shr $0x6,%rcx => 0x555555f3488e : or %rdx,(%rax,%rcx,8) 0x555555f34892 : lea 0x17711b(%rip),%r14 # 0x5555560ab9b4 0x555555f34899 : cmpl $0x2,(%r14) 0x555555f3489d : jne 0x555555f348f7 0x555555f3489f : mov 0xb8(%rbx),%rdi 0x555555f348a6 : mov 0xc0(%rbx),%esi 0x555555f348ac : lea -0x430(%rbp),%r12 Only construct and apply reader affinity masks for buffers with a nonnegative CPU. Skip the reader-side bitmap operations as well, since per-thread buffers no longer allocate an affinity mask. Fixes: 8384a2600c7ddfc8 ("perf record: Adapt affinity to machines with #CPUs > 1K") Signed-off-by: Paul Moses Acked-by: Namhyung Kim Cc: Adrian Hunter Cc: Alexander Shishkin Cc: Alexey Budankov Cc: Ian Rogers Cc: Ingo Molnar Cc: James Clark Cc: Jiri Olsa Cc: Mark Rutland Cc: Namhyung Kim Cc: Peter Zijlstra Signed-off-by: Arnaldo Carvalho de Melo --- tools/perf/builtin-record.c | 2 +- tools/perf/util/mmap.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/perf/builtin-record.c b/tools/perf/builtin-record.c index 0e98a613c37df9..085d3648a30a33 100644 --- a/tools/perf/builtin-record.c +++ b/tools/perf/builtin-record.c @@ -1580,7 +1580,7 @@ static struct perf_event_header finished_init_event = { static void record__adjust_affinity(struct record *rec, struct mmap *map) { - if (rec->opts.affinity != PERF_AFFINITY_SYS && + if (map->core.cpu.cpu >= 0 && rec->opts.affinity != PERF_AFFINITY_SYS && !bitmap_equal(thread->mask->affinity.bits, map->affinity_mask.bits, thread->mask->affinity.nbits)) { bitmap_zero(thread->mask->affinity.bits, thread->mask->affinity.nbits); diff --git a/tools/perf/util/mmap.c b/tools/perf/util/mmap.c index 6dcc4a9304b926..d6fbde9699bfcf 100644 --- a/tools/perf/util/mmap.c +++ b/tools/perf/util/mmap.c @@ -292,8 +292,8 @@ int mmap__mmap(struct mmap *map, struct mmap_params *mp, int fd, struct perf_cpu return -1; } - if (mp->affinity != PERF_AFFINITY_SYS && - perf_mmap__setup_affinity_mask(map, mp)) { + if (cpu.cpu >= 0 && mp->affinity != PERF_AFFINITY_SYS && + perf_mmap__setup_affinity_mask(map, mp)) { pr_debug2("failed to alloc mmap affinity mask, error %d\n", errno); return -1; From beb0ae6bcd7505e2e61babe5d98a8dd3b3f03c7f Mon Sep 17 00:00:00 2001 From: Stephen Smalley Date: Fri, 6 Nov 2026 13:29:13 -0500 Subject: [PATCH 0379/2102] selinux: check MAP_SHARED_VALIDATE mappings as shared selinux_mmap_file() only recognizes MAP_SHARED as a shared mapping, but MAP_SHARED_VALIDATE is also a shared mapping type. The mmap flags reach this hook before the mm code processes the mapping type. Consequently, a writable MAP_SHARED_VALIDATE mapping was failing to check the file write permission at mmap time, and a writable executable file mapping was wrongly checking process execmem permission as if it were private. Cc: stable@vger.kernel.org Link: https://github.com/SELinuxProject/selinux-kernel/issues/78 Fixes: 1c9725974074 ("mm: introduce MAP_SHARED_VALIDATE, a mechanism to safely define new mmap flags") Signed-off-by: Stephen Smalley Signed-off-by: Paul Moore --- security/selinux/hooks.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c index 9950f89dfaa230..6c4c64d6e9042f 100644 --- a/security/selinux/hooks.c +++ b/security/selinux/hooks.c @@ -4179,8 +4179,11 @@ static int selinux_mmap_file(struct file *file, unsigned long reqprot __always_unused, unsigned long prot, unsigned long flags) { + const unsigned long map_type = (flags & MAP_TYPE); + return selinux_mmap_file_common(file, prot, - (flags & MAP_TYPE) == MAP_SHARED, + (map_type == MAP_SHARED || + map_type == MAP_SHARED_VALIDATE), false); } From 2520694e60489136300df56d157fb5e04051eea5 Mon Sep 17 00:00:00 2001 From: Sean Christopherson Date: Fri, 30 Oct 2026 14:20:49 -0700 Subject: [PATCH 0380/2102] KVM: Reject user accesses to guest memory if current->mm != kvm->mm Reject user accesses to guest memory, which are supposed to be done only in the context of KVM_RUN or similar operations, if the current address space is not the VM's (host userspace) address space. If KVM writes to guest memory after the owning host process has exited, or if the VM is being destroyed in the context of a different process, then writing using the wrong address space will corrupt a different process' memory. Reject the access but don't WARN() or KVM_BUG_ON() event though attempting to access guest memory with a mismatched address space is a blatant KVM bug, because unfortunately KVM is buggy. On KVM VMX, when a vCPU is destroyed while L2 is active, KVM synthesizes a nested VM-Exit to force the vCPU out of L2 in order to free the nested VMX assets, and a side effect of a nested VM-Exit is that it flushes the cached shadow VMCS12 back to guest memory: vmx_vcpu_free() |-> nested_vmx_free_vcpu() |-> vmx_leave_nested() |-> nested_vmx_vmexit(vcpu, -1, 0, 0) |-> nested_flush_cached_shadow_vmcs12() |-> kvm_write_guest_cached() |-> __copy_to_user(ghc->hva, ...) Fix the bug broadly even though the "real" bug is that KVM abuses the nested VM-Exit flow for non-architectural purposes, as there may be other such violations lurking. For now, punt on fixing individual bugs and hardening the common flows, e.g. with WARNs. Opportunistically provide wrappers in anticipation of adding more checks and hardening, i.e. growing the logic beyond checking current->mm. Fixes: 61ada7488ffd ("KVM: nVMX: Cache shadow vmcs12 on VMEntry and flush to memory on VMExit") Cc: stable@vger.kernel.org Reported-by: Jim Mattson Closes: https://lore.kernel.org/all/20260908132838.2116068-1-jmattson@google.com Reviewed-by: James Houghton Tested-by: syzbot@syzkaller.appspotmail.com Link: https://patch.msgid.link/20261030212112.2598640-2-seanjc@google.com Signed-off-by: Sean Christopherson --- arch/x86/kvm/vmx/sgx.c | 2 +- arch/x86/kvm/vmx/vmx.c | 8 ++++---- include/linux/kvm_host.h | 25 +++++++++++++++++++++++-- virt/kvm/kvm_main.c | 24 ++++++++++++------------ 4 files changed, 40 insertions(+), 19 deletions(-) diff --git a/arch/x86/kvm/vmx/sgx.c b/arch/x86/kvm/vmx/sgx.c index 771c75a5834364..52a6d0f8bb9e9a 100644 --- a/arch/x86/kvm/vmx/sgx.c +++ b/arch/x86/kvm/vmx/sgx.c @@ -64,7 +64,7 @@ static void sgx_handle_emulation_failure(struct kvm_vcpu *vcpu, u64 addr, static int sgx_read_hva(struct kvm_vcpu *vcpu, unsigned long hva, void *data, unsigned int size) { - if (__copy_from_user(data, (void __user *)hva, size)) { + if (kvm_copy_from_user(vcpu->kvm, data, (void __user *)hva, size)) { sgx_handle_emulation_failure(vcpu, hva, size); return -EFAULT; } diff --git a/arch/x86/kvm/vmx/vmx.c b/arch/x86/kvm/vmx/vmx.c index 82eb891f684c58..fffdc6e5a7e770 100644 --- a/arch/x86/kvm/vmx/vmx.c +++ b/arch/x86/kvm/vmx/vmx.c @@ -4021,16 +4021,16 @@ static int init_rmode_tss(struct kvm *kvm, void __user *ua) int i; for (i = 0; i < 3; i++) { - if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE)) + if (kvm_copy_to_user(kvm, ua + PAGE_SIZE * i, zero_page, PAGE_SIZE)) return -EFAULT; } data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE; - if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16))) + if (kvm_copy_to_user(kvm, ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16))) return -EFAULT; data = ~0; - if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8))) + if (kvm_copy_to_user(kvm, ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8))) return -EFAULT; return 0; @@ -4065,7 +4065,7 @@ static int init_rmode_identity_map(struct kvm *kvm) for (i = 0; i < (PAGE_SIZE / sizeof(tmp)); i++) { tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER | _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE); - if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) { + if (kvm_copy_to_user(kvm, uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) { r = -EFAULT; goto out; } diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h index e7fc94e2910a86..be27b4e8f12dfa 100644 --- a/include/linux/kvm_host.h +++ b/include/linux/kvm_host.h @@ -1353,13 +1353,34 @@ int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc, gpa_t gpa, unsigned long len); +static __always_inline __must_check bool kvm_can_do_uaccess(struct kvm *kvm) +{ + return current->mm == kvm->mm; +} + +#define BUILD_KVM_COPY_USER_WRAPPER(fn, to_user, from_user) \ +static __always_inline __must_check unsigned long kvm_##fn(struct kvm *kvm, \ + void to_user *to, \ + const void from_user *from, \ + unsigned long n) \ +{ \ + if (!kvm_can_do_uaccess(kvm)) \ + return n; \ + \ + return __##fn(to, from, n); \ +} +BUILD_KVM_COPY_USER_WRAPPER(copy_from_user, , __user) +BUILD_KVM_COPY_USER_WRAPPER(copy_from_user_inatomic, , __user) +BUILD_KVM_COPY_USER_WRAPPER(copy_to_user, __user, ) +BUILD_KVM_COPY_USER_WRAPPER(copy_to_user_inatomic, __user, ) + #define __kvm_get_guest(kvm, gfn, offset, v) \ ({ \ unsigned long __addr = gfn_to_hva(kvm, gfn); \ typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset); \ int __ret = -EFAULT; \ \ - if (!kvm_is_error_hva(__addr)) \ + if (!kvm_is_error_hva(__addr) && kvm_can_do_uaccess(kvm)) \ __ret = get_user(v, __uaddr); \ __ret; \ }) @@ -1379,7 +1400,7 @@ int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc, typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset); \ int __ret = -EFAULT; \ \ - if (!kvm_is_error_hva(__addr)) \ + if (!kvm_is_error_hva(__addr) && kvm_can_do_uaccess(kvm)) \ __ret = put_user(v, __uaddr); \ if (!__ret) \ mark_page_dirty(kvm, gfn); \ diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c index cf4cb586f1407b..218456372b118e 100644 --- a/virt/kvm/kvm_main.c +++ b/virt/kvm/kvm_main.c @@ -3279,8 +3279,8 @@ static int next_segment(unsigned long len, int offset) } /* Copy @len bytes from guest memory at '(@gfn * PAGE_SIZE) + @offset' to @data */ -static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn, - void *data, int offset, int len) +static int __kvm_read_guest_page(struct kvm *kvm, struct kvm_memory_slot *slot, + gfn_t gfn, void *data, int offset, int len) { int r; unsigned long addr; @@ -3291,7 +3291,7 @@ static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn, addr = gfn_to_hva_memslot_prot(slot, gfn, NULL); if (kvm_is_error_hva(addr)) return -EFAULT; - r = __copy_from_user(data, (void __user *)addr + offset, len); + r = kvm_copy_from_user(kvm, data, (void __user *)addr + offset, len); if (r) return -EFAULT; return 0; @@ -3302,7 +3302,7 @@ int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset, { struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn); - return __kvm_read_guest_page(slot, gfn, data, offset, len); + return __kvm_read_guest_page(kvm, slot, gfn, data, offset, len); } EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest_page); @@ -3311,7 +3311,7 @@ int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data, { struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); - return __kvm_read_guest_page(slot, gfn, data, offset, len); + return __kvm_read_guest_page(vcpu->kvm, slot, gfn, data, offset, len); } EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_read_guest_page); @@ -3355,8 +3355,8 @@ int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned l } EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_read_guest); -static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn, - void *data, int offset, unsigned long len) +static int __kvm_read_guest_atomic(struct kvm *kvm, struct kvm_memory_slot *slot, + gfn_t gfn, void *data, int offset, unsigned long len) { int r; unsigned long addr; @@ -3368,7 +3368,7 @@ static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn, if (kvm_is_error_hva(addr)) return -EFAULT; pagefault_disable(); - r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len); + r = kvm_copy_from_user_inatomic(kvm, data, (void __user *)addr + offset, len); pagefault_enable(); if (r) return -EFAULT; @@ -3382,7 +3382,7 @@ int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa, struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); int offset = offset_in_page(gpa); - return __kvm_read_guest_atomic(slot, gfn, data, offset, len); + return __kvm_read_guest_atomic(vcpu->kvm, slot, gfn, data, offset, len); } EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_read_guest_atomic); @@ -3400,7 +3400,7 @@ static int __kvm_write_guest_page(struct kvm *kvm, addr = gfn_to_hva_memslot(memslot, gfn); if (kvm_is_error_hva(addr)) return -EFAULT; - r = __copy_to_user((void __user *)addr + offset, data, len); + r = kvm_copy_to_user(kvm, (void __user *)addr + offset, data, len); if (r) return -EFAULT; mark_page_dirty_in_slot(kvm, memslot, gfn); @@ -3538,7 +3538,7 @@ int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, if (unlikely(!ghc->memslot)) return kvm_write_guest(kvm, gpa, data, len); - r = __copy_to_user((void __user *)ghc->hva + offset, data, len); + r = kvm_copy_to_user(kvm, (void __user *)ghc->hva + offset, data, len); if (r) return -EFAULT; mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT); @@ -3576,7 +3576,7 @@ int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, if (unlikely(!ghc->memslot)) return kvm_read_guest(kvm, gpa, data, len); - r = __copy_from_user(data, (void __user *)ghc->hva + offset, len); + r = kvm_copy_from_user(kvm, data, (void __user *)ghc->hva + offset, len); if (r) return -EFAULT; From 99872af7b904c82bdb7ff64b5124cba667275faa Mon Sep 17 00:00:00 2001 From: Sean Christopherson Date: Fri, 30 Oct 2026 14:20:50 -0700 Subject: [PATCH 0381/2102] KVM: nVMX: Don't force a full nested VM-Exit when destroying a vCPU For all intents and purposes, revert commit b4b65b5642d6 ("KVM: x86: cleanup freeing of nested state") and go back to manually tearing down nested state when freeing a vCPU. When a vCPU is destroyed while L2 is active, KVM synthesizes a nested VM-Exit, which flushes the cached shadow VMCS12 back to guest memory: vmx_vcpu_free() |-> nested_vmx_free_vcpu() |-> vmx_leave_nested() |-> nested_vmx_vmexit(vcpu, -1, 0, 0) |-> nested_flush_cached_shadow_vmcs12() |-> kvm_write_guest_cached() |-> __copy_to_user(ghc->hva, ...) Accessing user memory via a memslot during VM destruction is broken, as there are no guarantees that current->mm == kvm->mm when the VM is dying, because the last reference to the VM can be put from a different process than the original creating processes. And even if the original process does put the final reference, during process exit, do_exit() calls exit_mm() before closing file descriptors, so vCPU destruction runs with current->mm == NULL on a borrowed lazy TLB active_mm. If the borrowed address space has a writable mapping at the to-be-written userspace address, KVM will corrupt an unrelated task's memory since uaccess APIs, including __copy_to_user(), don't sanity check current->mm (and *can't* perform KVM's current->mm == kvm->mm sanity check since that is firmly a KVM-only concept). Furthermore, the shadow VMCS flaw is only the tip of the iceberg, as the MSR load/store lists mean that emulating a nested VM-Exit can read or write an arbitrary set of MSRs, e.g. if MSR_KVM_SYSTEM_TIME_NEW is in L1's MSR load list: kvm_arch_vcpu_destroy() kvmclock_reset() - takes pv_time off kvm->gpc_list vmx_vcpu_free() nested_vmx_free_vcpu() vmx_leave_nested() nested_vmx_vmexit() __nested_vmx_vmexit() load_vmcs12_host_state() nested_vmx_load_msr() - writes the MSRs that L1 listed kvm_cpu_has_injectable_intr() - reads Xen's vcpu_info kvm_xen_destroy_vcpu() - deactivates the vcpu_info cache processing the MSR write puts the "pv_time" cache back on kvm->gpc_list, and the next list_del() writes into the freed vCPU. And as effectively pointed out by syzbot[*], attempting to fix each case individually is a losing game of whack-a-mole. Deliberately leave "nested_run_pending" as-is, because even though doing so creates potentially inconsistent state, KVM should *never* consume said state while freeing a vCPU. I.e. if leaving nested_run_pending set trips a sanity check or bug, then that just means there's more fixing to be done. Open code only the "free vCPU" path, i.e. keep emulating a nested VM-Exit when forcing a vCPU out of L2 via vmx_leave_nested(), as there are a number of updates buried in the nested VM-Exit flow that are needed if the vCPU is going to run in L1, e.g. clearing pending exceptions and MTF traps, setting the TSC offset+scale information back to L1, and so on and so forth. Note, this means svm_leave_nested() is all but guaranteed to be buggy, but that's basically an open secret at this point and at least any bugs "only" break L1, i.e. don't corrupt host state as is the case for abusing nested VM-Exit when freeing a vCPU. Link: https://lore.kernel.org/all/6ac0145f.34119e79.2f92f3.0003.GAE@google.com [*] Fixes: b4b65b5642d6 ("KVM: x86: cleanup freeing of nested state") Cc: stable@vger.kernel.org Co-developed-by: Chris Mason Signed-off-by: Chris Mason Reviewed-by: Jim Mattson Reported-by: Hyunwoo Kim Closes: https://lore.kernel.org/all/am3Bs0DjZ5kay9NJ@v4bel Tested-by: syzbot@syzkaller.appspotmail.com Link: https://patch.msgid.link/20261030212112.2598640-3-seanjc@google.com Signed-off-by: Sean Christopherson --- arch/x86/kvm/vmx/nested.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/arch/x86/kvm/vmx/nested.c b/arch/x86/kvm/vmx/nested.c index 879183c1bfa5b4..fa50129ea5847d 100644 --- a/arch/x86/kvm/vmx/nested.c +++ b/arch/x86/kvm/vmx/nested.c @@ -385,8 +385,15 @@ static void free_nested(struct kvm_vcpu *vcpu) */ void nested_vmx_free_vcpu(struct kvm_vcpu *vcpu) { + struct vcpu_vmx *vmx = to_vmx(vcpu); + vcpu_load(vcpu); - vmx_leave_nested(vcpu); + if (is_guest_mode(vcpu)) { + hrtimer_cancel(&vmx->nested.preemption_timer); + leave_guest_mode(vcpu); + vmx_switch_vmcs(vcpu, &vmx->vmcs01); + } + free_nested(vcpu); vcpu_put(vcpu); } From 93862ef1afdd6ceec1da7933bd6c65fa840b547b Mon Sep 17 00:00:00 2001 From: Sean Christopherson Date: Fri, 30 Oct 2026 14:20:51 -0700 Subject: [PATCH 0382/2102] KVM: PPC: Flush/zap all memslots on kvm_arch_flush_shadow_all() Flush/zap every memslot in kvm_arch_flush_shadow_all(), i.e. when the owning userspace process is exiting, as KVM must ensure all associated memory is unmapped from the guest. Cc: stable@vger.kernel.org Reviewed-by: Ritesh Harjani (IBM) Tested-by: syzbot@syzkaller.appspotmail.com Link: https://patch.msgid.link/20261030212112.2598640-4-seanjc@google.com Signed-off-by: Sean Christopherson --- arch/powerpc/include/asm/kvm_host.h | 1 - arch/powerpc/kvm/powerpc.c | 11 +++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/arch/powerpc/include/asm/kvm_host.h b/arch/powerpc/include/asm/kvm_host.h index 708a32f8977652..50a42f80e5f12e 100644 --- a/arch/powerpc/include/asm/kvm_host.h +++ b/arch/powerpc/include/asm/kvm_host.h @@ -910,7 +910,6 @@ struct kvm_vcpu_arch { #define __KVM_HAVE_CREATE_DEVICE static inline void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen) {} -static inline void kvm_arch_flush_shadow_all(struct kvm *kvm) {} static inline void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu) {} static inline void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu) {} diff --git a/arch/powerpc/kvm/powerpc.c b/arch/powerpc/kvm/powerpc.c index 9194cf492d1ca2..9e9d0865c2f624 100644 --- a/arch/powerpc/kvm/powerpc.c +++ b/arch/powerpc/kvm/powerpc.c @@ -764,6 +764,17 @@ void kvm_arch_commit_memory_region(struct kvm *kvm, kvmppc_core_commit_memory_region(kvm, old, new, change); } +void kvm_arch_flush_shadow_all(struct kvm *kvm) +{ + struct kvm_memory_slot *slot; + struct kvm_memslots *slots; + int bkt; + + slots = kvm_memslots(kvm); + kvm_for_each_memslot(slot, bkt, slots) + kvmppc_core_flush_memslot(kvm, slot); +} + void kvm_arch_flush_shadow_memslot(struct kvm *kvm, struct kvm_memory_slot *slot) { From 7a2ff8e1f2817741d1a68f00a9cdf05fa158be64 Mon Sep 17 00:00:00 2001 From: Sasha Levin Date: Wed, 14 Oct 2026 16:01:52 -0400 Subject: [PATCH 0383/2102] KVM: selftests: Provide empty installation rules on unsupported ARCHs Unsupported architectures provide all and clean, but installation and runlist generation fail with missing targets. Supply empty install, emit_tests and run_tests targets alongside the existing empty rules. This represents an unsupported suite without creating dummy artifacts. Fixes: 43fbd8cd389f ("KVM: selftests: Provide empty 'all' and 'clean' targets for unsupported ARCHs") Signed-off-by: Sasha Levin Link: https://patch.msgid.link/20261014200152.1365147-1-sashal@kernel.org Signed-off-by: Sean Christopherson --- tools/testing/selftests/kvm/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/testing/selftests/kvm/Makefile b/tools/testing/selftests/kvm/Makefile index 03d91f00092f4a..cc279abbb00437 100644 --- a/tools/testing/selftests/kvm/Makefile +++ b/tools/testing/selftests/kvm/Makefile @@ -11,6 +11,6 @@ endif include Makefile.kvm else # Empty targets for unsupported architectures -all: -clean: +all clean run_tests install emit_tests: +.PHONY: all clean run_tests install emit_tests endif From b2ddd6af0646503364e23c021f5d2748473c9d4e Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Tue, 22 Sep 2026 08:19:44 +0100 Subject: [PATCH 0384/2102] KVM: selftests: Fix arm64 sysreg header dependencies The rule generating the arm64 sysreg header targets the generated directory, and its only prerequisite is tools/arch/arm64/tools/*, which expands to the inner Makefile. An existing directory looks up to date, so an incremental build never regenerates sysreg-defs.h for a change to the sysreg table. A selftest referencing a register added to the table since then fails with undeclared SYS_* identifiers. Clean builds are unaffected. Always recurse into tools/arch/arm64/tools, whose Makefile already tracks the generator's inputs, and target the header rather than its directory. The recursion leaves the header untouched when nothing changed, so the dependents rebuild only when the header does. Fixes: 70c7b704ca725 ("KVM: selftests: Avoid using forced target for generating arm64 headers") Link: https://lore.kernel.org/r/arGRhHgP_izSwW4T@kernel.org Assisted-by: LLM Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20260922071945.693714-2-fuad.tabba@linux.dev Signed-off-by: Sean Christopherson --- tools/testing/selftests/kvm/Makefile.kvm | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm index 17a4256e908191..283c59d7649c67 100644 --- a/tools/testing/selftests/kvm/Makefile.kvm +++ b/tools/testing/selftests/kvm/Makefile.kvm @@ -319,10 +319,16 @@ arm64_hdr_outdir := $(tools_dir)/ endif GEN_HDRS := $(arm64_hdr_outdir)arch/arm64/include/generated/ +GEN_SYSREG_DEFS := $(GEN_HDRS)asm/sysreg-defs.h CFLAGS += -I$(GEN_HDRS) -$(GEN_HDRS): $(wildcard $(arm64_tools_dir)/*) +# The inner Makefile tracks the generator's inputs and leaves the header +# untouched when nothing changed, so dependents rebuild only when it does. +$(GEN_SYSREG_DEFS): FORCE $(MAKE) -C $(arm64_tools_dir) OUTPUT=$(arm64_hdr_outdir) + +FORCE: +.PHONY: FORCE endif no-pie-option := $(call try-run, echo 'int main(void) { return 0; }' | \ @@ -375,10 +381,10 @@ EXTRA_CLEAN += $(GEN_HDRS) \ $(TEST_GEN_OBJ) \ cscope.* -$(LIBKVM_C_OBJ): $(OUTPUT)/%.o: %.c $(GEN_HDRS) +$(LIBKVM_C_OBJ): $(OUTPUT)/%.o: %.c $(GEN_SYSREG_DEFS) $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $< -o $@ -$(LIBKVM_S_OBJ): $(OUTPUT)/%.o: %.S $(GEN_HDRS) +$(LIBKVM_S_OBJ): $(OUTPUT)/%.o: %.S $(GEN_SYSREG_DEFS) $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $< -o $@ # Compile the string overrides as freestanding to prevent the compiler from @@ -388,10 +394,10 @@ $(LIBKVM_STRING_OBJ): $(OUTPUT)/%.o: %.c $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -ffreestanding $< -o $@ $(shell mkdir -p $(sort $(dir $(TEST_GEN_PROGS)))) -$(SPLIT_TEST_GEN_OBJ): $(GEN_HDRS) +$(SPLIT_TEST_GEN_OBJ): $(GEN_SYSREG_DEFS) $(TEST_GEN_PROGS): $(LIBKVM_OBJS) $(TEST_GEN_PROGS_EXTENDED): $(LIBKVM_OBJS) -$(TEST_GEN_OBJ): $(GEN_HDRS) +$(TEST_GEN_OBJ): $(GEN_SYSREG_DEFS) cscope: include_paths = $(LINUX_TOOL_INCLUDE) $(LINUX_HDR_PATH) include lib .. cscope: From bdd05706f146a6aa3d6e0847fc3b4c61bf40901e Mon Sep 17 00:00:00 2001 From: Shivansh Dhiman Date: Thu, 8 Oct 2026 06:26:43 +0000 Subject: [PATCH 0385/2102] KVM: SVM: Clear VMCB save area instead of entire VMCB on shutdown intercept The AMD APM previously stated that after an intercepted shutdown, the entire VMCB state is undefined. In practice, only the save area is undefined and most of the control area remains valid. Revision 3.45 of the APM now makes this explicit: "After an intercepted shutdown, the VMCB control area is valid (with the exception of offsets 60h, 61h, and 68h) and the VMCB state save area is undefined." KVM zeroes the entire VMCB before INITing the vCPU based on the old wording, discarding control area state that hardware preserves. Clear only the save area and the three undefined control area fields (int_ctl[15:0] and int_state) in line with the updated APM. Also explicitly clear EVENTINJ. Hardware clears it on #VMEXIT, but only if VMRUN fully entered the guest. Clearing it here should be unnecessary, since a shutdown can only happen if the guest actually ran. Do so anyway, as there is no reason to carry a stale event across the vCPU reset, and the cost is negligible. Signed-off-by: Shivansh Dhiman Link: https://patch.msgid.link/20261008062643.1183018-1-shivansh.dhiman@amd.com Signed-off-by: Sean Christopherson --- arch/x86/kvm/svm/svm.c | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c index e30ee80624b726..0eed355dc9b7d7 100644 --- a/arch/x86/kvm/svm/svm.c +++ b/arch/x86/kvm/svm/svm.c @@ -2213,18 +2213,31 @@ static int shutdown_interception(struct kvm_vcpu *vcpu) /* - * VMCB is undefined after a SHUTDOWN intercept. INIT the vCPU to put - * the VMCB in a known good state. Unfortuately, KVM doesn't have - * KVM_MP_STATE_SHUTDOWN and can't add it without potentially breaking - * userspace. At a platform view, INIT is acceptable behavior as - * there exist bare metal platforms that automatically INIT the CPU - * in response to shutdown. + * The VMCB save area is undefined after a SHUTDOWN intercept, as are + * control area offsets 60h, 61h, and 68h (int_ctl[15:0] and int_state). + * INIT the vCPU to put the VMCB in a known good state. Unfortunately, + * KVM doesn't have KVM_MP_STATE_SHUTDOWN and can't add it without + * potentially breaking userspace. At a platform view, INIT is + * acceptable behavior as there exist bare metal platforms that + * automatically INIT the CPU in response to shutdown. * * The VM save area for SEV-ES guests has already been encrypted so it * cannot be reinitialized, i.e. synthesizing INIT is futile. */ if (!is_sev_es_guest(vcpu)) { - clear_page(svm->vmcb); + struct vmcb_control_area *control = &svm->vmcb->control; + + memset(&svm->vmcb->save, 0, sizeof(svm->vmcb->save)); + control->int_ctl &= ~GENMASK(15, 0); + control->int_state = 0; + + /* + * EVENTINJ is cleared on #VMEXIT, but only if VMRUN fully + * entered the guest. Manually clear the fields even though it + * should be redundant, as there is no downside to doing so. + */ + control->event_inj = 0; + control->event_inj_err = 0; #ifdef CONFIG_KVM_SMM if (is_smm(vcpu)) kvm_smm_changed(vcpu, false); From d41766c450650ec11702923309dc59b6e0c8ab4e Mon Sep 17 00:00:00 2001 From: Yosry Ahmed Date: Tue, 13 Oct 2026 19:53:58 +0000 Subject: [PATCH 0386/2102] KVM: SVM: Update tracked pCPU on pCPU switch When a pCPU switch is detected in pre_svm_run(), update the tracked pCPU and mark all fields dirty in both VMCBs (if nested is initialized), in addition to resetting the ASID generation in both VMCBs. Commit bf260dc9e7b8 ("KVM: SVM: Trigger new ASID allocation in both VMCBs on pCPU switch") reset the ASID generation in both VMCBs on a pCPU switch, but only updated the tracked pCPU for the active VMCB to avoid unnecessarily dirtying the inactive VMCB. Leaving the inactive VMCB's tracked pCPU set to an old pCPU still allows an ASID allocated on one pCPU to be used on another: - vCPU runs with both vmcb01 and vmcb02 on pCPU A (both track cpu=A). - With vmcb01 active, vCPU migrates to pCPU B. vmcb01.cpu is updated to B, asid_generation is reset to 0 in both VMCBs, and a new ASID is allocated on pCPU B (setting vmcb01.asid_generation = gen_B). vmcb02.cpu remains A. - vCPU switches to vmcb02 and migrates back to pCPU A before pre_svm_run(). Because vmcb02.cpu is still A, no pCPU switch is detected, leaving vmcb01 with cpu=B and asid_generation=gen_B. Because vmcb02.asid_generation is 0, a new ASID (asid_A) is allocated on pCPU A. - vCPU switches back to vmcb01 and migrates to pCPU B. Neither a pCPU change nor a generation mismatch is detected for vmcb01, so VMRUN on pCPU B uses asid_A (allocated on pCPU A), which may collide with another vCPU on pCPU B. Because the per-VMCB cpu tracking is shared between ASID management and per-pCPU hardware VMCB clean bits, also mark both VMCBs dirty when updating their tracked pCPU so that the inactive VMCB does not run with stale clean bits when later entered on the new pCPU. Fixes: bf260dc9e7b8 ("KVM: SVM: Trigger new ASID allocation in both VMCBs on pCPU switch") Cc: stable@vger.kernel.org Reported-by: Stefan Teodorescu Signed-off-by: Yosry Ahmed Reviewed-by: Jim Mattson Link: https://patch.msgid.link/20261013195358.163375-1-yosry@kernel.org Signed-off-by: Sean Christopherson --- arch/x86/kvm/svm/svm.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c index 0eed355dc9b7d7..afb45431734793 100644 --- a/arch/x86/kvm/svm/svm.c +++ b/arch/x86/kvm/svm/svm.c @@ -3893,7 +3893,8 @@ static int pre_svm_run(struct kvm_vcpu *vcpu) /* * If the previous VMRUN of the VMCB occurred on a different physical - * cpu, then mark the VMCB dirty as hardware's clean bits are per pCPU. + * cpu, mark the VMCB dirty and reset the ASID generation, as hardware's + * clean bits and ASIDs are per pCPU. * * Reset the ASID generation in both VMCBs. This will lead to assigning * a new ASID now, and then again when switching to the other VMCB. @@ -3907,11 +3908,16 @@ static int pre_svm_run(struct kvm_vcpu *vcpu) * another vCPU/VM. */ if (unlikely(svm->current_vmcb->cpu != vcpu->cpu)) { - vmcb_mark_all_dirty(svm->vmcb); - svm->current_vmcb->cpu = vcpu->cpu; + vmcb_mark_all_dirty(svm->vmcb01.ptr); + svm->vmcb01.cpu = vcpu->cpu; svm->vmcb01.asid_generation = 0; - svm->nested.vmcb02.asid_generation = 0; - } + + if (svm->nested.initialized) { + svm->nested.vmcb02.cpu = vcpu->cpu; + svm->nested.vmcb02.asid_generation = 0; + vmcb_mark_all_dirty(svm->nested.vmcb02.ptr); + } + } if (is_sev_guest(vcpu)) return pre_sev_run(svm, vcpu->cpu); From 20cf5e54a1bc1b22d96ddfc7d4f8d8b8fc8193e4 Mon Sep 17 00:00:00 2001 From: Sean Christopherson Date: Wed, 28 Oct 2026 12:02:53 -0700 Subject: [PATCH 0387/2102] KVM: s390: Drop unused and unreachable kvm_arch_vcpu_should_kick() Drop s390's kvm_arch_vcpu_should_kick() stub as the one and only call site is wrapped with "#ifndef CONFIG_S390". No functional change intended. Link: https://patch.msgid.link/20261028190259.1819571-2-seanjc@google.com Signed-off-by: Sean Christopherson --- arch/s390/kvm/s390/s390.c | 7 ------- 1 file changed, 7 deletions(-) diff --git a/arch/s390/kvm/s390/s390.c b/arch/s390/kvm/s390/s390.c index 18fb200f854a84..9900a1a1c1487f 100644 --- a/arch/s390/kvm/s390/s390.c +++ b/arch/s390/kvm/s390/s390.c @@ -3922,13 +3922,6 @@ bool kvm_arch_no_poll(struct kvm_vcpu *vcpu) return false; } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - /* kvm common code refers to this, but never calls it */ - BUG(); - return 0; -} - static int kvm_arch_vcpu_ioctl_get_one_reg(struct kvm_vcpu *vcpu, struct kvm_one_reg *reg) { From 0ee75a9dee9cc140a46a2be5ca500bebf4b120da Mon Sep 17 00:00:00 2001 From: Sean Christopherson Date: Wed, 28 Oct 2026 12:02:54 -0700 Subject: [PATCH 0388/2102] KVM: Add a @force param to __kvm_vcpu_kick() for PPC backwards compatibility Plumb in a @force param to __kvm_vcpu_kick() to force an IPI without checking kvm_arch_vcpu_should_kick(). The param will be used to drop kvm_arch_vcpu_should_kick() in favor of kvm_request_needs_ipi() without regressing PPC, which for unknown reasons unconditionally blasts an IPI in a variety of kvm_vcpu_kick() flows. No functional change intended (nothing yet passes in @force=true). Link: https://patch.msgid.link/20261028190259.1819571-3-seanjc@google.com Signed-off-by: Sean Christopherson --- include/linux/kvm_host.h | 6 +++--- virt/kvm/kvm_main.c | 10 +++++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h index be27b4e8f12dfa..e72138ec500182 100644 --- a/include/linux/kvm_host.h +++ b/include/linux/kvm_host.h @@ -1591,11 +1591,11 @@ void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu); bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu); #ifndef CONFIG_S390 -void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait); +void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait, bool force); static inline void kvm_vcpu_kick(struct kvm_vcpu *vcpu) { - __kvm_vcpu_kick(vcpu, false); + __kvm_vcpu_kick(vcpu, false, false); } #endif @@ -2336,7 +2336,7 @@ static __always_inline void kvm_make_request(int req, struct kvm_vcpu *vcpu) static inline void kvm_make_request_and_kick(int req, struct kvm_vcpu *vcpu) { kvm_make_request(req, vcpu); - __kvm_vcpu_kick(vcpu, req & KVM_REQUEST_WAIT); + __kvm_vcpu_kick(vcpu, req & KVM_REQUEST_WAIT, false); } #endif diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c index 218456372b118e..f8aff81f6a6ae3 100644 --- a/virt/kvm/kvm_main.c +++ b/virt/kvm/kvm_main.c @@ -3908,7 +3908,7 @@ EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_wake_up); /* * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode. */ -void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait) +void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait, bool force) { int me, cpu; @@ -3933,9 +3933,13 @@ void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait) * after kvm_arch_vcpu_should_kick(), which could result in sending an * IPI to the previous pCPU. But, that's ok because the purpose of the * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the - * vCPU also requires it to leave IN_GUEST_MODE. + * vCPU also requires it to leave IN_GUEST_MODE + * + * Note #2, do NOT check if an IPI is needed if @force is true, as the + * check also modifies vcpu->mode and KVM PPC needs to avoid that side + * effect for unknown historical reasons. */ - if (kvm_arch_vcpu_should_kick(vcpu)) { + if (force || kvm_arch_vcpu_should_kick(vcpu)) { cpu = READ_ONCE(vcpu->cpu); if (cpu != me && (unsigned int)cpu < nr_cpu_ids && cpu_online(cpu)) { /* From 2530231b023e25349e1fc2962be884caa621b699 Mon Sep 17 00:00:00 2001 From: Sean Christopherson Date: Wed, 28 Oct 2026 12:02:55 -0700 Subject: [PATCH 0389/2102] KVM: PPC: Explicitly force IPIs when directly kicking vCPUs Explicitly force an IPI when invoking kvm_vcpu_kick() directly instead of relying on kvm_arch_vcpu_should_kick() to unconditionally return 1/true. This will allow dropping kvm_arch_vcpu_should_kick() in favor of kvm_request_needs_ipi(). No functional change intended (1 || 1 == true). Reviewed-by: Gautam Menghani # PPC Link: https://patch.msgid.link/20261028190259.1819571-4-seanjc@google.com Signed-off-by: Sean Christopherson --- arch/powerpc/include/asm/kvm_ppc.h | 13 ++++++++++++- arch/powerpc/kvm/book3s.c | 4 ++-- arch/powerpc/kvm/book3s_pr.c | 2 +- arch/powerpc/kvm/booke.c | 6 +++--- arch/powerpc/kvm/e500_emulate.c | 2 +- arch/powerpc/kvm/powerpc.c | 2 +- 6 files changed, 20 insertions(+), 9 deletions(-) diff --git a/arch/powerpc/include/asm/kvm_ppc.h b/arch/powerpc/include/asm/kvm_ppc.h index 169ea6a7fbad44..bbe7378ad0efab 100644 --- a/arch/powerpc/include/asm/kvm_ppc.h +++ b/arch/powerpc/include/asm/kvm_ppc.h @@ -30,6 +30,17 @@ #endif #include +/* + * TODO: For unknown reasons, KVM PPC has historically ignored vcpu->mode when + * determining if kicking a vCPU needs an IPI. Either document why that + * behavior is necessary, or drop this helper and the @force param from + * __kvm_vcpu_kick(). + */ +static inline void kvmppc_vcpu_kick(struct kvm_vcpu *vcpu) +{ + __kvm_vcpu_kick(vcpu, false, true); +} + /* * KVMPPC_INST_SW_BREAKPOINT is debug Instruction * for supporting software breakpoint. @@ -598,7 +609,7 @@ static inline void kvmppc_clear_host_ipi(int cpu) static inline void kvmppc_fast_vcpu_kick(struct kvm_vcpu *vcpu) { - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); } static inline bool kvm_hv_mode_active(void) { return false; } diff --git a/arch/powerpc/kvm/book3s.c b/arch/powerpc/kvm/book3s.c index 2efbe05caed760..dce53c5a386801 100644 --- a/arch/powerpc/kvm/book3s.c +++ b/arch/powerpc/kvm/book3s.c @@ -260,7 +260,7 @@ void kvmppc_core_queue_external(struct kvm_vcpu *vcpu, * external interrupts for the guest just before entering * the guest. That is OK even if userspace did do a * KVM_INTERRUPT_SET on a pseries guest vcpu, because the - * caller (kvm_vcpu_ioctl_interrupt) does a kvm_vcpu_kick() + * caller (kvm_vcpu_ioctl_interrupt) does a kvmppc_vcpu_kick() * which ends up doing a smp_send_reschedule(), which will * pull the guest all the way out to the host, meaning that * we will call kvmppc_core_prepare_to_enter() before entering @@ -827,7 +827,7 @@ int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu, void kvmppc_decrementer_func(struct kvm_vcpu *vcpu) { kvmppc_core_queue_dec(vcpu); - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); } int kvmppc_core_vcpu_create(struct kvm_vcpu *vcpu) diff --git a/arch/powerpc/kvm/book3s_pr.c b/arch/powerpc/kvm/book3s_pr.c index ecfb88bf6464d2..1894968f2c25c4 100644 --- a/arch/powerpc/kvm/book3s_pr.c +++ b/arch/powerpc/kvm/book3s_pr.c @@ -2066,7 +2066,7 @@ static struct kvmppc_ops kvm_ops_pr = { .emulate_op = kvmppc_core_emulate_op_pr, .emulate_mtspr = kvmppc_core_emulate_mtspr_pr, .emulate_mfspr = kvmppc_core_emulate_mfspr_pr, - .fast_vcpu_kick = kvm_vcpu_kick, + .fast_vcpu_kick = kvmppc_vcpu_kick, .arch_vm_ioctl = kvm_arch_vm_ioctl_pr, #ifdef CONFIG_PPC_BOOK3S_64 .hcall_implemented = kvmppc_hcall_impl_pr, diff --git a/arch/powerpc/kvm/booke.c b/arch/powerpc/kvm/booke.c index 13ad4cf5fa71f8..fd7f24a68b31a1 100644 --- a/arch/powerpc/kvm/booke.c +++ b/arch/powerpc/kvm/booke.c @@ -650,7 +650,7 @@ static void kvmppc_watchdog_func(struct timer_list *t) if (new_tsr & TSR_WIS) { smp_wmb(); kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu); - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); } /* @@ -661,7 +661,7 @@ static void kvmppc_watchdog_func(struct timer_list *t) vcpu->arch.watchdog_enabled) { smp_wmb(); kvm_make_request(KVM_REQ_WATCHDOG, vcpu); - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); } /* @@ -1872,7 +1872,7 @@ void kvmppc_set_tsr_bits(struct kvm_vcpu *vcpu, u32 tsr_bits) set_bits(tsr_bits, &vcpu->arch.tsr); smp_wmb(); kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu); - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); } void kvmppc_clr_tsr_bits(struct kvm_vcpu *vcpu, u32 tsr_bits) diff --git a/arch/powerpc/kvm/e500_emulate.c b/arch/powerpc/kvm/e500_emulate.c index 051102d50c314a..10cd6b4ab45627 100644 --- a/arch/powerpc/kvm/e500_emulate.c +++ b/arch/powerpc/kvm/e500_emulate.c @@ -75,7 +75,7 @@ static int kvmppc_e500_emul_msgsnd(struct kvm_vcpu *vcpu, int rb) int cpir = cvcpu->arch.shared->pir; if ((param & PPC_DBELL_MSG_BRDCAST) || (cpir == pir)) { set_bit(prio, &cvcpu->arch.pending_exceptions); - kvm_vcpu_kick(cvcpu); + kvmppc_vcpu_kick(cvcpu); } } diff --git a/arch/powerpc/kvm/powerpc.c b/arch/powerpc/kvm/powerpc.c index 9e9d0865c2f624..45eea24a5c92fd 100644 --- a/arch/powerpc/kvm/powerpc.c +++ b/arch/powerpc/kvm/powerpc.c @@ -1914,7 +1914,7 @@ int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu, struct kvm_interrupt *irq) kvmppc_core_queue_external(vcpu, irq); - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); return 0; } From a8dabc687ddb1b686bdf2590aa32c666b2636b6d Mon Sep 17 00:00:00 2001 From: Sean Christopherson Date: Wed, 28 Oct 2026 12:02:56 -0700 Subject: [PATCH 0390/2102] KVM: MIPS: Rework kvm_arch_vcpu_should_kick() to use standard implementation Rework MIPS' kvm_arch_vcpu_should_kick() to use the "standard" arch implementation so that the arch hook can be dropped (MIPS is the only arch other than PPC that implements a non-standard hook, and PPC uses the recently added @force param when invoking __kvm_vcpu_kick() instead of relying on kvm_arch_vcpu_should_kick()). Convert MIPS to the standard implementation even though the code should be unreachable (neither kvm_vcpu_kick() nor kvm_make_request_and_kick() are used by MIPS or common KVM), so that there is a bisection point if the code is somehow reachable. No functional change intended (because the code is currently unreachable). Link: https://patch.msgid.link/20261028190259.1819571-5-seanjc@google.com Signed-off-by: Sean Christopherson --- arch/mips/kvm/mips.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/mips/kvm/mips.c b/arch/mips/kvm/mips.c index a53abbba43ea33..c37e212bc0a35f 100644 --- a/arch/mips/kvm/mips.c +++ b/arch/mips/kvm/mips.c @@ -122,7 +122,7 @@ bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu) int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) { - return 1; + return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; } int kvm_arch_enable_virtualization_cpu(void) From 7e52636d9c37eee473d4c6716799bc64274d3eab Mon Sep 17 00:00:00 2001 From: Sean Christopherson Date: Wed, 28 Oct 2026 12:02:57 -0700 Subject: [PATCH 0391/2102] KVM: Move kvm_arch_vcpu_should_kick() to common code as kvm_vcpu_should_kick() Dedup kvm_arch_vcpu_should_kick() now that all architectures except for PPC have identical implementations. PPC's implementation is unreachable as PPC always invokes __kvm_vcpu_kick() with @force=true. No functional change intended. Link: https://patch.msgid.link/20261028190259.1819571-6-seanjc@google.com Signed-off-by: Sean Christopherson --- arch/arm64/kvm/arm.c | 5 ----- arch/loongarch/kvm/vcpu.c | 5 ----- arch/mips/kvm/mips.c | 5 ----- arch/powerpc/kvm/powerpc.c | 5 ----- arch/riscv/kvm/vcpu.c | 5 ----- arch/x86/kvm/x86.c | 5 ----- include/linux/kvm_host.h | 1 - virt/kvm/kvm_main.c | 11 ++++++++--- 8 files changed, 8 insertions(+), 34 deletions(-) diff --git a/arch/arm64/kvm/arm.c b/arch/arm64/kvm/arm.c index 157bf4b8120201..ff14d592a4c8f7 100644 --- a/arch/arm64/kvm/arm.c +++ b/arch/arm64/kvm/arm.c @@ -128,11 +128,6 @@ bool is_kvm_arm_initialised(void) return kvm_arm_initialised; } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; -} - int kvm_vm_ioctl_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) { diff --git a/arch/loongarch/kvm/vcpu.c b/arch/loongarch/kvm/vcpu.c index 4026b9bf9f2d3e..76afd386abd2dd 100644 --- a/arch/loongarch/kvm/vcpu.c +++ b/arch/loongarch/kvm/vcpu.c @@ -379,11 +379,6 @@ int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu) vcpu->arch.mp_state.mp_state == KVM_MP_STATE_RUNNABLE; } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; -} - bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu) { unsigned long val; diff --git a/arch/mips/kvm/mips.c b/arch/mips/kvm/mips.c index c37e212bc0a35f..273dd932d119d2 100644 --- a/arch/mips/kvm/mips.c +++ b/arch/mips/kvm/mips.c @@ -120,11 +120,6 @@ bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu) return false; } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; -} - int kvm_arch_enable_virtualization_cpu(void) { return kvm_mips_callbacks->enable_virtualization_cpu(); diff --git a/arch/powerpc/kvm/powerpc.c b/arch/powerpc/kvm/powerpc.c index 45eea24a5c92fd..820abe64e04a4b 100644 --- a/arch/powerpc/kvm/powerpc.c +++ b/arch/powerpc/kvm/powerpc.c @@ -62,11 +62,6 @@ bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu) return false; } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return 1; -} - /* * Common checks before entering the guest world. Call with interrupts * enabled. diff --git a/arch/riscv/kvm/vcpu.c b/arch/riscv/kvm/vcpu.c index dd786f758eb76a..3981ba39ffc21b 100644 --- a/arch/riscv/kvm/vcpu.c +++ b/arch/riscv/kvm/vcpu.c @@ -239,11 +239,6 @@ int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu) !kvm_riscv_vcpu_stopped(vcpu) && !vcpu->arch.pause); } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; -} - bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu) { return (vcpu->arch.guest_context.sstatus & SR_SPP) ? true : false; diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 26e7beaff8a03c..802dd6fed8d436 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -10476,11 +10476,6 @@ unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu) return kvm_rip_read(vcpu); } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; -} - static inline u32 kvm_async_pf_hash_fn(gfn_t gfn) { BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU)); diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h index e72138ec500182..2226036331b0d2 100644 --- a/include/linux/kvm_host.h +++ b/include/linux/kvm_host.h @@ -1715,7 +1715,6 @@ void kvm_arch_disable_virtualization_cpu(void); bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu); int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu); bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu); -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu); bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu); bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu); bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu); diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c index f8aff81f6a6ae3..fe8bbc892c7434 100644 --- a/virt/kvm/kvm_main.c +++ b/virt/kvm/kvm_main.c @@ -191,7 +191,7 @@ void vcpu_put(struct kvm_vcpu *vcpu) } EXPORT_SYMBOL_FOR_KVM_INTERNAL(vcpu_put); -/* TODO: merge with kvm_arch_vcpu_should_kick */ +/* TODO: merge with kvm_vcpu_should_kick */ static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req) { int mode = kvm_vcpu_exiting_guest_mode(vcpu); @@ -209,6 +209,11 @@ static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req) return mode == IN_GUEST_MODE; } +static int kvm_vcpu_should_kick(struct kvm_vcpu *vcpu) +{ + return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; +} + static void ack_kick(void *_completed) { } @@ -3930,7 +3935,7 @@ void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait, bool force) /* * Note, the vCPU could get migrated to a different pCPU at any point - * after kvm_arch_vcpu_should_kick(), which could result in sending an + * after kvm_vcpu_should_kick(), which could result in sending an * IPI to the previous pCPU. But, that's ok because the purpose of the * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the * vCPU also requires it to leave IN_GUEST_MODE @@ -3939,7 +3944,7 @@ void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait, bool force) * check also modifies vcpu->mode and KVM PPC needs to avoid that side * effect for unknown historical reasons. */ - if (force || kvm_arch_vcpu_should_kick(vcpu)) { + if (force || kvm_vcpu_should_kick(vcpu)) { cpu = READ_ONCE(vcpu->cpu); if (cpu != me && (unsigned int)cpu < nr_cpu_ids && cpu_online(cpu)) { /* From 5c430e211f4dafdd7ebcf83d7dcc69d5711b1132 Mon Sep 17 00:00:00 2001 From: Sean Christopherson Date: Wed, 28 Oct 2026 12:02:58 -0700 Subject: [PATCH 0392/2102] KVM: Plumb the full request into __kvm_vcpu_kick() Plumb the full request instead of just a "wait" boolean into __kvm_vcpu_kick() so that it can use kvm_request_needs_ipi() instead of the flawed kvm_vcpu_should_kick(). No functional change intended. Link: https://patch.msgid.link/20261028190259.1819571-7-seanjc@google.com Signed-off-by: Sean Christopherson --- arch/powerpc/include/asm/kvm_ppc.h | 2 +- include/linux/kvm_host.h | 6 +++--- virt/kvm/kvm_main.c | 17 +++++++++-------- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/arch/powerpc/include/asm/kvm_ppc.h b/arch/powerpc/include/asm/kvm_ppc.h index bbe7378ad0efab..011dc422af7846 100644 --- a/arch/powerpc/include/asm/kvm_ppc.h +++ b/arch/powerpc/include/asm/kvm_ppc.h @@ -38,7 +38,7 @@ */ static inline void kvmppc_vcpu_kick(struct kvm_vcpu *vcpu) { - __kvm_vcpu_kick(vcpu, false, true); + __kvm_vcpu_kick(vcpu, 0, true); } /* diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h index 2226036331b0d2..fe300a22ab0f0a 100644 --- a/include/linux/kvm_host.h +++ b/include/linux/kvm_host.h @@ -1591,11 +1591,11 @@ void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu); bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu); #ifndef CONFIG_S390 -void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait, bool force); +void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, int request, bool force); static inline void kvm_vcpu_kick(struct kvm_vcpu *vcpu) { - __kvm_vcpu_kick(vcpu, false, false); + __kvm_vcpu_kick(vcpu, 0, false); } #endif @@ -2335,7 +2335,7 @@ static __always_inline void kvm_make_request(int req, struct kvm_vcpu *vcpu) static inline void kvm_make_request_and_kick(int req, struct kvm_vcpu *vcpu) { kvm_make_request(req, vcpu); - __kvm_vcpu_kick(vcpu, req & KVM_REQUEST_WAIT, false); + __kvm_vcpu_kick(vcpu, req, false); } #endif diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c index fe8bbc892c7434..3032f5b4785718 100644 --- a/virt/kvm/kvm_main.c +++ b/virt/kvm/kvm_main.c @@ -3913,7 +3913,7 @@ EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_wake_up); /* * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode. */ -void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait, bool force) +void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, int req, bool force) { int me, cpu; @@ -3948,14 +3948,15 @@ void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait, bool force) cpu = READ_ONCE(vcpu->cpu); if (cpu != me && (unsigned int)cpu < nr_cpu_ids && cpu_online(cpu)) { /* - * Use a reschedule IPI to kick the vCPU if the caller - * doesn't need to wait for a response, as KVM allows - * kicking vCPUs while IRQs are disabled, but using the - * SMP function call framework with IRQs disabled can - * deadlock due to taking cross-CPU locks. + * Use a reschedule IPI to kick the vCPU if the request + * doesn't need to wait for a response (or there is no + * request), as KVM allows kicking vCPUs while IRQs are + * disabled, but using the SMP function call framework + * with IRQs disabled can deadlock due to taking cross- + * CPU locks. */ - if (wait) - smp_call_function_single(cpu, ack_kick, NULL, wait); + if (req & KVM_REQUEST_WAIT) + smp_call_function_single(cpu, ack_kick, NULL, true); else smp_send_reschedule(cpu); } From fd3dd4d9c18638fdbeed2985681e90c1585e0ddd Mon Sep 17 00:00:00 2001 From: Sean Christopherson Date: Wed, 28 Oct 2026 12:02:59 -0700 Subject: [PATCH 0393/2102] KVM: Drop kvm_vcpu_should_kick() and use kvm_request_needs_ipi() Drop kvm_vcpu_should_kick() in favor of kvm_request_needs_ipi() to fix a bug where KVM will fail to wait for a vCPU to exit guest mode if the vCPU was already marked as EXITING_GUEST_MODE by a concurrent non-waiting kick. Because kvm_vcpu_should_kick() (was kvm_arch_vcpu_should_kick()) only waits (and sends an IPI to do so) if the target vCPU is fully IN_GUEST_MODE, the sending task will proceed even though it hasn't actually guaranteed the vCPU as fully exited the guest. The flaw is most problematic for SNP VMSA invalidation with in-place gmem conversion, as KVM invokes kvm_gmem_invalidate_start() => rmp_make_shared() (via kvm_gmem_make_shared() in quick succession when in-place conversion is enabled. I.e. if the target has been marked as EXITING_GUEST_MODE but has not yet received the other kicker's IPI, then updating the RMP will fail as the VMSA is still in-use and subsequent accesses to the page will encounter unexpected RMP #PFs. Note, the bug exists and affects VMSA invalidation even without in-place conversion, but is significantly more difficult to hit as PUNCH_HOLE and .release() have to wade through a lot more code and several locks to get from invalidation to kvm_gmem_free_folio(). Note #2, currently only x86 uses kvm_make_request_and_kick(), i.e. this is a glorified nop for all other architectures as the KVM_REQUEST_WAIT path is never taken. Fixes: 309d28576f0a ("KVM: SVM: Fix SNP AP destroy race with VMRUN") Fixes: d1a3c2162334 ("KVM: SEV: Forcefully invalidate SNP VMSA if its backing gmem page is zapped") Reported-by: Stefan Teodorescu Link: https://patch.msgid.link/20261028190259.1819571-8-seanjc@google.com Signed-off-by: Sean Christopherson --- virt/kvm/kvm_main.c | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c index 3032f5b4785718..83e727bf6452cd 100644 --- a/virt/kvm/kvm_main.c +++ b/virt/kvm/kvm_main.c @@ -191,7 +191,6 @@ void vcpu_put(struct kvm_vcpu *vcpu) } EXPORT_SYMBOL_FOR_KVM_INTERNAL(vcpu_put); -/* TODO: merge with kvm_vcpu_should_kick */ static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req) { int mode = kvm_vcpu_exiting_guest_mode(vcpu); @@ -209,11 +208,6 @@ static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req) return mode == IN_GUEST_MODE; } -static int kvm_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; -} - static void ack_kick(void *_completed) { } @@ -3935,7 +3929,7 @@ void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, int req, bool force) /* * Note, the vCPU could get migrated to a different pCPU at any point - * after kvm_vcpu_should_kick(), which could result in sending an + * after kvm_request_needs_ipi(), which could result in sending an * IPI to the previous pCPU. But, that's ok because the purpose of the * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the * vCPU also requires it to leave IN_GUEST_MODE @@ -3944,7 +3938,7 @@ void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, int req, bool force) * check also modifies vcpu->mode and KVM PPC needs to avoid that side * effect for unknown historical reasons. */ - if (force || kvm_vcpu_should_kick(vcpu)) { + if (force || kvm_request_needs_ipi(vcpu, req)) { cpu = READ_ONCE(vcpu->cpu); if (cpu != me && (unsigned int)cpu < nr_cpu_ids && cpu_online(cpu)) { /* From 018fe0700c569b50465b27d68deee7e9157e8e5f Mon Sep 17 00:00:00 2001 From: Guobin Zhang Date: Tue, 20 Oct 2026 19:24:25 +0800 Subject: [PATCH 0394/2102] riscv: signal: protect regs->status RMW from concurrent preemption __fstate_clean() performs a non-atomic read-modify-write (RMW) on task_pt_regs(current)->status to clear the FS bits. This RMW is unprotected - it runs with preemption enabled and IRQs on during signal delivery (setup_rt_frame -> fstate_save) and sigreturn (restore_fp_state -> fstate_restore). If a reschedule IPI or timer interrupt triggers preemption between the load and store of this RMW, __switch_to_vector() calls riscv_v_vstate_set_restore() which modifies the VS bits of the same regs->status. When the preempted task resumes, it stores back the stale value captured before preemption, overwriting the VS update and restoring VS=DIRTY while TIF_RISCV_V_DEFER_RESTORE remains set - a combination that should never occur and leads to vector state corruption. The race window: __fstate_clean (signal path) set_restore (schedule path) ----------------------------- ----------------------------- ld a0, regs->status // VS=DIRTY, FS=DIRTY <- preempted (reschedule IPI) regs->status VS = INITIAL set TIF_RISCV_V_DEFER_RESTORE <- resumed andi a0, ~FS ori a0, FS_CLEAN // stale a0 still has VS=DIRTY sd a0, regs->status // overwrites VS=INITIAL with VS=DIRTY -> result: VS=DIRTY + DEFER -> ANOMALY Fix by adding preempt_disable/enable in fstate_save() and fstate_restore(), which covers the RMW in __fstate_clean(), and around the RMW in fstate_off(). Add fstate_{save,restore}_preempt_off() for code that already runs with preemption disabled (the scheduler and kernel_mode_fpu). riscv_v_vstate_set_restore() has the identical hazard: it is called from __restore_v_state() (sigreturn path) with preemption enabled, and it can race the same way against the scheduler's own call to riscv_v_vstate_set_restore() for the same task in __switch_to_vector(). Wrap that call site with preempt_disable/enable as well. Add WARN_ON_ONCE(preemptible()) to riscv_v_vstate_restore() to catch any future unprotected callers at development time. Suggested-by: Andy Chiu Signed-off-by: Guobin Zhang Reviewed-by: Andy Chiu Link: https://patch.msgid.link/20261020-vector_fpu_regs_status_rmw_fix-v2-1-474a59155e96@intel.com Cc: stable@vger.kernel.org Signed-off-by: Paul Walmsley --- arch/riscv/include/asm/switch_to.h | 30 +++++++++++++++++++++++------ arch/riscv/include/asm/vector.h | 2 ++ arch/riscv/kernel/kernel_mode_fpu.c | 4 ++-- arch/riscv/kernel/signal.c | 2 ++ 4 files changed, 30 insertions(+), 8 deletions(-) diff --git a/arch/riscv/include/asm/switch_to.h b/arch/riscv/include/asm/switch_to.h index 123c89b694e876..970f89935f0ee0 100644 --- a/arch/riscv/include/asm/switch_to.h +++ b/arch/riscv/include/asm/switch_to.h @@ -28,11 +28,13 @@ static inline void __fstate_clean(struct pt_regs *regs) static inline void fstate_off(struct task_struct *task, struct pt_regs *regs) { + preempt_disable(); regs->status = (regs->status & ~SR_FS) | SR_FS_OFF; + preempt_enable(); } -static inline void fstate_save(struct task_struct *task, - struct pt_regs *regs) +static inline void fstate_save_preempt_off(struct task_struct *task, + struct pt_regs *regs) { if ((regs->status & SR_FS) == SR_FS_DIRTY) { __fstate_save(task); @@ -40,8 +42,8 @@ static inline void fstate_save(struct task_struct *task, } } -static inline void fstate_restore(struct task_struct *task, - struct pt_regs *regs) +static inline void fstate_restore_preempt_off(struct task_struct *task, + struct pt_regs *regs) { if ((regs->status & SR_FS) != SR_FS_OFF) { __fstate_restore(task); @@ -49,14 +51,30 @@ static inline void fstate_restore(struct task_struct *task, } } +static inline void fstate_save(struct task_struct *task, + struct pt_regs *regs) +{ + preempt_disable(); + fstate_save_preempt_off(task, regs); + preempt_enable(); +} + +static inline void fstate_restore(struct task_struct *task, + struct pt_regs *regs) +{ + preempt_disable(); + fstate_restore_preempt_off(task, regs); + preempt_enable(); +} + static inline void __switch_to_fpu(struct task_struct *prev, struct task_struct *next) { struct pt_regs *regs; regs = task_pt_regs(prev); - fstate_save(prev, regs); - fstate_restore(next, task_pt_regs(next)); + fstate_save_preempt_off(prev, regs); + fstate_restore_preempt_off(next, task_pt_regs(next)); } static __always_inline bool has_fpu(void) diff --git a/arch/riscv/include/asm/vector.h b/arch/riscv/include/asm/vector.h index cd09f32e1ea3f1..3381a535abb4dc 100644 --- a/arch/riscv/include/asm/vector.h +++ b/arch/riscv/include/asm/vector.h @@ -320,6 +320,8 @@ static inline void riscv_v_vstate_save(struct __riscv_v_ext_state *vstate, static inline void riscv_v_vstate_restore(struct __riscv_v_ext_state *vstate, struct pt_regs *regs) { + WARN_ON_ONCE(preemptible()); + if (riscv_v_vstate_query(regs)) { __riscv_v_vstate_restore(vstate, vstate->datap); __riscv_v_vstate_clean(regs); diff --git a/arch/riscv/kernel/kernel_mode_fpu.c b/arch/riscv/kernel/kernel_mode_fpu.c index 0ac8348876c499..03d847fbfcf68e 100644 --- a/arch/riscv/kernel/kernel_mode_fpu.c +++ b/arch/riscv/kernel/kernel_mode_fpu.c @@ -14,7 +14,7 @@ void kernel_fpu_begin(void) { preempt_disable(); - fstate_save(current, task_pt_regs(current)); + fstate_save_preempt_off(current, task_pt_regs(current)); csr_set(CSR_SSTATUS, SR_FS); } EXPORT_SYMBOL_GPL(kernel_fpu_begin); @@ -22,7 +22,7 @@ EXPORT_SYMBOL_GPL(kernel_fpu_begin); void kernel_fpu_end(void) { csr_clear(CSR_SSTATUS, SR_FS); - fstate_restore(current, task_pt_regs(current)); + fstate_restore_preempt_off(current, task_pt_regs(current)); preempt_enable(); } EXPORT_SYMBOL_GPL(kernel_fpu_end); diff --git a/arch/riscv/kernel/signal.c b/arch/riscv/kernel/signal.c index 59784dc117e454..6f6f3315bc0952 100644 --- a/arch/riscv/kernel/signal.c +++ b/arch/riscv/kernel/signal.c @@ -123,7 +123,9 @@ static long __restore_v_state(struct pt_regs *regs, void __user *sc_vec) * to avoid getting the vstate incorrectly clobbered by the * discarded vector state. */ + preempt_disable(); riscv_v_vstate_set_restore(current, regs); + preempt_enable(); /* Copy everything of __sc_riscv_v_state except datap. */ err = __copy_from_user(¤t->thread.vstate, &state->v_state, From e212c463eee96b2568d8c85ca4ee63049dbb18f2 Mon Sep 17 00:00:00 2001 From: Kuniyuki Iwashima Date: Wed, 28 Oct 2026 19:39:19 +0000 Subject: [PATCH 0395/2102] mm/kasan: detect double-free involving kfree_rcu_sheaf() Patch series "mm/kasan: Detect double-free involving kfree_rcu_sheaf().", v3. Recently, syzbot has reported several weird use-after-free splats. What they have in common is that "Freed by" points to rcu_free_sheaf(), whereas the object shown in "Call Trace:" and "Allocated by" is never supposed to be freed via kfree_rcu(). This means the object was a victim of a double-free somewhere else and was silently poisoned by rcu_free_sheaf() after being reallocated. This happens because kfree_rcu_sheaf() queues an object into the RCU sheaf without invoking any KASAN hooks. This series enables KASAN to detect double-free involving kfree_rcu_sheaf() immediately and adds KUnit tests for it. This patch (of 2): syzbot reported a weird use-after-free splat. [0] In the report, an object in the kmalloc-64 cache was freed via rcu_free_sheaf() while it was still in use, even though the object should always be freed with kfree() (in xfrm_hash_free()), implying that the object was a victim of a double-free involving kfree_rcu() somewhere else. When kvfree_call_rcu() frees an object via kfree_rcu_sheaf() and queues it into pcs->rcu_free, debug facilities are skipped, e.g., kasan_slab_pre_free(), kasan_record_aux_stack(), debug_rcu_head_queue(), etc. As a result, KASAN cannot detect the double-free at the call site. If the object is still in the KASAN quarantine when the sheaf is flushed, KASAN can detect the double-free in rcu_free_sheaf(), but with no trace of the suspect. Worse yet, once the object is evicted from the quarantine and reallocated before the sheaf is flushed, rcu_free_sheaf() silently poisons the live object, resulting in a false-positive use-after-free report on the new user. If __kfree_rcu_sheaf() simply calls kasan_slab_pre_free(), we can detect the second kfree_rcu(), but only while the object is poisoned in the KASAN quarantine after the first free: kfree() --(poisoned)--------------------> kfree_rcu() kfree_rcu() -> rcu_free_sheaf() -(poisoned)-> kfree_rcu() An object queued in pcs->rcu_free remains unpoisoned until the sheaf becomes full and rcu_free_sheaf() runs after the RCU grace period, so a subsequent kfree_rcu() or kfree() before rcu_free_sheaf() cannot be detected by shadow bytes alone: kfree_rcu() -(unpoisoned)-> kfree_rcu() -> rcu_free_sheaf() (too late!) kfree_rcu() -(unpoisoned)-> kfree() -> rcu_free_sheaf() (too late!) These cases can be detected if we call debug_rcu_head_queue() before kfree_rcu_sheaf(), but ODEBUG splat only shows the second free. To detect these cases with KASAN, we just need a 1-bit flag to indicate the state, which can reuse an unused bit in struct kasan_track.pid. (PID_MAX_LIMIT is 1<<22) The bit is marked along with recording the stack trace when deferring slab frees in kfree_rcu_sheaf() and checked in check_slab_allocation() so that any double-free pattern above can be detected immediately. Link: https://lore.kernel.org/20261028194014.3671161-1-kuniyu@google.com Link: https://lore.kernel.org/20261028194014.3671161-2-kuniyu@google.com Link: https://lore.kernel.org/all/6ac959ee.70ed5d86.2ac85.007d.GAE@google.com/ #[0] Fixes: ec66e0d59952 ("slab: add sheaf support for batching kfree_rcu() operations") Signed-off-by: Kuniyuki Iwashima Signed-off-by: Andrew Morton Acked-by: Vlastimil Babka (SUSE) Tested-by: Alexander Potapenko Reviewed-by: Alexander Potapenko Reviewed-by: Andrey Ryabinin Cc: Harry Yoo Cc: Andrey Konovalov Cc: Dmitry Vyukov Cc: Vincenzo Frascino Cc: Hao Li Cc: Christoph Lameter Cc: David Rientjes Cc: Roman Gushchin Cc: --- include/linux/kasan.h | 15 +++++++++++---- mm/kasan/common.c | 13 ++++++++----- mm/kasan/generic.c | 17 ++++++++++++++++- mm/kasan/kasan.h | 34 +++++++++++++++++++++++++++++++++- mm/slub.c | 13 ++++++++++--- 5 files changed, 78 insertions(+), 14 deletions(-) diff --git a/include/linux/kasan.h b/include/linux/kasan.h index bf233bde68c7eb..c1ac7971601e05 100644 --- a/include/linux/kasan.h +++ b/include/linux/kasan.h @@ -180,10 +180,12 @@ static __always_inline void * __must_check kasan_init_slab_obj( } bool __kasan_slab_pre_free(struct kmem_cache *s, void *object, - unsigned long ip); + unsigned long ip, bool after_rcu_delay); /** * kasan_slab_pre_free - Check whether freeing a slab object is safe. + * @s: Cache the object belongs to. * @object: Object to be freed. + * @after_rcu_delay: Whether the free follows an RCU grace period. * * This function checks whether freeing the given object is safe. It may * check for double-free and invalid-free bugs and report them. @@ -193,10 +195,12 @@ bool __kasan_slab_pre_free(struct kmem_cache *s, void *object, * @Return true if freeing the object is unsafe; false otherwise. */ static __always_inline bool kasan_slab_pre_free(struct kmem_cache *s, - void *object) + void *object, + bool after_rcu_delay) { if (kasan_enabled()) - return __kasan_slab_pre_free(s, object, _RET_IP_); + return __kasan_slab_pre_free(s, object, _RET_IP_, + after_rcu_delay); return false; } @@ -424,7 +428,8 @@ static inline void *kasan_init_slab_obj(struct kmem_cache *cache, return (void *)object; } -static inline bool kasan_slab_pre_free(struct kmem_cache *s, void *object) +static inline bool kasan_slab_pre_free(struct kmem_cache *s, void *object, + bool after_rcu_delay) { return false; } @@ -495,6 +500,7 @@ void kasan_cache_create(struct kmem_cache *cache, unsigned int *size, void kasan_cache_shrink(struct kmem_cache *cache); void kasan_cache_shutdown(struct kmem_cache *cache); void kasan_record_aux_stack(void *ptr); +void kasan_mark_rcu_free_pending(void *ptr); #else /* CONFIG_KASAN_GENERIC */ @@ -512,6 +518,7 @@ static inline void kasan_cache_create(struct kmem_cache *cache, static inline void kasan_cache_shrink(struct kmem_cache *cache) {} static inline void kasan_cache_shutdown(struct kmem_cache *cache) {} static inline void kasan_record_aux_stack(void *ptr) {} +static inline void kasan_mark_rcu_free_pending(void *ptr) {} #endif /* CONFIG_KASAN_GENERIC */ diff --git a/mm/kasan/common.c b/mm/kasan/common.c index 7d21c4db68d20f..4187606a88cf4b 100644 --- a/mm/kasan/common.c +++ b/mm/kasan/common.c @@ -68,6 +68,7 @@ void kasan_set_track(struct kasan_track *track, depot_stack_handle_t stack) track->timestamp = ts_nsec >> 9; #endif /* CONFIG_KASAN_EXTRA_INFO */ track->pid = current->pid; + track->rcu_free = 0; track->stack = stack; } @@ -231,7 +232,7 @@ void * __must_check __kasan_init_slab_obj(struct kmem_cache *cache, /* Returns true when freeing the object is not safe. */ static bool check_slab_allocation(struct kmem_cache *cache, void *object, - unsigned long ip) + unsigned long ip, bool after_rcu_delay) { void *tagged_object = object; @@ -242,7 +243,8 @@ static bool check_slab_allocation(struct kmem_cache *cache, void *object, return true; } - if (!kasan_byte_accessible(tagged_object)) { + if (!kasan_byte_accessible(tagged_object) || + kasan_check_rcu_free(cache, object, after_rcu_delay)) { kasan_report_invalid_free(tagged_object, ip, KASAN_REPORT_DOUBLE_FREE); return true; } @@ -259,17 +261,18 @@ static inline void poison_slab_object(struct kmem_cache *cache, void *object, kasan_poison(object, round_up(cache->object_size, KASAN_GRANULE_SIZE), KASAN_SLAB_FREE, init); + kasan_clear_rcu_free(cache, object); if (kasan_stack_collection_enabled()) kasan_save_free_info(cache, tagged_object); } bool __kasan_slab_pre_free(struct kmem_cache *cache, void *object, - unsigned long ip) + unsigned long ip, bool after_rcu_delay) { if (is_kfence_address(object)) return false; - return check_slab_allocation(cache, object, ip); + return check_slab_allocation(cache, object, ip, after_rcu_delay); } bool __kasan_slab_free(struct kmem_cache *cache, void *object, bool init, @@ -544,7 +547,7 @@ bool __kasan_mempool_poison_object(void *ptr, unsigned long ip) slab = page_slab(page); - if (check_slab_allocation(slab->slab_cache, ptr, ip)) + if (check_slab_allocation(slab->slab_cache, ptr, ip, false)) return false; poison_slab_object(slab->slab_cache, ptr, false); diff --git a/mm/kasan/generic.c b/mm/kasan/generic.c index 2b8e73f5f6a70a..3532a41ce966ed 100644 --- a/mm/kasan/generic.c +++ b/mm/kasan/generic.c @@ -533,10 +533,13 @@ size_t kasan_metadata_size(struct kmem_cache *cache, bool in_object) } /* + * Records an auxiliary stack trace for the object at @addr and, if @rcu_free + * is set, marks the object as pending an RCU-delayed free. + * * This function avoids dynamic memory allocations and thus can be called from * contexts that do not allow allocating memory. */ -void kasan_record_aux_stack(void *addr) +static void __kasan_record_aux_stack(void *addr, bool rcu_free) { struct slab *slab = kasan_addr_to_slab(addr); struct kmem_cache *cache; @@ -552,10 +555,22 @@ void kasan_record_aux_stack(void *addr) if (!alloc_meta) return; + if (rcu_free) + alloc_meta->alloc_track.rcu_free = 1; alloc_meta->aux_stack[1] = alloc_meta->aux_stack[0]; alloc_meta->aux_stack[0] = kasan_save_stack(0, 0); } +void kasan_record_aux_stack(void *addr) +{ + __kasan_record_aux_stack(addr, false); +} + +void kasan_mark_rcu_free_pending(void *addr) +{ + __kasan_record_aux_stack(addr, true); +} + void kasan_save_alloc_info(struct kmem_cache *cache, void *object, gfp_t flags) { struct kasan_alloc_meta *alloc_meta; diff --git a/mm/kasan/kasan.h b/mm/kasan/kasan.h index fc9169a547662b..43d6088995441a 100644 --- a/mm/kasan/kasan.h +++ b/mm/kasan/kasan.h @@ -191,7 +191,10 @@ static inline bool kasan_requires_meta(void) #define KASAN_STACK_DEPTH 64 struct kasan_track { - u32 pid; +#define KASAN_PID_BITS const_ilog2(PID_MAX_LIMIT) + u32 pid:KASAN_PID_BITS; + u32 rcu_free:1; + u32 unused:32 - (KASAN_PID_BITS + 1); depot_stack_handle_t stack; #ifdef CONFIG_KASAN_EXTRA_INFO u64 cpu:20; @@ -390,8 +393,37 @@ struct kasan_alloc_meta *kasan_get_alloc_meta(struct kmem_cache *cache, struct kasan_free_meta *kasan_get_free_meta(struct kmem_cache *cache, const void *object); void kasan_init_object_meta(struct kmem_cache *cache, const void *object); + +static inline bool kasan_check_rcu_free(struct kmem_cache *cache, + const void *object, + bool after_rcu_delay) +{ + struct kasan_alloc_meta *alloc_meta; + + alloc_meta = kasan_get_alloc_meta(cache, object); + if (!alloc_meta) + return false; + + return alloc_meta->alloc_track.rcu_free != after_rcu_delay; +} + +static inline void kasan_clear_rcu_free(struct kmem_cache *cache, + const void *object) +{ + struct kasan_alloc_meta *alloc_meta; + + alloc_meta = kasan_get_alloc_meta(cache, object); + if (alloc_meta) + alloc_meta->alloc_track.rcu_free = 0; +} #else static inline void kasan_init_object_meta(struct kmem_cache *cache, const void *object) { } +static inline bool kasan_check_rcu_free(struct kmem_cache *cache, const void *object, + bool after_rcu_delay) +{ + return false; +} +static inline void kasan_clear_rcu_free(struct kmem_cache *cache, const void *object) { } #endif depot_stack_handle_t kasan_save_stack(gfp_t flags, depot_flags_t depot_flags); diff --git a/mm/slub.c b/mm/slub.c index 45e077c7526c2a..cbc51440b3d95e 100644 --- a/mm/slub.c +++ b/mm/slub.c @@ -2722,7 +2722,7 @@ bool slab_free_hook(struct kmem_cache *s, void *x, bool init, * Give KASAN a chance to notice an invalid free operation before we * modify the object. */ - if (kasan_slab_pre_free(s, x)) + if (kasan_slab_pre_free(s, x, after_rcu_delay)) return false; #ifdef CONFIG_SLUB_RCU_DEBUG @@ -2738,7 +2738,7 @@ bool slab_free_hook(struct kmem_cache *s, void *x, bool init, * We have to do this manually because the rcu_head is * not located inside the object. */ - kasan_record_aux_stack(x); + kasan_mark_rcu_free_pending(x); delayed_free->object = x; call_rcu(&delayed_free->head, slab_free_after_rcu_debug); @@ -6298,6 +6298,12 @@ bool __kfree_rcu_sheaf(struct kmem_cache *s, void *obj, unsigned int free_flags) } do_free: + if (unlikely(kasan_slab_pre_free(s, obj, false))) { + local_unlock(&s->cpu_sheaves->lock); + goto out; + } + + kasan_mark_rcu_free_pending(obj); rcu_sheaf = pcs->rcu_free; @@ -6338,6 +6344,7 @@ bool __kfree_rcu_sheaf(struct kmem_cache *s, void *obj, unsigned int free_flags) local_unlock(&s->cpu_sheaves->lock); stat(s, FREE_RCU_SHEAF); +out: if (!IS_ENABLED(CONFIG_PREEMPT_RT)) lock_map_release(&kfree_rcu_sheaf_map); return true; @@ -6971,7 +6978,7 @@ void kfree_nolock(const void *object) * -> kfree_nolock() -> kasan_report_invalid_free() on the same CPU * is double buggy and deserves to deadlock. */ - if (kasan_slab_pre_free(s, x)) + if (kasan_slab_pre_free(s, x, false)) return; /* * memcg, kasan_slab_pre_free are done for 'x'. From 97a5aa11cc0cfe4dedd436c32793320b490c4331 Mon Sep 17 00:00:00 2001 From: Kuniyuki Iwashima Date: Wed, 28 Oct 2026 19:39:20 +0000 Subject: [PATCH 0396/2102] mm/kasan/kunit: add double-free tests involving kfree_rcu_sheaf() The new test cases verify that KASAN immediately detects all three combinations of double-free involving kfree_rcu_sheaf(): 1. kmem_cache_free() -> kfree_rcu() 2. kfree_rcu() -> kmem_cache_free() 3. kfree_rcu() -> kfree_rcu() Each test also evicts the object from the KASAN quarantine and reallocates it as a victim object before flushing the RCU sheaf to ensure the live victim object is not poisoned by the rejected double-free. Without the patch, all tests fail to detect the 2nd free, and the victim is poisoned: # kmem_cache_double_free_rcu_1: EXPECTATION FAILED at mm/kasan/kasan_test_c.c:1096 KASAN failure expected in "kfree_rcu(p, rcu)", but none occurred ... # kmem_cache_double_free_rcu_1: EXPECTATION FAILED at mm/kasan/kasan_test_c.c:1156 Expected (<...snipped READ_ONCE()...>&(victim->i)); }) == 42, but <...snipped READ_ONCE()...>victim->i == 117729280 (0x7046800) # kasan: pass:0 fail:3 skip:0 total:3 # Totals: pass:0 fail:3 skip:0 total:3 not ok 1 kasan In all cases, KASAN logs a false-positive use-after-free splat at READ_ONCE(victim->i), and it has no information about the suspect; the two stack traces ("Call Trace:" and "Allocated by") are of the live victim, and "Freed by" is of the RCU task. BUG: KASAN: slab-use-after-free in __kmem_cache_double_free_rcu+0x9ee/0xaf0 Read of size 4 at addr ffff8881076c2938 by task kunit_try_catch/513 ... Freed by task 0: ... __rcu_free_sheaf_prepare+0xf6/0x240 rcu_free_sheaf_nobarn+0x31/0xe0 rcu_core+0x75e/0x16b0 With the patch, all tests can detect the 2nd free immediately and prevent the victim from being poisoned: # kasan: pass:3 fail:0 skip:0 total:3 # Totals: pass:3 fail:0 skip:0 total:3 ok 1 kasan All the stack traces point to the same object for double-free, and the two free traces are shown in "Call Trace:" and "Freed by" (or "Last potentially related work creation:" in the 2nd/3rd test cases). BUG: KASAN: double-free in kvfree_call_rcu+0xb6/0x3c0 Free of addr ffff888108495938 by task kunit_try_catch/511 ... Call Trace: ... check_slab_allocation+0x10d/0x120 __kfree_rcu_sheaf+0x1c/0x2d0 kvfree_call_rcu+0xb6/0x3c0 __kmem_cache_double_free_rcu+0x310/0xaf0 Allocated by task 511: ... kmem_cache_alloc_noprof+0x14f/0x3c0 __kmem_cache_double_free_rcu+0x152/0xaf0 Freed by task 511: ... kmem_cache_free+0x14f/0x3c0 __kmem_cache_double_free_rcu+0x2c6/0xaf0 Notably, in the 2nd/3rd test cases, we can detect the 2nd free before the object is poisoned: Memory state around the buggy address: ffff888106dc7800: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc ffff888106dc7880: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc >ffff888106dc7900: fc fc fc fc fc fc fc 00 00 00 fc fc fc fc fc fc ^ ... ok 2 kmem_cache_double_free_rcu_2 Link: https://lore.kernel.org/20261028194014.3671161-3-kuniyu@google.com Fixes: ec66e0d59952 ("slab: add sheaf support for batching kfree_rcu() operations") Signed-off-by: Kuniyuki Iwashima Signed-off-by: Andrew Morton Reviewed-by: Alexander Potapenko Cc: Harry Yoo Cc: Andrey Ryabinin Cc: Vlastimil Babka Cc: Harry Yoo Cc: Andrey Konovalov Cc: Dmitry Vyukov Cc: Vincenzo Frascino Cc: Hao Li Cc: Christoph Lameter Cc: David Rientjes Cc: Roman Gushchin Cc: --- mm/kasan/kasan_test_c.c | 139 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) diff --git a/mm/kasan/kasan_test_c.c b/mm/kasan/kasan_test_c.c index b9e167ed5be328..3c9ffee8001b8f 100644 --- a/mm/kasan/kasan_test_c.c +++ b/mm/kasan/kasan_test_c.c @@ -30,6 +30,7 @@ #include #include "kasan.h" +#include "../slab.h" #define OOB_TAG_OFF (IS_ENABLED(CONFIG_KASAN_GENERIC) ? 0 : KASAN_GRANULE_SIZE) @@ -1070,6 +1071,139 @@ static void kmem_cache_double_free(struct kunit *test) kmem_cache_destroy(cache); } +#ifndef MODULE +static void __kmem_cache_double_free_rcu(struct kunit *test, int mode) +{ + struct kasan_rcu_info *p, *victim = NULL, **objs; + struct kmem_cache *cache; + int i, n = 0; + + KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC); + KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_PREEMPT_RT); + + cache = kmem_cache_create("test_cache", sizeof(*p), 0, SLAB_NO_MERGE, + NULL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache); + + if (!cache->sheaf_capacity) { + kmem_cache_destroy(cache); + kunit_skip(test, "Test requires sheaves"); + } + + objs = kunit_kcalloc(test, cache->sheaf_capacity * 2, sizeof(*objs), + GFP_KERNEL); + if (!objs) { + kunit_err(test, "Allocation failed: %s\n", __func__); + goto out; + } + + migrate_disable(); + + p = kmem_cache_alloc(cache, GFP_KERNEL); + if (!p) { + migrate_enable(); + kunit_err(test, "Allocation failed: %s\n", __func__); + goto out; + } + + switch (mode) { + case 1: + kmem_cache_free(cache, p); + /* p is already in quarantine. */ + KUNIT_EXPECT_KASAN_FAIL(test, kfree_rcu(p, rcu)); + migrate_enable(); + break; + case 2: + /* The actual free order is inverse. */ + kfree_rcu(p, rcu); + KUNIT_EXPECT_KASAN_FAIL(test, kmem_cache_free(cache, p)); + migrate_enable(); + break; + case 3: + kfree_rcu(p, rcu); + + for (i = 0; i < cache->sheaf_capacity - 1; i++) { + objs[i] = kmem_cache_alloc(cache, GFP_KERNEL); + kfree_rcu(objs[i], rcu); + } + + KUNIT_EXPECT_KASAN_FAIL(test, kfree_rcu(p, rcu)); + migrate_enable(); + + /* + * Move the 1st full sheaf to quarantine, keeping the + * 2nd in pcs->rcu_free. + */ + rcu_barrier(); + break; + } + + /* + * Move p to quarantine if not poisoned yet (case 2, + * or fallback in case 3). + */ + if (kasan_byte_accessible(p)) + kvfree_rcu_barrier_on_cache(cache); + + /* + * Evict p from quarantine and reallocate it as a live victim object + * before the RCU sheaf is flushed. + */ + kasan_quarantine_remove_cache(cache); + + for (i = 0; i < cache->sheaf_capacity * 2; i++) { + objs[n] = kmem_cache_alloc(cache, GFP_KERNEL); + if (!objs[n]) + break; + if (objs[n] == p) { + victim = objs[n]; + break; + } + n++; + } + + for (i = 0; i < n; i++) + kmem_cache_free(cache, objs[i]); + + KUNIT_EXPECT_PTR_EQ(test, victim, p); + if (victim != p) + goto out; + + WRITE_ONCE(victim->i, 42); + + /* + * If kfree_rcu() failed to reject the double-free above, + * flushing the RCU sheaf will silently poison the live + * victim and cause a false-positive UAF on victim->i. + */ + kvfree_rcu_barrier_on_cache(cache); + KUNIT_EXPECT_EQ(test, READ_ONCE(victim->i), 42); + + if (!READ_ONCE(test_status.report_found)) + kmem_cache_free(cache, victim); +out: + kmem_cache_destroy(cache); +} + +static void kmem_cache_double_free_rcu_1(struct kunit *test) +{ + /* kmem_cache_free() -> kfree_rcu() */ + __kmem_cache_double_free_rcu(test, 1); +} + +static void kmem_cache_double_free_rcu_2(struct kunit *test) +{ + /* kfree_rcu() -> kmem_cache_free() */ + __kmem_cache_double_free_rcu(test, 2); +} + +static void kmem_cache_double_free_rcu_3(struct kunit *test) +{ + /* kfree_rcu() -> kfree_rcu() */ + __kmem_cache_double_free_rcu(test, 3); +} +#endif + static void kmem_cache_invalid_free(struct kunit *test) { char *p; @@ -2239,6 +2373,11 @@ static struct kunit_case kasan_kunit_test_cases[] = { KUNIT_CASE(kfree_via_phys), KUNIT_CASE(kmem_cache_oob), KUNIT_CASE(kmem_cache_double_free), +#ifndef MODULE + KUNIT_CASE(kmem_cache_double_free_rcu_1), + KUNIT_CASE(kmem_cache_double_free_rcu_2), + KUNIT_CASE(kmem_cache_double_free_rcu_3), +#endif KUNIT_CASE(kmem_cache_invalid_free), KUNIT_CASE(kmem_cache_rcu_uaf), KUNIT_CASE(kmem_cache_rcu_reuse), From 53a6f71c147a445a6c305513acaa25f2e01a44e9 Mon Sep 17 00:00:00 2001 From: Mani Tofigh Date: Mon, 26 Oct 2026 11:19:22 -0400 Subject: [PATCH 0397/2102] mm, swap: stop cluster list scans once swapoff clears SWP_WRITEOK SWP_WRITEOK is cleared under si->lock when swapoff starts so that no new swap entries are allocated from the device, and try_to_unuse() then waits for writeback of the folios that still use the device. However, an order-0 allocation that chose the device can race with swapoff clearing the flag and then loop forever. It takes a cluster from the fragment cluster list of a higher order with isolate_lock_cluster(), the allocation from that cluster fails because SWP_WRITEOK is clear, and relocate_cluster() puts the cluster back on the same list, so the loop keeps finding clusters on it. The looping task is in reclaim, and it may have set writeback on a folio whose write has been queued but not yet submitted. swapoff then waits for that folio, while the reclaiming task, stuck in the loop, never reaches the point where it submits the write: CPU0 (reclaim) CPU1 (swapoff) -------------- -------------- shrink_folio_list() pageout(F) /* F under writeback, write not submitted */ folio_alloc_swap(G) /* order 0 */ swap_alloc_slow() del_from_avail_list(si, true) si->flags &= ~SWP_WRITEOK try_to_unuse() folio_wait_writeback(F) cluster_alloc_swap_entry() isolate_lock_cluster() /* allocation fails: !SWP_WRITEOK */ relocate_cluster() /* repeats forever */ swap_write_submit() /* never reached */ This results in a soft lockup on CPU0 and a swapoff that never returns. isolate_lock_cluster() used to check SWP_WRITEOK under si->lock until commit 07adc4cf1ecd ("mm, swap: implement dynamic allocation of swap table") removed that check. Restore the check. Since swapoff clears the flag under the same lock, isolate_lock_cluster() then returns NULL, which ends the scan; the swap slot allocation for G fails, and reclaim goes on to submit the write of F. Given that this is a race, its reproducibility is non-deterministic. We reproduce it by using a non-rotational swap device that is not synchronous, with 64K mTHP enabled, where one CPU repeatedly pages out two 64K folios and a 4K page with madvise(MADV_PAGEOUT), while other CPUs run swapoff and swapon on the same device. In my tests it triggers within 20s in each run, and with the fix applied, it runs for 300s without any hang/kernel report. This bug was found and reproduced deterministically using a deterministic hypervisor that is currently under development. Link: https://lore.kernel.org/20261026-swapoff-writeok-v1-1-4f4cd420aa33@columbia.edu Fixes: 07adc4cf1ecd ("mm, swap: implement dynamic allocation of swap table") Signed-off-by: Mani Tofigh Signed-off-by: Andrew Morton Acked-by: Kairui Song Cc: Chris Li Cc: Kemeng Shi Cc: Nhat Pham Cc: Baoquan He Cc: Barry Song Cc: Youngjun Park Cc: Tal Zussman Cc: Kairui Song Cc: --- mm/swapfile.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/mm/swapfile.c b/mm/swapfile.c index 2d2df53fc51a91..c2af13eb15b33d 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -635,6 +635,10 @@ static struct swap_cluster_info *isolate_lock_cluster( u8 flags = CLUSTER_FLAG_NONE; spin_lock(&si->lock); + + if (unlikely(!(si->flags & SWP_WRITEOK))) + goto out; + list_for_each_entry(ci, list, list) { if (!spin_trylock(&ci->lock)) continue; @@ -650,6 +654,7 @@ static struct swap_cluster_info *isolate_lock_cluster( found = ci; break; } +out: spin_unlock(&si->lock); /* Cluster's table is freed when and only when it's on the free list. */ From a2108a958143de74b4e5ddca12b01f05ecd030f9 Mon Sep 17 00:00:00 2001 From: Ridong Chen Date: Sun, 25 Oct 2026 19:02:09 +0800 Subject: [PATCH 0398/2102] mm/migrate: move NR_FILE_THPS on cross-node migration When a page cache folio is migrated to another node, __folio_migrate_mapping() moves the per-node and per-memcg counters that are keyed off the folio's node: NR_FILE_PAGES, NR_SHMEM, NR_SHMEM_THPS, NR_SWAPCACHE and NR_FILE_DIRTY. NR_FILE_THPS is not moved, although __filemap_add_folio() charges it to the source node and filemap_unaccount_folio() takes it off whatever node the folio lives on when it is removed. Commit 0b52c420350e ("mm: fix shmem THP counters on migration") added the NR_SHMEM_THPS case but not its file-backed counterpart. Now that ext4, xfs, btrfs and erofs can all have PMD-sized page cache folios, migrating them via NUMA balancing, mbind(), migratepages, demotion or memory offlining leaks FileHugePages on the source node and underflows it on the destination, in both /sys/devices/system/node/nodeN/meminfo and memory.numa_stat. The global value is unaffected, which is why this went unnoticed. Reproducer, on a 2-node QEMU guest with THP set to "always": 1. read a 256M ext4 file through a MADV_HUGEPAGE mapping while bound to node 0, so its page cache is 128 PMD-sized folios on node 0; 2. move the mapping to node 1 with mbind(MPOL_MF_MOVE); 3. unmap the file and drop its page cache. nr_file_hugepages in /sys/devices/system/node/nodeN/vmstat after each step (in units of PMD-sized folios): without this patch with this patch node0 node1 node0 node1 1. cached 128 0 128 0 2. migrated 128 0 0 128 3. dropped 128 0 (*) 0 0 (*) the counter has underflowed to -128; negative values read as 0. Without the patch the 128 folios stay accounted to node 0 forever, and every further round adds another 128. The same happens to the per-memcg per-node counter: after step 3, memory.stat of the cgroup shows "file_thp 0", while memory.numa_stat still shows "file_thp N0=268435456 N1=0". With the patch both are 0. Move NR_FILE_THPS together with NR_FILE_PAGES, using the same condition filemap_unaccount_folio() uses to take it off, so that THPs in the swap cache are left alone. Link: https://lore.kernel.org/20261025110209.4105994-1-ridong.chen@linux.dev Fixes: d68eccad3706 ("mm/filemap: Allow large folios to be added to the page cache") Signed-off-by: Ridong Chen Signed-off-by: Andrew Morton Acked-by: David Hildenbrand (Arm) Cc: Zi Yan Cc: Matthew Brost Cc: Joshua Hahn Cc: Byungchul Park Cc: Gregory Price Cc: Ying Huang Cc: Alistair Popple Cc: Matthew Wilcox (Oracle) Cc: "Garg, Shivank" Cc: --- mm/migrate.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/mm/migrate.c b/mm/migrate.c index 875079464930a4..f7dfe47656183c 100644 --- a/mm/migrate.c +++ b/mm/migrate.c @@ -700,6 +700,10 @@ static int __folio_migrate_mapping(struct address_space *mapping, mod_lruvec_state(old_lruvec, NR_SHMEM_THPS, -nr); mod_lruvec_state(new_lruvec, NR_SHMEM_THPS, nr); } + } else if (!folio_test_swapbacked(folio) && + folio_test_pmd_mappable(folio)) { + mod_lruvec_state(old_lruvec, NR_FILE_THPS, -nr); + mod_lruvec_state(new_lruvec, NR_FILE_THPS, nr); } #ifdef CONFIG_SWAP if (folio_test_swapcache(folio)) { From 4ac11db025da54f389796920b253221d1afe6aac Mon Sep 17 00:00:00 2001 From: Ridong Chen Date: Tue, 27 Oct 2026 12:32:14 +0800 Subject: [PATCH 0399/2102] mm/migrate: move NR_KERNEL_FILE_PAGES on cross-node migration NR_KERNEL_FILE_PAGES counts page cache folios of mappings flagged AS_KERNEL_FILE (currently the btrfs btree inode). It is a per-node counter: filemap_add_folio() adds to folio_pgdat() of the new folio and filemap_unaccount_folio() subtracts from folio_pgdat() of the folio being removed. __folio_migrate_mapping() does not move it when such a folio is migrated to another node, so the source node keeps the count forever and the destination node underflows once the folio is freed. btree folios are migratable through btree_migrate_folio(), so demotion, DAMON-based migration (DAMOS_MIGRATE_{HOT,COLD}) or memory offlining all hit this. Reproducer, on a QEMU guest with two memory tiers (node0 is DRAM with all CPUs, node1 is a CPU-less slower node described via HMAT) and /sys/kernel/mm/numa/demotion_enabled set: 1. mount a btrfs and create 20000 empty files, so that btree folios are cached on node0; 2. echo 2G > /sys/devices/system/node/node0/reclaim, which demotes them to node1; 3. umount and drop caches. nr_kernel_file_pages in /sys/devices/system/node/nodeN/vmstat after each step: without this patch with this patch node0 node1 node0 node1 1. cached 1868 0 1868 0 2. demoted 1868 0 36 1832 3. dropped 1832 0 (*) 0 0 (*) the counter has underflowed to -1832; negative values read as 0. The global value in /proc/vmstat is 0 after step 3 in both cases. Move it together with the other node-keyed page cache counters. It is a node-only counter, so use the node accessor, matching how it is accounted elsewhere. Interrupts are disabled here, as for the zone counters below. This was pointed out by Shivank while reviewing the NR_FILE_THPS fix for the same function. Link: https://lore.kernel.org/20261027043214.2248986-1-ridong.chen@linux.dev Fixes: e3a9ac4e866e ("mm: add vmstat for kernel_file pages") Signed-off-by: Ridong Chen Signed-off-by: Andrew Morton Suggested-by: Shivank Garg Acked-by: David Hildenbrand (Arm) Reviewed-by: Shivank Garg Acked-by: Zi Yan Acked-by: Shakeel Butt Cc: Matthew Brost Cc: Joshua Hahn Cc: Byungchul Park Cc: Gregory Price Cc: Ying Huang Cc: Alistair Popple Cc: Boris Burkov Cc: --- mm/migrate.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mm/migrate.c b/mm/migrate.c index f7dfe47656183c..28a8d7734735b9 100644 --- a/mm/migrate.c +++ b/mm/migrate.c @@ -705,6 +705,12 @@ static int __folio_migrate_mapping(struct address_space *mapping, mod_lruvec_state(old_lruvec, NR_FILE_THPS, -nr); mod_lruvec_state(new_lruvec, NR_FILE_THPS, nr); } + if (test_bit(AS_KERNEL_FILE, &mapping->flags)) { + __mod_node_page_state(oldzone->zone_pgdat, + NR_KERNEL_FILE_PAGES, -nr); + __mod_node_page_state(newzone->zone_pgdat, + NR_KERNEL_FILE_PAGES, nr); + } #ifdef CONFIG_SWAP if (folio_test_swapcache(folio)) { mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr); From 2a700ab992286e1d3893289909ec46569a725257 Mon Sep 17 00:00:00 2001 From: Muchun Song Date: Fri, 23 Oct 2026 14:34:25 +0800 Subject: [PATCH 0400/2102] mm: fix missing page-table destructor in pagetable_free() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Patch series "mm: Fix page-table teardown during memory hot-remove", v3. Memory hot-remove can free page-table pages allocated through paths with different constructor state. Some paths run the page-table constructor, while generic sparse-vmemmap population may not. The x86, RISC-V, and arm64 teardown paths did not handle that distinction consistently, leaving constructor/destructor accounting unbalanced. Make pagetable_free() handle any remaining constructor state before freeing a page-table page. Callers that already ran pagetable_dtor() have cleared that state, so the destructor is not run twice. The RISC-V and arm64 fixes then use this common helper for their memory-hot-remove paths. The architecture fixes depend on the common MM change in patch 1, so this remains a single series. I expect it to go through the MM tree, with review or acks from the relevant architecture maintainers. This patch (of 4): Since commit 49f599666420 ("mm: call ctor/dtor for kernel PTEs"), pte_alloc_one_kernel() runs the page-table constructor for kernel PTE tables. HVO (HugeTLB Vmemmap Optimization) uses pte_alloc_one_kernel() when splitting a PMD. Restoring the vmemmap backing pages does not collapse the PTE table, so a later memory hot-remove eventually frees it through pagetable_free() on x86-64. That releases the page without running the matching destructor and leaves NR_PAGETABLE elevated. Make pagetable_free() the common free-side primitive for page-table pages. It checks PageTable() and runs the destructor only when the constructor state is still present. Callers that explicitly ran pagetable_dtor() have already cleared PageTable(), so they are not destructed twice; pages that never ran a constructor are freed directly. Link: https://lore.kernel.org/20261023063428.3658761-1-songmuchun@bytedance.com Link: https://lore.kernel.org/20261023063428.3658761-2-songmuchun@bytedance.com Fixes: 49f599666420 ("mm: call ctor/dtor for kernel PTEs") Signed-off-by: Muchun Song Signed-off-by: Andrew Morton Reviewed-by: Jose A. Perez de Azpillaga Reviewed-by: Kevin Brodsky Acked-by: Dave Hansen Acked-by: David Hildenbrand (Arm) Reviewed-by: Anshuman Khandual Cc: Oscar Salvador Cc: Paul Walmsley Cc: Palmer Dabbelt Cc: Albert Ou Cc: Alexandre Ghiti Cc: Björn Töpel Cc: Catalin Marinas Cc: Will Deacon Cc: Mark Rutland Cc: Alexander Gordeev Cc: Alistair Popple Cc: # bf9e4e30f353: x86/mm: use pagetable_free() --- include/linux/mm.h | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/include/linux/mm.h b/include/linux/mm.h index 6af3b7008f1ad1..cb993a1d07284b 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -3971,23 +3971,6 @@ static inline void pagetable_free_kernel(struct ptdesc *pt) __pagetable_free(pt); } #endif -/** - * pagetable_free - Free pagetables - * @pt: The page table descriptor - * - * pagetable_free frees the memory of all page tables described by a page - * table descriptor and the memory for the descriptor itself. - */ -static inline void pagetable_free(struct ptdesc *pt) -{ - if (ptdesc_test_kernel(pt)) { - ptdesc_clear_kernel(pt); - pagetable_free_kernel(pt); - } else { - __pagetable_free(pt); - } -} - #if defined(CONFIG_SPLIT_PTE_PTLOCKS) #if ALLOC_SPLIT_PTLOCKS void __init ptlock_cache_init(void); @@ -4080,6 +4063,26 @@ static inline void pagetable_dtor(struct ptdesc *ptdesc) lruvec_stat_sub_folio(folio, NR_PAGETABLE); } +/** + * pagetable_free - Free pagetables + * @pt: The page table descriptor + * + * pagetable_free frees the memory of all page tables described by a page + * table descriptor and the memory for the descriptor itself. + */ +static inline void pagetable_free(struct ptdesc *pt) +{ + if (PageTable(ptdesc_page(pt))) + pagetable_dtor(pt); + + if (ptdesc_test_kernel(pt)) { + ptdesc_clear_kernel(pt); + pagetable_free_kernel(pt); + } else { + __pagetable_free(pt); + } +} + static inline void pagetable_dtor_free(struct ptdesc *ptdesc) { pagetable_dtor(ptdesc); From 352fca06aa692848a9b95f43740b4939f495ca4b Mon Sep 17 00:00:00 2001 From: Muchun Song Date: Fri, 23 Oct 2026 14:34:26 +0800 Subject: [PATCH 0401/2102] riscv/mm: fix hotplug page-table destructor handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RISC-V uses the same memory-hotplug teardown code for linear-map and vmemmap page tables. Late linear-map allocations run page-table constructors, while vmemmap and early allocations may not. free_pte_table() unconditionally calls pagetable_dtor(), corrupting NR_PAGETABLE accounting for constructor-free tables. free_pmd_table() avoids that for vmemmap using is_vmemmap, but mapping type is not a reliable proxy for constructor state. In particular, it becomes invalid once runtime vmemmap tables use the normal pgalloc helpers. Introduce free_pgtable_page() to select free_reserved_page() for reserved pages and pagetable_free() otherwise. The latter runs the destructor only when PageTable() is set, handling both constructor-backed and constructor-free tables. Link: https://lore.kernel.org/20261023063428.3658761-3-songmuchun@bytedance.com Fixes: c75a74f4ba19 ("riscv: mm: Add memory hotplugging support") Signed-off-by: Muchun Song Signed-off-by: Andrew Morton Reviewed-by: Björn Töpel Reviewed-by: Kevin Brodsky Acked-by: David Hildenbrand (Arm) Cc: Oscar Salvador Cc: Dave Hansen Cc: Paul Walmsley Cc: Palmer Dabbelt Cc: Albert Ou Cc: Alexandre Ghiti Cc: Björn Töpel Cc: Catalin Marinas Cc: Will Deacon Cc: Mark Rutland Cc: Alexander Gordeev Cc: Alistair Popple Cc: --- arch/riscv/mm/init.c | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/arch/riscv/mm/init.c b/arch/riscv/mm/init.c index 070ee69eabb381..3aabfe871935c4 100644 --- a/arch/riscv/mm/init.c +++ b/arch/riscv/mm/init.c @@ -1501,10 +1501,17 @@ struct execmem_info __init *execmem_arch_setup(void) #endif /* CONFIG_EXECMEM */ #ifdef CONFIG_MEMORY_HOTPLUG +static void __meminit free_pgtable_page(struct page *page) +{ + if (PageReserved(page)) + free_reserved_page(page); + else + pagetable_free(page_ptdesc(page)); +} + static void __meminit free_pte_table(pte_t *pte_start, pmd_t *pmd) { struct page *page = pmd_page(*pmd); - struct ptdesc *ptdesc = page_ptdesc(page); pte_t *pte; int i; @@ -1514,18 +1521,13 @@ static void __meminit free_pte_table(pte_t *pte_start, pmd_t *pmd) return; } - pagetable_dtor(ptdesc); - if (PageReserved(page)) - free_reserved_page(page); - else - pagetable_free(ptdesc); + free_pgtable_page(page); pmd_clear(pmd); } -static void __meminit free_pmd_table(pmd_t *pmd_start, pud_t *pud, bool is_vmemmap) +static void __meminit free_pmd_table(pmd_t *pmd_start, pud_t *pud) { struct page *page = pud_page(*pud); - struct ptdesc *ptdesc = page_ptdesc(page); pmd_t *pmd; int i; @@ -1535,12 +1537,7 @@ static void __meminit free_pmd_table(pmd_t *pmd_start, pud_t *pud, bool is_vmemm return; } - if (!is_vmemmap) - pagetable_dtor(ptdesc); - if (PageReserved(page)) - free_reserved_page(page); - else - pagetable_free(ptdesc); + free_pgtable_page(page); pud_clear(pud); } @@ -1660,7 +1657,7 @@ static void __meminit remove_pud_mapping(pud_t *pud_base, unsigned long addr, un remove_pmd_mapping(pmd_base, addr, next, is_vmemmap, altmap); if (pgtable_l4_enabled()) - free_pmd_table(pmd_base, pudp, is_vmemmap); + free_pmd_table(pmd_base, pudp); } } From fbf197512f5affda696dc4822e394d410b333792 Mon Sep 17 00:00:00 2001 From: Muchun Song Date: Fri, 23 Oct 2026 14:34:27 +0800 Subject: [PATCH 0402/2102] riscv/mm: fix missing destructor for hotplug PUD tables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commit 8472cc4503eb ("riscv: mm: call PUD/P4D ctor in special kernel pgtable alloc") made alloc_pud_late() run the PUD page-table constructor. However, free_pud_table() still frees non-reserved PUD tables directly without decrementing NR_PAGETABLE. Free PUD tables through the common free_pgtable_page() helper so that constructor-backed tables run the matching destructor before being freed. Link: https://lore.kernel.org/20261023063428.3658761-4-songmuchun@bytedance.com Fixes: 8472cc4503eb ("riscv: mm: call PUD/P4D ctor in special kernel pgtable alloc") Signed-off-by: Muchun Song Signed-off-by: Andrew Morton Reviewed-by: Björn Töpel Reviewed-by: Kevin Brodsky Acked-by: David Hildenbrand (Arm) Cc: Oscar Salvador Cc: Dave Hansen Cc: Paul Walmsley Cc: Palmer Dabbelt Cc: Albert Ou Cc: Alexandre Ghiti Cc: Björn Töpel Cc: Catalin Marinas Cc: Will Deacon Cc: Mark Rutland Cc: Alexander Gordeev Cc: Alistair Popple Cc: --- arch/riscv/mm/init.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/arch/riscv/mm/init.c b/arch/riscv/mm/init.c index 3aabfe871935c4..e822fce0af4b03 100644 --- a/arch/riscv/mm/init.c +++ b/arch/riscv/mm/init.c @@ -1553,10 +1553,7 @@ static void __meminit free_pud_table(pud_t *pud_start, p4d_t *p4d) return; } - if (PageReserved(page)) - free_reserved_page(page); - else - __free_pages(page, 0); + free_pgtable_page(page); p4d_clear(p4d); } From 26601a6c80c52c5336cd02b3379710077aeafc4a Mon Sep 17 00:00:00 2001 From: Muchun Song Date: Fri, 23 Oct 2026 14:34:28 +0800 Subject: [PATCH 0403/2102] arm64/mm: fix destructor for unconstructed hotplug page tables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commit c594b83457cc ("arm64: mm: call pagetable dtor when freeing hot-removed page tables") made free_hotplug_pgtable_page() unconditionally run the page-table destructor. This matches page tables allocated by the arm64 mapping code, which runs the corresponding constructors. However, arm64 also uses the generic sparse-vmemmap population code. Runtime intermediate page tables allocated by that code do not run a page-table constructor. Freeing one during memory hot-remove therefore runs a destructor without a matching constructor and corrupts NR_PAGETABLE accounting. Free intermediate page-table pages through pagetable_free(). It runs the destructor only for constructor-backed pages and then releases the page through the page-table freeing path. Link: https://lore.kernel.org/20261023063428.3658761-5-songmuchun@bytedance.com Fixes: c594b83457cc ("arm64: mm: call pagetable dtor when freeing hot-removed page tables") Signed-off-by: Muchun Song Signed-off-by: Andrew Morton Reviewed-by: Kevin Brodsky Acked-by: David Hildenbrand (Arm) Reviewed-by: Anshuman Khandual Reviewed-by: Catalin Marinas Cc: Oscar Salvador Cc: Dave Hansen Cc: Paul Walmsley Cc: Palmer Dabbelt Cc: Albert Ou Cc: Alexandre Ghiti Cc: Björn Töpel Cc: Will Deacon Cc: Mark Rutland Cc: Alexander Gordeev Cc: Alistair Popple Cc: --- arch/arm64/mm/mmu.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/arch/arm64/mm/mmu.c b/arch/arm64/mm/mmu.c index 140520b351e282..19459a4a870a2d 100644 --- a/arch/arm64/mm/mmu.c +++ b/arch/arm64/mm/mmu.c @@ -1495,8 +1495,7 @@ static void free_hotplug_page_range(struct page *page, size_t size, static void free_hotplug_pgtable_page(struct page *page) { - pagetable_dtor(page_ptdesc(page)); - free_hotplug_page_range(page, PAGE_SIZE, NULL); + pagetable_free(page_ptdesc(page)); } static bool pgtable_range_aligned(unsigned long start, unsigned long end, From 9378306c5d3db7e733d60a8b85a22b2b143ecffd Mon Sep 17 00:00:00 2001 From: Nickolai Zeldovich Date: Tue, 27 Oct 2026 15:20:14 -0400 Subject: [PATCH 0404/2102] xarray: clear the new head's parent before freeing the old head xas_shrink() passes the old head to xa_node_free(), which queues it with call_rcu(), before it clears the new head's parent pointer. A lockless walker that loads the new head after the grace period has started can still climb from it into the old head through xa_parent(), as xas_find(), xas_find_marked(), xas_next() and xas_prev() do when they step past the end of a node, and read the old head after it is freed. Clear the parent pointer before freeing the old head, as radix_tree_shrink() does. With a delay injected after xa_node_free() in xas_shrink(), KASAN reports a slab-use-after-free in the walker; with this patch it does not. Link: https://lore.kernel.org/20261027192014.844878-1-nickolai@csail.mit.edu Fixes: 58d6ea3085f2 ("xarray: Add XArray unconditional store operations") Signed-off-by: Nickolai Zeldovich Signed-off-by: Andrew Morton Cc: Matthew Wilcox (Oracle) --- lib/xarray.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/xarray.c b/lib/xarray.c index bfe7bef80f34eb..ae9d7fc68861c8 100644 --- a/lib/xarray.c +++ b/lib/xarray.c @@ -471,11 +471,12 @@ static void xas_shrink(struct xa_state *xas) if (!xa_is_node(entry)) RCU_INIT_POINTER(node->slots[0], XA_RETRY_ENTRY); xas_update(xas, node); + if (xa_is_node(entry)) + xa_to_node(entry)->parent = NULL; xa_node_free(node); if (!xa_is_node(entry)) break; node = xa_to_node(entry); - node->parent = NULL; } } From d7e3ce464470d0ff90b4a0ac87df9b3b7d8258da Mon Sep 17 00:00:00 2001 From: Andrew Morton Date: Fri, 30 Oct 2026 12:10:46 -0400 Subject: [PATCH 0405/2102] mm/mempolicy: use one node set for interleave weights Switching weighted interleave back to automatic mode while memory is being onlined can cause a kernel divide error on x86, and a panic if panic_on_oops is set. reduce_interleave_weights() scans N_MEMORY three times, but hotplug can cause N_MEMORY to change at runtime - and torn reads on that nodemask can cause a total sum of zero bandwidth. A node that was hot-unplugged and then hotplugged back can then cause this loop to generate a div/0. Record the nodes visited while summing their bandwidth, then use that same set when scaling and reducing the weights. This gives us a consistent state even if N_MEMORY changes. Link: https://lore.kernel.org/20261030161046.1497894-1-gourry@gourry.net Fixes: e341f9c3c841 ("mm/mempolicy: Weighted Interleave Auto-tuning") Signed-off-by: Andrew Morton Signed-off-by: Gregory Price (Meta) Reviewed-by: Joshua Hahn Cc: David Hildenbrand Cc: Zi Yan Cc: Rakie Kim Cc: Ying Huang Cc: Harry Yoo Cc: --- mm/mempolicy.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/mm/mempolicy.c b/mm/mempolicy.c index 4da1cb8777f681..5eb4d77eb740be 100644 --- a/mm/mempolicy.c +++ b/mm/mempolicy.c @@ -207,15 +207,22 @@ static u8 get_il_weight(int node) */ static void reduce_interleave_weights(unsigned int *bw, u8 *new_iw) { + nodemask_t nodes = NODE_MASK_NONE; u64 sum_bw = 0; unsigned int cast_sum_bw, scaling_factor = 1, iw_gcd = 0; int nid; - for_each_node_state(nid, N_MEMORY) + /* + * N_MEMORY can change while wi_state_lock is held. Remember the + * nodes contributing to sum_bw so all passes use the same set. + */ + for_each_node_state(nid, N_MEMORY) { + node_set(nid, nodes); sum_bw += bw[nid]; + } /* Scale bandwidths to whole numbers in the range [1, weightiness] */ - for_each_node_state(nid, N_MEMORY) { + for_each_node_mask(nid, nodes) { /* * Try not to perform 64-bit division. * If sum_bw < scaling_factor, then sum_bw < U32_MAX. @@ -234,7 +241,7 @@ static void reduce_interleave_weights(unsigned int *bw, u8 *new_iw) } /* 1:2 is strictly better than 16:32. Reduce by the weights' GCD. */ - for_each_node_state(nid, N_MEMORY) + for_each_node_mask(nid, nodes) new_iw[nid] /= iw_gcd; } From fc2c19648d681cc5fb00efa938b78460c2e5b44d Mon Sep 17 00:00:00 2001 From: Mani Tofigh Date: Tue, 27 Oct 2026 16:33:32 -0400 Subject: [PATCH 0406/2102] mm/shmem: fix swapin livelock on a mismatched large swap cache folio On a SWP_SYNCHRONOUS_IO swap device, a large shmem folio can be left in the swap cache over swap slots that another file now uses. Reading that other file then loops forever in shmem_get_folio_gfp(): shmem_swapin_folio() finds the large folio, rounds the index and the swap entry down to the folio's size, finds no matching entry in the file and returns -EEXIST, and the retry finds the same folio again. Since the task keeps the mapping locked, a munmap() of the same mapping waits forever. The folio is left behind when the slots are freed and reused while the swapin is still allocating it: Task A (reads X) Task B ---------------- ------ shmem_swapin_folio() allocate a large folio for X's slots punch a hole in X /* X's slots freed */ swap out file Y /* Y reuses those slots */ add the folio to the swap cache over those slots shmem_confirm_swap() fails /* -EEXIST, the folio stays in the swap cache */ Task C (reads Y) ---------------- shmem_swapin_folio() finds the large folio rounds down to its start, where Y has no entry /* -EEXIST, retried forever */ Before commit c246d236b18b ("mm/shmem: never bypass the swap cache for SWP_SYNCHRONOUS_IO"), a direct swapin that failed this way freed its folio instead of leaving it in the swap cache. do_swap_page() already drops a large swap cache folio that does not fit for anonymous memory. Do the same in shmem_swapin_folio() and on a -EEXIST, remove a large folio that is not anonymous/dirty/under-writeback from the swap cache so that the retry swaps in a folio that fits. The reproducer below fills a small brd swap device so that a 64K shmem folio and the 4K pages of another file land in the same slots, and races a read of the first file with a hole punch and a swapout of the second. This bug was identified and confirmed with the help of a deterministic hypervisor currently under development, but the non-deterministic C reproducer can typically trigger it in the 2-4s time range. With the fix, nothing is triggered after 600 seconds. Link: https://lore.kernel.org/20261027-shmem-swapin-mismatch-v1-1-84e30aa3b9e5@columbia.edu Fixes: c246d236b18b ("mm/shmem: never bypass the swap cache for SWP_SYNCHRONOUS_IO") Signed-off-by: Mani Tofigh Signed-off-by: Andrew Morton Reviewed-by: Baolin Wang Cc: Hugh Dickins Cc: Kairui Song Cc: Chris Li Cc: Kemeng Shi Cc: Nhat Pham Cc: Baoquan He Cc: Barry Song Cc: Youngjun Park Cc: David Hildenbrand Cc: Tal Zussman Cc: --- mm/shmem.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/mm/shmem.c b/mm/shmem.c index b8399bb7199789..cd686a4900f4ec 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -2612,11 +2612,14 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index, * and swap cache folios are never partially freed. */ folio_lock(folio); - if (!folio_matches_swap_entry(folio, swap) || - shmem_confirm_swap(mapping, index, swap) < 0) { + if (!folio_matches_swap_entry(folio, swap)) { error = -EEXIST; goto unlock; } + if (shmem_confirm_swap(mapping, index, swap) < 0) { + error = -EEXIST; + goto failed; + } if (!folio_test_uptodate(folio)) { error = -EIO; goto failed; @@ -2657,6 +2660,15 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index, error = -EEXIST; if (error == -EIO) shmem_set_folio_swapin_error(inode, index, folio, swap); + /* + * A large folio that does not fit the mapping, e.g. because its swap + * entries were freed and reused, would be found again on every retry. + * Drop it from the swap cache so the retry can swap in a fitting one. + */ + if (error == -EEXIST && folio && folio_test_large(folio) && + !folio_test_anon(folio) && !folio_test_dirty(folio) && + !folio_test_writeback(folio)) + swap_cache_del_folio(folio); unlock: if (folio) folio_unlock(folio); From cd5f5bf781b4ead6a6571818d5613ea2ed0145f3 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Fri, 30 Oct 2026 23:29:13 +0100 Subject: [PATCH 0407/2102] mm/memory-failure: fix folio refcount leak and min_order_for_split() locking hwpoison code can end up calling min_order_for_split() without holding the folio lock. There isn't really something that would prevent concurrent truncation. Consequently folio->mapping can get set to NULL after checking for "!folio->mapping", and if the compiler reloads folio->mapping, mapping_min_folio_order() would try to dereference NULL. While very unlikely to happen in practice, let's just enforce that min_order_for_split() is called with the folio lock held. We can significantly cleanup the calling hwpoison code, and just get rid of try_to_split_thp_page() to hold the folio lock for a bit longer. Just work on folios now, which further cleans up the code. We just have to be careful about doing the page_folio() after splitting, which we have to do already either way. Do not change the way we split for now, this needs more thought and should be done separately. Cleaning this up we fix another issue: in soft_offline_in_use_page(), we would currently have leaked a folio reference. In min_order_for_split(), document and assert that we need the folio lock. Drop the questionable VM_BUG_ON_PAGE(!page_count(p), p) check entirely. While updating the comment in soft_offline_in_use_page(), just drop the "NOTE" part that does not add any value to current code. The folio->mapping problem was identified by Sashiko, and Li Youhong reported it by sending a proposal fix. This likely does not really warrant CCing stable, but I expect little conflicts when doing the backport, so let's just CC stable because of the refcount leak. Link: https://lore.kernel.org/20261030-try_to_split_thp_page-v2-1-c957c9b42eab@kernel.org Fixes: 689b8986776c ("mm/memory-failure: improve large block size folio handling") Signed-off-by: David Hildenbrand (Arm) Signed-off-by: Andrew Morton Reported-by: Li Youhong Closes: https://lore.kernel.org/r/20260804035828.2684059-1-dayou5941@163.com Acked-by: Usama Arif Reviewed-by: Lorenzo Stoakes (ARM) Reviewed-by: Zi Yan Reviewed-by: Baolin Wang Acked-by: Miaohe Lin Cc: Liam R. Howlett Cc: Ryan Roberts Cc: Dev Jain Cc: Barry Song Cc: Lance Yang Cc: Naoya Horiguchi Cc: Wei Yang Cc: Nico Pache Cc: Luis Chamberlain Cc: Tal Zussman Cc: --- mm/huge_memory.c | 4 +++ mm/memory-failure.c | 63 +++++++++++++++------------------------------ 2 files changed, 25 insertions(+), 42 deletions(-) diff --git a/mm/huge_memory.c b/mm/huge_memory.c index eb913acb03b74b..0d589be136d21a 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -4551,10 +4551,14 @@ int folio_split(struct folio *folio, unsigned int new_order, * If a file-backed folio is truncated, 0 will be returned. Any subsequent * split attempt should get -EBUSY from split checking code. * + * Context: @folio must be locked. + * * Return: @folio's minimum order for split */ unsigned int min_order_for_split(struct folio *folio) { + VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); + if (folio_test_anon(folio)) return 0; diff --git a/mm/memory-failure.c b/mm/memory-failure.c index b705f9f97f420f..12aa4e52b2bce8 100644 --- a/mm/memory-failure.c +++ b/mm/memory-failure.c @@ -1744,26 +1744,6 @@ static int identify_page_state(unsigned long pfn, struct page *p, return page_action(ps, p, pfn); } -/* - * When 'release' is 'false', it means that if thp split has failed, - * there is still more to do, hence the page refcount we took earlier - * is still needed. - */ -static int try_to_split_thp_page(struct page *page, unsigned int new_order, - bool release) -{ - int ret; - - lock_page(page); - ret = split_huge_page_to_order(page, new_order); - unlock_page(page); - - if (ret && release) - put_page(page); - - return ret; -} - static void unmap_and_kill(struct list_head *to_kill, unsigned long pfn, struct address_space *mapping, pgoff_t index, int flags) { @@ -2548,9 +2528,6 @@ int memory_failure(unsigned long pfn, int flags) folio_unlock(folio); if (folio_test_large(folio)) { - const int new_order = min_order_for_split(folio); - int err; - /* * The flag must be set after the refcount is bumped * otherwise it may race with THP split. @@ -2565,24 +2542,25 @@ int memory_failure(unsigned long pfn, int flags) * page is a valid handlable page. */ folio_set_has_hwpoisoned(folio); - err = try_to_split_thp_page(p, new_order, /* release= */ false); + + folio_lock(folio); + split_huge_page_to_order(p, min_order_for_split(folio)); + folio = page_folio(p); + folio_unlock(folio); + /* * If splitting a folio to order-0 fails, kill the process. * Split the folio regardless to minimize unusable pages. * Because the memory failure code cannot handle large * folios, this split is always treated as if it failed. */ - if (err || new_order) { - /* get folio again in case the original one is split */ - folio = page_folio(p); + if (folio_test_large(folio)) { res = -EHWPOISON; kill_procs_now(p, pfn, flags, folio); - put_page(p); + folio_put(folio); action_result(pfn, MF_MSG_UNSPLIT_THP, MF_FAILED); goto unlock_mutex; } - VM_BUG_ON_PAGE(!page_count(p), p); - folio = page_folio(p); } /* @@ -2900,25 +2878,26 @@ static int soft_offline_in_use_page(struct page *page) .reason = MR_MEMORY_FAILURE, }; + folio_lock(folio); if (!huge && folio_test_large(folio)) { - const int new_order = min_order_for_split(folio); - /* - * If new_order (target split order) is not 0, do not split the - * folio at all to retain the still accessible large folio. - * NOTE: if minimizing the number of soft offline pages is - * preferred, split it to non-zero new_order like it is done in - * memory_failure(). + * If we cannot split to order-0, do not split the folio at all + * to retain the still accessible large folio. */ - if (new_order || try_to_split_thp_page(page, /* new_order= */ 0, - /* release= */ true)) { + if (!min_order_for_split(folio)) + ret = split_huge_page_to_order(page, 0) ? -EBUSY : 0; + else + ret = -EBUSY; + folio = page_folio(page); + + if (ret) { + folio_unlock(folio); + folio_put(folio); pr_info("%#lx: thp split failed\n", pfn); - return -EBUSY; + return ret; } - folio = page_folio(page); } - folio_lock(folio); if (!huge) folio_wait_writeback(folio); if (PageHWPoison(page)) { From 111894c595a078d8481db34f3355e8531990668e Mon Sep 17 00:00:00 2001 From: "Mike Rapoport (Microsoft)" Date: Sat, 31 Oct 2026 20:14:03 +0200 Subject: [PATCH 0408/2102] userfaultfd: clear uffd state in child PTEs if uffd is released during fork With UFFD_FEATURE_EVENT_FORK the userfaultfd context is duplicated for the child process, the child VMAs are registered with the new context, and uffd protection state from the parent PTEs is copied into the child. If the parent's userfaultfd is released before the fork event is read, userfaultfd_release_new() resets the VMA flags but keeps uffd state in the child PTEs. This leaves the child's VMAs in an inconsistent state: they are not registered with userfaultfd but their mappings carry uffd protection state. If the child registers the range with userfaultfd again, the stale state turns into protection the child never asked for. When a write fault makes such a PTE writable without copying the page, the uffd bit remains set and page_table_check_pte_flags() warns about it. Split resolving of the uffd PTE state out of userfaultfd_clear_vma() and call it from userfaultfd_release_new() before resetting the VMA. Link: https://lore.kernel.org/20261031-uffd-prot-bits-fork-event-v2-1-c448e57df417@kernel.org Fixes: f369b07c8614 ("mm/uffd: reset write protection when unregister with wp-mode") Signed-off-by: Mike Rapoport (Microsoft) Signed-off-by: Andrew Morton Reviewed-by: Jose A. Perez de Azpillaga Tested-by: Jose A. Perez de Azpillaga Reviewed-by: Tal Zussman Tested-by: Tal Zussman Cc: Peter Xu Cc: --- mm/userfaultfd.c | 47 ++++++++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index 169f681f9849b4..83ae65394cd4e4 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -2192,6 +2192,32 @@ static void userfaultfd_reset_ctx(struct vm_area_struct *vma) userfaultfd_set_ctx(vma, NULL, 0); } +/* + * Clear uffd state from a WP or RWP range: the uffd bit, WP markers and + * RWP PAGE_NONE entries. Call this before dropping the registration, as it + * needs the VMA flags to know what to resolve. + */ +static void userfaultfd_clear_ptes(struct vm_area_struct *vma, + unsigned long start, unsigned long end) +{ + unsigned int mm_cp_flags = 0; + struct mmu_gather tlb; + + if (!userfaultfd_protected(vma)) + return; + + if (userfaultfd_wp(vma)) + mm_cp_flags |= MM_CP_UFFD_WP_RESOLVE; + if (userfaultfd_rwp(vma)) + mm_cp_flags |= MM_CP_UFFD_RWP_RESOLVE; + if (vma_wants_manual_pte_write_upgrade(vma)) + mm_cp_flags |= MM_CP_TRY_CHANGE_WRITABLE; + + tlb_gather_mmu(&tlb, vma->vm_mm); + change_protection(&tlb, vma, start, end, mm_cp_flags); + tlb_finish_mmu(&tlb); +} + static struct vm_area_struct *userfaultfd_clear_vma(struct vma_iterator *vmi, struct vm_area_struct *prev, struct vm_area_struct *vma, @@ -2211,22 +2237,7 @@ static struct vm_area_struct *userfaultfd_clear_vma(struct vma_iterator *vmi, if (start == vma->vm_start && end == vma->vm_end) give_up_on_oom = true; - /* Clear the uffd bit and/or restore protnone PTEs */ - if (userfaultfd_protected(vma)) { - unsigned int mm_cp_flags = 0; - struct mmu_gather tlb; - - if (userfaultfd_wp(vma)) - mm_cp_flags |= MM_CP_UFFD_WP_RESOLVE; - if (userfaultfd_rwp(vma)) - mm_cp_flags |= MM_CP_UFFD_RWP_RESOLVE; - if (vma_wants_manual_pte_write_upgrade(vma)) - mm_cp_flags |= MM_CP_TRY_CHANGE_WRITABLE; - - tlb_gather_mmu(&tlb, vma->vm_mm); - change_protection(&tlb, vma, start, end, mm_cp_flags); - tlb_finish_mmu(&tlb); - } + userfaultfd_clear_ptes(vma, start, end); ret = vma_modify_flags_uffd(vmi, prev, vma, start, end, &new_vma_flags, NULL_VM_UFFD_CTX, @@ -2335,8 +2346,10 @@ static void userfaultfd_release_new(struct userfaultfd_ctx *ctx) /* the various vma->vm_userfaultfd_ctx still points to it */ mmap_write_lock(mm); for_each_vma(vmi, vma) { - if (vma->vm_userfaultfd_ctx.ctx == ctx) + if (vma->vm_userfaultfd_ctx.ctx == ctx) { + userfaultfd_clear_ptes(vma, vma->vm_start, vma->vm_end); userfaultfd_reset_ctx(vma); + } } mmap_write_unlock(mm); } From f987d9f38a46216d45326b7a61c619c574b45837 Mon Sep 17 00:00:00 2001 From: "Mike Rapoport (Microsoft)" Date: Sun, 1 Nov 2026 10:24:02 +0200 Subject: [PATCH 0409/2102] mm/vma: undo userfaultfd unmap preparation when unmapping fails vms_gather_munmap_vmas() collects VMAs to unmap and calls userfaultfd_unmap_prep() for each of these VMAs. This takes a reference to the userfaultfd context, raises ctx->mmap_changing and queues an UFFD_EVENT_UNMAP on the caller's list. If gathering fails half way, e.g. because one of the VMAs is sealed, or the operation fails after the VMAs were gathered, the original mappings stay intact but the queued events remain on the list. Depending on the caller they are either delivered although nothing was unmapped (munmap(), mremap(), mmap(MAP_FIXED)), or silently dropped (brk()). In the latter case the userfaultfd context and the mm_struct it pins are leaked and mmap_changing is never lowered, so UFFDIO_COPY, UFFDIO_ZEROPAGE and all other ioctls that check mmap_changing fail with -EAGAIN forever. With mseal() this is trivially triggered by an unprivileged process. Collect the events in do_vmi_align_munmap() on a local list and splice it to the caller's list only when the unmap completes, because mremap() may already have events for earlier unmaps on that list. Drop the pending events with a new userfaultfd_unmap_abort() helper when do_vmi_align_munmap() or __mmap_setup() fail. Link: https://lore.kernel.org/20261101-uffd-unmap-abort-v1-1-1588d7a7c61a@kernel.org Fixes: 65ac132027a8 ("userfaultfd: fix regression in userfaultfd_unmap_prep()") Signed-off-by: Mike Rapoport (Microsoft) Signed-off-by: Andrew Morton Reported-by: Noah Weinberger Reviewed-by: Tal Zussman Tested-by: Tal Zussman Cc: Liam R. Howlett Cc: Lorenzo Stoakes Cc: David Hildenbrand Cc: Jann Horn Cc: Pedro Falcato Cc: Peter Xu Cc: Vlastimil Babka Cc: --- include/linux/userfaultfd_k.h | 5 +++++ mm/userfaultfd.c | 19 +++++++++++++++++++ mm/vma.c | 28 +++++++++++++++++++++++----- tools/testing/vma/include/stubs.h | 4 ++++ 4 files changed, 51 insertions(+), 5 deletions(-) diff --git a/include/linux/userfaultfd_k.h b/include/linux/userfaultfd_k.h index dff9a5c9a0dfa4..5768a3902c7c60 100644 --- a/include/linux/userfaultfd_k.h +++ b/include/linux/userfaultfd_k.h @@ -277,6 +277,7 @@ extern int userfaultfd_unmap_prep(struct vm_area_struct *vma, unsigned long start, unsigned long end, struct list_head *uf); extern void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf); +void userfaultfd_unmap_abort(struct list_head *uf); extern bool userfaultfd_wp_unpopulated(struct vm_area_struct *vma); extern bool userfaultfd_wp_async(struct vm_area_struct *vma); extern bool userfaultfd_rwp_async(struct vm_area_struct *vma); @@ -443,6 +444,10 @@ static inline void userfaultfd_unmap_complete(struct mm_struct *mm, { } +static inline void userfaultfd_unmap_abort(struct list_head *uf) +{ +} + static inline bool uffd_disable_fault_around(struct vm_area_struct *vma) { return false; diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index 83ae65394cd4e4..a50dd8b3971e4c 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -3290,6 +3290,25 @@ void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf) } } +void userfaultfd_unmap_abort(struct list_head *uf) +{ + struct userfaultfd_unmap_ctx *unmap_ctx, *n; + + if (!uf) + return; + + list_for_each_entry_safe(unmap_ctx, n, uf, list) { + struct userfaultfd_ctx *ctx = unmap_ctx->ctx; + + atomic_dec(&ctx->mmap_changing); + VM_WARN_ON_ONCE(atomic_read(&ctx->mmap_changing) < 0); + userfaultfd_ctx_put(ctx); + + list_del(&unmap_ctx->list); + kfree(unmap_ctx); + } +} + static int userfaultfd_release(struct inode *inode, struct file *file) { struct userfaultfd_ctx *ctx = file->private_data; diff --git a/mm/vma.c b/mm/vma.c index e38e22a5e752e4..7966d1c60eafb0 100644 --- a/mm/vma.c +++ b/mm/vma.c @@ -1686,9 +1686,18 @@ int do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma, mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK); mt_on_stack(mt_detach); struct vma_munmap_struct vms; + struct list_head *uf_unmaps; + LIST_HEAD(uf_new_unmaps); int error; - init_vma_munmap(&vms, vmi, vma, start, end, uf, unlock); + /* + * @uf may already hold events of earlier successful unmaps, e.g. in + * mremap(). + * Collect new events on a separate list so they can be dropped if this + * unmap fails, and splice them into @uf on success. + */ + uf_unmaps = uf ? &uf_new_unmaps : NULL; + init_vma_munmap(&vms, vmi, vma, start, end, uf_unmaps, unlock); error = vms_gather_munmap_vmas(&vms, &mas_detach); if (error) goto gather_failed; @@ -1698,12 +1707,15 @@ int do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma, goto clear_tree_failed; /* Point of no return */ + if (uf) + list_splice_tail(&uf_new_unmaps, uf); vms_complete_munmap_vmas(&vms, &mas_detach); return 0; clear_tree_failed: reattach_vmas(&mas_detach); gather_failed: + userfaultfd_unmap_abort(&uf_new_unmaps); validate_mm(mm); return error; } @@ -2592,7 +2604,7 @@ static int __mmap_setup(struct mmap_state *map, struct vm_area_desc *desc, if (error) { /* On error VMAs will already have been reattached. */ vms->nr_pages = 0; - return error; + goto abort_unmaps; } map->next = vms->next; @@ -2602,8 +2614,10 @@ static int __mmap_setup(struct mmap_state *map, struct vm_area_desc *desc, } /* Check against address space limit. */ - if (!may_expand_vm(map->mm, &map->vma_flags, map->pglen - vms->nr_pages)) - return -ENOMEM; + if (!may_expand_vm(map->mm, &map->vma_flags, map->pglen - vms->nr_pages)) { + error = -ENOMEM; + goto abort_unmaps; + } /* Private writable mapping: check memory availability. */ if (accountable_mapping(map)) { @@ -2613,7 +2627,7 @@ static int __mmap_setup(struct mmap_state *map, struct vm_area_desc *desc, if (uncharged) { error = security_vm_enough_memory_mm(map->mm, uncharged); if (error) - return error; + goto abort_unmaps; } /* Our new mapping owns the entire charge now. */ @@ -2632,6 +2646,10 @@ static int __mmap_setup(struct mmap_state *map, struct vm_area_desc *desc, set_desc_from_map(desc, map); return 0; + +abort_unmaps: + userfaultfd_unmap_abort(uf); + return error; } static bool map_same_file(struct mmap_state *map) diff --git a/tools/testing/vma/include/stubs.h b/tools/testing/vma/include/stubs.h index 8d030a3ace8485..9f5b8e996abf68 100644 --- a/tools/testing/vma/include/stubs.h +++ b/tools/testing/vma/include/stubs.h @@ -148,6 +148,10 @@ static inline int userfaultfd_unmap_prep(struct vm_area_struct *vma, return 0; } +static inline void userfaultfd_unmap_abort(struct list_head *uf) +{ +} + static inline void mmap_write_downgrade(struct mm_struct *mm) { } From 043b024a416073c4e2927e25168ec640a0f30be7 Mon Sep 17 00:00:00 2001 From: Mauro Carvalho Chehab Date: Wed, 28 Oct 2026 09:09:57 +0100 Subject: [PATCH 0410/2102] mm: memory-failure: update statistics before emitting the trace event Today's rasdaemon-ci run showed a race condition at the page poison logic affecting userspace (rasdaemon): action_result() emits a memory_failure_event before incrementing num_poisoned_pages and updating the per-node memory failure statistics. That causes userspace to read /proc/meminfo to detect HardwareCorrupted trace events to warn if the value exceeds POISON_STAT_THRESHOLD. This works most of the cases, but there is a chance that the value not being updated in time before libtraceevent notification is handled. Root cause is commit e240ac52f7da ("mm/memory-failure.c: simplify num_poisoned_pages_inc/dec") which changed the order of updates. Rasdaemod-ci run up to Oct 27 worked properly, but on today's run, it failed to get the HardwareCorrupted data from /proc/meminfo because it was updated only after trigging the hardware error event: https://mchehab.github.io/rasdaemon-ci/failures/20261028T035110Z-40629018388/daily/aarch64/consumer-poison-page-stat.html E.g. it failed to log this: rasdaemon: Poison page statistics exceeded threshold: 4 kB (threshold: 0 kB) This is important for rasdaemon, as the consumer's action monitors a failed threshold before poisoning pages. So, if the counter doesn't update properly, it will end not poisoning pages at the expected threshold. Link: https://lore.kernel.org/d472a9a3ccfa8c0359d7d7acabed92c8927d8e47.1793174996.git.mchehab+huawei@kernel.org Fixes: e240ac52f7da ("mm/memory-failure.c: simplify num_poisoned_pages_inc/dec") Signed-off-by: Mauro Carvalho Chehab Signed-off-by: Andrew Morton Closes: https://github.com/mchehab/rasdaemon-ci/actions/runs/40629018388 Acked-by: Miaohe Lin Cc: Naoya Horiguchi Cc: zhenwei pi --- mm/memory-failure.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mm/memory-failure.c b/mm/memory-failure.c index 12aa4e52b2bce8..b215312f261b83 100644 --- a/mm/memory-failure.c +++ b/mm/memory-failure.c @@ -1320,13 +1320,13 @@ static bool panic_on_unrecoverable_mf(enum mf_action_page_type type, static int action_result(unsigned long pfn, enum mf_action_page_type type, enum mf_result result) { - trace_memory_failure_event(pfn, type, result); - if (type != MF_MSG_ALREADY_POISONED && type != MF_MSG_PFN_MAP) { num_poisoned_pages_inc(pfn); update_per_node_mf_stats(pfn, result); } + trace_memory_failure_event(pfn, type, result); + pr_err("%#lx: recovery action for %s: %s\n", pfn, action_page_types[type], action_name[result]); From cf5518aa1832d82b391ac2492863ae6a7315827c Mon Sep 17 00:00:00 2001 From: "Jose Fernandez (Anthropic)" Date: Sat, 31 Oct 2026 04:33:59 +0000 Subject: [PATCH 0411/2102] mm/filemap: stop fault-around when the walk steps back filemap_map_pages() can dereference a PTE pointer outside the page table it locked. KASAN has reported this as a use-after-free read [1]. The same path can also write out of bounds. When the stray entry reads as none, the fault-around loop maps a page there with set_pte_range(). Its fault-around loop walks the page cache and moves vmf->pte by the change in index. A lower index moves it back. xas_find() can step back to a lower index when a multi-index entry is split during the walk. [1] fixes xas_find(), but the loop still relies on the walk never stepping back. Stop the fault-around when the walk steps back. ->fault() maps the faulting page if the loop did not. Link: https://lore.kernel.org/20261031-jf-mm-filemap-map-pages-lower-bound-v2-1-21029744e589@linux.dev Link: https://lore.kernel.org/20260904121301.200049-1-krystianmkaniewski@gmail.com [1] Fixes: 6b24ca4a1a8d ("mm: Use multi-index entries in the page cache") Signed-off-by: Jose Fernandez (Anthropic) Signed-off-by: Andrew Morton Reviewed-by: Jan Kara Cc: Matthew Wilcox (Oracle) Cc: David Hildenbrand Cc: Krystian Kaniewski Cc: Pedro Falcato Cc: --- mm/filemap.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/mm/filemap.c b/mm/filemap.c index b04be64a5069f4..371a4bbd06876d 100644 --- a/mm/filemap.c +++ b/mm/filemap.c @@ -3968,6 +3968,13 @@ vm_fault_t filemap_map_pages(struct vm_fault *vmf, unsigned long end; vm_fault_t map_ret; + /* A lower index could move vmf->pte out of its page table. */ + if (unlikely(xas.xa_index < last_pgoff)) { + folio_unlock(folio); + folio_put(folio); + break; + } + addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT; vmf->pte += xas.xa_index - last_pgoff; last_pgoff = xas.xa_index; From 5fe092741502770107a0be7b3885ce55f7761f01 Mon Sep 17 00:00:00 2001 From: Aveline Noir Date: Mon, 2 Nov 2026 06:46:24 -0800 Subject: [PATCH 0412/2102] mm/damon/core: reset watermark wait state on each iteration Patch series "mm/damon: fix watermark state, kunit pid leak and selftest fake pass". Three hotfixes for core, kunit and selftest. Fix kdamond deactivation from missed watermark reset with patch 1. Fix pid leak in kunit test with patch 2. Fix a selftest wrongly passing when it should skip, with patch 3. Note for reviewers. This series is a collection of fixes that were initially developed by different people. Changelog is in each patch. This patch (of 3): Found while reviewing the DAMON source code that if an online commit removes all schemes while kdamond is waiting for watermark activation, the scheme loop becomes empty but min_wait_time keeps the previous positive value. kdamond then keeps sleeping instead of resuming monitoring without schemes. The way to wake up the kdamond again without DAMON is bit complicated. Install a scheme having watermarks that can activate the kdamond again, and remove the scheme again. Doable but cumbersome and complicated. Initialize min_wait_time and init_wait_time on each loop iteration so the wait is calculated from the current schemes and an empty scheme list resumes monitoring. Link: https://lore.kernel.org/20261102144627.88843-1-sj@kernel.org Link: https://lore.kernel.org/20261102144627.88843-2-sj@kernel.org Fixes: da87878010e5 ("mm/damon/sysfs: support online inputs update") Signed-off-by: Aveline Noir Signed-off-by: SJ Park Signed-off-by: Andrew Morton Reviewed-by: SJ Park Cc: Wang Xiaolei Cc: # 5.19.x --- mm/damon/core.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mm/damon/core.c b/mm/damon/core.c index 73b571b429cb34..7441cdea57dc5b 100644 --- a/mm/damon/core.c +++ b/mm/damon/core.c @@ -3976,10 +3976,11 @@ static int kdamond_wait_activation(struct damon_ctx *ctx) { struct damos *s; unsigned long wait_time; - unsigned long min_wait_time = 0; - bool init_wait_time = false; while (!kdamond_need_stop(ctx)) { + unsigned long min_wait_time = 0; + bool init_wait_time = false; + damon_for_each_scheme(s, ctx) { wait_time = damos_wmark_wait_us(s); if (!init_wait_time || wait_time < min_wait_time) { From 9d2cc214935ad78b8f54bf886f0b4e3f387fa44f Mon Sep 17 00:00:00 2001 From: Wang Xiaolei Date: Mon, 2 Nov 2026 06:46:25 -0800 Subject: [PATCH 0413/2102] mm/damon/tests/sysfs-kunit: fix leaked pid reference in add_targets test damon_sysfs_test_add_targets() creates its monitoring context with damon_new_ctx(), which leaves ctx->ops zero-initialized. Since DAMON_OPS_VADDR is zero, damon_target_has_pid() returns true for the context, and damon_sysfs_add_targets() therefore calls damon_set_target_pid() for each target it adds. That function grabs a reference to the target's struct pid via find_get_pid(). The test then tears the context down with damon_destroy_ctx(), which releases such a reference from ctx->ops.cleanup_target(). For the vaddr operations set that callback is damon_va_cleanup_target(), and it is the only place where the reference is put. The test never selects an operations set, though, so cleanup_target is NULL and both references -- one for each of the two damon_sysfs_add_targets() calls -- are leaked on every run of the test. Running the test with CONFIG_DEBUG_KMEMLEAK enabled reports the leaked struct pid objects as unreferenced. Fix this by selecting the vaddr operations set for the context before adding the targets, mirroring what the sysfs interface does. damon_select_ops() fails if the vaddr operations set is not registered, in which case the test cannot exercise the pid handling and skips itself. Link: https://lore.kernel.org/20261102144627.88843-3-sj@kernel.org Fixes: b8ee5575f763 ("mm/damon/sysfs-test: add a unit test for damon_sysfs_set_targets()") Signed-off-by: Wang Xiaolei Signed-off-by: SJ Park Signed-off-by: Andrew Morton Reviewed-by: SJ Park Cc: Michal Hocko Cc: Mike Rapoport Cc: Suren Baghdasaryan Cc: Vlastimil Babka Cc: "Liam R. Howlett" Cc: Brendan Higgins Cc: David Gow Cc: Aveline Noir Cc: # 6.7.x --- mm/damon/tests/sysfs-kunit.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/mm/damon/tests/sysfs-kunit.h b/mm/damon/tests/sysfs-kunit.h index 138a4b8d14e734..16373ba751dbc8 100644 --- a/mm/damon/tests/sysfs-kunit.h +++ b/mm/damon/tests/sysfs-kunit.h @@ -79,6 +79,15 @@ static void damon_sysfs_test_add_targets(struct kunit *test) kunit_skip(test, "ctx alloc fail"); } + if (damon_select_ops(ctx, DAMON_OPS_VADDR)) { + damon_destroy_ctx(ctx); + kfree(sysfs_targets->targets_arr); + kfree(sysfs_targets); + kfree(sysfs_target->regions); + kfree(sysfs_target); + kunit_skip(test, "vaddr ops not registered"); + } + damon_sysfs_add_targets(ctx, sysfs_targets); KUNIT_EXPECT_EQ(test, 1u, nr_damon_targets(ctx)); From c8c47f4072bdcff783cedd5a8565242a212af058 Mon Sep 17 00:00:00 2001 From: SJ Park Date: Mon, 2 Nov 2026 06:46:26 -0800 Subject: [PATCH 0414/2102] selftests/damon/sysfs_memcg_path_leak: define ksft_skip sysfs_memcg_path_leak test uses $ksft_skip without defining it. As a result, the test is marked as passed while it was skipped, like below. $ ./sysfs_memcg_path_leak.sh Run as root $ echo $? 0 Users who run the test could therefore wrongly believe the test was run and passed while it was skipped. Define the value at the beginning of the test. After this patch, the exit code reflects the skip. $ ./sysfs_memcg_path_leak.sh Run as root $ echo $? 4 Link: https://lore.kernel.org/20261102144627.88843-4-sj@kernel.org Fixes: dfa3cf0bc018 ("selftets/damon: add a test for memcg_path leak") Signed-off-by: SJ Park Signed-off-by: Andrew Morton Closes: https://sashiko.dev/#/bug/linux-a0456336-0608-4fec-ac22-0ee61d1d6a91 Reviewed-by: Aveline Noir Tested-by: Aveline Noir Cc: Shuah Khan Cc: Wang Xiaolei Cc: # 6.17.x --- tools/testing/selftests/damon/sysfs_memcg_path_leak.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/testing/selftests/damon/sysfs_memcg_path_leak.sh b/tools/testing/selftests/damon/sysfs_memcg_path_leak.sh index 34c37129c49fe1..d407dddb879ece 100755 --- a/tools/testing/selftests/damon/sysfs_memcg_path_leak.sh +++ b/tools/testing/selftests/damon/sysfs_memcg_path_leak.sh @@ -1,6 +1,9 @@ #!/bin/bash # SPDX-License-Identifier: GPL-2.0 +# Kselftest framework requirement - SKIP code is 4. +ksft_skip=4 + if [ $EUID -ne 0 ] then echo "Run as root" From ccf8bda05b19dc144bc7051936b08573476499ee Mon Sep 17 00:00:00 2001 From: Joas Antonio dos Santos Date: Mon, 2 Nov 2026 13:03:56 +0000 Subject: [PATCH 0415/2102] hugetlbfs: move hugetlbfs_free_inode tracepoint to ->destroy_inode() hugetlbfs_free_inode() calls trace_hugetlbfs_free_inode(), and the hugetlbfs__inode event class records inode->i_sb->s_dev. ->free_inode() runs from an RCU callback (destroy_inode() queues i_callback() with call_rcu()), and Documentation/filesystems/porting.rst says that this callback "is *NOT* ordered wrt superblock destruction; as the matter of fact, the superblock and all associated structures might be already gone". put_super() frees the superblock with call_rcu() followed by a workqueue item (destroy_super_rcu() -> destroy_super_work()). syzbot hit this with the event enabled: BUG: KASAN: slab-use-after-free in trace_event_raw_event_hugetlbfs__inode+0x45b/0x4c0 include/trace/events/hugetlbfs.h:36 Read of size 4 at addr ffff888038850010 by task syz-executor952/6134 hugetlbfs_free_inode+0x15e/0x1f0 fs/hugetlbfs/inode.c:1182 i_callback+0x46/0x80 fs/inode.c:317 rcu_do_batch kernel/rcu/tree.c:2650 [inline] rcu_core+0x5f0/0x1220 kernel/rcu/tree.c:2919 Allocated by task 6134: alloc_super fs/super.c:326 [inline] sget_fc+0x1ba/0x1f60 fs/super.c:874 hugetlbfs_get_tree+0x1e7/0x2b0 fs/hugetlbfs/inode.c:1431 Freed by task 855: kfree+0x22b/0x6d0 mm/slub.c:6923 process_one_work+0xac7/0x1b10 kernel/workqueue.c:3495 Emit the event from hugetlbfs_destroy_inode() instead. destroy_inode() calls ->destroy_inode() synchronously, before it queues the RCU callback, while the superblock is still alive; hugetlbfs_destroy_inode() already dereferences inode->i_sb there. ->free_inode() is left with only the kmem_cache_free(). Since the event no longer fires from ->free_inode(), rename it to hugetlbfs_destroy_inode so that its name matches where it is emitted, as suggested by David and Muchun. Found by syzbot; analysed and tested with the syzbot C reproducer on an arm64 KASAN kernel. Link: https://lore.kernel.org/20261102-b4-hugetlbfs-trace-v4-1-72371825bb5e@gmail.com Fixes: 014ad7c42a69 ("hugetlbfs: use tracepoints in hugetlbfs functions.") Signed-off-by: Joas Antonio dos Santos Signed-off-by: Andrew Morton Reported-by: Closes: https://lore.kernel.org/all/6ae27525.5451848c.f7707.0001.GAE@google.com/ Suggested-by: David Hildenbrand Suggested-by: Muchun Song Reviewed-by: Muchun Song Acked-by: David Hildenbrand (Arm) Cc: Oscar Salvador Cc: Hongbo Li Cc: --- fs/hugetlbfs/inode.c | 2 +- include/trace/events/hugetlbfs.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/fs/hugetlbfs/inode.c b/fs/hugetlbfs/inode.c index 02e0a65d596d86..558007fa5e885b 100644 --- a/fs/hugetlbfs/inode.c +++ b/fs/hugetlbfs/inode.c @@ -1187,12 +1187,12 @@ static struct inode *hugetlbfs_alloc_inode(struct super_block *sb) static void hugetlbfs_free_inode(struct inode *inode) { - trace_hugetlbfs_free_inode(inode); kmem_cache_free(hugetlbfs_inode_cachep, HUGETLBFS_I(inode)); } static void hugetlbfs_destroy_inode(struct inode *inode) { + trace_hugetlbfs_destroy_inode(inode); hugetlbfs_inc_free_inodes(HUGETLBFS_SB(inode->i_sb)); } diff --git a/include/trace/events/hugetlbfs.h b/include/trace/events/hugetlbfs.h index 8ba72c1d4f4d8b..a7932e0db0f88c 100644 --- a/include/trace/events/hugetlbfs.h +++ b/include/trace/events/hugetlbfs.h @@ -72,7 +72,7 @@ DEFINE_EVENT(hugetlbfs__inode, hugetlbfs_evict_inode, TP_ARGS(inode) ); -DEFINE_EVENT(hugetlbfs__inode, hugetlbfs_free_inode, +DEFINE_EVENT(hugetlbfs__inode, hugetlbfs_destroy_inode, TP_PROTO(struct inode *inode), From ff82ce7f90f52254029a73d12542c22e7e705aef Mon Sep 17 00:00:00 2001 From: "Lorenzo Stoakes (ARM)" Date: Mon, 2 Nov 2026 10:25:20 +0000 Subject: [PATCH 0416/2102] mm/vma: read anon_vma carefully in validate_mm() Commit 38564710f443 ("mm: implement and use vma_has_anon_rmap(), silence KCSAN") rather clumsily converted the read of vma->anon_vma into a vma_has_anon_rmap() without accounting for the separation between assignment of anon_vma and later use of it. vma_has_anon_rmap() is intended as an optimistic check, so doesn't need to protect against a torn read in vma->anon_vma. The caller is expected to take care of this themselves if they then in fact access the field. validate_mm() does indeed then reference the field, so resolve the issue via READ_ONCE(), and simplify the code by separating this into a new function validate_mm_anon_rmap(). Finally, add a vma_assert_stabilised() to make it clear the required state of the VMA. [kas@kernel.org: reduce ifdeffery] Link: https://lore.kernel.org/auhn01dpDzK47igy@thinkstation Link: https://lore.kernel.org/20261102-fix-validate_mm-v1-1-5c309614ef15@kernel.org Fixes: 38564710f443 ("mm: implement and use vma_has_anon_rmap(), silence KCSAN") Signed-off-by: Lorenzo Stoakes (ARM) Signed-off-by: Andrew Morton Reported-by: Closes: https://lore.kernel.org/all/6ae78418.6552420f.2a0efc.005c.GAE@google.com/ Reported-by: Songsen Yang Closes: https://lore.kernel.org/all/20261102074414.10902-1-yangsongsen@insta360.com/ Cc: Liam R. Howlett Cc: Vlastimil Babka Cc: Jann Horn Cc: Pedro Falcato Cc: Kiryl Shutsemau Cc: David Hildenbrand Cc: Lance Yang --- include/linux/mm.h | 2 -- mm/vma.c | 34 ++++++++++++++++++++++------------ 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/include/linux/mm.h b/include/linux/mm.h index cb993a1d07284b..d57c61b928f47a 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -4370,9 +4370,7 @@ anon_rmap_tree_iter_first(struct anon_vma *anon_vma, struct anon_vma_chain * anon_rmap_tree_iter_next(struct anon_vma_chain *avc, pgoff_t pgoff_start, pgoff_t pgoff_last); -#ifdef CONFIG_DEBUG_VM_RB void anon_rmap_tree_verify(struct anon_vma_chain *avc); -#endif #define anon_rmap_tree_foreach(avc, anon_vma, pgoff_start, pgoff_last) \ for (avc = anon_rmap_tree_iter_first(anon_vma, pgoff_start, pgoff_last); \ diff --git a/mm/vma.c b/mm/vma.c index 7966d1c60eafb0..c82e9306b11ac1 100644 --- a/mm/vma.c +++ b/mm/vma.c @@ -676,6 +676,26 @@ static int dup_anon_vma(struct vm_area_struct *dst, } #ifdef CONFIG_DEBUG_VM_MAPLE_TREE +static void validate_mm_anon_rmap(struct vm_area_struct *vma) +{ + struct anon_vma *anon_vma; + struct anon_vma_chain *avc; + + if (!IS_ENABLED(CONFIG_DEBUG_VM_RB)) + return; + + vma_assert_stabilised(vma); + + anon_vma = READ_ONCE(vma->anon_vma); + if (!anon_vma) + return; + + anon_vma_lock_read(anon_vma); + list_for_each_entry(avc, &vma->anon_vma_chain, same_vma) + anon_rmap_tree_verify(avc); + anon_vma_unlock_read(anon_vma); +} + void validate_mm(struct mm_struct *mm) { int bug = 0; @@ -685,10 +705,6 @@ void validate_mm(struct mm_struct *mm) mt_validate(&mm->mm_mt); for_each_vma(vmi, vma) { -#ifdef CONFIG_DEBUG_VM_RB - struct anon_vma *anon_vma = vma->anon_vma; - struct anon_vma_chain *avc; -#endif unsigned long vmi_start, vmi_end; bool warn = 0; @@ -709,14 +725,8 @@ void validate_mm(struct mm_struct *mm) vma_iter_dump_tree(&vmi); } -#ifdef CONFIG_DEBUG_VM_RB - if (vma_has_anon_rmap(vma)) { - anon_vma_lock_read(anon_vma); - list_for_each_entry(avc, &vma->anon_vma_chain, same_vma) - anon_rmap_tree_verify(avc); - anon_vma_unlock_read(anon_vma); - } -#endif + validate_mm_anon_rmap(vma); + /* Check for a infinite loop */ if (++i > mm->map_count + 10) { i = -1; From e8a71f284ba7eeddd9475bb0b65200e95428b497 Mon Sep 17 00:00:00 2001 From: "Liam R. Howlett (Google)" Date: Mon, 2 Nov 2026 21:07:22 -0500 Subject: [PATCH 0417/2102] maple_tree: fix rcu reader NULL dereference after the tree is emptied Patch series "maple_tree fixes for 7.3", v2. Two bugs found by an LLM review, and one problem Lorenzo Stoakes reported off list. An RCU reader that restarts after its node dies can dereference NULL if the tree was emptied, or holds a single entry in the root pointer. Patch 1 fixes it and patch 2 adds a test. With CONFIG_DEBUG_MAPLE_TREE, MT_WARN_ON() and the other WARN macros print the tree and call dump_stack() rather than WARN(), so syzbot never sees them. Patch 3 makes them WARN once per call site, after the dump, and makes the BUG macros BUG() after theirs. The userspace tests make WARN() fatal to keep failing as they did on dump_stack(). This patch (of 3): RCU readers may hit a NULL dereference if the tree is emptied while the walker is restarted from a dead node. Avoid the NULL dereference by checking for an emptied/pointer tree (0->ptr, 1-ULONG_MAX -> NULL) and set the maple state limits correctly. A reader of /proc//maps racing with an munmap() of the whole address space can hit this. The first implementation has the same problem in both directions. Initial fix was generated by LLM and sent by Chris Mason in private. [akpm@linux-foundation.org: fix reverse iterator state when the root disappears] Link: https://lore.kernel.org/20261104104137.2058705ac29734a7ab5666c1@linux-foundation.org Link: https://lore.kernel.org/20261103020724.2614498-1-liam@infradead.org Link: https://lore.kernel.org/20261103020724.2614498-2-liam@infradead.org Fixes: 54a611b60590 ("Maple Tree: add new data structure") Signed-off-by: Liam R. Howlett (Google) Signed-off-by: Andrew Morton Reported-by: Chris Mason Cc: Lorenzo Stoakes Cc: Alice Ryhl Cc: Andrew Ballance Cc: --- lib/maple_tree.c | 120 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 93 insertions(+), 27 deletions(-) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index 0b0036c9f84892..f7f51f1b40d931 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -3891,14 +3891,64 @@ static __always_inline void mas_rewalk(struct ma_state *mas, unsigned long index goto retry; } -static __always_inline bool mas_rewalk_if_dead(struct ma_state *mas, - struct maple_node *node, const unsigned long index) +/* + * mas_next_no_node() - Finish a next walk that restarted into a tree without + * nodes. + * @mas: The inactive maple state (ma_none or ma_root) + * + * The arrival here is either because there is a root value or nothing. Either + * way, the next entry is nothing. So set the limits and overwrite the status. + * + * Return: NULL + */ +static inline void *mas_next_no_node(struct ma_state *mas) { - if (unlikely(ma_dead_node(node))) { - mas_rewalk(mas, index); - return true; + if (mas_is_ptr(mas)) + mas->index = 1; + else + mas->index = 0; + + mas->last = ULONG_MAX; + mas->status = ma_none; + return NULL; +} + +/* + * mas_prev_no_node() - Finish a prev walk that restarted into a tree without + * nodes. + * @mas: The inactive maple state (ma_none or ma_root) + * @index: The start of the range the walk left + * @min: The lowest index to return + * + * The arrival here is either because there is a root value or nothing. With + * nothing, leave the limits mas_walk() sets for an empty tree. A root value + * sits at 0: stop on it as mas_prev_setup() does, unless the walk was at 0. + * + * Return: The root entry if @index and @min allow it, NULL otherwise. A node + * if the root changed again since the walk; the caller restarts. + */ +static inline void *mas_prev_no_node(struct ma_state *mas, unsigned long index, + unsigned long min) +{ + void *entry; + + mas->index = 0; + if (mas_is_none(mas)) { + mas->last = ULONG_MAX; + return NULL; } - return false; + + mas->last = 0; + if (!index || min) + return NULL; + + entry = mas_root(mas); + if (!entry) { + mas->status = ma_none; + mas->last = ULONG_MAX; + } + + return entry; } /* @@ -4006,14 +4056,14 @@ static void *mas_prev_slot(struct ma_state *mas, unsigned long min, bool empty) node = mas_mn(mas); type = mte_node_type(mas->node); pivots = ma_pivots(node, type); - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (mas->min <= min) { pivot = mas_safe_min(mas, pivots, mas->offset); - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (pivot <= min) goto underflow; @@ -4028,10 +4078,8 @@ static void *mas_prev_slot(struct ma_state *mas, unsigned long min, bool empty) if (mas->index <= min) goto underflow; - if (mas_prev_node(mas, min)) { - mas_rewalk(mas, save_point); - goto retry; - } + if (mas_prev_node(mas, min)) + goto dead; if (WARN_ON_ONCE(mas_is_underflow(mas))) return NULL; @@ -4045,8 +4093,8 @@ static void *mas_prev_slot(struct ma_state *mas, unsigned long min, bool empty) slots = ma_slots(node, type); entry = mas_slot(mas, slots, mas->offset); - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (likely(entry)) return entry; @@ -4063,6 +4111,17 @@ static void *mas_prev_slot(struct ma_state *mas, unsigned long min, bool empty) underflow: mas->status = ma_underflow; return NULL; + +dead: + mas_rewalk(mas, save_point); + if (likely(mas_is_active(mas))) + goto retry; + + entry = mas_prev_no_node(mas, save_point, min); + if (unlikely(xa_is_node(entry))) /* The root changed again */ + goto dead; + + return entry; } /* @@ -4176,8 +4235,8 @@ static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty) node = mas_mn(mas); type = mte_node_type(mas->node); pivots = ma_pivots(node, type); - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (mas->max >= max) { if (likely(mas->offset < mas->end)) @@ -4185,8 +4244,8 @@ static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty) else pivot = mas->max; - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (pivot >= max) { /* Was at the limit, next will extend beyond */ mas->status = ma_overflow; @@ -4208,10 +4267,8 @@ static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty) return NULL; } - if (mas_next_node(mas, node, max)) { - mas_rewalk(mas, save_point); - goto retry; - } + if (mas_next_node(mas, node, max)) + goto dead; if (WARN_ON_ONCE(mas_is_overflow(mas))) return NULL; @@ -4226,8 +4283,8 @@ static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty) slots = ma_slots(node, type); entry = mt_slot(mas->tree, slots, mas->offset); - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (entry) return entry; @@ -4244,6 +4301,13 @@ static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty) } return entry; + +dead: + mas_rewalk(mas, save_point); + if (likely(mas_is_active(mas))) + goto retry; + + return mas_next_no_node(mas); } /* @@ -5450,7 +5514,9 @@ void *mas_find(struct ma_state *mas, unsigned long max) /* Retries on dead nodes handled by mas_next_slot */ entry = mas_next_slot(mas, max, false); /* Ignore overflow */ - mas->status = ma_active; + if (mas_is_overflow(mas)) + mas->status = ma_active; + return entry; } EXPORT_SYMBOL_GPL(mas_find); From d46ba9f99dbafe936a2810bfac505f7dc339d7b8 Mon Sep 17 00:00:00 2001 From: "Liam R. Howlett (Google)" Date: Mon, 2 Nov 2026 21:07:23 -0500 Subject: [PATCH 0418/2102] maple_tree: test emptying tree while RCU reading Add a test case for the rcu reader being restarted by emptying the tree. A reverse walk from index 0 must not return the new root entry. Link: https://lore.kernel.org/20261103020724.2614498-3-liam@infradead.org Signed-off-by: Liam R. Howlett (Google) Signed-off-by: Andrew Morton Cc: Lorenzo Stoakes Cc: Chris Mason Cc: Alice Ryhl Cc: Andrew Ballance --- lib/test_maple_tree.c | 165 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 165 insertions(+) diff --git a/lib/test_maple_tree.c b/lib/test_maple_tree.c index fb40e193a3cb76..10e5577ea0f190 100644 --- a/lib/test_maple_tree.c +++ b/lib/test_maple_tree.c @@ -3740,6 +3740,170 @@ static noinline void __init check_range64_in_rcu(struct maple_tree *mt) rcu_barrier(); } +/* + * A reader that restarts after its leaf died may find a tree without nodes: + * emptied, or emptied and then given a single entry at 0. Each case starts + * from a tree with nodes, built by check_seq(). The stores run while the + * reader holds rcu_read_lock, so they use GFP_ATOMIC. + */ +static noinline void __init check_restart_no_node(struct maple_tree *mt) +{ + void *ptr = xa_mk_value(1234); + void *entry; + MA_STATE(mas, mt, 0, 0); + + MT_BUG_ON(mt, !mtree_empty(mt)); + mt_set_non_kernel(99999); + + /* find: the tree is emptied */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, 0); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != xa_mk_value(0)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != ULONG_MAX); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* next: the tree is emptied */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, 0); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != xa_mk_value(0)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + entry = mas_next(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != ULONG_MAX); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* find: the tree is emptied, then holds one entry at 0 */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, 0); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != xa_mk_value(0)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + MT_BUG_ON(mt, mtree_store(mt, 0, ptr, GFP_ATOMIC)); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + MT_BUG_ON(mt, mas.index != 1); + MT_BUG_ON(mt, mas.last != ULONG_MAX); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* find_rev: the tree is emptied */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, ULONG_MAX); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != xa_mk_value(100)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != ULONG_MAX); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* prev: the tree is emptied, then holds one entry at 0 */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, ULONG_MAX); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != xa_mk_value(100)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + MT_BUG_ON(mt, mtree_store(mt, 0, ptr, GFP_ATOMIC)); + entry = mas_prev(&mas, 0); + MT_BUG_ON(mt, entry != ptr); + MT_BUG_ON(mt, mas.status != ma_root); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != 0); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* find_rev: the entry at 0 is below the minimum */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, ULONG_MAX); + entry = mas_find_rev(&mas, 1); + MT_BUG_ON(mt, entry != xa_mk_value(100)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + MT_BUG_ON(mt, mtree_store(mt, 0, ptr, GFP_ATOMIC)); + entry = mas_find_rev(&mas, 1); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_root); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != 0); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* find_rev: the reader is at 0 when the tree gets one entry at 0 */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, 0); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != xa_mk_value(0)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + MT_BUG_ON(mt, mtree_store(mt, 0, ptr, GFP_ATOMIC)); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_root); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != 0); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* find_range_rev: the reader is at 0 when the tree gets one entry at 0 */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, 0); + entry = mas_find_range_rev(&mas, 0); + MT_BUG_ON(mt, entry != xa_mk_value(0)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + MT_BUG_ON(mt, mtree_store(mt, 0, ptr, GFP_ATOMIC)); + entry = mas_find_range_rev(&mas, 0); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_root); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != 0); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + mt_set_non_kernel(0); +} + static DEFINE_MTREE(tree); static int __init maple_tree_seed(void) { @@ -4031,6 +4195,7 @@ static int __init maple_tree_seed(void) check_range64_in_rcu(&tree); + check_restart_no_node(&tree); #if defined(BENCH) skip: From f51d35b81fb572c551e82ff72575d6dbb8e35ba9 Mon Sep 17 00:00:00 2001 From: "Liam R. Howlett (Google)" Date: Mon, 2 Nov 2026 21:07:24 -0500 Subject: [PATCH 0419/2102] maple_tree: update internal warning and bug_on code When CONFIG_DEBUG_MAPLE_TREE is set, call WARN_ON() once per site after the custom information is dumped about the tree. Without using the kernel's WARN_ON calls, syzbot will not catch issues detected by this code. The BUG_ON variants now stop instead of dumping and continuing. Update the non-debug code to call WARN_ON_ONCE() as well. The userspace tests asserted on dump_stack() but only print on WARN_ON(), so make WARN() fatal in maple-shared.h and have the maple test exit with the result of maple_tree_seed(). Link: https://lore.kernel.org/20261103020724.2614498-4-liam@infradead.org Fixes: f0a1f866aba1 ("maple_tree: add debug BUG_ON and WARN_ON variants") Signed-off-by: Liam R. Howlett (Google) Signed-off-by: Andrew Morton Reported-by: Lorenzo Stoakes Reviewed-by: Lorenzo Stoakes (ARM) Cc: Chris Mason Cc: Alice Ryhl Cc: Andrew Ballance Cc: --- include/linux/maple_tree.h | 48 ++++++++++++++--------------- tools/testing/radix-tree/maple.c | 13 +++++--- tools/testing/shared/maple-shared.h | 33 ++++++++++++++++++++ 3 files changed, 66 insertions(+), 28 deletions(-) diff --git a/include/linux/maple_tree.h b/include/linux/maple_tree.h index 691f6012daea37..3892201d7efd5f 100644 --- a/include/linux/maple_tree.h +++ b/include/linux/maple_tree.h @@ -684,7 +684,7 @@ void mt_cache_shrink(void); pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ + BUG_ON(1); \ } else { \ atomic_inc(&maple_tree_tests_passed); \ } \ @@ -700,7 +700,7 @@ void mt_cache_shrink(void); pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ + BUG_ON(1); \ } else { \ atomic_inc(&maple_tree_tests_passed); \ } \ @@ -717,7 +717,7 @@ void mt_cache_shrink(void); pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ + BUG_ON(1); \ } else { \ atomic_inc(&maple_tree_tests_passed); \ } \ @@ -726,16 +726,16 @@ void mt_cache_shrink(void); #define MT_WARN_ON(__tree, __x) ({ \ int ret = !!(__x); \ atomic_inc(&maple_tree_tests_run); \ - if (ret) { \ - pr_info("WARN at %s:%d (%u)\n", \ - __func__, __LINE__, __x); \ + if (!ret) { \ + atomic_inc(&maple_tree_tests_passed); \ + } else if (__ONCE_LITE_IF(ret)) { \ + pr_info("WARN at %s:%d\n", \ + __func__, __LINE__); \ mt_dump(__tree, mt_dump_hex); \ pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ - } else { \ - atomic_inc(&maple_tree_tests_passed); \ + WARN_ON(1); \ } \ unlikely(ret); \ }) @@ -743,17 +743,17 @@ void mt_cache_shrink(void); #define MAS_WARN_ON(__mas, __x) ({ \ int ret = !!(__x); \ atomic_inc(&maple_tree_tests_run); \ - if (ret) { \ - pr_info("WARN at %s:%d (%u)\n", \ - __func__, __LINE__, __x); \ + if (!ret) { \ + atomic_inc(&maple_tree_tests_passed); \ + } else if (__ONCE_LITE_IF(ret)) { \ + pr_info("WARN at %s:%d\n", \ + __func__, __LINE__); \ mas_dump(__mas); \ mt_dump((__mas)->tree, mt_dump_hex); \ pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ - } else { \ - atomic_inc(&maple_tree_tests_passed); \ + WARN_ON(1); \ } \ unlikely(ret); \ }) @@ -761,18 +761,18 @@ void mt_cache_shrink(void); #define MAS_WR_WARN_ON(__wrmas, __x) ({ \ int ret = !!(__x); \ atomic_inc(&maple_tree_tests_run); \ - if (ret) { \ - pr_info("WARN at %s:%d (%u)\n", \ - __func__, __LINE__, __x); \ + if (!ret) { \ + atomic_inc(&maple_tree_tests_passed); \ + } else if (__ONCE_LITE_IF(ret)) { \ + pr_info("WARN at %s:%d\n", \ + __func__, __LINE__); \ mas_wr_dump(__wrmas); \ mas_dump((__wrmas)->mas); \ mt_dump((__wrmas)->mas->tree, mt_dump_hex); \ pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ - } else { \ - atomic_inc(&maple_tree_tests_passed); \ + WARN_ON(1); \ } \ unlikely(ret); \ }) @@ -780,9 +780,9 @@ void mt_cache_shrink(void); #define MT_BUG_ON(__tree, __x) BUG_ON(__x) #define MAS_BUG_ON(__mas, __x) BUG_ON(__x) #define MAS_WR_BUG_ON(__mas, __x) BUG_ON(__x) -#define MT_WARN_ON(__tree, __x) WARN_ON(__x) -#define MAS_WARN_ON(__mas, __x) WARN_ON(__x) -#define MAS_WR_WARN_ON(__mas, __x) WARN_ON(__x) +#define MT_WARN_ON(__tree, __x) WARN_ON_ONCE(__x) +#define MAS_WARN_ON(__mas, __x) WARN_ON_ONCE(__x) +#define MAS_WR_WARN_ON(__mas, __x) WARN_ON_ONCE(__x) #endif /* CONFIG_DEBUG_MAPLE_TREE */ /** diff --git a/tools/testing/radix-tree/maple.c b/tools/testing/radix-tree/maple.c index bfe4b8626c429d..846c67e20e82ae 100644 --- a/tools/testing/radix-tree/maple.c +++ b/tools/testing/radix-tree/maple.c @@ -36502,22 +36502,27 @@ static void regression_tests(void) test_spanning_store_regression(); } -void maple_tree_tests(void) +int maple_tree_tests(void) { + int ret; + #if !defined(BENCH) regression_tests(); farmer_tests(); #endif - maple_tree_seed(); + ret = maple_tree_seed(); maple_tree_harvest(); + return ret; } int __weak main(void) { + int ret; + maple_tree_init(); - maple_tree_tests(); + ret = maple_tree_tests(); rcu_barrier(); if (nr_allocated) printf("nr_allocated = %d\n", nr_allocated); - return 0; + return ret ? EXIT_FAILURE : EXIT_SUCCESS; } diff --git a/tools/testing/shared/maple-shared.h b/tools/testing/shared/maple-shared.h index 2a1e9a8594a283..5f827709773a07 100644 --- a/tools/testing/shared/maple-shared.h +++ b/tools/testing/shared/maple-shared.h @@ -8,6 +8,7 @@ #include "shared.h" #include #include +#include #include "linux/init.h" void maple_rcu_cb(struct rcu_head *head); @@ -20,5 +21,37 @@ do { \ call_rcu(&((_p_struct)->_memb), rcu_cb); \ } while(0); +/* Make WARN() fatal */ +#undef WARN +#undef WARN_ON +#undef WARN_ONCE +#undef WARN_ON_ONCE +#define WARN(condition, format...) ({ \ + int __ret_warn_on = !!(condition); \ + if (unlikely(__ret_warn_on)) { \ + __WARN_printf(format); \ + assert(0); \ + } \ + unlikely(__ret_warn_on); \ +}) +#define WARN_ON(condition) \ + WARN(condition, "assertion failed at %s:%d\n", __FILE__, __LINE__) +#define WARN_ONCE(condition, format...) WARN(condition, format) +#define WARN_ON_ONCE(condition) WARN_ON(condition) + +/* Once state for the debug macros */ +#ifndef __ONCE_LITE_IF +#define __ONCE_LITE_IF(condition) \ + ({ \ + static bool __already_done; \ + bool __ret_once = false; \ + \ + if ((condition) && !__already_done) { \ + __already_done = true; \ + __ret_once = true; \ + } \ + __ret_once; \ + }) +#endif #endif /* __MAPLE_SHARED_H__ */ From 28ae0385b638f095109d282b927ac1a51f75c530 Mon Sep 17 00:00:00 2001 From: Umang Pokhriyal Date: Wed, 4 Nov 2026 15:04:57 +0530 Subject: [PATCH 0420/2102] userfaultfd: validate the whole range before changing write protection mwriteprotect_range() checks each VMA as it walks the range. When a later VMA is not registered for write protection, or is a hugetlb VMA the range is not aligned to, the call fails after the earlier VMAs were already changed. When unprotecting, userfaultfd_writeprotect() then skips wake_userfault(), so threads blocked on those pages are not woken although the pages are writable again. An unprivileged process can trigger this with a range that spans an unregistered VMA. It hasn't been seen in practice; it was found while reviewing the userfaultfd range ioctls with an LLM. Validate the whole range first, as mrwprotect_range() already does. Link: https://lore.kernel.org/20261104093457.152245-1-umangpokhriyall@gmail.com Fixes: a1b92a3f1498 ("mm/userfaultfd: support WP on multiple VMAs") Signed-off-by: Umang Pokhriyal Signed-off-by: Andrew Morton Reviewed-by: Mike Rapoport (Microsoft) Cc: Peter Xu Cc: David Hildenbrand Cc: Lorenzo Stoakes Cc: Liam R. Howlett Cc: Vlastimil Babka Cc: Suren Baghdasaryan Cc: Michal Hocko Cc: --- mm/userfaultfd.c | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index a50dd8b3971e4c..08fcc9d0174650 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -1105,21 +1105,26 @@ static int mwriteprotect_range(struct userfaultfd_ctx *ctx, unsigned long start, if (atomic_read(&ctx->mmap_changing)) goto out_unlock; + /* + * Validate every spanned VMA before changing any of them, so an + * invalid range is rejected without changing part of it. + */ err = -ENOENT; for_each_vma_range(vmi, dst_vma, end) { - - if (!userfaultfd_wp(dst_vma)) { - err = -ENOENT; - break; - } + if (!userfaultfd_wp(dst_vma)) + goto out_unlock; if (vma_is_hugetlb(dst_vma)) { - err = -EINVAL; page_mask = vma_kernel_pagesize(dst_vma) - 1; - if ((start & page_mask) || (len & page_mask)) - break; + if ((start & page_mask) || (len & page_mask)) { + err = -EINVAL; + goto out_unlock; + } } + } + vma_iter_set(&vmi, start); + for_each_vma_range(vmi, dst_vma, end) { _start = max(dst_vma->vm_start, start); _end = min(dst_vma->vm_end, end); From a4e667346a8d91e629a2ca9affc70dc28978f4a1 Mon Sep 17 00:00:00 2001 From: Krystian Kaniewski Date: Fri, 4 Sep 2026 14:12:59 +0200 Subject: [PATCH 0421/2102] xarray: fix index jumping backwards in xas_find() A bug in the XArray iterator xas_find() causes the iterator's index (xas->xa_index) to jump backwards when iterating over a multi-index entry (like a THP) that resides in a non-leaf node and is concurrently split. When iterating over a multi-index entry in a non-leaf node, xas_load() sets xas->xa_offset to the base offset of the entry, but leaves xas->xa_index at the requested index. When the caller subsequently wants to advance to the next entry, xas_find() is called. xas_find() attempts to synchronize xas->xa_offset with xas->xa_index before advancing. However, the fixup logic was incorrectly restricted to leaf nodes (!xas->xa_node->shift). Because the THP resides in a non-leaf node, the fixup is skipped. As a result, xas_find() simply increments xas->xa_offset and recalculates xas->xa_index based on this new offset. This causes xas->xa_index to jump backwards. If the THP was concurrently split, the entry at the new offset is a node pointer, so xas_find() descends into it and returns the folio at the backwards index. The caller (filemap_map_pages()) then calculates the PTE pointer based on this backwards index, resulting in an invalid memory access such as an out-of-bounds read or use-after-free on a page-table page freed via tlb_remove_table_rcu(). A userspace access that faults in a file-backed mapping can trigger this path. When the index moves backwards, filemap_map_pages() can calculate a PTE outside the page locked for fault-around and dereference a freed page-table page, resulting in a KASAN-detected use-after-free read. To fix this, check if xas->xa_offset matches get_offset(xas->xa_index, xas->xa_node). If it does not and the node is a non-leaf node, set xas->xa_offset to get_offset(xas->xa_index, xas->xa_node) before advancing. Also add test cases in test_xarray to verify xas_find() behavior when iterating over and splitting multi-index entries. Link: https://lore.kernel.org/20260904121301.200049-1-krystianmkaniewski@gmail.com Fixes: b803b42823d0 ("xarray: Add XArray iterators") Reported-by: syzbot+b72767277f29b6407083@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=b72767277f29b6407083 Closes: https://syzkaller.appspot.com/ai_job?id=a01c56bd-74d0-411c-afb4-ee6f0cb6cb61 Signed-off-by: Krystian Kaniewski Signed-off-by: Andrew Morton Tested-by: Jose Fernandez (Anthropic) Link: https://lore.kernel.org/20261104-jf-filemap-v2-pedro-reply-r2-74c87c6fbcf@linux.dev Cc: Matthew Wilcox (Oracle) Cc: Mike Rapoport Cc: --- lib/test_xarray.c | 70 +++++++++++++++++++++++++++++++++++++++++++++++ lib/xarray.c | 8 ++++-- 2 files changed, 75 insertions(+), 3 deletions(-) diff --git a/lib/test_xarray.c b/lib/test_xarray.c index 5ca0aefee9aa5f..615f7730a5bd4a 100644 --- a/lib/test_xarray.c +++ b/lib/test_xarray.c @@ -1247,6 +1247,75 @@ static noinline void check_multi_find_3(struct xarray *xa) } } +static noinline void check_multi_find_4(struct xarray *xa) +{ +#ifdef CONFIG_XARRAY_MULTI + unsigned int order = XA_CHUNK_SHIFT + 1; + unsigned long next = 1UL << order; + unsigned long start = next - 1; + XA_STATE(xas, xa, start); + XA_STATE_ORDER(split, xa, 0, 0); + void *entry; + unsigned long i; + + /* Multi-index entry in two slots of a non-leaf node. */ + xa_store_order(xa, 0, order, xa_mk_index(0), GFP_KERNEL); + XA_BUG_ON(xa, xa_store_index(xa, next, GFP_KERNEL) != NULL); + + rcu_read_lock(); + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != xa_mk_index(0)); + XA_BUG_ON(xa, xas.xa_index != start); + + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != xa_mk_index(next)); + XA_BUG_ON(xa, xas.xa_index != next); + + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != NULL); + rcu_read_unlock(); + + xa_erase_index(xa, next); + xa_erase_index(xa, 0); + XA_BUG_ON(xa, !xa_empty(xa)); + + /* Split the multi-index entry after a lookup begins inside it. */ + xa_store_order(xa, 0, order, xa_mk_index(0), GFP_KERNEL); + XA_BUG_ON(xa, xa_store_index(xa, next, GFP_KERNEL) != NULL); + + xas_set(&xas, start); + rcu_read_lock(); + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != xa_mk_index(0)); + XA_BUG_ON(xa, xas.xa_index != start); + rcu_read_unlock(); + + xas_split_alloc(&split, xa_mk_index(0), order, GFP_KERNEL); + if (xas_error(&split)) { + XA_BUG_ON(xa, true); + goto out; + } + xas_lock(&split); + xas_split(&split, xa_mk_index(0), order); + for (i = 0; i < next; i++) + __xa_store(xa, i, xa_mk_index(i), 0); + xas_unlock(&split); + + rcu_read_lock(); + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != xa_mk_index(next)); + XA_BUG_ON(xa, xas.xa_index != next); + + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != NULL); + rcu_read_unlock(); + +out: + xa_destroy(xa); + XA_BUG_ON(xa, !xa_empty(xa)); +#endif +} + static noinline void check_find_1(struct xarray *xa) { unsigned long i, j, k; @@ -1370,6 +1439,7 @@ static noinline void check_find(struct xarray *xa) check_multi_find_1(xa, i); check_multi_find_2(xa); check_multi_find_3(xa); + check_multi_find_4(xa); } /* See find_swap_entry() in mm/shmem.c */ diff --git a/lib/xarray.c b/lib/xarray.c index ae9d7fc68861c8..48f440d114e15f 100644 --- a/lib/xarray.c +++ b/lib/xarray.c @@ -1410,9 +1410,11 @@ void *xas_find(struct xa_state *xas, unsigned long max) entry = xas_load(xas); if (entry || xas_not_node(xas->xa_node)) return entry; - } else if (!xas->xa_node->shift && - xas->xa_offset != (xas->xa_index & XA_CHUNK_MASK)) { - xas->xa_offset = ((xas->xa_index - 1) & XA_CHUNK_MASK) + 1; + } else if (xas->xa_offset != get_offset(xas->xa_index, xas->xa_node)) { + if (!xas->xa_node->shift) + xas->xa_offset = ((xas->xa_index - 1) & XA_CHUNK_MASK) + 1; + else + xas->xa_offset = get_offset(xas->xa_index, xas->xa_node); } xas_next_offset(xas); From 369726f6be714852f4e73882a351938bd3f8c4cd Mon Sep 17 00:00:00 2001 From: Christoph Hellwig Date: Tue, 3 Nov 2026 15:08:09 +0100 Subject: [PATCH 0422/2102] xfs: always call xfs_update_stable_writes in xfs_ioctl_setattr_xflags Currently xfs_update_stable_writes() is never called when the RT flag is flipped because xfs_ioctl_setattr_xflags() updates ip->i_diflags before comparing the rtflag variable to XFS_IS_REALTIME_INODE(ip), and thus the stable flag can be set incorretly when flipping the realtime bit on an existing file. Fix this by unconditionally calling xfs_update_stable_writes for regular files. Fixes: d528a6c1d4b6 ("xfs: data checksums require stable writes") Reported-by: Wilfred Mallawa Signed-off-by: Christoph Hellwig Reviewed-by: Carlos Maiolino Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_ioctl.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/xfs/xfs_ioctl.c b/fs/xfs/xfs_ioctl.c index f81b6e52ac403d..36ba609a2593ad 100644 --- a/fs/xfs/xfs_ioctl.c +++ b/fs/xfs/xfs_ioctl.c @@ -595,7 +595,7 @@ xfs_ioctl_setattr_xflags( * Make the stable writes flag match that of the device the inode * resides on when flipping the RT flag. */ - if (rtflag != XFS_IS_REALTIME_INODE(ip) && S_ISREG(VFS_I(ip)->i_mode)) + if (S_ISREG(VFS_I(ip)->i_mode)) xfs_update_stable_writes(ip); xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG); From 8190880c904fd8ddb943d808e04b12174ce660f8 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Mon, 9 Nov 2026 18:51:12 -0500 Subject: [PATCH 0423/2102] xfs: don't skip the flush before shifting extents On an XFS file larger than 4 EiB, collapse range and insert range can drop dirty data without writing it back, and then fail with EFSCORRUPTED. xfs_prepare_shift() flushes the page cache from its offset to EOF, but passes i_size as the length. Above 4 EiB the end of that range can overflow and turn negative. filemap_write_and_wait_range() then writes nothing, but truncate_pagecache_range() takes the end as unsigned and drops every folio from the start of the range onward. A delalloc extent under a dropped folio stays in the data fork, and the shift returns -EFSCORRUPTED for it. The fix used here is to pass i_size - offset as the length. Fixes: 7f9f71be84bc ("xfs: extent shifting doesn't fully invalidate page cache") Fixes: feeb9b269523 ("filemap: skip write and wait if end offset precedes start") Signed-off-by: Chris Mason Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_bmap_util.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/xfs/xfs_bmap_util.c b/fs/xfs/xfs_bmap_util.c index 865aec3ae5ab32..537c6b29417cc7 100644 --- a/fs/xfs/xfs_bmap_util.c +++ b/fs/xfs/xfs_bmap_util.c @@ -980,7 +980,7 @@ xfs_prepare_shift( * Writeback and invalidate cache for the remainder of the file as we're * about to shift down every extent from offset to EOF. */ - error = xfs_flush_unmap_range(ip, offset, XFS_ISIZE(ip)); + error = xfs_flush_unmap_range(ip, offset, XFS_ISIZE(ip) - offset); if (error) return error; From d467837a485c3b811b94f4005825a05f1535adb3 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Mon, 9 Nov 2026 18:51:13 -0500 Subject: [PATCH 0424/2102] xfs: flush the shifted range before changing the file If writeback of the range to be shifted fails, collapse range on XFS can fail with its hole already punched, and insert range with the file already grown. Both calls change the file first: collapse range punches its hole, and insert range grows i_size. Only then does xfs_prepare_shift() flush the range from the offset to EOF, and that flush fails if the writeback fails. The fix used here is to flush and invalidate that range before the file is changed. Signed-off-by: Chris Mason Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_file.c | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/fs/xfs/xfs_file.c b/fs/xfs/xfs_file.c index 396aca8c66a90a..be1f775128d11f 100644 --- a/fs/xfs/xfs_file.c +++ b/fs/xfs/xfs_file.c @@ -1201,6 +1201,22 @@ xfs_falloc_setsize( &iattr); } +/* + * Collapse and insert range change the file in several steps, and each step + * writes back and empties the part of the page cache that it needs. That can + * fail. Do it here for everything that is going to move, before the first + * step, so that a failure leaves the file as it was. xfs_prepare_shift() + * starts one allocation unit before the offset, so do the same. + */ +static int +xfs_falloc_flush_shift_range( + struct xfs_inode *ip, + loff_t offset) +{ + offset -= min_t(loff_t, offset, xfs_inode_alloc_unitsize(ip)); + return xfs_flush_unmap_range(ip, offset, XFS_ISIZE(ip) - offset); +} + static int xfs_falloc_collapse_range( struct file *file, @@ -1222,6 +1238,10 @@ xfs_falloc_collapse_range( if (offset + len >= i_size_read(inode)) return -EINVAL; + error = xfs_falloc_flush_shift_range(XFS_I(inode), offset); + if (error) + return error; + error = xfs_collapse_file_space(XFS_I(inode), offset, len, ac); if (error) return error; @@ -1263,9 +1283,10 @@ xfs_falloc_insert_range( * fork. This shifts back out beyond EOF, but creates an expectedly * written post-eof block. The insert is going to flush, unmap and * cancel prealloc across this whole range, so flush EOF now before we - * bump i_size to provide consistent behavior. + * bump i_size to provide consistent behavior. Flush and unmap the rest + * of the range as well, so that a failure to do so leaves i_size alone. */ - error = filemap_write_and_wait_range(inode->i_mapping, isize, isize); + error = xfs_falloc_flush_shift_range(XFS_I(inode), offset); if (error) return error; From a38c5aadc06a3277aa2bbdfa0d5161038ae1f4ff Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Mon, 9 Nov 2026 18:51:14 -0500 Subject: [PATCH 0425/2102] xfs: don't change the block map under a dirty folio With CONFIG_TRANSPARENT_HUGEPAGE=y, writeback on XFS can write in place to a shared block and corrupt the other file that shares it. xfs_map_blocks() writes in place unless the COW fork has an extent for the block. write() and write faults reserve one before they dirty a folio over a shared block, so xfs_flush_unmap_range() writes back and truncates the range before a clone changes the block map. But the holder of a GUP write pin takes no filesystem lock, and the truncate keeps a large dirty folio that straddles the range: clone pin holder writeback ===== ========== ========= writes the range back dirties the folio truncate keeps the folio maps a shared block under it dirties it again finds no COW extent writes in place /* shared block */ The fix used here is to invalidate the range instead of truncating it, and to fail the call with -EINVAL if a dirty folio is left, before the block map changes. Fixes: 6795801366da ("xfs: Support large folios") Signed-off-by: Chris Mason Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_bmap_util.c | 17 +++++++++++++++-- fs/xfs/xfs_reflink.c | 2 +- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/fs/xfs/xfs_bmap_util.c b/fs/xfs/xfs_bmap_util.c index 537c6b29417cc7..4673d5174645a0 100644 --- a/fs/xfs/xfs_bmap_util.c +++ b/fs/xfs/xfs_bmap_util.c @@ -863,8 +863,21 @@ xfs_flush_unmap_range( error = filemap_write_and_wait_range(inode->i_mapping, start, end); if (error) return error; - truncate_pagecache_range(inode, start, end); - return 0; + + /* + * The callers go on to change the block map, so no folio may stay over + * the range. The holder of a GUP pin can mark a folio dirty again + * after the flush, with no lock of ours. A truncate drops such a folio + * if it lies inside the range. If it is a large folio that straddles + * the range, the truncate cannot split it, so it zeroes a part of the + * folio, keeps it, and reports nothing. The invalidation removes whole + * folios, changes no data, and fails on a dirty folio. + */ + error = invalidate_inode_pages2_range(inode->i_mapping, + start >> PAGE_SHIFT, end >> PAGE_SHIFT); + if (error == -EBUSY) + error = -EINVAL; + return error; } int diff --git a/fs/xfs/xfs_reflink.c b/fs/xfs/xfs_reflink.c index 104542b10d9e02..ff89516154bd1a 100644 --- a/fs/xfs/xfs_reflink.c +++ b/fs/xfs/xfs_reflink.c @@ -1663,7 +1663,7 @@ xfs_reflink_zero_posteof( /* * Prepare two files for range cloning. Upon a successful return both inodes * will have the iolock and mmaplock held, the page cache of the out file will - * be truncated, and any leases on the out file will have been broken. This + * be invalidated, and any leases on the out file will have been broken. This * function borrows heavily from xfs_file_aio_write_checks. * * The VFS allows partial EOF blocks to "match" for dedupe even though it hasn't From 6fe08320c38cc1165dc9193dcd3aa5539a6f9e73 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Mon, 9 Nov 2026 18:51:15 -0500 Subject: [PATCH 0426/2102] iomap: don't punch delalloc under a dirty EOF block After a failed buffered write, writeback on XFS can write in place to the shared block that contains EOF, and corrupt the other file that shares it. After a failed buffered write, iomap_write_delalloc_release() punches the delalloc reservation of the write, except under dirty folios, which still need it. It looks for dirty folios only up to i_size, and punches the rest unconditionally. But XFS rounds that punch down to a block boundary, so the block that contains EOF loses its COW fork reservation, and writeback goes to the shared block: block size 4096, i_size 5000, reservation 4096 to 8192 searched for dirty folios: 4096 to 5000 punched unconditionally: 5000 to 8192 rounded to blocks by XFS: 4096 to 8192 The fix used here is to look for dirty folios up to the end of the block that contains EOF. Fixes: f43dc4dc3eff ("iomap: buffered write failure should not truncate the page cache") Fixes: f6f91d290c8b ("xfs: punch delalloc extents from the COW fork for COW writes") Signed-off-by: Chris Mason Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/iomap/buffered-io.c | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/fs/iomap/buffered-io.c b/fs/iomap/buffered-io.c index d6e2f1ded5ca6f..d0980a7f27d14c 100644 --- a/fs/iomap/buffered-io.c +++ b/fs/iomap/buffered-io.c @@ -1495,9 +1495,34 @@ static void iomap_write_delalloc_scan(struct inode *inode, * mapping_seek_hole_data() will return it, and we will skip the punch because * the folio is dirty. THis is incorrect - we always need to punch out delalloc * beyond EOF in this case as writeback will never write back and covert that - * delalloc block beyond EOF. Hence we limit the cached data scan range to EOF, - * resulting in always punching out the range from the EOF to the end of the - * range the iomap spans. + * delalloc block beyond EOF. Hence we limit the cached data scan range, and + * always punch out the range from the end of the scan to the end of the range + * the iomap spans. + * + * The scan cannot simply end at EOF, because EOF is a byte offset and a + * delalloc reservation covers whole blocks. If EOF lies inside a block, it + * splits that block in two: + * + * [block start, EOF) File data. If it is dirty it will be written + * back, so the block must keep its delalloc + * backing. + * [EOF, block end) Beyond EOF. By the rule above, this would always + * be punched out. + * + * Both parts share one reservation, and it cannot be split: a punch of a part + * of a block takes away the reservation for the whole block. If the scan ended + * at EOF, we would skip the punch for the first part because it is dirty, and + * then punch the second part, which takes the reservation away from under the + * dirty data in the first part. On XFS, writeback that has lost a COW fork + * reservation like this writes in place, over a block that is shared with + * another file. + * + * Hence we treat the EOF block as a whole, and let the cached data over it + * decide: the scan range is rounded up to the end of the block that EOF lies + * in. If the data over the EOF block is dirty, the scan moves the punch start + * past the block. If it is clean, the block is punched like any other block in + * the range. Only blocks that start at or beyond EOF are punched + * unconditionally. If EOF is block aligned, the round up changes nothing. * * Intervals are of the form [start_byte, end_byte) (i.e. open ended) because it * matches the intervals returned by mapping_seek_hole_data(). i.e. SEEK_DATA @@ -1511,7 +1536,8 @@ void iomap_write_delalloc_release(struct inode *inode, loff_t start_byte, iomap_punch_t punch) { loff_t punch_start_byte = start_byte; - loff_t scan_end_byte = min(i_size_read(inode), end_byte); + loff_t scan_end_byte = min_t(u64, end_byte, + round_up((u64)i_size_read(inode), i_blocksize(inode))); /* * The caller must hold invalidate_lock to avoid races with page faults From f294ebd827e7a2b831b1eef4aaf437f07b2c235e Mon Sep 17 00:00:00 2001 From: Jiale Yao Date: Thu, 29 Oct 2026 13:29:48 +0800 Subject: [PATCH 0427/2102] powerpc/eeh: NUL-terminate force recovery input eeh_force_recover_write() can fill its entire stack buffer from userspace and then pass the unterminated data to strncmp() and sscanf(). This can make the string helpers read beyond the buffer. Reserve the last byte and initialize the buffer so every accepted input is NUL-terminated. Propagate copy errors before parsing as well. Fixes: 954bd99435b8 ("powerpc/eeh: Add eeh_force_recover to debugfs") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261029052948.2525048-1-yaojiale02@163.com --- arch/powerpc/kernel/eeh.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/arch/powerpc/kernel/eeh.c b/arch/powerpc/kernel/eeh.c index bb836f02101cf1..2d7898ef6b8c93 100644 --- a/arch/powerpc/kernel/eeh.c +++ b/arch/powerpc/kernel/eeh.c @@ -1728,10 +1728,12 @@ static ssize_t eeh_force_recover_write(struct file *filp, struct pci_controller *hose; uint32_t phbid, pe_no; struct eeh_pe *pe; - char buf[20]; + char buf[20] = {}; int ret; - ret = simple_write_to_buffer(buf, sizeof(buf), ppos, user_buf, count); + ret = simple_write_to_buffer(buf, sizeof(buf) - 1, ppos, user_buf, count); + if (ret < 0) + return ret; if (!ret) return -EFAULT; From 4e6e66ecf62185828f731914000a6b0baff355db Mon Sep 17 00:00:00 2001 From: Amit Machhiwal Date: Thu, 15 Oct 2026 00:22:15 +0530 Subject: [PATCH 0428/2102] KVM: PPC: Book3S HV: Disable preemption around host-side HPT lock users A previous change ("KVM: PPC: Book3S HV: Add preempt_disable() around virtual-mode HPTE bit-lock users") at [1] added preempt_disable() around guest vCPU HPT hcalls and page fault handlers executed in virtual mode. This ensures vCPU threads cannot be preempted while holding HPTE_V_HVLOCK or the reverse-map lock. However, several host-side virtual-mode paths in book3s_64_mmu_hv.c also acquire HPTE_V_HVLOCK and lock_rmap() in process context with preemption enabled. Specifically, kvm_unmap_rmapp() and kvm_age_rmapp() take both locks during MMU notifier callbacks and memslot flushes, while resize_hpt_rehash_hpte() acquires HPTE_V_HVLOCK during HPT resizing. If a host thread is preempted while holding either bit-lock, any guest vCPU thread scheduled on the same CPU spinning for the same lock with preemption disabled will never yield, resulting in a permanent CPU hang. Fix this by disabling preemption across these host-side critical sections. For kvm_unmap_rmapp() and kvm_age_rmapp(), place preempt_disable() before lock_rmap() so that both the rmap chain lock and the subsequent HPTE_V_HVLOCK bit-lock are held under a single non-preemptible window. To preserve the ABBA lock ordering between the two locks, re-enable preemption after dropping the rmap lock on any retry or early-exit path before spinning on cpu_relax(), allowing the lock holder to be scheduled. For kvm_htab_write(), the HPT migration restore path, replace the direct calls to kvmppc_do_h_remove() with kvmppc_virtmode_do_h_remove(), a thin wrapper that brackets kvmppc_do_h_remove() with preempt_disable() and preempt_enable(), mirroring the existing kvmppc_virtmode_do_h_enter() helper. For resize_hpt_rehash_hpte(), place preempt_disable() before the try_lock_hpte() spin loop and preempt_enable() after unlock_hpte() at the function exit. [1] https://git.kernel.org/powerpc/c/abbbe5ff83e7c9ed3a4d61b73011f1df7bf87907 Fixes: 6165d5dd99db ("KVM: PPC: Book3S HV: add virtual mode handlers for HPT hcalls and page faults") Cc: stable@vger.kernel.org # v5.14+ Signed-off-by: Amit Machhiwal Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261014185215.71832-1-amachhiw@linux.ibm.com --- arch/powerpc/kvm/book3s_64_mmu_hv.c | 33 +++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/arch/powerpc/kvm/book3s_64_mmu_hv.c b/arch/powerpc/kvm/book3s_64_mmu_hv.c index 00b8a3f855f46e..97740173974cec 100644 --- a/arch/powerpc/kvm/book3s_64_mmu_hv.c +++ b/arch/powerpc/kvm/book3s_64_mmu_hv.c @@ -47,6 +47,9 @@ static long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags, long pte_index, unsigned long pteh, unsigned long ptel, unsigned long *pte_idx_ret); +static void kvmppc_virtmode_do_h_remove(struct kvm *kvm, unsigned long flags, + unsigned long pte_index, unsigned long avpn, + unsigned long *hpret); struct kvm_resize_hpt { /* These fields read-only after init */ @@ -308,6 +311,22 @@ static long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags, } +/* + * Virtual-mode H_REMOVE. kvmppc_do_h_remove() is also called from real mode, + * where preempt_disable() is not usable, so the guard stays here. The function + * spins on HPTE_V_HVLOCK and then lock_rmap() (via remove_revmap_chain()); + * preemption must be disabled across both bit-locks so that spinning callers + * holding preempt_disable() can make forward progress. + */ +static void kvmppc_virtmode_do_h_remove(struct kvm *kvm, unsigned long flags, + unsigned long pte_index, unsigned long avpn, + unsigned long *hpret) +{ + preempt_disable(); + kvmppc_do_h_remove(kvm, flags, pte_index, avpn, hpret); + preempt_enable(); +} + static struct kvmppc_slb *kvmppc_mmu_book3s_hv_find_slbe(struct kvm_vcpu *vcpu, gva_t eaddr) { @@ -810,9 +829,11 @@ static void kvm_unmap_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn]; for (;;) { + preempt_disable(); lock_rmap(rmapp); if (!(*rmapp & KVMPPC_RMAP_PRESENT)) { unlock_rmap(rmapp); + preempt_enable(); break; } @@ -826,6 +847,7 @@ static void kvm_unmap_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) { /* unlock rmap before spinning on the HPTE lock */ unlock_rmap(rmapp); + preempt_enable(); while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK) cpu_relax(); continue; @@ -834,6 +856,7 @@ static void kvm_unmap_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, kvmppc_unmap_hpte(kvm, i, memslot, rmapp, gfn); unlock_rmap(rmapp); __unlock_hpte(hptep, be64_to_cpu(hptep[0])); + preempt_enable(); } } @@ -890,6 +913,7 @@ static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn]; retry: + preempt_disable(); lock_rmap(rmapp); if (*rmapp & KVMPPC_RMAP_REFERENCED) { *rmapp &= ~KVMPPC_RMAP_REFERENCED; @@ -897,6 +921,7 @@ static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, } if (!(*rmapp & KVMPPC_RMAP_PRESENT)) { unlock_rmap(rmapp); + preempt_enable(); return ret; } @@ -912,6 +937,7 @@ static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) { /* unlock rmap before spinning on the HPTE lock */ unlock_rmap(rmapp); + preempt_enable(); while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK) cpu_relax(); goto retry; @@ -931,6 +957,7 @@ static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, } while ((i = j) != head); unlock_rmap(rmapp); + preempt_enable(); return ret; } @@ -1219,6 +1246,7 @@ static unsigned long resize_hpt_rehash_hpte(struct kvm_resize_hpt *resize, if (!(vpte & HPTE_V_VALID) && !(vpte & HPTE_V_ABSENT)) return 0; /* nothing to do */ + preempt_disable(); while (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) cpu_relax(); @@ -1346,6 +1374,7 @@ static unsigned long resize_hpt_rehash_hpte(struct kvm_resize_hpt *resize, out: unlock_hpte(hptep, vpte); + preempt_enable(); return ret; } @@ -1868,7 +1897,7 @@ static ssize_t kvm_htab_write(struct file *file, const char __user *buf, nb += HPTE_SIZE; if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT)) - kvmppc_do_h_remove(kvm, 0, i, 0, tmp); + kvmppc_virtmode_do_h_remove(kvm, 0, i, 0, tmp); err = -EIO; ret = kvmppc_virtmode_do_h_enter(kvm, H_EXACT, i, v, r, tmp); @@ -1897,7 +1926,7 @@ static ssize_t kvm_htab_write(struct file *file, const char __user *buf, for (j = 0; j < hdr.n_invalid; ++j) { if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT)) - kvmppc_do_h_remove(kvm, 0, i, 0, tmp); + kvmppc_virtmode_do_h_remove(kvm, 0, i, 0, tmp); ++i; hptp += 2; } From d8c6ab0aeeca7cc2adfcf0ce1f796c6a86314ec0 Mon Sep 17 00:00:00 2001 From: Gautam Menghani Date: Mon, 12 Oct 2026 13:59:17 +0530 Subject: [PATCH 0429/2102] KVM: PPC: Book3S HV: Ensure that calls to idr_alloc are synchronized Calls to idr_alloc() in __prealloc_nested() are not currently synchronized. According to the documentation [1], the caller should provide their own locking to prevent concurrent modifications to the idr to prevent bugs. __prealloc_nested() calls idr_alloc() with GFP_KERNEL which can sleep and mmu_lock is a spinlock. So idr_alloc() cannot be moved under mmu_lock. In such cases the idr Documentation says: If you need to take a lock while allocating a new ID from the IDR, you may need to pass a restrictive set of GFP flags, which can lead to the IDR being unable to allocate memory. To work around this, you can call idr_preload() before taking the lock, and then idr_preload_end() after the allocation. Hence preload the idr memory with idr_preload() before taking mmu_lock, which allows us to use idr_alloc(..., GFP_NOWAIT) under the spinlock. This also allows to kill __prealloc_nested() and __add_nested(), as they are not needed anymore with idr_preload(). [1]: lib/idr.c Fixes: c0f00a18e2a8 ("KVM: PPC: Book3S HV Nested: Change nested guest lookup to use idr") Cc: stable@vger.kernel.org # 5.19+ Co-developed-by: Ritesh Harjani (IBM) Signed-off-by: Ritesh Harjani (IBM) Signed-off-by: Gautam Menghani Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261012082922.218799-2-gautam@linux.ibm.com --- arch/powerpc/kvm/book3s_hv_nested.c | 34 +++++++++-------------------- 1 file changed, 10 insertions(+), 24 deletions(-) diff --git a/arch/powerpc/kvm/book3s_hv_nested.c b/arch/powerpc/kvm/book3s_hv_nested.c index a6ff42d7666c10..e893fdd24f0a8b 100644 --- a/arch/powerpc/kvm/book3s_hv_nested.c +++ b/arch/powerpc/kvm/book3s_hv_nested.c @@ -702,20 +702,6 @@ static struct kvm_nested_guest *__find_nested(struct kvm *kvm, int lpid) return idr_find(&kvm->arch.kvm_nested_guest_idr, lpid); } -static bool __prealloc_nested(struct kvm *kvm, int lpid) -{ - if (idr_alloc(&kvm->arch.kvm_nested_guest_idr, - NULL, lpid, lpid + 1, GFP_KERNEL) != lpid) - return false; - return true; -} - -static void __add_nested(struct kvm *kvm, int lpid, struct kvm_nested_guest *gp) -{ - if (idr_replace(&kvm->arch.kvm_nested_guest_idr, gp, lpid)) - WARN_ON(1); -} - static void __remove_nested(struct kvm *kvm, int lpid) { idr_remove(&kvm->arch.kvm_nested_guest_idr, lpid); @@ -862,21 +848,21 @@ struct kvm_nested_guest *kvmhv_get_nested(struct kvm *kvm, int l1_lpid, if (!newgp) return NULL; - if (!__prealloc_nested(kvm, l1_lpid)) { - kvmhv_release_nested(newgp); - return NULL; - } - + idr_preload(GFP_KERNEL); spin_lock(&kvm->mmu_lock); gp = __find_nested(kvm, l1_lpid); if (!gp) { - __add_nested(kvm, l1_lpid, newgp); - ++newgp->refcnt; - gp = newgp; - newgp = NULL; + if (idr_alloc(&kvm->arch.kvm_nested_guest_idr, newgp, + l1_lpid, l1_lpid + 1, GFP_NOWAIT) >= 0) { + ++newgp->refcnt; + gp = newgp; + newgp = NULL; + } } - ++gp->refcnt; + if (gp) + ++gp->refcnt; spin_unlock(&kvm->mmu_lock); + idr_preload_end(); if (newgp) kvmhv_release_nested(newgp); From b9d9a8741752c5b42c65b1c8dffba867889b74e5 Mon Sep 17 00:00:00 2001 From: Gautam Menghani Date: Mon, 12 Oct 2026 13:59:18 +0530 Subject: [PATCH 0430/2102] KVM: PPC: Book3S HV: XICS: Update irq_type for cleanup to work In kvmppc_xive_connect_vcpu(), if any failures are encountered, the control flow jumps to the 'bail' label where kvmppc_xive_cleanup_vcpu() is called. This cleanup function exits prematurely since vcpu->arch.irq_type is set to KVMPPC_IRQ_DEFAULT at this point. This ends up resulting in wasted memory. Fix this by setting irq_type to KVMPPC_IRQ_XICS before vcpu configuration starts. This makes XICS initialization symmetrical to XIVE initialization done in kvmppc_xive_native_connect_vcpu(). Fixes: 5af50993850a ("KVM: PPC: Book3S HV: Native usage of the XIVE interrupt controller") Cc: stable@vger.kernel.org # 4.12+ Signed-off-by: Gautam Menghani Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261012082922.218799-3-gautam@linux.ibm.com --- arch/powerpc/kvm/book3s_xive.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/powerpc/kvm/book3s_xive.c b/arch/powerpc/kvm/book3s_xive.c index d348365df72d32..72c89e820e2fd1 100644 --- a/arch/powerpc/kvm/book3s_xive.c +++ b/arch/powerpc/kvm/book3s_xive.c @@ -1939,6 +1939,7 @@ int kvmppc_xive_connect_vcpu(struct kvm_device *dev, xc->vp_id = vp_id; xc->mfrr = 0xff; xc->valid = true; + vcpu->arch.irq_type = KVMPPC_IRQ_XICS; r = xive_native_get_vp_info(xc->vp_id, &xc->vp_cam, &xc->vp_chip_id); if (r) @@ -2027,7 +2028,6 @@ int kvmppc_xive_connect_vcpu(struct kvm_device *dev, return r; } - vcpu->arch.irq_type = KVMPPC_IRQ_XICS; return 0; } From 7279692d70f3e399b3dd2d07ffa365e9f533761f Mon Sep 17 00:00:00 2001 From: Gautam Menghani Date: Mon, 12 Oct 2026 13:59:19 +0530 Subject: [PATCH 0431/2102] KVM: PPC: Book3S HV: XICS: Avoid NULL ptr deref in kvmppc_xive_cleanup_vcpu() In kvmppc_xive_connect_vcpu() if there is a failure before xc->vp_ipi_data is setup, it can result in a NULL pointer dereference in kvmppc_xive_cleanup_vcpu() when accessing the MMIO page in xive_vm_esb_load(). Fix this by adding a check before masking the VP IPI before accessing the MMIO pages. Fixes: 5af50993850a ("KVM: PPC: Book3S HV: Native usage of the XIVE interrupt controller") Cc: stable@vger.kernel.org # 4.12+ Signed-off-by: Gautam Menghani Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261012082922.218799-4-gautam@linux.ibm.com --- arch/powerpc/kvm/book3s_xive.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/arch/powerpc/kvm/book3s_xive.c b/arch/powerpc/kvm/book3s_xive.c index 72c89e820e2fd1..9d2039ee37b2c9 100644 --- a/arch/powerpc/kvm/book3s_xive.c +++ b/arch/powerpc/kvm/book3s_xive.c @@ -1820,7 +1820,8 @@ void kvmppc_xive_cleanup_vcpu(struct kvm_vcpu *vcpu) kvmppc_xive_disable_vcpu_interrupts(vcpu); /* Mask the VP IPI */ - xive_vm_esb_load(&xc->vp_ipi_data, XIVE_ESB_SET_PQ_01); + if (xc->vp_ipi_data.eoi_mmio) + xive_vm_esb_load(&xc->vp_ipi_data, XIVE_ESB_SET_PQ_01); /* Free escalations */ for (i = 0; i < KVMPPC_XIVE_Q_COUNT; i++) { From b04be22bf6ea06b92bff7850328a8057b8d964ae Mon Sep 17 00:00:00 2001 From: Gautam Menghani Date: Mon, 12 Oct 2026 13:59:20 +0530 Subject: [PATCH 0432/2102] KVM: PPC: Book3S HV: Take SRCU read lock around kvmppc_h_page_init() call Since there is no srcu read lock around kvmppc_h_page_init(), a "suspicious rcu_dereference_check() usage" can be triggered by running host linux with CONFIG_PROVE_RCU=y and the following code in the guest: plpar_hcall_norets(H_PAGE_INIT, H_ZERO_PAGE, phys_addr, 0); ============================= WARNING: suspicious RCU usage 7.0.0-dirty #227 Not tainted ----------------------------- ./include/linux/kvm_host.h:1074 suspicious rcu_dereference_check() usage! other info that might help us debug this: rcu_scheduler_active = 2, debug_locks = 1 1 lock held by qemu-system-ppc/2093: #0: c000000354197ab0 (&vcpu->mutex){+.+.}-{3:3}, at: kvm_vcpu_ioctl+0x10c/0xaf0 stack backtrace: CPU: 30 UID: 0 PID: 2093 Comm: qemu-system-ppc Not tainted 7.0.0-dirty #227 PREEMPT(full) Hardware name: IBM,9080-HEX POWER10 (architected) 0x800200 0xf000006 of:IBM,FW1060.60 (NH1060_158) hv:phyp pSeries Call Trace: [c00000033e1bf430] [c000000001b3dbd4] dump_stack_lvl+0xc8/0x130 (unreliable) [c00000033e1bf470] [c0000000003da964] lockdep_rcu_suspicious+0x1f4/0x290 [c00000033e1bf520] [c000000000231424] gfn_to_memslot+0x1b4/0x1c0 [c00000033e1bf560] [c00000000023637c] kvm_clear_guest+0x9c/0x110 [c00000033e1bf5c0] [c0000000002714a4] kvmppc_h_page_init+0x160/0x1a0 [c00000033e1bf610] [c00000000026c040] kvmppc_pseries_do_hcall+0x1930/0x1940 [c00000033e1bf6d0] [c00000000026fb18] kvmppc_vcpu_run_hv+0x268/0x800 [c00000033e1bf7a0] [c000000000246b30] kvmppc_vcpu_run+0x30/0x50 [c00000033e1bf7c0] [c000000000241ed4] kvm_arch_vcpu_ioctl_run+0x364/0x530 [c00000033e1bf860] [c00000000022b870] kvm_vcpu_ioctl+0x1b0/0xaf0 [c00000033e1bfa50] [c0000000009b4514] sys_ioctl+0x144/0x190 [c00000033e1bfab0] [c000000000034330] system_call_exception+0x170/0x370 [c00000033e1bfe50] [c00000000000d05c] system_call_vectored_common+0x15c/0x2ec Fix this by taking a srcu read lock around kvmppc_h_page_init(). Fixes: 2d34d1c3bbfd ("KVM: PPC: Book3S HV: Implement virtual mode H_PAGE_INIT handler") Cc: stable@vger.kernel.org # 5.2+ Signed-off-by: Gautam Menghani Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261012082922.218799-5-gautam@linux.ibm.com --- arch/powerpc/kvm/book3s_hv.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/arch/powerpc/kvm/book3s_hv.c b/arch/powerpc/kvm/book3s_hv.c index 22283d46e8fe69..7c4aa12bf606ad 100644 --- a/arch/powerpc/kvm/book3s_hv.c +++ b/arch/powerpc/kvm/book3s_hv.c @@ -1388,9 +1388,11 @@ int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu) ret = kvmhv_copy_tofrom_guest_nested(vcpu); break; case H_PAGE_INIT: + idx = srcu_read_lock(&kvm->srcu); ret = kvmppc_h_page_init(vcpu, kvmppc_get_gpr(vcpu, 4), kvmppc_get_gpr(vcpu, 5), kvmppc_get_gpr(vcpu, 6)); + srcu_read_unlock(&kvm->srcu, idx); break; case H_SVM_PAGE_IN: ret = H_UNSUPPORTED; From 9751c361cb234f000261879b1b5015bf08f6a428 Mon Sep 17 00:00:00 2001 From: Gautam Menghani Date: Mon, 2 Nov 2026 14:46:59 +0530 Subject: [PATCH 0433/2102] KVM: PPC: Book3S HV: Avoid spurious interrupts caused by LPCR_MER bit A huge number of spurious interrupts can be seen immediately after a KVM on PowerNV guest boots up in XIVE mode. $ cat /proc/interrupts | grep SPU SPU: 223705 192439 273526 147623 Spurious interrupts This bug was introduced by commit ecd10702baae5 ("KVM: PPC: Book3S HV: Handle pending exceptions on guest entry with MSR_EE"). The root cause is that once LPCR_MER bit is set, it is supposed to be reset by software. But when a vCPU starts running with LPCR_MER set, the vCPU does not exit back to the host until the decrementer expires or there is an hcall, etc. This is because KVM on PowerNV guests have support for native XIVE, so they are not dependent on host for interrupt emulation. Due to this behaviour, a huge number of spurious interrupts are seen since LPCR_MER continues to be set and LPCR_MER cannot be reset until the vCPU exits to the host. Fix this behaviour by not using the LPCR_MER bit whenever native XIVE is available (currently in case of KVM on PowerNV only), as the XIVE hardware can present interrupts to the KVM guest vCPU directly. So the LPCR_MER functionality is not required. This reduces the number of spurious interrupts drastically. Fixes: ecd10702baae5 ("KVM: PPC: Book3S HV: Handle pending exceptions on guest entry with MSR_EE") Cc: stable@vger.kernel.org # 6.8+ Reported-by: Timothy Pearson Closes: https://lore.kernel.org/linuxppc-dev/582904882.11159.1786719390349.JavaMail.zimbra@raptorengineeringinc.com Signed-off-by: Gautam Menghani Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261102091700.253381-1-gautam@linux.ibm.com --- arch/powerpc/kvm/book3s_hv.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/powerpc/kvm/book3s_hv.c b/arch/powerpc/kvm/book3s_hv.c index 7c4aa12bf606ad..bafe9546087b28 100644 --- a/arch/powerpc/kvm/book3s_hv.c +++ b/arch/powerpc/kvm/book3s_hv.c @@ -4986,7 +4986,7 @@ int kvmhv_run_single_vcpu(struct kvm_vcpu *vcpu, u64 time_limit, if (!kvmhv_on_pseries() && (__kvmppc_get_msr_hv(vcpu) & MSR_EE)) kvmppc_inject_interrupt_hv(vcpu, BOOK3S_INTERRUPT_EXTERNAL, 0); - else + else if (!kvmppc_xive_enabled(vcpu)) lpcr |= LPCR_MER; } else { /* From 0a7ad2e55ff0de8c13dbe25aa87cecb0243b245e Mon Sep 17 00:00:00 2001 From: Christian Zigotzky A-EON Open Source Date: Sat, 24 Oct 2026 09:55:19 +0200 Subject: [PATCH 0434/2102] powerpc/pasemi: Defer Nemo IRQ initialization Since pas_pci_init() is now called later during boot, the i8259 initialization in pas_init_IRQ() happens too early and accesses registers that are not yet mapped, preventing the board from booting. Move the Nemo-specific i8259 initialization to pas_add_bridge(), after the ISA bridge has been discovered. Suggested-by: Darren Stevens Tested-by: Christian Zigotzky Signed-off-by: Christian Zigotzky A-EON Open Source Fixes: c144bc719234 ("powerpc/pasemi: Move PHB discovery") Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261024075519.18877-1-chzigotzky@xenosoft.de --- arch/powerpc/platforms/pasemi/pasemi.h | 6 ++++++ arch/powerpc/platforms/pasemi/pci.c | 5 +++++ arch/powerpc/platforms/pasemi/setup.c | 12 ++++-------- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/arch/powerpc/platforms/pasemi/pasemi.h b/arch/powerpc/platforms/pasemi/pasemi.h index 6f6743b8e48d12..01bcfa258625b1 100644 --- a/arch/powerpc/platforms/pasemi/pasemi.h +++ b/arch/powerpc/platforms/pasemi/pasemi.h @@ -7,6 +7,12 @@ extern void pas_pci_init(void); struct pci_dev; extern void pas_pci_dma_dev_setup(struct pci_dev *dev); +#ifdef CONFIG_PPC_PASEMI_NEMO +void __init nemo_init_IRQ(void); +#else +static inline void __init nemo_init_IRQ(void) { } +#endif + void __iomem *__init pasemi_pci_getcfgaddr(struct pci_dev *dev, int offset); extern void __init pasemi_map_registers(void); diff --git a/arch/powerpc/platforms/pasemi/pci.c b/arch/powerpc/platforms/pasemi/pci.c index 2df9552746529c..fb53782da7ecda 100644 --- a/arch/powerpc/platforms/pasemi/pci.c +++ b/arch/powerpc/platforms/pasemi/pci.c @@ -265,6 +265,11 @@ static int __init pas_add_bridge(struct device_node *dev) */ isa_bridge_find_early(hose); + /* + * ISA bridge is now active, add the i8259 cascade (if needed) + */ + nemo_init_IRQ(); + return 0; } diff --git a/arch/powerpc/platforms/pasemi/setup.c b/arch/powerpc/platforms/pasemi/setup.c index 45792ecd5dfd78..7a961f2a228f8f 100644 --- a/arch/powerpc/platforms/pasemi/setup.c +++ b/arch/powerpc/platforms/pasemi/setup.c @@ -216,10 +216,12 @@ static void sb600_8259_cascade(struct irq_desc *desc) chip->irq_eoi(&desc->irq_data); } -static void __init nemo_init_IRQ(struct mpic *mpic) +void __init nemo_init_IRQ(void) { struct device_node *np; int gpio_virq; + struct mpic *mpic; + /* Connect the SB600's legacy i8259 controller */ np = of_find_node_by_path("/pxp@0,e0000000"); i8259_init(np, 0); @@ -230,14 +232,10 @@ static void __init nemo_init_IRQ(struct mpic *mpic) irq_set_chained_handler(gpio_virq, sb600_8259_cascade); mpic_unmask_irq(irq_get_irq_data(gpio_virq)); + mpic = irq_get_chip_data(gpio_virq); irq_set_default_domain(mpic->irqhost); } -#else - -static inline void nemo_init_IRQ(struct mpic *mpic) -{ -} #endif static __init void pas_init_IRQ(void) @@ -300,8 +298,6 @@ static __init void pas_init_IRQ(void) mpic_unmask_irq(irq_get_irq_data(nmi_virq)); } - nemo_init_IRQ(mpic); - of_node_put(mpic_node); of_node_put(root); } From d369ba5a46c65c54b94c94713ca1fb4ad6a87ebf Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Tue, 3 Nov 2026 19:31:44 +0100 Subject: [PATCH 0435/2102] mm/memfd: handle GUP pins more reliably when write-sealing memfd_wait_for_pins() detects GUP references by comparing a folio's actual refcount with its expected refcount. As spelled out by folio_expected_ref_count(), obtaining the expected refcount when there can be concurrent folio (un)mapping is racy. So it is possible that a changing folio mapcount can race with our check for GUP references, and F_SEAL_WRITE might succeed even if there are some, allowing file contents to be modified after sealing. For folios with a reliable pincount, detect FOLL_PIN references using folio_maybe_dma_pinned() before falling back to the refcount comparison. For small folios without that, the 1024 pinning BIAS makes it very hard (although not impossible) to misguide the refcount comparison. This improves FOLL_PIN detection for folios with a pincount. Handling FOLL_GET and small folios requires a more fundamental change. Fortunately, most interfaces that allow for GUP'ing such pages use FOLL_PIN, in particular interfaces using FOLL_LONGTERM. However, we still have some FOLL_GET leftovers ... Fixes: 05f65b5c7090 ("shm: wait for pins to be released when sealing") Cc: stable@vger.kernel.org Cc: Chris Mason Reviewed-by: Lorenzo Stoakes (ARM) Link: https://patch.msgid.link/20261103-fixes_core_2-v1-1-f332954f1df4@kernel.org Reviewed-by: Lance Yang Signed-off-by: David Hildenbrand (Arm) --- mm/memfd.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/mm/memfd.c b/mm/memfd.c index 0e3ff3eebfa829..05088ab210baba 100644 --- a/mm/memfd.c +++ b/mm/memfd.c @@ -32,6 +32,13 @@ static bool memfd_folio_has_extra_refs(struct folio *folio) { + /* + * Use the precise pincount where available to avoid racy refcount + * comparisons. + */ + if (folio_has_pincount(folio) && folio_maybe_dma_pinned(folio)) + return true; + return folio_ref_count(folio) != folio_expected_ref_count(folio); } From 7cca01c39cc89f6ef39079484d26b6d99287a610 Mon Sep 17 00:00:00 2001 From: Sumit Gupta Date: Tue, 10 Nov 2026 15:42:46 +0530 Subject: [PATCH 0436/2102] cpufreq: CPPC: Set CPPC Enable register in cpu_init() As per ACPI 6.x s8.4.6.1.4 (CPPC Enable Register): "If supported by the platform, OSPM writes a one to this register to enable CPPC on this processor. If not implemented, OSPM assumes the platform always has CPPC enabled." The driver never writes this register. CPPC therefore stays disabled on platforms such as NVIDIA GB10 that wait for OSPM to enable it. Call cppc_set_enable() in cppc_cpufreq_cpu_init(). Fail init if enabling CPPC fails. If init fails after CPPC is enabled, disable it again. The register is optional, so -EOPNOTSUPP is not an error. Fixes: 5477fb3bd1e8 ("ACPI / CPPC: Add a CPUFreq driver for use with CPPC") Cc: All applicable # ab482f1bac6b "ACPI: CPPC: Refactor register value get and set ABIs" Signed-off-by: Sumit Gupta Reviewed-by: Christian Loehle [ rjw: Subject tweak ] Link: https://patch.msgid.link/20261110101246.3665797-1-sumitg@nvidia.com Signed-off-by: Rafael J. Wysocki --- drivers/cpufreq/cppc_cpufreq.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/drivers/cpufreq/cppc_cpufreq.c b/drivers/cpufreq/cppc_cpufreq.c index 957fa7775260b5..b2af24ae500864 100644 --- a/drivers/cpufreq/cppc_cpufreq.c +++ b/drivers/cpufreq/cppc_cpufreq.c @@ -714,7 +714,17 @@ static int cppc_cpufreq_cpu_init(struct cpufreq_policy *policy) pr_debug("Unsupported CPU co-ord type: %d\n", policy->shared_type); ret = -EFAULT; - goto out; + goto out_put; + } + + /* + * Enable CPPC. The Enable register is optional - some platforms + * may not support it. + */ + ret = cppc_set_enable(cpu, true); + if (ret && ret != -EOPNOTSUPP) { + pr_err("Failed to enable CPPC for CPU%u (%d)\n", cpu, ret); + goto out_put; } policy->fast_switch_possible = cppc_allow_fast_switch(policy->cpus); @@ -742,6 +752,8 @@ static int cppc_cpufreq_cpu_init(struct cpufreq_policy *policy) return 0; out: + cppc_set_enable(cpu, false); +out_put: cppc_cpufreq_put_cpu_data(policy); return ret; } From 45a25a1bfd267d9e420119a48e5291d7882395df Mon Sep 17 00:00:00 2001 From: Joas Antonio dos Santos Date: Tue, 10 Nov 2026 03:55:41 +0000 Subject: [PATCH 0437/2102] Bluetooth: hci_qca: clear qca_memdump when discarding dump packets qca_controller_memdump() frees qca_memdump when a memdump packet with a non-zero sequence number arrives while QCA_MEMDUMP_COLLECTION is not set, but leaves qca->qca_memdump pointing at the freed object. The next run of the work reads the stale pointer into its local variable, skips the allocation and uses the freed memory. Another packet with a non-zero sequence number frees it a second time, and a packet with sequence number 0 writes ram_dump_size, current_seq_no and received_dump into it. The original code cleared the pointer here; the assignment was dropped when the condition was changed to test QCA_MEMDUMP_COLLECTION. All other places that free the structure clear the pointer. A controller that sends two memdump events without a leading sequence number 0 can trigger a use-after-free or double free of a kmalloc object. Found by LLM-assisted source review. Fixes: 06d3fdfcdf5c ("Bluetooth: hci_qca: Add qcom devcoredump support") Cc: stable@vger.kernel.org Signed-off-by: Joas Antonio dos Santos Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/hci_qca.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/bluetooth/hci_qca.c b/drivers/bluetooth/hci_qca.c index d96ae0fc2b2e1b..dfaf4861f4983f 100644 --- a/drivers/bluetooth/hci_qca.c +++ b/drivers/bluetooth/hci_qca.c @@ -1132,6 +1132,7 @@ static void qca_controller_memdump(struct work_struct *work) if (!test_bit(QCA_MEMDUMP_COLLECTION, &qca->flags)) { bt_dev_err(hu->hdev, "QCA: Discarding other packets"); kfree(qca_memdump); + qca->qca_memdump = NULL; kfree_skb(skb); mutex_unlock(&qca->hci_memdump_lock); return; From a57a255ce204b51327ac4e840a7726b0ab9a1942 Mon Sep 17 00:00:00 2001 From: Shuai Zhang Date: Tue, 10 Nov 2026 17:29:28 +0800 Subject: [PATCH 0438/2102] Bluetooth: hci_qca: Reopen the UART after enabling QCA2066 QCA2066 does not reopen the UART after the controller is enabled, which causes RX/TX out-of-sync errors. The UART has to be reopened once the controller is powered on. qca_regulator_init() already enables the controller and then reopens the UART, but QCA2066 does not go through it. QCA2066 was added with its own SoC type and handled in the default case. Let QCA2066 go through qca_regulator_init() as well, and handle it in the other places that check the SoC type in the same way. This also applies the baudrate switching, flow control, shutdown and probe handling of those chips to QCA2066. btqca.c checks the SoC type in the same way, so the firmware version is also shown in the log. Signed-off-by: Shuai Zhang Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/btqca.c | 1 + drivers/bluetooth/hci_qca.c | 13 +++++++++++++ 2 files changed, 14 insertions(+) diff --git a/drivers/bluetooth/btqca.c b/drivers/bluetooth/btqca.c index 60735b70d89ad8..9f54e33e4250fb 100644 --- a/drivers/bluetooth/btqca.c +++ b/drivers/bluetooth/btqca.c @@ -983,6 +983,7 @@ int qca_uart_setup(struct hci_dev *hdev, uint8_t baudrate, switch (soc_type) { case QCA_WCN3991: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: /* get fw build info */ diff --git a/drivers/bluetooth/hci_qca.c b/drivers/bluetooth/hci_qca.c index dfaf4861f4983f..f10edada951249 100644 --- a/drivers/bluetooth/hci_qca.c +++ b/drivers/bluetooth/hci_qca.c @@ -1387,6 +1387,7 @@ static int qca_set_baudrate(struct hci_dev *hdev, uint8_t baudrate) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: usleep_range(1000, 10000); @@ -1474,6 +1475,7 @@ static int qca_check_speeds(struct hci_uart *hu) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: if (!qca_get_speed(hu, QCA_INIT_SPEED) && @@ -1517,6 +1519,7 @@ static int qca_set_speed(struct hci_uart *hu, enum qca_speed_type speed_type) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: hci_uart_set_flow_control(hu, true); @@ -1552,6 +1555,7 @@ static int qca_set_speed(struct hci_uart *hu, enum qca_speed_type speed_type) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: hci_uart_set_flow_control(hu, false); @@ -1868,6 +1872,7 @@ static int qca_power_on(struct hci_dev *hdev) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: ret = qca_regulator_init(hu); @@ -1990,6 +1995,7 @@ static int qca_setup(struct hci_uart *hu) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: if (qcadev && qcadev->bdaddr_property_broken) @@ -2023,6 +2029,7 @@ static int qca_setup(struct hci_uart *hu) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: break; @@ -2285,6 +2292,7 @@ static void qca_power_off(struct hci_uart *hu) break; case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: gpiod_set_value_cansleep(qcadev->bt_en, 0); msleep(100); @@ -2439,6 +2447,7 @@ static int qca_serdev_probe(struct serdev_device *serdev) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: qcadev->bt_power = devm_kzalloc(&serdev->dev, @@ -2458,6 +2467,7 @@ static int qca_serdev_probe(struct serdev_device *serdev) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: if (!device_property_present(&serdev->dev, "enable-gpios")) { @@ -2501,6 +2511,7 @@ static int qca_serdev_probe(struct serdev_device *serdev) if (!qcadev->bt_en && (data->soc_type == QCA_WCN6750 || + data->soc_type == QCA_QCA2066 || data->soc_type == QCA_WCN6855 || data->soc_type == QCA_WCN7850)) power_ctrl_enabled = false; @@ -2509,6 +2520,7 @@ static int qca_serdev_probe(struct serdev_device *serdev) GPIOD_IN); if (IS_ERR(qcadev->sw_ctrl) && (data->soc_type == QCA_WCN6750 || + data->soc_type == QCA_QCA2066 || data->soc_type == QCA_WCN6855 || data->soc_type == QCA_WCN7850)) { dev_err(&serdev->dev, "failed to acquire SW_CTRL gpio\n"); @@ -2593,6 +2605,7 @@ static void qca_serdev_remove(struct serdev_device *serdev) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: if (power->vregs_on) From 45e28b01e4d06282d03f08888f09722709d4b552 Mon Sep 17 00:00:00 2001 From: Shuai Zhang Date: Tue, 10 Nov 2026 17:29:29 +0800 Subject: [PATCH 0439/2102] Bluetooth: hci_qca: Don't use the serdev port after a failed reopen If serdev_device_open() fails in qca_port_reopen(), qca_regulator_init() or the qca_setup() retry path, the port is left closed but HCI_UART_PROTO_READY stays set. The error reaches qca_setup(), whose retry loop calls serdev_device_close() again, and hci_uart_close() or hci_uart_unregister_device() close it once more later. The HCI core also calls hci_uart_flush() from hci_dev_close_sync() before hdev->close(), which writes to the closed port. serdev_device_close() and serdev_device_write_flush() have no "not open" check. ttyport_open() clears serport->tty when it fails, so both end up passing NULL to the tty layer, and the runtime PM usage count is dropped once too often. Keep HCI_UART_PROTO_READY in sync with the port state in hci_qca: clear it when the port is closed, set it only after a successful open, and only call serdev_device_close() when it was set. hci_uart_open() already treats the flag as "port is open" and reopens the port when it is clear, so the next power on recovers. Make hci_uart_flush() skip the port flush when the flag is clear, as it already does for the proto flush. Signed-off-by: Shuai Zhang Reviewed-by: Bartosz Golaszewski Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/hci_qca.c | 33 +++++++++++++++++++++++++++------ drivers/bluetooth/hci_serdev.c | 6 ++++-- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/drivers/bluetooth/hci_qca.c b/drivers/bluetooth/hci_qca.c index f10edada951249..d693e28427251e 100644 --- a/drivers/bluetooth/hci_qca.c +++ b/drivers/bluetooth/hci_qca.c @@ -1755,6 +1755,27 @@ static bool qca_wakeup(struct hci_dev *hdev) return wakeup; } +static void qca_port_close(struct hci_uart *hu) +{ + /* HCI_UART_PROTO_READY tracks whether the port is open, so a port + * left closed by a failed qca_port_open() is not closed again by + * hci_uart_close() or hci_uart_unregister_device(). + */ + if (test_and_clear_bit(HCI_UART_PROTO_READY, &hu->flags)) + serdev_device_close(hu->serdev); +} + +static int qca_port_open(struct hci_uart *hu) +{ + int ret; + + ret = serdev_device_open(hu->serdev); + if (!ret) + set_bit(HCI_UART_PROTO_READY, &hu->flags); + + return ret; +} + static int qca_port_reopen(struct hci_uart *hu) { int ret; @@ -1764,8 +1785,8 @@ static int qca_port_reopen(struct hci_uart *hu) * Without this, we will have RTS and CTS synchronization * issues. */ - serdev_device_close(hu->serdev); - ret = serdev_device_open(hu->serdev); + qca_port_close(hu); + ret = qca_port_open(hu); if (ret) { bt_dev_err(hu->hdev, "failed to open port"); return ret; @@ -1789,12 +1810,12 @@ static int qca_regulator_init(struct hci_uart *hu) qcadev = serdev_device_get_drvdata(hu->serdev); if (!qcadev->bt_power->vregs_on) { - serdev_device_close(hu->serdev); + qca_port_close(hu); ret = qca_regulator_enable(qcadev); if (ret) return ret; - ret = serdev_device_open(hu->serdev); + ret = qca_port_open(hu); if (ret) { bt_dev_err(hu->hdev, "failed to open port"); return ret; @@ -2073,8 +2094,8 @@ static int qca_setup(struct hci_uart *hu) if (retries < MAX_INIT_RETRIES) { bt_dev_warn(hdev, "Retry BT power ON:%d", retries); if (hu->serdev) { - serdev_device_close(hu->serdev); - ret = serdev_device_open(hu->serdev); + qca_port_close(hu); + ret = qca_port_open(hu); if (ret) { bt_dev_err(hdev, "failed to open port"); return ret; diff --git a/drivers/bluetooth/hci_serdev.c b/drivers/bluetooth/hci_serdev.c index 48ba017e219bc3..d2c48df3419966 100644 --- a/drivers/bluetooth/hci_serdev.c +++ b/drivers/bluetooth/hci_serdev.c @@ -101,11 +101,13 @@ static int hci_uart_flush(struct hci_dev *hdev) kfree_skb(hu->tx_skb); hu->tx_skb = NULL; } + if (!test_bit(HCI_UART_PROTO_READY, &hu->flags)) + return 0; + /* Flush any pending characters in the driver and discipline. */ serdev_device_write_flush(hu->serdev); - if (test_bit(HCI_UART_PROTO_READY, &hu->flags)) - hu->proto->flush(hu); + hu->proto->flush(hu); return 0; } From 4728474344793dd67956e03a2cb244b71383ef7c Mon Sep 17 00:00:00 2001 From: Xu Rao Date: Tue, 10 Nov 2026 11:07:56 +0800 Subject: [PATCH 0440/2102] Bluetooth: MGMT: Fix runtime config status opcode The Set Default Runtime Configuration command uses opcode 0x004e, but set_def_runtime_config() reports its invalid-parameter status with the Set Default System Configuration opcode, 0x004c. A management client that matches Command Status events to its pending request by opcode therefore cannot associate the response with the request it sent. Runtime configuration parameters are not implemented, so the command still returns MGMT_STATUS_INVALID_PARAMS. Use MGMT_OP_SET_DEF_RUNTIME_CONFIG for the status event so the response identifies the command that was actually handled. Fixes: aececa645dc7 ("Bluetooth: mgmt: Add commands for runtime configuration") Signed-off-by: Xu Rao Cc: stable@vger.kernel.org Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/mgmt_config.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/bluetooth/mgmt_config.c b/net/bluetooth/mgmt_config.c index fdcc752c6f13f6..6a617656bfbe06 100644 --- a/net/bluetooth/mgmt_config.c +++ b/net/bluetooth/mgmt_config.c @@ -362,6 +362,6 @@ int set_def_runtime_config(struct sock *sk, struct hci_dev *hdev, void *data, { bt_dev_dbg(hdev, "sock %p", sk); - return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DEF_SYSTEM_CONFIG, + return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DEF_RUNTIME_CONFIG, MGMT_STATUS_INVALID_PARAMS); } From 1645edfa8c29e43239cca615cefcb19959d3aa36 Mon Sep 17 00:00:00 2001 From: Joas Antonio dos Santos Date: Tue, 10 Nov 2026 03:26:03 +0000 Subject: [PATCH 0441/2102] Bluetooth: L2CAP: validate MPS and MTU in ECRED connection response l2cap_ecred_conn_rsp() stores the MTU and MPS from the peer without checking them against the minimums required for enhanced credit based channels. The other LE and ECRED handlers (l2cap_le_connect_req(), l2cap_le_connect_rsp(), l2cap_ecred_conn_req(), l2cap_ecred_reconf_req()) all reject values below the minimum. With an MPS below L2CAP_SDULEN_SIZE, the pdu_len computation in l2cap_segment_le_sdu() wraps: pdu_len = chan->remote_mps - L2CAP_SDULEN_SIZE; pdu_len is then clamped to the SDU length, which l2cap_chan_send() has already limited to chan->omtu, so nothing is over-allocated and there is no memory safety issue. The result is that the whole SDU is sent as a single PDU, larger than the MPS the peer announced, and a channel is established with parameters the specification does not allow. Apply the same L2CAP_ECRED_MIN_MTU / L2CAP_ECRED_MIN_MPS checks that l2cap_ecred_conn_req() uses and drop the channel when the response carries smaller values. Found by LLM-assisted manual code review. Fixes: 15f02b910562 ("Bluetooth: L2CAP: Add initial code for Enhanced Credit Based Mode") Signed-off-by: Joas Antonio dos Santos Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/l2cap_core.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/net/bluetooth/l2cap_core.c b/net/bluetooth/l2cap_core.c index 7dcb0586a10b2a..0398cc5a2dc0a5 100644 --- a/net/bluetooth/l2cap_core.c +++ b/net/bluetooth/l2cap_core.c @@ -5701,6 +5701,16 @@ static inline int l2cap_ecred_conn_rsp(struct l2cap_conn *conn, break; } + /* + * Validate MPS and MTU per BT Core Spec + * Vol 3 Part A Sec 10.2 + */ + if (mtu < L2CAP_ECRED_MIN_MTU || + mps < L2CAP_ECRED_MIN_MPS) { + l2cap_chan_del(chan, ECONNREFUSED); + break; + } + chan->ident = 0; chan->dcid = dcid; chan->omtu = mtu; From d9a1bd14caf5d235499319f7aee9e641c12d90a9 Mon Sep 17 00:00:00 2001 From: Cen Zhang Date: Sat, 24 Oct 2026 23:27:49 +0800 Subject: [PATCH 0442/2102] Bluetooth: hci_conn: Initialize the device before hash insertion An hci_conn must have an initialized embedded device before an RCU reader can acquire a reference to it. __hci_conn_add() instead adds the connection to conn_hash before hci_conn_init_sysfs() calls device_initialize(). Holding hdev->lock during creation does not exclude hci_disconnect_all_sync(), which looks up the connection and calls hci_conn_get() under RCU without that lock. When a new incoming ACL request overlaps controller poweroff before the connection is registered in sysfs, the separate event and request workqueues can execute this sequence: 1. The event worker holds hdev->lock and publishes a new connection in __hci_conn_add(), before device_initialize(). 2. The request worker finds that connection under RCU, calls hci_conn_get() and leaves its RCU read-side critical section. 3. The event worker runs hci_conn_init_sysfs(), sets BT_CONNECT in hci_conn_request_evt() and releases hdev->lock. 4. The request worker calls hci_abort_conn_sync(), which acquires hdev->lock and reaches hci_conn_failed(), hci_conn_del() and hci_conn_del_sysfs() to delete the pending connection. 5. After abort returns, the request worker calls hci_conn_put(). device_initialize() resets the kobject reference count to one, discarding the walker's premature get. If no other device references exist, deletion of the unregistered device drops that one reference and bt_link_release() frees the hci_conn. The walker's trailing put then accesses the freed kobject, as shown by the KASAN report below. The RCU grace period in hci_conn_hash_del() cannot preserve the walker after it has left its read-side critical section. Initialize the device before hci_conn_hash_add() publishes the connection. The existing RCU publication then makes the initialized device visible to readers, so the walker takes a valid reference that survives deletion until its matching put. KASAN report as below: ================================================================== BUG: KASAN: slab-use-after-free in kobject_put+0x4f3/0x610 Read of size 1 at addr ffff88811e6fcd2c by task kworker/u17:0/559 Workqueue: hci0 hci_cmd_sync_work Call Trace: dump_stack_lvl+0x93/0xd0 print_report+0xce/0x630 ? kobject_put+0x4f3/0x610 ? srso_alias_return_thunk+0x5/0xfbef5 ? __virt_addr_valid+0x20d/0x410 ? kobject_put+0x4f3/0x610 kasan_report+0xe0/0x110 ? kobject_put+0x4f3/0x610 ? hci_disconnect_all_sync.constprop.0+0xd8/0x520 kobject_put+0x4f3/0x610 ? hci_disconnect_all_sync.constprop.0+0xd8/0x520 put_device+0x24/0x30 hci_disconnect_all_sync.constprop.0+0x176/0x520 ? hci_disconnect_all_sync.constprop.0+0xcd/0x520 ? __pfx_hci_disconnect_all_sync.constprop.0+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 hci_set_powered_sync+0x48f/0x680 ? __pfx_hci_set_powered_sync+0x10/0x10 ? __pfx___mutex_unlock_slowpath+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? lock_is_held_type+0x8f/0x100 set_powered_sync+0xaa/0x150 hci_cmd_sync_work+0x1b3/0x450 ? srso_alias_return_thunk+0x5/0xfbef5 process_one_work+0x908/0x19c0 ? __pfx_process_one_work+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? lock_is_held_type+0x8f/0x100 ? srso_alias_return_thunk+0x5/0xfbef5 worker_thread+0x65c/0xe40 ? __pfx_worker_thread+0x10/0x10 kthread+0x34f/0x460 ? srso_alias_return_thunk+0x5/0xfbef5 ? __pfx_kthread+0x10/0x10 ret_from_fork+0x659/0x940 ? __pfx_ret_from_fork+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? __switch_to+0x74f/0xf80 ? __pfx_kthread+0x10/0x10 ret_from_fork_asm+0x1a/0x30 Allocated by task 561: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 __kasan_kmalloc+0xaa/0xb0 __kmalloc_cache_noprof+0x251/0x610 __hci_conn_add+0x10c/0x1f70 hci_conn_add_unset+0x72/0x120 hci_conn_request_evt+0xb2b/0xd40 hci_event_packet+0x894/0xc70 hci_rx_work+0x367/0xf00 process_one_work+0x908/0x19c0 worker_thread+0x65c/0xe40 kthread+0x34f/0x460 ret_from_fork+0x659/0x940 ret_from_fork_asm+0x1a/0x30 Freed by task 559: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 kasan_save_free_info+0x3b/0x60 __kasan_slab_free+0x5f/0x80 kfree+0x307/0x580 bt_link_release+0x4a/0xb0 device_release+0xd7/0x280 kobject_put+0x1ad/0x610 put_device+0x24/0x30 hci_conn_del_sysfs+0x15d/0x190 hci_conn_del+0x684/0x1100 hci_abort_conn_sync+0x7d6/0xae0 hci_disconnect_all_sync.constprop.0+0x164/0x520 hci_set_powered_sync+0x48f/0x680 set_powered_sync+0xaa/0x150 hci_cmd_sync_work+0x1b3/0x450 process_one_work+0x908/0x19c0 worker_thread+0x65c/0xe40 kthread+0x34f/0x460 ret_from_fork+0x659/0x940 ret_from_fork_asm+0x1a/0x30 The buggy address belongs to the object at ffff88811e6fc000 which belongs to the cache kmalloc-8k of size 8192 The buggy address is located 3372 bytes inside of freed 8192-byte region [ffff88811e6fc000, ffff88811e6fe000) The buggy address belongs to the physical page: page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x11e6f8 head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0 flags: 0x200000000000040(head|node=0|zone=2) page_type: f5(slab) raw: 0200000000000040 ffff888100043180 dead000000000122 0000000000000000 raw: 0000000000000000 0000000000020002 00000000f5000000 0000000000000000 head: 0200000000000040 ffff888100043180 dead000000000122 0000000000000000 head: 0000000000000000 0000000000020002 00000000f5000000 0000000000000000 head: 0200000000000003 fffffffffffffe01 00000000ffffffff 00000000ffffffff head: 0000000000000000 0000000000000000 00000000ffffffff 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff88811e6fcc00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff88811e6fcc80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb >ffff88811e6fcd00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff88811e6fcd80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff88811e6fce00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ================================================================== Fixes: 94d9ba9f9888 ("Bluetooth: hci_sync: Fix UAF in hci_disconnect_all_sync") Assisted-by: LLM Signed-off-by: Cen Zhang Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_conn.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/net/bluetooth/hci_conn.c b/net/bluetooth/hci_conn.c index eebd73988bf66b..c468a9332e0589 100644 --- a/net/bluetooth/hci_conn.c +++ b/net/bluetooth/hci_conn.c @@ -1166,6 +1166,9 @@ static struct hci_conn *__hci_conn_add(struct hci_dev *hdev, int type, hci_dev_hold(hdev); + /* Initialize the device before publishing it to RCU readers. */ + hci_conn_init_sysfs(conn); + hci_conn_hash_add(hdev, conn); /* The SCO and eSCO connections will only be notified when their @@ -1177,7 +1180,6 @@ static struct hci_conn *__hci_conn_add(struct hci_dev *hdev, int type, hdev->notify(hdev, HCI_NOTIFY_CONN_ADD); } - hci_conn_init_sysfs(conn); return conn; } From 58d8a0955065fb00824865dca5b573a1becbb1ca Mon Sep 17 00:00:00 2001 From: Cen Zhang Date: Sun, 25 Oct 2026 00:15:17 +0800 Subject: [PATCH 0443/2102] Bluetooth: vhci: Flush suspend work after removing debugfs The VHCI controller must remain alive until suspend_work finishes. vhci_release() flushes the work before removing the force_suspend debugfs entry, so an active writer can queue work after that flush. A force_suspend write changing the suspend state can overlap the last close of /dev/vhci as follows: /dev/vhci close Debugfs writer Suspend worker --------------- -------------- -------------- vhci_release() force_suspend_write() flush_work() returns [not queued yet] schedule_work() --> hci_suspend_dev() check powered check !HCI_UNREGISTER hci_suspend_sync() unlock(req_lock) vhci_debugfs_remove() wait for writer hci_unregister_dev() hci_free_dev() drop last reference free hdev hci_clear_wake_reason() lock freed mutex use-after-free The controller locks serialize state access but do not retain the allocation. Unregister drains HCI-owned work, but does not cover VHCI's suspend_work on the system workqueue. Flush suspend_work again after removing the debugfs entries and before unregistering the controller. Removal waits for active writers and prevents new callbacks, so the second flush drains all remaining work while the controller and driver data are still alive. Retain the initial flush to preserve the existing teardown order. Runtime testing of this change was not performed. KASAN report as below: ================================================================== BUG: KASAN: use-after-free in __mutex_lock+0x1e68/0x2590 Read of size 8 at addr ffff8881011b80b0 by task kworker/0:0/9 Workqueue: events vhci_suspend_work Call Trace: dump_stack_lvl+0x93/0xd0 print_report+0xce/0x630 ? __mutex_lock+0x1e68/0x2590 ? srso_alias_return_thunk+0x5/0xfbef5 ? __virt_addr_valid+0x20d/0x410 ? __mutex_lock+0x1e68/0x2590 kasan_report+0xe0/0x110 ? __mutex_lock+0x1e68/0x2590 __mutex_lock+0x1e68/0x2590 ? hci_suspend_dev+0x1ff/0x650 ? srso_alias_return_thunk+0x5/0xfbef5 ? mark_held_locks+0x40/0x70 ? _raw_spin_unlock_irqrestore+0x44/0x60 ? srso_alias_return_thunk+0x5/0xfbef5 ? lockdep_hardirqs_on_prepare+0xea/0x1a0 ? srso_alias_return_thunk+0x5/0xfbef5 ? __pfx___mutex_lock+0x10/0x10 ? _raw_spin_unlock_irqrestore+0x44/0x60 ? srso_alias_return_thunk+0x5/0xfbef5 ? pmbd_gate_site_armed+0x31/0x1c0 ? srso_alias_return_thunk+0x5/0xfbef5 ? __pfx_pmbd_probe_hit_cookie+0x10/0x10 ? hci_suspend_dev+0x1ff/0x650 hci_suspend_dev+0x1ff/0x650 vhci_suspend_work+0xa5/0x190 process_one_work+0x908/0x19c0 ? __pfx_process_one_work+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? lock_is_held_type+0x8f/0x100 ? srso_alias_return_thunk+0x5/0xfbef5 worker_thread+0x65c/0xe40 ? __pfx_worker_thread+0x10/0x10 kthread+0x34f/0x460 ? srso_alias_return_thunk+0x5/0xfbef5 ? __pfx_kthread+0x10/0x10 ret_from_fork+0x659/0x940 ? __pfx_ret_from_fork+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? __switch_to+0x74f/0xf80 ? __pfx_kthread+0x10/0x10 ret_from_fork_asm+0x1a/0x30 The buggy address belongs to the physical page: page: refcount:0 mapcount:0 mapping:0000000000000000 index:0xffff8881011b9040 pfn:0x1011b8 flags: 0x200000000000000(node=0|zone=2) raw: 0200000000000000 ffffea0004073308 ffff88818863f180 0000000000000000 raw: ffff8881011b9040 0000000000000000 00000000ffffffff 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff8881011b7f80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ffff8881011b8000: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff >ffff8881011b8080: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ^ ffff8881011b8100: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ffff8881011b8180: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ================================================================== Fixes: d16e6d19ccc6 ("Bluetooth: hci_vhci: Fix calling hci_{suspend,resume}_dev") Assisted-by: LLM Signed-off-by: Cen Zhang Tested-by: Chad Aldreda Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/hci_vhci.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/bluetooth/hci_vhci.c b/drivers/bluetooth/hci_vhci.c index 8f7db0102b25fa..bedba3c140ac20 100644 --- a/drivers/bluetooth/hci_vhci.c +++ b/drivers/bluetooth/hci_vhci.c @@ -701,6 +701,8 @@ static int vhci_release(struct inode *inode, struct file *file) if (hdev) { if (!IS_ERR_OR_NULL(hdev->debugfs)) vhci_debugfs_remove(hdev); + /* Drain work queued by the last force_suspend writers. */ + flush_work(&data->suspend_work); hci_unregister_dev(hdev); hci_free_dev(hdev); } From f8ba3e2e82f06cbd469d6ee249fbf86c138247c9 Mon Sep 17 00:00:00 2001 From: Cen Zhang Date: Sat, 24 Oct 2026 23:28:23 +0800 Subject: [PATCH 0444/2102] Bluetooth: vhci: Serialize packet reception with device creation The hci_dev passed to hci_recv_frame() must stay alive until the receive operation finishes. __vhci_create_device() stores data->hdev before hci_register_dev() and frees the device if registration fails. vhci_get_user() checks and uses that pointer without taking the open_mutex held by the creator or a device reference. An incoming packet write can overlap the delayed default-create work scheduled by vhci_open(). If registration fails before acquiring the registration reference, the following order is possible: Default-create work Packet write vhci_create_device() mutex_lock(open_mutex) data->hdev = hdev vhci_get_user() load data->hdev hci_register_dev() fails hci_free_dev(hdev) bt_host_release(): kfree(hdev) data->hdev = NULL mutex_unlock(open_mutex) hci_recv_frame(hdev, skb) read hdev->flags The packet retains the pointer before the final put and reads flags after the allocation is freed. The HCI_UP/HCI_INIT test therefore accesses freed memory before it can reject the packet. Hold open_mutex from the packet-side pointer check until hci_recv_frame() returns. Creation and its error cleanup already hold this mutex, so the writer waits until they finish and cannot retain a failed device allocation. Release the mutex on the missing-device error path too. KASAN report as below: BUG: KASAN: use-after-free in hci_recv_frame+0x4e/0x7e0 Read of size 8 at addr ffff888107034138 by task python3/500 Call Trace: dump_stack_lvl+0x93/0xd0 print_report+0xce/0x630 ? hci_recv_frame+0x4e/0x7e0 ? srso_alias_return_thunk+0x5/0xfbef5 ? __virt_addr_valid+0x20d/0x410 ? hci_recv_frame+0x4e/0x7e0 kasan_report+0xe0/0x110 ? hci_recv_frame+0x4e/0x7e0 kasan_check_range+0x105/0x1b0 hci_recv_frame+0x4e/0x7e0 vhci_write+0x35a/0x4c0 vfs_write+0x637/0x1010 ? __pfx_vhci_write+0x10/0x10 ? __might_fault+0xdd/0x190 ? __pfx_vfs_write+0x10/0x10 ? __pfx_hrtimer_wakeup+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? srso_alias_return_thunk+0x5/0xfbef5 ? common_nsleep_timens+0xa8/0x160 ksys_write+0x111/0x200 ? __pfx_ksys_write+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? restore_fpregs_from_fpstate+0x55/0x100 do_syscall_64+0x115/0x6a0 entry_SYSCALL_64_after_hwframe+0x77/0x7f The buggy address belongs to the physical page: page: refcount:0 mapcount:0 mapping:0000000000000000 index:0xffff888107036a40 pfn:0x107034 flags: 0x200000000000000(node=0|zone=2) raw: 0200000000000000 ffffea00041c0308 ffff8881887bf180 0000000000000000 raw: ffff888107036a40 0000000000000000 00000000ffffffff 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff888107034000: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ffff888107034080: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff >ffff888107034100: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ^ ffff888107034180: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ffff888107034200: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ================================================================== Fixes: 23424c0d3169 ("Bluetooth: Add support creating virtual AMP controllers") Assisted-by: LLM Signed-off-by: Cen Zhang Tested-by: Chad Aldreda Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/hci_vhci.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/bluetooth/hci_vhci.c b/drivers/bluetooth/hci_vhci.c index bedba3c140ac20..7fec02705e58bf 100644 --- a/drivers/bluetooth/hci_vhci.c +++ b/drivers/bluetooth/hci_vhci.c @@ -524,7 +524,9 @@ static inline ssize_t vhci_get_user(struct vhci_data *data, case HCI_ACLDATA_PKT: case HCI_SCODATA_PKT: case HCI_ISODATA_PKT: + mutex_lock(&data->open_mutex); if (!data->hdev) { + mutex_unlock(&data->open_mutex); kfree_skb(skb); return -ENODEV; } @@ -532,6 +534,7 @@ static inline ssize_t vhci_get_user(struct vhci_data *data, hci_skb_pkt_type(skb) = pkt_type; ret = hci_recv_frame(data->hdev, skb); + mutex_unlock(&data->open_mutex); break; case HCI_VENDOR_PKT: From df33621e70363df4d6963ad5ff19a3ae740c7703 Mon Sep 17 00:00:00 2001 From: Cen Zhang Date: Sun, 25 Oct 2026 00:35:21 +0800 Subject: [PATCH 0445/2102] Bluetooth: L2CAP: Protect the receive reject-list lookup Reject-list entries must remain alive throughout a lookup. Management updates the list under hdev->lock, but l2cap_recv_frame() traverses it under conn->lock after l2cap_recv_acldata() has released hdev->lock. An established LE connection can still receive ACL data after its peer has been added to the reject list. If a management socket unblocks that peer during the receive-side lookup, the following ordering is possible: HCI receive Management l2cap_recv_acldata() release hdev->lock acquire conn->lock l2cap_recv_frame() lookup selects entry unblock_device() acquire hdev->lock hci_bdaddr_list_del() unlink and kfree(entry) read entry->bdaddr_type Management does not take conn->lock, so deletion can free the selected entry before the lookup reads its fields. This causes a use-after-free read in hci_bdaddr_list_lookup(). Compute the reject decision under the existing device lock in l2cap_recv_acldata() and pass only the boolean to l2cap_recv_frame(). For pending receive data, take the snapshot in l2cap_conn_ready() and l2cap_security_cfm(), which already hold hdev->lock. Publish it under conn->lock before queuing the worker on the existing device workqueue: HCI callback Pending RX worker hold hdev->lock acquire conn->lock lookup reject list save boolean; queue work release conn->lock acquire conn->lock consume boolean drain pending frames The snapshot belongs to the scheduled batch. A subsequent scheduling callback refreshes it under both locks, including when queue_work() coalesces with already pending work. No reject-list pointer survives the lookup, and the worker reads the boolean under conn->lock. Taking the device lock in the worker would deadlock against l2cap_conn_del(), which holds it while cancelling the work synchronously. A failed trylock followed by immediate self-requeue would instead keep retrying without a delay and extend a concurrent workqueue drain. Keep the lookup in the scheduling callbacks so the worker needs neither the device lock nor a retry. Skip scheduling when pending_rx is empty. KASAN report as below: ================================================================== BUG: KASAN: slab-use-after-free in hci_bdaddr_list_lookup+0x145/0x160 Read of size 1 at addr ffff88810cba64d6 by task kworker/u17:0/493 Workqueue: hci0 hci_rx_work Call Trace: dump_stack_lvl+0x93/0xd0 print_report+0xce/0x630 ? hci_bdaddr_list_lookup+0x145/0x160 ? srso_alias_return_thunk+0x5/0xfbef5 ? __virt_addr_valid+0x20d/0x410 ? hci_bdaddr_list_lookup+0x145/0x160 kasan_report+0xe0/0x110 ? hci_bdaddr_list_lookup+0x145/0x160 hci_bdaddr_list_lookup+0x145/0x160 l2cap_recv_frame+0x865/0x8830 ? srso_alias_return_thunk+0x5/0xfbef5 ? __mutex_lock+0x182c/0x2590 ? __pfx_l2cap_recv_frame+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? find_held_lock+0x2b/0x80 ? l2cap_recv_acldata+0x1eb/0x10e0 ? __pfx___mutex_lock+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? __mutex_unlock_slowpath+0x147/0x920 ? __pfx_l2cap_conn_hold_unless_zero+0x10/0x10 ? __pfx_hci_conn_enter_active_mode+0x10/0x10 ? l2cap_recv_acldata+0x13d/0x10e0 ? srso_alias_return_thunk+0x5/0xfbef5 l2cap_recv_acldata+0xe9f/0x10e0 ? srso_alias_return_thunk+0x5/0xfbef5 hci_rx_work+0x5a6/0xf00 ? srso_alias_return_thunk+0x5/0xfbef5 process_one_work+0x908/0x19c0 ? __pfx_process_one_work+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? lock_is_held_type+0x8f/0x100 ? srso_alias_return_thunk+0x5/0xfbef5 worker_thread+0x65c/0xe40 ? __pfx_worker_thread+0x10/0x10 kthread+0x34f/0x460 ? srso_alias_return_thunk+0x5/0xfbef5 ? __pfx_kthread+0x10/0x10 ret_from_fork+0x659/0x940 ? __pfx_ret_from_fork+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? __switch_to+0x74f/0xf80 ? __pfx_kthread+0x10/0x10 ret_from_fork_asm+0x1a/0x30 Allocated by task 604: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 __kasan_kmalloc+0xaa/0xb0 __kmalloc_cache_noprof+0x251/0x610 hci_bdaddr_list_add+0xdf/0x2c0 block_device+0x112/0x260 hci_sock_sendmsg+0x128b/0x22e0 sock_write_iter+0x4c0/0x550 do_iter_readv_writev+0x59c/0x860 vfs_writev+0x30e/0xc10 do_writev+0x241/0x2f0 do_syscall_64+0x115/0x6a0 entry_SYSCALL_64_after_hwframe+0x77/0x7f Freed by task 606: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 kasan_save_free_info+0x3b/0x60 __kasan_slab_free+0x5f/0x80 kfree+0x307/0x580 hci_bdaddr_list_del+0x1a9/0x2a0 unblock_device+0x112/0x260 hci_sock_sendmsg+0x128b/0x22e0 sock_write_iter+0x4c0/0x550 do_iter_readv_writev+0x59c/0x860 vfs_writev+0x30e/0xc10 do_writev+0x241/0x2f0 do_syscall_64+0x115/0x6a0 entry_SYSCALL_64_after_hwframe+0x77/0x7f The buggy address belongs to the object at ffff88810cba64c0 which belongs to the cache kmalloc-32 of size 32 The buggy address is located 22 bytes inside of freed 32-byte region [ffff88810cba64c0, ffff88810cba64e0) The buggy address belongs to the physical page: page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x10cba6 flags: 0x200000000000000(node=0|zone=2) page_type: f5(slab) raw: 0200000000000000 ffff888100042780 dead000000000100 dead000000000122 raw: 0000000000000000 0000000000400040 00000000f5000000 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff88810cba6380: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc ffff88810cba6400: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc >ffff88810cba6480: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc ^ ffff88810cba6500: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc ffff88810cba6580: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc ================================================================== Fixes: cc8dba2bc302 ("Bluetooth: Block ATT connection on LE when device is blocked") Assisted-by: LLM Signed-off-by: Cen Zhang Signed-off-by: Luiz Augusto von Dentz --- include/net/bluetooth/l2cap.h | 1 + net/bluetooth/l2cap_core.c | 61 +++++++++++++++++++++++++---------- 2 files changed, 45 insertions(+), 17 deletions(-) diff --git a/include/net/bluetooth/l2cap.h b/include/net/bluetooth/l2cap.h index 2a05bda8ab4321..bb2839972cf3ff 100644 --- a/include/net/bluetooth/l2cap.h +++ b/include/net/bluetooth/l2cap.h @@ -636,6 +636,7 @@ struct l2cap_conn { struct sk_buff_head pending_rx; struct work_struct pending_rx_work; + bool pending_rx_blocked __guarded_by(&lock); struct delayed_work id_addr_timer; diff --git a/net/bluetooth/l2cap_core.c b/net/bluetooth/l2cap_core.c index 0398cc5a2dc0a5..486b968143d3cc 100644 --- a/net/bluetooth/l2cap_core.c +++ b/net/bluetooth/l2cap_core.c @@ -1747,10 +1747,40 @@ static void l2cap_le_conn_ready(struct l2cap_conn *conn) } } -static void l2cap_conn_ready(struct l2cap_conn *conn) +static bool l2cap_is_blocked(struct hci_conn *hcon) + __must_hold(&hcon->hdev->lock) +{ + /* Since we can't actively block incoming LE connections we must + * at least ensure that we ignore incoming data from them. + */ + return hcon->type == LE_LINK && + hci_bdaddr_list_lookup(&hcon->hdev->reject_list, &hcon->dst, + bdaddr_dst_type(hcon)); +} + +static void l2cap_queue_pending_rx(struct hci_conn *hcon) + __must_hold(&hcon->hdev->lock) { + struct l2cap_conn *conn = hcon->l2cap_data; + + mutex_lock(&conn->lock); + + if (!skb_queue_empty(&conn->pending_rx)) { + /* Teardown holds hdev->lock while cancelling the worker. + * Pass the decision under conn->lock to avoid that lock. + */ + conn->pending_rx_blocked = l2cap_is_blocked(hcon); + queue_work(hcon->hdev->workqueue, &conn->pending_rx_work); + } + + mutex_unlock(&conn->lock); +} + +static void l2cap_conn_ready(struct hci_conn *hcon) + __must_hold(&hcon->hdev->lock) +{ + struct l2cap_conn *conn = hcon->l2cap_data; struct l2cap_chan *chan; - struct hci_conn *hcon = conn->hcon; BT_DBG("conn %p", conn); @@ -1782,7 +1812,7 @@ static void l2cap_conn_ready(struct l2cap_conn *conn) if (hcon->type == LE_LINK) l2cap_le_conn_ready(conn); - queue_work(hcon->hdev->workqueue, &conn->pending_rx_work); + l2cap_queue_pending_rx(hcon); } /* Notify sockets that we cannot guaranty reliability anymore */ @@ -7391,7 +7421,8 @@ static void l2cap_conless_channel(struct l2cap_conn *conn, __le16 psm, kfree_skb(skb); } -static void l2cap_recv_frame(struct l2cap_conn *conn, struct sk_buff *skb) +static void l2cap_recv_frame(struct l2cap_conn *conn, struct sk_buff *skb, + bool blocked) __must_hold(&conn->lock) { struct l2cap_hdr *lh = (void *) skb->data; @@ -7418,12 +7449,7 @@ static void l2cap_recv_frame(struct l2cap_conn *conn, struct sk_buff *skb) return; } - /* Since we can't actively block incoming LE connections we must - * at least ensure that we ignore incoming data from them. - */ - if (hcon->type == LE_LINK && - hci_bdaddr_list_lookup(&hcon->hdev->reject_list, &hcon->dst, - bdaddr_dst_type(hcon))) { + if (blocked) { kfree_skb(skb); return; } @@ -7471,7 +7497,7 @@ static void process_pending_rx(struct work_struct *work) */ while (!test_bit(HCI_CONN_ENC_KEY_SIZE_PEND, conn->hcon->flags) && (skb = skb_dequeue(&conn->pending_rx))) - l2cap_recv_frame(conn, skb); + l2cap_recv_frame(conn, skb, conn->pending_rx_blocked); mutex_unlock(&conn->lock); } @@ -7923,7 +7949,7 @@ static void l2cap_connect_cfm(struct hci_conn *hcon, u8 status) mutex_unlock(&conn->lock); - l2cap_conn_ready(conn); + l2cap_conn_ready(hcon); } int l2cap_disconn_ind(struct hci_conn *hcon) @@ -8062,8 +8088,7 @@ static void l2cap_security_cfm(struct hci_conn *hcon, u8 status, u8 encrypt) mutex_unlock(&conn->lock); /* Process data held back while the encryption key size was read */ - if (!skb_queue_empty(&conn->pending_rx)) - queue_work(hcon->hdev->workqueue, &conn->pending_rx_work); + l2cap_queue_pending_rx(hcon); } /* Append fragment into frame respecting the maximum len of rx_skb */ @@ -8152,6 +8177,7 @@ int l2cap_recv_acldata(struct hci_dev *hdev, u16 handle, { struct hci_conn *hcon; struct l2cap_conn *conn; + bool blocked; int len; /* Lock hdev for hci_conn, and race on l2cap_data vs. l2cap_conn_del */ @@ -8174,6 +8200,7 @@ int l2cap_recv_acldata(struct hci_dev *hdev, u16 handle, conn = l2cap_conn_add(hcon); conn = l2cap_conn_hold_unless_zero(conn); + blocked = l2cap_is_blocked(hcon); hcon = NULL; hci_dev_unlock(hdev); @@ -8210,7 +8237,7 @@ int l2cap_recv_acldata(struct hci_dev *hdev, u16 handle, if (len == skb->len) { /* Complete frame received */ - l2cap_recv_frame(conn, skb); + l2cap_recv_frame(conn, skb, blocked); goto unlock; } @@ -8234,7 +8261,7 @@ int l2cap_recv_acldata(struct hci_dev *hdev, u16 handle, * setting the socket unreliable. */ skb->len = len; - l2cap_recv_frame(conn, skb); + l2cap_recv_frame(conn, skb, blocked); l2cap_conn_unreliable(conn, ECOMM); goto unlock; } @@ -8284,7 +8311,7 @@ int l2cap_recv_acldata(struct hci_dev *hdev, u16 handle, */ struct sk_buff *rx_skb = conn->rx_skb; conn->rx_skb = NULL; - l2cap_recv_frame(conn, rx_skb); + l2cap_recv_frame(conn, rx_skb, blocked); } break; } From c5bdb87573726d3a10c58bb3ae09daf017be2297 Mon Sep 17 00:00:00 2001 From: Zhongqiu Han Date: Tue, 10 Nov 2026 21:58:14 +0800 Subject: [PATCH 0446/2102] cpufreq: Skip inactive policies in cpufreq_driver_target() A policy obtained with cpufreq_cpu_get() may become inactive before cpufreq_driver_target() acquires its rwsem, which may lead to a NULL pointer dereference: CPU X CPU Y (last CPU in policy) cpufreq_cpu_get() cpufreq_offline() __cpufreq_offline() ->exit() /* frees freq_table */ policy->freq_table = NULL cpufreq_driver_target() __cpufreq_driver_target() __target_index() policy->freq_table[index] /* NULL dereference */ Before commit 2372784542cb ("cpufreq: Drop 'freq_table' argument of __target_index()"), __cpufreq_driver_target() returned an error if policy->freq_table was NULL. Since the offline path clears it under the policy rwsem, which cpufreq_driver_target() also holds, that check was sufficient to prevent the crash. The race has been reachable in-tree since commit c210063b40ac ("cpufreq: mediatek: Add opp notification support"), which added the first caller of cpufreq_driver_target() that can run concurrently with CPU offline. Address this by making cpufreq_driver_target() return -EBUSY if the policy is inactive after acquiring its rwsem, in analogy with the checks in cpufreq_get(), refresh_frequency_limits() and the sysfs show() and store() callbacks. Reported-by: Sashiko Closes: https://sashiko.dev/#/patchset/20261104153042.3987338-1-zhongqiu.han%40oss.qualcomm.com Fixes: 2372784542cb ("cpufreq: Drop 'freq_table' argument of __target_index()") Fixes: c210063b40ac ("cpufreq: mediatek: Add opp notification support") Cc: 5.19+ # v5.19+ Signed-off-by: Zhongqiu Han Link: https://patch.msgid.link/20261110135814.621355-1-zhongqiu.han@oss.qualcomm.com Signed-off-by: Rafael J. Wysocki --- drivers/cpufreq/cpufreq.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/cpufreq/cpufreq.c b/drivers/cpufreq/cpufreq.c index 24319b214d7ba9..4332cb1140701d 100644 --- a/drivers/cpufreq/cpufreq.c +++ b/drivers/cpufreq/cpufreq.c @@ -2452,6 +2452,14 @@ int cpufreq_driver_target(struct cpufreq_policy *policy, { guard(cpufreq_policy_write)(policy); + /* + * The last CPU in the policy may have gone offline after the caller + * obtained it, in which case the policy is inactive and must not be + * used for changing the frequency. + */ + if (unlikely(policy_is_inactive(policy))) + return -EBUSY; + return __cpufreq_driver_target(policy, target_freq, relation); } EXPORT_SYMBOL_GPL(cpufreq_driver_target); From 2de253924266eeedb798fb662173726c90b0cf04 Mon Sep 17 00:00:00 2001 From: Eric Biggers Date: Tue, 10 Nov 2026 13:20:11 -0800 Subject: [PATCH 0447/2102] fscrypt: Initialize ->ci_master_key before publication fscrypt_prepare_setflags() assumes that if the key for an inode with a v2 encryption policy has been set up, then ->ci_master_key is non-NULL. This is a reasonable assumption, but it does not take into account the very short gap in fscrypt_setup_encryption_info() between the inode's fscrypt_inode_info being set and ->ci_master_key being initialized. Thus, a NULL pointer dereference was possible. Fix this by closing the gap: make fscrypt_setup_encryption_info() initialize ->ci_master_key before publication. If it loses the cmpxchg race afterwards, set it back to NULL so that put_crypt_info() continues to have the same behavior. Fixes: b1c0ec3599f4 ("fscrypt: add FS_IOC_REMOVE_ENCRYPTION_KEY ioctl") Cc: stable@vger.kernel.org Reported-by: Ada Smith Link: https://patch.msgid.link/20261110212011.35487-1-ebiggers@kernel.org Signed-off-by: Eric Biggers --- fs/crypto/keysetup.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/fs/crypto/keysetup.c b/fs/crypto/keysetup.c index a77b889d7578cb..0beec01c041850 100644 --- a/fs/crypto/keysetup.c +++ b/fs/crypto/keysetup.c @@ -621,6 +621,13 @@ fscrypt_setup_encryption_info(struct inode *inode, if (res) goto out; + /* + * Preemptively initialize ->ci_master_key, even though we don't know + * whether we'll win the race below yet, because if we do win the race + * then other tasks can see it right away and need ->ci_master_key. + */ + crypt_info->ci_master_key = mk; + /* * For existing inodes, multiple tasks may race to set the inode's * fscrypt info pointer. So use cmpxchg_release(). This pairs with the @@ -634,7 +641,6 @@ fscrypt_setup_encryption_info(struct inode *inode, * crypt_info. Now link it into the master key's inode list. */ if (mk) { - crypt_info->ci_master_key = mk; refcount_inc(&mk->mk_active_refs); spin_lock(&mk->mk_decrypted_inodes_lock); list_add(&crypt_info->ci_master_key_link, @@ -642,6 +648,12 @@ fscrypt_setup_encryption_info(struct inode *inode, spin_unlock(&mk->mk_decrypted_inodes_lock); } crypt_info = NULL; + } else { + /* + * Lost the race, so we won't be taking an active reference to + * the master key. Clear ->ci_master_key accordingly. + */ + crypt_info->ci_master_key = NULL; } res = 0; out: From 809f39842c1706089e0de82b5c1d851d84eec4dc Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Thu, 22 Oct 2026 12:29:08 -0700 Subject: [PATCH 0448/2102] KVM: nVMX: Clear nested.smm.guest_mode when freeing nested state If an SMI arrives while L2 is active, vmx_enter_smm() forces a VM-Exit to L1, and records in nested.smm.guest_mode that RSM has to re-enter L2 and in nested.smm.vmxon that the vCPU was post-VMXON. free_nested() clears the latter, but not the former. Userspace can get KVM to free the nested state while the vCPU is in SMM, with KVM_SET_NESTED_STATE, e.g. with no VMXON region to say that the vCPU isn't in VMX operation, or by flipping the SMM flag back and forth with KVM_SET_VCPU_EVENTS. When the guest then executes RSM, vmx_leave_smm() tries to re-enter L2 even though there is no vmcs12 any more, and nested_vmx_check_restored_vmcs12() dereferences the NULL nested.cached_vmcs12. Clear nested.smm.guest_mode along with the state that it refers to. Fixes: 8fcc4b5923af ("kvm: nVMX: Introduce KVM_CAP_NESTED_STATE") Reported-by: Karthikeyan Bhargavan Cc: stable@vger.kernel.org Assisted-by: LLM Cc: Chris Mason Co-developed-by: Amirmohammad Eftekhar Signed-off-by: Amirmohammad Eftekhar Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261022192908.554376-1-seanjc@google.com Signed-off-by: Sean Christopherson --- arch/x86/kvm/vmx/nested.c | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/x86/kvm/vmx/nested.c b/arch/x86/kvm/vmx/nested.c index fa50129ea5847d..cd9465f4ee343d 100644 --- a/arch/x86/kvm/vmx/nested.c +++ b/arch/x86/kvm/vmx/nested.c @@ -349,6 +349,7 @@ static void free_nested(struct kvm_vcpu *vcpu) vmx->nested.vmxon = false; vmx->nested.smm.vmxon = false; + vmx->nested.smm.guest_mode = false; vmx->nested.vmxon_ptr = INVALID_GPA; free_vpid(vmx->nested.vpid02); vmx->nested.posted_intr_nv = -1; From bcc359264f15095d3d167535cf5de0b7e4800279 Mon Sep 17 00:00:00 2001 From: Amirmohammad Eftekhar Date: Sat, 17 Oct 2026 11:30:10 +0200 Subject: [PATCH 0449/2102] KVM: nVMX: Clear nested.smm.guest_mode on a failed RSM-to-L2 vmx_leave_smm() consumes nested.smm.vmxon into nested.vmxon up front, but clears nested.smm.guest_mode only on the success path. On either failure arm (nested_vmx_check_restored_vmcs12() < 0, or nested_vmx_enter_non_root_mode() != NVMX_VMENTRY_SUCCESS) it returns early with nested.smm.guest_mode still true while nested.smm.vmxon is already false. em_rsm() turns that non-zero return into a triple fault, but the vCPU is left with the internal pair (smm.guest_mode=true, smm.vmxon=false). That pair is not representable in migration state: vmx_get_nested_state() serializes KVM_STATE_NESTED_SMM_GUEST_MODE without KVM_STATE_NESTED_SMM_VMXON, and vmx_set_nested_state() rejects exactly SMM_GUEST_MODE && !SMM_VMXON with -EINVAL. KVM thus serializes a state it refuses to restore -- a save/restore (live-migration) round-trip break. The leak is sticky: free_nested() and vCPU reset do not clear nested.smm.guest_mode (kvm_vcpu_reset() gates the nested unwind on is_guest_mode(), false here), so a later VMXON re-exposes the bad KVM_GET_NESTED_STATE with no SMI/RSM involved, for the life of the vCPU. Clear nested.smm.guest_mode before the consistency check and re-entry, so it is cleared on every exit from the block. nested.vmxon is left true, which is correct (L1 does have VMX on) and round-trips cleanly on its own. Not a memory-safety issue; fidelity / migration only. Cc: stable@vger.kernel.org Signed-off-by: Amirmohammad Eftekhar Link: https://patch.msgid.link/20261017093016.32348-1-amirmohammad.eftekhar@cispa.de Signed-off-by: Sean Christopherson --- arch/x86/kvm/vmx/vmx.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/arch/x86/kvm/vmx/vmx.c b/arch/x86/kvm/vmx/vmx.c index fffdc6e5a7e770..af52568b551b9f 100644 --- a/arch/x86/kvm/vmx/vmx.c +++ b/arch/x86/kvm/vmx/vmx.c @@ -8376,6 +8376,12 @@ int vmx_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram) } if (vmx->nested.smm.guest_mode) { + /* + * Note, even if RSM ultimately fails (hits SHUTDOWN), the vCPU + * is no longer in SMM with the intent to return to L2. + */ + vmx->nested.smm.guest_mode = false; + /* Triple fault if the state is invalid. */ if (nested_vmx_check_restored_vmcs12(vcpu) < 0) return 1; @@ -8385,7 +8391,6 @@ int vmx_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram) return 1; vcpu->arch.nested_run_pending = KVM_NESTED_RUN_PENDING; - vmx->nested.smm.guest_mode = false; } return 0; } From f96c59f40d1ef1fb8378ad11eed796338e20eec2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Mah=C3=A9?= Date: Mon, 9 Nov 2026 18:55:49 +0100 Subject: [PATCH 0450/2102] riscv: defconfig: enable onboard USB hub support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Banana Pi BPI-F3 (SpacemiT K1) has a VL817 USB 3.0 hub behind its DWC3 controller. The hub's power and reset come from the "usb2109,2817" and "usb2109,817" nodes in the device tree, which need the onboard_usb_dev driver. Without it, the hub regulator (USB30_HUB) stays off and the board's four USB-A ports are dead. Enable USB_ONBOARD_DEV as a module, as arm64 defconfig does. Tested on a Banana Pi BPI-F3 with v7.4-rc1 (dwc3 enabled as a module): the module autoloads, the hub comes up on both buses and a USB mouse on a USB-A port works. Without it, only the root hubs are seen. This patch was prepared with the help of an AI assistant (Claude), which also ran the build and boot tests. Signed-off-by: Frédéric Mahé Link: https://patch.msgid.link/20261109175555.323067-1-frederic.mahe@cirad.fr Signed-off-by: Paul Walmsley --- arch/riscv/configs/defconfig | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/riscv/configs/defconfig b/arch/riscv/configs/defconfig index 933cbf2735eca5..383fdd07a99f8e 100644 --- a/arch/riscv/configs/defconfig +++ b/arch/riscv/configs/defconfig @@ -223,6 +223,7 @@ CONFIG_USB_CDNS3_HOST=y CONFIG_USB_CDNS3_STARFIVE=m CONFIG_USB_MUSB_HDRC=m CONFIG_USB_MUSB_SUNXI=m +CONFIG_USB_ONBOARD_DEV=m CONFIG_NOP_USB_XCEIV=m CONFIG_USB_GADGET=y CONFIG_USB_CONFIGFS=m From 36eeb26031e90eeb81bbac3d3acad61d23fcbdf3 Mon Sep 17 00:00:00 2001 From: Christopher Hoover Date: Sun, 18 Oct 2026 19:34:19 -0700 Subject: [PATCH 0451/2102] iio: temperature: hid-sensor-temperature: Use per-instance callbacks hid-sensor-temperature keeps a single static struct hid_sensor_hub_callbacks for all instances and overwrites its pdev in every probe. With two temperature sensors, input reports for one are delivered with the other's platform device; once that device is removed, platform_get_drvdata() returns NULL and temperature_capture_sample() dereferences it: BUG: kernel NULL pointer dereference, address: 00000000000003a8 RIP: 0010:temperature_capture_sample+0xd/0x50 [hid_sensor_temperature] The oops happens in sensor_hub_raw_event() with the hub's spinlock held, so the hub's removal then hangs. It reproduces with two uhid devices that each declare a temperature sensor, one destroyed while the other still sends input reports. Keep the callbacks in struct temperature_state, as the other HID sensor drivers (accel, gyro, als, ...) do. Fixes: 59d0f2da3569 ("iio: hid: Add temperature sensor support") Cc: stable@vger.kernel.org Signed-off-by: Christopher Hoover Reviewed-by: Joshua Crofts Acked-by: Srinivas Pandruvada Signed-off-by: Jonathan Cameron --- drivers/iio/temperature/hid-sensor-temperature.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/drivers/iio/temperature/hid-sensor-temperature.c b/drivers/iio/temperature/hid-sensor-temperature.c index 5e3262e461f463..ae67daff6df5a2 100644 --- a/drivers/iio/temperature/hid-sensor-temperature.c +++ b/drivers/iio/temperature/hid-sensor-temperature.c @@ -15,6 +15,7 @@ struct temperature_state { struct hid_sensor_common common_attributes; struct hid_sensor_hub_attribute_info temperature_attr; + struct hid_sensor_hub_callbacks callbacks; struct { s32 temperature_data; aligned_s64 timestamp; @@ -181,11 +182,6 @@ static int temperature_parse_report(struct platform_device *pdev, return ret; } -static struct hid_sensor_hub_callbacks temperature_callbacks = { - .send_event = &temperature_proc_event, - .capture_sample = &temperature_capture_sample, -}; - /* Function to initialize the processing for usage id */ static int hid_temperature_probe(struct platform_device *pdev) { @@ -237,9 +233,13 @@ static int hid_temperature_probe(struct platform_device *pdev) platform_set_drvdata(pdev, indio_dev); - temperature_callbacks.pdev = pdev; + temp_st->callbacks = (struct hid_sensor_hub_callbacks) { + .send_event = temperature_proc_event, + .capture_sample = temperature_capture_sample, + .pdev = pdev, + }; ret = sensor_hub_register_callback(hsdev, HID_USAGE_SENSOR_TEMPERATURE, - &temperature_callbacks); + &temp_st->callbacks); if (ret) goto error_remove_trigger; From bbe4f3f668babc9443fc1f075695e43e17ca7976 Mon Sep 17 00:00:00 2001 From: Christopher Hoover Date: Sun, 18 Oct 2026 19:34:20 -0700 Subject: [PATCH 0452/2102] iio: humidity: hid-sensor-humidity: Use per-instance callbacks hid-sensor-humidity keeps a single static struct hid_sensor_hub_callbacks for all instances and overwrites its pdev in every probe, so with two humidity sensors, input reports for one are delivered with the other's platform device, and a NULL dereference follows once that device is removed. The same bug was found in hid-sensor-temperature, which shares this code. Keep the callbacks in struct hid_humidity_state, as the other HID sensor drivers (accel, gyro, als, ...) do. Fixes: d7ed89d5aadf ("iio: hid: Add humidity sensor support") Cc: stable@vger.kernel.org Signed-off-by: Christopher Hoover Reviewed-by: Joshua Crofts Acked-by: Srinivas Pandruvada Signed-off-by: Jonathan Cameron --- drivers/iio/humidity/hid-sensor-humidity.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/drivers/iio/humidity/hid-sensor-humidity.c b/drivers/iio/humidity/hid-sensor-humidity.c index 7cec81ff56856f..aa7d4f25c3937d 100644 --- a/drivers/iio/humidity/hid-sensor-humidity.c +++ b/drivers/iio/humidity/hid-sensor-humidity.c @@ -15,6 +15,7 @@ struct hid_humidity_state { struct hid_sensor_common common_attributes; struct hid_sensor_hub_attribute_info humidity_attr; + struct hid_sensor_hub_callbacks callbacks; struct { s32 humidity_data; aligned_s64 timestamp; @@ -184,11 +185,6 @@ static int humidity_parse_report(struct platform_device *pdev, return ret; } -static struct hid_sensor_hub_callbacks humidity_callbacks = { - .send_event = &humidity_proc_event, - .capture_sample = &humidity_capture_sample, -}; - /* Function to initialize the processing for usage id */ static int hid_humidity_probe(struct platform_device *pdev) { @@ -240,9 +236,13 @@ static int hid_humidity_probe(struct platform_device *pdev) platform_set_drvdata(pdev, indio_dev); - humidity_callbacks.pdev = pdev; + humid_st->callbacks = (struct hid_sensor_hub_callbacks) { + .send_event = humidity_proc_event, + .capture_sample = humidity_capture_sample, + .pdev = pdev, + }; ret = sensor_hub_register_callback(hsdev, HID_USAGE_SENSOR_HUMIDITY, - &humidity_callbacks); + &humid_st->callbacks); if (ret) goto error_remove_trigger; From fd4c92bbd3a64556e81042ff8d30545b15a3b93a Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 17:19:15 +0100 Subject: [PATCH 0453/2102] iio: hid-sensors: fix a division by zero convert_to_vtf_format() divides the micro part of a value by 10^(6 + exp). The unit exponent of a HID field is a nibble and goes down to -8. For -7 and -8 the argument of int_pow() is negative, which the unsigned parameter turns into a huge power of ten: 0 modulo 2^64. The division by it is a divide error. The exponent comes from the report descriptor of the sensor hub, the value from a write to the hysteresis attribute of the IIO device. Multiply by 10^(-exp - 6) in these two cases. Fixes: 73c6768b710a ("iio: hid-sensors: Common attribute and trigger") Cc: stable Signed-off-by: Josef Bacik Signed-off-by: Greg Kroah-Hartman Acked-by: Srinivas Pandruvada Signed-off-by: Jonathan Cameron --- drivers/iio/common/hid-sensors/hid-sensor-attributes.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/drivers/iio/common/hid-sensors/hid-sensor-attributes.c b/drivers/iio/common/hid-sensors/hid-sensor-attributes.c index 26f8554d18a57d..2289bb6a973431 100644 --- a/drivers/iio/common/hid-sensors/hid-sensor-attributes.c +++ b/drivers/iio/common/hid-sensors/hid-sensor-attributes.c @@ -142,7 +142,10 @@ static u32 convert_to_vtf_format(int size, int exp, int val1, int val2) if (val1 < 0 || val2 < 0) sign = -1; exp = hid_sensor_convert_exponent(exp); - if (exp < 0) { + if (exp < -6) { + value = abs(val1) * int_pow(10, -exp); + value += abs(val2) * int_pow(10, -exp - 6); + } else if (exp < 0) { divisor = int_pow(10, 6 + exp); value = abs(val1) * int_pow(10, -exp); value += abs(val2) / divisor; From d32bf759801e6df23038dc834622a122ec76a4dd Mon Sep 17 00:00:00 2001 From: Changyul Lee Date: Fri, 6 Nov 2026 12:47:37 -0500 Subject: [PATCH 0454/2102] iio: trigger: free the trigger ID after device_del() iio_trigger_unregister() returns the trigger ID to iio_trigger_ida before device_del() removes the "trigger" device. A trigger registered in between can get the same ID, and its device_add() fails: sysfs: cannot create duplicate filename '/bus/iio/devices/trigger0' For example, adding a sysfs trigger while an hrtimer trigger is being removed through configfs, or the other way around, hits this because the two paths do not share a lock. Free the ID after device_del(), as the error path of iio_trigger_register() already does, and drop the "Possible issue in here" comment. Fixes: 1637db44413e ("Staging: IIO: Trigger support added to core.") Signed-off-by: Changyul Lee Cc: stable@vger.kernel.org Signed-off-by: Jonathan Cameron --- drivers/iio/industrialio-trigger.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/iio/industrialio-trigger.c b/drivers/iio/industrialio-trigger.c index fc4651490d4243..1078ffa8e06a97 100644 --- a/drivers/iio/industrialio-trigger.c +++ b/drivers/iio/industrialio-trigger.c @@ -105,9 +105,8 @@ void iio_trigger_unregister(struct iio_trigger *trig_info) scoped_guard(mutex, &iio_trigger_list_lock) list_del(&trig_info->list); - ida_free(&iio_trigger_ida, trig_info->id); - /* Possible issue in here */ device_del(&trig_info->dev); + ida_free(&iio_trigger_ida, trig_info->id); } EXPORT_SYMBOL(iio_trigger_unregister); From 79c8dffd84e9784ec05bea68dbe5e71f7ec9941a Mon Sep 17 00:00:00 2001 From: Srinivas Pandruvada Date: Wed, 4 Nov 2026 08:53:19 -0800 Subject: [PATCH 0455/2102] iio: hid-sensors: fix fractional part for unit exponents -7 and -8 split_micro_fraction() scales the remainder to micro units by multiplying it by 10^(6 - exp). The unit exponent of a HID field goes down to -8, so exp can be 7 or 8 here. Then the argument of int_pow() is negative, which the unsigned parameter turns into a huge power of ten: 0 modulo 2^64. As a result, the fractional part of a value read from the hysteresis attributes is always reported as 0. Divide by 10^(exp - 6) in these two cases. This matches the reverse conversion in convert_to_vtf_format(). Fixes: 73c6768b710a ("iio: hid-sensors: Common attribute and trigger") Cc: stable@vger.kernel.org Signed-off-by: Srinivas Pandruvada Tested-by: Semyon Maryasin Signed-off-by: Jonathan Cameron --- drivers/iio/common/hid-sensors/hid-sensor-attributes.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/iio/common/hid-sensors/hid-sensor-attributes.c b/drivers/iio/common/hid-sensors/hid-sensor-attributes.c index 2289bb6a973431..cb7713646e2152 100644 --- a/drivers/iio/common/hid-sensors/hid-sensor-attributes.c +++ b/drivers/iio/common/hid-sensors/hid-sensor-attributes.c @@ -98,9 +98,14 @@ static void simple_div(int dividend, int divisor, int *whole, int *micro_frac) static void split_micro_fraction(unsigned int no, int exp, int *val1, int *val2) { int divisor = int_pow(10, exp); + unsigned int rem; *val1 = no / divisor; - *val2 = no % divisor * int_pow(10, 6 - exp); + rem = no % divisor; + if (exp > 6) + *val2 = rem / (unsigned int)int_pow(10, exp - 6); + else + *val2 = rem * int_pow(10, 6 - exp); } /* From 3df238d7a9f5ac7d78115958fd7a36139f61ca34 Mon Sep 17 00:00:00 2001 From: Douglas Anderson Date: Fri, 6 Nov 2026 11:38:01 -0800 Subject: [PATCH 0456/2102] kbuild: AutoFDO: Disable Profi (-fno-sample-profile-use-profi) Starting in Clang 21 (LLVM commit 2fc4a4a9d3a8 ("[Driver][SamplePGO] Enable -fsample-profile-use-profi (#146795)") [1]), the Clang driver automatically passes -mllvm -sample-profile-use-profi whenever -fprofile-sample-use is specified, enabling LLVM's flow-based profile inference algorithm (Profi) by default. However, as Rong Xu noted [2], the kernel's AutoFDO implementation uses flow-sensitive discriminators (FS-AFDO), and Profi has known issues with FS-AFDO that degrade runtime performance compared to LLVM's original profile propagation algorithm. In addition, Profi's min-cost max-flow solver (applyFlowInference) can hit pathological compile times (30+ minutes or hangs) on certain kernel control-flow graphs when profiles drift slightly or when combined with GCOV [3]. Pass -fno-sample-profile-use-profi to disable Profi and restore the original profile propagation behavior that kernel AutoFDO was tested with. Guard the flag with clang-min-version 210000 since it was introduced in Clang 21 alongside the default change, whereas CONFIG_AUTOFDO_CLANG supports Clang 17+. Note that cc-option cannot be used to probe for the flag because cc-option invokes Clang with -Werror but without -fprofile-sample-use, causing Clang to fail the probe with -Werror,-Wunused-command-line-argument. Although SampleProfileUseProfi currently defaults to false in the LLVM backend and is only enabled by the Clang driver, explicitly pass -Cllvm-args=-sample-profile-use-profi=false in RUSTFLAGS_AUTOFDO_CLANG and --mllvm=-sample-profile-use-profi=false in KBUILD_LDFLAGS as well so that C, Rust, and ThinLTO flags remain consistent even if rustc or LLVM defaults change in the future. Unlike the Clang driver flag -fno-sample-profile-use-profi (added in Clang 21), the underlying LLVM -sample-profile-use-profi option was introduced in LLVM 14, which predates the LLVM 17+ requirement of CONFIG_AUTOFDO_CLANG, so no version checks are needed for the Rust or linker flags. Cc: stable@vger.kernel.org Fixes: 315ad8780a12 ("kbuild: Add AutoFDO support for Clang build") Suggested-by: Rong Xu Reviewed-by: Rong Xu Reviewed-by: Snehasish Kumar Link: https://github.com/llvm/llvm-project/commit/2fc4a4a9d3a87a9e11c48ef25522aa17c2a71003 [1] Link: https://lore.kernel.org/r/CAF1bQ=S52KWHopqxksctbBirFEr5Mz1dKKMAoWh-dqLHii3Nig@mail.gmail.com [2] Link: https://github.com/ClangBuiltLinux/linux/issues/2188 [3] Signed-off-by: Douglas Anderson Reviewed-by: Nick Desaulniers Reported-by: Han Wang Reported-by: Yabin Cui Link: https://patch.msgid.link/20261106113800.v2.1.I0b27923381ef34cc99cdf8b65fea2e1bafce6370@changeid Signed-off-by: Nathan Chancellor --- scripts/Makefile.autofdo | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/Makefile.autofdo b/scripts/Makefile.autofdo index 57a3aba6ffc237..55fda66ad960c4 100644 --- a/scripts/Makefile.autofdo +++ b/scripts/Makefile.autofdo @@ -13,13 +13,16 @@ endif ifdef CLANG_AUTOFDO_PROFILE CFLAGS_AUTOFDO_CLANG += -fprofile-sample-use=$(CLANG_AUTOFDO_PROFILE) -ffunction-sections CFLAGS_AUTOFDO_CLANG += -fsplit-machine-functions + CFLAGS_AUTOFDO_CLANG += $(if $(call clang-min-version,210000),-fno-sample-profile-use-profi) RUSTFLAGS_AUTOFDO_CLANG += -Zprofile-sample-use=$(CLANG_AUTOFDO_PROFILE) -Zfunction-sections=y RUSTFLAGS_AUTOFDO_CLANG += -Cllvm-args=-split-machine-functions + RUSTFLAGS_AUTOFDO_CLANG += -Cllvm-args=-sample-profile-use-profi=false endif ifdef CONFIG_LTO_CLANG_THIN ifdef CLANG_AUTOFDO_PROFILE KBUILD_LDFLAGS += --lto-sample-profile=$(CLANG_AUTOFDO_PROFILE) + KBUILD_LDFLAGS += --mllvm=-sample-profile-use-profi=false endif KBUILD_LDFLAGS += --mllvm=-enable-fs-discriminator=true --mllvm=-improved-fs-discriminator=true -plugin-opt=thinlto KBUILD_LDFLAGS += $(call ld-option,-plugin-opt=-function-splitting=all,-plugin-opt=-split-machine-functions) From 715595adb6f411f568fd3e061fc93c8531d004e8 Mon Sep 17 00:00:00 2001 From: Myria Sarvay Date: Wed, 21 Oct 2026 10:53:20 +1100 Subject: [PATCH 0457/2102] arm64: Add CPU part numbers for newer Apple Silicon CPUs Add CPU part numbers and MIDR definitions for M3, M3 Pro, M3 Max, base M4, A18 Pro and M5 Pro so CPU workarounds can identify these cores. Use the SoC codenames for M4, A18 Pro and M5 Pro, with suffixes for their core types, as separate core codenames are not known. Signed-off-by: Myria Sarvay Signed-off-by: Michael Reeves Acked-by: Catalin Marinas Link: https://patch.msgid.link/20261021-apple-m3-m4-kvm-v2-1-04905152cc2a@gmail.com Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/cputype.h | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/arch/arm64/include/asm/cputype.h b/arch/arm64/include/asm/cputype.h index 6002d1d5f55f46..0cfa7b640b9c49 100644 --- a/arch/arm64/include/asm/cputype.h +++ b/arch/arm64/include/asm/cputype.h @@ -156,6 +156,18 @@ #define APPLE_CPU_PART_M2_AVALANCHE_PRO 0x035 #define APPLE_CPU_PART_M2_BLIZZARD_MAX 0x038 #define APPLE_CPU_PART_M2_AVALANCHE_MAX 0x039 +#define APPLE_CPU_PART_M3_SAWTOOTH 0x042 +#define APPLE_CPU_PART_M3_EVEREST 0x043 +#define APPLE_CPU_PART_M3_SAWTOOTH_PRO 0x044 +#define APPLE_CPU_PART_M3_EVEREST_PRO 0x045 +#define APPLE_CPU_PART_M3_SAWTOOTH_MAX 0x048 +#define APPLE_CPU_PART_M3_EVEREST_MAX 0x049 +#define APPLE_CPU_PART_M4_DONAN_ECORE 0x052 +#define APPLE_CPU_PART_M4_DONAN_PCORE 0x053 +#define APPLE_CPU_PART_A18_PRO_TAHITI_ECORE 0x060 +#define APPLE_CPU_PART_A18_PRO_TAHITI_PCORE 0x061 +#define APPLE_CPU_PART_M5_PRO_SOTRA_MCORE 0x064 +#define APPLE_CPU_PART_M5_PRO_SOTRA_PCORE 0x065 #define AMPERE_CPU_PART_AMPERE1 0xAC3 #define AMPERE_CPU_PART_AMPERE1A 0xAC4 @@ -252,6 +264,22 @@ #define MIDR_APPLE_M2_AVALANCHE_PRO MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_AVALANCHE_PRO) #define MIDR_APPLE_M2_BLIZZARD_MAX MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_BLIZZARD_MAX) #define MIDR_APPLE_M2_AVALANCHE_MAX MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_AVALANCHE_MAX) +#define MIDR_APPLE_M3_SAWTOOTH MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_SAWTOOTH) +#define MIDR_APPLE_M3_EVEREST MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_EVEREST) +#define MIDR_APPLE_M3_SAWTOOTH_PRO MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_SAWTOOTH_PRO) +#define MIDR_APPLE_M3_EVEREST_PRO MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_EVEREST_PRO) +#define MIDR_APPLE_M3_SAWTOOTH_MAX MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_SAWTOOTH_MAX) +#define MIDR_APPLE_M3_EVEREST_MAX MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_EVEREST_MAX) +#define MIDR_APPLE_M4_DONAN_ECORE MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M4_DONAN_ECORE) +#define MIDR_APPLE_M4_DONAN_PCORE MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M4_DONAN_PCORE) +#define MIDR_APPLE_A18_PRO_TAHITI_ECORE \ + MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_A18_PRO_TAHITI_ECORE) +#define MIDR_APPLE_A18_PRO_TAHITI_PCORE \ + MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_A18_PRO_TAHITI_PCORE) +#define MIDR_APPLE_M5_PRO_SOTRA_MCORE \ + MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M5_PRO_SOTRA_MCORE) +#define MIDR_APPLE_M5_PRO_SOTRA_PCORE \ + MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M5_PRO_SOTRA_PCORE) #define MIDR_AMPERE1 MIDR_CPU_MODEL(ARM_CPU_IMP_AMPERE, AMPERE_CPU_PART_AMPERE1) #define MIDR_AMPERE1A MIDR_CPU_MODEL(ARM_CPU_IMP_AMPERE, AMPERE_CPU_PART_AMPERE1A) #define MIDR_MICROSOFT_AZURE_COBALT_100 MIDR_CPU_MODEL(ARM_CPU_IMP_MICROSOFT, MICROSOFT_CPU_PART_AZURE_COBALT_100) From 736d91e59f079cc220ca348ae1d4b580f2ba0065 Mon Sep 17 00:00:00 2001 From: Michael Reeves Date: Wed, 21 Oct 2026 10:53:21 +1100 Subject: [PATCH 0458/2102] arm64: Apply existing Apple Silicon CPU workarounds to newer CPUs Add M3, M3 Pro, M3 Max, base M4, A18 Pro and M5 Pro to apple_cpus so they receive the existing PMU trap and broken SEIS workarounds. Add these CPUs to has_vgic_v3 so KVM detects TDIR support and can trap guest DIR accesses without trapping all common registers. Co-developed-by: Yureka Lilian Signed-off-by: Yureka Lilian Tested-by: Yureka Lilian Tested-by: Myria Sarvay Signed-off-by: Michael Reeves Acked-by: Catalin Marinas Link: https://patch.msgid.link/20261021-apple-m3-m4-kvm-v2-2-04905152cc2a@gmail.com Signed-off-by: Marc Zyngier --- arch/arm64/kernel/cpu_errata.c | 12 ++++++++++++ arch/arm64/kernel/cpufeature.c | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/arch/arm64/kernel/cpu_errata.c b/arch/arm64/kernel/cpu_errata.c index 38abd123c7404a..116f73afd03326 100644 --- a/arch/arm64/kernel/cpu_errata.c +++ b/arch/arm64/kernel/cpu_errata.c @@ -317,6 +317,18 @@ static const struct midr_range apple_cpus[] = { MIDR_ALL_VERSIONS(MIDR_APPLE_M2_AVALANCHE_PRO), MIDR_ALL_VERSIONS(MIDR_APPLE_M2_BLIZZARD_MAX), MIDR_ALL_VERSIONS(MIDR_APPLE_M2_AVALANCHE_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH_PRO), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST_PRO), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M4_DONAN_ECORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M4_DONAN_PCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_A18_PRO_TAHITI_ECORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_A18_PRO_TAHITI_PCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M5_PRO_SOTRA_MCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M5_PRO_SOTRA_PCORE), {}, }; diff --git a/arch/arm64/kernel/cpufeature.c b/arch/arm64/kernel/cpufeature.c index 34c5c03c0c9b4f..e69c2e2f716153 100644 --- a/arch/arm64/kernel/cpufeature.c +++ b/arch/arm64/kernel/cpufeature.c @@ -2207,6 +2207,18 @@ static bool can_trap_icv_dir_el1(const struct arm64_cpu_capabilities *entry, MIDR_ALL_VERSIONS(MIDR_APPLE_M2_AVALANCHE_PRO), MIDR_ALL_VERSIONS(MIDR_APPLE_M2_BLIZZARD_MAX), MIDR_ALL_VERSIONS(MIDR_APPLE_M2_AVALANCHE_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH_PRO), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST_PRO), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M4_DONAN_ECORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M4_DONAN_PCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_A18_PRO_TAHITI_ECORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_A18_PRO_TAHITI_PCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M5_PRO_SOTRA_MCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M5_PRO_SOTRA_PCORE), {}, }; struct arm_smccc_res res = {}; From d41bb3229ce8f573fd1f9d56e946604cb14324b0 Mon Sep 17 00:00:00 2001 From: Mostafa Saleh Date: Fri, 6 Nov 2026 17:27:49 +0000 Subject: [PATCH 0459/2102] KVM: arm64: Use consistent type for pool size All the pool sizes in the hypervisor are "unsigned long" but when they get passed to hyp_early_alloc_contig() or hyp_pool_init() they get truncated to 32-bits. That is not a big problem at the moment as to overflow this we need 4G bytes of carveout (2 TB of host or guest system memory). However when new users are added (as IOMMU) it is hard to reason about the carveout size anymore. Fixes: e75960408723 ("KVM: arm64: Introduce an early Hyp page allocator") Fixes: 8e17c66249e9 ("KVM: arm64: Introduce a Hyp buddy page allocator") Reviewed-by: Fuad Tabba Acked-by: Will Deacon Signed-off-by: Mostafa Saleh Reviewed-by: Oliver Upton Link: https://patch.msgid.link/20261106172750.2678873-1-smostafa@google.com Signed-off-by: Marc Zyngier --- arch/arm64/kvm/hyp/include/nvhe/early_alloc.h | 2 +- arch/arm64/kvm/hyp/include/nvhe/gfp.h | 4 ++-- arch/arm64/kvm/hyp/nvhe/early_alloc.c | 2 +- arch/arm64/kvm/hyp/nvhe/page_alloc.c | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/arch/arm64/kvm/hyp/include/nvhe/early_alloc.h b/arch/arm64/kvm/hyp/include/nvhe/early_alloc.h index dc61aaa56f3195..462883c4e3253d 100644 --- a/arch/arm64/kvm/hyp/include/nvhe/early_alloc.h +++ b/arch/arm64/kvm/hyp/include/nvhe/early_alloc.h @@ -7,7 +7,7 @@ void hyp_early_alloc_init(void *virt, unsigned long size); unsigned long hyp_early_alloc_nr_used_pages(void); void *hyp_early_alloc_page(void *arg); -void *hyp_early_alloc_contig(unsigned int nr_pages); +void *hyp_early_alloc_contig(unsigned long nr_pages); extern struct kvm_pgtable_mm_ops hyp_early_alloc_mm_ops; diff --git a/arch/arm64/kvm/hyp/include/nvhe/gfp.h b/arch/arm64/kvm/hyp/include/nvhe/gfp.h index 3766333bace966..3a428dc40b1490 100644 --- a/arch/arm64/kvm/hyp/include/nvhe/gfp.h +++ b/arch/arm64/kvm/hyp/include/nvhe/gfp.h @@ -29,6 +29,6 @@ void hyp_get_page(struct hyp_pool *pool, void *addr); void hyp_put_page(struct hyp_pool *pool, void *addr); /* Used pages cannot be freed */ -int hyp_pool_init(struct hyp_pool *pool, u64 pfn, unsigned int nr_pages, - unsigned int reserved_pages); +int hyp_pool_init(struct hyp_pool *pool, u64 pfn, unsigned long nr_pages, + unsigned long reserved_pages); #endif /* __KVM_HYP_GFP_H */ diff --git a/arch/arm64/kvm/hyp/nvhe/early_alloc.c b/arch/arm64/kvm/hyp/nvhe/early_alloc.c index 00de04153cc648..9fef0c7d2185e4 100644 --- a/arch/arm64/kvm/hyp/nvhe/early_alloc.c +++ b/arch/arm64/kvm/hyp/nvhe/early_alloc.c @@ -21,7 +21,7 @@ unsigned long hyp_early_alloc_nr_used_pages(void) return (cur - base) >> PAGE_SHIFT; } -void *hyp_early_alloc_contig(unsigned int nr_pages) +void *hyp_early_alloc_contig(unsigned long nr_pages) { unsigned long size = (nr_pages << PAGE_SHIFT); void *ret = (void *)cur; diff --git a/arch/arm64/kvm/hyp/nvhe/page_alloc.c b/arch/arm64/kvm/hyp/nvhe/page_alloc.c index 57f86aa0f82fcb..51460d420c94fa 100644 --- a/arch/arm64/kvm/hyp/nvhe/page_alloc.c +++ b/arch/arm64/kvm/hyp/nvhe/page_alloc.c @@ -229,12 +229,12 @@ void *hyp_alloc_pages(struct hyp_pool *pool, u8 order) return hyp_page_to_virt(p); } -int hyp_pool_init(struct hyp_pool *pool, u64 pfn, unsigned int nr_pages, - unsigned int reserved_pages) +int hyp_pool_init(struct hyp_pool *pool, u64 pfn, unsigned long nr_pages, + unsigned long reserved_pages) { phys_addr_t phys = hyp_pfn_to_phys(pfn); struct hyp_page *p; - int i; + unsigned long i; hyp_spin_lock_init(&pool->lock); pool->max_order = min(MAX_PAGE_ORDER, From fe5946524be82b1eeb1da17949684afc56087ff7 Mon Sep 17 00:00:00 2001 From: Xuheng Li Date: Mon, 9 Nov 2026 22:13:35 +0000 Subject: [PATCH 0460/2102] KVM: arm64: Don't replace a valid hyp block mapping with a table When kvm_pgtable_hyp_map() is asked to map part of a range that a valid block mapping already covers, hyp_map_walker_try_leaf() declines, as the request cannot be a leaf at the block's level. hyp_map_walker() then allocates a zeroed table and stores it over the valid block entry. The walk descends into the new table and maps the requested pages, but the rest of the block is now unmapped, and the valid block was replaced without break-before-make. No in-tree caller maps into an existing hyp block mapping today, so this cannot be triggered in mainline. Fail such a request with -EEXIST instead, so that a future caller gets an error rather than silently losing the rest of the block. The same check now catches a conflicting remap of an existing leaf, so drop the WARN_ON() from hyp_map_walker_try_leaf(): every caller checks the error, and a WARN is fatal at EL2. Do the check before the last-level WARN_ON(), which is kept for internal errors, and update the kernel-doc of kvm_pgtable_hyp_map() to match. Signed-off-by: Xuheng Li Reviewed-by: Vincent Donnefort Link: https://patch.msgid.link/20261109-hyp-block-map-v3-1-bd70e67eb0bf@cs.columbia.edu Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/kvm_pgtable.h | 2 +- arch/arm64/kvm/hyp/pgtable.c | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/arch/arm64/include/asm/kvm_pgtable.h b/arch/arm64/include/asm/kvm_pgtable.h index 1c9c57cd6ae40d..6d6ed85968475b 100644 --- a/arch/arm64/include/asm/kvm_pgtable.h +++ b/arch/arm64/include/asm/kvm_pgtable.h @@ -508,7 +508,7 @@ void kvm_pgtable_hyp_destroy(struct kvm_pgtable *pgt); * If device attributes are not explicitly requested in @prot, then the * mapping will be normal, cacheable. Attempts to install a new mapping * for a virtual address that is already mapped will be rejected with an - * error and a WARN(). + * error. * * Return: 0 on success, negative error code on failure. */ diff --git a/arch/arm64/kvm/hyp/pgtable.c b/arch/arm64/kvm/hyp/pgtable.c index 9c83837b184d35..94a59f29a20a21 100644 --- a/arch/arm64/kvm/hyp/pgtable.c +++ b/arch/arm64/kvm/hyp/pgtable.c @@ -414,7 +414,7 @@ static bool hyp_map_walker_try_leaf(const struct kvm_pgtable_visit_ctx *ctx, return true; if (!kvm_pte_valid(ctx->old)) ctx->mm_ops->get_page(ctx->ptep); - else if (WARN_ON((ctx->old ^ new) & ~KVM_PTE_LEAF_ATTR_HI_SW)) + else if ((ctx->old ^ new) & ~KVM_PTE_LEAF_ATTR_HI_SW) return false; smp_store_release(ctx->ptep, new); @@ -431,6 +431,14 @@ static int hyp_map_walker(const struct kvm_pgtable_visit_ctx *ctx, if (hyp_map_walker_try_leaf(ctx, data)) return 0; + /* + * A valid entry here is a leaf that conflicts with the request. + * Replacing a block with a table would need break-before-make, and + * would leave the rest of the block unmapped. + */ + if (kvm_pte_valid(ctx->old)) + return -EEXIST; + if (WARN_ON(ctx->level == KVM_PGTABLE_LAST_LEVEL)) return -EINVAL; From e1c5c6db6cc5e0314a773a08a2a7e50021596eee Mon Sep 17 00:00:00 2001 From: Xuheng Li Date: Mon, 9 Nov 2026 22:13:36 +0000 Subject: [PATCH 0461/2102] KVM: arm64: Order a later pinner's accesses after the hyp mapping Since commit 48d848882395 ("KVM: arm64: Defer EL2 stage-1 mapping on share"), hyp_pin_shared_mem() maps a shared page into the hypervisor's stage-1 only when its refcount goes from 0 to 1. The CPU that maps it runs dsb(ishst); isb() in kvm_pgtable_hyp_map(), which orders that CPU's own accesses. A CPU that pins the page later sees refcount >= 1, maps nothing and runs no barrier. It then accesses the page through an address it computed before taking the locks, so nothing orders its translation after the other CPU's PTE write. The access can use a translation performed while the entry was still invalid, and fault. A host can do this with any pinning hypercall by passing the same page from two CPUs, for example __pkvm_init_vm() with the same struct kvm: CPU A CPU B ----- ----- host_kvm = kern_hyp_va_host(x1) (host_kvm may be translated now, while its entry is invalid) __pkvm_init_vm(host_kvm) hyp_pin_shared_mem() host/hyp locks refcount 0 -> 1 pkvm_create_mappings_locked() kvm_pgtable_hyp_map() write the valid PTE dsb(ishst); isb() <- CPU A only unlock __pkvm_init_vm(host_kvm) hyp_pin_shared_mem() host/hyp locks refcount 1 -> 2: no mapping, no barrier unlock READ_ONCE(host_kvm->created_vcpus) uses the old translation: translation fault -> hyp_panic() A well-behaved host can hit this too. Since commit cf533b4d3630 ("KVM: arm64: Validate the host vCPU's VM before reading it under pKVM"), injecting an exception into a host vCPU that isn't loaded pins its struct kvm to read the VM's MTE flag. On an MTE-capable host, two vCPUs of one VM that do this at the same time from __kvm_adjust_pc() take the same path as CPU B above. The lock hand-off orders CPU B's loads and stores after CPU A's PTE write, but not its translation table walks. Arm's herd7 model with -variant vmsa allows the fault for this shape: a mapping made and completed with DSB; ISB on one CPU, handed over through a release/acquire, then used on another CPU through an address it already held. It forbids the fault once the second CPU runs DSB; ISB after the acquire. Make every successful pin end with dsb(ish); isb(), so that the pinning CPU's later accesses through the range are ordered after the mapping, whichever pin installed it. Fixes: 48d848882395 ("KVM: arm64: Defer EL2 stage-1 mapping on share") Cc: stable@vger.kernel.org Reviewed-by: Fuad Tabba Signed-off-by: Xuheng Li Link: https://patch.msgid.link/20261109-pin-barrier-v2-1-64ca73cae5e3@cs.columbia.edu Signed-off-by: Marc Zyngier --- arch/arm64/kvm/hyp/nvhe/mem_protect.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/arch/arm64/kvm/hyp/nvhe/mem_protect.c b/arch/arm64/kvm/hyp/nvhe/mem_protect.c index d4c332a918035c..5cb1a1e1f2fe96 100644 --- a/arch/arm64/kvm/hyp/nvhe/mem_protect.c +++ b/arch/arm64/kvm/hyp/nvhe/mem_protect.c @@ -1210,6 +1210,14 @@ int hyp_pin_shared_mem(void *from, void *to) PAGE_HYP)); } + /* + * Only the first pin of a page maps it, and that CPU's barriers order + * only its own accesses. Order this CPU's accesses through the range + * after the mapping, whichever pin made it. + */ + dsb(ish); + isb(); + unlock: hyp_unlock_component(); host_unlock_component(); From 93dc3df29b2a63271b294a1ad0740f7aee24fb59 Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Tue, 10 Nov 2026 09:14:20 +0300 Subject: [PATCH 0462/2102] KVM: arm64: nv: Invalidate whole L1 blocks on TLBI RIPAS2E1 The shadow stage-2 can map one of the L1's stage-2 blocks with several smaller leaves. This happens when the host backs the memory with smaller pages, when the memslot is dirty logging, or when the L1 block size falls between two host block sizes. When the L1 invalidates part of such a block, handle_ripas2e1is() only unmaps the requested range, so the shadow leaves for the rest of the block stay valid. A TLBI must remove every TLB entry for a block it touches, including the parts outside the range. The L1 does not need to issue another TLBI before reusing the rest of the block, so the L2 can still reach those pages through the stale shadow entries. Use compute_tlb_inval_range() in s2_mmu_unmap_range() to find the L1 block size, the same as the IPAS2E1 path does, and widen the range to whole L1 blocks. The other caller, handle_vmalls12e1is(), unmaps the whole IPA space, so the widening does not change anything there. This only affects nested virtualization: the host must be booted with kvm-arm.mode=nested and the VM must be given a virtual EL2. In such a VM it breaks the isolation that the L1 hypervisor provides. An L2 can keep reading and writing pages that the L1 has taken back and reused, either for itself or for another L2. The host, other VMs and VMs without nested virtualization are not affected, because the shadow stage-2 only maps the L1 VM's own memory. Fixes: 5d476ca57d7d ("KVM: arm64: nv: Add handling of range-based TLBI operations") Cc: stable@vger.kernel.org Signed-off-by: Dan Carpenter Link: https://patch.msgid.link/6817d113e5f0a9cafe0ce5bc0847276b7f14aacc.1794210561.git.dan@cryspen.com Signed-off-by: Marc Zyngier --- arch/arm64/kvm/sys_regs.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/arch/arm64/kvm/sys_regs.c b/arch/arm64/kvm/sys_regs.c index 850eba167aad6a..82b0313a3dce93 100644 --- a/arch/arm64/kvm/sys_regs.c +++ b/arch/arm64/kvm/sys_regs.c @@ -4098,6 +4098,17 @@ union tlbi_info { static void s2_mmu_unmap_range(struct kvm_s2_mmu *mmu, const union tlbi_info *info) { + u64 start = info->range.start; + u64 end = start + info->range.size; + + /* + * An L1 stage-2 block may be held in the shadow S2 as several smaller + * leaves, and R_TVTYQ requires the TLBI to invalidate all of them, so + * widen each end of the range to the L1 block containing it. + */ + start = ALIGN_DOWN(start, compute_tlb_inval_range(mmu, start >> 12)); + end = ALIGN(end, compute_tlb_inval_range(mmu, (end - 1) >> 12)); + /* * The unmap operation is allowed to drop the MMU lock and block, which * means that @mmu could be used for a different context than the one @@ -4121,7 +4132,7 @@ static void s2_mmu_unmap_range(struct kvm_s2_mmu *mmu, * the L1 needs to put its stage-2 in a consistent state before doing * the TLBI. */ - kvm_stage2_unmap_range(mmu, info->range.start, info->range.size, true); + kvm_stage2_unmap_range(mmu, start, end - start, true); } static bool handle_vmalls12e1is(struct kvm_vcpu *vcpu, struct sys_reg_params *p, From 49703de92bfdb784447937a8d65ad6ef1db9b23d Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Wed, 11 Nov 2026 14:02:04 +0300 Subject: [PATCH 0463/2102] KVM: arm64: vgic: Don't truncate offsets in vgic_find_mmio_region() In vgic_its_has_attr_regs() and vgic_its_attr_regs_access() we take a u64 "offset" from the user and pass it to vgic_find_mmio_region() to find the correct region. The problem is that vgic_find_mmio_region() truncates the "offset" to 32 bits so we might find a region even though really we shouldn't. Later the untruncated offset is used to calculate "addr". addr = its->vgic_its_base + offset; For example, an offset of 0x100000084 finds the 64-bit GITS_CBASER register at 0x80, and the write reaches update_64bit_reg() with an offset of 4 into the register and a length of 8. It exhibits as a UBSAN warning. [ 183.796046] UBSAN: shift-out-of-bounds in arch/arm64/kvm/vgic/vgic-mmio-v3.c:35:10 [ 183.796198] shift exponent 18446744073709551584 is too large for 64-bit type 'long long unsigned int' The GICv5 IRS code has the same problem in vgic_v5_has_attr_regs() and vgic_v5_irs_attr_regs_access(). Make vgic_find_mmio_region() and match_region() take the offset as a u64, so an offset of 2^32 or more no longer matches any region. The other callers only pass offsets which fit in 32 bits so they are not affected. Fortunately the effect of this bug is very minor. The worst case is that the VMM accesses an emulated register and sets something nonsensical and users are already allowed to do that without the bug. Fixes: 8331c23c28e8 ("KVM: arm64: vgic-its: Implement vgic_its_has_attr_regs and attr_regs_access") Fixes: 71091136d145 ("KVM: arm64: gic-v5: Handle userspace accesses to IRS MMIO region") Signed-off-by: Dan Carpenter Link: https://patch.msgid.link/avRLLMOiudnKoSlk@stanley.mountain Signed-off-by: Marc Zyngier --- arch/arm64/kvm/vgic/vgic-mmio.c | 4 ++-- arch/arm64/kvm/vgic/vgic-mmio.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/arch/arm64/kvm/vgic/vgic-mmio.c b/arch/arm64/kvm/vgic/vgic-mmio.c index fddb9da0403d55..59bdec495cd774 100644 --- a/arch/arm64/kvm/vgic/vgic-mmio.c +++ b/arch/arm64/kvm/vgic/vgic-mmio.c @@ -820,7 +820,7 @@ void vgic_write_irq_line_level_info(struct kvm_vcpu *vcpu, u32 intid, static int match_region(const void *key, const void *elt) { - const unsigned int offset = (unsigned long)key; + const u64 offset = (unsigned long)key; const struct vgic_register_region *region = elt; if (offset < region->reg_offset) @@ -834,7 +834,7 @@ static int match_region(const void *key, const void *elt) const struct vgic_register_region * vgic_find_mmio_region(const struct vgic_register_region *regions, - int nr_regions, unsigned int offset) + int nr_regions, u64 offset) { return bsearch((void *)(uintptr_t)offset, regions, nr_regions, sizeof(regions[0]), match_region); diff --git a/arch/arm64/kvm/vgic/vgic-mmio.h b/arch/arm64/kvm/vgic/vgic-mmio.h index 38ed730d68ac38..6c3c4de6883ef5 100644 --- a/arch/arm64/kvm/vgic/vgic-mmio.h +++ b/arch/arm64/kvm/vgic/vgic-mmio.h @@ -228,6 +228,6 @@ u64 vgic_sanitise_field(u64 reg, u64 field_mask, int field_shift, /* Find the proper register handler entry given a certain address offset */ const struct vgic_register_region * vgic_find_mmio_region(const struct vgic_register_region *regions, - int nr_regions, unsigned int offset); + int nr_regions, u64 offset); #endif From 126b47221b7b98d83c118781ce724c0515d86d9c Mon Sep 17 00:00:00 2001 From: Nathan Chancellor Date: Mon, 9 Nov 2026 13:00:12 -0500 Subject: [PATCH 0464/2102] powerpc/smp: Handle of_property_count_u32_elems() error in parse_thread_groups() After commit 0af298e62e5c ("treewide: refresh kmalloc_obj() conversions"), there is a warning on boot for several PowerPC configurations in QEMU: WARNING: mm/slub.c:5459 at ___kmalloc_large_node+0x174/0x1b0, CPU#0: swapper/0/1 Modules linked in: CPU: 0 UID: 0 PID: 1 Comm: swapper/0 Not tainted 7.4.0-rc1-00262-g0af298e62e5c #1 PREEMPT(lazy) NIP [c0000000006074e4] ___kmalloc_large_node+0x174/0x1b0 LR [c00000000060782c] __kmalloc_large_node_noprof+0x3c/0x150 Call Trace: ... [c00000000369fb60] [c000000000614ff0] __kmalloc_noprof+0x490/0x690 [c00000000369fbe0] [c000000000051308] _kzalloc_noprof.constprop.0+0x1c/0x74 [c00000000369fc00] [c00000000200b450] init_thread_group_cache_map+0xc0/0x2c4 ... In this case, of_property_count_u32_elems() returns -EINVAL because there is no "ibm,thread-groups" property. When kcalloc() was used to allocate thread_group_array, the multiplication overflow check in _kmalloc_array_noprof() caught that a really large allocation was requested (as -EINVAL was converted to size_t) and returned NULL. kzalloc_objs() has no such check, so the large allocation check in __kmalloc_large_noprof() triggers the visible warning above. Check if of_property_count_u32_elems() has returned an error and bail out if so, clearing up the warning. Fixes: 790a1662d3a2 ("powerpc/smp: Parse ibm,thread-groups with multiple properties") Signed-off-by: Nathan Chancellor Reviewed-by: Ritesh Harjani (IBM) Reviewed-by: Shrikanth Hegde Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261109-powerpc-smp-handle-count-err-v1-1-e777fde7f71a@kernel.org --- arch/powerpc/kernel/smp.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/arch/powerpc/kernel/smp.c b/arch/powerpc/kernel/smp.c index 7a25eaa59e6260..58824f5f4c8008 100644 --- a/arch/powerpc/kernel/smp.c +++ b/arch/powerpc/kernel/smp.c @@ -824,6 +824,8 @@ static int parse_thread_groups(struct device_node *dn, int i = 0; count = of_property_count_u32_elems(dn, "ibm,thread-groups"); + if (count < 0) + return count; thread_group_array = kzalloc_objs(u32, count); if (!thread_group_array) return -ENOMEM; From 6648db997a0b8223fefbee3b4d5391c0d90d0422 Mon Sep 17 00:00:00 2001 From: Sasha Levin Date: Tue, 3 Nov 2026 18:23:07 -0500 Subject: [PATCH 0465/2102] selftests/powerpc: override EMIT_TESTS instead of the emit_tests rule The powerpc Makefiles include lib.mk and then define their own emit_tests rule, so every selftests build that includes powerpc warns, on any architecture: Makefile:60: warning: overriding recipe for target 'emit_tests' ../lib.mk:183: warning: ignoring old recipe for target 'emit_tests' lib.mk used to keep the recipe in an EMIT_TESTS variable that Makefiles could override, as they still do with RUN_TESTS, INSTALL_RULE and CLEAN. Commit d4e59a536f50 ("selftests: Use runner.sh for emit targets") dropped the variable, and commit 58b33e78a317 ("selftests/powerpc: Fix emit_tests to work with run_kselftest.sh") then replaced the powerpc EMIT_TESTS definitions with rules. Bring EMIT_TESTS back in lib.mk and override it in the powerpc Makefiles again. Mark the lib.mk recipe with '+', so that the powerpc sub-makes still get the jobserver, as they did when $(MAKE) was in the rule itself. The emitted test lists don't change. Fixes: 58b33e78a317 ("selftests/powerpc: Fix emit_tests to work with run_kselftest.sh") Signed-off-by: Sasha Levin Acked-by: Michael Ellerman Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261103232307.1924618-3-sashal@kernel.org --- tools/testing/selftests/lib.mk | 6 +++++- tools/testing/selftests/powerpc/Makefile | 3 ++- tools/testing/selftests/powerpc/pmu/Makefile | 3 ++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/tools/testing/selftests/lib.mk b/tools/testing/selftests/lib.mk index 881f13ee2c8aca..506cb26510e4d9 100644 --- a/tools/testing/selftests/lib.mk +++ b/tools/testing/selftests/lib.mk @@ -179,11 +179,15 @@ else $(error Error: set INSTALL_PATH to use install) endif -emit_tests: +define EMIT_TESTS for TEST in $(TEST_GEN_PROGS) $(TEST_CUSTOM_PROGS) $(TEST_PROGS); do \ BASENAME_TEST=`basename $$TEST`; \ echo "$(COLLECTION):$$BASENAME_TEST"; \ done +endef + +emit_tests: + +$(EMIT_TESTS) # define if isn't already. It is undefined in make O= case. ifeq ($(RM),) diff --git a/tools/testing/selftests/powerpc/Makefile b/tools/testing/selftests/powerpc/Makefile index b175e94e1901db..aeab9366d09bf8 100644 --- a/tools/testing/selftests/powerpc/Makefile +++ b/tools/testing/selftests/powerpc/Makefile @@ -56,11 +56,12 @@ override define INSTALL_RULE done; endef -emit_tests: +override define EMIT_TESTS +@for TARGET in $(SUB_DIRS); do \ BUILD_TARGET=$(OUTPUT)/$$TARGET; \ $(MAKE) OUTPUT=$$BUILD_TARGET COLLECTION=$(COLLECTION)/$$TARGET -s -C $$TARGET $@;\ done; +endef override define CLEAN +@for TARGET in $(SUB_DIRS); do \ diff --git a/tools/testing/selftests/powerpc/pmu/Makefile b/tools/testing/selftests/powerpc/pmu/Makefile index 7e9dbf3d0d092d..3aca10223f0ff5 100644 --- a/tools/testing/selftests/powerpc/pmu/Makefile +++ b/tools/testing/selftests/powerpc/pmu/Makefile @@ -37,7 +37,7 @@ override define RUN_TESTS done; endef -emit_tests: +override define EMIT_TESTS for TEST in $(TEST_GEN_PROGS); do \ BASENAME_TEST=`basename $$TEST`; \ echo "$(COLLECTION):$$BASENAME_TEST"; \ @@ -46,6 +46,7 @@ emit_tests: BUILD_TARGET=$(OUTPUT)/$$TARGET; \ $(MAKE) OUTPUT=$$BUILD_TARGET COLLECTION=$(COLLECTION)/$$TARGET -s -C $$TARGET emit_tests; \ done; +endef DEFAULT_INSTALL_RULE := $(INSTALL_RULE) override define INSTALL_RULE From d513ec3c907b067d4a32b14ec6f73c3e041cb136 Mon Sep 17 00:00:00 2001 From: "Luiz Capitulino (Red Hat)" Date: Tue, 3 Nov 2026 22:40:18 -0500 Subject: [PATCH 0466/2102] powerpc/watchdog: disable watchdog when watchdog_thresh=0 On powerpc, trying to disable the hardlockup detector with: # echo 0 > /proc/sys/kernel/watchdog_thresh causes an immediate and endless hardlockup detection, eventually leading to an unusable system (splat example below). This happens because watchdog_calc_timeouts() sets wd_timer_period_ms, wd_panic_timeout_tb and wd_smp_panic_timeout_tb to zero, but start_watchdog() still starts the timer (with expiry=0) in this code path: proc_watchdog_thresh() proc_watchdog_update() __lockup_detector_reconfigure() watchdog_hardlockup_start() start_watchdog_on_cpu() start_watchdog() hrtimer_start() /* wd_timer_period_ms=0 */ However, according to Documentation/admin-guide/sysctl/kernel.rst, setting watchdog_thresh=0 should disable both the soft and hard lockup detectors. This condition is already checked in __lockup_detector_reconfigure() for the soft lockup detector and the arch-independent hardlockup detector, what's missing is powerpc performing the same check in start_watchdog(). [ 278.110085] watchdog: CPU 0 detected hard LOCKUP on other CPUs 1 [ 278.110086] watchdog: CPU 1 became unstuck TB:33050716089564575 [ 278.110097] CPU: 1 UID: 0 PID: 0 Comm: swapper/1 Kdump: loaded Tainted: G E 7.4.0-rc1 #1 PREEMPT(full) [ 278.110103] watchdog: CPU 0 TB:33050716089564185, last SMP heartbeat TB:33050716089563885 (0ms ago) [ 278.110109] Tainted: [E]=UNSIGNED_MODULE [ 278.110126] Hardware name: IBM,8375-42A POWER9 (architected) 0x4e0202 0xf000005 of:IBM,FW940.00 (VL940_027) hv:phyp pSeries [ 278.110136] NIP: c0000000001bd518 LR: c0000000014dedf8 CTR: 0000000000000000 [ 278.110145] REGS: c000000004b17a80 TRAP: 0900 Tainted: G E (7.4.0-rc1) [ 278.110155] MSR: 800000000280b033 CR: 22000224 XER: 20040004 [ 278.110189] CFAR: 0000000000000000 IRQMASK: 0 GPR00: 0000000000000000 c000000004b17d20 c000000001c38100 0000000000000000 GPR04: 000000000000ffff 0000000000000000 0000000000000000 0000000000000000 GPR08: 0000000000000000 0000000000000080 0000000000000080 ffffffffffffffff GPR12: 0000000000000000 c000000017fff300 0000000000000000 000000002ef3d820 GPR16: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 GPR20: 0000000000000000 0000000000000000 0000000000000000 0000000000000001 GPR24: 0000000000000001 00000040c0a6075e 0000000000000000 0000000000000001 GPR28: c0000001fdb5b140 0000000000000001 c000000002291968 c000000002291970 [ 278.110306] NIP [c0000000001bd518] plpar_hcall_norets_notrace+0x18/0x2c [ 278.110319] LR [c0000000014dedf8] check_and_cede_processor+0x48/0x60 [ 278.110333] Call Trace: [ 278.110338] [c000000004b17d20] [c000000004b17dd0] 0xc000000004b17dd0 (unreliable) [ 278.110354] [c000000004b17d80] [c0000000014df020] shared_cede_loop+0x70/0x170 [ 278.110367] [c000000004b17dc0] [c0000000014de460] cpuidle_enter_state+0x2f0/0x748 [ 278.110381] [c000000004b17e70] [c000000000fe43b8] cpuidle_enter+0x48/0x70 [ 278.110397] [c000000004b17eb0] [c0000000002cdcf8] call_cpuidle+0x48/0x90 [ 278.110409] [c000000004b17ed0] [c0000000002d6300] cpuidle_idle_call+0x160/0x2d0 [ 278.110422] [c000000004b17f20] [c0000000002d6578] do_idle+0x108/0x1f0 [ 278.110434] [c000000004b17f60] [c0000000002d6938] cpu_startup_entry+0x48/0x50 [ 278.110446] [c000000004b17f90] [c0000000000615c0] start_secondary+0x290/0x2a0 [ 278.110459] [c000000004b17fe0] [c00000000000e258] start_secondary_prolog+0x10/0x14 Fixes: 2104180a5369 ("powerpc/64s: implement arch-specific hardlockup watchdog") Cc: stable@vger.kernel.org Signed-off-by: Luiz Capitulino (Red Hat) Reviewed-by: Michael Ellerman Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261104034018.2676750-1-luiz.capitulino@linux.dev --- arch/powerpc/kernel/watchdog.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/powerpc/kernel/watchdog.c b/arch/powerpc/kernel/watchdog.c index 582ee3fd71c1ba..44f178e07531e6 100644 --- a/arch/powerpc/kernel/watchdog.c +++ b/arch/powerpc/kernel/watchdog.c @@ -487,6 +487,9 @@ static void start_watchdog(void *arg) if (!(watchdog_enabled & WATCHDOG_HARDLOCKUP_ENABLED)) return; + if (!watchdog_thresh) + return; + if (!cpumask_test_cpu(cpu, &watchdog_cpumask)) return; From dc6eb6f08be536223e8289c7a8b1f515b1355721 Mon Sep 17 00:00:00 2001 From: Bradley Morgan Date: Wed, 23 Sep 2026 17:56:31 +0000 Subject: [PATCH 0467/2102] powerpc32/modules: Reserve a PLT entry for ftrace_regs_caller Commit 7dfbfb87c243 ("powerpc/ftrace: Activate HAVE_DYNAMIC_FTRACE_WITH_REGS on PPC32") made count_relocs() undercount the PLT entries the loader consumes: module_finalize_ftrace() now creates two trampolines (mod->arch.tramp for ftrace_caller() and mod->arch.tramp_regs for ftrace_regs_caller()), while count_relocs() reserves only one entry for ftrace. So the core .plt ends up one ppc_plt_entry (16 bytes) short. The walk in do_plt_call() scans for a free slot with "while (entry->jump[0])" and has no bound check, so once the last reserved slot is used up, the walk steps past the end of the section and patch_instruction() writes the 4-instruction trampoline into whatever module memory follows the .plt. Count the second entry, mirroring what module_64.c does for the same pair of stubs. Signed-off-by: Bradley Morgan Fixes: 7dfbfb87c243 ("powerpc/ftrace: Activate HAVE_DYNAMIC_FTRACE_WITH_REGS on PPC32") Reviewed-by: Christophe Leroy (CS GROUP) Cc: stable@vger.kernel.org Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20260923175631.235276-1-brads@mainlining.org --- arch/powerpc/kernel/module_32.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/powerpc/kernel/module_32.c b/arch/powerpc/kernel/module_32.c index f930e3395a7f27..61152deffc55bf 100644 --- a/arch/powerpc/kernel/module_32.c +++ b/arch/powerpc/kernel/module_32.c @@ -41,6 +41,9 @@ static unsigned int count_relocs(const Elf32_Rela *rela, unsigned int num) #ifdef CONFIG_DYNAMIC_FTRACE _count_relocs++; /* add one for ftrace_caller */ +#ifdef CONFIG_DYNAMIC_FTRACE_WITH_REGS + _count_relocs++; /* add one for ftrace_regs_caller */ +#endif #endif return _count_relocs; } From 9500416c8aa7c271b85be6a0d5856da62b60223a Mon Sep 17 00:00:00 2001 From: Mohammad Shahid Date: Mon, 2 Nov 2026 20:07:19 +0530 Subject: [PATCH 0468/2102] powerpc/perf/vpa-dtl: use GFP_ATOMIC for DTL buffer allocation The DTL buffer is allocated while holding dtl_global_lock, which is spinlock. GFP_KERNEL allow direct memory reclaim and may sleep. Combining GFP_KERNEL with GFP_ATOMIC does not remove the direct reclaim. Use GFP_ATOMIC alone to ensure the allocation does not sleep while the spinlock is held. The issue is reported by script coccinelle call_kern.cocci. Signed-off-by: Mohammad Shahid Fixes: 4708fba19ade ("powerpc/vpa_dtl: Add interface to expose vpa dtl counters via perf") Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261102143719.165508-1-mdshahid03@gmail.com --- arch/powerpc/perf/vpa-dtl.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/powerpc/perf/vpa-dtl.c b/arch/powerpc/perf/vpa-dtl.c index 3e3d65b6c796c6..3d34417e6aaece 100644 --- a/arch/powerpc/perf/vpa-dtl.c +++ b/arch/powerpc/perf/vpa-dtl.c @@ -338,7 +338,7 @@ static int vpa_dtl_mem_alloc(int cpu) if (!dtl_cache) return -ENOMEM; - buf = kmem_cache_alloc_node(dtl_cache, GFP_KERNEL | GFP_ATOMIC, cpu_to_node(cpu)); + buf = kmem_cache_alloc_node(dtl_cache, GFP_ATOMIC, cpu_to_node(cpu)); if (!buf) { pr_warn("buffer allocation failed for cpu %d\n", cpu); return -ENOMEM; From da0c7b9ba5e91b745aeb857be096a60d63c27ec8 Mon Sep 17 00:00:00 2001 From: Shay Drory Date: Mon, 9 Nov 2026 14:28:45 +0200 Subject: [PATCH 0469/2102] RDMA/mlx5: Add missing error flow in mlx5_ib_set_vport_rep mlx5_ib_set_vport_rep() attaches the representor netdev to the IB device, which takes a netdev reference, and then adds the LAG demux rule. If mlx5_lag_demux_rule_add() fails, the error is returned without detaching the netdev. The eswitch does not call unload() for a representor whose load() failed, so the reference is never dropped and a later unregister_netdevice() of the representor waits forever while holding the eswitch representors lock. Add the demux rule before publishing the rep and attaching its netdev, so a failure there leaves nothing to undo. The rep pointers are still set before ib_device_set_netdev() sends the netdev attach event, so a listener never sees the attached port without its rep. If ib_device_set_netdev() fails, delete the demux rule and clear the rep pointers. ib_device_set_netdev() cannot fail here, as the port index is always valid and the port data was allocated when the uplink rep was loaded, so clearing the pointers does not race with lockless readers. Fixes: d6c9b4de8109 ("{net/RDMA}/mlx5: Add LAG demux table API and vport demux rules") Signed-off-by: Shay Drory Reviewed-by: Chiara Meiohas Reviewed-by: Mark Bloch Signed-off-by: Edward Srouji Link: https://patch.msgid.link/20261109-rep-netdev-leak-v2-1-9a6d164142e5@nvidia.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/mlx5/ib_rep.c | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/drivers/infiniband/hw/mlx5/ib_rep.c b/drivers/infiniband/hw/mlx5/ib_rep.c index 65d8767d1830c6..c460018d04754c 100644 --- a/drivers/infiniband/hw/mlx5/ib_rep.c +++ b/drivers/infiniband/hw/mlx5/ib_rep.c @@ -22,21 +22,30 @@ mlx5_ib_set_vport_rep(struct mlx5_core_dev *dev, if (!ibdev) return -EINVAL; + /* Only Vports that are not native to the LAG master eswitch need to add + * demux rule. + */ + if (mlx5_eswitch_get_total_vports(dev) <= vport_index) { + ret = mlx5_lag_demux_rule_add(rep_dev, rep->vport, vport_index); + if (ret) + return ret; + } + ibdev->port[vport_index].rep = rep; rep->rep_data[REP_IB].priv = ibdev; ndev = mlx5_ib_get_rep_netdev(rep->esw, rep->vport); ret = ib_device_set_netdev(&ibdev->ib_dev, ndev, vport_index + 1); if (ret) - return ret; + goto err_set_netdev; - /* Only Vports that are not native to the LAG master eswitch need to add - * demux rule. - */ - if (mlx5_eswitch_get_total_vports(dev) > vport_index) - return 0; + return 0; - return mlx5_lag_demux_rule_add(rep_dev, rep->vport, vport_index); +err_set_netdev: + rep->rep_data[REP_IB].priv = NULL; + ibdev->port[vport_index].rep = NULL; + mlx5_lag_demux_rule_del(rep_dev, vport_index); + return ret; } static void mlx5_ib_register_peer_vport_reps(struct mlx5_core_dev *mdev); From 1a509eca07176bc3363031c030d038ca9be9dfc0 Mon Sep 17 00:00:00 2001 From: Sasha Levin Date: Mon, 9 Nov 2026 08:47:08 -0500 Subject: [PATCH 0470/2102] memory: fsl_ifc: Do not dereference the unset global pointer in probe Commit a78ee2e05f7c ("memory: fsl_ifc: Clear fsl_ifc_ctrl_dev on probe failure and removal") assigns fsl_ifc_ctrl_dev near the end of probe, but probe still reads the IFC revision and fsl_ifc_ctrl_init() still programs the event registers before that. Both go through ifc_in32() and ifc_out32(), which take the register endianness from fsl_ifc_ctrl_dev, so the first probe dereferences a NULL pointer. Use local accessors that take the endianness from the controller being probed for these register accesses. Fixes: a78ee2e05f7c ("memory: fsl_ifc: Clear fsl_ifc_ctrl_dev on probe failure and removal") Signed-off-by: Sasha Levin Link: https://patch.msgid.link/20261109134708.263012-1-sashal@kernel.org Signed-off-by: Krzysztof Kozlowski --- drivers/memory/fsl_ifc.c | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/drivers/memory/fsl_ifc.c b/drivers/memory/fsl_ifc.c index 83991c05a6a5c5..abd033bd94c5a5 100644 --- a/drivers/memory/fsl_ifc.c +++ b/drivers/memory/fsl_ifc.c @@ -63,6 +63,23 @@ int fsl_ifc_find(phys_addr_t addr_base) } EXPORT_SYMBOL(fsl_ifc_find); +static u32 fsl_ifc_ctrl_in32(struct fsl_ifc_ctrl *ctrl, void __iomem *addr) +{ + if (ctrl->little_endian) + return ioread32(addr); + + return ioread32be(addr); +} + +static void fsl_ifc_ctrl_out32(struct fsl_ifc_ctrl *ctrl, u32 val, + void __iomem *addr) +{ + if (ctrl->little_endian) + iowrite32(val, addr); + else + iowrite32be(val, addr); +} + static int fsl_ifc_ctrl_init(struct fsl_ifc_ctrl *ctrl) { struct fsl_ifc_global __iomem *ifc = ctrl->gregs; @@ -70,16 +87,18 @@ static int fsl_ifc_ctrl_init(struct fsl_ifc_ctrl *ctrl) /* * Clear all the common status and event registers */ - if (ifc_in32(&ifc->cm_evter_stat) & IFC_CM_EVTER_STAT_CSER) - ifc_out32(IFC_CM_EVTER_STAT_CSER, &ifc->cm_evter_stat); + if (fsl_ifc_ctrl_in32(ctrl, &ifc->cm_evter_stat) & IFC_CM_EVTER_STAT_CSER) + fsl_ifc_ctrl_out32(ctrl, IFC_CM_EVTER_STAT_CSER, + &ifc->cm_evter_stat); /* enable all error and events */ - ifc_out32(IFC_CM_EVTER_EN_CSEREN, &ifc->cm_evter_en); + fsl_ifc_ctrl_out32(ctrl, IFC_CM_EVTER_EN_CSEREN, &ifc->cm_evter_en); /* enable all error and event interrupts */ - ifc_out32(IFC_CM_EVTER_INTR_EN_CSERIREN, &ifc->cm_evter_intr_en); - ifc_out32(0x0, &ifc->cm_erattr0); - ifc_out32(0x0, &ifc->cm_erattr1); + fsl_ifc_ctrl_out32(ctrl, IFC_CM_EVTER_INTR_EN_CSERIREN, + &ifc->cm_evter_intr_en); + fsl_ifc_ctrl_out32(ctrl, 0x0, &ifc->cm_erattr0); + fsl_ifc_ctrl_out32(ctrl, 0x0, &ifc->cm_erattr1); return 0; } @@ -231,7 +250,8 @@ static int fsl_ifc_ctrl_probe(struct platform_device *dev) dev_dbg(&dev->dev, "IFC REGISTERS are BIG endian\n"); } - version = ifc_in32(&ctrl->gregs->ifc_rev) & FSL_IFC_VERSION_MASK; + version = fsl_ifc_ctrl_in32(ctrl, &ctrl->gregs->ifc_rev) & + FSL_IFC_VERSION_MASK; banks = (version == FSL_IFC_VERSION_1_0_0) ? 4 : 8; dev_info(&dev->dev, "IFC version %d.%d, %d banks\n", From 9cfed185db8f1c12bf2629fb37c77d85bf93b193 Mon Sep 17 00:00:00 2001 From: Juan Parrado Date: Mon, 9 Nov 2026 20:41:18 +0100 Subject: [PATCH 0471/2102] Input: xpad - add support to Hori Real Arcade Pro 4 The HORI Real Arcade Pro 4 in PC mode is currently recognized by xpad.c as a 'Generic X-Box pad' and works out of the box. However, this generic name does not match the actual device name, making it difficult for users to distinguish this controller when multiple devices are connected. Tested on physical hardware. The proposed change works perfectly as is. The MAP_TRIGGERS_TO_BUTTONS parameter does not work here. Other arcade sticks use an identical configuration, such as the 'Street Fighter IV FightPad' and the 'Hori Real Arcade Pro.EX Premium VLX'. Signed-off-by: Juan Parrado Link: https://patch.msgid.link/20261109194118.18127-1-jparrado1817@gmail.com Cc: stable@vger.kernel.org Signed-off-by: Dmitry Torokhov --- drivers/input/joystick/xpad.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/input/joystick/xpad.c b/drivers/input/joystick/xpad.c index 53fd3b562f4140..21d95e4cae4db0 100644 --- a/drivers/input/joystick/xpad.c +++ b/drivers/input/joystick/xpad.c @@ -255,6 +255,7 @@ static const struct xpad_device { { 0x0f0d, 0x0063, "Hori Real Arcade Pro Hayabusa (USA) Xbox One", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE }, { 0x0f0d, 0x0067, "HORIPAD ONE", 0, XTYPE_XBOXONE }, { 0x0f0d, 0x0078, "Hori Real Arcade Pro V Kai Xbox One", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE }, + { 0x0f0d, 0x008c, "Real Arcade Pro 4", 0, XTYPE_XBOX360 }, { 0x0f0d, 0x00c5, "Hori Fighting Commander ONE", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE }, { 0x0f0d, 0x00dc, "HORIPAD FPS for Nintendo Switch", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 }, { 0x0f0d, 0x0151, "Hori Racing Wheel Overdrive for Xbox Series X", 0, XTYPE_XBOXONE }, From daf949c968d485badd6c1fc5b6965ea8175e7dda Mon Sep 17 00:00:00 2001 From: Weihong Guan Date: Wed, 11 Nov 2026 16:51:30 +0000 Subject: [PATCH 0472/2102] Bluetooth: hci_sync: Set random address on the set's handle When the controller supports a single advertising set, hci_add_adv_instance() gives instance 1 handle 0x00, and the parameters, data and enable commands for an instance use adv->handle. LE Set Advertising Set Random Address, from hci_set_adv_set_random_addr_sync(), still sends the instance number, 0x01, a set the controller doesn't have, so an instance using a random address, such as a non-connectable one, never starts: $ btmgmt add-adv -d 0A09434841445654455354 1 Add Advertising failed with status 0x0d (Invalid Parameters) < HCI Command: LE Set Extended Advertising Parameters Handle: 0x00 < HCI Command: LE Set Extended Advertising Data Handle: 0x00 < HCI Command: LE Set Advertising Set Random Address Advertising handle: 0x01 Send the instance's handle, looked up with hdev->lock held. hci_cc_le_set_adv_set_random_addr() records the address in the instance numbered as the handle and leaves handle 0x00 alone, as that handle's address is hdev->random_addr for instance 0. Instance 1's address on handle 0x00 would then go unrecorded, and its RPA timer never start, so record it in hci_set_adv_set_random_addr_sync() once the command succeeds, as the completion does for the other handles. Fixes: e77f43d531af ("Bluetooth: hci_core: Fix not handling hdev->le_num_of_adv_sets=1") Assisted-by: Claude:claude-opus-5.5 Signed-off-by: Weihong Guan Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_sync.c | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index 9213e3ef9f268e..320c5ba0d555dc 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -1258,6 +1258,8 @@ static int hci_set_adv_set_random_addr_sync(struct hci_dev *hdev, u8 instance, bdaddr_t *random_addr) { struct hci_cp_le_set_adv_set_rand_addr cp; + struct adv_info *adv; + u8 handle = instance; int err; if (!instance) { @@ -1269,15 +1271,46 @@ static int hci_set_adv_set_random_addr_sync(struct hci_dev *hdev, u8 instance, err = hci_set_random_addr_sync(hdev, random_addr); if (err) return err; + } else { + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); + if (adv) + handle = adv->handle; + hci_dev_unlock(hdev); } memset(&cp, 0, sizeof(cp)); - cp.handle = instance; + cp.handle = handle; bacpy(&cp.bdaddr, random_addr); - return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_SET_RAND_ADDR, - sizeof(cp), &cp, HCI_CMD_TIMEOUT); + err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_SET_RAND_ADDR, + sizeof(cp), &cp, HCI_CMD_TIMEOUT); + if (err || handle == instance) + return err; + + /* hci_cc_le_set_adv_set_random_addr() records the address of the + * instance numbered as the handle, and leaves handle 0x00 to + * hdev->random_addr, so record it here for an instance using another + * handle: instance 1 on handle 0x00, on a controller supporting a + * single advertising set. + */ + hci_dev_lock(hdev); + + adv = hci_find_adv_instance(hdev, instance); + if (adv) { + bacpy(&adv->random_addr, random_addr); + if (!bacmp(&hdev->rpa, random_addr)) { + adv->rpa_expired = false; + queue_delayed_work(hdev->workqueue, + &adv->rpa_expired_cb, + secs_to_jiffies(hdev->rpa_timeout)); + } + } + + hci_dev_unlock(hdev); + + return 0; } static int From e7e877bf658acd15fc7dda1bff3e66d0fa69a061 Mon Sep 17 00:00:00 2001 From: Weihong Guan Date: Wed, 11 Nov 2026 16:51:31 +0000 Subject: [PATCH 0473/2102] Bluetooth: hci_sync: Remove an advertising set by its handle When the controller supports a single advertising set, hci_add_adv_instance() gives instance 1 handle 0x00, but hci_remove_ext_adv_instance_sync() sends the instance number as the handle of LE Remove Advertising Set, so removing instance 1 fails: $ btmgmt rm-adv 1 Remove Advertising failed with status 0x03 (Failed) < HCI Command: LE Remove Advertising Set Handle: 1 > HCI Event: Command Complete Status: Unknown Advertising Identifier (0x42) Send the instance's handle, looked up with hdev->lock held. Two more things follow from the instance and the handle differing: - hci_cc_le_remove_adv_set() removes the instance numbered as the handle it sent, which for handle 0x00 is instance 0, so instance 1 would stay in hdev->adv_instances with its RPA timer running, and no MGMT_EV_ADVERTISING_REMOVED. The completion can't tell instance 1 from instance 0, which the MGMT Set Advertising path removes on the same handle, so remove instance 1 in hci_remove_ext_adv_instance_sync() once the command succeeds. - While Global Advertising is on, it owns handle 0x00 (adv_overridden_by_global()), and the set may be enabled for it, so the controller would refuse to remove it, with Command Disallowed. Remove only the instance then, leaving the set to Global Advertising. Fixes: e77f43d531af ("Bluetooth: hci_core: Fix not handling hdev->le_num_of_adv_sets=1") Assisted-by: Claude:claude-opus-5.5 Signed-off-by: Weihong Guan Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_sync.c | 55 +++++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 6 deletions(-) diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index 320c5ba0d555dc..d4a4f49df5ace8 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -2110,6 +2110,9 @@ int hci_enable_advertising(struct hci_dev *hdev) int hci_remove_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance, struct sock *sk) { + struct adv_info *adv = NULL; + u8 handle = instance; + bool global = false; int err; if (!ext_adv_capable(hdev)) @@ -2119,13 +2122,53 @@ int hci_remove_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance, if (err) return err; - /* If request specifies an instance that doesn't exist, fail */ - if (instance > 0 && !hci_find_adv_instance(hdev, instance)) - return -EINVAL; + if (instance) { + hci_dev_lock(hdev); + + adv = hci_find_adv_instance(hdev, instance); + if (adv) { + handle = adv->handle; + + /* An instance sharing handle 0x00 with Global + * Advertising doesn't own the set while Global + * Advertising is on, and the set may still be enabled + * for it, which the controller would refuse to remove. + */ + global = !handle && + (hci_dev_test_flag(hdev, HCI_ADVERTISING) || + hci_dev_test_flag(hdev, HCI_LE_ADV_0)); + } + + hci_dev_unlock(hdev); + + /* If request specifies an instance that doesn't exist, fail */ + if (!adv) + return -EINVAL; + } + + if (!global) { + err = __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_REMOVE_ADV_SET, + sizeof(handle), &handle, 0, + HCI_CMD_TIMEOUT, sk); + if (err) + return err; + } + + /* hci_cc_le_remove_adv_set() removes the instance numbered as the + * handle it sent, so remove here an instance using another handle: + * instance 1 on handle 0x00, on a controller supporting a single + * advertising set. The completion can't tell it from instance 0. + */ + if (handle != instance) { + hci_dev_lock(hdev); + + if (!hci_remove_adv_instance(hdev, instance)) + mgmt_advertising_removed(sk, hdev, instance); - return __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_REMOVE_ADV_SET, - sizeof(instance), &instance, 0, - HCI_CMD_TIMEOUT, sk); + hci_dev_unlock(hdev); + } + + return 0; } int hci_le_terminate_big_sync(struct hci_dev *hdev, u8 handle, u8 reason) From 8b1eff978e66efb5ed66b79591851203d05ab303 Mon Sep 17 00:00:00 2001 From: Weihong Guan Date: Wed, 11 Nov 2026 16:51:32 +0000 Subject: [PATCH 0474/2102] Bluetooth: hci_core: Add hci_free_adv_instance() hci_remove_adv_instance() looks the instance up by its number and then frees it. A caller that already holds the instance, found some other way, has to look it up again by number to remove it. Split the freeing into hci_free_adv_instance(), which takes the instance itself, and have hci_remove_adv_instance() call it after the lookup. No functional change. Suggested-by: Luiz Augusto von Dentz Assisted-by: Claude:claude-opus-5.5 Signed-off-by: Weihong Guan Signed-off-by: Luiz Augusto von Dentz --- include/net/bluetooth/hci_core.h | 1 + net/bluetooth/hci_core.c | 24 +++++++++++++++--------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/include/net/bluetooth/hci_core.h b/include/net/bluetooth/hci_core.h index 6fb713d5e4be98..fd4da751a24fc4 100644 --- a/include/net/bluetooth/hci_core.h +++ b/include/net/bluetooth/hci_core.h @@ -1972,6 +1972,7 @@ struct adv_info *hci_add_per_instance(struct hci_dev *hdev, u8 instance, u8 sid, int hci_set_adv_instance_data(struct hci_dev *hdev, u8 instance, u16 adv_data_len, u8 *adv_data, u16 scan_rsp_len, u8 *scan_rsp_data); +void hci_free_adv_instance(struct hci_dev *hdev, struct adv_info *adv_instance); int hci_remove_adv_instance(struct hci_dev *hdev, u8 instance); void hci_adv_instances_set_rpa_expired(struct hci_dev *hdev, bool rpa_expired); u32 hci_adv_instance_flags(struct hci_dev *hdev, u8 instance); diff --git a/net/bluetooth/hci_core.c b/net/bluetooth/hci_core.c index c97aec3caba023..846e6eb2d1bc8c 100644 --- a/net/bluetooth/hci_core.c +++ b/net/bluetooth/hci_core.c @@ -1610,17 +1610,11 @@ struct adv_info *hci_get_next_instance(struct hci_dev *hdev, u8 instance) } /* This function requires the caller holds hdev->lock */ -int hci_remove_adv_instance(struct hci_dev *hdev, u8 instance) +void hci_free_adv_instance(struct hci_dev *hdev, struct adv_info *adv_instance) { - struct adv_info *adv_instance; + BT_DBG("%s removing %dMR", hdev->name, adv_instance->instance); - adv_instance = hci_find_adv_instance(hdev, instance); - if (!adv_instance) - return -ENOENT; - - BT_DBG("%s removing %dMR", hdev->name, instance); - - if (hdev->cur_adv_instance == instance) { + if (hdev->cur_adv_instance == adv_instance->instance) { if (hdev->adv_instance_timeout) { cancel_delayed_work(&hdev->adv_instance_expire); hdev->adv_instance_timeout = false; @@ -1634,6 +1628,18 @@ int hci_remove_adv_instance(struct hci_dev *hdev, u8 instance) kfree(adv_instance); hdev->adv_instance_cnt--; +} + +/* This function requires the caller holds hdev->lock */ +int hci_remove_adv_instance(struct hci_dev *hdev, u8 instance) +{ + struct adv_info *adv_instance; + + adv_instance = hci_find_adv_instance(hdev, instance); + if (!adv_instance) + return -ENOENT; + + hci_free_adv_instance(hdev, adv_instance); return 0; } From 4dce35adafb5d258a58788c0282a0dd43e7ccd73 Mon Sep 17 00:00:00 2001 From: Weihong Guan Date: Wed, 11 Nov 2026 16:51:33 +0000 Subject: [PATCH 0475/2102] Bluetooth: hci_event: Find the owner of a terminated adv set hci_le_ext_adv_term_evt() looks the instance up by the event's handle, but when the controller supports a single advertising set, hci_add_adv_instance() gives instance 1 handle 0x00, which is also the handle of Global Advertising. For instance 1 the event then finds no instance, and: - a connection from it gets hdev->random_addr as its responder address, rather than the instance's random address, which SMP then checks against; - the connection stores handle 0x00 in conn->adv_instance, which is later restored as hdev->cur_adv_instance, so after the disconnection instance 0 is re-enabled rather than instance 1; - when the set terminates with an error, instance 0 is removed rather than instance 1, so instance 1 stays with no MGMT_EV_ADVERTISING_REMOVED. Find the instance owning the set: for handle 0x00 the instance enabled on it, as hci_le_ext_adv_set_enabled() tracks, and use its instance number and random address. On an error, free the instance found with hci_free_adv_instance() rather than looking it up again. Global Advertising, and any other handle, are handled as before. Fixes: e77f43d531af ("Bluetooth: hci_core: Fix not handling hdev->le_num_of_adv_sets=1") Assisted-by: Claude:claude-opus-5.5 Signed-off-by: Weihong Guan Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_event.c | 42 +++++++++++++++++++++++++++++---------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/net/bluetooth/hci_event.c b/net/bluetooth/hci_event.c index 5e6b25eb50538c..10c8b7b8e3299d 100644 --- a/net/bluetooth/hci_event.c +++ b/net/bluetooth/hci_event.c @@ -6158,6 +6158,26 @@ static void hci_le_pa_sync_lost_evt(struct hci_dev *hdev, void *data, hci_dev_unlock(hdev); } +/* The instance advertising on the set identified by handle. Handle 0x00 may + * be shared by Global Advertising and an instance, e.g. instance 1 when the + * controller supports a single advertising set, in which case the instance + * enabled on it, if any, owns the set (see hci_le_ext_adv_set_enabled()). + */ +static struct adv_info *hci_le_ext_adv_owner(struct hci_dev *hdev, u8 handle) +{ + struct adv_info *adv; + + if (handle) + return hci_find_adv_instance(hdev, handle); + + list_for_each_entry(adv, &hdev->adv_instances, list) { + if (!adv->handle && adv->enabled) + return adv; + } + + return NULL; +} + static void hci_le_ext_adv_term_evt(struct hci_dev *hdev, void *data, struct sk_buff *skb) { @@ -6181,15 +6201,18 @@ static void hci_le_ext_adv_term_evt(struct hci_dev *hdev, void *data, hci_dev_lock(hdev); - adv = hci_find_adv_instance(hdev, ev->handle); + adv = hci_le_ext_adv_owner(hdev, ev->handle); if (ev->status) { + u8 instance; + if (!adv) goto unlock; /* Remove advertising as it has been terminated */ - hci_remove_adv_instance(hdev, ev->handle); - mgmt_advertising_removed(NULL, hdev, ev->handle); + instance = adv->instance; + hci_free_adv_instance(hdev, adv); + mgmt_advertising_removed(NULL, hdev, instance); list_for_each_entry_safe(adv, n, &hdev->adv_instances, list) { if (adv->enabled) @@ -6206,22 +6229,19 @@ static void hci_le_ext_adv_term_evt(struct hci_dev *hdev, void *data, conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(ev->conn_handle)); if (conn) { - /* Store handle in the connection so the correct advertising - * instance can be re-enabled when disconnected. + /* Store the instance in the connection so the correct + * advertising instance can be re-enabled when disconnected. */ - conn->adv_instance = ev->handle; + conn->adv_instance = adv ? adv->instance : ev->handle; if (hdev->adv_addr_type != ADDR_LE_DEV_RANDOM || bacmp(&conn->resp_addr, BDADDR_ANY)) goto unlock; - if (!ev->handle) { - bacpy(&conn->resp_addr, &hdev->random_addr); - goto unlock; - } - if (adv) bacpy(&conn->resp_addr, &adv->random_addr); + else if (!ev->handle) + bacpy(&conn->resp_addr, &hdev->random_addr); } unlock: From fd038b82c71baa8dfb80e1781e53c0dbbda84e70 Mon Sep 17 00:00:00 2001 From: Chun-Yi Lee Date: Wed, 11 Nov 2026 17:45:18 +0800 Subject: [PATCH 0476/2102] Bluetooth: SMP: Fail if local and remote public key X coords match The commit 6d19628f539f ("Bluetooth: SMP: Fail if remote and local public keys are identical") patch be introduced since v5.13. Looks this patch can handle the CVE-2021-37577 issue. However, it only checks if the full 64-byte public key (X and Y coordinates) is identical, which is insufficient. In CVE-2021-37577: Bluetooth LE and BR/EDR Secure Connections pairing and Secure Simple Pairing using the Passkey entry protocol in Bluetooth Core Specifications 2.1 through 5.3 may permit an unauthenticated man-in-the-middle attacker to identify the Passkey used during pairing by reflection of a crafted public key with the same X coordinate as the offered public key and by reflection of the authentication evidence of the initiating device, potentially permitting this attacker to complete authenticated pairing with the responding device using the correct Passkey for the pairing session. This is a related issue to CVE-2020-26558. Furthermore, according to the Bluetooth Core Specification, the remote and local public keys should not have the same X coordinate: Bluetooth Core Specification Version: v5.4 (7.1 PHASE 1: PUBLIC KEY EXCHANGE) "If the two public keys have the same X coordinate and neither is the debug key (see [Vol 4] Part E, Section 7.6.4), each device should fail the pairing process." Bluetooth Core Specification Version: v6.0 (7.1 Phase 1: Public key exchange) "If the two public keys have the same X coordinate and neither is the debug key (see [Vol 4] Part E, Section 7.6.4), each device shall fail the pairing process." To ensure both initiator and responder roles strictly enforce this rule: - In smp_cmd_public_key(), restrict the check for the initiator to compare only the 32-byte X coordinate of the public keys rather than the full 64 bytes. - In sc_send_public_key(), add the corresponding check for the responder to verify that the 32-byte X coordinate of remote_pk does not match local_pk before transmitting its own public key. This makes the validation compliant with the specification and mitigates CVE-2021-37577 across both pairing roles. Fixes: 6d19628f539f ("Bluetooth: SMP: Fail if remote and local public keys are identical") Link: https://nvd.nist.gov/vuln/detail/cve-2021-37577 Signed-off-by: Chun-Yi Lee Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/smp.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/net/bluetooth/smp.c b/net/bluetooth/smp.c index b7015e37e1f1cc..6ccb38b1d56d3c 100644 --- a/net/bluetooth/smp.c +++ b/net/bluetooth/smp.c @@ -1898,6 +1898,16 @@ static u8 sc_send_public_key(struct smp_chan *smp) } done: + /* Check if remote and local public keys are the same and debug key is + * not in use. + */ + if (!test_bit(SMP_FLAG_DEBUG_KEY, &smp->flags) && + !test_bit(SMP_FLAG_INITIATOR, &smp->flags) && + !crypto_memneq(smp->remote_pk, smp->local_pk, 32)) { + bt_dev_err(hdev, "Remote and local public keys are identical"); + return SMP_DHKEY_CHECK_FAILED; + } + SMP_DBG("Local Public Key X: %32phN", smp->local_pk); SMP_DBG("Local Public Key Y: %32phN", smp->local_pk + 32); @@ -2749,7 +2759,8 @@ static int smp_cmd_public_key(struct l2cap_conn *conn, struct sk_buff *skb) * not in use. */ if (!test_bit(SMP_FLAG_DEBUG_KEY, &smp->flags) && - !crypto_memneq(key, smp->local_pk, 64)) { + test_bit(SMP_FLAG_INITIATOR, &smp->flags) && + !crypto_memneq(key, smp->local_pk, 32)) { bt_dev_err(hdev, "Remote and local public keys are identical"); return SMP_DHKEY_CHECK_FAILED; } From 1752a2c40059f845123946e01646b8a1798eeea4 Mon Sep 17 00:00:00 2001 From: Chandrashekar Devegowda Date: Wed, 11 Nov 2026 19:48:22 +0530 Subject: [PATCH 0477/2102] Bluetooth: btintel_pcie: Fix SCP DBGC base address BTINTEL_PCIE_DBGC_BASE_ADDR_SCP was entered as 0xf0d5d500 by mistake when the define was added. The base of the SCP debug controller is 0xf0d5d400, as documented in the Intel SCP SAS document, so the value is one register row too high. The status and wrap-around registers derived from it at offsets 0x1C and 0x2C therefore point at the wrong addresses, and the debug buffer status and wrap-around state read while dumping SCP debug traces are incorrect. Use 0xf0d5d400 so that the derived offsets land on the intended registers. Tested on an SCP platform by triggering a firmware exception and collecting the resulting devcoredump. With the corrected base address, the debug buffer status and wrap-around registers read back valid values and the DRAM monitor buffers in the dump are decoded correctly; with the old address they are read from the wrong registers. Fixes: e43b33bf8d67 ("Bluetooth: btintel_pcie: Load IOSF debug regs by controller variant") Signed-off-by: Chandrashekar Devegowda Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/btintel_pcie.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/bluetooth/btintel_pcie.h b/drivers/bluetooth/btintel_pcie.h index 3030b4e8b75039..5f315ebb4123cd 100644 --- a/drivers/bluetooth/btintel_pcie.h +++ b/drivers/bluetooth/btintel_pcie.h @@ -72,7 +72,7 @@ #define BTINTEL_PCIE_DBGC_CUR_DBGBUFF_STATUS (BTINTEL_PCIE_DBGC_BASE_ADDR + 0x1C) #define BTINTEL_PCIE_DBGC_DBGBUFF_WRAP_ARND (BTINTEL_PCIE_DBGC_BASE_ADDR + 0x2C) -#define BTINTEL_PCIE_DBGC_BASE_ADDR_SCP (0xf0d5d500) +#define BTINTEL_PCIE_DBGC_BASE_ADDR_SCP (0xf0d5d400) #define BTINTEL_PCIE_DBGC_CUR_DBGBUFF_STATUS_SCP (BTINTEL_PCIE_DBGC_BASE_ADDR_SCP + 0x1C) #define BTINTEL_PCIE_DBGC_DBGBUFF_WRAP_ARND_SCP (BTINTEL_PCIE_DBGC_BASE_ADDR_SCP + 0x2C) #define BTINTEL_PCIE_DBGC_ALLOCATION_OFFSET 0x100 From 9def7caa2e55d0c5708385ae0d0039e9eaa26c47 Mon Sep 17 00:00:00 2001 From: Juan Parrado Date: Mon, 9 Nov 2026 11:21:27 +0100 Subject: [PATCH 0478/2102] Input: xpad.c - add support for Hyperkin Xenon, Hori Taiko Controller DX, and 8BitDo M30 Add specific support to various controllers: - HORI Taiko Controller DX - 8BitDo M30 Wired Controller for Xbox - Hyperkin Xenon Controller Signed-off-by: Juan Parrado Link: https://patch.msgid.link/20261109102127.9417-1-jparrado1817@gmail.com Cc: stable@vger.kernel.org Signed-off-by: Dmitry Torokhov --- drivers/input/joystick/xpad.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/input/joystick/xpad.c b/drivers/input/joystick/xpad.c index 21d95e4cae4db0..86f4e756a7fc42 100644 --- a/drivers/input/joystick/xpad.c +++ b/drivers/input/joystick/xpad.c @@ -260,6 +260,7 @@ static const struct xpad_device { { 0x0f0d, 0x00dc, "HORIPAD FPS for Nintendo Switch", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 }, { 0x0f0d, 0x0151, "Hori Racing Wheel Overdrive for Xbox Series X", 0, XTYPE_XBOXONE }, { 0x0f0d, 0x0152, "Hori Racing Wheel Overdrive for Xbox Series X", 0, XTYPE_XBOXONE }, + { 0x0f0d, 0x01b1, "HORI Taiko Controller DX", 0, XTYPE_XBOX360 }, { 0x0f0d, 0x01b2, "HORI Taiko No Tatsujin Drum Controller", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x0f30, 0x010b, "Philips Recoil", 0, XTYPE_XBOX }, { 0x0f30, 0x0202, "Joytech Advanced Controller", 0, XTYPE_XBOX }, @@ -381,6 +382,7 @@ static const struct xpad_device { { 0x294b, 0x3404, "Snakebyte GAMEPAD RGB X", 0, XTYPE_XBOXONE }, { 0x2993, 0x2001, "TECNO Pocket Go", 0, XTYPE_XBOX360 }, { 0x2dc8, 0x2000, "8BitDo Pro 2 Wired Controller fox Xbox", 0, XTYPE_XBOXONE }, + { 0x2dc8, 0x200a, "8BitDo M30 Wired Controller for Xbox", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2dc8, 0x200f, "8BitDo Ultimate 3-mode Controller for Xbox", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2dc8, 0x201e, "8BitDo Pro 2 Wired Controller for Xbox", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2dc8, 0x3106, "8BitDo Ultimate Wireless / Pro 2 Wired Controller", 0, XTYPE_XBOX360 }, @@ -390,6 +392,7 @@ static const struct xpad_device { { 0x2dc8, 0x6001, "8BitDo SN30 Pro", 0, XTYPE_XBOX360 }, { 0x2e24, 0x0423, "Hyperkin DuchesS Xbox One pad", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2e24, 0x0652, "Hyperkin Duke X-Box One pad", 0, XTYPE_XBOXONE }, + { 0x2e24, 0x072e, "Hyperkin Xenon Controller", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2e24, 0x1688, "Hyperkin X91 X-Box One pad", 0, XTYPE_XBOXONE }, { 0x2e95, 0x0504, "SCUF Gaming Controller", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x31e3, 0x1100, "Wooting One", 0, XTYPE_XBOX360 }, From a7602ea542d4e5d1322973349f1d987cb9db3363 Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Wed, 11 Nov 2026 14:11:19 +0300 Subject: [PATCH 0479/2102] KVM: arm64: nv: Initialize hw_mmu to NULL for nested vCPUs Before commit 6ded46b5a4fd ("KVM: arm64: nv: Keep reference on stage-2 MMU when scheduled out"), kvm_vcpu_load_hw_mmu() would set ->hw_mmu on every load. Now it only sets it when it is set to NULL. In kvm_vcpu_init_nested() the vcpu->arch.hw_mmu points to &kvm->arch.mmu from when it was set in kvm_arch_vcpu_create(). Normally what happens next is a two step process. KVM_ARM_VCPU_INIT calls kvm_reset_vcpu_core() and that sets the vcpu into hyp context (vEL2). Then KVM_RUN calls kvm_vcpu_load_hw_mmu() which doesn't do anything. But that is fine because we are in hyp context and the ->hw_mmu already is pointing to the correct place. However if, for example, we are restoring a vcpu that was saved in L2 context, then the VMM uses KVM_SET_ONE_REG to overwrite the vEL2 state that kvm_reset_vcpu_core() set up, and the vCPU is in L2 context when KVM_RUN loads it for the first time. Ideally, kvm_vcpu_load_hw_mmu() would set the hw_mm to point to L2's page tables but, since is non-NULL, it leaves it as is. At this point L2 can access L1's memory. Fix this bug by setting ->hw_mmu to NULL in kvm_vcpu_init_nested() so that kvm_vcpu_load_hw_mmu() always sets it correctly on the first load. Fixes: 6ded46b5a4fd ("KVM: arm64: nv: Keep reference on stage-2 MMU when scheduled out") Cc: stable@vger.kernel.org Signed-off-by: Dan Carpenter Link: https://patch.msgid.link/d3571fb535e1832d2a067649f294b83d824d4350.1794395321.git.dan@cryspen.com [maz: added comment] Signed-off-by: Marc Zyngier --- arch/arm64/kvm/nested.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/arch/arm64/kvm/nested.c b/arch/arm64/kvm/nested.c index 4d83281a7a28b4..004db30e4553da 100644 --- a/arch/arm64/kvm/nested.c +++ b/arch/arm64/kvm/nested.c @@ -140,6 +140,14 @@ int kvm_vcpu_init_nested(struct kvm_vcpu *vcpu) kvm->arch.nested_mmus_size += S2_MMU_PER_VCPU; } + /* + * We can't rely on the S2 MMU staying the canonical one until + * the first run, as userspace can restore a nested context. + * Nuke the hw_mmu early to ensure that we pick the correct one + * at load time. + */ + vcpu->arch.hw_mmu = NULL; + return 0; } From 71c1be5cc4e083852c8437bd6afcb99ee3050e8e Mon Sep 17 00:00:00 2001 From: Felix Gu Date: Sun, 6 Sep 2026 21:30:31 +0800 Subject: [PATCH 0480/2102] phy: ingenic: fix unbalanced regulator disable in exit exit() and power_off() both disable vcc_supply, so the regulator gets disabled twice for every power cycle, causing an unbalanced disable WARN. Drop the regulator_disable() call from the exit callback and leave the regulator to the power_on/power_off pair. Fixes: 31de313dfdcf ("PHY: Ingenic: Add USB PHY driver using generic PHY framework.") Signed-off-by: Felix Gu Reviewed-by: Manivannan Sadhasivam Reviewed-by: Paul Cercueil Tested-by: Olivier Louvignes Reviewed-By: H. Nikolaus Schaller Link: https://patch.msgid.link/20260906-ingenic-v1-1-2311f3df8ddc@gmail.com Signed-off-by: Vinod Koul --- drivers/phy/ingenic/phy-ingenic-usb.c | 1 - 1 file changed, 1 deletion(-) diff --git a/drivers/phy/ingenic/phy-ingenic-usb.c b/drivers/phy/ingenic/phy-ingenic-usb.c index 7e62d46850fdaf..d8e5ef302b748b 100644 --- a/drivers/phy/ingenic/phy-ingenic-usb.c +++ b/drivers/phy/ingenic/phy-ingenic-usb.c @@ -124,7 +124,6 @@ static int ingenic_usb_phy_exit(struct phy *phy) struct ingenic_usb_phy *priv = phy_get_drvdata(phy); clk_disable_unprepare(priv->clk); - regulator_disable(priv->vcc_supply); return 0; } From 64207b5bc6be7db5e75ba9b7eb271dbda30834e5 Mon Sep 17 00:00:00 2001 From: Hongling Zeng Date: Wed, 9 Sep 2026 20:26:27 +0800 Subject: [PATCH 0481/2102] phy: ti-pipe3: Fix ignored clock enable return value in init ti_pipe3_init() ignores the return value of ti_pipe3_enable_clocks(), which can lead to: 1. Unclocked hardware access if clock enable fails 2. Unbalanced clock disables in error paths ti_pipe3_enable_clocks() returns an error code when clock enable fails and rolls back any partially enabled clocks. If we ignore this error and continue, we access hardware without proper clocking, which can cause bus errors. Additionally, if we reach error paths later in the function and call ti_pipe3_disable_clocks(), we'll be disabling already-disabled clocks, causing unbalanced disable warnings. Fix this by checking the return value of ti_pipe3_enable_clocks() and returning early if it fails. Fixes: 234738ea3390 ("phy: ti-pipe3: move clk initialization to a separate function") Reported-by: Sashiko AI Reviewed-by: Manivannan Sadhasivam Signed-off-by: Hongling Zeng Link: https://patch.msgid.link/20260909122630.1313205-2-zenghongling@kylinos.cn Signed-off-by: Vinod Koul --- drivers/phy/ti/phy-ti-pipe3.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/phy/ti/phy-ti-pipe3.c b/drivers/phy/ti/phy-ti-pipe3.c index b5543b5c674c83..0e3bc92187338a 100644 --- a/drivers/phy/ti/phy-ti-pipe3.c +++ b/drivers/phy/ti/phy-ti-pipe3.c @@ -498,9 +498,12 @@ static int ti_pipe3_init(struct phy *x) { struct ti_pipe3 *phy = phy_get_drvdata(x); u32 val; - int ret = 0; + int ret; + + ret = ti_pipe3_enable_clocks(phy); + if (ret) + return ret; - ti_pipe3_enable_clocks(phy); /* * Set pcie_pcs register to 0x96 for proper functioning of phy * as recommended in AM572x TRM SPRUHZ6, section 18.5.2.2, table From 6dc01e3516d79cf4d690d892499a0bd08a14285b Mon Sep 17 00:00:00 2001 From: Hongling Zeng Date: Wed, 9 Sep 2026 20:26:28 +0800 Subject: [PATCH 0482/2102] phy: ti: pipe3: Fix clock resource leak on probe errors When devm_phy_create() or devm_of_phy_provider_register() fails, the refclk that was enabled earlier is not disabled, causing a resource leak. Fix this by adding an error handling path to disable the clock when these functions fail. Fixes: 234738ea3390 ("phy: ti-pipe3: move clk initialization to a separate function") Signed-off-by: Hongling Zeng Reviewed-by: Manivannan Sadhasivam Link: https://patch.msgid.link/20260909122630.1313205-3-zenghongling@kylinos.cn Signed-off-by: Vinod Koul --- drivers/phy/ti/phy-ti-pipe3.c | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/drivers/phy/ti/phy-ti-pipe3.c b/drivers/phy/ti/phy-ti-pipe3.c index 0e3bc92187338a..021657cbce481d 100644 --- a/drivers/phy/ti/phy-ti-pipe3.c +++ b/drivers/phy/ti/phy-ti-pipe3.c @@ -834,21 +834,39 @@ static int ti_pipe3_probe(struct platform_device *pdev) */ if (phy->mode == PIPE3_MODE_SATA) { if (!IS_ERR(phy->refclk)) { - clk_prepare_enable(phy->refclk); + ret = clk_prepare_enable(phy->refclk); + if (ret) { + dev_err(dev, "Failed to enable refclk %d\n", ret); + goto err_pm_disable; + } phy->sata_refclk_enabled = true; } } generic_phy = devm_phy_create(dev, NULL, &ops); - if (IS_ERR(generic_phy)) - return PTR_ERR(generic_phy); + if (IS_ERR(generic_phy)) { + ret = PTR_ERR(generic_phy); + goto err_clk_disable; + } phy_set_drvdata(generic_phy, phy); ti_pipe3_power_off(generic_phy); phy_provider = devm_of_phy_provider_register(dev, of_phy_simple_xlate); - return PTR_ERR_OR_ZERO(phy_provider); + if (IS_ERR(phy_provider)) { + ret = PTR_ERR(phy_provider); + goto err_clk_disable; + } + + return 0; + +err_clk_disable: + if (phy->sata_refclk_enabled) + clk_disable_unprepare(phy->refclk); +err_pm_disable: + pm_runtime_disable(dev); + return ret; } static void ti_pipe3_remove(struct platform_device *pdev) From aeb637c73631851de0965514151f7ff7bc13f940 Mon Sep 17 00:00:00 2001 From: Hongling Zeng Date: Wed, 9 Sep 2026 20:26:29 +0800 Subject: [PATCH 0483/2102] phy: ti-pipe3: Fix EPROBE_DEFER handling for clock resources ti_pipe3_get_clk() has two issues with -EPROBE_DEFER error handling: 1. When devm_clk_get() for sysclk fails, the function returns -EINVAL instead of propagating the actual error code. This masks -EPROBE_DEFER to -EINVAL, breaking the probe deferral mechanism and causing permanent driver initialization failure on systems with non-deterministic probe ordering. 2. For SATA PHY refclk, the function ignores all errors to support older DTBs missing the refclk property. However, this incorrectly ignores -EPROBE_DEFER as well, causing the driver to proceed without waiting for the clock provider to become available. Fix both issues: - Return PTR_ERR(phy->sys_clk) instead of -EINVAL to propagate all error codes including -EPROBE_DEFER - Use devm_clk_get_optional() for SATA refclk to handle optional clocks while propagating -EPROBE_DEFER and other errors Fixes: a70143bbef6b ("drivers: phy: usb3/pipe3: Adapt pipe3 driver to Generic PHY Framework") Fixes: 7f33912d2978 ("phy: ti-pipe3: Fix SATA across suspend/resume") Suggested-by: Manivannan Sadhasivam Signed-off-by: Hongling Zeng Reviewed-by: Manivannan Sadhasivam Link: https://patch.msgid.link/20260909122630.1313205-4-zenghongling@kylinos.cn Signed-off-by: Vinod Koul --- drivers/phy/ti/phy-ti-pipe3.c | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/drivers/phy/ti/phy-ti-pipe3.c b/drivers/phy/ti/phy-ti-pipe3.c index 021657cbce481d..fdd81c935e5f3a 100644 --- a/drivers/phy/ti/phy-ti-pipe3.c +++ b/drivers/phy/ti/phy-ti-pipe3.c @@ -608,14 +608,20 @@ static int ti_pipe3_get_clk(struct ti_pipe3 *phy) struct clk *clk; struct device *dev = phy->dev; - phy->refclk = devm_clk_get(dev, "refclk"); + /* + * refclk is optional for SATA PHY to support older DTBs, but + * required for other modes. Use devm_clk_get_optional() for SATA + * which returns NULL for -ENOENT, allowing us to propagate all + * other errors including -EPROBE_DEFER. + */ + if (phy->mode == PIPE3_MODE_SATA) + phy->refclk = devm_clk_get_optional(dev, "refclk"); + else + phy->refclk = devm_clk_get(dev, "refclk"); + if (IS_ERR(phy->refclk)) { - dev_err(dev, "unable to get refclk\n"); - /* older DTBs have missing refclk in SATA PHY - * so don't bail out in case of SATA PHY. - */ - if (phy->mode != PIPE3_MODE_SATA) - return PTR_ERR(phy->refclk); + return dev_err_probe(dev, PTR_ERR(phy->refclk), + "unable to get refclk\n"); } if (phy->mode != PIPE3_MODE_SATA) { @@ -631,8 +637,8 @@ static int ti_pipe3_get_clk(struct ti_pipe3 *phy) if (phy->mode != PIPE3_MODE_PCIE || phy->phy_power_syscon) { phy->sys_clk = devm_clk_get(dev, "sysclk"); if (IS_ERR(phy->sys_clk)) { - dev_err(dev, "unable to get sysclk\n"); - return -EINVAL; + return dev_err_probe(dev, PTR_ERR(phy->sys_clk), + "unable to get sysclk\n"); } } From 2be6a65608a5e32b2be6f5da843b1f29f1091098 Mon Sep 17 00:00:00 2001 From: Hongling Zeng Date: Wed, 9 Sep 2026 20:26:30 +0800 Subject: [PATCH 0484/2102] phy: ti-pipe3: Fix clock leaks in init/exit error paths Two paths return without disabling the clocks that ti_pipe3_init() has just enabled, leaking clock enable references: 1. In ti_pipe3_init(), when regmap_update_bits() fails for PCIe mode, the function returns the error without calling ti_pipe3_disable_clocks(). The clocks stay permanently enabled since the PHY framework won't invoke the .exit callback on init failure. 2. In ti_pipe3_exit(), when the PHY is in SATA mode without dpll_reset_syscon, the function returns 0 early to avoid powering down the SATA DPLL (Errata i783), which also skips the ti_pipe3_disable_clocks() at the end of the function. Every init/exit cycle therefore leaks the clock enable reference taken in ti_pipe3_init(). Fix both by adding the missing ti_pipe3_disable_clocks() calls, consistent with how the DPLL program error path handles cleanup. Fixes: 234738ea3390 ("phy: ti-pipe3: move clk initialization to a separate function") Fixes: 0a0830feb2ad ("phy: ti-pipe3: fix suspend") Reported-by: Sashiko AI Closes: https://lore.kernel.org/all/20260518023657.41852C2BCB0@smtp.kernel.org/ Signed-off-by: Hongling Zeng Reviewed-by: Manivannan Sadhasivam Link: https://patch.msgid.link/20260909122630.1313205-5-zenghongling@kylinos.cn Signed-off-by: Vinod Koul --- drivers/phy/ti/phy-ti-pipe3.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/drivers/phy/ti/phy-ti-pipe3.c b/drivers/phy/ti/phy-ti-pipe3.c index fdd81c935e5f3a..0d4a49a3f0c79e 100644 --- a/drivers/phy/ti/phy-ti-pipe3.c +++ b/drivers/phy/ti/phy-ti-pipe3.c @@ -518,6 +518,8 @@ static int ti_pipe3_init(struct phy *x) val = 0x96 << OMAP_CTRL_PCIE_PCS_DELAY_COUNT_SHIFT; ret = regmap_update_bits(phy->pcs_syscon, phy->pcie_pcs_reg, PCIE_PCS_MASK, val); + if (ret) + ti_pipe3_disable_clocks(phy); return ret; } @@ -555,8 +557,10 @@ static int ti_pipe3_exit(struct phy *x) /* If dpll_reset_syscon is not present we wont power down SATA DPLL * due to Errata i783 */ - if (phy->mode == PIPE3_MODE_SATA && !phy->dpll_reset_syscon) + if (phy->mode == PIPE3_MODE_SATA && !phy->dpll_reset_syscon) { + ti_pipe3_disable_clocks(phy); return 0; + } /* PCIe doesn't have internal DPLL */ if (phy->mode != PIPE3_MODE_PCIE) { From 24314440a82bd2bb66049af4de8f89939a1fd77f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=A0t=C4=9Bp=C3=A1n=20Daleck=C3=BD?= Date: Thu, 1 Oct 2026 17:19:38 +0200 Subject: [PATCH 0485/2102] phy: marvell: a3700-comphy: Guard missing polarity argument MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Armada 3700 COMPHY binding specifies #phy-cells = <1>, so PHY references supply only the port argument. However, mvebu_a3700_comphy_xlate() unconditionally reads args[1] to select TX and RX polarity inversion. The PHY core does not initialize its of_phandle_args structure, and the phandle parser fills only the supplied cells, leaving args[1] uninitialized. Using the unused cell can program unintended SerDes polarity. On a Turris MOX with a Peridot switch running OpenWrt with Linux 6.18.54, the CPU link reports RX CRC errors and fails to pass traffic. The switch PCS does not record a partner advertisement despite link-up. Check args_count before reading args[1], leaving polarity inversion disabled when the second argument was not supplied. This does not change the binding or introduce a supported two-cell interface. The same change restores 2500BASE-X communication on the affected MOX with no CRC errors. Cold boots, reboots and interface down/up cycles were also tested successfully on Linux 6.18.54. Fixes: 934337080c6c ("phy: marvell: phy-mvebu-a3700-comphy: Add native kernel implementation") Cc: stable@vger.kernel.org Closes: https://github.com/openwrt/openwrt/issues/24069 Assisted-by: LLM Signed-off-by: Štěpán Dalecký Reviewed-by: Manivannan Sadhasivam Reviewed-by: Miquel Raynal Link: https://patch.msgid.link/20261001151939.23658-1-daleckystepan@gmail.com Signed-off-by: Vinod Koul --- drivers/phy/marvell/phy-mvebu-a3700-comphy.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/phy/marvell/phy-mvebu-a3700-comphy.c b/drivers/phy/marvell/phy-mvebu-a3700-comphy.c index 1d1db1737422a8..d19f0fa9ba7c70 100644 --- a/drivers/phy/marvell/phy-mvebu-a3700-comphy.c +++ b/drivers/phy/marvell/phy-mvebu-a3700-comphy.c @@ -1232,8 +1232,8 @@ static struct phy *mvebu_a3700_comphy_xlate(struct device *dev, return ERR_PTR(-EINVAL); } - lane->invert_tx = args->args[1] & BIT(0); - lane->invert_rx = args->args[1] & BIT(1); + lane->invert_tx = args->args_count > 1 && (args->args[1] & BIT(0)); + lane->invert_rx = args->args_count > 1 && (args->args[1] & BIT(1)); return phy; } From 9a07dfa7f6fe34e230de183c02a8180529091649 Mon Sep 17 00:00:00 2001 From: Michael Burch Date: Tue, 13 Oct 2026 09:22:49 -0500 Subject: [PATCH 0486/2102] Revert "phy: qcom: qmp-pcie: Skip PHY reset if already up" This reverts commit 910b828b22b7b91054b3bd4be676a017444b0e00. That commit skips the no-csr reset assert/deassert (and the 200-300us settle) whenever the bootloader already brought the PCIe QMP PHY up: skip_reset = qmp->skip_init && !qphy_checkbits(pcs, cfg->regs[QPHY_PCS_STATUS], cfg->phy_status); and states its own assumption explicitly: "This relies on the assumption that when skip_init is enabled and the PHY is reported as up, the bootloader has already configured the PHY correctly and the link is in a usable state." That assumption does not hold on the Dell XPS 13 9345 (X1E80100). UEFI boots from the NVMe behind pcie6a, so the PHY is always already started when Linux takes over, skip_init is true, and the reset is skipped. The link then never retrains and the root port comes up with no endpoint: qcom-pcie 1bf8000.pcie: Device found, but not active pci 0006:00:00.0: [17cb:0111] type 01 class 0x060400 PCIe Root Port (no 0006:01:00.0, no nvme at all) "Device found, but not active" is dw_pcie_wait_for_link() reporting LTSSM stuck in POLL.Active/POLL.Compliance -- receiver detected, training never completes -- so the machine cannot find its root filesystem and drops to a dracut emergency shell. v7.2 is unaffected because it always performed the reset. The commit was applied on its own as patch 1/4 of "PCI: qcom: Add link retention support"; 2/4-4/4 have not landed. Without them, qcom_pcie_host_init() still asserts PERST# and resets the controller before qcom_pcie_phy_power_on(), so the link is down while QPHY_PCS_STATUS still reports the bootloader's state, and the skip's precondition never holds. Revert it until the rest of the series lands. Fixes: 910b828b22b7 ("phy: qcom: qmp-pcie: Skip PHY reset if already up") Signed-off-by: Michael Burch Reviewed-by: Manivannan Sadhasivam Link: https://patch.msgid.link/20261013-qmp-pcie-skip-reset-revert-v1@michaelburch.net Signed-off-by: Vinod Koul --- drivers/phy/qualcomm/phy-qcom-qmp-pcie.c | 31 ++++++++---------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/drivers/phy/qualcomm/phy-qcom-qmp-pcie.c b/drivers/phy/qualcomm/phy-qcom-qmp-pcie.c index 9cfabf474fd63f..2b56ec534d8634 100644 --- a/drivers/phy/qualcomm/phy-qcom-qmp-pcie.c +++ b/drivers/phy/qualcomm/phy-qcom-qmp-pcie.c @@ -5715,7 +5715,6 @@ static int qmp_pcie_init(struct phy *phy) struct qmp_pcie *qmp = phy_get_drvdata(phy); const struct qmp_phy_cfg *cfg = qmp->cfg; void __iomem *pcs = qmp->pcs; - bool skip_reset; int ret; /* @@ -5731,9 +5730,6 @@ static int qmp_pcie_init(struct phy *phy) qphy_checkbits(pcs, cfg->regs[QPHY_START_CTRL], SERDES_START | PCS_START) && qphy_checkbits(pcs, cfg->regs[QPHY_PCS_POWER_DOWN_CONTROL], cfg->pwrdn_ctrl); - skip_reset = qmp->skip_init && !qphy_checkbits(pcs, cfg->regs[QPHY_PCS_STATUS], - cfg->phy_status); - if (!qmp->skip_init && !cfg->tbls.serdes_num) { dev_err(qmp->dev, "Init sequence not available\n"); return -ENODATA; @@ -5757,16 +5753,14 @@ static int qmp_pcie_init(struct phy *phy) } } - if (!skip_reset) { - ret = reset_control_assert(qmp->nocsr_reset); - if (ret) { - dev_err(qmp->dev, "no-csr reset assert failed\n"); - goto err_assert_reset; - } - - usleep_range(200, 300); + ret = reset_control_assert(qmp->nocsr_reset); + if (ret) { + dev_err(qmp->dev, "no-csr reset assert failed\n"); + goto err_assert_reset; } + usleep_range(200, 300); + if (!qmp->skip_init) { ret = reset_control_bulk_deassert(cfg->num_resets, qmp->resets); if (ret) { @@ -5815,11 +5809,8 @@ static int qmp_pcie_power_on(struct phy *phy) void __iomem *pcs = qmp->pcs; void __iomem *status; unsigned int mask, val; - bool skip_reset; int ret; - skip_reset = qmp->skip_init && !qphy_checkbits(pcs, cfg->regs[QPHY_PCS_STATUS], - cfg->phy_status); /* * Write CSR register for PHY that doesn't support no_csr reset or has not * been initialized. @@ -5843,12 +5834,10 @@ static int qmp_pcie_power_on(struct phy *phy) if (ret) return ret; - if (!skip_reset) { - ret = reset_control_deassert(qmp->nocsr_reset); - if (ret) { - dev_err(qmp->dev, "no-csr reset deassert failed\n"); - goto err_disable_pipe_clk; - } + ret = reset_control_deassert(qmp->nocsr_reset); + if (ret) { + dev_err(qmp->dev, "no-csr reset deassert failed\n"); + goto err_disable_pipe_clk; } if (qmp->skip_init) From 96246dc6c16a5e5a6b4b9fde8f4ab9cdeb201088 Mon Sep 17 00:00:00 2001 From: Shawn Lin Date: Thu, 15 Oct 2026 11:59:47 +0800 Subject: [PATCH 0487/2102] phy: rockchip: naneng-combphy: Fix overwritten PLL SSC control bit rk_combphy_common_cfg_ssc() first sets RK3568_PHYREG33_PLL_SSC_CTRL on the RK3588 and RK3576 SoCs, then, for PCIe at 24MHz, programs the PLL KVCO adjust field. The latter used a plain writel() of the FIELD_PREP() value, which cleared all the other bits of RK3568_PHYREG33, including the PLL_SSC_CTRL bit that had just been set a few lines above. Use rockchip_combphy_updatel() so that only the KVCO field is updated and the SSC control bit is preserved, as the comment and the pre-consolidation code intended. Fixes: 0b31f297557f ("phy: rockchip: naneng-combphy: Consolidate SSC configuration") Signed-off-by: Shawn Lin Reviewed-by: Manivannan Sadhasivam Reviewed-by: Sebastian Reichel Link: https://patch.msgid.link/1792036787-37927-1-git-send-email-shawn.lin@rock-chips.com Signed-off-by: Vinod Koul --- drivers/phy/rockchip/phy-rockchip-naneng-combphy.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c b/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c index 3102a99128f62c..b6cc010327831f 100644 --- a/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c +++ b/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c @@ -526,7 +526,8 @@ static void rk_combphy_common_cfg_ssc(struct rockchip_combphy_priv *priv, unsign val = FIELD_PREP(RK3568_PHYREG33_PLL_KVCO_MASK, RK3576_PHYREG33_PLL_KVCO_VALUE); - writel(val, priv->mmio + RK3568_PHYREG33); + rockchip_combphy_updatel(priv, RK3568_PHYREG33_PLL_KVCO_MASK, + val, RK3568_PHYREG33); } } From ba6618a1e7c02f384069f7817133ff8cb5c793b8 Mon Sep 17 00:00:00 2001 From: Selvarasu Ganesan Date: Tue, 20 Oct 2026 12:05:59 +0530 Subject: [PATCH 0488/2102] phy: exynos5-usbdrd: Use dynamic phy_cfg size to prevent OOB access MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The probe loop currently iterates using EXYNOS5_DRDPHYS_NUM (2), creating both UTMI and PIPE3 PHY instances regardless of the SoC capability. Several SoCs (Exynos2200, Exynos7870, Exynos850, Exynos990, and ExynosAutoV920) provide phy_cfg arrays containing only a single element. On these SoCs, when the loop reaches index 1, the driver reads past the end of the rodata array, populating the second PHY instance with garbage data. Since the configuration structure contains critical function pointers (phy_isol, phy_init, set_refclk), any subsequent access to this PHY instance via exynos5_usbdrd_phy_xlate could result in a kernel oops. Fix this by adding 'n_phy_cfg' to struct exynos5_usbdrd_phy_drvdata to store the actual size of the phy_cfg array for each SoC. Update the probe loop and the xlate function to bound their access against this value instead of the hardcoded EXYNOS5_DRDPHYS_NUM. Fixes: 59025887fb08 ("phy: Add new Exynos5 USB 3.0 PHY driver") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Selvarasu Ganesan Tested-by: Łukasz Lebiedziński Reviewed-by: Alim Akhtar Reviewed-by: André Draszik Reviewed-by: Peter Griffin Reviewed-by: Manivannan Sadhasivam Link: https://patch.msgid.link/20261020063559.3530901-1-selvarasu.g@samsung.com Signed-off-by: Vinod Koul --- drivers/phy/samsung/phy-exynos5-usbdrd.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/drivers/phy/samsung/phy-exynos5-usbdrd.c b/drivers/phy/samsung/phy-exynos5-usbdrd.c index 087d552eb5119c..f10cf7b6e0aa47 100644 --- a/drivers/phy/samsung/phy-exynos5-usbdrd.c +++ b/drivers/phy/samsung/phy-exynos5-usbdrd.c @@ -477,6 +477,7 @@ struct exynos5_usbdrd_phy_config { struct exynos5_usbdrd_phy_drvdata { const struct exynos5_usbdrd_phy_config *phy_cfg; + int n_phy_cfg; const struct exynos5_usbdrd_phy_tuning **phy_tunes; const struct phy_ops *phy_ops; const char * const *clk_names; @@ -1173,7 +1174,7 @@ static struct phy *exynos5_usbdrd_phy_xlate(struct device *dev, { struct exynos5_usbdrd_phy *phy_drd = dev_get_drvdata(dev); - if (WARN_ON(args->args[0] >= EXYNOS5_DRDPHYS_NUM)) + if (WARN_ON(args->args[0] >= phy_drd->drv_data->n_phy_cfg)) return ERR_PTR(-ENODEV); return phy_drd->phys[args->args[0]].phy; @@ -2021,6 +2022,7 @@ static const char * const exynos5_regulator_names[] = { static const struct exynos5_usbdrd_phy_drvdata exynos2200_usb32drd_phy = { .phy_cfg = phy_cfg_exynos2200, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos2200), .phy_ops = &exynos2200_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS2200_PHY_CTRL_USB20, .clk_names = exynos5_clk_names, @@ -2034,6 +2036,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos2200_usb32drd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos5420_usbdrd_phy = { .phy_cfg = phy_cfg_exynos5, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos5), .phy_ops = &exynos5_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, .pmu_offset_usbdrd1_phy = EXYNOS5420_USBDRD1_PHY_CONTROL, @@ -2047,6 +2050,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos5420_usbdrd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos5250_usbdrd_phy = { .phy_cfg = phy_cfg_exynos5, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos5), .phy_ops = &exynos5_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, .clk_names = exynos5_clk_names, @@ -2059,6 +2063,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos5250_usbdrd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos5433_usbdrd_phy = { .phy_cfg = phy_cfg_exynos5, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos5), .phy_ops = &exynos5_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, .pmu_offset_usbdrd1_phy = EXYNOS5433_USBHOST30_PHY_CONTROL, @@ -2072,6 +2077,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos5433_usbdrd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos7_usbdrd_phy = { .phy_cfg = phy_cfg_exynos5, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos5), .phy_ops = &exynos5_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, .clk_names = exynos5_clk_names, @@ -2084,6 +2090,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos7_usbdrd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos7870_usbdrd_phy = { .phy_cfg = phy_cfg_exynos7870, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos7870), .phy_tunes = exynos7870_tunes, .phy_ops = &exynos7870_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, @@ -2097,6 +2104,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos7870_usbdrd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos850_usbdrd_phy = { .phy_cfg = phy_cfg_exynos850, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos850), .phy_ops = &exynos850_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, .clk_names = exynos5_clk_names, @@ -2125,6 +2133,7 @@ static const struct exynos5_usbdrd_phy_tuning *exynos990_tunes[PTS_MAX] = { static const struct exynos5_usbdrd_phy_drvdata exynos990_usbdrd_phy = { .phy_cfg = phy_cfg_exynos850, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos850), .phy_ops = &exynos850_usbdrd_phy_ops, .phy_tunes = exynos990_tunes, .pmu_offset_usbdrd0_phy = EXYNOS990_PHY_CTRL_USB20, @@ -2661,6 +2670,7 @@ static const struct phy_ops exynosautov920_usb31drd_combo_ssphy_ops = { static const struct exynos5_usbdrd_phy_drvdata exynosautov920_usb31drd_combo_ssphy = { .phy_cfg = usb31drd_phy_cfg_exynosautov920, + .n_phy_cfg = ARRAY_SIZE(usb31drd_phy_cfg_exynosautov920), .phy_ops = &exynosautov920_usb31drd_combo_ssphy_ops, .pmu_offset_usbdrd0_phy = EXYNOSAUTOV920_PHY_CTRL_USB31, .clk_names = exynos5_clk_names, @@ -2691,6 +2701,7 @@ exynos5_usbdrd_phy_config usbdrd_hsphy_cfg_exynosautov920[] = { static const struct exynos5_usbdrd_phy_drvdata exynosautov920_usbdrd_combo_hsphy = { .phy_cfg = usbdrd_hsphy_cfg_exynosautov920, + .n_phy_cfg = ARRAY_SIZE(usbdrd_hsphy_cfg_exynosautov920), .phy_ops = &exynosautov920_usbdrd_combo_hsphy_ops, .pmu_offset_usbdrd0_phy = EXYNOSAUTOV920_PHY_CTRL_USB20, .clk_names = exynos5_clk_names, @@ -2719,6 +2730,7 @@ static const struct exynos5_usbdrd_phy_config phy_cfg_exynosautov920[] = { static const struct exynos5_usbdrd_phy_drvdata exynosautov920_usbdrd_phy = { .phy_cfg = phy_cfg_exynosautov920, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynosautov920), .phy_ops = &exynosautov920_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOSAUTOV920_PHY_CTRL_USB20, .clk_names = exynos5_clk_names, @@ -2895,6 +2907,7 @@ static const char * const gs101_regulator_names[] = { static const struct exynos5_usbdrd_phy_drvdata gs101_usbd31rd_phy = { .phy_cfg = phy_cfg_gs101, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_gs101), .phy_tunes = gs101_tunes, .phy_ops = &gs101_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = GS101_PHY_CTRL_USB20, @@ -3052,7 +3065,7 @@ static int exynos5_usbdrd_phy_probe(struct platform_device *pdev) dev_vdbg(dev, "Creating usbdrd_phy phy\n"); - for (i = 0; i < EXYNOS5_DRDPHYS_NUM; i++) { + for (i = 0; i < drv_data->n_phy_cfg; i++) { struct phy *phy = devm_phy_create(dev, NULL, drv_data->phy_ops); if (IS_ERR(phy)) From 518d5bc7a636696969e3f4a7f9c66483e4f35e1e Mon Sep 17 00:00:00 2001 From: Geert Uytterhoeven Date: Tue, 20 Oct 2026 14:27:51 +0200 Subject: [PATCH 0489/2102] phy: PHY_GOOGLE_USB should depend on ARCH_GOOGLE The Google Tensor SoC USB PHY is only present on Google Tensor G5 (Laguna) SoCs. Hence add a dependency on ARCH_GOOGLE, to prevent asking the user about this driver when configuring a kernel without Google Tensor SoC support. Fixes: cbce66669c82ee9a ("phy: Add Google Tensor SoC USB PHY driver") Signed-off-by: Geert Uytterhoeven Reviewed-by: Manivannan Sadhasivam Link: https://patch.msgid.link/90a172c2980073a09b4f01c21a251c3d0d2d6fe5.1792499240.git.geert+renesas@glider.be Signed-off-by: Vinod Koul --- drivers/phy/Kconfig | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/phy/Kconfig b/drivers/phy/Kconfig index 105fbe408aa25b..d151c05297d7e5 100644 --- a/drivers/phy/Kconfig +++ b/drivers/phy/Kconfig @@ -93,6 +93,7 @@ config PHY_ECONET_PCIE config PHY_GOOGLE_USB tristate "Google Tensor SoC USB PHY driver" + depends on ARCH_GOOGLE || COMPILE_TEST select GENERIC_PHY depends on TYPEC help From 5570a998b884c988dbe105430d7e2d8e9411e37e Mon Sep 17 00:00:00 2001 From: "Michael S. Tsirkin" Date: Fri, 6 Nov 2026 09:11:07 -0500 Subject: [PATCH 0490/2102] vhost: split out-of-order used ring batches at every wrap When a completion batch larger than the remaining space in the used ring is added without VIRTIO_F_IN_ORDER, vhost_add_used_n_ooo() splits it at the ring boundary only once. vhost-net can batch up to VHOST_NET_BATCH TX completions, so with a queue smaller than half the batch the tail of the second chunk runs past the end of the used ring and into whatever follows it in the vhost owner's address space: with a 32 entry queue, last_used_idx % 32 == 3 and a 64 entry batch, three used entries are written past the ring. To fix, keep splitting the remaining batch at each wrap until it is exhausted. Cc: stable@vger.kernel.org Reported-by: Seohyeon Maeng Cc: minki@morningstarsec.dev Fixes: 2b3b35eb989 ("vhost_net: batch used ring update in rx") Fixes: 4afb52c2af44 ("vhost_net: batch update used ring for datacopy TX") Cc: Jason Wang Signed-off-by: Michael S. Tsirkin --- drivers/vhost/vhost.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/drivers/vhost/vhost.c b/drivers/vhost/vhost.c index ea127af58adad8..ce80f7cbc22408 100644 --- a/drivers/vhost/vhost.c +++ b/drivers/vhost/vhost.c @@ -3153,18 +3153,21 @@ static int vhost_add_used_n_ooo(struct vhost_virtqueue *vq, struct vring_used_elem *heads, unsigned count) { - int start, n, r; + unsigned int n; + int r; - start = vq->last_used_idx & (vq->num - 1); - n = vq->num - start; - if (n < count) { + do { + unsigned int start = vq->last_used_idx & (vq->num - 1); + + n = min(vq->num - start, count); r = __vhost_add_used_n(vq, heads, n); if (r < 0) return r; heads += n; count -= n; - } - return __vhost_add_used_n(vq, heads, count); + } while (count); + + return 0; } static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq, From f53542298e5a66fa4ac73c6861df33deebe984b8 Mon Sep 17 00:00:00 2001 From: Claudio Imbrenda Date: Thu, 5 Nov 2026 16:37:01 +0100 Subject: [PATCH 0491/2102] KVM: s390: Fix UCONTROL inconsistencies For UCONTROL VMs, when a vCPU segment entry is mapped but unallocated, the tl field was set to 1. This collides with the present bit, which means that other parts of gmap would mistake the entry for a present one. Refactor the code to use a different combination of flags to indicate a mapped but unallocated segment. The new flags combination will result in several functions returning -EFAULT when used on UCONTROL guests. This is fine, since those interfaces should not be used for UCONTROL guests to begin with. Proper fencing of the interfaces that are not allowed for UCONTROL guests is outside the scope of this patch. Fixes: a2c17f9270cc ("KVM: s390: New gmap code") Signed-off-by: Claudio Imbrenda Cc: stable@vger.kernel.org # 7.0+ Acked-by: Christian Borntraeger Signed-off-by: Christian Borntraeger --- arch/s390/kvm/gmap/dat.h | 22 +++++++++++++++- arch/s390/kvm/gmap/gmap.c | 54 +++++++++++++++++++-------------------- 2 files changed, 47 insertions(+), 29 deletions(-) diff --git a/arch/s390/kvm/gmap/dat.h b/arch/s390/kvm/gmap/dat.h index 90389d47ba4e04..e6215c0b571f92 100644 --- a/arch/s390/kvm/gmap/dat.h +++ b/arch/s390/kvm/gmap/dat.h @@ -109,6 +109,8 @@ union pte { #define _REGION3_FR_MASK (_REGION3_MASK >> PAGE_SHIFT) #define _PAGES_PER_SEGMENT _PAGE_ENTRIES #define _PAGES_PER_REGION3 (_PAGES_PER_SEGMENT * _CRST_ENTRIES) +#define _UCAS_ENTRY_LENGTH 0 +#define _UCAS_ENTRY_OFFSET 3 /* Soft dirty, needed as macro for atomic operations on ptes */ #define _PAGE_SD 0x002 @@ -421,6 +423,23 @@ static inline union crste _crste_fc0(kvm_pfn_t pfn, int tt) return res; } +static inline union crste _crste_ucas(kvm_pfn_t pfn) +{ + union crste res = { .val = PFN_PHYS(pfn) }; + + res.h.i = 1; + res.h.tt = TABLE_TYPE_SEGMENT; + /* + * Segment entries do not have a TF or TL field; reuse those bits to + * indicate that this is a special mappped-but-not-allocated UCAS + * entry. Setting TL to 0 ensures that the entry will always be + * considered not present. + */ + res.h.fc0.tl = _UCAS_ENTRY_LENGTH; + res.h.fc0.tf = _UCAS_ENTRY_OFFSET; + return res; +} + /** * _crste() - Useful constructor for union crste with FC=1 * @pfn: the pfn this pte should point to. @@ -985,7 +1004,8 @@ static inline int dat_create_slot(struct kvm_s390_mmu_cache *mc, union asce asce static inline bool crste_is_ucas(union crste crste) { - return is_pmd(crste) && crste.h.i && crste.h.fc0.tl == 1 && crste.h.fc == 0; + return is_pmd(crste) && crste.h.i && !crste.h.fc && + crste.h.fc0.tl == _UCAS_ENTRY_LENGTH && crste.h.fc0.tf == _UCAS_ENTRY_OFFSET; } #endif /* ARCH_KVM_GMAP_DAT_H */ diff --git a/arch/s390/kvm/gmap/gmap.c b/arch/s390/kvm/gmap/gmap.c index bf91e3d5013b57..225fdae3d57ca7 100644 --- a/arch/s390/kvm/gmap/gmap.c +++ b/arch/s390/kvm/gmap/gmap.c @@ -777,16 +777,14 @@ static int gmap_ucas_map_one(struct kvm_s390_mmu_cache *mc, struct gmap *gmap, if (rc) return rc; if (!ptep) { - newcrste = _crste_fc0(p_gfn, TABLE_TYPE_SEGMENT); - newcrste.h.i = 1; - newcrste.h.fc0.tl = 1; + newcrste = _crste_ucas(p_gfn); } else { pt = pte_table_start(ptep); dat_set_ptval(pt, PTVAL_VMADDR, p_gfn >> (_SEGMENT_SHIFT - PAGE_SHIFT)); newcrste = _crste_fc0(virt_to_pfn(pt), TABLE_TYPE_SEGMENT); } - rc = dat_entry_walk(mc, c_gfn, gmap->asce, DAT_WALK_ALLOC, TABLE_TYPE_SEGMENT, - &crstep, &ptep); + rc = dat_entry_walk(mc, c_gfn, gmap->asce, DAT_WALK_ALLOC | DAT_WALK_IGN_HOLES, + TABLE_TYPE_SEGMENT, &crstep, &ptep); if (rc) return rc; do { @@ -802,8 +800,9 @@ static int gmap_ucas_translate_simple(struct gmap *gmap, gpa_t *gaddr, union crs union pte *ptep; int rc; - rc = dat_entry_walk(NULL, gpa_to_gfn(*gaddr), gmap->asce, DAT_WALK_CONTINUE, - TABLE_TYPE_SEGMENT, crstepp, &ptep); + rc = dat_entry_walk(NULL, gpa_to_gfn(*gaddr), gmap->asce, + DAT_WALK_IGN_HOLES | DAT_WALK_ANY, + TABLE_TYPE_PAGE_TABLE, crstepp, &ptep); if (rc || (!ptep && !crste_is_ucas(**crstepp))) return -EREMOTE; if (!ptep) @@ -840,26 +839,24 @@ int gmap_ucas_translate(struct kvm_s390_mmu_cache *mc, struct gmap *gmap, gpa_t if (rc <= 0) return rc; } - do { - scoped_guard(write_lock, &gmap->kvm->mmu_lock) { - rc = gmap_ucas_translate_simple(gmap, gaddr, &crstep); - if (rc <= 0) - return rc; - translated_address = (*gaddr & ~_SEGMENT_MASK) | - (crstep->val & _SEGMENT_MASK); - rc = gmap_ucas_map_one(mc, gmap, gpa_to_gfn(translated_address), gfn, true); - } - if (!rc) { - *gaddr = translated_address; - return 0; - } - if (rc != -ENOMEM) - return -EREMOTE; - rc = kvm_s390_mmu_cache_topup(mc); - if (rc) + rc = kvm_s390_mmu_cache_topup(mc); + if (rc) + return rc; + + scoped_guard(write_lock, &gmap->kvm->mmu_lock) { + rc = gmap_ucas_translate_simple(gmap, gaddr, &crstep); + if (rc <= 0) return rc; - } while (1); - return 0; + translated_address = (*gaddr & ~_SEGMENT_MASK) | + (crstep->val & _SEGMENT_MASK); + rc = gmap_ucas_map_one(mc, gmap, gpa_to_gfn(translated_address), gfn, true); + } + + if (!rc) + *gaddr = translated_address; + if (!rc || rc == -ENOMEM) + return rc; + return -EREMOTE; } int gmap_ucas_map(struct gmap *gmap, gfn_t p_gfn, gfn_t c_gfn, unsigned long count) @@ -896,8 +893,9 @@ static void gmap_ucas_unmap_one(struct gmap *gmap, gfn_t c_gfn) union pte *ptep; int rc; - rc = dat_entry_walk(NULL, c_gfn, gmap->asce, 0, TABLE_TYPE_SEGMENT, &crstep, &ptep); - if (rc) + rc = dat_entry_walk(NULL, c_gfn, gmap->asce, DAT_WALK_IGN_HOLES, + TABLE_TYPE_SEGMENT, &crstep, &ptep); + if (rc || !is_pmd(*crstep)) return; while (!dat_crstep_xchg_atomic(crstep, READ_ONCE(*crstep), _PMD_EMPTY, c_gfn, gmap->asce)) ; From e20789439160f34315be89b50cff4a9bab958678 Mon Sep 17 00:00:00 2001 From: Claudio Imbrenda Date: Thu, 5 Nov 2026 16:37:02 +0100 Subject: [PATCH 0492/2102] KVM: s390: Move some skey functions to headers Move some storage key handling functions to headers, since they will be needed from outside, and they are small, so inlining is acceptable. Signed-off-by: Claudio Imbrenda Cc: stable@vger.kernel.org # 7.0+: prerequisite for the next patch Reviewed-by: Janosch Frank Reviewed-by: Christian Borntraeger Signed-off-by: Christian Borntraeger --- arch/s390/kvm/gmap/dat.c | 26 -------------------------- arch/s390/kvm/gmap/dat.h | 26 ++++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/arch/s390/kvm/gmap/dat.c b/arch/s390/kvm/gmap/dat.c index a2031aece4ed1e..7a25e41a142392 100644 --- a/arch/s390/kvm/gmap/dat.c +++ b/arch/s390/kvm/gmap/dat.c @@ -159,32 +159,6 @@ bool __must_check dat_crstep_xchg_atomic(union crste *crstep, union crste old, u return cspg_crste(crstep, old, new); } -static void dat_set_storage_key_from_pgste(union pte pte, union pgste pgste) -{ - union skey nkey = { .acc = pgste.acc, .fp = pgste.fp }; - - page_set_storage_key(pte_origin(pte), nkey.skey, 0); -} - -static void dat_move_storage_key(union pte old, union pte new) -{ - page_set_storage_key(pte_origin(new), page_get_storage_key(pte_origin(old)), 1); -} - -static union pgste dat_save_storage_key_into_pgste(union pte pte, union pgste pgste) -{ - union skey skey; - - skey.skey = page_get_storage_key(pte_origin(pte)); - - pgste.acc = skey.acc; - pgste.fp = skey.fp; - pgste.gr |= skey.r; - pgste.gc |= skey.c; - - return pgste; -} - union pgste __dat_ptep_xchg(union pte *ptep, union pgste pgste, union pte new, gfn_t gfn, union asce asce, bool uses_skeys) { diff --git a/arch/s390/kvm/gmap/dat.h b/arch/s390/kvm/gmap/dat.h index e6215c0b571f92..9cdd1f122d7ae7 100644 --- a/arch/s390/kvm/gmap/dat.h +++ b/arch/s390/kvm/gmap/dat.h @@ -1008,4 +1008,30 @@ static inline bool crste_is_ucas(union crste crste) crste.h.fc0.tl == _UCAS_ENTRY_LENGTH && crste.h.fc0.tf == _UCAS_ENTRY_OFFSET; } +static inline void dat_set_storage_key_from_pgste(union pte pte, union pgste pgste) +{ + union skey nkey = { .acc = pgste.acc, .fp = pgste.fp }; + + page_set_storage_key(pte_origin(pte), nkey.skey, 0); +} + +static inline void dat_move_storage_key(union pte old, union pte new) +{ + page_set_storage_key(pte_origin(new), page_get_storage_key(pte_origin(old)), 1); +} + +static inline union pgste dat_save_storage_key_into_pgste(union pte pte, union pgste pgste) +{ + union skey skey; + + skey.skey = page_get_storage_key(pte_origin(pte)); + + pgste.acc = skey.acc; + pgste.fp = skey.fp; + pgste.gr |= skey.r; + pgste.gc |= skey.c; + + return pgste; +} + #endif /* ARCH_KVM_GMAP_DAT_H */ From 15f78685814616874615a7597f9693d6a6478c22 Mon Sep 17 00:00:00 2001 From: Claudio Imbrenda Date: Thu, 5 Nov 2026 16:37:03 +0100 Subject: [PATCH 0493/2102] KVM: s390: Fix idte_crste() clobber and table type Fix idte_crste() to add the missing table-type bits and the missing "memory" clobber. Fixes: 5a74e3d93417 ("KVM: s390: KVM-specific bitfields and helper functions") Signed-off-by: Claudio Imbrenda Cc: stable@vger.kernel.org # 7.0+ Reviewed-by: Janosch Frank Reviewed-by: Christian Borntraeger Signed-off-by: Christian Borntraeger --- arch/s390/kvm/gmap/dat.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/arch/s390/kvm/gmap/dat.h b/arch/s390/kvm/gmap/dat.h index 9cdd1f122d7ae7..79efc56710b782 100644 --- a/arch/s390/kvm/gmap/dat.h +++ b/arch/s390/kvm/gmap/dat.h @@ -646,20 +646,22 @@ static __always_inline void idte_crste(union crste *crstep, gfn_t gfn, unsigned unsigned long table_origin = __pa(crste_table_start(crstep)); unsigned long gaddr = gfn_to_gpa(gfn) & HPAGE_MASK; + table_origin |= crstep->val & _REGION_ENTRY_TYPE_MASK; + if (__builtin_constant_p(opt) && opt == 0) { /* flush without guest asce */ asm volatile("idte %[table_origin],0,%[gaddr],%[local]" : "+m" (*crstep) : [table_origin] "a" (table_origin), [gaddr] "a" (gaddr), [local] "i" (local) - : "cc"); + : "cc", "memory"); } else { /* flush with guest asce */ asm volatile("idte %[table_origin],%[asce],%[gaddr_opt],%[local]" : "+m" (*crstep) : [table_origin] "a" (table_origin), [gaddr_opt] "a" (gaddr | opt), [asce] "a" (asce.val), [local] "i" (local) - : "cc"); + : "cc", "memory"); } } From d71e7918b459d7766626121ea7af5d74cdac249d Mon Sep 17 00:00:00 2001 From: Claudio Imbrenda Date: Thu, 5 Nov 2026 16:37:04 +0100 Subject: [PATCH 0494/2102] KVM: s390: Improve unmapping of large ranges When unmapping guest ranges, each individual leaf DAT entry is invalidated. When unmapping large ranges, this results in a very large amount of invalidations, which is time consuming. Moreover, since the unmap callback is called by KVM while holding a spinlock, this also leads to stall warnings. Improve the situation by invalidating DAT entries higher in the tree, instead of each leaf individually. For small invalidations (up to 1 segment = 1M of guest memory), and special cases (like protected VMs) regardless of the size, the old and slow invalidation is performed; all leaf entries are invalidated one by one. For large invalidations (larger than 1M of guest memory), the new strategy is used: - Invalidate prefixes on the whole range, extending start and end to 1M granularity - Iterate through the page table pointed to by each pmd and unshadow entries as needed - Detach (invalidate) the pmd - Save storage keys as needed - Invalidate each (now detached) pte by simply overwriting it - Reattach the old pmd to point to the updated page table Fixes: a2c17f9270cc ("KVM: s390: New gmap code") Signed-off-by: Claudio Imbrenda Cc: stable@vger.kernel.org # 7.0+ Acked-by: Janosch Frank Reviewed-by: Christian Borntraeger Signed-off-by: Christian Borntraeger --- arch/s390/kvm/gmap/gmap.c | 136 +++++++++++++++++++++++++++++++++++--- 1 file changed, 125 insertions(+), 11 deletions(-) diff --git a/arch/s390/kvm/gmap/gmap.c b/arch/s390/kvm/gmap/gmap.c index 225fdae3d57ca7..b9d92bef5459db 100644 --- a/arch/s390/kvm/gmap/gmap.c +++ b/arch/s390/kvm/gmap/gmap.c @@ -434,17 +434,8 @@ static long _gmap_unmap_crste(union crste *crstep, gfn_t gfn, gfn_t next, struct return 0; } -/** - * gmap_unmap_gfn_range() - Unmap a range of guest addresses. - * @gmap: The gmap to act on. - * @slot: The memslot in which the range is located. - * @start: The first gfn to unmap. - * @end: The gfn after the last one to unmap. - * - * Context: Called with the kvm mmu write lock held. - * Return: false - */ -bool gmap_unmap_gfn_range(struct gmap *gmap, struct kvm_memory_slot *slot, gfn_t start, gfn_t end) +static bool gmap_unmap_gfn_range_slow(struct gmap *gmap, struct kvm_memory_slot *slot, + gfn_t start, gfn_t end) { const struct dat_walk_ops ops = { .pte_entry = _gmap_unmap_pte, @@ -462,6 +453,129 @@ bool gmap_unmap_gfn_range(struct gmap *gmap, struct kvm_memory_slot *slot, gfn_t return false; } +static long _gmap_unmap_pud_fast(union crste *crstep, gfn_t gfn, gfn_t next, struct dat_walk *w) +{ + union crste old = *crstep; + + /* We only care about large puds */ + if (!old.h.fc) + return 0; + /* + * The caller did not unmap prefixes outside the original range, which + * does not necessarily cover the whole pud. + * Since all prefixes are below 2G, the first pud covers them all; + * make sure all prefixes are unmapped whenever the first pud is being + * unmapped. + */ + if (!gfn) + gmap_unmap_prefix(w->priv, 0, next); + if (old.s.fc1.vsie_notif) + gmap_handle_vsie_unshadow_event(w->priv, gfn); + + if (machine_has_tlb_guest()) + idte_crste(crstep, gfn, IDTE_GUEST_ASCE, w->asce, 0); + else + idte_crste(crstep, gfn, 0, w->asce, 0); + *crstep = _CRSTE_EMPTY(old.h.tt); + + return 0; +} + +static long _gmap_unmap_pmd_fast(union crste *crstep, gfn_t gfn, gfn_t next, struct dat_walk *w) +{ + union crste old = *crstep; + struct page_table *pt; + gfn_t first, last; + unsigned int i; + + if (old.h.fc) { + if (old.s.fc1.vsie_notif) + gmap_handle_vsie_unshadow_event(w->priv, gfn); + + if (machine_has_tlb_guest()) + idte_crste(crstep, gfn, IDTE_GUEST_ASCE, w->asce, 0); + else + idte_crste(crstep, gfn, 0, w->asce, 0); + WRITE_ONCE(*crstep, _CRSTE_EMPTY(old.h.tt)); + + return 0; + } + + if (old.h.i) + return 0; + + pt = dereference_pmd(old.pmd); + first = max(gfn, w->start) & (PTRS_PER_PTE - 1); + last = (min(next, w->end) - 1) & (PTRS_PER_PTE - 1); + + for (i = first; i <= last; i++) + if (pte_needs_unshadow(pt->ptes[i], _PTE_EMPTY, pt->pgstes[i])) + gmap_handle_vsie_unshadow_event(w->priv, gfn + i); + + /* Detach the page table */ + if (machine_has_tlb_guest()) + idte_crste(crstep, gfn, IDTE_GUEST_ASCE, w->asce, 0); + else + idte_crste(crstep, gfn, 0, w->asce, 0); + + for (i = first; i <= last; i++) { + if (pte_hole(pt->ptes[i])) + continue; + if (!pt->ptes[i].h.i && uses_skeys(w->priv)) + pt->pgstes[i] = dat_save_storage_key_into_pgste(pt->ptes[i], pt->pgstes[i]); + pt->ptes[i] = _PTE_EMPTY; + pt->pgstes[i].vsie_notif = 0; + pt->pgstes[i].vsie_gmem = 0; + pt->pgstes[i].zero = 0; + pt->pgstes[i].prefix_notif = 0; + } + + barrier(); + /* Reattach the modified page table */ + WRITE_ONCE(*crstep, old); + + return 0; +} + +static bool gmap_unmap_gfn_range_fast(struct gmap *gmap, gfn_t start, gfn_t end) +{ + const struct dat_walk_ops ops = { + .pud_entry = _gmap_unmap_pud_fast, + .pmd_entry = _gmap_unmap_pmd_fast, + }; + gfn_t aligned_start = ALIGN_DOWN(start, _PAGE_ENTRIES); + gfn_t aligned_end = ALIGN(end, _PAGE_ENTRIES); + bool failed; + + lockdep_assert_held_write(&gmap->kvm->mmu_lock); + + /* Prefixes are below 2G; if the start is above 2G, nothing to do */ + if (aligned_start < _PAGES_PER_REGION3) + gmap_unmap_prefix(gmap, aligned_start, aligned_end); + + failed = _dat_walk_gfn_range(start, end, gmap->asce, &ops, DAT_WALK_IGN_HOLES, gmap); + KVM_BUG_ON(failed, gmap->kvm); + return false; +} + +/** + * gmap_unmap_gfn_range() - Unmap a range of guest addresses. + * @gmap: The gmap to act on. + * @slot: The memslot in which the range is located. + * @start: The first gfn to unmap. + * @end: The gfn after the last one to unmap. + * + * Context: Called with the kvm mmu write lock held. + * Return: false + */ +bool gmap_unmap_gfn_range(struct gmap *gmap, struct kvm_memory_slot *slot, gfn_t start, gfn_t end) +{ + if ((end - start <= _PAGES_PER_SEGMENT) || + test_bit(GMAP_FLAG_EXPORT_ON_UNMAP, &gmap->flags) || is_ucontrol(gmap)) + return gmap_unmap_gfn_range_slow(gmap, slot, start, end); + return gmap_unmap_gfn_range_fast(gmap, start, end); +} + static union pgste __pte_test_and_clear_softdirty(union pte *ptep, union pgste pgste, gfn_t gfn, struct gmap *gmap) { From 6761f65e6823876534a9c3eec4cee1674dce415d Mon Sep 17 00:00:00 2001 From: Claudio Imbrenda Date: Thu, 5 Nov 2026 16:37:05 +0100 Subject: [PATCH 0495/2102] KVM: s390: vsie: Fix pinning using the wrong flag When pinning guest memory using pin_blocks(), gfn_to_page() was used, which under the hood uses FOLL_GET, which is the wrong type of flag for memory that is accessed directly by hardware. Fix by using kvm_vcpu_{,un}map(), which uses FOLL_PIN and is the correct thing to do. While technically a bugfix, the previous behaviour can only lead to guest corruption in extremely convoluted test scenarios that cannot happen in real/production systems. Fixes: e38c884df921 ("KVM: s390: Switch to new gmap") Signed-off-by: Claudio Imbrenda Cc: stable@vger.kernel.org #7.0+ Reviewed-by: Christian Borntraeger Signed-off-by: Christian Borntraeger --- arch/s390/kvm/s390/vsie.c | 133 ++++++++++++++------------------------ 1 file changed, 47 insertions(+), 86 deletions(-) diff --git a/arch/s390/kvm/s390/vsie.c b/arch/s390/kvm/s390/vsie.c index 5926689fa2267b..3ce133f20fa2cd 100644 --- a/arch/s390/kvm/s390/vsie.c +++ b/arch/s390/kvm/s390/vsie.c @@ -49,20 +49,21 @@ struct vsie_page { /* address of the last reported fault to guest2 */ unsigned long fault_addr; /* 0x0228 */ /* calculated guest addresses of satellite control blocks */ - gpa_t sca_gpa; /* 0x0230 */ - gpa_t itdba_gpa; /* 0x0238 */ - gpa_t gvrd_gpa; /* 0x0240 */ - gpa_t riccbd_gpa; /* 0x0248 */ - gpa_t sdnx_gpa; /* 0x0250 */ + struct kvm_host_map sca_map; /* 0x0230 */ + struct kvm_host_map itdba_map; /* 0x0260 */ + struct kvm_host_map gvrd_map; /* 0x0290 */ + struct kvm_host_map riccbd_map; /* 0x02c0 */ + struct kvm_host_map sdnx_map; /* 0x02f0 */ + struct kvm_host_map scb_map; /* 0x0320 */ /* * guest address of the original SCB. Remains set for free vsie * pages, so we can properly look them up in our addr_to_page * radix tree. */ - gpa_t scb_gpa; /* 0x0258 */ + gpa_t scb_gpa; /* 0x0350 */ /* the shadow gmap in use by the vsie_page */ - struct gmap_cache gmap_cache; /* 0x0260 */ - __u8 reserved[0x06f8 - 0x0278]; /* 0x0278 */ + struct gmap_cache gmap_cache; /* 0x0358 */ + __u8 reserved[0x06f8 - 0x0370]; /* 0x0370 */ struct kvm_s390_crypto_cb crycb; /* 0x06f8 */ __u8 fac[8 + S390_ARCH_FAC_LIST_SIZE_BYTE];/* 0x07f8 */ }; @@ -681,72 +682,43 @@ static int map_prefix(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page, struct } /* - * Pin the guest page given by gpa and set hpa to the pinned host address. + * pin_guest_page() - Pin the given guest page and return its hpa. + * @vcpu: the vCPU + * @gpa: the gpa to pin + * @map: the map representing this pinning. + * * Will always be pinned writable. * - * Returns: - 0 on success - * - -EINVAL if the gpa is not valid guest storage + * Returns: - 0 if the gpa is not valid guest storage, + * - The host hpa of the pinned page in case of success */ -static int pin_guest_page(struct kvm *kvm, gpa_t gpa, hpa_t *hpa) -{ - struct page *page; - - page = gfn_to_page(kvm, gpa_to_gfn(gpa)); - if (!page) - return -EINVAL; - *hpa = (hpa_t)page_to_phys(page) + (gpa & ~PAGE_MASK); - return 0; -} - -/* Unpins a page previously pinned via pin_guest_page, marking it as dirty. */ -static void unpin_guest_page(struct kvm *kvm, gpa_t gpa, hpa_t hpa) +static hpa_t pin_guest_page(struct kvm_vcpu *vcpu, gpa_t gpa, struct kvm_host_map *map) { - kvm_release_page_dirty(pfn_to_page(phys_to_pfn(hpa))); - /* mark the page always as dirty for migration */ - mark_page_dirty(kvm, gpa_to_gfn(gpa)); + if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), map)) + return 0; + return (hpa_t)PFN_PHYS(map->pfn) + (gpa & ~PAGE_MASK); } /* unpin all blocks previously pinned by pin_blocks(), marking them dirty */ static void unpin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) { struct kvm_s390_sie_block *scb_s = &vsie_page->scb_s; - hpa_t hpa; - hpa = (u64) scb_s->scaoh << 32 | scb_s->scaol; - if (hpa) { - unpin_guest_page(vcpu->kvm, vsie_page->sca_gpa, hpa); - vsie_page->sca_gpa = 0; - scb_s->scaol = 0; - scb_s->scaoh = 0; - } + kvm_vcpu_unmap(vcpu, &vsie_page->sca_map); + scb_s->scaol = 0; + scb_s->scaoh = 0; - hpa = scb_s->itdba; - if (hpa) { - unpin_guest_page(vcpu->kvm, vsie_page->itdba_gpa, hpa); - vsie_page->itdba_gpa = 0; - scb_s->itdba = 0; - } + kvm_vcpu_unmap(vcpu, &vsie_page->itdba_map); + scb_s->itdba = 0; - hpa = scb_s->gvrd; - if (hpa) { - unpin_guest_page(vcpu->kvm, vsie_page->gvrd_gpa, hpa); - vsie_page->gvrd_gpa = 0; - scb_s->gvrd = 0; - } + kvm_vcpu_unmap(vcpu, &vsie_page->gvrd_map); + scb_s->gvrd = 0; - hpa = scb_s->riccbd; - if (hpa) { - unpin_guest_page(vcpu->kvm, vsie_page->riccbd_gpa, hpa); - vsie_page->riccbd_gpa = 0; - scb_s->riccbd = 0; - } + kvm_vcpu_unmap(vcpu, &vsie_page->riccbd_map); + scb_s->riccbd = 0; - hpa = scb_s->sdnxo; - if (hpa) { - unpin_guest_page(vcpu->kvm, vsie_page->sdnx_gpa, hpa); - vsie_page->sdnx_gpa = 0; - scb_s->sdnxo = 0; - } + kvm_vcpu_unmap(vcpu, &vsie_page->sdnx_map); + scb_s->sdnxo = 0; } /* @@ -783,13 +755,12 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) ((gpa + offsetof(struct bsca_block, cpu[0]) - 1) & PAGE_MASK)) rc = set_validity_icpt(scb_s, 0x003bU); if (!rc) { - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) + hpa = pin_guest_page(vcpu, gpa, &vsie_page->sca_map); + if (!hpa) rc = set_validity_icpt(scb_s, 0x0034U); } if (rc) goto unpin; - vsie_page->sca_gpa = gpa; scb_s->scaoh = (u32)((u64)hpa >> 32); scb_s->scaol = (u32)(u64)hpa; } @@ -801,12 +772,11 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) goto unpin; } /* 256 bytes cannot cross page boundaries */ - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) { + hpa = pin_guest_page(vcpu, gpa, &vsie_page->itdba_map); + if (!hpa) { rc = set_validity_icpt(scb_s, 0x0080U); goto unpin; } - vsie_page->itdba_gpa = gpa; scb_s->itdba = hpa; } @@ -820,12 +790,11 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) * 512 bytes vector registers cannot cross page boundaries * if this block gets bigger, we have to shadow it. */ - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) { + hpa = pin_guest_page(vcpu, gpa, &vsie_page->gvrd_map); + if (!hpa) { rc = set_validity_icpt(scb_s, 0x1310U); goto unpin; } - vsie_page->gvrd_gpa = gpa; scb_s->gvrd = hpa; } @@ -836,13 +805,12 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) goto unpin; } /* 64 bytes cannot cross page boundaries */ - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) { + hpa = pin_guest_page(vcpu, gpa, &vsie_page->riccbd_map); + if (!hpa) { rc = set_validity_icpt(scb_s, 0x0043U); goto unpin; } /* Validity 0x0044 will be checked by SIE */ - vsie_page->riccbd_gpa = gpa; scb_s->riccbd = hpa; } if (((scb_s->ecb & ECB_GS) && !(scb_s->ecd & ECD_HOSTREGMGMT)) || @@ -866,12 +834,11 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) /* Due to alignment rules (checked above) this cannot * cross page boundaries */ - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) { + hpa = pin_guest_page(vcpu, gpa, &vsie_page->sdnx_map); + if (!hpa) { rc = set_validity_icpt(scb_s, 0x10b0U); goto unpin; } - vsie_page->sdnx_gpa = gpa; scb_s->sdnxo = hpa | sdnxc; } return 0; @@ -881,13 +848,9 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) } /* unpin the scb provided by guest 2, marking it as dirty */ -static void unpin_scb(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page, - gpa_t gpa) +static void unpin_scb(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) { - hpa_t hpa = virt_to_phys(vsie_page->scb_o); - - if (hpa) - unpin_guest_page(vcpu->kvm, gpa, hpa); + kvm_vcpu_unmap(vcpu, &vsie_page->scb_map); vsie_page->scb_o = NULL; } @@ -901,12 +864,10 @@ static int pin_scb(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page, gpa_t gpa) { hpa_t hpa; - int rc; - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) { - rc = kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING); - WARN_ON_ONCE(rc); + hpa = pin_guest_page(vcpu, gpa, &vsie_page->scb_map); + if (!hpa) { + WARN_ON_ONCE(kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING)); return 1; } vsie_page->scb_o = phys_to_virt(hpa); @@ -1601,7 +1562,7 @@ int kvm_s390_handle_vsie(struct kvm_vcpu *vcpu) out_unshadow: unshadow_scb(vcpu, vsie_page); out_unpin_scb: - unpin_scb(vcpu, vsie_page, scb_addr); + unpin_scb(vcpu, vsie_page); out_put: put_vsie_page(vsie_page); From acba37c2e2df26ad722d470777044fd21620834e Mon Sep 17 00:00:00 2001 From: Frank Li Date: Fri, 6 Nov 2026 11:18:08 -0500 Subject: [PATCH 0496/2102] Revert "arm64: dts: imx8qm-ss-conn: add usbotg3 iommu information" This reverts commit 73c3b40e536d9cb624db90b460bc384147576a57. There is a hack in U-Boot, which calls sc_rm_set_master_sid() to set the SID for bus masters that depend on power domain information of the node. But cdns_usb is a child node of the glue driver, which does not need power domain information. More time is needed to find a good method to program sc_rm_set_master_sid() in the kernel and reduce U-Boot dependence. So revert this patch first to get USB host working again. Reported-by: Emanuele Ghidoli Link: https://lore.kernel.org/imx/b911ff91-ce7b-462e-a7fb-f8c6d682c85b@gmail.com/ Cc: Peng Fan Fixes: 73c3b40e536d ("arm64: dts: imx8qm-ss-conn: add usbotg3 iommu information") Signed-off-by: Frank Li --- arch/arm64/boot/dts/freescale/imx8qm-ss-conn.dtsi | 4 ---- 1 file changed, 4 deletions(-) diff --git a/arch/arm64/boot/dts/freescale/imx8qm-ss-conn.dtsi b/arch/arm64/boot/dts/freescale/imx8qm-ss-conn.dtsi index f25f62d51f69ee..1d1cde2bd879df 100644 --- a/arch/arm64/boot/dts/freescale/imx8qm-ss-conn.dtsi +++ b/arch/arm64/boot/dts/freescale/imx8qm-ss-conn.dtsi @@ -67,7 +67,3 @@ compatible = "fsl,imx8qm-usdhc", "fsl,imx8qxp-usdhc", "fsl,imx7d-usdhc"; iommus = <&smmu 0x11 0x7f80>; }; - -&usbotg3_cdns3 { - iommus = <&smmu 0x4 0x7f80>; -}; From f3183d7ad10120437bcc3f4a751cd256ba69793f Mon Sep 17 00:00:00 2001 From: Weihong Guan Date: Thu, 12 Nov 2026 03:34:28 +0000 Subject: [PATCH 0497/2102] Bluetooth: hci_sync: Drop the command's sk reference hci_cmd_sync_alloc() takes a reference on the sk a command is sent for (sock_hold()), and hci_cmd_sync_complete() means to drop it, but looks for the sk in the response skb, which never carries one. The reference is never dropped: every command sent with an sk leaks it, and with it the sk and a reference on the bluetooth module. The commands sent with an sk are LE Remove Advertising Set and LE Clear Advertising Sets, for MGMT's Remove Advertising and the instance removals, and Read Local OOB (Extended) Data. After each, the module's refcnt stays one higher with no socket left open, and the module can't be unloaded until a reboot. Drop the reference from the request command, hdev->req_skb, before freeing it. Fixes: cba6b758711c ("Bluetooth: hci_sync: Make use of hci_cmd_sync_queue set 2") Assisted-by: Claude:claude-opus-5.5 Signed-off-by: Weihong Guan Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_sync.c | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index d4a4f49df5ace8..e771f0f2f30863 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -31,21 +31,23 @@ static void hci_cmd_sync_complete(struct hci_dev *hdev, u8 result, u16 opcode, hdev->req_result = result; WRITE_ONCE(hdev->req_status, HCI_REQ_DONE); - /* Free the request command so it is not used as response */ + /* Free the request command so it is not used as response, and drop + * the reference hci_cmd_sync_alloc() took on its sk, if set: the + * response skb doesn't carry it. + */ hci_dev_lock(hdev); - kfree_skb(hdev->req_skb); - hdev->req_skb = NULL; - hci_dev_unlock(hdev); - - if (skb) { - struct sock *sk = hci_skb_sk(skb); + if (hdev->req_skb) { + struct sock *sk = hci_skb_sk(hdev->req_skb); - /* Drop sk reference if set */ if (sk) sock_put(sk); + } + kfree_skb(hdev->req_skb); + hdev->req_skb = NULL; + hci_dev_unlock(hdev); + if (skb) hdev->req_rsp = skb_get(skb); - } wake_up_interruptible(&hdev->req_wait_q); } From 3b069de8a5d688c7e8381b99d6cdb7467fcae0de Mon Sep 17 00:00:00 2001 From: Amir Abudubai Date: Wed, 11 Nov 2026 15:49:05 -0600 Subject: [PATCH 0498/2102] Bluetooth: L2CAP: Fix size check for receive buffer space Check that available receive space covers a full MTU-sized SDU and its overhead, rather than just the overhead. Otherwise, credits can be exhausted before an SDU is completed. This could result in a deadlock under some configurations and SDU combinations. This follows the SDU-sized credit policy from commit 96cd8eaa131f ("Bluetooth: L2CAP: Derive rx credits from MTU and MPS"). Clarify the comment by replacing "packet" with "SDU". Fixes: ce60b9231b66 ("Bluetooth: compute LE flow credits based on recvbuf space") Signed-off-by: Amir Abudubai Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/l2cap_sock.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/net/bluetooth/l2cap_sock.c b/net/bluetooth/l2cap_sock.c index e5c15c083c1acc..304ebafdfeaa01 100644 --- a/net/bluetooth/l2cap_sock.c +++ b/net/bluetooth/l2cap_sock.c @@ -1229,11 +1229,11 @@ static void l2cap_publish_rx_avail(struct l2cap_chan *chan) /* Correct available memory by estimated sk_buff overhead. * This is significant due to small transfer sizes. However, accept - * at least one full packet if receive space is non-zero. + * at least one full SDU if receive space is non-zero. */ expected_skbs = DIV_ROUND_UP(avail, chan->mps); skb_overhead = expected_skbs * sizeof(struct sk_buff); - if (skb_overhead < avail) + if (avail - skb_overhead >= chan->imtu + L2CAP_SDULEN_SIZE) l2cap_chan_rx_avail(chan, avail - skb_overhead); else l2cap_chan_rx_avail(chan, -1); From f6562cd116a013a5a9b549e51d79ba658f9f8981 Mon Sep 17 00:00:00 2001 From: Bo Cao Date: Thu, 12 Nov 2026 15:09:53 +0800 Subject: [PATCH 0499/2102] bpf, sockmap: Fix ring capacity invariant break in bpf_msg_push_data() A push at msg->size on a full ring reads the length of the free slot. It is 0, so nothing is copied and sg.end moves onto sg.start. The ring looks empty and the next push overwrites live elements. The prog needs CAP_BPF and CAP_NET_ADMIN. Fixes: 15ab0548e310 ("bpf, sockmap: Several fixes to bpf_msg_push_data") Signed-off-by: Bo Cao Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/tencent_F9A4094B6B79A77230BD540754D65D17BD0A@qq.com --- net/core/filter.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/net/core/filter.c b/net/core/filter.c index d68b5215040506..1a60a2a70e2d81 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -2883,6 +2883,10 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, if (start > offset + l) return -EINVAL; + /* A push at the end of the msg works on the last element */ + if (i == msg->sg.end && start != offset) + sk_msg_iter_var_prev(i); + space = MAX_MSG_FRAGS - sk_msg_elem_used(msg); /* If no space available will fallback to copy, we need at @@ -2892,7 +2896,7 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, * offset case because its the common case for inserting a * header. */ - if (!space || (space == 1 && start != offset)) + if (!space || (space == 1 && start != offset && start < offset + l)) copy = msg->sg.data[i].length; if (unlikely(copy + len < copy)) @@ -2908,8 +2912,6 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, raw = page_address(page); - if (i == msg->sg.end) - sk_msg_iter_var_prev(i); psge = sk_msg_elem(msg, i); front = start - offset; back = psge->length - front; @@ -2931,8 +2933,6 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, } if (start - offset) { - if (i == msg->sg.end) - sk_msg_iter_var_prev(i); psge = sk_msg_elem(msg, i); rsge = sk_msg_elem_cpy(msg, i); rsge_copy = sk_msg_elem_is_copy(msg, i); From e536074468a283c3adacbc23a8991d71a16c4f5c Mon Sep 17 00:00:00 2001 From: Adethya Srinivasan Date: Thu, 12 Nov 2026 15:54:06 +0000 Subject: [PATCH 0500/2102] bpf: Reject writable map iterators on read-only maps With CAP_BPF and CAP_PERFMON, an iterator program can write into a frozen BPF_F_RDONLY_PROG array. The verifier treats the contents of such an array as constants. Reject writable map iterators on maps with BPF_F_RDONLY_PROG set. Keep allowing read-only iterators. Fixes: d3cc2ab546ad ("bpf: Implement bpf iterator for array maps") Fixes: d6c4503cc296 ("bpf: Implement bpf iterator for hash maps") Signed-off-by: Adethya Srinivasan Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/LO2P302MB019721D7E507DFA1C707F102BC702@LO2P302MB0197.GBRP302.PROD.OUTLOOK.COM --- kernel/bpf/map_iter.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/kernel/bpf/map_iter.c b/kernel/bpf/map_iter.c index a58c148692e6c3..7a769e5f539724 100644 --- a/kernel/bpf/map_iter.c +++ b/kernel/bpf/map_iter.c @@ -99,8 +99,8 @@ static struct bpf_iter_reg bpf_map_reg_info = { /* * For an iterator that hands the live map value to the program as a writable - * buffer: the verifier knows nothing of the map, so the special fields of the - * value have to lie outside of what the program may write. + * buffer: the verifier knows nothing of the map, so read-only maps + * and special fields of the value have to be protected from writes. */ int bpf_iter_map_check_value_write(const struct bpf_prog *prog, const struct bpf_map *map) @@ -109,7 +109,13 @@ int bpf_iter_map_check_value_write(const struct bpf_prog *prog, const struct btf_field *field; u32 i; - if (IS_ERR_OR_NULL(rec) || !prog->aux->max_rdwr_write) + if (!prog->aux->max_rdwr_write) + return 0; + + if (map->map_flags & BPF_F_RDONLY_PROG) + return -EACCES; + + if (IS_ERR_OR_NULL(rec)) return 0; for (i = 0; i < rec->cnt; i++) { From e1224c9a9053d12a3375acaac1566e268835e99d Mon Sep 17 00:00:00 2001 From: Adethya Srinivasan Date: Thu, 12 Nov 2026 15:54:07 +0000 Subject: [PATCH 0501/2102] selftests/bpf: Check writable iterator attach to a read-only array Reuse dump_bpf_array_map(), which writes to ctx->value, and attempt to attach it to an array with BPF_F_RDONLY_PROG set. Assert that the attach returns -EACCES and destroy the link if it unexpectedly succeeds. The test fails on an unfixed kernel and passes with the fix applied. Signed-off-by: Adethya Srinivasan Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/LO2P302MB019736CF58FAA4C98C6F78AABC702@LO2P302MB0197.GBRP302.PROD.OUTLOOK.COM --- .../selftests/bpf/prog_tests/bpf_iter.c | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tools/testing/selftests/bpf/prog_tests/bpf_iter.c b/tools/testing/selftests/bpf/prog_tests/bpf_iter.c index c69080ca14f5a1..5249b07cd62afe 100644 --- a/tools/testing/selftests/bpf/prog_tests/bpf_iter.c +++ b/tools/testing/selftests/bpf/prog_tests/bpf_iter.c @@ -1100,6 +1100,39 @@ static void test_bpf_array_map(void) bpf_iter_bpf_array_map__destroy(skel); } +static void test_bpf_array_map_rdonly(void) +{ + DECLARE_LIBBPF_OPTS(bpf_iter_attach_opts, opts); + struct bpf_iter_bpf_array_map *skel; + union bpf_iter_link_info linfo = {}; + struct bpf_link *link; + int err; + + skel = bpf_iter_bpf_array_map__open(); + if (!ASSERT_OK_PTR(skel, "bpf_iter_bpf_array_map__open")) + return; + + err = bpf_map__set_map_flags(skel->maps.arraymap1, BPF_F_RDONLY_PROG); + if (!ASSERT_OK(err, "set_map_flags")) + goto out; + + err = bpf_iter_bpf_array_map__load(skel); + if (!ASSERT_OK(err, "bpf_iter_bpf_array_map__load")) + goto out; + + linfo.map.map_fd = bpf_map__fd(skel->maps.arraymap1); + opts.link_info = &linfo; + opts.link_info_len = sizeof(linfo); + link = bpf_program__attach_iter(skel->progs.dump_bpf_array_map, &opts); + err = libbpf_get_error(link); + ASSERT_EQ(err, -EACCES, "attach_rdonly_write_iter"); + if (!err) + bpf_link__destroy(link); + +out: + bpf_iter_bpf_array_map__destroy(skel); +} + static void test_bpf_array_map_iter_fd(void) { struct bpf_iter_bpf_array_map *skel; @@ -1770,6 +1803,8 @@ void test_bpf_iter(void) test_bpf_percpu_hash_map(); if (test__start_subtest("bpf_array_map")) test_bpf_array_map(); + if (test__start_subtest("bpf_array_map_rdonly")) + test_bpf_array_map_rdonly(); if (test__start_subtest("bpf_array_map_iter_fd")) test_bpf_array_map_iter_fd(); if (test__start_subtest("bpf_percpu_array_map")) From bd59a58663895778da607fd02a8f17a93db97d16 Mon Sep 17 00:00:00 2001 From: Emil Tsalapatis Date: Mon, 9 Nov 2026 18:16:10 +0000 Subject: [PATCH 0502/2102] bpf: Use dedicated workqueue for freeing BPF programs BPF program freeing currently runs from the system workqueue. With BPF program pack allocations, freeing the last program in a pack can take pack_mutex and call into execmem/vmalloc code to change page permissions. That path may queue a vmalloc purge helper to the same CPU and wait for it to finish. If enough other BPF program free workers are already active on that CPU, they can all block on pack_mutex and consume the system workqueue active slots. The worker holding pack_mutex then waits for the vmalloc purge work, but that purge work cannot run because the queue is full of pack_mutex waiters: [ 24.646667] INFO: task kworker/0:4:1291 blocked for more than 10 seconds. [ 24.646669] Not tainted 7.3.0-00001-gdeaa120a9b25-dirty #11 [ 24.646670] "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message. [ 24.646671] task:kworker/0:4 state:D stack:0 pid:1291 tgid:1291 ppid:2 task_flags:0x4208060 flags:0x00080000 [ 24.646675] Workqueue: events bpf_prog_free_deferred [ 24.646678] Call Trace: [ 24.646680] [ 24.646686] __schedule+0x5bc/0x1430 [ 24.646702] schedule+0x3f/0x100 [ 24.646706] schedule_timeout+0x106/0x110 [ 24.646711] ? srso_alias_return_thunk+0x5/0xfbef5 [ 24.646713] ? mark_held_locks+0x49/0x80 [ 24.646720] ? srso_alias_return_thunk+0x5/0xfbef5 [ 24.646723] ? lockdep_hardirqs_on_prepare+0xdc/0x190 [ 24.646726] ? srso_alias_return_thunk+0x5/0xfbef5 [ 24.646732] __wait_for_common+0xc1/0x1d0 [ 24.646735] ? __pfx_schedule_timeout+0x10/0x10 [ 24.646748] ? __flush_work+0x1f8/0x550 [ 24.646751] __flush_work+0x309/0x550 [ 24.646759] ? __pfx_wq_barrier_func+0x10/0x10 [ 24.646783] __purge_vmap_area_lazy+0x3e4/0x440 [ 24.646796] _vm_unmap_aliases+0x2d5/0x330 [ 24.646810] change_page_attr_set_clr+0xb9/0x580 [ 24.646817] ? srso_alias_return_thunk+0x5/0xfbef5 [ 24.646833] set_memory_nx+0x3b/0x50 [ 24.646838] __execmem_cache_free+0x35/0xb0 [ 24.646848] execmem_free+0x98/0x160 [ 24.646864] bpf_prog_pack_free+0x152/0x190 [ 24.646871] bpf_jit_binary_pack_free+0x17/0x90 [ 24.646876] bpf_jit_free+0x5e/0x130 [ 24.646882] process_one_work+0x289/0x790 [ 24.646886] ? srso_alias_return_thunk+0x5/0xfbef5 [ 24.646888] ? srso_alias_return_thunk+0x5/0xfbef5 [ 24.646902] worker_thread+0x1b3/0x370 [ 24.646908] ? __pfx_worker_thread+0x10/0x10 [ 24.646911] kthread+0xf7/0x130 [ 24.646914] ? __pfx_kthread+0x10/0x10 [ 24.646920] ret_from_fork+0x293/0x300 [ 24.646923] ? __pfx_kthread+0x10/0x10 [ 24.646927] ret_from_fork_asm+0x1a/0x30 [ 24.646947] Move deferred freeing of BPF programs, program images, and trampoline images to a dedicated workqueue to avoid this deadlock. Fixes: 72210662c5a2 ("mm: vmalloc: offload free_vmap_area_lock lock") Reported-by: Andrii Nakryiko Signed-off-by: Emil Tsalapatis Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261109181610.7027-1-emil@etsalapatis.com --- include/linux/bpf.h | 1 + kernel/bpf/core.c | 20 ++++++++++++++++++-- kernel/bpf/trampoline.c | 2 +- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/include/linux/bpf.h b/include/linux/bpf.h index fdbf638300fc51..1dd9db16f32403 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -70,6 +70,7 @@ extern spinlock_t btf_idr_lock; extern struct kobject *btf_kobj; extern struct bpf_mem_alloc bpf_global_ma, bpf_global_percpu_ma; extern bool bpf_global_ma_set; +extern struct workqueue_struct *bpf_prog_free_wq __ro_after_init; typedef u64 (*bpf_callback_t)(u64, u64, u64, u64, u64); typedef int (*bpf_iter_init_seq_priv_t)(void *private_data, diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index 831f73f8259931..fc8b133c15f900 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -3143,6 +3144,17 @@ static void bpf_free_used_btfs(struct bpf_prog_aux *aux) kfree(aux->used_btfs); } +struct workqueue_struct *bpf_prog_free_wq __ro_after_init; + +static int __init bpf_prog_free_wq_init(void) +{ + bpf_prog_free_wq = alloc_workqueue("bpf_prog_free", WQ_PERCPU, 1); + if (!bpf_prog_free_wq) + panic("Failed to allocate BPF program free workqueue\n"); + return 0; +} +early_initcall(bpf_prog_free_wq_init); + static void bpf_prog_free_images(struct work_struct *work) { struct bpf_prog_aux *aux; @@ -3198,7 +3210,7 @@ static void bpf_prog_free_deferred(struct work_struct *work) /* The symbols are looked up under rcu_read_lock() */ INIT_RCU_WORK(&aux->rwork, bpf_prog_free_images); if (ksyms) - queue_rcu_work(system_percpu_wq, &aux->rwork); + queue_rcu_work(bpf_prog_free_wq, &aux->rwork); else bpf_prog_free_images(&aux->rwork.work); } @@ -3211,7 +3223,11 @@ void bpf_prog_free(struct bpf_prog *fp) bpf_prog_put(aux->dst_prog); bpf_token_put(aux->token); INIT_WORK(&aux->work, bpf_prog_free_deferred); - schedule_work(&aux->work); + /* + * Free BPF programs on a dedicated workqueue to avoid blocking or slowing + * down the system workqueue. + */ + queue_work(bpf_prog_free_wq, &aux->work); } /* RNG for unprivileged user space with separated state from prandom_u32(). */ diff --git a/kernel/bpf/trampoline.c b/kernel/bpf/trampoline.c index 21d460866dfef8..b0052c7565d84a 100644 --- a/kernel/bpf/trampoline.c +++ b/kernel/bpf/trampoline.c @@ -584,7 +584,7 @@ static void __bpf_tramp_image_put_rcu(struct rcu_head *rcu) im = container_of(rcu, struct bpf_tramp_image, rcu); INIT_WORK(&im->work, __bpf_tramp_image_put_deferred); - schedule_work(&im->work); + queue_work(bpf_prog_free_wq, &im->work); } /* callback, fexit step 2. Called after percpu_ref_kill confirms. */ From b7cc45994c3f9c5f24397fcc0251f6c23bff9bd8 Mon Sep 17 00:00:00 2001 From: Shihuang Liu Date: Mon, 9 Nov 2026 17:47:23 +0800 Subject: [PATCH 0503/2102] bpf: Check variable-offset accesses against special fields btf_struct_access() rejects direct access to special fields (kptr, ...) of program allocated objects, but for a variable offset it only checks the access at min_off. This is enough for compiler generated BTF where members don't overlap, but btf_struct_check_meta() allows overlapping members in hand-written BTF: struct node { int arr[4]; /* offset 0, size 16 */ struct foo __kptr *p; /* offset 8 */ }; A 4-byte store to arr[i] passes the check at offset 0 and overwrites p at run time for i == 2 or 3; bpf_obj_free_fields() then frees the corrupted pointer. Check the offsets the register can really take, min_off + k * step. No separate constant offset path is needed: reg->step is never 0 (___mark_reg_known() sets it to 1), so a constant offset is k == 0. Verified with hand-written BTF: a variable-offset store to arr[i] is now rejected with "direct access to kptr is disallowed", while a store to arr[i].data with step == sizeof(elem) still loads. Fixes: 89e72f81a455 ("bpf: Varying offset access support for PTR_TO_BTF_ID pointers") Signed-off-by: Shihuang Liu Signed-off-by: Alexei Starovoitov Link: https://lore.kernel.org/bpf/20261108152941.7363-1-shlomojune6@gmail.com/ Link: https://patch.msgid.link/20261109094723.14614-1-shlomojune6@gmail.com --- kernel/bpf/btf.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c index 8bf39098ba97a1..2265362d8342f1 100644 --- a/kernel/bpf/btf.c +++ b/kernel/bpf/btf.c @@ -8094,7 +8094,12 @@ int btf_struct_access(struct bpf_verifier_log *log, for (i = 0; i < rec->cnt; i++) { struct btf_field *field = &rec->fields[i]; u32 offset = field->offset; - if (off < offset + field->size && offset < off + size) { + /* An access at 'lo' or above ends after the start of the field. */ + s64 lo = max(min_off, (s64)offset - size + 1); + + /* Round up to min_off + k * step. The step is never 0. */ + lo += imod(min_off - lo, reg->step); + if (lo <= max_off && lo < offset + field->size) { bpf_log(log, "direct access to %s is disallowed\n", btf_field_type_name(field->type)); From a088b092a8962db62327690ae2d0d68827e81229 Mon Sep 17 00:00:00 2001 From: Aristeu Rozanski Date: Thu, 12 Nov 2026 10:11:20 -0800 Subject: [PATCH 0504/2102] EDAC/i5000: Fix slot number passed to determine_mtr() When the logic mapping branch/slot/channel was reworked back in 64e1fdaf55d6 ("i5000_edac: Fix the logic that retrieves memory information") i5000_init_csrows() was not updated and kept passing twice the number of slots to determine_mtr(), which leads to accessing past the end of i5000_pvt.b1_mtr[]. This was found by KASAN. Fixes: 64e1fdaf55d6 ("i5000_edac: Fix the logic that retrieves memory information") Signed-off-by: Aristeu Rozanski Signed-off-by: Andrew Luebke Signed-off-by: Borislav Petkov (AMD) Tested-by: Andrew Luebke Cc: stable@vger.kernel.org Link: https://lore.kernel.org/all/20220921181009.oxytvicy6sry6it7@redhat.com --- drivers/edac/i5000_edac.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/drivers/edac/i5000_edac.c b/drivers/edac/i5000_edac.c index c0faf55f78129f..342b69909600b4 100644 --- a/drivers/edac/i5000_edac.c +++ b/drivers/edac/i5000_edac.c @@ -1253,14 +1253,12 @@ static int i5000_init_csrows(struct mem_ctl_info *mci) struct i5000_pvt *pvt; struct dimm_info *dimm; int empty; - int max_csrows; int mtr; int csrow_megs; int channel; int slot; pvt = mci->pvt_info; - max_csrows = pvt->maxdimmperch * 2; empty = 1; /* Assume NO memory */ @@ -1271,7 +1269,7 @@ static int i5000_init_csrows(struct mem_ctl_info *mci) * to map the dimms. A good cleanup would be to remove this array, * and do a loop here with branch, channel, slot */ - for (slot = 0; slot < max_csrows; slot++) { + for (slot = 0; slot < pvt->maxdimmperch; slot++) { for (channel = 0; channel < pvt->maxch; channel++) { mtr = determine_mtr(pvt, slot, channel); From ad3bee5c582e95754ac483f00dbeed882b9eb5dc Mon Sep 17 00:00:00 2001 From: Keegan Freyhof Date: Tue, 10 Nov 2026 09:49:42 -0800 Subject: [PATCH 0505/2102] bnxt_en: Map HWRM_ERR_CODE_PF_UNAVAILABLE to -ECOMM The current use of -ENODEV for both PCI being disabled and FW's HWRM_ERR_CODE_PF_UNAVAILABLE errors makes it impossible for the caller to distinguish between the 2 errors. As a result, a disabled VF device will cause the driver to pointlessly retry setting L2 filters believing that the PF is down. Fix it by using -ECOMM instead for HWRM_ERR_CODE_PF_UNAVAILABLE which means that the FW is failing the command on the VF because the PF is down. This new -ECOMM error code which is more accurate will now propagate to userspace instead of -ENODEV on some VF failure paths when the PF is down. Fixes: 662c9b22f5b5 ("bnxt_en: improve VF error messages when PF is unavailable") Reviewed-by: Kalesh AP Signed-off-by: Keegan Freyhof Signed-off-by: Michael Chan Link: https://patch.msgid.link/20261110174943.2106347-2-michael.chan@broadcom.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/broadcom/bnxt/bnxt.c | 14 +++++++------- drivers/net/ethernet/broadcom/bnxt/bnxt_hwrm.c | 4 +++- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.c b/drivers/net/ethernet/broadcom/bnxt/bnxt.c index 6846a27bfef4c0..82b44e7362cc1a 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.c @@ -11318,7 +11318,7 @@ static int bnxt_init_chip(struct bnxt *bp, bool irq_re_init) /* Filter for default vnic 0 */ rc = bnxt_hwrm_set_vnic_filter(bp, 0, 0, bp->dev->dev_addr); if (rc) { - if (BNXT_VF(bp) && rc == -ENODEV) + if (rc == -ECOMM) netdev_err(bp->dev, "Cannot configure L2 filter while PF is unavailable\n"); else netdev_err(bp->dev, "HWRM vnic filter failure rc: %x\n", rc); @@ -12476,7 +12476,7 @@ int bnxt_update_link(struct bnxt *bp, bool chng_link_state) rc = hwrm_req_send(bp, req); if (rc) { hwrm_req_drop(bp, req); - if (BNXT_VF(bp) && rc == -ENODEV) { + if (rc == -ECOMM) { netdev_warn(bp->dev, "Cannot obtain link state while PF unavailable.\n"); rc = 0; } @@ -13953,7 +13953,7 @@ static int bnxt_cfg_rx_mode(struct bnxt *bp, struct netdev_hw_addr_list *uc, for (i = 1, off = 0; i < vnic->uc_filter_count; i++, off += ETH_ALEN) { rc = bnxt_hwrm_set_vnic_filter(bp, 0, i, vnic->uc_list + off); if (rc) { - if (BNXT_VF(bp) && rc == -ENODEV) { + if (rc == -ECOMM) { netdev_warn(bp->dev, "Cannot configure L2 filters while PF is unavailable, will retry\n"); rc = -EAGAIN; } else if (rc == -EAGAIN) { @@ -17003,7 +17003,7 @@ static int bnxt_set_dflt_rings(struct bnxt *bp, bool sh) } rc = __bnxt_reserve_rings(bp); - if (rc && rc != -ENODEV) + if (rc && rc != -ECOMM) netdev_warn(bp->dev, "Unable to reserve tx rings\n"); bnxt_adj_tx_rings(bp); @@ -17013,7 +17013,7 @@ static int bnxt_set_dflt_rings(struct bnxt *bp, bool sh) /* Rings may have been trimmed, re-reserve the trimmed rings. */ if (bnxt_need_reserve_rings(bp)) { rc = __bnxt_reserve_rings(bp); - if (rc && rc != -ENODEV) + if (rc && rc != -ECOMM) netdev_warn(bp->dev, "2nd rings reservation failed.\n"); bnxt_adj_tx_rings(bp); } @@ -17039,7 +17039,7 @@ static int bnxt_init_dflt_ring_mode(struct bnxt *bp) bnxt_clear_int_mode(bp); rc = bnxt_set_dflt_rings(bp, true); if (rc) { - if (BNXT_VF(bp) && rc == -ENODEV) + if (rc == -ECOMM) netdev_err(bp->dev, "Cannot configure VF rings while PF is unavailable.\n"); else netdev_err(bp->dev, "Not enough rings available.\n"); @@ -17417,7 +17417,7 @@ static int bnxt_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) bnxt_aux_devices_init(bp); rc = bnxt_set_dflt_rings(bp, true); if (rc) { - if (BNXT_VF(bp) && rc == -ENODEV) { + if (rc == -ECOMM) { netdev_err(bp->dev, "Cannot configure VF rings while PF is unavailable.\n"); } else { netdev_err(bp->dev, "Not enough rings available.\n"); diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt_hwrm.c b/drivers/net/ethernet/broadcom/bnxt/bnxt_hwrm.c index 5bfabdca7d0e2a..de02d1baa75142 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt_hwrm.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt_hwrm.c @@ -360,7 +360,7 @@ static int __hwrm_to_stderr(u32 hwrm_err) case HWRM_ERR_CODE_CMD_NOT_SUPPORTED: return -EOPNOTSUPP; case HWRM_ERR_CODE_PF_UNAVAILABLE: - return -ENODEV; + return -ECOMM; default: return -EIO; } @@ -716,6 +716,8 @@ static int __hwrm_send(struct bnxt *bp, struct bnxt_hwrm_ctx *ctx) * ENOMEM: HWRM has no buffers. * EAGAIN: HWRM busy or reset in progress. * EOPNOTSUPP: Invalid request type. + * ENODEV: PCI device is disabled. + * ECOMM: The parent PF is unavailable when issued on VFs. * EIO: Any other error. * Error handling is orthogonal to request ownership. An unowned request will * still be consumed on error. If the caller owns the request, then the caller From 5ab726ff726b76b12f0594657ca5f49ba74d3241 Mon Sep 17 00:00:00 2001 From: Keegan Freyhof Date: Tue, 10 Nov 2026 09:49:43 -0800 Subject: [PATCH 0506/2102] bnxt_en: Wait for the PF in bnxt_resume() When bnxt_resume() is called on a VF with the PF running in the same kernel, the initial FW message may timeout if the PF has not been initialized. Use the more appropriate bnxt_hwrm_poll() with the silent flag to suppress warning messages and loop up to 10 times if the error code warrants additional polling. This initial polling is done without the rtnl_lock() to allow the PF running in the same kernel (which will also require the rtnl_lock) to finish its initialization. This fixes a failure found in the lab when running system hibernate on a BCM57608 NIC with 64 VFs created. The FW version is 238.1.59.0. bnxt_en 0000:23:08.5 eno4v5: hwrm req_type 0x0 seq id 0xb0 error 0xa bnxt_en 0000:23:08.5: PM: dpm_run_callback(): pci_pm_restore returns -19 bnxt_en 0000:23:08.5: PM: failed to restore async: error -19 bnxt_en 0000:23:08.3 eno4v3: hwrm req_type 0x0 seq id 0xb0 error 0xa bnxt_en 0000:23:08.4 eno4v4: hwrm req_type 0x0 seq id 0xb0 error 0xa bnxt_en 0000:23:08.7 eno4v7: hwrm req_type 0x0 seq id 0xb0 error 0xa bnxt_en 0000:23:08.3: PM: dpm_run_callback(): pci_pm_restore returns -19 bnxt_en 0000:23:08.4: PM: dpm_run_callback(): pci_pm_restore returns -19 Tested on dual-port BCM57608 with 64 VFs on each port. The polling loop provides adequate margins. Fixes: f65a2044a8c9 ("bnxt_en: Add suspend/resume callbacks.") Reviewed-by: Pavan Chebbi Signed-off-by: Keegan Freyhof Signed-off-by: Michael Chan Link: https://patch.msgid.link/20261110174943.2106347-3-michael.chan@broadcom.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/broadcom/bnxt/bnxt.c | 37 ++++++++++++++++++++--- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.c b/drivers/net/ethernet/broadcom/bnxt/bnxt.c index 82b44e7362cc1a..e78cf7ad3cbc8d 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.c @@ -17573,21 +17573,50 @@ static int bnxt_suspend(struct device *device) return rc; } +#define BNXT_RESUME_MAX_RETRY 10 + static int bnxt_resume(struct device *device) { struct net_device *dev = dev_get_drvdata(device); struct bnxt *bp = netdev_priv(dev); - int rc = 0; + int i, rc; - rtnl_lock(); - netdev_lock(dev); rc = pci_enable_device(bp->pdev); if (rc) { netdev_err(dev, "Cannot re-enable PCI device during resume, err = %d\n", rc); - goto resume_exit; + return rc; } pci_set_master(bp->pdev); + if (BNXT_VF(bp)) { + for (i = 0; i < BNXT_RESUME_MAX_RETRY; i++) { + rc = bnxt_hwrm_poll(bp); + if (rc != -EAGAIN && rc != -EBUSY && rc != -ECOMM) + break; + + /* Wait briefly for -EAGAIN (FW busy), a bit longer for + * -ECOMM (PF down) to allow the PF to fully initialize. + * For -EBUSY, the message typically has timed out, so + * try again immediately. + */ + if (i < BNXT_RESUME_MAX_RETRY - 1) { + if (rc == -EAGAIN) + msleep(250); + else if (rc == -ECOMM) + msleep(750); + } + } + if (rc) { + netdev_err(dev, + "Firmware not responding during resume, rc = %d\n", + rc); + return -ENODEV; + } + } + + rtnl_lock(); + netdev_lock(dev); + if (bnxt_hwrm_ver_get(bp)) { rc = -ENODEV; goto resume_exit; From 1ff671ca32abb771270f3535d0f6cf4f93344416 Mon Sep 17 00:00:00 2001 From: Miro Kropacek Date: Wed, 21 Oct 2026 12:23:36 +1000 Subject: [PATCH 0507/2102] m68k: Fix atari mouse movement Kernels are built with -funsigned-char since version 6.2, resulting in the signed 8-bit position deltas reported by the IKBD being misinterpreted as unsigned. The hook is handed a raw IKBD packet, so take it as a byte stream and apply the sign to the two displacement values alone. Fixes: 3bc753c06dd02a35 ("kbuild: treat char as always unsigned") Link: https://lists.debian.org/debian-68k/2026/08/msg00000.html Suggested-by: Dmitry Torokhov Signed-off-by: Miro Kropacek Reviewed-by: Michael Schmitz Reviewed-by: Geert Uytterhoeven Acked-by: Geert Uytterhoeven Link: https://patch.msgid.link/20261021022336.2232886-1-miro.kropacek@gmail.com Signed-off-by: Dmitry Torokhov --- arch/m68k/atari/atakeyb.c | 2 +- arch/m68k/include/asm/atarikb.h | 4 +++- drivers/input/mouse/atarimouse.c | 6 +++--- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/arch/m68k/atari/atakeyb.c b/arch/m68k/atari/atakeyb.c index 49a9a459bdf4cc..b715e2b8351c8f 100644 --- a/arch/m68k/atari/atakeyb.c +++ b/arch/m68k/atari/atakeyb.c @@ -39,7 +39,7 @@ void (*atari_MIDI_interrupt_hook) (void); /* Hook for keyboard inputdev driver */ void (*atari_input_keyboard_interrupt_hook) (unsigned char, char); /* Hook for mouse inputdev driver */ -void (*atari_input_mouse_interrupt_hook) (char *); +void (*atari_input_mouse_interrupt_hook)(u8 *buf); EXPORT_SYMBOL(atari_input_keyboard_interrupt_hook); EXPORT_SYMBOL(atari_input_mouse_interrupt_hook); diff --git a/arch/m68k/include/asm/atarikb.h b/arch/m68k/include/asm/atarikb.h index 68f3622bf59193..bdf67bff147249 100644 --- a/arch/m68k/include/asm/atarikb.h +++ b/arch/m68k/include/asm/atarikb.h @@ -15,6 +15,8 @@ #ifndef _LINUX_ATARIKB_H #define _LINUX_ATARIKB_H +#include + void ikbd_write(const char *, int); void ikbd_mouse_button_action(int mode); void ikbd_mouse_rel_pos(void); @@ -37,7 +39,7 @@ extern void (*atari_MIDI_interrupt_hook) (void); /* Hook for keyboard inputdev driver */ extern void (*atari_input_keyboard_interrupt_hook) (unsigned char, char); /* Hook for mouse inputdev driver */ -extern void (*atari_input_mouse_interrupt_hook) (char *); +extern void (*atari_input_mouse_interrupt_hook)(u8 *buf); int atari_keyb_init(void); diff --git a/drivers/input/mouse/atarimouse.c b/drivers/input/mouse/atarimouse.c index b1219cc4d9a2a0..c5b794262e856b 100644 --- a/drivers/input/mouse/atarimouse.c +++ b/drivers/input/mouse/atarimouse.c @@ -60,7 +60,7 @@ extern int atari_mouse_buttons; static struct input_dev *atamouse_dev; -static void atamouse_interrupt(char *buf) +static void atamouse_interrupt(u8 *buf) { int buttons, dx, dy; @@ -71,8 +71,8 @@ static void atamouse_interrupt(char *buf) #endif /* only relative events get here */ - dx = buf[1]; - dy = buf[2]; + dx = (s8)buf[1]; + dy = (s8)buf[2]; input_report_rel(atamouse_dev, REL_X, dx); input_report_rel(atamouse_dev, REL_Y, dy); From 7f1e33230b7c7a55318765862b255b41e5c97cfb Mon Sep 17 00:00:00 2001 From: Breno Leitao Date: Tue, 10 Nov 2026 04:18:32 -0800 Subject: [PATCH 0508/2102] bpf: Report RCU-tasks quiescent states in do_check() I am seeing rcu_tasks stalls in the Meta fleet on debug kernels (KASAN, kmemleak, lockdep), where a task loading a BPF program stays in the verifier for over 20 minutes: INFO: rcu_tasks detected stalls on tasks: 000000000cc1a43d: .. nvcsw: 4/4 holdout: 1 idle_cpu: -1/91 task:GlobalCPUThread state:R running task pid:175256 tgid:169948 ppid:1 Call Trace: __create_object __kmalloc_node_track_caller_noprof krealloc_node_align_noprof copy_array bpf_copy_verifier_state bpf_split_cur_state do_check_common do_check_main bpf_check bpf_prog_load __sys_bpf The main loop in do_check() only calls cond_resched(), which is a no-op on PREEMPTION kernels. Involuntary preemption is not a Tasks-RCU quiescent state, so the loading task never reports one and stays a holdout until bpf_prog_load() returns. Meanwhile every synchronize_rcu_tasks() caller waits, e.g. ftrace_shutdown() of a dynamic ftrace_ops. Upgrade it to cond_resched_tasks_rcu_qs(), which reports a quiescent state even when cond_resched() does nothing. The need_resched() check goes away, as cond_resched() does it already. Fixes: 3c2ce60bdd3d ("bpf: adjust verifier heuristics") Signed-off-by: Breno Leitao Signed-off-by: Alexei Starovoitov Reviewed-by: Paul E. McKenney Link: https://patch.msgid.link/20261110-bpf-verifier-rcu-tasks-qs-v1-1-99e8f798a6dc@debian.org --- kernel/bpf/verifier.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 5e4700fda66b9f..232551fd7cefdd 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -20627,8 +20627,7 @@ static int do_check(struct bpf_verifier_env *env) if (signal_pending(current)) return -EAGAIN; - if (need_resched()) - cond_resched(); + cond_resched_tasks_rcu_qs(); /* reset current history entry on each new instruction */ env->cur_hist_ent = NULL; From cc2f90768e971bcc3a3445201cf6a55d761c8e09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Le=20Goffic?= Date: Fri, 30 Oct 2026 16:58:32 +0100 Subject: [PATCH 0509/2102] pinctrl: scmi: send the drive strength in microamperes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SCMI gives the drive strength in microamperes, but PIN_CONFIG_DRIVE_STRENGTH is in milliamperes and was sent unchanged. Convert it on set and on get. It is the only unit that differs: the debounce is in microseconds and the pull resistances in ohms on both sides, and every other value is a flag or implementation defined. Fixes: eb524cb651b7 ("pinctrl: Implementation of the generic scmi-pinctrl driver") Signed-off-by: Clément Le Goffic Reviewed-by: Cristian Marussi Signed-off-by: Linus Walleij --- drivers/pinctrl/pinctrl-scmi.c | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/drivers/pinctrl/pinctrl-scmi.c b/drivers/pinctrl/pinctrl-scmi.c index c93d61dfa28227..6bc94c68e89a96 100644 --- a/drivers/pinctrl/pinctrl-scmi.c +++ b/drivers/pinctrl/pinctrl-scmi.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -155,6 +156,15 @@ static int pinctrl_scmi_map_pinconf_type(enum pin_config_param param, return 0; } +static u32 pinctrl_scmi_map_pinconf_arg_get(enum pin_config_param param, + u32 value) +{ + if (param == PIN_CONFIG_DRIVE_STRENGTH) + return value / MILLI; + + return value; +} + static int pinctrl_scmi_map_pinconf_type_get(enum pin_config_param param, enum scmi_pinctrl_conf_type *type) { @@ -167,13 +177,17 @@ static int pinctrl_scmi_map_pinconf_type_get(enum pin_config_param param, } static int pinctrl_scmi_map_pinconf_type_set(enum pin_config_param param, - enum scmi_pinctrl_conf_type *type) + enum scmi_pinctrl_conf_type *type, + u32 *arg) { if (param == PIN_CONFIG_LEVEL) { *type = SCMI_PIN_OUTPUT_VALUE; return 0; } + if (param == PIN_CONFIG_DRIVE_STRENGTH) + *arg *= MILLI; + return pinctrl_scmi_map_pinconf_type(param, type); } @@ -203,6 +217,7 @@ static int pinctrl_scmi_pinconf_get(struct pinctrl_dev *pctldev, if (ret) return ret; + config_value = pinctrl_scmi_map_pinconf_arg_get(config_type, config_value); *config = pinconf_to_config_packed(config_type, config_value); return 0; @@ -267,12 +282,13 @@ static int pinctrl_scmi_pinconf_set(struct pinctrl_dev *pctldev, param = pinconf_to_config_param(configs[i]); if (param == PIN_CONFIG_PERSIST_STATE) continue; - ret = pinctrl_scmi_map_pinconf_type_set(param, &p_config_type[cnt]); + p_config_value[cnt] = pinconf_to_config_argument(configs[i]); + ret = pinctrl_scmi_map_pinconf_type_set(param, &p_config_type[cnt], + &p_config_value[cnt]); if (ret) { dev_err(pmx->dev, "Error map pinconf_type %d\n", ret); goto free_config; } - p_config_value[cnt] = pinconf_to_config_argument(configs[i]); cnt++; } @@ -310,13 +326,13 @@ static int pinctrl_scmi_pinconf_group_set(struct pinctrl_dev *pctldev, for (i = 0; i < num_configs; i++) { param = pinconf_to_config_param(configs[i]); - ret = pinctrl_scmi_map_pinconf_type_set(param, &p_config_type[i]); + p_config_value[i] = pinconf_to_config_argument(configs[i]); + ret = pinctrl_scmi_map_pinconf_type_set(param, &p_config_type[i], + &p_config_value[i]); if (ret) { dev_err(pmx->dev, "Error map pinconf_type %d\n", ret); goto free_config; } - - p_config_value[i] = pinconf_to_config_argument(configs[i]); } ret = pinctrl_ops->settings_conf(pmx->ph, group, GROUP_TYPE, @@ -359,6 +375,7 @@ static int pinctrl_scmi_pinconf_group_get(struct pinctrl_dev *pctldev, if (ret) return ret; + config_value = pinctrl_scmi_map_pinconf_arg_get(config_type, config_value); *config = pinconf_to_config_packed(config_type, config_value); return 0; From 5786097b380d053310ee8a63d8adc047b480bebb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Le=20Goffic?= Date: Fri, 30 Oct 2026 16:58:33 +0100 Subject: [PATCH 0510/2102] pinctrl: scmi: map the schmitt trigger enable to its SCMI type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PIN_CONFIG_INPUT_SCHMITT_ENABLE was sent as INPUT_MODE, which drives the input buffer, and PIN_CONFIG_INPUT_SCHMITT, a threshold, as INPUT_SCHMITT, which only takes 0 or 1. Send the enable as INPUT_SCHMITT and refuse the threshold, the protocol has no type for it. Fixes: eb524cb651b7 ("pinctrl: Implementation of the generic scmi-pinctrl driver") Signed-off-by: Clément Le Goffic Reviewed-by: Cristian Marussi Signed-off-by: Linus Walleij --- drivers/pinctrl/pinctrl-scmi.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/drivers/pinctrl/pinctrl-scmi.c b/drivers/pinctrl/pinctrl-scmi.c index 6bc94c68e89a96..5de47e060e8c2a 100644 --- a/drivers/pinctrl/pinctrl-scmi.c +++ b/drivers/pinctrl/pinctrl-scmi.c @@ -128,11 +128,8 @@ static int pinctrl_scmi_map_pinconf_type(enum pin_config_param param, case PIN_CONFIG_INPUT_ENABLE: *type = SCMI_PIN_INPUT_MODE; break; - case PIN_CONFIG_INPUT_SCHMITT: - *type = SCMI_PIN_INPUT_SCHMITT; - break; case PIN_CONFIG_INPUT_SCHMITT_ENABLE: - *type = SCMI_PIN_INPUT_MODE; + *type = SCMI_PIN_INPUT_SCHMITT; break; case PIN_CONFIG_MODE_LOW_POWER: *type = SCMI_PIN_LOW_POWER_MODE; From 9d69679d7d48c2a122f158185422392e576c3374 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Le=20Goffic?= Date: Fri, 30 Oct 2026 16:58:34 +0100 Subject: [PATCH 0511/2102] pinctrl: scmi: send the settings without argument as enabled MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bias-bus-hold, bias-disable, bias-high-impedance, drive-open-drain, drive-open-source and drive-push-pull take no argument in Linux, so they were sent with the value 0, which the protocol reads as disabled. Send 1. Fixes: eb524cb651b7 ("pinctrl: Implementation of the generic scmi-pinctrl driver") Signed-off-by: Clément Le Goffic Reviewed-by: Cristian Marussi Signed-off-by: Linus Walleij --- drivers/pinctrl/pinctrl-scmi.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/drivers/pinctrl/pinctrl-scmi.c b/drivers/pinctrl/pinctrl-scmi.c index 5de47e060e8c2a..f74ef0952ba9b7 100644 --- a/drivers/pinctrl/pinctrl-scmi.c +++ b/drivers/pinctrl/pinctrl-scmi.c @@ -173,6 +173,21 @@ static int pinctrl_scmi_map_pinconf_type_get(enum pin_config_param param, return pinctrl_scmi_map_pinconf_type(param, type); } +static bool pinctrl_scmi_pinconf_arg_ignored(enum pin_config_param param) +{ + switch (param) { + case PIN_CONFIG_BIAS_BUS_HOLD: + case PIN_CONFIG_BIAS_DISABLE: + case PIN_CONFIG_BIAS_HIGH_IMPEDANCE: + case PIN_CONFIG_DRIVE_OPEN_DRAIN: + case PIN_CONFIG_DRIVE_OPEN_SOURCE: + case PIN_CONFIG_DRIVE_PUSH_PULL: + return true; + default: + return false; + } +} + static int pinctrl_scmi_map_pinconf_type_set(enum pin_config_param param, enum scmi_pinctrl_conf_type *type, u32 *arg) @@ -182,6 +197,9 @@ static int pinctrl_scmi_map_pinconf_type_set(enum pin_config_param param, return 0; } + if (pinctrl_scmi_pinconf_arg_ignored(param)) + *arg = 1; + if (param == PIN_CONFIG_DRIVE_STRENGTH) *arg *= MILLI; From 169169e26ab498e4a3ee07313e986176f4bc52f0 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Wed, 11 Nov 2026 22:59:59 +0100 Subject: [PATCH 0512/2102] mm/userfaultfd: fix PTE table overruns in UFFDIO_MOVE With a folded PMD, pmd_addr_end() simply returns the supplied end. move_present_ptes() can therefore walk past the source or destination PTE table during UFFDIO_MOVE. pmd_addr_end() is only intended for page table traversal, in patterns like "next = pmd_addr_end(addr, end);". With folded PMDs, a higher level has already clamped the range to the PTE table. Folded PMDs are uncommon, but can occur even on arm64, for example with 64K pages and a 42-bit virtual address space. Extract the calculation from folio_pte_range() into pte_table_clamped_end() and use it to clamp both ranges. This preserves the wraparound handling from commit f681d4580d5c ("mm: fix address wraparound when scanning large folio PTEs"). Fixes: 50944692052b ("userfaultfd: opportunistic TLB-flush batching for present pages in MOVE") Cc: stable@vger.kernel.org Reported-by: Chris Mason Reviewed-by: Baolin Wang Link: https://patch.msgid.link/20261111-pte_table_clamped_end-v1-1-2dbe339c487a@kernel.org Reviewed-by: Lokesh Gidra Signed-off-by: David Hildenbrand (Arm) --- include/linux/pgtable.h | 24 ++++++++++++++++++++++++ mm/memory.c | 7 +------ mm/userfaultfd.c | 4 ++-- 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/include/linux/pgtable.h b/include/linux/pgtable.h index 780fe849ff8b7e..66d369870a740f 100644 --- a/include/linux/pgtable.h +++ b/include/linux/pgtable.h @@ -12,6 +12,7 @@ #ifdef CONFIG_MMU #include +#include #include #include #include @@ -1518,6 +1519,29 @@ static inline void arch_swap_restore(swp_entry_t entry, struct folio *folio) }) #endif +/** + * pte_table_clamped_end() - Limit a range to a single PTE table. + * @addr: Start address. + * @end: Exclusive end address. + * + * Only use pmd_addr_end() when traversing page tables, in a pattern like:: + * + * next = pmd_addr_end(addr, end); + * + * Higher levels already bound the range when PMDs are folded. Use this + * helper elsewhere to clamp the range regardless of PMD folding. + * + * Return: The exclusive end of the PTE table containing @addr, capped at @end. + */ +static inline unsigned long pte_table_clamped_end(unsigned long addr, + unsigned long end) +{ + const unsigned long pmd_end = (addr & PMD_MASK) + PMD_SIZE; + + /* Compare inclusive ends to avoid wraparounds. */ + return min(pmd_end - 1, end - 1) + 1; +} + /* * When walking page tables, we usually want to skip any p?d_none entries; * and any p?d_bad entries - reporting the error before resetting to none. diff --git a/mm/memory.c b/mm/memory.c index ec3d9d99ccee2f..ee792a2c0ccea4 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -4959,13 +4959,8 @@ static void folio_pte_range(const struct folio *folio, { /* Stay within the page table and VMA boundaries. */ const unsigned long pmd_start = addr & PMD_MASK; - const unsigned long pmd_end = pmd_start + PMD_SIZE; const unsigned long lower = max(pmd_start, vma->vm_start); - /* - * We cannot use pmd_addr_end(), as it does not clamp reliably. To - * avoid wraparounds, compute using the inclusive end. - */ - const unsigned long upper = min(pmd_end - 1, vma->vm_end - 1) + 1; + const unsigned long upper = pte_table_clamped_end(addr, vma->vm_end); const unsigned long offset = idx << PAGE_SHIFT; /* diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index 169f681f9849b4..57650e6f040d1e 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -1266,8 +1266,8 @@ static long move_present_ptes(struct mm_struct *mm, unsigned long src_start = src_addr; unsigned long src_end; - len = pmd_addr_end(dst_addr, dst_addr + len) - dst_addr; - src_end = pmd_addr_end(src_addr, src_addr + len); + len = pte_table_clamped_end(dst_addr, dst_addr + len) - dst_addr; + src_end = pte_table_clamped_end(src_addr, src_addr + len); flush_cache_range(src_vma, src_addr, src_end); double_pt_lock(dst_ptl, src_ptl); From d8bbf585893c7868234b71d7e7f32484ed0d8458 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Wed, 11 Nov 2026 23:00:00 +0100 Subject: [PATCH 0513/2102] mm/rmap: fix PTE table overruns during batched unmap With a folded PMD, pmd_addr_end() simply returns the supplied end. folio_unmap_pte_batch() can therefore walk past the PTE table when unmapping a large folio. Folded PMDs are uncommon, but can occur even on arm64, for example with 64K pages and a 42-bit virtual address space. Use pte_table_clamped_end() to clamp the range to the PTE table and VMA boundaries. Fixes: 354dffd29575 ("mm: support batched unmap for lazyfree large folios during reclamation") Cc: stable@vger.kernel.org Reported-by: Chris Mason Reviewed-by: Baolin Wang Link: https://patch.msgid.link/20261111-pte_table_clamped_end-v1-2-2dbe339c487a@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/rmap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mm/rmap.c b/mm/rmap.c index 0faef46806e5ca..491a954b7fa447 100644 --- a/mm/rmap.c +++ b/mm/rmap.c @@ -1978,7 +1978,7 @@ static inline unsigned int folio_unmap_pte_batch(struct folio *folio, return 1; /* We may only batch within a single VMA and a single page table. */ - end_addr = pmd_addr_end(addr, vma->vm_end); + end_addr = pte_table_clamped_end(addr, vma->vm_end); max_nr = (end_addr - addr) >> PAGE_SHIFT; /* We only support lazyfree or file folios batching for now ... */ From 2d9b9352ef885837f246225e9b814a05e9ed2a4a Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Wed, 11 Nov 2026 23:00:01 +0100 Subject: [PATCH 0514/2102] mm/rmap: fix PTE table overruns during batched reference checks With a folded PMD, pmd_addr_end() simply returns the supplied end. folio_referenced_one() can therefore walk past the PTE table when checking references to a large folio. Folded PMDs are uncommon, but can occur even on arm64, for example with 64K pages and a 42-bit virtual address space. Use pte_table_clamped_end() to clamp the range to the PTE table and VMA boundaries. Fixes: 52e054f71840 ("mm: rmap: support batched checks of the references for large folios") Cc: stable@vger.kernel.org Reported-by: Chris Mason Reviewed-by: Baolin Wang Link: https://patch.msgid.link/20261111-pte_table_clamped_end-v1-3-2dbe339c487a@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/rmap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mm/rmap.c b/mm/rmap.c index 491a954b7fa447..65646ed6fc4536 100644 --- a/mm/rmap.c +++ b/mm/rmap.c @@ -973,7 +973,7 @@ static bool folio_referenced_one(struct folio *folio, pteval = ptep_get(pvmw.pte); if (pvmw.pte && pte_present(pteval) && folio_test_large(folio)) { - const unsigned long end_addr = pmd_addr_end(address, vma->vm_end); + const unsigned long end_addr = pte_table_clamped_end(address, vma->vm_end); const unsigned int max_nr = (end_addr - address) >> PAGE_SHIFT; nr = folio_pte_batch(folio, pvmw.pte, pteval, max_nr); From 7183af7f01c839ecef87840a90c0d8c5843f37d7 Mon Sep 17 00:00:00 2001 From: Zi Yan Date: Tue, 10 Nov 2026 22:19:25 -0500 Subject: [PATCH 0515/2102] mm/huge_memory: prevent losing PG_waiters in __split_folio_to_order() __split_folio_to_order() calls prep_compound_page() on each new head page to create a compound page after clear_compound_head(). prep_compound_page() uses non atomic __SetPageHead(). It is mostly OK, since the folio is locked and frozen and no one else is supposed to modify the folio's flags. However, code calling migration_entry_wait() can reach the folio by PFN, then access its flags. It is because softleaf_entry_wait_on_locked() used by migration_entry_wait() sets PG_waiters concurrently without taking a reference and the frozen refcount during split cannot block it. Meanwhile, __SetPageHead() does a plain read and write, so PG_waiters atomically set by softleaf_entry_wait_on_locked() will be lost if the set happens after __SetPageHead()'s read and before its write. One example code interleaving: CPU0: __split_folio_to_order(new_order>0) CPU1: do_swap_page() 1. clear_compound_head(new_head) new_head->compound_info = 0 (page_folio(new_head) == new_head now) 2. migration_entry_wait() softleaf_to_folio(entry) page_folio() -> new_head (not the old head any more) 3. prep_compound_page(new_head, new_order) __SetPageHead(new_head) tmp = new_head->flags.f <-- load; PG_waiters == 0 in tmp 4. folio_set_waiters(new_head) set_bit(PG_waiters, &flags.f) enqueue on waitqueue, sleep 5. new_head->flags.f = tmp | (1UL << PG_head) <-- store; overwrites step 4, PG_waiters == 0 again Later, folio_unlock(new_folio) sees no PG_waiters, skips folio_wake_bit(), and CPU1 can remain blocked indefinitely. Fix it by setting PG_head along with other flags in new_folio->flags before smp_wmb() and clear_compound_head(). The remaining compound page metadata is set after clear_compound_head(). In that way, after clear_compound_head() makes new_folio visible, nothing overwrites the PG_waiters from softleaf_entry_wait_on_locked() by modifying new_folio->flags non-atomically. While at it, use data_race() to suppress the KCSAN issue reported by Ye Liu's patch (the second Closes) on reading folio->flags in __split_folio_to_order(). Suggested-by: Kiryl Shutsemau Reported-by: David Hildenbrand Closes: https://lore.kernel.org/all/DMHE8BEEER1H.2BIY52NXATPIA@nvidia.com/ Reported-by: Ye Liu Closes: https://lore.kernel.org/all/20261029-data_race_huge_mem-v1-1-112e331291c1@linux.dev/ Fixes: c010d47f107f6 ("mm: thp: split huge page to any lower order pages") Cc: stable@vger.kernel.org Signed-off-by: Zi Yan Reviewed-by: David Hildenbrand (Arm) Reviewed-by: Kiryl Shutsemau (Meta) Reviewed-by: Baolin Wang Reviewed-by: Ye Liu Link: https://patch.msgid.link/20261110-fix-split_folio_to_order-race-v4-1-cc5042f33408@nvidia.com Signed-off-by: David Hildenbrand (Arm) --- mm/huge_memory.c | 32 ++++++++++++++++++++++++++++---- mm/internal.h | 2 ++ mm/page_alloc.c | 17 +++++++++++++++-- 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/mm/huge_memory.c b/mm/huge_memory.c index eb913acb03b74b..2e7f4e4c13d275 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -3775,6 +3775,7 @@ static void __split_folio_to_order(struct folio *folio, int old_order, * Don't pass it around before clear_compound_head(). */ struct folio *new_folio = (struct folio *)new_head; + memdesc_flags_t new_flags; VM_BUG_ON_PAGE(atomic_read(&new_folio->_mapcount) != -1, new_head); @@ -3791,8 +3792,15 @@ static void __split_folio_to_order(struct folio *folio, int old_order, * unreferenced sub-pages of an anonymous THP: we can simply drop * PG_anon_exclusive (-> PG_mappedtodisk) for these here. */ - new_folio->flags.f &= ~PAGE_FLAGS_CHECK_AT_PREP; - new_folio->flags.f |= (folio->flags.f & + new_flags.f = new_folio->flags.f & ~PAGE_FLAGS_CHECK_AT_PREP; + /* + * data_race() is used because folio->flags is only read here, + * but a reference-less writer can still write to it, e.g., + * PG_waiters update from softleaf_entry_wait_on_locked(). + * The flag is not transferred to new_flags as it is + * folio specific, so it is not lost. + */ + new_flags.f |= data_race(folio->flags.f) & ((1L << PG_referenced) | (1L << PG_swapbacked) | (1L << PG_swapcache) | @@ -3810,7 +3818,19 @@ static void __split_folio_to_order(struct folio *folio, int old_order, #endif (1L << PG_dirty) | (1L << PG_dropbehind) | - LRU_GEN_MASK | LRU_REFS_MASK)); + LRU_GEN_MASK | LRU_REFS_MASK); + + /* + * Set PG_head before smp_wmb() and clear_compound_head(). + * After clear_compound_head() marks new_head as a folio of its + * own, new_head->flags must not be modified by plain RMWs. + * A plain RMW can cause a loss of atomic PG_* updates from + * a reference-less writer, e.g., setting PG_waiters via + * softleaf_entry_wait_on_locked(). + */ + if (new_order) + new_flags.f |= 1L << PG_head; + WRITE_ONCE(new_folio->flags.f, new_flags.f); new_folio->mapping = folio->mapping; new_folio->index = folio->index + i; @@ -3840,7 +3860,11 @@ static void __split_folio_to_order(struct folio *folio, int old_order, */ clear_compound_head(new_head); if (new_order) { - prep_compound_page(new_head, new_order); + /* + * PG_head is set above, so only set up the remaining + * metadata on head page and tail pages. + */ + __prep_compound_page(new_head, new_order); folio_set_large_rmappable(new_folio); } diff --git a/mm/internal.h b/mm/internal.h index e3f92883bf2384..a0e0c4f910208c 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -834,6 +834,8 @@ static inline void prep_compound_tail(struct page *tail, VM_WARN_ON_ONCE(tail->private); } +void __prep_compound_page(struct page *page, unsigned int order); + #if defined CONFIG_COMPACTION || defined CONFIG_CMA /* diff --git a/mm/page_alloc.c b/mm/page_alloc.c index eb4f02617f53c0..fcc6ec394678a7 100644 --- a/mm/page_alloc.c +++ b/mm/page_alloc.c @@ -682,18 +682,31 @@ static inline bool pcp_allowed_order(unsigned int order) * This usage means that zero-order pages may not be compound. */ -void prep_compound_page(struct page *page, unsigned int order) +/* + * Set up the metadata on head page and tail pages. + * Caller must set PG_head before this. + */ +void __prep_compound_page(struct page *page, unsigned int order) { int i; int nr_pages = 1 << order; - __SetPageHead(page); for (i = 1; i < nr_pages; i++) prep_compound_tail(page + i, page, order); prep_compound_head(page, order); } +/* + * PG_head is set non-atomically. It should be used when no one else can modify + * @page's flags. + */ +void prep_compound_page(struct page *page, unsigned int order) +{ + __SetPageHead(page); + __prep_compound_page(page, order); +} + static inline void set_buddy_order(struct page *page, unsigned int order) { set_page_private(page, order); From 8ed87a9adf48703b5729f9d020eb15fa79ffb099 Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Tue, 10 Nov 2026 14:47:01 +0100 Subject: [PATCH 0516/2102] gpiolib: don't overwrite the entire flags field in gpiod_get_direction() gpiod_get_direction() snapshots desc->flags with READ_ONCE(), updates FLAG_IS_OUT in the local copy and writes the whole word back with WRITE_ONCE(). Any bit that a concurrent user sets or clears atomically in between - for instance: FLAG_USED_AS_IRQ from gpiochip_lock_as_irq() - is silently lost. Update FLAG_IS_OUT with a single atomic assign_bit() directly on desc->flags. The earlier READ_ONCE() snapshot is only used for the open-drain check and stays. Cc: stable@vger.kernel.org Fixes: 2559f2e09211 ("gpio: reinforce desc->flags handling") Reviewed-by: Kent Gibson Link: https://patch.msgid.link/20261110-gpio-desc-flags-atomic-v3-1-2f463bce8086@oss.qualcomm.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index acd3a1710f84d6..91041ce0fd4919 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -489,8 +489,7 @@ int gpiod_get_direction(struct gpio_desc *desc) if (ret > 0) ret = 1; - assign_bit(GPIOD_FLAG_IS_OUT, &flags, !ret); - WRITE_ONCE(desc->flags, flags); + assign_bit(GPIOD_FLAG_IS_OUT, &desc->flags, !ret); return ret; } From 7d1d799d6251bc8cd1d5cfc881b0c09060b6b90d Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Tue, 10 Nov 2026 14:47:02 +0100 Subject: [PATCH 0517/2102] gpio: shared: use atomic set_bit() for descriptor flags Use the atomic set_bit() instead of __set_bit() on desc->flags so that every modification of the field uses atomic bitops. No functional change as these run before any line of the chip can be requested. Cc: stable@vger.kernel.org Fixes: eb374f764a70 ("gpio: provide gpiod_is_shared()") Fixes: a060b8c511ab ("gpiolib: implement low-level, shared GPIO support") Reviewed-by: Kent Gibson Link: https://patch.msgid.link/20261110-gpio-desc-flags-atomic-v3-2-2f463bce8086@oss.qualcomm.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib-shared.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/drivers/gpio/gpiolib-shared.c b/drivers/gpio/gpiolib-shared.c index edb04a5bb987e1..f34315a2059a2b 100644 --- a/drivers/gpio/gpiolib-shared.c +++ b/drivers/gpio/gpiolib-shared.c @@ -532,8 +532,7 @@ int gpiochip_setup_shared(struct gpio_chip *gc) * This is a shared GPIO proxy. Mark its * descriptor as such and return here. */ - __set_bit(GPIOD_FLAG_SHARED_PROXY, - &gdev->descs[0].flags); + set_bit(GPIOD_FLAG_SHARED_PROXY, &gdev->descs[0].flags); return 0; } } @@ -573,7 +572,7 @@ int gpiochip_setup_shared(struct gpio_chip *gc) desc = &gdev->descs[entry->offset]; - __set_bit(GPIOD_FLAG_SHARED, &desc->flags); + set_bit(GPIOD_FLAG_SHARED, &desc->flags); /* * Shared GPIOs are not requested via the normal path. Make * them inaccessible to anyone even before we register the From 8509d643ffb7be508568c696c9fe45eb1f84c33c Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Tue, 10 Nov 2026 14:47:03 +0100 Subject: [PATCH 0518/2102] gpiolib: clear debounce period before the "requested" flag The debounce_period_us field is protected by the GPIOD_FLAG_REQUESTED flag, so it should be cleared before the flag, else it could potentially race with a new request. Suggested-by: Kent Gibson Closes: https://lore.kernel.org/all/20261105042905.GB8436@rigel/ Fixes: 81625f362497 ("gpio: cdev: go back to storing debounce period in the GPIO descriptor") Reviewed-by: Kent Gibson Link: https://patch.msgid.link/20261110-gpio-desc-flags-atomic-v3-3-2f463bce8086@oss.qualcomm.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index 91041ce0fd4919..dc0f21f1fd3e40 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -2707,6 +2707,10 @@ void gpiod_free_commit(struct gpio_desc *desc) if (guard.gc->free) guard.gc->free(guard.gc, gpiod_hwgpio(desc)); +#ifdef CONFIG_GPIO_CDEV + WRITE_ONCE(desc->debounce_period_us, 0); +#endif + clear_bit(GPIOD_FLAG_ACTIVE_LOW, &flags); clear_bit(GPIOD_FLAG_REQUESTED, &flags); clear_bit(GPIOD_FLAG_OPEN_DRAIN, &flags); @@ -2724,9 +2728,6 @@ void gpiod_free_commit(struct gpio_desc *desc) #endif desc_set_label(desc, NULL); WRITE_ONCE(desc->flags, flags); -#ifdef CONFIG_GPIO_CDEV - WRITE_ONCE(desc->debounce_period_us, 0); -#endif gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_RELEASED); } } From 63d7aedf6add8a24415af4c010588f63fa7296ab Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Tue, 10 Nov 2026 14:47:04 +0100 Subject: [PATCH 0519/2102] gpiolib: don't overwrite the entire flags field in gpiod_free_commit() Use set_mask_bits() to clear all request-related flags in one go instead of risking racing with concurrent users and overwriting any changes they could have done between READ_ONCE() and WRITE_ONCE(). Cc: stable@vger.kernel.org Fixes: 35b545332b80 ("gpio: remove gpio_lock") Reviewed-by: Kent Gibson Link: https://patch.msgid.link/20261110-gpio-desc-flags-atomic-v3-4-2f463bce8086@oss.qualcomm.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib.c | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index dc0f21f1fd3e40..a26ea4bfb99f22 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -2710,24 +2710,23 @@ void gpiod_free_commit(struct gpio_desc *desc) #ifdef CONFIG_GPIO_CDEV WRITE_ONCE(desc->debounce_period_us, 0); #endif - - clear_bit(GPIOD_FLAG_ACTIVE_LOW, &flags); - clear_bit(GPIOD_FLAG_REQUESTED, &flags); - clear_bit(GPIOD_FLAG_OPEN_DRAIN, &flags); - clear_bit(GPIOD_FLAG_OPEN_SOURCE, &flags); - clear_bit(GPIOD_FLAG_PULL_UP, &flags); - clear_bit(GPIOD_FLAG_PULL_DOWN, &flags); - clear_bit(GPIOD_FLAG_BIAS_DISABLE, &flags); - clear_bit(GPIOD_FLAG_EDGE_RISING, &flags); - clear_bit(GPIOD_FLAG_EDGE_FALLING, &flags); - clear_bit(GPIOD_FLAG_EVENT_CLOCK_REALTIME, &flags); - clear_bit(GPIOD_FLAG_EVENT_CLOCK_HTE, &flags); - clear_bit(GPIOD_FLAG_IS_HOGGED, &flags); #ifdef CONFIG_OF_DYNAMIC WRITE_ONCE(desc->hog, NULL); #endif desc_set_label(desc, NULL); - WRITE_ONCE(desc->flags, flags); + set_mask_bits(&desc->flags, + BIT(GPIOD_FLAG_ACTIVE_LOW) | + BIT(GPIOD_FLAG_REQUESTED) | + BIT(GPIOD_FLAG_OPEN_DRAIN) | + BIT(GPIOD_FLAG_OPEN_SOURCE) | + BIT(GPIOD_FLAG_PULL_UP) | + BIT(GPIOD_FLAG_PULL_DOWN) | + BIT(GPIOD_FLAG_BIAS_DISABLE) | + BIT(GPIOD_FLAG_EDGE_RISING) | + BIT(GPIOD_FLAG_EDGE_FALLING) | + BIT(GPIOD_FLAG_EVENT_CLOCK_REALTIME) | + BIT(GPIOD_FLAG_EVENT_CLOCK_HTE) | + BIT(GPIOD_FLAG_IS_HOGGED), 0); gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_RELEASED); } } From fa8bc4aa06674e78a4ee702966419aa4fdd8dc94 Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Tue, 10 Nov 2026 14:47:05 +0100 Subject: [PATCH 0520/2102] gpio: cdev: don't overwrite the whole flags field when configuring lines linehandle_flags_to_desc_flags() and gpio_v2_line_config_flags_to_desc_flags() read the flags word with READ_ONCE(), modify the local copy and write it back with WRITE_ONCE(). The per-request config_mutex does not exclude sysfs, the irq core or drivers touching the same descriptor, so bits they set or clear concurrently can be lost. Build the mask of bits owned by the line configuration and their new values locally and apply them with gpiod_update_flags(). The whole group changes in a single atomic step. While at it: rename the functions whose semantics changed from "conversion" to "flags update" accordingly. Cc: stable@vger.kernel.org Fixes: b7adfb6076ff ("gpio: cdev: update flags at once when reconfiguring from user-space") Reviewed-by: Kent Gibson Link: https://patch.msgid.link/20261110-gpio-desc-flags-atomic-v3-5-2f463bce8086@oss.qualcomm.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib-cdev.c | 93 ++++++++++++++++++------------------- 1 file changed, 46 insertions(+), 47 deletions(-) diff --git a/drivers/gpio/gpiolib-cdev.c b/drivers/gpio/gpiolib-cdev.c index 3f1f8c9acfc3c1..5f78960eb7f1ea 100644 --- a/drivers/gpio/gpiolib-cdev.c +++ b/drivers/gpio/gpiolib-cdev.c @@ -140,24 +140,25 @@ static int linehandle_validate_flags(u32 flags) return 0; } -static void linehandle_flags_to_desc_flags(u32 lflags, unsigned long *flagsp) +static void linehandle_update_desc_flags(u32 lflags, struct gpio_desc *desc) { - unsigned long flags = READ_ONCE(*flagsp); + unsigned long flags = 0, mask; - assign_bit(GPIOD_FLAG_ACTIVE_LOW, &flags, - lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW); - assign_bit(GPIOD_FLAG_OPEN_DRAIN, &flags, - lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN); - assign_bit(GPIOD_FLAG_OPEN_SOURCE, &flags, - lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE); - assign_bit(GPIOD_FLAG_PULL_UP, &flags, - lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP); - assign_bit(GPIOD_FLAG_PULL_DOWN, &flags, - lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN); - assign_bit(GPIOD_FLAG_BIAS_DISABLE, &flags, - lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE); + mask = BIT(GPIOD_FLAG_ACTIVE_LOW) | + BIT(GPIOD_FLAG_OPEN_DRAIN) | + BIT(GPIOD_FLAG_OPEN_SOURCE) | + BIT(GPIOD_FLAG_PULL_UP) | + BIT(GPIOD_FLAG_PULL_DOWN) | + BIT(GPIOD_FLAG_BIAS_DISABLE); - WRITE_ONCE(*flagsp, flags); + __assign_bit(GPIOD_FLAG_ACTIVE_LOW, &flags, lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW); + __assign_bit(GPIOD_FLAG_OPEN_DRAIN, &flags, lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN); + __assign_bit(GPIOD_FLAG_OPEN_SOURCE, &flags, lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE); + __assign_bit(GPIOD_FLAG_PULL_UP, &flags, lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP); + __assign_bit(GPIOD_FLAG_PULL_DOWN, &flags, lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN); + __assign_bit(GPIOD_FLAG_BIAS_DISABLE, &flags, lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE); + + set_mask_bits(&desc->flags, mask, flags); } static long linehandle_set_config(struct linehandle_state *lh, @@ -182,7 +183,7 @@ static long linehandle_set_config(struct linehandle_state *lh, for (i = 0; i < lh->num_descs; i++) { desc = lh->descs[i]; - linehandle_flags_to_desc_flags(lflags, &desc->flags); + linehandle_update_desc_flags(lflags, desc); if (lflags & GPIOHANDLE_REQUEST_OUTPUT) { int val = !!gcnf.default_values[i]; @@ -346,7 +347,7 @@ static int linehandle_create(struct gpio_device *gdev, void __user *ip) if (ret) return ret; lh->descs[i] = desc; - linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags); + linehandle_update_desc_flags(handlereq.flags, desc); ret = gpiod_set_transitory(desc, false); if (ret < 0) @@ -1223,37 +1224,35 @@ static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc, return 0; } -static void gpio_v2_line_config_flags_to_desc_flags(u64 lflags, - unsigned long *flagsp) +static void linereq_update_desc_flags(u64 lflags, struct gpio_desc *desc) { - unsigned long flags = READ_ONCE(*flagsp); - - assign_bit(GPIOD_FLAG_ACTIVE_LOW, &flags, - lflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW); - - assign_bit(GPIOD_FLAG_EDGE_RISING, &flags, - lflags & GPIO_V2_LINE_FLAG_EDGE_RISING); - assign_bit(GPIOD_FLAG_EDGE_FALLING, &flags, - lflags & GPIO_V2_LINE_FLAG_EDGE_FALLING); - - assign_bit(GPIOD_FLAG_OPEN_DRAIN, &flags, - lflags & GPIO_V2_LINE_FLAG_OPEN_DRAIN); - assign_bit(GPIOD_FLAG_OPEN_SOURCE, &flags, - lflags & GPIO_V2_LINE_FLAG_OPEN_SOURCE); + unsigned long flags = 0, mask; - assign_bit(GPIOD_FLAG_PULL_UP, &flags, - lflags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP); - assign_bit(GPIOD_FLAG_PULL_DOWN, &flags, - lflags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN); - assign_bit(GPIOD_FLAG_BIAS_DISABLE, &flags, - lflags & GPIO_V2_LINE_FLAG_BIAS_DISABLED); + mask = BIT(GPIOD_FLAG_ACTIVE_LOW) | + BIT(GPIOD_FLAG_EDGE_RISING) | + BIT(GPIOD_FLAG_EDGE_FALLING) | + BIT(GPIOD_FLAG_OPEN_DRAIN) | + BIT(GPIOD_FLAG_OPEN_SOURCE) | + BIT(GPIOD_FLAG_PULL_UP) | + BIT(GPIOD_FLAG_PULL_DOWN) | + BIT(GPIOD_FLAG_BIAS_DISABLE) | + BIT(GPIOD_FLAG_EVENT_CLOCK_REALTIME) | + BIT(GPIOD_FLAG_EVENT_CLOCK_HTE); - assign_bit(GPIOD_FLAG_EVENT_CLOCK_REALTIME, &flags, - lflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME); - assign_bit(GPIOD_FLAG_EVENT_CLOCK_HTE, &flags, - lflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE); + __assign_bit(GPIOD_FLAG_ACTIVE_LOW, &flags, lflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW); + __assign_bit(GPIOD_FLAG_EDGE_RISING, &flags, lflags & GPIO_V2_LINE_FLAG_EDGE_RISING); + __assign_bit(GPIOD_FLAG_EDGE_FALLING, &flags, lflags & GPIO_V2_LINE_FLAG_EDGE_FALLING); + __assign_bit(GPIOD_FLAG_OPEN_DRAIN, &flags, lflags & GPIO_V2_LINE_FLAG_OPEN_DRAIN); + __assign_bit(GPIOD_FLAG_OPEN_SOURCE, &flags, lflags & GPIO_V2_LINE_FLAG_OPEN_SOURCE); + __assign_bit(GPIOD_FLAG_PULL_UP, &flags, lflags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP); + __assign_bit(GPIOD_FLAG_PULL_DOWN, &flags, lflags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN); + __assign_bit(GPIOD_FLAG_BIAS_DISABLE, &flags, lflags & GPIO_V2_LINE_FLAG_BIAS_DISABLED); + __assign_bit(GPIOD_FLAG_EVENT_CLOCK_REALTIME, &flags, + lflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME); + __assign_bit(GPIOD_FLAG_EVENT_CLOCK_HTE, &flags, + lflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE); - WRITE_ONCE(*flagsp, flags); + set_mask_bits(&desc->flags, mask, flags); } static long linereq_get_values(struct linereq *lr, void __user *ip) @@ -1411,7 +1410,7 @@ static long linereq_set_config(struct linereq *lr, void __user *ip) */ if (!(flags & GPIO_V2_LINE_DIRECTION_FLAGS)) continue; - gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags); + linereq_update_desc_flags(flags, desc); edflags = flags & GPIO_V2_LINE_EDGE_DETECTOR_FLAGS; if (flags & GPIO_V2_LINE_FLAG_OUTPUT) { int val = gpio_v2_line_config_output_value(&lc, i); @@ -1667,7 +1666,7 @@ static int linereq_create(struct gpio_device *gdev, void __user *ip) lr->lines[i].desc = desc; flags = gpio_v2_line_config_flags(lc, i); - gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags); + linereq_update_desc_flags(flags, desc); ret = gpiod_set_transitory(desc, false); if (ret < 0) @@ -2062,7 +2061,7 @@ static int lineevent_create(struct gpio_device *gdev, void __user *ip) le->desc = desc; le->eflags = eflags; - linehandle_flags_to_desc_flags(lflags, &desc->flags); + linehandle_update_desc_flags(lflags, desc); ret = gpiod_direction_input(desc); if (ret) From 7a14efb16083531e442de4c7897bce74ac8635e8 Mon Sep 17 00:00:00 2001 From: Hyunjung Ko Date: Tue, 10 Nov 2026 02:02:23 +0900 Subject: [PATCH 0521/2102] phy: phy-bcm-ns2-usbdrd: cancel extcon work on unbind to avoid use-after-free ns2_drd_phy_probe() schedules driver->wq_extcon (extcon_work), which is also queued from the ID/VBUS GPIO interrupt handler gpio_irq_handler(). The work handler dereferences the driver data via container_of(). struct ns2_phy_driver is allocated with devm_kzalloc() and the driver has no remove callback, so on unbind devres frees it after probe's resources are released. The GPIO interrupts are requested with devm_request_irq(), and so released by devres; free_irq() only stops further interrupts, it does not cancel a delayed work that is already queued. probe() queues wq_extcon with a debounce delay before returning, and the GPIO interrupt can queue it too, so on unbind the pending work can run after ns2_phy_driver has been freed, dereferencing freed memory (use-after-free). Register the work with devm_delayed_work_autocancel() instead of INIT_DELAYED_WORK(). It is set up before the GPIO interrupts are requested, so on unwind devres frees the interrupts first - after which the work can no longer be queued - and then cancels the work while the driver data is still valid. extcon_work() does not re-queue itself, so a single cancel drains it. Found by static analysis and code review; not runtime-reproduced (needs Broadcom Northstar2 USB DRD PHY hardware). Fixes: 787f24543c4a ("phy: phy-bcm-ns2-usbdrd: Broadcom USB DRD PHY driver for Northstar2") Cc: stable@vger.kernel.org Signed-off-by: Hyunjung Ko Reviewed-by: Florian Fainelli Acked-by: Ray Jui Link: https://patch.msgid.link/20261109170223.1829473-1-hj351016@gmail.com Signed-off-by: Vinod Koul --- drivers/phy/broadcom/phy-bcm-ns2-usbdrd.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/drivers/phy/broadcom/phy-bcm-ns2-usbdrd.c b/drivers/phy/broadcom/phy-bcm-ns2-usbdrd.c index 171bf097a8b811..de2930457250b5 100644 --- a/drivers/phy/broadcom/phy-bcm-ns2-usbdrd.c +++ b/drivers/phy/broadcom/phy-bcm-ns2-usbdrd.c @@ -2,6 +2,7 @@ // Copyright (C) 2017 Broadcom #include +#include #include #include #include @@ -339,7 +340,9 @@ static int ns2_drd_phy_probe(struct platform_device *pdev) if (ret < 0) driver->debounce_jiffies = msecs_to_jiffies(GPIO_DELAY); - INIT_DELAYED_WORK(&driver->wq_extcon, extcon_work); + ret = devm_delayed_work_autocancel(dev, &driver->wq_extcon, extcon_work); + if (ret) + return ret; driver->id_irq = gpiod_to_irq(driver->id_gpiod); if (driver->id_irq < 0) { From 9a0dd2a09484e5ba45eb8e6ab58c0effe18703a3 Mon Sep 17 00:00:00 2001 From: "Oliver F. Brown" Date: Tue, 10 Nov 2026 14:05:46 +0200 Subject: [PATCH 0522/2102] phy: freescale: phy-fsl-imx8-mipi-dphy: Fix hs_zero underflow The hs_zero timing is computed as n = (144 * (hs_clk_rate / 1000000) - 47500) / 10000; cfg->m_prg_hs_zero = n < 1 ? 1 : n; hs_clk_rate is an unsigned long, so the subtraction is done unsigned and wraps for any rate below about 330 MHz, where 144 * MHz < 47500. Because n is a u32, the wrapped value is never seen as negative and the "n < 1" clamp does not take effect. The garbage value is then truncated into the 8-bit m_prg_hs_zero register field. At the minimum supported rate of 80 MHz this programs 199 on 64-bit and 181 on 32-bit, instead of the intended minimum of 1. Make n signed and do the arithmetic in int so the clamp works on both 32-bit and 64-bit. The divided rate is at most 1500, so 144 * 1500 fits easily in an int. Fixes: f4c8116e294b ("phy: Add driver for mixel mipi dphy found on NXP's i.MX8 SoCs") Cc: stable@vger.kernel.org Signed-off-by: Oliver F. Brown Signed-off-by: Stefan Ghetu Reviewed-by: Frank Li Reviewed-by: Laurentiu Palcu Link: https://patch.msgid.link/20261110120546.6247-1-stefan.ghetu@nxp.com Signed-off-by: Vinod Koul --- drivers/phy/freescale/phy-fsl-imx8-mipi-dphy.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/drivers/phy/freescale/phy-fsl-imx8-mipi-dphy.c b/drivers/phy/freescale/phy-fsl-imx8-mipi-dphy.c index 0928a526e2ab36..84bd21aaf9e840 100644 --- a/drivers/phy/freescale/phy-fsl-imx8-mipi-dphy.c +++ b/drivers/phy/freescale/phy-fsl-imx8-mipi-dphy.c @@ -191,8 +191,7 @@ static int mixel_dphy_config_from_opts(struct phy *phy, unsigned long ref_clk = clk_get_rate(priv->phy_ref_clk); u32 lp_t, numerator, denominator; unsigned long long tmp; - u32 n; - int i; + int n, i; if (dphy_opts->hs_clk_rate > DATA_RATE_MAX_SPEED || dphy_opts->hs_clk_rate < DATA_RATE_MIN_SPEED) @@ -276,7 +275,7 @@ static int mixel_dphy_config_from_opts(struct phy *phy, cfg->mc_prg_hs_prepare = dphy_opts->clk_prepare > lp_t ? 1 : 0; /* hs_zero: formula from NXP BSP */ - n = (144 * (dphy_opts->hs_clk_rate / 1000000) - 47500) / 10000; + n = (144 * (int)(dphy_opts->hs_clk_rate / 1000000) - 47500) / 10000; cfg->m_prg_hs_zero = n < 1 ? 1 : n; /* clk_zero: formula from NXP BSP */ From 7aca8e31a8fbf2ceffb487cec67ae300b95fa8b1 Mon Sep 17 00:00:00 2001 From: Christian Loehle Date: Fri, 13 Nov 2026 13:04:11 +0000 Subject: [PATCH 0523/2102] ACPI: CPPC: Reject EPP registers narrower than 8 bits The EPP interfaces use an 8-bit preference, but ACPI permits narrower fields. With a 4- or 6-bit SystemMemory field, writing 128 succeeds but stores zero, requesting maximum performance instead. Reject a present EPP register narrower than eight bits during _CPC probe. Use the existing error path to release previously acquired resources and leave the CPU's CPPC descriptor unpublished. Keep absent EPP entries and registers at least eight bits wide on their existing paths. Fail the whole probe instead of disabling only EPP. This also makes amd-pstate's acpi_cpc_valid() check reject the platform before registering its MSR or shared-memory driver. No affected hardware is known or expected and the specification is expected to no longer permit these in the future [1]. Fixes: 922607a2b462 ("cpufreq: CPPC: Add support for autonomous selection") Link: https://github.com/tianocore/edk2/issues/10838 [1] Signed-off-by: Christian Loehle Reviewed-by: Mario Limonciello (AMD) Cc: All applicable [ rjw: Changelog tweak ] Link: https://patch.msgid.link/20261113130411.1433174-1-christian.loehle@arm.com Signed-off-by: Rafael J. Wysocki --- drivers/acpi/cppc_acpi.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/drivers/acpi/cppc_acpi.c b/drivers/acpi/cppc_acpi.c index 05a547bbe93681..24fc26d45a782d 100644 --- a/drivers/acpi/cppc_acpi.c +++ b/drivers/acpi/cppc_acpi.c @@ -2081,6 +2081,15 @@ int acpi_cppc_processor_probe(struct acpi_processor *pr) cpc_apply_platform_quirks(gas_t, i - 2, platform_quirks); + /* EPP interfaces require the full 0-255 preference range. */ + if (i - 2 == ENERGY_PERF && gas_t->bit_width < 8 && + !IS_NULL_REG(gas_t)) { + pr_debug("CPU%d: EPP register width %u is not supported\n", + pr->id, gas_t->bit_width); + ret = -EOPNOTSUPP; + goto out_free; + } + /* * The PCC Subspace index is encoded inside * the CPC table entries. The same PCC index From 51222df62c7af2f0f11ec25c9fa8bcaa0f87fac8 Mon Sep 17 00:00:00 2001 From: Shunsuke Nagashima Date: Sun, 27 Sep 2026 21:10:53 +0900 Subject: [PATCH 0524/2102] wifi: ath10k: fix status of bundled mgmt tx completions ath10k_wmi_event_mgmt_tx_bundle_compl() takes the completion status of each report from desc_ids[i] instead of status[i]. Any non-zero status is handled as "not acked", so a bundled report is marked as acked if and only if its descriptor id is 0, whatever status the firmware returned. Take the status from status[i]. Tested-on: WCN3990 hw1.0 SNOC WLAN.HL.2.0.c10-00459-QCAHLSWMTPLZ-1 Fixes: 4b816f170b1f ("ath10k: add support for ack rssi value of management tx packets") Cc: stable@vger.kernel.org Signed-off-by: Shunsuke Nagashima Reviewed-by: David Heidelberg Reviewed-by: Loic Poulain Link: https://patch.msgid.link/20260927-ath10k-bundle-status-v1-1-a1eea048ada9@nagashi.ma Signed-off-by: Jeff Johnson --- drivers/net/wireless/ath/ath10k/wmi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/wireless/ath/ath10k/wmi.c b/drivers/net/wireless/ath/ath10k/wmi.c index e57588c19c800c..67be6e8171cd7d 100644 --- a/drivers/net/wireless/ath/ath10k/wmi.c +++ b/drivers/net/wireless/ath/ath10k/wmi.c @@ -2512,7 +2512,7 @@ int ath10k_wmi_event_mgmt_tx_bundle_compl(struct ath10k *ar, struct sk_buff *skb for (i = 0; i < num_reports; i++) { memset(¶m, 0, sizeof(struct mgmt_tx_compl_params)); param.desc_id = __le32_to_cpu(arg.desc_ids[i]); - param.status = __le32_to_cpu(arg.desc_ids[i]); + param.status = __le32_to_cpu(arg.status[i]); if (test_bit(WMI_SERVICE_TX_DATA_ACK_RSSI, ar->wmi.svc_map)) param.ack_rssi = __le32_to_cpu(arg.ack_rssi[i]); From ce8010f11f3ea62f8675e9bc921ee485aef82019 Mon Sep 17 00:00:00 2001 From: Yuan Yao Date: Fri, 13 Nov 2026 19:22:02 +0800 Subject: [PATCH 0525/2102] Input: trackpoint - add new TP JYT_NDT device variant id 7 The new trackpoint variant id 7 is found on Lenovo Thinkpad X14 Gen1 laptop(Product Name: 21XMA006CD), it belongs to JYT_NDT with confirmation from Vishnu Sankar in Lenovo. now it's incorrectly probed as Generic or Logitech PS/2 mouse. Add the variant id 7 to match the TP_READ_ID command return value, probe the device as trackpoint correctly. BEFORE: input: PS/2 Generic Mouse as /devices/platform/i8042/serio1/input/input63 AFTER: psmouse serio1: trackpoint: JYT_NDT TrackPoint firmware: 0xa1, buttons: 3/3 input: TPPS/2 JYT_NDT TrackPoint as /devices/platform/i8042/serio1/input/input8 Signed-off-by: Yuan Yao Link: https://patch.msgid.link/20261113112202.10304-2-yaoyuan@linux.alibaba.com Cc: stable@vger.kernel.org Signed-off-by: Dmitry Torokhov --- drivers/input/mouse/trackpoint.c | 2 ++ drivers/input/mouse/trackpoint.h | 1 + 2 files changed, 3 insertions(+) diff --git a/drivers/input/mouse/trackpoint.c b/drivers/input/mouse/trackpoint.c index 3bd8fdf56cd3d2..2dde8cc5cab155 100644 --- a/drivers/input/mouse/trackpoint.c +++ b/drivers/input/mouse/trackpoint.c @@ -25,6 +25,7 @@ static const char * const trackpoint_variants[] = { [TP_VARIANT_NXP] = "NXP", [TP_VARIANT_JYT_SYNAPTICS] = "JYT_Synaptics", [TP_VARIANT_SYNAPTICS] = "Synaptics", + [TP_VARIANT_JYT_NDT] = "JYT_NDT" }; /* @@ -285,6 +286,7 @@ static int trackpoint_start_protocol(struct psmouse *psmouse, case TP_VARIANT_ELAN: case TP_VARIANT_NXP: case TP_VARIANT_JYT_SYNAPTICS: + case TP_VARIANT_JYT_NDT: case TP_VARIANT_SYNAPTICS: if (variant_id) *variant_id = param[0]; diff --git a/drivers/input/mouse/trackpoint.h b/drivers/input/mouse/trackpoint.h index 3e03cdb3944984..2aa76311e40043 100644 --- a/drivers/input/mouse/trackpoint.h +++ b/drivers/input/mouse/trackpoint.h @@ -30,6 +30,7 @@ #define TP_VARIANT_NXP 0x04 #define TP_VARIANT_JYT_SYNAPTICS 0x05 #define TP_VARIANT_SYNAPTICS 0x06 +#define TP_VARIANT_JYT_NDT 0x07 /* * Commands From d48ea86919434695da12d280dccab72b094397e1 Mon Sep 17 00:00:00 2001 From: Youssef Samir Date: Fri, 6 Nov 2026 20:44:34 +0100 Subject: [PATCH 0526/2102] accel/qaic: Harden checks in BO execute and wait IOCTLs send_bo_list_to_device() does not validate if the BOs the user passes through DRM_QAIC_EXECUTE_BO and DRM_QAIC_PARTIAL_EXECUTE_BO IOCTLs are attached to the DBC provided. This allows the user to slice and attach BOs to one DBC, and execute them over another DBC. The same case applies for qaic_wait_bo_ioctl() as well, as it neither checks if the BO is sliced, nor if it is attached to the passed DBC. Fixes: ff13be830333 ("accel/qaic: Add datapath") Signed-off-by: Youssef Samir Reviewed-by: Jeff Hugo [jhugo: Fix minor typos in commit text] Signed-off-by: Jeff Hugo Link: https://patch.msgid.link/20261106194434.4062205-1-youssef.abdulrahman@oss.qualcomm.com --- drivers/accel/qaic/qaic_data.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/drivers/accel/qaic/qaic_data.c b/drivers/accel/qaic/qaic_data.c index ee35e13091b308..be3ceb8c51a09d 100644 --- a/drivers/accel/qaic/qaic_data.c +++ b/drivers/accel/qaic/qaic_data.c @@ -1256,6 +1256,11 @@ static int send_bo_list_to_device(struct qaic_device *qdev, struct drm_file *fil goto unlock_bo; } + if (bo->dbc->id != dbc->id) { + ret = -EINVAL; + goto unlock_bo; + } + if (is_partial && pexec[i].resize > bo->base.size) { ret = -EINVAL; goto unlock_bo; @@ -1769,6 +1774,17 @@ int qaic_wait_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file } bo = to_qaic_bo(obj); + + if (!bo->sliced) { + ret = -EINVAL; + goto put_obj; + } + + if (bo->dbc->id != dbc->id) { + ret = -EINVAL; + goto put_obj; + } + timeout = args->timeout ? args->timeout : wait_exec_default_timeout_ms; timeout = msecs_to_jiffies(timeout); ret = wait_for_completion_interruptible_timeout(&bo->xfer_done, timeout); From f172beb64c26e2f4f3a1e7e92e6e710241a29c1e Mon Sep 17 00:00:00 2001 From: Jiri Slaby Date: Mon, 2 Nov 2026 07:47:06 +0100 Subject: [PATCH 0527/2102] MAINTAINERS: fix bouncing {sbranden,rjui}@broadcom.com Both emails are bouncing like: Final-Recipient: rfc822; rjui@broadcom.com Action: failed Status: 5.1.3 Diagnostic-Code: smtp; The email account that you tried to reach does not exist. Please try double-checking the recipient's email address for typos or unnecessary spaces. According to Florian, it should be first.lastname@broadcom.com. Signed-off-by: Jiri Slaby (SUSE) Acked-by: Florian Fainelli Link: https://lore.kernel.org/all/688738af-100b-48af-bee1-4bcbe4422f94@broadcom.com Cc: bcm-kernel-feedback-list@broadcom.com Cc: linux-arm-kernel@lists.infradead.org Cc: Scott Branden Cc: Ray Jui Link: https://lore.kernel.org/r/510bf9b037c522ccfba270926c95170291115ef3.1793602003.git.jirislaby@kernel.org Signed-off-by: Florian Fainelli --- MAINTAINERS | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index 222b7fc2c3aab8..a39978e88cc278 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5328,8 +5328,8 @@ F: drivers/iommu/generic_pt/fmt/*bcm2712* BROADCOM BCM281XX/BCM11XXX/BCM216XX ARM ARCHITECTURE M: Florian Fainelli -M: Ray Jui -M: Scott Branden +M: Ray Jui +M: Scott Branden R: Broadcom internal kernel review list S: Maintained T: git https://github.com/broadcom/mach-bcm @@ -5626,8 +5626,8 @@ F: drivers/net/mdio/mdio-bcm-unimac.c F: include/linux/platform_data/mdio-bcm-unimac.h BROADCOM IPROC ARM ARCHITECTURE -M: Ray Jui -M: Scott Branden +M: Ray Jui +M: Scott Branden R: Broadcom internal kernel review list L: linux-arm-kernel@lists.infradead.org (moderated for non-subscribers) S: Maintained @@ -5664,7 +5664,7 @@ F: drivers/net/ethernet/broadcom/bgmac* F: drivers/net/ethernet/broadcom/unimac.h BROADCOM KONA GPIO DRIVER -M: Ray Jui +M: Ray Jui R: Broadcom internal kernel review list S: Supported F: Documentation/devicetree/bindings/gpio/brcm,kona-gpio.yaml From a56d5a485be4a9d52f0d7b3ed0dc3521367cb986 Mon Sep 17 00:00:00 2001 From: Alex Kazinsky Date: Fri, 13 Nov 2026 15:08:40 +0400 Subject: [PATCH 0528/2102] blk-iocost: Fix overflow in donation weight calculation hweight_after_donation() receives usage as u32, clamped to the range [1, WEIGHT_ONE]. Since WEIGHT_ONE is 1 << 16, multiplying it by usage equal to WEIGHT_ONE wraps the 32-bit unsigned result to zero before it is passed to div64_s64(). This makes new_hwi zero, which is then clamped to 1, incorrectly reducing the cgroup's in-use weight to the minimum. Cast WEIGHT_ONE to s64 before multiplication to preserve the full product. Found by Linux Verification Center (linuxtesting.org) with SVACE static analysis tool. Fixes: f1de2439ec43 ("blk-iocost: revamp donation amount determination") Cc: stable@vger.kernel.org Signed-off-by: Alex Kazinsky Acked-by: Tejun Heo Link: https://patch.msgid.link/20261113110842.4189035-1-a.kazinsky@ideco.ru Signed-off-by: Jens Axboe --- block/blk-iocost.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/block/blk-iocost.c b/block/blk-iocost.c index 1c1025157d8e48..0ffe34bd95b739 100644 --- a/block/blk-iocost.c +++ b/block/blk-iocost.c @@ -1853,7 +1853,8 @@ static u32 hweight_after_donation(struct ioc_gq *iocg, u32 old_hwi, u32 hwm, delta = div64_s64(WEIGHT_ONE * (now->vnow - vtime), now->vnow - ioc->period_at_vtime); target = WEIGHT_ONE * MARGIN_TARGET_PCT / 100; - new_hwi = div64_s64(WEIGHT_ONE * usage, WEIGHT_ONE - target + delta); + new_hwi = div64_s64((s64)WEIGHT_ONE * usage, + WEIGHT_ONE - target + delta); return clamp_t(s64, new_hwi, 1, hwm); } From d2a64291eec3327cf5421cf228e8cbc6d1dd368f Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Fri, 13 Nov 2026 08:33:19 -0700 Subject: [PATCH 0529/2102] io_uring: don't run canceled local work from a foreign mm on release Since commit 89baa3154a72 ("io_uring: run cancelations synchronously on ring release"), the task dropping the last reference to a ring runs the first cancelation pass itself. For DEFER_TASKRUN, that includes running the pending local work in cancel mode. That task need not be the one that submitted the requests, a forked child holding an inherited ring fd is one example. Only run canceled local work from a task that shares the mm of the submitter, or from a kthread like io_ring_exit_work() where such copies fail. Reported-by: Yingjie Wang Fixes: 89baa3154a72 ("io_uring: run cancelations synchronously on ring release") Signed-off-by: Jens Axboe --- io_uring/io_uring.c | 4 ++++ io_uring/tw.c | 7 ++++--- io_uring/tw.h | 11 +++++++++++ 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/io_uring/io_uring.c b/io_uring/io_uring.c index 5db57bf675f0e7..39bb18b96cb996 100644 --- a/io_uring/io_uring.c +++ b/io_uring/io_uring.c @@ -2550,6 +2550,10 @@ static __cold void io_ring_ctx_wait_inflight(struct io_ring_ctx *ctx) /* Only wait if this task has attached to the ring */ if (!tctx || !xa_load(&tctx->xa, (unsigned long)ctx)) return; + /* Requests may sit in local work that only exit work can run */ + if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) && + !io_local_work_cancel_allowed(ctx)) + return; if (atomic_read(&tctx->in_cancel)) return; diff --git a/io_uring/tw.c b/io_uring/tw.c index 0b5066f9722450..b4a9e28ce7794c 100644 --- a/io_uring/tw.c +++ b/io_uring/tw.c @@ -286,10 +286,11 @@ void __cold io_cancel_local_task_work(struct io_ring_ctx *ctx) * The work list consumer side is serialized by ->uring_lock, see * __io_run_local_work(). Grab it to guard against racing with normal * task_work running, as the task may be exiting. The ring is going - * away, run the entries in cancel mode right here - the callers - * provide the same process context the per-ctx fallback work that - * they were previously punted to ran in. + * away, run the entries in cancel mode right here, if allowed. */ + if (!io_local_work_cancel_allowed(ctx)) + return; + guard(mutex)(&ctx->uring_lock); while (!mpscq_empty(&ctx->work_list)) { diff --git a/io_uring/tw.h b/io_uring/tw.h index 3ade5ad577fda5..6bc69a234f0531 100644 --- a/io_uring/tw.h +++ b/io_uring/tw.h @@ -88,6 +88,17 @@ static inline int io_run_task_work(void) return ret; } +/* + * Canceled local work may still copy to user memory. Only run it from a kthread, + * where such copies fail, or from a task that shares the mm of the submitter. + */ +static inline bool io_local_work_cancel_allowed(struct io_ring_ctx *ctx) +{ + struct task_struct *tsk = ctx->submitter_task; + + return !current->mm || (tsk && current->mm == READ_ONCE(tsk->mm)); +} + static inline bool io_local_work_pending(struct io_ring_ctx *ctx) { return !mpscq_empty(&ctx->work_list); From 29dfa436bc488056a84ee423ba82336db453e2a6 Mon Sep 17 00:00:00 2001 From: Vladimir Petrzhikovskii Date: Tue, 10 Nov 2026 16:38:27 +0100 Subject: [PATCH 0530/2102] virtio_net: check RX buffer length before DMA sync An RX queue that uses the DMA API (rq->use_page_pool_dma, for example with VIRTIO_F_ACCESS_PLATFORM) syncs each received buffer with page_pool_dma_sync_for_cpu() using the length the device wrote to the used ring, and checks that length against the posted buffer only after the sync. With SWIOTLB bouncing (swiotlb=force, or a confidential-computing guest), the sync copies from the shared bounce buffer into the guest's private page, so an oversized length also copies the bytes the device wrote past the posted buffer over the neighbouring page pool fragments. The later check drops the packet, but the copy has already happened. A malicious device, such as a host the confidential guest does not trust, can overwrite guest kernel memory next to an RX buffer with bytes it chooses, which is enough to take an unprivileged guest process to root. Check the length before the sync in the per-fragment loops. receive_buf() has to sync the header before the length check, because the mergeable error path reads num_buffers from it, so limit that sync to the posted length. A device that reports correct lengths sees no change. The driver has synced with the device's length since commit 295525e29a5b ("virtio_net: merge dma operations when filling mergeable buffers"), at first in virtnet_rq_unmap(). Commit 24fbd3967f3f ("virtio_net: add page_pool support for buffer allocation") moved the sync to the page_pool call sites that this patch changes, so the patch applies to v7.1 and later. Older kernels need a separate backport that limits the sync in virtnet_rq_unmap(). Found by an LLM code review agent auditing users of the DMA API; the fix and this changelog were also written with an LLM coding assistant and reviewed by us. Reproduced in QEMU with swiotlb=force and iommu_platform=on, a test-only device change that reports a used length 64 bytes past the posted buffer and writes a marker there, and a guest kprobe module that reads the buffer after the sync: without this patch the marker reaches the guest page for small and mergeable buffers; with it the packets are dropped and counted in rx_length_errors. The virtio_net selftest basic_features.sh passes with and without mergeable buffers. Fixes: 295525e29a5b ("virtio_net: merge dma operations when filling mergeable buffers") Cc: stable@vger.kernel.org Co-developed-by: Nikolai Kalinin Signed-off-by: Nikolai Kalinin Signed-off-by: Vladimir Petrzhikovskii Link: https://patch.msgid.link/20261110-b4-virtionet-rxlen-v2-1-6ec5aa0edf9f@dfb.sh Signed-off-by: Jakub Kicinski --- drivers/net/virtio_net.c | 63 +++++++++++++++++++++++++++------------- 1 file changed, 43 insertions(+), 20 deletions(-) diff --git a/drivers/net/virtio_net.c b/drivers/net/virtio_net.c index ed20e76fbc4c79..28b84de8615375 100644 --- a/drivers/net/virtio_net.c +++ b/drivers/net/virtio_net.c @@ -792,19 +792,32 @@ static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx) return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1); } -static int check_mergeable_len(struct net_device *dev, void *mrg_ctx, - unsigned int len) +/* Length of the mergeable buffer that add_recvbuf_mergeable() posted. */ +static unsigned int mergeable_ctx_to_buflen(void *mrg_ctx) { - unsigned int headroom, tailroom, room, truesize; + unsigned int headroom, tailroom, room; - truesize = mergeable_ctx_to_truesize(mrg_ctx); headroom = mergeable_ctx_to_headroom(mrg_ctx); tailroom = headroom ? sizeof(struct skb_shared_info) : 0; room = SKB_DATA_ALIGN(headroom + tailroom); - if (len > truesize - room) { - pr_debug("%s: rx error: len %u exceeds truesize %lu\n", - dev->name, len, (unsigned long)(truesize - room)); + return mergeable_ctx_to_truesize(mrg_ctx) - room; +} + +/* Length of the small buffer that add_recvbuf_small() posts. */ +static unsigned int small_buflen(const struct virtnet_info *vi) +{ + return vi->hdr_len + GOOD_PACKET_LEN; +} + +static int check_mergeable_len(struct net_device *dev, void *mrg_ctx, + unsigned int len) +{ + unsigned int buflen = mergeable_ctx_to_buflen(mrg_ctx); + + if (len > buflen) { + pr_debug("%s: rx error: len %u exceeds buffer length %u\n", + dev->name, len, buflen); DEV_STATS_INC(dev, rx_length_errors); return -1; } @@ -1797,15 +1810,15 @@ static struct page *xdp_linearize_page(struct net_device *dev, p = virt_to_head_page(buf); off = buf - page_address(p); - if (rq->use_page_pool_dma) - page_pool_dma_sync_for_cpu(rq->page_pool, p, - off, buflen); - if (check_mergeable_len(dev, ctx, buflen)) { page_pool_put_page(rq->page_pool, p, -1, true); goto err_buf; } + if (rq->use_page_pool_dma) + page_pool_dma_sync_for_cpu(rq->page_pool, p, + off, buflen); + /* guard against a misconfigured or uncooperative backend that * is sending packet larger than the MTU. */ @@ -2165,15 +2178,15 @@ static int virtnet_build_xdp_buff_mrg(struct net_device *dev, page = virt_to_head_page(buf); offset = buf - page_address(page); - if (rq->use_page_pool_dma) - page_pool_dma_sync_for_cpu(rq->page_pool, page, - offset, len); - if (check_mergeable_len(dev, ctx, len)) { page_pool_put_page(rq->page_pool, page, -1, true); goto err; } + if (rq->use_page_pool_dma) + page_pool_dma_sync_for_cpu(rq->page_pool, page, + offset, len); + truesize = mergeable_ctx_to_truesize(ctx); xdp_frags_truesz += truesize; @@ -2446,15 +2459,15 @@ static struct sk_buff *receive_mergeable(struct net_device *dev, u64_stats_add(&stats->bytes, len); page = virt_to_head_page(buf); + if (check_mergeable_len(dev, ctx, len)) + goto err_skb; + if (rq->use_page_pool_dma) { offset = buf - page_address(page); page_pool_dma_sync_for_cpu(rq->page_pool, page, offset, len); } - if (check_mergeable_len(dev, ctx, len)) - goto err_skb; - truesize = mergeable_ctx_to_truesize(ctx); curr_skb = virtnet_skb_append_frag(rq, head_skb, curr_skb, page, buf, len, truesize); @@ -2574,12 +2587,22 @@ static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq, /* Sync the memory before touching anything through buf, * unless virtio core did it already. + * + * len comes from the device and is checked against the buffer + * only later, so never sync past the buffer posted to the device. + * The sync still covers the header, which receive_buf() and the + * mergeable drop path read. Big buffers never come from the page + * pool, so a buffer here is either mergeable or small. */ if (rq->use_page_pool_dma) { struct page *page = virt_to_head_page(buf); int offset = buf - page_address(page); + unsigned int buflen = vi->mergeable_rx_bufs ? + mergeable_ctx_to_buflen(ctx) : + small_buflen(vi); - page_pool_dma_sync_for_cpu(rq->page_pool, page, offset, len); + page_pool_dma_sync_for_cpu(rq->page_pool, page, offset, + min(len, buflen)); } /* About the flags below: @@ -2655,7 +2678,7 @@ static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq, buf += VIRTNET_RX_PAD + xdp_headroom; ctx = mergeable_len_to_ctx(alloc_len, xdp_headroom); - err = virtnet_rq_submit(rq, buf, vi->hdr_len + GOOD_PACKET_LEN, ctx, gfp); + err = virtnet_rq_submit(rq, buf, small_buflen(vi), ctx, gfp); if (err < 0) page_pool_put_page(rq->page_pool, virt_to_head_page(buf), -1, false); From aa40afa831ebfe45e40a23721711059f2ac584d4 Mon Sep 17 00:00:00 2001 From: Hyunwoo Kim Date: Tue, 10 Nov 2026 23:04:44 +0900 Subject: [PATCH 0531/2102] tcp: fix NULL pointer dereference when restarting a Fast Open listener When a valid RST is received for a Fast Open child accepted before the three-way handshake completes, reqsk_fastopen_remove() adds the request_sock to the listener's RST list if the listener is in TCP_LISTEN. An application can call shutdown(SHUT_RD) on a listener socket. inet_csk_listen_stop() checks rskq_rst_head without holding fastopenq.lock. If rskq_rst_head is NULL, it does not acquire the lock and therefore does not synchronize with an insertion by reqsk_fastopen_remove() after that function has passed the TCP_LISTEN check. The more likely outcome of this race, even without a subsequent listen(), is a leak. If reqsk_fastopen_remove() inserts a request_sock after inet_csk_listen_stop() observes an empty list and returns, the request_sock is stranded in rskq_rst_head and keeps a reference on the listener. The socket is already in TCP_CLOSE, so a subsequent close() does not call inet_csk_listen_stop() again. If listen() is called again on the same socket before the delayed list insertion, the insertion can overlap the queue initialization in reqsk_queue_alloc(). If it occurs after rskq_rst_head is set to NULL but before rskq_rst_tail is set to NULL, rskq_rst_head points to the request_sock while rskq_rst_tail is NULL. When a valid RST is later received for another accepted Fast Open child, rskq_rst_head is not NULL, so reqsk_fastopen_remove() attempts to write the request_sock pointer to rskq_rst_tail->dl_next while rskq_rst_tail is NULL. KASAN reports: BUG: KASAN: null-ptr-deref in reqsk_fastopen_remove+0x147/0x210 Write of size 8 at addr 0000000000000088 by task swapper/3/0 ... Call Trace: ... reqsk_fastopen_remove+0x147/0x210 tcp_check_req+0xa70/0x1060 ... tcp_rcv_state_process+0x1cb/0x2ae0 ... tcp_v4_do_rcv+0x1fe/0x740 tcp_v4_rcv+0x1744/0x2070 ... ip_protocol_deliver_rcu+0x5c/0x280 ip_local_deliver_finish+0x171/0x330 ip_local_deliver+0x107/0x370 ... To widen the race window, the issue was reproduced after adding mdelay(3000) immediately after reqsk_fastopen_remove() checks that the listener is in TCP_LISTEN and immediately after reqsk_queue_alloc() sets rskq_rst_head to NULL. Make inet_csk_listen_stop() acquire fastopenq.lock regardless of the value of rskq_rst_head and detach the list while holding the lock. With this synchronization, reqsk_fastopen_remove() either inserts the request_sock before inet_csk_listen_stop() acquires the lock, in which case inet_csk_listen_stop() reclaims it, or sees that the listener is not in TCP_LISTEN and does not insert anything. Fixes: 0536fcc039a8 ("tcp: prepare fastopen code for upcoming listener changes") Cc: stable@vger.kernel.org Signed-off-by: Hyunwoo Kim Reviewed-by: Kuniyuki Iwashima Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/avMkfJrXhCFXn8M_@v4bel Signed-off-by: Jakub Kicinski --- net/ipv4/inet_connection_sock.c | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/net/ipv4/inet_connection_sock.c b/net/ipv4/inet_connection_sock.c index 6c079929e06f69..ca3057192e6dae 100644 --- a/net/ipv4/inet_connection_sock.c +++ b/net/ipv4/inet_connection_sock.c @@ -1533,17 +1533,15 @@ void inet_csk_listen_stop(struct sock *sk) if (!has_current_bpf_ctx()) cond_resched(); } - if (queue->fastopenq.rskq_rst_head) { - /* Free all the reqs queued in rskq_rst_head. */ - spin_lock_bh(&queue->fastopenq.lock); - req = queue->fastopenq.rskq_rst_head; - queue->fastopenq.rskq_rst_head = NULL; - spin_unlock_bh(&queue->fastopenq.lock); - while (req != NULL) { - next = req->dl_next; - reqsk_put(req); - req = next; - } + /* Free all the reqs queued in rskq_rst_head. */ + spin_lock_bh(&queue->fastopenq.lock); + req = queue->fastopenq.rskq_rst_head; + queue->fastopenq.rskq_rst_head = NULL; + spin_unlock_bh(&queue->fastopenq.lock); + while (req != NULL) { + next = req->dl_next; + reqsk_put(req); + req = next; } WARN_ON_ONCE(sk->sk_ack_backlog); } From 109d5fda6c07649d4bb9270fd99f5c75e3e49fde Mon Sep 17 00:00:00 2001 From: Martin Wetterwald Date: Thu, 22 Oct 2026 10:29:24 +0200 Subject: [PATCH 0532/2102] platform/raspberrypi: vchiq: register bus at subsys_initcall Since 6.19-rc1, with CONFIG_BCM2835_VCHIQ=y and CONFIG_SND_BCM2835=y (both builtin), the sound cards bcm2835_headphones and bcm2835_hdmi are not detected anymore (vc4-hdmi is not affected). dmesg shows: Driver 'bcm2835-audio' was unable to register with bus_type 'vchiq-bus' because the bus was not initialized. Since the VCHIQ interface was moved out of staging, its bus is no longer guaranteed to be registered before its client drivers. bcm2835-audio, still in drivers/staging, registers at device_initcall level and now runs first. Register the bus and the platform driver at subsys_initcall so the bus exists before any client driver, independently of link order. The platform driver probe already returns -EPROBE_DEFER while the firmware is not ready, so probing earlier is safe. When built as modules, this is equivalent to module_init() and nothing changes. Tested on Raspberry Pi 1B rev2, 1B+, 2B, 3B and 4B with VCHIQ and bcm2835-audio both builtin and both as modules. Cc: stable@vger.kernel.org Fixes: aa125180c673 ("platform/raspberrypi: Destage VCHIQ interface") Reported-by: Martin Wetterwald Closes: https://lore.kernel.org/r/CAFERDQ0FpdVvA5VJxOyRAE_pgxnPVmFx1tkZio5R272j6Bs4tg@mail.gmail.com/ Reviewed-by: Jai Luthra Tested-by: Gaston Gonzalez # Raspberry Pi Zero Signed-off-by: Martin Wetterwald Link: https://lore.kernel.org/r/20261022082927.59030-1-martin@wetterwald.eu Signed-off-by: Florian Fainelli --- drivers/platform/raspberrypi/vchiq-interface/vchiq_arm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/platform/raspberrypi/vchiq-interface/vchiq_arm.c b/drivers/platform/raspberrypi/vchiq-interface/vchiq_arm.c index dae1fc0fea2925..8823d9526fbeb2 100644 --- a/drivers/platform/raspberrypi/vchiq-interface/vchiq_arm.c +++ b/drivers/platform/raspberrypi/vchiq-interface/vchiq_arm.c @@ -1462,7 +1462,7 @@ static int __init vchiq_driver_init(void) return ret; } -module_init(vchiq_driver_init); +subsys_initcall(vchiq_driver_init); static void __exit vchiq_driver_exit(void) { From 603b4fd69b4e77770761ea03451e2164186f8590 Mon Sep 17 00:00:00 2001 From: Vineet Gupta Date: Thu, 24 Sep 2026 21:16:00 -0700 Subject: [PATCH 0533/2102] ARC: io: work around GCC PR127718 in __raw_write{w,l}() The __raw_write{w,l}() accessors use inline asm with an "m" operand for the store destination. GCC's ARC backend lets "m" match any legitimate address, including the register-indexed [b,c] forms that only loads support: stores only have [reg], [reg,s9] and [limm] addressing. With newer GCC (late-combine in GCC 15, combine in GCC 16), a writew() with a scaled, non-constant offset gets stw.as r2,[r0,r1] which the assembler rejects: Error: inappropriate arguments for opcode 'stw' With GCC 16 this breaks even hsdk_defconfig (drivers/net/pcs/ pcs-xpcs-plat.c) and axs101_defconfig. allyesconfig additionally trips in drivers/pinctrl/renesas/pinctrl-rza2.c and drivers/video/fbdev/ s3c-fb.c. Work around it by passing the address in a register and using a fixed [%1] address in the asm template, so the compiler can't pick an addressing mode that stores don't support. This is the minimal fix. The next patch drops the inline asm altogether. Link: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=127718 Cc: stable@vger.kernel.org Signed-off-by: Vineet Gupta --- arch/arc/include/asm/io.h | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/arch/arc/include/asm/io.h b/arch/arc/include/asm/io.h index 00171a212b3cb2..b4a3393d1bdca4 100644 --- a/arch/arc/include/asm/io.h +++ b/arch/arc/include/asm/io.h @@ -133,10 +133,14 @@ static inline void __raw_writeb(u8 b, volatile void __iomem *addr) #define __raw_writew __raw_writew static inline void __raw_writew(u16 s, volatile void __iomem *addr) { + /* + * Not an "m" operand: GCC can pick a register-indexed address for it, + * which ST doesn't support (GCC PR target/127718). + */ __asm__ __volatile__( - " stw%U1 %0, %1 \n" + " stw %0, [%1] \n" : - : "r" (s), "m" (*(volatile u16 __force *)addr) + : "r" (s), "r" (addr) : "memory"); } @@ -144,10 +148,11 @@ static inline void __raw_writew(u16 s, volatile void __iomem *addr) #define __raw_writel __raw_writel static inline void __raw_writel(u32 w, volatile void __iomem *addr) { + /* See __raw_writew() above for why this doesn't use an "m" operand. */ __asm__ __volatile__( - " st%U1 %0, %1 \n" + " st %0, [%1] \n" : - : "r" (w), "m" (*(volatile u32 __force *)addr) + : "r" (w), "r" (addr) : "memory"); } From ab86b62012b9e046b9b7d7f4b637e31eab273549 Mon Sep 17 00:00:00 2001 From: Sergei Nizovtsev Date: Wed, 11 Nov 2026 21:35:52 +0100 Subject: [PATCH 0534/2102] bpf, lsm: Mark backing_file_alloc/free LSM hooks as untrusted The backing_file_alloc and backing_file_free LSM hooks get the backing file as "struct file *backing_file", but its f_path is not populated while they run: - security_backing_file_alloc() is called from init_backing_file() in alloc_empty_backing_file(), before vfs_open() sets f_path, so backing_file->f_path.dentry is NULL; - security_backing_file_free() can run for a backing file whose open failed and whose f_path was already cleared. Neither hook is listed in untrusted_lsm_hooks, so bpf_lsm_is_trusted() lets BPF LSM programs use the argument as a trusted pointer. A program attached to lsm/backing_file_alloc can pass &backing_file->f_path to the trusted-args kfunc bpf_path_d_path(), and d_path() dereferences the NULL dentry on the first open of a file on overlayfs. Add both hooks to untrusted_lsm_hooks, next to file_alloc_security and file_free_security, which are listed there for the same reason. The program above is then rejected at load time with "R1 must be referenced or trusted". Fixes: 6af36aeb147a ("lsm: add backing_file LSM hooks") Signed-off-by: Sergei Nizovtsev Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261111203614.1221188-1-snizovtsev@cloudlinux.com --- kernel/bpf/bpf_lsm.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c index f58dce888ff4a7..f39a3766f2245a 100644 --- a/kernel/bpf/bpf_lsm.c +++ b/kernel/bpf/bpf_lsm.c @@ -411,6 +411,8 @@ BTF_ID(func, bpf_lsm_bpf_map_free) BTF_ID(func, bpf_lsm_bpf_prog_free) BTF_ID(func, bpf_lsm_file_alloc_security) BTF_ID(func, bpf_lsm_file_free_security) +BTF_ID(func, bpf_lsm_backing_file_alloc) +BTF_ID(func, bpf_lsm_backing_file_free) #ifdef CONFIG_SECURITY_NETWORK BTF_ID(func, bpf_lsm_sk_alloc_security) BTF_ID(func, bpf_lsm_sk_free_security) From 9ed19503a7b34e1ffb2b81236843204c473b0ae0 Mon Sep 17 00:00:00 2001 From: Yang Xiuwei Date: Sat, 14 Nov 2026 12:11:23 +0800 Subject: [PATCH 0535/2102] io_uring: fail soft links on negative IOU_COMPLETE results Handlers such as fsync return IOU_COMPLETE with a negative cqe.res. The old io_req_complete() path called req_set_fail() for res < 0. After completions moved into the core, that check was dropped, so IOSQE_IO_LINK dependents kept running after the head failed. Fixes: 97b388d70b53 ("io_uring: handle completions in the core") Signed-off-by: Yang Xiuwei Link: https://patch.msgid.link/20261114041123.109163-1-yangxiuwei@kylinos.cn Signed-off-by: Jens Axboe --- io_uring/io_uring.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/io_uring/io_uring.c b/io_uring/io_uring.c index 39bb18b96cb996..be5a4f9505e09d 100644 --- a/io_uring/io_uring.c +++ b/io_uring/io_uring.c @@ -1537,9 +1537,11 @@ static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags) ret = __io_issue_sqe(req, issue_flags, def); if (ret == IOU_COMPLETE) { - /* not all handlers take care of the internal restart codes */ - if (unlikely(req->cqe.res <= -ERESTARTSYS)) - req->cqe.res = io_fixup_restart_res(req->cqe.res); + if (unlikely(req->cqe.res < 0)) { + if (req->cqe.res <= -ERESTARTSYS) + req->cqe.res = io_fixup_restart_res(req->cqe.res); + req_set_fail(req); + } if (issue_flags & IO_URING_F_COMPLETE_DEFER) io_req_complete_defer(req); else From 9a7cbe50dd95594d6fb3c57b8454ace58d8d8d0a Mon Sep 17 00:00:00 2001 From: Yang Xiuwei Date: Sat, 14 Nov 2026 15:22:45 +0800 Subject: [PATCH 0536/2102] io_uring/futex: fail soft links when cancelling a wait __io_futex_cancel() completes the request with -ECANCELED but does not call req_set_fail(). IOSQE_IO_LINK dependents then still run. Fixes: 194bb58c6090 ("io_uring: add support for futex wake and wait") Signed-off-by: Yang Xiuwei Link: https://patch.msgid.link/20261114072246.741950-2-yangxiuwei@kylinos.cn Signed-off-by: Jens Axboe --- io_uring/futex.c | 1 + 1 file changed, 1 insertion(+) diff --git a/io_uring/futex.c b/io_uring/futex.c index 9e4e63ee7bc151..615eaa9104b143 100644 --- a/io_uring/futex.c +++ b/io_uring/futex.c @@ -107,6 +107,7 @@ static bool __io_futex_cancel(struct io_kiocb *req) } hlist_del_init(&req->hash_node); + req_set_fail(req); io_req_set_res(req, -ECANCELED, 0); io_req_task_work_add(req); return true; From 4d3db66c5363dcf42c3d43ebaea330ac2d1888bb Mon Sep 17 00:00:00 2001 From: Yang Xiuwei Date: Sat, 14 Nov 2026 15:22:46 +0800 Subject: [PATCH 0537/2102] io_uring/rw: fail soft links on IOPOLL short or error IO io_complete_rw_iopoll() updates cqe.res when the transfer does not match the requested length, but it does not call req_set_fail(). Soft linked requests then still run after a short or failed IOPOLL read or write. Fixes: b66ceaf324b3 ("io_uring: move iopoll reissue into regular IO path") Signed-off-by: Yang Xiuwei Link: https://patch.msgid.link/20261114072246.741950-3-yangxiuwei@kylinos.cn Signed-off-by: Jens Axboe --- io_uring/rw.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/io_uring/rw.c b/io_uring/rw.c index 3a8559ff4dc662..cf20597ba6a814 100644 --- a/io_uring/rw.c +++ b/io_uring/rw.c @@ -606,8 +606,10 @@ static void io_complete_rw_iopoll(struct kiocb *kiocb, long res) if (res == -EAGAIN && io_rw_should_reissue(req)) req->flags |= REQ_F_REISSUE | REQ_F_BL_NO_RECYCLE; - else if (unlikely(final_res != req->cqe.res)) + else if (unlikely(final_res != req->cqe.res)) { + req_set_fail(req); req->cqe.res = final_res; + } /* order with io_iopoll_complete() checking ->iopoll_completed */ smp_store_release(&req->iopoll_completed, 1); From 26b8f029ce5224dd5c5f45a4bc964a209c259914 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 12 Nov 2026 23:53:20 +0100 Subject: [PATCH 0538/2102] mm: limit pagecache folio refcount when mapping pages With large file folios, overflowing the folio mapcount and refcount became possible more easily. For anon folios it is currently not really an issue: each large anon folio can only be mapped once into a process; on 4k kernels it would be more processes than usually allowed on a system, and on 16k or 64k kernels the processes alone would consume hundreds of GiB. Something to be sorted out at some point, but it's not as urgent. Being able to overflow the refcount is not really big news, but it's about time that we do something about it because some modern technology might find ways to abuse it :) One of the enablers for that was commit ddc58f27f9ee ("mm: drop tail page refcounting"), however, file thp support was added later. File folios can be mapped multiple times into the same process, allowing for processes to hold many references to the same folio. As a short-term solution, let's introduce two folio refcount limits: one for ordinary consumers and one for admins. Leave some headroom before the refcount goes negative, which we really don't want (having the mapcount go negative is also not expected). Start reporting SIGBUS and a ratelimited warning if we run into limits. When restoring mappings from migration entries, instead zap the pte/pmd entry. We allow for slightly exceeding the limit to keep things simpler. During fork(), prefer not copying page table entries over failing fork. For fault-around, check in next_uptodate_folio() before trying to lock the folio. Export folio_ref_count_over_limit_slowpath() using EXPORT_SYMBOL_GPL right away so modules can use it through try_get_page(), where we will use it next. Use has_capability_noaudit(current, CAP_SYS_RESOURCE), so filesystem credential overrides do not affect access to the admin reserve, and to not generate auditing messages simply because we access optional reserves. Don't grant access to the admin reserve from kernel threads, from interrupt context, where "current" is just the interrupted task, or with IRQs disabled, as even unaudited capability checks can take locks. This is far from ideal, but better than all easy alternatives we can backport comfortably. For now it fixes the big problem: letting the refcount (+mapcount) go negative and cause trouble. This is only a temporary fix. Keep the mapping checks explicit and separate from reference acquisition: most are expected to disappear when we rework the underlying refcounting. Check order 0 folios as well for consistency: each folio_add_file_rmap*() and folio_dup_file_rmap*() needs a prior check. Adjust the check in folio_get() to just check for invalid refcounts and drop folio_ref_zero_or_close_to_overflow(): we really don't want negative refcounts or negative mapcounts. Convert to VM_WARN_ON_FOLIO as we touch it. Also, just document -EHWPOISON for copy_present_ptes() while at it. Note: When zapping file migration entries, uffd-wp is preserved using PTE markers, but uffd-rwp protection is lost because there is no corresponding marker. try_to_unmap() already has the same problem when unmapping file folios, so we'll happily ignore it. Reported-by: Chris Mason Fixes: 800d8c63b2e9 ("shmem: add huge pages support") Fixes: 99cb0dbd47a1 ("mm,thp: add read-only THP support for (non-shmem) FS") Fixes: 793917d997df ("mm/readahead: Add large folio readahead") Cc: stable@vger.kernel.org Reviewed-by: Jose A. Perez de Azpillaga Acked-by: Zi Yan Reviewed-by: Pedro Falcato Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-1-ad3deef0bd23@kernel.org Signed-off-by: David Hildenbrand (Arm) --- include/linux/mm.h | 36 ++++++++++++++++++++++++++++++++---- mm/filemap.c | 2 ++ mm/folio.c | 26 ++++++++++++++++++++++++++ mm/huge_memory.c | 32 ++++++++++++++++++++++++++++++-- mm/memory.c | 37 +++++++++++++++++++++++++++++++++---- mm/migrate.c | 11 +++++++++++ mm/userfaultfd.c | 4 ++++ 7 files changed, 138 insertions(+), 10 deletions(-) diff --git a/include/linux/mm.h b/include/linux/mm.h index 6af3b7008f1ad1..e948aea60d1992 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -2249,9 +2249,37 @@ vm_fault_t finish_fault(struct vm_fault *vmf); * back into memory. */ -/* 127: arbitrary random number, small enough to assemble well */ -#define folio_ref_zero_or_close_to_overflow(folio) \ - ((unsigned int) folio_ref_count(folio) + 127u <= 127u) +/* Leave separate reserves for administrators and concurrent reference gains. */ +#define FOLIO_REF_COUNT_LIMIT (INT_MAX - (1U << 26)) +#define FOLIO_REF_COUNT_ADMIN_LIMIT (INT_MAX - (1U << 25)) + +bool folio_ref_count_over_limit_slowpath(const struct folio *folio, + unsigned int ref_count); + +/** + * folio_ref_count_over_limit - Check whether to refuse more folio references. + * @folio: The folio. + * + * Check before adding page table mappings or other significant refcount users + * to pagecache folios (!hugetlb), either before acquiring references or + * afterwards with rollback if the operation is refused. + * + * Checking other folios does no harm. + * + * This check is an approximation; we leave some headroom such that concurrent + * increments, batches, temporary references, or other bounded refcount + * consumers are not a problem. + * + * Return: True if the caller should refuse the operation, false otherwise. + */ +static inline bool folio_ref_count_over_limit(const struct folio *folio) +{ + const unsigned int ref_count = folio_ref_count(folio); + + if (likely(ref_count < FOLIO_REF_COUNT_LIMIT)) + return false; + return folio_ref_count_over_limit_slowpath(folio, ref_count); +} /** * folio_get - Increment the reference count on a folio. @@ -2263,7 +2291,7 @@ vm_fault_t finish_fault(struct vm_fault *vmf); */ static inline void folio_get(struct folio *folio) { - VM_BUG_ON_FOLIO(folio_ref_zero_or_close_to_overflow(folio), folio); + VM_WARN_ON_FOLIO(folio_ref_count(folio) <= 0, folio); folio_ref_inc(folio); } diff --git a/mm/filemap.c b/mm/filemap.c index b04be64a5069f4..453d88db5ee207 100644 --- a/mm/filemap.c +++ b/mm/filemap.c @@ -3774,6 +3774,8 @@ static struct folio *next_uptodate_folio(struct xa_state *xas, continue; if (!folio_try_get(folio)) continue; + if (unlikely(folio_ref_count_over_limit(folio))) + goto skip; if (folio_test_locked(folio)) goto skip; /* Has the page moved or been split? */ diff --git a/mm/folio.c b/mm/folio.c index 35e242b48870b0..38046a40a9db52 100644 --- a/mm/folio.c +++ b/mm/folio.c @@ -107,6 +107,32 @@ void __folio_put(struct folio *folio) } EXPORT_SYMBOL(__folio_put); +bool folio_ref_count_over_limit_slowpath(const struct folio *folio, + unsigned int ref_count) +{ + if (ref_count >= FOLIO_REF_COUNT_ADMIN_LIMIT) + goto over_limit; + /* Background threads must not consume admin reserves. */ + if (current->flags & PF_KTHREAD) + goto over_limit; + /* Neither must interrupt contexts on behalf of the interrupted task. */ + if (!in_task()) + goto over_limit; + /* Capability checks are not safe with IRQs disabled. */ + if (irqs_disabled()) + goto over_limit; + /* Use the task's credentials, which filesystem overrides cannot change. */ + if (has_capability_noaudit(current, CAP_SYS_RESOURCE)) + return false; + +over_limit: + pr_warn_ratelimited("folio:%p refcount:%d mapcount:%d mapping:%p index:%#lx reached refcount limit\n", + folio, (int)ref_count, folio_mapcount(folio), + folio_mapping(folio), folio->index); + return true; +} +EXPORT_SYMBOL_GPL(folio_ref_count_over_limit_slowpath); + typedef void (*move_fn_t)(struct lruvec *lruvec, struct folio *folio); static void lru_add(struct lruvec *lruvec, struct folio *folio) diff --git a/mm/huge_memory.c b/mm/huge_memory.c index 2e7f4e4c13d275..7791872f14af70 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -1626,6 +1626,7 @@ static vm_fault_t insert_pmd(struct vm_area_struct *vma, unsigned long addr, { struct mm_struct *mm = vma->vm_mm; pgtable_t pgtable = NULL; + vm_fault_t ret = VM_FAULT_NOPAGE; spinlock_t *ptl; pmd_t entry; @@ -1662,6 +1663,10 @@ static vm_fault_t insert_pmd(struct vm_area_struct *vma, unsigned long addr, if (is_huge_zero_folio(fop.folio)) { entry = pmd_mkspecial(entry); } else { + if (unlikely(folio_ref_count_over_limit(fop.folio))) { + ret = VM_FAULT_SIGBUS; + goto out_unlock; + } folio_get(fop.folio); folio_add_file_rmap_pmd(fop.folio, &fop.folio->page, vma); add_mm_counter(mm, mm_counter_file(fop.folio), HPAGE_PMD_NR); @@ -1688,7 +1693,7 @@ static vm_fault_t insert_pmd(struct vm_area_struct *vma, unsigned long addr, spin_unlock(ptl); if (pgtable) pte_free(mm, pgtable); - return VM_FAULT_NOPAGE; + return ret; } /** @@ -1759,6 +1764,7 @@ static vm_fault_t insert_pud(struct vm_area_struct *vma, unsigned long addr, pud_t *pud, struct folio_or_pfn fop, pgprot_t prot, bool write) { struct mm_struct *mm = vma->vm_mm; + vm_fault_t ret = VM_FAULT_NOPAGE; spinlock_t *ptl; pud_t entry; @@ -1784,6 +1790,10 @@ static vm_fault_t insert_pud(struct vm_area_struct *vma, unsigned long addr, if (fop.is_folio) { entry = folio_mk_pud(fop.folio, vma->vm_page_prot); + if (unlikely(folio_ref_count_over_limit(fop.folio))) { + ret = VM_FAULT_SIGBUS; + goto out_unlock; + } folio_get(fop.folio); folio_add_file_rmap_pud(fop.folio, &fop.folio->page, vma); add_mm_counter(mm, mm_counter_file(fop.folio), HPAGE_PUD_NR); @@ -1799,7 +1809,7 @@ static vm_fault_t insert_pud(struct vm_area_struct *vma, unsigned long addr, update_mmu_cache_pud(vma, addr, pud); out_unlock: spin_unlock(ptl); - return VM_FAULT_NOPAGE; + return ret; } /** @@ -2095,6 +2105,14 @@ int copy_huge_pud(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma if (page) { struct folio *folio = page_folio(page); + if (unlikely(folio_ref_count_over_limit(folio))) { + /* + * VM_MIXEDMAP may contain driver-inserted pages with no + * fault handler to reconstruct the mapping. + */ + ret = (dst_vma->vm_flags & VM_MIXEDMAP) ? -ENOMEM : 0; + goto out_unlock; + } folio_get(folio); /* * TODO: once we support anonymous pages, use @@ -5239,6 +5257,16 @@ void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct folio *folio if (!(pvmw->pmd && !pvmw->pte)) return; + if (!folio_test_anon(folio) && unlikely(folio_ref_count_over_limit(folio))) { + /* Leave the file mapping absent so it can be faulted in. */ + pmd_clear(pvmw->pmd); + if (arch_needs_pgtable_deposit()) + zap_deposited_table(mm, pvmw->pmd); + update_hiwater_rss(mm); + add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR); + return; + } + entry = softleaf_from_pmd(*pvmw->pmd); folio_get(folio); pmde = folio_mk_pmd(folio, READ_ONCE(vma->vm_page_prot)); diff --git a/mm/memory.c b/mm/memory.c index ee792a2c0ccea4..115b994cabfd2a 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -1168,7 +1168,10 @@ static __always_inline void __copy_present_ptes(struct vm_area_struct *dst_vma, * consecutive pages of the same folio by copying them as well. * * Returns -EAGAIN if one preallocated page is required to copy the next PTE. - * Otherwise, returns the number of copied PTEs (at least 1). + * Returns -ENOMEM if the file folio refcount is too high and the PTE must + * be copied. + * Returns -EHWPOISON if copying a page fails. + * Otherwise, returns the number of processed PTEs (at least 1). */ static inline int copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, @@ -1186,6 +1189,20 @@ copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma folio = page_folio(page); + if (!folio_test_anon(folio) && unlikely(folio_ref_count_over_limit(folio))) { + /* + * VM_MIXEDMAP may contain pages inserted by a driver at mmap + * time, with no fault handler to restore a missing PTE. + */ + if (dst_vma->vm_flags & VM_MIXEDMAP) + return -ENOMEM; + if (userfaultfd_pte_rwp(dst_vma, pte)) + return -ENOMEM; + /* Preserve uffd-wp protection when faulting the page back in. */ + cond_install_uffd_wp_ptes(dst_vma, addr, dst_pte, pte, 1); + return 1; + } + /* * If we likely have to copy, just don't bother with batching. Make * sure that the common "small folio" case is as fast as possible @@ -1367,9 +1384,9 @@ copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, /* * If we need a pre-allocated page for this pte, drop the * locks, allocate, and try again. - * If copy failed due to hwpoison in source page, break out. + * Other errors abort the copy after releasing the page table locks. */ - if (unlikely(ret == -EAGAIN || ret == -EHWPOISON)) + if (unlikely(ret < 0)) break; if (unlikely(prealloc)) { /* @@ -1399,7 +1416,7 @@ copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, goto out; } entry.val = 0; - } else if (ret == -EBUSY || unlikely(ret == -EHWPOISON)) { + } else if (ret == -EBUSY || ret == -ENOMEM || unlikely(ret == -EHWPOISON)) { goto out; } else if (ret == -EAGAIN) { prealloc = folio_prealloc(src_mm, src_vma, addr, false); @@ -2474,6 +2491,8 @@ static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte, if (unlikely(is_zero_folio(folio))) { pteval = pte_mkspecial(pteval); } else { + if (unlikely(folio_ref_count_over_limit(folio))) + return -EOVERFLOW; folio_get(folio); pteval = mk_pte(page, prot); if (mkwrite) { @@ -5747,6 +5766,9 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *pa if (unlikely(folio_test_has_hwpoisoned(folio))) return ret; + if (unlikely(folio_ref_count_over_limit(folio))) + return VM_FAULT_SIGBUS; + /* * Archs like ppc64 need additional space to store information * related to pte entry. Use the preallocated table for that. @@ -5801,6 +5823,9 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *pa * @page: The first page to create a PTE for. * @nr: The number of PTEs to create. * @addr: The first address to create a PTE for. + * + * For file mappings, the caller must check folio_ref_count_over_limit() + * before installing PTEs. */ void set_pte_range(struct vm_fault *vmf, struct folio *folio, struct page *page, unsigned int nr, unsigned long addr) @@ -5967,6 +5992,10 @@ vm_fault_t finish_fault(struct vm_fault *vmf) goto fallback; } + if (!is_cow && unlikely(folio_ref_count_over_limit(folio))) { + ret = VM_FAULT_SIGBUS; + goto unlock; + } folio_ref_add(folio, nr_pages - 1); set_pte_range(vmf, folio, page, nr_pages, addr); type = is_cow ? MM_ANONPAGES : mm_counter_file(folio); diff --git a/mm/migrate.c b/mm/migrate.c index 875079464930a4..e6cd83cf32aa16 100644 --- a/mm/migrate.c +++ b/mm/migrate.c @@ -385,6 +385,17 @@ static bool remove_migration_pte(struct folio *folio, try_to_map_unused_to_zeropage(&pvmw, folio, old_pte, idx)) continue; + if (!folio_test_anon(folio) && !folio_test_hugetlb(folio) && + unlikely(folio_ref_count_over_limit(folio))) { + /* File contents remain available for a later fault. */ + pte_clear(vma->vm_mm, pvmw.address, pvmw.pte); + cond_install_uffd_wp_ptes(vma, pvmw.address, + pvmw.pte, old_pte, 1); + update_hiwater_rss(vma->vm_mm); + dec_mm_counter(vma->vm_mm, mm_counter_file(folio)); + continue; + } + folio_get(folio); new = folio_page(folio, idx); pte = mk_pte(new, READ_ONCE(vma->vm_page_prot)); diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index 57650e6f040d1e..14fdbf217f00e3 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -373,6 +373,10 @@ static int mfill_atomic_install_pte(pmd_t *dst_pmd, goto out_unlock; if (page_in_cache) { + if (unlikely(folio_ref_count_over_limit(folio))) { + ret = -ENOMEM; + goto out_unlock; + } folio_add_file_rmap_pte(folio, page, dst_vma); } else { folio_add_new_anon_rmap(folio, dst_vma, dst_addr, RMAP_EXCLUSIVE); From c6c9a4c1c9a1669693330205cb9d86fafd3cf235 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 12 Nov 2026 23:53:21 +0100 Subject: [PATCH 0539/2102] mm: limit pagecache folio refcount when splicing into pipes Similar to mapping pagecache folios into page tables, let's reject additional references when splicing folios into a pipe if the refcount is at its limit. This will prevent more cases of possible folio refcount overflows with large pagecache folios. Introduce folio_get_checked() for checked reference acquisition when the caller already holds a reference. It warns and fails on a non-positive refcount and rejects additional references at the limit. Add __folio_ref_count_over_limit() so folio_get_checked() can reuse the refcount instead of having to read it a second time. Use folio_get_checked() in splice_folio_into_pipe() and fuse_ref_folio(), returning -EFAULT on failure, like we already do for pipe-buffer duplication. Similarly, make try_get_page() use it instead. Likely try_get_page() should be renamed (or removed) later, as it doesn't match the folio_try_get() semantics and is confusing. If we hit the limit after splicing some data, return the number of bytes already spliced. Teach the callers to handle errors, and stop filemap_splice_read() if we only spliced part of a folio, so we don't skip ahead to the next folio: note that we wouldn't run into this scenario before as we always spliced the requested range. The check in try_get_page() also covers pipe-buffer duplication by tee() and partial pipe-to-pipe splicing. Note that we deliberately will not fall back to the slow path of copying the folio, particularly as the folio might have an invalid refcount. If it is ever really required, we can revisit. Fixes: 800d8c63b2e9 ("shmem: add huge pages support") Fixes: 99cb0dbd47a1 ("mm,thp: add read-only THP support for (non-shmem) FS") Fixes: 793917d997df ("mm/readahead: Add large folio readahead") Cc: stable@vger.kernel.org Reviewed-by: Jose A. Perez de Azpillaga Reviewed-by: Pedro Falcato Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-2-ad3deef0bd23@kernel.org Signed-off-by: David Hildenbrand (Arm) --- fs/fuse/dev.c | 4 +++- include/linux/mm.h | 49 ++++++++++++++++++++++++++++++++++++++-------- mm/filemap.c | 26 ++++++++++++++---------- mm/internal.h | 4 ++-- mm/shmem.c | 7 +++++-- 5 files changed, 67 insertions(+), 23 deletions(-) diff --git a/fs/fuse/dev.c b/fs/fuse/dev.c index 3641abb90d6bb3..50f41bb2878323 100644 --- a/fs/fuse/dev.c +++ b/fs/fuse/dev.c @@ -1230,7 +1230,9 @@ static int fuse_ref_folio(struct fuse_copy_state *cs, struct folio *folio, if (cs->nr_segs >= cs->pipe->max_usage) return -EIO; - folio_get(folio); + if (!folio_get_checked(folio)) + return -EFAULT; + err = unlock_request(cs->req); if (err) { folio_put(folio); diff --git a/include/linux/mm.h b/include/linux/mm.h index e948aea60d1992..95d5e9a13e51aa 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -2257,8 +2257,9 @@ bool folio_ref_count_over_limit_slowpath(const struct folio *folio, unsigned int ref_count); /** - * folio_ref_count_over_limit - Check whether to refuse more folio references. + * __folio_ref_count_over_limit - Check whether to refuse more folio references. * @folio: The folio. + * @ref_count: The sampled folio reference count. * * Check before adding page table mappings or other significant refcount users * to pagecache folios (!hugetlb), either before acquiring references or @@ -2272,15 +2273,27 @@ bool folio_ref_count_over_limit_slowpath(const struct folio *folio, * * Return: True if the caller should refuse the operation, false otherwise. */ -static inline bool folio_ref_count_over_limit(const struct folio *folio) +static inline bool __folio_ref_count_over_limit(const struct folio *folio, + unsigned int ref_count) { - const unsigned int ref_count = folio_ref_count(folio); - if (likely(ref_count < FOLIO_REF_COUNT_LIMIT)) return false; return folio_ref_count_over_limit_slowpath(folio, ref_count); } +/** + * folio_ref_count_over_limit - Check whether to refuse more folio references. + * @folio: The folio. + * + * See __folio_ref_count_over_limit(). + * + * Return: True if the caller should refuse the operation, false otherwise. + */ +static inline bool folio_ref_count_over_limit(const struct folio *folio) +{ + return __folio_ref_count_over_limit(folio, folio_ref_count(folio)); +} + /** * folio_get - Increment the reference count on a folio. * @folio: The folio. @@ -2305,15 +2318,35 @@ static inline void get_page(struct page *page) folio_get(folio); } -static inline __must_check bool try_get_page(struct page *page) +/** + * folio_get_checked - Try to acquire a reference to a live folio. + * @folio: The folio. + * + * The caller must already hold a reference to @folio. Warn and fail on a + * non-positive refcount, and refuse additional references at the limit. + * + * Use folio_try_get() for speculative reference acquisition where the + * refcount can legitimately be zero. + * + * Return: True if the refcount was incremented, false otherwise. + */ +static inline __must_check bool folio_get_checked(struct folio *folio) { - page = compound_head(page); - if (WARN_ON_ONCE(page_ref_count(page) <= 0)) + const int ref_count = folio_ref_count(folio); + + if (WARN_ON_ONCE(ref_count <= 0)) + return false; + if (unlikely(__folio_ref_count_over_limit(folio, ref_count))) return false; - page_ref_inc(page); + folio_ref_inc(folio); return true; } +static inline __must_check bool try_get_page(struct page *page) +{ + return folio_get_checked(page_folio(page)); +} + /** * folio_put - Decrement the reference count on a folio. * @folio: The folio. diff --git a/mm/filemap.c b/mm/filemap.c index 453d88db5ee207..f9e34144c53c74 100644 --- a/mm/filemap.c +++ b/mm/filemap.c @@ -3047,10 +3047,11 @@ generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter) EXPORT_SYMBOL(generic_file_read_iter); /* - * Splice subpages from a folio into a pipe. + * Splice subpages from a folio into a pipe. Return the number of bytes spliced, + * or -EFAULT if we cannot splice from the folio. */ -size_t splice_folio_into_pipe(struct pipe_inode_info *pipe, - struct folio *folio, loff_t fpos, size_t size) +ssize_t splice_folio_into_pipe(struct pipe_inode_info *pipe, + struct folio *folio, loff_t fpos, size_t size) { struct page *page; size_t spliced = 0, offset = offset_in_folio(folio, fpos); @@ -3063,13 +3064,15 @@ size_t splice_folio_into_pipe(struct pipe_inode_info *pipe, struct pipe_buffer *buf = pipe_head_buf(pipe); size_t part = min_t(size_t, PAGE_SIZE - offset, size - spliced); + if (!folio_get_checked(folio)) + return spliced ? spliced : -EFAULT; + *buf = (struct pipe_buffer) { .ops = &page_cache_pipe_buf_ops, .page = page, .offset = offset, .len = part, }; - folio_get(folio); pipe->head++; page++; spliced += part; @@ -3094,9 +3097,10 @@ size_t splice_folio_into_pipe(struct pipe_inode_info *pipe, * Return: On success, the number of bytes read will be returned and *@ppos * will be updated if appropriate; 0 will be returned if there is no more data * to be read; -EAGAIN will be returned if the pipe had no space, and some - * other negative error code will be returned on error. A short read may occur - * if the pipe has insufficient space, we reach the end of the data or we hit a - * hole. + * other negative error code will be returned on error; -EFAULT will be returned + * if acquiring a folio reference fails and no data has been spliced. + * A short read may occur if the pipe has insufficient space, we reach the + * end of the data, hit a hole or hit a folio refcount limit. */ ssize_t filemap_splice_read(struct file *in, loff_t *ppos, struct pipe_inode_info *pipe, @@ -3154,7 +3158,7 @@ ssize_t filemap_splice_read(struct file *in, loff_t *ppos, for (i = 0; i < folio_batch_count(&fbatch); i++) { struct folio *folio = fbatch.folios[i]; - size_t n; + ssize_t n; if (folio_pos(folio) >= end_offset) goto out; @@ -3170,13 +3174,15 @@ ssize_t filemap_splice_read(struct file *in, loff_t *ppos, n = min_t(loff_t, len, isize - *ppos); n = splice_folio_into_pipe(pipe, folio, *ppos, n); - if (!n) + if (n <= 0) { + error = n; goto out; + } len -= n; total_spliced += n; *ppos += n; in->f_ra.prev_pos = *ppos; - if (pipe_is_full(pipe)) + if (pipe_is_full(pipe) || *ppos < folio_next_pos(folio)) goto out; } diff --git a/mm/internal.h b/mm/internal.h index a0e0c4f910208c..85cf7becf8588a 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -1274,8 +1274,8 @@ struct migration_target_control { /* * mm/filemap.c */ -size_t splice_folio_into_pipe(struct pipe_inode_info *pipe, - struct folio *folio, loff_t fpos, size_t size); +ssize_t splice_folio_into_pipe(struct pipe_inode_info *pipe, + struct folio *folio, loff_t fpos, size_t size); static inline bool vma_is_single_threaded_private(struct vm_area_struct *vma) { diff --git a/mm/shmem.c b/mm/shmem.c index b8399bb7199789..4d73fbf081f911 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -3744,7 +3744,8 @@ static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos, struct inode *inode = file_inode(in); struct address_space *mapping = inode->i_mapping; struct folio *folio = NULL; - size_t total_spliced = 0, used, npages, n, part; + size_t total_spliced = 0, used, npages, part; + ssize_t n; loff_t isize; int error = 0; @@ -3830,8 +3831,10 @@ static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos, n = splice_zeropage_into_pipe(pipe, *ppos, part); } - if (!n) + if (n <= 0) { + error = n; break; + } len -= n; total_spliced += n; *ppos += n; From 317bd7d28b248fd4d4e14614d7c30b17a36ef4d7 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 12 Nov 2026 23:53:22 +0100 Subject: [PATCH 0540/2102] mm/mmu_gather: flush pending references early before the folio limit When a task zaps mappings (e.g., MADV_DONTNEED), it can drop the PT lock and defer dropping the folio references. In the meantime, page faults can refault pagecache folios, creating more references for the same folios. These deferred references can build up over multiple VMAs. Let's just request a flush after enqueueing folios whose refcount reached a certain threshold. Start flushing well before new references are refused, regardless of the caller's privileges. When returning "true" from __tlb_remove_folio_pages_size(), PTE zapping will flush the TLB before dropping the PT lock, but drop the references afterwards. Refaults can still race with that, but flushing early reduces the risk of letting others hit the limit. This is a temporary measure until we have something better. Reported-by: Chris Mason Fixes: 800d8c63b2e9 ("shmem: add huge pages support") Fixes: 99cb0dbd47a1 ("mm,thp: add read-only THP support for (non-shmem) FS") Fixes: 793917d997df ("mm/readahead: Add large folio readahead") Cc: stable@vger.kernel.org Reviewed-by: Jose A. Perez de Azpillaga Reviewed-by: Lance Yang Reviewed-by: Pedro Falcato Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-3-ad3deef0bd23@kernel.org Signed-off-by: David Hildenbrand (Arm) --- include/asm-generic/tlb.h | 4 ++-- include/linux/mm.h | 1 + mm/memory.c | 4 ++-- mm/mmu_gather.c | 10 ++++++---- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/include/asm-generic/tlb.h b/include/asm-generic/tlb.h index 3f4a180b48f3c0..4bba02fd5d543f 100644 --- a/include/asm-generic/tlb.h +++ b/include/asm-generic/tlb.h @@ -75,8 +75,8 @@ * - __tlb_remove_folio_pages_size() * * __tlb_remove_folio_pages_size() is the basic primitive that queues pages - * for freeing. It will return a boolean indicating if the queue is (now) - * full and a call to tlb_flush_mmu() is required. + * for freeing. It returns true when a call to tlb_flush_mmu() is required, + * either because the queue is full or a folio is near its refcount limit. * * tlb_remove_page() and tlb_remove_page_size() imply the call to * tlb_flush_mmu() when required and has no return value. diff --git a/include/linux/mm.h b/include/linux/mm.h index 95d5e9a13e51aa..12a090d8d07fac 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -2252,6 +2252,7 @@ vm_fault_t finish_fault(struct vm_fault *vmf); /* Leave separate reserves for administrators and concurrent reference gains. */ #define FOLIO_REF_COUNT_LIMIT (INT_MAX - (1U << 26)) #define FOLIO_REF_COUNT_ADMIN_LIMIT (INT_MAX - (1U << 25)) +#define FOLIO_REF_COUNT_FLUSH_LIMIT (INT_MAX - (1U << 27)) bool folio_ref_count_over_limit_slowpath(const struct folio *folio, unsigned int ref_count); diff --git a/mm/memory.c b/mm/memory.c index 115b994cabfd2a..7f019afc35ca07 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -2076,8 +2076,8 @@ static unsigned long zap_pte_range(struct mmu_gather *tlb, pte_unmap_unlock(start_pte, ptl); /* - * If we forced a TLB flush (either due to running out of - * batch buffers or because we needed to flush dirty TLB + * If we forced a TLB flush (either to release batched + * references or because we needed to flush dirty TLB * entries before releasing the ptl), free the batched * memory too. Come back again if we didn't do everything. */ diff --git a/mm/mmu_gather.c b/mm/mmu_gather.c index 9f353f0e2ef4d2..e98397ac577c4e 100644 --- a/mm/mmu_gather.c +++ b/mm/mmu_gather.c @@ -179,10 +179,7 @@ static bool __tlb_remove_folio_pages_size(struct mmu_gather *tlb, #endif batch = tlb->active; - /* - * Add the page and check if we are full. If so - * force a flush. - */ + /* Add the pages before deciding whether we need to flush. */ if (likely(nr_pages == 1)) { batch->encoded_pages[batch->nr++] = encode_page(page, flags); } else { @@ -190,6 +187,11 @@ static bool __tlb_remove_folio_pages_size(struct mmu_gather *tlb, batch->encoded_pages[batch->nr++] = encode_page(page, flags); batch->encoded_pages[batch->nr++] = encode_nr_pages(nr_pages); } + /* Flush pending references well before new references are refused. */ + if (unlikely((unsigned int)folio_ref_count(page_folio(page)) >= + FOLIO_REF_COUNT_FLUSH_LIMIT)) + return true; + /* * Make sure that we can always add another "page" + "nr_pages", * requiring two entries instead of only a single one. From b8ba6cc9943222676d46ac77d3d3de2685a55bf8 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 12 Nov 2026 23:53:23 +0100 Subject: [PATCH 0541/2102] iommufd: fix cleanup when adding memfd folio pins fails folio_add_pins() can fail after memfd_pin_folios() succeeded pinning a folio. Upcoming folio refcount limit checks will make this easier to trigger. Let's fix three problems in the error handling: 1. pfn_reader_release_pins() uses the allocated array size instead of the number of folios returned by memfd_pin_folios(). With large folios, cleanup can unpin uninitialized entries. Remember the number of returned folios and use that during cleanup. 2. pin_memfd_pages() returns on failure without releasing the pins acquired by the current call. Release the per-page pins for folios already expanded into the page array, and the single pins for the remaining folios. 3. pfn_reader_next() returns on failure before updating batch_end_index, even if the batch already contains successfully expanded folios. Update it before propagating the error so cleanup releases those pins as well. Fixes: 92687c793644 ("iommufd: pfn_reader for file mappings") Cc: stable@vger.kernel.org Reviewed-by: Lance Yang Reviewed-by: Jason Gunthorpe Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-4-ad3deef0bd23@kernel.org Signed-off-by: David Hildenbrand (Arm) --- drivers/iommu/iommufd/pages.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/drivers/iommu/iommufd/pages.c b/drivers/iommu/iommufd/pages.c index 2f6153108add73..fcdbde007a9ab5 100644 --- a/drivers/iommu/iommufd/pages.c +++ b/drivers/iommu/iommufd/pages.c @@ -781,6 +781,7 @@ struct pfn_reader_user { struct file *file; struct folio **ufolios; size_t ufolios_len; + unsigned long ufolios_count; unsigned long ufolios_offset; struct folio **ufolios_next; }; @@ -800,6 +801,7 @@ static void pfn_reader_user_init(struct pfn_reader_user *user, user->file = (pages->type == IOPT_ADDRESS_FILE) ? pages->file : NULL; user->ufolios = NULL; user->ufolios_len = 0; + user->ufolios_count = 0; user->ufolios_next = NULL; user->ufolios_offset = 0; } @@ -843,6 +845,7 @@ static long pin_memfd_pages(struct pfn_reader_user *user, unsigned long start, offset >>= PAGE_SHIFT; user->ufolios_next = user->ufolios; + user->ufolios_count = nfolios; user->ufolios_offset = offset; for (i = 0; i < nfolios; i++) { @@ -859,8 +862,12 @@ static long pin_memfd_pages(struct pfn_reader_user *user, unsigned long start, } else { int rc = folio_add_pins(folio, npin - 1); - if (rc) + if (rc) { + unpin_user_pages(user->upages, + upages - user->upages); + unpin_folios(user->ufolios + i, nfolios - i); return rc; + } while (npin--) *upages++ = folio_page(folio, offset++); @@ -1251,14 +1258,14 @@ static int pfn_reader_next(struct pfn_reader *pfns) return -EINVAL; rc = pfn_reader_fill_span(pfns); + pfns->batch_end_index = pfns->batch_start_index + + pfns->batch.total_pfns; if (rc) return rc; if (WARN_ON(!pfns->batch.total_pfns)) return -EINVAL; - pfns->batch_end_index = - pfns->batch_start_index + pfns->batch.total_pfns; if (pfns->batch_end_index == pfns->span.last_used + 1) interval_tree_double_span_iter_next(&pfns->span); @@ -1320,7 +1327,7 @@ static void pfn_reader_release_pins(struct pfn_reader *pfns) if (!user->file) { unpin_user_pages(user->upages + start_index, npages); } else { - long n = user->ufolios_len / sizeof(*user->ufolios); + const unsigned long n = user->ufolios_count; unpin_folios(user->ufolios_next, user->ufolios + n - user->ufolios_next); From 2d9bcd380585abc436f055fbb618b34f98882004 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 12 Nov 2026 23:53:24 +0100 Subject: [PATCH 0542/2102] mm/gup: limit pagecache folio refcount when grabbing references Let's add __folio_ref_count_over_limit() checks in fast and slow GUP before acquiring additional references or pins. Keep it simple and use the check for all folio types. Also propagate try_grab_folio() errors when grabbing additional references in __get_user_pages() and in memfd_pin_folios(), so hitting the limit returns -ENOMEM instead of -EFAULT and -EINVAL, respectively. Keep the existing invalid-refcount warnings. Fixes: 800d8c63b2e9 ("shmem: add huge pages support") Fixes: 99cb0dbd47a1 ("mm,thp: add read-only THP support for (non-shmem) FS") Fixes: 793917d997df ("mm/readahead: Add large folio readahead") Cc: stable@vger.kernel.org Reviewed-by: Jose A. Perez de Azpillaga Reviewed-by: Pedro Falcato Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-5-ad3deef0bd23@kernel.org Signed-off-by: David Hildenbrand (Arm) --- include/linux/mm.h | 11 +++++------ mm/gup.c | 32 +++++++++++++++++++++----------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/include/linux/mm.h b/include/linux/mm.h index 12a090d8d07fac..daf07b2d208f14 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -2266,6 +2266,9 @@ bool folio_ref_count_over_limit_slowpath(const struct folio *folio, * to pagecache folios (!hugetlb), either before acquiring references or * afterwards with rollback if the operation is refused. * + * Also required when pinning folios without a dedicated pincount that use + * GUP_PIN_COUNTING_BIAS. + * * Checking other folios does no harm. * * This check is an approximation; we leave some headroom such that concurrent @@ -2987,12 +2990,8 @@ static inline bool folio_maybe_dma_pinned(struct folio *folio) return atomic_read(&folio->_pincount) > 0; /* - * folio_ref_count() is signed. If that refcount overflows, then - * folio_ref_count() returns a negative value, and callers will avoid - * further incrementing the refcount. - * - * Here, for that overflow case, use the sign bit to count a little - * bit higher via unsigned math, and thus still get an accurate result. + * Use unsigned math so even an unexpected negative refcount is + * treated as possibly pinned. */ return ((unsigned int)folio_ref_count(folio)) >= GUP_PIN_COUNTING_BIAS; diff --git a/mm/gup.c b/mm/gup.c index 2b405cce2ca5ca..7605da0e06d8d7 100644 --- a/mm/gup.c +++ b/mm/gup.c @@ -74,10 +74,14 @@ static inline void sanity_check_pinned_pages(struct page **pages, static inline struct folio *try_get_folio(struct page *page, int refs) { struct folio *folio; + int ref_count; retry: folio = page_folio(page); - if (WARN_ON_ONCE(folio_ref_count(folio) < 0)) + ref_count = folio_ref_count(folio); + if (WARN_ON_ONCE(ref_count < 0)) + return NULL; + if (unlikely(__folio_ref_count_over_limit(folio, ref_count))) return NULL; if (unlikely(!folio_ref_try_add(folio, refs))) return NULL; @@ -140,7 +144,13 @@ static void gup_put_folio(struct folio *folio, int refs, unsigned int flags) int __must_check try_grab_folio(struct folio *folio, int refs, unsigned int flags) { - if (WARN_ON_ONCE(folio_ref_count(folio) <= 0)) + const int ref_count = folio_ref_count(folio); + + if (WARN_ON_ONCE(ref_count <= 0)) + return -ENOMEM; + + if ((flags & (FOLL_GET | FOLL_PIN)) && + unlikely(__folio_ref_count_over_limit(folio, ref_count))) return -ENOMEM; if (unlikely(!(flags & FOLL_PCI_P2PDMA) && folio_is_pci_p2pdma(folio))) @@ -1482,17 +1492,17 @@ static long __get_user_pages(struct mm_struct *mm, struct folio *folio = page_folio(page); /* - * Since we already hold refcount on the - * large folio, this should never fail. + * Grabbing more references can fail once we + * hit folio refcount limits. */ - if (try_grab_folio(folio, page_increm - 1, - gup_flags)) { + ret = try_grab_folio(folio, page_increm - 1, + gup_flags); + if (ret) { /* - * Release the 1st page ref if the - * folio is problematic, fail hard. + * Release the folio reference we + * already took. */ gup_put_folio(folio, 1, gup_flags); - ret = -EFAULT; goto out; } } @@ -3538,10 +3548,10 @@ long memfd_pin_folios(struct file *memfd, loff_t start, loff_t end, break; } - if (try_grab_folio(folio, 1, FOLL_PIN)) { + ret = try_grab_folio(folio, 1, FOLL_PIN); + if (ret) { folio_unlock(folio); folio_batch_release(&fbatch); - ret = -EINVAL; goto err; } From b1ed5a45b994a6473ca1cf34f35a1bf87f1d8e2a Mon Sep 17 00:00:00 2001 From: Jeff Johnson Date: Sat, 14 Nov 2026 08:13:06 -0800 Subject: [PATCH 0543/2102] Revert "wifi: ath10k: Stop unanswered temperature reads" As reported by Nicolas Escande [1] this will break some setups where temperature reporting is supported but there are occasional requests where there isn't a response. Revert this implementation where a single unreported temperature read at any time will stop all future requests. Alternate solutions are being discussed. Link: https://lore.kernel.org/all/DMRPC2GCD51O.S4DMHZFDKRFG@gmail.com/ # [1] Signed-off-by: Jeff Johnson --- drivers/net/wireless/ath/ath10k/core.c | 1 - drivers/net/wireless/ath/ath10k/thermal.c | 9 +-------- drivers/net/wireless/ath/ath10k/thermal.h | 2 -- 3 files changed, 1 insertion(+), 11 deletions(-) diff --git a/drivers/net/wireless/ath/ath10k/core.c b/drivers/net/wireless/ath/ath10k/core.c index a749ae582b0a49..7c2939cbde5f05 100644 --- a/drivers/net/wireless/ath/ath10k/core.c +++ b/drivers/net/wireless/ath/ath10k/core.c @@ -2985,7 +2985,6 @@ int ath10k_core_start(struct ath10k *ar, enum ath10k_firmware_mode mode, clear_bit(ATH10K_FLAG_CRASH_FLUSH, &ar->dev_flags); ar->running_fw = fw; - ar->thermal.broken = false; if (!test_bit(ATH10K_FW_FEATURE_NON_BMI, ar->running_fw->fw_file.fw_features)) { diff --git a/drivers/net/wireless/ath/ath10k/thermal.c b/drivers/net/wireless/ath/ath10k/thermal.c index 9ff7de0abd1297..9bb486f8e92078 100644 --- a/drivers/net/wireless/ath/ath10k/thermal.c +++ b/drivers/net/wireless/ath/ath10k/thermal.c @@ -75,12 +75,6 @@ static ssize_t ath10k_thermal_show_temp(struct device *dev, goto out; } - /* Don't stall every read on firmware that never answers */ - if (ar->thermal.broken) { - ret = -EOPNOTSUPP; - goto out; - } - reinit_completion(&ar->thermal.wmi_sync); ret = ath10k_wmi_pdev_get_temperature(ar); if (ret) { @@ -96,8 +90,7 @@ static ssize_t ath10k_thermal_show_temp(struct device *dev, time_left = wait_for_completion_timeout(&ar->thermal.wmi_sync, ATH10K_THERMAL_SYNC_TIMEOUT_HZ); if (!time_left) { - ath10k_warn(ar, "failed to synchronize thermal read, not asking again until the firmware restarts\n"); - ar->thermal.broken = true; + ath10k_warn(ar, "failed to synchronize thermal read\n"); ret = -ETIMEDOUT; goto out; } diff --git a/drivers/net/wireless/ath/ath10k/thermal.h b/drivers/net/wireless/ath/ath10k/thermal.h index d1fb5b958c37c1..1f4de9fbf2b30b 100644 --- a/drivers/net/wireless/ath/ath10k/thermal.h +++ b/drivers/net/wireless/ath/ath10k/thermal.h @@ -19,8 +19,6 @@ struct ath10k_thermal { /* protected by conf_mutex */ u32 throttle_state; u32 quiet_period; - /* the running firmware did not answer a temperature request */ - bool broken; /* temperature value in Celsius degree * protected by data_lock */ From bd212a6f298841dbc7e74c7726ca5f0e648f322e Mon Sep 17 00:00:00 2001 From: Miri Korenblit Date: Wed, 30 Sep 2026 12:25:04 +0300 Subject: [PATCH 0544/2102] wifi: iwlwifi: trans: don't memset trans::conf when it is still needed Currently, trans::conf is cleared in opmode_leave(), which means that in the rest of the remove() it will be zeroed. But some of the freeing code still needs some data from it, for example the cmd_queue id. For older devices that their cmd_queue id is not 0, it can cause us to free queue 0 as it was a command queue. A command queue is different from a regular queue, the first has its cmd as regular kmalloc'ed memory while a regular queue has it from a kmem_cache, so the two should be freed differently. To avoid that, don't clear the trans::conf, there won't be a new opmode anyway in the device's lifecycle. Reviewed-by: Johannes Berg Link: https://patch.msgid.link/20260930122439.5ea1111fca04.I2214b2bee4d2051f3597d7ab8c7746f521d48cc4@changeid Signed-off-by: Miri Korenblit --- drivers/net/wireless/intel/iwlwifi/iwl-trans.c | 1 - 1 file changed, 1 deletion(-) diff --git a/drivers/net/wireless/intel/iwlwifi/iwl-trans.c b/drivers/net/wireless/intel/iwlwifi/iwl-trans.c index 6ddf4945ed1c37..70effba46c1ca0 100644 --- a/drivers/net/wireless/intel/iwlwifi/iwl-trans.c +++ b/drivers/net/wireless/intel/iwlwifi/iwl-trans.c @@ -432,7 +432,6 @@ void iwl_trans_op_mode_leave(struct iwl_trans *trans) cancel_delayed_work_sync(&trans->restart.wk); trans->op_mode = NULL; - memset(&trans->conf, 0, sizeof(trans->conf)); trans->state = IWL_TRANS_NO_FW; } From 01d682fdd6e3e2427841498d601bacf0f486f7c7 Mon Sep 17 00:00:00 2001 From: Emmanuel Grumbach Date: Wed, 30 Sep 2026 12:25:05 +0300 Subject: [PATCH 0545/2102] wifi: iwlwifi: honor the per-channel 320 MHz regulatory flag When support for the MCC update response version 8 was added, the API change was implemented only partially. That version introduced two new pieces of information about 320 MHz: the global capability REG_CAPA_V5_320MHZ_ALLOWED and a per-channel bit, BIT(12), in the channel flags carried by the response. Only the former was picked up. BIT(12) kept its previous meaning in the driver, NVM_CHANNEL_DC_HIGH, a leftover from old devices that nothing used, so the new bit was silently dropped. The two are not equivalent, the per-channel bit can be more restrictive than the global capability. When that happens, cfg80211 is told that 320 MHz is allowed, mac80211 builds a 320 MHz channel context, and the firmware rejects the resulting PHY_CONTEXT_CMD and asserts with 0x200014FC. Rename the bit to NVM_CHANNEL_320MHZ and set NL80211_RRF_NO_320MHZ for the channels that don't have it, so that we cap the bandwidth at 160 MHz instead of asserting the firmware. The bit is checked in every band, so that a future band that supports 320 MHz is covered as well. Assisted-by: GitHub-Copilot:claude-opus-5 Closes: https://bugzilla.kernel.org/show_bug.cgi?id=221675 Signed-off-by: Emmanuel Grumbach Link: https://patch.msgid.link/20260930122439.08094e4c344f.Ic0a4bf544fd6ebaf1fc62b40bf463bd289e58cf0@changeid Signed-off-by: Miri Korenblit --- .../wireless/intel/iwlwifi/iwl-nvm-parse.c | 6 ++--- .../wireless/intel/iwlwifi/iwl-nvm-parse.h | 7 ++++-- .../wireless/intel/iwlwifi/tests/nvm_parse.c | 24 +++++++++++++++---- 3 files changed, 28 insertions(+), 9 deletions(-) diff --git a/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.c b/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.c index 31badfa35f976b..8c166e0479ebb8 100644 --- a/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.c +++ b/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.c @@ -106,8 +106,6 @@ static const u16 iwl_unii9_nvm_channels[] = { #define IWL_NVM_NUM_CHANNELS_EXT 51 #define IWL_NVM_NUM_CHANNELS_UHB 110 #define IWL_NVM_NUM_CHANNELS_UNII9 ARRAY_SIZE(iwl_unii9_nvm_channels) -#define NUM_2GHZ_CHANNELS 14 -#define NUM_5GHZ_CHANNELS 37 #define FIRST_2GHZ_HT_MINUS 5 #define LAST_2GHZ_HT_PLUS 9 #define N_HW_ADDR_MASK 0xF @@ -280,7 +278,7 @@ static inline void iwl_nvm_print_channel_flags(struct device *dev, u32 level, CHECK_AND_PRINT_I(40MHZ), CHECK_AND_PRINT_I(80MHZ), CHECK_AND_PRINT_I(160MHZ), - CHECK_AND_PRINT_I(DC_HIGH), + CHECK_AND_PRINT_I(320MHZ), CHECK_AND_PRINT_I(VLP), CHECK_AND_PRINT_I(AFC)); #undef CHECK_AND_PRINT_I @@ -1632,6 +1630,8 @@ u32 iwl_nvm_get_regdom_bw_flags(const u16 *nvm_chan, flags |= NL80211_RRF_NO_80MHZ; if (!(nvm_flags & NVM_CHANNEL_160MHZ)) flags |= NL80211_RRF_NO_160MHZ; + if (!(nvm_flags & NVM_CHANNEL_320MHZ)) + flags |= NL80211_RRF_NO_320MHZ; if (!(nvm_flags & NVM_CHANNEL_ACTIVE)) flags |= NL80211_RRF_NO_IR; diff --git a/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.h b/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.h index 9ebb72d3726a5d..7b11682f5d45c1 100644 --- a/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.h +++ b/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.h @@ -10,6 +10,9 @@ #include "iwl-nvm-utils.h" #include "mei/iwl-mei.h" +#define NUM_2GHZ_CHANNELS 14 +#define NUM_5GHZ_CHANNELS 37 + /** * enum iwl_nvm_sbands_flags - modification flags for the channel profiles * @@ -82,7 +85,7 @@ struct iwl_reg_capa { * @NVM_CHANNEL_40MHZ: 40 MHz channel okay * @NVM_CHANNEL_80MHZ: 80 MHz channel okay * @NVM_CHANNEL_160MHZ: 160 MHz channel okay - * @NVM_CHANNEL_DC_HIGH: DC HIGH required/allowed (?) + * @NVM_CHANNEL_320MHZ: 320 MHz channel okay * @NVM_CHANNEL_VLP: client support connection to UHB VLP AP * @NVM_CHANNEL_AFC: client support connection to UHB AFC AP * @NVM_CHANNEL_VLP_AP_NOT_ALLOWED: UHB VLP AP not allowed, @@ -101,7 +104,7 @@ enum iwl_nvm_channel_flags { NVM_CHANNEL_40MHZ = BIT(9), NVM_CHANNEL_80MHZ = BIT(10), NVM_CHANNEL_160MHZ = BIT(11), - NVM_CHANNEL_DC_HIGH = BIT(12), + NVM_CHANNEL_320MHZ = BIT(12), NVM_CHANNEL_VLP = BIT(13), NVM_CHANNEL_AFC = BIT(14), NVM_CHANNEL_VLP_AP_NOT_ALLOWED = BIT(15), diff --git a/drivers/net/wireless/intel/iwlwifi/tests/nvm_parse.c b/drivers/net/wireless/intel/iwlwifi/tests/nvm_parse.c index 853911900bfd2f..5a50807e31817c 100644 --- a/drivers/net/wireless/intel/iwlwifi/tests/nvm_parse.c +++ b/drivers/net/wireless/intel/iwlwifi/tests/nvm_parse.c @@ -2,7 +2,7 @@ /* * KUnit tests for NVM parse * - * Copyright (C) 2025 Intel Corporation + * Copyright (C) 2025-2026 Intel Corporation */ #include #include @@ -12,7 +12,9 @@ MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); static const struct nvm_flag_case { const char *desc; + int ch_idx; u16 nvm_flags; + struct iwl_reg_capa reg_capa; u32 reg_rule_flags; u32 set_reg_rule_flags; u32 clear_reg_rule_flags; @@ -36,6 +38,20 @@ static const struct nvm_flag_case { .clear_reg_rule_flags = NL80211_RRF_ALLOW_6GHZ_VLP_AP | NL80211_RRF_NO_6GHZ_VLP_CLIENT, }, + { + .desc = "Allow 320 MHz on a 6 GHz channel that reports it", + .ch_idx = NUM_2GHZ_CHANNELS + NUM_5GHZ_CHANNELS, + .nvm_flags = NVM_CHANNEL_320MHZ, + .reg_capa = { .allow_320mhz = true, }, + .clear_reg_rule_flags = NL80211_RRF_NO_320MHZ, + }, + { + .desc = "Restrict 320 MHz on a 6 GHz channel without the bit", + .ch_idx = NUM_2GHZ_CHANNELS + NUM_5GHZ_CHANNELS, + .nvm_flags = 0, + .reg_capa = { .allow_320mhz = true, }, + .set_reg_rule_flags = NL80211_RRF_NO_320MHZ, + }, }; KUNIT_ARRAY_PARAM_DESC(nvm_flag, nvm_flag_cases, desc) @@ -43,11 +59,11 @@ KUNIT_ARRAY_PARAM_DESC(nvm_flag, nvm_flag_cases, desc) static void test_nvm_flags(struct kunit *test) { const struct nvm_flag_case *params = test->param_value; - struct iwl_reg_capa reg_capa = {}; u32 flags = 0; - flags = iwl_nvm_get_regdom_bw_flags(NULL, 0, params->nvm_flags, - reg_capa); + flags = iwl_nvm_get_regdom_bw_flags(NULL, params->ch_idx, + params->nvm_flags, + params->reg_capa); if ((params->set_reg_rule_flags & flags) != params->set_reg_rule_flags) KUNIT_FAIL(test, "Expected set bits:0x%08x flags:0x%08x\n", From b1d515352b88395fa7401468e1a60087d55359ff Mon Sep 17 00:00:00 2001 From: Emmanuel Grumbach Date: Wed, 30 Sep 2026 12:25:06 +0300 Subject: [PATCH 0546/2102] wifi: iwlwifi: mvm: don't send LARI_CONFIG_CHANGE to old FW Lari is not supported by 7260. The firmware doesn't understand this command and crashes with BAD_COMMAND. Devices 7260 / 3160 and 7265 that use -17.ucode are affected. Don't sent it to firmwares that are too old to support this command. Closes: https://bugzilla.kernel.org/show_bug.cgi?id=222030 Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Emmanuel Grumbach Link: https://patch.msgid.link/20260930122439.a23d894e48dc.I245ab48bfddddf51e5f2bd4dad7fb316f27b93f5@changeid Signed-off-by: Miri Korenblit --- drivers/net/wireless/intel/iwlwifi/mvm/fw.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/net/wireless/intel/iwlwifi/mvm/fw.c b/drivers/net/wireless/intel/iwlwifi/mvm/fw.c index ae109e3ea141c2..6cee41bb1ffbbb 100644 --- a/drivers/net/wireless/intel/iwlwifi/mvm/fw.c +++ b/drivers/net/wireless/intel/iwlwifi/mvm/fw.c @@ -1553,6 +1553,9 @@ static void iwl_mvm_lari_cfg(struct iwl_mvm *mvm) size_t cmd_size; int ret; + if (mvm->fw->ucode_ver < 26) + return; + /* * LARI_CONFIG_CHANGE triggers a profile update, so send * LARI_CONFIG_EXTENSION first to make sure its data is applied From f77034f1f5b11fa4b2312d21668655fc8bb54145 Mon Sep 17 00:00:00 2001 From: Emmanuel Grumbach Date: Wed, 30 Sep 2026 12:25:07 +0300 Subject: [PATCH 0547/2102] wifi: iwlwifi: mvm: fix VHT NSS reporting on pre-MQ devices iwl_mvm_rx_rx_mpdu() and iwl_mvm_rx_handle_tcm() parse the rate_n_flags they get from struct iwl_rx_phy_info, which is in the version 1 format. There, the number of spatial streams minus one is encoded in bits 4-5, i.e. RATE_VHT_MCS_NSS_MSK, but both of them used RATE_MCS_NSS_MSK. This used to work by accident: RATE_MCS_NSS_MSK was BIT(4), which overlaps the low bit of the version 1 field, and that is enough for our 2x2 devices. Since the version 3 rate format was introduced, RATE_MCS_NSS_MSK is BIT(5), which is always 0 in a version 1 rate, so every received VHT frame is now reported as single stream. On an 8260 this shows up as half the actual rate being reported: rx bitrate: 390.0 MBit/s VHT-MCS 8 80MHz short GI VHT-NSS 1 instead of 780.0 MBit/s with VHT-NSS 2. Devices using the multi-queue RX path are not affected, they convert the rate to the version 3 format before parsing it. Closes: https://bugzilla.kernel.org/show_bug.cgi?id=221685 Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Emmanuel Grumbach Reviewed-by: Johannes Berg Link: https://patch.msgid.link/20260930122439.67a780de1fc6.Ia9429e120ea269c781a36d5fa2fe601c7deb1a39@changeid Signed-off-by: Miri Korenblit --- drivers/net/wireless/intel/iwlwifi/mvm/rx.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/net/wireless/intel/iwlwifi/mvm/rx.c b/drivers/net/wireless/intel/iwlwifi/mvm/rx.c index 8c197a090c2b1a..0be307ae92f6ce 100644 --- a/drivers/net/wireless/intel/iwlwifi/mvm/rx.c +++ b/drivers/net/wireless/intel/iwlwifi/mvm/rx.c @@ -257,7 +257,7 @@ static void iwl_mvm_rx_handle_tcm(struct iwl_mvm *mvm, ARRAY_SIZE(thresh_tpt))) return; thr = thresh_tpt[rate_n_flags & RATE_VHT_MCS_RATE_CODE_MSK]; - thr *= 1 + FIELD_GET(RATE_MCS_NSS_MSK, rate_n_flags); + thr *= 1 + FIELD_GET(RATE_VHT_MCS_NSS_MSK, rate_n_flags); } thr <<= ((rate_n_flags & RATE_MCS_CHAN_WIDTH_MSK_V1) >> @@ -502,7 +502,7 @@ void iwl_mvm_rx_rx_mpdu(struct iwl_mvm *mvm, struct napi_struct *napi, u8 stbc = (rate_n_flags & RATE_MCS_STBC_MSK) >> RATE_MCS_STBC_POS; rx_status->nss = - FIELD_GET(RATE_MCS_NSS_MSK, rate_n_flags) + 1; + FIELD_GET(RATE_VHT_MCS_NSS_MSK, rate_n_flags) + 1; rx_status->rate_idx = rate_n_flags & RATE_VHT_MCS_RATE_CODE_MSK; rx_status->encoding = RX_ENC_VHT; rx_status->enc_flags |= stbc << RX_ENC_FLAG_STBC_SHIFT; From 271e7fdce95854cced921284ba158ed75b666e32 Mon Sep 17 00:00:00 2001 From: Michal Luczaj Date: Sat, 7 Nov 2026 18:58:23 +0100 Subject: [PATCH 0548/2102] selftests/bpf: Remove sockmap update from bpf_iter_unix BPF iterator programs that can update sockmaps will be limited to iter/sockmap. Remove the update from the unix selftest. This reverts commit 997b8483d44c ("selftests/bpf: Extend bpf_iter_unix to attempt deadlocking"). Signed-off-by: Michal Luczaj Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Link: https://patch.msgid.link/20261107-sockmap-update-limit-iter-v3-1-7c0bad1ad036@rbox.co --- tools/testing/selftests/bpf/progs/bpf_iter_unix.c | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/tools/testing/selftests/bpf/progs/bpf_iter_unix.c b/tools/testing/selftests/bpf/progs/bpf_iter_unix.c index 3061b148f3388a..90beada0386d41 100644 --- a/tools/testing/selftests/bpf/progs/bpf_iter_unix.c +++ b/tools/testing/selftests/bpf/progs/bpf_iter_unix.c @@ -7,13 +7,6 @@ char _license[] SEC("license") = "GPL"; -SEC(".maps") struct { - __uint(type, BPF_MAP_TYPE_SOCKMAP); - __uint(max_entries, 1); - __type(key, __u32); - __type(value, __u64); -} sockmap; - static long sock_i_ino(const struct sock *sk) { const struct socket *sk_socket = sk->sk_socket; @@ -82,8 +75,5 @@ int dump_unix(struct bpf_iter__unix *ctx) BPF_SEQ_PRINTF(seq, "\n"); - /* Test for deadlock. */ - bpf_map_update_elem(&sockmap, &(int){0}, sk, 0); - return 0; } From 18f6c47d1097b703814e97c79239ce9dafb160f8 Mon Sep 17 00:00:00 2001 From: Michal Luczaj Date: Sat, 7 Nov 2026 18:58:24 +0100 Subject: [PATCH 0549/2102] bpf, sockmap: Restrict iter-context sockmap updates to iter/sockmap Among tracing progs, allow only iter/sockmap to update sockmaps and sockhashes. Previously, any BPF_TRACE_ITER program could perform these updates, which caused locking issues in specific scenarios [1][2][3]. This tightening is part of the broader effort to lock down the BPF API [4]. [1]: commit 4d328dd69538 ("bpf, sockmap: Fix af_unix iter deadlock") [2]: commit 64c2f93fc325 ("bpf, sockmap: Take state lock for af_unix iter") [3]: https://msgid.link/87echn2fhd.fsf@cloudflare.com [4]: https://msgid.link/akRZ_e7DJh2aP-2i@john-p8 Reported-by: Sashiko Suggested-by: Jakub Sitnicki Signed-off-by: Michal Luczaj Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Link: https://patch.msgid.link/20261107-sockmap-update-limit-iter-v3-2-7c0bad1ad036@rbox.co Closes: https://msgid.link/20260626205814.BAC3C1F000E9@smtp.kernel.org --- kernel/bpf/verifier.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 232551fd7cefdd..9b228ffbe3fe97 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -10526,6 +10526,7 @@ static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) { enum bpf_attach_type eatype = env->prog->expected_attach_type; enum bpf_prog_type type = resolve_prog_type(env->prog); + const char *afname = env->prog->aux->attach_func_name; if (func_id != BPF_FUNC_map_update_elem && func_id != BPF_FUNC_map_delete_elem) @@ -10536,7 +10537,8 @@ static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) */ switch (type) { case BPF_PROG_TYPE_TRACING: - if (eatype == BPF_TRACE_ITER) + if (eatype == BPF_TRACE_ITER && + !strcmp(afname + strlen(BPF_ITER_FUNC_PREFIX), "sockmap")) return true; break; case BPF_PROG_TYPE_SOCK_OPS: From e16c83fa764fa7c533d57d803c1e7ff88b7422ff Mon Sep 17 00:00:00 2001 From: Michal Luczaj Date: Sat, 7 Nov 2026 18:58:25 +0100 Subject: [PATCH 0550/2102] selftests/bpf: Add negative test for sockmap update from non-sockmap iter Iterator-context sockmap updates are now restricted to iter/sockmap. Add a test that attempts an update from iter/unix and expects it to fail. Signed-off-by: Michal Luczaj Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261107-sockmap-update-limit-iter-v3-3-7c0bad1ad036@rbox.co --- .../selftests/bpf/progs/verifier_sockmap_mutate.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c b/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c index 20332a731d4e4f..1516fe1524bba6 100644 --- a/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c +++ b/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c @@ -19,6 +19,12 @@ struct bpf_iter__sockmap { }; } __attribute__((preserve_access_index)); +struct bpf_iter__unix { + union { + struct sock *unix_sk; + }; +} __attribute__((preserve_access_index)); + struct { __uint(type, BPF_MAP_TYPE_SOCKHASH); __uint(max_entries, 1); @@ -113,6 +119,14 @@ int test_trace_iter(struct bpf_iter__sockmap *ctx) return 0; } +SEC("iter/unix") +__failure __msg("cannot update sockmap in this context") +int test_trace_iter_unix(struct bpf_iter__unix *ctx) +{ + test_sockmap_mutate(ctx->unix_sk); + return 0; +} + SEC("raw_tp/kfree") __failure __msg("cannot update sockmap in this context") int test_raw_tp_delete(const void *ctx __always_unused) From c8d1abec647223131a8a81c60445a628c1676e26 Mon Sep 17 00:00:00 2001 From: Michal Luczaj Date: Sat, 7 Nov 2026 18:58:26 +0100 Subject: [PATCH 0551/2102] bpf, docs: Document BPF_ITER_NOSLEEP Commit dfcd17659112 ("bpf: Reject sleepable programs for task_vma iterator") introduced BPF_ITER_NOSLEEP, but did not update the docs. Mention the flag in bpf_iterators.rst. Signed-off-by: Michal Luczaj Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261107-sockmap-update-limit-iter-v3-4-7c0bad1ad036@rbox.co --- Documentation/bpf/bpf_iterators.rst | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Documentation/bpf/bpf_iterators.rst b/Documentation/bpf/bpf_iterators.rst index 72435e32ffa16b..c534215f05de77 100644 --- a/Documentation/bpf/bpf_iterators.rst +++ b/Documentation/bpf/bpf_iterators.rst @@ -351,9 +351,15 @@ The following is the breakdown for each field in struct ``bpf_iter_reg``. the bpf iterator. * - feature - Specifies certain action requests in the kernel BPF iterator - infrastructure. Currently, only BPF_ITER_RESCHED is supported. This means - that the kernel function cond_resched() is called to avoid other kernel - subsystem (e.g., rcu) misbehaving. + infrastructure. + + BPF_ITER_RESCHED + the kernel function cond_resched() is called to avoid other kernel + subsystem (e.g., rcu) misbehaving + + BPF_ITER_NOSLEEP + ``seq_operations::show()`` cannot run sleepable programs + * - seq_info - Specifies the set of seq operations for the BPF iterator and helpers to initialize/free the private data for the corresponding ``seq_file``. From 3164b25576aad2433d75431ee283a41fc849dee0 Mon Sep 17 00:00:00 2001 From: Michal Luczaj Date: Sat, 7 Nov 2026 18:58:27 +0100 Subject: [PATCH 0552/2102] bpf: Restrict bpf_sock_destroy() to iter/{tcp,udp} A subsequent patch will mark bpf_iter__sockmap::sk as PTR_TRUSTED, making bpf_sock_destroy() callable from the iter/sockmap. Unlike iter/{tcp,udp}, the sockmap iterator does not run progs with the socket lock held, so destroying a socket from that context is unsafe. Restrict the allowed callers of bpf_sock_destroy() to iter/{tcp,udp}. Suggested-by: Alexei Starovoitov Signed-off-by: Michal Luczaj Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261107-sockmap-update-limit-iter-v3-5-7c0bad1ad036@rbox.co --- net/core/filter.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/net/core/filter.c b/net/core/filter.c index 1a60a2a70e2d81..16d92e5e12b845 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -13061,11 +13061,20 @@ BTF_KFUNCS_START(bpf_sk_iter_kfunc_ids) BTF_ID_FLAGS(func, bpf_sock_destroy) BTF_KFUNCS_END(bpf_sk_iter_kfunc_ids) +BTF_SET_START(bpf_sk_iter_locked_ids) +#if defined(CONFIG_INET) && defined(CONFIG_PROC_FS) +BTF_ID(func, bpf_iter_tcp) +BTF_ID(func, bpf_iter_udp) +#endif +BTF_SET_END(bpf_sk_iter_locked_ids) + static int tracing_iter_filter(const struct bpf_prog *prog, u32 kfunc_id) { if (btf_id_set8_contains(&bpf_sk_iter_kfunc_ids, kfunc_id) && - prog->expected_attach_type != BPF_TRACE_ITER) + (prog->expected_attach_type != BPF_TRACE_ITER || + !btf_id_set_contains(&bpf_sk_iter_locked_ids, prog->aux->attach_btf_id))) return -EACCES; + return 0; } From dd6e63efc2bef680a962acf6cdffb859832b5091 Mon Sep 17 00:00:00 2001 From: Michal Luczaj Date: Sat, 7 Nov 2026 18:58:28 +0100 Subject: [PATCH 0553/2102] bpf: Mark bpf_iter__sockmap::sk as PTR_TRUSTED In preparation for plain-PTR_TO_BTF_ID removal: allow calling bpf helpers with sk provided by iter/sockmap. Suggested-by: Alexei Starovoitov Signed-off-by: Michal Luczaj Signed-off-by: Alexei Starovoitov Link: https://msgid.link/DM92JCFA4X4U.30MTDH0KCPTJ@gmail.com Link: https://patch.msgid.link/20261107-sockmap-update-limit-iter-v3-6-7c0bad1ad036@rbox.co --- net/core/sock_map.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/core/sock_map.c b/net/core/sock_map.c index 282c6a4b2b05fe..0d7a8d9405d196 100644 --- a/net/core/sock_map.c +++ b/net/core/sock_map.c @@ -2002,7 +2002,7 @@ static struct bpf_iter_reg sock_map_iter_reg = { { offsetof(struct bpf_iter__sockmap, key), PTR_TO_BUF | PTR_MAYBE_NULL | MEM_RDONLY }, { offsetof(struct bpf_iter__sockmap, sk), - PTR_TO_BTF_ID_OR_NULL }, + PTR_TO_BTF_ID_OR_NULL | PTR_TRUSTED }, }, }; From b7f6028a7bc3e5d90c8a78ee97c67323cf8bacbd Mon Sep 17 00:00:00 2001 From: Michal Luczaj Date: Sat, 7 Nov 2026 18:58:29 +0100 Subject: [PATCH 0554/2102] selftests/bpf: Add iter/sockmap bpf_sock_destroy() negative test bpf_sock_destroy() is restricted to socket-locked iters, TCP and UDP. Fail attempting it from iter/sockmap. Signed-off-by: Michal Luczaj Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261107-sockmap-update-limit-iter-v3-7-7c0bad1ad036@rbox.co --- .../selftests/bpf/progs/sock_destroy_prog_fail.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tools/testing/selftests/bpf/progs/sock_destroy_prog_fail.c b/tools/testing/selftests/bpf/progs/sock_destroy_prog_fail.c index dd6850b58e2590..7b9f5779a184e2 100644 --- a/tools/testing/selftests/bpf/progs/sock_destroy_prog_fail.c +++ b/tools/testing/selftests/bpf/progs/sock_destroy_prog_fail.c @@ -20,3 +20,14 @@ int BPF_PROG(trace_tcp_destroy_sock, struct sock *sk) return 0; } +SEC("iter/sockmap") +__failure __msg("calling kernel function bpf_sock_destroy is not allowed") +int iter_sockmap_destroy(struct bpf_iter__sockmap *ctx) +{ + struct sock *sk = ctx->sk; + + if (sk) + bpf_sock_destroy((struct sock_common *)sk); + + return 0; +} From 22bc1ef8ac8244eb260529215d82217fd757830d Mon Sep 17 00:00:00 2001 From: Michal Luczaj Date: Sat, 7 Nov 2026 18:58:30 +0100 Subject: [PATCH 0555/2102] bpf: Fix "unresolved symbol tcp_request_sock" build error CONFIG_WERROR=y CONFIG_NET=y CONFIG_INET=n build fails: WARN: resolve_btfids: unresolved symbol tcp_request_sock Failed to generate BTF for vmlinux Try to disable CONFIG_DEBUG_INFO_BTF make[2]: *** [scripts/Makefile.vmlinux:72: vmlinux.unstripped] Error 1 make[1]: *** [.../Makefile:1379: vmlinux] Error 2 make: *** [Makefile:248: __sub-make] Error 2 Handle it in the style of commit d82a532a6115 ("bpf: Fix "unresolved symbol" build error with resolve_btfids"): force BTF generation. Signed-off-by: Michal Luczaj Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261107-sockmap-update-limit-iter-v3-8-7c0bad1ad036@rbox.co --- net/core/filter.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/net/core/filter.c b/net/core/filter.c index 16d92e5e12b845..9b00c5fb93bf85 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -12380,6 +12380,10 @@ const struct bpf_func_proto bpf_skc_to_tcp_timewait_sock_proto = { BPF_CALL_1(bpf_skc_to_tcp_request_sock, struct sock *, sk) { + /* Ensure BTF for the structs exists even with CONFIG_INET=n. */ + BTF_TYPE_EMIT(struct inet_request_sock); + BTF_TYPE_EMIT(struct tcp_request_sock); + #ifdef CONFIG_INET if (sk && sk->sk_prot == &tcp_prot && sk->sk_state == TCP_NEW_SYN_RECV) return (unsigned long)sk; From 4722bac72de6f220e3e89fad04588ce606d49e6e Mon Sep 17 00:00:00 2001 From: Henry Martin Date: Thu, 5 Nov 2026 14:03:31 +0800 Subject: [PATCH 0556/2102] bpf: Fix verifier model mismatch on __sk_buff.remote_port narrow read On little endian, the ctx access conversion for __sk_buff.remote_port loads the 16-bit skc_dport and shifts it left by 16, producing a 4-byte value of up to 0xffff0000. It reports its width through bpf_target_off() as 2, the member size. A 2-byte read is a narrower load of this 4-byte ctx field, but the fixup pass only masks the result when the access size is smaller than the reported width, so the masking is skipped. The verifier models the register as [0, 0xffff] while the runtime value is [0, 0xffff0000]. Arithmetic the verifier folds to a constant can therefore take any 16-bit port value at runtime, enabling out-of-bounds reads and writes relative to map values. Report the real produced width (4) so the fixup pass applies the usual RSH/AND masking to narrow reads. Full 4-byte reads are unaffected. Fixes: 8a31db5615667 ("bpf: add access to sock fields and pkt data from sk_skb programs") Reported-by: zeroday zhao Signed-off-by: Henry Martin Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261105060331.1912252-1-bsdhenrymartin@gmail.com --- net/core/filter.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/net/core/filter.c b/net/core/filter.c index 9b00c5fb93bf85..7fa8b81fd1dcb0 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -10444,13 +10444,19 @@ static u32 bpf_convert_ctx_access(enum bpf_access_type type, case offsetof(struct __sk_buff, remote_port): BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2); + /* + * The converted value is 4 bytes wide, not 2: on little + * endian the 16-bit port is shifted into the high half. + * Don't use bpf_target_off() here, it would report the + * member size and the narrow-load masking in the fixup + * pass would be skipped. + */ + *target_size = 4; *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk), si->dst_reg, si->src_reg, offsetof(struct sk_buff, sk)); *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg, - bpf_target_off(struct sock_common, - skc_dport, - 2, target_size)); + offsetof(struct sock_common, skc_dport)); #ifndef __BIG_ENDIAN_BITFIELD *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16); #endif From 90f4e698f9c1f7162296593d17b8223db05c8298 Mon Sep 17 00:00:00 2001 From: Shakeel Butt Date: Thu, 12 Nov 2026 09:27:13 -0800 Subject: [PATCH 0557/2102] bpf, cgroup: Don't read freed effective arrays in BPF_PROG_QUERY BPF_PROG_QUERY gets the cgroup from an fd before it takes cgroup_mutex. If the cgroup is removed in between and its bpf refcount drops to zero, cgroup_bpf_release() can run first. It frees the effective arrays but leaves the pointers, so a BPF_F_QUERY_EFFECTIVE query then reads freed memory. The window is small because the release work also takes cgroup_mutex. Check under the lock that the bpf refcount isn't zero, and return -ENOENT if it is, the error the fd lookup gives for a removed cgroup. The release work only runs after the count hits zero, and it takes the same lock. Reproduced in a VM with a debug-only delay between the fd lookup and the lock: KASAN reports a use-after-free in cgroup_bpf_prog_query(). With this patch, the query returns -ENOENT. Fixes: 4bfc0bb2c60e ("bpf: decouple the lifetime of cgroup_bpf from cgroup itself") Signed-off-by: Shakeel Butt Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261112172721.440275-2-shakeel.butt@linux.dev --- kernel/bpf/cgroup.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index 57a785241d42fb..9258c2669fa8d9 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -1446,6 +1446,14 @@ static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr, if (effective_query && prog_attach_flags) return -EINVAL; + /* + * cgroup_bpf_release() frees the effective arrays once the bpf + * refcount is zero. It takes this lock too, so a nonzero count means + * the arrays are still valid. + */ + if (percpu_ref_is_zero(&cgrp->bpf.refcnt)) + return -ENOENT; + if (type == BPF_STRUCT_OPS) { u32 type_id = attr->query.type_id; From b2e007371909ed9f88ff7227e0353f6bb88387e5 Mon Sep 17 00:00:00 2001 From: Shakeel Butt Date: Thu, 12 Nov 2026 09:27:14 -0800 Subject: [PATCH 0558/2102] bpf, cgroup: Don't attach to a removed cgroup Attach gets the cgroup from an fd before it takes cgroup_mutex. If the cgroup is removed in between and cgroup_bpf_release() runs first, attach adds a program that never runs: - With BPF_PROG_ATTACH the program leaks, since nothing can detach it. - With a link that uses cgroup storage, the storage stays on the freed cgroup's list, and freeing the map later writes to the freed cgroup. - A cgroup struct_ops link is attached but never called. The window is small today because the release work also waits for cgroup_mutex. The next patch stops that, which makes the race easy to hit. Check cgroup_is_dead() under the lock and return -ENOENT, the error the fd lookup gives for a removed cgroup. rmdir marks the cgroup dead under cgroup_mutex before it starts the release, so the check is exact. Reproduced in a VM with debug-only delays. With the next patch applied, a link attach queued behind a slow mkdir lands on the released cgroup, and freeing the map then hits a KASAN use-after-free in cgroup_storage_map_free(). BPF_PROG_ATTACH leaks the program. With this patch, attach returns -ENOENT. Fixes: 4bfc0bb2c60e ("bpf: decouple the lifetime of cgroup_bpf from cgroup itself") Fixes: 369d9dcd8fb8 ("bpf: Add infrastructure to support attaching struct_ops to cgroups") Signed-off-by: Shakeel Butt Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261112172721.440275-3-shakeel.butt@linux.dev --- kernel/bpf/cgroup.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index 9258c2669fa8d9..334237096759fc 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -988,6 +988,13 @@ static int __cgroup_bpf_attach(struct cgroup *cgrp, /* replace_prog implies BPF_F_REPLACE, and vice versa */ return -EINVAL; + /* + * The cgroup may have been removed since the caller looked it up. + * Then its bpf state may be freed, and nothing would detach this. + */ + if (cgroup_is_dead(cgrp)) + return -ENOENT; + atype = bpf_cgroup_atype_find(type, new_prog->aux->attach_btf_id); if (atype < 0) return -EINVAL; @@ -3170,6 +3177,12 @@ int cgroup_bpf_struct_ops_attach(struct bpf_map *map, const union bpf_attr *attr cgroup_lock(); + /* See the cgroup_is_dead() check in __cgroup_bpf_attach() */ + if (cgroup_is_dead(cgrp)) { + err = -ENOENT; + goto unlock; + } + if (attr->link_create.cgroup.expected_revision && attr->link_create.cgroup.expected_revision != cgrp->bpf.revisions[atype]) { err = -ESTALE; From 40aec6bab02e0977f75a87d466005f6492987848 Mon Sep 17 00:00:00 2001 From: Shakeel Butt Date: Thu, 12 Nov 2026 09:27:15 -0800 Subject: [PATCH 0559/2102] bpf, cgroup: Protect cgroup_bpf state with its own mutex In the Meta fleet, tasks that only read or free cgroup bpf state often wait minutes for cgroup_mutex: - In one day, hung-task reports (blocked over 120 seconds) showed this for BPF_PROG_QUERY on 1,075 hosts, the cgroup bpf release work on 458 hosts and link info on 94 hosts. - The query callers are a container manager's health checks. Over 30 days, 6,700 hosts reported one hung. The typical wait is 11 minutes, the longest 75 minutes. - The cgroup_mutex holder is almost always a cgroup mkdir or rmdir that is waiting for kernfs_rwsem. Only attach, detach and replace need cgroup_mutex. They update the effective arrays of all descendants, so the hierarchy must not change. Add cgroup_bpf_mutex for the bpf state. Attach, detach and replace take cgroup_mutex and then cgroup_bpf_mutex. Everything else (query, link info, the release work, dropping an LSM attach type, freeing a cgroup storage map) takes only cgroup_bpf_mutex. cgroup_bpf_inherit() still runs at mkdir with only cgroup_mutex, so mkdir never waits for cgroup_bpf_mutex. It writes the new cgroup, which no one else can see yet. What it reads from the ancestors changes only under cgroup_mutex, and the release work can't run for them because they are online. The release work no longer waits for cgroup_mutex, so attach must check that the cgroup is still alive. The previous patch does that. With a test delay that makes a mkdir hold cgroup_mutex for 5 seconds, BPF_PROG_QUERY and link info now return in under a millisecond instead of 4.6 seconds. Attach and detach still wait. Signed-off-by: Shakeel Butt Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261112172721.440275-4-shakeel.butt@linux.dev --- include/linux/bpf-cgroup-defs.h | 1 + include/linux/bpf-cgroup.h | 3 + kernel/bpf/cgroup.c | 137 +++++++++++++++++++++----------- kernel/bpf/local_storage.c | 8 +- 4 files changed, 102 insertions(+), 47 deletions(-) diff --git a/include/linux/bpf-cgroup-defs.h b/include/linux/bpf-cgroup-defs.h index 0147b8bec97368..671f27ba6a620c 100644 --- a/include/linux/bpf-cgroup-defs.h +++ b/include/linux/bpf-cgroup-defs.h @@ -53,6 +53,7 @@ enum cgroup_bpf_attach_type { MAX_CGROUP_BPF_ATTACH_TYPE }; +/* Locking: see cgroup_bpf_mutex in kernel/bpf/cgroup.c */ struct cgroup_bpf { /* array of effective progs in this cgroup */ struct bpf_prog_array __rcu *effective[MAX_CGROUP_BPF_ATTACH_TYPE]; diff --git a/include/linux/bpf-cgroup.h b/include/linux/bpf-cgroup.h index 02ef7f899b3dee..dfa7a75507c965 100644 --- a/include/linux/bpf-cgroup.h +++ b/include/linux/bpf-cgroup.h @@ -421,6 +421,9 @@ static inline bool cgroup_bpf_sock_enabled(struct sock *sk, __ret; \ }) +/* Take cgroup_mutex first if you need both. See kernel/bpf/cgroup.c. */ +void cgroup_bpf_lock(void); +void cgroup_bpf_unlock(void); int cgroup_bpf_prog_attach(const union bpf_attr *attr, enum bpf_prog_type ptype, struct bpf_prog *prog); int cgroup_bpf_prog_detach(const union bpf_attr *attr, diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index 334237096759fc..ae082ac86130b4 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -206,13 +206,53 @@ unsigned int __cgroup_bpf_run_lsm_current(const void *ctx, return ret; } +/* + * cgroup_bpf_mutex protects the bpf state of all cgroups: prog lists, + * effective arrays, flags, revisions, storage lists, link->cgroup, + * link->map of struct_ops links and cgroup_lsm_atype[]. + * + * Take cgroup_mutex first if you need both. This mutex doesn't keep a + * cgroup alive or the hierarchy stable. Attach, detach and replace walk + * the descendants, so they take both. Everything else takes only this one. + * + * cgroup_bpf_inherit() runs at mkdir with only cgroup_mutex. That's safe: + * it writes the new cgroup, which no one else can see yet, and what it + * reads from the ancestors changes only under cgroup_mutex. The ancestors + * are online, and only rmdir, which needs cgroup_mutex, starts a release. + */ +static DEFINE_MUTEX(cgroup_bpf_mutex); + +#define cgroup_bpf_held() lockdep_is_held(&cgroup_bpf_mutex) + +void cgroup_bpf_lock(void) +{ + mutex_lock(&cgroup_bpf_mutex); +} + +void cgroup_bpf_unlock(void) +{ + mutex_unlock(&cgroup_bpf_mutex); +} + +static void cgroup_bpf_lock_hierarchy(void) +{ + cgroup_lock(); + mutex_lock(&cgroup_bpf_mutex); +} + +static void cgroup_bpf_unlock_hierarchy(void) +{ + mutex_unlock(&cgroup_bpf_mutex); + cgroup_unlock(); +} + #ifdef CONFIG_BPF_LSM static enum cgroup_bpf_attach_type bpf_cgroup_atype_find(enum bpf_attach_type attach_type, u32 attach_btf_id) { int i; - lockdep_assert_held(&cgroup_mutex); + lockdep_assert_held(&cgroup_bpf_mutex); if (attach_type != BPF_LSM_CGROUP) return to_cgroup_bpf_attach_type(attach_type); @@ -233,7 +273,7 @@ void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype) { int i = cgroup_atype - CGROUP_LSM_START; - lockdep_assert_held(&cgroup_mutex); + lockdep_assert_held(&cgroup_bpf_mutex); if (!cgroup_lsm_atype[i].attach_btf_id) { cgroup_lsm_atype[i].attach_btf_id = attach_btf_id; @@ -249,13 +289,13 @@ void bpf_cgroup_atype_put(int cgroup_atype) { int i = cgroup_atype - CGROUP_LSM_START; - cgroup_lock(); + cgroup_bpf_lock(); if (--cgroup_lsm_atype[i].refcnt <= 0) { WRITE_ONCE(cgroup_lsm_atype[i].returns_errno, true); cgroup_lsm_atype[i].attach_btf_id = 0; } WARN_ON_ONCE(cgroup_lsm_atype[i].refcnt < 0); - cgroup_unlock(); + cgroup_bpf_unlock(); } #else static enum cgroup_bpf_attach_type @@ -459,7 +499,7 @@ static void cgroup_bpf_release(struct work_struct *work) unsigned int atype; - cgroup_lock(); + cgroup_bpf_lock(); for (atype = 0; atype < ARRAY_SIZE(cgrp->bpf.progs); atype++) { struct hlist_head *progs = &cgrp->bpf.progs[atype]; @@ -480,7 +520,7 @@ static void cgroup_bpf_release(struct work_struct *work) } old_array = rcu_dereference_protected( cgrp->bpf.effective[atype], - lockdep_is_held(&cgroup_mutex)); + cgroup_bpf_held()); bpf_cgroup_array_free(old_array, atype); } @@ -489,7 +529,7 @@ static void cgroup_bpf_release(struct work_struct *work) bpf_cgroup_storage_free(storage); } - cgroup_unlock(); + cgroup_bpf_unlock(); for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p)) cgroup_bpf_put(p); @@ -665,7 +705,9 @@ static void activate_effective_progs(struct cgroup *cgrp, enum cgroup_bpf_attach_type atype, struct bpf_prog_array *old_array) { + /* cgroup_bpf_inherit() holds only cgroup_mutex, see cgroup_bpf_mutex */ old_array = rcu_replace_pointer(cgrp->bpf.effective[atype], old_array, + lockdep_is_held(&cgroup_bpf_mutex) || lockdep_is_held(&cgroup_mutex)); /* free prog array after grace period, since __cgroup_bpf_run_*() * might be still walking the array @@ -687,6 +729,9 @@ static int cgroup_bpf_inherit(struct cgroup *cgrp) struct cgroup *p; int ret, i; + /* See the comment above cgroup_bpf_mutex */ + lockdep_assert_held(&cgroup_mutex); + ret = percpu_ref_init(&cgrp->bpf.refcnt, cgroup_bpf_release_fn, 0, GFP_KERNEL); if (ret) @@ -747,6 +792,8 @@ static int update_effective_progs(struct cgroup *cgrp, struct cgroup_subsys_state *css; int err; + lockdep_assert_held(&cgroup_bpf_mutex); + /* allocate and recompute effective prog arrays */ css_for_each_descendant_pre(css, &cgrp->self) { struct cgroup *desc = container_of(css, struct cgroup, self); @@ -954,7 +1001,7 @@ static int insert_pl_to_hlist(struct bpf_prog_list *pl, struct hlist_head *progs * @revision: bpf_prog_list revision * * Exactly one of @prog or @link can be non-null. - * Must be called with cgroup_mutex held. + * Must be called with cgroup_mutex and cgroup_bpf_mutex held. */ static int __cgroup_bpf_attach(struct cgroup *cgrp, struct bpf_prog *prog, struct bpf_prog *replace_prog, @@ -1100,10 +1147,10 @@ static int cgroup_bpf_attach(struct cgroup *cgrp, { int ret; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); ret = __cgroup_bpf_attach(cgrp, prog, replace_prog, link, type, flags, id_or_fd, revision); - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return ret; } @@ -1181,7 +1228,7 @@ static void replace_effective_prog(struct cgroup *cgrp, progs = rcu_dereference_protected( desc->bpf.effective[atype], - lockdep_is_held(&cgroup_mutex)); + cgroup_bpf_held()); item = &progs->items[pos]; prog_list_replace_item(pl, item); } @@ -1209,7 +1256,7 @@ static bool cgroup_bpf_storages_compatible(struct bpf_prog *old_prog, * @new_prog: &struct bpf_prog for the target BPF program with its refcnt * incremented * - * Must be called with cgroup_mutex held. + * Must be called with cgroup_mutex and cgroup_bpf_mutex held. */ static int __cgroup_bpf_replace(struct cgroup *cgrp, struct bpf_cgroup_link *link, @@ -1257,7 +1304,7 @@ static int cgroup_bpf_replace(struct bpf_link *link, struct bpf_prog *new_prog, cg_link = container_of(link, struct bpf_cgroup_link, link); - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); /* link might have been auto-released by dying cgroup, so fail */ if (!cg_link->cgroup) { ret = -ENOLINK; @@ -1269,7 +1316,7 @@ static int cgroup_bpf_replace(struct bpf_link *link, struct bpf_prog *new_prog, } ret = __cgroup_bpf_replace(cg_link->cgroup, cg_link, new_prog); out_unlock: - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return ret; } @@ -1340,7 +1387,7 @@ static void purge_effective_progs(struct cgroup *cgrp, struct bpf_prog_list *pl, progs = rcu_dereference_protected( desc->bpf.effective[atype], - lockdep_is_held(&cgroup_mutex)); + cgroup_bpf_held()); /* Remove the program from the array */ WARN_ONCE(bpf_cgroup_array_delete_safe_at(progs, pos, atype), @@ -1358,7 +1405,7 @@ static void purge_effective_progs(struct cgroup *cgrp, struct bpf_prog_list *pl, * @revision: bpf_prog_list revision * * At most one of @prog or @link can be non-NULL. - * Must be called with cgroup_mutex held. + * Must be called with cgroup_mutex and cgroup_bpf_mutex held. */ static int __cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog, struct bpf_cgroup_link *link, enum bpf_attach_type type, @@ -1428,13 +1475,13 @@ static int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog, { int ret; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); ret = __cgroup_bpf_detach(cgrp, prog, NULL, type, revision); - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return ret; } -/* Must be called with cgroup_mutex held to avoid races. */ +/* Must be called with cgroup_bpf_mutex held. */ static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr, union bpf_attr __user *uattr, u32 uattr_size) { @@ -1488,7 +1535,7 @@ static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr, for (atype = from_atype; atype <= to_atype; atype++) { if (effective_query) { effective = rcu_dereference_protected(cgrp->bpf.effective[atype], - lockdep_is_held(&cgroup_mutex)); + cgroup_bpf_held()); total_cnt += bpf_cgroup_array_length(effective, atype); } else { total_cnt += prog_list_length(&cgrp->bpf.progs[atype], NULL); @@ -1518,7 +1565,7 @@ static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr, for (atype = from_atype; atype <= to_atype && total_cnt; atype++) { if (effective_query) { effective = rcu_dereference_protected(cgrp->bpf.effective[atype], - lockdep_is_held(&cgroup_mutex)); + cgroup_bpf_held()); cnt = min_t(int, bpf_cgroup_array_length(effective, atype), total_cnt); ret = bpf_cgroup_array_copy_to_user(effective, prog_ids, cnt, atype); } else { @@ -1559,9 +1606,9 @@ static int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr, { int ret; - cgroup_lock(); + cgroup_bpf_lock(); ret = __cgroup_bpf_query(cgrp, attr, uattr, uattr_size); - cgroup_unlock(); + cgroup_bpf_unlock(); return ret; } @@ -1629,11 +1676,11 @@ static void bpf_cgroup_link_release(struct bpf_link *link) if (!cg_link->cgroup) return; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); /* re-check cgroup under lock again */ if (!cg_link->cgroup) { - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return; } @@ -1645,7 +1692,7 @@ static void bpf_cgroup_link_release(struct bpf_link *link) cg = cg_link->cgroup; cg_link->cgroup = NULL; - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); cgroup_put(cg); } @@ -1672,10 +1719,10 @@ static void bpf_cgroup_link_show_fdinfo(const struct bpf_link *link, container_of(link, struct bpf_cgroup_link, link); u64 cg_id = 0; - cgroup_lock(); + cgroup_bpf_lock(); if (cg_link->cgroup) cg_id = cgroup_id(cg_link->cgroup); - cgroup_unlock(); + cgroup_bpf_unlock(); seq_printf(seq, "cgroup_id:\t%llu\n" @@ -1691,10 +1738,10 @@ static int bpf_cgroup_link_fill_link_info(const struct bpf_link *link, container_of(link, struct bpf_cgroup_link, link); u64 cg_id = 0; - cgroup_lock(); + cgroup_bpf_lock(); if (cg_link->cgroup) cg_id = cgroup_id(cg_link->cgroup); - cgroup_unlock(); + cgroup_bpf_unlock(); info->cgroup.cgroup_id = cg_id; info->cgroup.attach_type = link->attach_type; @@ -2971,11 +3018,11 @@ static int __cgroup_struct_ops_link_detach(struct bpf_link *link, bool wake_poll struct bpf_map *map; struct cgroup *cgrp; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); cgrp = cg_link->cgroup; if (!cgrp) { - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return 0; } @@ -2987,7 +3034,7 @@ static int __cgroup_struct_ops_link_detach(struct bpf_link *link, bool wake_poll break; } if (WARN_ON_ONCE(!pl)) { - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return -ENOENT; } @@ -3005,7 +3052,7 @@ static int __cgroup_struct_ops_link_detach(struct bpf_link *link, bool wake_poll kfree(pl); static_branch_dec(&cgroup_bpf_enabled_key[atype]); - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return 0; } @@ -3028,15 +3075,15 @@ static void cgroup_struct_ops_link_show_fdinfo(const struct bpf_link *link, stru struct bpf_cgroup_link *cg_link = container_of(link, struct bpf_cgroup_link, link); - cgroup_lock(); + cgroup_bpf_lock(); if (!cg_link->cgroup) { - cgroup_unlock(); + cgroup_bpf_unlock(); return; } seq_printf(seq, "map_id:\t%u\n", cg_link->map->id); seq_printf(seq, "cgroup_id:\t%llu\n", cgroup_id(cg_link->cgroup)); - cgroup_unlock(); + cgroup_bpf_unlock(); } static int cgroup_struct_ops_link_fill_link_info(const struct bpf_link *link, @@ -3044,15 +3091,15 @@ static int cgroup_struct_ops_link_fill_link_info(const struct bpf_link *link, { struct bpf_cgroup_link *cg_link = container_of(link, struct bpf_cgroup_link, link); - cgroup_lock(); + cgroup_bpf_lock(); if (!cg_link->cgroup) { - cgroup_unlock(); + cgroup_bpf_unlock(); return 0; } info->struct_ops.map_id = cg_link->map->id; info->struct_ops.cgroup_id = cgroup_id(cg_link->cgroup); - cgroup_unlock(); + cgroup_bpf_unlock(); return 0; } @@ -3070,7 +3117,7 @@ static int cgroup_struct_ops_link_update(struct bpf_link *link, struct bpf_map * if (!bpf_struct_ops_valid_to_reg(new_map)) return -EINVAL; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); cgrp = cg_link->cgroup; if (!cgrp) { @@ -3103,7 +3150,7 @@ static int cgroup_struct_ops_link_update(struct bpf_link *link, struct bpf_map * cgrp->bpf.revisions[atype]++; out: - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return err; } @@ -3175,7 +3222,7 @@ int cgroup_bpf_struct_ops_attach(struct bpf_map *map, const union bpf_attr *attr atype = bpf_struct_ops_map_cgroup_atype(map); progs = &cgrp->bpf.progs[atype]; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); /* See the cgroup_is_dead() check in __cgroup_bpf_attach() */ if (cgroup_is_dead(cgrp)) { @@ -3218,12 +3265,12 @@ int cgroup_bpf_struct_ops_attach(struct bpf_map *map, const union bpf_attr *attr cgrp->bpf.revisions[atype]++; static_branch_inc(&cgroup_bpf_enabled_key[atype]); - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return bpf_link_settle(&link_primer); unlock: - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); cleanup: kfree(pl); diff --git a/kernel/bpf/local_storage.c b/kernel/bpf/local_storage.c index 83cd527a2542bd..2cfbddeb1c7e97 100644 --- a/kernel/bpf/local_storage.c +++ b/kernel/bpf/local_storage.c @@ -345,14 +345,18 @@ static void cgroup_storage_map_free(struct bpf_map *_map) struct list_head *storages = &map->list; struct bpf_cgroup_storage *storage, *stmp; - cgroup_lock(); + /* + * Attach and cgroup_bpf_release() change the same cgroup storage + * lists under other maps' locks, so take cgroup_bpf_mutex. + */ + cgroup_bpf_lock(); list_for_each_entry_safe(storage, stmp, storages, list_map) { bpf_cgroup_storage_unlink(storage); bpf_cgroup_storage_free(storage); } - cgroup_unlock(); + cgroup_bpf_unlock(); WARN_ON(!RB_EMPTY_ROOT(&map->root)); WARN_ON(!list_empty(&map->list)); From 4b4eb7f44ee05754339d07e9df649809f45d14c5 Mon Sep 17 00:00:00 2001 From: Shakeel Butt Date: Thu, 12 Nov 2026 10:38:03 -0800 Subject: [PATCH 0560/2102] bpf, cgroup: Don't lose errors in effective BPF_LSM_CGROUP queries An effective BPF_LSM_CGROUP query walks one attach type per LSM hook. __cgroup_bpf_query() sets ret to -ENOSPC before the loop when prog_cnt is too small, but the effective branch then overwrites ret with each type's copy result: - If the buffer runs out exactly at the end of a type, the last copy returns 0 and the query returns 0 instead of -ENOSPC. - If one type's copy faults and a later one succeeds, the query returns 0 instead of -EFAULT. Return -EFAULT right away when a copy faults, as the non-effective branch does, and leave ret alone otherwise. The copy helper then no longer needs to return -ENOSPC. That also removes a false -ENOSPC it gave when a dummy entry followed the last copied program. Reproduced in a VM with two BPF_LSM_CGROUP programs on different hooks. An effective query with prog_cnt=1 returned 0, and so did one whose first id slot was not writable. With this patch they fail with -ENOSPC and -EFAULT. Queries of other attach types already did. Fixes: b79c9fc9551b ("bpf: implement BPF_PROG_QUERY for BPF_LSM_CGROUP") Reported-by: Sashiko Signed-off-by: Shakeel Butt Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261112183804.1171535-1-shakeel.butt@linux.dev Closes: https://lore.kernel.org/bpf/sashiko-outbox-211618@kernel.org/ --- kernel/bpf/cgroup.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index ae082ac86130b4..f195d5fcae6c6c 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -464,7 +464,7 @@ static int bpf_cgroup_array_copy_to_user(struct bpf_prog_array *array, return -EFAULT; i++; } - return item->prog ? -ENOSPC : 0; + return 0; } static int bpf_cgroup_array_delete_safe_at(struct bpf_prog_array *array, @@ -1567,7 +1567,8 @@ static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr, effective = rcu_dereference_protected(cgrp->bpf.effective[atype], cgroup_bpf_held()); cnt = min_t(int, bpf_cgroup_array_length(effective, atype), total_cnt); - ret = bpf_cgroup_array_copy_to_user(effective, prog_ids, cnt, atype); + if (bpf_cgroup_array_copy_to_user(effective, prog_ids, cnt, atype)) + return -EFAULT; } else { struct hlist_head *progs; struct bpf_prog_list *pl; From 953e4f5a168238731a1ccf7c7631c83e19dbd7fd Mon Sep 17 00:00:00 2001 From: koraynilay Date: Tue, 10 Nov 2026 17:16:59 +0100 Subject: [PATCH 0561/2102] ksmbd: set create_time to btime in ksmbd_vfs_fill_dentry_attrs() ksmbd_vfs_fill_dentry_attrs() queries vfs_getattr() with STATX_BTIME, but discards ksmbd_kstat->kstat->btime and unconditionally initializes ksmbd_kstat->create_time to ksmbd_kstat->kstat->ctime. Check ksmbd_kstat->kstat->result_mask for STATX_BTIME and set ksmbd_kstat->create_time to ksmbd_kstat->kstat->btime, only falling back to ctime if btime isn't returned, matching the existing behavior in smb2_open(). Fixes: 5614c8c487f6 ("ksmbd: replace generic_fillattr with vfs_getattr") Cc: stable@vger.kernel.org Assisted-by: Gemini:3.8-flash-high antigravity-cli-1.5.3 Signed-off-by: koraynilay Reviewed-by: Ian Bridges Tested-by: Ian Bridges Signed-off-by: Namjae Jeon --- fs/smb/server/vfs.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/fs/smb/server/vfs.c b/fs/smb/server/vfs.c index cb3f4f5fe9cf0b..0c95d466837032 100644 --- a/fs/smb/server/vfs.c +++ b/fs/smb/server/vfs.c @@ -1914,7 +1914,10 @@ int ksmbd_vfs_fill_dentry_attrs(struct ksmbd_work *work, if (rc) return rc; - time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime); + if (ksmbd_kstat->kstat->result_mask & STATX_BTIME) + time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->btime); + else + time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime); ksmbd_kstat->create_time = time; /* From e803eb371559d64f337d3078d5e7749716b39160 Mon Sep 17 00:00:00 2001 From: koraynilay Date: Wed, 11 Nov 2026 23:25:34 +0100 Subject: [PATCH 0562/2102] ksmbd: fix timestamp corruption on special values When a timestamp is being sent with "-1" or "-2" as its value because it should be ignored, as specified in MS-FSCC 2.4.7 FileBasicInformation, ksmbd would clobber it in both the xattr and on-disk value by setting it to -1. simple reproducer: echo test > file.txt smbclient //127.0.0.1/test -U user%pass -c "put file.txt repro.txt" smbclient //127.0.0.1/test -U user%pass -c "allinfo repro.txt" smbclient //127.0.0.1/test -U user%pass -c "setmode repro.txt +h" stat repro.txt # the actual file on disk behind smb smbclient //127.0.0.1/test -U user%pass -c "allinfo repro.txt" which would show, respectively: altname: REPRO~MQ.TXT create_time: Wed Nov 11 21:23:16 2026 UTC access_time: Wed Nov 11 21:23:16 2026 UTC write_time: Wed Nov 11 21:23:16 2026 UTC change_time: Wed Nov 11 21:23:16 2026 UTC attributes: A (20) File: /tmp/repro.txt [...] Access: 1601-01-01 00:00:00.000000000 +0000 Modify: 2026-11-11 21:58:10.145349236 +0000 Change: 2026-11-11 21:58:10.206350216 +0000 Birth: 2026-11-11 21:58:10.144349220 +0000 altname: REPRO~MQ.TXT create_time: Wed Dec 31 23:59:59 1969 UTC access_time: Mon Jan 1 00:00:04 1601 UTC write_time: Wed Nov 11 21:23:16 2026 UTC change_time: Wed Nov 11 21:23:16 2026 UTC attributes: HA (22) This patch also makes the smb2.timestamps.freeze-thaw test from smbtorture pass. Cc: stable@vger.kernel.org Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3") Link: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/16023025-8a78-492f-8b96-c873b042ac50 Assisted-by: Gemini:3.8-flash-high antigravity-cli-1.5.3 Signed-off-by: koraynilay Reviewed-by: Ian Bridges Tested-by: Ian Bridges Signed-off-by: Namjae Jeon --- fs/smb/server/smb2pdu.c | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/fs/smb/server/smb2pdu.c b/fs/smb/server/smb2pdu.c index fe17d406123746..2950ea59075402 100644 --- a/fs/smb/server/smb2pdu.c +++ b/fs/smb/server/smb2pdu.c @@ -8866,6 +8866,7 @@ static int set_file_basic_info(struct ksmbd_file *fp, const struct mnt_idmap *idmap; __le32 attrs_mask = FILE_ATTRIBUTE_DIRECTORY_LE | FILE_ATTRIBUTE_COMPRESSED_LE; + s64 crtime, time; int rc = 0; if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE)) @@ -8881,21 +8882,25 @@ static int set_file_basic_info(struct ksmbd_file *fp, (file_info->Attributes & FILE_ATTRIBUTE_TEMPORARY_LE)) return -EINVAL; - if (file_info->CreationTime) - fp->create_time = le64_to_cpu(file_info->CreationTime); + crtime = (s64)le64_to_cpu(file_info->CreationTime); + if (crtime > 0) + fp->create_time = crtime; - if (file_info->LastAccessTime) { + time = (s64)le64_to_cpu(file_info->LastAccessTime); + if (time > 0) { attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime); attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET); } - if (file_info->ChangeTime) { - fp->change_time = le64_to_cpu(file_info->ChangeTime); + time = (s64)le64_to_cpu(file_info->ChangeTime); + if (time > 0) { + fp->change_time = time; inode_set_ctime_to_ts(inode, ksmbd_NTtimeToUnix(file_info->ChangeTime)); } - if (file_info->LastWriteTime) { + time = (s64)le64_to_cpu(file_info->LastWriteTime); + if (time > 0) { attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime); attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME); } @@ -8914,7 +8919,7 @@ static int set_file_basic_info(struct ksmbd_file *fp, } if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) && - (file_info->CreationTime || file_info->Attributes)) { + (crtime > 0 || file_info->Attributes)) { struct xattr_dos_attrib da = {0}; da.version = 4; From 91d16c8a2d6b161eac4907eb5a9442510e4f2ce2 Mon Sep 17 00:00:00 2001 From: Ian Bridges Date: Wed, 11 Nov 2026 21:18:50 -0600 Subject: [PATCH 0563/2102] ksmbd: fix out-of-bounds read in expired-session LOCK check smb2_session_expired_cmd_allowed() runs from smb2_check_user_session() before ksmbd_smb2_check_message() has validated the request. For a LOCK on an expired Kerberos session it scans the lock elements, using the unvalidated NextCommand field as the command length. A malformed request makes it read past the request buffer. BUG: KASAN: slab-out-of-bounds in smb2_session_expired_cmd_allowed+0x260/0x2a0 [ksmbd] Call Trace: smb2_session_expired_cmd_allowed+0x260/0x2a0 [ksmbd] smb2_check_user_session+0x4ff/0x680 [ksmbd] handle_ksmbd_work+0x465/0x1cb0 [ksmbd] Decide whether a command may run on an expired session from the command alone. Move the unlock-only rule for LOCK into smb2_lock(), which runs after the request has been validated. An expired session can still release byte-range locks but cannot take new ones, as before. A LOCK on an expired session now goes through the normal request checks before smb2_lock() sees it, as CLOSE and LOGOFF already do. A malformed one is rejected by those checks instead of returning STATUS_NETWORK_SESSION_EXPIRED. Fixes: a47634cd729b ("ksmbd: expire SMB sessions when Kerberos tickets expire") Cc: stable@vger.kernel.org Signed-off-by: Ian Bridges Tested-by: Michail Andreas Michalopoulos Signed-off-by: Namjae Jeon --- fs/smb/server/smb2pdu.c | 57 +++++++++++++++++------------------------ 1 file changed, 23 insertions(+), 34 deletions(-) diff --git a/fs/smb/server/smb2pdu.c b/fs/smb/server/smb2pdu.c index 2950ea59075402..945303c27ce94e 100644 --- a/fs/smb/server/smb2pdu.c +++ b/fs/smb/server/smb2pdu.c @@ -1014,39 +1014,15 @@ int smb2_allocate_rsp_buf(struct ksmbd_work *work) return 0; } -static bool smb2_session_expired_cmd_allowed(struct ksmbd_work *work, - unsigned int cmd) +/* + * MS-SMB2 3.3.5.2.9 lets LOGOFF, CLOSE and LOCK proceed on an expired + * session. CANCEL is allowed too. For LOCK, smb2_lock() allows only + * unlocks, after the request has been validated. + */ +static bool smb2_session_expired_cmd_allowed(unsigned int cmd) { - struct smb2_lock_req *req; - unsigned int len, lock_count, i; - - if (cmd == SMB2_CANCEL_HE || cmd == SMB2_CLOSE_HE || - cmd == SMB2_LOGOFF_HE) - return true; - if (cmd != SMB2_LOCK_HE) - return false; - - req = ksmbd_req_buf_next(work); - if (req->hdr.NextCommand) - len = le32_to_cpu(req->hdr.NextCommand); - else { - len = get_rfc1002_len(work->request_buf); - if (len < work->next_smb2_rcv_hdr_off) - return false; - len -= work->next_smb2_rcv_hdr_off; - } - - lock_count = le16_to_cpu(req->LockCount); - if (!lock_count || len < offsetof(struct smb2_lock_req, locks) || - lock_count > (len - offsetof(struct smb2_lock_req, locks)) / - sizeof(struct smb2_lock_element)) - return false; - - for (i = 0; i < lock_count; i++) { - if (le32_to_cpu(req->locks[i].Flags) != SMB2_LOCKFLAG_UNLOCK) - return false; - } - return true; + return cmd == SMB2_CANCEL_HE || cmd == SMB2_CLOSE_HE || + cmd == SMB2_LOGOFF_HE || cmd == SMB2_LOCK_HE; } static bool smb2_session_kerberos_expired(struct ksmbd_session *sess) @@ -1124,7 +1100,7 @@ int smb2_check_user_session(struct ksmbd_work *work) pr_err("compound request on a non-valid session (state %d)\n", work->sess->state); if (smb2_session_kerberos_expired(work->sess) && - smb2_session_expired_cmd_allowed(work, cmd)) + smb2_session_expired_cmd_allowed(cmd)) return 1; return smb2_session_kerberos_expired(work->sess) ? -EKEYEXPIRED : -EINVAL; @@ -1136,7 +1112,7 @@ int smb2_check_user_session(struct ksmbd_work *work) work->sess = ksmbd_session_lookup_all_states(conn, sess_id); if (work->sess) { if (smb2_session_kerberos_expired(work->sess)) { - return smb2_session_expired_cmd_allowed(work, cmd) ? + return smb2_session_expired_cmd_allowed(cmd) ? 1 : -EKEYEXPIRED; } if (work->sess->state != SMB2_SESSION_VALID) { @@ -10885,6 +10861,19 @@ int smb2_lock(struct ksmbd_work *work) if (smb2_compound_has_failed(work, &rsp->hdr)) return -EACCES; + /* An expired session may release byte-range locks, not take them. */ + if (work->sess && smb2_session_kerberos_expired(work->sess)) { + lock_count = le16_to_cpu(req->LockCount); + for (i = 0; i < lock_count; i++) { + if (le32_to_cpu(req->locks[i].Flags) != + SMB2_LOCKFLAG_UNLOCK) { + rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED; + err = -EKEYEXPIRED; + goto out2; + } + } + } + if (work->next_smb2_rcv_hdr_off && !has_file_id(req->VolatileFileId)) { ksmbd_debug(SMB, "Compound request set FID = %llu\n", From 3d322b98b56628ee69e4528a52cc1f445880fa17 Mon Sep 17 00:00:00 2001 From: Michail Andreas Michalopoulos Date: Fri, 13 Nov 2026 02:47:44 +0700 Subject: [PATCH 0564/2102] ksmbd: sign the last response of a compound that ends early is_chained_smb2_message() ends a compound early when the next command does not fit in the request, or its response would not fit in the response buffer. Since commit e2b76ab8b5c9 ("ksmbd: add support for read compound"), __handle_ksmbd_work() then signs ksmbd_resp_buf_curr(), which is_chained_smb2_message() only moves to the response of the command just processed when it chains to the next command or reaches the last one. On an early end it returns without moving it, so for a command after the first, the previous command's response was signed again, over the iovecs of both responses, and the response of this command was left unsigned. Neither signature verifies at the client. Handle an early end as the end of the compound: pad the response to 8 bytes and make it the current one. smb2_allocate_rsp_buf() leaves room for that padding in the response buffer of a compound. Only a compound whose NextCommand points past the end of the message, or whose responses fill the response buffer, takes this path. Sashiko pointed it out in its review of an unrelated series. An AI assistant was used to draft the patch and as an independent reviewer. Fixes: e2b76ab8b5c9 ("ksmbd: add support for read compound") Signed-off-by: Michail Andreas Michalopoulos Reviewed-by: Ian Bridges Tested-by: Ian Bridges Signed-off-by: Namjae Jeon --- fs/smb/server/smb2pdu.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/fs/smb/server/smb2pdu.c b/fs/smb/server/smb2pdu.c index 945303c27ce94e..2a87975fb208d9 100644 --- a/fs/smb/server/smb2pdu.c +++ b/fs/smb/server/smb2pdu.c @@ -699,7 +699,7 @@ bool is_chained_smb2_message(struct ksmbd_work *work) get_rfc1002_len(work->request_buf)) { pr_err("next command(%u) offset exceeds smb msg size\n", next_cmd); - return false; + goto last_rsp; } /* @@ -716,16 +716,21 @@ bool is_chained_smb2_message(struct ksmbd_work *work) if ((u64)ALIGN(get_rfc1002_len(work->response_buf), 8) + next_rsp_sz > work->response_sz) { pr_err("next response offset exceeds response buffer size\n"); - return false; + goto last_rsp; } ksmbd_debug(SMB, "got SMB2 chained command\n"); init_chained_smb2_rsp(work); return true; - } else if (work->next_smb2_rcv_hdr_off) { + } + +last_rsp: + if (work->next_smb2_rcv_hdr_off) { /* - * This is last request in chained command, - * align response to 8 byte + * This is the last response of a compound, also when the + * compound ends early because the next command does not fit. + * Align it to 8 bytes and make it the current response, which + * is the one the caller signs. */ len = ALIGN(get_rfc1002_len(work->response_buf), 8); len = len - get_rfc1002_len(work->response_buf); From fecd3599f21255553989b4a4303de77ec05ac556 Mon Sep 17 00:00:00 2001 From: Ian Bridges Date: Thu, 12 Nov 2026 12:36:07 -0600 Subject: [PATCH 0565/2102] ksmbd: ignore the allocation size create context on a read-only share On a read-only share, ksmbd refuses writes over SMB, even from a user whose account could write the files in the underlying filesystem. Such a user can still open an existing file for write on the share, but the WRITE requests that follow are refused. If the open carries an SMB2_CREATE_ALLOCATION_SIZE create context, smb2_open() still calls vfs_fallocate() on the file, and the filesystem allows it because of the user's write permission. The user can thereby reserve any amount of disk space through the read-only share, up to filling the filesystem. The file's size and data do not change. Ignore the context on read-only shares. It requests space for a file being created or overwritten, and such a share permits neither. Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3") Cc: stable@vger.kernel.org Signed-off-by: Ian Bridges Signed-off-by: Namjae Jeon --- fs/smb/server/smb2pdu.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fs/smb/server/smb2pdu.c b/fs/smb/server/smb2pdu.c index 2a87975fb208d9..a5601d170d2328 100644 --- a/fs/smb/server/smb2pdu.c +++ b/fs/smb/server/smb2pdu.c @@ -5277,7 +5277,8 @@ int smb2_open(struct ksmbd_work *work) if (IS_ERR(az_req)) { rc = PTR_ERR(az_req); goto err_out1; - } else if (az_req) { + } else if (az_req && + test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) { int err; if (le16_to_cpu(az_req->ccontext.DataOffset) + From f2f961e0983c8f339f842e1a8c351e6963793868 Mon Sep 17 00:00:00 2001 From: koraynilay Date: Thu, 12 Nov 2026 12:16:36 +0100 Subject: [PATCH 0566/2102] ksmbd: fix negative timestamps being saved to disk When setting a timestamp before epoch 0, ksmbd converts it from NT format to Unix format without normalizing it, leading to the nanoseconds field to be saved (on-disk too) as a negative number, which leads to a garbled stat command output and a reported +4 seconds in the timestamp. This bug also violates a struct timespec64 invariant, as documented in the set_normalized_timespec64() kernel-doc: [...] * Note: The tv_nsec part is always in the range of 0 <= tv_nsec < NSEC_PER_SEC. * For negative values only the tv_sec field is negative ! */ Reproducer, with /tmp as the local filesystem folder exported as [test] in ksmbd.conf and /mnt as the smb folder mounted with mount -t cifs: mount -t cifs //127.0.0.1/test /mnt -o username=user,password=pass touch /mnt/test.txt touch -d "1969-07-20 20:17:40.123456789" /mnt/test.txt stat -c "Server local (/tmp): %y" /tmp/test.txt stat -c "CIFS client (/mnt): %y" /mnt/test.txt --cached=never smbclient //127.0.0.1/test -U user%pass -c "allinfo test.txt" which prints (stat output is garbled because of negative value): Server local (/tmp): 1969-07-20 20:17:41.()*+,--00 +0000 CIFS client (/mnt): 1969-07-20 20:17:45.+(/+)*/00 +0000 altname: TESTT~K6.TXT [...] access_time: Sun Jul 20 20:17:44 1969 UTC write_time: Sun Jul 20 20:17:44 1969 UTC [...] Fix this by using set_normalized_timespec64() in ksmbd_NTtimeToUnix(). Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3") Cc: stable@vger.kernel.org Assisted-by: Gemini:3.8-flash-high antigravity-cli-1.5.3 Signed-off-by: koraynilay Reviewed-by: Ian Bridges Tested-by: Ian Bridges Signed-off-by: Namjae Jeon --- fs/smb/server/misc.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/fs/smb/server/misc.c b/fs/smb/server/misc.c index 5037f37c9226e5..94781246b4d651 100644 --- a/fs/smb/server/misc.c +++ b/fs/smb/server/misc.c @@ -336,8 +336,7 @@ struct timespec64 ksmbd_NTtimeToUnix(__le64 ntutc) if (t < 0) { abs_t = -t; ts.tv_nsec = do_div(abs_t, 10000000) * 100; - ts.tv_nsec = -ts.tv_nsec; - ts.tv_sec = -abs_t; + set_normalized_timespec64(&ts, -abs_t, -ts.tv_nsec); } else { abs_t = t; ts.tv_nsec = do_div(abs_t, 10000000) * 100; From d4912d6440bf6d255e1fa1c360c8ddb39d0e01bd Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Sun, 15 Nov 2026 08:12:06 -0700 Subject: [PATCH 0567/2102] io_uring/io-wq: show stuck workers rather than WARN on a slow exit io_wq_exit_workers() triggers a WARN_ON_ONCE() if it has waited more than IO_URING_EXIT_WAIT_MAX for the workers to exit. That can be triggered at will, for example with an open on a FUSE mount where the server never replies to the lookup. The worker can't be canceled, and the exit waits until the server goes away. The stack trace from the WARN isn't useful either, as it's that of the exiting task and that is always the task exit, exec, or SQPOLL thread exit path. Print a message and show the workers that are still around instead, that's where the interesting stack traces are. Reported-by: syzbot+b0d54b9e81de55179e47@syzkaller.appspotmail.com Signed-off-by: Jens Axboe --- io_uring/io-wq.c | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/io_uring/io-wq.c b/io_uring/io-wq.c index 92df54c6f50ca5..52ba4b06b5af3d 100644 --- a/io_uring/io-wq.c +++ b/io_uring/io-wq.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -1448,6 +1449,22 @@ static void io_wq_cancel_tw_create(struct io_wq *wq) } } +static bool io_wq_worker_show(struct io_worker *worker, void *data) +{ + sched_show_task(worker->task); + return false; +} + +/* The exit path is always the same, show what the workers are stuck on */ +static void io_wq_show_stuck_workers(struct io_wq *wq) +{ + pr_warn("io-wq: %s/%d stuck waiting for workers to exit\n", + current->comm, task_pid_nr(current)); + rcu_read_lock(); + io_wq_for_each_worker(wq, io_wq_worker_show, NULL); + rcu_read_unlock(); +} + static void io_wq_exit_workers(struct io_wq *wq) { unsigned long timeout, warn_timeout; @@ -1469,8 +1486,8 @@ static void io_wq_exit_workers(struct io_wq *wq) * * where completely overloading the system with tons of long running * io-wq items can easily trigger the hung task timeout. Only sleep - * uninterruptibly for half that time, and warn if we exceeded end - * up waiting more than IO_URING_EXIT_WAIT_MAX. + * uninterruptibly for half that time, and show the stuck workers if + * we end up waiting more than IO_URING_EXIT_WAIT_MAX. */ timeout = sysctl_hung_task_timeout_secs * HZ / 2; if (!timeout) @@ -1479,7 +1496,8 @@ static void io_wq_exit_workers(struct io_wq *wq) do { if (wait_for_completion_timeout(&wq->worker_done, timeout)) break; - WARN_ON_ONCE(time_after(jiffies, warn_timeout)); + if (time_after(jiffies, warn_timeout)) + DO_ONCE_LITE(io_wq_show_stuck_workers, wq); } while (1); spin_lock_irq(&wq->hash->wait.lock); From 78c4f290e2637f8039e2124a174a24a341b38b1e Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Sun, 15 Nov 2026 00:33:49 +0800 Subject: [PATCH 0568/2102] ublk: validate all parameters for zoned devices ublk_validate_params() returns as soon as zoned parameters are valid, skipping the subsequent DMA alignment, segment and integrity checks. SET_PARAMS therefore accepts combinations that it rejects for a non-zoned device, including integrity parameters without UBLK_F_INTEGRITY. Invalid parameters may reach disk creation or advertise an integrity format that the server cannot access. Continue checking the remaining parameter types after successful zoned validation. Preserve the zoned validator's errors and the requirement for zoned devices to supply zoned parameters. Fixes: e84025d2a9cb ("ublk: add DMA alignment limit") Signed-off-by: Shao Mingyin Reviewed-by: Ming Lei Reviewed-by: Caleb Sander Mateos Link: https://patch.msgid.link/20261115003349683IFDCSTYhPzQtBozUiO8qN@zte.com.cn Signed-off-by: Jens Axboe --- drivers/block/ublk_drv.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/drivers/block/ublk_drv.c b/drivers/block/ublk_drv.c index d415be37d5ede6..c124d703efc93c 100644 --- a/drivers/block/ublk_drv.c +++ b/drivers/block/ublk_drv.c @@ -1012,10 +1012,14 @@ static int ublk_validate_params(const struct ublk_device *ub) if (ub->params.types & UBLK_PARAM_TYPE_DEVT) return -EINVAL; - if (ub->params.types & UBLK_PARAM_TYPE_ZONED) - return ublk_dev_param_zoned_validate(ub); - else if (ublk_dev_is_zoned(ub)) + if (ub->params.types & UBLK_PARAM_TYPE_ZONED) { + int ret = ublk_dev_param_zoned_validate(ub); + + if (ret) + return ret; + } else if (ublk_dev_is_zoned(ub)) { return -EINVAL; + } if (ub->params.types & UBLK_PARAM_TYPE_DMA_ALIGN) { const struct ublk_param_dma_align *p = &ub->params.dma; From a6f37fb3f5747bb7cca5cd6630dfeea4435022a1 Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Sun, 15 Nov 2026 00:33:52 +0800 Subject: [PATCH 0569/2102] ublk: dispatch the next fetch after a batch failure When a batch fetch fails, for example because its provided-buffer group is empty, ublk_batch_dispatch() removes the failed fetch and returns. Pending I/O tags stay in evts_fifo even if another fetch with usable buffers is already queued. With no new I/O or fetch submission to select it, that fetch and the outstanding block requests cannot make progress. Claim the next queued fetch under evts_lock before completing and freeing the failed one, then schedule its dispatch in the proper task context. Marking it active before dropping the lock also prevents cancellation from taking it before its task work is queued. Fixes: a4d883755399 ("ublk: add UBLK_U_IO_FETCH_IO_CMDS for batch I/O processing") Cc: stable@vger.kernel.org Signed-off-by: Shao Mingyin Reviewed-by: Ming Lei Link: https://patch.msgid.link/20261115003352168cE_tyVxSyZV124AM31htL@zte.com.cn Signed-off-by: Jens Axboe --- drivers/block/ublk_drv.c | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/drivers/block/ublk_drv.c b/drivers/block/ublk_drv.c index c124d703efc93c..0699f22714fd42 100644 --- a/drivers/block/ublk_drv.c +++ b/drivers/block/ublk_drv.c @@ -835,23 +835,27 @@ static void __ublk_release_fcmd(struct ublk_queue *ubq) WRITE_ONCE(ubq->active_fcmd, NULL); } -/* - * Nothing can move on, so clear ->active_fcmd, and the caller should stop - * dispatching - */ -static void ublk_batch_deinit_fetch_buf(struct ublk_queue *ubq, - const struct ublk_batch_io_data *data, - struct ublk_batch_fetch_cmd *fcmd, - int res) +static struct ublk_batch_fetch_cmd *__ublk_acquire_fcmd(struct ublk_queue *ubq); + +/* Remove the failed fetch and claim the next one before dropping its reference. */ +static struct ublk_batch_fetch_cmd * +ublk_batch_deinit_fetch_buf(struct ublk_queue *ubq, + const struct ublk_batch_io_data *data, + struct ublk_batch_fetch_cmd *fcmd, + int res) { + struct ublk_batch_fetch_cmd *next_fcmd; + spin_lock(&ubq->evts_lock); list_del_init(&fcmd->node); WARN_ON_ONCE(fcmd != ubq->active_fcmd); __ublk_release_fcmd(ubq); + next_fcmd = __ublk_acquire_fcmd(ubq); spin_unlock(&ubq->evts_lock); io_uring_cmd_done(fcmd->cmd, res, data->issue_flags); ublk_batch_free_fcmd(fcmd); + return next_fcmd; } static int ublk_batch_fetch_post_cqe(struct ublk_batch_fetch_cmd *fcmd, @@ -2045,7 +2049,10 @@ ublk_batch_dispatch(struct ublk_queue *ubq, } if (ret < 0) { - ublk_batch_deinit_fetch_buf(ubq, data, fcmd, ret); + new_fcmd = ublk_batch_deinit_fetch_buf(ubq, data, fcmd, ret); + if (new_fcmd) + io_uring_cmd_complete_in_task(new_fcmd->cmd, + ublk_batch_tw_cb); return; } From 52aedfca88cdc3c5676f65ce8ab01f87eac9e132 Mon Sep 17 00:00:00 2001 From: "Rafael J. Wysocki" Date: Fri, 13 Nov 2026 15:29:01 +0100 Subject: [PATCH 0570/2102] ACPI: CPPC: Drop compliance checks involving nominal performance On a number of Intel platforms in the field, the nominal performance value in ACPI _CPC (which is an integer embedded in the _CPC package) is less than the guaranteed performance value, and it may even be less than the minimum nonlinear performance value or greater than the highest performance value (that all come from register reads). The new specification compliance checks involving those values added by commit 32299b29a887 ("ACPI: CPPC: Validate _CPC entry and control semantics") cause the CPPC library to refuse to work for some CPUs on the affected systems which in turn causes the intel_pstate driver to overestimate the maximum performance levels for those CPUs. One of the affected systems is Dell Pro 5 14 P514260. In this particular case, the fact that the specification is not exactly followed has no implications and the checks enforcing compliance are not really useful, so drop the checks in question from the CPPC library. If really necessary, they will need to be done elsewhere. Fixes: 32299b29a887 ("ACPI: CPPC: Validate _CPC entry and control semantics") Reviewed-by: Christian Loehle Signed-off-by: Rafael J. Wysocki Link: https://patch.msgid.link/6060382.DvuYhMxLoT@rafael.j.wysocki --- drivers/acpi/cppc_acpi.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/acpi/cppc_acpi.c b/drivers/acpi/cppc_acpi.c index 24fc26d45a782d..b4cf93dec18b5c 100644 --- a/drivers/acpi/cppc_acpi.c +++ b/drivers/acpi/cppc_acpi.c @@ -2949,9 +2949,9 @@ int cppc_get_perf_caps(int cpunum, struct cppc_perf_caps *perf_caps) if (!high || !low || !nom || !ref || !min_nonlinear || high > U32_MAX || low > U32_MAX || guaranteed > U32_MAX || nom > U32_MAX || ref > U32_MAX || min_nonlinear > U32_MAX || - high < nom || nom < min_nonlinear || min_nonlinear < low || + high < min_nonlinear || min_nonlinear < low || (CPC_SUPPORTED(guaranteed_reg) && - (guaranteed < low || guaranteed > nom))) { + (guaranteed < low || guaranteed > high))) { ret = -EFAULT; goto out_err; } From 22139b5a46353184f43d120b569b01447843d363 Mon Sep 17 00:00:00 2001 From: Sankara Tankala Date: Fri, 13 Nov 2026 21:10:01 +0530 Subject: [PATCH 0571/2102] thermal: int340x: processor_thermal: Fix Nova Lake-S PCI device ID Nova Lake-S uses the same processor thermal PCI device ID as Nova Lake-H, 0xD703. The 0xAD03 ID added for Nova Lake-S is the Arrow Lake-S ID (PCI_DEVICE_ID_INTEL_ARL_S_THERMAL). The ARL-S entry comes first in the PCI ID table, so the NVL-S entry never matched. However, proc_thermal_rfim_add() matches on the device ID alone, so Arrow Lake-S, which has DLVR, wrongly gets the Nova Lake DLVR register map. Replace the separate NVL_H and NVL_S IDs with a single NVL ID, 0xD703, and drop the 0xAD03 entries. Fixes: af1b80b94126 ("thermal: int340x: processor_thermal: Add Nova Lake processor thermal device") Fixes: dbd911a07f14 ("thermal: intel: int340x: Add DLVR support for Nova Lake") Cc: stable@vger.kernel.org Signed-off-by: Sankara Tankala Acked-by: Srinivas Pandruvada Link: https://patch.msgid.link/20261113154001.2081-1-sankara.narayana@intel.com Signed-off-by: Rafael J. Wysocki --- .../intel/int340x_thermal/processor_thermal_device.h | 3 +-- .../intel/int340x_thermal/processor_thermal_device_pci.c | 7 +------ .../thermal/intel/int340x_thermal/processor_thermal_rfim.c | 3 +-- 3 files changed, 3 insertions(+), 10 deletions(-) diff --git a/drivers/thermal/intel/int340x_thermal/processor_thermal_device.h b/drivers/thermal/intel/int340x_thermal/processor_thermal_device.h index b79937a386ec0f..87d8ff9c717352 100644 --- a/drivers/thermal/intel/int340x_thermal/processor_thermal_device.h +++ b/drivers/thermal/intel/int340x_thermal/processor_thermal_device.h @@ -27,8 +27,7 @@ #define PCI_DEVICE_ID_INTEL_JSL_THERMAL 0x4E03 #define PCI_DEVICE_ID_INTEL_LNLM_THERMAL 0x641D #define PCI_DEVICE_ID_INTEL_MTLP_THERMAL 0x7D03 -#define PCI_DEVICE_ID_INTEL_NVL_H_THERMAL 0xD703 -#define PCI_DEVICE_ID_INTEL_NVL_S_THERMAL 0xAD03 +#define PCI_DEVICE_ID_INTEL_NVL_THERMAL 0xD703 #define PCI_DEVICE_ID_INTEL_RPL_THERMAL 0xA71D #define PCI_DEVICE_ID_INTEL_SKL_THERMAL 0x1903 #define PCI_DEVICE_ID_INTEL_TGL_THERMAL 0x9A03 diff --git a/drivers/thermal/intel/int340x_thermal/processor_thermal_device_pci.c b/drivers/thermal/intel/int340x_thermal/processor_thermal_device_pci.c index 7d6fee59ade202..f218ee247ab485 100644 --- a/drivers/thermal/intel/int340x_thermal/processor_thermal_device_pci.c +++ b/drivers/thermal/intel/int340x_thermal/processor_thermal_device_pci.c @@ -501,12 +501,7 @@ static const struct pci_device_id proc_thermal_pci_ids[] = { PROC_THERMAL_FEATURE_DVFS | PROC_THERMAL_FEATURE_WT_HINT | PROC_THERMAL_FEATURE_POWER_FLOOR | PROC_THERMAL_FEATURE_PTC | PROC_THERMAL_FEATURE_SOC_POWER_SLIDER) }, - { PCI_DEVICE_DATA(INTEL, NVL_H_THERMAL, PROC_THERMAL_FEATURE_RAPL | - PROC_THERMAL_FEATURE_DLVR | PROC_THERMAL_FEATURE_DVFS | - PROC_THERMAL_FEATURE_MSI_SUPPORT | PROC_THERMAL_FEATURE_WT_HINT | - PROC_THERMAL_FEATURE_POWER_FLOOR | PROC_THERMAL_FEATURE_PTC | - PROC_THERMAL_FEATURE_SOC_POWER_SLIDER) }, - { PCI_DEVICE_DATA(INTEL, NVL_S_THERMAL, PROC_THERMAL_FEATURE_RAPL | + { PCI_DEVICE_DATA(INTEL, NVL_THERMAL, PROC_THERMAL_FEATURE_RAPL | PROC_THERMAL_FEATURE_DLVR | PROC_THERMAL_FEATURE_DVFS | PROC_THERMAL_FEATURE_MSI_SUPPORT | PROC_THERMAL_FEATURE_WT_HINT | PROC_THERMAL_FEATURE_POWER_FLOOR | PROC_THERMAL_FEATURE_PTC | diff --git a/drivers/thermal/intel/int340x_thermal/processor_thermal_rfim.c b/drivers/thermal/intel/int340x_thermal/processor_thermal_rfim.c index 96279756177f67..1832f13634d857 100644 --- a/drivers/thermal/intel/int340x_thermal/processor_thermal_rfim.c +++ b/drivers/thermal/intel/int340x_thermal/processor_thermal_rfim.c @@ -472,8 +472,7 @@ int proc_thermal_rfim_add(struct pci_dev *pdev, struct proc_thermal_device *proc dlvr_mmio_regs_table = lnl_dlvr_mmio_regs; dlvr_mapping = lnl_dlvr_mapping; break; - case PCI_DEVICE_ID_INTEL_NVL_H_THERMAL: - case PCI_DEVICE_ID_INTEL_NVL_S_THERMAL: + case PCI_DEVICE_ID_INTEL_NVL_THERMAL: dlvr_mmio_regs_table = nvl_dlvr_mmio_regs; ddr_data_rate_reg = &nvl_ddr_data_rate_reg; break; From e6872defbb2eb1dc61b3ea168ca13e1362efbd86 Mon Sep 17 00:00:00 2001 From: Wayne Ho Date: Fri, 13 Nov 2026 13:48:57 +0800 Subject: [PATCH 0572/2102] hwmon: (sht3x) Fix overflow when writing alert limits limit_write() encodes the limits with 32-bit arithmetic, which overflows for the largest accepted values: (130000 + 45000) * 24543 = 4295025000 > U32_MAX 100000 * 42950 = 4295000000 > U32_MAX Writing 130000 to temp1_max therefore programs -45 degrees C, and writing 100000 to humidity1_max programs 0 %RH, so a limit set to its maximum makes the alert fire instead of never firing. Reading the attributes back returns the cached values, so this is not visible from sysfs. Use 64-bit arithmetic and clamp each result to its field width. Even with 64-bit arithmetic, 130000 encodes to 0x200, which overflows the 9-bit temperature field, and 100000 encodes to 0x10000, which is still 0 after masking. Prepared with the help of an AI coding assistant (Claude); I reproduced the bug and tested the fix on hardware. Fixes: 7c84f7f80d6f ("hwmon: add support for Sensirion SHT3x sensors") Cc: stable@vger.kernel.org Reported-by: Sashiko Closes: https://lore.kernel.org/linux-hwmon/20260725222229.EA69B1F000E9@smtp.kernel.org/ Signed-off-by: Wayne Ho Link: https://patch.msgid.link/20261113054857.97048-1-wayneho219@gmail.com Signed-off-by: Guenter Roeck --- drivers/hwmon/sht3x.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/hwmon/sht3x.c b/drivers/hwmon/sht3x.c index c217a4d0c9f18d..697b54e0ad9469 100644 --- a/drivers/hwmon/sht3x.c +++ b/drivers/hwmon/sht3x.c @@ -387,8 +387,8 @@ static size_t limit_write(struct device *dev, * adapted for fixed point arithmetic and packed the same as * in limit_read() */ - raw = ((u32)(temperature + 45000) * 24543) >> (16 + 7); - raw |= ((humidity * 42950) >> 16) & 0xfe00; + raw = min(((u64)(temperature + 45000) * 24543) >> (16 + 7), 0x1ff); + raw |= min(((u64)humidity * 42950) >> 16, 0xffff) & 0xfe00; put_unaligned_be16(raw, position); position += SHT3X_WORD_LEN; From 69624d7d821ec7d3f9801e86acf555a8edc82f99 Mon Sep 17 00:00:00 2001 From: Rosen Penev Date: Fri, 13 Nov 2026 22:20:23 -0800 Subject: [PATCH 0573/2102] hwmon: (dell-smm) Reject a fan_max that the BIOS cannot take The fan_max module parameter is used without any range check, unlike fan_mult. dell_smm_init_hwmon() allocates the nominal speed table with devm_kmalloc_array(dev, data->i8k_fan_max + 1, ...) and fan_max=4294967295 wraps the count to 0. devm_kmalloc() then returns ZERO_SIZE_PTR, which the first successful nominal speed call writes through. Values above 255 are also meaningless: the fan state is passed to the BIOS as fan | (speed << 8), so the higher bits end up in other parts of the request. Large values that do not wrap still cost one SMM call per state and fan while probing. Fail probing if the maximum fan state does not fit in a byte, like the existing check for fan_mult. Fixes: 81474fc2fae9 ("i8k: Add support for configurable maximum fan speed value") cc: stable@vger.kernel.org Signed-off-by: Rosen Penev Link: https://patch.msgid.link/6d3b86acf6713e9286e60ecf788582e840946238.1794633179.git.rosenp@gmail.com Signed-off-by: Guenter Roeck --- drivers/hwmon/dell-smm-hwmon.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/hwmon/dell-smm-hwmon.c b/drivers/hwmon/dell-smm-hwmon.c index 5ec487843faaa8..47c06376aa528a 100644 --- a/drivers/hwmon/dell-smm-hwmon.c +++ b/drivers/hwmon/dell-smm-hwmon.c @@ -1248,6 +1248,12 @@ static int dell_smm_init_data(struct device *dev, const struct dell_smm_ops *ops return -EINVAL; } data->i8k_fan_max = fan_max ? : I8K_FAN_HIGH; + /* The BIOS takes the fan state in a single byte */ + if (data->i8k_fan_max > U8_MAX) { + dev_err(dev, "maximum fan state %u is too large (max %u)\n", + data->i8k_fan_max, U8_MAX); + return -EINVAL; + } data->i8k_pwm_mult = DIV_ROUND_UP(255, data->i8k_fan_max); return 0; From 07571b42cf41d0e42fb890713340a8f0a3c03d56 Mon Sep 17 00:00:00 2001 From: Ziheng Wei Date: Sun, 15 Nov 2026 16:02:01 +0800 Subject: [PATCH 0574/2102] hwmon: (nct6775) Fix incorrect struct cast in beep callbacks On big-endian architectures, writing the in[1-*]_beep, fan[1-*]_beep and temp[1-*]_beep sysfs attributes in the nct6775 hardware monitoring driver always changes channel 0 due to an incorrect struct downcast in the beep store callbacks. The driver defines these sysfs attributes using SENSOR_TEMPLATE(), which initializes them as struct sensor_device_attribute (where the index is a 32-bit int). However, the sysfs store callbacks nct6775_store_beep() and store_temp_beep() incorrectly downcast the attribute to a struct sensor_device_attribute_2 (where the index is an 8-bit u8). Because both structs start with struct device_attribute, container_of() resolves to the same base address. On big-endian architectures, reading the 8-bit index field from the memory layout of a 32-bit int fetches the most significant byte (which is 0), rather than the intended channel number. This type mismatch causes all beep writes to change the beep setting of channel 0, regardless of which channel the user targeted. Fix the type casts in the two store callbacks. Not runtime-tested: the only big-endian machine available to me (s390x under QEMU) cannot build the platform driver (no HAS_IOPORT). Fixes: 30846993047b ("hwmon: (nct6775) Add support for beep attributes") Cc: stable@vger.kernel.org Signed-off-by: Ziheng Wei Link: https://patch.msgid.link/20261115080203.910033-2-zihengw03@163.com Signed-off-by: Guenter Roeck --- drivers/hwmon/nct6775-core.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/hwmon/nct6775-core.c b/drivers/hwmon/nct6775-core.c index 3515a962adac85..ac6f3f0ca2b363 100644 --- a/drivers/hwmon/nct6775-core.c +++ b/drivers/hwmon/nct6775-core.c @@ -1857,7 +1857,7 @@ EXPORT_SYMBOL_GPL(nct6775_show_beep); ssize_t nct6775_store_beep(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - struct sensor_device_attribute_2 *sattr = to_sensor_dev_attr_2(attr); + struct sensor_device_attribute *sattr = to_sensor_dev_attr(attr); struct nct6775_data *data = dev_get_drvdata(dev); int nr = data->BEEP_BITS[sattr->index]; int regindex = nr >> 3; @@ -1911,7 +1911,7 @@ static ssize_t store_temp_beep(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - struct sensor_device_attribute_2 *sattr = to_sensor_dev_attr_2(attr); + struct sensor_device_attribute *sattr = to_sensor_dev_attr(attr); struct nct6775_data *data = dev_get_drvdata(dev); int nr, bit, regindex; unsigned long val; From fb47eb0528d275362b01423ceb956e3ce1f9d715 Mon Sep 17 00:00:00 2001 From: Ziheng Wei Date: Sun, 15 Nov 2026 16:02:02 +0800 Subject: [PATCH 0575/2102] hwmon: (w83791d) Fix incorrect struct cast in show_temp1() and store_temp1() On big-endian architectures, accessing the temp1_max and temp1_max_hyst sysfs attributes in the w83791d hardware monitoring driver uses a huge out-of-bounds index, because show_temp1() and store_temp1() downcast the attribute to the wrong struct. The driver defines the temp1_* attributes with SENSOR_ATTR_2(), which initializes them as struct sensor_device_attribute_2 (where the index is an 8-bit u8). The temp1_input attribute has index 0, temp1_max has index 1 and temp1_max_hyst has index 2. However, show_temp1() and store_temp1() downcast the attribute to struct sensor_device_attribute (where the index is a 32-bit int) and use it to index data->temp1[]. Because both structs start with struct device_attribute, container_of() resolves to the same base address, but the field widths differ. On big-endian architectures, reading the 32-bit int from the memory layout of the two u8 fields yields index << 24: 0x01000000 for temp1_max and 0x02000000 for temp1_max_hyst, instead of 1 and 2. data->temp1[] has only 3 elements, so the access runs off the end of the array by up to 32 MiB. Fix the type casts in show_temp1() and store_temp1(). Confirmed on a big-endian s390x QEMU guest with the driver bound to an emulated chip: temp1_max and temp1_max_hyst read 0 instead of the register values. Not tested on real hardware. Fixes: 9873964d6eb2 ("[PATCH] HWMON: w83791d: New hardware monitoring driver for the Winbond W83791D") Cc: stable@vger.kernel.org Signed-off-by: Ziheng Wei Link: https://patch.msgid.link/20261115080203.910033-3-zihengw03@163.com Signed-off-by: Guenter Roeck --- drivers/hwmon/w83791d.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/hwmon/w83791d.c b/drivers/hwmon/w83791d.c index 8bb457326c0bce..530935a6df7fc2 100644 --- a/drivers/hwmon/w83791d.c +++ b/drivers/hwmon/w83791d.c @@ -924,7 +924,7 @@ static struct sensor_device_attribute sda_temp_tolerance[] = { static ssize_t show_temp1(struct device *dev, struct device_attribute *devattr, char *buf) { - struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr); + struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr); struct w83791d_data *data = w83791d_update_device(dev); return sprintf(buf, "%d\n", TEMP1_FROM_REG(data->temp1[attr->index])); } @@ -932,7 +932,7 @@ static ssize_t show_temp1(struct device *dev, struct device_attribute *devattr, static ssize_t store_temp1(struct device *dev, struct device_attribute *devattr, const char *buf, size_t count) { - struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr); + struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr); struct i2c_client *client = to_i2c_client(dev); struct w83791d_data *data = i2c_get_clientdata(client); int nr = attr->index; From d4f7d626cc1a966dca930a5ba07e8c4739adceb0 Mon Sep 17 00:00:00 2001 From: Ziheng Wei Date: Sun, 15 Nov 2026 16:02:03 +0800 Subject: [PATCH 0576/2102] hwmon: (w83792d) Fix incorrect struct cast in show_temp1() and store_temp1() On big-endian architectures, accessing the temp1_max and temp1_max_hyst sysfs attributes in the w83792d hardware monitoring driver uses a huge out-of-bounds index, because show_temp1() and store_temp1() downcast the attribute to the wrong struct. The driver defines the temp1_* attributes with SENSOR_DEVICE_ATTR_2(), which initializes them as struct sensor_device_attribute_2 (where the index is an 8-bit u8). The temp1_input attribute has index 0, temp1_max has index 1 and temp1_max_hyst has index 2. However, show_temp1() and store_temp1() downcast the attribute to struct sensor_device_attribute (where the index is a 32-bit int) and use it to index data->temp1[]. Because both structs start with struct device_attribute, container_of() resolves to the same base address, but the field widths differ. On big-endian architectures, reading the 32-bit int from the memory layout of the two u8 fields yields index << 24: 0x01000000 for temp1_max and 0x02000000 for temp1_max_hyst, instead of 1 and 2. data->temp1[] has only 3 elements, so the access runs off the end of the array by up to 32 MiB. Fix the type casts in show_temp1() and store_temp1(). Confirmed on a big-endian s390x QEMU guest with the driver bound to an emulated chip: temp1_max and temp1_max_hyst read 0 instead of the register values. Not tested on real hardware. Fixes: 1f8dae31fe8d ("[PATCH] hwmon: w83792d use arrays of attributes") Cc: stable@vger.kernel.org Signed-off-by: Ziheng Wei Link: https://patch.msgid.link/20261115080203.910033-4-zihengw03@163.com Signed-off-by: Guenter Roeck --- drivers/hwmon/w83792d.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/hwmon/w83792d.c b/drivers/hwmon/w83792d.c index 2de6d7b685836b..cba9077134b67e 100644 --- a/drivers/hwmon/w83792d.c +++ b/drivers/hwmon/w83792d.c @@ -487,7 +487,7 @@ store_fan_div(struct device *dev, struct device_attribute *attr, static ssize_t show_temp1(struct device *dev, struct device_attribute *attr, char *buf) { - struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr); + struct sensor_device_attribute_2 *sensor_attr = to_sensor_dev_attr_2(attr); int nr = sensor_attr->index; struct w83792d_data *data = w83792d_update_device(dev); return sprintf(buf, "%d\n", TEMP1_FROM_REG(data->temp1[nr])); @@ -496,7 +496,7 @@ static ssize_t show_temp1(struct device *dev, struct device_attribute *attr, static ssize_t store_temp1(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr); + struct sensor_device_attribute_2 *sensor_attr = to_sensor_dev_attr_2(attr); int nr = sensor_attr->index; struct i2c_client *client = to_i2c_client(dev); struct w83792d_data *data = i2c_get_clientdata(client); From 4e83ea5b22193fd0db8bcee5682935f1d528705e Mon Sep 17 00:00:00 2001 From: Zhao Feng Date: Wed, 11 Nov 2026 16:32:36 +0800 Subject: [PATCH 0577/2102] watchdog: npcm: fix sleeping clock call in restart handler The watchdog .restart callback runs in atomic context: it is invoked from the restart handler chain via atomic_notifier_call_chain(), under an RCU read-side critical section, on every reboot or restart. Since commit af084fdccfaf ("watchdog: npcm: Enable clock if provided"), npcm_wdt_restart() calls clk_prepare_enable(), and clk_prepare() takes a mutex unconditionally, so kernels built with CONFIG_DEBUG_ATOMIC_SLEEP=y report BUG: sleeping function called from invalid context on every reboot. Worse, a panic-time restart can block on prepare_lock and never issue the reset at all. Get the clock with devm_clk_get_optional_prepared() at probe time and keep it prepared for the lifetime of the driver, so the restart handler only needs clk_enable(), which is safe in atomic context. With the clock permanently prepared, npcm_wdt_start() and npcm_wdt_stop() are simplified to clk_enable()/clk_disable() as well. Fixes: af084fdccfaf ("watchdog: npcm: Enable clock if provided") Cc: stable@vger.kernel.org Signed-off-by: Zhao Feng Link: https://patch.msgid.link/20261111083236.248-1-zhaofeng2@cmss.chinamobile.com Signed-off-by: Guenter Roeck --- drivers/watchdog/npcm_wdt.c | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/drivers/watchdog/npcm_wdt.c b/drivers/watchdog/npcm_wdt.c index 07ea810fb8c90e..df7f66e7796508 100644 --- a/drivers/watchdog/npcm_wdt.c +++ b/drivers/watchdog/npcm_wdt.c @@ -180,7 +180,7 @@ static int npcm_wdt_start(struct watchdog_device *wdd) { struct npcm_wdt *wdt = to_npcm_wdt(wdd); - clk_prepare_enable(wdt->clk); + clk_enable(wdt->clk); __npcm_wdt_start(wdd); @@ -193,7 +193,7 @@ static int npcm_wdt_stop(struct watchdog_device *wdd) writel(0, wdt->reg); - clk_disable_unprepare(wdt->clk); + clk_disable(wdt->clk); return 0; } @@ -242,8 +242,12 @@ static int npcm_wdt_restart(struct watchdog_device *wdd, { struct npcm_wdt *wdt = to_npcm_wdt(wdd); - /* For reset, we start the WDT clock and leave it running. */ - clk_prepare_enable(wdt->clk); + /* + * For reset, we start the WDT clock and leave it running. + * The clock was prepared at probe time; only clk_enable() is + * safe in this atomic (restart notifier) context. + */ + clk_enable(wdt->clk); writel(NPCM_WTR | NPCM_WTRE | NPCM_WTE, wdt->reg); udelay(1000); @@ -417,7 +421,12 @@ static int npcm_wdt_probe(struct platform_device *pdev) start = res->start; - wdt->clk = devm_clk_get_optional(&pdev->dev, NULL); + /* + * Keep the clock prepared for the lifetime of the driver: + * npcm_wdt_restart() runs in atomic context and may only call + * clk_enable(). + */ + wdt->clk = devm_clk_get_optional_prepared(&pdev->dev, NULL); if (IS_ERR(wdt->clk)) return PTR_ERR(wdt->clk); From 38828d44f31e4366b2963d5786d06d3358e8ae58 Mon Sep 17 00:00:00 2001 From: Song Liu Date: Tue, 10 Nov 2026 21:35:51 -0800 Subject: [PATCH 0578/2102] rcu-tasks: Use pr_debug() for callback contend/collapse messages Commit 5de907d24919 ("rcu-tasks: Disable callback contend/collapse messages by default") added the rcupdate.rcu_task_collapse_debug module parameter to gate the three pr_info() messages that report RCU Tasks switching between CPU-0 and per-CPU callback queuing. The kernel already has a mechanism for debug-only messages that are off by default: pr_debug(). Use pr_debug() for these messages, and remove the rcu_task_collapse_debug module parameter, its documentation, and its boot-time announcement. The messages stay off by default. On CONFIG_DYNAMIC_DEBUG=y kernels, they can be enabled at boot with: dyndbg="file kernel/rcu/tasks.h +p" or at runtime with: echo 'file kernel/rcu/tasks.h +p' > /proc/dynamic_debug/control Assisted-by: Claude:claude-opus-5 Signed-off-by: Song Liu Reviewed-by: Joel Fernandes Reviewed-by: Paul E. McKenney Tested-by: Breno Leitao Signed-off-by: Joel Fernandes --- Documentation/admin-guide/kernel-parameters.txt | 7 ------- kernel/rcu/tasks.h | 15 +++------------ 2 files changed, 3 insertions(+), 19 deletions(-) diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt index 0b3c140babd944..176648941aec2b 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -6369,13 +6369,6 @@ Kernel parameters period to instead use normal non-expedited grace-period processing. - rcupdate.rcu_task_collapse_debug= [KNL] - Enable debugging prints that record when RCU Tasks - and RCU Tasks Trace expand to per-CPU callback - queuing and collapse back to CPU-0 queuing. - This is default-disabled due to the fact that - some workloads can make it quite noisy. - rcupdate.rcu_task_collapse_lim= [KNL] Set the maximum number of callbacks present at the beginning of a grace period that allows diff --git a/kernel/rcu/tasks.h b/kernel/rcu/tasks.h index fcac7361ec51ec..743f777b4c18fe 100644 --- a/kernel/rcu/tasks.h +++ b/kernel/rcu/tasks.h @@ -178,8 +178,6 @@ static int rcu_task_contend_lim __read_mostly = 100; module_param(rcu_task_contend_lim, int, 0444); static int rcu_task_collapse_lim __read_mostly = 10; module_param(rcu_task_collapse_lim, int, 0444); -static bool rcu_task_collapse_debug __read_mostly; -module_param(rcu_task_collapse_debug, bool, 0644); static int rcu_task_lazy_lim __read_mostly = 32; module_param(rcu_task_lazy_lim, int, 0444); @@ -392,8 +390,7 @@ static void call_rcu_tasks_generic(struct rcu_head *rhp, rcu_callback_t func, WRITE_ONCE(rtp->percpu_enqueue_shift, 0); WRITE_ONCE(rtp->percpu_dequeue_lim, rcu_task_cpu_ids); smp_store_release(&rtp->percpu_enqueue_lim, rcu_task_cpu_ids); - if (data_race(rcu_task_collapse_debug)) - pr_info("Switching %s to per-CPU callback queuing.\n", rtp->name); + pr_debug("Switching %s to per-CPU callback queuing.\n", rtp->name); } raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags); } @@ -514,9 +511,7 @@ static int rcu_tasks_need_gpcb(struct rcu_tasks *rtp) smp_store_release(&rtp->percpu_enqueue_lim, 1); rtp->percpu_dequeue_gpseq = get_state_synchronize_rcu(); gpdone = false; - if (data_race(rcu_task_collapse_debug)) - pr_info("Starting switch %s to CPU-0 callback queuing.\n", - rtp->name); + pr_debug("Starting switch %s to CPU-0 callback queuing.\n", rtp->name); } raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags); } @@ -524,9 +519,7 @@ static int rcu_tasks_need_gpcb(struct rcu_tasks *rtp) raw_spin_lock_irqsave(&rtp->cbs_gbl_lock, flags); if (rtp->percpu_enqueue_lim < rtp->percpu_dequeue_lim) { WRITE_ONCE(rtp->percpu_dequeue_lim, 1); - if (data_race(rcu_task_collapse_debug)) - pr_info("Completing switch %s to CPU-0 callback queuing.\n", - rtp->name); + pr_debug("Completing switch %s to CPU-0 callback queuing.\n", rtp->name); } if (rtp->percpu_dequeue_lim == 1) { for (cpu = rtp->percpu_dequeue_lim; cpu < rcu_task_cpu_ids; cpu++) { @@ -711,8 +704,6 @@ static void __init rcu_tasks_bootup_oddness(void) pr_info("\tTasks-RCU CPU stall info multiplier clamped to %d (rcu_task_stall_info_mult).\n", rtsimc); rcu_task_stall_info_mult = rtsimc; } - if (rcu_task_collapse_debug) - pr_info("\tTasks-RCU callback contend/collapse debug enabled.\n"); #endif /* #ifdef CONFIG_TASKS_RCU */ #ifdef CONFIG_TASKS_RCU pr_info("\tTrampoline variant of Tasks RCU enabled.\n"); From c3f98ff6309a29979e1867bc3c9d4172755ca122 Mon Sep 17 00:00:00 2001 From: Nathan Chancellor Date: Sat, 14 Nov 2026 21:26:10 -0700 Subject: [PATCH 0579/2102] rcu/nocb: Avoid unsequenced accesses to jiffies in show_rcu_nocb_state() After a recent improvement in clang to warn on unsequenced accesses to volatile variables [1], an instance appears in show_rcu_nocb_state(), which can break the build with CONFIG_WERROR=y / W=e: In file included from kernel/rcu/tree.c:5123: kernel/rcu/tree_nocb.h:1651:3: error: unsequenced accesses to volatile qualified 'jiffies' [-Werror,-Wunsequenced] 1650 | jiffies - rdp->nocb_bypass_first, | ~~~~~~~ 1651 | jiffies - rdp->nocb_nobypass_last, | ^ Per C11 5.1.2.3.2, accessing a volatile object is a side effect. Per C11 6.5.2, unsequenced side effects on the same scalar object are undefined behavior. Per C11 6.5.2.2.10/12, the evaluation of arguments in a function call is indeterminately sequenced, meaning any side effects in the arguments are unsequenced. Add a local variable to hold the value of jiffies before the function call so that there are no unsequenced side effects, clearing up the warning. Cc: stable@vger.kernel.org Fixes: f7a81b12d6af ("rcu/nocb: Print no-CBs diagnostics when rcutorture writer unduly delayed") Closes: https://github.com/ClangBuiltLinux/linux/issues/2192 Link: https://github.com/llvm/llvm-project/commit/955715460eaf9188c241c74750637fc82dfcc423 [1] Signed-off-by: Nathan Chancellor Reviewed-by: Joel Fernandes Signed-off-by: Joel Fernandes --- kernel/rcu/tree_nocb.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/kernel/rcu/tree_nocb.h b/kernel/rcu/tree_nocb.h index b6cfee4e503997..8448a7c578e84c 100644 --- a/kernel/rcu/tree_nocb.h +++ b/kernel/rcu/tree_nocb.h @@ -1618,6 +1618,7 @@ static void show_rcu_nocb_state(struct rcu_data *rdp) struct rcu_segcblist *rsclp = &rdp->cblist; bool waslocked; bool wassleep; + unsigned long j; if (rdp->nocb_gp_rdp == rdp) show_rcu_nocb_gp_state(rdp); @@ -1639,6 +1640,7 @@ static void show_rcu_nocb_state(struct rcu_data *rdp) rsclp->gp_seq[RCU_NEXT_READY_TAIL].exp); sprintf(bufn, "%ld", rsclp->seglen[RCU_NEXT_TAIL]); sprintf(bufb, "%ld", rcu_cblist_n_cbs(&rdp->nocb_bypass)); + j = jiffies; pr_info(" CB %d^%d->%d %c%c%c%c%c F%ld L%ld C%d %c%s%c%s%c%s%c%s%c%s q%ld %c CPU %d%s\n", rdp->cpu, rdp->nocb_gp_rdp->cpu, nocb_next_rdp ? nocb_next_rdp->cpu : -1, @@ -1647,8 +1649,8 @@ static void show_rcu_nocb_state(struct rcu_data *rdp) "lL"[raw_spin_is_locked(&rdp->nocb_lock)], "sS"[!!rdp->nocb_cb_sleep], ".W"[swait_active(&rdp->nocb_cb_wq)], - jiffies - rdp->nocb_bypass_first, - jiffies - rdp->nocb_nobypass_last, + j - rdp->nocb_bypass_first, + j - rdp->nocb_nobypass_last, rdp->nocb_nobypass_count, ".D"[rcu_segcblist_ready_cbs(rsclp)], rcu_segcblist_segempty(rsclp, RCU_DONE_TAIL) ? "" : bufd, From 5ae07c10854f7ac38da02e8313a59dfcfeb44a61 Mon Sep 17 00:00:00 2001 From: Julian Anastasov Date: Mon, 5 Oct 2026 13:06:17 +0000 Subject: [PATCH 0580/2102] ipvs: fix problems during connection deletion Sashiko reports for problem when deleting connections. If connection timer expires, its callback can not be concurrently running but if connection is deleted the callback can be running on another CPU even after all references are released. Before now we continued with the connection freeing, risking the callback to access the deleted connection after it is freed. As ip_vs_conn_del() runs under RCU lock there is no risk for accessing a connection freed by concurrent timer callback. As Sashiko warns, the risk is present if normal connection expires and tries to delete its cp->control chain with ip_vs_conn_del_put() without holding a RCU read lock. It is evident that as the pending timer and the running timer callback do not hold reference for the connection, there are races which is difficult to avoid. Change the connection refcounting as follows: * the connection hashing does not take reference anymore * new connection handoffs its reference to the timer if started in __ip_vs_conn_put_timer(), to hold it while it is pending. * if user finds connection in hash table it gets reference and can handoff this reference to the pending timer if this timer is started in __ip_vs_conn_put_timer(), otherwise puts its reference if the timer was already pending which is the common case. * the pending timer handoffs its reference to the running timer callback implicitly. By this way, the timer callback in the common case has the last reference. In rare cases, while the timer callback is running and before it changes refcnt from 1 to 0, other users can get reference and to handoff it again to the pending timer they arm. In this case, the expiration is deferred for later time. As result, cp->refcnt accounts all current connection users and the pending and running timer. Two paths can try to delete the connection: the normal expiration path and ip_vs_conn_del() if it successfully steals the connection reference from the pending timer. refcount_dec_if_one() will tell us if we were the last active user with no packets accessing the connection and no pending/running timers. Change ip_vs_conn_unlink() to directly unhash the connection because when we are the last user the connection's forwarding method can not change. Use smp_acquire__after_ctrl_dep() after refcount_dec_if_one() and before reading the connection fields. ip_vs_conn_expire() does not need to call timer_delete() anymore because the pending timer is already accounted in refcnt. Add explicit rcu_read_lock() while deleting the cp->control chain to protect from concurrent timer callback for ct to expire it before us and to cause use-after-free. During such races, try to keep 0 in cp->timeout as it is a request for deleting our cp->control chain immediately. Make sure we do not send timeout 0 (seconds) in the v1 sync message because the backup server will select some large default value which is not desired for small timeouts. Remove the smp_mb__before_atomic() call from __ip_vs_conn_put(), it is from the atomic_dec() era, now refcount_dec() has RELEASE semantics. Link: https://sashiko.dev/#/patchset/cover.1789435989.git.zihanx%40nebusec.ai Link: https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1790266803.git.zihanx%40nebusec.ai Fixes: f9200a52eedf ("ipvs: avoid expiring many connections from timer") Signed-off-by: Julian Anastasov Signed-off-by: Pablo Neira Ayuso --- include/net/ip_vs.h | 1 - net/netfilter/ipvs/ip_vs_conn.c | 99 ++++++++++++++++++--------------- net/netfilter/ipvs/ip_vs_sync.c | 2 +- 3 files changed, 55 insertions(+), 47 deletions(-) diff --git a/include/net/ip_vs.h b/include/net/ip_vs.h index 9a83bff32569da..97097d60d1c4b5 100644 --- a/include/net/ip_vs.h +++ b/include/net/ip_vs.h @@ -1685,7 +1685,6 @@ static inline bool __ip_vs_conn_get(struct ip_vs_conn *cp) /* put back the conn without restarting its timer */ static inline void __ip_vs_conn_put(struct ip_vs_conn *cp) { - smp_mb__before_atomic(); refcount_dec(&cp->refcnt); } void ip_vs_conn_put(struct ip_vs_conn *cp); diff --git a/net/netfilter/ipvs/ip_vs_conn.c b/net/netfilter/ipvs/ip_vs_conn.c index 94f25fb7d87e45..86c5e6c7b5afe0 100644 --- a/net/netfilter/ipvs/ip_vs_conn.c +++ b/net/netfilter/ipvs/ip_vs_conn.c @@ -293,7 +293,6 @@ static inline int ip_vs_conn_hash(struct ip_vs_conn *cp) cp->flags |= IP_VS_CONN_F_HASHED; WRITE_ONCE(cp->hn0.hash_key, hash_key); WRITE_ONCE(cp->hn1.hash_key, hash_key2); - refcount_inc(&cp->refcnt); hlist_bl_add_head_rcu(&cp->hn0.node, head); if (use2) hlist_bl_add_head_rcu(&cp->hn1.node, head2); @@ -319,11 +318,27 @@ static inline bool ip_vs_conn_unlink(struct ip_vs_conn *cp) struct hlist_bl_head *head, *head2; u32 hash_key, hash_key2; struct ip_vs_rht *t; - bool ret = false; bool use2; + /* No more users and no running/pending timer except us? */ + if (!refcount_dec_if_one(&cp->refcnt)) + return false; + + /* The ONE_PACKET connection is special: + * - the flag is present only for normal connections, not for templates + * - its timer is never started + * - it is never hashed, so you can not find it and delete it + * - it is not synced + * - it has only one user + * - it is freed after use immediately + */ if (cp->flags & IP_VS_CONN_F_ONE_PACKET) - return refcount_dec_if_one(&cp->refcnt); + return true; + + /* Add the needed ACQUIRE barrier between the above + * refcount_dec_if_one() call and the read of cp fields + */ + smp_acquire__after_ctrl_dep(); rcu_read_lock(); local_bh_disable(); @@ -337,15 +352,11 @@ static inline bool ip_vs_conn_unlink(struct ip_vs_conn *cp) false /* new_hash2 */, &head, &head2); if (cp->flags & IP_VS_CONN_F_HASHED) { - /* Decrease refcnt and unlink conn only if we are last user */ - if (use2 == ip_vs_conn_use_hash2(cp) && - refcount_dec_if_one(&cp->refcnt)) { - hlist_bl_del_rcu(&cp->hn0.node); - if (use2) - hlist_bl_del_rcu(&cp->hn1.node); - cp->flags &= ~IP_VS_CONN_F_HASHED; - ret = true; - } + /* Unlink conn as we are the last user */ + hlist_bl_del_rcu(&cp->hn0.node); + if (use2) + hlist_bl_del_rcu(&cp->hn1.node); + cp->flags &= ~IP_VS_CONN_F_HASHED; } conn_tab_unlock(head, head2); @@ -353,7 +364,7 @@ static inline bool ip_vs_conn_unlink(struct ip_vs_conn *cp) local_bh_enable(); rcu_read_unlock(); - return ret; + return true; } @@ -621,9 +632,12 @@ static void __ip_vs_conn_put_timer(struct ip_vs_conn *cp) { unsigned long t = (cp->flags & IP_VS_CONN_F_ONE_PACKET) ? 0 : cp->timeout; - mod_timer(&cp->timer, jiffies+t); - __ip_vs_conn_put(cp); + /* Handoff our reference to the timer if it was just armed, + * put the reference if timer was already pending. + */ + if (mod_timer(&cp->timer, jiffies + t)) + __ip_vs_conn_put(cp); } void ip_vs_conn_put(struct ip_vs_conn *cp) @@ -1322,9 +1336,18 @@ static void ip_vs_conn_rcu_free(struct rcu_head *head) kmem_cache_free(ip_vs_conn_cachep, cp); } -/* Try to delete connection while not holding reference */ +/* Try to delete connection while not holding reference. + * It can be called concurrently and always under RCU lock + * to protect from connection deletion from others. + * Used when we need to remove the connection immediately + * and without overloading the timer processing. + * OTOH, we use ip_vs_conn_expire_now() when we prefer to + * leave the current context (packet processing) and to + * remove the connection from timer. + */ static void ip_vs_conn_del(struct ip_vs_conn *cp) { + /* Steal reference from the pending timer */ if (timer_delete(&cp->timer)) { /* Drop cp->control chain too */ if (cp->control) @@ -1333,20 +1356,11 @@ static void ip_vs_conn_del(struct ip_vs_conn *cp) } } -/* Try to delete connection while holding reference */ -static void ip_vs_conn_del_put(struct ip_vs_conn *cp) -{ - if (timer_delete(&cp->timer)) { - /* Drop cp->control chain too */ - if (cp->control) - cp->timeout = 0; - __ip_vs_conn_put(cp); - ip_vs_conn_expire(&cp->timer); - } else { - __ip_vs_conn_put(cp); - } -} - +/* Connection is removed in the following steps: + * - timer expires (with ref) or connection is deleted (with stolen ref) + * - there should be no more users except us (pending/running timer, + * n_control>0 or refcnt>1) + */ static void ip_vs_conn_expire(struct timer_list *t) { struct ip_vs_conn *cp = timer_container_of(cp, t, timer); @@ -1362,23 +1376,18 @@ static void ip_vs_conn_expire(struct timer_list *t) if (likely(ip_vs_conn_unlink(cp))) { struct ip_vs_conn *ct = cp->control; - /* delete the timer if it is activated by other users */ - timer_delete(&cp->timer); - /* does anybody control me? */ if (ct) { - bool has_ref = !cp->timeout && __ip_vs_conn_get(ct); - + rcu_read_lock(); ip_vs_control_del(cp); /* Drop CTL or non-assured TPL if not used anymore */ - if (has_ref && !atomic_read(&ct->n_control) && + if (!cp->timeout && !atomic_read(&ct->n_control) && (!(ct->flags & IP_VS_CONN_F_TEMPLATE) || !(ct->state & IP_VS_CTPL_S_ASSURED))) { IP_VS_DBG(4, "drop controlling connection\n"); - ip_vs_conn_del_put(ct); - } else if (has_ref) { - __ip_vs_conn_put(ct); + ip_vs_conn_del(ct); } + rcu_read_unlock(); } if ((cp->flags & IP_VS_CONN_F_NFCT) && @@ -1413,8 +1422,8 @@ static void ip_vs_conn_expire(struct timer_list *t) refcount_read(&cp->refcnt), atomic_read(&cp->n_control)); - refcount_inc(&cp->refcnt); - cp->timeout = 60*HZ; + if (cp->timeout || atomic_read(&cp->n_control)) + cp->timeout = 60 * HZ; if (ipvs->sync_state & IP_VS_STATE_MASTER) ip_vs_sync_conn(ipvs, cp, sysctl_sync_threshold(ipvs)); @@ -1432,7 +1441,7 @@ static void ip_vs_conn_expire(struct timer_list *t) void ip_vs_conn_expire_now(struct ip_vs_conn *cp) { /* Using mod_timer_pending will ensure the timer is not - * modified after the final timer_delete in ip_vs_conn_expire. + * started without giving it new reference. */ if (timer_pending(&cp->timer) && time_after(cp->timer.expires, jiffies)) @@ -1500,9 +1509,9 @@ ip_vs_conn_new(const struct ip_vs_conn_param *p, int dest_af, spin_lock_init(&cp->lock); /* - * Set the entry is referenced by the current thread before hashing - * it in the table, so that other thread run ip_vs_random_dropentry - * but cannot drop this entry. + * Set the entry as referenced by the current thread before starting + * the timer and giving it our reference to allow other threads to + * run ip_vs_random_dropentry() or any deletion method safely. */ refcount_set(&cp->refcnt, 1); diff --git a/net/netfilter/ipvs/ip_vs_sync.c b/net/netfilter/ipvs/ip_vs_sync.c index 157f5c8361ab46..1caacf419af995 100644 --- a/net/netfilter/ipvs/ip_vs_sync.c +++ b/net/netfilter/ipvs/ip_vs_sync.c @@ -732,7 +732,7 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) s->v4.vport = cp->vport; s->v4.dport = cp->dport; s->v4.fwmark = htonl(cp->fwmark); - s->v4.timeout = htonl(cp->timeout / HZ); + s->v4.timeout = htonl(max(1UL, cp->timeout / HZ)); m->nr_conns++; #ifdef CONFIG_IP_VS_IPV6 From d4e4cd04de2c47ed05f837a26edd20c56be3f097 Mon Sep 17 00:00:00 2001 From: Zihan Xi Date: Mon, 5 Oct 2026 13:06:18 +0000 Subject: [PATCH 0581/2102] ipvs: avoid stack overflow from recursive connection expiration When a controlled IPVS connection expires, its controller may be expired synchronously if it has no remaining controlled connections. A chain of controlled connections can then recurse through ip_vs_conn_expire() and exhaust the kernel stack during namespace cleanup. Continue expiration with the controller after the current connection has been fully cleaned up instead of calling ip_vs_conn_del() recursively. Keep the expiration walk under RCU, preserve the immediate-drop timeout for a controller with its own controller, and switch to deletion mode before the next iteration. This keeps controlled-connection cleanup synchronous while using one stack frame for the whole chain. The timer callback race during connection deletion is handled by the preceding connection-deletion fix. This patch depends on "ipvs: fix problems during connection deletion" to protect the iterative controller cleanup from the timer callback race. Fixes: f9200a52eedf ("ipvs: avoid expiring many connections from timer") Cc: stable@vger.kernel.org Reported-by: Vega Co-developed-by: Luxing Yin Signed-off-by: Luxing Yin Signed-off-by: Zihan Xi Signed-off-by: Julian Anastasov Signed-off-by: Pablo Neira Ayuso --- net/netfilter/ipvs/ip_vs_conn.c | 40 ++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/net/netfilter/ipvs/ip_vs_conn.c b/net/netfilter/ipvs/ip_vs_conn.c index 86c5e6c7b5afe0..27db8d558a0303 100644 --- a/net/netfilter/ipvs/ip_vs_conn.c +++ b/net/netfilter/ipvs/ip_vs_conn.c @@ -1336,9 +1336,23 @@ static void ip_vs_conn_rcu_free(struct rcu_head *head) kmem_cache_free(ip_vs_conn_cachep, cp); } -/* Try to delete connection while not holding reference. +/* Try to steal the reference from the pending timer. * It can be called concurrently and always under RCU lock * to protect from connection deletion from others. + */ +static bool ip_vs_conn_del_reference(struct ip_vs_conn *cp) +{ + /* Steal reference from the pending timer */ + if (!timer_delete(&cp->timer)) + return false; + + /* Drop cp->control chain too */ + if (cp->control) + cp->timeout = 0; + return true; +} + +/* Try to delete connection while not holding reference. * Used when we need to remove the connection immediately * and without overloading the timer processing. * OTOH, we use ip_vs_conn_expire_now() when we prefer to @@ -1347,13 +1361,8 @@ static void ip_vs_conn_rcu_free(struct rcu_head *head) */ static void ip_vs_conn_del(struct ip_vs_conn *cp) { - /* Steal reference from the pending timer */ - if (timer_delete(&cp->timer)) { - /* Drop cp->control chain too */ - if (cp->control) - cp->timeout = 0; + if (ip_vs_conn_del_reference(cp)) ip_vs_conn_expire(&cp->timer); - } } /* Connection is removed in the following steps: @@ -1366,6 +1375,9 @@ static void ip_vs_conn_expire(struct timer_list *t) struct ip_vs_conn *cp = timer_container_of(cp, t, timer); struct netns_ipvs *ipvs = cp->ipvs; + rcu_read_lock(); + +repeat: /* * do I control anybody? */ @@ -1375,19 +1387,18 @@ static void ip_vs_conn_expire(struct timer_list *t) /* Unlink conn if not referenced anymore */ if (likely(ip_vs_conn_unlink(cp))) { struct ip_vs_conn *ct = cp->control; + bool next = false; /* does anybody control me? */ if (ct) { - rcu_read_lock(); ip_vs_control_del(cp); /* Drop CTL or non-assured TPL if not used anymore */ if (!cp->timeout && !atomic_read(&ct->n_control) && (!(ct->flags & IP_VS_CONN_F_TEMPLATE) || !(ct->state & IP_VS_CTPL_S_ASSURED))) { IP_VS_DBG(4, "drop controlling connection\n"); - ip_vs_conn_del(ct); + next = ip_vs_conn_del_reference(ct); } - rcu_read_unlock(); } if ((cp->flags & IP_VS_CONN_F_NFCT) && @@ -1414,7 +1425,11 @@ static void ip_vs_conn_expire(struct timer_list *t) else call_rcu(&cp->rcu_head, ip_vs_conn_rcu_free); atomic_dec(&ipvs->conn_count); - return; + if (next) { + cp = ct; + goto repeat; + } + goto out; } expire_later: @@ -1429,6 +1444,9 @@ static void ip_vs_conn_expire(struct timer_list *t) ip_vs_sync_conn(ipvs, cp, sysctl_sync_threshold(ipvs)); __ip_vs_conn_put_timer(cp); + +out: + rcu_read_unlock(); } /* Modify timer, so that it expires as soon as possible. From a107e150e105836bb5349cdee14541d4995009ea Mon Sep 17 00:00:00 2001 From: Zihan Xi Date: Mon, 5 Oct 2026 13:06:19 +0000 Subject: [PATCH 0582/2102] ipvs: reject FTP control ports as data ports The FTP helper must not treat a configured control port as a data port. Accepting such a port can leave IPVS connections in a state that leads to recursive expiration and kernel stack exhaustion. Reject zero and configured control ports before creating passive data connections. For active mode, reject a zero client port and a derived data port that is itself a configured control port. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Reported-by: Vega Co-developed-by: Luxing Yin Signed-off-by: Luxing Yin Signed-off-by: Zihan Xi Signed-off-by: Julian Anastasov Signed-off-by: Pablo Neira Ayuso --- net/netfilter/ipvs/ip_vs_ftp.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/net/netfilter/ipvs/ip_vs_ftp.c b/net/netfilter/ipvs/ip_vs_ftp.c index 9e3e005a826353..4822a1a75212d6 100644 --- a/net/netfilter/ipvs/ip_vs_ftp.c +++ b/net/netfilter/ipvs/ip_vs_ftp.c @@ -62,6 +62,17 @@ static unsigned short ports[IP_VS_APP_MAX_PORTS] = {21, 0}; module_param_array(ports, ushort, &ports_count, 0444); MODULE_PARM_DESC(ports, "Ports to monitor for FTP control commands"); +static bool is_control_port(u16 port) +{ + unsigned int i; + + for (i = 0; i < ports_count; i++) { + if (ports[i] == port) + return true; + } + return false; +} + static char *ip_vs_ftp_data_ptr(struct sk_buff *skb, struct ip_vs_iphdr *ipvsh) { @@ -319,6 +330,10 @@ static int ip_vs_ftp_out(struct ip_vs_app *app, struct ip_vs_conn *cp, return 1; } + /* Do not redirect data to control ports */ + if (!port || is_control_port(ntohs(port))) + return 0; + /* Now update or create a connection entry for it */ { struct ip_vs_conn_param p; @@ -529,6 +544,9 @@ static int ip_vs_ftp_in(struct ip_vs_app *app, struct ip_vs_conn *cp, return 1; } + if (!port || is_control_port(ntohs(cp->vport) - 1)) + return 0; + /* Passive mode off */ cp->app_data = (void *) IP_VS_FTP_ACTIVE; From 4656934d460da68382cf91766a1ff2d0610554ae Mon Sep 17 00:00:00 2001 From: Theodor Arsenij Larionov Trichkine Date: Thu, 15 Oct 2026 23:09:02 +0300 Subject: [PATCH 0583/2102] ipvs: ftp: skip conntrack templates in ip_vs_ftp_out A CT target hooked after conntrack attaches its template to a packet that conntrack left without an entry. On an IPVS FTP PASV/EPSV reply, ip_vs_ftp_out() then mangles with the template and creates an expectation with the template as master. Deleting the CT rule frees the template and leaves the expectation, so a later expectation flush reads freed memory: BUG: KASAN: slab-use-after-free in nf_ct_unlink_expect_report Reachable with CAP_NET_ADMIN in a user namespace. Skip templates, as nft_ct and nfnetlink_queue do. Fixes: f4bc17cdd205 ("ipvs: netfilter connection tracking changes") Cc: stable@vger.kernel.org Signed-off-by: Theodor Arsenij Larionov Trichkine Acked-by: Julian Anastasov Signed-off-by: Pablo Neira Ayuso --- net/netfilter/ipvs/ip_vs_ftp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/netfilter/ipvs/ip_vs_ftp.c b/net/netfilter/ipvs/ip_vs_ftp.c index 4822a1a75212d6..44de99f4d187f9 100644 --- a/net/netfilter/ipvs/ip_vs_ftp.c +++ b/net/netfilter/ipvs/ip_vs_ftp.c @@ -383,7 +383,7 @@ static int ip_vs_ftp_out(struct ip_vs_app *app, struct ip_vs_conn *cp, buf_len = strlen(buf); ct = nf_ct_get(skb, &ctinfo); - if (ct) { + if (ct && !nf_ct_is_template(ct)) { bool mangled; /* If mangling fails this function will return 0 From f3aff3d80b5793dbec1ad4081e2f3bb40aff5fd3 Mon Sep 17 00:00:00 2001 From: Julian Anastasov Date: Mon, 2 Nov 2026 10:07:27 +0200 Subject: [PATCH 0584/2102] ipvs: update flags and seqs in backup server under lock Sashiko reports that we modify the conn flags and seq values in the backup server without holding cp->lock. The same is true for other fields such as state, old_state and timeout which are modified by protocols under lock. Extend the locked region in ip_vs_proc_conn() to update the fields atomically. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Link: https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20260927220816.268206-1-pablo%40netfilter.org Signed-off-by: Julian Anastasov Signed-off-by: Pablo Neira Ayuso --- net/netfilter/ipvs/ip_vs_sync.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/net/netfilter/ipvs/ip_vs_sync.c b/net/netfilter/ipvs/ip_vs_sync.c index 1caacf419af995..ba2fa1f9d08ed6 100644 --- a/net/netfilter/ipvs/ip_vs_sync.c +++ b/net/netfilter/ipvs/ip_vs_sync.c @@ -850,6 +850,7 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa unsigned long timeout, __u32 fwmark, struct ip_vs_sync_conn_options *opt) { + struct ip_vs_conn *cp_new = NULL; struct ip_vs_dest *dest; struct ip_vs_conn *cp; @@ -891,9 +892,6 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa flags &= IP_VS_CONN_F_BACKUP_UPD_MASK; flags |= cp->flags & ~IP_VS_CONN_F_BACKUP_UPD_MASK; cp->flags = flags; - spin_unlock_bh(&cp->lock); - if (!dest) - ip_vs_try_bind_dest(cp); } else { /* * Find the appropriate destination for the connection. @@ -920,6 +918,8 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa } if (!(flags & IP_VS_CONN_F_TEMPLATE)) kfree(param->pe_data); + cp_new = cp; + spin_lock_bh(&cp->lock); } if (opt) { @@ -951,6 +951,9 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa else cp->timeout = (3*60*HZ); } + spin_unlock_bh(&cp->lock); + if (!dest && !cp_new) + ip_vs_try_bind_dest(cp); ip_vs_conn_put(cp); } From aa9afc79f57ba5ef4385aa85cfb7dd50d5c484f6 Mon Sep 17 00:00:00 2001 From: Julian Anastasov Date: Mon, 2 Nov 2026 10:07:28 +0200 Subject: [PATCH 0585/2102] ipvs: read flags and seqs in master atomically After we fixed the double read of cp->flags in the master with commit 3e3fe49e8678 ("ipvs: fix buffer overflow when sending sync messages") Sashiko reports that we should also read the cp->flags and the seqs atomically. So if the SEQ_MASK is set, re-read the flags and the seqs under cp->lock to provide a snapshot when sending the sync message. Fixes: 3e3fe49e8678 ("ipvs: fix buffer overflow when sending sync messages") Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Link: https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20260927220816.268206-1-pablo%40netfilter.org Signed-off-by: Julian Anastasov Signed-off-by: Pablo Neira Ayuso --- net/netfilter/ipvs/ip_vs_sync.c | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/net/netfilter/ipvs/ip_vs_sync.c b/net/netfilter/ipvs/ip_vs_sync.c index ba2fa1f9d08ed6..f11c59eca5536f 100644 --- a/net/netfilter/ipvs/ip_vs_sync.c +++ b/net/netfilter/ipvs/ip_vs_sync.c @@ -539,6 +539,7 @@ static int ip_vs_sync_conn_needed(struct netns_ipvs *ipvs, static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) { + struct ip_vs_sync_conn_options opts; struct ip_vs_sync_mesg_v0 *m; struct ip_vs_sync_conn_v0 *s; struct ip_vs_sync_buff *buff; @@ -557,6 +558,14 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, if (!ip_vs_sync_conn_needed(ipvs, cp, pkts)) return; + if (flags & IP_VS_CONN_F_SEQ_MASK) { + /* Take atomic snapshot of flags and seqs */ + spin_lock_bh(&cp->lock); + flags = cp->flags; + memcpy(&opts, &cp->sync_conn_opt, sizeof(opts)); + spin_unlock_bh(&cp->lock); + } + spin_lock_bh(&ipvs->sync_buff_lock); if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) { spin_unlock_bh(&ipvs->sync_buff_lock); @@ -604,7 +613,7 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, if (seq_mask) { struct ip_vs_sync_conn_options *opt = (struct ip_vs_sync_conn_options *)&s[1]; - memcpy(opt, &cp->sync_conn_opt, sizeof(*opt)); + memcpy(opt, &opts, sizeof(*opt)); } m->nr_conns++; @@ -630,6 +639,7 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, */ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) { + struct ip_vs_sync_conn_options opts; struct ip_vs_sync_mesg *m; union ip_vs_sync_conn *s; struct ip_vs_sync_buff *buff; @@ -651,6 +661,13 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) if (!ip_vs_sync_conn_needed(ipvs, cp, pkts)) goto control; flags = READ_ONCE(cp->flags); + if (flags & IP_VS_CONN_F_SEQ_MASK) { + /* Take atomic snapshot of flags and seqs */ + spin_lock_bh(&cp->lock); + flags = cp->flags; + memcpy(&opts, &cp->sync_conn_opt, sizeof(opts)); + spin_unlock_bh(&cp->lock); + } /* Sanity checks */ pe_name_len = 0; @@ -752,9 +769,9 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) if (seq_mask) { *(p++) = IPVS_OPT_SEQ_DATA; *(p++) = sizeof(struct ip_vs_sync_conn_options); - hton_seq(&cp->in_seq, (struct ip_vs_seq *)p); + hton_seq(&opts.in_seq, (struct ip_vs_seq *)p); p += sizeof(struct ip_vs_seq); - hton_seq(&cp->out_seq, (struct ip_vs_seq *)p); + hton_seq(&opts.out_seq, (struct ip_vs_seq *)p); p += sizeof(struct ip_vs_seq); } /* Handle pe data */ From 567ca80d77baf4c9ab635865375956084c8bb52a Mon Sep 17 00:00:00 2001 From: Julian Anastasov Date: Mon, 2 Nov 2026 10:28:14 +0200 Subject: [PATCH 0586/2102] ipvs: honor the overload state and do not enter it forever Sashiko warns that we may enter the dest overload state forever if setting the u_threshold to 1 races with the ip_vs_unbind_dest() call for the last connection for dest. The problem is that we prefer ip_vs_unbind_dest() to avoid using locks while reading the threshold. To avoid the race, add a smp_mb() in __ip_vs_dest_update_overload() that is paired with the atomic_fetch_dec() in ip_vs_unbind_dest() which allows to re-read the totalconns and to leave the overload state if we are below l_threshold_val. Also, remove the overload parameter from ip_vs_dest_update_overload() because we just need to know the current state while deciding which threshold ranges to use. This ip_vs_dest_is_overloaded() check can be in __ip_vs_dest_update_overload() instead. To avoid ip_vs_bind_dest() to enter lock just to initialize u_threshold_val to INT_MAX, do it in ip_vs_new_dest(). The LBLC and LBLCR schedulers do not honor the global overload state for cached dests, so add a ip_vs_dest_is_overloaded() check for the situations where we may fallback from overloaded dest (LBLC and LBLCR) or when we hit a cached dest (LBLC). Also, move the ip_vs_dest_set_min() call in LBLCR after the ip_vs_dest_set_erase() call that removes the most-loaded server because due to races we may work with dest that is in process of removing, i.e. ip_vs_dest_set_min() and ip_vs_dest_set_max() may return same dest. Link: https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261019150249.1879516-2-pablo%40netfilter.org Fixes: 3ba20137287f ("ipvs: fix more races around the overload flag") Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Signed-off-by: Julian Anastasov Signed-off-by: Pablo Neira Ayuso --- include/net/ip_vs.h | 2 +- net/netfilter/ipvs/ip_vs_conn.c | 4 ++-- net/netfilter/ipvs/ip_vs_ctl.c | 30 ++++++++++++++++++------------ net/netfilter/ipvs/ip_vs_lblc.c | 8 +++++--- net/netfilter/ipvs/ip_vs_lblcr.c | 13 +++++++------ 5 files changed, 33 insertions(+), 24 deletions(-) diff --git a/include/net/ip_vs.h b/include/net/ip_vs.h index 97097d60d1c4b5..c1f7a3f144f1d4 100644 --- a/include/net/ip_vs.h +++ b/include/net/ip_vs.h @@ -1922,7 +1922,7 @@ static inline void ip_vs_dest_put_and_free(struct ip_vs_dest *dest) kfree(dest); } -void ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload); +void ip_vs_dest_update_overload(struct ip_vs_dest *dest); /* Check if dest is in overloaded state */ static inline bool ip_vs_dest_is_overloaded(const struct ip_vs_dest *dest) diff --git a/net/netfilter/ipvs/ip_vs_conn.c b/net/netfilter/ipvs/ip_vs_conn.c index 27db8d558a0303..66fcdc00ef3750 100644 --- a/net/netfilter/ipvs/ip_vs_conn.c +++ b/net/netfilter/ipvs/ip_vs_conn.c @@ -1168,7 +1168,7 @@ ip_vs_bind_dest(struct ip_vs_conn *cp, struct ip_vs_dest *dest) atomic_inc(&dest->activeconns); tc = atomic_inc_return(&dest->totalconns); if (tc >= READ_ONCE(dest->u_threshold_val)) - ip_vs_dest_update_overload(dest, true); + ip_vs_dest_update_overload(dest); } else { /* It is a persistent connection/template, so increase the persistent connection counter */ @@ -1261,7 +1261,7 @@ static inline void ip_vs_unbind_dest(struct ip_vs_conn *cp) atomic_dec(&dest->activeconns); tc = atomic_fetch_dec(&dest->totalconns); if (tc <= READ_ONCE(dest->l_threshold_val)) - ip_vs_dest_update_overload(dest, false); + ip_vs_dest_update_overload(dest); } else { /* It is a persistent connection/template, so decrease the persistent connection counter */ diff --git a/net/netfilter/ipvs/ip_vs_ctl.c b/net/netfilter/ipvs/ip_vs_ctl.c index ce9fe20d6106a8..5868adda6ed6ea 100644 --- a/net/netfilter/ipvs/ip_vs_ctl.c +++ b/net/netfilter/ipvs/ip_vs_ctl.c @@ -1304,12 +1304,12 @@ void ip_vs_stats_free(struct ip_vs_stats *stats) } } -/* Update overload flag based on number of dest conns and lower/upper +/* Update overload state based on number of dest conns and lower/upper * connection thresholds: - * - conns reach u_threshold and exceed it: set the flag - * - conns go below l_threshold (or 75% of u_threshold): clear the flag + * - conns reach u_threshold and exceed it: set the overload state + * - conns go below l_threshold (or 75% of u_threshold): clear the state */ -static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload) +static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest) { int conns; u32 l, u; @@ -1320,10 +1320,18 @@ static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload) /* Low threshold defaults to 75% of upper threshold */ l = READ_ONCE(dest->l_threshold) ? : (u - (u >> 2)); conns = atomic_read(&dest->totalconns); - if (conns >= (overload ? l : u)) { + if (conns >= (ip_vs_dest_is_overloaded(dest) ? l : u)) { WRITE_ONCE(dest->u_threshold_val, INT_MAX); WRITE_ONCE(dest->l_threshold_val, l); - return; + /* Commit thresholds before repeating the check, + * it is paired with atomic_fetch_dec() in + * ip_vs_unbind_dest() to avoid entering the + * overload state forever. + */ + smp_mb(); + conns = atomic_read(&dest->totalconns); + if (conns >= l) + return; } } @@ -1331,10 +1339,10 @@ static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload) WRITE_ONCE(dest->l_threshold_val, 0); } -void ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload) +void ip_vs_dest_update_overload(struct ip_vs_dest *dest) { spin_lock_bh(&dest->dst_lock); - __ip_vs_dest_update_overload(dest, overload); + __ip_vs_dest_update_overload(dest); spin_unlock_bh(&dest->dst_lock); } @@ -1406,13 +1414,10 @@ __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest, if (READ_ONCE(dest->u_threshold) != udest->u_threshold || READ_ONCE(dest->l_threshold) != udest->l_threshold) { - bool overload; - spin_lock_bh(&dest->dst_lock); WRITE_ONCE(dest->u_threshold, udest->u_threshold); WRITE_ONCE(dest->l_threshold, udest->l_threshold); - overload = ip_vs_dest_is_overloaded(dest); - __ip_vs_dest_update_overload(dest, overload); + __ip_vs_dest_update_overload(dest); spin_unlock_bh(&dest->dst_lock); } @@ -1477,6 +1482,7 @@ ip_vs_new_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) if (ret < 0) goto err_stats; + dest->u_threshold_val = INT_MAX; dest->af = udest->af; dest->protocol = svc->protocol; dest->vaddr = svc->addr; diff --git a/net/netfilter/ipvs/ip_vs_lblc.c b/net/netfilter/ipvs/ip_vs_lblc.c index e1111c3b27211a..f5ce1f2afb8606 100644 --- a/net/netfilter/ipvs/ip_vs_lblc.c +++ b/net/netfilter/ipvs/ip_vs_lblc.c @@ -467,10 +467,11 @@ is_overloaded(struct ip_vs_dest *dest, struct ip_vs_service *svc) struct ip_vs_dest *d; list_for_each_entry_rcu(d, &svc->destinations, n_list) { - if (atomic_read(&d->activeconns)*2 - < atomic_read(&d->weight)) { + if (ip_vs_dest_is_overloaded(d)) + continue; + if (atomic_read(&d->activeconns) * 2 < + atomic_read(&d->weight)) return 1; - } } } return 0; @@ -507,6 +508,7 @@ ip_vs_lblc_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, dest = en->dest; if ((dest->cflags & IP_VS_DEST_CF_AVAILABLE) && + !ip_vs_dest_is_overloaded(dest) && atomic_read(&dest->weight) > 0 && !is_overloaded(dest, svc)) goto out; } diff --git a/net/netfilter/ipvs/ip_vs_lblcr.c b/net/netfilter/ipvs/ip_vs_lblcr.c index dfb5bf83750dba..4046608922e7cb 100644 --- a/net/netfilter/ipvs/ip_vs_lblcr.c +++ b/net/netfilter/ipvs/ip_vs_lblcr.c @@ -630,10 +630,11 @@ is_overloaded(struct ip_vs_dest *dest, struct ip_vs_service *svc) struct ip_vs_dest *d; list_for_each_entry_rcu(d, &svc->destinations, n_list) { - if (atomic_read(&d->activeconns)*2 - < atomic_read(&d->weight)) { + if (ip_vs_dest_is_overloaded(d)) + continue; + if (atomic_read(&d->activeconns) * 2 < + atomic_read(&d->weight)) return 1; - } } } return 0; @@ -658,9 +659,6 @@ ip_vs_lblcr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, if (en) { en->lastuse = jiffies; - /* Get the least loaded destination */ - dest = ip_vs_dest_set_min(&en->set); - /* More than one destination + enough time passed by, cleanup */ if (atomic_read(&en->set.size) > 1 && time_after(jiffies, en->set.lastmod + @@ -676,6 +674,9 @@ ip_vs_lblcr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, spin_unlock_bh(&svc->sched_lock); } + /* Get the least loaded destination */ + dest = ip_vs_dest_set_min(&en->set); + /* If the destination is not overloaded, use it */ if (dest && !is_overloaded(dest, svc)) goto out; From 1d1e8bc81f790a48cd643b1b1762de43334d4f14 Mon Sep 17 00:00:00 2001 From: Axel Mierczuk Date: Tue, 3 Nov 2026 11:57:45 -0500 Subject: [PATCH 0587/2102] ipvs: validate cport in received sync records Local templates have cport 0 and IP_VS_CONN_F_NO_CPORT clear, so ip_vs_conn_in_get() cannot match them. A template received over the unauthenticated sync protocol with a nonzero cport can reach the protocol state machine. Before template state validation, this could cause out-of-bounds reads, crashes and kernel data leaks. Ordinary records with cport 0 and IP_VS_CONN_F_NO_CPORT clear, or with a nonzero cport and IP_VS_CONN_F_NO_CPORT set, create connections that incoming lookups cannot match. The latter also keeps the cport-zero fallback in ip_vs_conn_in_get() enabled. Reject all three cases. Continue accepting ordinary connections with cport 0 and IP_VS_CONN_F_NO_CPORT. The companion commit f96e91748f63 ("ipvs: filter some flags received in the backup server") rejects template records carrying IP_VS_CONN_F_NO_CPORT. Fixes: 87375ab47cd0 ("[IPVS]: ip_vs_ftp breaks connections using persistence") Cc: stable@vger.kernel.org Suggested-by: Julian Anastasov Signed-off-by: Axel Mierczuk Acked-by: Julian Anastasov Signed-off-by: Pablo Neira Ayuso --- net/netfilter/ipvs/ip_vs_sync.c | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/net/netfilter/ipvs/ip_vs_sync.c b/net/netfilter/ipvs/ip_vs_sync.c index f11c59eca5536f..7e562e745ab5d5 100644 --- a/net/netfilter/ipvs/ip_vs_sync.c +++ b/net/netfilter/ipvs/ip_vs_sync.c @@ -871,6 +871,25 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa struct ip_vs_dest *dest; struct ip_vs_conn *cp; + /* Templates require cport 0. Ordinary connections require + * NO_CPORT exactly when cport is 0. + */ + if (flags & IP_VS_CONN_F_TEMPLATE) { + if (param->cport) { + IP_VS_DBG(2, "BACKUP, template with cport dropped\n"); + kfree(param->pe_data); + return; + } + } else if (!param->cport && !(flags & IP_VS_CONN_F_NO_CPORT)) { + IP_VS_DBG(2, "BACKUP, conn without cport dropped\n"); + kfree(param->pe_data); + return; + } else if (param->cport && (flags & IP_VS_CONN_F_NO_CPORT)) { + IP_VS_DBG(2, "BACKUP, conn with cport and NO_CPORT dropped\n"); + kfree(param->pe_data); + return; + } + if (!(flags & IP_VS_CONN_F_TEMPLATE)) { cp = ip_vs_conn_in_get(param); if (cp && ((cp->dport != dport) || From 5c8d6e2596e0935e2ace0b94e86ffb99e8434cd9 Mon Sep 17 00:00:00 2001 From: Axel Mierczuk Date: Tue, 3 Nov 2026 11:57:46 -0500 Subject: [PATCH 0588/2102] ipvs: skip cport 0 connections in ip_vs_conn_out_get() ip_vs_conn_out_get() does not filter templates. A template with cport 0 is matched by a packet sent to client port 0 that traverses the out hook, and handle_response() then runs ip_vs_set_state() and the timeout update on a connection that must never see packets. A backup server receives such templates over the unauthenticated sync protocol. An ordinary connection scheduled for a client that uses source port 0 has cport 0 as well and is matched the same way. Apply the rule used by __ip_vs_conn_in_get(): a lookup for client port 0 matches only connections flagged IP_VS_CONN_F_NO_CPORT, which still wait for their cport, and a lookup for a nonzero client port matches only connections without this flag. Test p->vport, which was already compared with cp->cport, instead of reading cp->cport again. ip_vs_ftp_out() relies on the first case: it looks up the data connection with client port 0 to find the IP_VS_CONN_F_NO_CPORT entry created for an earlier PASV or EPSV reply. That lookup keeps working. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Suggested-by: Julian Anastasov Signed-off-by: Axel Mierczuk Signed-off-by: Pablo Neira Ayuso --- net/netfilter/ipvs/ip_vs_conn.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/net/netfilter/ipvs/ip_vs_conn.c b/net/netfilter/ipvs/ip_vs_conn.c index 66fcdc00ef3750..83d8a9153a342f 100644 --- a/net/netfilter/ipvs/ip_vs_conn.c +++ b/net/netfilter/ipvs/ip_vs_conn.c @@ -590,6 +590,8 @@ struct ip_vs_conn *ip_vs_conn_out_get(const struct ip_vs_conn_param *p) ip_vs_addr_equal(p->af, p->vaddr, &cp->caddr) && ip_vs_addr_equal(p->af, p->caddr, saddr) && + (!p->vport ^ + (!(cp->flags & IP_VS_CONN_F_NO_CPORT))) && p->protocol == cp->protocol) { if (__ip_vs_conn_get(cp)) goto out; From 7439e0fed91f55e4b48b9e725ad60575cb881d09 Mon Sep 17 00:00:00 2001 From: Julian Anastasov Date: Fri, 6 Nov 2026 01:15:34 +0200 Subject: [PATCH 0589/2102] ipvs: do not create conns from packets with port 0 We should disallow normal connections with cport 0 to be created from packets by the scheduler (from clients) or by ip_vs_new_conn_out (from real servers) because later such traffic can not hit the connection due to the NO_CPORT requirement. As result, it can lead to duplicate connection for every packet. Do the same for vport 0. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Link: https://sashiko.dev/#/patchset/20261104201530.147292-1-ja%40ssi.bg Link: https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261103140308.591690-3-pablo%40netfilter.org Link: https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20260925141115.16126-1-axel.mierczuk%401password.com Signed-off-by: Julian Anastasov Signed-off-by: Pablo Neira Ayuso --- net/netfilter/ipvs/ip_vs_core.c | 3 ++- net/netfilter/ipvs/ip_vs_proto_sctp.c | 7 +++++++ net/netfilter/ipvs/ip_vs_proto_tcp.c | 7 +++++++ net/netfilter/ipvs/ip_vs_proto_udp.c | 6 ++++++ 4 files changed, 22 insertions(+), 1 deletion(-) diff --git a/net/netfilter/ipvs/ip_vs_core.c b/net/netfilter/ipvs/ip_vs_core.c index 8a3c880fdb266e..f3eb72e95024dd 100644 --- a/net/netfilter/ipvs/ip_vs_core.c +++ b/net/netfilter/ipvs/ip_vs_core.c @@ -1305,6 +1305,7 @@ static inline bool is_new_conn_expected(const struct ip_vs_conn *cp, * In fwmark-VS actual vaddr and vport are unknown to IPVS * 2) Real Server and Virtual Service were NOT configured without port: * This is to allow match of different VS to the same RS ip-addr + * 3) Client port is not 0 */ struct ip_vs_conn *ip_vs_new_conn_out(struct ip_vs_service *svc, struct ip_vs_dest *dest, @@ -1328,7 +1329,7 @@ struct ip_vs_conn *ip_vs_new_conn_out(struct ip_vs_service *svc, /* check pre-requisites are satisfied */ if (svc->fwmark) return NULL; - if (!vport || !dport) + if (!vport || !dport || !cport) return NULL; /* for persistent service first create connection template */ diff --git a/net/netfilter/ipvs/ip_vs_proto_sctp.c b/net/netfilter/ipvs/ip_vs_proto_sctp.c index fb8af6b15a3999..cb34bcceb4f641 100644 --- a/net/netfilter/ipvs/ip_vs_proto_sctp.c +++ b/net/netfilter/ipvs/ip_vs_proto_sctp.c @@ -30,6 +30,7 @@ sctp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb, sch = skb_header_pointer(skb, iph->len + sizeof(_sctph), sizeof(_schunkh), &_schunkh); if (sch) { + /* Accept packet without scheduling? */ if (sch->type == SCTP_CID_ABORT || !(sysctl_sloppy_sctp(ipvs) || sch->type == SCTP_CID_INIT)) @@ -56,6 +57,12 @@ sctp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb, if (svc) { int ignored; + /* Do not create connection for port 0 */ + if (!ports[0] || !ports[1]) { + *verdict = NF_DROP; + return 0; + } + if (ip_vs_todrop(ipvs)) { /* * It seems that we are very loaded. diff --git a/net/netfilter/ipvs/ip_vs_proto_tcp.c b/net/netfilter/ipvs/ip_vs_proto_tcp.c index fec0e8b47b7165..25d4576d0e1299 100644 --- a/net/netfilter/ipvs/ip_vs_proto_tcp.c +++ b/net/netfilter/ipvs/ip_vs_proto_tcp.c @@ -48,6 +48,7 @@ tcp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb, if (likely(!ip_vs_iph_icmp(iph))) { th = skb_header_pointer(skb, iph->len, sizeof(_tcph), &_tcph); if (th) { + /* Accept packet without scheduling? */ if (th->rst || !(sysctl_sloppy_tcp(ipvs) || th->syn)) return 1; ports = &th->source; @@ -74,6 +75,12 @@ tcp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb, if (svc) { int ignored; + /* Do not create connection for port 0 */ + if (!ports[0] || !ports[1]) { + *verdict = NF_DROP; + return 0; + } + if (ip_vs_todrop(ipvs)) { /* * It seems that we are very loaded. diff --git a/net/netfilter/ipvs/ip_vs_proto_udp.c b/net/netfilter/ipvs/ip_vs_proto_udp.c index f32785682402dd..ab3ab95241687e 100644 --- a/net/netfilter/ipvs/ip_vs_proto_udp.c +++ b/net/netfilter/ipvs/ip_vs_proto_udp.c @@ -62,6 +62,12 @@ udp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb, if (svc) { int ignored; + /* Do not create connection for port 0 */ + if (!ports[0] || !ports[1]) { + *verdict = NF_DROP; + return 0; + } + if (ip_vs_todrop(ipvs)) { /* * It seems that we are very loaded. From 5367e14e92bbb0779612d36cce7c6e95d3bc5e68 Mon Sep 17 00:00:00 2001 From: Darong Lu Date: Mon, 9 Nov 2026 10:06:47 +0800 Subject: [PATCH 0590/2102] ipvs: wait grace period before reusing destinations An IPVS destination can be removed from a service and immediately reused from dest_trash before an RCU grace period has elapsed. Reusing its n_list or d_list can make existing readers follow links into another service or real-server hash chain. The grace-period cookie is also saved when a live destination is unhashed for an edit and consumed when it is rehashed. Describe rcu_state as the cookie for an unlink, covering both trash and rehash cases. When a destination is retrieved from dest_trash, ip_vs_add_dest() currently restarts its estimator before waiting for the grace period. If the estimator was on a tick chain, ip_vs_stop_estimator() removed est->list with hlist_del_rcu(), so an estimator kthread can still be traversing that node. ip_vs_start_estimator() rewrites the node on its temporary list on success, or initializes it on failure, before the current wait. A reader can then follow the changed link or stop traversing the chain early. Wait immediately after retrieving the destination, before starting its estimator. The conditional grace-period wait then covers the destination list, real-server hash and estimator list on both estimator success and failure paths. Fixes: bcbde4c0a755 ("ipvs: make the service replacement more robust") Cc: stable@vger.kernel.org Reported-by: Vega Reported-by: Darong Lu Co-developed-by: Jiayuan Chen Signed-off-by: Jiayuan Chen Signed-off-by: Darong Lu Signed-off-by: Ren Wei Signed-off-by: Julian Anastasov Signed-off-by: Pablo Neira Ayuso --- include/net/ip_vs.h | 4 +- net/netfilter/ipvs/ip_vs_ctl.c | 110 ++++++++++++++++++++++++++------- 2 files changed, 91 insertions(+), 23 deletions(-) diff --git a/include/net/ip_vs.h b/include/net/ip_vs.h index c1f7a3f144f1d4..8dc80d5d42dca3 100644 --- a/include/net/ip_vs.h +++ b/include/net/ip_vs.h @@ -1021,7 +1021,9 @@ struct ip_vs_dest { struct rcu_head rcu_head; struct list_head t_list; /* in dest_trash */ - unsigned int in_rs_table:1; /* we are in rs_table */ + unsigned long rcu_state; /* GP cookie on unlink (trash or rehash) */ + unsigned int in_rs_table:1, /* we are in rs_table */ + need_gp:1; /* Need GP on rehash */ }; /* The scheduler object */ diff --git a/net/netfilter/ipvs/ip_vs_ctl.c b/net/netfilter/ipvs/ip_vs_ctl.c index 5868adda6ed6ea..be818bf7d3806c 100644 --- a/net/netfilter/ipvs/ip_vs_ctl.c +++ b/net/netfilter/ipvs/ip_vs_ctl.c @@ -64,7 +64,8 @@ int ip_vs_get_debug_level(void) /* Protos */ -static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup); +static void __ip_vs_del_service(struct ip_vs_service *svc, + struct list_head *dest_trash, bool cleanup); #ifdef CONFIG_IP_VS_IPV6 @@ -918,6 +919,11 @@ static void ip_vs_rs_hash(struct netns_ipvs *ipvs, struct ip_vs_dest *dest) */ hash = ip_vs_rs_hashkey(dest->af, &dest->addr, port); + /* Need RCU grace period when rehashing */ + if (dest->need_gp) { + cond_synchronize_rcu(dest->rcu_state); + dest->need_gp = 0; + } hlist_add_head_rcu(&dest->d_list, &ipvs->rs_table[hash]); dest->in_rs_table = 1; } @@ -1111,6 +1117,8 @@ ip_vs_trash_get_dest(struct ip_vs_service *svc, int dest_af, struct ip_vs_dest *dest; struct netns_ipvs *ipvs = svc->ipvs; + lockdep_assert_held(&ipvs->service_mutex); + /* * Find the destination in trash */ @@ -1144,24 +1152,57 @@ ip_vs_trash_get_dest(struct ip_vs_service *svc, int dest_af, return dest; } -/* Put destination in trash */ -static void ip_vs_trash_put_dest(struct netns_ipvs *ipvs, +/* Add destination in temp list for trash */ +static void ip_vs_trash_add_dest(struct netns_ipvs *ipvs, struct ip_vs_dest *dest, unsigned long istart, - bool cleanup) + struct list_head *dest_trash) { - spin_lock_bh(&ipvs->dest_trash_lock); IP_VS_DBG_BUF(3, "Moving dest %s:%u into trash, dest->refcnt=%d\n", IP_VS_DBG_ADDR(dest->af, &dest->addr), ntohs(dest->port), refcount_read(&dest->refcnt)); + /* dest lives in trash with reference */ + list_add(&dest->t_list, dest_trash); + dest->idle_start = istart; +} + +/* Put destinations in trash */ +static void ip_vs_trash_put_dests(struct netns_ipvs *ipvs, + struct list_head *dest_trash, bool cleanup) +{ + spin_lock_bh(&ipvs->dest_trash_lock); if (list_empty(&ipvs->dest_trash) && !cleanup) mod_timer(&ipvs->dest_trash_timer, jiffies + (IP_VS_DEST_TRASH_PERIOD >> 1)); - /* dest lives in trash with reference */ - list_add(&dest->t_list, &ipvs->dest_trash); - dest->idle_start = istart; + list_splice(dest_trash, &ipvs->dest_trash); spin_unlock_bh(&ipvs->dest_trash_lock); } +/* Put destination back in trash */ +static void ip_vs_trash_put_back(struct netns_ipvs *ipvs, + struct ip_vs_dest *dest) +{ + LIST_HEAD(dest_trash); + + ip_vs_trash_add_dest(ipvs, dest, dest->idle_start, &dest_trash); + ip_vs_trash_put_dests(ipvs, &dest_trash, false); +} + +/* Put destinations in trash and save the RCU state */ +static void ip_vs_trash_save_dests(struct netns_ipvs *ipvs, + struct list_head *dest_trash, bool cleanup) +{ + struct ip_vs_dest *dest; + unsigned long rcu_state; + + if (!list_empty(dest_trash)) { + /* Remember when dests were removed and added to dest_trash */ + rcu_state = get_state_synchronize_rcu(); + list_for_each_entry(dest, dest_trash, t_list) + dest->rcu_state = rcu_state; + ip_vs_trash_put_dests(ipvs, dest_trash, cleanup); + } +} + static void ip_vs_dest_rcu_free(struct rcu_head *head) { struct ip_vs_dest *dest; @@ -1377,8 +1418,16 @@ __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest, if ((udest->conn_flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_DFWD_METHOD(dest) || udest->tun_type != dest->tun_type || - udest->tun_port != dest->tun_port) + udest->tun_port != dest->tun_port) { + bool unlinked = dest->in_rs_table; + ip_vs_rs_unhash(dest); + if (unlinked) { + dest->rcu_state = get_state_synchronize_rcu(); + /* Need grace period in this or next dest update */ + dest->need_gp = 1; + } + } /* set the tunnel info */ dest->tun_type = udest->tun_type; @@ -1562,6 +1611,11 @@ ip_vs_add_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) dest = ip_vs_trash_get_dest(svc, udest->af, &daddr, dport); if (dest != NULL) { + /* Readers may still follow the n_list, d_list or estimator list + * links. Wait before reusing any of them. + */ + cond_synchronize_rcu(dest->rcu_state); + IP_VS_DBG_BUF(3, "Get destination %s:%u from trash, " "dest->refcnt=%d, service %u/%s:%u\n", IP_VS_DBG_ADDR(udest->af, &daddr), ntohs(dport), @@ -1572,11 +1626,14 @@ ip_vs_add_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) ret = ip_vs_start_estimator(svc->ipvs, &dest->stats); /* On error put back dest into the trash */ - if (ret < 0) - ip_vs_trash_put_dest(svc->ipvs, dest, dest->idle_start, - false); - else + if (ret < 0) { + ip_vs_trash_put_back(svc->ipvs, dest); + } else { + /* need_gp matters only on dest edit, reinit it */ + dest->need_gp = 0; + __ip_vs_update_dest(svc, dest, udest, 1); + } } else { /* * Allocate and initialize the dest structure @@ -1640,7 +1697,7 @@ ip_vs_edit_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) * Delete a destination (must be already unlinked from the service) */ static void __ip_vs_del_dest(struct netns_ipvs *ipvs, struct ip_vs_dest *dest, - bool cleanup) + struct list_head *dest_trash, bool cleanup) { ip_vs_stop_estimator(ipvs, &dest->stats); @@ -1649,7 +1706,7 @@ static void __ip_vs_del_dest(struct netns_ipvs *ipvs, struct ip_vs_dest *dest, */ ip_vs_rs_unhash(dest); - ip_vs_trash_put_dest(ipvs, dest, 0, cleanup); + ip_vs_trash_add_dest(ipvs, dest, 0, dest_trash); /* Queue up delayed work to expire all no destination connections. * No-op when CONFIG_SYSCTL is disabled. @@ -1699,6 +1756,7 @@ ip_vs_del_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) { struct ip_vs_dest *dest; __be16 dport = udest->port; + LIST_HEAD(dest_trash); /* We use function that requires RCU lock */ rcu_read_lock(); @@ -1718,7 +1776,9 @@ ip_vs_del_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) /* * Delete the destination */ - __ip_vs_del_dest(svc->ipvs, dest, false); + __ip_vs_del_dest(svc->ipvs, dest, &dest_trash, false); + + ip_vs_trash_save_dests(svc->ipvs, &dest_trash, false); return 0; } @@ -2063,7 +2123,8 @@ ip_vs_edit_service(struct ip_vs_service *svc, struct ip_vs_service_user_kern *u) * - The service must be unlinked, unlocked and not referenced! * - We are called under _bh lock */ -static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup) +static void __ip_vs_del_service(struct ip_vs_service *svc, + struct list_head *dest_trash, bool cleanup) { struct ip_vs_dest *dest, *nxt; struct ip_vs_scheduler *old_sched; @@ -2097,7 +2158,7 @@ static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup) */ list_for_each_entry_safe(dest, nxt, &svc->destinations, n_list) { __ip_vs_unlink_dest(svc, dest, 0); - __ip_vs_del_dest(svc->ipvs, dest, cleanup); + __ip_vs_del_dest(svc->ipvs, dest, dest_trash, cleanup); } /* @@ -2120,7 +2181,8 @@ static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup) /* * Unlink a service from list and try to delete it if its refcnt reached 0 */ -static void ip_vs_unlink_service(struct ip_vs_service *svc, bool cleanup) +static void ip_vs_unlink_service(struct ip_vs_service *svc, + struct list_head *dest_trash, bool cleanup) { ip_vs_unregister_conntrack(svc); /* Hold svc to avoid double release from dest_trash */ @@ -2130,7 +2192,7 @@ static void ip_vs_unlink_service(struct ip_vs_service *svc, bool cleanup) */ ip_vs_svc_unhash(svc); - __ip_vs_del_service(svc, cleanup); + __ip_vs_del_service(svc, dest_trash, cleanup); } /* @@ -2140,12 +2202,14 @@ static int ip_vs_del_service(struct ip_vs_service *svc) { struct netns_ipvs *ipvs; struct ip_vs_rht *t, *p; + LIST_HEAD(dest_trash); int ns; if (svc == NULL) return -EEXIST; ipvs = svc->ipvs; - ip_vs_unlink_service(svc, false); + ip_vs_unlink_service(svc, &dest_trash, false); + ip_vs_trash_save_dests(ipvs, &dest_trash, false); /* Drop the table if no more services */ ns = ip_vs_get_num_services(ipvs); @@ -2196,6 +2260,7 @@ static int ip_vs_flush(struct netns_ipvs *ipvs, bool cleanup) struct hlist_bl_node *ne; struct hlist_bl_node *e; struct ip_vs_rht *t, *p; + LIST_HEAD(dest_trash); /* Stop the resizer and drop the tables */ if (!test_and_set_bit(IP_VS_WORK_SVC_NORESIZE, &ipvs->work_flags)) @@ -2205,8 +2270,9 @@ static int ip_vs_flush(struct netns_ipvs *ipvs, bool cleanup) if (ip_vs_get_num_services(ipvs)) { ip_vs_rht_walk_buckets(ipvs->svc_table, head) { hlist_bl_for_each_entry_safe(svc, e, ne, head, s_list) - ip_vs_unlink_service(svc, cleanup); + ip_vs_unlink_service(svc, &dest_trash, cleanup); } + ip_vs_trash_save_dests(ipvs, &dest_trash, cleanup); } /* Unregister the hash table and release it after RCU grace period */ From f17d77541c909b7c03fa29095d45f23a79699879 Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Sun, 15 Nov 2026 16:26:32 -0800 Subject: [PATCH 0591/2102] hwmon: Use per-device lockdep keys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently, mutex_init(&hwdev->lock) in __hwmon_device_register() assigns a single static lockdep key to all hardware monitoring device locks. If one hardware monitoring device accesses another hardware monitoring device (for example, pwm-fan controlling a PWM output provided by adt7470), lockdep sees two instances of the same lock class acquired in sequence and reports a false-positive recursive locking warning. Give each struct hwmon_device its own dynamic struct lock_class_key, registered via lockdep_register_key() and initialized with mutex_init_with_key() before any error path that calls hwmon_dev_release(), and cleaned up with mutex_destroy() and lockdep_unregister_key() in hwmon_dev_release(). This allows nested locking across distinct hwmon devices while preserving full lockdep deadlock and self-recursion detection. Fixes: 3ad2a7b9b15d ("hwmon: Serialize accesses in hwmon core") Cc: stable@vger.kernel.org Cc: Davíð Steinn Geirsson Signed-off-by: Guenter Roeck --- drivers/hwmon/hwmon.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/hwmon/hwmon.c b/drivers/hwmon/hwmon.c index 73a818806d3d2c..6cfcdb9f60b779 100644 --- a/drivers/hwmon/hwmon.c +++ b/drivers/hwmon/hwmon.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -37,6 +38,7 @@ struct hwmon_device { const char *label; struct device dev; const struct hwmon_chip_info *chip; + struct lock_class_key lock_key; struct mutex lock; struct list_head tzdata; struct attribute_group group; @@ -136,6 +138,8 @@ static void hwmon_dev_release(struct device *dev) hwmon_free_attrs(hwdev->group.attrs_const); kfree(hwdev->groups); kfree(hwdev->label); + mutex_destroy(&hwdev->lock); + lockdep_unregister_key(&hwdev->lock_key); kfree(hwdev); } @@ -939,6 +943,8 @@ __hwmon_device_register(struct device *dev, const char *name, void *drvdata, } hdev = &hwdev->dev; + lockdep_register_key(&hwdev->lock_key); + mutex_init_with_key(&hwdev->lock, &hwdev->lock_key); if (chip) { const struct attribute **attrs; @@ -993,7 +999,6 @@ __hwmon_device_register(struct device *dev, const char *name, void *drvdata, tdev = tdev->parent; hdev->of_node = tdev ? tdev->of_node : NULL; hwdev->chip = chip; - mutex_init(&hwdev->lock); dev_set_drvdata(hdev, drvdata); dev_set_name(hdev, HWMON_ID_FORMAT, id); err = device_register(hdev); From dc61b19db1f77deb4c15bb71e64f46071447837c Mon Sep 17 00:00:00 2001 From: Karol Wachowski Date: Tue, 10 Nov 2026 13:15:34 +0100 Subject: [PATCH 0592/2102] accel/ivpu: Defer recovery until probe completes An error IRQ that fires after ivpu_boot() enables interrupts queues recovery_work during probe. If probe then fails, the device is torn down while the work runs, and the work faults on the unmapped BARs: BUG: unable to handle page fault for address: ffffcfc6680200f4 Workqueue: events_unbound ivpu_pm_recovery_work [intel_vpu] RIP: 0010:ivpu_hw_ip_ipc_rx_addr_get+0xc/0xb0 [intel_vpu] Call Trace: ivpu_wait_for_ready+0x155/0x220 [intel_vpu] ivpu_boot+0x9e/0x270 [intel_vpu] ivpu_resume+0xa4/0xd0 [intel_vpu] ivpu_pm_reset_complete+0x2c/0x90 [intel_vpu] ivpu_pm_recovery_work+0xf6/0x140 [intel_vpu] If probe succeeds, the recovery runs concurrently with the rest of probe, and its pm_runtime_disable() discards the initial autosuspend request, leaving the NPU active until first use. Any recovery that starts while the NPU is idle loses the pending autosuspend the same way. Keep recovery_work disabled from ivpu_pm_init() until ivpu_pm_enable(). A trigger during probe still runs diagnostics and masks interrupts, and ivpu_pm_enable() runs the deferred recovery before the initial autosuspend request. A trigger racing with ivpu_pm_enable() can cause a second, harmless recovery. Request autosuspend at the end of ivpu_pm_reset_complete() so the NPU suspends again after every reset. Fixes: 852be13f3bd3 ("accel/ivpu: Add PM support") Cc: stable@vger.kernel.org # v6.10+ Reported-by: Daksh Sahni Closes: https://lore.kernel.org/r/20261107174215.15818-1-swizzguy76@gmail.com Tested-by: Daksh Sahni Reviewed-by: Jeff Hugo Signed-off-by: Karol Wachowski Link: https://patch.msgid.link/20261110121534.3566028-1-karol.wachowski@linux.intel.com --- drivers/accel/ivpu/ivpu_pm.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/drivers/accel/ivpu/ivpu_pm.c b/drivers/accel/ivpu/ivpu_pm.c index aa813262253e4a..e4b79c946ca013 100644 --- a/drivers/accel/ivpu/ivpu_pm.c +++ b/drivers/accel/ivpu/ivpu_pm.c @@ -150,8 +150,8 @@ static void ivpu_pm_reset_complete(struct ivpu_device *vdev) up_write(&vdev->pm->reset_lock); atomic_set(&vdev->pm->reset_pending, 0); - pm_runtime_mark_last_busy(vdev->drm.dev); pm_runtime_enable(vdev->drm.dev); + pm_request_autosuspend(vdev->drm.dev); } static void ivpu_pm_recovery_work(struct work_struct *work) @@ -415,6 +415,7 @@ void ivpu_pm_init(struct ivpu_device *vdev) atomic_set(&pm->engine_reset_counter, 0); INIT_WORK(&pm->recovery_work, ivpu_pm_recovery_work); + disable_work(&pm->recovery_work); INIT_DELAYED_WORK(&pm->job_timeout_work, ivpu_job_timeout_work); if (ivpu_disable_recovery) @@ -439,6 +440,12 @@ void ivpu_pm_enable(struct ivpu_device *vdev) { struct device *dev = vdev->drm.dev; + enable_work(&vdev->pm->recovery_work); + if (atomic_read(&vdev->pm->reset_pending)) { + queue_work(system_dfl_wq, &vdev->pm->recovery_work); + flush_work(&vdev->pm->recovery_work); + } + pm_runtime_allow(dev); pm_runtime_put_autosuspend(dev); } From c7ef3bffd5f48bde1a1bbbd181fbc73e721d87e9 Mon Sep 17 00:00:00 2001 From: Haowen Tu Date: Mon, 16 Nov 2026 10:24:42 +0800 Subject: [PATCH 0593/2102] Input: max77693-haptic - disable bias on failed open max77693_haptic_open() enables the MAX77843 bias before enabling the motor regulator. If regulator_enable() fails, the function returns without turning the bias off. The input core does not call the close callback after a failed open, so its bias cleanup does not run either. Disable the bias before returning the regulator error. The bias helper already handles reporting register access errors and is a no-op for the other supported chip variants. Fixes: 56bbc99e6914 ("Input: max77693: Add support for Maxim 77843") Signed-off-by: Haowen Tu Link: https://patch.msgid.link/98F5ACA9EADBEC89+20261116022442.3298673-1-tuhaowen@uniontech.com Signed-off-by: Dmitry Torokhov --- drivers/input/misc/max77693-haptic.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/input/misc/max77693-haptic.c b/drivers/input/misc/max77693-haptic.c index 10325c1296da86..7973f76ab15123 100644 --- a/drivers/input/misc/max77693-haptic.c +++ b/drivers/input/misc/max77693-haptic.c @@ -278,6 +278,7 @@ static int max77693_haptic_open(struct input_dev *dev) if (error) { dev_err(haptic->dev, "failed to enable regulator: %d\n", error); + max77843_haptic_bias(haptic, false); return error; } From e9c183840d9729300f6128812936b7939145412f Mon Sep 17 00:00:00 2001 From: Andreas Kemnade Date: Wed, 11 Nov 2026 22:14:02 +0100 Subject: [PATCH 0594/2102] drm/omap: dss: fix handling deferrals Forward the error given by of_drm_get_bridge_by_endpoint() if it is EPROBE_DEFER to ensure output gets initialized later when available. On GTA04/OMAP3 no display was found, but it appeared after doing rmmod omapdrm ; modprobe omapdrm Fixes: b7e9b93fc8ecf ("drm/omap: dss: don't create a panel_bridge") Signed-off-by: Andreas Kemnade Reviewed-by: Luca Ceresoli Reviewed-by: Tomi Valkeinen Link: https://patch.msgid.link/20261111-gta04-drm-regression-fix-v2-1-010caf3b08bd@kemnade.info Signed-off-by: Tomi Valkeinen --- drivers/gpu/drm/omapdrm/dss/output.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/gpu/drm/omapdrm/dss/output.c b/drivers/gpu/drm/omapdrm/dss/output.c index 36d37deac80263..b5cef5093a8834 100644 --- a/drivers/gpu/drm/omapdrm/dss/output.c +++ b/drivers/gpu/drm/omapdrm/dss/output.c @@ -24,6 +24,9 @@ int omapdss_device_init_output(struct omap_dss_device *out, bridge = of_drm_get_bridge_by_endpoint(out->dev->of_node, out->of_port, 0); if (IS_ERR(bridge)) { + if (PTR_ERR(bridge) == -EPROBE_DEFER) + return PTR_ERR(bridge); + dev_dbg(out->dev, "failed to find video sink\n"); return 0; } From 9e7a9295c90e28e1bb6e88b76aaa91839266352b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Syrj=C3=A4l=C3=A4?= Date: Thu, 5 Nov 2026 14:47:37 +0200 Subject: [PATCH 0595/2102] drm/i915/cdclk: Ignore SWF18 in SKL CDCLK sanitization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently on SKL/derivatives we are checking whether the VBIOS/GOP programmed the SWF18 scratch register appropriately. SWF18 is where the VBIOS/GOP should stuff some information about what outputs it enabled. A related register SWF06 is where the VBIOS/GOP is supposed to stuff the maximum CDCLK frequency. I think only SWF06 is really used by the Windows driver (and even that only up to and including ADL), the other stuff it doesn't even look at. Apparently at least some coreboot based systems don't set these scratch registers up at all. SWF18 not being populated leads us to reprogram the CDCLK PLL during driver initialization, while the display pipes are still potentially active. We also set CDCLK to its minimum frequency, under the assumption that nothing actually needs a higher CDCLK frequency when it hasn't even been correctly initialized. Due to some other changes in the code we may no longer force a full CDCLK recalculation and reprogramming upon the first atomic commit, so CDCLK can remain at a potentially too low a frequency indefinitely. To fix this let's just stop looking at SWF18 completely. We don't look at that register on any other platform either, and neither does Windows from what I can see. We also do an actual readout of the CDCLK state from the hardware so we should be able to spot if anything is wrong enough to need reprogramming. v2: Rewrite the commit message to mix up SWF06 vs. SWF18 Cc: stable@vger.kernel.org Fixes: ba91b9eecb47 ("drm/i915/cdclk: Decouple cdclk from state->modeset") Closes: https://gitlab.freedesktop.org/drm/i915/kernel/-/work_items/16595 Closes: https://gitlab.freedesktop.org/drm/i915/kernel/-/work_items/17423 Signed-off-by: Ville Syrjälä Link: https://patch.msgid.link/20261105124737.24456-1-ville.syrjala@linux.intel.com Reviewed-by: Mika Kahola (cherry picked from commit a6e9767ca2e353277aa06d4c796093ef71a191b6) Signed-off-by: Joonas Lahtinen --- drivers/gpu/drm/i915/display/intel_cdclk.c | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/drivers/gpu/drm/i915/display/intel_cdclk.c b/drivers/gpu/drm/i915/display/intel_cdclk.c index 92e6fca861f64a..0f2f693c78d48d 100644 --- a/drivers/gpu/drm/i915/display/intel_cdclk.c +++ b/drivers/gpu/drm/i915/display/intel_cdclk.c @@ -1269,18 +1269,7 @@ static void skl_set_cdclk(struct intel_display *display, static void skl_sanitize_cdclk(struct intel_display *display) { - u32 cdctl, expected, swf18; - - /* - * check if the pre-os initialized the display - * There is SWF18 scratchpad register defined which is set by the - * pre-os which can be used by the OS drivers to check the status - */ - swf18 = intel_de_read(display, SWF_ILK(0x18)); - if ((swf18 & 0x00FFFFFF) == 0) { - drm_dbg_kms(display->drm, "Sanitizing CDCLK due to SWF18 0x%x\n", swf18); - goto sanitize; - } + u32 cdctl, expected; intel_update_cdclk(display); intel_cdclk_dump_config(display, &display->cdclk.hw, "Current CDCLK"); From 715f145f6204363a50853eb15719dc860db0bc01 Mon Sep 17 00:00:00 2001 From: Hanson Wang Date: Fri, 6 Nov 2026 18:23:15 +0800 Subject: [PATCH 0596/2102] drm/i915/dsb: Realign GOSUB only for QW slots 6 and 7 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit intel_dsb_gosub_align() moves free_pos to the next cacheline unconditionally, but only clears the skipped bytes when at most two QW slots remain. Wa_16024917128 forbids GOSUB in slots 6 and 7 only. A larger gap is still executed. A Panther Lake DSB dump showed nonzero data in that gap, with the tail at 0x58 and GOSUB at 0x80. Advance free_pos only when the instruction would land in slot 6 or 7, and fill that gap with NOPs. Emit GOSUB in place for every other slot. intel_dsb_align_tail() still clears the rest of the cacheline. Update free_pos inside the existing gap check in intel_dsb_align_tail() as well, so the two helpers keep the same shape. Fixes: 2c41d62f6fb1 ("drm/i915/dsb: Implement intel_dsb_gosub()") Cc: stable@vger.kernel.org # v6.17+ Signed-off-by: Hanson Wang Signed-off-by: Ville Syrjälä Link: https://patch.msgid.link/20261106102315.1361645-1-hanson.wang@ugreen.com (cherry picked from commit a2f5df6c5468b4f65e58c4125bba3f0e3cdc6aa1) Signed-off-by: Joonas Lahtinen --- drivers/gpu/drm/i915/display/intel_dsb.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/i915/display/intel_dsb.c b/drivers/gpu/drm/i915/display/intel_dsb.c index d9a270362a82c2..07d864039e82cd 100644 --- a/drivers/gpu/drm/i915/display/intel_dsb.c +++ b/drivers/gpu/drm/i915/display/intel_dsb.c @@ -589,10 +589,10 @@ static void intel_dsb_align_tail(struct intel_dsb *dsb) tail = dsb->free_pos * 4; aligned_tail = ALIGN(tail, CACHELINE_BYTES); - if (aligned_tail > tail) + if (aligned_tail > tail) { dsb_buffer_fill(dsb, dsb->free_pos, 0, aligned_tail - tail); - - dsb->free_pos = aligned_tail / 4; + dsb->free_pos = aligned_tail / 4; + } } static void intel_dsb_gosub_align(struct intel_dsb *dsb) @@ -607,11 +607,15 @@ static void intel_dsb_gosub_align(struct intel_dsb *dsb) /* * Wa_16024917128 * "Ensure GOSUB is not placed in cacheline QW slot 6 or 7 (numbered 0-7)" + * + * Move to the next cacheline only for those two slots. The skipped + * bytes stay in the programmed range, so fill them with NOPs. Any + * other slot can take the GOSUB directly. */ - if (aligned_tail - tail <= 2 * 8) + if (aligned_tail - tail <= 2 * 8) { dsb_buffer_fill(dsb, dsb->free_pos, 0, aligned_tail - tail); - - dsb->free_pos = aligned_tail / 4; + dsb->free_pos = aligned_tail / 4; + } } void intel_dsb_gosub(struct intel_dsb *dsb, From b1e4074bfd00bc7dcf760c8eeb9b694895e5296e Mon Sep 17 00:00:00 2001 From: Luigi Santivetti Date: Thu, 5 Nov 2026 12:25:37 +0000 Subject: [PATCH 0597/2102] drm/imagination: use appropriate poll function for non-iomem pvr_power_send_command() checks the contents of some memory on the CPU that's written to by the firmware. readl_poll_timeout() expects the address to read from to be qualified with __iomem, that is generally used for registers or memory that is accessed through a bus and other than regular system memory. For PowerVR in particular, __iomem is not accurate as the memory pointed to by can strictly be system memory only. Fix this by lifting one level of abstraction in the macro expansion chain and explicitly provide what routine should be used for reading. Fixes: cc1aeedb98ad ("drm/imagination: Implement firmware infrastructure and META FW support") Reported-by: kernel test robot Closes: https://lore.kernel.org/oe-kbuild-all/202610302136.3nli2ijx-lkp@intel.com/ Signed-off-by: Luigi Santivetti Tested-by: Gyeyoung Baek Reviewed-by: Alessio Belle Link: https://patch.msgid.link/20261105-fix-sparse-iomem-warning-v1-1-35c13069f271@imgtec.com Signed-off-by: Alessio Belle --- drivers/gpu/drm/imagination/pvr_power.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/imagination/pvr_power.c b/drivers/gpu/drm/imagination/pvr_power.c index eb4b6ecdf4f4d0..c7c160913d7cc6 100644 --- a/drivers/gpu/drm/imagination/pvr_power.c +++ b/drivers/gpu/drm/imagination/pvr_power.c @@ -59,7 +59,8 @@ pvr_power_send_command(struct pvr_device *pvr_dev, struct rogue_fwif_kccb_cmd *p return err; /* Wait for FW to acknowledge. */ - return readl_poll_timeout(pvr_dev->fw_dev.power_sync, value, value != 0, 100, + return readx_poll_timeout(READ_ONCE, + *pvr_dev->fw_dev.power_sync, value, value != 0, 100, POWER_SYNC_TIMEOUT_US); } From 90035d3f26e011e16fcf9c5071571f0d956b5219 Mon Sep 17 00:00:00 2001 From: Guangshuo Li Date: Wed, 8 Jul 2026 19:43:54 +0800 Subject: [PATCH 0598/2102] accel/rocket: put IOMMU domain on BO creation failure rocket_ioctl_create_bo() takes an IOMMU domain reference for each newly created BO. The normal GEM object release path drops that reference from rocket_gem_bo_free(). However, the BO creation error paths free the object with drm_gem_shmem_object_free(), which bypasses the driver's GEM .free callback. Those paths therefore release the shmem object without dropping the IOMMU domain reference. Drop the domain reference explicitly on the BO creation error path before freeing the shmem object. Fixes: 658ebeac3351 ("accel/rocket: Add IOCTL for BO creation") Signed-off-by: Guangshuo Li Reviewed-by: Tomeu Vizoso Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/20260708114354.753817-1-lgs201920130244@gmail.com --- drivers/accel/rocket/rocket_gem.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/accel/rocket/rocket_gem.c b/drivers/accel/rocket/rocket_gem.c index d981c6a93ff12f..79135351b8e380 100644 --- a/drivers/accel/rocket/rocket_gem.c +++ b/drivers/accel/rocket/rocket_gem.c @@ -127,6 +127,8 @@ int rocket_ioctl_create_bo(struct drm_device *dev, void *data, struct drm_file * mutex_unlock(&rocket_priv->mm_lock); err: + rocket_iommu_domain_put(rkt_obj->domain); + rkt_obj->domain = NULL; drm_gem_shmem_object_free(gem_obj); return ret; From 349a91af66d6a50ac3b82fd025dca7289a5b8ec3 Mon Sep 17 00:00:00 2001 From: Igor Paunovic Date: Fri, 31 Jul 2026 08:49:32 +0200 Subject: [PATCH 0599/2102] accel/rocket: release the shared device's devres on teardown rocket_device_init() attaches its allocations to the shared "rknn" platform device via devres: devm_drm_dev_alloc(), devm_kcalloc() for the cores array and devm_mutex_init(). That device is registered at module init, never binds to a driver, and is only unregistered at module exit - so its devres list is not released for as long as the module is loaded. rocket_device_fini() only calls drm_dev_unregister(): it does not run the drm_dev_put() devres action or free any of the other entries. Every fini/re-init cycle therefore leaks the previous rocket_device (with its embedded drm_device and all drmm state, including the accel minor number), the cores array and the mutex devres node. The cycle is easy to trigger: unbind the last bound core and bind one again, or fail the first core's probe (-EPROBE_DEFER retries included). Observable symptom, RK3588 (Orange Pi 5 Plus): each unbind/rebind cycle of all three cores moves the accel node forward - /dev/accel/accel0 comes back as accel1, then accel2 - because every leaked drm_device keeps its minor pinned. Wrap the initialization in a devres group and release exactly that group wherever the device is torn down: on the rocket_device_init() error path, when the first core's rocket_core_init() fails, and when the last core is removed. Each fini now frees what the matching init allocated, and the accel minor is reusable again. Fixes: ed98261b4168 ("accel/rocket: Add a new driver for Rockchip's NPU") Signed-off-by: Igor Paunovic Reviewed-by: Tomeu Vizoso Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/20260731064933.12548-2-royalnet026@gmail.com --- drivers/accel/rocket/rocket_drv.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/accel/rocket/rocket_drv.c b/drivers/accel/rocket/rocket_drv.c index 5d7805c41dc3d1..06f187647aecb6 100644 --- a/drivers/accel/rocket/rocket_drv.c +++ b/drivers/accel/rocket/rocket_drv.c @@ -24,6 +24,7 @@ */ static struct platform_device *drm_dev; static struct rocket_device *rdev; +static void *rdev_group; static void rocket_iommu_domain_destroy(struct kref *kref) @@ -163,14 +164,19 @@ static int rocket_probe(struct platform_device *pdev) if (rdev == NULL) { /* First core probing, initialize DRM device. */ + rdev_group = devres_open_group(&drm_dev->dev, NULL, GFP_KERNEL); + if (!rdev_group) + return -ENOMEM; rdev = rocket_device_init(drm_dev, &rocket_drm_driver); if (IS_ERR(rdev)) { int err = PTR_ERR(rdev); dev_err(&pdev->dev, "failed to initialize rocket device\n"); rdev = NULL; + devres_release_group(&drm_dev->dev, rdev_group); return err; } + devres_close_group(&drm_dev->dev, rdev_group); } unsigned int core = rdev->num_cores; @@ -190,6 +196,7 @@ static int rocket_probe(struct platform_device *pdev) if (rdev->num_cores == 0) { rocket_device_fini(rdev); rdev = NULL; + devres_release_group(&drm_dev->dev, rdev_group); } } @@ -213,6 +220,7 @@ static void rocket_remove(struct platform_device *pdev) /* Last core removed, deinitialize DRM device. */ rocket_device_fini(rdev); rdev = NULL; + devres_release_group(&drm_dev->dev, rdev_group); } } From 97e48904cbdb32e4a66bd60d26ce45657f58bc46 Mon Sep 17 00:00:00 2001 From: Igor Paunovic Date: Tue, 22 Sep 2026 10:01:05 +0200 Subject: [PATCH 0600/2102] accel/rocket: number the cores by devicetree position, not bind order rocket_job_hw_submit() programs the S_POINTER registers of a core with an extra bit derived from core->index, the way the vendor driver derives it from the hardware number of the core. rocket_probe() sets core->index to the slot the core takes in rdev->cores[], which is the order the cores bind in. The two agree only while the cores that bind are a prefix of the core nodes in the devicetree, in devicetree order. Unbind them and bind them back with a different core first, have one core's probe deferred behind a sibling's, or disable a core other than the last one, and every task submitted to a core whose slot is not its hardware number times out after 500 ms. The reset that follows does not help, and the inference finishes with wrong output. Observed on an Orange Pi 5 Plus with a KASAN build, over all six bind orders of the three cores: only the devicetree order ran clean. The other five produced 27 to 141 "NPU job timed out". In four of them no output tensor changed with the input, and the harness gave up before its first measured round; the fifth got through a six-second run with 27 timeouts and a wrong top-1 class. All but one of the timeouts land on the cores whose slot is not their hardware number, in proportion to the tasks the scheduler hands them, and in both directions of the mismatch. Number the cores by their position among the core nodes in the devicetree instead, which is what the hardware number is. The wrong value has been assigned since the driver was added, but it only reached the hardware once the extra bit was introduced, hence the Fixes tag below. Fixes: 0810d5ad88a1 ("accel/rocket: Add job submission IOCTL") Cc: stable@vger.kernel.org Assisted-by: LLM sparse Signed-off-by: Igor Paunovic Reviewed-by: Heiko Stuebner [tomeu: shortened the comments and dropped checkpatch from Assisted-by] Reviewed-by: Tomeu Vizoso Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/20260922080114.44662-3-royalnet026@gmail.com --- drivers/accel/rocket/rocket_core.h | 4 ++++ drivers/accel/rocket/rocket_drv.c | 22 +++++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/drivers/accel/rocket/rocket_core.h b/drivers/accel/rocket/rocket_core.h index f6d7382854ca9e..6eb975322e0c22 100644 --- a/drivers/accel/rocket/rocket_core.h +++ b/drivers/accel/rocket/rocket_core.h @@ -30,6 +30,10 @@ struct rocket_core { struct device *dev; struct rocket_device *rdev; + /* + * Hardware number of the core: its position among the core nodes in + * the devicetree. + */ unsigned int index; int irq; diff --git a/drivers/accel/rocket/rocket_drv.c b/drivers/accel/rocket/rocket_drv.c index 06f187647aecb6..9a3509dd586488 100644 --- a/drivers/accel/rocket/rocket_drv.c +++ b/drivers/accel/rocket/rocket_drv.c @@ -158,10 +158,30 @@ static const struct drm_driver rocket_drm_driver = { .desc = "rocket DRM", }; +static int rocket_core_hw_index(struct device *dev) +{ + struct device_node *np; + int index = 0; + + for_each_matching_node(np, dev->driver->of_match_table) { + if (np == dev->of_node) { + of_node_put(np); + return index; + } + index++; + } + + return -ENODEV; +} + static int rocket_probe(struct platform_device *pdev) { + int index = rocket_core_hw_index(&pdev->dev); int ret; + if (index < 0) + return index; + if (rdev == NULL) { /* First core probing, initialize DRM device. */ rdev_group = devres_open_group(&drm_dev->dev, NULL, GFP_KERNEL); @@ -185,7 +205,7 @@ static int rocket_probe(struct platform_device *pdev) rdev->cores[core].rdev = rdev; rdev->cores[core].dev = &pdev->dev; - rdev->cores[core].index = core; + rdev->cores[core].index = index; rdev->num_cores++; From 5c4aeafcac8c46be7b08b86795baa64453eb68aa Mon Sep 17 00:00:00 2001 From: Chaoyi Chen Date: Fri, 14 Aug 2026 10:24:52 +0800 Subject: [PATCH 0601/2102] accel/rocket: Fix the extra iommu_group_get call in rocket_job_handle_irq The rocket attaches the IOMMU group in rocket_job_run() and detaches it in rocket_job_handle_irq(). Calling iommu_group_get() in rocket_job_handle_irq() causes the reference count to increase unexpectedly. And this causes rocket_core_fini() to fail to release the IOMMU group, leading to a resource leak. Fixes: 0810d5ad88a1 ("accel/rocket: Add job submission IOCTL") Signed-off-by: Chaoyi Chen Reviewed-by: Tomeu Vizoso [tomeu: Fixes points at the commit that added the call] Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/20260814022453.437-4-kernel@airkyi.com --- drivers/accel/rocket/rocket_job.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/accel/rocket/rocket_job.c b/drivers/accel/rocket/rocket_job.c index c3edb94355a397..36659521de421c 100644 --- a/drivers/accel/rocket/rocket_job.c +++ b/drivers/accel/rocket/rocket_job.c @@ -379,7 +379,7 @@ static void rocket_job_handle_irq(struct rocket_core *core) return; } - iommu_detach_group(NULL, iommu_group_get(core->dev)); + iommu_detach_group(NULL, core->iommu_group); dma_fence_signal(core->in_flight_job->done_fence); pm_runtime_put_autosuspend(core->dev); core->in_flight_job = NULL; From 4d8cb7be620e969e4189cc209f2338b6a77c80fd Mon Sep 17 00:00:00 2001 From: Haoming Gao Date: Thu, 12 Nov 2026 23:53:00 +0800 Subject: [PATCH 0602/2102] accel/rocket: publish read fences for input buffers Fix the bug that a fence is not attached to a BO reservation when the BO is read. An exported input buffer can appear writable while an accepted Rocket job is still reading it, allowing a later writer to overwrite data in use. Fixes: 0810d5ad88a1 ("accel/rocket: Add job submission IOCTL") Signed-off-by: Haoming Gao Reviewed-by: Tomeu Vizoso Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/20261112155300.299899-1-Naixumogu@whut.edu.cn --- drivers/accel/rocket/rocket_job.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/drivers/accel/rocket/rocket_job.c b/drivers/accel/rocket/rocket_job.c index 36659521de421c..285af1044be101 100644 --- a/drivers/accel/rocket/rocket_job.c +++ b/drivers/accel/rocket/rocket_job.c @@ -201,12 +201,13 @@ static int rocket_acquire_object_fences(struct drm_gem_object **bos, static void rocket_attach_object_fences(struct drm_gem_object **bos, int bo_count, - struct dma_fence *fence) + struct dma_fence *fence, + enum dma_resv_usage usage) { int i; for (i = 0; i < bo_count; i++) - dma_resv_add_fence(bos[i]->resv, fence, DMA_RESV_USAGE_WRITE); + dma_resv_add_fence(bos[i]->resv, fence, usage); } static int rocket_job_push(struct rocket_job *job) @@ -248,7 +249,10 @@ static int rocket_job_push(struct rocket_job *job) drm_sched_entity_push_job(&job->base); } - rocket_attach_object_fences(job->out_bos, job->out_bo_count, job->inference_done_fence); + rocket_attach_object_fences(job->in_bos, job->in_bo_count, + job->inference_done_fence, DMA_RESV_USAGE_READ); + rocket_attach_object_fences(job->out_bos, job->out_bo_count, + job->inference_done_fence, DMA_RESV_USAGE_WRITE); err_unlock: drm_gem_unlock_reservations(bos, bo_count, &acquire_ctx); From 7d4a177d0d9bc0ca04caec9293ccb902a853cc47 Mon Sep 17 00:00:00 2001 From: Marek Szyprowski Date: Mon, 9 Nov 2026 18:06:02 +0100 Subject: [PATCH 0603/2102] dma: swiotlb: Properly tear down the default pool on exit With CONFIG_SWIOTLB_DYNAMIC enabled, the default memory pool is added to the io_tlb_default_mem.pools RCU list during initialization. When an IOMMU takes over DMA translation, swiotlb_exit() tears the default pool down and clears it with memset(), but leaves its node on the pools list. The list then contains a zeroed entry with a NULL next pointer, and any later walk of the list, for example mem_used() when reading the io_tlb_used debugfs file, dereferences an invalid pointer and crashes. swiotlb_exit() also leaves the io_tlb_default_mem fields that describe the pool. io_tlb_default_mem.nslabs and can_grow stay set, so is_swiotlb_allocated() and is_swiotlb_active() keep returning true, and swiotlb_find_slots() can schedule dynamic pool allocation after teardown. Without CONFIG_SWIOTLB_DYNAMIC, a later mapping can reach the zeroed defpool and hit BUG_ON(area_index >= pool->nareas). Before the pool data was split out of struct io_tlb_mem, swiotlb_exit() cleared the whole structure, including nslabs. Clear can_grow and cancel any pending dyn_alloc work, then remove the default pool from the list and subtract its slots from nslabs, and wait for an RCU grace period before clearing it, so that no reader can still see it. Without CONFIG_SWIOTLB_DYNAMIC, reset nslabs directly. As a result, with CONFIG_SWIOTLB_DYNAMIC swiotlb no longer silently keeps working through dynamic or transient pools after an IOMMU has turned it off, so for example dma-iommu bouncing for untrusted devices reports that bounce buffers are inactive, as it did before the dynamic pools support. Fixes: 158dbe9c9a3d ("swiotlb: separate memory pool data from other allocator data") Fixes: 62708b2ba405 ("swiotlb: add a flag whether SWIOTLB is allowed to grow") Fixes: 1aaa736815eb ("swiotlb: allocate a new memory pool when existing pools are full") Closes: https://sashiko.dev/#/bug/linux-f75998aa-65ea-4596-9bb4-fa83773012a3 Cc: stable@vger.kernel.org Link: https://lore.kernel.org/r/20261109170603.385791-1-m.szyprowski@samsung.com Signed-off-by: Marek Szyprowski --- kernel/dma/swiotlb.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/kernel/dma/swiotlb.c b/kernel/dma/swiotlb.c index 9b0bc272dd82f5..786954bc5e6a65 100644 --- a/kernel/dma/swiotlb.c +++ b/kernel/dma/swiotlb.c @@ -665,6 +665,17 @@ void __init swiotlb_exit(void) return; pr_info("tearing down default memory pool\n"); +#ifdef CONFIG_SWIOTLB_DYNAMIC + io_tlb_default_mem.can_grow = false; + cancel_work_sync(&io_tlb_default_mem.dyn_alloc); + spin_lock(&io_tlb_default_mem.lock); + list_del_rcu(&mem->node); + io_tlb_default_mem.nslabs -= mem->nslabs; + spin_unlock(&io_tlb_default_mem.lock); + synchronize_rcu(); +#else + io_tlb_default_mem.nslabs = 0; +#endif tbl_vaddr = (unsigned long)phys_to_virt(mem->start); tbl_size = PAGE_ALIGN(mem->end - mem->start); slots_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), mem->nslabs)); From c3fe8795ecd844d0bf76102217bec01cce01b715 Mon Sep 17 00:00:00 2001 From: Gyeyoung Baek Date: Sun, 1 Nov 2026 16:37:00 +0900 Subject: [PATCH 0604/2102] accel/rocket: Fix drm_mm UAF on close vs in-flight job The drm_mm and its mutex live in rocket_file_priv, which rocket_postclose() frees on fd close. But a BO held by an in-flight job is only freed after close, from the drm_sched free_job worker, and its destructor then accesses the already freed drm_mm and mutex. BUG: KASAN: slab-use-after-free in __mutex_trylock_common+0x90/0x1e8 Workqueue: .npu drm_sched_free_job_work [gpu_sched] Call trace: __mutex_lock rocket_gem_bo_free rocket_job_cleanup rocket_job_free drm_sched_free_job_work [gpu_sched] Move drm_mm and the mutex out of rocket_file_priv into the kref-managed rocket_iommu_domain (renamed to rocket_vm). Their lifetime now matches the vm's: as long as a BO or job references the vm, the address-space state stays alive. Fixes: 658ebeac3351 ("accel/rocket: Add IOCTL for BO creation") Cc: stable@vger.kernel.org Signed-off-by: Gyeyoung Baek Reviewed-by: Tomeu Vizoso [tomeu: Rebased on the BO creation error path fix] [tomeu: Fixes points at the commit that added the drm_mm to rocket_file_priv] Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/20261101073700.1261966-1-gye976@gmail.com --- drivers/accel/rocket/rocket_drv.c | 74 +++++++++++++++---------------- drivers/accel/rocket/rocket_drv.h | 13 +++--- drivers/accel/rocket/rocket_gem.c | 35 ++++++++------- drivers/accel/rocket/rocket_gem.h | 4 +- drivers/accel/rocket/rocket_job.c | 6 +-- drivers/accel/rocket/rocket_job.h | 2 +- 6 files changed, 66 insertions(+), 68 deletions(-) diff --git a/drivers/accel/rocket/rocket_drv.c b/drivers/accel/rocket/rocket_drv.c index 9a3509dd586488..e62a20edeca756 100644 --- a/drivers/accel/rocket/rocket_drv.c +++ b/drivers/accel/rocket/rocket_drv.c @@ -27,46 +27,54 @@ static struct rocket_device *rdev; static void *rdev_group; static void -rocket_iommu_domain_destroy(struct kref *kref) +rocket_vm_destroy(struct kref *kref) { - struct rocket_iommu_domain *domain = container_of(kref, struct rocket_iommu_domain, kref); + struct rocket_vm *vm = container_of(kref, struct rocket_vm, kref); - iommu_domain_free(domain->domain); - domain->domain = NULL; - kfree(domain); + drm_mm_takedown(&vm->mm); + mutex_destroy(&vm->lock); + iommu_domain_free(vm->domain); + vm->domain = NULL; + kfree(vm); } -static struct rocket_iommu_domain* -rocket_iommu_domain_create(struct device *dev) +static struct rocket_vm * +rocket_vm_create(struct device *dev) { - struct rocket_iommu_domain *domain = kmalloc_obj(*domain); + struct rocket_vm *vm = kmalloc_obj(*vm); + u64 start, end; void *err; - if (!domain) + if (!vm) return ERR_PTR(-ENOMEM); - domain->domain = iommu_paging_domain_alloc(dev); - if (IS_ERR(domain->domain)) { - err = ERR_CAST(domain->domain); - kfree(domain); + vm->domain = iommu_paging_domain_alloc(dev); + if (IS_ERR(vm->domain)) { + err = ERR_CAST(vm->domain); + kfree(vm); return err; } - kref_init(&domain->kref); - return domain; + start = vm->domain->geometry.aperture_start; + end = vm->domain->geometry.aperture_end; + drm_mm_init(&vm->mm, start, end - start + 1); + mutex_init(&vm->lock); + kref_init(&vm->kref); + + return vm; } -struct rocket_iommu_domain * -rocket_iommu_domain_get(struct rocket_file_priv *rocket_priv) +struct rocket_vm * +rocket_vm_get(struct rocket_file_priv *rocket_priv) { - kref_get(&rocket_priv->domain->kref); - return rocket_priv->domain; + kref_get(&rocket_priv->vm->kref); + return rocket_priv->vm; } void -rocket_iommu_domain_put(struct rocket_iommu_domain *domain) +rocket_vm_put(struct rocket_vm *vm) { - kref_put(&domain->kref, rocket_iommu_domain_destroy); + kref_put(&vm->kref, rocket_vm_destroy); } static int @@ -74,7 +82,6 @@ rocket_open(struct drm_device *dev, struct drm_file *file) { struct rocket_device *rdev = to_rocket_device(dev); struct rocket_file_priv *rocket_priv; - u64 start, end; int ret; if (!try_module_get(THIS_MODULE)) @@ -87,29 +94,22 @@ rocket_open(struct drm_device *dev, struct drm_file *file) } rocket_priv->rdev = rdev; - rocket_priv->domain = rocket_iommu_domain_create(rdev->cores[0].dev); - if (IS_ERR(rocket_priv->domain)) { - ret = PTR_ERR(rocket_priv->domain); + rocket_priv->vm = rocket_vm_create(rdev->cores[0].dev); + if (IS_ERR(rocket_priv->vm)) { + ret = PTR_ERR(rocket_priv->vm); goto err_free; } file->driver_priv = rocket_priv; - start = rocket_priv->domain->domain->geometry.aperture_start; - end = rocket_priv->domain->domain->geometry.aperture_end; - drm_mm_init(&rocket_priv->mm, start, end - start + 1); - mutex_init(&rocket_priv->mm_lock); - ret = rocket_job_open(rocket_priv); if (ret) - goto err_mm_takedown; + goto err_vm_put; return 0; -err_mm_takedown: - mutex_destroy(&rocket_priv->mm_lock); - drm_mm_takedown(&rocket_priv->mm); - rocket_iommu_domain_put(rocket_priv->domain); +err_vm_put: + rocket_vm_put(rocket_priv->vm); err_free: kfree(rocket_priv); err_put_mod: @@ -123,9 +123,7 @@ rocket_postclose(struct drm_device *dev, struct drm_file *file) struct rocket_file_priv *rocket_priv = file->driver_priv; rocket_job_close(rocket_priv); - mutex_destroy(&rocket_priv->mm_lock); - drm_mm_takedown(&rocket_priv->mm); - rocket_iommu_domain_put(rocket_priv->domain); + rocket_vm_put(rocket_priv->vm); kfree(rocket_priv); module_put(THIS_MODULE); } diff --git a/drivers/accel/rocket/rocket_drv.h b/drivers/accel/rocket/rocket_drv.h index 2c673bb99ccc1d..2754f46f174982 100644 --- a/drivers/accel/rocket/rocket_drv.h +++ b/drivers/accel/rocket/rocket_drv.h @@ -11,22 +11,23 @@ extern const struct dev_pm_ops rocket_pm_ops; -struct rocket_iommu_domain { +struct rocket_vm { struct iommu_domain *domain; + struct drm_mm mm; + /* protects @mm */ + struct mutex lock; struct kref kref; }; struct rocket_file_priv { struct rocket_device *rdev; - struct rocket_iommu_domain *domain; - struct drm_mm mm; - struct mutex mm_lock; + struct rocket_vm *vm; struct drm_sched_entity sched_entity; }; -struct rocket_iommu_domain *rocket_iommu_domain_get(struct rocket_file_priv *rocket_priv); -void rocket_iommu_domain_put(struct rocket_iommu_domain *domain); +struct rocket_vm *rocket_vm_get(struct rocket_file_priv *rocket_priv); +void rocket_vm_put(struct rocket_vm *vm); #endif diff --git a/drivers/accel/rocket/rocket_gem.c b/drivers/accel/rocket/rocket_gem.c index 79135351b8e380..8f802df3e0f143 100644 --- a/drivers/accel/rocket/rocket_gem.c +++ b/drivers/accel/rocket/rocket_gem.c @@ -14,20 +14,20 @@ static void rocket_gem_bo_free(struct drm_gem_object *obj) { struct rocket_gem_object *bo = to_rocket_bo(obj); - struct rocket_file_priv *rocket_priv = bo->driver_priv; + struct rocket_vm *vm = bo->vm; size_t unmapped; drm_WARN_ON(obj->dev, refcount_read(&bo->base.pages_use_count) > 1); - unmapped = iommu_unmap(bo->domain->domain, bo->mm.start, bo->size); + unmapped = iommu_unmap(vm->domain, bo->mm.start, bo->size); drm_WARN_ON(obj->dev, unmapped != bo->size); - mutex_lock(&rocket_priv->mm_lock); + mutex_lock(&vm->lock); drm_mm_remove_node(&bo->mm); - mutex_unlock(&rocket_priv->mm_lock); + mutex_unlock(&vm->lock); - rocket_iommu_domain_put(bo->domain); - bo->domain = NULL; + rocket_vm_put(vm); + bo->vm = NULL; drm_gem_shmem_free(&bo->base); } @@ -64,6 +64,7 @@ int rocket_ioctl_create_bo(struct drm_device *dev, void *data, struct drm_file * struct drm_gem_shmem_object *shmem_obj; struct rocket_gem_object *rkt_obj; struct drm_gem_object *gem_obj; + struct rocket_vm *vm; struct sg_table *sgt; int ret; @@ -74,8 +75,8 @@ int rocket_ioctl_create_bo(struct drm_device *dev, void *data, struct drm_file * gem_obj = &shmem_obj->base; rkt_obj = to_rocket_bo(gem_obj); - rkt_obj->driver_priv = rocket_priv; - rkt_obj->domain = rocket_iommu_domain_get(rocket_priv); + vm = rocket_vm_get(rocket_priv); + rkt_obj->vm = vm; rkt_obj->size = args->size; rkt_obj->offset = 0; @@ -85,15 +86,15 @@ int rocket_ioctl_create_bo(struct drm_device *dev, void *data, struct drm_file * goto err; } - mutex_lock(&rocket_priv->mm_lock); - ret = drm_mm_insert_node_generic(&rocket_priv->mm, &rkt_obj->mm, + mutex_lock(&vm->lock); + ret = drm_mm_insert_node_generic(&vm->mm, &rkt_obj->mm, rkt_obj->size, PAGE_SIZE, 0, 0); - mutex_unlock(&rocket_priv->mm_lock); + mutex_unlock(&vm->lock); if (ret) goto err; - ret = iommu_map_sgtable(rocket_priv->domain->domain, + ret = iommu_map_sgtable(vm->domain, rkt_obj->mm.start, shmem_obj->sgt, IOMMU_READ | IOMMU_WRITE); @@ -118,17 +119,17 @@ int rocket_ioctl_create_bo(struct drm_device *dev, void *data, struct drm_file * return 0; err_unmap: - iommu_unmap(rocket_priv->domain->domain, + iommu_unmap(vm->domain, rkt_obj->mm.start, rkt_obj->size); err_remove_node: - mutex_lock(&rocket_priv->mm_lock); + mutex_lock(&vm->lock); drm_mm_remove_node(&rkt_obj->mm); - mutex_unlock(&rocket_priv->mm_lock); + mutex_unlock(&vm->lock); err: - rocket_iommu_domain_put(rkt_obj->domain); - rkt_obj->domain = NULL; + rocket_vm_put(rkt_obj->vm); + rkt_obj->vm = NULL; drm_gem_shmem_object_free(gem_obj); return ret; diff --git a/drivers/accel/rocket/rocket_gem.h b/drivers/accel/rocket/rocket_gem.h index 24043033450941..e1fbbd8cf71901 100644 --- a/drivers/accel/rocket/rocket_gem.h +++ b/drivers/accel/rocket/rocket_gem.h @@ -9,9 +9,7 @@ struct rocket_gem_object { struct drm_gem_shmem_object base; - struct rocket_file_priv *driver_priv; - - struct rocket_iommu_domain *domain; + struct rocket_vm *vm; struct drm_mm_node mm; size_t size; u32 offset; diff --git a/drivers/accel/rocket/rocket_job.c b/drivers/accel/rocket/rocket_job.c index 285af1044be101..c6fe3f67b067ba 100644 --- a/drivers/accel/rocket/rocket_job.c +++ b/drivers/accel/rocket/rocket_job.c @@ -268,7 +268,7 @@ static void rocket_job_cleanup(struct kref *ref) refcount); unsigned int i; - rocket_iommu_domain_put(job->domain); + rocket_vm_put(job->vm); dma_fence_put(job->done_fence); dma_fence_put(job->inference_done_fence); @@ -349,7 +349,7 @@ static struct dma_fence *rocket_job_run(struct drm_sched_job *sched_job) if (ret < 0) goto err_put_fences; - ret = iommu_attach_group(job->domain->domain, core->iommu_group); + ret = iommu_attach_group(job->vm->domain, core->iommu_group); if (ret < 0) goto err_put_pm; @@ -590,7 +590,7 @@ static int rocket_ioctl_submit_job(struct drm_device *dev, struct drm_file *file kref_init(&rjob->refcount); rjob->rdev = rdev; - rjob->domain = rocket_iommu_domain_get(file_priv); + rjob->vm = rocket_vm_get(file_priv); ret = drm_sched_job_init(&rjob->base, &file_priv->sched_entity, diff --git a/drivers/accel/rocket/rocket_job.h b/drivers/accel/rocket/rocket_job.h index 4ae00feec3b939..9373c3d0273b4f 100644 --- a/drivers/accel/rocket/rocket_job.h +++ b/drivers/accel/rocket/rocket_job.h @@ -36,7 +36,7 @@ struct rocket_job { /* Fence to be signaled by IRQ handler when the job is complete. */ struct dma_fence *done_fence; - struct rocket_iommu_domain *domain; + struct rocket_vm *vm; struct kref refcount; }; From b2895c80151171fc792c2d467d2743d2660b2b29 Mon Sep 17 00:00:00 2001 From: Igor Paunovic Date: Sat, 14 Nov 2026 16:05:18 +1300 Subject: [PATCH 0605/2102] accel/rocket: request the core clocks by name rocket_core_init() never sets the .id of the clocks, so all four are requested with a NULL name and each one resolves to the first clock in the DT, aclk. As a result aclk is taken and enabled four times, while hclk, pclk and the NPU compute clock are never enabled by the driver. It only works today because the power-domain driver enables those clocks for it. Give the four clocks their names, in the order the binding defines: aclk, hclk, npu and pclk. With that, a DT that lacks any of these clock-names fails probe with -ENOENT instead of running on the wrong clock. Fixes: ed98261b4168 ("accel/rocket: Add a new driver for Rockchip's NPU") Signed-off-by: Igor Paunovic Tested-by: Sidong Yang Tested-by: Diederik de Haas # NanoPC-T6 LTS, NanoPC-T6 Plus Reviewed-by: Sebastian Reichel Reviewed-by: Jiaxing Hu [Jiaxing: shortened the commit message, named the clock indices] Signed-off-by: Jiaxing Hu Reviewed-by: Heiko Stuebner Reviewed-by: Tomeu Vizoso Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/13f16cecfc7082c865b4d9308f0ccb50bee57500.1794615323.git.gahing@gahingwoo.com --- drivers/accel/rocket/rocket_core.c | 4 ++++ drivers/accel/rocket/rocket_core.h | 10 +++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/drivers/accel/rocket/rocket_core.c b/drivers/accel/rocket/rocket_core.c index b3b2fa9ba645a6..d4c06ad4ba9571 100644 --- a/drivers/accel/rocket/rocket_core.c +++ b/drivers/accel/rocket/rocket_core.c @@ -28,6 +28,10 @@ int rocket_core_init(struct rocket_core *core) if (err) return dev_err_probe(dev, err, "failed to get resets for core %d\n", core->index); + core->clks[ROCKET_CLK_ACLK].id = "aclk"; + core->clks[ROCKET_CLK_HCLK].id = "hclk"; + core->clks[ROCKET_CLK_NPU].id = "npu"; + core->clks[ROCKET_CLK_PCLK].id = "pclk"; err = devm_clk_bulk_get(dev, ARRAY_SIZE(core->clks), core->clks); if (err) return dev_err_probe(dev, err, "failed to get clocks for core %d\n", core->index); diff --git a/drivers/accel/rocket/rocket_core.h b/drivers/accel/rocket/rocket_core.h index 6eb975322e0c22..0b7e82ae7ef28d 100644 --- a/drivers/accel/rocket/rocket_core.h +++ b/drivers/accel/rocket/rocket_core.h @@ -27,6 +27,14 @@ #define rocket_core_writel(core, reg, value) \ writel(value, (core)->core_iomem + (REG_CORE_##reg) - REG_CORE_S_STATUS) +enum rocket_clk { + ROCKET_CLK_ACLK, + ROCKET_CLK_HCLK, + ROCKET_CLK_NPU, + ROCKET_CLK_PCLK, + ROCKET_CLK_MAX, +}; + struct rocket_core { struct device *dev; struct rocket_device *rdev; @@ -40,7 +48,7 @@ struct rocket_core { void __iomem *pc_iomem; void __iomem *cna_iomem; void __iomem *core_iomem; - struct clk_bulk_data clks[4]; + struct clk_bulk_data clks[ROCKET_CLK_MAX]; struct reset_control_bulk_data resets[2]; struct iommu_group *iommu_group; From 0d8026c7ac0c79a8ebe2942a3c3114c06aced734 Mon Sep 17 00:00:00 2001 From: Daejun Park Date: Mon, 9 Nov 2026 17:26:56 +0900 Subject: [PATCH 0606/2102] xfs: break layouts before swapping extents XFS_IOC_SWAPEXT does not break pNFS layouts. A client can keep writing to blocks that the swap moved to the temporary file. xfs_fsr frees those blocks when it closes that file. The writes then land in whatever reuses them. Lock with xfs_ilock2_io_mmap(), as the exchange-range ioctls do. Fixes: 781355c6e5ae ("xfs: recall pNFS layouts on conflicting access") Cc: stable@vger.kernel.org Signed-off-by: Daejun Park Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_bmap_util.c | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/fs/xfs/xfs_bmap_util.c b/fs/xfs/xfs_bmap_util.c index 4673d5174645a0..d2f421ae8d6f18 100644 --- a/fs/xfs/xfs_bmap_util.c +++ b/fs/xfs/xfs_bmap_util.c @@ -1567,9 +1567,9 @@ xfs_swap_extents( * page cache safely. Once we have done this we can take the ilocks and * do the rest of the checks. */ - lock_two_nondirectories(VFS_I(ip), VFS_I(tip)); - filemap_invalidate_lock_two(VFS_I(ip)->i_mapping, - VFS_I(tip)->i_mapping); + error = xfs_ilock2_io_mmap(ip, tip); + if (error) + return error; /* Verify that both files have the same format */ if ((VFS_I(ip)->i_mode & S_IFMT) != (VFS_I(tip)->i_mode & S_IFMT)) { @@ -1775,9 +1775,7 @@ xfs_swap_extents( xfs_iunlock(ip, XFS_ILOCK_EXCL); xfs_iunlock(tip, XFS_ILOCK_EXCL); out_unlock: - filemap_invalidate_unlock_two(VFS_I(ip)->i_mapping, - VFS_I(tip)->i_mapping); - unlock_two_nondirectories(VFS_I(ip), VFS_I(tip)); + xfs_iunlock2_io_mmap(ip, tip); return error; out_trans_cancel: From 844bc1167f1b2d19d9495a556599af24dc4468bd Mon Sep 17 00:00:00 2001 From: Daejun Park Date: Tue, 10 Nov 2026 09:38:17 +0900 Subject: [PATCH 0607/2102] xfs: wait for direct I/O before swapping extents An AIO direct write drops the iolock before its bios complete. XFS_IOC_SWAPEXT does not wait for it. The write can land in blocks that the swap moved to the temporary file. Once xfs_fsr frees them, the write corrupts whatever reuses them. Wait for direct I/O first, as exchange-range does. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Signed-off-by: Daejun Park Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_bmap_util.c | 1 + 1 file changed, 1 insertion(+) diff --git a/fs/xfs/xfs_bmap_util.c b/fs/xfs/xfs_bmap_util.c index d2f421ae8d6f18..73e7db3203c0b0 100644 --- a/fs/xfs/xfs_bmap_util.c +++ b/fs/xfs/xfs_bmap_util.c @@ -1270,6 +1270,7 @@ xfs_swap_extent_flush( { int error; + inode_dio_wait(VFS_I(ip)); error = filemap_write_and_wait(VFS_I(ip)->i_mapping); if (error) return error; From 6995680ff5bb79c82edcdc46e9d762d7cb72ac64 Mon Sep 17 00:00:00 2001 From: Jiaxing Hu Date: Sat, 14 Nov 2026 16:05:19 +1300 Subject: [PATCH 0608/2102] accel/rocket: take the completion register writes under job_lock The IRQ handler writes OPERATION_ENABLE and INTERRUPT_CLEAR before it takes job_lock, while rocket_job_hw_submit() sets OPERATION_ENABLE to 1 under that lock. If the two run at the same time, the 0 written by the IRQ handler can overwrite the 1 written for a new task and stop a task that has just started. Move both writes into the existing scoped_guard(), so they are under the same lock as the submit. Fixes: 0810d5ad88a1 ("accel/rocket: Add job submission IOCTL") Signed-off-by: Jiaxing Hu Tested-by: Igor Paunovic # RK3588, three cores, induced reset, JOB_TIMEOUT_MS=2 Reviewed-by: Heiko Stuebner Tested-by: Sidong Yang # RK3588, ROCK 5B+ Reviewed-by: Tomeu Vizoso Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/1adbff3238fd312e23daab83ed936ad13d7f223f.1794615323.git.gahing@gahingwoo.com --- drivers/accel/rocket/rocket_job.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/drivers/accel/rocket/rocket_job.c b/drivers/accel/rocket/rocket_job.c index c6fe3f67b067ba..5eae1560774ee7 100644 --- a/drivers/accel/rocket/rocket_job.c +++ b/drivers/accel/rocket/rocket_job.c @@ -373,10 +373,15 @@ static void rocket_job_handle_irq(struct rocket_core *core) { pm_runtime_mark_last_busy(core->dev); - rocket_pc_writel(core, OPERATION_ENABLE, 0x0); - rocket_pc_writel(core, INTERRUPT_CLEAR, 0x1ffff); + scoped_guard(mutex, &core->job_lock) { + /* + * Stopping the block belongs under the lock. hw_submit() writes + * OPERATION_ENABLE too, and outside the lock this zero can land + * after that one and stop a task that has only just started. + */ + rocket_pc_writel(core, OPERATION_ENABLE, 0x0); + rocket_pc_writel(core, INTERRUPT_CLEAR, 0x1ffff); - scoped_guard(mutex, &core->job_lock) if (core->in_flight_job) { if (core->in_flight_job->next_task_idx < core->in_flight_job->task_count) { rocket_job_hw_submit(core, core->in_flight_job); @@ -388,6 +393,7 @@ static void rocket_job_handle_irq(struct rocket_core *core) pm_runtime_put_autosuspend(core->dev); core->in_flight_job = NULL; } + } } static void From f0b9e58eee233547e5d77e467ccee89d7a59dd63 Mon Sep 17 00:00:00 2001 From: Hengyu Liang Date: Thu, 12 Nov 2026 05:20:18 -0500 Subject: [PATCH 0609/2102] xfs: fix f_bfree underflow in statfs() Commit dd324cb79e54 ("xfs: refactor xfs_fs_statfs") made xfs_statfs_data() limit f_bfree with max(0LL, ...) instead of max_t(int64_t, 0, ...). However, the value is an unsigned difference, so max() never picks 0. As of now, when the free block counter is below the count of unavailable blocks, statfs() reports f_bfree and f_bavail close to 2^64 instead of 0, and df prints negative sizes. A similar issue happened before and was fixed by commit 237aac4624aa ("xfs: ensure f_bfree returned by statfs() is non-negative"). Perhaps the refactored code needs that fix as well. The issue can be reproduced on a new 2 GiB filesystem mounted on /mnt: for i in $(seq 3000); do head -c 65536 /dev/zero > /mnt/s$i; done dd if=/dev/zero of=/mnt/big bs=1M xfs_io -x -c 'resblks 100000000' /mnt for i in $(seq 1 2 3000); do rm /mnt/s$i; done sync df -h /mnt Before commit dd324cb79e54 ("xfs: refactor xfs_fs_statfs"), the result is: Filesystem Size Used Avail Use% Mounted on /dev/vda 2.0G 2.0G 0 100% /mnt After that commit, the result is: Filesystem Size Used Avail Use% Mounted on /dev/vda 2.0G -64Z -24K 100% /mnt This patch will compare the difference as a signed value again. Fixes: dd324cb79e54 ("xfs: refactor xfs_fs_statfs") Cc: stable@vger.kernel.org # v6.14 Signed-off-by: Hengyu Liang Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_super.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/xfs/xfs_super.c b/fs/xfs/xfs_super.c index 5a06132aa38466..42be6bd34d43e9 100644 --- a/fs/xfs/xfs_super.c +++ b/fs/xfs/xfs_super.c @@ -916,7 +916,7 @@ xfs_statfs_data( xfs_sum_freecounter(mp, XC_FREE_BLOCKS); /* make sure st->f_bfree does not underflow */ - st->f_bfree = max(0LL, + st->f_bfree = max_t(int64_t, 0, fdblocks - xfs_freecounter_unavailable(mp, XC_FREE_BLOCKS)); /* From dce0eba182f2e18c5b5312d6ca18eb23dce73531 Mon Sep 17 00:00:00 2001 From: Jiaxing Hu Date: Sat, 14 Nov 2026 16:05:20 +1300 Subject: [PATCH 0610/2102] accel/rocket: wait for a running IRQ handler before resetting a core drm_sched_stop() does not wait for a threaded IRQ handler that is already running, so call synchronize_irq() after it to make sure the handler has finished before the reset. Before synchronize_irq(), mask the interrupt and clear the raw status, so that the NPU core cannot report a completion afterwards. Do this under job_lock, because the submit path sets the interrupt mask under the same lock. Only touch these registers when the device is powered: check with pm_runtime_get_if_active(), so that a register access with the power domain off cannot raise an SError. Fixes: 0810d5ad88a1 ("accel/rocket: Add job submission IOCTL") Suggested-by: Igor Paunovic Signed-off-by: Jiaxing Hu Tested-by: Igor Paunovic # RK3588, three cores, induced reset, JOB_TIMEOUT_MS=2 Reviewed-by: Heiko Stuebner Tested-by: Sidong Yang # RK3588, ROCK 5B+ Reviewed-by: Tomeu Vizoso [tomeu: added Fixes] Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/18667b2afdcaae217fa1038f5348ab23ed756bdc.1794615323.git.gahing@gahingwoo.com --- drivers/accel/rocket/rocket_job.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/drivers/accel/rocket/rocket_job.c b/drivers/accel/rocket/rocket_job.c index 5eae1560774ee7..29532c29340824 100644 --- a/drivers/accel/rocket/rocket_job.c +++ b/drivers/accel/rocket/rocket_job.c @@ -404,6 +404,16 @@ rocket_reset(struct rocket_core *core, struct drm_sched_job *bad) drm_sched_stop(&core->sched, bad); + scoped_guard(mutex, &core->job_lock) { + if (pm_runtime_get_if_active(core->dev) > 0) { + rocket_pc_writel(core, INTERRUPT_MASK, 0x0); + rocket_pc_writel(core, INTERRUPT_CLEAR, 0x1ffff); + pm_runtime_put_autosuspend(core->dev); + } + } + + synchronize_irq(core->irq); + /* * Remaining interrupts have been handled, but we might still have * stuck jobs. Let's make sure the PM counters stay balanced by From 56b3c41b05ae2fc342ac874757d65482322eb360 Mon Sep 17 00:00:00 2001 From: Yiqing Wu Date: Mon, 16 Nov 2026 09:48:02 +0800 Subject: [PATCH 0611/2102] xfs: remove unused variable in xchk_stats_estimate_bufsize() The css variable in xchk_stats_estimate_bufsize() is initialized to point to the start of the cs_stats array and incremented on every iteration of the scan loop, but it is never dereferenced. GCC flags this as a dead assignment when building with W=1: fs/xfs/scrub/stats.c:146:34: warning: variable css set but not used [-Wunused-but-set-variable=] Drop the variable and the loop increment. Signed-off-by: Yiqing Wu Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/scrub/stats.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/fs/xfs/scrub/stats.c b/fs/xfs/scrub/stats.c index 6934d76cfd156b..dfdac4e7b4ad34 100644 --- a/fs/xfs/scrub/stats.c +++ b/fs/xfs/scrub/stats.c @@ -143,7 +143,6 @@ STATIC size_t xchk_stats_estimate_bufsize( struct xchk_stats *cs) { - struct xchk_scrub_stats *css = &cs->cs_stats[0]; unsigned int i; size_t field_width; size_t ret = 0; @@ -157,7 +156,7 @@ xchk_stats_estimate_bufsize( offsetof(struct xchk_scrub_stats, checktime_us)) / sizeof(uint64_t)); - for (i = 0; i < XFS_SCRUB_TYPE_NR; i++, css++) { + for (i = 0; i < XFS_SCRUB_TYPE_NR; i++) { if (!name_map[i]) continue; From 5c7da17f904da61c6912ae719e8f3c3eb353ee88 Mon Sep 17 00:00:00 2001 From: Yiqing Wu Date: Mon, 16 Nov 2026 10:05:10 +0800 Subject: [PATCH 0612/2102] xfs: remove unused variable in xrep_tempfile_copyin() The pos variable in xrep_tempfile_copyin() is initialized from the starting file offset and incremented on every iteration of the copy loop, but it is never used. GCC flags this as a dead assignment when building with W=1: fs/xfs/scrub/tempfile.c:493:33: warning: variable pos set but not used [-Wunused-but-set-variable=] Drop the variable and the loop increment. Signed-off-by: Yiqing Wu Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/scrub/tempfile.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/fs/xfs/scrub/tempfile.c b/fs/xfs/scrub/tempfile.c index 59a9213a3c7ddf..6340afcc22cf7f 100644 --- a/fs/xfs/scrub/tempfile.c +++ b/fs/xfs/scrub/tempfile.c @@ -490,7 +490,6 @@ xrep_tempfile_copyin( struct xfs_buf *bp; xfs_fileoff_t flush_mask; xfs_fileoff_t end = off + len; - loff_t pos = XFS_FSB_TO_B(mp, off); int error = 0; ASSERT(S_ISREG(VFS_I(sc->tempip)->i_mode)); @@ -498,7 +497,7 @@ xrep_tempfile_copyin( /* Flush buffers to disk every 512K */ flush_mask = XFS_B_TO_FSBT(mp, (1U << 19)) - 1; - for (; off < end; off++, pos += mp->m_sb.sb_blocksize) { + for (; off < end; off++) { struct xfs_bmbt_irec map; int nmaps = 1; From 765db499ad5837365b445b26b6fc81f30f134758 Mon Sep 17 00:00:00 2001 From: Eric Sandeen Date: Fri, 13 Nov 2026 18:59:24 -0600 Subject: [PATCH 0613/2102] xfs: properly order xfsstats proc/sysfs init and teardown The xfs statistics are accessible both through procfs and through sysctls, so they need to be fully set up before exposure via those interfaces, and those interfaces both need to be torn down before the underlying percpu structures are freed. Today we get that wrong on both ends - we expose them through xfs_init_procfs before allocating the percpu structures, and we free those percpu structures before tearing down sysctls and procfs. Fix init_xfs_fs by calling alloc_percpu(xfsstats) prior to xfs_init_procfs(), and fix the error unwind path to reflect this, then also move free_percpu() to after tearing down both procfs and sysctls in exit_xfs_fs. Reported-by: Hanxiang Xu Fixes: 80529c45ab66 ("xfs: pass xfsstats structures to handlers and macros") Signed-off-by: Eric Sandeen Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_super.c | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/fs/xfs/xfs_super.c b/fs/xfs/xfs_super.c index 42be6bd34d43e9..2f6999b6947e6b 100644 --- a/fs/xfs/xfs_super.c +++ b/fs/xfs/xfs_super.c @@ -2668,9 +2668,15 @@ init_xfs_fs(void) if (error) goto out_destroy_wq; + xfsstats.xs_stats = alloc_percpu(struct xfsstats); + if (!xfsstats.xs_stats) { + error = -ENOMEM; + goto out_mru_cache_uninit; + } + error = xfs_init_procfs(); if (error) - goto out_mru_cache_uninit; + goto out_free_stats; error = xfs_sysctl_register(); if (error) @@ -2686,16 +2692,10 @@ init_xfs_fs(void) xfsstats.xs_kobj.kobject.kset = xfs_kset; - xfsstats.xs_stats = alloc_percpu(struct xfsstats); - if (!xfsstats.xs_stats) { - error = -ENOMEM; - goto out_kset_unregister; - } - error = xfs_sysfs_init(&xfsstats.xs_kobj, &xfs_stats_ktype, NULL, "stats"); if (error) - goto out_free_stats; + goto out_kset_unregister; error = xchk_global_stats_setup(xfs_debugfs); if (error) @@ -2727,8 +2727,6 @@ init_xfs_fs(void) xchk_global_stats_teardown(); out_remove_stats_kobj: xfs_sysfs_del(&xfsstats.xs_kobj); - out_free_stats: - free_percpu(xfsstats.xs_stats); out_kset_unregister: kset_unregister(xfs_kset); out_debugfs_unregister: @@ -2736,6 +2734,8 @@ init_xfs_fs(void) xfs_sysctl_unregister(); out_cleanup_procfs: xfs_cleanup_procfs(); + out_free_stats: + free_percpu(xfsstats.xs_stats); out_mru_cache_uninit: xfs_mru_cache_uninit(); out_destroy_wq: @@ -2756,11 +2756,11 @@ exit_xfs_fs(void) #endif xchk_global_stats_teardown(); xfs_sysfs_del(&xfsstats.xs_kobj); - free_percpu(xfsstats.xs_stats); kset_unregister(xfs_kset); debugfs_remove(xfs_debugfs); xfs_sysctl_unregister(); xfs_cleanup_procfs(); + free_percpu(xfsstats.xs_stats); xfs_mru_cache_uninit(); xfs_destroy_workqueues(); xfs_destroy_caches(); From 14866e632fa48a0b4c385ab0121526575eb8f88c Mon Sep 17 00:00:00 2001 From: Marek Szyprowski Date: Tue, 10 Nov 2026 00:08:29 +0100 Subject: [PATCH 0614/2102] dma-pool: decrypt pages before creating the shared remap atomic_pool_expand() creates the pgprot_decrypted() remap of the pool pages before calling set_memory_decrypted() on them. The error path when gen_pool_add_virt() fails does the reverse: it re-encrypts the pages and only then tears down the decrypted remap. In both cases there is a window where a decrypted (shared) kernel mapping points at a page that is still private, i.e. encrypted, to the guest. dma_direct_alloc() gets this right: it converts the pages first, then creates the remap, and on error removes the remap before re-encrypting. Do the same in atomic_pool_expand(). The pages are now converted before arch_dma_prep_coherent() and the remap, and the error path unwinds in reverse order. If set_memory_decrypted() fails, the encryption state of the pages is unknown (the conversion may have partially succeeded), so they must not be returned to the page allocator or CMA and are intentionally leaked, as before. No remap exists at that point any more, so nothing else needs to be undone. Add a comment explaining this. Closes: https://sashiko.dev/#/bug/linux-9212d9b5-4a56-43e2-bc00-6e69b724078b Fixes: 76a19940bd62 ("dma-direct: atomic allocations must come from atomic coherent pools") Reviewed-by: Aneesh Kumar K.V (Arm) Link: https://lore.kernel.org/r/20261109230830.1707975-1-m.szyprowski@samsung.com Signed-off-by: Marek Szyprowski --- kernel/dma/pool.c | 48 +++++++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/kernel/dma/pool.c b/kernel/dma/pool.c index 381b3cb28368fc..5e8cf12e822292 100644 --- a/kernel/dma/pool.c +++ b/kernel/dma/pool.c @@ -106,6 +106,22 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size, if (!page) goto out; + /* + * Memory in the atomic DMA pools must be unencrypted, the pools do not + * shrink so no re-encryption occurs in dma_direct_free(). + */ + if (dma_pool->cc_shared) { + ret = set_memory_decrypted((unsigned long)page_to_virt(page), + 1 << order); + /* + * On failure the encryption state of the pages is unknown, + * so they must not be returned to the page allocator or CMA. + * Leak them intentionally. + */ + if (ret) + goto out; + } + arch_dma_prep_coherent(page, pool_size); #ifdef CONFIG_DMA_DIRECT_REMAP @@ -116,42 +132,30 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size, addr = dma_common_contiguous_remap(page, pool_size, prot, __builtin_return_address(0)); - if (!addr) - goto free_page; + if (!addr) { + ret = -ENOMEM; + goto encrypt_pages; + } #else addr = page_to_virt(page); #endif - /* - * Memory in the atomic DMA pools must be unencrypted, the pools do not - * shrink so no re-encryption occurs in dma_direct_free(). - */ - if (dma_pool->cc_shared) { - ret = set_memory_decrypted((unsigned long)page_to_virt(page), - 1 << order); - if (ret) { - leak_pages = true; - goto remove_mapping; - } - } - ret = gen_pool_add_virt(dma_pool->pool, (unsigned long)addr, page_to_phys(page), pool_size, NUMA_NO_NODE); if (ret) - goto encrypt_mapping; + goto remove_mapping; dma_atomic_pool_size_add(gfp, pool_size); return 0; -encrypt_mapping: - if (dma_pool->cc_shared && - set_memory_encrypted((unsigned long)page_to_virt(page), 1 << order)) - leak_pages = true; - remove_mapping: #ifdef CONFIG_DMA_DIRECT_REMAP dma_common_free_remap(addr, pool_size); -free_page: +encrypt_pages: #endif + if (dma_pool->cc_shared && + set_memory_encrypted((unsigned long)page_to_virt(page), 1 << order)) + leak_pages = true; + if (!leak_pages && !dma_release_from_contiguous(NULL, page, 1 << order)) __free_pages(page, order); From 36161ff0c00fd52f725c14748ca54c83d86d1626 Mon Sep 17 00:00:00 2001 From: Jiaxing Hu Date: Sat, 14 Nov 2026 16:05:21 +1300 Subject: [PATCH 0615/2102] accel/rocket: let the core suspend after a reset The reset path drops the runtime PM reference with pm_runtime_put_noidle(), which does not let the device suspend, so the power domain is never switched off and on again. Use pm_runtime_put_autosuspend() instead, so the reset path handles runtime PM the same way as a normal job completion. Also drop the runtime PM reference after rocket_core_reset(), so the NPU core stays powered during the reset. Link: https://lore.kernel.org/all/20260819073530.6087-1-royalnet026@gmail.com/ Fixes: 0810d5ad88a1 ("accel/rocket: Add job submission IOCTL") Signed-off-by: Jiaxing Hu Reviewed-by: Heiko Stuebner Tested-by: Sidong Yang # RK3588, ROCK 5B+ Reviewed-by: Tomeu Vizoso [tomeu: dropped the outdated RK3576 rationale from above] Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/2afd051e37b8dd4f10e347a3537b0086973d554c.1794615323.git.gahing@gahingwoo.com --- drivers/accel/rocket/rocket_job.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/drivers/accel/rocket/rocket_job.c b/drivers/accel/rocket/rocket_job.c index 29532c29340824..6f581df0b41329 100644 --- a/drivers/accel/rocket/rocket_job.c +++ b/drivers/accel/rocket/rocket_job.c @@ -399,6 +399,8 @@ static void rocket_job_handle_irq(struct rocket_core *core) static void rocket_reset(struct rocket_core *core, struct drm_sched_job *bad) { + bool put_job_ref; + if (!atomic_read(&core->reset.pending)) return; @@ -417,11 +419,10 @@ rocket_reset(struct rocket_core *core, struct drm_sched_job *bad) /* * Remaining interrupts have been handled, but we might still have * stuck jobs. Let's make sure the PM counters stay balanced by - * manually calling pm_runtime_put_noidle(). + * dropping the job's reference once the core has been reset. */ scoped_guard(mutex, &core->job_lock) { - if (core->in_flight_job) - pm_runtime_put_noidle(core->dev); + put_job_ref = core->in_flight_job; iommu_detach_group(NULL, core->iommu_group); @@ -431,6 +432,9 @@ rocket_reset(struct rocket_core *core, struct drm_sched_job *bad) /* Proceed with reset now. */ rocket_core_reset(core); + if (put_job_ref) + pm_runtime_put_autosuspend(core->dev); + /* NPU has been reset, we can clear the reset pending bit. */ atomic_set(&core->reset.pending, 0); From 3b6942b132033cbc3f6566f698709d9038daf7b2 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Thu, 12 Nov 2026 16:46:11 -0500 Subject: [PATCH 0616/2102] xfs: test for reflink after the dio write checks A direct write that is not block aligned can expose stale disk contents on XFS if it races with the first clone of the file. xfs_file_dio_write_unaligned() falls back to buffered I/O if the file is reflinked, and tests for that right after it takes the iolock. But xfs_file_write_checks() runs after the test and can drop the iolock, for example if S_NOSEC is not set. A clone can run in that gap: direct write clone ============ ===== takes the iolock shared sees that the file is not reflinked drops the iolock shares the blocks takes the iolock exclusive writes a part of a new COW block maps the whole block into the file /* the rest was never written */ The fix used here is to move the test after xfs_file_write_checks(). Fixes: ed1128c2d0c8 ("xfs: reduce exclusive locking on unaligned dio") Signed-off-by: Chris Mason Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_file.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/fs/xfs/xfs_file.c b/fs/xfs/xfs_file.c index be1f775128d11f..0236be58a4afdb 100644 --- a/fs/xfs/xfs_file.c +++ b/fs/xfs/xfs_file.c @@ -866,9 +866,15 @@ xfs_file_dio_write_unaligned( if (ret) return ret; + ret = xfs_file_write_checks(iocb, from, &iolock, NULL); + if (ret) + goto out_unlock; + /* * We can't properly handle unaligned direct I/O to reflink files yet, - * as we can't unshare a partial block. + * as we can't unshare a partial block. xfs_file_write_checks() can + * drop the iolock and take it again, and the file can be reflinked in + * between, so test for that only now. */ if (xfs_is_cow_inode(ip)) { trace_xfs_reflink_bounce_dio_write(iocb, from); @@ -876,10 +882,6 @@ xfs_file_dio_write_unaligned( goto out_unlock; } - ret = xfs_file_write_checks(iocb, from, &iolock, NULL); - if (ret) - goto out_unlock; - /* * If we are doing exclusive unaligned I/O, this must be the only I/O * in-flight. Otherwise we risk data corruption due to unwritten extent From 7b2438af4d91dcb8fe3de99e55beb06f3c168309 Mon Sep 17 00:00:00 2001 From: Christoph Hellwig Date: Thu, 12 Nov 2026 16:46:12 -0500 Subject: [PATCH 0617/2102] xfs: refuse writes to files racing with realtime inode flag changes Zoned writes need to reserve space before taking the iolock to avoid deadlocks with garbage collection. But this means that the realtime inode flag which indicates if the file will be placed on the zoned realtime device or the main data device can be flipped after taking the reservation and before taking the write, or after deciding to go down the regular write path, both of which can't work. Re-sample the realtime flag just before the actual write, and refuse the write if the flag changed. Do not retry the write using the now correct path, as switching the flag under a write is not a normal use case, and trying to flip between the zoned and regular path is an inherent life lock as it could be switched around again the next time this check is performed. Fixes: 058dd70c65ab ("xfs: implement buffered writes to zoned RT devices") Fixes: 2e2383405824 ("xfs: implement direct writes to zoned RT devices") Reported-by: Chris Mason Signed-off-by: Christoph Hellwig Signed-off-by: Chris Mason Reviewed-by: Carlos Maiolino Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_file.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/fs/xfs/xfs_file.c b/fs/xfs/xfs_file.c index 0236be58a4afdb..1e56d239b0e48b 100644 --- a/fs/xfs/xfs_file.c +++ b/fs/xfs/xfs_file.c @@ -441,6 +441,19 @@ xfs_file_write_checks( goto restart; } + /* + * Now that we are in the same IOLOCK critical section as the actual + * write, check that the inode still has the realtime flag in the state + * that the caller expects. If not, some deliberately cleared it while + * I/O is ongoing, so bail out. + */ + if (xfs_is_zoned_inode(XFS_I(inode)) != !!ac) { + xfs_warn_ratelimited(XFS_I(inode)->i_mount, + "RT flag modifying during write for inode 0x%llx.", + inode->i_ino); + return -EINVAL; + } + /* * If the offset is beyond the size of the file, we need to zero all * blocks that fall between the existing EOF and the start of this From bdc3ee45df55d8aa478d8a5d6a7e9b1186f511ba Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Thu, 12 Nov 2026 16:46:13 -0500 Subject: [PATCH 0618/2102] xfs: test for always COW after the dio write checks A direct write to a zoned file from vectors that are not block aligned can silently corrupt the file's data, if the realtime flag is cleared and set again while the write starts. Every bio of an always COW write has to cover whole blocks, so xfs_file_dio_write_aligned() passes IOMAP_DIO_FSBLOCK_ALIGNED for such an inode. But it tests for always COW before it takes the IOLOCK, and the realtime flag of a file with no blocks can change until then: xfs_file_dio_write_zoned() FS_IOC_FSSETXATTR ========================== ================= xfs_zoned_write_space_reserve() clears the realtime flag xfs_file_dio_write_aligned() xfs_is_always_cow_inode() is false sets the realtime flag xfs_ilock_iocb_for_write() xfs_file_write_checks() iomap_dio_rw() splits a bio inside a block The fix used here is to test for always COW once the IOLOCK is held. Before commit 8caec6c9fef7 ("xfs: support sub-block aligned vectors in always COW mode"), xfs_file_dio_write() made the same test with no lock held, to send such vectors down the unaligned path. So v6.15 to v6.18 have the same race, and need a different version of this fix. Fixes: 2e2383405824 ("xfs: implement direct writes to zoned RT devices") Signed-off-by: Chris Mason Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_file.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/fs/xfs/xfs_file.c b/fs/xfs/xfs_file.c index 1e56d239b0e48b..2252b986b63dc5 100644 --- a/fs/xfs/xfs_file.c +++ b/fs/xfs/xfs_file.c @@ -708,14 +708,6 @@ xfs_file_dio_write_aligned( unsigned int dio_flags = 0; ssize_t ret; - /* - * For always COW inodes, each bio must be aligned to the file system - * block size and not just the device sector size because we need to - * allocate a block-aligned amount of space for each write. - */ - if (xfs_is_always_cow_inode(ip)) - dio_flags |= IOMAP_DIO_FSBLOCK_ALIGNED; - ret = xfs_ilock_iocb_for_write(iocb, &iolock); if (ret) return ret; @@ -732,6 +724,15 @@ xfs_file_dio_write_aligned( xfs_ilock_demote(ip, XFS_IOLOCK_EXCL); iolock = XFS_IOLOCK_SHARED; } + + /* + * For always COW inodes, each bio must be aligned to the file system + * block size and not just the device sector size because we need to + * allocate a block-aligned amount of space for each write. The + * realtime flag can change until we hold the IOLOCK, so test only now. + */ + if (xfs_is_always_cow_inode(ip)) + dio_flags |= IOMAP_DIO_FSBLOCK_ALIGNED; if (mapping_stable_writes(iocb->ki_filp->f_mapping)) dio_flags |= IOMAP_DIO_BOUNCE; trace_xfs_file_direct_write(iocb, from); From f01f70e00770c6d21b468f80b488e6407a6947dc Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Thu, 12 Nov 2026 16:46:14 -0500 Subject: [PATCH 0619/2102] xfs: refuse fallocate racing with realtime flag changes On a zoned XFS, fallocate() can dereference a NULL pointer if the realtime flag of the file is set during the call. xfs_file_fallocate() reserves zoned space only for a zoned inode, and tests for that before it takes the iolock. FS_IOC_FSSETXATTR can change the realtime flag of a file with no blocks in that gap. xfs_falloc_force_zero() then sees a zoned inode and reads the reservation, which is NULL: fallocate(FALLOC_FL_ZERO_RANGE) FS_IOC_FSSETXATTR =============================== ================= takes the iolock sees that the inode is not zoned waits for the iolock sets the realtime flag drops the iolock xfs_falloc_force_zero() sees that the inode is zoned /* ac is NULL */ The fix used here is to test again under the iolock, and to fail the call with -EINVAL if the answer has changed, as the write path does. Fixes: 058dd70c65ab ("xfs: implement buffered writes to zoned RT devices") Signed-off-by: Chris Mason Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_file.c | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/fs/xfs/xfs_file.c b/fs/xfs/xfs_file.c index 2252b986b63dc5..7676ae6d66563a 100644 --- a/fs/xfs/xfs_file.c +++ b/fs/xfs/xfs_file.c @@ -1536,6 +1536,21 @@ xfs_falloc_allocate_range( FALLOC_FL_ZERO_RANGE | FALLOC_FL_INSERT_RANGE | \ FALLOC_FL_UNSHARE_RANGE | FALLOC_FL_WRITE_ZEROES) +/* + * For zoned file systems, zeroing the first and last block of a hole punch + * requires allocating a new block to rewrite the remaining data and new zeroes + * out of place, which needs a space reservation. + */ +static inline bool +xfs_falloc_needs_zoned_resv( + struct xfs_inode *ip, + int mode) +{ + return xfs_is_zoned_inode(ip) && + (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE | + FALLOC_FL_COLLAPSE_RANGE)); +} + STATIC long __xfs_file_fallocate( struct file *file, @@ -1554,6 +1569,19 @@ __xfs_file_fallocate( if (error) goto out_unlock; + /* + * The caller looked at the realtime flag before we took the IOLOCK, to + * decide if it has to reserve space. Bail out if the flag has changed + * since. + */ + if (xfs_falloc_needs_zoned_resv(ip, mode) != !!ac) { + xfs_warn_ratelimited(ip->i_mount, + "RT flag modifying during fallocate for inode 0x%llx.", + inode->i_ino); + error = -EINVAL; + goto out_unlock; + } + /* * Must wait for all AIO to complete before we continue as AIO can * change the file size on completion without holding any locks we @@ -1649,16 +1677,11 @@ xfs_file_fallocate( return -EOPNOTSUPP; /* - * For zoned file systems, zeroing the first and last block of a hole - * punch requires allocating a new block to rewrite the remaining data - * and new zeroes out of place. Get a reservations for those before - * taking the iolock. Dip into the reserved pool because we are - * expected to be able to punch a hole even on a completely full - * file system. + * Get the reservation before taking the iolock. Dip into the reserved + * pool because we are expected to be able to punch a hole even on a + * completely full file system. */ - if (xfs_is_zoned_inode(XFS_I(inode)) && - (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE | - FALLOC_FL_COLLAPSE_RANGE))) + if (xfs_falloc_needs_zoned_resv(XFS_I(inode), mode)) return xfs_file_zoned_fallocate(file, mode, offset, len); return __xfs_file_fallocate(file, mode, offset, len, NULL); } From 230565493938cc0284116ff3795eb5343781eb97 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Thu, 12 Nov 2026 16:46:15 -0500 Subject: [PATCH 0620/2102] xfs: take the MMAPLOCK in xfs_fileattr_set() A store through a shared mapping can corrupt a realtime file system on disk, or shut a file system down, if FS_IOC_FSSETXATTR changes the realtime flag or an extent size hint of the file during the write fault. A write fault reads the flag and the hints more than once: to choose delayed allocation, to size the block reservation, and again in the allocator. All of these have to see the same values. System calls that write do the same, but they hold the IOLOCK, which keeps the ioctl out. A fault only holds the MMAPLOCK, which the ioctl does not take: write fault FS_IOC_FSSETXATTR =========== ================= takes the MMAPLOCK xfs_iomap_write_direct() reserves blocks for the old hint takes the ILOCK raises the hint drops the ILOCK takes the ILOCK xfs_bmapi_write() allocates for the new hint /* more than was reserved */ The fix used here is to make the ioctl take the MMAPLOCK of a regular file as well. Signed-off-by: Chris Mason Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_inode.c | 3 ++- fs/xfs/xfs_ioctl.c | 17 +++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/fs/xfs/xfs_inode.c b/fs/xfs/xfs_inode.c index cb61305e4b80dc..0584ad11f92ba3 100644 --- a/fs/xfs/xfs_inode.c +++ b/fs/xfs/xfs_inode.c @@ -134,7 +134,8 @@ xfs_lock_flags_assert( * take both the i_rwsem and the invalidate_lock. These locks should *only* be * both taken in places where we need to invalidate the page cache in a race * free manner (e.g. truncate, hole punch and other extent manipulation - * functions). + * functions), or where we change inode attributes that both kinds of IO rely + * on (xfs_fileattr_set). */ void xfs_ilock( diff --git a/fs/xfs/xfs_ioctl.c b/fs/xfs/xfs_ioctl.c index 36ba609a2593ad..4a139eef84efc3 100644 --- a/fs/xfs/xfs_ioctl.c +++ b/fs/xfs/xfs_ioctl.c @@ -757,6 +757,7 @@ xfs_fileattr_set( struct xfs_trans *tp; struct xfs_dquot *pdqp = NULL; struct xfs_dquot *olddquot = NULL; + bool isreg = S_ISREG(VFS_I(ip)->i_mode); int error; trace_xfs_ioctl_setattr(ip); @@ -804,10 +805,18 @@ xfs_fileattr_set( xfs_ioctl_setattr_prepare_dax(ip, fa); + /* + * A write fault only holds the MMAPLOCK, and it looks at the realtime + * flag and at the extent size hints more than once. Only regular files + * have write faults. + */ + if (isreg) + xfs_ilock(ip, XFS_MMAPLOCK_EXCL); + tp = xfs_ioctl_setattr_get_trans(ip, pdqp); if (IS_ERR(tp)) { error = PTR_ERR(tp); - goto error_free_dquots; + goto error_unlock; } error = xfs_ioctl_setattr_check_extsize(ip, fa); @@ -864,6 +873,8 @@ xfs_fileattr_set( skip_xattr: error = xfs_trans_commit(tp); + if (isreg) + xfs_iunlock(ip, XFS_MMAPLOCK_EXCL); /* * Release any dquot(s) the inode had kept before chown. @@ -875,7 +886,9 @@ xfs_fileattr_set( error_trans_cancel: xfs_trans_cancel(tp); -error_free_dquots: +error_unlock: + if (isreg) + xfs_iunlock(ip, XFS_MMAPLOCK_EXCL); xfs_qm_dqrele(pdqp); return error; } From 03cbbd80a3e7070e8ab63996a94a7815722c2578 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Thu, 12 Nov 2026 16:46:16 -0500 Subject: [PATCH 0621/2102] xfs: restart faults racing with realtime flag changes On a zoned XFS, a store through a shared mapping can dereference a NULL pointer if the realtime flag of the file is set as the write fault starts. xfs_write_fault() reserves zoned space only for a zoned inode. The reservation can wait for garbage collection, which takes the MMAPLOCK, so it comes ahead of that lock, and so does the test for a zoned inode. FS_IOC_FSSETXATTR can set the flag of a file with no blocks right after the test: write fault FS_IOC_FSSETXATTR =========== ================= xfs_write_fault() sees that the inode is not zoned sets the realtime flag takes the MMAPLOCK xfs_buffered_write_iomap_begin() sees that the inode is zoned /* ac is NULL */ The fix used here is to test again under the MMAPLOCK, which keeps the ioctl out since "xfs: take the MMAPLOCK in xfs_fileattr_set()", and to start the fault over if the flag has changed. Fixes: 058dd70c65ab ("xfs: implement buffered writes to zoned RT devices") Signed-off-by: Chris Mason Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_file.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/fs/xfs/xfs_file.c b/fs/xfs/xfs_file.c index 7676ae6d66563a..8070a07e601f59 100644 --- a/fs/xfs/xfs_file.c +++ b/fs/xfs/xfs_file.c @@ -2039,11 +2039,22 @@ __xfs_write_fault( lock_mode = XFS_MMAPLOCK_EXCL; } - if (IS_DAX(inode)) + /* + * The caller picked the zoned or the regular path with no lock held. + * The realtime flag cannot change under the MMAPLOCK, so look at it + * again, and start over if it has changed. + */ + if (xfs_is_zoned_inode(ip) != !!ac) { + xfs_warn_ratelimited(ip->i_mount, + "RT flag modifying during page fault for inode 0x%llx.", + inode->i_ino); + ret = VM_FAULT_NOPAGE; + } else if (IS_DAX(inode)) { ret = xfs_dax_fault_locked(vmf, order, true); - else + } else { ret = iomap_page_mkwrite(vmf, &xfs_buffered_write_iomap_ops, ac); + } xfs_iunlock(ip, lock_mode); sb_end_pagefault(inode->i_sb); From 44e555acd77a839110f3b1e02a75f9165baaaeec Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Thu, 12 Nov 2026 16:46:17 -0500 Subject: [PATCH 0622/2102] xfs: don't enable DAX on zoned inodes A store through a shared mapping can dereference a NULL pointer if the file is zoned and has S_DAX. The zoned code does not support DAX, but XFS doesn't check for this: with dax=always or FS_XFLAG_DAX, an inode gets S_DAX if its device does DAX, and an internal zoned section on pmem does. The write fault then takes the zoned path: xfs_filemap_fault() xfs_write_fault() xfs_write_fault_zoned() page_folio(vmf->page) /* NULL in a DAX fault */ ftruncate() crashes in a similar way, in xfs_reflink_end_cow(). The fix used here is to never set S_DAX on a zoned inode, and to refuse to change the realtime flag of an S_DAX inode on a zoned file system. Zoned files now use the page cache with dax=always or FS_XFLAG_DAX. A file whose realtime flag is cleared stays without DAX until its inode is evicted. Fixes: be458049ffe3 ("xfs: enable the zoned RT device feature") Signed-off-by: Chris Mason Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_ioctl.c | 8 +++++--- fs/xfs/xfs_iops.c | 4 ++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/fs/xfs/xfs_ioctl.c b/fs/xfs/xfs_ioctl.c index 4a139eef84efc3..c76e36dadf952b 100644 --- a/fs/xfs/xfs_ioctl.c +++ b/fs/xfs/xfs_ioctl.c @@ -564,11 +564,13 @@ xfs_ioctl_setattr_xflags( /* * If S_DAX is enabled on this file, we can only switch the - * device if both support fsdax. We can't update S_DAX because - * there might be other threads walking down the access paths. + * device if both support fsdax, and the zoned code does not. + * We can't update S_DAX because there might be other threads + * walking down the access paths. */ if (IS_DAX(VFS_I(ip)) && - (mp->m_ddev_targp->bt_daxdev == NULL || + (xfs_has_zoned(mp) || + mp->m_ddev_targp->bt_daxdev == NULL || (mp->m_rtdev_targp && mp->m_rtdev_targp->bt_daxdev == NULL))) return -EINVAL; diff --git a/fs/xfs/xfs_iops.c b/fs/xfs/xfs_iops.c index d307ec97fac820..a84a4c1c3fc2f1 100644 --- a/fs/xfs/xfs_iops.c +++ b/fs/xfs/xfs_iops.c @@ -1373,6 +1373,10 @@ xfs_inode_supports_dax( if (mp->m_sb.sb_blocksize != PAGE_SIZE) return false; + /* The zoned code does not support DAX. */ + if (xfs_is_zoned_inode(ip)) + return false; + /* Device has to support DAX too. */ return xfs_inode_buftarg(ip)->bt_daxdev != NULL; } From 855abf2cf8cd69a248362ca4b518de9387dd6bf5 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Thu, 12 Nov 2026 16:46:18 -0500 Subject: [PATCH 0623/2102] xfs: test for realtime and reflink under the pNFS locks A pNFS client can write to blocks that its file shares with another file, or that are no part of its file, if a LAYOUTGET races with a clone or with FS_IOC_FSSETXATTR. xfs_fs_map_blocks() hands out no layout for a reflinked or a realtime inode, since the client writes in place and only knows the data device. But it tests for both before it takes the IOLOCK, and both flags are set under that lock: LAYOUTGET clone ========= ===== takes the IOLOCK breaks the layouts xfs_fs_map_blocks() sees no reflink flag waits for the IOLOCK sets the reflink flag shares the blocks drops the IOLOCK maps the shared blocks /* the client writes in place */ If FS_IOC_FSSETXATTR sets the realtime flag of an empty file instead, the blocks come from the realtime device, and nfsd points the client at the same address on the data device. The fix used here is to test for both once the locks are held. Fixes: e54b5bf9d7ae ("xfs: recognize the reflink feature bit") Fixes: 527851124d10 ("xfs: implement pNFS export operations") Signed-off-by: Chris Mason Reviewed-by: Christoph Hellwig Signed-off-by: Carlos Maiolino --- fs/xfs/xfs_pnfs.c | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/fs/xfs/xfs_pnfs.c b/fs/xfs/xfs_pnfs.c index 065875c8b7dab8..945f7a3e11ca71 100644 --- a/fs/xfs/xfs_pnfs.c +++ b/fs/xfs/xfs_pnfs.c @@ -147,21 +147,6 @@ xfs_fs_map_blocks( if (xfs_is_shutdown(mp)) return -EIO; - /* - * We can't export inodes residing on the realtime device. The realtime - * device doesn't have a UUID to identify it, so the client has no way - * to find it. - */ - if (XFS_IS_REALTIME_INODE(ip)) - return -ENXIO; - - /* - * The pNFS block layout spec actually supports reflink like - * functionality, but the Linux pNFS server doesn't implement it yet. - */ - if (xfs_is_reflink_inode(ip)) - return -ENXIO; - /* * Lock out any other I/O before we flush and invalidate the pagecache, * and then hand out a layout to the remote system. This is very @@ -174,6 +159,23 @@ xfs_fs_map_blocks( */ xfs_ilock(ip, XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL); + /* + * We can't export inodes residing on the realtime device. The realtime + * device doesn't have a UUID to identify it, so the client has no way + * to find it. The flag is set under the IOLOCK, so test only now. + */ + error = -ENXIO; + if (XFS_IS_REALTIME_INODE(ip)) + goto out_unlock; + + /* + * The pNFS block layout spec actually supports reflink like + * functionality, but the Linux pNFS server doesn't implement it yet. + * This flag is set under the IOLOCK as well. + */ + if (xfs_is_reflink_inode(ip)) + goto out_unlock; + error = -EINVAL; limit = mp->m_super->s_maxbytes; if (!write) From b4d01c788bfa50dc65ffb5fbc9db4135004c0e01 Mon Sep 17 00:00:00 2001 From: "Markus Schneider-Pargmann (TI)" Date: Tue, 3 Nov 2026 14:15:33 +0100 Subject: [PATCH 0624/2102] drm/tilcdc: Fix suspend/resume drvdata drvdata contains a pointer to a struct tilcdc_drm_private and not a pointer to a struct drm_device anymore. Note that this breaks suspend/resume at the moment, it hangs on acquiring a mutex. Interpret drvdata correctly as struct tilcdc_drm_private as is done in the rest of the driver. Fixes: 3301302060da ("drm/tilcdc: Modernize driver initialization and cleanup paths") Cc: stable@vger.kernel.org Signed-off-by: Markus Schneider-Pargmann (TI) Reviewed-by: Kory Maincent Reviewed-by: Luca Ceresoli Link: https://patch.msgid.link/20261103-v7-4-topic-am335lpm-tilcdc-v1-1-b7f91f9c9a05@baylibre.com Signed-off-by: Luca Ceresoli --- drivers/gpu/drm/tilcdc/tilcdc_drv.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/tilcdc/tilcdc_drv.c b/drivers/gpu/drm/tilcdc/tilcdc_drv.c index 1d6c9a423a4104..e82cb2686c5f3b 100644 --- a/drivers/gpu/drm/tilcdc/tilcdc_drv.c +++ b/drivers/gpu/drm/tilcdc/tilcdc_drv.c @@ -235,7 +235,8 @@ static const struct drm_driver tilcdc_driver = { static int tilcdc_pm_suspend(struct device *dev) { - struct drm_device *ddev = dev_get_drvdata(dev); + struct tilcdc_drm_private *priv = dev_get_drvdata(dev); + struct drm_device *ddev = &priv->ddev; int ret = 0; ret = drm_mode_config_helper_suspend(ddev); @@ -248,7 +249,8 @@ static int tilcdc_pm_suspend(struct device *dev) static int tilcdc_pm_resume(struct device *dev) { - struct drm_device *ddev = dev_get_drvdata(dev); + struct tilcdc_drm_private *priv = dev_get_drvdata(dev); + struct drm_device *ddev = &priv->ddev; /* Select default pin state */ pinctrl_pm_select_default_state(dev); From e7732ec135b501e87ab060d992b3b5f2ec4396c9 Mon Sep 17 00:00:00 2001 From: Moshe Shemesh Date: Thu, 12 Nov 2026 15:27:19 +0200 Subject: [PATCH 0625/2102] RDMA/mlx5: Skip vport context query on FW without ib_virt support Since commit b02289b3d60f ("RDMA: Validate grh_required when handling AVs"), mlx5_port_immutable() unconditionally issues QUERY_HCA_VPORT_CONTEXT on InfiniBand ports to read grh_required. Devices that do not support the InfiniBand virtualization interface (ib_virt cleared) are not guaranteed to implement this command. For example, Connect-IB with FW 10.10.5020 rejects it and mlx5_ib fails to probe: mlx5_core 0000:01:00.0: mlx5_cmd_out_err:810:(pid 731): QUERY_HCA_VPORT_CONTEXT(0x762) op_mod(0x0) failed, status bad operation(0x2), syndrome (0x3590f5), err(-22) infiniband mlx5_0: Couldn't create per-port data mlx5_ib.rdma: probe of mlx5_core.rdma.0 failed with error -12 All other HCA vport context users in mlx5_ib are already gated on ib_virt, either directly, as in set_has_smi_cap(), mlx5_ib_get_plane_num() and mlx5_ib_modify_port(), or via mlx5_use_mad_ifc(), which selects MAD_IFC for port queries when ib_virt is not supported. Skipping the query loses nothing. grh_required indicates a GID-based vport, which only exists with InfiniBand virtualization. Without ib_virt the port is always LID-based and the field is zero, even on firmware that accepts the command. This also matches the behavior before b02289b3d60f, when grh_required was filled in only by mlx5_query_hca_port() and was never set on the MAD_IFC path. Fixes: b02289b3d60f ("RDMA: Validate grh_required when handling AVs") Cc: stable@vger.kernel.org Reported-by: Tony Battersby Closes: https://lore.kernel.org/all/064dfa67-8fd4-40f0-b925-6d1e0cd42e6a@cybernetics.com/ Tested-by: Tony Battersby Signed-off-by: Moshe Shemesh Signed-off-by: Edward Srouji Link: https://patch.msgid.link/20261112-moshe-ib-virt-guard-v1-1-6d2caf8bdb1b@nvidia.com Signed-off-by: Leon Romanovsky --- drivers/infiniband/hw/mlx5/main.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/infiniband/hw/mlx5/main.c b/drivers/infiniband/hw/mlx5/main.c index 65455aedd559b6..2ab38068db8388 100644 --- a/drivers/infiniband/hw/mlx5/main.c +++ b/drivers/infiniband/hw/mlx5/main.c @@ -3536,7 +3536,8 @@ static int mlx5_port_immutable(struct ib_device *ibdev, u32 port_num, if (err) return err; - if (ll == IB_LINK_LAYER_INFINIBAND) { + if (ll == IB_LINK_LAYER_INFINIBAND && + MLX5_CAP_GEN(dev->mdev, ib_virt)) { if (ibdev->type == RDMA_DEVICE_TYPE_SMI) port_num = smi_to_native_portnum(dev, port_num); From 06cfbf21b33772266a03a580182b74233f41f2b2 Mon Sep 17 00:00:00 2001 From: Miri Korenblit Date: Sat, 14 Nov 2026 19:31:58 +0200 Subject: [PATCH 0626/2102] wifi: iwlwifi: mvm: correctly check the API version The check for the firmware version for the reset handshake was wrong. mvm->fw->ucode_ver is the major number itself. No need to mask it with IWL_UCODE_MAJOR. We could look at the major number from IWL_UCODE_TLV_FW_VERSION but we don't remember that number and looking at fw->ucode_ver is good enough. Fixes: 0eaa1f245ac0 ("wifi: iwlwifi: mvm: don't support the reset handshake for old firmwares") Reported-and-tested-by: Chris Bainbridge Link: https://lore.kernel.org/linux-wireless/amzVtgQb2p-_nShU@debian.local/ Signed-off-by: Miri Korenblit Link: https://patch.msgid.link/20261114193144.ab54bc9717fc.I8cda260e2ef7aedd790915a17cb6832010f82aa4@changeid Signed-off-by: Miri Korenblit --- drivers/net/wireless/intel/iwlwifi/mvm/ops.c | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/drivers/net/wireless/intel/iwlwifi/mvm/ops.c b/drivers/net/wireless/intel/iwlwifi/mvm/ops.c index 1832514573612e..3d35c922706fbd 100644 --- a/drivers/net/wireless/intel/iwlwifi/mvm/ops.c +++ b/drivers/net/wireless/intel/iwlwifi/mvm/ops.c @@ -1412,15 +1412,13 @@ iwl_op_mode_mvm_start(struct iwl_trans *trans, const struct iwl_rf_cfg *cfg, sizeof(mvm->hw->wiphy->fw_version), "%.31s", fw->fw_version); - trans->conf.fw_reset_handshake = - fw_has_capa(&mvm->fw->ucode_capa, - IWL_UCODE_TLV_CAPA_FW_RESET_HANDSHAKE); - - /* Those firmware versions claim to support the fw_reset_handshake + /* Some firmware versions claim to support the fw_reset_handshake * but they are buggy. */ - if (IWL_UCODE_MAJOR(mvm->fw->ucode_ver) <= 77) - trans->conf.fw_reset_handshake = false; + trans->conf.fw_reset_handshake = + fw_has_capa(&mvm->fw->ucode_capa, + IWL_UCODE_TLV_CAPA_FW_RESET_HANDSHAKE) && + mvm->fw->ucode_ver > 77; trans->conf.queue_alloc_cmd_ver = iwl_fw_lookup_cmd_ver(mvm->fw, From ec95877e2ea1c655e914c34fa23fd51e32315fec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Toke=20H=C3=B8iland-J=C3=B8rgensen?= Date: Wed, 21 Oct 2026 14:02:36 +0200 Subject: [PATCH 0627/2102] wifi: ath9k: make sure we stop the wmi tasklet on init fail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ath9k_wmi_event_tasklet() reschedules itself until device initialisation is complete, but if the initialisation fails it is never interrupted. Syzbot triggered a use-after-free in tasklet_action_common because of this. Add a guard to the reschedule logic so it aborts if wmi->stopped is set, and add a call to ath9k_wmi_event_drain() in ath9k_stop_wmi(), so we are sure that the queue is drained and the tasklet is stopped on teardown. Fixes: 1af8dc9ca726 ("wifi: ath9k: Clean up device initialisation guards") Reported-by: syzbot+e91dc13b1b37759b3d9f@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=e91dc13b1b37759b3d9f Tested-by: syzbot+e91dc13b1b37759b3d9f@syzkaller.appspotmail.com Signed-off-by: Toke Høiland-Jørgensen Tested-by: Eduard Zateev Link: https://patch.msgid.link/20261021120237.481898-1-toke@toke.dk Signed-off-by: Johannes Berg --- drivers/net/wireless/ath/ath9k/wmi.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/drivers/net/wireless/ath/ath9k/wmi.c b/drivers/net/wireless/ath/ath9k/wmi.c index 44e91815a15943..520bb2347dfcd0 100644 --- a/drivers/net/wireless/ath/ath9k/wmi.c +++ b/drivers/net/wireless/ath/ath9k/wmi.c @@ -118,6 +118,8 @@ void ath9k_stop_wmi(struct ath9k_htc_priv *priv) mutex_lock(&wmi->op_mutex); wmi->stopped = true; mutex_unlock(&wmi->op_mutex); + + ath9k_wmi_event_drain(priv); } void ath9k_destroy_wmi(struct ath9k_htc_priv *priv) @@ -148,7 +150,8 @@ void ath9k_wmi_event_tasklet(struct tasklet_struct *t) /* Check if ath9k_init_device() completed. */ if (!smp_load_acquire(&priv->initialized)) { - tasklet_schedule(t); + if (!READ_ONCE(wmi->stopped)) + tasklet_schedule(t); return; } From 15a174764be1b201b1a2302ba7d407f168b0c0b7 Mon Sep 17 00:00:00 2001 From: "Felix K." Date: Thu, 22 Oct 2026 12:55:52 +0200 Subject: [PATCH 0628/2102] wifi: ath9k: fix beacon slot selection once TSF exceeds 2^39 us MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ath9k_beacon_choose_slot() derives the staggered beacon slot from the TSF as tsftu = TSF_TO_TU((tsf * ATH_BCBUF) >> 32, tsf * ATH_BCBUF); slot = (tsftu % (intval * ATH_BCBUF)) / intval; TSF_TO_TU() truncates its result to 32 bits, so tsftu is (tsf / 128) mod 2^32 and wraps every 2^39 us (~6.36 days). 2^32 is not a multiple of intval * ATH_BCBUF (800 for the default beacon interval of 100 TU, 2^32 mod 800 = 96), so every wrap shifts the computed position within the beacon interval by 96/100 of a slot. After the first wrap the SWBA handler therefore picks the vif of the previous slot: every BSS sends its beacon one slot (12.8 ms) late, while its timestamp is still corrected by the tsf_adjust of its own slot, so clients see the beacon 12.8 ms after their expected TBTT. After n wraps the beacons are n slots late (up to 89.6 ms), until the error wraps around after 8 wraps (~51 days). This affects every AP or mesh setup, also with a single vif, since 8 slots are always used. Internal resets (e.g. on stuck beacon) preserve the TSF, so the state only recovers when the interface is restarted and ath9k_start() resets the TSF. Compute the offset within the beacon interval from the 64-bit TSF instead. For TSF values below 2^39 us the result is identical to the old calculation. TSF_TO_TU() in ath9k.h has no other user and is removed. Observed on a TP-Link Archer C7 v2 (QCA9558, AHB) running OpenWrt 25.12.5 (backports 6.18.26) with three AP interfaces on 2.4 GHz. The TSF was set via debugfs (regidx/regval 0x804c/0x8050) followed by "echo 1 > ath9k/reset", and beacons were captured with a second device in monitor mode. Beacon timestamp modulo beacon interval, identical for all three BSS: TSF offset 3.40 days (0 wraps) 384 us 6.36 days (1 wrap) 13184 us 25.45 days (4 wraps) 51584 us 44.54 days (7 wraps) 89984 us 50.90 days (8 wraps) 384 us With the beacons 89.6 ms late, a power saving IoT client (EV charger controller) went from 40 ms to 1.4 s average ping RTT (max 7.2 s) with 1.9% packet loss within 9 minutes. Most other clients were not visibly affected in that time. Tested with this patch applied on the same device, using the same debugfs TSF method: the beacons are no longer delayed. The offset stays at 384 us for all three BSS with the TSF set to 0, 1, 4 and 7 wraps, and with the TSF set to 7 wraps the EV charger controller stayed at 40 ms average ping RTT (max 117 ms, no loss) over 5 minutes. ath9k_htc_choose_bslot() in htc_drv_beacon.c uses a similar 32-bit TU conversion (wrapping every 2^42 us, ~50.9 days); it is addressed in a separate patch. Fixes: dd347f2fb2dd ("ath9k: fix beacon timer handling issues") Cc: stable@vger.kernel.org Signed-off-by: Felix K. Acked-by: Toke Høiland-Jørgensen Link: https://patch.msgid.link/20261022105552.4174828-1-fk@mutemail.de Signed-off-by: Johannes Berg --- drivers/net/wireless/ath/ath9k/ath9k.h | 3 --- drivers/net/wireless/ath/ath9k/beacon.c | 10 +++++----- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/drivers/net/wireless/ath/ath9k/ath9k.h b/drivers/net/wireless/ath/ath9k/ath9k.h index e8635bf81f9d09..5c15b2e3cdcfbc 100644 --- a/drivers/net/wireless/ath/ath9k/ath9k.h +++ b/drivers/net/wireless/ath/ath9k/ath9k.h @@ -691,9 +691,6 @@ void ath9k_set_txpower(struct ath_softc *sc, struct ieee80211_vif *vif); #define ATH_DEFAULT_BINTVAL 100 /* TU */ #define ATH_DEFAULT_BMISS_LIMIT 10 -#define TSF_TO_TU(_h,_l) \ - ((((u32)(_h)) << 22) | (((u32)(_l)) >> 10)) - struct ath_beacon { enum { OK, /* no change needed */ diff --git a/drivers/net/wireless/ath/ath9k/beacon.c b/drivers/net/wireless/ath/ath9k/beacon.c index 4a27e3753c0367..8a9bd23d3d931e 100644 --- a/drivers/net/wireless/ath/ath9k/beacon.c +++ b/drivers/net/wireless/ath/ath9k/beacon.c @@ -308,7 +308,7 @@ static int ath9k_beacon_choose_slot(struct ath_softc *sc) struct ath_common *common = ath9k_hw_common(sc->sc_ah); struct ath_beacon_config *cur_conf = &sc->cur_chan->beacon; u16 intval; - u32 tsftu; + u32 offset; u64 tsf; int slot; @@ -322,11 +322,11 @@ static int ath9k_beacon_choose_slot(struct ath_softc *sc) intval = cur_conf->beacon_interval ? : ATH_DEFAULT_BINTVAL; tsf = ath9k_hw_gettsf64(sc->sc_ah); tsf += TU_TO_USEC(sc->sc_ah->config.sw_beacon_response_time); - tsftu = TSF_TO_TU((tsf * ATH_BCBUF) >>32, tsf * ATH_BCBUF); - slot = (tsftu % (intval * ATH_BCBUF)) / intval; + div_u64_rem(tsf, TU_TO_USEC(intval), &offset); + slot = offset * ATH_BCBUF / TU_TO_USEC(intval); - ath_dbg(common, BEACON, "slot: %d tsf: %llu tsftu: %u\n", - slot, tsf, tsftu / ATH_BCBUF); + ath_dbg(common, BEACON, "slot: %d tsf: %llu offset: %u\n", + slot, tsf, offset); return slot; } From 05497f91c322d00c9cf8f27255090a544223c5fd Mon Sep 17 00:00:00 2001 From: "Felix K." Date: Thu, 22 Oct 2026 12:56:56 +0200 Subject: [PATCH 0629/2102] wifi: ath9k_htc: fix beacon slot selection once TSF exceeds 2^42 us MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ath9k_htc_choose_bslot() derives the beacon slot from the TSF reported in the SWBA event as tsftu = TSF_TO_TU(tsf >> 32, tsf); slot = ((tsftu % intval) * ATH9K_HTC_MAX_BCN_VIF) / intval; TSF_TO_TU() truncates its result to 32 bits, so tsftu is (tsf / 1024) mod 2^32 and wraps every 2^42 us (~50.9 days). 2^32 is not a multiple of the beacon interval (2^32 mod 100 = 96 for the default of 100 TU), so every wrap shifts the computed position within the beacon interval by 4 TU. Depending on where in the interval the SWBA event arrives, the wrong slot is chosen after one or more wraps. The state only recovers when the TSF is reset. Compute the offset within the beacon interval from the 64-bit TSF instead. For TSF values below 2^42 us and an even beacon interval the result is identical to the old calculation. TSF_TO_TU() in htc.h has no other user and is removed. This is the same issue as in ath9k_beacon_choose_slot(), which is fixed separately. Compile tested only, I do not have ath9k_htc hardware. Fixes: 832f6a18fc2a ("ath9k_htc: Add beacon slots") Cc: stable@vger.kernel.org Signed-off-by: Felix K. Tested-by: Mehmet Fide Acked-by: Toke Høiland-Jørgensen Link: https://patch.msgid.link/20261022105656.4175421-1-fk@mutemail.de Signed-off-by: Johannes Berg --- drivers/net/wireless/ath/ath9k/htc.h | 2 -- drivers/net/wireless/ath/ath9k/htc_drv_beacon.c | 10 +++++----- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/drivers/net/wireless/ath/ath9k/htc.h b/drivers/net/wireless/ath/ath9k/htc.h index 4d2b75d0212efa..59e0b3cf7f0f52 100644 --- a/drivers/net/wireless/ath/ath9k/htc.h +++ b/drivers/net/wireless/ath/ath9k/htc.h @@ -39,8 +39,6 @@ #define ATH_RESTART_CALINTERVAL 1200000 /* 20 minutes */ #define ATH_DEFAULT_BMISS_LIMIT 10 -#define TSF_TO_TU(_h, _l) \ - ((((u32)(_h)) << 22) | (((u32)(_l)) >> 10)) extern struct ieee80211_ops ath9k_htc_ops; extern int htc_modparam_nohwcrypt; diff --git a/drivers/net/wireless/ath/ath9k/htc_drv_beacon.c b/drivers/net/wireless/ath/ath9k/htc_drv_beacon.c index 81fa7cbad89213..b478af1502f2e6 100644 --- a/drivers/net/wireless/ath/ath9k/htc_drv_beacon.c +++ b/drivers/net/wireless/ath/ath9k/htc_drv_beacon.c @@ -266,20 +266,20 @@ static int ath9k_htc_choose_bslot(struct ath9k_htc_priv *priv, { struct ath_common *common = ath9k_hw_common(priv->ah); u64 tsf; - u32 tsftu; + u32 offset; u16 intval; int slot; intval = priv->cur_beacon_conf.beacon_interval; tsf = be64_to_cpu(swba->tsf); - tsftu = TSF_TO_TU(tsf >> 32, tsf); - slot = ((tsftu % intval) * ATH9K_HTC_MAX_BCN_VIF) / intval; + div_u64_rem(tsf, TU_TO_USEC(intval), &offset); + slot = (offset * ATH9K_HTC_MAX_BCN_VIF) / TU_TO_USEC(intval); slot = ATH9K_HTC_MAX_BCN_VIF - slot - 1; ath_dbg(common, BEACON, - "Choose slot: %d, tsf: %llu, tsftu: %u, intval: %u\n", - slot, tsf, tsftu, intval); + "Choose slot: %d, tsf: %llu, offset: %u, intval: %u\n", + slot, tsf, offset, intval); return slot; } From 763b13f622e2758726e8e3ecaef819db8fa0430a Mon Sep 17 00:00:00 2001 From: Johannes Berg Date: Tue, 3 Nov 2026 16:43:31 +0100 Subject: [PATCH 0630/2102] wifi: ath9k: uninline ar9003_paprd_create_curve() helpers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ar9003_paprd_create_curve() calls the two helpers, but if they get inlined the stack can exceed 1k with clang, causing warnings/errors. Mark the two helpers to not be inlined due to stack ("noinline_for_stack") to fix that. Acked-by: Toke Høiland-Jørgensen Link: https://patch.msgid.link/20261103164331.d661e4447139.I759358de0d74f858b9410a5db6918cd7e12dd877@changeid Signed-off-by: Johannes Berg --- drivers/net/wireless/ath/ath9k/ar9003_paprd.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/drivers/net/wireless/ath/ath9k/ar9003_paprd.c b/drivers/net/wireless/ath/ath9k/ar9003_paprd.c index 6170e37d020577..17e28ad216cfa6 100644 --- a/drivers/net/wireless/ath/ath9k/ar9003_paprd.c +++ b/drivers/net/wireless/ath/ath9k/ar9003_paprd.c @@ -416,7 +416,8 @@ static inline int find_proper_scale(int expn, int N) #define NUM_BIN 23 -static bool create_pa_curve(u32 *data_L, u32 *data_U, u32 *pa_table, u16 *gain) +static noinline_for_stack bool +create_pa_curve(u32 *data_L, u32 *data_U, u32 *pa_table, u16 *gain) { unsigned int thresh_accum_cnt; int x_est[NUM_BIN + 1], Y[NUM_BIN + 1], theta[NUM_BIN + 1]; @@ -817,9 +818,10 @@ void ar9003_paprd_setup_gain_table(struct ath_hw *ah, int chain) } EXPORT_SYMBOL(ar9003_paprd_setup_gain_table); -static bool ar9003_paprd_retrain_pa_in(struct ath_hw *ah, - struct ath9k_hw_cal_data *caldata, - int chain) +static noinline_for_stack bool +ar9003_paprd_retrain_pa_in(struct ath_hw *ah, + struct ath9k_hw_cal_data *caldata, + int chain) { u32 *pa_in = caldata->pa_table[chain]; int capdiv_offset, quick_drop_offset; From d33cad95d2e4996105e68f6ccb65bdce7ad1d636 Mon Sep 17 00:00:00 2001 From: Pengpeng Hou Date: Sun, 20 Sep 2026 21:09:18 +0800 Subject: [PATCH 0631/2102] RISC-V: KVM: Validate AIA MMIO address ranges The AIA address setters check alignment but not the complete fixed-size APLIC and IMSIC MMIO regions. A range can therefore wrap when its end is formed or extend beyond the selected guest physical address space before it is registered on the KVM MMIO bus. Check the complete range in both setters. Return -EINVAL for alignment or arithmetic overflow and -E2BIG for a range beyond the selected GPA limit, following the arm64 VGIC address-validation convention. Recheck only the APLIC range during initialization: userspace can set its address and then change KVM_CAP_VM_GPA_BITS while the VM still has no vCPUs or memory slots. An IMSIC address, in contrast, can only be set for an existing vCPU, which already prevents subsequent GPA-width changes. No additional pass over the vCPUs is needed. Keep the existing required-address checks and IMSIC cleanup path. The issue was found by our static-analysis tool. Fixes: 89d01306e34d ("RISC-V: KVM: Implement device interface for AIA irqchip") Assisted-by: gpt 5 Signed-off-by: Pengpeng Hou Reviewed-by: Anup Patel Link: https://lore.kernel.org/r/3046cfd67c5f962014cd38e49a0e8bf28b6fb53f.1789872556.git.hppiscas@163.com Signed-off-by: Anup Patel --- arch/riscv/kvm/aia_device.c | 49 ++++++++++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/arch/riscv/kvm/aia_device.c b/arch/riscv/kvm/aia_device.c index 97833a04268a9c..e79b92882ea800 100644 --- a/arch/riscv/kvm/aia_device.c +++ b/arch/riscv/kvm/aia_device.c @@ -10,7 +10,9 @@ #include #include #include +#include #include +#include #include static int aia_create(struct kvm_device *dev, u32 type) @@ -142,17 +144,37 @@ static int aia_config(struct kvm *kvm, unsigned long type, return 0; } +static int aia_check_addr_range(struct kvm *kvm, u64 addr, u64 alignment, + u64 size) +{ + u64 end; + + if (!IS_ALIGNED(addr, alignment)) + return -EINVAL; + + if (check_add_overflow(addr, size, &end)) + return -EINVAL; + + if (end > kvm_riscv_gstage_gpa_size(kvm->arch.pgd_levels)) + return -E2BIG; + + return 0; +} + static int aia_aplic_addr(struct kvm *kvm, u64 *addr, bool write) { struct kvm_aia *aia = &kvm->arch.aia; + int ret; if (write) { /* Writes can only be done before irqchip is initialized */ if (kvm_riscv_aia_initialized(kvm)) return -EBUSY; - if (*addr & (KVM_DEV_RISCV_APLIC_ALIGN - 1)) - return -EINVAL; + ret = aia_check_addr_range(kvm, *addr, KVM_DEV_RISCV_APLIC_ALIGN, + KVM_DEV_RISCV_APLIC_SIZE); + if (ret) + return ret; aia->aplic_addr = *addr; } else @@ -166,6 +188,7 @@ static int aia_imsic_addr(struct kvm *kvm, u64 *addr, { struct kvm_vcpu *vcpu; struct kvm_vcpu_aia *vcpu_aia; + int ret; vcpu = kvm_get_vcpu(kvm, vcpu_idx); if (!vcpu) @@ -177,8 +200,10 @@ static int aia_imsic_addr(struct kvm *kvm, u64 *addr, if (kvm_riscv_aia_initialized(kvm)) return -EBUSY; - if (*addr & (KVM_DEV_RISCV_IMSIC_ALIGN - 1)) - return -EINVAL; + ret = aia_check_addr_range(kvm, *addr, KVM_DEV_RISCV_IMSIC_ALIGN, + KVM_DEV_RISCV_IMSIC_SIZE); + if (ret) + return ret; } mutex_lock(&vcpu->mutex); @@ -248,6 +273,15 @@ static int aia_init(struct kvm *kvm) if (aia->nr_sources && aia->aplic_addr == KVM_RISCV_AIA_UNDEF_ADDR) return -EINVAL; + /* The GPA width may change after setting APLIC's address on an empty VM. */ + if (aia->nr_sources) { + ret = aia_check_addr_range(kvm, aia->aplic_addr, + KVM_DEV_RISCV_APLIC_ALIGN, + KVM_DEV_RISCV_APLIC_SIZE); + if (ret) + return ret; + } + /* Group index bits must not overlap guest and HART index bits. */ if (aia->nr_group_bits && aia->nr_group_shift < (IMSIC_MMIO_PAGE_SHIFT + @@ -269,6 +303,13 @@ static int aia_init(struct kvm *kvm) goto fail_cleanup_imsics; } + /* The GPA width may change after setting IMSIC addresses on an empty VM. */ + ret = aia_check_addr_range(kvm, vaia->imsic_addr, + KVM_DEV_RISCV_IMSIC_ALIGN, + KVM_DEV_RISCV_IMSIC_SIZE); + if (ret) + goto fail_cleanup_imsics; + /* All IMSICs should have matching base PPN */ if (base_ppn == KVM_RISCV_AIA_UNDEF_ADDR) base_ppn = aia_imsic_ppn(aia, vaia->imsic_addr); From ea4302d313014da5ea988f03ee7b88e29e161dcf Mon Sep 17 00:00:00 2001 From: Pengpeng Hou Date: Sun, 20 Sep 2026 21:09:55 +0800 Subject: [PATCH 0632/2102] RISC-V: KVM: Disallow GPA-width changes after AIA init KVM_ENABLE_CAP(KVM_CAP_VM_GPA_BITS) allows userspace to reduce the stage-2 GPA width while a VM has no vCPUs or memory slots. AIA initialization can complete with an APLIC and no vCPUs or memory slots. The APLIC MMIO device has then been registered, but the existing checks still allow userspace to shrink the GPA width below its address. Reject GPA-width changes after AIA initialization. Both paths hold kvm->lock, serializing the width change with AIA initialization. The issue was found by our static-analysis tool. Fixes: 7263b4fdb0b2 ("RISC-V: KVM: Reuse KVM_CAP_VM_GPA_BITS to select HGATP.MODE") Reviewed-by: Anup Patel Assisted-by: gpt 5 Signed-off-by: Pengpeng Hou Reviewed-by: Nutty Liu Link: https://lore.kernel.org/r/fbe7337f6989994ad4dbc4dc03a67e8ebfa61f8d.1789872556.git.hppiscas@163.com Signed-off-by: Anup Patel --- arch/riscv/kvm/vm.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/arch/riscv/kvm/vm.c b/arch/riscv/kvm/vm.c index 58500a19b33bdb..17598d487e8377 100644 --- a/arch/riscv/kvm/vm.c +++ b/arch/riscv/kvm/vm.c @@ -251,7 +251,8 @@ int kvm_vm_ioctl_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) mutex_lock(&kvm->lock); mutex_lock(&kvm->slots_lock); - if (kvm->created_vcpus || !kvm_are_all_memslots_empty(kvm)) + if (kvm->created_vcpus || !kvm_are_all_memslots_empty(kvm) || + kvm_riscv_aia_initialized(kvm)) r = -EBUSY; else kvm->arch.pgd_levels = new_levels; From ca6d379ee2f123512c30aa5b0592db648186d9af Mon Sep 17 00:00:00 2001 From: Li Jinyue Date: Thu, 22 Oct 2026 02:52:48 +0000 Subject: [PATCH 0633/2102] RISC-V: KVM: Fix double free of the split page cache kvm_riscv_mmu_free_pgd() frees pgd_split_page_cache after dropping mmu_lock. It is reached from kvm_arch_flush_shadow_all(), i.e. from the MMU notifier ->release() callback, which can run concurrently for the same VM from exit_mmap() and from mmu_notifier_unregister() in kvm_destroy_vm(). The stage-2 teardown is serialized by mmu_lock and the second caller finds kvm->arch.pgd already cleared, but both callers then go on to free the cache, and kvm_mmu_free_memory_cache() does not tolerate concurrent callers: BUG: KASAN: double-free in kvfree+0x28/0x32 ... kfree+0xc4/0x428 kvfree+0x28/0x32 kvm_mmu_free_memory_cache+0x178/0x246 kvm_riscv_mmu_free_pgd+0x20e/0x2b4 kvm_arch_flush_shadow_all+0x1a/0x24 kvm_mmu_notifier_release+0x36/0x7c __mmu_notifier_release+0x182/0x66a exit_mmap+0x7f8/0x8c4 mmput+0x7e/0x2fc do_exit+0x57a/0x22b4 ... Freed by task 15956 on cpu 3 at 8926.103524s: ... kvm_mmu_free_memory_cache+0x178/0x246 kvm_riscv_mmu_free_pgd+0x20e/0x2b4 kvm_arch_flush_shadow_all+0x1a/0x24 kvm_mmu_notifier_release+0x36/0x7c mmu_notifier_unregister+0xf0/0x328 kvm_put_kvm+0x32a/0x7b8 kvm_vm_release+0x3a/0x50 __fput+0x330/0x974 The cache only feeds huge page splitting from VM ioctls, so it does not need to be released together with the page table. Free it from kvm_arch_destroy_vm() instead, which runs once after the MMU notifier has been unregistered, as arm64 and x86 already do. The error path in kvm_arch_init_vm() is not affected because the cache cannot have been filled at that point. Found by syzkaller. Fixes: 6c7f75ef096a ("RISC-V: KVM: Add the split page cache for ioctl context") Cc: stable@vger.kernel.org Signed-off-by: Li Jinyue Reviewed-by: Nutty Liu Reviewed-by: Anup Patel Link: https://lore.kernel.org/r/20261022025248.477832-1-jinyue.li@linux.alibaba.com Signed-off-by: Anup Patel --- arch/riscv/kvm/mmu.c | 2 -- arch/riscv/kvm/vm.c | 2 ++ 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/arch/riscv/kvm/mmu.c b/arch/riscv/kvm/mmu.c index 738d9ee1eac9d6..6b77891d458248 100644 --- a/arch/riscv/kvm/mmu.c +++ b/arch/riscv/kvm/mmu.c @@ -845,8 +845,6 @@ void kvm_riscv_mmu_free_pgd(struct kvm *kvm) if (pgd) free_pages((unsigned long)pgd, get_order(kvm_riscv_gstage_pgd_size)); - - kvm_mmu_free_memory_cache(&kvm->arch.pgd_split_page_cache); } void kvm_riscv_mmu_update_hgatp(struct kvm_vcpu *vcpu) diff --git a/arch/riscv/kvm/vm.c b/arch/riscv/kvm/vm.c index 17598d487e8377..cb8f604d3b54e9 100644 --- a/arch/riscv/kvm/vm.c +++ b/arch/riscv/kvm/vm.c @@ -54,6 +54,8 @@ void kvm_arch_destroy_vm(struct kvm *kvm) kvm_destroy_vcpus(kvm); kvm_riscv_aia_destroy_vm(kvm); + + kvm_mmu_free_memory_cache(&kvm->arch.pgd_split_page_cache); } int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irql, From 403daa3414a6ad1378082f97b3a8bec08a50c641 Mon Sep 17 00:00:00 2001 From: Davidlohr Bueso Date: Fri, 23 Oct 2026 10:37:31 -0700 Subject: [PATCH 0634/2102] RISC-V: KVM: Do not touch the envcfg CSRs on the SiFive P550 The SiFive P550 (ESWIN EIC7700X) implements the hypervisor extension on a privileged spec 1.11 base, so it has neither henvcfg nor senvcfg. KVM swaps senvcfg on every guest entry and writes henvcfg on vCPU load regardless, and the host dies on the first guest entry: Oops - illegal instruction [#1] Modules linked in: kvm CPU: 2 UID: 0 PID: 127 Comm: qemu-system-ris Not tainted 7.2.0+ #4 PREEMPTLAZY Hardware name: Unknown Unknown Product/Unknown Product, BIOS 2024.01 01/01/2024 epc : kvm_riscv_vcpu_enter_exit+0x26/0xcf8 [kvm] ra : kvm_arch_vcpu_ioctl_run+0x4ce/0x5a6 [kvm] status: 0000000200000100 badaddr: 0000000010a797f3 cause: 0000000000000002 [] kvm_riscv_vcpu_enter_exit+0x26/0xcf8 [kvm] [] kvm_arch_vcpu_ioctl_run+0x4ce/0x5a6 [kvm] [] kvm_vcpu_ioctl+0x180/0x5e4 [kvm] [] __riscv_sys_ioctl+0x84/0x9a [] do_trap_ecall_u+0x1d8/0x38a [] handle_exception+0x168/0x174 Code: 84aa 892e b703 8887 1773 1067 3023 16e5 b783 8907 (97f3) 10a7 Introduce a hardware quirk for this core, similar to the Andes AX66 TLB one, and skip both CSRs when it is set. The FWFT features that KVM implements with henvcfg bits then disabled. Fixes: db3c01c7a308 ("RISCV: KVM: Add senvcfg context save/restore") Suggested-by: Anup Patel Signed-off-by: Davidlohr Bueso Reviewed-by: Anup Patel Link: https://lore.kernel.org/r/20261023173731.3559650-1-dave@stgolabs.net Signed-off-by: Anup Patel --- arch/riscv/include/asm/kvm_host.h | 1 + arch/riscv/kvm/main.c | 9 +++++++++ arch/riscv/kvm/vcpu.c | 6 ++++-- arch/riscv/kvm/vcpu_config.c | 16 ++++++++++------ arch/riscv/kvm/vcpu_sbi_fwft.c | 20 +++++++++++++++----- 5 files changed, 39 insertions(+), 13 deletions(-) diff --git a/arch/riscv/include/asm/kvm_host.h b/arch/riscv/include/asm/kvm_host.h index e28f058a94d707..d705b538875d5c 100644 --- a/arch/riscv/include/asm/kvm_host.h +++ b/arch/riscv/include/asm/kvm_host.h @@ -333,5 +333,6 @@ void kvm_riscv_vcpu_record_steal_time(struct kvm_vcpu *vcpu); /* Flags representing implementation specific details */ DECLARE_STATIC_KEY_FALSE(kvm_riscv_vsstage_tlb_no_gpa); +DECLARE_STATIC_KEY_FALSE(kvm_riscv_no_xenvcfg); #endif /* __RISCV_KVM_HOST_H__ */ diff --git a/arch/riscv/kvm/main.c b/arch/riscv/kvm/main.c index 89568ccce01de5..0725c8e03c6ad4 100644 --- a/arch/riscv/kvm/main.c +++ b/arch/riscv/kvm/main.c @@ -15,11 +15,13 @@ #include #include #include +#include #include static DEFINE_PER_CPU(bool, kvm_riscv_virtualization_enabled); DEFINE_STATIC_KEY_FALSE(kvm_riscv_vsstage_tlb_no_gpa); +DEFINE_STATIC_KEY_FALSE(kvm_riscv_no_xenvcfg); static void kvm_riscv_setup_vendor_features(void) { @@ -29,6 +31,13 @@ static void kvm_riscv_setup_vendor_features(void) static_branch_enable(&kvm_riscv_vsstage_tlb_no_gpa); kvm_info("VS-stage TLB does not cache guest physical address and VMID\n"); } + + /* SiFive P550 (ESWIN EIC7700X): H on a 1.11 base, no henvcfg/senvcfg */ + if (riscv_cached_mvendorid(0) == SIFIVE_VENDOR_ID && + riscv_cached_marchid(0) == 0x8000000000000008ULL) { + static_branch_enable(&kvm_riscv_no_xenvcfg); + kvm_info("henvcfg and senvcfg CSRs not implemented\n"); + } } long kvm_arch_dev_ioctl(struct file *filp, diff --git a/arch/riscv/kvm/vcpu.c b/arch/riscv/kvm/vcpu.c index dd786f758eb76a..8b4f70c77b8f9c 100644 --- a/arch/riscv/kvm/vcpu.c +++ b/arch/riscv/kvm/vcpu.c @@ -775,7 +775,8 @@ static __always_inline void kvm_riscv_vcpu_swap_in_guest_state(struct kvm_vcpu * struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr; vcpu->arch.host_scounteren = csr_swap(CSR_SCOUNTEREN, csr->scounteren); - vcpu->arch.host_senvcfg = csr_swap(CSR_SENVCFG, csr->senvcfg); + if (!static_branch_unlikely(&kvm_riscv_no_xenvcfg)) + vcpu->arch.host_senvcfg = csr_swap(CSR_SENVCFG, csr->senvcfg); if (riscv_has_extension_unlikely(RISCV_ISA_EXT_SMSTATEEN)) vcpu->arch.host_sstateen0 = csr_swap(CSR_SSTATEEN0, smcsr->sstateen0); if (riscv_has_extension_unlikely(RISCV_ISA_EXT_ZICFISS)) @@ -789,7 +790,8 @@ static __always_inline void kvm_riscv_vcpu_swap_in_host_state(struct kvm_vcpu *v struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr; csr->scounteren = csr_swap(CSR_SCOUNTEREN, vcpu->arch.host_scounteren); - csr->senvcfg = csr_swap(CSR_SENVCFG, vcpu->arch.host_senvcfg); + if (!static_branch_unlikely(&kvm_riscv_no_xenvcfg)) + csr->senvcfg = csr_swap(CSR_SENVCFG, vcpu->arch.host_senvcfg); if (riscv_has_extension_unlikely(RISCV_ISA_EXT_SMSTATEEN)) smcsr->sstateen0 = csr_swap(CSR_SSTATEEN0, vcpu->arch.host_sstateen0); if (riscv_has_extension_unlikely(RISCV_ISA_EXT_ZICFISS)) diff --git a/arch/riscv/kvm/vcpu_config.c b/arch/riscv/kvm/vcpu_config.c index b68aa830aaf51c..9b8e4f1f12f43c 100644 --- a/arch/riscv/kvm/vcpu_config.c +++ b/arch/riscv/kvm/vcpu_config.c @@ -82,9 +82,11 @@ void kvm_riscv_vcpu_config_load(struct kvm_vcpu *vcpu) nsh = nacl_shmem(); nacl_csr_write(nsh, CSR_HEDELEG, cfg->hedeleg); nacl_csr_write(nsh, CSR_HIDELEG, cfg->hideleg); - nacl_csr_write(nsh, CSR_HENVCFG, cfg->henvcfg); - if (IS_ENABLED(CONFIG_32BIT)) - nacl_csr_write(nsh, CSR_HENVCFGH, cfg->henvcfg >> 32); + if (!static_branch_unlikely(&kvm_riscv_no_xenvcfg)) { + nacl_csr_write(nsh, CSR_HENVCFG, cfg->henvcfg); + if (IS_ENABLED(CONFIG_32BIT)) + nacl_csr_write(nsh, CSR_HENVCFGH, cfg->henvcfg >> 32); + } if (riscv_has_extension_unlikely(RISCV_ISA_EXT_SMSTATEEN)) { nacl_csr_write(nsh, CSR_HSTATEEN0, cfg->hstateen0); if (IS_ENABLED(CONFIG_32BIT)) @@ -93,9 +95,11 @@ void kvm_riscv_vcpu_config_load(struct kvm_vcpu *vcpu) } else { csr_write(CSR_HEDELEG, cfg->hedeleg); csr_write(CSR_HIDELEG, cfg->hideleg); - csr_write(CSR_HENVCFG, cfg->henvcfg); - if (IS_ENABLED(CONFIG_32BIT)) - csr_write(CSR_HENVCFGH, cfg->henvcfg >> 32); + if (!static_branch_unlikely(&kvm_riscv_no_xenvcfg)) { + csr_write(CSR_HENVCFG, cfg->henvcfg); + if (IS_ENABLED(CONFIG_32BIT)) + csr_write(CSR_HENVCFGH, cfg->henvcfg >> 32); + } if (riscv_has_extension_unlikely(RISCV_ISA_EXT_SMSTATEEN)) { csr_write(CSR_HSTATEEN0, cfg->hstateen0); if (IS_ENABLED(CONFIG_32BIT)) diff --git a/arch/riscv/kvm/vcpu_sbi_fwft.c b/arch/riscv/kvm/vcpu_sbi_fwft.c index 7d0aaeff537b27..79a83f1145f6ed 100644 --- a/arch/riscv/kvm/vcpu_sbi_fwft.c +++ b/arch/riscv/kvm/vcpu_sbi_fwft.c @@ -132,6 +132,12 @@ static long kvm_sbi_fwft_envcfg_flag_get(struct kvm_vcpu *vcpu, return SBI_SUCCESS; } +/* Features implemented by setting bits in henvcfg need the CSR to exist */ +static inline bool kvm_sbi_fwft_have_henvcfg(void) +{ + return !static_branch_unlikely(&kvm_riscv_no_xenvcfg); +} + static bool kvm_sbi_fwft_misaligned_delegation_supported(struct kvm_vcpu *vcpu) { return misaligned_traps_can_delegate(); @@ -208,7 +214,8 @@ static long kvm_sbi_fwft_set_cfi(struct kvm_vcpu *vcpu, static bool kvm_sbi_fwft_landing_pad_supported(struct kvm_vcpu *vcpu) { - return riscv_isa_extension_available(vcpu->arch.isa, ZICFILP); + return kvm_sbi_fwft_have_henvcfg() && + riscv_isa_extension_available(vcpu->arch.isa, ZICFILP); } static void kvm_sbi_fwft_reset_landing_pad(struct kvm_vcpu *vcpu) @@ -236,7 +243,8 @@ static long kvm_sbi_fwft_get_landing_pad(struct kvm_vcpu *vcpu, static bool kvm_sbi_fwft_shadow_stack_supported(struct kvm_vcpu *vcpu) { - return riscv_isa_extension_available(vcpu->arch.isa, ZICFISS); + return kvm_sbi_fwft_have_henvcfg() && + riscv_isa_extension_available(vcpu->arch.isa, ZICFISS); } static void kvm_sbi_fwft_reset_shadow_stack(struct kvm_vcpu *vcpu) @@ -264,8 +272,9 @@ static long kvm_sbi_fwft_get_shadow_stack(struct kvm_vcpu *vcpu, static bool kvm_sbi_fwft_pte_ad_hw_updating_supported(struct kvm_vcpu *vcpu) { - return riscv_isa_extension_available(vcpu->arch.isa, SVADU) && - riscv_isa_extension_available(vcpu->arch.isa, SVADE); + return kvm_sbi_fwft_have_henvcfg() && + riscv_isa_extension_available(vcpu->arch.isa, SVADU) && + riscv_isa_extension_available(vcpu->arch.isa, SVADE); } static void kvm_sbi_fwft_reset_pte_ad_hw_updating(struct kvm_vcpu *vcpu) @@ -305,7 +314,8 @@ static bool try_to_set_pmm(unsigned long value) static bool kvm_sbi_fwft_pointer_masking_pmlen_supported(struct kvm_vcpu *vcpu) { - return riscv_isa_extension_available(vcpu->arch.isa, SMNPM); + return kvm_sbi_fwft_have_henvcfg() && + riscv_isa_extension_available(vcpu->arch.isa, SMNPM); } static bool kvm_sbi_fwft_pointer_masking_pmlen_init(struct kvm_vcpu *vcpu) From f4eda00f503ed260b0269dbfe59e25ac04243f3c Mon Sep 17 00:00:00 2001 From: SeungJu Cheon Date: Fri, 16 Oct 2026 19:14:58 +0900 Subject: [PATCH 0635/2102] KVM: riscv: Set Accessed bit in dirty-log write fault fast path kvm_riscv_mmu_dirty_log_write_fault_fast() considers a leaf with W and D set already handled, even if aging has cleared its A bit. On hardware that faults when A is clear, the fast path returns true without setting A and skips the slow path that would set it. The guest retries the same store, but A is still clear, so it faults again. This repeats indefinitely, preventing the guest from making progress. Host reclaim or page_idle can trigger this while dirty logging is enabled, potentially hanging vCPUs during live migration. Require _PAGE_ACCESSED in addition to W and D before treating the fault as handled, and set A along with W and D. The existing cmpxchg loop retries if aging changes the PTE before the update. Fixes: 7705be59eb2d ("KVM: riscv: Fast-path dirty logging write faults") Cc: stable@vger.kernel.org # 7.2+ Signed-off-by: SeungJu Cheon Reviewed-by: Jinyu Tang Reviewed-by: Anup Patel Link: https://lore.kernel.org/r/20261016101458.221648-1-suunj1331@gmail.com Signed-off-by: Anup Patel --- arch/riscv/kvm/mmu.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/arch/riscv/kvm/mmu.c b/arch/riscv/kvm/mmu.c index 6b77891d458248..5b7cb559c22a34 100644 --- a/arch/riscv/kvm/mmu.c +++ b/arch/riscv/kvm/mmu.c @@ -591,14 +591,15 @@ static bool kvm_riscv_mmu_dirty_log_write_fault_fast(struct kvm *kvm, dirty_marked = true; } - if ((pte_val(old_pte) & (_PAGE_WRITE | _PAGE_DIRTY)) == - (_PAGE_WRITE | _PAGE_DIRTY)) { + if ((pte_val(old_pte) & + (_PAGE_WRITE | _PAGE_DIRTY | _PAGE_ACCESSED)) == + (_PAGE_WRITE | _PAGE_DIRTY | _PAGE_ACCESSED)) { new_pte = old_pte; ret = true; break; } - new_pte = pte_mkdirty(pte_mkwrite_novma(old_pte)); + new_pte = pte_mkyoung(pte_mkdirty(pte_mkwrite_novma(old_pte))); if (kvm_riscv_gstage_try_update_pte(&gstage, ptep_level, gpa, ptep, old_pte, new_pte)) { From 1fd50d34d80053a2e319531d171db0ec1e59360b Mon Sep 17 00:00:00 2001 From: Qingwei Hu Date: Tue, 27 Oct 2026 14:26:02 +0800 Subject: [PATCH 0636/2102] RISC-V: KVM: Validate PMU counter info using available counters COUNTER_GET_INFO validates the counter index using the pmc[] storage capacity rather than the number of counters advertised by NUM_COUNTERS. When fewer counters are available, a guest can query an index outside the advertised range and receive success. Validate the index using kvm_pmu_num_counters(), matching the counter initialization and read paths. Fixes: 8f0153ecd3bf ("RISC-V: KVM: Add skeleton support for perf") Signed-off-by: Qingwei Hu Reviewed-by: Anup Patel Link: https://lore.kernel.org/r/20261027062602.323691-1-qingwei.hu@bytedance.com Signed-off-by: Anup Patel --- arch/riscv/kvm/vcpu_pmu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/riscv/kvm/vcpu_pmu.c b/arch/riscv/kvm/vcpu_pmu.c index e095d1ff439f19..ea788619091ad1 100644 --- a/arch/riscv/kvm/vcpu_pmu.c +++ b/arch/riscv/kvm/vcpu_pmu.c @@ -560,7 +560,7 @@ int kvm_riscv_vcpu_pmu_ctr_info(struct kvm_vcpu *vcpu, unsigned long cidx, { struct kvm_pmu *kvpmu = vcpu_to_pmu(vcpu); - if (cidx >= RISCV_KVM_MAX_COUNTERS || cidx == 1) { + if (cidx >= kvm_pmu_num_counters(kvpmu) || cidx == 1) { retdata->err_val = SBI_ERR_INVALID_PARAM; return 0; } From e9bf49bbc4227048685c78f97e1446845760df4f Mon Sep 17 00:00:00 2001 From: Yangyu Chen Date: Sat, 31 Oct 2026 02:58:36 +0800 Subject: [PATCH 0637/2102] RISC-V: KVM: Fix G-stage page table memory leak on VM destroy kvm_riscv_mmu_free_pgd() tears down the G-stage with kvm_riscv_gstage_unmap_range() over the whole guest physical address space. That function looks up each address with kvm_riscv_gstage_get_leaf(), which walks down to the leaf PTE, and then clears only that leaf. kvm_riscv_gstage_op_pte() frees a page table only when it is called on a non-leaf PTE, which never happens here, so every page table below the PGD is leaked when a VM is destroyed. With 4 KiB mappings this is one page per 2 MiB of guest memory that was ever mapped, plus the upper-level tables. The leaked pages are not slab, vmalloc or page cache, so they show up only as unaccounted used memory. On a SpacemiT K3 host, a workload that creates and destroys tens of thousands of small VMs leaked 0.5-1 MiB per VM and ran the host out of memory after about 20,000 VMs. Add kvm_riscv_gstage_unmap_all(), which calls kvm_riscv_gstage_op_pte() with GSTAGE_OP_CLEAR on every PGD entry. That recursively clears all leaf PTEs and frees each page table below the PGD. Use it in kvm_riscv_mmu_free_pgd(). Tested with a reproducer script that builds a minimal KVM host kernel from a source tree and boots it under QEMU 11.0.2 (TCG, rv64 with H, Sv57x4 G-stage). Its init creates 10 VMs one after another. Each guest writes one word in every 2 MiB of an 8 GiB RAM region (anonymous memory with MADV_NOHUGEPAGE, so 4 KiB G-stage mappings) and then shuts down, so each VM needs 4096 last-level page tables (16 MiB). MemFree lost per VM, after one warm-up VM: before: 16415 kB (RESULT: LEAK) after: 1636 kB (RESULT: OK, noise) The bug was found while investigating the host OOM, and the fix and reproducer were written with the help of an AI coding assistant (Claude). The analysis, fix and test results above were reviewed by the submitter. Fixes: 9d05c1fee837 ("RISC-V: KVM: Implement stage2 page table programming") Cc: stable@vger.kernel.org Signed-off-by: Yangyu Chen Tested-by: James Morris Reviewed-by: Anup Patel Link: https://lore.kernel.org/r/tencent_C8B170AF63DC42F81A47F9EA044BB4B11C09@qq.com Signed-off-by: Anup Patel --- arch/riscv/include/asm/kvm_gstage.h | 2 ++ arch/riscv/kvm/gstage.c | 22 ++++++++++++++++++++++ arch/riscv/kvm/mmu.c | 3 +-- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/arch/riscv/include/asm/kvm_gstage.h b/arch/riscv/include/asm/kvm_gstage.h index aaf080ba1b77a2..90ec9e0b34b182 100644 --- a/arch/riscv/include/asm/kvm_gstage.h +++ b/arch/riscv/include/asm/kvm_gstage.h @@ -80,6 +80,8 @@ bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr, bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage, gpa_t start, gpa_t size, bool may_block); +bool kvm_riscv_gstage_unmap_all(struct kvm_gstage *gstage); + bool kvm_riscv_gstage_wp_range(struct kvm_gstage *gstage, gpa_t start, gpa_t end); bool kvm_riscv_gstage_wp_pt_masked(struct kvm_gstage *gstage, gfn_t base_gfn, diff --git a/arch/riscv/kvm/gstage.c b/arch/riscv/kvm/gstage.c index be70607a33ea03..0aace3215d3e83 100644 --- a/arch/riscv/kvm/gstage.c +++ b/arch/riscv/kvm/gstage.c @@ -456,6 +456,28 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage, return flush; } +/* + * Clear every G-stage mapping and free all page tables below the PGD. + * kvm_riscv_gstage_unmap_range() only clears leaf PTEs and leaves the + * page tables in place, so it cannot be used to tear down a G-stage. + */ +bool kvm_riscv_gstage_unmap_all(struct kvm_gstage *gstage) +{ + u32 level = gstage->pgd_levels - 1; + pte_t *pgd = (pte_t *)gstage->pgd; + unsigned long i, page_size; + bool flush = false; + + if (gstage_level_to_page_size(gstage, level, &page_size)) + return false; + + for (i = 0; i < kvm_riscv_gstage_pgd_size / sizeof(pte_t); i++) + flush |= kvm_riscv_gstage_op_pte(gstage, i * page_size, &pgd[i], + level, GSTAGE_OP_CLEAR); + + return flush; +} + bool kvm_riscv_gstage_wp_range(struct kvm_gstage *gstage, gpa_t start, gpa_t end) { int ret; diff --git a/arch/riscv/kvm/mmu.c b/arch/riscv/kvm/mmu.c index 5b7cb559c22a34..6861c0e2728d58 100644 --- a/arch/riscv/kvm/mmu.c +++ b/arch/riscv/kvm/mmu.c @@ -832,8 +832,7 @@ void kvm_riscv_mmu_free_pgd(struct kvm *kvm) write_lock(&kvm->mmu_lock); if (kvm->arch.pgd) { kvm_riscv_gstage_init(&gstage, kvm); - flush = kvm_riscv_gstage_unmap_range(&gstage, 0UL, - kvm_riscv_gstage_gpa_size(kvm->arch.pgd_levels), false); + flush = kvm_riscv_gstage_unmap_all(&gstage); pgd = READ_ONCE(kvm->arch.pgd); kvm->arch.pgd = NULL; kvm->arch.pgd_phys = 0; From 0ad8ea7fa7dc0f0d0e45f7ed4933d5433dac4291 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnther=20Noack?= Date: Fri, 13 Nov 2026 21:23:23 +0100 Subject: [PATCH 0638/2102] landlock: Fix layer composition of LANDLOCK_ACCESS_FS_REFER MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In landlock_get_fs_access_mask(), only add the LANDLOCK_ACCESS_FS_REFER right if any filesystem access rights are handled at all. This prevents us from accidentally treating non-filesystem layers as if they handled LANDLOCK_ACCESS_FS_REFER. landlock_get_fs_access_mask() is used when initializing the layer masks for doing access right checks, so this bug meant that we unintentionally denied "refer" (e.g., link, rename) operations in layered cases, where the same operation would have been accepted if only either one of the two layers had been enforced. If the rulesets individually allow an operation, the composition of these rulesets should also allow it. The bug only manifests as soon as one other layer handles filesystem access rights. Otherwise, Landlock filesystem path walk is guarded by an early exit for the case that no filesystem-enforcing layer exists. Reported-by: Dwi Siswanto Closes: https://github.com/landlock-lsm/linux/issues/67 Closes: https://github.com/landlock-lsm/go-landlock/issues/66 Fixes: fff69fb03dde ("landlock: Support network rules with TCP bind and connect") Cc: stable@vger.kernel.org Signed-off-by: Günther Noack Link: https://patch.msgid.link/20261113-b4-landlock-refer-nonfs-layer-v3-1-02d7e42bcdfd@gmail.com Signed-off-by: Mickaël Salaün --- security/landlock/domain.h | 13 ++++++++++--- security/landlock/errata/abi-4.h | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/security/landlock/domain.h b/security/landlock/domain.h index 935e18b12b3cc8..d9ebf4857fce8c 100644 --- a/security/landlock/domain.h +++ b/security/landlock/domain.h @@ -262,9 +262,16 @@ static inline access_mask_t landlock_get_fs_access_mask(const struct landlock_domain *const domain, const u16 layer_level) { - /* Handles all initially denied by default access rights. */ - return domain->layers[layer_level].handled.fs | - _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; + access_mask_t handled = domain->layers[layer_level].handled.fs; + + /* + * Handles all initially denied by default access rights, but only for + * layers handling filesystem accesses. + */ + if (handled) + handled |= _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; + + return handled; } static inline access_mask_t diff --git a/security/landlock/errata/abi-4.h b/security/landlock/errata/abi-4.h index fe11ec7d7ddf55..9784ca64507305 100644 --- a/security/landlock/errata/abi-4.h +++ b/security/landlock/errata/abi-4.h @@ -20,3 +20,24 @@ * that rely on these protocols while using Landlock network restrictions. */ LANDLOCK_ERRATUM(1) + +/** + * DOC: erratum_5 + * + * Erratum 5: Denial of ``LANDLOCK_ACCESS_FS_REFER`` in layered domains + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * This fix addresses an issue where ``LANDLOCK_ACCESS_FS_REFER`` was implicitly + * handled in domain layers that handle no filesystem access rights. + * + * With this fix, a reparenting operation is allowed in a layered Landlock + * domain if and only if each layer, enforced on its own, would allow it. + * + * Impact: + * + * In kernels without this fix, if a domain combined a layer that handles + * filesystem access rights with a layer that doesn't, the resulting layered + * domain would deny all ``LANDLOCK_ACCESS_FS_REFER`` operations, even when the + * filesystem layer granted these operations with a rule. + */ +LANDLOCK_ERRATUM(5) From 9286361ea5cc821fc149b680b56a186669452722 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnther=20Noack?= Date: Fri, 13 Nov 2026 21:23:24 +0100 Subject: [PATCH 0639/2102] landlock: Add KUnit test for landlock_get_fs_access_mask() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This checks that landlock_upgrade_handled_layer_config() and landlock_get_fs_access_mask() together result in the right handled access rights being reported by landlock_get_fs_access_mask(): LANDLOCK_ACCESS_FS_REFER is only implicit if any of the other filesystem access rights are handled. Signed-off-by: Günther Noack Link: https://patch.msgid.link/20261113-b4-landlock-refer-nonfs-layer-v3-2-02d7e42bcdfd@gmail.com Signed-off-by: Mickaël Salaün --- security/landlock/domain.c | 44 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/security/landlock/domain.c b/security/landlock/domain.c index 4c0b1f0e1db5df..71756c68d08e74 100644 --- a/security/landlock/domain.c +++ b/security/landlock/domain.c @@ -753,6 +753,49 @@ static void test_landlock_get_deny_masks(struct kunit *const test) &layers1)); } +static void test_get_fs_access_mask(struct kunit *const test) +{ + static const struct { + struct layer_config config; + access_mask_t expected_fs; + } layers[] = { + { + .config.handled.net = LANDLOCK_ACCESS_NET_BIND_TCP, + .expected_fs = 0, + }, + { + .config.handled.scope = LANDLOCK_SCOPE_SIGNAL, + .expected_fs = 0, + }, + { + .config.handled.fs = LANDLOCK_ACCESS_FS_EXECUTE, + .expected_fs = LANDLOCK_ACCESS_FS_EXECUTE | + LANDLOCK_ACCESS_FS_REFER, + }, + { + .config.handled.fs = LANDLOCK_ACCESS_FS_REFER, + .expected_fs = LANDLOCK_ACCESS_FS_REFER, + }, + }; + struct landlock_domain *domain; + size_t i; + + domain = kunit_kzalloc(test, + struct_size(domain, layers, ARRAY_SIZE(layers)), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, domain); + domain->num_layers = ARRAY_SIZE(layers); + + for (i = 0; i < ARRAY_SIZE(layers); i++) + domain->layers[i] = + landlock_upgrade_handled_layer_config(layers[i].config); + + for (i = 0; i < ARRAY_SIZE(layers); i++) + KUNIT_EXPECT_EQ_MSG(test, layers[i].expected_fs, + landlock_get_fs_access_mask(domain, i), + "layer %zu", i); +} + #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */ #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST @@ -761,6 +804,7 @@ static struct kunit_case test_cases[] = { /* clang-format off */ KUNIT_CASE(test_get_layer_deny_mask), KUNIT_CASE(test_landlock_get_deny_masks), + KUNIT_CASE(test_get_fs_access_mask), {} /* clang-format on */ }; From 047e27306d268d6972f8242b69f50e5814b09282 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnther=20Noack?= Date: Fri, 13 Nov 2026 21:23:25 +0100 Subject: [PATCH 0640/2102] selftests/landlock: Test that layering does not break refer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Regression test to exercise that layered Landlock domains do not accidentally deny the LANDLOCK_ACCESS_FS_REFER access right. This used to be the case when layering a non-filesystem ruleset with a filesystem-enforcing ruleset. In that case, REFER operations that would have been allowed for the individual rulesets would get denied when layering the same rulesets. Link: https://github.com/landlock-lsm/linux/issues/67 Link: https://github.com/landlock-lsm/go-landlock/issues/66 Fixes: fff69fb03dde ("landlock: Support network rules with TCP bind and connect") Cc: stable@vger.kernel.org Signed-off-by: Günther Noack Link: https://patch.msgid.link/20261113-b4-landlock-refer-nonfs-layer-v3-3-02d7e42bcdfd@gmail.com Signed-off-by: Mickaël Salaün --- tools/testing/selftests/landlock/fs_test.c | 54 ++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/tools/testing/selftests/landlock/fs_test.c b/tools/testing/selftests/landlock/fs_test.c index f725882fa4a78b..6d9baab0fae8cb 100644 --- a/tools/testing/selftests/landlock/fs_test.c +++ b/tools/testing/selftests/landlock/fs_test.c @@ -2612,6 +2612,60 @@ TEST_F_FORK(layout1, refer_denied_by_default4) layer_dir_s1d1_refer); } +/* + * Regression test for layered domains: The two enforced Landlock layers both do + * not restrict the tested "refer" operations on their own, so they should also + * not restrict them when they are layered, regardless of the layer order. + */ +static void test_layering_does_not_break_refer( + struct __test_metadata *const _metadata, + const struct landlock_ruleset_attr *const non_fs_attr, + const bool non_fs_first) +{ + ASSERT_EQ(0, unlink(file1_s1d2)); + + if (non_fs_first) + drop_access_rights(_metadata, non_fs_attr); + + enforce_fs(_metadata, LANDLOCK_ACCESS_FS_REFER, layer_dir_s1d1_refer); + + if (!non_fs_first) + drop_access_rights(_metadata, non_fs_attr); + + EXPECT_EQ(0, test_rename(file1_s1d1, file1_s1d2)); + EXPECT_EQ(0, test_rename(file1_s1d2, file1_s1d1)); + EXPECT_EQ(0, test_exchange(file2_s1d1, file2_s1d2)); + EXPECT_EQ(0, test_exchange(file2_s1d2, file2_s1d1)); +} + +static const struct landlock_ruleset_attr net_attr = { + .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP, +}; + +static const struct landlock_ruleset_attr scoped_attr = { + .scoped = LANDLOCK_SCOPE_SIGNAL, +}; + +TEST_F_FORK(layout1, layering_fs_then_net_does_not_break_refer) +{ + test_layering_does_not_break_refer(_metadata, &net_attr, false); +} + +TEST_F_FORK(layout1, layering_net_then_fs_does_not_break_refer) +{ + test_layering_does_not_break_refer(_metadata, &net_attr, true); +} + +TEST_F_FORK(layout1, layering_fs_then_scoped_does_not_break_refer) +{ + test_layering_does_not_break_refer(_metadata, &scoped_attr, false); +} + +TEST_F_FORK(layout1, layering_scoped_then_fs_does_not_break_refer) +{ + test_layering_does_not_break_refer(_metadata, &scoped_attr, true); +} + /* * Tests walking through a denied root mount. */ From 386250ca4f55510404d365c7877cfe9ba67547f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnther=20Noack?= Date: Fri, 13 Nov 2026 21:23:26 +0100 Subject: [PATCH 0641/2102] landlock: Simplify landlock_get_fs_access_mask() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Return the handled FS access mask as it is, instead of artificially adding LANDLOCK_ACCESS_FS_REFER to it. Since commit d6c7cf84a24f ("landlock: Simplify initially denied access rights"), the merge operation already bakes the initially denied access rights (LANDLOCK_ACCESS_FS_REFER) into the a layer's handled FS access rights. -- They don't need to be added explicitly any more. No functional change. Signed-off-by: Günther Noack Link: https://patch.msgid.link/20261113-b4-landlock-refer-nonfs-layer-v3-4-02d7e42bcdfd@gmail.com Signed-off-by: Mickaël Salaün --- security/landlock/domain.h | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/security/landlock/domain.h b/security/landlock/domain.h index d9ebf4857fce8c..812c324cb6ef22 100644 --- a/security/landlock/domain.h +++ b/security/landlock/domain.h @@ -262,16 +262,12 @@ static inline access_mask_t landlock_get_fs_access_mask(const struct landlock_domain *const domain, const u16 layer_level) { - access_mask_t handled = domain->layers[layer_level].handled.fs; - /* - * Handles all initially denied by default access rights, but only for - * layers handling filesystem accesses. + * Initially denied by default access rights are already included for + * layers handling filesystem accesses, see + * landlock_upgrade_handled_layer_config(). */ - if (handled) - handled |= _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; - - return handled; + return domain->layers[layer_level].handled.fs; } static inline access_mask_t From 57493c3b7f449a60d1c43322158671b98684f9b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnther=20Noack?= Date: Fri, 13 Nov 2026 21:23:27 +0100 Subject: [PATCH 0642/2102] landlock: Clarify implicit handling of LANDLOCK_ACCESS_FS_REFER MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The LANDLOCK_ACCESS_FS_REFER right is handled implicitly in a ruleset, but only if any other filesystem access right is declared as handled in the given ruleset. The old documentation was still a remnant from the times when filesystem access rights were the only access rights that existed in Landlock, but it became misleading when we introduced additional types of access rights. Fixes: fff69fb03dde ("landlock: Support network rules with TCP bind and connect") Signed-off-by: Günther Noack Link: https://patch.msgid.link/20261113-b4-landlock-refer-nonfs-layer-v3-5-02d7e42bcdfd@gmail.com [mic: Reword _LANDLOCK_ACCESS_FS_INITIALLY_DENIED comment, fix comment wrapping, and include erratum 5 in userspace-api/landlock.rst] Signed-off-by: Mickaël Salaün --- Documentation/userspace-api/landlock.rst | 3 +++ include/uapi/linux/landlock.h | 17 +++++++++-------- security/landlock/access.h | 11 +++++------ tools/testing/selftests/landlock/fs_test.c | 7 ++++--- 4 files changed, 21 insertions(+), 17 deletions(-) diff --git a/Documentation/userspace-api/landlock.rst b/Documentation/userspace-api/landlock.rst index 3d45b956b6407c..24cfc2c23cb2c4 100644 --- a/Documentation/userspace-api/landlock.rst +++ b/Documentation/userspace-api/landlock.rst @@ -780,6 +780,9 @@ in the running kernel. .. kernel-doc:: security/landlock/errata/abi-1.h :doc: erratum_4 +.. kernel-doc:: security/landlock/errata/abi-4.h + :doc: erratum_5 + How to check for errata ~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/include/uapi/linux/landlock.h b/include/uapi/linux/landlock.h index 24510e5d8479a0..7e38b9d1bf1279 100644 --- a/include/uapi/linux/landlock.h +++ b/include/uapi/linux/landlock.h @@ -22,10 +22,10 @@ * enacted. Vice versa, access rights that are not specifically listed here are * not going to be denied by this ruleset when it is enacted. * - * For historical reasons, the %LANDLOCK_ACCESS_FS_REFER right is always denied - * by default, even when its bit is not set in @handled_access_fs. In order to - * add new rules with this access right, the bit must still be set explicitly - * (cf. `Filesystem flags`_). + * For historical reasons, as soon as any filesystem access right is handled in + * @handled_access_fs, the %LANDLOCK_ACCESS_FS_REFER right is always denied as + * well. In order to add new rules with this access right, the bit must still + * be set explicitly (cf. `Filesystem flags`_). * * The explicit listing of *handled access rights* is required for backwards * compatibility reasons. In most use cases, processes that use Landlock will @@ -462,10 +462,11 @@ struct landlock_capability_attr { * This access right is available since the second version of the Landlock * ABI. * - * This is the only access right which is denied by default by any ruleset, - * even if the right is not specified as handled at ruleset creation time. - * The only way to make a ruleset grant this right is to explicitly allow it - * for a specific directory by adding a matching rule to the ruleset. + * This is the only access right which is denied by default by any ruleset + * that handles filesystem access rights, even if the right is not specified + * as handled at ruleset creation time. The only way to make a ruleset grant + * this right is to explicitly allow it for a specific directory by adding a + * matching rule to the ruleset. * * In particular, when using the first Landlock ABI version, Landlock will * always deny attempts to reparent files between different directories. diff --git a/security/landlock/access.h b/security/landlock/access.h index f9eaa2f536866d..72afd236f883e6 100644 --- a/security/landlock/access.h +++ b/security/landlock/access.h @@ -18,10 +18,9 @@ #include "limits.h" /* - * All access rights that are denied by default whether they are handled or not - * by a ruleset/layer. This must be ORed with the .handled field of all - * domain->layers[] entries when we need to get the absolute handled access - * masks, see landlock_upgrade_handled_layer_config(). + * All filesystem access rights that are denied by default when a layer handles + * any filesystem access right, even if they are not explicitly declared as + * handled themselves. See landlock_upgrade_handled_layer_config(). */ /* clang-format off */ #define _LANDLOCK_ACCESS_FS_INITIALLY_DENIED ( \ @@ -178,8 +177,8 @@ static inline struct layer_config landlock_upgrade_handled_layer_config(struct layer_config layer_config) { /* - * All access rights that are denied by default whether they are - * explicitly handled or not. + * All filesystem access rights that are denied by default as soon as + * any other filesystem access right is handled. */ if (layer_config.handled.fs) layer_config.handled.fs |= _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; diff --git a/tools/testing/selftests/landlock/fs_test.c b/tools/testing/selftests/landlock/fs_test.c index 6d9baab0fae8cb..48c1f896dc9a0e 100644 --- a/tools/testing/selftests/landlock/fs_test.c +++ b/tools/testing/selftests/landlock/fs_test.c @@ -3034,8 +3034,8 @@ TEST_F_FORK(layout1, reparent_exdev_layers_rename1) /* * Moving the file2_s1d3 file below dir_s2d3 is denied because the - * second layer does not handle REFER, which is always denied by - * default. + * second layer does not handle REFER, which is always denied as soon as + * any other filesystem access right is handled. */ ASSERT_EQ(-1, rename(file2_s1d3, file1_s2d3)); ASSERT_EQ(EXDEV, errno); @@ -3073,7 +3073,8 @@ TEST_F_FORK(layout1, reparent_exdev_layers_rename2) ASSERT_EQ(EXDEV, errno); /* * Modifying the layout is now denied because the second layer does not - * handle REFER, which is always denied by default. + * handle REFER, which is always denied as soon as any other filesystem + * access right is handled. */ ASSERT_EQ(-1, rename(file2_s1d2, file1_s2d3)); ASSERT_EQ(EXDEV, errno); From a026947e08d65375df593de2d02fbfacdf34b173 Mon Sep 17 00:00:00 2001 From: Mika Westerberg Date: Thu, 5 Nov 2026 11:32:00 +0200 Subject: [PATCH 0643/2102] thunderbolt: Return -ETIMEDOUT if XDomain peer returns ERROR_NOT_READY The XDomain protocol retries the message when it gets -EAGAIN from the handler. However, this also happens if the remote peer replies with ERROR_NOT_READY as tb_xdp_handle_error() also returns -EAGAIN. This can lead to infinite retry loop. Fix this by returning -ETIMEDOUT in that case. Cc: stable@vger.kernel.org Fixes: 8e1de7042596 ("thunderbolt: Add support for XDomain lane bonding") Signed-off-by: Mika Westerberg --- drivers/thunderbolt/xdomain.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/thunderbolt/xdomain.c b/drivers/thunderbolt/xdomain.c index 563a8b65c8543a..2c95e1786770e6 100644 --- a/drivers/thunderbolt/xdomain.c +++ b/drivers/thunderbolt/xdomain.c @@ -1370,7 +1370,7 @@ static int tb_xdomain_get_uuid(struct tb_xdomain *xd) return -EAGAIN; } dev_dbg(&xd->dev, "failed to read remote UUID\n"); - return ret; + return ret != -EAGAIN ? ret : -ETIMEDOUT; } dev_dbg(&xd->dev, "got remote UUID %pUb\n", &uuid); @@ -1425,7 +1425,7 @@ static int tb_xdomain_get_link_status(struct tb_xdomain *xd) return -EAGAIN; } dev_dbg(&xd->dev, "failed to receive remote link status\n"); - return ret; + return ret != -EAGAIN ? ret : -ETIMEDOUT; } dev_dbg(&xd->dev, "remote link supports width %#x speed %#x\n", slw, sls); @@ -1472,7 +1472,7 @@ static int tb_xdomain_link_state_change(struct tb_xdomain *xd, return -EAGAIN; } dev_err(&xd->dev, "failed request link state change, aborting\n"); - return ret; + return ret != -EAGAIN ? ret : -ETIMEDOUT; } dev_dbg(&xd->dev, "received link state change response\n"); @@ -1564,7 +1564,7 @@ static int tb_xdomain_get_properties(struct tb_xdomain *xd) dev_err(&xd->dev, "failed read XDomain properties from %pUb\n", xd->remote_uuid); - return ret; + return ret != -EAGAIN ? ret : -ETIMEDOUT; } mutex_lock(&xd->lock); From 65f634533c8eacd6e6e8acb38cd905ce11e765ef Mon Sep 17 00:00:00 2001 From: Suyuan Wang Date: Thu, 12 Nov 2026 09:57:03 +0000 Subject: [PATCH 0644/2102] thunderbolt: Keep the USB4 port when component_add() fails When component_add() fails, usb4_port_device_add() unregisters the device but doesn't return: ret = component_add(&usb4->dev, &connector_ops); if (ret) { dev_err(&usb4->dev, "failed to add component\n"); device_unregister(&usb4->dev); } The port was registered just before, so device_unregister() normally drops the last reference and usb4_port_device_release() frees usb4. The function still goes on to set up runtime PM on usb4->dev and returns usb4 to usb4_switch_add_ports(), which stores the stale pointer in port->usb4. When the router is removed later, usb4_switch_remove_ports() calls component_del() and device_unregister() on that pointer again. component_add() can fail on allocation, or when binding the aggregate driver fails. It isn't common, but when it happens the result is a use-after-free and a double unregister. The USB4 port can keep working without the component link. Keep the port registered when component_add() fails, and track whether the component was added, so that usb4_port_device_remove() only calls component_del() for a registered component. Otherwise component_del() would hit its WARN_ON(). Found with a static analysis tool and checked by hand. Fixes: 5dddb4169284 ("thunderbolt: Link USB4 ports to their USB Type-C connectors") Reported-by: Alok Tiwari Closes: https://lore.kernel.org/all/20250622140455.2884518-1-alok.a.tiwari@oracle.com/ Suggested-by: Mika Westerberg Cc: stable@vger.kernel.org Co-developed-by: Kaixuan Li Signed-off-by: Kaixuan Li Signed-off-by: Suyuan Wang Signed-off-by: Mika Westerberg --- drivers/thunderbolt/tb.h | 2 ++ drivers/thunderbolt/usb4_port.c | 12 +++++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/drivers/thunderbolt/tb.h b/drivers/thunderbolt/tb.h index e86845762e226c..8ed373e94b652f 100644 --- a/drivers/thunderbolt/tb.h +++ b/drivers/thunderbolt/tb.h @@ -314,6 +314,7 @@ struct tb_port { * @can_offline: Does the port have necessary platform support to move * it into offline mode and back * @offline: The port is currently in offline mode + * @component_added: The port was added to the component framework * @margining: Pointer to margining structure if enabled */ struct usb4_port { @@ -321,6 +322,7 @@ struct usb4_port { struct tb_port *port; bool can_offline; bool offline; + bool component_added; #ifdef CONFIG_USB4_DEBUGFS_MARGINING struct tb_margining *margining; #endif diff --git a/drivers/thunderbolt/usb4_port.c b/drivers/thunderbolt/usb4_port.c index 890de530debc1f..7582acadf37cfa 100644 --- a/drivers/thunderbolt/usb4_port.c +++ b/drivers/thunderbolt/usb4_port.c @@ -320,11 +320,12 @@ struct usb4_port *usb4_port_device_add(struct tb_port *port) return ERR_PTR(ret); } + /* The port works fine without the component, so don't fail here */ ret = component_add(&usb4->dev, &connector_ops); - if (ret) { - dev_err(&usb4->dev, "failed to add component\n"); - device_unregister(&usb4->dev); - } + if (ret) + dev_err(&usb4->dev, "failed to add component: %d\n", ret); + else + usb4->component_added = true; if (!tb_is_upstream_port(port)) device_set_wakeup_capable(&usb4->dev, true); @@ -348,7 +349,8 @@ struct usb4_port *usb4_port_device_add(struct tb_port *port) */ void usb4_port_device_remove(struct usb4_port *usb4) { - component_del(&usb4->dev, &connector_ops); + if (usb4->component_added) + component_del(&usb4->dev, &connector_ops); device_unregister(&usb4->dev); } From 25c38ab9e6b69cfdc13aeff19470f7d0893b1702 Mon Sep 17 00:00:00 2001 From: Antonio Borneo Date: Mon, 16 Nov 2026 14:24:02 +0100 Subject: [PATCH 0645/2102] watchdog: stm32_iwdg: set driver data before requesting interrupt The interrupt handler accesses the driver data, which is currently set after devm_request_irq() returns. If the watchdog was started by the bootloader and a pretimeout interrupt is pending, the handler can run before the driver data is set, resulting in a NULL pointer dereference. Move the IRQ request after setting the driver data to ensure it is available when the interrupt handler runs. Fixes: 3ab1663af6c1 ("watchdog: stm32_iwdg: Add pretimeout support") Cc: stable@vger.kernel.org Reported-by: Sashiko Link: https://sashiko.dev/#/patchset/20261106163429.618392-1-antonio.borneo%40foss.st.com?part=3 Signed-off-by: Antonio Borneo Link: https://patch.msgid.link/20261116132416.1184447-2-antonio.borneo@foss.st.com Signed-off-by: Guenter Roeck --- drivers/watchdog/stm32_iwdg.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/watchdog/stm32_iwdg.c b/drivers/watchdog/stm32_iwdg.c index 8a6f0b78a2b0a6..cac76dab8d854b 100644 --- a/drivers/watchdog/stm32_iwdg.c +++ b/drivers/watchdog/stm32_iwdg.c @@ -346,15 +346,15 @@ static int stm32_iwdg_probe(struct platform_device *pdev) wdd->max_hw_heartbeat_ms = ((RLR_MAX + 1) * wdt->data->max_prescaler * 1000) / wdt->rate; + watchdog_set_drvdata(wdd, wdt); + watchdog_set_nowayout(wdd, WATCHDOG_NOWAYOUT); + watchdog_init_timeout(wdd, 0, dev); + /* Initialize IRQ, this might override wdd->info, hence it is here. */ ret = stm32_iwdg_irq_init(pdev, wdt); if (ret) return ret; - watchdog_set_drvdata(wdd, wdt); - watchdog_set_nowayout(wdd, WATCHDOG_NOWAYOUT); - watchdog_init_timeout(wdd, 0, dev); - /* * In case of CONFIG_WATCHDOG_HANDLE_BOOT_ENABLED is set * (Means U-Boot/bootloaders leaves the watchdog running) From abbf55699ff6a8830b864aa1fab9f24edc9e72a6 Mon Sep 17 00:00:00 2001 From: Antonio Borneo Date: Mon, 16 Nov 2026 14:24:03 +0100 Subject: [PATCH 0646/2102] watchdog: stm32_iwdg: serialize accesses to EWCR register On STM32MP1xx platforms, EWCR contains both the pretimeout interrupt configuration and a write-only bit used to acknowledge the interrupt. On SMP systems, the read-modify-write operation in the pretimeout IRQ handler can race with writes that update the pretimeout configuration. Protect these accesses with a spinlock to prevent concurrent updates. Don't use the helpers reg_read()/reg_write() in the critical sections as they rely on relaxed memory access, which are not ordered against locking. Fixes: 3ab1663af6c1 ("watchdog: stm32_iwdg: Add pretimeout support") Cc: stable@vger.kernel.org Signed-off-by: Antonio Borneo Link: https://patch.msgid.link/20261116132416.1184447-3-antonio.borneo@foss.st.com Signed-off-by: Guenter Roeck --- drivers/watchdog/stm32_iwdg.c | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/drivers/watchdog/stm32_iwdg.c b/drivers/watchdog/stm32_iwdg.c index cac76dab8d854b..30c26a8beae424 100644 --- a/drivers/watchdog/stm32_iwdg.c +++ b/drivers/watchdog/stm32_iwdg.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #define DEFAULT_TIMEOUT 10 @@ -82,6 +83,7 @@ struct stm32_iwdg { struct clk *clk_lsi; struct clk *clk_pclk; unsigned int rate; + spinlock_t lock; /* serialize IWDG_EWCR register access */ }; static inline u32 reg_read(void __iomem *base, u32 reg) @@ -98,6 +100,7 @@ static int stm32_iwdg_start(struct watchdog_device *wdd) { struct stm32_iwdg *wdt = watchdog_get_drvdata(wdd); u32 tout, ptot, presc, iwdg_rlr, iwdg_ewcr, iwdg_pr, iwdg_sr; + unsigned long flags; int ret; dev_dbg(wdd->parent, "%s\n", __func__); @@ -124,8 +127,11 @@ static int stm32_iwdg_start(struct watchdog_device *wdd) /* set prescaler & reload registers */ reg_write(wdt->regs, IWDG_PR, iwdg_pr); reg_write(wdt->regs, IWDG_RLR, iwdg_rlr); - if (wdt->data->has_early_wakeup) - reg_write(wdt->regs, IWDG_EWCR, iwdg_ewcr | EWCR_EWIE); + if (wdt->data->has_early_wakeup) { + spin_lock_irqsave(&wdt->lock, flags); + writel(iwdg_ewcr | EWCR_EWIE, wdt->regs + IWDG_EWCR); + spin_unlock_irqrestore(&wdt->lock, flags); + } reg_write(wdt->regs, IWDG_KR, KR_KEY_ENABLE); /* wait for the registers to be updated (max 100ms) */ @@ -185,11 +191,16 @@ static irqreturn_t stm32_iwdg_isr(int irq, void *wdog_arg) { struct watchdog_device *wdd = wdog_arg; struct stm32_iwdg *wdt = watchdog_get_drvdata(wdd); + unsigned long flags; u32 reg; - reg = reg_read(wdt->regs, IWDG_EWCR); + spin_lock_irqsave(&wdt->lock, flags); + + reg = readl(wdt->regs + IWDG_EWCR); reg |= EWCR_EWIC; - reg_write(wdt->regs, IWDG_EWCR, reg); + writel(reg, wdt->regs + IWDG_EWCR); + + spin_unlock_irqrestore(&wdt->lock, flags); watchdog_notify_pretimeout(wdd); @@ -323,6 +334,8 @@ static int stm32_iwdg_probe(struct platform_device *pdev) if (!wdt) return -ENOMEM; + spin_lock_init(&wdt->lock); + wdt->data = of_device_get_match_data(&pdev->dev); if (!wdt->data) return -ENODEV; From 920cd269c9228c5f51a8bbd65575010890797afa Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Tue, 10 Nov 2026 11:35:02 +0000 Subject: [PATCH 0647/2102] nvmet: clean up DH group state on initialization failure nvmet_setup_dhgroup() leaves the DH transform and group ID initialized when private-key generation, public-key allocation, or public-key generation fails. A subsequent invocation with the same DH group incorrectly returns success because the existing transform and group ID are treated as proof of successful initialization. Release the transform and reset the group state on initialization failures so that subsequent attempts can properly retry setup. Fixes: 7a277c37d352 ("nvmet-auth: Diffie-Hellman key exchange support") Signed-off-by: Sreeraj S Kurup Reviewed-by: Hannes Reinecke Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/target/auth.c | 67 +++++++++++++++++++++----------------- 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/drivers/nvme/target/auth.c b/drivers/nvme/target/auth.c index ccba84b1344e0f..681459b5db3b5f 100644 --- a/drivers/nvme/target/auth.c +++ b/drivers/nvme/target/auth.c @@ -76,8 +76,11 @@ int nvmet_setup_dhgroup(struct nvmet_ctrl *ctrl, u8 dhgroup_id) return 0; } crypto_free_kpp(ctrl->dh_tfm); + kfree_sensitive(ctrl->dh_key); ctrl->dh_tfm = NULL; ctrl->dh_gid = 0; + ctrl->dh_key = NULL; + ctrl->dh_keysize = 0; } if (dhgroup_id == NVME_AUTH_DHGROUP_NULL) @@ -95,38 +98,42 @@ int nvmet_setup_dhgroup(struct nvmet_ctrl *ctrl, u8 dhgroup_id) __func__, ctrl->cntlid, dhgroup_id, PTR_ERR(ctrl->dh_tfm)); ret = PTR_ERR(ctrl->dh_tfm); - ctrl->dh_tfm = NULL; - ctrl->dh_gid = 0; - } else { - ctrl->dh_gid = dhgroup_id; - pr_debug("%s: ctrl %d setup DH group %d\n", - __func__, ctrl->cntlid, ctrl->dh_gid); - ret = nvme_auth_gen_privkey(ctrl->dh_tfm, ctrl->dh_gid); - if (ret < 0) { - pr_debug("%s: ctrl %d failed to generate private key, err %d\n", - __func__, ctrl->cntlid, ret); - kfree_sensitive(ctrl->dh_key); - ctrl->dh_key = NULL; - return ret; - } - ctrl->dh_keysize = crypto_kpp_maxsize(ctrl->dh_tfm); - kfree_sensitive(ctrl->dh_key); - ctrl->dh_key = kzalloc(ctrl->dh_keysize, GFP_KERNEL); - if (!ctrl->dh_key) { - pr_warn("ctrl %d failed to allocate public key\n", - ctrl->cntlid); - return -ENOMEM; - } - ret = nvme_auth_gen_pubkey(ctrl->dh_tfm, ctrl->dh_key, - ctrl->dh_keysize); - if (ret < 0) { - pr_warn("ctrl %d failed to generate public key\n", - ctrl->cntlid); - kfree(ctrl->dh_key); - ctrl->dh_key = NULL; - } + goto err; + } + + ctrl->dh_gid = dhgroup_id; + pr_debug("%s: ctrl %d setup DH group %d\n", + __func__, ctrl->cntlid, ctrl->dh_gid); + ret = nvme_auth_gen_privkey(ctrl->dh_tfm, ctrl->dh_gid); + if (ret < 0) { + pr_debug("%s: ctrl %d failed to generate private key, err %d\n", + __func__, ctrl->cntlid, ret); + goto err; + } + ctrl->dh_keysize = crypto_kpp_maxsize(ctrl->dh_tfm); + ctrl->dh_key = kzalloc(ctrl->dh_keysize, GFP_KERNEL); + if (!ctrl->dh_key) { + pr_warn("ctrl %d failed to allocate public key\n", + ctrl->cntlid); + ret = -ENOMEM; + goto err; + } + ret = nvme_auth_gen_pubkey(ctrl->dh_tfm, ctrl->dh_key, + ctrl->dh_keysize); + if (ret < 0) { + pr_warn("ctrl %d failed to generate public key\n", + ctrl->cntlid); + goto err; } + return 0; +err: + kfree_sensitive(ctrl->dh_key); + ctrl->dh_key = NULL; + crypto_free_kpp(ctrl->dh_tfm); + ctrl->dh_tfm = NULL; + ctrl->dh_gid = 0; + ctrl->dh_keysize = 0; return ret; } From 21f0f264962358f3af6e08805b21d32abdd0e35f Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Mon, 9 Nov 2026 14:24:28 +0000 Subject: [PATCH 0648/2102] nvmet: reject invalid write-protect feature values The Set Features handler for namespace write protection currently accepts unsupported values. The default case in the write-protect switch leaves the status unchanged, causing the command to return success even though no valid setting was applied. Return NVME_SC_INVALID_FIELD | NVME_STATUS_DNR for unsupported values. This also prevents issuing a namespace-change notification for an invalid request. Fixes: 3a1f7c79ae6d ("nvmet: make nvmet_find_namespace() req based") Signed-off-by: Sreeraj S Kurup Reviewed-by: Hannes Reinecke Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/target/admin-cmd.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/nvme/target/admin-cmd.c b/drivers/nvme/target/admin-cmd.c index 6732d6d078e35c..e0be6eb0fa0447 100644 --- a/drivers/nvme/target/admin-cmd.c +++ b/drivers/nvme/target/admin-cmd.c @@ -1252,6 +1252,7 @@ static u16 nvmet_set_feat_write_protect(struct nvmet_req *req) status = 0; break; default: + status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR; break; } From 706076f51eb78ebb4cc7fb06751bf09042fb515c Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Tue, 10 Nov 2026 08:15:59 +0000 Subject: [PATCH 0649/2102] nvmet: synchronize DH-CHAP secret removal The empty-secret path in nvmet_auth_set_key() modifies and frees host authentication secrets without holding nvmet_config_sem. nvmet_setup_auth() accesses these fields under the read lock, allowing concurrent secret removal to cause a use-after-free. Acquire nvmet_config_sem for writing while clearing the secrets to synchronize with authentication setup. Fixes: bb2df18958b4 ("nvmet-auth: allow to clear DH-HMAC-CHAP keys") Signed-off-by: Sreeraj S Kurup Reviewed-by: Hannes Reinecke Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/target/auth.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/nvme/target/auth.c b/drivers/nvme/target/auth.c index 681459b5db3b5f..8ca5a061d56569 100644 --- a/drivers/nvme/target/auth.c +++ b/drivers/nvme/target/auth.c @@ -26,6 +26,7 @@ int nvmet_auth_set_key(struct nvmet_host *host, const char *secret, char *dhchap_secret; if (!strlen(secret)) { + down_write(&nvmet_config_sem); if (set_ctrl) { kfree(host->dhchap_ctrl_secret); host->dhchap_ctrl_secret = NULL; @@ -35,6 +36,7 @@ int nvmet_auth_set_key(struct nvmet_host *host, const char *secret, host->dhchap_secret = NULL; host->dhchap_key_hash = 0; } + up_write(&nvmet_config_sem); return 0; } if (sscanf(secret, "DHHC-1:%hhd:%*s", &key_hash) != 1) From f7141618d5d0b51bc2a64961bab738a0fe57e83f Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Mon, 9 Nov 2026 22:59:19 +0800 Subject: [PATCH 0650/2102] nvme-auth: use the parsed offset for the DH-CHAP key nvme_auth_parse_key() accepts the DH-HMAC-CHAP key with if (sscanf(secret, "DHHC-1:%hhd:%*s:", &key_hash) != 1) return -EINVAL; and then skips a hardcoded ten characters: key = nvme_auth_extract_key(secret + 10, key_hash); The ten characters assume that the hash identifier is exactly two characters long. A string such as "DHHC-1:1:" still makes sscanf() return 1, and secret + 10 then points one byte past the NUL terminator of the buffer. nvme_auth_extract_key() starts with strlen(secret), so it reads past the end of the allocation. The sysfs dhchap_secret and dhchap_ctrl_secret stores only require seven characters and a "DHHC-1:" prefix, so a short value reaches this code (even though the nvme-fabrics option parser rejects secrets shorter than eleven characters). Use the %n conversion to obtain the real offset after the "DHHC-1::" prefix and reject a string where the prefix is not complete. This accepts both one and two character hash identifiers and never starts the key past the terminator. Fixes: f50fff73d620 ("nvme: implement In-Band authentication") Cc: stable@vger.kernel.org Signed-off-by: Shao Mingyin Reviewed-by: Hannes Reinecke Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/common/auth.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/nvme/common/auth.c b/drivers/nvme/common/auth.c index e2e0c736540afd..1fdc4e4ed0b94d 100644 --- a/drivers/nvme/common/auth.c +++ b/drivers/nvme/common/auth.c @@ -489,17 +489,19 @@ int nvme_auth_parse_key(const char *secret, struct nvme_dhchap_key **ret_key) { struct nvme_dhchap_key *key; u8 key_hash; + int offset = 0; if (!secret) { *ret_key = NULL; return 0; } - if (sscanf(secret, "DHHC-1:%hhd:%*s:", &key_hash) != 1) + if (sscanf(secret, "DHHC-1:%hhd:%n", &key_hash, &offset) != 1 || + !offset) return -EINVAL; /* Pass in the secret without the 'DHHC-1:XX:' prefix */ - key = nvme_auth_extract_key(secret + 10, key_hash); + key = nvme_auth_extract_key(secret + offset, key_hash); if (IS_ERR(key)) { *ret_key = NULL; return PTR_ERR(key); From cb21777e86a33286badffe5fa76c6a0acb086cd6 Mon Sep 17 00:00:00 2001 From: Platon Miller Date: Wed, 11 Nov 2026 01:09:41 +0100 Subject: [PATCH 0651/2102] nvme-pci: merge duplicate 1d97:2263 entries in nvme_id_table The nvme_id_table currently contains two separate entries for PCI ID 1d97:2263: one for SPCC with NVME_QUIRK_DISABLE_WRITE_ZEROES, and another later in the table for Lexar NM610 with NVME_QUIRK_BOGUS_NID. Because pci_match_device() returns on the first match, the Lexar NM610 entry is unreachable, leaving those drives without NVME_QUIRK_BOGUS_NID. Merge the quirks for 1d97:2263 into a single entry with both NVME_QUIRK_DISABLE_WRITE_ZEROES and NVME_QUIRK_BOGUS_NID, and remove the redundant entry. Fixes: 200dccd07df2 ("nvme-pci: add NVME_QUIRK_BOGUS_NID for Lexar NM610") Signed-off-by: Platon Miller Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/host/pci.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/drivers/nvme/host/pci.c b/drivers/nvme/host/pci.c index 66496c4ba8048a..076603df01abbb 100644 --- a/drivers/nvme/host/pci.c +++ b/drivers/nvme/host/pci.c @@ -4430,8 +4430,9 @@ static const struct pci_device_id nvme_id_table[] = { .driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, }, { PCI_DEVICE(0x15b7, 0x2001), /* Sandisk Skyhawk */ .driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, }, - { PCI_DEVICE(0x1d97, 0x2263), /* SPCC */ - .driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, }, + { PCI_DEVICE(0x1d97, 0x2263), /* SPCC / Lexar NM610 */ + .driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES | + NVME_QUIRK_BOGUS_NID, }, { PCI_DEVICE(0x144d, 0xa80b), /* Samsung PM9B1 256G and 512G */ .driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES | NVME_QUIRK_BOGUS_NID, }, @@ -4491,8 +4492,6 @@ static const struct pci_device_id nvme_id_table[] = { .driver_data = NVME_QUIRK_NO_DEEPEST_PS, }, { PCI_DEVICE(0xc0a9, 0x540a), /* Crucial P2 */ .driver_data = NVME_QUIRK_BOGUS_NID, }, - { PCI_DEVICE(0x1d97, 0x2263), /* Lexar NM610 */ - .driver_data = NVME_QUIRK_BOGUS_NID, }, { PCI_DEVICE(0x1d97, 0x1d97), /* Lexar NM620 */ .driver_data = NVME_QUIRK_BOGUS_NID, }, { PCI_DEVICE(0x1d97, 0x2269), /* Lexar NM760 */ From 6ca87397aeebcfae3057653c3e7c008ccb0bb926 Mon Sep 17 00:00:00 2001 From: Fei Yu Date: Mon, 9 Nov 2026 09:48:52 +0800 Subject: [PATCH 0652/2102] drm/syncobj: Limit the number of handles and use kvmalloc for user-sized arrays MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The syncobj ioctls allocate several temporary arrays whose size is taken directly from the u32 count_handles provided by userspace: - handles and syncobjs in drm_syncobj_array_find() - points and entries in drm_syncobj_array_wait_timeout() - points and chains in drm_syncobj_timeline_signal_ioctl() These are kmalloc() allocations, so a count above KMALLOC_MAX_SIZE / element size trips the WARN_ON_ONCE_GFP() in ___kmalloc_large_node(): WARNING: mm/slub.c:5459 at ___kmalloc_large_node+0x10c/0x170 mm/slub.c:5459 Call Trace: __kmalloc_large_node_noprof+0x18/0x90 mm/slub.c:5502 __do_kmalloc_node mm/slub.c:5519 [inline] __kmalloc_noprof+0x3f6/0x710 mm/slub.c:5556 _kmalloc_noprof include/linux/slab.h:995 [inline] _kmalloc_array_noprof include/linux/slab.h:1211 [inline] drm_syncobj_array_find+0x3a/0x440 drivers/gpu/drm/drm_syncobj.c:1241 drm_syncobj_timeline_wait_ioctl+0x18a/0x640 drivers/gpu/drm/drm_syncobj.c:1356 drm_ioctl_kernel+0x2df/0x3b0 drivers/gpu/drm/drm_ioctl.c:817 drm_ioctl+0x70e/0xba0 drivers/gpu/drm/drm_ioctl.c:914 The wait entries are 64 bytes each on 64-bit, so with a 4 MiB KMALLOC_MAX_SIZE a wait on more than about 64K handles already fails today, with a warning. Fix this in two parts: - Reject more than DRM_SYNCOBJ_MAX_HANDLES (1M) handles with -EINVAL in drm_syncobj_array_find(), which every ioctl taking a handle array goes through. The limit is a fixed number, so it is the same on all architectures. It is above what these ioctls can handle today: with a 4 MiB KMALLOC_MAX_SIZE the 8-byte arrays already fail above 512K handles on 64-bit, so no request that succeeds now is rejected. A static_assert() makes sure that the largest per-handle allocation, the wait entries, stays below the INT_MAX size limit of kvmalloc(). - Switch the six allocations to kvmalloc(), so that handle counts up to the limit (64 MiB of wait entries for 1M handles) no longer depend on physically contiguous memory. Using kvmalloc() alone is not enough: the reproducer asks for more than INT_MAX bytes, which hits the WARN_ON_ONCE() in __kvmalloc_node_noprof() instead. Fixes: 3e6fb72d6cef ("drm/syncobj: Add a syncobj_array_find helper") Reported-by: syzbot+95416f957d84e858b377@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=95416f957d84e858b377 Suggested-by: Christian König Cc: stable@vger.kernel.org Signed-off-by: Fei Yu Reviewed-by: Christian König Signed-off-by: Christian König Link: https://lore.kernel.org/r/20261109014852.2127723-1-fei.yu@intel.com --- drivers/gpu/drm/drm_syncobj.c | 44 +++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/drm_syncobj.c b/drivers/gpu/drm/drm_syncobj.c index f1d4da1685457c..c8a8c49d12fb22 100644 --- a/drivers/gpu/drm/drm_syncobj.c +++ b/drivers/gpu/drm/drm_syncobj.c @@ -199,6 +199,7 @@ #include #include #include +#include #include #include @@ -220,6 +221,16 @@ struct syncobj_wait_entry { u64 point; }; +/* + * Upper limit for the number of handles passed to a single ioctl. This is a + * fixed number so that the limit is the same on all architectures. The + * largest per-handle allocation is the wait entry array, which must stay + * below the INT_MAX size limit of kvmalloc(). + */ +#define DRM_SYNCOBJ_MAX_HANDLES SZ_1M +static_assert(DRM_SYNCOBJ_MAX_HANDLES <= + INT_MAX / sizeof(struct syncobj_wait_entry)); + static void syncobj_wait_syncobj_func(struct drm_syncobj *syncobj, struct syncobj_wait_entry *wait); @@ -1051,7 +1062,7 @@ static signed long drm_syncobj_array_wait_timeout(struct drm_syncobj **syncobjs, lockdep_assert_none_held_once(); } - points = kmalloc_array(count, sizeof(*points), GFP_KERNEL); + points = kvmalloc_array(count, sizeof(*points), GFP_KERNEL); if (points == NULL) return -ENOMEM; @@ -1064,7 +1075,7 @@ static signed long drm_syncobj_array_wait_timeout(struct drm_syncobj **syncobjs, goto err_free_points; } - entries = kzalloc_objs(*entries, count); + entries = kvzalloc_objs(*entries, count); if (!entries) { timeout = -ENOMEM; goto err_free_points; @@ -1185,10 +1196,10 @@ static signed long drm_syncobj_array_wait_timeout(struct drm_syncobj **syncobjs, &entries[i].fence_cb); dma_fence_put(entries[i].fence); } - kfree(entries); + kvfree(entries); err_free_points: - kfree(points); + kvfree(points); return timeout; } @@ -1238,7 +1249,10 @@ static int drm_syncobj_array_find(struct drm_file *file_private, struct drm_syncobj **syncobjs; int ret; - handles = kmalloc_array(count_handles, sizeof(*handles), GFP_KERNEL); + if (count_handles > DRM_SYNCOBJ_MAX_HANDLES) + return -EINVAL; + + handles = kvmalloc_array(count_handles, sizeof(*handles), GFP_KERNEL); if (handles == NULL) return -ENOMEM; @@ -1248,7 +1262,7 @@ static int drm_syncobj_array_find(struct drm_file *file_private, goto err_free_handles; } - syncobjs = kmalloc_objs(*syncobjs, count_handles); + syncobjs = kvmalloc_objs(*syncobjs, count_handles); if (syncobjs == NULL) { ret = -ENOMEM; goto err_free_handles; @@ -1262,16 +1276,16 @@ static int drm_syncobj_array_find(struct drm_file *file_private, } } - kfree(handles); + kvfree(handles); *syncobjs_out = syncobjs; return 0; err_put_syncobjs: while (i-- > 0) drm_syncobj_put(syncobjs[i]); - kfree(syncobjs); + kvfree(syncobjs); err_free_handles: - kfree(handles); + kvfree(handles); return ret; } @@ -1283,7 +1297,7 @@ static void drm_syncobj_array_free(struct drm_syncobj **syncobjs, for (i = 0; i < count; i++) drm_syncobj_put(syncobjs[i]); - kfree(syncobjs); + kvfree(syncobjs); } int @@ -1572,8 +1586,8 @@ drm_syncobj_timeline_signal_ioctl(struct drm_device *dev, void *data, if (ret < 0) return ret; - points = kmalloc_array(args->count_handles, sizeof(*points), - GFP_KERNEL); + points = kvmalloc_array(args->count_handles, sizeof(*points), + GFP_KERNEL); if (!points) { ret = -ENOMEM; goto out; @@ -1586,7 +1600,7 @@ drm_syncobj_timeline_signal_ioctl(struct drm_device *dev, void *data, goto err_points; } - chains = kmalloc_objs(*chains, args->count_handles); + chains = kvmalloc_objs(*chains, args->count_handles); if (!chains) { ret = -ENOMEM; goto err_points; @@ -1609,9 +1623,9 @@ drm_syncobj_timeline_signal_ioctl(struct drm_device *dev, void *data, dma_fence_put(fence); } err_chains: - kfree(chains); + kvfree(chains); err_points: - kfree(points); + kvfree(points); out: drm_syncobj_array_free(syncobjs, args->count_handles); From ba1213be15c613a1c03db69ea6480ca140a6ca00 Mon Sep 17 00:00:00 2001 From: Mani Tofigh Date: Wed, 11 Nov 2026 17:46:31 -0500 Subject: [PATCH 0653/2102] nvme: fix deadlock on nvme_subsystems_lock in nvme_init_subsystem() Connecting a controller to a new subsystem deadlocks when sysfs_create_link() fails in nvme_init_subsystem(), e.g., on an allocation failure. The error path drops the last subsystem reference with nvme_subsystems_lock held and nvme_destroy_subsystem() takes the same lock again: nvme nvme0: failed to create sysfs link from subsystem. ============================================ WARNING: possible recursive locking detected ... nvmesubsys/95 is trying to acquire lock: (nvme_subsystems_lock){+.+.}-{4:4}, at: nvme_destroy_subsystem+0x1b/0x1e0 but task is already holding lock: (nvme_subsystems_lock){+.+.}-{4:4}, at: nvme_init_identify+0x81e/0x34b0 ... Call Trace: __mutex_lock+0x1a2/0x26e0 nvme_destroy_subsystem+0x1b/0x1e0 nvme_init_identify.cold+0x3bc/0x56f nvme_init_ctrl_finish+0x1bc/0x7a0 nvme_loop_configure_admin_queue+0x205/0x2b0 nvme_loop_create_ctrl+0x480/0xd10 nvmf_dev_write+0x365/0x650 vfs_write+0x1e3/0x1250 ksys_write+0xfa/0x200 do_syscall_64+0xfb/0x590 entry_SYSCALL_64_after_hwframe+0x77/0x7f ... INFO: task nvmesubsys:95 blocked for more than 20 seconds. INFO: task nvmesubsys:95 is blocked on a mutex likely owned by task nvmesubsys:95. Every later controller setup or removal then waits for the lock too. The nvme_validate_cntlid() error path for an existing subsystem does the same put, and deadlocks the same way if the other references go away in between. Drop the lock before the put. For a new subsystem, take it off the list first so another controller can't find it in between. With the fix, the connect fails and the next connect works. 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 30s. Fixes: 32fd90c40768 ("nvme: change locking for the per-subsystem controller list") Cc: stable@vger.kernel.org Signed-off-by: Mani Tofigh Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/host/core.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/nvme/host/core.c b/drivers/nvme/host/core.c index cd0df9b038063a..f43582e5f6c4a9 100644 --- a/drivers/nvme/host/core.c +++ b/drivers/nvme/host/core.c @@ -3413,7 +3413,11 @@ static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) return 0; out_put_subsystem: + if (!found) + list_del_init(&subsys->entry); + mutex_unlock(&nvme_subsystems_lock); nvme_put_subsystem(subsys); + return ret; out_unlock: mutex_unlock(&nvme_subsystems_lock); return ret; From 1738de07a79b9abdcffe03571c442033b80e7fed Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Thu, 12 Nov 2026 22:01:05 +0800 Subject: [PATCH 0654/2102] nvmet: handle short reads and writes in the file backend When the file backend falls back to its bvec mempool, large requests are submitted in synchronous chunks. A short completion advances the file position by the full chunk length and is eventually overwritten with the total request length. The target reports success for an incomplete write or returns unread buffer contents as valid data. The common completion path has another short-I/O case: a zero-byte return, such as a read at EOF after the backing file is truncated, is passed to errno_to_nvme_status() and becomes success. Stop at any incomplete chunk and convert nonnegative short completions to -EIO in both paths. Preserve negative errors and full completions. Fixes: d5eff33ee6f8 ("nvmet: add simple file backed ns support") Fixes: c6aa3542e010 ("nvmet: add error log support for file backend") Cc: stable@vger.kernel.org Reviewed-by: Christoph Hellwig Signed-off-by: Shao Mingyin Signed-off-by: Keith Busch --- drivers/nvme/target/io-cmd-file.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/nvme/target/io-cmd-file.c b/drivers/nvme/target/io-cmd-file.c index 695963dd932ee7..e95ab1f08cff39 100644 --- a/drivers/nvme/target/io-cmd-file.c +++ b/drivers/nvme/target/io-cmd-file.c @@ -113,7 +113,7 @@ static void nvmet_file_io_done(struct kiocb *iocb, long ret) } if (unlikely(ret != req->transfer_len)) - status = errno_to_nvme_status(req, ret); + status = errno_to_nvme_status(req, ret < 0 ? ret : -EIO); nvmet_req_complete(req, status); } @@ -150,8 +150,11 @@ static bool nvmet_file_execute_io(struct nvmet_req *req, int ki_flags) if (unlikely(is_sync) && (nr_bvec - 1 == 0 || bv_cnt == NVMET_MAX_MPOOL_BVEC)) { ret = nvmet_file_submit_bvec(req, pos, bv_cnt, len, 0); - if (ret < 0) + if (ret != len) { + if (ret >= 0) + ret = -EIO; goto complete; + } pos += len; bv_cnt = 0; From bcd5316e708d418f03707c183571549ad878cfff Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Thu, 12 Nov 2026 22:01:06 +0800 Subject: [PATCH 0655/2102] nvmet: use overflow-safe range checks in the file backend The file backend shifts a host-supplied SLBA to form a byte offset before checking it against the namespace size. The shift can discard high bits: with a 4 KiB block size, SLBA 2^52 + 1 becomes offset 4096. The range check then accepts a command aimed outside the namespace and the backend accesses data at the wrapped offset. Reject overflowing LBA-to-byte conversions and check the transfer length against the remaining namespace size without adding it to the offset. Apply the checks to reads, writes, discard and write zeroes. Fixes: 9c891c139894 ("nvmet: check fileio lba range access boundaries") Cc: stable@vger.kernel.org Signed-off-by: Shao Mingyin Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/target/io-cmd-file.c | 40 ++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/drivers/nvme/target/io-cmd-file.c b/drivers/nvme/target/io-cmd-file.c index e95ab1f08cff39..3098b902f51987 100644 --- a/drivers/nvme/target/io-cmd-file.c +++ b/drivers/nvme/target/io-cmd-file.c @@ -117,6 +117,19 @@ static void nvmet_file_io_done(struct kiocb *iocb, long ret) nvmet_req_complete(req, status); } +static bool nvmet_file_check_lba_range(struct nvmet_req *req, u64 slba, + u64 len, loff_t *pos) +{ + u64 pos64; + + if (check_shl_overflow(slba, req->ns->blksize_shift, &pos64) || + pos64 > req->ns->size || len > req->ns->size - pos64) + return false; + + *pos = pos64; + return true; +} + static bool nvmet_file_execute_io(struct nvmet_req *req, int ki_flags) { ssize_t nr_bvec = req->sg_cnt; @@ -131,8 +144,9 @@ static bool nvmet_file_execute_io(struct nvmet_req *req, int ki_flags) if (req->f.mpool_alloc && nr_bvec > NVMET_MAX_MPOOL_BVEC) is_sync = true; - pos = le64_to_cpu(req->cmd->rw.slba) << req->ns->blksize_shift; - if (unlikely(pos + req->transfer_len > req->ns->size)) { + if (unlikely(!nvmet_file_check_lba_range(req, + le64_to_cpu(req->cmd->rw.slba), + req->transfer_len, &pos))) { ret = -ENOSPC; goto complete; } @@ -282,19 +296,22 @@ static void nvmet_file_execute_discard(struct nvmet_req *req) int i; for (i = 0; i <= le32_to_cpu(req->cmd->dsm.nr); i++) { + u64 len64; + status = nvmet_copy_from_sgl(req, i * sizeof(range), &range, sizeof(range)); if (status) break; - offset = le64_to_cpu(range.slba) << req->ns->blksize_shift; - len = le32_to_cpu(range.nlb); - len <<= req->ns->blksize_shift; - if (offset + len > req->ns->size) { + if (check_shl_overflow((u64)le32_to_cpu(range.nlb), + req->ns->blksize_shift, &len64) || + !nvmet_file_check_lba_range(req, le64_to_cpu(range.slba), + len64, &offset)) { req->error_slba = le64_to_cpu(range.slba); status = errno_to_nvme_status(req, -ENOSPC); break; } + len = len64; ret = vfs_fallocate(req->ns->file, mode, offset, len); if (ret && ret != -EOPNOTSUPP) { @@ -339,16 +356,17 @@ static void nvmet_file_write_zeroes_work(struct work_struct *w) int mode = FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE; loff_t offset; loff_t len; + u64 len64; int ret; - offset = le64_to_cpu(write_zeroes->slba) << req->ns->blksize_shift; - len = (((sector_t)le16_to_cpu(write_zeroes->length) + 1) << - req->ns->blksize_shift); - - if (unlikely(offset + len > req->ns->size)) { + if (check_shl_overflow((u64)le16_to_cpu(write_zeroes->length) + 1, + req->ns->blksize_shift, &len64) || + !nvmet_file_check_lba_range(req, le64_to_cpu(write_zeroes->slba), + len64, &offset)) { nvmet_req_complete(req, errno_to_nvme_status(req, -ENOSPC)); return; } + len = len64; ret = vfs_fallocate(req->ns->file, mode, offset, len); nvmet_req_complete(req, ret < 0 ? errno_to_nvme_status(req, ret) : 0); From 1193566c35ead643e954ff8356bb54b1cd78378a Mon Sep 17 00:00:00 2001 From: Martin Belanger Date: Thu, 12 Nov 2026 16:13:34 -0500 Subject: [PATCH 0656/2102] nvme-tcp: use an aligned buffer for the TLS record type The buffers that receive the TLS record type are char arrays. put_cmsg() and tls_get_record_type() access them as struct cmsghdr, which needs a stricter alignment than a char array has. Use a union with struct cmsghdr, sized with CMSG_SPACE(), as svc_tcp_recv_cmsg() and xs_tls_read_record() in sunrpc do. Fixes: 2837966ab2a8 ("nvme-tcp: control message handling for recvmsg()") Cc: stable@vger.kernel.org Signed-off-by: Martin Belanger Reviewed-by: Hannes Reinecke Signed-off-by: Keith Busch --- drivers/nvme/host/tcp.c | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/drivers/nvme/host/tcp.c b/drivers/nvme/host/tcp.c index 2587db92a3a24e..2be355315df290 100644 --- a/drivers/nvme/host/tcp.c +++ b/drivers/nvme/host/tcp.c @@ -77,6 +77,12 @@ MODULE_PARM_DESC(tls_handshake_timeout, /* TLS records read while waiting for the ICResp, the ICResp included */ #define NVME_TCP_ICRESP_MAX_RECORDS 8 +/* control message buffer for the TLS record type */ +union nvme_tcp_tls_cmsg { + struct cmsghdr cmsg; + u8 buf[CMSG_SPACE(sizeof(u8))]; +}; + static int nvme_tcp_cpu_queues[NR_CPUS]; static DEFINE_SPINLOCK(nvme_tcp_cpu_queues_lock); @@ -1653,11 +1659,11 @@ static int nvme_tcp_skip_tls_record(struct nvme_tcp_queue *queue, .iov_base = buf, .iov_len = sizeof(buf), }; - char cbuf[CMSG_LEN(sizeof(char))] = {}; + union nvme_tcp_tls_cmsg u = {}; /* kTLS fails a control record read without a cmsg buffer */ struct msghdr drain = { - .msg_control = cbuf, - .msg_controllen = sizeof(cbuf), + .msg_control = &u, + .msg_controllen = sizeof(u), }; ret = kernel_recvmsg(queue->sock, &drain, &iov, 1, sizeof(buf), @@ -1682,7 +1688,7 @@ static int nvme_tcp_skip_tls_record(struct nvme_tcp_queue *queue, static int nvme_tcp_recv_icresp(struct nvme_tcp_queue *queue, struct nvme_tcp_icresp_pdu *icresp) { - char cbuf[CMSG_LEN(sizeof(char))]; + union nvme_tcp_tls_cmsg u; struct msghdr msg; struct kvec iov; u8 ctype; @@ -1690,12 +1696,12 @@ static int nvme_tcp_recv_icresp(struct nvme_tcp_queue *queue, for (i = 0; i < NVME_TCP_ICRESP_MAX_RECORDS; i++) { memset(&msg, 0, sizeof(msg)); - memset(cbuf, 0, sizeof(cbuf)); + memset(&u, 0, sizeof(u)); iov.iov_base = icresp; iov.iov_len = sizeof(*icresp); if (nvme_tcp_queue_tls(queue)) { - msg.msg_control = cbuf; - msg.msg_controllen = sizeof(cbuf); + msg.msg_control = &u; + msg.msg_controllen = sizeof(u); } msg.msg_flags = MSG_WAITALL; ret = kernel_recvmsg(queue->sock, &msg, &iov, 1, @@ -1703,8 +1709,7 @@ static int nvme_tcp_recv_icresp(struct nvme_tcp_queue *queue, if (ret <= 0 || !nvme_tcp_queue_tls(queue)) return ret; - ctype = tls_get_record_type(queue->sock->sk, - (struct cmsghdr *)cbuf); + ctype = tls_get_record_type(queue->sock->sk, &u.cmsg); if (ctype == TLS_RECORD_TYPE_DATA) return ret; From 76afef5e29221e68f9a19df767f94b092c31e974 Mon Sep 17 00:00:00 2001 From: Martin Belanger Date: Thu, 12 Nov 2026 16:13:35 -0500 Subject: [PATCH 0657/2102] nvme-tcp: move the TLS record read loop into a helper Move the read loop out of nvme_tcp_skip_tls_record() into a new helper, nvme_tcp_drain_tls_record(). The next patch uses the helper to read TLS records that arrive on a live queue. No functional change. Cc: stable@vger.kernel.org Signed-off-by: Martin Belanger Reviewed-by: Hannes Reinecke Signed-off-by: Keith Busch --- drivers/nvme/host/tcp.c | 60 ++++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 22 deletions(-) diff --git a/drivers/nvme/host/tcp.c b/drivers/nvme/host/tcp.c index 2be355315df290..7ccb234b296a5f 100644 --- a/drivers/nvme/host/tcp.c +++ b/drivers/nvme/host/tcp.c @@ -1629,31 +1629,16 @@ static int nvme_tcp_recv_tls_alert(struct nvme_tcp_queue *queue, } /* - * Discard a TLS record that arrived in place of the ICResp. A peer may send - * a NewSessionTicket as soon as the handshake completes. + * Read the rest of a TLS record whose first part was read into @msg. * - * Returns 0 when the record was discarded and the ICResp can be read, or a - * negative errno if the connection cannot continue. + * Returns the bytes read, or a negative errno. */ -static int nvme_tcp_skip_tls_record(struct nvme_tcp_queue *queue, - struct msghdr *msg, u8 ctype, int len) +static int nvme_tcp_drain_tls_record(struct nvme_tcp_queue *queue, + struct msghdr *msg, int flags) { u8 buf[NVME_TCP_TLS_REC_CHUNK]; - int ret; + int ret, drained = 0; - switch (ctype) { - case TLS_RECORD_TYPE_HANDSHAKE: - break; - case TLS_RECORD_TYPE_ALERT: - ret = nvme_tcp_recv_tls_alert(queue, msg, len); - return ret ? : -ENOTCONN; - default: - pr_err("queue %d: unhandled TLS record %u\n", - nvme_tcp_queue_id(queue), ctype); - return -ENOTCONN; - } - - /* the ICResp is in a later record, drain this one first */ while (!(msg->msg_flags & MSG_EOR)) { struct kvec iov = { .iov_base = buf, @@ -1667,16 +1652,47 @@ static int nvme_tcp_skip_tls_record(struct nvme_tcp_queue *queue, }; ret = kernel_recvmsg(queue->sock, &drain, &iov, 1, sizeof(buf), - 0); + flags); if (ret <= 0) { pr_warn("queue %d: failed to drain TLS record: %d\n", nvme_tcp_queue_id(queue), ret); return ret ? : -ECONNRESET; } + drained += ret; msg->msg_flags = drain.msg_flags; } - return 0; + return drained; +} + +/* + * Discard a TLS record that arrived in place of the ICResp. A peer may send + * a NewSessionTicket as soon as the handshake completes. + * + * Returns 0 when the record was discarded and the ICResp can be read, or a + * negative errno if the connection cannot continue. + */ +static int nvme_tcp_skip_tls_record(struct nvme_tcp_queue *queue, + struct msghdr *msg, u8 ctype, int len) +{ + int ret; + + switch (ctype) { + case TLS_RECORD_TYPE_HANDSHAKE: + break; + case TLS_RECORD_TYPE_ALERT: + ret = nvme_tcp_recv_tls_alert(queue, msg, len); + return ret ? : -ENOTCONN; + default: + pr_err("queue %d: unhandled TLS record %u\n", + nvme_tcp_queue_id(queue), ctype); + return -ENOTCONN; + } + + /* the ICResp is in a later record, drain this one first */ + ret = nvme_tcp_drain_tls_record(queue, msg, 0); + + return ret < 0 ? ret : 0; } /* From 687e743e4089b2a854982b321cb2d681ae5d6136 Mon Sep 17 00:00:00 2001 From: Martin Belanger Date: Thu, 12 Nov 2026 16:13:36 -0500 Subject: [PATCH 0658/2102] nvme-tcp: consume TLS records without application data A peer may send a TLS record without application data at any time after the handshake: a NewSessionTicket, a KeyUpdate or an alert. tls_sw_read_sock() cannot pass such a record to nvme_tcp_recv_skb(). It returns -EINVAL and leaves the record at the head of the receive queue. nvme_tcp_try_recv() then starts error recovery, and the controller reconnects. TLS 1.3 allows a server to send a NewSessionTicket at any time after the handshake (RFC 8446, section 4.6.1). Alerts can also arrive at any time. On -EINVAL, read the record with recvmsg(), which reports the record type. Discard handshake messages other than KeyUpdate. Log alerts, and fail the queue on a fatal alert. Fail the queue on a KeyUpdate, which nvme-tcp cannot answer, and on any other record type. recvmsg() takes the socket lock, so release it around the read. Handle these records in one helper, also for the records that arrive ahead of the ICResp. A warning alert ahead of the ICResp no longer fails the connection. On a poll queue, nvme_tcp_poll() and nvme_tcp_io_work() can both see the record while the socket lock is released. A queue flag makes sure that only one of them reads it. svc_tcp_recvfrom() in sunrpc handles -EINVAL from read_sock() the same way. Fixes: be8e82caa685 ("nvme-tcp: enable TLS handshake upcall") Cc: stable@vger.kernel.org Signed-off-by: Martin Belanger Reviewed-by: Hannes Reinecke Signed-off-by: Keith Busch --- drivers/nvme/host/tcp.c | 113 ++++++++++++++++++++++++++++++++++------ 1 file changed, 97 insertions(+), 16 deletions(-) diff --git a/drivers/nvme/host/tcp.c b/drivers/nvme/host/tcp.c index 7ccb234b296a5f..34bd3a49f77804 100644 --- a/drivers/nvme/host/tcp.c +++ b/drivers/nvme/host/tcp.c @@ -123,6 +123,7 @@ enum nvme_tcp_queue_flags { NVME_TCP_Q_LIVE = 1, NVME_TCP_Q_POLLING = 2, NVME_TCP_Q_IO_CPU_SET = 3, + NVME_TCP_Q_TLS_RECORD = 4, }; #define NVME_TCP_OPT_NR_QUEUES(opts) ((opts)->nr_io_queues + \ @@ -1450,6 +1451,8 @@ static int nvme_tcp_try_send(struct nvme_tcp_queue *queue) return ret; } +static int nvme_tcp_recv_tls_record(struct nvme_tcp_queue *queue); + static int nvme_tcp_try_recv(struct nvme_tcp_queue *queue) { struct socket *sock = queue->sock; @@ -1462,10 +1465,31 @@ static int nvme_tcp_try_recv(struct nvme_tcp_queue *queue) lock_sock(sk); queue->nr_cqe = 0; consumed = sock->ops->read_sock(sk, &rd_desc, nvme_tcp_recv_skb); + /* + * kTLS cannot pass a TLS record without application data to + * nvme_tcp_recv_skb(). It returns -EINVAL and leaves the record at + * the head of the receive queue. recvmsg() takes the socket lock, + * so read the record without it. + */ + if (unlikely(consumed == -EINVAL && nvme_tcp_queue_tls(queue) && + queue->rd_enabled)) { + /* + * On a poll queue, nvme_tcp_poll() and nvme_tcp_io_work() can + * both get here for the same record. Only one of them reads it. + */ + if (test_and_set_bit(NVME_TCP_Q_TLS_RECORD, &queue->flags)) { + consumed = 0; + } else { + release_sock(sk); + consumed = nvme_tcp_recv_tls_record(queue); + lock_sock(sk); + clear_bit(NVME_TCP_Q_TLS_RECORD, &queue->flags); + } + } /* * nvme_tcp_recv_skb() handles its own errors, so a queue that is - * still enabled failed inside read_sock(). Handle it before - * release_sock() processes the backlog. + * still enabled failed inside read_sock() or while reading a TLS + * record. Handle it before release_sock() processes the backlog. */ if (unlikely(consumed < 0 && consumed != -EAGAIN && queue->rd_enabled)) { @@ -1666,33 +1690,88 @@ static int nvme_tcp_drain_tls_record(struct nvme_tcp_queue *queue, } /* - * Discard a TLS record that arrived in place of the ICResp. A peer may send - * a NewSessionTicket as soon as the handshake completes. + * Consume a TLS record without application data. The first @len bytes of + * the record were read into @msg and @data. * - * Returns 0 when the record was discarded and the ICResp can be read, or a - * negative errno if the connection cannot continue. + * A KeyUpdate needs new keys that nothing here can supply. Other handshake + * messages, such as a NewSessionTicket, are discarded. + * + * Returns the bytes read after the first @len, or a negative errno if the + * connection cannot continue. */ -static int nvme_tcp_skip_tls_record(struct nvme_tcp_queue *queue, - struct msghdr *msg, u8 ctype, int len) +static int nvme_tcp_consume_tls_record(struct nvme_tcp_queue *queue, + struct msghdr *msg, u8 ctype, + const u8 *data, int len, int flags) { int ret; switch (ctype) { case TLS_RECORD_TYPE_HANDSHAKE: + if (data[0] == TLS_HANDSHAKE_KEYUPDATE) { + dev_err(queue->ctrl->ctrl.device, + "queue %d: TLS KeyUpdate is not supported\n", + nvme_tcp_queue_id(queue)); + return -EKEYEXPIRED; + } break; case TLS_RECORD_TYPE_ALERT: ret = nvme_tcp_recv_tls_alert(queue, msg, len); - return ret ? : -ENOTCONN; + if (ret) + return ret; + break; default: - pr_err("queue %d: unhandled TLS record %u\n", - nvme_tcp_queue_id(queue), ctype); - return -ENOTCONN; + dev_err(queue->ctrl->ctrl.device, + "queue %d: unexpected TLS record %u\n", + nvme_tcp_queue_id(queue), ctype); + return -EPROTO; } - /* the ICResp is in a later record, drain this one first */ - ret = nvme_tcp_drain_tls_record(queue, msg, 0); + return nvme_tcp_drain_tls_record(queue, msg, flags); +} + +/* + * Read the TLS record that read_sock() could not pass to + * nvme_tcp_recv_skb(). The caller must not hold the socket lock. + * + * Returns the bytes consumed, or a negative errno if the connection cannot + * continue. + */ +static int nvme_tcp_recv_tls_record(struct nvme_tcp_queue *queue) +{ + u8 buf[NVME_TCP_TLS_REC_CHUNK]; + union nvme_tcp_tls_cmsg u = {}; + struct kvec iov = { + .iov_base = buf, + .iov_len = sizeof(buf), + }; + struct msghdr msg = { + .msg_control = &u, + .msg_controllen = sizeof(u), + }; + int len, ret; + u8 ctype; + + len = kernel_recvmsg(queue->sock, &msg, &iov, 1, sizeof(buf), + MSG_DONTWAIT); + if (len <= 0) + goto fail; + + ctype = tls_get_record_type(queue->sock->sk, &u.cmsg); + ret = nvme_tcp_consume_tls_record(queue, &msg, ctype, buf, len, + MSG_DONTWAIT); + if (ret < 0) { + len = ret; + goto fail; + } + + return len + ret; + +fail: + /* read_sock() left a whole record, so none of it can be missing */ + if (len == -EAGAIN) + return -EPROTO; - return ret < 0 ? ret : 0; + return len ? : -ECONNRESET; } /* @@ -1729,7 +1808,9 @@ static int nvme_tcp_recv_icresp(struct nvme_tcp_queue *queue, if (ctype == TLS_RECORD_TYPE_DATA) return ret; - ret = nvme_tcp_skip_tls_record(queue, &msg, ctype, ret); + /* the ICResp is in a later record */ + ret = nvme_tcp_consume_tls_record(queue, &msg, ctype, + (const u8 *)icresp, ret, 0); if (ret < 0) return ret; } From 62dae895f986f7459fea1deebd89a0bce76a886f Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Mon, 9 Nov 2026 22:59:21 +0800 Subject: [PATCH 0659/2102] nvmet-auth: store the DH-CHAP key offset instead of hardcoding it nvmet_auth_set_key() accepts variable-width hash identifiers, but nvmet_setup_auth() always skips ten bytes before extracting the key. For "DHHC-1:1:" this starts one byte past the allocated string's NUL terminator, causing an out-of-bounds read in nvme_auth_extract_key(). Other nonstandard prefix widths also select the wrong key bytes. Use %n to validate the complete prefix and record its actual length for both host and controller secrets. Keep the offsets as int, matching the scan result, so whitespace or leading zeroes in the hash identifier do not truncate the saved offset. Fixes: db1312dd9548 ("nvmet: implement basic In-Band Authentication") Cc: stable@vger.kernel.org Signed-off-by: Shao Mingyin Reviewed-by: Christoph Hellwig Signed-off-by: Keith Busch --- drivers/nvme/target/auth.c | 14 +++++++++++--- drivers/nvme/target/nvmet.h | 2 ++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/drivers/nvme/target/auth.c b/drivers/nvme/target/auth.c index 8ca5a061d56569..a4a2a5cfd823f9 100644 --- a/drivers/nvme/target/auth.c +++ b/drivers/nvme/target/auth.c @@ -24,6 +24,7 @@ int nvmet_auth_set_key(struct nvmet_host *host, const char *secret, { unsigned char key_hash; char *dhchap_secret; + int offset = 0; if (!strlen(secret)) { down_write(&nvmet_config_sem); @@ -31,15 +32,18 @@ int nvmet_auth_set_key(struct nvmet_host *host, const char *secret, kfree(host->dhchap_ctrl_secret); host->dhchap_ctrl_secret = NULL; host->dhchap_ctrl_key_hash = 0; + host->dhchap_ctrl_key_offset = 0; } else { kfree(host->dhchap_secret); host->dhchap_secret = NULL; host->dhchap_key_hash = 0; + host->dhchap_key_offset = 0; } up_write(&nvmet_config_sem); return 0; } - if (sscanf(secret, "DHHC-1:%hhd:%*s", &key_hash) != 1) + if (sscanf(secret, "DHHC-1:%hhd:%n", &key_hash, &offset) != 1 || + !offset) return -EINVAL; if (key_hash > 3) { pr_warn("Invalid DH-HMAC-CHAP hash id %d\n", @@ -54,10 +58,12 @@ int nvmet_auth_set_key(struct nvmet_host *host, const char *secret, kfree(host->dhchap_ctrl_secret); host->dhchap_ctrl_secret = strim(dhchap_secret); host->dhchap_ctrl_key_hash = key_hash; + host->dhchap_ctrl_key_offset = offset; } else { kfree(host->dhchap_secret); host->dhchap_secret = strim(dhchap_secret); host->dhchap_key_hash = key_hash; + host->dhchap_key_offset = offset; } up_write(&nvmet_config_sem); return 0; @@ -186,14 +192,16 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset) * Skip the 'DHHC-1:XX:' prefix. Keep the old keys until the new ones * are there: a controller without a host key needs no authentication. */ - host_key = nvme_auth_extract_key(host->dhchap_secret + 10, + host_key = nvme_auth_extract_key(host->dhchap_secret + + host->dhchap_key_offset, host->dhchap_key_hash); if (IS_ERR(host_key)) { ret = NVME_AUTH_DHCHAP_FAILURE_NOT_USABLE; goto out_unlock; } if (host->dhchap_ctrl_secret) { - ctrl_key = nvme_auth_extract_key(host->dhchap_ctrl_secret + 10, + ctrl_key = nvme_auth_extract_key(host->dhchap_ctrl_secret + + host->dhchap_ctrl_key_offset, host->dhchap_ctrl_key_hash); if (IS_ERR(ctrl_key)) { nvme_auth_free_key(host_key); diff --git a/drivers/nvme/target/nvmet.h b/drivers/nvme/target/nvmet.h index 2c2460ef5e2b74..e33884a81efc9f 100644 --- a/drivers/nvme/target/nvmet.h +++ b/drivers/nvme/target/nvmet.h @@ -401,6 +401,8 @@ struct nvmet_host { struct config_group group; u8 *dhchap_secret; u8 *dhchap_ctrl_secret; + int dhchap_key_offset; + int dhchap_ctrl_key_offset; u8 dhchap_key_hash; u8 dhchap_ctrl_key_hash; u8 dhchap_hash_id; From f2937481c28033e10e8a29b8742a767e73c696df Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Sat, 14 Nov 2026 02:02:47 +0800 Subject: [PATCH 0660/2102] nvme-loop: release the target request when SG setup fails nvme_loop_queue_rq() calls nvmet_req_init(), which takes a reference on the submission queue percpu ref, pins the namespace and, for a reservation-enabled namespace, takes a per-controller PR reference. If sg_alloc_table_chained() then fails under memory pressure, the function returns BLK_STS_RESOURCE without calling nvmet_req_uninit(). blk-mq retries the same request and nvmet_req_init() overwrites req->ns and req->pc_ref, leaking the queue, namespace and PR references taken by the failed attempt each time this happens. Release the request before returning BLK_STS_RESOURCE. Fixes: 3a85a5de29ea ("nvme-loop: add a NVMe loopback host driver") Cc: stable@vger.kernel.org Reviewed-by: Christoph Hellwig Signed-off-by: Shao Mingyin Signed-off-by: Keith Busch --- drivers/nvme/target/loop.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/nvme/target/loop.c b/drivers/nvme/target/loop.c index 80b67608eb155e..d04be1f41d5229 100644 --- a/drivers/nvme/target/loop.c +++ b/drivers/nvme/target/loop.c @@ -159,6 +159,7 @@ static blk_status_t nvme_loop_queue_rq(struct blk_mq_hw_ctx *hctx, blk_rq_nr_phys_segments(req), iod->sg_table.sgl, NVME_INLINE_SG_CNT)) { nvme_cleanup_cmd(req); + nvmet_req_uninit(&iod->req); return BLK_STS_RESOURCE; } From 9dac3b1aa2a99e126a5504b7f5bc781c8b2771e0 Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Sat, 14 Nov 2026 02:02:49 +0800 Subject: [PATCH 0661/2102] nvmet-tcp: only wait for in-capsule data for inline SGLs nvmet-tcp decides whether to wait for in-capsule data using only the write direction and SGL length. A write using a transport SGL can fit within inline_data_size without carrying any in-capsule data. The response path then withholds its R2T, leaving the command stuck. If request initialization fails, the same length-only test both withholds the error response and attempts to drain inline data that will never arrive. This can also consume the following PDU as data or a digest. Require an offset data-block SGL in both checks. Share a helper that only uses command and port fields, as the completion callback can run before nvmet_req_init() has finished. Fixes: bdaf13279192 ("nvmet-tcp: fix a segmentation fault during io parsing error") Fixes: 872d26a391da ("nvmet-tcp: add NVMe over TCP target driver") Cc: stable@vger.kernel.org Signed-off-by: Shao Mingyin Signed-off-by: Keith Busch --- drivers/nvme/target/tcp.c | 42 +++++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/drivers/nvme/target/tcp.c b/drivers/nvme/target/tcp.c index 5105317cc61e3c..8a2e0e056131b3 100644 --- a/drivers/nvme/target/tcp.c +++ b/drivers/nvme/target/tcp.c @@ -270,6 +270,30 @@ static inline bool nvmet_tcp_has_inline_data(struct nvmet_tcp_cmd *cmd) !cmd->rbytes_done; } +/* + * Check whether the SGL of @cmd carries in-capsule data that the host + * will send right after the command PDU. Only the offset form of the + * data block descriptor is in-capsule; a regular transport SGL is + * fetched through an R2T instead. + */ +static inline bool nvmet_tcp_sgl_is_inline(struct nvmet_tcp_cmd *cmd) +{ + struct nvme_sgl_desc *sgl = &cmd->req.cmd->common.dptr.sgl; + u32 len = le32_to_cpu(sgl->length); + + if (sgl->type != ((NVME_SGL_FMT_DATA_DESC << 4) | + NVME_SGL_FMT_OFFSET)) + return false; + + if (!nvme_is_write(cmd->req.cmd)) + return false; + + if (!len) + return false; + + return len <= cmd->req.port->inline_data_size; +} + static inline struct nvmet_tcp_cmd * nvmet_tcp_get_cmd(struct nvmet_tcp_queue *queue) { @@ -626,25 +650,19 @@ static void nvmet_tcp_queue_response(struct nvmet_req *req) struct nvmet_tcp_queue *queue = cmd->queue; enum nvmet_tcp_recv_state queue_state; struct nvmet_tcp_cmd *queue_cmd; - struct nvme_sgl_desc *sgl; - u32 len; /* Pairs with store_release in nvmet_prepare_receive_pdu() */ queue_state = smp_load_acquire(&queue->rcv_state); queue_cmd = READ_ONCE(queue->cmd); if (unlikely(cmd == queue_cmd)) { - sgl = &cmd->req.cmd->common.dptr.sgl; - len = le32_to_cpu(sgl->length); - /* - * Wait for inline data before processing the response. - * Avoid using helpers, this might happen before - * nvmet_req_init is completed. + * Wait for in-capsule data before processing the response. + * This can happen before nvmet_req_init() has completed, so + * only look at the SGL descriptor itself. */ if (queue_state == NVMET_TCP_RECV_PDU && - len && len <= cmd->req.port->inline_data_size && - nvme_is_write(cmd->req.cmd)) + nvmet_tcp_sgl_is_inline(cmd)) return; } @@ -982,7 +1000,6 @@ static int nvmet_tcp_handle_icreq(struct nvmet_tcp_queue *queue) static int nvmet_tcp_handle_req_failure(struct nvmet_tcp_queue *queue, struct nvmet_tcp_cmd *cmd, struct nvmet_req *req) { - size_t data_len = le32_to_cpu(req->cmd->common.dptr.sgl.length); int ret; /* @@ -992,8 +1009,7 @@ static int nvmet_tcp_handle_req_failure(struct nvmet_tcp_queue *queue, * otherwise we will need to prepare a buffer and receive the * stale data before continuing forward. */ - if (!nvme_is_write(cmd->req.cmd) || !data_len || - data_len > cmd->req.port->inline_data_size) { + if (!nvmet_tcp_sgl_is_inline(cmd)) { nvmet_prepare_receive_pdu(queue); return 0; } From 347d50d92e25d4b9c50c5f5c1d8b727b9c88d12c Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Sat, 14 Nov 2026 02:02:50 +0800 Subject: [PATCH 0662/2102] nvme-tcp: require the R2T offset to match the data sent nvme_tcp_handle_r2t() rejects offsets below data_sent but accepts larger offsets. The send iterator still points at data_sent, so the next H2CData PDU carries bytes from that position while advertising the larger offset. A target that accepts the PDU can place the data at the wrong position; the Linux target rejects it and fails the connection. Require the R2T offset to equal data_sent, rejecting the invalid request before transmitting data with a mismatched offset. Fixes: 3f2304f8c6d6 ("nvme-tcp: add NVMe over TCP host driver") Cc: stable@vger.kernel.org Reviewed-by: Christoph Hellwig Signed-off-by: Shao Mingyin Signed-off-by: Keith Busch --- drivers/nvme/host/tcp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/nvme/host/tcp.c b/drivers/nvme/host/tcp.c index 34bd3a49f77804..62a594b8ab9bfa 100644 --- a/drivers/nvme/host/tcp.c +++ b/drivers/nvme/host/tcp.c @@ -854,7 +854,7 @@ static int nvme_tcp_handle_r2t(struct nvme_tcp_queue *queue, return -EPROTO; } - if (unlikely(r2t_offset < req->data_sent)) { + if (unlikely(r2t_offset != req->data_sent)) { dev_err(queue->ctrl->ctrl.device, "req %d unexpected r2t offset %u (expected %zu)\n", rq->tag, r2t_offset, req->data_sent); From 8c1f99419b6cc51892e259497c8e10a5d079621a Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Sat, 14 Nov 2026 02:02:53 +0800 Subject: [PATCH 0663/2102] nvmet-fcloop: free the LS request when delivery fails fcloop_h2t_ls_req() allocates a fcloop_lsreq from lsreq_cache and hands it to nvmet_fc_rcv_ls_req(). That function only takes ownership on success and returns an error without invoking any completion callback when the target port is shutting down, the LS payload is too large, or the target has no free LS request slot. The error is returned as-is, so the fcloop_lsreq is leaked; every failed LS during a target port teardown or an LS slot exhaustion loses one slab object. The target-to-host direction already frees the request when nvme_fc_rcv_ls_req() fails. Do the same here. Fixes: 772042dd38ee ("nvmet-fcloop: allocate/free fcloop_lsreq directly") Cc: stable@vger.kernel.org Reviewed-by: Christoph Hellwig Signed-off-by: Shao Mingyin Signed-off-by: Keith Busch --- drivers/nvme/target/fcloop.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/nvme/target/fcloop.c b/drivers/nvme/target/fcloop.c index b63af3b643a648..a9cde536c33ba1 100644 --- a/drivers/nvme/target/fcloop.c +++ b/drivers/nvme/target/fcloop.c @@ -379,6 +379,8 @@ fcloop_h2t_ls_req(struct nvme_fc_local_port *localport, ret = nvmet_fc_rcv_ls_req(rport->targetport, rport, &tls_req->ls_rsp, lsreq->rqstaddr, lsreq->rqstlen); + if (ret) + kmem_cache_free(lsreq_cache, tls_req); return ret; } From 153eac284ebf68be74993643e9b2fe2f9b2b1d88 Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Sat, 14 Nov 2026 02:02:55 +0800 Subject: [PATCH 0664/2102] nvmet-fc: reject duplicate queue IDs on Create Connection nvmet_fc_alloc_target_queue() stores the new queue with WARN_ON(assoc->queues[qid]); assoc->queues[qid] = queue; The queue ID comes straight from the Create Connection LS and is only checked against NVMET_NR_QUEUES. A remote initiator can send a second Create Connection for a queue ID that already exists, or send queue ID 0 which was already created as the admin queue by Create Association. The WARN fires and the old pointer is overwritten: the old queue's base reference is never put, so its workqueue, nvmet_sq and nvmet_cq are never released. For the admin queue this also leaves the controller reference unreachable from nvmet_fc_delete_target_assoc(), so the controller and its subsystem reference leak permanently. Publish the queue with cmpxchg() and destroy the newly created queue if the slot is already taken, returning the normal queue allocation error to the initiator. This keeps the existing error path and makes both duplicate and admin queue IDs fail cleanly. Fixes: c53432030d86 ("nvme-fabrics: Add target support for FC transport") Cc: stable@vger.kernel.org Reviewed-by: Christoph Hellwig Signed-off-by: Shao Mingyin Signed-off-by: Keith Busch --- drivers/nvme/target/fc.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/drivers/nvme/target/fc.c b/drivers/nvme/target/fc.c index bccfbaea6dfcb9..5d6c1c79508af0 100644 --- a/drivers/nvme/target/fc.c +++ b/drivers/nvme/target/fc.c @@ -816,8 +816,17 @@ nvmet_fc_alloc_target_queue(struct nvmet_fc_tgt_assoc *assoc, if (ret) goto out_fail_iodlist; - WARN_ON(assoc->queues[qid]); - assoc->queues[qid] = queue; + /* + * Publish the queue only if the slot is still free. A Create + * Connection may arrive twice for the same queue ID, or with the + * admin queue ID that was created by Create Association; replacing + * the old pointer would leak that queue and its controller + * reference forever. + */ + if (cmpxchg(&assoc->queues[qid], NULL, queue)) { + nvmet_sq_destroy(&queue->nvme_sq); + goto out_fail_iodlist; + } return queue; From 3f82752e089283eb8204b9d2ebd8246077031173 Mon Sep 17 00:00:00 2001 From: Shao Mingyin Date: Sat, 14 Nov 2026 02:02:58 +0800 Subject: [PATCH 0665/2102] nvmet: roll back queue bindings on connection failure nvmet_install_queue() publishes the SQ controller pointer before claiming the CQ. If the CQ is already connected, it leaves the SQ pointer and the controller reference taken for it behind on failure. An install_queue() callback failure also leaves the CQ bound after clearing the SQ pointer. The reference taken in nvmet_install_queue() is in addition to the one the caller already holds: the caller's put releases the reference acquired before the call, while this one belongs to the CQ binding. It is not released on this path, so the controller stays alive and a Connect retry on the same queue keeps finding the stale binding. Clear the tentative SQ binding and release the extra reference on a CQ conflict. On a transport installation failure, destroy the CQ binding as well, so its controller table entry and reference are released. Link: https://lore.kernel.org/all/20261106015842.3534898-6-kanie@linux.alibaba.com/ Fixes: bb78836b3a7c ("nvmet: fabrics: add CQ init and destroy") Cc: stable@vger.kernel.org Reviewed-by: Christoph Hellwig Signed-off-by: Shao Mingyin Signed-off-by: Keith Busch --- drivers/nvme/target/fabrics-cmd.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/nvme/target/fabrics-cmd.c b/drivers/nvme/target/fabrics-cmd.c index fc626c2fd2c924..6f0fc695e64992 100644 --- a/drivers/nvme/target/fabrics-cmd.c +++ b/drivers/nvme/target/fabrics-cmd.c @@ -216,6 +216,8 @@ static u16 nvmet_install_queue(struct nvmet_ctrl *ctrl, struct nvmet_req *req) if (old) { pr_warn("queue already connected!\n"); req->error_loc = offsetof(struct nvmf_connect_command, opcode); + req->sq->ctrl = NULL; + nvmet_ctrl_put(ctrl); return NVME_SC_CONNECT_CTRL_BUSY | NVME_STATUS_DNR; } @@ -242,6 +244,7 @@ static u16 nvmet_install_queue(struct nvmet_ctrl *ctrl, struct nvmet_req *req) err: req->sq->ctrl = NULL; + nvmet_cq_destroy(req->cq); return ret; } From 7fce38923253c27650835c91201b222214aeb149 Mon Sep 17 00:00:00 2001 From: Martin George Date: Mon, 16 Nov 2026 15:32:43 +0530 Subject: [PATCH 0666/2102] nvme-sysfs: use kfree_sensitive() for DH-HMAC-CHAP secrets dhchap_secret_store() and dhchap_ctrl_secret_store() free the raw "DHHC-1:..." secret with plain kfree(), leaving it in the freed slab. As these are the runtime rotation handlers, every secret change also leaves the previous secret behind. Free them with kfree_sensitive() instead. Signed-off-by: Martin George Reviewed-by: Hannes Reinecke Signed-off-by: Keith Busch --- drivers/nvme/host/sysfs.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/drivers/nvme/host/sysfs.c b/drivers/nvme/host/sysfs.c index 9672ca3f74d2e8..35f871e3e0c0ae 100644 --- a/drivers/nvme/host/sysfs.c +++ b/drivers/nvme/host/sysfs.c @@ -850,10 +850,10 @@ static ssize_t dhchap_secret_store(struct device *dev, ret = nvme_auth_parse_key(dhchap_secret, &key); if (ret) { - kfree(dhchap_secret); + kfree_sensitive(dhchap_secret); return ret; } - kfree(opts->dhchap_secret); + kfree_sensitive(opts->dhchap_secret); opts->dhchap_secret = dhchap_secret; host_key = ctrl->host_key; mutex_lock(&ctrl->dhchap_auth_mutex); @@ -861,7 +861,7 @@ static ssize_t dhchap_secret_store(struct device *dev, mutex_unlock(&ctrl->dhchap_auth_mutex); nvme_auth_free_key(host_key); } else - kfree(dhchap_secret); + kfree_sensitive(dhchap_secret); /* Start re-authentication */ dev_info(ctrl->device, "re-authenticating controller\n"); queue_work(nvme_wq, &ctrl->dhchap_auth_work); @@ -907,10 +907,10 @@ static ssize_t dhchap_ctrl_secret_store(struct device *dev, ret = nvme_auth_parse_key(dhchap_secret, &key); if (ret) { - kfree(dhchap_secret); + kfree_sensitive(dhchap_secret); return ret; } - kfree(opts->dhchap_ctrl_secret); + kfree_sensitive(opts->dhchap_ctrl_secret); opts->dhchap_ctrl_secret = dhchap_secret; ctrl_key = ctrl->ctrl_key; mutex_lock(&ctrl->dhchap_auth_mutex); @@ -918,7 +918,7 @@ static ssize_t dhchap_ctrl_secret_store(struct device *dev, mutex_unlock(&ctrl->dhchap_auth_mutex); nvme_auth_free_key(ctrl_key); } else - kfree(dhchap_secret); + kfree_sensitive(dhchap_secret); /* Start re-authentication */ dev_info(ctrl->device, "re-authenticating controller\n"); queue_work(nvme_wq, &ctrl->dhchap_auth_work); From 68099cf27253a8c89d703a282d3d811446d9453b Mon Sep 17 00:00:00 2001 From: Martin George Date: Mon, 16 Nov 2026 15:32:44 +0530 Subject: [PATCH 0667/2102] nvme-fabrics: use kfree_sensitive() for the old DH-HMAC-CHAP secret When a connect string overrides dhchap_secret or dhchap_ctrl_secret, nvmf_parse_options() frees the previous raw secret with plain kfree(). The invalid-input path already uses kfree_sensitive(), so do the same for the replaced secret. Signed-off-by: Martin George Reviewed-by: Hannes Reinecke Signed-off-by: Keith Busch --- drivers/nvme/host/fabrics.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/nvme/host/fabrics.c b/drivers/nvme/host/fabrics.c index c262538523fb61..5ed91557f07065 100644 --- a/drivers/nvme/host/fabrics.c +++ b/drivers/nvme/host/fabrics.c @@ -1026,7 +1026,7 @@ static int nvmf_parse_options(struct nvmf_ctrl_options *opts, ret = -EINVAL; goto out; } - kfree(opts->dhchap_secret); + kfree_sensitive(opts->dhchap_secret); opts->dhchap_secret = p; break; case NVMF_OPT_DHCHAP_CTRL_SECRET: @@ -1041,7 +1041,7 @@ static int nvmf_parse_options(struct nvmf_ctrl_options *opts, ret = -EINVAL; goto out; } - kfree(opts->dhchap_ctrl_secret); + kfree_sensitive(opts->dhchap_ctrl_secret); opts->dhchap_ctrl_secret = p; break; case NVMF_OPT_TLS: From 9016b8b9e80d3d340b4ad83d457501e944834538 Mon Sep 17 00:00:00 2001 From: Nick Spooner Date: Fri, 13 Nov 2026 08:19:29 -0700 Subject: [PATCH 0668/2102] ata: libata-scsi: fix REQUESTED MAX LBA field for REMOVE ELEMENT AND TRUNCATE ata_scsi_remove_element_and_truncate_xlat() copies the REQUESTED CAPACITY field, req_capacity, to REQUESTED MAX LBA for every block count except 1. However, SAT-6 specifies that if REQUESTED CAPACITY is greater than one, the REQUESTED MAX LBA shall be set to REQUESTED CAPACITY minus one, since the max LBA = count - 1 (see SAT-6 rev2, 9.16.1, Table 74). For example, if a capacity C > 1 is requested, the capacity ends up one block larger if the drive can provide C + 1. If the drive can provide C but not C + 1, a request that should be valid is instead rejected with INVALID FIELD IN CDB (see ACS-5 rev10, 7.33.3.3). Modify ata_scsi_remove_element_and_truncate_xlat() to decrement req_capacity, except when equal to 1 or 0 (rejected if 1, let the device choose if 0). Tested by issuing sg_rem_rest_elem on a Seagate drive ST32000NM001F, firmware db02 and checking the taskfile. Fixes: db496721cb0d ("ata: libata-scsi: add support for the REMOVE ELEMENT AND TRUNCATE command") Cc: stable@vger.kernel.org Signed-off-by: Nick Spooner Link: https://lore.kernel.org/r/20261113151929.9586-1-nicholas.spooner@seagate.com Signed-off-by: Niklas Cassel --- drivers/ata/libata-scsi.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/ata/libata-scsi.c b/drivers/ata/libata-scsi.c index 87a57495d2e4bf..20ea1c997d56b3 100644 --- a/drivers/ata/libata-scsi.c +++ b/drivers/ata/libata-scsi.c @@ -4991,6 +4991,9 @@ ata_scsi_remove_element_and_truncate_xlat(struct ata_queued_cmd *qc) return 1; } + if (req_capacity > 1) + req_capacity--; + id = get_unaligned_be32(&cdb[10]); tf->protocol = ATA_PROT_NODATA; From 76248359ac32e97cd7d1bd55a4c94a2ad4009871 Mon Sep 17 00:00:00 2001 From: Piyus Kedia Date: Thu, 12 Nov 2026 23:08:12 +0530 Subject: [PATCH 0669/2102] Bluetooth: L2CAP: clear the SDU before the receive callback l2cap_ecred_data_rcv() completes a reassembled SDU by calling l2cap_ecred_recv() with chan->sdu still set, and only clears the reassembly state after it returns: if (chan->sdu->len == chan->sdu_len) { err = l2cap_ecred_recv(chan, chan->sdu); if (!err) { chan->sdu = NULL; ... l2cap_ecred_recv() hands the SDU to the channel's receive callback, which takes ownership of it on success, and then updates the credits: err = chan->ops->recv(chan, skb); ... l2cap_chan_le_send_credits(chan); l2cap_chan_le_send_credits() calls l2cap_le_rx_credits(), which reads size_t sdu_len = chan->sdu ? chan->sdu->len : 0; so between the callback consuming the skb and the assignment above, chan->sdu is a dangling pointer that is dereferenced. For the 6LoWPAN channel the callback frees the skb outright - chan_recv_cb() -> recv_pkt() ends in consume_skb(skb) and returns NET_RX_SUCCESS - so the read is a straightforward use-after-free that KASAN reports: BUG: KASAN: slab-use-after-free in l2cap_le_rx_credits net/bluetooth/l2cap_core.c:576 [inline] BUG: KASAN: slab-use-after-free in l2cap_chan_le_send_credits+0xa8/0x3e0 net/bluetooth/l2cap_core.c:6811 Read of size 4 at addr ffff88800e134070 by task kworker/u21:2/11352 Workqueue: hci0 hci_rx_work l2cap_le_rx_credits net/bluetooth/l2cap_core.c:576 [inline] l2cap_chan_le_send_credits+0xa8/0x3e0 net/bluetooth/l2cap_core.c:6811 l2cap_ecred_recv+0x63/0x120 net/bluetooth/l2cap_core.c:6873 l2cap_ecred_data_rcv net/bluetooth/l2cap_core.c:6976 [inline] l2cap_data_channel net/bluetooth/l2cap_core.c:7028 [inline] l2cap_recv_frame+0x6c3c/0x9650 net/bluetooth/l2cap_core.c:7162 l2cap_recv_acldata+0x6fd/0xe60 net/bluetooth/l2cap_core.c:7902 hci_acldata_packet net/bluetooth/hci_core.c:3865 [inline] hci_rx_work+0x3c0/0xbe0 net/bluetooth/hci_core.c:4092 Freed by task 11352: recv_pkt net/bluetooth/6lowpan.c chan_recv_cb+0x88/0x150 net/bluetooth/6lowpan.c:367 l2cap_ecred_recv+0x61/0x160 net/bluetooth/l2cap_core.c:6864 The buggy address belongs to the object at ffff88800e134000 which belongs to the cache skbuff_head_cache of size 240 The buggy address is located 112 bytes inside of freed 240-byte region Offset 112 is sk_buff.len. Only a multi-frame SDU is affected: the single-frame path already calls l2cap_ecred_recv() with chan->sdu NULL, so l2cap_le_rx_credits() reads a zero sdu_len there. l2cap_reassemble_sdu() completes a segmented SDU the same way and has the same defect. On an ERTM or streaming channel l2cap_sock_recv_cb() calls l2cap_publish_rx_avail(), which reaches l2cap_chan_le_send_credits() through l2cap_chan_rx_avail(), and that function evaluates u16 return_credits = l2cap_le_rx_credits(chan); in its initializer - before the mode test that makes the rest of it a no-op for a non-LE channel. So chan->sdu is dereferenced on that path too, and the result is discarded. What makes it a use-after-free rather than a stale read is a consumer that frees the skb from another thread: BNEP's session kthread takes it off the socket with a lockless skb_dequeue() (net/bluetooth/bnep/core.c:530, freed at :533) and never takes the socket lock, so lock_sock() is no defence. Fix both sites. Clear the reassembly state before handing the SDU to the callback, which makes the fragmented path behave like the single-frame one, and free the SDU on the spot if the callback refused it - the error path's kfree_skb(chan->sdu) used to do that, and the callbacks leave the skb to the caller when they fail. Clearing it first is also the arithmetically correct input, not merely a safe one. l2cap_le_rx_credits() subtracts sdu_len from chan->rx_avail because a partially reassembled SDU will claim that much receive buffer once it completes: if (chan->rx_avail <= sdu_len) return 0; return DIV_ROUND_UP(chan->rx_avail - sdu_len, chan->mps); A completed SDU is no longer waiting for that space. If the callback queued it, l2cap_sock_recv_cb() has already called l2cap_publish_rx_avail(), which recomputes rx_avail from sk_rcvbuf - sk_rmem_alloc with that skb included in sk_rmem_alloc; if the callback consumed it, as the 6LoWPAN one does, it occupies nothing at all. Either way the reassembly buffer is empty, so zero is the right sdu_len, and a NULL chan->sdu is how l2cap_le_rx_credits() expresses that - the same value l2cap_le_flowctl_init() depends on when it seeds chan->rx_credits on an idle channel. Carrying the old length into the calculation instead would subtract the SDU a second time and under-grant credits on every delivery, and once rx_avail fell to the size of one SDU the channel would be granted none at all. Per Documentation/process/generated-content.rst: the use-after-free was found by an AI-driven fuzzing harness built on syzkaller, developed jointly by Kapil Vaswani and myself, which drove a virtual HCI controller and a 6LoWPAN channel under KASAN on x86_64. The root-cause analysis, this changelog and the patch were written with the assistance of a large language model over an extended session, and reviewed by hand; the before/after testing below the --- was run by us. Fixes: ce60b9231b66 ("Bluetooth: compute LE flow credits based on recvbuf space") Signed-off-by: Kapil Vaswani Signed-off-by: Piyus Kedia Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/l2cap_core.c | 53 ++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/net/bluetooth/l2cap_core.c b/net/bluetooth/l2cap_core.c index 486b968143d3cc..4ee1e62ded7ed8 100644 --- a/net/bluetooth/l2cap_core.c +++ b/net/bluetooth/l2cap_core.c @@ -6226,6 +6226,7 @@ static void append_skb_frag(struct sk_buff *skb, struct sk_buff *new_frag, static int l2cap_reassemble_sdu(struct l2cap_chan *chan, struct sk_buff *skb, struct l2cap_ctrl *control) { + struct sk_buff *sdu; int err = -EINVAL; switch (control->sar) { @@ -6286,15 +6287,25 @@ static int l2cap_reassemble_sdu(struct l2cap_chan *chan, struct sk_buff *skb, if (chan->sdu->len != chan->sdu_len) break; - err = chan->ops->recv(chan, chan->sdu); + /* Reassembly complete. Hand the SDU over before the + * callback, for the reason given in l2cap_ecred_data_rcv(): + * the callback takes ownership and may free it, while + * l2cap_chan_rx_avail() -> l2cap_chan_le_send_credits() reads + * chan->sdu->len on the way out - it does so before the mode + * test that makes the rest of that function a no-op here. + * Return directly, since the state this leaves is what the + * trailing error block would otherwise set again. + */ + sdu = chan->sdu; + chan->sdu = NULL; + chan->sdu_last_frag = NULL; + chan->sdu_len = 0; - if (!err) { - /* Reassembly complete */ - chan->sdu = NULL; - chan->sdu_last_frag = NULL; - chan->sdu_len = 0; - } - break; + err = chan->ops->recv(chan, sdu); + if (err) + kfree_skb(sdu); + + return err; } if (err) { @@ -7285,12 +7296,26 @@ static int l2cap_ecred_data_rcv(struct l2cap_chan *chan, struct sk_buff *skb) skb = NULL; if (chan->sdu->len == chan->sdu_len) { - err = l2cap_ecred_recv(chan, chan->sdu); - if (!err) { - chan->sdu = NULL; - chan->sdu_last_frag = NULL; - chan->sdu_len = 0; - } + struct sk_buff *sdu = chan->sdu; + + /* The receive callback takes ownership of a reassembled SDU and + * may free it, while l2cap_ecred_recv() goes on to update the + * credits - which reads chan->sdu->len. Drop the reassembly + * state before handing the SDU over, and release it here if the + * callback refused it, so that it is still freed exactly once. + * The reassembly state is already clear at that point, so + * return instead of falling into the failed: block, whose + * kfree_skb(chan->sdu) would have nothing left to free. + */ + chan->sdu = NULL; + chan->sdu_last_frag = NULL; + chan->sdu_len = 0; + + err = l2cap_ecred_recv(chan, sdu); + if (err) + kfree_skb(sdu); + + return 0; } failed: From 0d8f6981f55e28d8fac703bbd0e29bd9496c8b5b Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Fri, 13 Nov 2026 11:15:44 -0500 Subject: [PATCH 0670/2102] Bluetooth: 6lowpan: Always consume the skb in chan_recv_cb The l2cap_chan_ops recv callback takes ownership of the skb on success and leaves it to the caller on failure. chan_recv_cb() violates this: when recv_pkt() fails it returns -EAGAIN even though skb_share_check() may already have dropped the caller's reference to a shared skb and replaced it with a clone. The L2CAP caller then calls kfree_skb() on the original skb, over-releasing it, while the clone is leaked. Make recv_pkt() free the skb on its drop path and have chan_recv_cb() always consume the skb and return 0, including the lookup failures, so the caller never frees it again. A dropped packet is accounted in rx_dropped and no longer reported as a receive error to L2CAP. Fixes: 11e3ff707278 ("6lowpan: Use skb_cow in IPHC decompression.") Assisted-by: OpenCode:claude-sonnet-5.5 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/6lowpan.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/net/bluetooth/6lowpan.c b/net/bluetooth/6lowpan.c index 8c51c20f6c4b13..68ca2f49dadc9b 100644 --- a/net/bluetooth/6lowpan.c +++ b/net/bluetooth/6lowpan.c @@ -345,6 +345,7 @@ static int recv_pkt(struct sk_buff *skb, struct net_device *dev, return NET_RX_SUCCESS; drop: + kfree_skb(skb); dev->stats.rx_dropped++; return NET_RX_DROP; } @@ -356,21 +357,26 @@ static int chan_recv_cb(struct l2cap_chan *chan, struct sk_buff *skb) struct lowpan_peer *peer; int err; + /* The skb is always consumed, so never return an error that would + * make the caller free it again. + */ peer = lookup_peer(chan->conn); if (!peer) - return -ENOENT; + goto drop; dev = lookup_dev(chan->conn); if (!dev || !dev->netdev) - return -ENOENT; + goto drop; err = recv_pkt(skb, dev->netdev, peer); - if (err) { + if (err) BT_DBG("recv pkt %d", err); - err = -EAGAIN; - } - return err; + return 0; + +drop: + kfree_skb(skb); + return 0; } static int setup_header(struct sk_buff *skb, struct net_device *netdev, From 43ec31efbc92b2ffa2f707b04acc6d7a6173c728 Mon Sep 17 00:00:00 2001 From: Heiko Stuebner Date: Tue, 10 Nov 2026 11:15:53 +0100 Subject: [PATCH 0671/2102] MAINTAINERS: Add two reviewers to the Rockchip DRM entry Chaoyi Chen and Damon Ding volunteered to become reviewers for the Rockchip DRM drivers, so add them to the MAINTAINERS entry. Reviewed-by: Chaoyi Chen Reviewed-by: Damon Ding Signed-off-by: Heiko Stuebner Link: https://patch.msgid.link/20261110101554.1809467-1-heiko@sntech.de --- MAINTAINERS | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index fee86f9d845761..3eaba09ac3c6fa 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -9140,6 +9140,8 @@ DRM DRIVERS FOR ROCKCHIP M: Sandy Huang M: Heiko Stübner M: Andy Yan +R: Chaoyi Chen +R: Damon Ding L: dri-devel@lists.freedesktop.org L: linux-rockchip@lists.infradead.org S: Maintained From 06069d6d650dbef746eb933e2f4fbfc686b6d330 Mon Sep 17 00:00:00 2001 From: Zack Rusin Date: Wed, 11 Nov 2026 13:41:45 -0500 Subject: [PATCH 0672/2102] drm/vmwgfx: validate command body sizes before parsing vmw_cmd_check verifies that a command's declared size fits in the submitted buffer, but handlers can access fields beyond the declared body. A truncated body can therefore cause relocations to target the next command. Applying those relocations after validation can change an already validated command ID and bypass command restrictions. Legacy query conversion can also overwrite the next command, while texture-state parsing can access fields beyond a truncated final record. Check each handler's minimum body size before accessing command fields. Use the common prefix for shared handlers to preserve shorter command variants, and reject texture-state arrays containing incomplete records. Fixes: fb1d9738ca05 ("drm/vmwgfx: Add DRM driver for VMware Virtual GPU") Cc: stable@vger.kernel.org Signed-off-by: Zack Rusin Reviewed-by: Maaz Mombasawala Link: https://patch.msgid.link/20261111193836.3161904-1-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c | 200 ++++++++++++++++++++++++ 1 file changed, 200 insertions(+) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c b/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c index a9136a6523cbac..7b943e99061e6f 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c @@ -564,6 +564,29 @@ static int vmw_cmd_ok(struct vmw_private *dev_priv, return 0; } +/** + * vmw_cmd_body_fits - Check that a command body covers what a handler reads + * + * @header: Pointer to the command header in the command stream. + * @size: Number of body bytes that the command handler interprets. + * + * vmw_cmd_check() only verifies that @header->size fits into the submitted + * command buffer. A handler that reads past the declared body reads the next + * command, which is verified separately. A relocation recorded there would + * rewrite the already verified command after verification has finished. + * + * Return: true if the body is at least @size bytes, false otherwise. + */ +static bool vmw_cmd_body_fits(const SVGA3dCmdHeader *header, size_t size) +{ + if (likely(header->size >= size)) + return true; + + VMW_DEBUG_USER("SVGA3D command %u: body size %u is smaller than %zu.\n", + header->id, header->size, size); + return false; +} + /** * vmw_resources_reserve - Reserve all resources on the sw_context's resource * list. @@ -810,6 +833,9 @@ static int vmw_cmd_cid_check(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, uint32_t) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, &cmd->body, NULL); @@ -853,6 +879,8 @@ static int vmw_cmd_set_render_target_check(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; if (cmd->body.type >= SVGA3D_RT_MAX) { VMW_DEBUG_USER("Illegal render target type %u.\n", @@ -898,6 +926,8 @@ static int vmw_cmd_surface_copy_check(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, @@ -918,6 +948,9 @@ static int vmw_cmd_buffer_copy_check(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.src, NULL); @@ -937,6 +970,9 @@ static int vmw_cmd_pred_copy_check(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.srcSid, NULL); @@ -956,6 +992,9 @@ static int vmw_cmd_stretch_blt_check(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.src.sid, NULL); @@ -974,6 +1013,9 @@ static int vmw_cmd_blt_surf_screen_check(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdBlitSurfaceToScreen) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.srcImage.sid, NULL); @@ -986,6 +1028,9 @@ static int vmw_cmd_present_check(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdPresent) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.sid, NULL); @@ -1243,6 +1288,8 @@ static int vmw_cmd_dx_define_query(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; if (cmd->body.type < SVGA3D_QUERYTYPE_MIN || cmd->body.type >= SVGA3D_QUERYTYPE_MAX) @@ -1280,6 +1327,8 @@ static int vmw_cmd_dx_bind_query(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; /* * Look up the buffer pointed to by q.mobid, put it on the relocation @@ -1310,6 +1359,9 @@ static int vmw_cmd_begin_gb_query(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdBeginGBQuery) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, &cmd->body.cid, NULL); @@ -1329,6 +1381,9 @@ static int vmw_cmd_begin_query(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdBeginQuery) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (unlikely(dev_priv->has_mob)) { VMW_DECLARE_CMD_VAR(gb_cmd, SVGA3dCmdBeginGBQuery); @@ -1364,6 +1419,9 @@ static int vmw_cmd_end_gb_query(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_cid_check(dev_priv, sw_context, header); if (unlikely(ret != 0)) return ret; @@ -1394,6 +1452,9 @@ static int vmw_cmd_end_query(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (dev_priv->has_mob) { VMW_DECLARE_CMD_VAR(gb_cmd, SVGA3dCmdEndGBQuery); @@ -1440,6 +1501,9 @@ static int vmw_cmd_wait_gb_query(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_cid_check(dev_priv, sw_context, header); if (unlikely(ret != 0)) return ret; @@ -1468,6 +1532,9 @@ static int vmw_cmd_wait_query(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (dev_priv->has_mob) { VMW_DECLARE_CMD_VAR(gb_cmd, SVGA3dCmdWaitForGBQuery); @@ -1637,6 +1704,15 @@ static int vmw_cmd_tex_state(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + + /* The loop below must not read a truncated trailing state. */ + if ((header->size - sizeof(cmd->body)) % sizeof(*cur_state)) { + VMW_DEBUG_USER("Invalid texture state size %u.\n", + header->size); + return -EINVAL; + } ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, @@ -1782,6 +1858,9 @@ static int vmw_cmd_bind_gb_surface(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdBindGBSurface) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_switch_backup(dev_priv, sw_context, vmw_res_surface, user_surface_converter, &cmd->body.sid, &cmd->body.mobid, 0); @@ -1801,6 +1880,9 @@ static int vmw_cmd_update_gb_image(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdUpdateGBImage) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.image.sid, NULL); @@ -1820,6 +1902,9 @@ static int vmw_cmd_update_gb_surface(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdUpdateGBSurface) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_CLEAR, user_surface_converter, &cmd->body.sid, NULL); @@ -1839,6 +1924,9 @@ static int vmw_cmd_readback_gb_image(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdReadbackGBImage) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.image.sid, NULL); @@ -1859,6 +1947,9 @@ static int vmw_cmd_readback_gb_surface(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdReadbackGBSurface) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_CLEAR, user_surface_converter, &cmd->body.sid, NULL); @@ -1879,6 +1970,9 @@ static int vmw_cmd_invalidate_gb_image(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdInvalidateGBImage) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.image.sid, NULL); @@ -1899,6 +1993,9 @@ static int vmw_cmd_invalidate_gb_surface(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdInvalidateGBSurface) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_CLEAR, user_surface_converter, &cmd->body.sid, NULL); @@ -1921,6 +2018,8 @@ static int vmw_cmd_shader_define(struct vmw_private *dev_priv, struct vmw_resource *ctx; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, @@ -1960,6 +2059,8 @@ static int vmw_cmd_shader_destroy(struct vmw_private *dev_priv, struct vmw_resource *ctx; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, @@ -1999,6 +2100,8 @@ static int vmw_cmd_set_shader(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; if (!vmw_shadertype_is_valid(VMW_SM_LEGACY, cmd->body.type)) { VMW_DEBUG_USER("Illegal shader type %u.\n", @@ -2077,6 +2180,8 @@ static int vmw_cmd_set_shader_const(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, @@ -2104,6 +2209,9 @@ static int vmw_cmd_bind_gb_shader(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdBindGBShader) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_switch_backup(dev_priv, sw_context, vmw_res_shader, user_shader_converter, &cmd->body.shid, &cmd->body.mobid, cmd->body.offsetInBytes); @@ -2133,6 +2241,9 @@ vmw_cmd_dx_set_single_constant_buffer(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.sid, &res); @@ -2186,6 +2297,9 @@ vmw_cmd_dx_set_constant_buffer_offset(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (cmd->body.slot >= SVGA3D_DX_MAX_CONSTBUFFERS) { VMW_DEBUG_USER("Illegal const buffer slot %u.\n", (unsigned int) cmd->body.slot); @@ -2217,6 +2331,9 @@ static int vmw_cmd_dx_set_shader_res(struct vmw_private *dev_priv, u32 num_sr_view = (cmd->header.size - sizeof(cmd->body)) / sizeof(SVGA3dShaderResourceViewId); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if ((u64) cmd->body.startView + (u64) num_sr_view > (u64) SVGA3D_DX_MAX_SRVIEWS || !vmw_shadertype_is_valid(dev_priv->sm_type, cmd->body.type)) { @@ -2252,6 +2369,8 @@ static int vmw_cmd_dx_set_shader(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; if (!vmw_shadertype_is_valid(dev_priv->sm_type, cmd->body.type)) { VMW_DEBUG_USER("Illegal shader type %u.\n", @@ -2309,6 +2428,9 @@ static int vmw_cmd_dx_set_vertex_buffers(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + num = (cmd->header.size - sizeof(cmd->body)) / sizeof(SVGA3dVertexBuffer); if ((u64)num + (u64)cmd->body.startBuffer > @@ -2360,6 +2482,9 @@ static int vmw_cmd_dx_set_index_buffer(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.sid, &res); @@ -2395,6 +2520,9 @@ static int vmw_cmd_dx_set_rendertargets(struct vmw_private *dev_priv, sizeof(SVGA3dRenderTargetViewId); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (num_rt_view > SVGA3D_DX_MAX_RENDER_TARGETS) { VMW_DEBUG_USER("Invalid DX Rendertarget binding.\n"); return -EINVAL; @@ -2426,6 +2554,9 @@ static int vmw_cmd_dx_clear_rendertarget_view(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); struct vmw_resource *ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_view_id_val_add(sw_context, vmw_view_rt, cmd->body.renderTargetViewId); @@ -2448,6 +2579,9 @@ static int vmw_cmd_dx_clear_depthstencil_view(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); struct vmw_resource *ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_view_id_val_add(sw_context, vmw_view_ds, cmd->body.depthStencilViewId); @@ -2481,6 +2615,9 @@ static int vmw_cmd_dx_view_define(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(*cmd) - sizeof(*header))) + return -EINVAL; + if (unlikely(cmd->sid == SVGA3D_INVALID_ID)) { VMW_DEBUG_USER("Invalid surface id.\n"); return -EINVAL; @@ -2529,6 +2666,9 @@ static int vmw_cmd_dx_set_so_targets(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + num = (cmd->header.size - sizeof(cmd->body)) / sizeof(SVGA3dSoTarget); if (num > SVGA3D_DX_MAX_SOTARGETS) { @@ -2582,6 +2722,9 @@ static int vmw_cmd_dx_so_define(struct vmw_private *dev_priv, if (IS_ERR_OR_NULL(res)) return res ? PTR_ERR(res) : -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(*cmd) - sizeof(*header))) + return -EINVAL; + ret = vmw_cotable_notify(res, cmd->defined_id); return ret; @@ -2617,6 +2760,9 @@ static int vmw_cmd_dx_check_subresource(struct vmw_private *dev_priv, offsetof(typeof(*cmd), sid)); cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->sid))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->sid, NULL); @@ -2658,6 +2804,9 @@ static int vmw_cmd_dx_view_remove(struct vmw_private *dev_priv, struct vmw_resource *view; int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!ctx_node) return -EINVAL; @@ -2695,6 +2844,9 @@ static int vmw_cmd_dx_define_shader(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!ctx_node) return -EINVAL; @@ -2726,6 +2878,9 @@ static int vmw_cmd_dx_destroy_shader(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!ctx_node) return -EINVAL; @@ -2752,6 +2907,9 @@ static int vmw_cmd_dx_bind_shader(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (cmd->body.cid != SVGA3D_INVALID_ID) { ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, @@ -2803,6 +2961,9 @@ static int vmw_cmd_dx_genmips(struct vmw_private *dev_priv, struct vmw_resource *view; struct vmw_res_cache_entry *rcache; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + view = vmw_view_id_val_add(sw_context, vmw_view_sr, cmd->body.shaderResourceViewId); if (IS_ERR(view)) @@ -2836,6 +2997,9 @@ static int vmw_cmd_dx_transfer_from_buffer(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.srcSid, NULL); @@ -2861,6 +3025,9 @@ static int vmw_cmd_intra_surface_copy(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdIntraSurfaceCopy) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!(dev_priv->capabilities2 & SVGA_CAP2_INTRA_SURFACE_COPY)) return -EINVAL; @@ -2909,6 +3076,9 @@ static int vmw_cmd_clear_uav_uint(struct vmw_private *dev_priv, } *cmd = container_of(header, typeof(*cmd), header); struct vmw_resource *ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -2928,6 +3098,9 @@ static int vmw_cmd_clear_uav_float(struct vmw_private *dev_priv, } *cmd = container_of(header, typeof(*cmd), header); struct vmw_resource *ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -2949,6 +3122,9 @@ static int vmw_cmd_set_uav(struct vmw_private *dev_priv, sizeof(SVGA3dUAViewId); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -2981,6 +3157,9 @@ static int vmw_cmd_set_cs_uav(struct vmw_private *dev_priv, sizeof(SVGA3dUAViewId); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -3013,6 +3192,9 @@ static int vmw_cmd_dx_define_streamoutput(struct vmw_private *dev_priv, } *cmd = container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -3044,6 +3226,9 @@ static int vmw_cmd_dx_destroy_streamoutput(struct vmw_private *dev_priv, SVGA3dCmdDXDestroyStreamOutput body; } *cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!ctx_node) { DRM_ERROR("DX Context not set.\n"); return -EINVAL; @@ -3081,6 +3266,9 @@ static int vmw_cmd_dx_bind_streamoutput(struct vmw_private *dev_priv, } *cmd = container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -3123,6 +3311,9 @@ static int vmw_cmd_dx_set_streamoutput(struct vmw_private *dev_priv, } *cmd = container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!ctx_node) { DRM_ERROR("DX Context not set.\n"); return -EINVAL; @@ -3175,6 +3366,9 @@ static int vmw_cmd_indexed_instanced_indirect(struct vmw_private *dev_priv, SVGA3dCmdDXDrawIndexedInstancedIndirect body; } *cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -3192,6 +3386,9 @@ static int vmw_cmd_instanced_indirect(struct vmw_private *dev_priv, SVGA3dCmdDXDrawInstancedIndirect body; } *cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -3209,6 +3406,9 @@ static int vmw_cmd_dispatch_indirect(struct vmw_private *dev_priv, SVGA3dCmdDXDispatchIndirect body; } *cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; From c1e6267b9dd3e04f9dc29e500414cc4fc237dec1 Mon Sep 17 00:00:00 2001 From: Zack Rusin Date: Mon, 26 Oct 2026 23:15:33 -0400 Subject: [PATCH 0673/2102] drm/vmwgfx: validate backup buffer size in command buffer processing vmw_cmd_res_switch_backup lets userspace bind an arbitrary MOB to a resource without checking that the MOB is large enough for the resource's guest_memory_size. The dirty-tracking bitmap is allocated based on the MOB size, but later accessed using the (larger) surface size, causing an out-of-bounds write in the bitmap that corrupts adjacent slab memory. Add a check that backup_offset + res->guest_memory_size does not exceed the buffer size before allowing the backup switch. DX shaders and stream outputs never set guest_memory_size, and both were allocated with kmalloc(), so the check would read uninitialized memory for SVGA_3D_CMD_DX_BIND_SHADER and SVGA_3D_CMD_DX_BIND_STREAMOUTPUT and could reject valid binds. Allocate both with kzalloc() so their guest_memory_size is 0 and the check only bounds the offset. Fixes: a97e21923b42 ("drm/vmwgfx: Hook up guest-backed surfaces") Cc: stable@vger.kernel.org Reported-by: Zero Day Initiative # ZDI-CAN-34068 Closes: https://lore.kernel.org/all/BYAPR01MB38301CFC012E873340F77E3D80662@BYAPR01MB3830.prod.exchangelabs.com/ Signed-off-by: Zack Rusin Reviewed-by: Ian Forbes Link: https://patch.msgid.link/20261027031533.2241918-1-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c | 8 ++++++++ drivers/gpu/drm/vmwgfx/vmwgfx_shader.c | 2 +- drivers/gpu/drm/vmwgfx/vmwgfx_streamoutput.c | 2 +- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c b/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c index 7b943e99061e6f..435425f1adfa67 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c @@ -1794,6 +1794,7 @@ static int vmw_cmd_res_switch_backup(struct vmw_private *dev_priv, { struct vmw_bo *vbo; void *info; + u64 end; int ret; info = vmw_execbuf_info_from_res(sw_context, res); @@ -1804,6 +1805,13 @@ static int vmw_cmd_res_switch_backup(struct vmw_private *dev_priv, if (ret) return ret; + if (check_add_overflow((u64)backup_offset, + (u64)res->guest_memory_size, &end) || + end > vbo->tbo.base.size) { + VMW_DEBUG_USER("Backup buffer too small for resource.\n"); + return -EINVAL; + } + vmw_validation_res_switch_backup(sw_context->ctx, info, vbo, backup_offset); return 0; diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_shader.c b/drivers/gpu/drm/vmwgfx/vmwgfx_shader.c index 39811cf19db154..033157efb1fc0a 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_shader.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_shader.c @@ -597,7 +597,7 @@ int vmw_dx_shader_add(struct vmw_cmdbuf_res_manager *man, if (!vmw_shader_id_ok(user_key, shader_type)) return -EINVAL; - shader = kmalloc_obj(*shader); + shader = kzalloc_obj(*shader); if (!shader) { return -ENOMEM; } diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_streamoutput.c b/drivers/gpu/drm/vmwgfx/vmwgfx_streamoutput.c index 52c6cfa163dacb..34d5b71fa42fe4 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_streamoutput.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_streamoutput.c @@ -284,7 +284,7 @@ int vmw_dx_streamoutput_add(struct vmw_cmdbuf_res_manager *man, struct vmw_private *dev_priv = ctx->dev_priv; int ret; - so = kmalloc_obj(*so); + so = kzalloc_obj(*so); if (!so) { return -ENOMEM; } From c4b134969ce350cdd4e726b5102b85b8a2d6fad5 Mon Sep 17 00:00:00 2001 From: Jaeyeong Lee Date: Sun, 26 Jul 2026 13:08:56 -0400 Subject: [PATCH 0674/2102] drm/vmwgfx: Erase the detached resource entry on resource release vmw_bo_add_detached_resource() stores a raw struct vmw_resource pointer in bo->detached_resources without taking a reference on the resource, and the only place that erases the entry again is vmw_resource_mob_attach(). A resource that is never validated, and therefore never attached to its backing mob, keeps its entry until the buffer object itself is destroyed. vmw_resource_release() detaches the resource from the mob RB tree and drops its reference on the backing buffer object, but leaves the detached_resources entry in place. Userspace can hold an independent GEM handle on that buffer object, either because DRM_VMW_GB_SURFACE_CREATE returned one in rep.buffer_handle, or because DRM_VMW_GB_SURFACE_REF minted one with drm_gem_handle_create(). The buffer object then outlives the surface while still holding a pointer to freed memory. Any later surface lookup for that buffer object dereferences it: vmw_prime_handle_to_fd() vmw_lookup_surface_handle_for_buffer() vmw_lookup_user_surface_for_buffer() vmw_bo_surface() res->func->res_type <-- use-after-free read vmw_bo_surface() walks detached_resources before the mob RB tree, so the stale entry is matched first. The kref_get_unless_zero() in vmw_lookup_user_surface_for_buffer() does not help here: it runs after the dereference, and struct vmw_user_surface is freed with kfree_rcu() on a slab that is not SLAB_TYPESAFE_BY_RCU, so the memory is handed out to unrelated allocations once the grace period elapses. A sequence that reaches this from userspace is to create a guest-backed surface with drm_vmw_surface_flag_create_buffer, never validate it, release it with DRM_VMW_UNREF_SURFACE, and then call DRM_IOCTL_PRIME_HANDLE_TO_FD on the buffer handle returned by the create ioctl. All of the ioctls involved are DRM_RENDER_ALLOW. Erase the entry next to the existing vmw_resource_mob_detach() call, so that a released resource is removed from both containers, mirroring what vmw_resource_mob_attach() does. The dumb buffer teardown path in vmw_bo_free() clears res->guest_memory_bo before dropping its surface reference, so it does not reach this code and is unaffected. Fixes: d6667f0ddf46 ("drm/vmwgfx: Fix handling of dumb buffers") Cc: stable@vger.kernel.org Signed-off-by: Jaeyeong Lee Reviewed-by: Zack Rusin [zack: rebased; dropped the v7.2-rc4 analysis note from the commit message] Signed-off-by: Zack Rusin Link: https://patch.msgid.link/20260725143859.797134-1-finpiler@protonmail.com --- drivers/gpu/drm/vmwgfx/vmwgfx_resource.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_resource.c b/drivers/gpu/drm/vmwgfx/vmwgfx_resource.c index e3a187a2c7a1cc..ad13688bd7da7a 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_resource.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_resource.c @@ -138,6 +138,7 @@ static void vmw_resource_release(struct kref *kref) } res->guest_memory_dirty = false; vmw_resource_mob_detach(res); + vmw_bo_del_detached_resource(res->guest_memory_bo, res); if (res->dirty) res->func->dirty_free(res); if (res->coherent) From 05ee42f3dd5484415fac587d0efb8fe846b74c2c Mon Sep 17 00:00:00 2001 From: Zack Rusin Date: Thu, 29 Oct 2026 10:44:49 -0400 Subject: [PATCH 0675/2102] drm/vmwgfx: avoid underflow when stripping short GuestInfo replies vmw_host_get_guestinfo subtracts the two-byte reply prefix using max(reply_len - 2, (size_t)0). Since reply_len is unsigned, a one-byte reply wraps to SIZE_MAX instead of being clamped to zero. The subsequent copy can read past the host reply allocation. Theoretically malformed host reply can reach this path when the driver queries the GuestInfo parameter used to enable VKMS. Check the reply length before subtracting the prefix so short replies produce an empty payload and cannot cause an out-of-bounds read. Sashiko reported this while reviewing the i386 hypercall changes. Fixes: 89da76fde68d ("drm/vmwgfx: Add VMWare host messaging capability") Cc: stable@vger.kernel.org Closes: https://sashiko.dev/#/patchset/4ab10678a8f50053934b62b56af81f881c1d3798.1788414669.git.zack.rusin%40broadcom.com Signed-off-by: Zack Rusin Reviewed-by: Maaz Mombasawala Link: https://patch.msgid.link/20261029215738.3010276-1-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_msg.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c b/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c index fd77ab6568cbbc..49e04a50c6ed20 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c @@ -431,7 +431,7 @@ int vmw_host_get_guestinfo(const char *guest_info_param, /* Remove reply code, which are the first 2 characters of * the reply */ - reply_len = max(reply_len - 2, (size_t) 0); + reply_len = reply_len > 2 ? reply_len - 2 : 0; reply_len = min(reply_len, *length); if (reply_len > 0) From 9725b0454e65f15ae76788f2004a7ba8b493362a Mon Sep 17 00:00:00 2001 From: Zack Rusin Date: Thu, 29 Oct 2026 10:45:07 -0400 Subject: [PATCH 0676/2102] drm/vmwgfx: bound MKSSTAT lengths before rounding to pages vmw_mksstat_add_ioctl rounds the user-supplied 64bit lengths to page counts before comparing them with the descriptors page arrays. PFN_UP can wrap for lengths near U64_MAX. On 32bit kernels, storing a large page count in size_t can also truncate it to a value that passes the checks. A render-node client can therefore register a descriptor with lengths that exceed its pinned page arrays, including nonzero lengths with no backing pages. Compare each byte length with its page array's capacity before rounding or narrowing it. Compute those capacities in 64 bits and calculate the page counts only after all three lengths have passed validation. Sashiko reported this while reviewing the i386 hypercall changes. Fixes: 7a7a933edd6c ("drm/vmwgfx: Introduce VMware mks-guest-stats") Cc: stable@vger.kernel.org Closes: https://sashiko.dev/#/patchset/4ab10678a8f50053934b62b56af81f881c1d3798.1788414669.git.zack.rusin%40broadcom.com Signed-off-by: Zack Rusin Reviewed-by: Maaz Mombasawala Link: https://patch.msgid.link/20261029215738.3010276-2-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_msg.c | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c b/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c index 49e04a50c6ed20..58da332486bd2c 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c @@ -939,9 +939,12 @@ int vmw_mksstat_add_ioctl(struct drm_device *dev, void *data, struct vmw_private *const dev_priv = vmw_priv(dev); - const size_t num_pages_stat = PFN_UP(arg->stat_len); - const size_t num_pages_info = PFN_UP(arg->info_len); - const size_t num_pages_strs = PFN_UP(arg->strs_len); + const u64 max_stat_len = (u64)MKS_GUEST_STAT_INSTANCE_MAX_STAT_PPNS * PAGE_SIZE; + const u64 max_info_len = (u64)MKS_GUEST_STAT_INSTANCE_MAX_INFO_PPNS * PAGE_SIZE; + const u64 max_strs_len = (u64)MKS_GUEST_STAT_INSTANCE_MAX_STRS_PPNS * PAGE_SIZE; + size_t num_pages_stat; + size_t num_pages_info; + size_t num_pages_strs; long desc_len; long nr_pinned_stat; long nr_pinned_info; @@ -965,11 +968,15 @@ int vmw_mksstat_add_ioctl(struct drm_device *dev, void *data, if (!arg->description) return -EINVAL; - if (num_pages_stat > ARRAY_SIZE(pdesc->statPPNs) || - num_pages_info > ARRAY_SIZE(pdesc->infoPPNs) || - num_pages_strs > ARRAY_SIZE(pdesc->strsPPNs)) + if (arg->stat_len > max_stat_len || + arg->info_len > max_info_len || + arg->strs_len > max_strs_len) return -EINVAL; + num_pages_stat = PFN_UP(arg->stat_len); + num_pages_info = PFN_UP(arg->info_len); + num_pages_strs = PFN_UP(arg->strs_len); + /* Find an available slot in the mksGuestStats user array and reserve it */ for (slot = 0; slot < ARRAY_SIZE(dev_priv->mksstat_user_pids); ++slot) if (!atomic_cmpxchg(&dev_priv->mksstat_user_pids[slot], 0, MKSSTAT_PID_RESERVED)) From 556271f0ade9d3f1ed0a386f29d3363be294c1fc Mon Sep 17 00:00:00 2001 From: Zack Rusin Date: Tue, 27 Oct 2026 02:07:05 -0400 Subject: [PATCH 0677/2102] drm/vmwgfx: keep cursor mappings and pins with each plane state Cursor plane states duplicate the user object reference without acquiring its mapping or pin. Preparing the duplicated state nevertheless unmaps that object, and only pins the new buffer if it is not already pinned. Cleanup of an older state can therefore remove a mapping or pin still needed by another cursor commit. Repeated cursor updates from KMS clients can then access an unmapped or movable buffer. Give each prepared state its own mapping, buffer reference and pin, and reset the mapping when duplicating a state. Release only the resources owned by that state in cleanup_fb(). Map the required image extent for every state so resizing a cursor on the same buffer cannot reuse a smaller cached mapping. Unwind the pin and reservation if preparation fails. Fixes: 965544150d1c ("drm/vmwgfx: Refactor cursor handling") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Zack Rusin Reviewed-by: Maaz Mombasawala Tested-by: fausten Link: https://patch.msgid.link/20261027211729.646988-2-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c | 71 ++++++++++++-------- drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.h | 4 ++ drivers/gpu/drm/vmwgfx/vmwgfx_kms.c | 1 + 3 files changed, 49 insertions(+), 27 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c index 5a69606a0593bc..942d07079ef7fe 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c @@ -112,8 +112,7 @@ static void vmw_cursor_update_mob(struct vmw_private *vmw, { SVGAGBCursorHeader *header; SVGAGBAlphaCursorHeader *alpha_header; - struct vmw_bo *bo = vmw_user_object_buffer(&vps->uo); - u32 *image = vmw_bo_map_and_cache(bo); + u32 *image = vps->cursor.map.virtual; const u32 image_size = vps->base.crtc_w * vps->base.crtc_h * sizeof(*image); header = vmw_bo_map_and_cache(vps->cursor.mob); @@ -132,7 +131,6 @@ static void vmw_cursor_update_mob(struct vmw_private *vmw, memcpy(header + 1, image, image_size); vmw_write(vmw, SVGA_REG_CURSOR_MOBID, vmw_bo_mobid(vps->cursor.mob)); - vmw_bo_unmap(bo); vmw_bo_unmap(vps->cursor.mob); } @@ -490,9 +488,21 @@ vmw_cursor_plane_cleanup_fb(struct drm_plane *plane, { struct vmw_cursor_plane *vcp = vmw_plane_to_vcp(plane); struct vmw_plane_state *vps = vmw_plane_state_to_vps(old_state); + struct vmw_bo *bo; + int ret; - if (!vmw_user_object_is_null(&vps->uo)) - vmw_user_object_unmap(&vps->uo); + if (vps->cursor.map.bo) { + bo = to_vmw_bo(&vps->cursor.map.bo->base); + ret = ttm_bo_reserve(&bo->tbo, false, false, NULL); + if (WARN_ON_ONCE(ret)) + return; + + ttm_bo_kunmap(&vps->cursor.map); + vps->cursor.map.bo = NULL; + ttm_bo_unpin(&bo->tbo); + ttm_bo_unreserve(&bo->tbo); + vmw_bo_unreference(&bo); + } vmw_cursor_mob_unmap(vps); vmw_cursor_mob_put(vcp, vps); @@ -625,10 +635,12 @@ int vmw_cursor_plane_prepare_fb(struct drm_plane *plane, struct vmw_surface *surface; int ret = 0; - if (!vmw_user_object_is_null(&vps->uo)) { - vmw_user_object_unmap(&vps->uo); + /* + * A duplicated state only owns the user object reference. Its mappings + * and pins belong to the old state until cleanup_fb(). + */ + if (!vmw_user_object_is_null(&vps->uo)) vmw_user_object_unref(&vps->uo); - } if (fb) { if (vmw_framebuffer_to_vfb(fb)->bo) { @@ -652,31 +664,34 @@ int vmw_cursor_plane_prepare_fb(struct drm_plane *plane, bo = vmw_user_object_buffer(&vps->uo); if (bo) { struct ttm_operation_ctx ctx = { false, false }; + size_t size = (size_t)new_state->crtc_w * + new_state->crtc_h * sizeof(u32); ret = ttm_bo_reserve(&bo->tbo, true, false, NULL); if (ret != 0) - return -ENOMEM; + return ret; ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); if (ret != 0) - return -ENOMEM; + goto out_unreserve; /* - * vmw_bo_pin_reserved also validates, so to skip - * the extra validation use ttm_bo_pin directly + * vmw_bo_pin_reserved() also validates, so to skip + * the extra validation use ttm_bo_pin directly. + * Every state takes its own pin, the buffer can + * still be in use by an older state whose commit + * hasn't been cleaned up yet. */ - if (!bo->tbo.pin_count) - ttm_bo_pin(&bo->tbo); - - if (vmw_framebuffer_to_vfb(fb)->bo) { - const u32 size = new_state->crtc_w * - new_state->crtc_h * - sizeof(u32); - - (void)vmw_bo_map_and_cache_size(bo, size); - } else { - vmw_bo_map_and_cache(bo); + ttm_bo_pin(&bo->tbo); + + ret = ttm_bo_kmap(&bo->tbo, 0, PFN_UP(size), + &vps->cursor.map); + if (ret) { + vps->cursor.map.bo = NULL; + ttm_bo_unpin(&bo->tbo); + goto out_unreserve; } + vmw_bo_reference(bo); ttm_bo_unreserve(&bo->tbo); } if (!vmw_user_object_is_null(&vps->uo)) { @@ -703,6 +718,10 @@ int vmw_cursor_plane_prepare_fb(struct drm_plane *plane, } return 0; + +out_unreserve: + ttm_bo_unreserve(&bo->tbo); + return ret; } /** @@ -796,7 +815,6 @@ void vmw_cursor_plane_atomic_update(struct drm_plane *plane, struct drm_atomic_commit *state) { - struct vmw_bo *bo; struct drm_plane_state *new_state = drm_atomic_get_new_plane_state(state, plane); struct drm_plane_state *old_state = @@ -823,9 +841,8 @@ vmw_cursor_plane_atomic_update(struct drm_plane *plane, vmw_cursor_update_mob(dev_priv, vps); break; case VMW_CURSOR_UPDATE_GB_ONLY: - bo = vmw_user_object_buffer(&vps->uo); - if (bo) - vmw_send_define_cursor_cmd(dev_priv, bo->map.virtual, + if (vps->cursor.map.virtual) + vmw_send_define_cursor_cmd(dev_priv, vps->cursor.map.virtual, vps->base.crtc_w, vps->base.crtc_h, vps->base.hotspot_x, diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.h b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.h index d32cf17d013b51..9b50f80f9635a4 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.h +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.h @@ -14,6 +14,8 @@ #include "drm/drm_fourcc.h" #include "drm/drm_plane.h" +#include + #include struct SVGA3dCmdHeader; @@ -41,6 +43,8 @@ struct vmw_cursor_plane_state { enum vmw_cursor_update_type update_type; bool changed; bool surface_changed; + /* The mapped buffer is referenced and pinned by this state. */ + struct ttm_bo_kmap_obj map; struct vmw_bo *mob; struct { s32 hotspot_x; diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c b/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c index a6c3304e1a67d8..f196e29f1b3bee 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c @@ -275,6 +275,7 @@ vmw_du_plane_duplicate_state(struct drm_plane *plane) vps->cpp = 0; vps->cursor.mob = NULL; + memset(&vps->cursor.map, 0, sizeof(vps->cursor.map)); /* Each ref counted resource needs to be acquired again */ vmw_user_object_ref(&vps->uo); From 6baeb251d709d5f31f2a0ae89ca5ca054d0e04e7 Mon Sep 17 00:00:00 2001 From: Zack Rusin Date: Tue, 27 Oct 2026 02:08:24 -0400 Subject: [PATCH 0678/2102] drm/vmwgfx: validate GB-only cursor command limits Guest-backed devices without cursor MOB support define cursor images with SVGA_CMD_DEFINE_ALPHA_CURSOR. SVGA_REG_CURSOR_MAX_DIMENSION belongs to the cursor MOB register class and reads as zero on devices that do not expose that class. Applying this register to GB-only cursors rejects every nonempty image submitted by KMS clients, leaving Xorg without a hardware cursor. The submission transport also limits the command size. A 96x96 image fits the 40 KiB FIFO image limit, but exceeds the 32 KiB command-buffer limit and causes a device command error when submitted through that transport. Validate GB-only images against SVGA_MAX_CURSOR_CMD_DIMENSION and SVGA_MAX_CURSOR_CMD_BYTES. For command-buffer submission, also bound the whole command by SVGA_CB_MAX_COMMAND_SIZE, including its header. Calculate the image byte count in 64 bits and keep the register-based dimension and MOB size checks for MOB cursors. Fixes: d5ed8749168a ("drm/vmwgfx: enforce cursor size limits for MOB cursors") Cc: stable@vger.kernel.org Reported-by: Yunfeng Li Closes: https://patch.msgid.link/20260830151619.2452307-1-yunfeng.li.nb@gmail.com Assisted-by: LLM Signed-off-by: Zack Rusin Reviewed-by: Maaz Mombasawala Tested-by: fausten Link: https://patch.msgid.link/20261027211729.646988-3-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c | 23 ++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c index 942d07079ef7fe..14490ead99cd2e 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c @@ -778,8 +778,27 @@ int vmw_cursor_plane_atomic_check(struct drm_plane *plane, "surface not suitable for cursor\n"); return -EINVAL; } - } else if (update_type == VMW_CURSOR_UPDATE_GB_ONLY || - update_type == VMW_CURSOR_UPDATE_MOB) { + } else if (update_type == VMW_CURSOR_UPDATE_GB_ONLY) { + u64 image_size = (u64)new_state->crtc_w * + new_state->crtc_h * sizeof(u32); + u32 max_size = SVGA_MAX_CURSOR_CMD_BYTES; + + /* The command-buffer limit includes the define-cursor header. */ + if (vmw->cman) + max_size = min_t(u32, max_size, + SVGA_CB_MAX_COMMAND_SIZE - + sizeof(struct vmw_svga_fifo_cmd_define_cursor)); + + if (!new_state->crtc_w || !new_state->crtc_h || + new_state->crtc_w > SVGA_MAX_CURSOR_CMD_DIMENSION || + new_state->crtc_h > SVGA_MAX_CURSOR_CMD_DIMENSION || + image_size > max_size) { + drm_dbg_kms(&vmw->drm, + "Cursor dimensions (%u, %u) violate command limits\n", + new_state->crtc_w, new_state->crtc_h); + return -EINVAL; + } + } else if (update_type == VMW_CURSOR_UPDATE_MOB) { u32 cursor_max_dim = vmw_read(vmw, SVGA_REG_CURSOR_MAX_DIMENSION); From c116d38c3ad3ccdc1153ee7713c0eafd62b1c235 Mon Sep 17 00:00:00 2001 From: Tomas M Date: Tue, 27 Oct 2026 03:23:23 +0200 Subject: [PATCH 0679/2102] drm/vmwgfx: include legacy hotspots in GB-only cursor images The guest-backed cursor path without cursor MOB support defines the image using only the hotspot from the plane state. Its position calculation also includes the legacy hotspot supplied through DRM_VMW_CURSOR_BYPASS. Xorg's xf86-video-vmware driver supplies its hotspot through that ioctl and loads the image with drmModeSetCursor(), which does not set a plane hotspot. The mismatched image and position hotspots displace the visible cursor by the legacy offset. Use the combined hotspot for both the GB-only image command and cursor position, matching the legacy and MOB image paths. Fixes: eef295a85082 ("drm/vmwgfx: Restore Guest-Backed only cursor plane support") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Tomas M Reviewed-by: Maaz Mombasawala Tested-by: fausten Signed-off-by: Zack Rusin Link: https://patch.msgid.link/20261027211729.646988-4-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c index 14490ead99cd2e..f0661e5effeb16 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c @@ -852,6 +852,10 @@ vmw_cursor_plane_atomic_update(struct drm_plane *plane, return; } + /* Include legacy Xorg cursor-bypass offsets in the image and position. */ + hotspot_x = vps->cursor.legacy.hotspot_x + new_state->hotspot_x; + hotspot_y = vps->cursor.legacy.hotspot_y + new_state->hotspot_y; + switch (vps->cursor.update_type) { case VMW_CURSOR_UPDATE_LEGACY: vmw_cursor_plane_update_legacy(dev_priv, vps); @@ -864,8 +868,7 @@ vmw_cursor_plane_atomic_update(struct drm_plane *plane, vmw_send_define_cursor_cmd(dev_priv, vps->cursor.map.virtual, vps->base.crtc_w, vps->base.crtc_h, - vps->base.hotspot_x, - vps->base.hotspot_y); + hotspot_x, hotspot_y); break; case VMW_CURSOR_UPDATE_NONE: /* do nothing */ @@ -878,9 +881,6 @@ vmw_cursor_plane_atomic_update(struct drm_plane *plane, cursor_x = new_state->crtc_x + du->set_gui_x; cursor_y = new_state->crtc_y + du->set_gui_y; - hotspot_x = vps->cursor.legacy.hotspot_x + new_state->hotspot_x; - hotspot_y = vps->cursor.legacy.hotspot_y + new_state->hotspot_y; - vmw_cursor_update_position(dev_priv, true, cursor_x + hotspot_x, cursor_y + hotspot_y); } From 13e766130673ec3b9df8b72ff1dbe6826cac1dfe Mon Sep 17 00:00:00 2001 From: Zack Rusin Date: Tue, 27 Oct 2026 04:29:38 -0400 Subject: [PATCH 0680/2102] drm/vmwgfx: reserve dumb buffers while detaching their surfaces vmw_bo_free() detaches the surface associated with a dumb buffer and clears its guest memory binding. It reserves the resource, but does not hold the buffer reservation required by vmw_resource_mob_detach(). TTM releases that reservation before invoking the buffer destructor. KMS clients destroying dumb buffers can therefore trigger the reservation assertion from vmw_resource_mob_detach(). GNOME reaches this path through DRM_IOCTL_MODE_DESTROY_DUMB during cursor and display updates. Reacquire the buffer reservation while detaching the surface and clearing its dirty tracking and guest memory binding. Acquire it after cmdbuf_mutex, following the command validation lock order, and release it before releasing the resource and GEM object. Fixes: d6667f0ddf46 ("drm/vmwgfx: Fix handling of dumb buffers") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Zack Rusin Reviewed-by: Maaz Mombasawala Tested-by: fausten Link: https://patch.msgid.link/20261027211729.646988-5-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_bo.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_bo.c b/drivers/gpu/drm/vmwgfx/vmwgfx_bo.c index 9c7a73c0b0dc39..a6d7156e428162 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_bo.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_bo.c @@ -55,6 +55,8 @@ static void vmw_bo_free(struct ttm_buffer_object *bo) /* Reserve and switch the backing mob. */ mutex_lock(&res->dev_priv->cmdbuf_mutex); (void)vmw_resource_reserve(res, false, true); + /* TTM drops the reservation before calling the destructor. */ + dma_resv_lock(bo->base.resv, NULL); vmw_resource_mob_detach(res); if (res->dirty) res->func->dirty_free(res); @@ -62,6 +64,7 @@ static void vmw_bo_free(struct ttm_buffer_object *bo) vmw_bo_dirty_release(res->guest_memory_bo); res->guest_memory_bo = NULL; res->guest_memory_offset = 0; + dma_resv_unlock(bo->base.resv); vmw_resource_unreserve(res, true, false, false, NULL, 0); mutex_unlock(&res->dev_priv->cmdbuf_mutex); From d6263d9bfa931dfc7e0dd922a6ee52b5535caa74 Mon Sep 17 00:00:00 2001 From: Zack Rusin Date: Tue, 27 Oct 2026 08:07:40 -0400 Subject: [PATCH 0681/2102] drm/vmwgfx: validate the framebuffer selected for cursor updates Cursor atomic checks select an update path and look up surfaces through vps->uo. That object is copied from the previous plane state and is only replaced with the new framebuffer's object in prepare_fb(). Switching between snooped surfaces and buffer objects therefore applies the old framebuffer's cursor limits to the new image. KMS clients can also submit a guest-backed surface without a backing BO. The check accepts it, but the MOB update later copies from a NULL source. Zero-sized MOB images pass the check as well, then fail preparation when mapping zero pages, so TEST_ONLY accepts a commit that cannot succeed. Resolve the user object directly from the selected framebuffer in both validation and preparation. Apply the matching cursor limits, reject zero dimensions and require a backing BO for GB-only and MOB images. Recheck the backing BO in preparation before mapping it, while keeping snooped surfaces independent of a BO mapping. Fixes: 965544150d1c ("drm/vmwgfx: Refactor cursor handling") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Zack Rusin Reviewed-by: Maaz Mombasawala Tested-by: fausten Link: https://patch.msgid.link/20261027211729.646988-6-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c | 59 ++++++++++++++------ 1 file changed, 42 insertions(+), 17 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c index f0661e5effeb16..9e8ea9e07f40f2 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c @@ -89,10 +89,26 @@ vmw_cursor_plane_update_legacy(struct vmw_private *vmw, } } +static struct vmw_user_object +vmw_cursor_plane_user_object(struct drm_framebuffer *fb) +{ + struct vmw_user_object uo = { 0 }; + + if (!fb) + return uo; + + if (vmw_framebuffer_to_vfb(fb)->bo) + uo.buffer = vmw_framebuffer_to_vfbd(fb)->buffer; + else + uo = vmw_framebuffer_to_vfbs(fb)->uo; + + return uo; +} + static enum vmw_cursor_update_type -vmw_cursor_update_type(struct vmw_private *vmw, struct vmw_plane_state *vps) +vmw_cursor_update_type(struct vmw_private *vmw, struct vmw_user_object *uo) { - struct vmw_surface *surface = vmw_user_object_surface(&vps->uo); + struct vmw_surface *surface = vmw_user_object_surface(uo); if (surface && surface->snooper.image) return VMW_CURSOR_UPDATE_LEGACY; @@ -642,17 +658,10 @@ int vmw_cursor_plane_prepare_fb(struct drm_plane *plane, if (!vmw_user_object_is_null(&vps->uo)) vmw_user_object_unref(&vps->uo); - if (fb) { - if (vmw_framebuffer_to_vfb(fb)->bo) { - vps->uo.buffer = vmw_framebuffer_to_vfbd(fb)->buffer; - vps->uo.surface = NULL; - } else { - memcpy(&vps->uo, &vmw_framebuffer_to_vfbs(fb)->uo, sizeof(vps->uo)); - } - vmw_user_object_ref(&vps->uo); - } + vps->uo = vmw_cursor_plane_user_object(fb); + vmw_user_object_ref(&vps->uo); - vps->cursor.update_type = vmw_cursor_update_type(vmw, vps); + vps->cursor.update_type = vmw_cursor_update_type(vmw, &vps->uo); switch (vps->cursor.update_type) { case VMW_CURSOR_UPDATE_LEGACY: surface = vmw_user_object_surface(&vps->uo); @@ -662,6 +671,9 @@ int vmw_cursor_plane_prepare_fb(struct drm_plane *plane, case VMW_CURSOR_UPDATE_GB_ONLY: case VMW_CURSOR_UPDATE_MOB: { bo = vmw_user_object_buffer(&vps->uo); + if (fb && !bo) + return -EINVAL; + if (bo) { struct ttm_operation_ctx ctx = { false, false }; size_t size = (size_t)new_state->crtc_w * @@ -744,7 +756,7 @@ int vmw_cursor_plane_atomic_check(struct drm_plane *plane, int ret = 0; struct drm_crtc_state *crtc_state = NULL; struct vmw_surface *surface = NULL; - struct vmw_plane_state *vps = vmw_plane_state_to_vps(new_state); + struct vmw_user_object uo; enum vmw_cursor_update_type update_type; struct drm_framebuffer *fb = new_state->fb; @@ -763,7 +775,21 @@ int vmw_cursor_plane_atomic_check(struct drm_plane *plane, if (!fb) return 0; - update_type = vmw_cursor_update_type(vmw, vps); + if (!new_state->crtc_w || !new_state->crtc_h) { + drm_dbg_kms(&vmw->drm, + "Cursor dimensions (%u, %u) must be nonzero\n", + new_state->crtc_w, new_state->crtc_h); + return -EINVAL; + } + + /* The duplicated plane state's user object still belongs to the old FB. */ + uo = vmw_cursor_plane_user_object(fb); + update_type = vmw_cursor_update_type(vmw, &uo); + if ((update_type == VMW_CURSOR_UPDATE_GB_ONLY || + update_type == VMW_CURSOR_UPDATE_MOB) && + !vmw_user_object_buffer(&uo)) + return -EINVAL; + if (update_type == VMW_CURSOR_UPDATE_LEGACY) { if (new_state->crtc_w != VMW_CURSOR_SNOOP_WIDTH || new_state->crtc_h != VMW_CURSOR_SNOOP_HEIGHT) { @@ -772,7 +798,7 @@ int vmw_cursor_plane_atomic_check(struct drm_plane *plane, new_state->crtc_w, new_state->crtc_h); return -EINVAL; } - surface = vmw_user_object_surface(&vps->uo); + surface = vmw_user_object_surface(&uo); if (!surface || !surface->snooper.image) { drm_warn(&vmw->drm, "surface not suitable for cursor\n"); @@ -789,8 +815,7 @@ int vmw_cursor_plane_atomic_check(struct drm_plane *plane, SVGA_CB_MAX_COMMAND_SIZE - sizeof(struct vmw_svga_fifo_cmd_define_cursor)); - if (!new_state->crtc_w || !new_state->crtc_h || - new_state->crtc_w > SVGA_MAX_CURSOR_CMD_DIMENSION || + if (new_state->crtc_w > SVGA_MAX_CURSOR_CMD_DIMENSION || new_state->crtc_h > SVGA_MAX_CURSOR_CMD_DIMENSION || image_size > max_size) { drm_dbg_kms(&vmw->drm, From 8a9b3b4c3a6cc95ea959183e20871d2421a6b986 Mon Sep 17 00:00:00 2001 From: Zack Rusin Date: Tue, 27 Oct 2026 14:48:55 -0400 Subject: [PATCH 0682/2102] drm/vmwgfx: reserve cursor MOBs before unpinning them vmw_cursor_mob_destroy() unpins cursor MOBs when discarding an image from the plane's cache or destroying the cursor plane. It calls ttm_bo_unpin() without reserving the BO, although TTM requires its reservation to be held when changing pin counts and LRU membership. KMS clients issuing repeated nonblocking cursor updates can exhaust the cache and reach this path. On a lockdep-enabled kernel this triggers reservation assertions in ttm_bo_unpin() and ttm_resource_unevictable(). Reserve the MOB around ttm_bo_unpin(), then release the reservation before dropping the BO reference. Fixes: 485d98d472d5 ("drm/vmwgfx: Add support for CursorMob and CursorBypass 4") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Zack Rusin Reviewed-by: Maaz Mombasawala Tested-by: fausten Link: https://patch.msgid.link/20261027211729.646988-7-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c index 9e8ea9e07f40f2..b678e5b68db7bb 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c @@ -166,10 +166,17 @@ static u32 vmw_cursor_mob_size(enum vmw_cursor_update_type update_type, static void vmw_cursor_mob_destroy(struct vmw_bo **vbo) { + int ret; + if (!(*vbo)) return; + ret = ttm_bo_reserve(&(*vbo)->tbo, false, false, NULL); + if (WARN_ON_ONCE(ret)) + return; + ttm_bo_unpin(&(*vbo)->tbo); + ttm_bo_unreserve(&(*vbo)->tbo); vmw_bo_unreference(vbo); } From d3cbc7400e075eb8b50845fe0bb9fa2ad560df60 Mon Sep 17 00:00:00 2001 From: Ian Forbes Date: Thu, 14 May 2026 10:31:03 -0500 Subject: [PATCH 0683/2102] drm/vmwgfx: Never destroy STDU zero's Screen Target When some VMware clients connect to a VM they query the existing screen target information to create a window of the same size. If the VM display is asleep and the CRTC is disabled we don't have a screen target and the client will not create a window which may lead it to have no way of accepting user input. Without input the VM cannot be awoken and the user is left with a blank screen. This can be overcome by using the 'Send Key' command from the client's application menu but this is not an ideal experience for users. This can be fixed by always leaving display unit zero with a screen target. Fixes: 7ef91dcba172 ("drm/vmwgfx: Don't destroy Screen Target when CRTC is enabled but inactive") Signed-off-by: Ian Forbes Reviewed-by: Zack Rusin Signed-off-by: Zack Rusin Link: https://patch.msgid.link/20260514153103.1465013-1-ian.forbes@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c b/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c index cbf55084110adb..c6eec395d503c9 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c @@ -448,6 +448,13 @@ static void vmw_stdu_crtc_atomic_disable(struct drm_crtc *crtc, !new_crtc_state->mode_changed) return; + /* Never destroy DU 0's ST so that the VM client always has a + * window to accept input from. Otherwise we may never receive + * input to wake the VM when the CRTC is disabled during idle. + */ + if (stdu->base.unit == 0) + return; + ret = vmw_stdu_destroy_st(dev_priv, stdu); if (ret) DRM_ERROR("Failed to destroy Screen Target\n"); From 0771ae93718bb016f80eb8e7d4b43135ad168999 Mon Sep 17 00:00:00 2001 From: Ian Forbes Date: Fri, 22 May 2026 14:53:03 -0500 Subject: [PATCH 0684/2102] drm/vmwgfx: Check whether CRTC is active when updating planes The IGT test kms_universal_plane triggers the error condition in this branch because the screen target is not defined. Also access the STDU via the plane since it's guaranteed to be non-null. Fixes: e05162c017e2 ("drm: Store new plane state in a variable for atomic_update and disable") Signed-off-by: Ian Forbes Reviewed-by: Zack Rusin Signed-off-by: Zack Rusin Link: https://patch.msgid.link/20260522195303.797091-1-ian.forbes@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c b/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c index c6eec395d503c9..993c6b315db4c5 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c @@ -44,6 +44,8 @@ container_of(x, struct vmw_screen_target_display_unit, base.encoder) #define vmw_connector_to_stdu(x) \ container_of(x, struct vmw_screen_target_display_unit, base.connector) +#define vmw_primary_to_stdu(x) \ + container_of(x, struct vmw_screen_target_display_unit, base.primary) /* * Some renderers such as llvmpipe will align the width and height of their @@ -1418,7 +1420,8 @@ vmw_stdu_primary_plane_atomic_update(struct drm_plane *plane, int ret; /* If case of device error, maintain consistent atomic state */ - if (crtc && new_state->fb) { + if (crtc && new_state->fb && + drm_atomic_get_new_crtc_state(state, crtc)->active) { struct vmw_framebuffer *vfb = vmw_framebuffer_to_vfb(new_state->fb); stdu = vmw_crtc_to_stdu(crtc); @@ -1442,9 +1445,8 @@ vmw_stdu_primary_plane_atomic_update(struct drm_plane *plane, if (ret) DRM_ERROR("Failed to update STDU.\n"); } else { - crtc = old_state->crtc; - stdu = vmw_crtc_to_stdu(crtc); - dev_priv = vmw_priv(crtc->dev); + stdu = vmw_primary_to_stdu(plane); + dev_priv = vmw_priv(plane->dev); /* Blank STDU when fb and crtc are NULL */ if (!stdu->defined) From f01848d84577e5860a187eea64f5321acaf1f893 Mon Sep 17 00:00:00 2001 From: Zack Rusin Date: Thu, 29 Oct 2026 01:26:03 -0400 Subject: [PATCH 0685/2102] drm/vmwgfx: log missing primary planes only once Stop filling kernel logs due to something that's not even a bug. Some igt tests, e.g. kms_flip trigger this message ~17000 times which makes all the other diagnostics almost impossible to find. Just inform the user about this condition once and let it through afterward. Fixes: a60ccade88f9 ("drm/vmwgfx: Fix crtc's atomic check conditional") Cc: stable@vger.kernel.org Signed-off-by: Zack Rusin Reviewed-by: Maaz Mombasawala Link: https://patch.msgid.link/20261029215540.3008997-1-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_kms.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c b/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c index f196e29f1b3bee..fed844ccd7893f 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c @@ -155,9 +155,8 @@ int vmw_du_crtc_atomic_check(struct drm_crtc *crtc, * some actual rendering so give a clue as why it's blank. */ if (new_state->enable && !has_primary) - drm_dbg_driver(&vmw->drm, - "CRTC without a primary plane will be blank.\n"); - + drm_info_once(&vmw->drm, + "CRTC without a primary plane will be blank.\n"); if (new_state->connector_mask != connector_mask && new_state->connector_mask != 0) { From eee4285a8c3c918bbd21791e17f2bb261a709792 Mon Sep 17 00:00:00 2001 From: Zack Rusin Date: Thu, 29 Oct 2026 02:22:25 -0400 Subject: [PATCH 0686/2102] drm/vmwgfx: log MOB limits outside the manager spinlock vmw_gmrid_man_get_node reports MOB limit expansion and allocation failures through vmw_host_printf while holding gman->lock. The helper formats its messages with GFP_KERNEL allocations, which may sleep. KDE startup and desktop mode changes can reach this path, producing "BUG: sleeping function called from invalid context" from kvasprintf() while the manager spinlock is held. That's likely a separate bug because KDE shouldn't be using that much memory but to debug that properly stop filling kernel logs with warnings. Defer both host messages until after dropping the spinlock. Capture the failed allocation's page limit and roll back its accounting while locked, then report the error and free the resource after unlocking. Use drm_warn for the guest messages so they identify the device. Fixes: cfdc3458db8a ("drm/vmwgfx: Be a lot more flexible with MOB limits") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Zack Rusin Reviewed-by: Maaz Mombasawala Link: https://patch.msgid.link/20261029215700.3009996-1-zack.rusin@broadcom.com --- drivers/gpu/drm/vmwgfx/vmwgfx_gmrid_manager.c | 55 ++++++++++++------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_gmrid_manager.c b/drivers/gpu/drm/vmwgfx/vmwgfx_gmrid_manager.c index d607452dff6a8e..cc580ce5779782 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_gmrid_manager.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_gmrid_manager.c @@ -54,8 +54,11 @@ static int vmw_gmrid_man_get_node(struct ttm_resource_manager *man, const struct ttm_place *place, struct ttm_resource **res) { + struct vmw_private *vmw = vmw_priv_from_ttm(bo->bdev); struct vmwgfx_gmrid_man *gman = to_gmrid_manager(man); - int id; + u32 max_gmr_pages = 0; + bool mob_overflow = false; + int id, ret = 0; *res = kmalloc_obj(**res); if (!*res) @@ -85,43 +88,53 @@ static int vmw_gmrid_man_get_node(struct ttm_resource_manager *man, const unsigned long max_graphics_pages = totalram_pages() / 2; uint32_t new_max_pages = 0; - DRM_WARN("vmwgfx: mob memory overflow. Consider increasing guest RAM and graphicsMemory.\n"); - vmw_host_printf("vmwgfx, warning: mob memory overflow. Consider increasing guest RAM and graphicsMemory.\n"); + mob_overflow = true; + drm_warn(&vmw->drm, + "vmwgfx: mob memory overflow. Consider increasing guest RAM and graphicsMemory.\n"); if (gman->max_gmr_pages > (max_graphics_pages / 2)) { - DRM_WARN("vmwgfx: guest requires more than half of RAM for graphics.\n"); + drm_warn(&vmw->drm, + "vmwgfx: guest requires more than half of RAM for graphics.\n"); new_max_pages = max_graphics_pages; } else new_max_pages = gman->max_gmr_pages * 2; if (new_max_pages > gman->max_gmr_pages && new_max_pages >= gman->used_gmr_pages) { - DRM_WARN("vmwgfx: increasing guest mob limits to %u KiB.\n", - ((new_max_pages) << (PAGE_SHIFT - 10))); + drm_warn(&vmw->drm, + "vmwgfx: increasing guest mob limits to %u KiB.\n", + new_max_pages << (PAGE_SHIFT - 10)); gman->max_gmr_pages = new_max_pages; } else { - char buf[256]; - snprintf(buf, sizeof(buf), - "vmwgfx, error: guest graphics is out of memory (mob limit at: %u KiB).\n", - ((gman->max_gmr_pages) << (PAGE_SHIFT - 10))); - vmw_host_printf(buf); - DRM_WARN("%s", buf); - goto nospace; + max_gmr_pages = gman->max_gmr_pages; + gman->used_gmr_pages -= PFN_UP((*res)->size); + ret = -ENOSPC; + goto out_unlock; } } } (*res)->start = id; +out_unlock: spin_unlock(&gman->lock); - return 0; -nospace: - gman->used_gmr_pages -= PFN_UP((*res)->size); - spin_unlock(&gman->lock); - ida_free(&gman->gmr_ida, id); - ttm_resource_fini(man, *res); - kfree(*res); - return -ENOSPC; + /* Host logging allocates with GFP_KERNEL and must run unlocked. */ + if (mob_overflow) + vmw_host_printf("%s", + "vmwgfx, warning: mob memory overflow. Consider increasing guest RAM and graphicsMemory.\n"); + if (ret) { + char buf[256]; + + snprintf(buf, sizeof(buf), + "vmwgfx, error: guest graphics is out of memory (mob limit at: %u KiB).\n", + max_gmr_pages << (PAGE_SHIFT - 10)); + vmw_host_printf("%s", buf); + drm_warn(&vmw->drm, "%s", buf); + ida_free(&gman->gmr_ida, id); + ttm_resource_fini(man, *res); + kfree(*res); + } + return ret; } static void vmw_gmrid_man_put_node(struct ttm_resource_manager *man, From ac65fcce7f4d6e327ab7b755f999a8b15381d3f0 Mon Sep 17 00:00:00 2001 From: Antonio Borneo Date: Mon, 16 Nov 2026 20:01:30 +0100 Subject: [PATCH 0687/2102] watchdog: stm32_iwdg: use managed variant of dev_pm_set_wake_irq() On probe failure after stm32_iwdg_irq_init() or on driver unbind, the struct wake_irq allocated by dev_pm_set_wake_irq() is leaked and dev->power.wakeirq remains attached to the device. Any subsequent attempt to re-probe the device hits the dev->power.wakeirq check in dev_pm_attach_wake_irq(), triggers a dev_WARN_ONCE() splat, and fails probe with -EEXIST. Use the managed version devm_pm_set_wake_irq(). This is reported by Sashiko inside the raw log of another commit that touches the same driver. Fixes: 3ab1663af6c1 ("watchdog: stm32_iwdg: Add pretimeout support") Reported-by: Sashiko Link: https://sashiko.dev/#/message/20261116132416.1184447-3-antonio.borneo%40foss.st.com Link: https://sashiko.dev/#/log/249869 Signed-off-by: Antonio Borneo Link: https://patch.msgid.link/20261116190130.1191501-1-antonio.borneo@foss.st.com Signed-off-by: Guenter Roeck --- drivers/watchdog/stm32_iwdg.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/watchdog/stm32_iwdg.c b/drivers/watchdog/stm32_iwdg.c index 30c26a8beae424..2d37fce0ff680f 100644 --- a/drivers/watchdog/stm32_iwdg.c +++ b/drivers/watchdog/stm32_iwdg.c @@ -309,7 +309,7 @@ static int stm32_iwdg_irq_init(struct platform_device *pdev, if (ret) return ret; - ret = dev_pm_set_wake_irq(dev, irq); + ret = devm_pm_set_wake_irq(dev, irq); if (ret) return ret; } From 73d857b33cdfaf35f8d3f833b36745d91c18db13 Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Mon, 9 Nov 2026 17:54:35 -0800 Subject: [PATCH 0688/2102] hwmon: (nct6775) Fix target temp and tolerance for NCT6106/6116/6126 In nct6775_probe(), the nct6106, nct6116, and nct6126 chip cases leave target_temp_mask, tolerance_mask, and speed_tolerance_limit zero-initialized. As a result, reading pwm*_target_temp from sysfs always returns 0, writing to pwm*_target_temp, pwm*_temp_tolerance, pwm*_crit_temp_tolerance, or fan*_tolerance clamps user-supplied values to 0, and pwm_update_registers() fails to clear existing tolerance bits in REG_FAN_MODE when updating fan control modes. Initialize target_temp_mask to 0xff, tolerance_mask to 0x07, and speed_tolerance_limit to 63 for NCT6106, NCT6116, and NCT6126, matching the hardware register layout shared with NCT5525 and NCT6776+. Fixes: 6c009501ff20 ("hwmon: (nct6775) Add support for NCT6102D/6106D") Fixes: 29c7cb485b32 ("hwmon: (nct6775) Integrate new model nct6116") Fixes: 437b3c2a4bdc ("hwmon: (nct6775) Add support for NCT6126D") Cc: stable@vger.kernel.org Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-76f191d0-4c79-4982-887e-e5c9a2ed7136 Cc: Anton Lundin Signed-off-by: Guenter Roeck --- drivers/hwmon/nct6775-core.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/drivers/hwmon/nct6775-core.c b/drivers/hwmon/nct6775-core.c index ac6f3f0ca2b363..123d62a87a43d0 100644 --- a/drivers/hwmon/nct6775-core.c +++ b/drivers/hwmon/nct6775-core.c @@ -3572,6 +3572,9 @@ int nct6775_probe(struct device *dev, struct nct6775_data *data, data->fan_from_reg = fan_from_reg13; data->fan_from_reg_min = fan_from_reg13; + data->target_temp_mask = 0xff; + data->tolerance_mask = 0x07; + data->speed_tolerance_limit = 63; data->temp_label = nct6776_temp_label; data->temp_mask = NCT6776_TEMP_MASK; @@ -3648,6 +3651,9 @@ int nct6775_probe(struct device *dev, struct nct6775_data *data, data->fan_from_reg = fan_from_reg13; data->fan_from_reg_min = fan_from_reg13; + data->target_temp_mask = 0xff; + data->tolerance_mask = 0x07; + data->speed_tolerance_limit = 63; data->temp_label = nct6776_temp_label; data->temp_mask = NCT6776_TEMP_MASK; @@ -3725,6 +3731,9 @@ int nct6775_probe(struct device *dev, struct nct6775_data *data, data->fan_from_reg = fan_from_reg13; data->fan_from_reg_min = fan_from_reg13; + data->target_temp_mask = 0xff; + data->tolerance_mask = 0x07; + data->speed_tolerance_limit = 63; data->temp_label = nct6776_temp_label; data->temp_mask = NCT6776_TEMP_MASK; From 3cc60eb1b9aa07da81593f8f027efefb67185144 Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Mon, 9 Nov 2026 18:13:26 -0800 Subject: [PATCH 0689/2102] hwmon: (nct6775) Fix swapped temperature tolerance register writes sensor_dev_template_pwm_temp_tolerance uses index 0 (backed by REG_FAN_MODE via pwm_update_registers()) while sensor_dev_template_pwm_crit_temp_tolerance uses index 1 (backed by REG_CRITICAL_TEMP_TOLERANCE). However, store_temp_tolerance() checks if (index) with inverted branches. As a result, writing to pwm*_temp_tolerance writes the new tolerance to REG_CRITICAL_TEMP_TOLERANCE instead of REG_FAN_MODE, while writing to pwm*_crit_temp_tolerance updates REG_FAN_MODE with temp_tolerance[0] and leaves REG_CRITICAL_TEMP_TOLERANCE unchanged. Invert the index check in store_temp_tolerance() so index 0 updates fan mode registers via pwm_update_registers() and index 1 writes to REG_CRITICAL_TEMP_TOLERANCE. Fixes: cdcaeceb74ff ("hwmon: (nct6775) Add support for automatic fan control") Cc: stable@vger.kernel.org Reported-by: Sashiko Cc: Anton Lundin Signed-off-by: Guenter Roeck --- drivers/hwmon/nct6775-core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/hwmon/nct6775-core.c b/drivers/hwmon/nct6775-core.c index 123d62a87a43d0..a1b6924cd4b717 100644 --- a/drivers/hwmon/nct6775-core.c +++ b/drivers/hwmon/nct6775-core.c @@ -2997,7 +2997,7 @@ store_temp_tolerance(struct device *dev, struct device_attribute *attr, mutex_lock(&data->update_lock); data->temp_tolerance[index][nr] = val; - if (index) + if (!index) err = pwm_update_registers(data, nr); else err = nct6775_write_value(data, data->REG_CRITICAL_TEMP_TOLERANCE[nr], val); From 39cd14ca605d1aa55a0ad26767014a88b5c39f20 Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Mon, 9 Nov 2026 18:14:18 -0800 Subject: [PATCH 0690/2102] hwmon: (nct6775) Fix tolerance bitmask when reading REG_FAN_MODE On NCT6775, bits 0..3 of REG_FAN_MODE hold the temperature or fan speed tolerance (tolerance_mask is 0x0f), whereas on NCT5525, NCT6106, NCT6116, NCT6126, and NCT6776+, only bits 0..2 hold the temperature tolerance or low 3 bits of speed tolerance (tolerance_mask is 0x07). However, nct6775_update_pwm() masks fanmodecfg with a hardcoded 0x0f. When bit 3 of REG_FAN_MODE is set on chips where tolerance_mask is 0x07, nct6775_update_pwm() includes bit 3 in temp_tolerance[0] and target_speed_tolerance, corrupting reported tolerance values and causing pwm_update_registers() to OR bit 3 back into REG_FAN_MODE. Mask fanmodecfg with data->tolerance_mask instead of 0x0f in nct6775_update_pwm(). Fixes: cdcaeceb74ff ("hwmon: (nct6775) Add support for automatic fan control") Cc: stable@vger.kernel.org Reported-by: Sashiko Cc: Anton Lundin Signed-off-by: Guenter Roeck --- drivers/hwmon/nct6775-core.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/hwmon/nct6775-core.c b/drivers/hwmon/nct6775-core.c index a1b6924cd4b717..6e00318c47fdb8 100644 --- a/drivers/hwmon/nct6775-core.c +++ b/drivers/hwmon/nct6775-core.c @@ -1455,10 +1455,10 @@ static int nct6775_update_pwm(struct device *dev) if (!data->temp_tolerance[0][i] || data->pwm_enable[i] != speed_cruise) - data->temp_tolerance[0][i] = fanmodecfg & 0x0f; + data->temp_tolerance[0][i] = fanmodecfg & data->tolerance_mask; if (!data->target_speed_tolerance[i] || data->pwm_enable[i] == speed_cruise) { - u8 t = fanmodecfg & 0x0f; + u8 t = fanmodecfg & data->tolerance_mask; if (data->REG_TOLERANCE_H) { err = nct6775_read_value(data, data->REG_TOLERANCE_H[i], ®); From e9bc5937517b64b0ed34b3e73e4b1630a4505ecf Mon Sep 17 00:00:00 2001 From: Ben Grisdale Date: Wed, 11 Nov 2026 12:51:54 +0000 Subject: [PATCH 0691/2102] regulator: tps65132: Fix incorrect bits for VNEG/VPOS discharge According to the TPS65132 datasheet [1], DISN (VNEG active discharge) is bit 0 of register 0x03, while DISP (VPOS active discharge) is bit 1, as described in Table 6. The driver currently has them swapped around, so setting the active discharge of one output changes it on the other. Swap the bit definitions to be consistent with the datasheet. Fixes: 77c129bfefc8 ("regulator: tps65132: add regulator driver for TI TPS65132") Link: https://www.ti.com/lit/ds/symlink/tps65132.pdf [1] Signed-off-by: Ben Grisdale Link: https://patch.msgid.link/20261111-tps65132-discharge-fix-v1-1-c796428a5d43@protonmail.ch Signed-off-by: Mark Brown --- drivers/regulator/tps65132-regulator.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/regulator/tps65132-regulator.c b/drivers/regulator/tps65132-regulator.c index 912db82ab51d06..42388a170116c9 100644 --- a/drivers/regulator/tps65132-regulator.c +++ b/drivers/regulator/tps65132-regulator.c @@ -37,8 +37,8 @@ #define TPS65132_VOUT_VMAX 6000000 #define TPS65132_VOUT_STEP 100000 -#define TPS65132_REG_APPS_DIS_VPOS BIT(0) -#define TPS65132_REG_APPS_DIS_VNEG BIT(1) +#define TPS65132_REG_APPS_DIS_VNEG BIT(0) +#define TPS65132_REG_APPS_DIS_VPOS BIT(1) #define TPS65132_REGULATOR_ID_VPOS 0 #define TPS65132_REGULATOR_ID_VNEG 1 From 32bcf30c28e0ce850b3ca58d4ec3041ee18e7931 Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Tue, 27 Oct 2026 09:02:55 -0700 Subject: [PATCH 0692/2102] watchdog: core: Clear wd_data pointer on errors In watchdog_cdev_register(), if device registration fails after the core watchdog_core_data structure is allocated and assigned to the persistent watchdog_device structure, the function frees the data but leaves a dangling pointer. During device registration, watchdog_cdev_register() links the newly allocated wd_data to wdd->wd_data. If a subsequent initialization step fails, such as the watchdog_kworker validation, dev_set_name(), misc_register(), or cdev_device_add(), the function cleans up by freeing wd_data via kfree() or put_device(). However, it fails to clear the wdd->wd_data pointer before returning. Furthermore, if cdev_device_add() fails after misc_register() exposed /dev/watchdog to userspace, a concurrent open may hold a reference to wd_data while the caller frees wdd, leaving wd_data->wdd dangling. Fix the problem by clearing wdd->wd_data on all error paths during watchdog registration, and clearing wd_data->wdd under wd_data->lock if cdev_device_add() fails. Fixes: b4ffb1909843 ("watchdog: Separate and maintain variables based on variable lifetime") Reported-by: Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-50fc8217-05c7-468f-a867-6ba925b50226 Reviewed-by: Tzung-Bi Shih Signed-off-by: Guenter Roeck Link: https://patch.msgid.link/20261027160302.2519282-2-linux@roeck-us.net Signed-off-by: Guenter Roeck --- drivers/watchdog/watchdog_dev.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/watchdog/watchdog_dev.c b/drivers/watchdog/watchdog_dev.c index e8c1fcb53c56c0..ed5b351842710c 100644 --- a/drivers/watchdog/watchdog_dev.c +++ b/drivers/watchdog/watchdog_dev.c @@ -1033,6 +1033,7 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) wdd->wd_data = wd_data; if (IS_ERR_OR_NULL(watchdog_kworker)) { + wdd->wd_data = NULL; kfree(wd_data); return -ENODEV; } @@ -1046,6 +1047,7 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) dev_set_drvdata(&wd_data->dev, wdd); err = dev_set_name(&wd_data->dev, "watchdog%d", wdd->id); if (err) { + wdd->wd_data = NULL; put_device(&wd_data->dev); return err; } @@ -1066,6 +1068,7 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) pr_err("%s: a legacy watchdog module is probably present.\n", wdd->info->identity); old_wd_data = NULL; + wdd->wd_data = NULL; put_device(&wd_data->dev); return err; } @@ -1084,6 +1087,10 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) misc_deregister(&watchdog_miscdev); old_wd_data = NULL; } + mutex_lock(&wd_data->lock); + wd_data->wdd = NULL; + wdd->wd_data = NULL; + mutex_unlock(&wd_data->lock); put_device(&wd_data->dev); return err; } From 4da537f3b55220b31e5967466d54daaa38203660 Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Tue, 27 Oct 2026 09:02:56 -0700 Subject: [PATCH 0693/2102] watchdog: core: Add missing locks Add missing locks to watchdog_open(), watchdog_cdev_unregister(), and watchdog_set_last_hw_keepalive(). Also protect old_wd_data with its own lock to prevent its modification while in use, acquiring wd_data->lock before releasing old_wd_data_lock in watchdog_open() to avoid a TOCTOU race, and keeping misc_deregister() outside old_wd_data_lock to avoid lock ordering inversion with misc_mtx. Fixes: b4ffb1909843 ("watchdog: Separate and maintain variables based on variable lifetime") Reviewed-by: Tzung-Bi Shih Signed-off-by: Guenter Roeck Link: https://patch.msgid.link/20261027160302.2519282-3-linux@roeck-us.net Signed-off-by: Guenter Roeck --- drivers/watchdog/watchdog_dev.c | 42 ++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/drivers/watchdog/watchdog_dev.c b/drivers/watchdog/watchdog_dev.c index ed5b351842710c..50224877ff49eb 100644 --- a/drivers/watchdog/watchdog_dev.c +++ b/drivers/watchdog/watchdog_dev.c @@ -55,6 +55,7 @@ static dev_t watchdog_devt; /* Reference to watchdog device behind /dev/watchdog */ static struct watchdog_core_data *old_wd_data; +static DEFINE_MUTEX(old_wd_data_lock); static struct kthread_worker *watchdog_kworker; @@ -869,17 +870,32 @@ static int watchdog_open(struct inode *inode, struct file *file) int err; /* Get the corresponding watchdog device */ - if (imajor(inode) == MISC_MAJOR) + if (imajor(inode) == MISC_MAJOR) { + mutex_lock(&old_wd_data_lock); wd_data = old_wd_data; - else + if (!wd_data) { + mutex_unlock(&old_wd_data_lock); + return -ENODEV; + } + mutex_lock(&wd_data->lock); + mutex_unlock(&old_wd_data_lock); + } else { wd_data = container_of(inode->i_cdev, struct watchdog_core_data, cdev); + mutex_lock(&wd_data->lock); + } /* the watchdog is single open! */ - if (test_and_set_bit(_WDOG_DEV_OPEN, &wd_data->status)) + if (test_and_set_bit(_WDOG_DEV_OPEN, &wd_data->status)) { + mutex_unlock(&wd_data->lock); return -EBUSY; + } wdd = wd_data->wdd; + if (!wdd) { + err = -ENODEV; + goto out_clear; + } /* * If the /dev/watchdog device is open, we don't want the module @@ -909,6 +925,8 @@ static int watchdog_open(struct inode *inode, struct file *file) */ wd_data->open_deadline = KTIME_MAX; + mutex_unlock(&wd_data->lock); + /* dev/watchdog is a virtual (and thus non-seekable) filesystem */ return stream_open(inode, file); @@ -916,6 +934,7 @@ static int watchdog_open(struct inode *inode, struct file *file) module_put(wd_data->wdd->ops->owner); out_clear: clear_bit(_WDOG_DEV_OPEN, &wd_data->status); + mutex_unlock(&wd_data->lock); return err; } @@ -1085,7 +1104,9 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) wdd->id, MAJOR(watchdog_devt), wdd->id); if (wdd->id == 0) { misc_deregister(&watchdog_miscdev); + mutex_lock(&old_wd_data_lock); old_wd_data = NULL; + mutex_unlock(&old_wd_data_lock); } mutex_lock(&wd_data->lock); wd_data->wdd = NULL; @@ -1131,9 +1152,12 @@ static void watchdog_cdev_unregister(struct watchdog_device *wdd) cdev_device_del(&wd_data->cdev, &wd_data->dev); if (wdd->id == 0) { misc_deregister(&watchdog_miscdev); + mutex_lock(&old_wd_data_lock); old_wd_data = NULL; + mutex_unlock(&old_wd_data_lock); } + mutex_lock(&wd_data->lock); if (watchdog_active(wdd) && test_bit(WDOG_STOP_ON_UNREGISTER, &wdd->status)) { watchdog_stop(wdd); @@ -1141,7 +1165,6 @@ static void watchdog_cdev_unregister(struct watchdog_device *wdd) watchdog_hrtimer_pretimeout_stop(wdd); - mutex_lock(&wd_data->lock); wd_data->wdd = NULL; wdd->wd_data = NULL; mutex_unlock(&wd_data->lock); @@ -1208,20 +1231,27 @@ int watchdog_set_last_hw_keepalive(struct watchdog_device *wdd, { struct watchdog_core_data *wd_data; ktime_t now; + int ret = 0; if (!wdd) return -EINVAL; wd_data = wdd->wd_data; + if (!wd_data) + return -ENODEV; + + mutex_lock(&wd_data->lock); now = ktime_get(); wd_data->last_hw_keepalive = ktime_sub(now, ms_to_ktime(last_ping_ms)); if (watchdog_hw_running(wdd) && handle_boot_enabled) - return __watchdog_ping(wdd); + ret = __watchdog_ping(wdd); - return 0; + mutex_unlock(&wd_data->lock); + + return ret; } EXPORT_SYMBOL_GPL(watchdog_set_last_hw_keepalive); From d22343336beb0fdfa583da80a08684f8e18878ec Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Tue, 27 Oct 2026 09:02:57 -0700 Subject: [PATCH 0694/2102] watchdog: core: Prevent ping worker from re-arming timer on suspend In watchdog_dev_suspend(), hrtimer_cancel() is called before kthread_cancel_work_sync(). If the timer expired just before hrtimer_cancel() and queued watchdog_ping_work(), the worker can run and acquire wd_data->lock while kthread_cancel_work_sync() waits for it to finish. Because no state flag indicates that the watchdog is suspended, watchdog_worker_should_ping() returns true and __watchdog_ping() re-arms wd_data->timer while the device is suspended. Add a _WDOG_SUSPENDED internal status bit to wd_data->status, set it under wd_data->lock in watchdog_dev_suspend(), clear it under wd_data->lock in watchdog_dev_resume(), and check it in watchdog_worker_should_ping(), watchdog_need_worker(), and __watchdog_ping() so the timer cannot be armed while suspended. Fixes: 60bcd91aafd2 ("watchdog: introduce watchdog_dev_suspend/resume") Reviewed-by: Tzung-Bi Shih Signed-off-by: Guenter Roeck Link: https://patch.msgid.link/20261027160302.2519282-4-linux@roeck-us.net Signed-off-by: Guenter Roeck --- drivers/watchdog/watchdog_core.h | 1 + drivers/watchdog/watchdog_dev.c | 15 +++++++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/drivers/watchdog/watchdog_core.h b/drivers/watchdog/watchdog_core.h index ab825d9f9248d0..c6df5a584357a2 100644 --- a/drivers/watchdog/watchdog_core.h +++ b/drivers/watchdog/watchdog_core.h @@ -60,6 +60,7 @@ struct watchdog_core_data { #define _WDOG_DEV_OPEN 0 /* Opened ? */ #define _WDOG_ALLOW_RELEASE 1 /* Did we receive the magic char ? */ #define _WDOG_KEEPALIVE 2 /* Did we receive a keepalive ? */ +#define _WDOG_SUSPENDED 3 /* Suspended ? */ }; /* diff --git a/drivers/watchdog/watchdog_dev.c b/drivers/watchdog/watchdog_dev.c index 50224877ff49eb..e38f1ef8e683ea 100644 --- a/drivers/watchdog/watchdog_dev.c +++ b/drivers/watchdog/watchdog_dev.c @@ -81,6 +81,9 @@ static inline bool watchdog_need_worker(struct watchdog_device *wdd) unsigned int hm = wdd->max_hw_heartbeat_ms; unsigned int t = wdd->timeout * 1000; + if (test_bit(_WDOG_SUSPENDED, &wdd->wd_data->status)) + return false; + /* * A worker to generate heartbeat requests is needed if all of the * following conditions are true. @@ -154,9 +157,10 @@ static int __watchdog_ping(struct watchdog_device *wdd) now = ktime_get(); if (ktime_after(earliest_keepalive, now)) { - hrtimer_start(&wd_data->timer, - ktime_sub(earliest_keepalive, now), - HRTIMER_MODE_REL_HARD); + if (!test_bit(_WDOG_SUSPENDED, &wd_data->status)) + hrtimer_start(&wd_data->timer, + ktime_sub(earliest_keepalive, now), + HRTIMER_MODE_REL_HARD); return 0; } @@ -207,7 +211,7 @@ static bool watchdog_worker_should_ping(struct watchdog_core_data *wd_data) { struct watchdog_device *wdd = wd_data->wdd; - if (!wdd) + if (!wdd || test_bit(_WDOG_SUSPENDED, &wd_data->status)) return false; if (watchdog_active(wdd)) @@ -1318,6 +1322,8 @@ int watchdog_dev_suspend(struct watchdog_device *wdd) mutex_lock(&wd_data->lock); if (watchdog_worker_should_ping(wd_data)) ret = __watchdog_ping(wd_data->wdd); + if (!ret) + set_bit(_WDOG_SUSPENDED, &wd_data->status); mutex_unlock(&wd_data->lock); if (ret) @@ -1346,6 +1352,7 @@ int watchdog_dev_resume(struct watchdog_device *wdd) * ping worker if needed. */ mutex_lock(&wd_data->lock); + clear_bit(_WDOG_SUSPENDED, &wd_data->status); if (watchdog_worker_should_ping(wd_data)) ret = __watchdog_ping(wd_data->wdd); mutex_unlock(&wd_data->lock); From 19f018a8a898a81d848be4b12bb9f707721bdb02 Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Tue, 27 Oct 2026 09:02:58 -0700 Subject: [PATCH 0695/2102] watchdog: core: Stop pretimeout hrtimer on suspend During system suspend, watchdog_dev_suspend() pings the watchdog (which restarts the software pretimeout hrtimer) and stops the keepalive ping worker, but fails to stop the pretimeout hrtimer. Because CLOCK_MONOTONIC continues ticking until the system fully suspends, a suspend process taking longer than the configured pretimeout will trigger a spurious pretimeout event. Stop the pretimeout hrtimer in watchdog_dev_suspend(), prevent watchdog_hrtimer_pretimeout_start() from starting it while the watchdog is suspended, and restart it in watchdog_dev_resume() if the hardware watchdog is running. Fixes: 60bcd91aafd2 ("watchdog: introduce watchdog_dev_suspend/resume") Reviewed-by: Tzung-Bi Shih Signed-off-by: Guenter Roeck Link: https://patch.msgid.link/20261027160302.2519282-5-linux@roeck-us.net Signed-off-by: Guenter Roeck --- drivers/watchdog/watchdog_dev.c | 3 +++ drivers/watchdog/watchdog_hrtimer_pretimeout.c | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/drivers/watchdog/watchdog_dev.c b/drivers/watchdog/watchdog_dev.c index e38f1ef8e683ea..af756ee228b239 100644 --- a/drivers/watchdog/watchdog_dev.c +++ b/drivers/watchdog/watchdog_dev.c @@ -1334,6 +1334,7 @@ int watchdog_dev_suspend(struct watchdog_device *wdd) * suspended */ hrtimer_cancel(&wd_data->timer); + watchdog_hrtimer_pretimeout_stop(wdd); kthread_cancel_work_sync(&wd_data->work); return 0; @@ -1355,6 +1356,8 @@ int watchdog_dev_resume(struct watchdog_device *wdd) clear_bit(_WDOG_SUSPENDED, &wd_data->status); if (watchdog_worker_should_ping(wd_data)) ret = __watchdog_ping(wd_data->wdd); + if (watchdog_hw_running(wdd) && !ret) + watchdog_hrtimer_pretimeout_start(wdd); mutex_unlock(&wd_data->lock); return ret; diff --git a/drivers/watchdog/watchdog_hrtimer_pretimeout.c b/drivers/watchdog/watchdog_hrtimer_pretimeout.c index 49a05ea60c9792..5c88e6467994b9 100644 --- a/drivers/watchdog/watchdog_hrtimer_pretimeout.c +++ b/drivers/watchdog/watchdog_hrtimer_pretimeout.c @@ -31,7 +31,8 @@ void watchdog_hrtimer_pretimeout_start(struct watchdog_device *wdd) { if (!(wdd->info->options & WDIOF_PRETIMEOUT) && wdd->pretimeout && - !watchdog_pretimeout_invalid(wdd, wdd->pretimeout)) + !watchdog_pretimeout_invalid(wdd, wdd->pretimeout) && + !test_bit(_WDOG_SUSPENDED, &wdd->wd_data->status)) hrtimer_start(&wdd->wd_data->pretimeout_timer, ktime_set(wdd->timeout - wdd->pretimeout, 0), HRTIMER_MODE_REL); From 8cdd82238ed3f366850dd0bd1e130e09ba2ebc4c Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Tue, 27 Oct 2026 09:02:59 -0700 Subject: [PATCH 0696/2102] watchdog: core: Restore WDOG_HW_RUNNING if stopping watchdog fails In watchdog_stop(), WDOG_HW_RUNNING is cleared before calling wdd->ops->stop(). If wdd->ops->stop() returns an error, WDOG_ACTIVE remains set, but WDOG_HW_RUNNING is left cleared. As a result, subsequent calls to watchdog_ping() become no-ops, and watchdog_release() sees watchdog_hw_running() as false and drops the module and device references while the ping worker (guided by WDOG_ACTIVE) continues to run. Restore WDOG_HW_RUNNING if wdd->ops->stop() fails. Fixes: 3c10bbde10fe ("watchdog: core: Clear WDOG_HW_RUNNING before calling the stop function") Cc: Tzung-Bi Shih Signed-off-by: Guenter Roeck Reviewed-by: Tzung-Bi Shih Link: https://patch.msgid.link/20261027160302.2519282-6-linux@roeck-us.net Signed-off-by: Guenter Roeck --- drivers/watchdog/watchdog_dev.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/watchdog/watchdog_dev.c b/drivers/watchdog/watchdog_dev.c index af756ee228b239..47b0735ed6ac83 100644 --- a/drivers/watchdog/watchdog_dev.c +++ b/drivers/watchdog/watchdog_dev.c @@ -312,6 +312,7 @@ static int watchdog_stop(struct watchdog_device *wdd) clear_bit(WDOG_HW_RUNNING, &wdd->status); err = wdd->ops->stop(wdd); if (err < 0) { + set_bit(WDOG_HW_RUNNING, &wdd->status); pr_err("watchdog%d: Failed to stop watchdog: %pe\n", wdd->id, ERR_PTR(err)); } From 9208893253e755b3acf2bc1af038d5c973cc3b45 Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Tue, 27 Oct 2026 09:03:51 -0700 Subject: [PATCH 0697/2102] watchdog: core: Cancel timer if cdev_device_add() fails If misc_register() exposed the device to userspace before cdev_device_add() is called, a concurrent watchdog_open() could start the watchdog and arm wd_data->timer as well as the pretimeout timer. Also, if the hardware watchdog was already running, watchdog_open() expects the device and module references to have been acquired prior to opening. If cdev_device_add() then fails, the error path drops the device reference but fails to stop the watchdog, cancel the timers, and stop the worker, leaving the watchdog active and timers armed that can later fire and dereference freed memory. Furthermore, if a concurrent watchdog_open() saw hw_running == true before cdev_device_add() was called, it skipped taking its own device reference, allowing put_device() on the error path to free wd_data while the file descriptor is still open. Similarly, when unregistering a running watchdog that is not currently open, the extra hw_running module and device references were never released. Fix the problem by initializing wd_data and taking the running-watchdog references before exposing the device via misc_register(), stopping the watchdog and canceling both the heartbeat and pretimeout timers and stopping the worker on registration failure, and releasing unclaimed running-watchdog references on registration failure and unregistration. Fixes: ee142889e32f ("watchdog: Introduce WDOG_HW_RUNNING flag") Reported-by: Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-50fc8217-05c7-468f-a867-6ba925b50226 Reviewed-by: Tzung-Bi Shih Signed-off-by: Guenter Roeck Link: https://patch.msgid.link/20261027160353.2519323-1-linux@roeck-us.net Signed-off-by: Guenter Roeck --- drivers/watchdog/watchdog_dev.c | 79 ++++++++++++++++++++------------- 1 file changed, 49 insertions(+), 30 deletions(-) diff --git a/drivers/watchdog/watchdog_dev.c b/drivers/watchdog/watchdog_dev.c index 47b0735ed6ac83..ef2254188f7fa8 100644 --- a/drivers/watchdog/watchdog_dev.c +++ b/drivers/watchdog/watchdog_dev.c @@ -1046,6 +1046,7 @@ static const struct class watchdog_class = { static int watchdog_cdev_register(struct watchdog_device *wdd) { struct watchdog_core_data *wd_data; + bool hw_running; int err; wd_data = kzalloc_obj(struct watchdog_core_data); @@ -1081,6 +1082,29 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) HRTIMER_MODE_REL_HARD); watchdog_hrtimer_pretimeout_init(wdd); + /* Fill in the data structures */ + cdev_init(&wd_data->cdev, &watchdog_fops); + wd_data->cdev.owner = wdd->ops->owner; + + /* Record time of most recent heartbeat as 'just before now'. */ + wd_data->last_hw_keepalive = ktime_sub(ktime_get(), 1); + watchdog_set_open_deadline(wd_data); + + /* + * If the watchdog is running, prevent its driver from being unloaded, + * and schedule an immediate ping. + */ + if (watchdog_hw_running(wdd)) { + __module_get(wdd->ops->owner); + get_device(&wd_data->dev); + if (handle_boot_enabled) + hrtimer_start(&wd_data->timer, 0, + HRTIMER_MODE_REL_HARD); + else + pr_info("watchdog%d running and kernel based pre-userspace handler disabled\n", + wdd->id); + } + if (wdd->id == 0) { old_wd_data = wd_data; watchdog_miscdev.parent = wdd->parent; @@ -1092,16 +1116,10 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) pr_err("%s: a legacy watchdog module is probably present.\n", wdd->info->identity); old_wd_data = NULL; - wdd->wd_data = NULL; - put_device(&wd_data->dev); - return err; + goto err_clear; } } - /* Fill in the data structures */ - cdev_init(&wd_data->cdev, &watchdog_fops); - wd_data->cdev.owner = wdd->ops->owner; - /* Add the device */ err = cdev_device_add(&wd_data->cdev, &wd_data->dev); if (err) { @@ -1113,34 +1131,29 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) old_wd_data = NULL; mutex_unlock(&old_wd_data_lock); } - mutex_lock(&wd_data->lock); - wd_data->wdd = NULL; - wdd->wd_data = NULL; - mutex_unlock(&wd_data->lock); - put_device(&wd_data->dev); - return err; + goto err_clear; } - /* Record time of most recent heartbeat as 'just before now'. */ - wd_data->last_hw_keepalive = ktime_sub(ktime_get(), 1); - watchdog_set_open_deadline(wd_data); + return 0; - /* - * If the watchdog is running, prevent its driver from being unloaded, - * and schedule an immediate ping. - */ - if (watchdog_hw_running(wdd)) { - __module_get(wdd->ops->owner); - get_device(&wd_data->dev); - if (handle_boot_enabled) - hrtimer_start(&wd_data->timer, 0, - HRTIMER_MODE_REL_HARD); - else - pr_info("watchdog%d running and kernel based pre-userspace handler disabled\n", - wdd->id); +err_clear: + mutex_lock(&wd_data->lock); + hw_running = watchdog_hw_running(wdd); + if (watchdog_active(wdd)) + watchdog_stop(wdd); + watchdog_hrtimer_pretimeout_stop(wdd); + if (hw_running && !test_bit(_WDOG_DEV_OPEN, &wd_data->status)) { + module_put(wdd->ops->owner); + put_device(&wd_data->dev); } + wd_data->wdd = NULL; + wdd->wd_data = NULL; + mutex_unlock(&wd_data->lock); - return 0; + hrtimer_cancel(&wd_data->timer); + kthread_cancel_work_sync(&wd_data->work); + put_device(&wd_data->dev); + return err; } /** @@ -1153,6 +1166,7 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) static void watchdog_cdev_unregister(struct watchdog_device *wdd) { struct watchdog_core_data *wd_data = wdd->wd_data; + bool hw_running; cdev_device_del(&wd_data->cdev, &wd_data->dev); if (wdd->id == 0) { @@ -1163,6 +1177,7 @@ static void watchdog_cdev_unregister(struct watchdog_device *wdd) } mutex_lock(&wd_data->lock); + hw_running = watchdog_hw_running(wdd); if (watchdog_active(wdd) && test_bit(WDOG_STOP_ON_UNREGISTER, &wdd->status)) { watchdog_stop(wdd); @@ -1170,6 +1185,10 @@ static void watchdog_cdev_unregister(struct watchdog_device *wdd) watchdog_hrtimer_pretimeout_stop(wdd); + if (hw_running && !test_bit(_WDOG_DEV_OPEN, &wd_data->status)) { + module_put(wdd->ops->owner); + put_device(&wd_data->dev); + } wd_data->wdd = NULL; wdd->wd_data = NULL; mutex_unlock(&wd_data->lock); From e1d91be1ec2e68458d4e4eef33b0401016c54e26 Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Tue, 27 Oct 2026 09:03:52 -0700 Subject: [PATCH 0698/2102] watchdog: core: Fix unbalanced module_put() in watchdog_open() If the hardware watchdog is running (hw_running is true), try_module_get() is skipped. However, if watchdog_start() then fails, the code jumps to out_mod and unconditionally calls module_put(). This can cause a premature driver module unload while hardware timers or interrupts are active by dropping a reference that was never acquired. Only call module_put() if the hardware watchdog is not running to fix the problem. Reported-by: SashikoSashiko Link: https://sashiko.dev/#/bug/linux-64bd788f-a53c-4792-96ca-43b6c69c5fab Fixes: ee142889e32f ("watchdog: Introduce WDOG_HW_RUNNING flag") Reviewed-by: Tzung-Bi Shih Signed-off-by: Guenter Roeck Link: https://patch.msgid.link/20261027160353.2519323-2-linux@roeck-us.net Signed-off-by: Guenter Roeck --- drivers/watchdog/watchdog_dev.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/watchdog/watchdog_dev.c b/drivers/watchdog/watchdog_dev.c index ef2254188f7fa8..7c80d3753252d6 100644 --- a/drivers/watchdog/watchdog_dev.c +++ b/drivers/watchdog/watchdog_dev.c @@ -936,7 +936,8 @@ static int watchdog_open(struct inode *inode, struct file *file) return stream_open(inode, file); out_mod: - module_put(wd_data->wdd->ops->owner); + if (!hw_running) + module_put(wd_data->wdd->ops->owner); out_clear: clear_bit(_WDOG_DEV_OPEN, &wd_data->status); mutex_unlock(&wd_data->lock); From d8cda274400b52c5bb542158ae9f220f72f059f0 Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Tue, 27 Oct 2026 09:03:53 -0700 Subject: [PATCH 0699/2102] watchdog: core: Update last_keepalive in watchdog_start() When starting a watchdog whose hardware is already running, watchdog_start() calls __watchdog_ping() before marking the watchdog active, and fails to update wd_data->last_keepalive. As a result: 1. wd_data->last_keepalive remains 0, causing watchdog_get_timeleft() to calculate the elapsed time since the epoch and return 0 time left. 2. watchdog_update_worker() inside __watchdog_ping() evaluates watchdog_need_worker() and watchdog_next_keepalive() while WDOG_ACTIVE is still clear, using wd_data->open_deadline instead of wd_data->last_keepalive. If open_deadline has expired, the background keepalive timer is not armed; conversely, if the active watchdog does not need a worker, the boot keepalive timer is not canceled. Set WDOG_ACTIVE and wd_data->last_keepalive to started_at before calling __watchdog_ping(), and revert WDOG_ACTIVE and update the worker if __watchdog_ping() fails. Fixes: fbbe35dfcf94 ("watchdog: use __watchdog_ping in startup") Reviewed-by: Tzung-Bi Shih Signed-off-by: Guenter Roeck Link: https://patch.msgid.link/20261027160353.2519323-3-linux@roeck-us.net Signed-off-by: Guenter Roeck --- drivers/watchdog/watchdog_dev.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/drivers/watchdog/watchdog_dev.c b/drivers/watchdog/watchdog_dev.c index 7c80d3753252d6..aad3f1f1b4ce8d 100644 --- a/drivers/watchdog/watchdog_dev.c +++ b/drivers/watchdog/watchdog_dev.c @@ -264,10 +264,14 @@ static int watchdog_start(struct watchdog_device *wdd) started_at = ktime_get(); if (watchdog_hw_running(wdd) && wdd->ops->ping) { + set_bit(WDOG_ACTIVE, &wdd->status); + wd_data->last_keepalive = started_at; err = __watchdog_ping(wdd); if (err == 0) { - set_bit(WDOG_ACTIVE, &wdd->status); watchdog_hrtimer_pretimeout_start(wdd); + } else { + clear_bit(WDOG_ACTIVE, &wdd->status); + watchdog_update_worker(wdd); } } else { err = wdd->ops->start(wdd); From 1731c729762b54e41965a822415dd35b91570b81 Mon Sep 17 00:00:00 2001 From: Davidlohr Bueso Date: Fri, 6 Nov 2026 15:37:11 -0800 Subject: [PATCH 0700/2102] cxl/region: Restore a target's position from its slot after sorting Region auto-discovery records each arriving endpoint decoder in the first free @targets slot and sets cxled->pos to that slot. Once every member has arrived, cxl_region_sort_targets() calculates each one's interleave position and sorts the array by it. The original version of that function then restored cxled->pos from the member's slot in the sorted array, so that follow-on code could rely on p->targets[cxled->pos] naming the member, failed sort or not. Commit 0cf36a85c140 ("cxl/region: Use cxl_calc_interleave_pos() for auto-discovery") dropped that restore. cxled->pos now keeps whatever cxl_calc_interleave_pos() returned, which on failure is a negative errno. A member that could not be placed is left in a region it cannot be detached from by position: deleting that region runs __cxl_decoder_detach(), which finds pos < 0 and triggers: cxl region0: expected mem0:decoder3.0 at position -6 WARNING: drivers/cxl/core/region.c:2314 at __cxl_decoder_detach+0x483/0x910 A decoder committed by firmware behind a switch whose own decoders were not committed for the range is enough to get there The same stale position is what commit cbda6a2c2bec ("cxl/region: Fix out-of-bounds access in cxl_cancel_auto_attach()") had to work around by walking the array instead of indexing it. Restore cxled->pos from the member's slot after the sort. Fixes: 0cf36a85c140 ("cxl/region: Use cxl_calc_interleave_pos() for auto-discovery") Reviewed-by: Alison Schofield Signed-off-by: Davidlohr Bueso Reviewed-by: Ben Cheatham Reviewed-by: Li Ming Link: https://patch.msgid.link/20261106233711.2654827-1-dave@stgolabs.net Signed-off-by: Dave Jiang --- drivers/cxl/core/region.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/cxl/core/region.c b/drivers/cxl/core/region.c index a048bd5c06cb64..d344bc4b5aab25 100644 --- a/drivers/cxl/core/region.c +++ b/drivers/cxl/core/region.c @@ -2045,6 +2045,14 @@ static int cxl_region_sort_targets(struct cxl_region *cxlr) sort(p->targets, p->nr_targets, sizeof(p->targets[0]), cmp_interleave_pos, NULL); + /* + * Restore cxled->pos from its ->targets[] slot so that follow-on + * code paths can reliably do p->targets[cxled->pos] to + * self-reference their entry, whether or not the sort succeeded. + */ + for (i = 0; i < p->nr_targets; i++) + p->targets[i]->pos = i; + dev_dbg(&cxlr->dev, "region sort %s\n", rc ? "failed" : "successful"); return rc; } From b8183f9259b55fd79ecd0f2039bb4e9393eac936 Mon Sep 17 00:00:00 2001 From: Alison Schofield Date: Tue, 3 Nov 2026 09:07:10 -0800 Subject: [PATCH 0701/2102] cxl/region: Reject a repeat write of an endpoint decoder to targetN Writing an endpoint decoder to a region targetN attribute that already holds it returns -EBUSY, but leaves the partially populated region in an inconsistent state. The targetN attribute still names the decoder, so the failed write gives no indication that the region was damaged. Filling the remaining target positions can then trigger a NULL pointer dereference in cxl_region_setup_targets(). This can be reproduced through sysfs: echo $decoder > /sys/bus/cxl/devices/region0/target0 echo $decoder > /sys/bus/cxl/devices/region0/target0 echo $other_decoder > /sys/bus/cxl/devices/region0/target1 An existing check recognizes the repeated assignment but incorrectly allows the attachment to proceed, damaging region state. Remove that check so the repeated write is rejected without disturbing the existing attachment, consistent with the documented targetN ABI. Fixes: 9995576cef48 ("cxl/region: Move region-position validation to a helper") Signed-off-by: Alison Schofield Reviewed-by: Jonathan Cameron Reviewed-by: Ben Cheatham Reviewed-by: Dave Jiang Link: https://patch.msgid.link/e8235faea3d75dbfd45f197fe657c467b6259705.1793724885.git.alison.schofield@intel.com Signed-off-by: Dave Jiang --- drivers/cxl/core/region.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/drivers/cxl/core/region.c b/drivers/cxl/core/region.c index d344bc4b5aab25..f8c88113de357b 100644 --- a/drivers/cxl/core/region.c +++ b/drivers/cxl/core/region.c @@ -1764,9 +1764,6 @@ static int cxl_region_validate_position(struct cxl_region *cxlr, return -ENXIO; } - if (p->targets[pos] == cxled) - return 0; - if (p->targets[pos]) { struct cxl_endpoint_decoder *cxled_target = p->targets[pos]; struct cxl_memdev *cxlmd_target = cxled_to_memdev(cxled_target); From ce09d8c13a15fe881d0a04c91979dcdf45ed9543 Mon Sep 17 00:00:00 2001 From: Henry Martin Date: Wed, 11 Nov 2026 16:23:13 +0800 Subject: [PATCH 0702/2102] sctp: fix skb_over_panic when adding addresses with a pending delete of another family sctp_make_asconf_update_ip() accounts for a pending DEL_IP parameter by reusing the length of the address being added. The write-back side instead serializes the pending address itself, with its own address family. If the pending delete is IPv6 (20-byte parameter) while the added addresses are IPv4 (8-byte), the chunk is allocated 12 bytes short and sctp_addto_chunk() writes past the end of the skb. E.g. on mainline (05441d697f7f): skbuff: skb_over_panic: text:ffffffff84859c77 len:392 put:20 tail:0x188 end:0x180 dev: kernel BUG at net/core/skbuff.c:215! CPU: 0 UID: 1000 PID: 379 Comm: poc_sctp Call Trace: skb_panic skb_put sctp_addto_chunk sctp_make_asconf_update_ip sctp_send_asconf_add_ip sctp_setsockopt_bindx __x64_sys_setsockopt Requires addip enabled on the endpoint (net.sctp.addip_enable=1). Account for the pending delete with its own address family, as the write-back side already does. This issue was discovered by an LLM code scanner. Cc: stable@vger.kernel.org Fixes: 8a07eb0a50ae ("sctp: Add ASCONF operation on the single-homed host") Signed-off-by: Henry Martin Acked-by: Xin Long Link: https://patch.msgid.link/20261111082313.1606366-1-bsdhenrymartin@gmail.com Signed-off-by: Jakub Kicinski --- net/sctp/sm_make_chunk.c | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/net/sctp/sm_make_chunk.c b/net/sctp/sm_make_chunk.c index 15c2d87575a8a7..ba0474c2a0bc82 100644 --- a/net/sctp/sm_make_chunk.c +++ b/net/sctp/sm_make_chunk.c @@ -2870,7 +2870,6 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, int addr_param_len = 0; union sctp_addr *addr; int totallen = 0, i; - int del_pickup = 0; struct sctp_af *af; void *addr_buf; @@ -2885,16 +2884,21 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, totallen += addr_param_len; addr_buf += af->sockaddr_len; - if (asoc->asconf_addr_del_pending && !del_pickup) { - /* reuse the parameter length from the same scope one */ - totallen += paramlen; - totallen += addr_param_len; - del_pickup = 1; - - pr_debug("%s: picked same-scope del_pending addr, " - "totallen for all addresses is %d\n", - __func__, totallen); - } + } + + if (asoc->asconf_addr_del_pending) { + /* The DEL_IP parameter is serialized from the pending address + * itself below; account for its own address family, which may + * differ from the added ones. + */ + addr = asoc->asconf_addr_del_pending; + af = sctp_get_af_specific(addr->v4.sin_family); + totallen += paramlen; + totallen += af->to_addr_param(addr, &addr_param); + + pr_debug("%s: picked del_pending addr, " + "totallen for all addresses is %d\n", + __func__, totallen); } /* Create an asconf chunk with the required length. */ @@ -2917,7 +2921,7 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, addr_buf += af->sockaddr_len; } - if (flags == SCTP_PARAM_ADD_IP && del_pickup) { + if (flags == SCTP_PARAM_ADD_IP && asoc->asconf_addr_del_pending) { addr = asoc->asconf_addr_del_pending; af = sctp_get_af_specific(addr->v4.sin_family); addr_param_len = af->to_addr_param(addr, &addr_param); From 4cad287cb13c1fc32e4afa590e4148fa288d5741 Mon Sep 17 00:00:00 2001 From: Lorenzo Bianconi Date: Wed, 11 Nov 2026 10:54:27 +0100 Subject: [PATCH 0703/2102] net: stmmac: re-base EST after PTP settime64 stmmac_set_time() initializes the PTP clock through stmmac_init_systime() (TSINIT) while holding only ptp_lock. It neither takes est_lock nor disables and re-bases EST around the step, unlike stmmac_adjust_time(), which performs TSUPDT through stmmac_adjust_systime() under est_lock. Both operations change the PHC system time, so both invalidate the absolute EST base time. With settime64, a concurrent tc_taprio_configure() can read the pre-step clock through gettimex64() and program EST with a base time that is already stale once TSINIT lands. Separately, a taprio offload installed before the clock_settime() is never re-based and keeps running with its old base time until taprio is reconfigured. Take est_lock for the whole disable/step/reprogram sequence, as stmmac_adjust_time() does: disable EST before initializing the clock and call __stmmac_setup_est() afterwards so the base time is recomputed from the reserved taprio base time and the new clock. This keeps the established est_lock -> ptp_lock ordering: stmmac_init_systime() only uses readl_poll_timeout_atomic() under ptp_lock, and __stmmac_setup_est() takes ptp_lock through gettimex64(). Fixes: b60189e0392f ("net: stmmac: Integrate EST with TAPRIO scheduler API") Signed-off-by: Lorenzo Bianconi Reviewed-by: Nicolai Buchwitz Reviewed-by: Maxime Chevallier Link: https://patch.msgid.link/20261111-stmmac_set_time-est_lock-v1-1-da1554f233e6@oss.qualcomm.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c index 31a66e855d6b1a..6370bdc6c58b55 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c @@ -129,10 +129,19 @@ static int stmmac_set_time(struct ptp_clock_info *ptp, container_of(ptp, struct stmmac_priv, ptp_clock_ops); unsigned long flags; + mutex_lock(&priv->est_lock); + if (priv->est && priv->est->enable) + stmmac_est_configure(priv, priv, priv->est, + priv->plat->clk_ptp_rate, false); + write_lock_irqsave(&priv->ptp_lock, flags); stmmac_init_systime(priv, priv->ptpaddr, ts->tv_sec, ts->tv_nsec); write_unlock_irqrestore(&priv->ptp_lock, flags); + if (priv->est && priv->est->enable) + __stmmac_setup_est(priv); + mutex_unlock(&priv->est_lock); + return 0; } From 1b02f90976d4bdf8c67d19dadf31b4bba05eb66f Mon Sep 17 00:00:00 2001 From: Joas Antonio dos Santos Date: Thu, 12 Nov 2026 16:23:27 +0000 Subject: [PATCH 0704/2102] net: usb: smsc75xx: reject frames without a full header and FCS smsc75xx_rx_fixup() takes the frame length from the RX command word supplied by the device and strips the FCS by using "size - 4" for the allocation, skb_put() and memcpy() of each frame that is not the last one in the URB. The length is only checked against an upper bound and against skb->len, so a device can report a length field of 2..5, which gives a size of 0..3 after RXW_PADDING is subtracted. size is a u32, so "size - 4" then wraps to 0xfffffffc..0xffffffff. __netdev_alloc_skb() adds NET_SKB_PAD to the unsigned length, which wraps back to a small value and the allocation succeeds. skb_put() adds the length to the 32-bit skb->tail and skb->len, which also wrap, so the skb_over_panic() check does not fire. The following memcpy() then tries to copy almost 4 GiB from the URB buffer into that small allocation and writes far beyond it. A malicious or malfunctioning USB device can use this to corrupt kernel memory or crash the machine. A frame that holds an FCS but less than an Ethernet header is not valid either. usbnet drops it when it is the last frame in the URB, but the other frames go straight to usbnet_skb_return(), where eth_type_trans() reads an Ethernet header that was never copied into the new skb. Reject frames that are too short to hold an Ethernet header and an FCS, which covers both cases with one check. The driver does not set FLAG_RX_ASSEMBLE, so usbnet already counts rx_errors when smsc75xx_rx_fixup() returns 0. Also count rx_length_errors for these frames, as usbnet does for the short frames it drops itself. Found by LLM-assisted source review. Fixes: 1b3b2d9e772b ("net: usb: smsc75xx: stop lying about skb->truesize") Cc: stable@vger.kernel.org Signed-off-by: Joas Antonio dos Santos Reviewed-by: Andrew Lunn Link: https://patch.msgid.link/20261112-smsc75xx-rx-fcs-v3-1-6ad0378d0384@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/usb/smsc75xx.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/net/usb/smsc75xx.c b/drivers/net/usb/smsc75xx.c index 6f72a3f1590794..d1eca6bf7770f7 100644 --- a/drivers/net/usb/smsc75xx.c +++ b/drivers/net/usb/smsc75xx.c @@ -2217,6 +2217,14 @@ static int smsc75xx_rx_fixup(struct usbnet *dev, struct sk_buff *skb) return 0; } + if (unlikely(size < ETH_HLEN + ETH_FCS_LEN)) { + netif_dbg(dev, rx_err, dev->net, + "size err rx_cmd_a=0x%08x\n", + rx_cmd_a); + dev->net->stats.rx_length_errors++; + return 0; + } + /* last frame in this batch */ if (skb->len == size) { smsc75xx_rx_csum_offload(dev, skb, rx_cmd_a, From f675070191f202010b010160b509a543dd232ae6 Mon Sep 17 00:00:00 2001 From: Juan Agustin Niccolini Date: Wed, 11 Nov 2026 12:47:03 -0500 Subject: [PATCH 0705/2102] tcp: Fix the SO_REUSEPORT bind cache admitting a conflicting socket When the port is in the FASTREUSEPORT_STRICT state, inet_csk_get_port() skips the bind conflict check if sk_reuseport_match() finds the new socket's address covered by the socket cached in tb->fast_*. This is only safe if both sockets match on everything inet_bind_conflict() reads. The cache misses some of it: - It does not record sk_bound_dev_if or sk_reuse. - It records the family and IPV6_V6ONLY but never compares them with the new socket, so a cached v6only [::] (or 0.0.0.0) socket covers a dual-stack [::] socket. As a result, an unprivileged user can bind and listen on a port that another user is listening on, for example a dual-stack [::] socket on top of a 0.0.0.0 listener: victim: bind(0.0.0.0:P), listen() attacker: SO_REUSEPORT + IPV6_V6ONLY, bind([::]:P) /* fills cache */ attacker: SO_REUSEPORT, bind([::]:P), listen() /* should fail */ Only take the fast path when the new socket matches the cached one in family, IPV6_V6ONLY, bound device and SO_REUSEADDR. Identical SO_REUSEPORT listeners, the workload this cache was added for, still skip the scan (binding 16384 of them: 9.80 ms before, 9.86 ms after, 5874 ms with the full check every time). Fixes: 637bc8bbe6c0 ("inet: reset tb->fastreuseport when adding a reuseport sk") Cc: stable@vger.kernel.org Signed-off-by: Juan Agustin Niccolini Reviewed-by: Kuniyuki Iwashima Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261111174704.24312-2-juanagusnicco@gmail.com Signed-off-by: Jakub Kicinski --- include/net/inet_hashtables.h | 2 ++ net/ipv4/inet_connection_sock.c | 15 ++++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/include/net/inet_hashtables.h b/include/net/inet_hashtables.h index 6e2fe186d0dcb0..44b7e39a1245b0 100644 --- a/include/net/inet_hashtables.h +++ b/include/net/inet_hashtables.h @@ -87,6 +87,8 @@ struct inet_bind_bucket { __be32 fast_rcv_saddr; unsigned short fast_sk_family; bool fast_ipv6_only; + unsigned char fast_sk_reuse; + int fast_bound_dev_if; struct hlist_node node; struct hlist_head bhash2; struct rcu_head rcu; diff --git a/net/ipv4/inet_connection_sock.c b/net/ipv4/inet_connection_sock.c index ca3057192e6dae..d1c864b4252fae 100644 --- a/net/ipv4/inet_connection_sock.c +++ b/net/ipv4/inet_connection_sock.c @@ -420,13 +420,18 @@ static inline int sk_reuseport_match(struct inet_bind_bucket *tb, return 0; if (!uid_eq(tb->fastuid, sk_uid(sk))) return 0; - /* We only need to check the rcv_saddr if this tb was once marked + /* We only need to check the fast_* fields if this tb was once marked * without fastreuseport and then was reset, as we can only know that - * the fast_*rcv_saddr doesn't have any conflicts with the socks on the - * owners list. + * the socket they describe doesn't have any conflicts with the socks + * on the owners list. */ if (tb->fastreuseport == FASTREUSEPORT_ANY) return 1; + if (tb->fast_sk_family != sk->sk_family || + tb->fast_ipv6_only != ipv6_only_sock(sk) || + tb->fast_bound_dev_if != sk->sk_bound_dev_if || + tb->fast_sk_reuse != sk->sk_reuse) + return 0; #if IS_ENABLED(CONFIG_IPV6) if (tb->fast_sk_family == AF_INET6) return ipv6_rcv_saddr_equal(&tb->fast_v6_rcv_saddr, @@ -455,6 +460,8 @@ void inet_csk_update_fastreuse(const struct sock *sk, tb->fast_rcv_saddr = sk->sk_rcv_saddr; tb->fast_ipv6_only = ipv6_only_sock(sk); tb->fast_sk_family = sk->sk_family; + tb->fast_sk_reuse = sk->sk_reuse; + tb->fast_bound_dev_if = sk->sk_bound_dev_if; #if IS_ENABLED(CONFIG_IPV6) tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr; #endif @@ -482,6 +489,8 @@ void inet_csk_update_fastreuse(const struct sock *sk, tb->fast_rcv_saddr = sk->sk_rcv_saddr; tb->fast_ipv6_only = ipv6_only_sock(sk); tb->fast_sk_family = sk->sk_family; + tb->fast_sk_reuse = sk->sk_reuse; + tb->fast_bound_dev_if = sk->sk_bound_dev_if; #if IS_ENABLED(CONFIG_IPV6) tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr; #endif From 540410997a7da285994280097219a38c5d786473 Mon Sep 17 00:00:00 2001 From: Juan Agustin Niccolini Date: Wed, 11 Nov 2026 12:47:04 -0500 Subject: [PATCH 0706/2102] selftests: net: Add SO_REUSEPORT bind cache test to bind_wildcard.c Add a test for the bug fixed by "tcp: Fix the SO_REUSEPORT bind cache admitting a conflicting socket". With a 0.0.0.0 listener on the port, a v6only [::] SO_REUSEPORT socket fills the bind cache, and a dual-stack [::] SO_REUSEPORT socket must then fail to bind with EADDRINUSE. Without the fix: # RUN global.reuseport_v6only_cache ... # bind_wildcard.c:860:reuseport_v6only_cache:Expected ret (0) == -1 (-1) # reuseport_v6only_cache: Test terminated by assertion # FAIL global.reuseport_v6only_cache not ok 1 global.reuseport_v6only_cache With it: # RUN global.reuseport_v6only_cache ... # OK global.reuseport_v6only_cache ok 1 global.reuseport_v6only_cache Signed-off-by: Juan Agustin Niccolini Reviewed-by: Kuniyuki Iwashima Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261111174704.24312-3-juanagusnicco@gmail.com Signed-off-by: Jakub Kicinski --- tools/testing/selftests/net/bind_wildcard.c | 54 +++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/tools/testing/selftests/net/bind_wildcard.c b/tools/testing/selftests/net/bind_wildcard.c index be3298c791b22e..334a0cf87edfc7 100644 --- a/tools/testing/selftests/net/bind_wildcard.c +++ b/tools/testing/selftests/net/bind_wildcard.c @@ -811,4 +811,58 @@ TEST_F(bind_wildcard, reuseport) bind_socket(_metadata, self, variant, i, SO_REUSEPORT); } +/* The SO_REUSEPORT bind cache (tb->fast_*) filled by a v6only [::] socket + * must not let a dual-stack [::] socket skip the conflict check against a + * 0.0.0.0 listener. + */ +TEST(reuseport_v6only_cache) +{ + struct sockaddr_in6 addr6 = { + .sin6_family = AF_INET6, + .sin6_addr = in6addr_any, + }; + struct sockaddr_in addr4 = { + .sin_family = AF_INET, + .sin_addr.s_addr = htonl(INADDR_ANY), + }; + socklen_t addrlen; + int fd[3], ret; + int on = 1; + + ASSERT_EQ(unshare(CLONE_NEWNET), 0); + + /* bind(0.0.0.0:P), listen() */ + fd[0] = socket(AF_INET, SOCK_STREAM, 0); + ASSERT_GT(fd[0], 0); + ASSERT_EQ(bind(fd[0], (struct sockaddr *)&addr4, sizeof(addr4)), 0); + ASSERT_EQ(listen(fd[0], 1), 0); + + addrlen = sizeof(addr4); + ASSERT_EQ(getsockname(fd[0], (struct sockaddr *)&addr4, &addrlen), 0); + addr6.sin6_port = addr4.sin_port; + + /* SO_REUSEPORT + IPV6_V6ONLY, bind([::]:P) fills the cache. */ + fd[1] = socket(AF_INET6, SOCK_STREAM, 0); + ASSERT_GT(fd[1], 0); + ret = setsockopt(fd[1], SOL_IPV6, IPV6_V6ONLY, &on, sizeof(on)); + ASSERT_EQ(ret, 0); + ret = setsockopt(fd[1], SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)); + ASSERT_EQ(ret, 0); + ASSERT_EQ(bind(fd[1], (struct sockaddr *)&addr6, sizeof(addr6)), 0); + + /* SO_REUSEPORT, bind([::]:P) conflicts with 0.0.0.0:P. */ + fd[2] = socket(AF_INET6, SOCK_STREAM, 0); + ASSERT_GT(fd[2], 0); + ret = setsockopt(fd[2], SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)); + ASSERT_EQ(ret, 0); + + ret = bind(fd[2], (struct sockaddr *)&addr6, sizeof(addr6)); + ASSERT_EQ(ret, -1); + ASSERT_EQ(errno, EADDRINUSE); + + close(fd[2]); + close(fd[1]); + close(fd[0]); +} + TEST_HARNESS_MAIN From 5aac571d919087d766d85729e0b53f41d275eb7b Mon Sep 17 00:00:00 2001 From: Hangbin Liu Date: Thu, 12 Nov 2026 13:46:44 +0800 Subject: [PATCH 0707/2102] ipv6: ioam6: do not modify shared tuninfo eh.nexthdr ioam6_do_inline() and ioam6_do_encap() stored the next header into the shared ilwt->tuninfo template and then memcpy()ed it into the skb. The lwtstate is used from multiple CPUs without locking, so another packet can overwrite eh.nexthdr between the store and the memcpy. The packet can then leave with an HBH nexthdr that does not match its payload (e.g. TCP labelled as UDP, or a local packet labelled IPPROTO_IPV6). Set nexthdr on the per-packet Hop-by-Hop copy after memcpy instead, leave the shared template read-only. Mark the tuninfo argument const now that the shared template is no longer modified, and drop the unnecessary (u8 *) cast in memcpy. Fixes: 3edede08ff37 ("ipv6: ioam: Support for IOAM injection with lwtunnels") Fixes: 8cb3bf8bff3c ("ipv6: ioam: Add support for the ip6ip6 encapsulation") Reported-by: Sashiko Closes: https://lore.kernel.org/netdev/179336082844.3134.1265197633714491521@kernel.org Reviewed-by: Justin Iurman Signed-off-by: Hangbin Liu Link: https://patch.msgid.link/20261112-ipv6_ioam_lock-v4-1-89e3381be525@kylinos.cn Signed-off-by: Jakub Kicinski --- net/ipv6/ioam6_iptunnel.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/net/ipv6/ioam6_iptunnel.c b/net/ipv6/ioam6_iptunnel.c index cfb2c41634a0b0..e8be0d922f7463 100644 --- a/net/ipv6/ioam6_iptunnel.c +++ b/net/ipv6/ioam6_iptunnel.c @@ -254,10 +254,11 @@ static int ioam6_do_fill(struct net *net, struct sk_buff *skb) } static int ioam6_do_inline(struct net *net, struct sk_buff *skb, - struct ioam6_lwt_encap *tuninfo, + const struct ioam6_lwt_encap *tuninfo, struct dst_entry *cache_dst) { struct ipv6hdr *oldhdr, *hdr; + struct ipv6_opt_hdr *opt_hdr; int hdrlen, err; hdrlen = (tuninfo->eh.hdrlen + 1) << 3; @@ -276,12 +277,13 @@ static int ioam6_do_inline(struct net *net, struct sk_buff *skb, hdr = ipv6_hdr(skb); memmove(hdr, oldhdr, sizeof(*oldhdr)); - tuninfo->eh.nexthdr = hdr->nexthdr; skb_set_transport_header(skb, sizeof(*hdr)); skb_postpush_rcsum(skb, hdr, sizeof(*hdr) + hdrlen); - memcpy(skb_transport_header(skb), (u8 *)tuninfo, hdrlen); + opt_hdr = (struct ipv6_opt_hdr *)skb_transport_header(skb); + memcpy(opt_hdr, tuninfo, hdrlen); + opt_hdr->nexthdr = hdr->nexthdr; hdr->nexthdr = NEXTHDR_HOP; hdr->payload_len = cpu_to_be16(skb->len - sizeof(*hdr)); @@ -290,7 +292,7 @@ static int ioam6_do_inline(struct net *net, struct sk_buff *skb, } static int ioam6_do_encap(struct net *net, struct sk_buff *skb, - struct ioam6_lwt_encap *tuninfo, + const struct ioam6_lwt_encap *tuninfo, bool has_tunsrc, struct in6_addr *tunsrc, struct in6_addr *tundst, @@ -298,6 +300,7 @@ static int ioam6_do_encap(struct net *net, struct sk_buff *skb, { struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr, *inner_hdr; + struct ipv6_opt_hdr *opt_hdr; int hdrlen, len, err; hdrlen = (tuninfo->eh.hdrlen + 1) << 3; @@ -314,8 +317,9 @@ static int ioam6_do_encap(struct net *net, struct sk_buff *skb, skb_mac_header_rebuild(skb); skb_set_transport_header(skb, sizeof(*hdr)); - tuninfo->eh.nexthdr = NEXTHDR_IPV6; - memcpy(skb_transport_header(skb), (u8 *)tuninfo, hdrlen); + opt_hdr = (struct ipv6_opt_hdr *)skb_transport_header(skb); + memcpy(opt_hdr, tuninfo, hdrlen); + opt_hdr->nexthdr = NEXTHDR_IPV6; hdr = ipv6_hdr(skb); memcpy(hdr, inner_hdr, sizeof(*hdr)); From ea538b5790eed4f042ea787ea761cb1a695f8138 Mon Sep 17 00:00:00 2001 From: Henry Martin Date: Thu, 12 Nov 2026 12:24:15 +0800 Subject: [PATCH 0708/2102] ip6mr: prevent info-leak in ip6mr_cache_report() The non-WHOLEPKT branch copies the IPv6 header at offset 0 and then appends 40 bytes with skb_put(), but the mrt6msg is written at offset 0 after skb_reset_transport_header(), so the appended 40 bytes are never initialized. They hold stale heap contents. The report is queued to the mroute6 socket and copied into the IP6MRA_CREPORT_PKT netlink attribute, disclosing the stale bytes to user space. The stale bytes can contain kernel heap and image pointers, and the report is reachable from an unprivileged user namespace (MRT6_INIT in a new netns, plus the non-root RTNLGRP_IPV6_MROUTE_R group). Use skb_put_zero() instead, as the IPv4 code does since commit 4f34002e2e376 ("ipmr: prevent info-leak in pmr_cache_report()"). This issue was discovered by Tencent CodeBuddy Security. Fixes: 7bc570c8b4f75 ("[IPV6] MROUTE: Support multicast forwarding.") Cc: stable@vger.kernel.org Signed-off-by: Henry Martin Reviewed-by: Ido Schimmel Link: https://patch.msgid.link/20261112042415.617221-1-bsdhenrymartin@gmail.com Signed-off-by: Jakub Kicinski --- net/ipv6/ip6mr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/ipv6/ip6mr.c b/net/ipv6/ip6mr.c index dd0638d3c3f95a..b7ae220d6b21de 100644 --- a/net/ipv6/ip6mr.c +++ b/net/ipv6/ip6mr.c @@ -1154,7 +1154,7 @@ static int ip6mr_cache_report(const struct mr_table *mrt, struct sk_buff *pkt, /* * Add our header */ - skb_put(skb, sizeof(*msg)); + skb_put_zero(skb, sizeof(*msg)); skb_reset_transport_header(skb); msg = (struct mrt6msg *)skb_transport_header(skb); From f2540da93a113d3f0a70fd0961e00eb849ce8342 Mon Sep 17 00:00:00 2001 From: Yves Bieri Date: Thu, 12 Nov 2026 18:21:49 +0100 Subject: [PATCH 0709/2102] sctp: do not free a new asoc peeled off while sendmsg slept When sctp_sendmsg() creates a new association and sending on it fails with anything but -ESRCH, it frees the association. The send can sleep in sctp_wait_for_sndbuf(), which releases the socket lock, and meanwhile another thread can peel the new association off to a new socket. The wait then returns -EPIPE, and sctp_sendmsg() frees an association that now belongs to the peeled-off socket, without holding that socket's lock. If the peeled-off socket frees the association first, e.g. on close(), sctp_sendmsg() frees it a second time. Otherwise a syscall running concurrently on the peeled-off socket can use it after sctp_sendmsg() freed it. Both are reachable by an unprivileged user. The double free on net with KASAN: BUG: KASAN: double-free in sctp_tsnmap_free+0x5c/0x80 sctp_association_free+0x1eb/0x750 sctp_sendmsg+0x15ff/0x2020 Freed by task 836: sctp_association_free+0x1eb/0x750 sctp_primitive_ABORT+0x85/0xe0 sctp_close+0x22a/0x8d0 Commit dfcb9f4f99f1 ("sctp: deny peeloff operation on asocs with threads sleeping on it") fixed this double free by denying the peeloff. Commit cea0cc80a677 ("sctp: use the right sk after waking up from wait_buf sleep") replaced that check, and commit a0ff660058b8 ("sctp: return error if the asoc has been peeled off in sctp_wait_for_sndbuf") reverted it to return -EPIPE, without restoring the check. Fix this by holding a reference on the new association while sending on it, and by freeing it on error only if this socket still owns it. asoc->base.sk only changes in sctp_sock_migrate(), which runs with this socket locked, so the ownership check is stable. The reference keeps the check safe if the new owner frees the association meanwhile. Userspace still gets -EPIPE, and the association stays with the socket it was peeled off to. This was found by Xint Code, an AI code review agent, and reproduced as an unprivileged user on net with KASAN (trace above), without modifying the kernel or using error injection. With this patch the sender gets -EPIPE and the association keeps working on the peeled-off socket. Without a peeloff, a failed send that created the association (EAGAIN, EINTR) still frees it, and a peer ABORT while the sender sleeps still frees it exactly once. The SCTP selftest sctp_vrf.sh passes. The reproducer is available on request. Fixes: a0ff660058b8 ("sctp: return error if the asoc has been peeled off in sctp_wait_for_sndbuf") Cc: stable@vger.kernel.org Signed-off-by: Yves Bieri Acked-by: Xin Long Link: https://patch.msgid.link/20261112172149.27355-1-yves.bieri@theori.io Signed-off-by: Jakub Kicinski --- net/sctp/socket.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/net/sctp/socket.c b/net/sctp/socket.c index 8e647737b2567d..bc68af88e27104 100644 --- a/net/sctp/socket.c +++ b/net/sctp/socket.c @@ -2063,6 +2063,11 @@ static int sctp_sendmsg(struct sock *sk, struct msghdr *msg, size_t msg_len) asoc = transport->asoc; new = true; + /* sctp_sendmsg_to_asoc() may release the socket lock, + * and the new asoc can be peeled off meanwhile. Hold + * it, and free it on error only if sk still owns it. + */ + sctp_association_hold(asoc); } if (!sctp_style(sk, TCP) && !(sflags & SCTP_ADDR_OVER)) @@ -2084,8 +2089,11 @@ static int sctp_sendmsg(struct sock *sk, struct msghdr *msg, size_t msg_len) /* Send msg to the asoc */ err = sctp_sendmsg_to_asoc(asoc, msg, msg_len, transport, sinfo); - if (err < 0 && err != -ESRCH && new) - sctp_association_free(asoc); + if (new) { + if (err < 0 && err != -ESRCH && asoc->base.sk == sk) + sctp_association_free(asoc); + sctp_association_put(asoc); + } out_unlock: release_sock(sk); From 6836fa400109ac8495224a35f9b2c16dc9d0d129 Mon Sep 17 00:00:00 2001 From: Wenbo Sun Date: Thu, 12 Nov 2026 11:36:22 +0800 Subject: [PATCH 0710/2102] net: dcb: flush rewrite table on device unregister In dcbnl_flush_dev(), which is called upon NETDEV_UNREGISTER for net devices with dcbnl_ops, only entries in dcb_app_list matching dev->ifindex are freed. The entries in dcb_rewr_list added via dcb_setrewr() are not flushed. This causes a memory leak of struct dcb_app_type nodes in dcb_rewr_list when a DCB-capable net device is unregistered, and leaves stale entries in the global rewrite table that could inappropriately match if another net device later reuses the same ifindex. Iterate over dcb_rewr_list in dcbnl_flush_dev() and remove and free all entries matching dev->ifindex, mirroring the cleanup performed for dcb_app_list. This issue was found via LLM-assisted code review, confirmed by reproducing the leaked rewrite table entry upon netdevice unregistration in a User-Mode Linux (ARCH=um) environment, and verified in UML by confirming that all rewrite table entries for the unregistered netdevice are flushed. Fixes: 622f1b2fae2e ("net: dcb: add new rewrite table") Reviewed-by: Daniel Machon Tested-by: Daniel Machon Reviewed-by: Petr Machata Signed-off-by: Wenbo Sun Link: https://patch.msgid.link/20261112033622.40333-1-sunwenbo@cmss.chinamobile.com Signed-off-by: Jakub Kicinski --- net/dcb/dcbnl.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/net/dcb/dcbnl.c b/net/dcb/dcbnl.c index ad0aebe0ad3d2b..95250658ecc156 100644 --- a/net/dcb/dcbnl.c +++ b/net/dcb/dcbnl.c @@ -2393,6 +2393,13 @@ static void dcbnl_flush_dev(struct net_device *dev) } } + list_for_each_entry_safe(itr, tmp, &dcb_rewr_list, list) { + if (itr->ifindex == dev->ifindex) { + list_del(&itr->list); + kfree(itr); + } + } + spin_unlock_bh(&dcb_lock); } From 2718849027426f09c649a59b8f93fa7a00ced3ed Mon Sep 17 00:00:00 2001 From: Arnd Bergmann Date: Fri, 13 Nov 2026 11:11:00 +0100 Subject: [PATCH 0711/2102] net: kunit: move struct net_devmem_dmabuf_binding off stack The net_devmem_dmabuf_binding structure is really way too big to live on the stack, and causes warnings on my randconfig build machine with a reasonable per-function limit: net/core/net_test.c: In function 'netmem_ref_test_tcp_devmem_recv': net/core/net_test.c:1720:1: error: the frame size of 1744 bytes is larger than 1536 bytes [-Werror=frame-larger-than=] 1720 | } | ^ net/core/net_test.c: In function 'netmem_ref_test_skb_segment': net/core/net_test.c:1477:1: error: the frame size of 1584 bytes is larger than 1536 bytes [-Werror=frame-larger-than=] Since the binding object is never used concurrently in multiple tests, avoid this by just having a global copy of it and reinitializing it for every user. Fixes: 2285346afc99 ("net: kunit: test netmem, page_pool, and skb frag refcounting") Signed-off-by: Arnd Bergmann Reviewed-by: Mina Almasry Link: https://patch.msgid.link/20261113101109.3227815-1-arnd@kernel.org Signed-off-by: Jakub Kicinski --- net/core/net_test.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/net/core/net_test.c b/net/core/net_test.c index 2b5080c226636c..c36333b362115f 100644 --- a/net/core/net_test.c +++ b/net/core/net_test.c @@ -834,13 +834,14 @@ static void netmem_ref_test_pp_page(struct kunit *test) #endif #if defined(CONFIG_PAGE_POOL) && defined(CONFIG_NET_DEVMEM) +static struct net_devmem_dmabuf_binding binding; + static void dummy_percpu_ref_release(struct percpu_ref *ref) { } static void netmem_ref_test_net_iov(struct kunit *test) { - struct net_devmem_dmabuf_binding binding = {}; struct page_pool_params pp_params = { .order = 0, .pool_size = 4, @@ -853,6 +854,7 @@ static void netmem_ref_test_net_iov(struct kunit *test) long base_ref; int err; + memset(&binding, 0, sizeof(binding)); err = percpu_ref_init(&binding.ref, dummy_percpu_ref_release, PERCPU_REF_INIT_ATOMIC, GFP_KERNEL); KUNIT_ASSERT_EQ(test, err, 0); @@ -995,7 +997,6 @@ static void netmem_ref_test_release_data(struct kunit *test) .nid = NUMA_NO_NODE, }; struct sk_buff *skb, *clone1, *clone2, *ext; - struct net_devmem_dmabuf_binding binding = {}; struct net_iov niov = {}; struct page_pool *pool; struct page *page; @@ -1004,6 +1005,7 @@ static void netmem_ref_test_release_data(struct kunit *test) int base_ref; int i; + memset(&binding, 0, sizeof(binding)); pool = page_pool_create(&pp_params); KUNIT_ASSERT_FALSE(test, IS_ERR(pool)); page = page_pool_dev_alloc_pages(pool); @@ -1185,7 +1187,6 @@ static void netmem_ref_test_skb_segment(struct kunit *test) .flags = SKBFL_ZEROCOPY_ENABLE, }; struct sk_buff *head, *list, *segs, *seg; - struct net_devmem_dmabuf_binding binding = {}; struct net_iov niov = {}; struct page *pp_page, *reg_page; netmem_ref pp_nm, niov_nm; @@ -1193,6 +1194,7 @@ static void netmem_ref_test_skb_segment(struct kunit *test) long base_pp_ref, base_iov_ref; int base_pp_page_ref, base_reg_ref; + memset(&binding, 0, sizeof(binding)); pool = page_pool_create(&pp_params); KUNIT_ASSERT_FALSE(test, IS_ERR(pool)); pp_page = page_pool_dev_alloc_pages(pool); @@ -1484,7 +1486,6 @@ static void netmem_ref_test_try_coalesce(struct kunit *test) .nid = NUMA_NO_NODE, }; struct sk_buff *to, *from, *clone; - struct net_devmem_dmabuf_binding binding = {}; struct net_iov niov = {}; struct page *pp_page, *reg_page; netmem_ref pp_nm, niov_nm; @@ -1494,6 +1495,7 @@ static void netmem_ref_test_try_coalesce(struct kunit *test) bool fragstolen; int delta; + memset(&binding, 0, sizeof(binding)); pool = page_pool_create(&pp_params); KUNIT_ASSERT_FALSE(test, IS_ERR(pool)); pp_page = page_pool_dev_alloc_pages(pool); @@ -1616,7 +1618,6 @@ static void netmem_ref_test_tcp_devmem_recv(struct kunit *test) .pool_size = 4, .nid = NUMA_NO_NODE, }; - struct net_devmem_dmabuf_binding binding = {}; struct msghdr msg = {}; struct dmabuf_token token; struct dmabuf_cmsg *cmsg; @@ -1630,6 +1631,7 @@ static void netmem_ref_test_tcp_devmem_recv(struct kunit *test) long base_iov_ref; int ret; + memset(&binding, 0, sizeof(binding)); KUNIT_ASSERT_EQ(test, sock_create_kern(&init_net, AF_INET, SOCK_STREAM, IPPROTO_TCP, &sock), From de9886cb02f3efeba86a9c6f5f9f6a31d8b006fe Mon Sep 17 00:00:00 2001 From: Wenbo Sun Date: Fri, 13 Nov 2026 17:01:08 +0800 Subject: [PATCH 0712/2102] team: validate the length of U32 and S32 option data In team_nl_options_set_doit(), the policy for TEAM_ATTR_OPTION_DATA in team_attr_option_nl_policy is NLA_BINARY because the payload layout varies with the option type. For TEAM_OPTION_TYPE_U32 and TEAM_OPTION_TYPE_S32, the payload is read directly with nla_get_u32(attr_data) and nla_get_s32(attr_data) without checking its attribute length. When userspace supplies a truncated attribute (0 to 3 bytes), nla_get_u32() or nla_get_s32() performs an out-of-bounds read past the attribute buffer. Conversely, oversized payloads (> 4 bytes) would also have trailing bytes silently ignored instead of being rejected as invalid input. Validate that nla_len(attr_data) equals sizeof(u32) or sizeof(s32) for TEAM_OPTION_TYPE_U32 and TEAM_OPTION_TYPE_S32 respectively, and return -EINVAL otherwise, consistent with how NLA_U32/NLA_S32 attributes are validated and similar to commit 5bef3ac184b5 ("team: better TEAM_OPTION_TYPE_STRING validation"). This issue was identified with the assistance of an LLM-based code review of Netlink option handlers in the team driver, confirmed by sending malformed U32 (notify_peers_count) and S32 (priority) option attributes on a UML kernel, and verified after the patch that invalid lengths (0..3, 5, and 8 bytes) are rejected with -EINVAL while valid 4-byte options still work as expected. Built with W=1 on UML, x86_64 allmodconfig, and x86_64 allyesconfig with zero new warnings or errors. Fixes: 3d249d4ca7d0 ("net: introduce ethernet teaming device") Fixes: 69821638b274 ("team: add signed 32-bit team option type") Signed-off-by: Wenbo Sun Reviewed-by: Jiri Pirko Reviewed-by: Hangbin Liu Link: https://patch.msgid.link/20261113090108.175889-1-sunwenbo@cmss.chinamobile.com Signed-off-by: Jakub Kicinski --- drivers/net/team/team_core.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/net/team/team_core.c b/drivers/net/team/team_core.c index cfb833c307c14f..65ac25e97ae311 100644 --- a/drivers/net/team/team_core.c +++ b/drivers/net/team/team_core.c @@ -2834,6 +2834,10 @@ int team_nl_options_set_doit(struct sk_buff *skb, struct genl_info *info) ctx.info = opt_inst_info; switch (opt_type) { case TEAM_OPTION_TYPE_U32: + if (nla_len(attr_data) != sizeof(u32)) { + err = -EINVAL; + goto team_put; + } ctx.data.u32_val = nla_get_u32(attr_data); break; case TEAM_OPTION_TYPE_STRING: @@ -2853,6 +2857,10 @@ int team_nl_options_set_doit(struct sk_buff *skb, struct genl_info *info) ctx.data.bool_val = attr_data ? true : false; break; case TEAM_OPTION_TYPE_S32: + if (nla_len(attr_data) != sizeof(s32)) { + err = -EINVAL; + goto team_put; + } ctx.data.s32_val = nla_get_s32(attr_data); break; default: From 92c569c28b63067da0276f67f711a3ac20a62aca Mon Sep 17 00:00:00 2001 From: Amaan Cheval Date: Thu, 12 Nov 2026 14:44:50 +0530 Subject: [PATCH 0713/2102] gve: refuse XDP on queue formats without XDP support Commit d8a8ca14c937 ("gve: add XDP_TX and XDP_REDIRECT support for DQ RDA") enabled XDP on DQO-RDA by dropping the queue_format check from verify_xdp_configuration(), which until then refused every format but GQI-QPL. Nothing replaced it: gve_set_netdev_xdp_features() advertises no XDP features for DQO-QPL and GQI-RDA and gve_xdp_xmit() rejects both, but the core only checks that ndo_bpf exists, so a native XDP program, and an AF_XDP socket on top of it, can still be attached on a queue format the driver does not support. The DQO-QPL RX path was never written for that. Its page accounting assumes the driver keeps a reference of its own across every handoff: gve_xdp_done_dqo() passes the buffer to xdp_do_redirect() and then recycles it with gve_reuse_buffer(), so a redirect target that releases the buffer synchronously, such as an AF_XDP socket in copy mode, can drop the page's last reference when pagecnt_bias runs out. The page is then freed while it is still DMA-mapped and registered in the QPL, and the driver posts it back to the device. GQI-RDA is no better off: an XDP_TX there goes through gve_tx_fill_xdp(), which copies the frame into tx->tx_fifo, but a raw-addressing TX ring never allocates that FIFO, so the first XDP_TX writes through a NULL tx_fifo.base. Refuse XDP setup in gve_verify_xdp_configuration() whenever the driver advertises no XDP features for the current queue format, which today means DQO-QPL and GQI-RDA. A zero-copy XSK pool bind is already refused by the core for the same reason, and a copy-mode bind never reaches the driver and is harmless without a program. Fixes: d8a8ca14c937 ("gve: add XDP_TX and XDP_REDIRECT support for DQ RDA") Cc: stable@vger.kernel.org Reviewed-by: Joshua Washington Signed-off-by: Amaan Cheval Tested-by on v2: Link: https://patch.msgid.link/20261112091451.22969-2-amaan.cheval@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/google/gve/gve_main.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/net/ethernet/google/gve/gve_main.c b/drivers/net/ethernet/google/gve/gve_main.c index 0ee69bc11d8366..35cf0f06a0f27b 100644 --- a/drivers/net/ethernet/google/gve/gve_main.c +++ b/drivers/net/ethernet/google/gve/gve_main.c @@ -1798,6 +1798,12 @@ static int gve_verify_xdp_configuration(struct net_device *dev, struct gve_priv *priv = netdev_priv(dev); u16 max_xdp_mtu; + if (!(dev->xdp_features & NETDEV_XDP_ACT_BASIC)) { + NL_SET_ERR_MSG_MOD(extack, + "XDP is not supported on this queue format."); + return -EOPNOTSUPP; + } + if (dev->features & NETIF_F_GRO_HW) { NL_SET_ERR_MSG_MOD(extack, "XDP is not supported when HW-GRO is on."); From 3946899dbeac2397fdd1727d74a3547d2b13caf3 Mon Sep 17 00:00:00 2001 From: Amaan Cheval Date: Thu, 12 Nov 2026 14:44:51 +0530 Subject: [PATCH 0714/2102] gve: fix RX page refcount overflow from INT_MAX pagecnt_bias gve's GQI and DQO-QPL RX paths set every RX page's refcount to INT_MAX and hand references to the stack by decrementing page_info->pagecnt_bias, to avoid an atomic op per packet. This leaves no room for anyone else: while a fresh page's buffer sits in an skb its refcount is already INT_MAX, so a single get_page() from the stack overflows it to negative. splice() of received TCP data into a pipe takes such a reference, and the onward splice into a socket then fails: skb_splice_from_iter() sees page_count() < 1, sendpage_ok() fails and the send returns -EIO (since commit 2e910b95329c ("net: Add a function to splice pages into an skbuff for MSG_SPLICE_PAGES")). tee() of the pipe fails with -EFAULT via try_get_page(). On GQI the reuse check gve_rx_can_recycle_buffer() also sees page_count() < pagecnt_bias, WARNs and calls gve_schedule_reset(), so a task that merely pins a fresh RX page (e.g. holds spliced data in an undrained tee() pipe) can reset the NIC. Use USHRT_MAX in a u16, as igb, igc, ixgbe, i40e and hns3 do: the bias only has to make the per-packet atomic rare, so a small value keeps page_count() far below INT_MAX however many references the stack takes. Refill by adding a fixed batch and setting the bias to it, which keeps the rule `references = page_count() - bias` intact. Refilling at 0 hands the driver's last reference to the consumer once every USHRT_MAX handoffs rather than once every INT_MAX, which is only safe because every consumer on these paths holds its reference until the driver has recycled the buffer. The previous patch keeps it that way by blocking XDP on DQO-QPL, so this one depends on it. Trees before 6.17, without commit d8a8ca14c937 ("gve: add XDP_TX and XDP_REDIRECT support for DQ RDA"), still refuse XDP on every format but GQI-QPL in verify_xdp_configuration(), so there this patch stands alone. Reproduced on gVNIC in GQI-QPL mode (GCE n2-standard-8, 6.12) and in DQO-RDA mode (GCE c3-standard-8, 6.12, where DQO-RDA still uses the bias) with the help of relay.py -- a small splice(2) TCP proxy -- relaying a download while the RX ring is refilled with fresh pages: ethtool -G eth0 rx 512 && ethtool -G eth0 rx 1024 # fresh RX pages ./relay.py $HOST 8080 & # splice()s both ways for i in $(seq 200); do curl -so /dev/null \ --connect-to $HOST:80:127.0.0.1:8080 http://$HOST/file; done Most downloads failed with EIO before the fix (tee() with EFAULT) and all completed after it. relay.py is at the Link below. This bug was found and fixed with the help of an AI coding assistant (Claude Code) over an interactive session; it read the driver and splice/pipe code and ran the tests above. Link: https://github.com/amaanc/kernel-bias Fixes: 9b8dd5e5ea48 ("gve: DQO: Add RX path") Fixes: 58401b2a46e7 ("gve: Add rx buffer pagecnt bias") Fixes: 82fd151d38d9 ("gve: Reduce alloc and copy costs in the GQ rx path") Cc: stable@vger.kernel.org Reviewed-by: Harshitha Ramamurthy Tested-by: Harshitha Ramamurthy Reviewed-by: Maciej Fijalkowski Signed-off-by: Amaan Cheval Tested-by on v2: Link: https://patch.msgid.link/20261112091451.22969-3-amaan.cheval@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/google/gve/gve.h | 2 +- .../net/ethernet/google/gve/gve_buffer_mgmt_dqo.c | 4 ++-- drivers/net/ethernet/google/gve/gve_rx.c | 8 ++++---- drivers/net/ethernet/google/gve/gve_utils.c | 12 ++++-------- drivers/net/ethernet/google/gve/gve_utils.h | 2 +- 5 files changed, 12 insertions(+), 16 deletions(-) diff --git a/drivers/net/ethernet/google/gve/gve.h b/drivers/net/ethernet/google/gve/gve.h index e509488a3d3e1a..143d8cd595aa27 100644 --- a/drivers/net/ethernet/google/gve/gve.h +++ b/drivers/net/ethernet/google/gve/gve.h @@ -119,7 +119,7 @@ struct gve_rx_slot_page_info { void *page_address; u32 page_offset; /* offset to write to in page */ unsigned int buf_size; - int pagecnt_bias; /* expected pagecnt if only the driver has a ref */ + u16 pagecnt_bias; /* expected pagecnt if only the driver has a ref */ u16 pad; /* adjustment for rx padding */ u8 can_flip; /* tracks if the networking stack is using the page */ }; diff --git a/drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c b/drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c index 6880d1531ba5ef..52223baf03036d 100644 --- a/drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c +++ b/drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c @@ -149,8 +149,8 @@ int gve_alloc_qpl_page_dqo(struct gve_rx_ring *rx, buf_state->last_single_ref_offset = 0; /* The page already has 1 ref. */ - page_ref_add(buf_state->page_info.page, INT_MAX - 1); - buf_state->page_info.pagecnt_bias = INT_MAX; + page_ref_add(buf_state->page_info.page, USHRT_MAX - 1); + buf_state->page_info.pagecnt_bias = USHRT_MAX; return 0; } diff --git a/drivers/net/ethernet/google/gve/gve_rx.c b/drivers/net/ethernet/google/gve/gve_rx.c index 81ea800e66e941..3bed1986637666 100644 --- a/drivers/net/ethernet/google/gve/gve_rx.c +++ b/drivers/net/ethernet/google/gve/gve_rx.c @@ -152,8 +152,8 @@ static void gve_setup_rx_buffer(struct gve_rx_ring *rx, page_info->buf_size = rx->packet_buffer_size; *slot_addr = cpu_to_be64(addr); /* The page already has 1 ref */ - page_ref_add(page, INT_MAX - 1); - page_info->pagecnt_bias = INT_MAX; + page_ref_add(page, USHRT_MAX - 1); + page_info->pagecnt_bias = USHRT_MAX; } static int gve_rx_alloc_buffer(struct gve_priv *priv, struct device *dev, @@ -230,8 +230,8 @@ static int gve_rx_prefill_pages(struct gve_rx_ring *rx, rx->qpl_copy_pool[j].buf_size = rx->packet_buffer_size; /* The page already has 1 ref. */ - page_ref_add(page, INT_MAX - 1); - rx->qpl_copy_pool[j].pagecnt_bias = INT_MAX; + page_ref_add(page, USHRT_MAX - 1); + rx->qpl_copy_pool[j].pagecnt_bias = USHRT_MAX; } } diff --git a/drivers/net/ethernet/google/gve/gve_utils.c b/drivers/net/ethernet/google/gve/gve_utils.c index caed38cd5f2b3b..930555ac8fe912 100644 --- a/drivers/net/ethernet/google/gve/gve_utils.c +++ b/drivers/net/ethernet/google/gve/gve_utils.c @@ -93,15 +93,11 @@ void gve_dec_pagecnt_bias(struct gve_rx_slot_page_info *page_info) { page_info->pagecnt_bias--; if (page_info->pagecnt_bias == 0) { - int pagecount = page_count(page_info->page); - - /* If we have run out of bias - set it back up to INT_MAX - * minus the existing refs. + /* Out of bias: take another batch. USHRT_MAX keeps this rare + * while leaving page_count() far below INT_MAX. */ - page_info->pagecnt_bias = INT_MAX - pagecount; - - /* Set pagecount back up to max. */ - page_ref_add(page_info->page, INT_MAX - pagecount); + page_info->pagecnt_bias = USHRT_MAX; + page_ref_add(page_info->page, USHRT_MAX); } } diff --git a/drivers/net/ethernet/google/gve/gve_utils.h b/drivers/net/ethernet/google/gve/gve_utils.h index bf2e9a0adb36ee..c686142d37eaf5 100644 --- a/drivers/net/ethernet/google/gve/gve_utils.h +++ b/drivers/net/ethernet/google/gve/gve_utils.h @@ -25,7 +25,7 @@ struct sk_buff *gve_rx_copy_data(struct net_device *dev, struct napi_struct *nap struct sk_buff *gve_rx_copy(struct net_device *dev, struct napi_struct *napi, struct gve_rx_slot_page_info *page_info, u16 len); -/* Decrement pagecnt_bias. Set it back to INT_MAX if it reached zero. */ +/* Decrement pagecnt_bias. Top it up by USHRT_MAX if it reached zero. */ void gve_dec_pagecnt_bias(struct gve_rx_slot_page_info *page_info); void gve_add_napi(struct gve_priv *priv, int ntfy_idx, From 1932779607d2fc895464c676a2a420aa07403976 Mon Sep 17 00:00:00 2001 From: Haishuang Yan Date: Wed, 11 Nov 2026 00:30:01 +0900 Subject: [PATCH 0715/2102] virtio_net: Disable AF_XDP pools on queues above curr_queue_pairs With an XDP program attached, virtnet_xdp_set() adds nr_cpu_ids queue pairs for XDP_TX and raises curr_queue_pairs and real_num_rx_queues to match. virtnet_xsk_pool_enable() accepts any queue below curr_queue_pairs, so an AF_XDP zero-copy socket can be bound to one of them. When the program is removed, the queue count goes down again while the pool stays bound to the driver. When the socket is closed afterwards, virtnet_xsk_pool_disable() rejects the queue with -EINVAL, and the core frees the pool anyway: WARNING: net/xdp/xsk_buff_pool.c:160 at xp_disable_drv_zc+0x1ee/0x260 BUG: KASAN: slab-use-after-free in xp_alloc_batch+0x930/0xb40 Read of size 8 at addr ffff8880028eb400 by task ksoftirqd/0/14 xp_alloc_batch+0x930/0xb40 try_fill_recv+0xb27/0x26e0 as rq->xsk_pool still points to it and the queue is refilled from it. The device going away with XDP attached, e.g. on hot-unplug or driver unbind, ends the same way without an explicit removal: unregister_netdevice_many_notify() removes XDP before the xsk notifier unbinds the socket, so the pool is disabled on a queue above curr_queue_pairs there as well. Removing XDP must not fail, so let virtnet_xsk_pool_disable() accept any queue the driver has, below max_queue_pairs. The receive and send queues above curr_queue_pairs still exist, so they are unbound as usual. This was pointed out by the Sashiko review of v1 of this series, and reproduced in QEMU by binding a socket to an XDP queue and then either removing XDP and closing the socket, or unbinding the device from virtio_net. Fixes: 09d2b3182c8e ("virtio_net: xsk: bind/unbind xsk for rx") Signed-off-by: Haishuang Yan Link: https://patch.msgid.link/20261110153003.23731-3-yanhaishuang@cmss.chinamobile.com Signed-off-by: Jakub Kicinski --- drivers/net/virtio_net.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/net/virtio_net.c b/drivers/net/virtio_net.c index 28b84de8615375..1cd64f9e12e745 100644 --- a/drivers/net/virtio_net.c +++ b/drivers/net/virtio_net.c @@ -6040,7 +6040,8 @@ static int virtnet_xsk_pool_disable(struct net_device *dev, u16 qid) struct send_queue *sq; int err; - if (qid >= vi->curr_queue_pairs) + /* Removing XDP can leave the pool on a queue above curr_queue_pairs */ + if (qid >= vi->max_queue_pairs) return -EINVAL; sq = &vi->sq[qid]; From 533ec433efdc11196f438da90d683053a57257ff Mon Sep 17 00:00:00 2001 From: Xin Long Date: Thu, 12 Nov 2026 10:01:42 -0500 Subject: [PATCH 0716/2102] sctp: validate SACK pull length against chunk length, not skb length sctp_sm_pull_sack() derives its pull length from the num_gap_ack_blocks and num_dup_tsns fields in the SACK body, but validates it against chunk->skb->len (the remaining packet data) rather than the SACK chunk's declared length. A malformed SACK with an inflated num_dup_tsns can pass this check when subsequent chunks pad the skb, advancing skb->data past the SACK boundary into later chunks. This misaligns the skb cursor for subsequent chunk processing. When an AUTH chunk follows, sctp_sf_authenticate() reads and compares the HMAC digest from the wrong skb offset while sctp_auth_calculate_hmac() writes the computed HMAC through the correct chunk_hdr pointer, bypassing the authentication check. Fix by validating the computed pull length against the chunk's declared body length instead of the total remaining skb data. Fixes: 730fc3d05cd4 ("[SCTP]: Implete SCTP-AUTH parameter processing") Reported-by: on Sim Signed-off-by: Xin Long Link: https://patch.msgid.link/3fbf59d17a91c46098e3d4115e06987918b68c45.1794495702.git.lucien.xin@gmail.com Signed-off-by: Jakub Kicinski --- net/sctp/sm_statefuns.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/net/sctp/sm_statefuns.c b/net/sctp/sm_statefuns.c index 64519fd8f94335..6a4205de0aa69c 100644 --- a/net/sctp/sm_statefuns.c +++ b/net/sctp/sm_statefuns.c @@ -6372,7 +6372,8 @@ static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk) num_dup_tsns = ntohs(sack->num_dup_tsns); len = sizeof(struct sctp_sackhdr); len += (num_blocks + num_dup_tsns) * sizeof(__u32); - if (len > chunk->skb->len) + if (len > ntohs(chunk->chunk_hdr->length) - + sizeof(struct sctp_chunkhdr)) return NULL; skb_pull(chunk->skb, len); From 3a2f97af36754b64083d463a4cee0af26826bec8 Mon Sep 17 00:00:00 2001 From: Aldo Ariel Panzardo Date: Wed, 7 Oct 2026 18:20:48 -0300 Subject: [PATCH 0717/2102] drm/vmwgfx: return an error when a shared GB surface has no backup buffer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit vmw_gb_surface_reference_internal() rejects a surface that has no backup buffer by logging an error and jumping to out_bad_resource, but it never sets ret on that path. ret is still 0 from the earlier successful vmw_surface_handle_reference(), so the ioctl returns success while leaving the reply structure unfilled — user space is handed a "successful" reply that was never produced. DRM_VMW_GB_SURFACE_REF is DRM_RENDER_ALLOW, so an unprivileged local user can reach it. Set ret to -EINVAL and, on the error paths, drop the reference that vmw_surface_handle_reference() took; once the ioctl fails user space no longer releases it via DRM_VMW_UNREF_SURFACE. The unref is guarded by ret so the shared success fall-through keeps the reference the caller still owns, and it also plugs the same leak on the drm_gem_handle_create() failure path. Fixes: 14b1c33e8429 ("drm/vmwgfx: Add new ioctl for GB surface create and reference") Cc: stable@vger.kernel.org Suggested-by: Zack Rusin Signed-off-by: Aldo Ariel Panzardo Reviewed-by: Zack Rusin [zack: aligned a continuation line with the open parenthesis] Signed-off-by: Zack Rusin Link: https://patch.msgid.link/20261007212051.2574235-2-qwe.aldo@gmail.com --- drivers/gpu/drm/vmwgfx/vmwgfx_surface.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c b/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c index bd0563741e89d9..164886a3e62fb2 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c @@ -1720,6 +1720,7 @@ vmw_gb_surface_reference_internal(struct drm_device *dev, srf = &user_srf->srf; if (!srf->res.guest_memory_bo) { DRM_ERROR("Shared GB surface is missing a backup buffer.\n"); + ret = -EINVAL; goto out_bad_resource; } metadata = &srf->metadata; @@ -1758,6 +1759,9 @@ vmw_gb_surface_reference_internal(struct drm_device *dev, rep->creq.must_be_zero = 0; out_bad_resource: + if (ret) + ttm_ref_object_base_unref(vmw_fpriv(file_priv)->tfile, + base->handle); ttm_base_object_unref(&base); return ret; From 30131b82b062180183a09a97183a944fadab72ee Mon Sep 17 00:00:00 2001 From: Aldo Ariel Panzardo Date: Wed, 7 Oct 2026 18:20:49 -0300 Subject: [PATCH 0718/2102] drm/vmwgfx: close TOCTOU on guest_memory_bo in surface reference ioctl vmw_gb_surface_reference_internal() checks srf->res.guest_memory_bo for NULL and reads its vma_node offset and base.size outside the cmdbuf_mutex scope that protects the backup pointer. A concurrent backup switch, e.g. from SVGA_3D_CMD_BIND_GB_SURFACE via vmw_resource_unreserve(), drops its reference to the old buffer and installs a new one under cmdbuf_mutex. The unlocked check in the surface reference ioctl can see a transient NULL. The reads after the unlock can return another buffer's offset and size; a further switch can drop that buffer's last reference and free it while the ioctl reads from it. Move the NULL check inside the mutex, and read buffer_map_handle and buffer_size while still holding it. Fixes: a97e21923b42 ("drm/vmwgfx: Hook up guest-backed surfaces") Cc: stable@vger.kernel.org Reported-by: Sashiko Closes: https://lore.kernel.org/r/20260808233347.209DD1F000E9@smtp.kernel.org Signed-off-by: Aldo Ariel Panzardo Reviewed-by: Zack Rusin Signed-off-by: Zack Rusin Link: https://patch.msgid.link/20261007212051.2574235-3-qwe.aldo@gmail.com --- drivers/gpu/drm/vmwgfx/vmwgfx_surface.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c b/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c index 164886a3e62fb2..3064a2a960e1f8 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c @@ -1718,23 +1718,32 @@ vmw_gb_surface_reference_internal(struct drm_device *dev, user_srf = container_of(base, struct vmw_user_surface, prime.base); srf = &user_srf->srf; + metadata = &srf->metadata; + + mutex_lock(&dev_priv->cmdbuf_mutex); + if (!srf->res.guest_memory_bo) { + mutex_unlock(&dev_priv->cmdbuf_mutex); DRM_ERROR("Shared GB surface is missing a backup buffer.\n"); ret = -EINVAL; goto out_bad_resource; } - metadata = &srf->metadata; - mutex_lock(&dev_priv->cmdbuf_mutex); /* Protect res->backup */ ret = drm_gem_handle_create(file_priv, &srf->res.guest_memory_bo->tbo.base, &backup_handle); - mutex_unlock(&dev_priv->cmdbuf_mutex); if (ret != 0) { + mutex_unlock(&dev_priv->cmdbuf_mutex); drm_err(dev, "Wasn't able to create a backing handle for surface sid = %u.\n", req->sid); goto out_bad_resource; } + rep->crep.buffer_map_handle = + drm_vma_node_offset_addr(&srf->res.guest_memory_bo->tbo.base.vma_node); + rep->crep.buffer_size = srf->res.guest_memory_bo->tbo.base.size; + + mutex_unlock(&dev_priv->cmdbuf_mutex); + rep->creq.base.svga3d_flags = SVGA3D_FLAGS_LOWER_32(metadata->flags); rep->creq.base.format = metadata->format; rep->creq.base.mip_levels = metadata->mip_levels[0]; @@ -1747,9 +1756,6 @@ vmw_gb_surface_reference_internal(struct drm_device *dev, rep->crep.handle = user_srf->prime.base.handle; rep->crep.backup_size = srf->res.guest_memory_size; rep->crep.buffer_handle = backup_handle; - rep->crep.buffer_map_handle = - drm_vma_node_offset_addr(&srf->res.guest_memory_bo->tbo.base.vma_node); - rep->crep.buffer_size = srf->res.guest_memory_bo->tbo.base.size; rep->creq.version = drm_vmw_gb_surface_v1; rep->creq.svga3d_flags_upper_32_bits = From 030e6d11d3e5eb7328f7a3e8177737a4b1c30654 Mon Sep 17 00:00:00 2001 From: Aldo Ariel Panzardo Date: Wed, 23 Sep 2026 09:26:01 -0300 Subject: [PATCH 0719/2102] drm/vmwgfx: do not hand the embedded sg_table to the PRIME core vmw_gem_object_get_sg_table() returns vmw_tt->vsgt.sgt when the buffer object has already been DMA mapped. vmw_ttm_map_dma() sets that field to &vmw_tt->sgt, which is a member embedded inside the struct vmw_ttm_tt allocation and not a table of its own. The core owns whatever .get_sg_table returns. drm_gem_map_dma_buf() takes the table and drm_gem_unmap_dma_buf() destroys it in full: dma_unmap_sgtable(attach->dev, sgt, dir, DMA_ATTR_SKIP_CPU_SYNC); sg_free_table(sgt); kfree(sgt); Both are ops of drm_gem_prime_dmabuf_ops, so the core ends up calling kfree() on &vmw_tt->sgt, which is not the start of an allocation. The preceding sg_free_table() also destroys a scatterlist that vmwgfx still considers its own and frees again from vmw_ttm_unmap_dma(). drm_gem_unmap_dma_buf() runs from dma_buf_detach(), including the importer's error path, so a failed import is enough to reach it: exporting a bound buffer with DRM_IOCTL_PRIME_HANDLE_TO_FD and importing it on a second DRM device with DRM_IOCTL_PRIME_FD_TO_HANDLE is sufficient. Both ioctls are DRM_RENDER_ALLOW. Observed on 6.12.101 with KASAN, as uid 65534: BUG: KASAN: invalid-free in drm_gem_unmap_dma_buf+0xb3/0xf0 Free of addr ffff888008290450 by task poc_mm04_sgtabl/321 CPU: 1 UID: 65534 PID: 321 Comm: poc_mm04_sgtabl Not tainted 6.12.101 #4 kasan_report_invalid_free+0x94/0xc0 check_slab_allocation+0x116/0x120 kfree+0x103/0x360 drm_gem_unmap_dma_buf+0xb3/0xf0 dma_buf_detach+0x165/0x510 drm_gem_prime_import_dev+0x33e/0x430 which belongs to the cache kmalloc-192 of size 192 The buggy address is located 80 bytes inside of 144-byte region [ffff888008290400, ffff888008290490) 80 is offsetof(struct vmw_ttm_tt, sgt) and 144 is sizeof(struct vmw_ttm_tt), which identifies the freed pointer as the embedded member. Always return a table the core can own, as the other drivers do. Reusing the cached representation would require copying it into a freshly allocated sg_table, never returning the alias. Fixes: 8afa13a0583f ("drm/vmwgfx: Implement DRIVER_GEM") Cc: stable@vger.kernel.org Signed-off-by: Aldo Ariel Panzardo Reviewed-by: Zack Rusin Signed-off-by: Zack Rusin Link: https://patch.msgid.link/20260923122601.438892-1-qwe.aldo@gmail.com --- drivers/gpu/drm/vmwgfx/vmwgfx_gem.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c b/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c index 39f8c46550c27e..a0233729b31a1a 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c @@ -73,10 +73,13 @@ static struct sg_table *vmw_gem_object_get_sg_table(struct drm_gem_object *obj) struct vmw_ttm_tt *vmw_tt = container_of(bo->ttm, struct vmw_ttm_tt, dma_ttm); - if (vmw_tt->vsgt.sgt) - return vmw_tt->vsgt.sgt; - - return drm_prime_pages_to_sg(obj->dev, vmw_tt->dma_ttm.pages, vmw_tt->dma_ttm.num_pages); + /* + * Do not return &vmw_tt->sgt: the core owns what this returns and + * drm_gem_unmap_dma_buf() sg_free_table()s and kfree()s it, but that + * sg_table is embedded in the vmw_ttm_tt allocation. + */ + return drm_prime_pages_to_sg(obj->dev, vmw_tt->dma_ttm.pages, + vmw_tt->dma_ttm.num_pages); } static int vmw_gem_vmap(struct drm_gem_object *obj, struct iosys_map *map) From 06f8a6708a98dff199ef7ea553b092efc38b4eab Mon Sep 17 00:00:00 2001 From: Vladimir Popov Date: Tue, 14 Apr 2026 13:55:27 +0300 Subject: [PATCH 0720/2102] drm/vmwgfx: fix NULL pointer dereference in vmw_validation_bo_fence() If vmw_execbuf_fence_commands() call fails in vmw_kms_helper_validation_finish(), it sets *p_fence = NULL. If ctx->bo_list is not empty, the caller, vmw_kms_helper_validation_finish(), passes the fence through a chain of functions to dma_fence_is_array(), which causes a NULL pointer dereference in dma_fence_is_array(): vmw_kms_helper_validation_finish() // pass NULL fence vmw_validation_done() vmw_validation_bo_fence() ttm_eu_fence_buffer_objects() // pass NULL fence dma_resv_add_fence() dma_fence_is_container() dma_fence_is_array() // NULL deref Fix this by adding a NULL check in vmw_validation_bo_fence(): if the fence is NULL, fall back to ttm_eu_backoff_reservation()to safely release the buffer object reservations without attempting to add a NULL fence to dma_resv. This is safe because when fence is NULL, vmw_fallback_wait() has already been called inside vmw_execbuf_fence_commands() to synchronize the GPU. Found by Linux Verification Center (linuxtesting.org) with SVACE. Fixes: 038ecc503236 ("drm/vmwgfx: Add a validation module v2") Cc: stable@vger.kernel.org Signed-off-by: Vladimir Popov Reviewed-by: Zack Rusin Signed-off-by: Zack Rusin Link: https://patch.msgid.link/20260414105529.9883-1-popov.nkv@gmail.com --- drivers/gpu/drm/vmwgfx/vmwgfx_validation.h | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_validation.h b/drivers/gpu/drm/vmwgfx/vmwgfx_validation.h index 353d837907d84a..fc04555ca50525 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_validation.h +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_validation.h @@ -127,16 +127,23 @@ vmw_validation_bo_reserve(struct vmw_validation_context *ctx, * vmw_validation_bo_fence - Unreserve and fence buffer objects registered * with a validation context * @ctx: The validation context + * @fence: Fence with which to fence all buffer objects taking part in the + * command submission. * * This function unreserves the buffer objects previously reserved using - * vmw_validation_bo_reserve, and fences them with a fence object. + * vmw_validation_bo_reserve, and fences them with a fence object if the + * given fence object is not NULL. */ static inline void vmw_validation_bo_fence(struct vmw_validation_context *ctx, struct vmw_fence_obj *fence) { - ttm_eu_fence_buffer_objects(&ctx->ticket, &ctx->bo_list, - (void *) fence); + /* fence is able to be NULL if vmw_execbuf_fence_commands() fails */ + if (fence) + ttm_eu_fence_buffer_objects(&ctx->ticket, &ctx->bo_list, + (void *)fence); + else + ttm_eu_backoff_reservation(&ctx->ticket, &ctx->bo_list); } /** From 1914e9ac680d04613d25e545a2733d2e4d870fe3 Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Tue, 30 Jun 2026 16:32:23 +0300 Subject: [PATCH 0721/2102] drm/vmwgfx: Fix NULL vs error pointer bug in vmw_prime_import_sg_table() The vmw_prime_import_sg_table() function is expected to return error pointers on error and not NULL. Otherwise it leads to a NULL dereference in the caller drm_gem_prime_import_dev(). Propagate the error code from vmw_bo_create(). Fixes: b32233acceff ("drm/vmwgfx: Fix prime import/export") Signed-off-by: Dan Carpenter Reviewed-by: Zack Rusin Signed-off-by: Zack Rusin Link: https://patch.msgid.link/akPFZ-e9usvsYgf_@stanley.mountain --- drivers/gpu/drm/vmwgfx/vmwgfx_gem.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c b/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c index a0233729b31a1a..2969b74fff17a0 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c @@ -187,7 +187,7 @@ struct drm_gem_object *vmw_prime_import_sg_table(struct drm_device *dev, { int ret; struct vmw_private *dev_priv = vmw_priv(dev); - struct drm_gem_object *gem = NULL; + struct drm_gem_object *gem; struct vmw_bo *vbo; struct vmw_bo_params params = { .domain = (dev_priv->has_mob) ? VMW_BO_DOMAIN_SYS : VMW_BO_DOMAIN_VRAM, @@ -204,8 +204,10 @@ struct drm_gem_object *vmw_prime_import_sg_table(struct drm_device *dev, dma_resv_lock(params.resv, NULL); ret = vmw_bo_create(dev_priv, ¶ms, &vbo); - if (ret != 0) + if (ret != 0) { + gem = ERR_PTR(ret); goto out_no_bo; + } vbo->tbo.base.funcs = &vmw_gem_object_funcs; From a2239d5dbbda3a61b6323df8836f605921a29f7f Mon Sep 17 00:00:00 2001 From: Shay Drory Date: Thu, 12 Nov 2026 20:29:40 +0200 Subject: [PATCH 0722/2102] net/mlx5: IFC, enlarge active_port field to support 8 port LAG active_port is a bitmask with a bit per LAG port. The cited commit enabled 8 port LAG, but active_port remained 4 bits wide. Enlarge active_port to 8 bits, as defined in the PRM. Fixes: e0e6adfe8c20 ("net/mlx5: Enable 8 ports LAG") Signed-off-by: Shay Drory Reviewed-by: Mark Bloch Reviewed-by: Akiva Goldberger Signed-off-by: Tariq Toukan Link: https://patch.msgid.link/20261112182940.3655773-1-tariqt@nvidia.com Signed-off-by: Jakub Kicinski --- include/linux/mlx5/mlx5_ifc.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/linux/mlx5/mlx5_ifc.h b/include/linux/mlx5/mlx5_ifc.h index 697fc9387b73ae..37b6e47c909141 100644 --- a/include/linux/mlx5/mlx5_ifc.h +++ b/include/linux/mlx5/mlx5_ifc.h @@ -12453,8 +12453,8 @@ struct mlx5_ifc_lagc_bits { u8 reserved_at_18[0x5]; u8 lag_state[0x3]; - u8 reserved_at_20[0xc]; - u8 active_port[0x4]; + u8 reserved_at_20[0x8]; + u8 active_port[0x8]; u8 reserved_at_30[0x4]; u8 tx_remap_affinity_2[0x4]; u8 reserved_at_38[0x4]; From 97d4a585db2b91d855f957be0a9f126068c5be93 Mon Sep 17 00:00:00 2001 From: Cheng Yongkang Date: Sun, 15 Nov 2026 20:45:19 -0800 Subject: [PATCH 0723/2102] io_uring/timeout: don't rearm a multishot timeout on cancel io_timeout_complete() does not check tw.cancel. When it runs from io_cancel_local_task_work(), a multishot timeout that has not reached its count still posts an IORING_CQE_F_MORE completion and rearms its timer. With a zero interval the timer expires again right away and queues new task work, so the drain keeps running it until posting a CQE fails. Normally the CQ fills up quickly and the request then completes. But if userspace moves the CQ head far ahead of the tail, for example to cq.tail + 0x7fffffff, posting keeps succeeding and ring teardown is delayed for a long time. Don't post another CQE or rearm the timer when tw.cancel is set, so the request completes through io_req_task_complete(), like the poll and linked timeout task work does when cancelled. Fixes: ea97f6c8558e ("io_uring: add support for multishot timeouts") Signed-off-by: Cheng Yongkang Link: https://patch.msgid.link/20261116044519.281756-1-teel4res@gmail.com Signed-off-by: Jens Axboe --- io_uring/timeout.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/io_uring/timeout.c b/io_uring/timeout.c index fa7b0d9a81d695..db78059cfeab12 100644 --- a/io_uring/timeout.c +++ b/io_uring/timeout.c @@ -115,7 +115,8 @@ static void io_timeout_complete(struct io_tw_req tw_req, io_tw_token_t tw) struct io_ring_ctx *ctx = req->ctx; if (!io_timeout_finish(timeout, data)) { - if (io_req_post_cqe(req, -ETIME, IORING_CQE_F_MORE)) { + if (!tw.cancel && + io_req_post_cqe(req, -ETIME, IORING_CQE_F_MORE)) { /* re-arm timer */ raw_spin_lock_irq(&ctx->timeout_lock); list_add(&timeout->list, ctx->timeout_list.prev); From e5a346e4309d720c47fe8331a00068608fad47dd Mon Sep 17 00:00:00 2001 From: Cheng Yongkang Date: Sun, 15 Nov 2026 20:45:31 -0800 Subject: [PATCH 0724/2102] io_uring/rsrc: keep the old file when a file update fails __io_sqe_files_update() resets the slot before it calls fget() on the new fd. If fget() fails, the fd is an io_uring file, or the node allocation fails, the update stops and reports that entry as not done, but the old file has already been removed. Later requests that use the slot fail with -EBADF, and if the old file was registered with a tag, its tag CQE is posted as if it had been removed on purpose. Reset the slot only after the new file has been checked and its node allocated, as io_install_fixed_file() does. Removal with fd == -1 still resets the slot right away. Fixes: c3a31e605620 ("io_uring: add support for IORING_REGISTER_FILES_UPDATE") Cc: stable@vger.kernel.org Signed-off-by: Cheng Yongkang Link: https://patch.msgid.link/20261116044531.281978-1-teel4res@gmail.com Signed-off-by: Jens Axboe --- io_uring/rsrc.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/io_uring/rsrc.c b/io_uring/rsrc.c index 8de5737d223e8b..0b811d3c9c0e9f 100644 --- a/io_uring/rsrc.c +++ b/io_uring/rsrc.c @@ -363,8 +363,6 @@ static int __io_sqe_files_update(struct io_ring_ctx *ctx, if (i >= ctx->file_table.data.nr) break; i = array_index_nospec(i, ctx->file_table.data.nr); - if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) - io_file_bitmap_clear(&ctx->file_table, i); if (fd != -1) { struct file *file = fget(fd); @@ -388,11 +386,15 @@ static int __io_sqe_files_update(struct io_ring_ctx *ctx, fput(file); break; } + if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) + io_file_bitmap_clear(&ctx->file_table, i); ctx->file_table.data.nodes[i] = node; if (tag) node->tag = tag; io_fixed_file_set(node, file); io_file_bitmap_set(&ctx->file_table, i); + } else if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) { + io_file_bitmap_clear(&ctx->file_table, i); } } return done ? done : err; From b7322810d1870ccc0d293ad383d94ef583d5057b Mon Sep 17 00:00:00 2001 From: Siddharth Chintamaneni Date: Mon, 16 Nov 2026 19:31:46 +0000 Subject: [PATCH 0725/2102] io_uring/kbuf: initialize arg->out_len from arg->max_len in io_buffers_select() io_buffers_select() passes &arg->out_len to io_provided_buffers_select() on the legacy provided-buffer path. Because callers initialize arg->max_len (from sqe->len) while leaving arg->out_len as 0, io_provided_buffers_select() sees *len == 0 and always selects the full buffer size buf->len, ignoring the user-specified sqe->len limit. Initialize arg->out_len = arg->max_len before calling io_provided_buffers_select(). Fixes: 35c8711c8fc4 ("io_uring/kbuf: add helpers for getting/peeking multiple buffers") Signed-off-by: Siddharth Chintamaneni Link: https://patch.msgid.link/20261116193146.65315-1-sidchintamaneni@gmail.com Signed-off-by: Jens Axboe --- io_uring/kbuf.c | 1 + 1 file changed, 1 insertion(+) diff --git a/io_uring/kbuf.c b/io_uring/kbuf.c index abf44f5dba26a0..873d66a06b3605 100644 --- a/io_uring/kbuf.c +++ b/io_uring/kbuf.c @@ -370,6 +370,7 @@ int io_buffers_select(struct io_kiocb *req, struct buf_sel_arg *arg, req->flags |= REQ_F_BUF_MORE; } } else { + arg->out_len = arg->max_len; ret = io_provided_buffers_select(req, &arg->out_len, sel->buf_list, arg->iovs); } out_unlock: From 1846c049cfe325abe0be8d1ea50eda16aa02d1a8 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sat, 14 Nov 2026 01:17:08 +0100 Subject: [PATCH 0726/2102] objtool/rust: add more `noreturn` Rust functions for Rust 1.101.0 Starting with Rust 1.101.0 (expected 2026-12-24), `objtool` may report: rust/kernel.o: warning: objtool: _R..._6kernel3pci2ioINtB7_6DeviceNtNtB9_6device5BoundE8cfg_size() falls through to next function _R..._6kernel3oppNtB5_3OPP18from_raw_opp_owned() (and others) due to calls to the `noreturn` symbol: core::panicking::unreachable_default_msg Rust now outlines the constant messages of the panicking macros [1], thus `unreachable!()` (i.e. without arguments) calls that new function instead of `core::panicking::panic`, which is already in the list. The same change introduced the equivalent `noreturn` functions for `panic!()`, `todo!()` and `unimplemented!()`, which lead to the same warning when those are used: core::panicking::panic_default_msg core::panicking::todo_default_msg core::panicking::unimplemented_default_msg Thus add the mangled ones to the list so that `objtool` knows they are actually `noreturn`. See commit 56d680dd23c3 ("objtool/rust: list `noreturn` Rust functions") for more details. Cc: stable@vger.kernel.org # 6.12.x (Rust is pinned in older LTSs) Cc: Josh Poimboeuf Cc: Peter Zijlstra Link: https://github.com/rust-lang/rust/pull/163766 [1] Reviewed-by: Gary Guo Link: https://patch.msgid.link/20261114001708.80599-1-ojeda@kernel.org Signed-off-by: Miguel Ojeda --- tools/objtool/check.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tools/objtool/check.c b/tools/objtool/check.c index 931c5c412f15d8..4ef5bf97d33351 100644 --- a/tools/objtool/check.c +++ b/tools/objtool/check.c @@ -206,9 +206,13 @@ static bool is_rust_noreturn(const struct symbol *func) str_ends_with(func->name, "_4core9panicking9panic_fmt") || str_ends_with(func->name, "_4core9panicking14panic_explicit") || str_ends_with(func->name, "_4core9panicking14panic_nounwind") || + str_ends_with(func->name, "_4core9panicking16todo_default_msg") || + str_ends_with(func->name, "_4core9panicking17panic_default_msg") || str_ends_with(func->name, "_4core9panicking18panic_bounds_check") || str_ends_with(func->name, "_4core9panicking18panic_nounwind_fmt") || str_ends_with(func->name, "_4core9panicking19assert_failed_inner") || + str_ends_with(func->name, "_4core9panicking23unreachable_default_msg") || + str_ends_with(func->name, "_4core9panicking25unimplemented_default_msg") || str_ends_with(func->name, "_4core9panicking30panic_null_pointer_dereference") || str_ends_with(func->name, "_4core9panicking32panic_null_reference_constructed") || str_ends_with(func->name, "_4core9panicking36panic_misaligned_pointer_dereference") || From 1eaa31fa41125db78a50abef7f0a35aa22af40d0 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sun, 18 Oct 2026 19:54:57 +0200 Subject: [PATCH 0727/2102] x86/rust: use `-Zindirect-branch-cs-prefix` for RETPOLINE builds The C compiler is asked to add a `cs` prefix to the `call` and `jmp` instructions that go through the indirect thunks for the `r8`-`r15` registers, which makes them 6 bytes long instead of 5. That gives `patch_retpoline()` enough room to inline them, e.g. as `lfence; call *%r11` for `spectre_v2=retpoline,lfence`. However, Rust code does not get the prefix, e.g. for a `CONFIG_MITIGATION_RETPOLINE=y` build: $ objdump -dr rust/kernel.o ... e2b: e8 00 00 00 00 call e30 <...> e2c: R_X86_64_PLT32 __x86_indirect_thunk_r11-0x4 Moreover, since commit 4a1e02b15ac1 ("x86,retpoline: Optimize patch_retpoline()"), `emit_indirect()` assumes there is enough room for the inlined sequence -- e.g. with `spectre_v2=retpoline,lfence`, the kernel warns and dies while patching a site inside `core`: WARNING: arch/x86/kernel/alternative.c:736 at apply_retpolines+0x2ee/0x400, CPU#0: swapper/0/0 ... Call Trace: ? _RNvMs6_NtNtCshS2CUL9MEDn_4core3fmt8buildersNtB5_9DebugList21finish_non_exhaustive+0x5b/0xd0 ... alternative_instructions+0x1d/0x60 arch_cpu_finalize_init+0x5a/0xb0 start_kernel+0x1f4/0x280 Similarly, paranoid FineIBT rewrites each kCFI call site into a fixed 20-byte sequence, i.e. the 14 bytes of the kCFI check plus a 6-byte call. For a 5-byte call, that overwrites the first byte of the next instruction, corrupting Rust code: SMP alternatives: Using paranoid FineIBT CFI ... Oops: double fault: 0000 [#1] ... RIP: 0010:_RNvNtCsdVypMZsLRAh_4core3fmt5write+0x1e9/0x210 Code: ... b8 68 81 16 9f 41 3b 43 f5 2e 4d 8d 5b f0 75 fd 41 ff e3 c0 eb 02 b0 01 ... ... Kernel panic - not syncing: Fatal exception in interrupt Non-paranoid FineIBT is not affected, since it only rewrites the kCFI check and leaves the call itself to `apply_retpolines()`. We added support for `-Zindirect-branch-cs-prefix` [1][2] in Rust 1.91.0 [3]. Thus pass it for `RETPOLINE` builds when possible, which makes all sites indeed get the prefix: e3c: 2e e8 00 00 00 00 cs call e42 <...> e3e: R_X86_64_PLT32 __x86_indirect_thunk_r11-0x4 The kernel above boots fine with `spectre_v2=retpoline,lfence`, inlining the Rust sites as well. For older Rust compilers, set the LLVM module flag instead, which has the same code-generation effect. This means that every Rust version that the kernel supports gets the prefix, that the kernel boots fine with `spectre_v2=retpoline,lfence`, and that paranoid FineIBT no longer corrupts. In addition, add it to our target modifier workaround for `rustdoc`. Cc: stable@vger.kernel.org # 6.18.y+ Link: https://github.com/rust-lang/rust/issues/116852 [1] Link: https://github.com/rust-lang/compiler-team/issues/899 [2] Link: https://github.com/rust-lang/rust/pull/140740 [3] Reported-by: Kent Overstreet Acked-by: Borislav Petkov Link: https://patch.msgid.link/20261018175457.87803-1-ojeda@kernel.org Signed-off-by: Miguel Ojeda --- arch/x86/Makefile | 1 + rust/Makefile | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/arch/x86/Makefile b/arch/x86/Makefile index b7e08519b8c1e2..83b07961b850ed 100644 --- a/arch/x86/Makefile +++ b/arch/x86/Makefile @@ -21,6 +21,7 @@ RETPOLINE_CFLAGS := -mretpoline-external-thunk RETPOLINE_VDSO_CFLAGS := -mretpoline endif RETPOLINE_CFLAGS += $(CONFIG_CC_OPT_INDIRECT_BRANCH_CS_PREFIX) +RETPOLINE_RUSTFLAGS += $(if $(call rustc-min-version,109100),-Zindirect-branch-cs-prefix,-Zllvm_module_flag=indirect_branch_cs_prefix:u32:1:override) ifdef CONFIG_MITIGATION_RETHUNK RETHUNK_CFLAGS := -mfunction-return=thunk-extern diff --git a/rust/Makefile b/rust/Makefile index 0165626decbe7e..6dceabbf02c872 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -167,7 +167,7 @@ pin_init-flags := \ rustdoc_modifiers_workaround := $(if $(call rustc-min-version,108800),-Cunsafe-allow-abi-mismatch=fixed-x18) # Similarly, for doctests (https://github.com/rust-lang/rust/issues/146465). -doctests_modifiers_workaround := $(rustdoc_modifiers_workaround)$(if $(call rustc-min-version,109100),$(comma)sanitizer) +doctests_modifiers_workaround := $(rustdoc_modifiers_workaround)$(if $(call rustc-min-version,109100),$(comma)sanitizer$(comma)indirect-branch-cs-prefix) quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $< cmd_rustdoc = \ From df71affdd95ea60fa3fb31e666389a53fd3297db Mon Sep 17 00:00:00 2001 From: Marwan Mohamed Zein Date: Sat, 14 Nov 2026 15:21:55 +0200 Subject: [PATCH 0728/2102] rust: iov: fix return lifetime of `copy_from_iter_raw()` The returned slice is derived from `out`, but lifetime elision ties it to `self` because this is a method. Explicitly bind the return lifetime to `out` so the returned slice cannot outlive its backing buffer. Fixes: 06cb58b310ea ("rust: iov: add iov_iter abstractions for ITER_SOURCE") Cc: stable@vger.kernel.org Reported-by: spidermana Closes: https://github.com/Rust-for-Linux/linux/issues/1265 Signed-off-by: Marwan Mohamed Zein Link: https://patch.msgid.link/20261114132156.49243-1-marawanzein222@gmail.com [ Reworded title. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/iov.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/iov.rs b/rust/kernel/iov.rs index 43bae8923c4611..8caf045180476c 100644 --- a/rust/kernel/iov.rs +++ b/rust/kernel/iov.rs @@ -161,7 +161,7 @@ impl<'data> IovIterSource<'data> { /// /// This will never write uninitialized bytes to the provided buffer. #[inline] - pub fn copy_from_iter_raw(&mut self, out: &mut [MaybeUninit]) -> &mut [u8] { + pub fn copy_from_iter_raw<'a>(&mut self, out: &'a mut [MaybeUninit]) -> &'a mut [u8] { let capacity = out.len(); let out = out.as_mut_ptr().cast::(); From 685dc94d51ca427c0ae5983491916b1279617047 Mon Sep 17 00:00:00 2001 From: Hao Tan Date: Tue, 10 Nov 2026 15:04:35 +0800 Subject: [PATCH 0729/2102] wifi: rtw89: coex: Disable pre-AGC for out-of-band links When Wi-Fi and Bluetooth are on different RF bands, neither the TDD nor the FDD binding has a band. _update_coex_bind() records that as dm->out_of_band. _set_wl_preagc_ctrl() disables pre-AGC when the TDD binding is 5 GHz, or when the role is still NOLINK. After commit a76501e1d148 ("wifi: rtw89: coex: Separate _ntfy_role_info into two function"), a 5 GHz-only STA is no longer NOLINK. With Wi-Fi on 5 GHz and Bluetooth on 2.4 GHz, tdd_bind is empty, so pre-AGC stays enabled. On RTL8851B this programs the pre-AGC table, and a VHT80 link drops shortly after association. Also disable pre-AGC when dm->out_of_band is set. Overlapping TDD and FDD bindings are unchanged. Tested on RTL8851BE (RFE 5, rtw8851b_fw-1.bin 0.29.41.5) with 5 GHz Wi-Fi and 2.4 GHz Bluetooth. Fixes: a76501e1d148 ("wifi: rtw89: coex: Separate _ntfy_role_info into two function") Cc: stable@vger.kernel.org Link: https://lore.kernel.org/linux-wireless/340ed206ff6a4680a46806e3bea5dbc5@realtek.com/ Signed-off-by: Hao Tan Acked-by: Ping-Ke Shih Signed-off-by: Ping-Ke Shih Link: https://patch.msgid.link/E6568F470624C07E+179429427543.116514.14355630958613033614@guwolf.com --- drivers/net/wireless/realtek/rtw89/coex.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/net/wireless/realtek/rtw89/coex.c b/drivers/net/wireless/realtek/rtw89/coex.c index 61e8b601ca3420..411c1490b03fc3 100644 --- a/drivers/net/wireless/realtek/rtw89/coex.c +++ b/drivers/net/wireless/realtek/rtw89/coex.c @@ -6604,7 +6604,8 @@ static void _set_wl_preagc_ctrl(struct rtw89_dev *rtwdev) if (!(bt->run_patch_code && bt->enable.now)) { is_preagc = BTC_PREAGC_DISABLE; - } else if (dm->tdd_bind.rf_band == BIT(RTW89_BAND_5G)) { + } else if (dm->out_of_band || + dm->tdd_bind.rf_band == BIT(RTW89_BAND_5G)) { is_preagc = BTC_PREAGC_DISABLE; } else if (rinfo->link_mode[RTW89_MAC_0] == BTC_WLINK_NOLINK || btc->cx.bt0.link_info.link_cnt.now == 0) { From 845dbb71d620c8f76ed63fa2cd25008194ad3426 Mon Sep 17 00:00:00 2001 From: Gu Bin Date: Fri, 13 Nov 2026 11:57:22 +0800 Subject: [PATCH 0730/2102] tools: gpio: gpio-watch: do not clobber errno on read error gpio-watch reads line change events from a gpiochip character device and reports a read() error or short read with perror(), which prints strerror(errno). If read() fails, say with EINTR, the inner if (rd != sizeof(chg)) errno = EIO; replaces the real errno with EIO, so the message always reports "Input/output error" instead of the actual cause. Only synthesize EIO for short reads (rd >= 0), keeping the errno that read() set when it failed. Fixes: 33f0c47b8fb4 ("tools: gpio: implement gpio-watch") Signed-off-by: Gu Bin Link: https://patch.msgid.link/20261113035723.2215-1-gubin@cmss.chinamobile.com Signed-off-by: Bartosz Golaszewski --- tools/gpio/gpio-watch.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/gpio/gpio-watch.c b/tools/gpio/gpio-watch.c index 41e76d24419224..e7733cedcf0d6f 100644 --- a/tools/gpio/gpio-watch.c +++ b/tools/gpio/gpio-watch.c @@ -64,7 +64,7 @@ int main(int argc, char **argv) memset(&chg, 0, sizeof(chg)); rd = read(pfd.fd, &chg, sizeof(chg)); if (rd < 0 || rd != sizeof(chg)) { - if (rd != sizeof(chg)) + if (rd >= 0 && rd != sizeof(chg)) errno = EIO; perror("error reading line change event"); From 74aee8e06277df39ec10ed043bae0ed5b7a83864 Mon Sep 17 00:00:00 2001 From: Lianjie Wang Date: Thu, 5 Nov 2026 04:56:31 +0900 Subject: [PATCH 0731/2102] gpio: virtio: bound the line names block by its configured size virtio_gpio_get_names() walks the line names that the device returns in a block of gpio_names_size bytes, which the driver ends with a NUL, and checks each name only after stepping past it. If the block holds fewer than ngpio names, the walk reaches the end of the block after the last name, and the next iteration starts strlen() at the byte after the allocation. With a block that holds one name for four lines, KASAN reports: BUG: KASAN: slab-out-of-bounds in strlen+0x57/0x70 Read of size 1 at addr ffff8880026687c0 by task swapper/0/1 Call Trace: strlen+0x57/0x70 virtio_gpio_probe+0xcb4/0xfc0 virtio_dev_probe+0xa7a/0xc50 Allocated by task 1: devm_kmalloc+0x6e/0x280 virtio_gpio_probe+0xc06/0xfc0 The buggy address is located 0 bytes to the right of allocated 64-byte region [ffff888002668780, ffff8880026687c0) Check that a name starts inside the block before reading it. Fixes: 3a29355a22c0 ("gpio: Add virtio-gpio driver") Cc: stable@vger.kernel.org Signed-off-by: Lianjie Wang Acked-by: Viresh Kumar Link: https://patch.msgid.link/20261104195632.1702765-1-lian@is.s.u-tokyo.ac.jp Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-virtio.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/gpio/gpio-virtio.c b/drivers/gpio/gpio-virtio.c index d0ae3d57c64037..aea5bf67fc0833 100644 --- a/drivers/gpio/gpio-virtio.c +++ b/drivers/gpio/gpio-virtio.c @@ -520,13 +520,13 @@ static const char **virtio_gpio_get_names(struct virtio_gpio *vgpio, gpio_names[gpio_names_size - 1] = '\0'; for (i = 0, str = gpio_names; i < ngpio; i++) { - names[i] = str; - str += strlen(str) + 1; /* zero-length strings are allowed */ - - if (str > gpio_names + gpio_names_size) { + if (str >= gpio_names + gpio_names_size) { dev_err(dev, "gpio_names block is too short (%d)\n", i); return NULL; } + + names[i] = str; + str += strlen(str) + 1; /* zero-length strings are allowed */ } return names; From 9e3032dc4d92e6214ae687b4c474de9270ce74a2 Mon Sep 17 00:00:00 2001 From: Lianjie Wang Date: Thu, 5 Nov 2026 04:56:32 +0900 Subject: [PATCH 0732/2102] gpio: virtio: compute the line names size in a size_t virtio_gpio_get_names() computes the size of the GET_LINE_NAMES response as sizeof(*res) + gpio_names_size in an int, where gpio_names_size is a u32 from the config space. A gpio_names_size of 0xffffffff makes the size 0, devm_kzalloc() returns ZERO_SIZE_PTR, and reading the status byte of the response through it oopses: Oops: general protection fault, probably for non-canonical address 0xdffffc0000000002: 0000 [#1] SMP KASAN PTI KASAN: null-ptr-deref in range [0x0000000000000010-0x0000000000000017] RIP: 0010:_virtio_gpio_req+0x2b8/0x550 Call Trace: virtio_gpio_probe+0xc2a/0xfc0 virtio_dev_probe+0xa7a/0xc50 Compute the size with struct_size() into a size_t. Fixes: 3a29355a22c0 ("gpio: Add virtio-gpio driver") Cc: stable@vger.kernel.org Signed-off-by: Lianjie Wang Acked-by: Viresh Kumar Link: https://patch.msgid.link/20261104195632.1702765-2-lian@is.s.u-tokyo.ac.jp Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-virtio.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/gpio/gpio-virtio.c b/drivers/gpio/gpio-virtio.c index aea5bf67fc0833..759d5cd0f62a4d 100644 --- a/drivers/gpio/gpio-virtio.c +++ b/drivers/gpio/gpio-virtio.c @@ -494,12 +494,13 @@ static const char **virtio_gpio_get_names(struct virtio_gpio *vgpio, struct device *dev = &vgpio->vdev->dev; u8 *gpio_names, *str; const char **names; - int i, ret, len; + size_t len; + int i, ret; if (!gpio_names_size) return NULL; - len = sizeof(*res) + gpio_names_size; + len = struct_size(res, value, gpio_names_size); res = devm_kzalloc(dev, len, GFP_KERNEL); if (!res) return NULL; From f95bdff1d53471159e3c7112c5de4f6240772521 Mon Sep 17 00:00:00 2001 From: David Thompson Date: Fri, 13 Nov 2026 13:44:44 -0500 Subject: [PATCH 0733/2102] gpio: mlxbf2: Disable interrupts around the chip lock in direction ops mlxbf2_gpio_lock_acquire() takes the generic GPIO chip lock with gpio_generic_chip_lock(), a plain raw_spin_lock() that leaves interrupts enabled. The same lock is also taken with the irqsave variant by the IRQ callbacks (irq_set_type, irq_enable, irq_disable), which run with the IRQ descriptor lock held. This creates a possible deadlock that lockdep reports as an IRQ lock inversion: CPU0 CPU1 ---- ---- lock(&chip->lock) lock(irq_desc->lock) lock(&chip->lock) lock(irq_desc->lock) If a GPIO interrupt arrives on CPU0 while it holds the chip lock during a direction change, the interrupt handler spins on the descriptor lock that CPU1 holds, while CPU1 spins on the chip lock held by CPU0. This was seen during probe of pwr-mlxbf. acpi_dev_gpio_irq_get() sets the pin to input through mlxbf2_gpio_direction_input(), and then irq_set_irq_type() runs with the descriptor lock held. Use the irqsave variant for the chip lock in mlxbf2_gpio_lock_acquire() and its release counterpart, and pass the saved flags from mlxbf2_gpio_direction_input() and mlxbf2_gpio_direction_output(). This matches the IRQ callbacks, so interrupts stay disabled for the whole ModeX update. Fixes: 2b725265cb08 ("gpio: mlxbf2: Introduce IRQ support") Cc: stable@vger.kernel.org Signed-off-by: David Thompson Link: https://patch.msgid.link/20261113184444.3431-1-davthompson@nvidia.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-mlxbf2.c | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/drivers/gpio/gpio-mlxbf2.c b/drivers/gpio/gpio-mlxbf2.c index b3b107c07cbec5..ed724d544c03d5 100644 --- a/drivers/gpio/gpio-mlxbf2.c +++ b/drivers/gpio/gpio-mlxbf2.c @@ -128,12 +128,20 @@ static int mlxbf2_gpio_get_lock_res(struct platform_device *pdev) * Acquire the YU arm_gpio_lock to be able to change the direction * mode. If the lock_active bit is already set, return an error. */ -static int mlxbf2_gpio_lock_acquire(struct mlxbf2_gpio_context *gs) +static int mlxbf2_gpio_lock_acquire(struct mlxbf2_gpio_context *gs, + unsigned long *flags) { u32 arm_gpio_lock_val; mutex_lock(yu_arm_gpio_lock_param.lock); - gpio_generic_chip_lock(&gs->chip); + /* + * Disable interrupts before taking the chip lock. The GPIO irq + * callbacks take this lock while holding the irq descriptor lock, + * and the irq handler takes the descriptor lock in hardirq context. + * A plain spin_lock() here lets lockdep report an inversion, and + * can deadlock if a GPIO interrupt arrives on this CPU. + */ + gpio_generic_chip_lock_irqsave(&gs->chip, *flags); arm_gpio_lock_val = readl(yu_arm_gpio_lock_param.io); @@ -141,7 +149,7 @@ static int mlxbf2_gpio_lock_acquire(struct mlxbf2_gpio_context *gs) * When lock active bit[31] is set, ModeX is write enabled */ if (YU_LOCK_ACTIVE_BIT(arm_gpio_lock_val)) { - gpio_generic_chip_unlock(&gs->chip); + gpio_generic_chip_unlock_irqrestore(&gs->chip, *flags); mutex_unlock(yu_arm_gpio_lock_param.lock); return -EINVAL; } @@ -154,12 +162,13 @@ static int mlxbf2_gpio_lock_acquire(struct mlxbf2_gpio_context *gs) /* * Release the YU arm_gpio_lock after changing the direction mode. */ -static void mlxbf2_gpio_lock_release(struct mlxbf2_gpio_context *gs) +static void mlxbf2_gpio_lock_release(struct mlxbf2_gpio_context *gs, + unsigned long flags) __releases(&gs->chip.lock) __releases(yu_arm_gpio_lock_param.lock) { writel(YU_ARM_GPIO_LOCK_RELEASE, yu_arm_gpio_lock_param.io); - gpio_generic_chip_unlock(&gs->chip); + gpio_generic_chip_unlock_irqrestore(&gs->chip, flags); mutex_unlock(yu_arm_gpio_lock_param.lock); } @@ -185,20 +194,21 @@ static int mlxbf2_gpio_direction_input(struct gpio_chip *chip, unsigned int offset) { struct mlxbf2_gpio_context *gs = gpiochip_get_data(chip); + unsigned long flags; int ret; /* * Although the arm_gpio_lock was set in the probe function, check again * if it is still enabled to be able to write to the ModeX registers. */ - ret = mlxbf2_gpio_lock_acquire(gs); + ret = mlxbf2_gpio_lock_acquire(gs, &flags); if (ret < 0) return ret; writel(BIT(offset), gs->gpio_io + YU_GPIO_MODE0_CLEAR); writel(BIT(offset), gs->gpio_io + YU_GPIO_MODE1_CLEAR); - mlxbf2_gpio_lock_release(gs); + mlxbf2_gpio_lock_release(gs, flags); return ret; } @@ -212,6 +222,7 @@ static int mlxbf2_gpio_direction_output(struct gpio_chip *chip, int value) { struct mlxbf2_gpio_context *gs = gpiochip_get_data(chip); + unsigned long flags; int ret = 0; /* @@ -219,14 +230,14 @@ static int mlxbf2_gpio_direction_output(struct gpio_chip *chip, * check again it is still enabled to be able to write to the * ModeX registers. */ - ret = mlxbf2_gpio_lock_acquire(gs); + ret = mlxbf2_gpio_lock_acquire(gs, &flags); if (ret < 0) return ret; writel(BIT(offset), gs->gpio_io + YU_GPIO_MODE1_CLEAR); writel(BIT(offset), gs->gpio_io + YU_GPIO_MODE0_SET); - mlxbf2_gpio_lock_release(gs); + mlxbf2_gpio_lock_release(gs, flags); return ret; } From 2e002a1d05b1979006f3c46eb6cb5cc36e5630ac Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Tue, 10 Nov 2026 10:29:34 +0100 Subject: [PATCH 0734/2102] gpiolib: keep the line state workqueue alive until device release gpiod_line_state_notify() races with a concurrent gpiochip_remove() which unconditionally destroys the line state workqueue causing a use-after-free situation where queue_work() can schedule a work on a freed workqueue. Keep the line state workqueue alive until GPIO device release. Cc: stable@vger.kernel.org Fixes: 07c61d4da43f ("gpiolib: notify user-space about in-kernel line state changes") Closes: https://sashiko.dev/#/bug/linux-d0e9e518-2348-4fe3-857d-f3d61a42f159 Link: https://patch.msgid.link/20261110-gpio-line-state-wq-uaf-v2-1-ce6d8266656e@oss.qualcomm.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib-cdev.c | 2 +- drivers/gpio/gpiolib.c | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/drivers/gpio/gpiolib-cdev.c b/drivers/gpio/gpiolib-cdev.c index 5f78960eb7f1ea..bfe442db7cd383 100644 --- a/drivers/gpio/gpiolib-cdev.c +++ b/drivers/gpio/gpiolib-cdev.c @@ -2764,6 +2764,7 @@ int gpiolib_cdev_register(struct gpio_chip *gc, dev_t devt) ret = cdev_device_add(&gdev->chrdev, &gdev->dev); if (ret) { destroy_workqueue(gdev->line_state_wq); + gdev->line_state_wq = NULL; return ret; } @@ -2774,7 +2775,6 @@ int gpiolib_cdev_register(struct gpio_chip *gc, dev_t devt) void gpiolib_cdev_unregister(struct gpio_device *gdev) { - destroy_workqueue(gdev->line_state_wq); cdev_device_del(&gdev->chrdev, &gdev->dev); blocking_notifier_call_chain(&gdev->device_notifier, 0, NULL); } diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index 6f8f30b767ef0e..63cc4064bfa4b2 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -900,6 +901,9 @@ static void gpiodev_release(struct device *dev) synchronize_srcu(&gdev->desc_srcu); cleanup_srcu_struct(&gdev->desc_srcu); + if (gdev->line_state_wq) + destroy_workqueue(gdev->line_state_wq); + ida_free(&gpio_ida, gdev->id); kfree_const(gdev->label); kfree(gdev->descs); From e2954988bb987c1432806379f602573d2388df93 Mon Sep 17 00:00:00 2001 From: Niklas Cassel Date: Mon, 16 Nov 2026 20:10:09 +0100 Subject: [PATCH 0735/2102] ata: libata-scsi: fix the INC_512 bit test for SECURITY PROTOCOL IN/OUT ata_scsi_security_inout_xlat() tests the INC_512 bit with cdb[4] & 7. INC_512 is bit 7 of byte 4 of the SECURITY PROTOCOL IN and SECURITY PROTOCOL OUT CDBs (SPC-6, tables 280 and 282), and bits 6:0 of that byte are reserved. Test bit 7 instead. Fixes: 818831c8b22f ("libata: implement SECURITY PROTOCOL IN/OUT") Cc: stable@vger.kernel.org Reviewed-by: Damien Le Moal Link: https://lore.kernel.org/r/20261116191008.2954277-2-cassel@kernel.org Signed-off-by: Niklas Cassel --- drivers/ata/libata-scsi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/ata/libata-scsi.c b/drivers/ata/libata-scsi.c index 20ea1c997d56b3..c08643571ce488 100644 --- a/drivers/ata/libata-scsi.c +++ b/drivers/ata/libata-scsi.c @@ -4812,7 +4812,7 @@ static unsigned int ata_scsi_security_inout_xlat(struct ata_queued_cmd *qc) return 1; } - if (cdb[4] & 7) { /* INC_512 */ + if (cdb[4] & 0x80) { /* INC_512 */ if (len > 0xffff) { ata_scsi_set_invalid_field(qc->dev, scmd, 6, 0); return 1; From e6e2181c6920ff59ded349a100f80cf85d074601 Mon Sep 17 00:00:00 2001 From: Alexandre Becholey Date: Fri, 13 Nov 2026 14:44:58 +0000 Subject: [PATCH 0736/2102] gpio: ljca: Validate the pin index of interrupt events ljca_gpio_event_cb() takes the pin index of every item in a GPIO interrupt event from the device and passes it to set_bit() on the reenable_irqs bitmap, which is only LJCA_MAX_GPIO_NUM (64) bits long. The index is a u8, so a malfunctioning or malicious device can set bits past the end of the bitmap, in the members that follow it in struct ljca_gpio_dev: the output_enabled bitmap, the connect_mode pointer and the irq_lock mutex. connect_mode is later dereferenced and written to by ljca_gpio_set_config() and ljca_irq_set_type(), so the device can flip bits of a kernel pointer that is then used for a write. Until commit 4c4e6ea4a120 ("gpio: ljca: Fix duplicated IRQ mapping") an index without an IRQ mapping made irq_find_mapping() fail and the handler returned before set_bit(). Since that change nothing checks the index. A device bound to usb-ljca can trigger this by sending one GPIO interrupt event, once the gpiochip is registered, with an index that sets a bit of connect_mode which is still clear in a kernel pointer: 175 (bit 47) on arm64, 174 (bit 46) on x86_64. The next GPIO line request then faults in ljca_gpio_set_config(). With dummy_hcd and KASAN, on arm64 (torvalds/master 067c5c24cef2): Unable to handle kernel paging request at virtual address ffff7000023dfd30 pc : ljca_gpio_set_config (drivers/gpio/gpio-ljca.c:212) and on x86_64 (torvalds/master 7e1392a42ea2, nokaslr): BUG: unable to handle page fault for address: ffffc8800f5452b8 RIP: 0010:ljca_gpio_set_config (drivers/gpio/gpio-ljca.c:212) Ignore event items whose pin index is not below the number of GPIOs of the chip. That number never exceeds LJCA_MAX_GPIO_NUM, because usb-ljca rejects larger values at enumeration, so set_bit() stays inside the bitmap. Valid items in the same event are still handled. The bug was found by AI agents (Claude Mythos and Claude Opus models). The analysis and the patch were reviewed by a human, who also reproduced the bug on x86_64 and aarch64 with current master. Fixes: 4c4e6ea4a120 ("gpio: ljca: Fix duplicated IRQ mapping") Cc: stable@vger.kernel.org Signed-off-by: Alexandre Becholey Link: https://patch.msgid.link/20261113144432.1354180-1-alex@becholey.ch Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-ljca.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/drivers/gpio/gpio-ljca.c b/drivers/gpio/gpio-ljca.c index 067e5c472abdd7..997b361a402411 100644 --- a/drivers/gpio/gpio-ljca.c +++ b/drivers/gpio/gpio-ljca.c @@ -292,9 +292,14 @@ static void ljca_gpio_event_cb(void *context, u8 cmd, const void *evt_data, return; for (i = 0; i < packet->num; i++) { - generic_handle_domain_irq(ljca_gpio->gc.irq.domain, - packet->item[i].index); - set_bit(packet->item[i].index, ljca_gpio->reenable_irqs); + u8 index = packet->item[i].index; + + /* The pin index comes from the device, do not trust it */ + if (index >= ljca_gpio->gc.ngpio) + continue; + + generic_handle_domain_irq(ljca_gpio->gc.irq.domain, index); + set_bit(index, ljca_gpio->reenable_irqs); } schedule_work(&ljca_gpio->work); From 297ae15901733df7562a6781613fb49f3d270401 Mon Sep 17 00:00:00 2001 From: Kalpesh Solanki Date: Thu, 12 Nov 2026 18:38:33 +0530 Subject: [PATCH 0737/2102] bonding: reject IEEE 802.15.4 and 6LoWPAN devices in bond_enslave When the first non-Ethernet slave is enslaved to a bond, bond_setup_by_slave() copies slave_dev->type to the bond device. However, the bonding driver does not set up subsystem-specific mid-layer contexts or private structures: 1. IEEE 802.15.4 routines (such as ieee802154_llsec_dump_table(), nl-phy.c, and socket callbacks) identify WPAN devices by dev->type alone and unconditionally dereference dev->ieee802154_ptr and dev->ml_priv (ieee802154_mlme_ops). Because bonding never allocates these, this results in a NULL pointer dereference. 2. The 6LoWPAN netdevice notifier (lowpan_event()) identifies devices by dev->type == ARPHRD_6LOWPAN and treats netdev_priv(dev) as struct lowpan_dev. On a bond master, netdev_priv() is struct bonding, so writes to lowpan_dev(dev)->ctx.table flags on events like NETDEV_DOWN corrupt the bonding driver's private state. The team driver closed an identical gap in commit 9043be310c6a ("team: reject CAN, IEEE 802.15.4 and 6LoWPAN devices in team_port_add"). Bonding previously only blocked CAN devices in commit 8ba68464e478 ("bonding: refuse to enslave CAN devices"). Reject ARPHRD_IEEE802154, ARPHRD_IEEE802154_MONITOR, and ARPHRD_6LOWPAN devices in bond_enslave(). Fixes: 872254dd6b1f ("net/bonding: Enable bonding to enslave non ARPHRD_ETHER") Signed-off-by: Kalpesh Solanki Reviewed-by: Oliver Hartkopp Reviewed-by: Hangbin Liu Link: https://patch.msgid.link/20261112130833.233208-1-skalpesh942@gmail.com Signed-off-by: Paolo Abeni --- drivers/net/bonding/bond_main.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/net/bonding/bond_main.c b/drivers/net/bonding/bond_main.c index e9f5e753f6770b..042d7c75548fac 100644 --- a/drivers/net/bonding/bond_main.c +++ b/drivers/net/bonding/bond_main.c @@ -1894,9 +1894,12 @@ int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev, struct sockaddr_storage ss; int res = 0, i; - if (slave_dev->type == ARPHRD_CAN) { + if (slave_dev->type == ARPHRD_CAN || + slave_dev->type == ARPHRD_IEEE802154 || + slave_dev->type == ARPHRD_IEEE802154_MONITOR || + slave_dev->type == ARPHRD_6LOWPAN) { BOND_NL_ERR(bond_dev, extack, - "CAN devices cannot be enslaved"); + "CAN, IEEE 802.15.4 and 6LoWPAN devices cannot be enslaved"); return -EPERM; } From 748ea6c389c01af93a1d372876ab4176e3f0a916 Mon Sep 17 00:00:00 2001 From: Johan Hovold Date: Fri, 6 Nov 2026 09:01:55 +0100 Subject: [PATCH 0738/2102] USB: serial: mct_u232: fix NULL-deref on open() failure The driver uses a second interrupt endpoint for reading but still dereferences the port bulk-in URB pointer, which is no longer overridden by the driver, in an error path. Fix the dev_err() on failure to submit the read interrupt URB to avoid dereferencing a NULL-pointer. Fixes: 35807187e4b3 ("USB: mct_u232: clean up read implementation") Reported-by: syzbot+58b2d8b19cd6761a395b@syzkaller.appspotmail.com Closes: https://lore.kernel.org/6aed834c.dadc8e63.45095.0003.GAE@google.com Cc: stable@vger.kernel.org # 3.10 Signed-off-by: Johan Hovold --- drivers/usb/serial/mct_u232.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/usb/serial/mct_u232.c b/drivers/usb/serial/mct_u232.c index a6de18917ec9fd..8a7aee2b26dda4 100644 --- a/drivers/usb/serial/mct_u232.c +++ b/drivers/usb/serial/mct_u232.c @@ -457,7 +457,7 @@ static int mct_u232_open(struct tty_struct *tty, struct usb_serial_port *port) if (retval) { dev_err(&port->dev, "usb_submit_urb(read) failed pipe 0x%x err %d\n", - port->read_urb->pipe, retval); + priv->read_urb->pipe, retval); goto error; } From d091d9a05f78af9332785f1767467a0a88d24233 Mon Sep 17 00:00:00 2001 From: Haowen Tu Date: Mon, 16 Nov 2026 13:10:24 +0800 Subject: [PATCH 0739/2102] USB: serial: f81232: drain work on failed open The interrupt URB is submitted before usb_serial_generic_open() starts the bulk read URBs. A modem-status notification can therefore queue interrupt_work before a bulk read submission fails. A bulk read that completes before a later submission fails can also queue lsr_work. The error path kills the interrupt URB but does not drain either work item. The tty port is not initialized after a failed open, so the close callback, which normally flushes this work, is not called. If the device is then disconnected, the work can outlive the port private data it uses. Flush both work items after killing the interrupt URB. The generic open error path has already killed any submitted bulk read URBs, so neither source can queue more work at this point. Fixes: 87fe5adcd8de ("USB: f81232: implement read IIR/MSR with endpoint") Signed-off-by: Haowen Tu Cc: stable@vger.kernel.org # 4.1 Signed-off-by: Johan Hovold --- drivers/usb/serial/f81232.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/usb/serial/f81232.c b/drivers/usb/serial/f81232.c index 9a3ede35a3d9ea..b62e93e7612c40 100644 --- a/drivers/usb/serial/f81232.c +++ b/drivers/usb/serial/f81232.c @@ -695,6 +695,7 @@ static int f81232_tiocmset(struct tty_struct *tty, static int f81232_open(struct tty_struct *tty, struct usb_serial_port *port) { + struct f81232_private *priv = usb_get_serial_port_data(port); int result; result = f81232_port_enable(port); @@ -715,6 +716,8 @@ static int f81232_open(struct tty_struct *tty, struct usb_serial_port *port) result = usb_serial_generic_open(tty, port); if (result) { usb_kill_urb(port->interrupt_in_urb); + flush_work(&priv->interrupt_work); + flush_work(&priv->lsr_work); return result; } From a12cc63129380a5364e787d92b30a3257f66c250 Mon Sep 17 00:00:00 2001 From: Justinien Bouron Date: Mon, 16 Nov 2026 12:54:30 -0800 Subject: [PATCH 0740/2102] ata: libata-core: Add max sector quirk to INTEL SSDSCKKB240G8 INTEL SSDSCKKB240G8 with firmware version XC311102 runs into FPDMA timeout errors when queue/max_sectors_kb is set to BLK_DEF_MAX_SECTORS_CAP = 4096KiB / 8192 sectors. Similar to model SSDSC2KG480G8, the issue disappears when setting this max size to 8191 sectors, thus apply the same quirk. Firmware version X5A1ME59 for SSDSCKKB240G8 is un-affected by this bug thus keep the quirk specific to firmware XC311102. Fixes: 9b8b84879d4a ("block: Increase BLK_DEF_MAX_SECTORS_CAP") Signed-off-by: Justinien Bouron Reviewed-by: Gunnar Kudrjavets Cc: stable@vger.kernel.org Reviewed-by: Damien Le Moal Link: https://lore.kernel.org/r/20261116205430.44305-1-jbouron@amazon.com Signed-off-by: Niklas Cassel --- drivers/ata/libata-core.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/ata/libata-core.c b/drivers/ata/libata-core.c index 5ff45a5cbfe4a7..2a5ca1b9ee5c03 100644 --- a/drivers/ata/libata-core.c +++ b/drivers/ata/libata-core.c @@ -4204,6 +4204,7 @@ static const struct ata_dev_quirk_value __ata_dev_max_sec_quirks[] = { { "LITEON EP1-*", NULL, 1024 }, { "DELLBOSS VD", "MV.R00-0", 8191 }, { "INTEL SSDSC2KG480G8", "XCV10120", 8191 }, + { "INTEL SSDSCKKB240G8", "XC311102", 8191 }, { }, }; @@ -4474,6 +4475,8 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = { ATA_QUIRK_MAX_SEC }, { "INTEL*SSDSC2CT*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM | ATA_QUIRK_NO_FUA }, + { "INTEL SSDSCKKB240G8", "XC311102", ATA_QUIRK_ZERO_AFTER_TRIM | + ATA_QUIRK_MAX_SEC }, { "INTEL*SSD*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM }, { "SSD*INTEL*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM }, { "Samsung*SSD*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM }, From 586a87701101ba11477c8b5cdc1528413318ab77 Mon Sep 17 00:00:00 2001 From: Yang Siyuan Date: Tue, 17 Nov 2026 19:08:12 +0800 Subject: [PATCH 0741/2102] reset: core: honour optional resets when the GPIO fallback returns -ENOENT __fwnode_reset_control_get() honours RESET_CONTROL_FLAGS_BIT_OPTIONAL by returning NULL when the requested reset is not described in the device tree. The reset-gpio fallback breaks this: when __reset_add_reset_gpio_device() fails with -ENOENT, the error is returned even for an optional reset. This is reachable on Allwinner SoCs, whose pinctrl uses three-cell GPIO specifiers. The reset-gpio fallback only supports two cells, so it returns -ENOENT and a consumer asking for an optional reset fails to probe instead of falling back to its own GPIO handling. mmc-pwrseq-simple on the Anbernic RG35XX family hits this: its wifi_pwrseq node has reset-gpios but no resets, so the SDIO WiFi adapter never probes. Return NULL only for -ENOENT when the reset was requested as optional. A reset that is described but cannot be used is still an error, so -EPROBE_DEFER and all other failures are propagated. Signed-off-by: Yang Siyuan Reviewed-by: Philipp Zabel Signed-off-by: Philipp Zabel --- drivers/reset/core.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/reset/core.c b/drivers/reset/core.c index 4a582721782f49..1ae7ca1e8552f9 100644 --- a/drivers/reset/core.c +++ b/drivers/reset/core.c @@ -1216,6 +1216,8 @@ __fwnode_reset_control_get(struct fwnode_handle *fwnode, const char *id, int ind ret = __reset_add_reset_gpio_device(fwnode, &args); if (ret) { fwnode_handle_put(args.fwnode); + if (ret == -ENOENT && optional) + return NULL; return ERR_PTR(ret); } } From 8868b79a430e626ad72b11d355514bed34cbb8b9 Mon Sep 17 00:00:00 2001 From: Cunhao Lu <1579567540@qq.com> Date: Fri, 13 Nov 2026 10:33:06 +0800 Subject: [PATCH 0742/2102] MAINTAINERS: exclude CAN documentation from general networking The SocketCAN, ISO-TP and J1939 documents and the CAN driver documentation directory match the broad Documentation/networking/ pattern in NETWORKING [GENERAL]. This makes get_maintainer.pl select netdev and the general networking maintainers for these CAN-specific documentation changes. Exclude these paths from NETWORKING [GENERAL], as is already done for net/can/ and the CAN selftests. Add the driver documentation directory to CAN NETWORK DRIVERS to cover files without a dedicated CAN entry. Suggested-by: Jakub Kicinski Link: https://lore.kernel.org/all/20261111161459.4879a82d@kernel.org/ Signed-off-by: Cunhao Lu <1579567540@qq.com> Link: https://patch.msgid.link/20261113-exclude-can-docs-from-netdev-v2-1-8ae9dc553024@qq.com Signed-off-by: Paolo Abeni --- MAINTAINERS | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 056408bc086ead..a809df29a6c5c2 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5992,6 +5992,7 @@ T: git git://git.kernel.org/pub/scm/linux/kernel/git/mkl/linux-can.git T: git git://git.kernel.org/pub/scm/linux/kernel/git/mkl/linux-can-next.git F: Documentation/devicetree/bindings/net/can/ F: Documentation/devicetree/bindings/phy/ti,tcan104x-can.yaml +F: Documentation/networking/device_drivers/can/ F: drivers/net/can/ F: drivers/phy/phy-can-transceiver.c F: include/linux/can/bittiming.h @@ -19601,6 +19602,10 @@ F: samples/pktgen/ F: tools/net/ F: tools/testing/selftests/net/ X: Documentation/networking/batman-adv.rst +X: Documentation/networking/can.rst +X: Documentation/networking/device_drivers/can/ +X: Documentation/networking/iso15765-2.rst +X: Documentation/networking/j1939.rst X: Documentation/networking/mac80211-injection.rst X: Documentation/networking/mac80211_hwsim/ X: Documentation/networking/regulatory.rst From 754c5f89ae2eafd6aabb4ef01917211faa0485ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jens=20Emil=20Schulz=20=C3=98stergaard?= Date: Mon, 9 Nov 2026 14:50:41 +0100 Subject: [PATCH 0743/2102] pinctrl: ocelot: use a raw spinlock for the GPIO regmap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The irq_chip callbacks .irq_mask, .irq_unmask and .irq_ack access the GPIO regmap. genirq calls them with the raw spinlock irq_desc::lock held, for example from irq_startup() in __setup_irq(). The regmap is created with devm_regmap_init_mmio() and guarded by a spinlock_t, which is a sleeping lock on PREEMPT_RT and must not be taken under a raw spinlock. Make the GPIO regmap use a raw spinlock. Its accesses are short MMIO reads and writes. The other regmaps of the driver are not used from the irq_chip callbacks and are left unchanged. The issue was found with CONFIG_PROVE_RAW_LOCK_NESTING on a lan9668 board (pcb8385), when a level low interrupt on one of its GPIOs is requested, and was seen on lan969x when a PHY interrupt on a GPIO is requested: ============================= [ BUG: Invalid wait context ] ----------------------------- swapper/0/1 is trying to lock: c3046c10 (pinctrl_ocelot:34:(config)->lock){....}-{3:3}, at: regmap_lock_spinlock+0xc/0x40 other info that might help us debug this: context-{5:5} locks held by swapper/0/1: 6, last CPU#0: ... #4: c3200b5c (request_class){+.+.}-{4:4}, at: __setup_irq+0x140/0x840 #5: c3200a7c (lock_class){....}-{2:2}, at: __setup_irq+0x168/0x840 stack backtrace: ... _raw_spin_lock_irqsave from regmap_lock_spinlock+0xc/0x40 regmap_lock_spinlock from regmap_read+0x2c/0x80 regmap_read from ocelot_irq_unmask_level+0x6c/0x240 ocelot_irq_unmask_level from irq_enable+0x38/0xc0 irq_enable from __irq_startup+0x70/0xc0 __irq_startup from irq_startup+0xb8/0x180 irq_startup from __setup_irq+0x4d0/0x840 __setup_irq from request_threaded_irq+0xbc/0x180 request_threaded_irq from devm_request_threaded_irq+0x70/0x140 With the fix the report is gone on the lan9668 board. Fixes: c297561bc98a ("pinctrl: ocelot: Fix interrupt controller") Signed-off-by: Jens Emil Schulz Østergaard Signed-off-by: Linus Walleij --- drivers/pinctrl/pinctrl-ocelot.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/pinctrl/pinctrl-ocelot.c b/drivers/pinctrl/pinctrl-ocelot.c index 58d3cde9f964da..06dd49782d7497 100644 --- a/drivers/pinctrl/pinctrl-ocelot.c +++ b/drivers/pinctrl/pinctrl-ocelot.c @@ -2440,6 +2440,7 @@ static int ocelot_pinctrl_probe(struct platform_device *pdev) .reg_bits = 32, .val_bits = 32, .reg_stride = 4, + .use_raw_spinlock = true, }; info = devm_kzalloc(dev, sizeof(*info), GFP_KERNEL); From 5cf0969621bc014b5305e6ff8b7e28f20060c3e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jens=20Emil=20Schulz=20=C3=98stergaard?= Date: Mon, 9 Nov 2026 14:50:42 +0100 Subject: [PATCH 0744/2102] pinctrl: ocelot: do not use the chained irqchip behind a sleeping bus MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since the driver can use a regmap on a bus that can sleep, as for VSC7512 attached over SPI, it still registers the gpiochip as not sleeping and adds the chained irqchip when the node has an interrupt. The chained handler and the irq_chip callbacks run in atomic context and access the registers through that regmap, and consumers may use the lines of a gpiochip that is not marked as sleeping from atomic context. Mark the gpiochip as sleeping when the regmap can sleep, and do not register the chained irqchip in that case. The issue was found by code inspection and reproduced on a lan9668 board (pcb8385) with a lan9645x attached over SPI, whose pinctrl node has an interrupt, by requesting an edge interrupt on one of its GPIOs through the GPIO character device: BUG: sleeping function called from invalid context at kernel/locking/mutex.c:623 in_atomic(): 1, irqs_disabled(): 128, non_block: 0, pid: 420, name: gpiomon preempt_count: 1, expected: 0 locks held by gpiomon/420: 3, last CPU#0: #0: 84463cd0 (&gdev->srcu){.+.+}-{0:0}, at: lineinfo_get+0x13f/0x140 #1: 838bbd30 (request_class){+.+.}-{4:4}, at: __setup_irq+0xe8/0x5c0 #2: 838bbc70 (lock_class){-...}-{2:2}, at: __setup_irq+0x104/0x5c0 ... Call trace: ... mutex_lock_nested from regmap_update_bits_base+0x1c/0x80 regmap_update_bits_base from ocelot_irq_unmask+0x42/0x80 ocelot_irq_unmask from irq_enable+0x1e/0x80 irq_enable from irq_startup+0x64/0xc0 irq_startup from __setup_irq+0x38c/0x5c0 __setup_irq from request_threaded_irq+0x86/0x140 request_threaded_irq from edge_detector_setup+0x1d8/0x240 edge_detector_setup from linereq_create+0x3e2/0x540 linereq_create from gpio_ioctl+0xa4/0x240 With the fix the lan9645x gpiochip is registered as sleeping and without the chained irqchip, the request fails with -ENXIO instead and without lockdep reports. Fixes: 181f604b33cd ("pinctrl: ocelot: add ability to be used in a non-mmio configuration") Signed-off-by: Jens Emil Schulz Østergaard Reviewed-by: Colin Foster Signed-off-by: Linus Walleij --- drivers/pinctrl/pinctrl-ocelot.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/pinctrl/pinctrl-ocelot.c b/drivers/pinctrl/pinctrl-ocelot.c index 06dd49782d7497..90a1f859db67ba 100644 --- a/drivers/pinctrl/pinctrl-ocelot.c +++ b/drivers/pinctrl/pinctrl-ocelot.c @@ -2367,8 +2367,9 @@ static int ocelot_gpiochip_register(struct platform_device *pdev, gc->parent = &pdev->dev; gc->base = -1; gc->label = "ocelot-gpio"; + gc->can_sleep = regmap_might_sleep(info->map); - irq = platform_get_irq_optional(pdev, 0); + irq = gc->can_sleep ? 0 : platform_get_irq_optional(pdev, 0); if (irq > 0) { girq = &gc->irq; gpio_irq_chip_set_chip(girq, &ocelot_irqchip); From 94f6244411ac7e3108f85d1c672e8564d10945cc Mon Sep 17 00:00:00 2001 From: Ruben Wauters Date: Fri, 13 Nov 2026 08:25:57 +0000 Subject: [PATCH 0745/2102] MAINTAINERS: Update Ruben Wauters email address Due to issues from my mailhost with sending and receiving patches, I am moving to a linux.dev address. Signed-off-by: Ruben Wauters Signed-off-by: Thomas Zimmermann Acked-by: Thomas Zimmermann Link: https://patch.msgid.link/20261113082738.6447-1-ruben.wauters@linux.dev --- .mailmap | 1 + MAINTAINERS | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.mailmap b/.mailmap index 610983fe3123ba..66fc8065b082ee 100644 --- a/.mailmap +++ b/.mailmap @@ -816,6 +816,7 @@ Ronak Doshi Muchun Song Muchun Song Ross Zwisler +Ruben Wauters Rudolf Marek Rui Saraiva Sachin Mokashi diff --git a/MAINTAINERS b/MAINTAINERS index 3eaba09ac3c6fa..d40d8ef0188f2e 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -8330,7 +8330,7 @@ F: Documentation/devicetree/bindings/display/panel/panel-edp.yaml F: drivers/gpu/drm/panel/panel-edp.c DRM DRIVER FOR GENERIC USB DISPLAY -M: Ruben Wauters +M: Ruben Wauters S: Maintained W: https://github.com/notro/gud/wiki T: git https://gitlab.freedesktop.org/drm/misc/kernel.git From f02d1f70d361c42d09569e51612d6be5ffceb7d6 Mon Sep 17 00:00:00 2001 From: Thomas Zimmermann Date: Tue, 10 Nov 2026 09:45:19 +0100 Subject: [PATCH 0746/2102] drm/vblank: timer: Do not block within critical section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove try-to-cancel loop from drm_crtc_vblank_start_timer() to avoid a possible livelock while spinning within the loop. Hold interval_lock when starting and forwarding the vblank timer's hrtimer to avoid forwarding an already queued timer. The vblank helper drm_vblank_disable_and_save() and the vblank IRQ handler hold the spin lock vblank_time_lock at some point. This can result in a deadlock if the vblank timer's disable code in drm_crtc_vblank_cancel_timer() calls hrtimer_cancel() directly: the helper waits for the timer function to complete and the timer function waits for the helper to release vblank_time_lock. drm_crtc_vblank_cancel_timer() works around this problem by calling hrtimer_try_to_cancel() instead. For re-enabling the vblank timer, drm_crtc_vblank_start_timer() currently waits for the vblank timer to stop. It runs into the same locking problem while waiting for the timer function to complete. Resolve the locking problem by removing hrtimer_try_to_cancel() from drm_crtc_vblank_start_timer(). Hold interval_lock while starting or forwarding the hrtimer. Without holding interval_lock, drm_crtc_vblank_start_timer() could set an interval and start the hrtimer; while a concurrent timer function forwards the timer with the old interval. This can corrupt the ordering of the hrtimer's internal queue. Holding the lock prevents this from happening. When starting the vblank timer, it is still possible that an already running timer sends out a vblank event at the previous vblank interval. This is merely an inconsistency and not critical. Closes: https://lore.kernel.org/dri-devel/20260914111129.300691F00898@smtp.kernel.org/ Suggested-by: Ville Syrjälä Signed-off-by: Thomas Zimmermann Reviewed-by: Zack Rusin Fixes: 74afeb812850 ("drm/vblank: Add vblank timer") Cc: Louis Chauvet Cc: Javier Martinez Canillas Cc: David Airlie Cc: Simona Vetter Cc: Maarten Lankhorst Cc: Maxime Ripard Cc: dri-devel@lists.freedesktop.org Cc: # v6.19+ Link: https://patch.msgid.link/20261110084710.503870-2-tzimmermann@suse.de --- drivers/gpu/drm/drm_vblank.c | 34 ++++++++++++---------------------- 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/drivers/gpu/drm/drm_vblank.c b/drivers/gpu/drm/drm_vblank.c index f90fb2d13e423d..8cc8d018d353a7 100644 --- a/drivers/gpu/drm/drm_vblank.c +++ b/drivers/gpu/drm/drm_vblank.c @@ -2179,19 +2179,18 @@ static enum hrtimer_restart drm_vblank_timer_function(struct hrtimer *timer) struct drm_crtc *crtc = vtimer->crtc; const struct drm_crtc_helper_funcs *crtc_funcs = crtc->helper_private; struct drm_device *dev = crtc->dev; - unsigned long flags; - ktime_t interval; - u64 ret_overrun; + u64 ret_overrun = 1; bool succ; - spin_lock_irqsave(&vtimer->interval_lock, flags); - interval = vtimer->interval; - spin_unlock_irqrestore(&vtimer->interval_lock, flags); + scoped_guard(spinlock_irqsave, &vtimer->interval_lock) { + ktime_t interval = vtimer->interval; - if (!interval) - return HRTIMER_NORESTART; + if (!interval || hrtimer_is_queued(timer)) + return HRTIMER_NORESTART; + + ret_overrun = hrtimer_forward_now(timer, interval); + } - ret_overrun = hrtimer_forward_now(&vtimer->timer, interval); if (ret_overrun != 1) drm_dbg_vbl(dev, "vblank timer overrun\n"); @@ -2220,7 +2219,6 @@ int drm_crtc_vblank_start_timer(struct drm_crtc *crtc) { struct drm_vblank_crtc *vblank = drm_crtc_vblank_crtc(crtc); struct drm_vblank_crtc_timer *vtimer = &vblank->vblank_timer; - unsigned long flags; if (!vtimer->crtc) { /* @@ -2230,22 +2228,14 @@ int drm_crtc_vblank_start_timer(struct drm_crtc *crtc) spin_lock_init(&vtimer->interval_lock); hrtimer_setup(&vtimer->timer, drm_vblank_timer_function, CLOCK_MONOTONIC, HRTIMER_MODE_REL); - } else { - /* - * Timer should not be active. If it is, wait for the - * previous cancel operations to finish. - */ - while (hrtimer_active(&vtimer->timer)) - hrtimer_try_to_cancel(&vtimer->timer); } drm_calc_timestamping_constants(crtc, &crtc->mode); - spin_lock_irqsave(&vtimer->interval_lock, flags); - vtimer->interval = ns_to_ktime(vblank->framedur_ns); - spin_unlock_irqrestore(&vtimer->interval_lock, flags); - - hrtimer_start(&vtimer->timer, vtimer->interval, HRTIMER_MODE_REL); + scoped_guard(spinlock_irqsave, &vtimer->interval_lock) { + vtimer->interval = ns_to_ktime(vblank->framedur_ns); + hrtimer_start(&vtimer->timer, vtimer->interval, HRTIMER_MODE_REL); + } return 0; } From e109454dce1db5a5659509407305c849bc959af5 Mon Sep 17 00:00:00 2001 From: Thomas Zimmermann Date: Tue, 10 Nov 2026 09:45:20 +0100 Subject: [PATCH 0747/2102] drm/vblank: Cancel vblank timer outside of critical section Cancel the vblank timer's hrtimer after disabling the vblank timer to avoid running timer function with outdated interval. Stopping and restarting the vblank timer with a different interval can leave behind an already-running timer function that uses the previous interval. This can result in a vblank event with inconsistent timing. At the same time, canceling the hrtimer in drm_crtc_vblank_cancel_timer() with hrtimer_cancel() is not possible due to a deadlock between vblank_time_lock and the hrtimer. Resolve this problem by calling hrtimer_cancel() outside of vblank_time_lock's critical section. Implement this with the new callback sync_vblank in struct drm_crtc_funcs. Invoke this callback after switching off the vblank. Some internal bookkeeping is necessary to ensure that the timer is really switched off. Implement sync_vblank for vblank timers with the new helper drm_crtc_vblank_helper_sync_vblank_timer(). From there, the vblank function drm_crtc_blank_stop_timer() stops the hrtimer unconditionally. Install drm_crtc_vblank_helper_sync_vblank_timer() in most drivers via DRM_CRTC_VBLANK_TIMER_FUNCS. Update vmwgfx, which does not use this macro. Implement the locking in drm_crtc_vblank_cancel_timer() with a guard. Also remove the call to hrtimer_try_to_cancel() from that function. It is no longer needed with sync_vblank invoking hrtimer_cancel(). v2: - handle uninitialized timer in drm_crtc_vblank_cancel_timer() Signed-off-by: Thomas Zimmermann Reviewed-by: Zack Rusin Link: https://patch.msgid.link/20261110084710.503870-3-tzimmermann@suse.de --- drivers/gpu/drm/drm_vblank.c | 56 +++++++++++++++++++++++----- drivers/gpu/drm/drm_vblank_helper.c | 16 ++++++++ drivers/gpu/drm/vmwgfx/vmwgfx_ldu.c | 3 +- drivers/gpu/drm/vmwgfx/vmwgfx_scrn.c | 2 + drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c | 2 + drivers/gpu/drm/vmwgfx/vmwgfx_vkms.c | 2 +- include/drm/drm_crtc.h | 9 +++++ include/drm/drm_vblank.h | 16 ++++++++ include/drm/drm_vblank_helper.h | 2 + 9 files changed, 96 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/drm_vblank.c b/drivers/gpu/drm/drm_vblank.c index 8cc8d018d353a7..c26464ca4a12ca 100644 --- a/drivers/gpu/drm/drm_vblank.c +++ b/drivers/gpu/drm/drm_vblank.c @@ -1403,6 +1403,9 @@ void drm_crtc_vblank_off(struct drm_crtc *crtc) spin_unlock_irq(&dev->event_lock); + if (crtc->funcs->sync_vblank) + crtc->funcs->sync_vblank(crtc); + /* Will be reset by the modeset helpers when re-enabling the crtc by * calling drm_calc_timestamping_constants(). */ vblank->hwmode.crtc_clock = 0; @@ -2246,28 +2249,61 @@ EXPORT_SYMBOL(drm_crtc_vblank_start_timer); * @crtc: the CRTC * * Drivers should call this function from their CRTC's disable_vblank - * function to stop a vblank timer. + * function to stop a vblank timer. Only signals the timer to stop at + * the next invocation. Non-blocking. To fully stop the vblank timer, + * drivers should invoke drm_crtc_vblank_stop_timer(). */ void drm_crtc_vblank_cancel_timer(struct drm_crtc *crtc) { struct drm_vblank_crtc *vblank = drm_crtc_vblank_crtc(crtc); struct drm_vblank_crtc_timer *vtimer = &vblank->vblank_timer; - unsigned long flags; + + if (!vtimer->crtc) + return; /* - * Calling hrtimer_cancel() can result in a deadlock with DRM's - * vblank_time_lime_lock and hrtimers' softirq_expiry_lock. So + * Calling hrtimer_cancel() here can result in a deadlock between + * DRM's vblank_time_lock and hrtimers' softirq_expiry_lock. So * clear interval and indicate cancellation. The timer function - * will cancel itself on the next invocation. + * will cancel itself on the next invocation. Otherwise cancel it + * in drm_crtc_vblank_stop_canceled_timer(). */ + scoped_guard(spinlock_irqsave, &vtimer->interval_lock) + vtimer->interval = 0; +} +EXPORT_SYMBOL(drm_crtc_vblank_cancel_timer); + +/** + * drm_crtc_vblank_stop_canceled_timer - Stops a CRTC's previously canceled vblank timer + * @crtc: the CRTC + * + * Drivers should call this function from their CRTC's sync_vblank + * function to fully stop a vblank timer. The timer must have been + * canceled before. Use drm_crtc_vblank_stop_timer() to stop a vblank + * timer unconditionally. + * + * The function blocks until a running timer function has returned. + */ +void drm_crtc_vblank_stop_canceled_timer(struct drm_crtc *crtc) +{ + struct drm_vblank_crtc *vblank = drm_crtc_vblank_crtc(crtc); + struct drm_vblank_crtc_timer *vtimer = &vblank->vblank_timer; + ktime_t interval; - spin_lock_irqsave(&vtimer->interval_lock, flags); - vtimer->interval = 0; - spin_unlock_irqrestore(&vtimer->interval_lock, flags); + if (!vtimer->crtc) + return; - hrtimer_try_to_cancel(&vtimer->timer); + /* + * The vblank timer is off if it has an interval of zero. Cancel + * it before drm_crtc_vblank_start_timer() reprograms it. + */ + scoped_guard(spinlock_irqsave, &vtimer->interval_lock) + interval = vtimer->interval; + + if (!interval) + hrtimer_cancel(&vtimer->timer); } -EXPORT_SYMBOL(drm_crtc_vblank_cancel_timer); +EXPORT_SYMBOL(drm_crtc_vblank_stop_canceled_timer); /** * drm_crtc_vblank_get_vblank_timeout - Returns the vblank timeout diff --git a/drivers/gpu/drm/drm_vblank_helper.c b/drivers/gpu/drm/drm_vblank_helper.c index d3f8147ecdc126..7465d74ce29e41 100644 --- a/drivers/gpu/drm/drm_vblank_helper.c +++ b/drivers/gpu/drm/drm_vblank_helper.c @@ -146,6 +146,22 @@ void drm_crtc_vblank_helper_disable_vblank_timer(struct drm_crtc *crtc) } EXPORT_SYMBOL(drm_crtc_vblank_helper_disable_vblank_timer); +/** + * drm_crtc_vblank_helper_sync_vblank_timer - Implements struct &drm_crtc_funcs.sync_vblank + * @crtc: The CRTC + * + * The helper drm_crtc_vblank_helper_sync_vblank_timer() implements + * sync_vblank of struct drm_crtc_funcs for CRTCs that require a + * VBLANK timer. + * + * See also struct &drm_crtc_funcs.sync_vblank. + */ +void drm_crtc_vblank_helper_sync_vblank_timer(struct drm_crtc *crtc) +{ + drm_crtc_vblank_stop_canceled_timer(crtc); +} +EXPORT_SYMBOL(drm_crtc_vblank_helper_sync_vblank_timer); + /** * drm_crtc_vblank_helper_get_vblank_timestamp_from_timer - * Implements struct &drm_crtc_funcs.get_vblank_timestamp diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_ldu.c b/drivers/gpu/drm/vmwgfx/vmwgfx_ldu.c index b147f5db9df549..a7828b8ed68ee0 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_ldu.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_ldu.c @@ -33,7 +33,7 @@ #include #include #include - +#include #define vmw_crtc_to_ldu(x) \ container_of(x, struct vmw_legacy_display_unit, base.crtc) @@ -256,6 +256,7 @@ static const struct drm_crtc_funcs vmw_legacy_crtc_funcs = { .page_flip = drm_atomic_helper_page_flip, .enable_vblank = vmw_vkms_enable_vblank, .disable_vblank = vmw_vkms_disable_vblank, + .sync_vblank = drm_crtc_vblank_helper_sync_vblank_timer, .get_vblank_timestamp = vmw_vkms_get_vblank_timestamp, }; diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_scrn.c b/drivers/gpu/drm/vmwgfx/vmwgfx_scrn.c index 89714d5c235b6d..bc6c200f51293a 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_scrn.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_scrn.c @@ -35,6 +35,7 @@ #include #include #include +#include #define vmw_crtc_to_sou(x) \ container_of(x, struct vmw_screen_object_unit, base.crtc) @@ -312,6 +313,7 @@ static const struct drm_crtc_funcs vmw_screen_object_crtc_funcs = { .page_flip = drm_atomic_helper_page_flip, .enable_vblank = vmw_vkms_enable_vblank, .disable_vblank = vmw_vkms_disable_vblank, + .sync_vblank = drm_crtc_vblank_helper_sync_vblank_timer, .get_vblank_timestamp = vmw_vkms_get_vblank_timestamp, }; diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c b/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c index 993c6b315db4c5..08b32babc1cda2 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c @@ -37,6 +37,7 @@ #include #include #include +#include #define vmw_crtc_to_stdu(x) \ container_of(x, struct vmw_screen_target_display_unit, base.crtc) @@ -794,6 +795,7 @@ static const struct drm_crtc_funcs vmw_stdu_crtc_funcs = { .page_flip = drm_atomic_helper_page_flip, .enable_vblank = vmw_vkms_enable_vblank, .disable_vblank = vmw_vkms_disable_vblank, + .sync_vblank = drm_crtc_vblank_helper_sync_vblank_timer, .get_vblank_timestamp = vmw_vkms_get_vblank_timestamp, .get_crc_sources = vmw_vkms_get_crc_sources, .set_crc_source = vmw_vkms_set_crc_source, diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_vkms.c b/drivers/gpu/drm/vmwgfx/vmwgfx_vkms.c index 3d0d5dfa869f9a..8ce10cf9c19eec 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_vkms.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_vkms.c @@ -299,7 +299,7 @@ vmw_vkms_crtc_cleanup(struct drm_crtc *crtc) struct vmw_display_unit *du = vmw_crtc_to_du(crtc); if (vmw->vkms_enabled) - drm_crtc_vblank_cancel_timer(crtc); + drm_crtc_vblank_stop_timer(crtc); if (du->vkms.surface) vmw_surface_unreference(&du->vkms.surface); diff --git a/include/drm/drm_crtc.h b/include/drm/drm_crtc.h index be5dca538d87ed..46546006f361c8 100644 --- a/include/drm/drm_crtc.h +++ b/include/drm/drm_crtc.h @@ -908,6 +908,15 @@ struct drm_crtc_funcs { */ void (*disable_vblank)(struct drm_crtc *crtc); + /** + * @sync_vblank: + * + * Synchronizes vblank hardware and software state after switching off + * vblanks for the given CRTC. Called without holding vblank locks. Allows + * the driver to clean up vblank state outside of critical sections. + */ + void (*sync_vblank)(struct drm_crtc *crtc); + /** * @get_vblank_timestamp: * diff --git a/include/drm/drm_vblank.h b/include/drm/drm_vblank.h index 2fcef9c0f5b1ba..257b83d145ce74 100644 --- a/include/drm/drm_vblank.h +++ b/include/drm/drm_vblank.h @@ -319,6 +319,22 @@ void drm_crtc_set_max_vblank_count(struct drm_crtc *crtc, int drm_crtc_vblank_start_timer(struct drm_crtc *crtc); void drm_crtc_vblank_cancel_timer(struct drm_crtc *crtc); +void drm_crtc_vblank_stop_canceled_timer(struct drm_crtc *crtc); + +/** + * drm_crtc_vblank_stop_timer - Stops a CRTC's vblank timer + * @crtc: the CRTC + * + * Drivers should call this function to fully stop a CRTC's vblank timer. + * + * The function blocks until a running timer function has returned. + */ +static inline void drm_crtc_vblank_stop_timer(struct drm_crtc *crtc) +{ + drm_crtc_vblank_cancel_timer(crtc); + drm_crtc_vblank_stop_canceled_timer(crtc); +} + void drm_crtc_vblank_get_vblank_timeout(struct drm_crtc *crtc, ktime_t *vblank_time); /* diff --git a/include/drm/drm_vblank_helper.h b/include/drm/drm_vblank_helper.h index 28051f08d0f422..dd0029e045be44 100644 --- a/include/drm/drm_vblank_helper.h +++ b/include/drm/drm_vblank_helper.h @@ -37,6 +37,7 @@ void drm_crtc_vblank_atomic_disable(struct drm_crtc *crtc, int drm_crtc_vblank_helper_enable_vblank_timer(struct drm_crtc *crtc); void drm_crtc_vblank_helper_disable_vblank_timer(struct drm_crtc *crtc); +void drm_crtc_vblank_helper_sync_vblank_timer(struct drm_crtc *crtc); bool drm_crtc_vblank_helper_get_vblank_timestamp_from_timer(struct drm_crtc *crtc, int *max_error, ktime_t *vblank_time, @@ -51,6 +52,7 @@ bool drm_crtc_vblank_helper_get_vblank_timestamp_from_timer(struct drm_crtc *crt #define DRM_CRTC_VBLANK_TIMER_FUNCS \ .enable_vblank = drm_crtc_vblank_helper_enable_vblank_timer, \ .disable_vblank = drm_crtc_vblank_helper_disable_vblank_timer, \ + .sync_vblank = drm_crtc_vblank_helper_sync_vblank_timer, \ .get_vblank_timestamp = drm_crtc_vblank_helper_get_vblank_timestamp_from_timer #endif From 81c8333141b9aa465d98bb4c035284556e699701 Mon Sep 17 00:00:00 2001 From: Jaeyeong Lee Date: Thu, 12 Nov 2026 04:32:17 +0000 Subject: [PATCH 0748/2102] net/tls: serialize context removal in tls_device_down() tls_device_down() moves each context to tls_device_down_list while holding tls_device_lock. It then drops its reference and removes the context after releasing the lock. tls_device_queue_ctx_destruction() removes contexts from the same list under tls_device_lock. If it removes an adjacent context while tls_device_down() is deleting its node, the two list updates can interleave. One update can then target a context freed by the other path, causing a use-after-free write. Drop the reference and remove the context in the existing tls_device_lock critical section. Keep tls_device_free_ctx() after releasing the lock. This issue was found with a static analysis tool. Fixes: f6336724a4d4 ("net/tls: Remove the context from the list in tls_device_down") Cc: stable@vger.kernel.org Signed-off-by: Jaeyeong Lee Link: https://patch.msgid.link/20261112043209.102404-1-lee@jaeyeong.cc Signed-off-by: Paolo Abeni --- net/tls/tls_device.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/net/tls/tls_device.c b/net/tls/tls_device.c index 4cdfbb57ecff0a..fa7170cd4fd10f 100644 --- a/net/tls/tls_device.c +++ b/net/tls/tls_device.c @@ -1350,6 +1350,8 @@ static int tls_device_down(struct net_device *netdev) spin_unlock_irqrestore(&tls_device_lock, flags); list_for_each_entry_safe(ctx, tmp, &list, list) { + bool free_ctx; + /* Stop offloaded TX and switch to the fallback. * tls_is_skb_tx_device_offloaded will return false. */ @@ -1387,17 +1389,19 @@ static int tls_device_down(struct net_device *netdev) */ spin_lock_irqsave(&tls_device_lock, flags); list_move_tail(&ctx->list, &tls_device_down_list); + /* Serialize the final removal with sk_destruct. */ + free_ctx = refcount_dec_and_test(&ctx->refcount); + if (free_ctx) + list_del(&ctx->list); spin_unlock_irqrestore(&tls_device_lock, flags); /* Device contexts for RX and TX will be freed in on sk_destruct * by tls_device_free_ctx. rx_conf and tx_conf stay in TLS_HW. - * Now release the ref taken above. */ - if (refcount_dec_and_test(&ctx->refcount)) { + if (free_ctx) { /* sk_destruct ran after tls_device_down took a ref, and * it returned early. Complete the destruction here. */ - list_del(&ctx->list); tls_device_free_ctx(ctx); } } From 29219e5254abb48aa98feb1b5d7e7002bc917cec Mon Sep 17 00:00:00 2001 From: Jernej Skrabec Date: Sun, 15 Nov 2026 16:07:58 +0100 Subject: [PATCH 0749/2102] regulator: axp20x: AXP313A: set ramp_delay The AXP313A DCDC outputs need time to reach a new voltage, but the driver reports no ramp delay. cpufreq thus raises the CPU clock before the higher voltage is reached, which causes oopses and hangs within minutes of DVFS activity on H616 boards like the Orange Pi Zero3. The datasheet doesn't specify the slew rate. The vendor device trees wait 25 us per 10 mV step, so set a ramp delay of 400 uV/us for all three DCDCs. Fixes: 60fd7eb89670 ("regulator: axp20x: Add support for AXP313a variant") Signed-off-by: Jernej Skrabec Acked-by: Chen-Yu Tsai Link: https://patch.msgid.link/20261115150758.16650-1-jernej.skrabec@gmail.com Signed-off-by: Mark Brown --- drivers/regulator/axp20x-regulator.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/drivers/regulator/axp20x-regulator.c b/drivers/regulator/axp20x-regulator.c index e88da44aa2a0d4..53b1e0499c00aa 100644 --- a/drivers/regulator/axp20x-regulator.c +++ b/drivers/regulator/axp20x-regulator.c @@ -744,18 +744,18 @@ static const struct linear_range axp313a_dcdc3_ranges[] = { }; static const struct regulator_desc axp313a_regulators[] = { - AXP_DESC_RANGES(AXP313A, DCDC1, "dcdc1", "vin1", + AXP_DESC_RANGES_DELAY(AXP313A, DCDC1, "dcdc1", "vin1", axp313a_dcdc1_ranges, AXP313A_DCDC1_NUM_VOLTAGES, AXP313A_DCDC1_CONTROL, AXP313A_DCDC_V_OUT_MASK, - AXP313A_OUTPUT_CONTROL, BIT(0)), - AXP_DESC_RANGES(AXP313A, DCDC2, "dcdc2", "vin2", + AXP313A_OUTPUT_CONTROL, BIT(0), 400), + AXP_DESC_RANGES_DELAY(AXP313A, DCDC2, "dcdc2", "vin2", axp313a_dcdc2_ranges, AXP313A_DCDC23_NUM_VOLTAGES, AXP313A_DCDC2_CONTROL, AXP313A_DCDC_V_OUT_MASK, - AXP313A_OUTPUT_CONTROL, BIT(1)), - AXP_DESC_RANGES(AXP313A, DCDC3, "dcdc3", "vin3", + AXP313A_OUTPUT_CONTROL, BIT(1), 400), + AXP_DESC_RANGES_DELAY(AXP313A, DCDC3, "dcdc3", "vin3", axp313a_dcdc3_ranges, AXP313A_DCDC23_NUM_VOLTAGES, AXP313A_DCDC3_CONTROL, AXP313A_DCDC_V_OUT_MASK, - AXP313A_OUTPUT_CONTROL, BIT(2)), + AXP313A_OUTPUT_CONTROL, BIT(2), 400), AXP_DESC(AXP313A, ALDO1, "aldo1", "vin1", 500, 3500, 100, AXP313A_ALDO1_CONTROL, AXP313A_LDO_V_OUT_MASK, AXP313A_OUTPUT_CONTROL, BIT(3)), From bb5caf7a2e0b2dae8e8905d32fc376703eabcfc4 Mon Sep 17 00:00:00 2001 From: Sebastian Reichel Date: Tue, 10 Nov 2026 01:41:58 +0100 Subject: [PATCH 0750/2102] spi: Fix runtime PM imbalance on pump transfer message error The current SPI message pumping code may drop the runtime PM twice when an SPI message cannot be sent: spi_master spi2: noqueue transfer failed rockchip-spi feb20000.spi: Runtime PM usage count underflow! Fix the problem by always keeping the runtime PM count increased when exiting __spi_pump_transfer_message(), as the caller handles decreasing it. Note, that the function already keeps the RPM usage counter increased for the error paths following after the prepare_transfer_hardware step. Cc: stable@vger.kernel.org Fixes: bef4a48f4ef7 ("spi: Fix null dereference on suspend") Signed-off-by: Sebastian Reichel Tested-by: Alexander Shiyan Link: https://patch.msgid.link/20261110-spi-runtime-pm-fix-v1-1-8601ebb2f6a8@collabora.com Signed-off-by: Mark Brown --- drivers/spi/spi.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/drivers/spi/spi.c b/drivers/spi/spi.c index 8a06fb4e309a96..f57f8d5c04345c 100644 --- a/drivers/spi/spi.c +++ b/drivers/spi/spi.c @@ -1967,7 +1967,6 @@ static int __spi_pump_transfer_message(struct spi_controller *ctlr, if (!was_busy && ctlr->auto_runtime_pm) { ret = pm_runtime_get_sync(ctlr->dev.parent); if (ret < 0) { - pm_runtime_put_noidle(ctlr->dev.parent); dev_err(&ctlr->dev, "Failed to power device: %d\n", ret); @@ -1988,9 +1987,6 @@ static int __spi_pump_transfer_message(struct spi_controller *ctlr, "failed to prepare transfer hardware: %d\n", ret); - if (ctlr->auto_runtime_pm) - pm_runtime_put(ctlr->dev.parent); - msg->status = ret; spi_finalize_current_message(ctlr); From 3a191eec3627acd558640cf4092e9e337aa15291 Mon Sep 17 00:00:00 2001 From: Fredric Cover Date: Thu, 12 Nov 2026 04:21:36 +0000 Subject: [PATCH 0751/2102] smb: client: convert path_consumed to mount charset units MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit path_consumed in a DFS referral counts bytes of the canonical path, which is in the DFS cache charset (utf8). dfs_parse_target_referral() applies it as an offset into full_path, which is in the mount charset. When the mount charset is not utf8, each non-ASCII character in the consumed part that encodes longer in utf8 than in the mount charset makes the offset too large, so leading characters of the prefix path are dropped. For example, with iocharset=iso8859-1, mounting //srv/dfs/café é/sub yields the prefix "ub" instead of "sub" and the mount fails with -ENOENT. (A single accented character only worked because the offset happened to land after the delimiter.) Translate the count in parse_dfs_target(), where both strings are available, by matching path components: count the delimiters in the consumed part of the canonical path and find the same position in the mount charset path. Delimiters are ASCII in both and are not affected by remapping. If the consumed bytes are identical in both strings, which is the case for utf8 mounts and ASCII-only prefixes using the default backslash delimiter, the value is used unchanged. This assumes the server reports PathConsumed on a component boundary; a translated value that ends mid-component is rounded up to the next boundary. Tested against Samba on a KASAN kernel: with iocharset=iso8859-1, links with 0 to 3 accented characters followed by a tail, a two-level tail, an accented tail, a link in a subdirectory, and mapposix with an accented name; iso8859-15 and cp932 mounts; and iocharset=utf8 controls. Not tested against Windows servers, with posixpaths, or with reserved characters under mapchars/mapposix. Signed-off-by: Fredric Cover Cc: stable@vger.kernel.org Signed-off-by: Paulo Alcantara --- fs/smb/client/dfs.c | 77 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 3 deletions(-) diff --git a/fs/smb/client/dfs.c b/fs/smb/client/dfs.c index 57c90a2512a3cb..788cdda9a573ee 100644 --- a/fs/smb/client/dfs.c +++ b/fs/smb/client/dfs.c @@ -85,16 +85,87 @@ static void set_root_smb_session(struct cifs_mount_ctx *mnt_ctx) ctx->dfs_root_ses = ses; } +static bool dfs_is_delim(wchar_t c) +{ + return c == '/' || c == '\\'; +} + +/* + * @consumed counts bytes of the canonical (cache charset) path @cpath. + * Return the matching byte offset in @fpath, which holds the same path in + * the mount charset. Offsets are matched by path component, since the + * delimiters are ASCII in every charset and survive remapping. + */ +static int dfs_consumed_to_local(const struct nls_table *nls, + const char *cpath, const char *fpath, + int consumed) +{ + size_t clen = strlen(cpath), flen = strlen(fpath), off = 0; + int ndelims = 0, seen = 0, i; + bool ends_on_delim; + + if (consumed < 0) + return -EINVAL; + + /* Identical bytes in both strings: units already agree */ + if ((size_t)consumed <= min(clen, flen) && + !memcmp(cpath, fpath, consumed)) + return consumed; + + if ((size_t)consumed > clen) + consumed = clen; + + for (i = 0; i < consumed; i++) + if (dfs_is_delim(cpath[i])) + ndelims++; + ends_on_delim = consumed && dfs_is_delim(cpath[consumed - 1]); + + while (off < flen) { + wchar_t uni; + int len; + + len = nls->char2uni((const unsigned char *)fpath + off, + flen - off, &uni); + if (len <= 0) { + uni = (unsigned char)fpath[off]; + len = 1; + } + if (dfs_is_delim(uni)) { + /* check if start of next component */ + if (!ends_on_delim && seen == ndelims) + break; + seen++; + if (ends_on_delim && seen == ndelims) { + /* just past the last consumed delimiter */ + off += len; + break; + } + } + off += len; + } + return off; +} + static inline int parse_dfs_target(struct smb3_fs_context *ctx, struct dfs_ref_walk *rw, struct dfs_info3_param *tgt) { - int rc; const char *fpath = ref_walk_fpath(rw) + 1; + const char *cpath = ref_walk_path(rw) + 1; + int rc; rc = ref_walk_get_tgt(rw, tgt); - if (!rc) - rc = dfs_parse_target_referral(fpath, tgt, ctx); + if (!rc) { + struct dfs_info3_param local = *tgt; + int off; + + off = dfs_consumed_to_local(rw->mnt_ctx->cifs_sb->local_nls, + cpath, fpath, tgt->path_consumed); + if (off < 0) + return off; + local.path_consumed = off; + rc = dfs_parse_target_referral(fpath, &local, ctx); + } return rc; } From 09599d876dd1c4ee6641aac7b467208b9a210158 Mon Sep 17 00:00:00 2001 From: Suraj Gupta Date: Thu, 12 Nov 2026 23:19:26 +0530 Subject: [PATCH 0752/2102] MAINTAINERS: Add Suraj Gupta as AXI Ethernet co-maintainer Add myself as co-maintainer of the Xilinx AXI Ethernet driver. I have been contributing patches to and reviewing patches for this driver, and will continue to help with review and maintenance. Signed-off-by: Suraj Gupta Acked-by: Radhey Shyam Pandey Link: https://patch.msgid.link/20261112174926.2102832-1-suraj.gupta2@amd.com Signed-off-by: Paolo Abeni --- MAINTAINERS | 1 + 1 file changed, 1 insertion(+) diff --git a/MAINTAINERS b/MAINTAINERS index a809df29a6c5c2..66e609de66faab 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -30686,6 +30686,7 @@ F: drivers/iio/adc/xilinx-ams.c XILINX AXI ETHERNET DRIVER M: Radhey Shyam Pandey +M: Suraj Gupta S: Maintained F: Documentation/devicetree/bindings/net/xlnx,axi-ethernet.yaml F: drivers/net/ethernet/xilinx/xilinx_axienet* From 5e9b2ad9b8384cd3c417cd5e2c3bc7eee4a72791 Mon Sep 17 00:00:00 2001 From: Shay Drory Date: Thu, 12 Nov 2026 20:24:03 +0200 Subject: [PATCH 0753/2102] net/mlx5e: rep, Fix races between devcom PAIR event and uplink close mlx5e_sqs2vport_stop() frees each rep_sq and its per-peer send-to-vport rules (rep_sq->sq_peer) while holding only the uplink's priv->state_lock (it runs from the ndo_stop -> mlx5e_deactivate_priv_channels -> mlx5e_rep_deactivate_channels path). The same rep_sq->sq_peer entries are inserted and erased by the devcom ESW_OFFLOADS PAIR/UNPAIR handler (mlx5e_vport_rep_event_pair/unpair), which runs under the devcom component write semaphore and takes no state_lock. The two lock sets are disjoint, so closing the uplink of one eswitch can run concurrently with a pairing/unpairing event driven by the peer eswitch, both mutating the same rep's vport_sqs_list / sq_peer. This is a use-after-free: one side frees rep_sq / sq_peer while the other walks the list or inserts/erases the xarray. The add side (mlx5e_sqs2vport_start) is not safe either. It takes the devcom read semaphore only via mlx5_devcom_for_each_peer_begin(), which is gated on comp->ready. The PAIR handler does all of its rep work before setting ready, so a first-time PAIR runs with ready == false and start can list_add() into vport_sqs_list while the handler walks it. Add mlx5_devcom_comp_read_lock/unlock(), which take the component semaphore for read regardless of ready, and hold it across both mlx5e_sqs2vport_start() and mlx5e_sqs2vport_stop(). Start still adds peer rules only when the component is ready, now checked under the lock. Lock ordering is preserved: start already took state_lock -> comp->sem (read); stop now does the same. The event handler takes comp->sem and never state_lock, so there is no inversion. Fixes: 898b07861565 ("net/mlx5: Add send to vport rules on paired device") Signed-off-by: Shay Drory Reviewed-by: Moshe Shemesh Signed-off-by: Tariq Toukan Link: https://patch.msgid.link/20261112182403.3646298-1-tariqt@nvidia.com Signed-off-by: Paolo Abeni --- .../net/ethernet/mellanox/mlx5/core/en_rep.c | 21 ++++++++++--------- .../ethernet/mellanox/mlx5/core/lib/devcom.c | 14 +++++++++++++ .../ethernet/mellanox/mlx5/core/lib/devcom.h | 2 ++ 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c b/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c index c7b4a8a827738b..ca5da48626f64d 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c @@ -506,10 +506,11 @@ static int mlx5e_sqs2vport_start(struct mlx5_eswitch *esw, struct mlx5_eswitch_rep *rep, u32 *sqns_array, int sqns_num) { + struct mlx5_devcom_comp_dev *devcom = esw->devcom; struct mlx5_flow_handle *flow_rule; struct mlx5e_rep_priv *rpriv; struct mlx5e_rep_sq *rep_sq; - bool devcom_locked = false; + bool peers_ready; int err; int i; @@ -518,9 +519,8 @@ static int mlx5e_sqs2vport_start(struct mlx5_eswitch *esw, rpriv = mlx5e_rep_to_rep_priv(rep); - if (mlx5_devcom_comp_is_ready(esw->devcom) && - mlx5_devcom_for_each_peer_begin(esw->devcom)) - devcom_locked = true; + mlx5_devcom_comp_read_lock(devcom); + peers_ready = mlx5_devcom_comp_is_ready(devcom); for (i = 0; i < sqns_num; i++) { rep_sq = kzalloc_obj(*rep_sq); @@ -541,7 +541,7 @@ static int mlx5e_sqs2vport_start(struct mlx5_eswitch *esw, rep_sq->sqn = sqns_array[i]; xa_init(&rep_sq->sq_peer); - if (devcom_locked) { + if (peers_ready) { err = mlx5e_sqs2vport_add_peers_rules(esw, rep, rep_sq, i); if (err) { mlx5_eswitch_del_send_to_vport_rule(rep_sq->send_to_vport_rule); @@ -554,16 +554,13 @@ static int mlx5e_sqs2vport_start(struct mlx5_eswitch *esw, list_add(&rep_sq->list, &rpriv->vport_sqs_list); } - if (devcom_locked) - mlx5_devcom_for_each_peer_end(esw->devcom); + mlx5_devcom_comp_read_unlock(devcom); return 0; out_err: mlx5e_sqs2vport_stop(esw, rep); - - if (devcom_locked) - mlx5_devcom_for_each_peer_end(esw->devcom); + mlx5_devcom_comp_read_unlock(devcom); return err; } @@ -630,8 +627,12 @@ mlx5e_remove_sqs_fwd_rules(struct mlx5e_priv *priv) struct mlx5_eswitch *esw = priv->mdev->priv.eswitch; struct mlx5e_rep_priv *rpriv = priv->ppriv; struct mlx5_eswitch_rep *rep = rpriv->rep; + struct mlx5_devcom_comp_dev *devcom; + devcom = esw->devcom; + mlx5_devcom_comp_read_lock(devcom); mlx5e_sqs2vport_stop(esw, rep); + mlx5_devcom_comp_read_unlock(devcom); } static int diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.c b/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.c index 75855481522b11..aed9e2a74162fa 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.c @@ -456,6 +456,20 @@ void mlx5_devcom_comp_unlock(struct mlx5_devcom_comp_dev *devcom) up_write(&devcom->comp->sem); } +void mlx5_devcom_comp_read_lock(struct mlx5_devcom_comp_dev *devcom) +{ + if (!devcom) + return; + down_read(&devcom->comp->sem); +} + +void mlx5_devcom_comp_read_unlock(struct mlx5_devcom_comp_dev *devcom) +{ + if (!devcom) + return; + up_read(&devcom->comp->sem); +} + int mlx5_devcom_comp_trylock(struct mlx5_devcom_comp_dev *devcom) { if (!devcom) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.h b/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.h index 7a704fafdbd3a8..94b0fe20cc265f 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.h @@ -79,6 +79,8 @@ void *mlx5_devcom_get_next_peer_data_rcu(struct mlx5_devcom_comp_dev *devcom, void mlx5_devcom_comp_lock(struct mlx5_devcom_comp_dev *devcom); void mlx5_devcom_comp_unlock(struct mlx5_devcom_comp_dev *devcom); +void mlx5_devcom_comp_read_lock(struct mlx5_devcom_comp_dev *devcom); +void mlx5_devcom_comp_read_unlock(struct mlx5_devcom_comp_dev *devcom); int mlx5_devcom_comp_trylock(struct mlx5_devcom_comp_dev *devcom); void mlx5_devcom_comp_assert_locked(struct mlx5_devcom_comp_dev *devcom); From 6a75ce0866bb1efe67947fc5536a476381d7a9d9 Mon Sep 17 00:00:00 2001 From: koraynilay Date: Thu, 12 Nov 2026 12:16:37 +0100 Subject: [PATCH 0754/2102] smb: client: fix negative timestamps being read from smb When reading a timestamp before epoch 0, cifs converts it from NT format to Unix format without normalizing it, leading to the nanoseconds field to be used as a negative number, which leads to a garbled stat command output. This bug also violates a struct timespec64 invariant, as documented in the set_normalized_timespec64() kernel-doc: [...] * Note: The tv_nsec part is always in the range of 0 <= tv_nsec < * NSEC_PER_SEC. * For negative values only the tv_sec field is negative ! */ Reproducer, with /tmp as the local filesystem folder exported as [test] in ksmbd.conf and /mnt as the smb folder mounted with mount -t cifs: mount -t cifs //127.0.0.1/test /mnt -o username=user,password=pass touch -d "1969-07-20 20:17:40.123456789" /tmp/test.txt stat -c "Server local (/tmp): %y" /tmp/test.txt stat -c "CIFS client (/mnt): %y" /mnt/test.txt --cached=never smbclient //127.0.0.1/test -U user%pass -c "allinfo test.txt" which prints (stat output is garbled because of negative value): Server local (/tmp): 1969-07-20 20:17:40.123456789 +0000 CIFS client (/mnt): 1969-07-20 20:17:41.()*+,--00 +0000 altname: TESTT~K6.TXT [...] access_time: Sun Jul 20 20:17:40 1969 UTC write_time: Sun Jul 20 20:17:40 1969 UTC [...] Fix this by using set_normalized_timespec64() in cifs_NTtimeToUnix(). Fixes: 2ae83bf93882 ("[CIFS] Fix setting time before epoch (negative time values)") Cc: stable@vger.kernel.org Assisted-by: Gemini:3.8-flash-high antigravity-cli-1.5.3 Signed-off-by: koraynilay Reviewed-by: Namjae Jeon Signed-off-by: Paulo Alcantara --- fs/smb/client/netmisc.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/fs/smb/client/netmisc.c b/fs/smb/client/netmisc.c index cf737ede1ab33a..033ca8f7e15195 100644 --- a/fs/smb/client/netmisc.c +++ b/fs/smb/client/netmisc.c @@ -133,8 +133,7 @@ cifs_NTtimeToUnix(__le64 ntutc) if (t < 0) { abs_t = -t; ts.tv_nsec = (time64_t)(do_div(abs_t, 10000000) * 100); - ts.tv_nsec = -ts.tv_nsec; - ts.tv_sec = -abs_t; + set_normalized_timespec64(&ts, -abs_t, -ts.tv_nsec); } else { abs_t = t; ts.tv_nsec = (time64_t)do_div(abs_t, 10000000) * 100; From b05fb50e255a3214683ee3f6a9433ea442c0ce04 Mon Sep 17 00:00:00 2001 From: Hex Lindqvist Date: Fri, 13 Nov 2026 14:20:24 -0800 Subject: [PATCH 0755/2102] Bluetooth: btintel: Don't log unsupported debug features as an error Since commit af395330abed ("Bluetooth: btintel: Add Intel devcoredump support"), setup sends Read Supported Features (0xfca6) to decide whether to register devcoredump. Older controllers such as the 8260 and 8265 reject it with Command Disallowed, so every probe logs: Bluetooth: hci0: Reading supported features failed (-16) Bluetooth: hci0: Error reading debug features This is harmless: it happens after the firmware is loaded and only means devcoredump is not registered. Log the failure at debug level there, and keep the error in btintel_set_quality_report(), where the user asked for the feature. Tested on an 8265 (8087:0a2b): the messages are gone and Bluetooth works as before. AI was used to help write and test this patch. Fixes: af395330abed ("Bluetooth: btintel: Add Intel devcoredump support") Closes: https://bugzilla.kernel.org/show_bug.cgi?id=219387 Signed-off-by: Hex Lindqvist Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/btintel.c | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/drivers/bluetooth/btintel.c b/drivers/bluetooth/btintel.c index 929018428c1924..4cc5273fb17540 100644 --- a/drivers/bluetooth/btintel.c +++ b/drivers/bluetooth/btintel.c @@ -1511,11 +1511,8 @@ static int btintel_read_debug_features(struct hci_dev *hdev, */ skb = __hci_cmd_sync(hdev, 0xfca6, sizeof(page_no), &page_no, HCI_INIT_TIMEOUT); - if (IS_ERR(skb)) { - bt_dev_err(hdev, "Reading supported features failed (%ld)", - PTR_ERR(skb)); + if (IS_ERR(skb)) return PTR_ERR(skb); - } if (skb->len != (sizeof(features->page1) + 3)) { bt_dev_err(hdev, "Supported features event size mismatch"); @@ -1632,8 +1629,10 @@ int btintel_set_quality_report(struct hci_dev *hdev, bool enable) * supported, need to load the additional DDC config to enable. */ err = btintel_read_debug_features(hdev, &features); - if (err) + if (err) { + bt_dev_err(hdev, "Reading supported features failed (%d)", err); return err; + } /* Set or reset the debug features. */ if (enable) @@ -1684,7 +1683,7 @@ static int btintel_register_devcoredump_support(struct hci_dev *hdev) err = btintel_read_debug_features(hdev, &features); if (err) { - bt_dev_info(hdev, "Error reading debug features"); + bt_dev_dbg(hdev, "Reading supported features failed (%d)", err); return err; } From 1f150a0bb8a1a2302f6895ac410f0aaaaa63b756 Mon Sep 17 00:00:00 2001 From: Jeremy Dean Clifton Date: Tue, 17 Nov 2026 02:33:42 +0000 Subject: [PATCH 0756/2102] Bluetooth: hci_conn: Free the unset handle when adding a connection fails hci_conn_add_unset() reserves a handle from hdev->unset_handle_ida and passes it to __hci_conn_add(). When __hci_conn_add() returns an error, no hci_conn exists, so hci_conn_cleanup() never runs and the handle is never returned to the IDA. It stays reserved until the device is released. The Sashiko AI reviewer found this while reviewing a change that adds another error return to __hci_conn_add(). Free the handle in hci_conn_add_unset() when __hci_conn_add() fails. Fixes: 181a42edddf5 ("Bluetooth: Make handle of hci_conn be unique") Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Jeremy Dean Clifton Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_conn.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/net/bluetooth/hci_conn.c b/net/bluetooth/hci_conn.c index c468a9332e0589..e44d9b29ab78f9 100644 --- a/net/bluetooth/hci_conn.c +++ b/net/bluetooth/hci_conn.c @@ -1186,6 +1186,7 @@ static struct hci_conn *__hci_conn_add(struct hci_dev *hdev, int type, struct hci_conn *hci_conn_add_unset(struct hci_dev *hdev, int type, bdaddr_t *dst, u8 dst_type, u8 role) { + struct hci_conn *conn; int handle; bt_dev_dbg(hdev, "dst %pMR", dst); @@ -1194,7 +1195,11 @@ struct hci_conn *hci_conn_add_unset(struct hci_dev *hdev, int type, if (unlikely(handle < 0)) return ERR_PTR(-ECONNREFUSED); - return __hci_conn_add(hdev, type, dst, dst_type, role, handle); + conn = __hci_conn_add(hdev, type, dst, dst_type, role, handle); + if (IS_ERR(conn)) + ida_free(&hdev->unset_handle_ida, handle); + + return conn; } struct hci_conn *hci_conn_add(struct hci_dev *hdev, int type, bdaddr_t *dst, From 56abe5c17b4d7e3bdc83b9671549f407a7113ceb Mon Sep 17 00:00:00 2001 From: Jeremy Dean Clifton Date: Tue, 17 Nov 2026 02:33:43 +0000 Subject: [PATCH 0757/2102] Bluetooth: hci_conn: Refuse new connections once HCI_UP is cleared hci_dev_close_sync() clears HCI_UP and later calls hci_conn_hash_flush() to delete every connection. A connection created by __hci_conn_add() after the flush has run is never deleted. It keeps the hci_dev_hold() reference and the sysfs device taken in __hci_conn_add(), so the hci_dev is never freed, and its works can still be queued after the workqueue is drained. Check HCI_UP in __hci_conn_add(), which serves both hci_conn_add() and hci_conn_add_unset(). All callers hold hdev->lock: the HCI event handlers, create_pa_complete() in hci_sync.c, and the l2cap, sco, iso and mgmt paths that reach the hci_connect_*() and hci_bind_*() helpers. hci_conn_hash_flush() runs under hdev->lock too, so a connection is either added before the flush and deleted by it, or refused. Also include lockdep_assert_held() so the locking rule is checked. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Jeremy Dean Clifton Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_conn.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/net/bluetooth/hci_conn.c b/net/bluetooth/hci_conn.c index e44d9b29ab78f9..2fb37e078d731b 100644 --- a/net/bluetooth/hci_conn.c +++ b/net/bluetooth/hci_conn.c @@ -1019,6 +1019,15 @@ static struct hci_conn *__hci_conn_add(struct hci_dev *hdev, int type, struct hci_conn *conn; struct smp_irk *irk = NULL; + lockdep_assert_held(&hdev->lock); + + /* hci_dev_close_sync() clears HCI_UP before hci_conn_hash_flush(). + * A connection added after that would never be flushed, so refuse + * it. The caller holds hdev->lock, which the flush also takes. + */ + if (!test_bit(HCI_UP, &hdev->flags)) + return ERR_PTR(-ENETDOWN); + switch (type) { case ACL_LINK: if (!hdev->acl_mtu) From 1ea7a0946b9ea0a962640fc314bdef268e7c2791 Mon Sep 17 00:00:00 2001 From: Jeremy Dean Clifton Date: Tue, 17 Nov 2026 02:33:44 +0000 Subject: [PATCH 0758/2102] Bluetooth: hci_sync: Disable connection works before draining A connection delayed work whose timer was armed before hci_dev_close_sync() can expire while drain_workqueue() runs. delayed_work_timer_fn() then queues it on the draining workqueue and triggers the "cannot queue ... on wq" warning. hci_conn_drop() can also queue disc_work from another context during the drain. Disable the per-connection delayed works under hdev->lock before draining. A disabled work is cancelled and any later attempt to queue it fails, so neither the timers nor hci_conn_drop() can queue it. The connections are deleted by hci_conn_hash_flush() below, so nothing needs to re-enable the works. Fixes: 76727c02c1e1 ("Bluetooth: Call drain_workqueue() before resetting state") Reported-by: syzbot+5897b3c764f5989ea942@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=5897b3c764f5989ea942 Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Jeremy Dean Clifton Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_sync.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index e771f0f2f30863..44ce776890d162 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -5772,6 +5772,7 @@ static int hci_dev_shutdown(struct hci_dev *hdev) int hci_dev_close_sync(struct hci_dev *hdev) { + struct hci_conn *conn; bool auto_off; int err = 0; @@ -5839,6 +5840,22 @@ int hci_dev_close_sync(struct hci_dev *hdev) cancel_delayed_work_sync(&adv_instance->rpa_expired_cb); } + /* A delayed work whose timer was armed before close would queue + * itself while the workqueue is draining. Disable the connection + * works so that hci_conn_drop() and the timers can no longer queue + * them. The connections are deleted below, so nothing re-enables + * them. HCI_UP is clear, so no new connection can be added after + * this walk. + */ + hci_dev_lock(hdev); + list_for_each_entry(conn, &hdev->conn_hash.list, list) { + disable_delayed_work(&conn->disc_work); + disable_delayed_work(&conn->auto_accept_work); + disable_delayed_work(&conn->idle_work); + disable_delayed_work(&conn->le_conn_timeout); + } + hci_dev_unlock(hdev); + /* Avoid potential lockdep warnings from the *_flush() calls by * ensuring the workqueue is empty up front. */ From ee43bade37c4578b52a76cf0cdb199d3c0019506 Mon Sep 17 00:00:00 2001 From: Zhao Li Date: Mon, 16 Nov 2026 16:05:38 +0800 Subject: [PATCH 0759/2102] Bluetooth: hci_serdev: serialize flush with transmit work hci_uart_flush() runs on HCI close and reset and frees hu->tx_skb while write_work may still be sending the same partial frame. The worker can then resume with a freed skb, or both paths can free the frame. The tty flush has stopped write_work before freeing the partial frame since commit 1b0d946d6f08 ("Bluetooth: hci_uart: clear HCI_UART_SENDING when write_work is canceled"). Do the same in the serdev flush: disable and drain write_work before releasing the frame, and hold HCI_UART_SENDING meanwhile so that hci_uart_tx_wakeup() only records HCI_UART_TX_WAKEUP. Then re-enable the work, release SENDING and replay a wakeup that arrived in between. AI assistance was used. Fixes: 82f5169bf3d3 ("Bluetooth: hci_uart: add serdev driver support library") Cc: stable@vger.kernel.org # needs adjustments for <= 7.4 Signed-off-by: Zhao Li Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/hci_serdev.c | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/drivers/bluetooth/hci_serdev.c b/drivers/bluetooth/hci_serdev.c index d2c48df3419966..194f11251cc5e5 100644 --- a/drivers/bluetooth/hci_serdev.c +++ b/drivers/bluetooth/hci_serdev.c @@ -97,17 +97,26 @@ static int hci_uart_flush(struct hci_dev *hdev) BT_DBG("hdev %p serdev %p", hdev, hu->serdev); + /* Stop write_work and hold SENDING so wakeups only set TX_WAKEUP. */ + disable_work_sync(&hu->write_work); + set_bit(HCI_UART_SENDING, &hu->tx_state); + if (hu->tx_skb) { kfree_skb(hu->tx_skb); hu->tx_skb = NULL; } - if (!test_bit(HCI_UART_PROTO_READY, &hu->flags)) - return 0; + if (test_bit(HCI_UART_PROTO_READY, &hu->flags)) { + /* Flush any pending characters in the driver and discipline. */ + serdev_device_write_flush(hu->serdev); - /* Flush any pending characters in the driver and discipline. */ - serdev_device_write_flush(hu->serdev); + hu->proto->flush(hu); + } - hu->proto->flush(hu); + /* Resume TX and replay a wakeup recorded while it was stopped. */ + enable_work(&hu->write_work); + clear_bit(HCI_UART_SENDING, &hu->tx_state); + if (test_bit(HCI_UART_TX_WAKEUP, &hu->tx_state)) + hci_uart_tx_wakeup(hu); return 0; } From c9eb955c4fe2c2611a57625767c4cc57ab8c7558 Mon Sep 17 00:00:00 2001 From: Michael McAllister Date: Mon, 16 Nov 2026 16:35:14 +0000 Subject: [PATCH 0760/2102] Bluetooth: hci_mrvl: Leave the serdev port lifetime to hci_serdev hci_uart_register_device_priv() opens the port before calling mrvl_open(), so Marvell opens it twice. Likewise, mrvl_close() closes it before the transport closes it again during unregister or registration error cleanup. Remove the extra calls and let hci_serdev own the port lifetime. This also avoids failing probe when serdev rejects a second open with -EALREADY. Fixes: be70e5e774a6 ("Bluetooth: hci_mrvl: Add serdev support") Reported-by: Markus Probst Closes: https://lore.kernel.org/341e56b1ff7d8a5b109e26e30dfed61faa54d603.camel@posteo.de/ Signed-off-by: Michael McAllister Reviewed-by: Loic Poulain Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/hci_mrvl.c | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/drivers/bluetooth/hci_mrvl.c b/drivers/bluetooth/hci_mrvl.c index 5798a8db016ee0..def19907c172e9 100644 --- a/drivers/bluetooth/hci_mrvl.c +++ b/drivers/bluetooth/hci_mrvl.c @@ -57,7 +57,6 @@ struct hci_mrvl_pkt { static int mrvl_open(struct hci_uart *hu) { struct mrvl_data *mrvl; - int ret; BT_DBG("hu %p", hu); @@ -75,17 +74,7 @@ static int mrvl_open(struct hci_uart *hu) hu->priv = mrvl; - if (hu->serdev) { - ret = serdev_device_open(hu->serdev); - if (ret) - goto err; - } - return 0; -err: - kfree(mrvl); - - return ret; } static int mrvl_close(struct hci_uart *hu) @@ -94,9 +83,6 @@ static int mrvl_close(struct hci_uart *hu) BT_DBG("hu %p", hu); - if (hu->serdev) - serdev_device_close(hu->serdev); - skb_queue_purge(&mrvl->txq); skb_queue_purge(&mrvl->rawq); kfree_skb(mrvl->rx_skb); From 5beb86f98c3d45f6d64be5b6d6c77480487b41b4 Mon Sep 17 00:00:00 2001 From: Nguyen Ngoc Thang Date: Tue, 17 Nov 2026 21:49:37 +0700 Subject: [PATCH 0761/2102] Bluetooth: L2CAP: return LE credits from recvmsg under the conn lock l2cap_chan_le_send_credits() allocates an ident from conn->tx_ida, sends L2CAP_LE_CREDITS and frees the ident right away, since the command has no response. The RX path frees idents in l2cap_put_ident() under conn->lock. That only works if the credits path holds conn->lock too, so that no response can be processed between the allocation and the free. The RX path does, but l2cap_sock_recvmsg() calls l2cap_publish_rx_avail() -> l2cap_chan_rx_avail() -> l2cap_chan_le_send_credits() with only the socket lock held. If the remote answers the credits packet with L2CAP_COMMAND_REJ, l2cap_put_ident() can free the ident first, and the credits path then frees it again: ida_free called for id=3 which is not allocated. WARNING: lib/idr.c:594 at ida_free+0x24c/0x2d4 lib/idr.c:594 Call trace: ida_free+0x24c/0x2d4 lib/idr.c:594 l2cap_chan_le_send_credits+0x17c/0x29c net/bluetooth/l2cap_core.c:7113 l2cap_chan_rx_avail+0xb4/0x134 net/bluetooth/l2cap_core.c:7126 l2cap_publish_rx_avail+0x110/0x168 net/bluetooth/l2cap_sock.c l2cap_sock_recvmsg+0x280/0x7b8 net/bluetooth/l2cap_sock.c:1317 The same unlocked call also updates chan->rx_credits and reads chan->sdu concurrently with the RX path. Publish rx_avail from recvmsg under conn->lock and chan->lock, taken with l2cap_chan_lock_conn() as l2cap_sock_defer() already does, before taking the socket lock to keep the conn->lock -> chan->lock -> sk_lock order. Assert conn->lock in l2cap_chan_le_send_credits() so that an unlocked caller is caught by lockdep. Fixes: 6e1930ece855 ("Bluetooth: L2CAP: fix tx ident leak for commands without a response") Reported-by: syzbot+9dc8780713b11155dd74@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=9dc8780713b11155dd74 Signed-off-by: Nguyen Ngoc Thang Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/l2cap_core.c | 3 +++ net/bluetooth/l2cap_sock.c | 8 ++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/net/bluetooth/l2cap_core.c b/net/bluetooth/l2cap_core.c index 4ee1e62ded7ed8..686e86c04d7ea1 100644 --- a/net/bluetooth/l2cap_core.c +++ b/net/bluetooth/l2cap_core.c @@ -7150,6 +7150,9 @@ static void l2cap_chan_le_send_credits(struct l2cap_chan *chan) pkt.cid = cpu_to_le16(chan->scid); pkt.credits = cpu_to_le16(return_credits); + /* Keeps l2cap_put_ident() from releasing ident before we do */ + lockdep_assert_held(&conn->lock); + ident = l2cap_get_ident(conn); l2cap_send_cmd(conn, ident, L2CAP_LE_CREDITS, sizeof(pkt), &pkt); diff --git a/net/bluetooth/l2cap_sock.c b/net/bluetooth/l2cap_sock.c index 304ebafdfeaa01..6b65710845dcb4 100644 --- a/net/bluetooth/l2cap_sock.c +++ b/net/bluetooth/l2cap_sock.c @@ -1292,6 +1292,7 @@ static int l2cap_sock_recvmsg(struct socket *sock, struct msghdr *msg, { struct sock *sk = sock->sk; struct l2cap_pinfo *pi = l2cap_pi(sk); + bool have_conn; int err; if (unlikely(flags & MSG_ERRQUEUE)) @@ -1312,9 +1313,12 @@ static int l2cap_sock_recvmsg(struct socket *sock, struct msghdr *msg, pi->chan->mode != L2CAP_MODE_EXT_FLOWCTL) return err; - lock_sock(sk); - + /* Returning credits must be serialized with the RX path */ + have_conn = l2cap_chan_lock_conn(pi->chan); l2cap_publish_rx_avail(pi->chan); + l2cap_chan_unlock_conn(pi->chan, have_conn); + + lock_sock(sk); /* Attempt to put pending rx data in the socket buffer */ while (!list_empty(&pi->rx_busy)) { From d341ef030f3ceb8bf25e462b23c0b4addc5d7380 Mon Sep 17 00:00:00 2001 From: Triet Hoang Date: Tue, 18 Aug 2026 11:15:04 +0700 Subject: [PATCH 0762/2102] accel/rocket: Check allocations before use Check the result of kmalloc_objs() in rocket_job_open() before using the allocated buffer. Fixes: 0810d5ad88a1 ("accel/rocket: Add job submission IOCTL") Signed-off-by: Triet Hoang Tested-by: Igor Paunovic # RK3588, functional, no fault injection Reviewed-by: Tomeu Vizoso [tomeu: Rebased and fixed commit message prefix] Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/20260818041505.1579320-1-triet.hoang.dev@gmail.com --- drivers/accel/rocket/rocket_job.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/accel/rocket/rocket_job.c b/drivers/accel/rocket/rocket_job.c index 6f581df0b41329..b5bd53744194bb 100644 --- a/drivers/accel/rocket/rocket_job.c +++ b/drivers/accel/rocket/rocket_job.c @@ -562,6 +562,9 @@ int rocket_job_open(struct rocket_file_priv *rocket_priv) unsigned int core; int ret; + if (!scheds) + return -ENOMEM; + for (core = 0; core < rdev->num_cores; core++) scheds[core] = &rdev->cores[core].sched; @@ -570,9 +573,9 @@ int rocket_job_open(struct rocket_file_priv *rocket_priv) scheds, rdev->num_cores, NULL); if (WARN_ON(ret)) - return ret; + kfree(scheds); - return 0; + return ret; } void rocket_job_close(struct rocket_file_priv *rocket_priv) From 9bca2b5f1a4fa93ed628d47e66d1d8df86937131 Mon Sep 17 00:00:00 2001 From: Triet Hoang Date: Tue, 18 Aug 2026 11:15:05 +0700 Subject: [PATCH 0763/2102] accel/rocket: Keep scheduler allocation in rocket_file_priv Keep the scheduler allocation in rocket_file_priv and free it unconditionally in rocket_job_close(). This is to prevent a memory leak. Fixes: 0810d5ad88a1 ("accel/rocket: Add job submission IOCTL") Suggested-by: Igor Paunovic Link: https://lore.kernel.org/all/20260817093009.22359-1-royalnet026@gmail.com/ Signed-off-by: Triet Hoang Tested-by: Igor Paunovic # RK3588, functional, incl. concurrent clients Reviewed-by: Tomeu Vizoso [tomeu: Added Fixes, fixed prefix, rebased and extended commit message] Signed-off-by: Tomeu Vizoso Link: https://patch.msgid.link/20260818041505.1579320-2-triet.hoang.dev@gmail.com --- drivers/accel/rocket/rocket_drv.h | 1 + drivers/accel/rocket/rocket_job.c | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/drivers/accel/rocket/rocket_drv.h b/drivers/accel/rocket/rocket_drv.h index 2754f46f174982..7069ececffc434 100644 --- a/drivers/accel/rocket/rocket_drv.h +++ b/drivers/accel/rocket/rocket_drv.h @@ -24,6 +24,7 @@ struct rocket_file_priv { struct rocket_vm *vm; + struct drm_gpu_scheduler **scheds; struct drm_sched_entity sched_entity; }; diff --git a/drivers/accel/rocket/rocket_job.c b/drivers/accel/rocket/rocket_job.c index b5bd53744194bb..7b798a90bc492e 100644 --- a/drivers/accel/rocket/rocket_job.c +++ b/drivers/accel/rocket/rocket_job.c @@ -574,6 +574,8 @@ int rocket_job_open(struct rocket_file_priv *rocket_priv) rdev->num_cores, NULL); if (WARN_ON(ret)) kfree(scheds); + else + rocket_priv->scheds = scheds; return ret; } @@ -582,7 +584,7 @@ void rocket_job_close(struct rocket_file_priv *rocket_priv) { struct drm_sched_entity *entity = &rocket_priv->sched_entity; - kfree(entity->sched_list); + kfree(rocket_priv->scheds); drm_sched_entity_destroy(entity); } From 43b85636ea0d33152bf16816b7601e785723596d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Sat, 14 Nov 2026 16:16:50 -0300 Subject: [PATCH 0764/2102] drm/vc4: Drop BO usecnt before releasing the old FB MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The async page flip completion drops the old FB reference before decrementing its BO usecnt. If that was the last reference, the BO is already freed or recycled into the BO cache when vc4_bo_dec_usecnt() runs, leading to a use-after-free or a refcount underflow. For example, while running glmark2-es2-drm in the Raspberry Pi 3, the following warning appears: [ 459.078834] ------------[ cut here ]------------ [ 459.078855] refcount_t: underflow; use-after-free. [ 459.078952] WARNING: lib/refcount.c:96 at refcount_dec_not_one+0xa0/0xa8, CPU#0: swapper/0/0 [ 459.079316] Call trace: [ 459.079323] refcount_dec_not_one+0xa0/0xa8 (P) [ 459.079335] vc4_bo_dec_usecnt+0x30/0x118 [vc4] [ 459.079371] vc4_async_page_flip_complete_with_cleanup+0xa0/0xc4 [vc4] [ 459.079395] dma_fence_signal_timestamp_locked+0xb0/0x12c [ 459.079408] dma_fence_signal+0x3c/0x6c [ 459.079416] vc4_irq_render_job_done+0x24/0xbc [vc4] [ 459.079440] vc4_irq+0x120/0x138 [vc4] This could happen when userspace removes the old FB and closes its GEM handle while the flip is still pending. Decrement the BO usecnt before releasing the old FB reference. Do this by unifying the two fence callbacks and only decrementing the BO usecnt in VC4_GEN_4. Cc: stable@vger.kernel.org Fixes: 4d12c36fb73b ("drm/vc4: crtc: Move the BO handling out of common page-flip callback") Reviewed-by: Iago Toral Quiroga Link: https://patch.msgid.link/20261114-vc4-async-flip-fixes-v2-1-d33cbe99ed5d@igalia.com Signed-off-by: Maíra Canal --- drivers/gpu/drm/vc4/vc4_crtc.c | 60 ++++++++++++---------------------- 1 file changed, 21 insertions(+), 39 deletions(-) diff --git a/drivers/gpu/drm/vc4/vc4_crtc.c b/drivers/gpu/drm/vc4/vc4_crtc.c index f42cd535323020..c558b527c7e603 100644 --- a/drivers/gpu/drm/vc4/vc4_crtc.c +++ b/drivers/gpu/drm/vc4/vc4_crtc.c @@ -895,6 +895,7 @@ vc4_async_page_flip_complete(struct vc4_async_flip_state *flip_state) { struct drm_crtc *crtc = flip_state->crtc; struct drm_device *dev = crtc->dev; + struct vc4_dev *vc4 = to_vc4_dev(dev); struct drm_plane *plane = crtc->primary; vc4_plane_async_set_fb(plane, flip_state->fb); @@ -909,39 +910,27 @@ vc4_async_page_flip_complete(struct vc4_async_flip_state *flip_state) drm_crtc_vblank_put(crtc); drm_framebuffer_put(flip_state->fb); - if (flip_state->old_fb) - drm_framebuffer_put(flip_state->old_fb); - - kfree(flip_state); -} + if (flip_state->old_fb) { + /* + * Decrement the BO usecnt in order to keep the inc/dec + * calls balanced when the planes are updated through + * the async update path. + * + * FIXME: we should move to generic async-page-flip when + * it's available, so that we can get rid of this + * hand-made cleanup_fb() logic. + */ + if (vc4->gen == VC4_GEN_4) { + struct drm_gem_dma_object *dma_bo = + drm_fb_dma_get_gem_obj(flip_state->old_fb, 0); -static void vc4_async_page_flip_complete_with_cleanup(struct dma_fence *fence, - struct dma_fence_cb *cb) -{ - struct vc4_async_flip_state *flip_state = - container_of(cb, struct vc4_async_flip_state, cb); - struct vc4_bo *bo = NULL; + vc4_bo_dec_usecnt(to_vc4_bo(&dma_bo->base)); + } - if (flip_state->old_fb) { - struct drm_gem_dma_object *dma_bo = - drm_fb_dma_get_gem_obj(flip_state->old_fb, 0); - bo = to_vc4_bo(&dma_bo->base); + drm_framebuffer_put(flip_state->old_fb); } - vc4_async_page_flip_complete(flip_state); - dma_fence_put(fence); - - /* - * Decrement the BO usecnt in order to keep the inc/dec - * calls balanced when the planes are updated through - * the async update path. - * - * FIXME: we should move to generic async-page-flip when - * it's available, so that we can get rid of this - * hand-made cleanup_fb() logic. - */ - if (bo) - vc4_bo_dec_usecnt(bo); + kfree(flip_state); } static void vc4_async_page_flip_fence_complete(struct dma_fence *fence, @@ -959,30 +948,23 @@ static int vc4_async_set_fence_cb(struct drm_device *dev, { struct drm_framebuffer *fb = flip_state->fb; struct drm_gem_dma_object *dma_bo = drm_fb_dma_get_gem_obj(fb, 0); - dma_fence_func_t async_page_flip_complete_function; - struct vc4_dev *vc4 = to_vc4_dev(dev); struct dma_fence *fence; int ret; - if (vc4->gen == VC4_GEN_4) - async_page_flip_complete_function = vc4_async_page_flip_complete_with_cleanup; - else - async_page_flip_complete_function = vc4_async_page_flip_fence_complete; - ret = dma_resv_get_singleton(dma_bo->base.resv, DMA_RESV_USAGE_READ, &fence); if (ret) return ret; /* If there's no fence, complete the page flip immediately */ if (!fence) { - async_page_flip_complete_function(fence, &flip_state->cb); + vc4_async_page_flip_fence_complete(fence, &flip_state->cb); return 0; } /* If the fence has already been completed, complete the page flip */ if (dma_fence_add_callback(fence, &flip_state->cb, - async_page_flip_complete_function)) - async_page_flip_complete_function(fence, &flip_state->cb); + vc4_async_page_flip_fence_complete)) + vc4_async_page_flip_fence_complete(fence, &flip_state->cb); return 0; } From 12a321af56c436e299414d8c276457dcf387e0cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Sat, 14 Nov 2026 16:16:51 -0300 Subject: [PATCH 0765/2102] drm/vc4: Complete async page flips from an ordered workqueue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Async page flips complete from a dma_fence callback, which runs in the fence signaling context: the VC4 render job IRQ handler on RPi 0-3 since commit e8941ac97f28 ("drm/vc4: Remove BOs seqnos"), and the V3D IRQ handler on RPi 4-5 since commit d19e00ee06a9 ("drm/vc4: crtc: Fix out of order frames during asynchronous page flips"). Completing the flip may sleep: on RPi 0-3, vc4_bo_dec_usecnt() takes bo->madv_lock, and on all platforms, dropping the last framebuffer reference takes fb_lock and can free the BO. When running the kernel with CONFIG_DEBUG_ATOMIC_SLEEP=y on RPi 3, this triggers the following warning: [ 2511.636319] BUG: sleeping function called from invalid context at kernel/locking/mutex.c:623 [ 2511.636667] in_atomic(): 1, irqs_disabled(): 1, non_block: 0, pid: 0, name: swapper/0 [ 2511.636681] preempt_count: 1000002, expected: 0 [ 2511.636689] RCU nest depth: 0, expected: 0 [ 2511.636698] locks held by swapper/0/0: 1, on CPU#0: [ 2511.636711] #0: ffff000037183198 (&fence->inline_lock){-...}-{3:3}, at: dma_fence_signal+0x88/0xec [ 2511.636892] Hardware name: Raspberry Pi 3 Model B Plus Rev 1.3 (DT) [ 2511.636899] Call trace: [ 2511.636991] mutex_lock_nested+0x24/0x30 [ 2511.637002] vc4_bo_dec_usecnt+0x40/0x124 [vc4] [ 2511.637070] vc4_async_page_flip_complete_with_cleanup+0xa0/0xc4 [vc4] [ 2511.637102] dma_fence_signal_timestamp_locked+0x118/0x290 [ 2511.637116] dma_fence_signal+0x9c/0xec [ 2511.637126] vc4_irq_render_job_done+0x24/0x114 [vc4] [ 2511.637158] vc4_irq+0x16c/0x274 [vc4] Make the fence callback only queue a work item on a per-CRTC ordered workqueue and complete the flip from it. Flips with no fence or an already signaled one still complete inline, but only after flushing that workqueue, so they can't complete before earlier flips on the same CRTC whose fence already signaled. Cc: stable@vger.kernel.org Fixes: d19e00ee06a9 ("drm/vc4: crtc: Fix out of order frames during asynchronous page flips") Fixes: e8941ac97f28 ("drm/vc4: Remove BOs seqnos") Reviewed-by: Iago Toral Quiroga Link: https://patch.msgid.link/20261114-vc4-async-flip-fixes-v2-2-d33cbe99ed5d@igalia.com Signed-off-by: Maíra Canal --- drivers/gpu/drm/vc4/vc4_crtc.c | 51 +++++++++++++++++++++------------- drivers/gpu/drm/vc4/vc4_drv.h | 6 ++++ 2 files changed, 38 insertions(+), 19 deletions(-) diff --git a/drivers/gpu/drm/vc4/vc4_crtc.c b/drivers/gpu/drm/vc4/vc4_crtc.c index c558b527c7e603..177ee27ab6d150 100644 --- a/drivers/gpu/drm/vc4/vc4_crtc.c +++ b/drivers/gpu/drm/vc4/vc4_crtc.c @@ -884,15 +884,18 @@ struct vc4_async_flip_state { struct drm_framebuffer *fb; struct drm_framebuffer *old_fb; struct drm_pending_vblank_event *event; + struct dma_fence *fence; struct dma_fence_cb cb; + struct work_struct work; }; -/* Called when the V3D execution for the BO being flipped to is done, so that - * we can actually update the plane's address to point to it. +/* Executed when the V3D execution for the BO being flipped to is done, so + * that we can actually update the plane's address to point to it. */ -static void -vc4_async_page_flip_complete(struct vc4_async_flip_state *flip_state) +static void vc4_async_page_flip_work(struct work_struct *work) { + struct vc4_async_flip_state *flip_state = + container_of(work, struct vc4_async_flip_state, work); struct drm_crtc *crtc = flip_state->crtc; struct drm_device *dev = crtc->dev; struct vc4_dev *vc4 = to_vc4_dev(dev); @@ -930,17 +933,19 @@ vc4_async_page_flip_complete(struct vc4_async_flip_state *flip_state) drm_framebuffer_put(flip_state->old_fb); } + dma_fence_put(flip_state->fence); kfree(flip_state); } -static void vc4_async_page_flip_fence_complete(struct dma_fence *fence, - struct dma_fence_cb *cb) +static void vc4_async_page_flip_fence_cb(struct dma_fence *fence, + struct dma_fence_cb *cb) { struct vc4_async_flip_state *flip_state = container_of(cb, struct vc4_async_flip_state, cb); + struct vc4_crtc *vc4_crtc = to_vc4_crtc(flip_state->crtc); - vc4_async_page_flip_complete(flip_state); - dma_fence_put(fence); + /* Completing the flip may sleep, so defer it to a worker. */ + queue_work(vc4_crtc->async_flip_wq, &flip_state->work); } static int vc4_async_set_fence_cb(struct drm_device *dev, @@ -948,23 +953,26 @@ static int vc4_async_set_fence_cb(struct drm_device *dev, { struct drm_framebuffer *fb = flip_state->fb; struct drm_gem_dma_object *dma_bo = drm_fb_dma_get_gem_obj(fb, 0); - struct dma_fence *fence; + struct vc4_crtc *vc4_crtc = to_vc4_crtc(flip_state->crtc); int ret; - ret = dma_resv_get_singleton(dma_bo->base.resv, DMA_RESV_USAGE_READ, &fence); + INIT_WORK(&flip_state->work, vc4_async_page_flip_work); + + ret = dma_resv_get_singleton(dma_bo->base.resv, DMA_RESV_USAGE_READ, + &flip_state->fence); if (ret) return ret; - /* If there's no fence, complete the page flip immediately */ - if (!fence) { - vc4_async_page_flip_fence_complete(fence, &flip_state->cb); + if (flip_state->fence && + !dma_fence_add_callback(flip_state->fence, &flip_state->cb, + vc4_async_page_flip_fence_cb)) return 0; - } - /* If the fence has already been completed, complete the page flip */ - if (dma_fence_add_callback(fence, &flip_state->cb, - vc4_async_page_flip_fence_complete)) - vc4_async_page_flip_fence_complete(fence, &flip_state->cb); + /* No fence or the fence has already signaled. Complete the flip + * immediately, after earlier queued flips. + */ + flush_workqueue(vc4_crtc->async_flip_wq); + vc4_async_page_flip_work(&flip_state->work); return 0; } @@ -990,7 +998,7 @@ vc4_async_page_flip_common(struct drm_crtc *crtc, /* Save the current FB before it's replaced by the new one in * drm_atomic_set_fb_for_plane(). We'll need the old FB in - * vc4_async_page_flip_complete() to decrement the BO usecnt and keep + * vc4_async_page_flip_work() to decrement the BO usecnt and keep * it consistent. * FIXME: we should move to generic async-page-flip when it's * available, so that we can get rid of this hand-made cleanup_fb() @@ -1395,6 +1403,11 @@ int __vc4_crtc_init(struct drm_device *drm, drm_crtc_helper_add(crtc, crtc_helper_funcs); + vc4_crtc->async_flip_wq = drmm_alloc_ordered_workqueue(drm, "%s-async-flip", + 0, crtc->name); + if (IS_ERR(vc4_crtc->async_flip_wq)) + return PTR_ERR(vc4_crtc->async_flip_wq); + if (vc4->gen == VC4_GEN_4) { drm_mode_crtc_set_gamma_size(crtc, ARRAY_SIZE(vc4_crtc->lut_r)); drm_crtc_enable_color_mgmt(crtc, 0, false, crtc->gamma_size); diff --git a/drivers/gpu/drm/vc4/vc4_drv.h b/drivers/gpu/drm/vc4/vc4_drv.h index 09134809bf1565..f68486be08a6f4 100644 --- a/drivers/gpu/drm/vc4/vc4_drv.h +++ b/drivers/gpu/drm/vc4/vc4_drv.h @@ -596,6 +596,12 @@ struct vc4_crtc { * access to that value. */ unsigned int current_hvs_channel; + + /** + * @async_flip_wq: Ordered workqueue completing the CRTC's async + * page flips. + */ + struct workqueue_struct *async_flip_wq; }; #define to_vc4_crtc(_crtc) \ From f9fc6da01a290609428d308033143f1d96ab658f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Sat, 14 Nov 2026 16:16:52 -0300 Subject: [PATCH 0766/2102] drm/vc4: Look up the async page flip fence before committing the flip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit vc4_async_page_flip_common() ignores dma_resv_get_singleton() failures. By then the plane state already points at the new framebuffer, so the flip is never completed. So, its state leaks, the vblank reference is never dropped and the event is never sent. Look up the fence before changing any state, so the error can be properly returned to userspace. Cc: stable@vger.kernel.org Fixes: d19e00ee06a9 ("drm/vc4: crtc: Fix out of order frames during asynchronous page flips") Reviewed-by: Iago Toral Quiroga Link: https://patch.msgid.link/20261114-vc4-async-flip-fixes-v2-3-d33cbe99ed5d@igalia.com Signed-off-by: Maíra Canal --- drivers/gpu/drm/vc4/vc4_crtc.c | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/vc4/vc4_crtc.c b/drivers/gpu/drm/vc4/vc4_crtc.c index 177ee27ab6d150..4b6d4a5f7bc9b7 100644 --- a/drivers/gpu/drm/vc4/vc4_crtc.c +++ b/drivers/gpu/drm/vc4/vc4_crtc.c @@ -948,33 +948,22 @@ static void vc4_async_page_flip_fence_cb(struct dma_fence *fence, queue_work(vc4_crtc->async_flip_wq, &flip_state->work); } -static int vc4_async_set_fence_cb(struct drm_device *dev, - struct vc4_async_flip_state *flip_state) +static void vc4_async_set_fence_cb(struct vc4_async_flip_state *flip_state) { - struct drm_framebuffer *fb = flip_state->fb; - struct drm_gem_dma_object *dma_bo = drm_fb_dma_get_gem_obj(fb, 0); struct vc4_crtc *vc4_crtc = to_vc4_crtc(flip_state->crtc); - int ret; INIT_WORK(&flip_state->work, vc4_async_page_flip_work); - ret = dma_resv_get_singleton(dma_bo->base.resv, DMA_RESV_USAGE_READ, - &flip_state->fence); - if (ret) - return ret; - if (flip_state->fence && !dma_fence_add_callback(flip_state->fence, &flip_state->cb, vc4_async_page_flip_fence_cb)) - return 0; + return; /* No fence or the fence has already signaled. Complete the flip * immediately, after earlier queued flips. */ flush_workqueue(vc4_crtc->async_flip_wq); vc4_async_page_flip_work(&flip_state->work); - - return 0; } static int @@ -983,14 +972,22 @@ vc4_async_page_flip_common(struct drm_crtc *crtc, struct drm_pending_vblank_event *event, uint32_t flags) { - struct drm_device *dev = crtc->dev; + struct drm_gem_dma_object *dma_bo = drm_fb_dma_get_gem_obj(fb, 0); struct drm_plane *plane = crtc->primary; struct vc4_async_flip_state *flip_state; + int ret; flip_state = kzalloc_obj(*flip_state); if (!flip_state) return -ENOMEM; + ret = dma_resv_get_singleton(dma_bo->base.resv, DMA_RESV_USAGE_READ, + &flip_state->fence); + if (ret) { + kfree(flip_state); + return ret; + } + drm_framebuffer_get(fb); flip_state->fb = fb; flip_state->crtc = crtc; @@ -1016,7 +1013,7 @@ vc4_async_page_flip_common(struct drm_crtc *crtc, */ drm_atomic_set_fb_for_plane(plane->state, fb); - vc4_async_set_fence_cb(dev, flip_state); + vc4_async_set_fence_cb(flip_state); /* Driver takes ownership of state on successful async commit. */ return 0; From 8b456f136a76a29fee8d36934740cb7f7fb5c837 Mon Sep 17 00:00:00 2001 From: koraynilay Date: Mon, 16 Nov 2026 16:45:26 +0100 Subject: [PATCH 0767/2102] smb: client: fix times assignments in cifs_posix_to_fattr() Currently cifs_posix_to_fattr() wrongly sets SMB's CreationTime to fattr->cf_ctime. Fix this by setting fattr->cf_createtime to SMB's CreationTime and fattr->cf_ctime to SMB's ChangeTime, matching the behaviour of __dir_info_to_fattr(). This patch also fixes a few related issues reported by sashiko on another patch (see Sashiko Link tag). Reproducers for these bugs, with /tmp as the local filesystem folder exported as [test] in ksmbd.conf and /mnt as the smb folder mounted with mount -t cifs: mount -t cifs //127.0.0.1/test /mnt -o username=ciao,password=c,posix Issue 1: ctime clobbered by CreationTime during readdir mkdir -p /mnt/dir touch /mnt/dir/file sleep 4 chmod 644 /mnt/dir/file stat -c "ctime and btime before readdir: %Z %W" /mnt/dir/file ls -lc /mnt/dir > /dev/null stat -c "ctime and btime after readdir: %Z %W" /mnt/dir/file stat -c "ctime and btime on disk: %Z %W" /tmp/dir/file output before the fix, notice how ctime is the same as btime after the readdir, while it's 4 seconds ahead (because of the sleep 4) before the readdir (on disk timestamps are not touched): ctime and btime before readdir: 1794842068 1794842064 ctime and btime after readdir: 1794842064 1794842064 ctime and btime on disk: 1794842068 1794842064 output after the fix: ctime and btime before readdir: 1794842908 1794842904 ctime and btime after readdir: 1794842908 1794842904 ctime and btime on disk: 1794842908 1794842904 Issue 2: btime and ptime wiped out by readdir [ no reproducer as it only happens after the linked patch series is applied, since it needs cifs_i->createtime = fattr->cf_createtime in cifs_fattr_to_inode() ] Issue 3: in-memory inode aliasing (flock bypass on hardlink via readdir) mkdir -p /mnt/dir1 /mnt/dir2 echo "test" > /mnt/dir1/h1 ln /mnt/dir1/h1 /mnt/dir2/h2 exec 3< /mnt/dir1/h1 flock -x -n 3 # get exclusive lock ls /mnt/dir2 > /dev/null exec 4< /mnt/dir2/h2 flock -x -n 4 if [ $? -eq 0 ];then echo "acquired: duplicate in-memory inode" else echo "blocked: same inode" fi output before the fix: acquired: duplicate in-memory inode output after the fix: blocked: same inode Fixes: 3d519bd1269f ("cifs: plumb smb2 POSIX dir enumeration") Cc: stable@vger.kernel.org Reported-by: Sashiko Link: https://sashiko.dev/#/patchset/20261115180343.576773-1-koray.fra%40gmail.com?part=10 Link: https://lore.kernel.org/all/20261115180343.576773-11-koray.fra@gmail.com/ Assisted-by: Gemini:3.8-flash-high antigravity-cli-1.5.7 Signed-off-by: koraynilay Reviewed-by: Namjae Jeon Signed-off-by: Paulo Alcantara --- fs/smb/client/readdir.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fs/smb/client/readdir.c b/fs/smb/client/readdir.c index 525f9918148589..5d335f12eb2445 100644 --- a/fs/smb/client/readdir.c +++ b/fs/smb/client/readdir.c @@ -253,9 +253,10 @@ cifs_posix_to_fattr(struct cifs_fattr *fattr, struct smb2_posix_info *info, fattr->cf_bytes = le64_to_cpu(info->AllocationSize); fattr->cf_eof = le64_to_cpu(info->EndOfFile); + fattr->cf_createtime = le64_to_cpu(info->CreationTime); fattr->cf_atime = cifs_NTtimeToUnix(info->LastAccessTime); fattr->cf_mtime = cifs_NTtimeToUnix(info->LastWriteTime); - fattr->cf_ctime = cifs_NTtimeToUnix(info->CreationTime); + fattr->cf_ctime = cifs_NTtimeToUnix(info->ChangeTime); fattr->cf_nlink = le32_to_cpu(info->HardLinks); fattr->cf_cifsattrs = le32_to_cpu(info->DosAttributes); From 7c585e2f72633f5577b872baca6367f735ff1eec Mon Sep 17 00:00:00 2001 From: Alison Schofield Date: Fri, 6 Nov 2026 14:22:37 -0800 Subject: [PATCH 0768/2102] cxl/test: Free the decoder registry when cxl_test_init() fails Decoder registry entries persist across mock device removal to support topology replay. Sashiko review found that if cxl_test_init() fails after decoders are enumerated, the entries leak because cxl_test_exit() is never called. Free the registry entries and destroy the xarray during error unwind. Fixes: f3b1d2260703 ("tools/testing/cxl: Enable replay of user regions as auto regions") Signed-off-by: Alison Schofield Reviewed-by: Jonathan Cameron Link: https://patch.msgid.link/20261106222240.958402-1-alison.schofield@intel.com Signed-off-by: Dave Jiang --- tools/testing/cxl/test/cxl.c | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/tools/testing/cxl/test/cxl.c b/tools/testing/cxl/test/cxl.c index 3eb1051b1ee8a4..e3bed17ae2538f 100644 --- a/tools/testing/cxl/test/cxl.c +++ b/tools/testing/cxl/test/cxl.c @@ -2436,6 +2436,17 @@ static int cxl_topo_init(void) return cxl_type3_topo_init(); } +static void free_decoder_registry(void) +{ + unsigned long index; + void *entry; + + xa_for_each(&decoder_registry, index, entry) { + xa_erase(&decoder_registry, index); + kfree(entry); + } +} + static __init int cxl_test_init(void) { struct range mappable; @@ -2525,20 +2536,11 @@ static __init int cxl_test_init(void) gen_pool_destroy(cxl_mock_pool); err_gen_pool_create: unregister_cxl_mock_ops(&cxl_mock_ops); + free_decoder_registry(); + xa_destroy(&decoder_registry); return rc; } -static void free_decoder_registry(void) -{ - unsigned long index; - void *entry; - - xa_for_each(&decoder_registry, index, entry) { - xa_erase(&decoder_registry, index); - kfree(entry); - } -} - static __exit void cxl_test_exit(void) { hmem_test_exit(); From a02576de05178f15ffe6fc7551496de7de8acfde Mon Sep 17 00:00:00 2001 From: Richard Cheng Date: Tue, 3 Nov 2026 14:34:09 +0800 Subject: [PATCH 0769/2102] cxl/port: Fix endpoint RAS error unmasking Moving endpoint RAS handling from cxl_pci to cxl_port left cxl_ras_unmask() checking whether port->uport_dev is a PCI device. Endpoint ports always use a cxl_memdev as uport_dev, so this check returns early and leaves the CXL RAS error masks unchanged. Resolve the PCI device directly through the memdev's parent. Rename helper to cxl_endpoint_ras_unmask() and its param to endpoint to make its endpoint-only scope explicit. Fixes: dab7162d0ae7 ("cxl/port: Move endpoint component register management to cxl_port") Signed-off-by: Richard Cheng Reviewed-by: Ben Cheatham Link: https://patch.msgid.link/20261103063409.18275-1-icheng@nvidia.com Signed-off-by: Dave Jiang --- drivers/cxl/port.c | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/drivers/cxl/port.c b/drivers/cxl/port.c index c12fd0b89883a6..7b4726c7276d43 100644 --- a/drivers/cxl/port.c +++ b/drivers/cxl/port.c @@ -72,19 +72,21 @@ static int cxl_switch_port_probe(struct cxl_port *port) return 0; } -static int cxl_ras_unmask(struct cxl_port *port) +static int cxl_endpoint_ras_unmask(struct cxl_port *endpoint) { + struct cxl_memdev *cxlmd = to_cxl_memdev(endpoint->uport_dev); + struct device *parent = cxlmd->dev.parent; struct pci_dev *pdev; void __iomem *addr; u32 orig_val, val, mask; u16 cap; int rc; - if (!dev_is_pci(port->uport_dev)) + if (!dev_is_pci(parent)) return 0; - pdev = to_pci_dev(port->uport_dev); + pdev = to_pci_dev(parent); - if (!port->regs.ras) { + if (!endpoint->regs.ras) { pci_dbg(pdev, "No RAS registers.\n"); return 0; } @@ -98,7 +100,7 @@ static int cxl_ras_unmask(struct cxl_port *port) return rc; if (cap & PCI_EXP_DEVCTL_URRE) { - addr = port->regs.ras + CXL_RAS_UNCORRECTABLE_MASK_OFFSET; + addr = endpoint->regs.ras + CXL_RAS_UNCORRECTABLE_MASK_OFFSET; orig_val = readl(addr); mask = CXL_RAS_UNCORRECTABLE_MASK_MASK | @@ -110,7 +112,7 @@ static int cxl_ras_unmask(struct cxl_port *port) } if (cap & PCI_EXP_DEVCTL_CERE) { - addr = port->regs.ras + CXL_RAS_CORRECTABLE_MASK_OFFSET; + addr = endpoint->regs.ras + CXL_RAS_CORRECTABLE_MASK_OFFSET; orig_val = readl(addr); val = orig_val & ~CXL_RAS_CORRECTABLE_MASK_MASK; writel(val, addr); @@ -152,7 +154,7 @@ static int cxl_endpoint_port_probe(struct cxl_port *port) devm_cxl_dport_rch_ras_setup(dport); devm_cxl_port_ras_setup(port); - if (cxl_ras_unmask(port)) + if (cxl_endpoint_ras_unmask(port)) dev_dbg(&port->dev, "failed to unmask RAS interrupts\n"); /* From a0abc1e4c9d5b8b846abe4293b7bca578736da8a Mon Sep 17 00:00:00 2001 From: Sung Byeongchan Date: Sat, 7 Nov 2026 18:36:01 +0900 Subject: [PATCH 0770/2102] ieee802154: require CAP_NET_ADMIN for SIOCSIFADDR PF_IEEE802154 DGRAM sockets are available to ordinary init-net processes. Their family-specific SIOCSIFADDR path calls the netdev ioctl directly and does not pass through the generic network-device setter capability check. An unprivileged process can therefore change the PAN ID and short address of a separately administrator-owned down WPAN interface. In a local fakelb fixture, uid 1000 changed both identifiers and the values remained active through a later administrator interface open in three of three fresh KASAN boots. Require CAP_NET_ADMIN in the socket network namespace before processing SIOCSIFADDR. Keep SIOCGIFADDR and all existing state and value checks unchanged. The fixed kernel rejected the same unprivileged request with -EPERM and preserved the administrator identity in three of three matched boots. Administrator SET, running-device, invalid-value, wrong-device, cleanup, later-open and recovery controls passed in all baseline and fixed runs. The demonstrated impact is local cross-principal WPAN identity and policy modification after privileged device setup. Memory corruption, disclosure, RCE and LPE were not demonstrated. Fixes: 9ec767160357 ("net: add IEEE 802.15.4 socket family implementation") Cc: stable@vger.kernel.org Signed-off-by: Sung Byeongchan Reviewed-by: Miquel Raynal Link: https://patch.msgid.link/20261107093601.619363-1-tjdqudcks0424@naver.com Signed-off-by: Jakub Kicinski --- net/ieee802154/socket.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/net/ieee802154/socket.c b/net/ieee802154/socket.c index be8ca1f053a2b6..362457de8424cc 100644 --- a/net/ieee802154/socket.c +++ b/net/ieee802154/socket.c @@ -128,6 +128,10 @@ static int ieee802154_dev_ioctl(struct sock *sk, struct ifreq __user *arg, int ret = -ENOIOCTLCMD; struct net_device *dev; + if (cmd == SIOCSIFADDR && + !ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) + return -EPERM; + if (get_user_ifreq(&ifr, NULL, arg)) return -EFAULT; From 5a277aa7eb4d4f1f05534d6c3dcb1a9fa4f6b8f2 Mon Sep 17 00:00:00 2001 From: Dave Jiang Date: Tue, 17 Nov 2026 15:31:16 -0700 Subject: [PATCH 0771/2102] nvdimm/namespace: Nest mapping locks under the bus lock create_namespaces() takes every mapping lock in a region with mutex_lock_nested() and uses the mapping index as the subclass. Lockdep supports only 8 subclasses. A region with more mappings, such as a 12-way CXL pmem region, triggers: DEBUG_LOCKS_WARN_ON(subclass >= MAX_LOCKDEP_SUBCLASSES) and lockdep turns itself off. The caller holds the nvdimm bus reconfig_mutex. Take the mapping locks with mutex_lock_nest_lock() under that lock instead. Lockdep then tracks any number of mapping locks. Fixes: ae8219f186d8 ("libnvdimm, label: convert label tracking to a linked list") Signed-off-by: Dave Jiang Tested-by: Alison Schofield Reviewed-by: Alison Schofield Link: https://patch.msgid.link/20261117223116.3478672-1-dave.jiang@intel.com Signed-off-by: Alison Schofield --- drivers/nvdimm/namespace_devs.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/drivers/nvdimm/namespace_devs.c b/drivers/nvdimm/namespace_devs.c index 557fe0cb43e241..3aa0a9026efa8a 100644 --- a/drivers/nvdimm/namespace_devs.c +++ b/drivers/nvdimm/namespace_devs.c @@ -2031,6 +2031,7 @@ static struct device **scan_labels(struct nd_region *nd_region) static struct device **create_namespaces(struct nd_region *nd_region) { + struct nvdimm_bus *nvdimm_bus = walk_to_nvdimm_bus(&nd_region->dev); struct nd_mapping *nd_mapping; struct device **devs; int i; @@ -2038,10 +2039,16 @@ static struct device **create_namespaces(struct nd_region *nd_region) if (nd_region->ndr_mappings == 0) return NULL; - /* lock down all mappings while we scan labels */ + /* + * Lock down all mappings while we scan labels. A region can have + * more mappings than lockdep has subclasses, so nest the mapping + * locks under the bus lock rather than giving each its own subclass. + */ + lockdep_assert_held(&nvdimm_bus->reconfig_mutex); for (i = 0; i < nd_region->ndr_mappings; i++) { nd_mapping = &nd_region->mapping[i]; - mutex_lock_nested(&nd_mapping->lock, i); + mutex_lock_nest_lock(&nd_mapping->lock, + &nvdimm_bus->reconfig_mutex); } devs = scan_labels(nd_region); From 3e8c853c959e9637ed66ae1e55e0d3bb97372cc5 Mon Sep 17 00:00:00 2001 From: Joas Antonio dos Santos Date: Tue, 10 Nov 2026 09:03:23 +0000 Subject: [PATCH 0772/2102] mac802154: llsec: reject secured frames with security level 0 mac802154_llsec_decrypt() handles every received frame that has the Security Enabled bit set. The security level is taken from the auxiliary security header of the frame and is not required to be non-zero. The only check that looks at level 0 rejects the frame only if level 0 is not allowed by the matching seclevel entry, the entry has device_override set and the device is not seclevel_exempt: if (!(seclevel.sec_levels & BIT(hdr.sec.level)) && (hdr.sec.level == 0 && seclevel.device_override && !dev->dev.seclevel_exempt)) { Otherwise the frame reaches llsec_do_decrypt(), which sends every level other than IEEE802154_SCF_SECLEVEL_ENC to llsec_do_decrypt_auth(). There ieee802154_sechdr_authtag_len() returns 0 for level 0 and req = aead_request_alloc(llsec_tfm_by_len(key, authlen), GFP_ATOMIC); looks for a transform with an authentication tag size of 0. The key only has transforms for tag sizes 4, 8 and 16, so llsec_tfm_by_len() runs into its BUG(). The frame is not authenticated at that point. A station in radio range can crash a node that has llsec enabled if it sends a frame that matches a configured key entry and a device table entry (source address, key id mode and key id are sent in the clear and can be observed), uses a frame type that has a seclevel entry and carries a frame counter that is not lower than the stored one. No key material is needed. The frame counter of that device is also updated before the BUG() is reached. A frame with the Security Enabled bit set and security level 0 carries no protection and cannot be processed by the incoming security procedure. Reject it before any key or device state is looked up. The transmit side already leaves such frames alone in mac802154_llsec_encrypt(). Found by LLM-assisted source review. Fixes: 4c14a2fb5d14 ("mac802154: add llsec decryption method") Cc: stable@vger.kernel.org Signed-off-by: Joas Antonio dos Santos Reviewed-by: Miquel Raynal Link: https://patch.msgid.link/20261110-llsec-seclevel-none-v1-1-06ef143e467f@gmail.com Signed-off-by: Jakub Kicinski --- net/mac802154/llsec.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/net/mac802154/llsec.c b/net/mac802154/llsec.c index 85452ef9a58c69..32565f18897e56 100644 --- a/net/mac802154/llsec.c +++ b/net/mac802154/llsec.c @@ -1019,6 +1019,8 @@ int mac802154_llsec_decrypt(struct mac802154_llsec *sec, struct sk_buff *skb) return 0; if (hdr.fc.version == 0) return -EINVAL; + if (hdr.sec.level == IEEE802154_SCF_SECLEVEL_NONE) + return -EINVAL; read_lock_bh(&sec->lock); if (!sec->params.enabled) { From 035fe1092f38476f7ea14705cf735640fd217f0a Mon Sep 17 00:00:00 2001 From: Hengyu Liang Date: Fri, 13 Nov 2026 14:33:55 -0500 Subject: [PATCH 0773/2102] neighbour: do not update an existing proxy entry on SIOCSARP Commit dc2a27e524ac ("neighbour: Update pneigh_entry in pneigh_create().") moved the update of flags, protocol and permanent from neigh_add() into pneigh_create(). However, arp_req_set_public() also calls pneigh_create(), with all three set to zero. As of now, SIOCSARP on an address that already has a proxy entry clears the flags of the entry and makes it non-permanent. The entry is then removed when the carrier goes down, and the host no longer answers ARP requests for the address. A similar issue happened before with the protocol. It was fixed by commit cbada1048847 ("neighbour: restore protocol != 0 check in pneigh update"). Perhaps flags and permanent need a fix as well. The issue can be reproduced with: ip link add d0 type veth peer name d1 ip link set d0 up ip link set d1 up ip neigh add proxy 10.9.9.9 dev d0 arp -i d0 -Ds 10.9.9.9 d0 pub ip link set d1 down sleep 1 ip neigh show proxy Before commit dc2a27e524ac ("neighbour: Update pneigh_entry in pneigh_create()."), the result is: 10.9.9.9 dev d0 proxy After that commit, the result is empty. This patch will add an update argument to pneigh_create(). Only neigh_add() sets it, so SIOCSARP leaves an existing entry alone again. Fixes: dc2a27e524ac ("neighbour: Update pneigh_entry in pneigh_create().") Signed-off-by: Hengyu Liang Reviewed-by: Kuniyuki Iwashima Reviewed-by: Ido Schimmel Link: https://patch.msgid.link/20261113193355.3820232-1-hengyul@cs.unc.edu Signed-off-by: Jakub Kicinski --- include/net/neighbour.h | 2 +- net/core/neighbour.c | 9 ++++++--- net/ipv4/arp.c | 2 +- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/include/net/neighbour.h b/include/net/neighbour.h index 79a5a548a12912..d6d691fec124d2 100644 --- a/include/net/neighbour.h +++ b/include/net/neighbour.h @@ -394,7 +394,7 @@ struct pneigh_entry *pneigh_lookup(struct neigh_table *tbl, const void *key, struct net_device *dev); int pneigh_create(struct neigh_table *tbl, const void *key, struct net_device *dev, u32 flags, u8 protocol, - bool permanent); + bool permanent, bool update); int pneigh_delete(struct neigh_table *tbl, const void *key, struct net_device *dev); diff --git a/net/core/neighbour.c b/net/core/neighbour.c index d6e9c7c59a892c..ae2db3912454ad 100644 --- a/net/core/neighbour.c +++ b/net/core/neighbour.c @@ -783,7 +783,7 @@ struct pneigh_entry *pneigh_lookup(struct neigh_table *tbl, int pneigh_create(struct neigh_table *tbl, const void *pkey, struct net_device *dev, - u32 flags, u8 protocol, bool permanent) + u32 flags, u8 protocol, bool permanent, bool update) { struct pneigh_entry *n; unsigned int key_len; @@ -793,8 +793,11 @@ int pneigh_create(struct neigh_table *tbl, mutex_lock(&tbl->phash_lock); n = pneigh_lookup(tbl, pkey, dev); - if (n) + if (n) { + if (!update) + goto out; goto update; + } key_len = tbl->key_len; n = kzalloc(sizeof(*n) + key_len, GFP_KERNEL); @@ -2155,7 +2158,7 @@ static int neigh_add(struct sk_buff *skb, struct nlmsghdr *nlh, } err = pneigh_create(tbl, dst, dev, ndm_flags, protocol, - !!(ndm->ndm_state & NUD_PERMANENT)); + !!(ndm->ndm_state & NUD_PERMANENT), true); goto out; } diff --git a/net/ipv4/arp.c b/net/ipv4/arp.c index 1ca4ced280aef2..3bc8db6ccd68e0 100644 --- a/net/ipv4/arp.c +++ b/net/ipv4/arp.c @@ -1099,7 +1099,7 @@ static int arp_req_set_public(struct net *net, struct arpreq *r, if (mask) { __be32 ip = ((struct sockaddr_in *)&r->arp_pa)->sin_addr.s_addr; - return pneigh_create(tbl, &ip, dev, 0, 0, false); + return pneigh_create(tbl, &ip, dev, 0, 0, false, false); } return arp_req_set_proxy(net, dev, 1); From 686b5f47f8cc6ec8ad092dd10d944a75d731ea5b Mon Sep 17 00:00:00 2001 From: Maxime Chevallier Date: Fri, 13 Nov 2026 11:32:35 +0100 Subject: [PATCH 0774/2102] net: stmmac: Clear DMA errors for multi-channel interrupts The Multi-MSI interrupt handler doesn't clear the DMA error interrupts, and this leads to interrupt storms when one of these interrupts starts firing : - The RBU (rx buff unav) which triggers under high traffic load This triggers easily with iperf3 and small udp packets, and shows when running the netpoll kselftest - The RPS (rx process stop) which triggers when we stop the DMA RX. This one shows when restarting the RX logic without doing a down/up cycle, like when attaching an XDP program. The XSK kselftests triggers it. Let's make sure we clear these interrupts for multi-MSI cases, and call stmmac_global_err() upon fatal bus errors. For that introduce an "ERR" DMA dir, as we don't want to touch the RI/TI bits when handling these interrupts. Both of the above storms have been found on dwmac-motorcomm (YT6801), and are triggered by the xdp.py, xsk_reconfig.py, xdp_features.py, ring_reconfig.py and netpoll_basic kernel selftests. This seems to only affect dwmac4, there's no multi-msi mode on dwmac1000 (except on loongson which I couldn't test), and on dwxgmac these interrupts are masked as of today. Fixes: 6ccf12ae111e ("net: stmmac: use interrupt mode INTM=1 for multi-MSI") Fixes: 1b9707e6f1a9 ("net: stmmac: enable RPS and RBU interrupts") Reviewed-by: Nicolai Buchwitz Reviewed-by: Lorenzo Bianconi Tested-by: Magnus Leatti Signed-off-by: Maxime Chevallier Link: https://patch.msgid.link/20261113103236.2184751-1-maxime.chevallier@bootlin.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/stmicro/stmmac/common.h | 1 + .../net/ethernet/stmicro/stmmac/dwmac4_dma.h | 5 +++++ .../net/ethernet/stmicro/stmmac/dwmac4_lib.c | 2 ++ .../net/ethernet/stmicro/stmmac/stmmac_main.c | 19 +++++++++++++++++++ 4 files changed, 27 insertions(+) diff --git a/drivers/net/ethernet/stmicro/stmmac/common.h b/drivers/net/ethernet/stmicro/stmmac/common.h index c74bc7c9750e98..a972bee66504ba 100644 --- a/drivers/net/ethernet/stmicro/stmmac/common.h +++ b/drivers/net/ethernet/stmicro/stmmac/common.h @@ -382,6 +382,7 @@ enum dma_irq_dir { DMA_DIR_RX = 0x1, DMA_DIR_TX = 0x2, DMA_DIR_RXTX = 0x3, + DMA_DIR_ERR = 0x4, }; enum request_irq_err { diff --git a/drivers/net/ethernet/stmicro/stmmac/dwmac4_dma.h b/drivers/net/ethernet/stmicro/stmmac/dwmac4_dma.h index 43b036d4e95bdd..a7caac3c98e6cd 100644 --- a/drivers/net/ethernet/stmicro/stmmac/dwmac4_dma.h +++ b/drivers/net/ethernet/stmicro/stmmac/dwmac4_dma.h @@ -173,6 +173,11 @@ static inline u32 dma_chanx_base_addr(const struct dwmac4_addrs *addrs, DMA_CHAN_STATUS_TI | \ DMA_CHAN_STATUS_MSK_COMMON) +#define DMA_CHAN_STATUS_MSK_ERR (DMA_CHAN_STATUS_AIS | \ + DMA_CHAN_STATUS_FBE | \ + DMA_CHAN_STATUS_RPS | \ + DMA_CHAN_STATUS_RBU) + int dwmac4_dma_reset(void __iomem *ioaddr); void dwmac4_enable_dma_irq(struct stmmac_priv *priv, void __iomem *ioaddr, u32 chan, bool rx, bool tx); diff --git a/drivers/net/ethernet/stmicro/stmmac/dwmac4_lib.c b/drivers/net/ethernet/stmicro/stmmac/dwmac4_lib.c index a0249715fafafd..02aa1a3dd1e25c 100644 --- a/drivers/net/ethernet/stmicro/stmmac/dwmac4_lib.c +++ b/drivers/net/ethernet/stmicro/stmmac/dwmac4_lib.c @@ -150,6 +150,8 @@ int dwmac4_dma_interrupt(struct stmmac_priv *priv, void __iomem *ioaddr, intr_status &= DMA_CHAN_STATUS_MSK_RX; else if (dir == DMA_DIR_TX) intr_status &= DMA_CHAN_STATUS_MSK_TX; + else if (dir == DMA_DIR_ERR) + intr_status &= DMA_CHAN_STATUS_MSK_ERR; /* ABNORMAL interrupts */ if (unlikely(intr_status & DMA_CHAN_STATUS_AIS)) { diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c index 25894771e9e9f8..0bcbf837d9cc85 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c @@ -3145,6 +3145,22 @@ static int stmmac_napi_check(struct stmmac_priv *priv, u32 chan, u32 dir) return status; } +static void stmmac_dma_err_interrupt(struct stmmac_priv *priv) +{ + u8 channels_to_check = max(priv->plat->rx_queues_to_use, + priv->plat->tx_queues_to_use); + int status; + u8 chan; + + for (chan = 0; chan < channels_to_check; chan++) { + status = stmmac_dma_interrupt_status(priv, priv->ioaddr, + &priv->xstats, chan, + DMA_DIR_ERR); + if (unlikely(status & tx_hard_error)) + stmmac_global_err(priv); + } +} + /** * stmmac_dma_interrupt - DMA ISR * @priv: driver private structure @@ -6498,6 +6514,9 @@ static irqreturn_t stmmac_mac_interrupt(int irq, void *dev_id) /* To handle Common interrupts */ stmmac_common_interrupt(priv); + if (priv->plat->core_type == DWMAC_CORE_GMAC4) + stmmac_dma_err_interrupt(priv); + return IRQ_HANDLED; } From c35761f43c582460b45429f51be5c2a0f07ed9af Mon Sep 17 00:00:00 2001 From: Anthony Pighin Date: Thu, 12 Nov 2026 09:31:40 -0500 Subject: [PATCH 0775/2102] net: gianfar: clear the pending Rx skb when freeing the Rx ring gfar_clean_rx_ring() keeps a frame that spans several Rx buffers in rx_queue->skb between NAPI polls. When the interface is stopped (close, MTU change, reset), free_skb_rx_queue() frees that skb but leaves the pointer set, and nothing clears it when the rings are set up again. After the restart, gfar_clean_rx_ring() picks up the stale pointer. The first buffer it sees has RXBD_FIRST set, so the overrun handling frees the skb a second time. By then the skb has usually been reallocated, so the second free releases another owner's skb and data while they are still in use. Clear rx_queue->skb after freeing it. Hit during development, as intermittent kernel panics in our automated regression on an NXP LS1021A board (eTSEC), in an L2 Ethernet traffic test that shuts and re-enables ports. It was seen on 6.6, 6.12 and 6.18 based kernels, crashing in unrelated places such as kmem_cache_alloc() called from build_skb() in gfar_poll_rx_sq(). With the fix, the same test ran 90 bounces with no warnings or crashes. Fixes: 75354148ce69 ("gianfar: Add paged allocation and Rx S/G") Cc: stable@vger.kernel.org Signed-off-by: Anthony Pighin Reviewed-by: Daniel Machon Link: https://patch.msgid.link/20261112143140.1395197-1-anthony.pighin@nokia.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/freescale/gianfar.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/net/ethernet/freescale/gianfar.c b/drivers/net/ethernet/freescale/gianfar.c index cf636fc5aafac2..19010e08fc55fe 100644 --- a/drivers/net/ethernet/freescale/gianfar.c +++ b/drivers/net/ethernet/freescale/gianfar.c @@ -1092,6 +1092,7 @@ static void free_skb_rx_queue(struct gfar_priv_rx_q *rx_queue) struct rxbd8 *rxbdp = rx_queue->rx_bd_base; dev_kfree_skb(rx_queue->skb); + rx_queue->skb = NULL; for (i = 0; i < rx_queue->rx_ring_size; i++) { struct gfar_rx_buff *rxb = &rx_queue->rx_buff[i]; From 6e9764591bcc34705d1c7bb13b31b7e161db4110 Mon Sep 17 00:00:00 2001 From: Avi Weiss Date: Sun, 15 Nov 2026 13:42:34 +0200 Subject: [PATCH 0776/2102] net: ena: avoid double-counting TX DMA mappings on failure ena_tx_map_skb() increments tx_info->num_of_bufs after each successful DMA mapping. If a later fragment mapping fails, the error path adds the fragment index to this count before calling ena_unmap_tx_buff(). This can cause DMA unmapping of buffers that were never mapped and out-of-bounds access to the buffer array. Remove the extra increment so that cleanup uses only the number of successfully mapped buffers. Discovered by comparing the in-tree ENA driver with Amazon's standalone ENA driver. Fixes: 38005ca816a7 ("net: ena: add functions for handling Low Latency Queues in ena_netdev") Co-developed-by: Evgeny Ostrovsky Signed-off-by: Evgeny Ostrovsky Signed-off-by: Avi Weiss Reviewed-by: Daniel Machon Link: https://patch.msgid.link/20261115114233.2307630-2-thnkslprpt@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/amazon/ena/ena_netdev.c | 1 - 1 file changed, 1 deletion(-) diff --git a/drivers/net/ethernet/amazon/ena/ena_netdev.c b/drivers/net/ethernet/amazon/ena/ena_netdev.c index ecc6f1d827f9cf..560b20a5861c8a 100644 --- a/drivers/net/ethernet/amazon/ena/ena_netdev.c +++ b/drivers/net/ethernet/amazon/ena/ena_netdev.c @@ -2609,7 +2609,6 @@ static int ena_tx_map_skb(struct ena_ring *tx_ring, tx_info->skb = NULL; - tx_info->num_of_bufs += i; ena_unmap_tx_buff(tx_ring, tx_info); return -EINVAL; From c5e5ac57b559962498886435394b9cbcef20d553 Mon Sep 17 00:00:00 2001 From: Wajeeh Atrash Date: Sun, 15 Nov 2026 13:42:40 +0200 Subject: [PATCH 0777/2102] net: ena: set admin device pointer before queue allocations On the first probe, ena_com_admin_init() allocates the completion contexts and admin SQ/CQ buffers before setting admin_queue->ena_dev. Their allocation failure paths log through this pointer, which is still NULL. A failed allocation therefore dereferences NULL instead of returning -ENOMEM. Set admin_queue->ena_dev before the first allocation so the helpers can log errors and return -ENOMEM normally. This issue has already been fixed in Amazon's standalone ENA driver (commit 7d1dc4341d4f). Fixes: da580ca8de2c ("net: ena: add device distinct log prefix to files") Signed-off-by: Wajeeh Atrash Signed-off-by: Avi Weiss Link: https://patch.msgid.link/20261115114239.2308017-2-thnkslprpt@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/amazon/ena/ena_com.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/ethernet/amazon/ena/ena_com.c b/drivers/net/ethernet/amazon/ena/ena_com.c index 297fb36ab8c16f..9b14cddf4432ee 100644 --- a/drivers/net/ethernet/amazon/ena/ena_com.c +++ b/drivers/net/ethernet/amazon/ena/ena_com.c @@ -1992,6 +1992,7 @@ int ena_com_admin_init(struct ena_com_dev *ena_dev, admin_queue->q_depth = ENA_ADMIN_QUEUE_DEPTH; + admin_queue->ena_dev = ena_dev; admin_queue->q_dmadev = ena_dev->dmadev; admin_queue->polling = false; admin_queue->curr_cmd_id = 0; @@ -2045,7 +2046,6 @@ int ena_com_admin_init(struct ena_com_dev *ena_dev, if (ret) goto error; - admin_queue->ena_dev = ena_dev; admin_queue->running_state = true; return 0; From 728a2abd15a767f662a44030931ea7b2959b4e88 Mon Sep 17 00:00:00 2001 From: Nathan Chancellor Date: Sat, 14 Nov 2026 21:30:07 -0700 Subject: [PATCH 0778/2102] mptcp: Avoid unsequenced accesses to jiffies in mptcp_reset_tout_timer() After a recent improvement in clang to warn on unsequenced accesses to volatile variables [1], an instance appears in mptcp_reset_tout_timer(), which can break the build with CONFIG_WERROR=y / W=e: net/mptcp/protocol.c:3044:20: error: unsequenced accesses to volatile qualified 'jiffies' [-Werror,-Wunsequenced] 3044 | tcp_jiffies32 + jiffies + mptcp_close_timeout(sk); | ~~~~~~~~~~~~~ ^ Per C11 5.1.2.3.2, accessing a volatile object is a side effect. Per C11 6.5.2, unsequenced side effects on the same scalar object are undefined behavior. Per C11 6.5.3, unless otherwise specified, side effects and value computations of subexpressions are unsequenced within expressions. Add an explicit sequence point by splitting the addition expression in half, eliminating the undefined behavior and clearing up the warning. Cc: stable@vger.kernel.org Fixes: 76a13b315709 ("mptcp: invoke MP_FAIL response when needed") Closes: https://github.com/ClangBuiltLinux/linux/issues/2193 Link: https://github.com/llvm/llvm-project/commit/955715460eaf9188c241c74750637fc82dfcc423 [1] Signed-off-by: Nathan Chancellor Reviewed-by: Matthieu Baerts (NGI0) Link: https://patch.msgid.link/20261114-mptcp-wunsequenced-v1-1-707a73a6c172@kernel.org Signed-off-by: Jakub Kicinski --- net/mptcp/protocol.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/net/mptcp/protocol.c b/net/mptcp/protocol.c index 8968db58083ef4..8a9efebf34979b 100644 --- a/net/mptcp/protocol.c +++ b/net/mptcp/protocol.c @@ -3041,7 +3041,8 @@ void mptcp_reset_tout_timer(struct mptcp_sock *msk, unsigned long fail_tout) return; close_timeout = (unsigned long)inet_csk(sk)->icsk_mtup.probe_timestamp - - tcp_jiffies32 + jiffies + mptcp_close_timeout(sk); + tcp_jiffies32; + close_timeout += jiffies + mptcp_close_timeout(sk); /* the close timeout takes precedence on the fail one, and here at least one of * them is active From cf704cc62ffaf9206f1cbc12c2a3baec316b0ac1 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolenko Date: Thu, 12 Nov 2026 16:58:20 -0800 Subject: [PATCH 0779/2102] net: e1000: fix warning in iounmap on probe failure In e1000_probe(), the error unwinding path at err_sw_init unconditionally calls iounmap(hw->ce4100_gbe_mdio_base_virt). On non-CE4100 hardware, hw->ce4100_gbe_mdio_base_virt remains NULL. Passing NULL to iounmap() triggers a WARN_ON_ONCE on x86 architectures. Furthermore, on CE4100 hardware, if probe fails before or during MDIO mapping, ce4100_gbe_mdio_base_virt is also NULL. Fix this by adding a NULL pointer check before calling iounmap() on hw->ce4100_gbe_mdio_base_virt. iounmap(hw->hw_addr) remains unconditional because every code path reaching err_sw_init occurs after hw->hw_addr has been successfully mapped. Reported-by: syzbot+ca1ef9e2e234b8d3599b@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=ca1ef9e2e234b8d3599b Fixes: 13acde8fffc0 ("e1000: cleanup CE4100 MDIO registers access") Cc: stable@vger.kernel.org Signed-off-by: Svyatoslav Nikolenko Reviewed-by: Aleksandr Loktionov Signed-off-by: Tony Nguyen Link: https://patch.msgid.link/20261113005823.130021-4-anthony.l.nguyen@intel.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/intel/e1000/e1000_main.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/intel/e1000/e1000_main.c b/drivers/net/ethernet/intel/e1000/e1000_main.c index d7f5c6f1614206..d7e279b739b8d4 100644 --- a/drivers/net/ethernet/intel/e1000/e1000_main.c +++ b/drivers/net/ethernet/intel/e1000/e1000_main.c @@ -1227,7 +1227,8 @@ static int e1000_probe(struct pci_dev *pdev, const struct pci_device_id *ent) kfree(adapter->rx_ring); err_dma: err_sw_init: - iounmap(hw->ce4100_gbe_mdio_base_virt); + if (hw->ce4100_gbe_mdio_base_virt) + iounmap(hw->ce4100_gbe_mdio_base_virt); iounmap(hw->hw_addr); err_ioremap: disable_dev = !test_and_set_bit(__E1000_DISABLED, &adapter->flags); From 9c9863f9b9f120b771a908849157791a32eadb02 Mon Sep 17 00:00:00 2001 From: Zxyan Zhu Date: Sat, 14 Nov 2026 09:55:54 +0800 Subject: [PATCH 0780/2102] net: stmmac: re-enable on-chip parity checkers for XGMAC ASP 0x2 Commit 669a55560e4b ("net: stmmac: Check more MAC HW features for XGMAC Core 3.20") made dwxgmac3_safety_feat_config() bail out early for asp == 0x2, assuming that configuration has no parity protection. Per the DWC_xgmac databook, the ASP field of MAC_HW_Feature3 selects: 0x1 (AS_EPPE): all automotive safety features, with ECC and parity ports on the external application interface 0x2 (AS_NEPPE): all automotive safety features, without ECC or parity ports on the external application interface 0x3 (AS_PPE): all automotive safety features, with parity ports on the external application interface The reset value of the field is defined as: (DWCXG_ASP_ALL && DWCXG_ASP_PPE == 1) ? "3" : (DWCXG_ASP_ALL && DWCXG_ASP_PPE == 0) ? "2" : (DWCXG_ASP_ALL && DWCXG_ASP_PPE == 2) ? "1" : "0" so ASP 0x2 implies DWCXG_ASP_ALL = 1, where the internal FSM state parity and timeout (MAC_FSM_Control) and the on-chip data-path parity (MTL_DPP_CONTROL) features exist; only the ports on the external application interface are absent. The early return therefore skips enabling safety checkers that are present in the hardware. Drop 0x2 from the condition so the FSM and data-path parity checkers are enabled again. Also update the safety feature descriptions printed by stmmac_dma_cap_show() to spell out that ASP 0x1/0x2/0x3 differ only in the ECC or parity ports on the external application interface; the previous wording, "All Safety Features without ECC or Parity", suggests the on-chip checkers are absent from an ASP 0x2 device. Keep the early return for ASP 0x4 (EASP), which selects only ECC protection for external memory and has no on-chip parity features. Tested on XGMAC 3.10 and 3.40 cores. Fixes: 669a55560e4b ("net: stmmac: Check more MAC HW features for XGMAC Core 3.20") Cc: stable@vger.kernel.org Signed-off-by: Zxyan Zhu Reviewed-by: Maxime Chevallier Reviewed-by: Nicolai Buchwitz Link: https://patch.msgid.link/20261114015554.2187341-1-zxyan0222@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/stmicro/stmmac/dwxgmac2_core.c | 6 +++--- drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_core.c b/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_core.c index 1a88cbaed70ca1..6b2bfc2411098a 100644 --- a/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_core.c +++ b/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_core.c @@ -859,10 +859,10 @@ dwxgmac3_safety_feat_config(void __iomem *ioaddr, unsigned int asp, value |= XGMAC_TCEIE; /* TSO Memory Correctable Error */ writel(value, ioaddr + XGMAC_DMA_ECC_INT_ENABLE); - /* 0x2: Without ECC or Parity Ports on External Application Interface - * 0x4: Only ECC Protection for External Memory feature is selected + /* 0x4: Only ECC Protection for External Memory feature is + * selected, without any on-chip parity protection */ - if (asp == 0x2 || asp == 0x4) + if (asp == 0x4) return 0; /* 4. Enable Parity and Timeout for FSM */ diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c index 0bcbf837d9cc85..ee63f5ecf57018 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c @@ -6760,9 +6760,9 @@ static int stmmac_dma_cap_show(struct seq_file *seq, void *v) }; static const char * const dwxgmac_safety_feature_desc[] = { "No", - "All Safety Features with ECC and Parity", - "All Safety Features without ECC or Parity", - "All Safety Features with Parity Only", + "All Safety Features with ECC and Parity Ports on External Application Interface", + "All Safety Features without ECC or Parity Ports on External Application Interface", + "All Safety Features with Parity Ports on External Application Interface", "ECC Only", "UNDEFINED", "UNDEFINED", From 0dcf21648f258d2be36def2aacc8c7ee5e15e2ee Mon Sep 17 00:00:00 2001 From: Ali Tariq Date: Fri, 13 Nov 2026 18:24:34 +0500 Subject: [PATCH 0781/2102] net: spacemit: Fix TX timeout work deadlocking on itself emac_tx_timeout_task() takes RTNL and calls dev_close(), which ends up waiting for the work itself. The function call hierarchy is as follows emac_tx_timeout_task() dev_close() emac_stop() emac_down() cancel_work_sync(&priv->tx_timeout_task) The work never finishes and keeps RTNL held, so after a TX timeout everything that needs RTNL hangs. Remove cancel_work_sync() from emac_down(). Disable the work in emac_suspend() instead, and enable it again in emac_resume(). emac_remove() runs before the devm-managed unregister_netdev(), so use disable_work_sync() there to stop the work from being queued again. Found by code inspection. Not reproduced on hardware. Tested on Orange Pi RV2 (SpacemiT K1) with suspend/resume cycles and kselftest, with lockdep enabled. Fixes: bfec6d7f2001 ("net: spacemit: Add K1 Ethernet MAC") Reported-by: Troy Mitchell Closes: https://lore.kernel.org/all/DMO74K2MG3D7.15UUOU1O66K6N@linux.spacemit.com/ Suggested-by: Vivian Wang Signed-off-by: Ali Tariq Reviewed-by: Vivian Wang Reviewed-by: Muhammad Bilal Link: https://patch.msgid.link/20261113132435.434615-2-alitariq45892@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/spacemit/k1_emac.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/drivers/net/ethernet/spacemit/k1_emac.c b/drivers/net/ethernet/spacemit/k1_emac.c index 71a80838bffd0b..51edc95f54c88d 100644 --- a/drivers/net/ethernet/spacemit/k1_emac.c +++ b/drivers/net/ethernet/spacemit/k1_emac.c @@ -1732,7 +1732,6 @@ static int emac_down(struct emac_priv *priv) napi_disable(&priv->napi); timer_delete_sync(&priv->txtimer); - cancel_work_sync(&priv->tx_timeout_task); timer_delete_sync(&priv->stats_timer); @@ -2010,8 +2009,9 @@ static void emac_remove(struct platform_device *pdev) { struct emac_priv *priv = platform_get_drvdata(pdev); + disable_work_sync(&priv->tx_timeout_task); + timer_shutdown_sync(&priv->txtimer); - cancel_work_sync(&priv->tx_timeout_task); timer_shutdown_sync(&priv->stats_timer); @@ -2024,6 +2024,8 @@ static int emac_resume(struct device *dev) struct net_device *ndev = priv->ndev; int ret; + enable_work(&priv->tx_timeout_task); + ret = clk_prepare_enable(priv->bus_clk); if (ret < 0) { dev_err(dev, "Failed to enable bus clock: %d\n", ret); @@ -2051,6 +2053,8 @@ static int emac_suspend(struct device *dev) struct emac_priv *priv = dev_get_drvdata(dev); struct net_device *ndev = priv->ndev; + disable_work_sync(&priv->tx_timeout_task); + if (!ndev || !netif_running(ndev)) { clk_disable_unprepare(priv->bus_clk); return 0; From f60eae61466cca9b50690bd3f2b5b4b2397d9376 Mon Sep 17 00:00:00 2001 From: Ali Tariq Date: Fri, 13 Nov 2026 18:24:35 +0500 Subject: [PATCH 0782/2102] net: spacemit: Hold RTNL lock in emac_resume() and emac_suspend() The emac_resume() calls the emac_open() and emac_suspend() calls emac_stop() functions directly without holding the lock through rtnl_lock(). These functions rely on phy_disconnect() which reads pointer with rtnl_dereference(). But since no lock is being held, rtnl_dereference throws a suspicious RCU usage on Orange Pi RV2 (SpacemiT K1) warning when lockdep is enabled. WARNING: suspicious RCU usage drivers/net/phy/phy_device.c:1831 suspicious rcu_dereference_protected() usage! Call Trace: phy_detach_internal+0x490/0x5f2 phy_disconnect+0x90/0xc0 emac_stop+0x114/0x626 emac_suspend+0xac/0x126 platform_pm_suspend+0x72/0xe4 Take RTNL in emac_suspend() and emac_resume() before the netif_running() checks, so the interface can't be opened or closed between the check and emac_stop() or emac_open(). Found by CI suspend tests on Orange Pi RV2 (SpacemiT K1). Tested on the same board with lockdep enabled: 12 suspend/resume cycles without the warning, and kselftest with no new failures. Fixes: bfec6d7f2001 ("net: spacemit: Add K1 Ethernet MAC") Signed-off-by: Ali Tariq Reviewed-by: Vivian Wang Reviewed-by: Muhammad Bilal Link: https://patch.msgid.link/20261113132435.434615-3-alitariq45892@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/spacemit/k1_emac.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/spacemit/k1_emac.c b/drivers/net/ethernet/spacemit/k1_emac.c index 51edc95f54c88d..d07d8a1aa5ee01 100644 --- a/drivers/net/ethernet/spacemit/k1_emac.c +++ b/drivers/net/ethernet/spacemit/k1_emac.c @@ -2031,11 +2031,16 @@ static int emac_resume(struct device *dev) dev_err(dev, "Failed to enable bus clock: %d\n", ret); return ret; } + rtnl_lock(); - if (!netif_running(ndev)) + if (!netif_running(ndev)) { + rtnl_unlock(); return 0; + } ret = emac_open(ndev); + rtnl_unlock(); + if (ret) { clk_disable_unprepare(priv->bus_clk); return ret; @@ -2055,12 +2060,16 @@ static int emac_suspend(struct device *dev) disable_work_sync(&priv->tx_timeout_task); + rtnl_lock(); + if (!ndev || !netif_running(ndev)) { + rtnl_unlock(); clk_disable_unprepare(priv->bus_clk); return 0; } emac_stop(ndev); + rtnl_unlock(); clk_disable_unprepare(priv->bus_clk); netif_device_detach(ndev); From 0a3778b93be43f80ac529a1305a521ac55207a95 Mon Sep 17 00:00:00 2001 From: Kalpesh Solanki Date: Thu, 12 Nov 2026 18:40:55 +0530 Subject: [PATCH 0783/2102] tun: disallow setting ARPHRD_MCTP link type via TUNSETLINK When an IFF_TUN device is registered as ARPHRD_NONE, mctp_register() attaches an mctp_dev context to it. For ARPHRD_NONE and ARPHRD_LOOPBACK devices, incoming packets in mctp_pkttype_receive() invoke __mctp_cb(skb), which initializes cb->magic = 0x4d435450 and zeros cb->halen. If a userspace process sets the link type of the TUN device to ARPHRD_MCTP via ioctl(fd, TUNSETLINK, ARPHRD_MCTP) and transmits a frame carrying protocol ETH_P_MCTP, mctp_pkttype_receive() evaluates dev->type == ARPHRD_MCTP and calls mctp_cb(skb). Because frames allocated in tun_get_user() have a cleared skb->cb and were not constructed by an MCTP hardware driver, mctp_cb() trips: WARN_ON(cb->magic != 0x4d435450); On systems configured with panic_on_warn=1, an unprivileged user in a user+net namespace can trigger a denial-of-service kernel panic. MCTP communication over TUN interfaces is designed to use ARPHRD_NONE. Setting ARPHRD_MCTP on TUN is invalid and has never functioned. Disallow ARPHRD_MCTP in TUNSETLINK by returning -EINVAL. Fixes: ff4cc3ac93e1 ("[TUNTAP]: Allow setting the linktype of the tap device from userspace") Signed-off-by: Kalpesh Solanki Link: https://patch.msgid.link/20261112131056.234801-1-skalpesh942@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/tun.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/net/tun.c b/drivers/net/tun.c index 86fd44e1075506..d4870bdc156f4c 100644 --- a/drivers/net/tun.c +++ b/drivers/net/tun.c @@ -3375,7 +3375,8 @@ static long __tun_chr_ioctl(struct file *file, unsigned int cmd, ret = -EBUSY; } else if ((unsigned short)arg == ARPHRD_IEEE802154 || (unsigned short)arg == ARPHRD_IEEE802154_MONITOR || - (unsigned short)arg == ARPHRD_6LOWPAN) { + (unsigned short)arg == ARPHRD_6LOWPAN || + (unsigned short)arg == ARPHRD_MCTP) { ret = -EINVAL; } else { ret = call_netdevice_notifiers(NETDEV_PRE_TYPE_CHANGE, From ff1ee9cc8993b1e5cf6459108dba1576fee221d0 Mon Sep 17 00:00:00 2001 From: Gal Pressman Date: Sun, 15 Nov 2026 09:29:34 +0200 Subject: [PATCH 0784/2102] net/mlx5e: Fix XSK pool corruption when switching channels When the device supports tis_tir_td_order, mlx5e_safe_switch_params() closes the old channels only after the new ones are activated. With an AF_XDP socket bound, the old and the new channel hold an XSK RQ on the same pool. The old RQ returns its buffers to the pool while the new RQ is already allocating from it. Since the pool is lockless and expects a single user at a time, it gets out of sync. Close the old XSK queues before activating the new channels, the rest of the old channels can still be closed later. The crash was hit by our regression tests, with a random sequence of binding xdpsock to every queue and later changing the ring size. This resolves the following call trace: BUG: kernel NULL pointer dereference, address: 0000000000000068 RIP: 0010:mlx5e_free_rx_mpwqe+0x113/0x250 [mlx5_core] Call Trace: mlx5e_dealloc_rx_mpwqe+0x38/0xb0 [mlx5_core] mlx5e_free_rx_descs+0x126/0x170 [mlx5_core] mlx5e_close_rq+0x81/0xb0 [mlx5_core] mlx5e_close_channels+0x4b/0xa0 [mlx5_core] mlx5e_safe_switch_params+0x34d/0x3e0 [mlx5_core] mlx5e_xdp_set+0x287/0x3a0 [mlx5_core] dev_xdp_install+0x269/0x400 Fixes: 3b88a535a8e1 ("net/mlx5e: Defer channels closure to reduce interface down time") Signed-off-by: Gal Pressman Reviewed-by: Nimrod Oren Signed-off-by: Tariq Toukan Link: https://patch.msgid.link/20261115072934.353341-1-tariqt@nvidia.com Signed-off-by: Jakub Kicinski --- .../net/ethernet/mellanox/mlx5/core/en_main.c | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c index d8563f86384473..227695dfa51dfa 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c @@ -3421,6 +3421,23 @@ static int mlx5e_switch_priv_params(struct mlx5e_priv *priv, return 0; } +/* The old and the new channel of the same index are bound to the same + * XSK pool, which is lockless and expects a single user at a time. + * Close the old XSK queues before the new ones are activated, even + * when the closure of the rest of the old channels is deferred. + */ +static void mlx5e_close_channels_xsk(struct mlx5e_channels *chs) +{ + int i; + + for (i = 0; i < chs->num; i++) { + struct mlx5e_channel *c = chs->c[i]; + + if (test_bit(MLX5E_CHANNEL_STATE_XSK, c->state)) + mlx5e_close_xsk(c); + } +} + static int mlx5e_switch_priv_channels(struct mlx5e_priv *priv, struct mlx5e_channels *old_chs, struct mlx5e_channels *new_chs, @@ -3452,6 +3469,8 @@ static int mlx5e_switch_priv_channels(struct mlx5e_priv *priv, mlx5e_set_xdp_feature(priv); if (!MLX5_CAP_GEN(priv->mdev, tis_tir_td_order)) mlx5e_close_channels(old_chs); + else + mlx5e_close_channels_xsk(old_chs); priv->profile->update_rx(priv); mlx5e_selq_apply(&priv->selq); From 5ec918f8d66a0311c52cc767ade67e7019beb176 Mon Sep 17 00:00:00 2001 From: Nathan Chancellor Date: Sat, 14 Nov 2026 21:38:26 -0700 Subject: [PATCH 0785/2102] net: microchip: encx24j600: Avoid unsequenced accesses to jiffies in encx24j600_tx() After a recent improvement in clang to warn on unsequenced accesses to volatile variables [1], an instance appears in encx24j600_tx(), which can break the build with CONFIG_WERROR=y / W=e: drivers/net/ethernet/microchip/encx24j600.c:898:14: error: unsequenced accesses to volatile qualified 'jiffies' [-Werror,-Wunsequenced] 898 | jiffies, jiffies - dev_trans_start(dev)); | ~~~~~~~ ^ Per C11 5.1.2.3.2, accessing a volatile object is a side effect. Per C11 6.5.2, unsequenced side effects on the same scalar object are undefined behavior. Per C11 6.5.2.2.10/12, the evaluation of arguments in a function call is indeterminately sequenced, meaning any side effects in the arguments are unsequenced. Add a local variable to hold the value of jiffies before the function call so that there are no unsequenced side effects, clearing up the warning. Cc: stable@vger.kernel.org Fixes: 04fbfce7a222 ("net: Microchip encx24j600 driver") Closes: https://github.com/ClangBuiltLinux/linux/issues/2196 Link: https://github.com/llvm/llvm-project/commit/955715460eaf9188c241c74750637fc82dfcc423 [1] Signed-off-by: Nathan Chancellor Reviewed-by: Andrew Lunn Link: https://patch.msgid.link/20261114-encx24j600-wunsequenced-v1-1-c978fc36cacd@kernel.org Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/microchip/encx24j600.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/microchip/encx24j600.c b/drivers/net/ethernet/microchip/encx24j600.c index b011bf5c2305c8..ebc067cb2c9d28 100644 --- a/drivers/net/ethernet/microchip/encx24j600.c +++ b/drivers/net/ethernet/microchip/encx24j600.c @@ -893,9 +893,10 @@ static netdev_tx_t encx24j600_tx(struct sk_buff *skb, struct net_device *dev) static void encx24j600_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct encx24j600_priv *priv = netdev_priv(dev); + unsigned long j = jiffies; netif_err(priv, tx_err, dev, "TX timeout at %ld, latency %ld\n", - jiffies, jiffies - dev_trans_start(dev)); + j, j - dev_trans_start(dev)); dev->stats.tx_errors++; netif_wake_queue(dev); From 695d0824cb6b27ff1a1cdeabb2d5138f00b15251 Mon Sep 17 00:00:00 2001 From: Nathan Chancellor Date: Sun, 15 Nov 2026 21:45:22 -0700 Subject: [PATCH 0786/2102] qca_spi: Avoid unsequenced accesses to jiffies in qcaspi_netdev_tx_timeout() After a recent improvement in clang to warn on unsequenced accesses to volatile variables [1], an instance appears in qcaspi_netdev_tx_timeout(), which can break the build with CONFIG_WERROR=y / W=e: drivers/net/ethernet/qualcomm/qca_spi.c:805:16: error: unsequenced accesses to volatile qualified 'jiffies' [-Werror,-Wunsequenced] 805 | jiffies, jiffies - dev_trans_start(dev)); | ~~~~~~~ ^ Per C11 5.1.2.3.2, accessing a volatile object is a side effect. Per C11 6.5.2, unsequenced side effects on the same scalar object are undefined behavior. Per C11 6.5.2.2.10/12, the evaluation of arguments in a function call is indeterminately sequenced, meaning any side effects in the arguments are unsequenced. Printing jiffies on its own is not that useful for debugging transmit timeouts, so get rid of it to clear up the warning. Cc: stable@vger.kernel.org Fixes: 291ab06ecf67 ("net: qualcomm: new Ethernet over SPI driver for QCA7000") Closes: https://github.com/ClangBuiltLinux/linux/issues/2197 Link: https://github.com/llvm/llvm-project/commit/955715460eaf9188c241c74750637fc82dfcc423 [1] Signed-off-by: Nathan Chancellor Acked-by: Stefan Wahren Reviewed-by: Nick Desaulniers Link: https://patch.msgid.link/20261115-qca_spi-wunsequenced-v2-1-8cf32f12d546@kernel.org Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/qualcomm/qca_spi.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/net/ethernet/qualcomm/qca_spi.c b/drivers/net/ethernet/qualcomm/qca_spi.c index 38a779f4b866ca..249b4b549a12b4 100644 --- a/drivers/net/ethernet/qualcomm/qca_spi.c +++ b/drivers/net/ethernet/qualcomm/qca_spi.c @@ -801,8 +801,8 @@ qcaspi_netdev_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct qcaspi *qca = netdev_priv(dev); - netdev_info(qca->net_dev, "Transmit timeout at %ld, latency %ld\n", - jiffies, jiffies - dev_trans_start(dev)); + netdev_info(qca->net_dev, "Transmit timeout, latency %ld\n", + jiffies - dev_trans_start(dev)); qca->net_dev->stats.tx_errors++; /* Trigger tx queue flush and QCA7000 reset */ set_bit(SPI_RESET, &qca->flags); From 98382d41f92f048cf3cbb7af415f48a722b19ebc Mon Sep 17 00:00:00 2001 From: Daniel Wade Date: Sun, 15 Nov 2026 23:32:11 +1030 Subject: [PATCH 0787/2102] net: bridge: fix skb leak of reinjected link-local frames br_handle_frame() passes the link-local frames it neither forwards nor delivers (01:80:c2:00:00:02 to 0d and 0f, unless set in the group forward mask) through NF_HOOK() at NF_BR_LOCAL_IN. Since commit 3b2e2904deb3 ("net: bridge: fix per-port af_packet sockets") the okfn only learns the source and returns 1, which becomes RX_HANDLER_PASS. That commit sent the nf_queue case to RX_HANDLER_CONSUMED, which is right for the synchronous return, but the frame comes back: on reinjection nf_reinject() calls the okfn and ignores its return value, because every other okfn consumes the skb. This one no longer does, so nothing frees the frame. NFQA_CFG_F_FAIL_OPEN leaks it the same way with no verdict at all, when the queue or the listener's socket is full. Each frame leaks an skb, and one sent from a local socket keeps that socket charged, so neither it nor the network namespace holding it is freed. Bridge, rule and queue need only CAP_NET_ADMIN in a netns, so with user namespaces an unprivileged user can exhaust kernel memory. nf_reinject() cannot free the skb on a 1 from the okfn, because other okfns return NET_RX_DROP, which is 1, after freeing it. Call nf_hook() instead of NF_HOOK() and do the learning and the RX_HANDLER_PASS return in br_handle_frame() on 1, as the 0x00 and 0x0e cases already do and as vrf_rcv_nfhook() does. The okfn then runs only for a reinjected frame, which br_handle_frame() has already reported consumed and cannot pass on the port, so it learns from the frame and frees it. These frames were not delivered before this change either. Also set *pskb before the new RX_HANDLER_PASS, as the other such returns do; skb_share_check() may have replaced the skb, and the commit above added that return without the assignment. Discovered by an AI code review agent and reproduced on unmodified mainline under KASAN: an unprivileged user in a new user and network namespace bridged a veth, queued link-local frames to an NFQUEUE listener that accepted every one, and leaked an skb per frame. With this patch the reinjected frames are freed and nothing leaks. Fixes: 3b2e2904deb3 ("net: bridge: fix per-port af_packet sockets") Cc: stable@vger.kernel.org Signed-off-by: Daniel Wade Reviewed-by: Xia Yan Acked-by: Nikolay Aleksandrov Link: https://patch.msgid.link/20261115130211.7724-1-danjwade95@gmail.com Signed-off-by: Jakub Kicinski --- net/bridge/br_input.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/net/bridge/br_input.c b/net/bridge/br_input.c index fc2e381c4fe039..b5bd9d6808fd97 100644 --- a/net/bridge/br_input.c +++ b/net/bridge/br_input.c @@ -257,13 +257,18 @@ static void __br_handle_local_finish(struct sk_buff *skb) br_fdb_update(p->br, p, vlan, eth_hdr(skb)->h_source, 0); } -/* note: already called with rcu_read_lock */ +/* okfn of the link-local NF_BR_LOCAL_IN hook in br_handle_frame(). It is + * only called when a queued frame is reinjected, after br_handle_frame() + * returned RX_HANDLER_CONSUMED for it, so the frame can no longer be + * passed up on the port and has to be freed here. + * note: already called with rcu_read_lock + */ static int br_handle_local_finish(struct net *net, struct sock *sk, struct sk_buff *skb) { __br_handle_local_finish(skb); + kfree_skb(skb); - /* return 1 to signal the okfn() was called so it's ok to use the skb */ - return 1; + return 0; } static int nf_hook_bridge_pre(struct sk_buff *skb, struct sk_buff **pskb) @@ -424,11 +429,14 @@ static rx_handler_result_t br_handle_frame(struct sk_buff **pskb) /* The else clause should be hit when nf_hook(): * - returns < 0 (drop/error) * - returns = 0 (stolen/nf_queue) - * Thus return 1 from the okfn() to signal the skb is ok to pass + * On 1 the frame is passed on here. The okfn() only runs if a + * queued frame is reinjected later, and must consume it then. */ - if (NF_HOOK(NFPROTO_BRIDGE, NF_BR_LOCAL_IN, + if (nf_hook(NFPROTO_BRIDGE, NF_BR_LOCAL_IN, dev_net(skb->dev), NULL, skb, skb->dev, NULL, br_handle_local_finish) == 1) { + *pskb = skb; + __br_handle_local_finish(skb); return RX_HANDLER_PASS; } else { return RX_HANDLER_CONSUMED; From 81d2cf1c6d567260e3195d2ef049f44446a462a7 Mon Sep 17 00:00:00 2001 From: Daniel Machon Date: Mon, 16 Nov 2026 10:56:04 +0100 Subject: [PATCH 0788/2102] net: sparx5: fix RX ring stall on frames from inactive ports If the source port of a received frame does not map to a port with a netdev, sparx5_fdma_rx_get_frame() returns false without consuming the DB. The DB keeps its DONE bit, so every following poll picks the same DB and grows its skb with skb_put() again. This ends in skb_over_panic(), or in an RX stall if no more frames arrive. Drop the frame and return true, so that the DB is consumed like any other. Remove the extraction queue flush, as the FDMA has already extracted the frame, and ratelimit the error, as the source port comes from the hardware. Confirmed on Sparx5 (PCB135) with a kernel modified to give received frames an out-of-range source port, which made the board reset. The fix was tested the same way: only the bad frames are dropped. Fixes: 10615907e9b5 ("net: sparx5: switchdev: adding frame DMA functionality") Reported-by: Zhang Hewei Closes: https://lore.kernel.org/netdev/tencent_ACC296C1F221C304053BD0F1F4B0D2C2BA06@qq.com/ Signed-off-by: Daniel Machon Link: https://patch.msgid.link/20261116-sparx5-rx-inactive-port-v1-1-343d8bab58bb@microchip.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c b/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c index 15ec9b053824f5..8675702bf1504e 100644 --- a/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c +++ b/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c @@ -157,9 +157,15 @@ static bool sparx5_fdma_rx_get_frame(struct sparx5 *sparx5, struct sparx5_rx *rx sparx5->ports[fi.src_port] : NULL; if (!port || !port->ndev) { - dev_err(sparx5->dev, "Data on inactive port %d\n", fi.src_port); - sparx5_xtr_flush(sparx5, XTR_QUEUE); - return false; + dev_err_ratelimited(sparx5->dev, "Data on inactive port %d\n", + fi.src_port); + + /* Drop the frame, but report the DB as consumed so the + * caller advances past it and recycles the DCB. + */ + kfree_skb(skb); + + return true; } skb->dev = port->ndev; skb_pull(skb, IFH_LEN * sizeof(u32)); From 1a47bc214d00fbfaeb9a963a8aac2e4e58d36e71 Mon Sep 17 00:00:00 2001 From: Daniel Machon Date: Mon, 16 Nov 2026 10:56:05 +0100 Subject: [PATCH 0789/2102] net: lan969x: fix RX ring stall on frames from inactive ports If the source port of a received frame does not map to an active port, or build_skb() fails, lan969x_fdma_rx_get_frame() returns the page to the page_pool and returns NULL, and the NAPI poll loop breaks without advancing past the DB. The DB keeps its DONE bit, so every following poll returns the same page to the page_pool again, and RX stops on all ports. Drop the frame and advance past the DB like for any other frame, and replace the WARN_ON() with a ratelimited error, as the source port comes from the hardware. Confirmed on lan969x (EV23X71A) with a kernel modified to give received frames an out-of-range source port, which stopped RX on all ports. The fix was tested the same way: only the bad frames are dropped. Fixes: d84ad2c0d80c ("net: lan969x: add FDMA implementation") Reported-by: Zhang Hewei Closes: https://lore.kernel.org/netdev/tencent_ACC296C1F221C304053BD0F1F4B0D2C2BA06@qq.com/ Signed-off-by: Daniel Machon Link: https://patch.msgid.link/20261116-sparx5-rx-inactive-port-v1-2-343d8bab58bb@microchip.com Signed-off-by: Jakub Kicinski --- .../ethernet/microchip/sparx5/lan969x/lan969x_fdma.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c b/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c index 053d125eda6584..fd532c89f91100 100644 --- a/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c +++ b/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c @@ -113,8 +113,11 @@ static struct sk_buff *lan969x_fdma_rx_get_frame(struct sparx5 *sparx5, sparx5_ifh_parse(sparx5, page_address(page), &fi); port = fi.src_port < consts->n_ports ? sparx5->ports[fi.src_port] : NULL; - if (WARN_ON(!port)) + if (!port) { + dev_err_ratelimited(sparx5->dev, "Data on inactive port %d\n", + fi.src_port); goto free_page; + } skb = build_skb(page_address(page), fdma->db_size); if (unlikely(!skb)) @@ -258,10 +261,8 @@ int lan969x_fdma_napi_poll(struct napi_struct *napi, int weight) break; skb = lan969x_fdma_rx_get_frame(sparx5, rx); - if (!skb) - break; - - napi_gro_receive(&rx->napi, skb); + if (skb) + napi_gro_receive(&rx->napi, skb); fdma_db_advance(fdma); counter++; From 2c0d5e36aaf3cee1bc53c761704202b845be54d6 Mon Sep 17 00:00:00 2001 From: Siddharth Chintamaneni Date: Sat, 14 Nov 2026 16:26:31 +0000 Subject: [PATCH 0790/2102] af_unix: Fix scm_stat.nr_fds leak in unix_dgram_disconnected(). When a connected SOCK_DGRAM socket disconnects (e.g. via connect() with AF_UNSPEC), reconnects to a different peer, or observes a dead peer in unix_dgram_sendmsg(), unix_dgram_disconnected() purges all unread datagrams from sk->sk_receive_queue via skb_queue_purge_reason(). Because skb_queue_purge_reason() frees each skb without calling scm_stat_del(sk, skb), any SCM_RIGHTS file descriptors attached to the purged skbs remain permanently accounted in u->scm_stat.nr_fds (reported as scm_fds in /proc//fdinfo/) for the remaining lifetime of the socket. Move scm_stat_add() and scm_stat_del() above unix_dgram_disconnected(), splice sk->sk_receive_queue onto a local list under the queue lock, and call scm_stat_del() before kfree_skb_reason() on each purged skb. Fixes: 3c32da19a858 ("unix: Show number of pending scm files of receive queue in fdinfo") Signed-off-by: Siddharth Chintamaneni Reviewed-by: Kuniyuki Iwashima Link: https://patch.msgid.link/20261114162632.16346-2-sidchintamaneni@gmail.com Signed-off-by: Jakub Kicinski --- net/unix/af_unix.c | 59 +++++++++++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 24 deletions(-) diff --git a/net/unix/af_unix.c b/net/unix/af_unix.c index f847cf1fbeafec..91c1d6cad4974c 100644 --- a/net/unix/af_unix.c +++ b/net/unix/af_unix.c @@ -609,6 +609,28 @@ static void unix_write_space(struct sock *sk) rcu_read_unlock(); } +static void scm_stat_add(struct sock *sk, struct sk_buff *skb) +{ + struct scm_fp_list *fp = UNIXCB(skb).fp; + struct unix_sock *u = unix_sk(sk); + + if (unlikely(fp && fp->count)) { + atomic_add(fp->count, &u->scm_stat.nr_fds); + unix_add_edges(fp, u); + } +} + +static void scm_stat_del(struct sock *sk, struct sk_buff *skb) +{ + struct scm_fp_list *fp = UNIXCB(skb).fp; + struct unix_sock *u = unix_sk(sk); + + if (unlikely(fp && fp->count)) { + atomic_sub(fp->count, &u->scm_stat.nr_fds); + unix_del_edges(fp); + } +} + /* When dgram socket disconnects (or changes its peer), we clear its receive * queue of packets arrived from previous peer. First, it allows to do * flow control based only on wmem_alloc; second, sk connected to peer @@ -616,8 +638,19 @@ static void unix_write_space(struct sock *sk) static void unix_dgram_disconnected(struct sock *sk, struct sock *other) { if (!skb_queue_empty(&sk->sk_receive_queue)) { - skb_queue_purge_reason(&sk->sk_receive_queue, - SKB_DROP_REASON_UNIX_DISCONNECT); + struct sk_buff_head tmp; + struct sk_buff *skb; + + __skb_queue_head_init(&tmp); + + spin_lock(&sk->sk_receive_queue.lock); + skb_queue_splice_init(&sk->sk_receive_queue, &tmp); + spin_unlock(&sk->sk_receive_queue.lock); + + while ((skb = __skb_dequeue(&tmp)) != NULL) { + scm_stat_del(sk, skb); + kfree_skb_reason(skb, SKB_DROP_REASON_UNIX_DISCONNECT); + } wake_up_interruptible_all(&unix_sk(sk)->peer_wait); @@ -2059,28 +2092,6 @@ static bool unix_skb_scm_eq(const struct sock *sk, struct sk_buff *skb, unix_secdata_eq(scm, skb); } -static void scm_stat_add(struct sock *sk, struct sk_buff *skb) -{ - struct scm_fp_list *fp = UNIXCB(skb).fp; - struct unix_sock *u = unix_sk(sk); - - if (unlikely(fp && fp->count)) { - atomic_add(fp->count, &u->scm_stat.nr_fds); - unix_add_edges(fp, u); - } -} - -static void scm_stat_del(struct sock *sk, struct sk_buff *skb) -{ - struct scm_fp_list *fp = UNIXCB(skb).fp; - struct unix_sock *u = unix_sk(sk); - - if (unlikely(fp && fp->count)) { - atomic_sub(fp->count, &u->scm_stat.nr_fds); - unix_del_edges(fp); - } -} - static void unix_orphan_scm(struct sock *sk, struct sk_buff *skb) { scm_stat_del(sk, skb); From c550cea62c1e176629b1d814365b22aecfe6f4d5 Mon Sep 17 00:00:00 2001 From: Siddharth Chintamaneni Date: Sat, 14 Nov 2026 16:26:32 +0000 Subject: [PATCH 0791/2102] selftest: af_unix: Test scm_fds on dgram disconnect. Add dgram_disconnect_fdinfo in scm_rights.c verifying that scm_fds in /proc/self/fdinfo/ returns to 0 when a connected SOCK_DGRAM socket with queued SCM_RIGHTS datagrams disconnects via connect(AF_UNSPEC) or observes a dead peer in send(). Signed-off-by: Siddharth Chintamaneni Reviewed-by: Kuniyuki Iwashima Link: https://patch.msgid.link/20261114162632.16346-3-sidchintamaneni@gmail.com Signed-off-by: Jakub Kicinski --- .../selftests/net/af_unix/scm_rights.c | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/tools/testing/selftests/net/af_unix/scm_rights.c b/tools/testing/selftests/net/af_unix/scm_rights.c index c165f250220a4a..19aa26c60f3b58 100644 --- a/tools/testing/selftests/net/af_unix/scm_rights.c +++ b/tools/testing/selftests/net/af_unix/scm_rights.c @@ -395,4 +395,79 @@ TEST_F(scm_rights, mixed_lowpoint) close_sockets(6); } +static int count_scm_fds(struct __test_metadata *_metadata, int fd) +{ + char path[64], *line = NULL; + int scm_fds = -1, ret; + size_t unused = 0; + FILE *f; + + snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", fd); + + f = fopen(path, "r"); + ASSERT_NE(NULL, f); + + while (getline(&line, &unused, f) != -1) { + if (strncmp(line, "scm_fds:", 8)) + continue; + + ret = sscanf(line + 8, "%d", &scm_fds); + ASSERT_EQ(1, ret); + + break; + } + + free(line); + + ret = fclose(f); + ASSERT_EQ(0, ret); + + return scm_fds; +} + +TEST(dgram_disconnect_fdinfo) +{ + const FIXTURE_VARIANT(scm_rights) variant = { + .name = "UNIX ", + .type = SOCK_DGRAM, + }; + FIXTURE_DATA(scm_rights) self = {}; + struct sockaddr addr = { + .sa_family = AF_UNSPEC, + }; + int ret; + + ret = unshare(CLONE_NEWNET); + ASSERT_EQ(0, ret); + + create_socketpairs(_metadata, &self, &variant, 2); + + /* 1. Disconnect via connect(AF_UNSPEC) */ + __send_fd(_metadata, &self, &variant, 0, 0); + ASSERT_EQ(2, count_scm_fds(_metadata, self.fd[0])); + + ret = connect(self.fd[0], &addr, sizeof(addr.sa_family)); + ASSERT_EQ(0, ret); + ASSERT_EQ(0, count_scm_fds(_metadata, self.fd[0])); + + /* 2. Dead-peer disconnect via send() */ + __send_fd(_metadata, &self, &variant, 1, 1); + ASSERT_EQ(2, count_scm_fds(_metadata, self.fd[2])); + + ret = close(self.fd[3]); + ASSERT_EQ(0, ret); + + ret = send(self.fd[2], "x", 1, 0); + ASSERT_EQ(-1, ret); + ASSERT_EQ(ECONNREFUSED, errno); + ASSERT_EQ(0, count_scm_fds(_metadata, self.fd[2])); + + ret = close(self.fd[0]); + ASSERT_EQ(0, ret); + ret = close(self.fd[1]); + ASSERT_EQ(0, ret); + ret = close(self.fd[2]); + ASSERT_EQ(0, ret); +} + TEST_HARNESS_MAIN From e0696bf65006d888c713ff54269c7fd32bbe62a7 Mon Sep 17 00:00:00 2001 From: Stanley Jhu Date: Thu, 12 Nov 2026 08:41:10 +0800 Subject: [PATCH 0792/2102] scsi: rpmb: core: Guard frame requests and teardown with mutex rpmb_route_frames() invokes the provider callback without serialization, which causes two races: 1. Concurrent callers on the same rpmb_dev interleave multi-frame authenticated sequences on the region's single result register and receive each other's responses without error. 2. rpmb_dev_unregister() calls device_del() and allows the parent provider device to be freed while an in-flight rpmb_route_frames() call still dereferences rdev->dev.parent, causing a use-after-free. Serialize rpmb_route_frames() and rpmb_dev_unregister() with a mutex in struct rpmb_dev and clear descr.route_frames on unregistration so new requests fail with -ENODEV. Also update the stale kerneldoc note advising providers to unregister from their parent release callback, which cannot run while the child rpmb_dev still holds a parent reference. Fixes: 1e9046e3a154 ("rpmb: add Replay Protected Memory Block (RPMB) subsystem") Cc: stable@vger.kernel.org Signed-off-by: Stanley Jhu Tested-by: Alexey Charkov Link: https://patch.msgid.link/20261112004112.3059801-2-stanleyjhu@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/misc/rpmb-core.c | 20 ++++++++++++++++++-- include/linux/rpmb.h | 3 +++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/drivers/misc/rpmb-core.c b/drivers/misc/rpmb-core.c index ecf14acf230ae0..0fda893dd74dba 100644 --- a/drivers/misc/rpmb-core.c +++ b/drivers/misc/rpmb-core.c @@ -45,6 +45,8 @@ EXPORT_SYMBOL_GPL(rpmb_dev_put); * @rsp: rpmb response frames * @rsp_len: length of rpmb response frames in bytes * + * Context: Might sleep. + * * Returns: < 0 on failure */ int rpmb_route_frames(struct rpmb_dev *rdev, u8 *req, @@ -53,6 +55,10 @@ int rpmb_route_frames(struct rpmb_dev *rdev, u8 *req, if (!req || !req_len || !rsp || !rsp_len) return -EINVAL; + guard(mutex)(&rdev->lock); + if (!rdev->descr.route_frames) + return -ENODEV; + return rdev->descr.route_frames(rdev->dev.parent, req, req_len, rsp, rsp_len); } @@ -62,6 +68,7 @@ static void rpmb_dev_release(struct device *dev) { struct rpmb_dev *rdev = to_rpmb_dev(dev); + mutex_destroy(&rdev->lock); ida_free(&rpmb_ida, rdev->id); kfree(rdev->descr.dev_id); kfree(rdev); @@ -123,8 +130,9 @@ EXPORT_SYMBOL_GPL(rpmb_interface_unregister); * rpmb_dev_unregister() - unregister RPMB partition from the RPMB subsystem * @rdev: the rpmb device to unregister * - * This function should be called from the release function of the - * underlying device used when the RPMB device was registered. + * This function should be called from the remove or unbind callback of the + * underlying device used when the RPMB device was registered, never from + * a device release callback. * * Returns: < 0 on failure */ @@ -133,6 +141,12 @@ int rpmb_dev_unregister(struct rpmb_dev *rdev) if (!rdev) return -EINVAL; + scoped_guard(mutex, &rdev->lock) { + if (!rdev->descr.route_frames) + return 0; + rdev->descr.route_frames = NULL; + } + device_del(&rdev->dev); rpmb_dev_put(rdev); @@ -164,6 +178,7 @@ struct rpmb_dev *rpmb_dev_register(struct device *dev, rdev = kzalloc_obj(*rdev); if (!rdev) return ERR_PTR(-ENOMEM); + mutex_init(&rdev->lock); rdev->descr = *descr; rdev->descr.dev_id = kmemdup(descr->dev_id, descr->dev_id_len, GFP_KERNEL); @@ -194,6 +209,7 @@ struct rpmb_dev *rpmb_dev_register(struct device *dev, err_free_dev_id: kfree(rdev->descr.dev_id); err_free_rdev: + mutex_destroy(&rdev->lock); kfree(rdev); return ERR_PTR(ret); } diff --git a/include/linux/rpmb.h b/include/linux/rpmb.h index ed3f8e431eff03..11a5d2646e385b 100644 --- a/include/linux/rpmb.h +++ b/include/linux/rpmb.h @@ -7,6 +7,7 @@ #define __RPMB_H__ #include +#include #include /** @@ -48,12 +49,14 @@ struct rpmb_descr { * struct rpmb_dev - device which can support RPMB partition * * @dev : device + * @lock : serialises requests and protects them against teardown * @id : device_id * @list_node : linked list node * @descr : RPMB description */ struct rpmb_dev { struct device dev; + struct mutex lock; int id; struct list_head list_node; struct rpmb_descr descr; From 7bc9b854cd68ed2d06949540ca18a44368569c64 Mon Sep 17 00:00:00 2001 From: Stanley Jhu Date: Thu, 12 Nov 2026 08:41:11 +0800 Subject: [PATCH 0793/2102] scsi: ufs: rpmb: Decouple device lifecycle from devres to avoid UAF Region device lifetime in ufs-rpmb fails on host removal in three ways: 1. ufs_rpmb_probe() allocates struct ufs_rpmb_dev with devm_kzalloc() on the host device even though it embeds a reference-counted struct device, so devres frees the memory on host unbind regardless of live references. 2. Probe takes no reference on hba->ufs_rpmb_wlun, so scsi_remove_host() frees the scsi_device while an RPMB request is still in flight. 3. Child rpmb_dev holds a parent reference on ufs_rpmb->dev until rpmb_dev_unregister() runs, which sits inside ufs_rpmb_device_release() and therefore never runs on unbind. Allocate struct ufs_rpmb_dev with kzalloc_obj() and free it in ufs_rpmb_device_release(), hold a get_device() reference on the WLUN across the region lifetime, call rpmb_dev_unregister() explicitly during removal and probe unwind, and reject requests when the WLUN is offline. Fixes: b06b8c421485 ("scsi: ufs: core: Add OP-TEE based RPMB driver for UFS devices") Cc: stable@vger.kernel.org Signed-off-by: Stanley Jhu Link: https://patch.msgid.link/20261112004112.3059801-3-stanleyjhu@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/core/ufs-rpmb.c | 79 +++++++++++++++++++++---------------- 1 file changed, 44 insertions(+), 35 deletions(-) diff --git a/drivers/ufs/core/ufs-rpmb.c b/drivers/ufs/core/ufs-rpmb.c index 65f2d71cf073bf..11d2d8e789d00a 100644 --- a/drivers/ufs/core/ufs-rpmb.c +++ b/drivers/ufs/core/ufs-rpmb.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -36,13 +37,14 @@ struct ufs_rpmb_dev { u8 region_id; struct device dev; struct rpmb_dev *rdev; - struct ufs_hba *hba; + struct scsi_device *sdev; struct list_head node; }; -static int ufs_sec_submit(struct ufs_hba *hba, u16 spsp, void *buffer, size_t len, bool send) +static int ufs_sec_submit(struct ufs_rpmb_dev *ufs_rpmb, u16 spsp, + void *buffer, size_t len, bool send) { - struct scsi_device *sdev = hba->ufs_rpmb_wlun; + struct scsi_device *sdev = ufs_rpmb->sdev; struct scsi_failure failure_defs[] = { { .sense_key = UNIT_ATTENTION, @@ -62,6 +64,9 @@ static int ufs_sec_submit(struct ufs_hba *hba, u16 spsp, void *buffer, size_t le }; u8 cdb[12] = { }; + if (!sdev || !scsi_device_online(sdev)) + return -ENODEV; + cdb[0] = send ? SECURITY_PROTOCOL_OUT : SECURITY_PROTOCOL_IN; cdb[1] = UFS_RPMB_SEC_PROTOCOL; put_unaligned_be16(spsp, &cdb[2]); @@ -74,13 +79,12 @@ static int ufs_sec_submit(struct ufs_hba *hba, u16 spsp, void *buffer, size_t le /* UFS RPMB route frames implementation */ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_len, u8 *resp, - unsigned int resp_len) + unsigned int resp_len) { struct ufs_rpmb_dev *ufs_rpmb = dev_get_drvdata(dev); struct rpmb_frame *frm_out = (struct rpmb_frame *)req; bool need_result_read = true; u16 req_type, protocol_id; - struct ufs_hba *hba; int ret; if (!ufs_rpmb) { @@ -88,8 +92,6 @@ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_l return -ENODEV; } - hba = ufs_rpmb->hba; - /* req_resp is at the end of an RPMB frame. */ if (req_len < sizeof(*frm_out)) return -EINVAL; @@ -122,7 +124,7 @@ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_l protocol_id = ufs_rpmb->region_id << 8 | UFS_RPMB_SEC_PROTOCOL_ID; - ret = ufs_sec_submit(hba, protocol_id, req, req_len, true); + ret = ufs_sec_submit(ufs_rpmb, protocol_id, req, req_len, true); if (ret) { dev_err(dev, "Command failed with ret=%d\n", ret); return ret; @@ -133,7 +135,8 @@ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_l memset(frm_resp, 0, sizeof(*frm_resp)); put_unaligned_be16(RPMB_RESULT_READ, &frm_resp->req_resp); - ret = ufs_sec_submit(hba, protocol_id, resp, resp_len, true); + ret = ufs_sec_submit(ufs_rpmb, protocol_id, resp, resp_len, + true); if (ret) { dev_err(dev, "Result read request failed with ret=%d\n", ret); return ret; @@ -141,7 +144,8 @@ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_l } if (!ret) { - ret = ufs_sec_submit(hba, protocol_id, resp, resp_len, false); + ret = ufs_sec_submit(ufs_rpmb, protocol_id, resp, resp_len, + false); if (ret) dev_err(dev, "Response read failed with ret=%d\n", ret); } @@ -151,23 +155,31 @@ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_l static void ufs_rpmb_device_release(struct device *dev) { - struct ufs_rpmb_dev *ufs_rpmb = dev_get_drvdata(dev); + struct ufs_rpmb_dev *ufs_rpmb = + container_of(dev, struct ufs_rpmb_dev, dev); - rpmb_dev_unregister(ufs_rpmb->rdev); + put_device(&ufs_rpmb->sdev->sdev_gendev); + kfree(ufs_rpmb); } /* UFS RPMB device registration */ int ufs_rpmb_probe(struct ufs_hba *hba) { + struct rpmb_descr descr = { + .type = RPMB_TYPE_UFS, + .route_frames = ufs_rpmb_route_frames, + .reliable_wr_count = hba->dev_info.rpmb_io_size, + }; + struct scsi_device *sdev = hba->ufs_rpmb_wlun; struct ufs_rpmb_dev *ufs_rpmb, *it, *tmp; u8 dev_id[UFS_RPMB_ID_LEN]; struct rpmb_dev *rdev; - char *cid = NULL; + char *cid; int region; u32 cap; int ret; - if (!hba->ufs_rpmb_wlun || hba->dev_info.b_advanced_rpmb_en) { + if (!sdev || hba->dev_info.b_advanced_rpmb_en) { dev_info(hba->dev, "Skip OP-TEE RPMB registration\n"); return -ENODEV; } @@ -178,25 +190,22 @@ int ufs_rpmb_probe(struct ufs_hba *hba) return -EINVAL; } - struct rpmb_descr descr = { - .type = RPMB_TYPE_UFS, - .route_frames = ufs_rpmb_route_frames, - .reliable_wr_count = hba->dev_info.rpmb_io_size, - }; - for (region = 0; region < ARRAY_SIZE(hba->dev_info.rpmb_region_size); region++) { cap = hba->dev_info.rpmb_region_size[region]; if (!cap) continue; - ufs_rpmb = devm_kzalloc(hba->dev, sizeof(*ufs_rpmb), GFP_KERNEL); + ufs_rpmb = kzalloc_obj(*ufs_rpmb); if (!ufs_rpmb) { ret = -ENOMEM; goto err_out; } - ufs_rpmb->hba = hba; - ufs_rpmb->dev.parent = &hba->ufs_rpmb_wlun->sdev_gendev; + get_device(&sdev->sdev_gendev); + + ufs_rpmb->sdev = sdev; + ufs_rpmb->region_id = region; + ufs_rpmb->dev.parent = &sdev->sdev_gendev; ufs_rpmb->dev.bus = &ufs_rpmb_bus_type; ufs_rpmb->dev.release = ufs_rpmb_device_release; dev_set_name(&ufs_rpmb->dev, "ufs_rpmb%d", region); @@ -207,16 +216,14 @@ int ufs_rpmb_probe(struct ufs_hba *hba) ret = device_register(&ufs_rpmb->dev); if (ret) { dev_err(hba->dev, "Failed to register UFS RPMB device %d\n", region); - put_device(&ufs_rpmb->dev); - goto err_out; + goto err_put; } /* Create unique ID by appending region number to device_id */ cid = kasprintf(GFP_KERNEL, "%s-R%d", hba->dev_info.device_id, region); if (!cid) { - device_unregister(&ufs_rpmb->dev); ret = -ENOMEM; - goto err_out; + goto err_unreg; } blake2b(NULL, 0, cid, strlen(cid), dev_id, UFS_RPMB_ID_LEN); @@ -227,29 +234,30 @@ int ufs_rpmb_probe(struct ufs_hba *hba) /* Register RPMB device */ rdev = rpmb_dev_register(&ufs_rpmb->dev, &descr); + kfree(cid); if (IS_ERR(rdev)) { dev_err(hba->dev, "Failed to register UFS RPMB device.\n"); - device_unregister(&ufs_rpmb->dev); ret = PTR_ERR(rdev); - goto err_out; + goto err_unreg; } - kfree(cid); - cid = NULL; - ufs_rpmb->rdev = rdev; - ufs_rpmb->region_id = region; - list_add_tail(&ufs_rpmb->node, &hba->rpmbs); dev_info(hba->dev, "UFS RPMB region %d registered (capacity=%u)\n", region, cap); } return 0; + +err_unreg: + device_unregister(&ufs_rpmb->dev); + goto err_out; +err_put: + put_device(&ufs_rpmb->dev); err_out: - kfree(cid); list_for_each_entry_safe(it, tmp, &hba->rpmbs, node) { list_del(&it->node); + rpmb_dev_unregister(it->rdev); device_unregister(&it->dev); } @@ -269,6 +277,7 @@ void ufs_rpmb_remove(struct ufs_hba *hba) dev_info(hba->dev, "Removing UFS RPMB region %d\n", ufs_rpmb->region_id); /* Remove from list first */ list_del(&ufs_rpmb->node); + rpmb_dev_unregister(ufs_rpmb->rdev); /* Unregister device */ device_unregister(&ufs_rpmb->dev); } From b1de2bd5a4d64d190156aa442c5295ce635f9992 Mon Sep 17 00:00:00 2001 From: Stanley Jhu Date: Thu, 12 Nov 2026 08:41:12 +0800 Subject: [PATCH 0794/2102] scsi: ufs: rpmb: Drop the unregistered ufs_rpmb bus ufs_rpmb_probe() assigns ufs_rpmb_bus_type to dev.bus without ever calling bus_register(). Since commit 36f35b8df697 ("driver core: reject devices with unregistered buses"), device_register() rejects unregistered buses with -EINVAL and UFS RPMB region registration fails. ufs_rpmb_bus_type defines no callbacks and has no drivers, and consumers look up regions through /sys/class/rpmb. Drop ufs_rpmb_bus_type and leave dev.bus unset. Fixes: b06b8c421485 ("scsi: ufs: core: Add OP-TEE based RPMB driver for UFS devices") Cc: stable@vger.kernel.org Reviewed-by: Bean Huo Signed-off-by: Stanley Jhu Tested-by: Alexey Charkov Link: https://patch.msgid.link/20261112004112.3059801-4-stanleyjhu@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/core/ufs-rpmb.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/drivers/ufs/core/ufs-rpmb.c b/drivers/ufs/core/ufs-rpmb.c index 11d2d8e789d00a..6803f3e62d786c 100644 --- a/drivers/ufs/core/ufs-rpmb.c +++ b/drivers/ufs/core/ufs-rpmb.c @@ -28,10 +28,6 @@ #define UFS_RPMB_SEC_PROTOCOL 0xEC /* JEDEC UFS application */ #define UFS_RPMB_SEC_PROTOCOL_ID 0x01 /* JEDEC UFS RPMB protocol ID, CDB byte3 */ -static const struct bus_type ufs_rpmb_bus_type = { - .name = "ufs_rpmb", -}; - /* UFS RPMB device structure */ struct ufs_rpmb_dev { u8 region_id; @@ -206,7 +202,6 @@ int ufs_rpmb_probe(struct ufs_hba *hba) ufs_rpmb->sdev = sdev; ufs_rpmb->region_id = region; ufs_rpmb->dev.parent = &sdev->sdev_gendev; - ufs_rpmb->dev.bus = &ufs_rpmb_bus_type; ufs_rpmb->dev.release = ufs_rpmb_device_release; dev_set_name(&ufs_rpmb->dev, "ufs_rpmb%d", region); From 040d27029306f59a78c3af32f665693590244043 Mon Sep 17 00:00:00 2001 From: Niklas Cassel Date: Tue, 17 Nov 2026 13:29:53 +0100 Subject: [PATCH 0795/2102] scsi: scsi_ioctl: Require write access for the depopulation commands scsi_cmd_allowed() lets anybody who can open a SCSI device, even read-only, send any SERVICE ACTION IN(16) command. Besides READ CAPACITY(16) and the other read-only service actions, that opcode also carries the storage element depopulation commands of SBC-4: REMOVE ELEMENT AND TRUNCATE, RESTORE ELEMENTS AND REBUILD and REMOVE ELEMENT AND MODIFY ZONES. These change the capacity of the device, and after REMOVE ELEMENT AND TRUNCATE the data on the device is most likely gone. SCSI devices that support depopulation execute these commands directly, and libata translates them to the equivalent ATA commands, so a user with read-only access to the device node can truncate the device through SG_IO, SCSI_IOCTL_SEND_COMMAND or bsg. Treat these service actions like FORMAT UNIT and ERASE, which also destroy data, and only allow them if the device is opened for writing. The other SERVICE ACTION IN(16) service actions remain allowed for everybody who can open the device. Cc: stable@vger.kernel.org # 2a0adbb80a2f: scsi: define depopulation capabilities related service actions Reviewed-by: Damien Le Moal Signed-off-by: Niklas Cassel Fixes: db496721cb0d ("ata: libata-scsi: add support for the REMOVE ELEMENT AND TRUNCATE command") Fixes: 1e307ca61a9c ("ata: libata-scsi: add support for the RESTORE ELEMENTS AND REBUILD command") Fixes: b448bb42bd10 ("ata: libata-scsi: add support for the REMOVE ELEMENT AND MODIFY ZONES command") Link: https://patch.msgid.link/20261117122952.3451870-2-cassel@kernel.org Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/scsi_ioctl.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/drivers/scsi/scsi_ioctl.c b/drivers/scsi/scsi_ioctl.c index bf049d9cb71915..91525103d0743b 100644 --- a/drivers/scsi/scsi_ioctl.c +++ b/drivers/scsi/scsi_ioctl.c @@ -300,7 +300,6 @@ bool scsi_cmd_allowed(unsigned char *cmd, bool open_for_write) case GPCMD_VERIFY_10: case VERIFY_16: case REPORT_LUNS: - case SERVICE_ACTION_IN_16: case RECEIVE_DIAGNOSTIC: case MAINTENANCE_IN: /* also GPCMD_SEND_KEY, which is a write command */ case GPCMD_READ_BUFFER_CAPACITY: @@ -330,6 +329,21 @@ bool scsi_cmd_allowed(unsigned char *cmd, bool open_for_write) /* ZBC */ case ZBC_IN: return true; + /* + * The storage element depopulation commands share the opcode of the + * read-only SERVICE ACTION IN(16) commands, but change the capacity + * of the device and may destroy its data, so treat them as writing + * commands. + */ + case SERVICE_ACTION_IN_16: + switch (cmd[1] & 0x1f) { + case SAI_REMOVE_ELEMENT_AND_TRUNCATE: + case SAI_RESTORE_ELEMENTS_AND_REBUILD: + case SAI_REMOVE_ELEMENT_AND_MODIFY_ZONES: + return open_for_write; + default: + return true; + } /* Basic writing commands */ case WRITE_6: case WRITE_10: From cbd9818ebed38fd8ddd6af7335d60908aceb93f4 Mon Sep 17 00:00:00 2001 From: Weidong Wang Date: Sun, 8 Nov 2026 03:01:08 -0600 Subject: [PATCH 0796/2102] scsi: libfc: Fix rport kref leak in fc_rport_enter_ready() fc_rport_enter_ready() takes a reference on the rport unconditionally, but only queues event_work, whose handler drops that reference, when no event is pending. If rdata->event is already set, the && short-circuits past both queue_work() and the compensating kref_put(), so the reference is leaked and the fc_rport_priv is never freed. This is reachable from the wire: a PLOGI from a well-known address goes straight to fc_rport_enter_ready(), and a second PLOGI for the same S_ID while RPORT_EV_READY is still pending enters it again. After the rport is logged out, kmemleak reports: unreferenced object 0xffff888... (size 512): backtrace: __kmalloc_noprof fc_rport_create fc_rport_recv_req fc_lport_recv_els_req fc_lport_recv fcoe_receive_work Commit 823a65409c89 ("scsi: libfc: Skip additional kref updating work event") fixed the same pattern in fc_rport_enter_delete(). Do the same here: only take the reference when no event is pending, i.e. when the work is actually going to be queued. The issue was found with an LLM-based bug-finding tool; the reproducer, fix and changelog were drafted with AI assistance (Claude), then reviewed and tested by the submitter. Fixes: 4d2095cc42a2 ("scsi: libfc: Revisit kref handling") Cc: stable@vger.kernel.org Signed-off-by: Weidong Wang Reviewed-by: Hannes Reinecke Link: https://patch.msgid.link/20261108-h123-send-v1-1-b7672ff849f0@illinois.edu Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/libfc/fc_rport.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/drivers/scsi/libfc/fc_rport.c b/drivers/scsi/libfc/fc_rport.c index c25979d96808a9..7b093854462e44 100644 --- a/drivers/scsi/libfc/fc_rport.c +++ b/drivers/scsi/libfc/fc_rport.c @@ -550,10 +550,11 @@ static void fc_rport_enter_ready(struct fc_rport_priv *rdata) FC_RPORT_DBG(rdata, "Port is Ready\n"); - kref_get(&rdata->kref); - if (rdata->event == RPORT_EV_NONE && - !queue_work(rport_event_queue, &rdata->event_work)) - kref_put(&rdata->kref, fc_rport_destroy); + if (rdata->event == RPORT_EV_NONE) { + kref_get(&rdata->kref); + if (!queue_work(rport_event_queue, &rdata->event_work)) + kref_put(&rdata->kref, fc_rport_destroy); + } rdata->event = RPORT_EV_READY; } From 947d8e9a4d1ea6cc71427e7f701e5c2cf35391c9 Mon Sep 17 00:00:00 2001 From: Stanley Jhu Date: Wed, 11 Nov 2026 16:48:53 +0800 Subject: [PATCH 0797/2102] scsi: ufs: ufs-pci: Check hba->vops in system PM callbacks ufshcd_pci_tbl[] defines the Samsung 0xC00C and AMD 0x1B29 PCI IDs with .driver_data set to 0, so ufshcd_pci_probe() leaves hba->vops NULL. Both ufshcd_pci_suspend_prepare() and ufshcd_pci_resume_complete() dereference hba->vops->name without checking hba->vops: 1. System suspend on an AMD 0x1B29 or Samsung 0xC00C host enters the PM prepare phase and calls ufshcd_pci_suspend_prepare(). 2. ufshcd_pci_suspend_prepare() evaluates strcmp(hba->vops->name, "intel-pci"), dereferences NULL, and triggers a kernel oops in the suspending task. Check that hba->vops is non-NULL before reading hba->vops->name in both callbacks so hosts without variant operations use the generic ufshcd_suspend_prepare() and ufshcd_resume_complete() paths. Fixes: bb44826c3bdb ("scsi: ufs: ufs-pci: Fix S0ix/S3 for Intel controllers") Cc: stable@vger.kernel.org Signed-off-by: Stanley Jhu Reviewed-by: Adrian Hunter Link: https://patch.msgid.link/20261111084853.3530107-1-stanleyjhu@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/host/ufshcd-pci.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/ufs/host/ufshcd-pci.c b/drivers/ufs/host/ufshcd-pci.c index 668b57403e6261..f9abbbc436f45a 100644 --- a/drivers/ufs/host/ufshcd-pci.c +++ b/drivers/ufs/host/ufshcd-pci.c @@ -644,7 +644,7 @@ static int ufshcd_pci_suspend_prepare(struct device *dev) { struct ufs_hba *hba = dev_get_drvdata(dev); - if (!strcmp(hba->vops->name, "intel-pci")) + if (hba->vops && !strcmp(hba->vops->name, "intel-pci")) return ufs_intel_suspend_prepare(dev); return ufshcd_suspend_prepare(dev); @@ -654,7 +654,7 @@ static void ufshcd_pci_resume_complete(struct device *dev) { struct ufs_hba *hba = dev_get_drvdata(dev); - if (!strcmp(hba->vops->name, "intel-pci")) { + if (hba->vops && !strcmp(hba->vops->name, "intel-pci")) { ufs_intel_resume_complete(dev); return; } From 7470a1f2a84d68d177560b78388e640771b6b94a Mon Sep 17 00:00:00 2001 From: Kyle Mahlkuch Date: Wed, 11 Nov 2026 11:47:41 -0600 Subject: [PATCH 0798/2102] scsi: lpfc: Fix race conditions in ELS retry handling This patch addresses a race condition in the lpfc driver's ELS retry event handling that can lead to a use-after-free in the lpfc_cancel_retry_delay_tmo(), where the NLP_DELAY_TMO flag is cleared before acquiring the lock to check if the retry event is queued. This creates a window where the timer can be rescheduled and fire, causing both the cancel path and the worker thread to release the same reference, resulting in a double-put and use-after-free. Moved capture ndlp and clear evt_arg1 under hbalock while dequeuing LPFC_EVT_ELS_RETRY in lpfc_work_list_done(). Signed-off-by: Kyle Mahlkuch Fixes: e47c9093531d ("[SCSI] lpfc 8.2.5 : Correct ndlp referencing issues") Reviewed-by: Hannes Reinecke Reviewed-by: Paul Ely Link: https://patch.msgid.link/dcea48dd-f76c-4bb0-9275-c12ef9bd78a2@linux.ibm.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/lpfc/lpfc_els.c | 29 +++++++++++++++++++++++------ drivers/scsi/lpfc/lpfc_hbadisc.c | 11 ++++++++++- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/drivers/scsi/lpfc/lpfc_els.c b/drivers/scsi/lpfc/lpfc_els.c index 804aa7509b6926..8d5bf2510d7a0b 100644 --- a/drivers/scsi/lpfc/lpfc_els.c +++ b/drivers/scsi/lpfc/lpfc_els.c @@ -4477,18 +4477,35 @@ lpfc_issue_els_edc(struct lpfc_vport *vport, uint8_t retry) void lpfc_cancel_retry_delay_tmo(struct lpfc_vport *vport, struct lpfc_nodelist *nlp) { - struct lpfc_work_evt *evtp; + struct lpfc_hba *phba = vport->phba; + struct lpfc_work_evt *evtp = &nlp->els_retry_evt; + struct lpfc_nodelist *arg_ndlp = NULL; + unsigned long flags; if (!test_and_clear_bit(NLP_DELAY_TMO, &nlp->nlp_flag)) return; timer_delete_sync(&nlp->nlp_delayfunc); nlp->nlp_last_elscmd = 0; - if (!list_empty(&nlp->els_retry_evt.evt_listp)) { - list_del_init(&nlp->els_retry_evt.evt_listp); - /* Decrement nlp reference count held for the delayed retry */ - evtp = &nlp->els_retry_evt; - lpfc_nlp_put((struct lpfc_nodelist *)evtp->evt_arg1); + + /* + * If retry event is queued, remove it under lock and consume + * its payload to prevent double-put. The event holds a reference + * to the nodelist that must be released exactly once. + */ + spin_lock_irqsave(&phba->hbalock, flags); + if (!list_empty(&evtp->evt_listp)) { + list_del_init(&evtp->evt_listp); + /* Take local copy and clear to prevent reuse */ + arg_ndlp = (struct lpfc_nodelist *)evtp->evt_arg1; + evtp->evt_arg1 = NULL; + smp_wmb(); /* Ensure NULL visible before unlock */ } + spin_unlock_irqrestore(&phba->hbalock, flags); + + /* Drop the event-held reference outside the lock */ + if (arg_ndlp) + lpfc_nlp_put(arg_ndlp); + if (test_and_clear_bit(NLP_NPR_2B_DISC, &nlp->nlp_flag)) { if (vport->num_disc_nodes) { if (vport->port_state < LPFC_VPORT_READY) { diff --git a/drivers/scsi/lpfc/lpfc_hbadisc.c b/drivers/scsi/lpfc/lpfc_hbadisc.c index 57cdd669928c2d..b447b9acfe7bfc 100644 --- a/drivers/scsi/lpfc/lpfc_hbadisc.c +++ b/drivers/scsi/lpfc/lpfc_hbadisc.c @@ -840,12 +840,21 @@ lpfc_work_list_done(struct lpfc_hba *phba) while (!list_empty(&phba->work_list)) { list_remove_head((&phba->work_list), evtp, typeof(*evtp), evt_listp); + /* + * The ELS retry event can be requeued by lpfc_els_retry_delay() + * as soon as hbalock is dropped. Consume the payload within the + * hbalock to prevent reuse or double-put. + */ + if (evtp->evt == LPFC_EVT_ELS_RETRY) { + ndlp = (struct lpfc_nodelist *)(evtp->evt_arg1); + evtp->evt_arg1 = NULL; + } spin_unlock_irq(&phba->hbalock); hba_pci_err = test_bit(HBA_PCI_ERR, &phba->bit_flags); free_evt = 1; switch (evtp->evt) { case LPFC_EVT_ELS_RETRY: - ndlp = (struct lpfc_nodelist *) (evtp->evt_arg1); + /* ndlp was already captured under hbalock */ if (!hba_pci_err) { lpfc_els_retry_delay_handler(ndlp); free_evt = 0; /* evt is part of ndlp */ From 7494b0c50c9fcd9f9f5235777bb506dd45676557 Mon Sep 17 00:00:00 2001 From: Rosen Penev Date: Tue, 17 Nov 2026 20:04:17 -0800 Subject: [PATCH 0799/2102] hwmon: (dell-smm) Reject out-of-range pwm values dell_smm_write() scales the value written to pwmN with DIV_ROUND_CLOSEST(val, data->i8k_pwm_mult) before clamping the result to the valid fan states. The rounding adds i8k_pwm_mult / 2 to val first, which overflows for values near LONG_MAX and wraps to a large negative number. That is then clamped to 0, so writing a huge value turns the fan off instead of running it at the highest speed. With the default fan_max of 2, writing any value from LONG_MAX - 63 up to LONG_MAX selects fan state 0. The pwm range is well defined, so return -EINVAL for values outside 0 to 255, as is the convention for pwm attributes. Fixes: e7f5f275c62a ("i8k: Implement hwmon based fan speed control") Cc: stable@vger.kernel.org Signed-off-by: Rosen Penev Link: https://patch.msgid.link/20261118040417.19049-1-rosenp@gmail.com Signed-off-by: Guenter Roeck --- drivers/hwmon/dell-smm-hwmon.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/hwmon/dell-smm-hwmon.c b/drivers/hwmon/dell-smm-hwmon.c index 47c06376aa528a..5963f908972fb1 100644 --- a/drivers/hwmon/dell-smm-hwmon.c +++ b/drivers/hwmon/dell-smm-hwmon.c @@ -1030,6 +1030,9 @@ static int dell_smm_write(struct device *dev, enum hwmon_sensor_types type, u32 case hwmon_pwm: switch (attr) { case hwmon_pwm_input: + if (val < 0 || val > 255) + return -EINVAL; + pwm = clamp_val(DIV_ROUND_CLOSEST(val, data->i8k_pwm_mult), 0, data->i8k_fan_max); From a410375a249c4f9e1eb3d7f2c864d3f4ef4b8365 Mon Sep 17 00:00:00 2001 From: Laurence Oberman Date: Mon, 9 Nov 2026 15:11:20 -0500 Subject: [PATCH 0800/2102] scsi: scsi_dh_alua: Set handler_data before alua_initialize() Since commit 50759b881e1d ("scsi: device_handler: alua: Call scsi_device_put() from non-atomic context"), alua_rtpg_queue() only queues an RTPG when sdev->handler_data points at an alua_dh_data whose port group matches: struct alua_dh_data *h = sdev->handler_data; ... if (h && rcu_dereference(h->pg) == pg) { However alua_bus_attach() only assigns sdev->handler_data after alua_initialize() returns, and alua_initialize() -> alua_check_vpd() is where the initial RTPG is queued. At that point handler_data is still NULL, so the initial RTPG is silently dropped: no RTPG is sent, nothing is logged, and sdev->access_state keeps its zeroed default of active/optimized for every path. With dm-multipath this goes unnoticed, as pg_init calls scsi_dh_activate() once the map is loaded, which queues an RTPG after handler_data is set, and multipathd's alua prioritizer issues its own RTPG from userspace. Anything relying on sdev->access_state without a subsequent activate (sysfs access_state/preferred_path, native SCSI multipath path selection) sees every path as active/optimized until a Unit Attention or rescan triggers an RTPG. Seen on an HP P2000 G3 FC array (implicit ALUA, two port groups, four paths per LUN) with dm-multipath not in use: sg_rtpg reports port group 0 active/non-optimized and port group 1 active/optimized, but /sys/class/scsi_device/H:C:T:L/device/access_state reads active/optimized on all four paths after boot, and no "alua: port group XX state ..." message is logged. Writing "activate" to dh_state sends the RTPG and corrects access_state. Kernels without commit 50759b881e1d queue the attach-time RTPG unconditionally and are not affected. Fix by assigning sdev->handler_data before calling alua_initialize(), and clearing it again on failure. sdev->handler is only set once scsi_dh_handler_attach() sees ->attach() succeed, so no handler callback can observe the partially initialised alua_dh_data. On the failure paths of alua_initialize(), h has not been added to a port group and no RTPG has been queued, so freeing it is unchanged. Fixes: 50759b881e1d ("scsi: device_handler: alua: Call scsi_device_put() from non-atomic context") Cc: stable@vger.kernel.org Signed-off-by: Laurence Oberman Reviewed-by: Martin Wilck Link: https://patch.msgid.link/20261109201120.1067815-1-loberman@redhat.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/device_handler/scsi_dh_alua.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/drivers/scsi/device_handler/scsi_dh_alua.c b/drivers/scsi/device_handler/scsi_dh_alua.c index 87ac0a6d63e54a..84ff3aed2c462f 100644 --- a/drivers/scsi/device_handler/scsi_dh_alua.c +++ b/drivers/scsi/device_handler/scsi_dh_alua.c @@ -1233,13 +1233,20 @@ static int alua_bus_attach(struct scsi_device *sdev) INIT_LIST_HEAD(&h->node); mutex_init(&h->init_mutex); + /* + * alua_rtpg_queue() only queues an RTPG when sdev->handler_data + * points at this alua_dh_data, so set it before alua_initialize() + * otherwise the initial RTPG issued from alua_check_vpd() is + * silently dropped and sdev->access_state is never populated. + */ + sdev->handler_data = h; err = alua_initialize(sdev, h); if (err != SCSI_DH_OK && err != SCSI_DH_DEV_OFFLINED) goto failed; - sdev->handler_data = h; return SCSI_DH_OK; failed: + sdev->handler_data = NULL; kfree(h); return err; } From dd6ff53a2706628cdd08edb202e36153de22fec9 Mon Sep 17 00:00:00 2001 From: Laurence Oberman Date: Fri, 13 Nov 2026 09:50:46 -0500 Subject: [PATCH 0801/2102] scsi: mpt3sas: Fix off-by-one in NVMe PRP list transfer size limit Commit 04631f55afc5 ("scsi: mpt3sas: Limit NVMe request size to 2 MiB") capped max_hw_sectors at 2 MiB on the basis that the 4 KiB PRP list buffer holds 512 entries. That does not account for how base_make_prp_nvme() fills the buffer: - PRP1 is placed in the main message frame and covers the first, possibly partial, page of the transfer. - When the list reaches the last 8-byte slot of the page, that slot is used for a chain pointer, so only 511 data PRPs fit. A transfer of length L starting at page offset O needs DIV_ROUND_UP(L - (4096 - O), 4096) list entries. A page aligned 2 MiB transfer needs 511 and fits. A transfer that starts at a non-zero page offset, which O_DIRECT permits with 512 byte logical blocks, can need 512: the chain pointer is written to slot 511 and the next PRP to slot 512, one entry past the end of the per-command PCIe SGL buffer. This is not limited to exactly 2 MiB; under the 2 MiB cap, any transfer of 2 MiB - 3 KiB or more starting at offset 3584 overruns, and likewise for other offsets. This was hit with the 2 MiB cap applied, on a Grace (arm64, SMMUv3 in translated mode) system with a SAS3816 and an NVMe drive, running xfs_repair from fstests on a KASAN kernel: sd 0:2:0:0: [sda] tag#2682 page boundary curr_buff: 0x00000000e986a684 BUG: KASAN: vmalloc-out-of-bounds in _base_build_sg_scmd_ieee+0x115c/0x1508 [mpt3sas] Write of size 8 at addr ffff80008cc8a000 by task xfs_repair/210713 ... The buggy address belongs to a 0-page vmalloc region starting at 0xffff80008cc89000 allocated at dma_common_pages_remap+0x30/0x88 ... Unable to handle kernel paging request at virtual address ffff80008cc8a000 Internal error: Oops: 0000000096000047 [#1] SMP pc : _base_build_sg_scmd_ieee+0x380/0x1508 [mpt3sas] Call trace: _base_build_sg_scmd_ieee+0x380/0x1508 [mpt3sas] (P) scsih_qcmd+0xdc8/0x15c8 [mpt3sas] scsi_dispatch_cmd+0x1f8/0x578 scsi_queue_rq+0x528/0x12f0 ... __blkdev_direct_IO+0x760/0xd40 blkdev_direct_IO+0x338/0x4a0 blkdev_read_iter+0x1e4/0x370 With the IOMMU remapping the coherent pool page, the overrun faults on the guard page. Without that remap it silently corrupts 8 bytes of the adjacent physical page. Limit the transfer to 511 NVMe pages (2 MiB - 4 KiB), which fits the PRP list for any starting offset. With this limit the list never reaches the last slot of the page, so the "page boundary curr_buff" message, which is only printed on the overrun path, can no longer trigger. Fixes: 04631f55afc5 ("scsi: mpt3sas: Limit NVMe request size to 2 MiB") Cc: stable@vger.kernel.org Tested-by: Laurence Oberman Signed-off-by: Laurence Oberman Link: https://patch.msgid.link/20261113145047.623807-1-loberman@redhat.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/mpt3sas/mpt3sas_scsih.c | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/drivers/scsi/mpt3sas/mpt3sas_scsih.c b/drivers/scsi/mpt3sas/mpt3sas_scsih.c index a77bbc3d2b6662..04255286a2a69e 100644 --- a/drivers/scsi/mpt3sas/mpt3sas_scsih.c +++ b/drivers/scsi/mpt3sas/mpt3sas_scsih.c @@ -57,6 +57,14 @@ #include "mpt3sas_base.h" +/* + * Largest NVMe transfer whose PRP list fits in one NVME_PRP_PAGE_SIZE + * buffer (last entry reserved for the chain pointer) for any buffer + * offset: (4096 / 8 - 1) * 4096 = 2 MiB - 4 KiB. + */ +#define MPT3SAS_NVME_MAX_XFER \ + ((NVME_PRP_PAGE_SIZE / NVME_PRP_SIZE - 1) * NVME_PRP_PAGE_SIZE) + #define RAID_CHANNEL 1 #define PCIE_CHANNEL 2 @@ -2741,14 +2749,22 @@ scsih_sdev_configure(struct scsi_device *sdev, struct queue_limits *lim) /* * The HBA firmware passes the NVMe drive's MDTS * (Maximum Data Transfer Size) up to the driver. However, - * the driver hardcodes a 4K buffer size for the PRP list, - * accommodating at most 512 entries. This strictly limits - * the maximum supported NVMe I/O transfer to 2 MiB. + * the driver hardcodes a 4K buffer size for the PRP list. + * base_make_prp_nvme() reserves the last slot of that page + * for a chain pointer, leaving 511 data PRP entries, and + * PRP1 in the main message frame covers the first, possibly + * partial, page. + * + * A transfer that is not page aligned spans one more page + * than its length implies, so a 2 MiB I/O starting at a + * non-zero page offset needs 512 list entries and overruns + * the PRP buffer by one. Limit transfers to 511 pages, which + * fits the PRP list for any starting offset. * * Cap max_hw_sectors to the smaller of the drive's reported - * MDTS or the 2 MiB driver limit to prevent kernel oopses. + * MDTS or the driver limit to prevent kernel oopses. */ - lim->max_hw_sectors = SZ_2M >> SECTOR_SHIFT; + lim->max_hw_sectors = MPT3SAS_NVME_MAX_XFER >> SECTOR_SHIFT; if (pcie_device->nvme_mdts) lim->max_hw_sectors = min(lim->max_hw_sectors, pcie_device->nvme_mdts >> SECTOR_SHIFT); From 9f9e0b1e5399045982788a954d3461de894e40c7 Mon Sep 17 00:00:00 2001 From: Changyul Lee Date: Mon, 9 Nov 2026 11:06:51 -0500 Subject: [PATCH 0802/2102] scsi: ch: Remove the minor from ch_index_idr after device_destroy() ch_remove() removes the minor from ch_index_idr before device_destroy() removes the "sch" device. A changer probed in between can get the same minor, and its device_create() fails: sysfs: cannot create duplicate filename '/class/scsi_changer/sch0' ... ch 1:0:0:0: ch0: device_create failed The new changer is then not attached. Replace the IDR entry with NULL instead, so that ch_open() still fails with -ENXIO for the changer being removed, and remove the minor after device_destroy(). Fixes: da707c54c342 ("[SCSI] ch: fix device minor number management bug") Signed-off-by: Changyul Lee Reviewed-by: Laurence Oberman Link: https://patch.msgid.link/20261109160651.986356-1-lcy8047@gmail.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/ch.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/drivers/scsi/ch.c b/drivers/scsi/ch.c index b2c9fb71c9e0a7..390425671a3a7a 100644 --- a/drivers/scsi/ch.c +++ b/drivers/scsi/ch.c @@ -952,11 +952,15 @@ static void ch_remove(struct scsi_device *sd) scsi_changer *ch = dev_get_drvdata(dev); spin_lock(&ch_index_lock); - idr_remove(&ch_index_idr, ch->minor); + idr_replace(&ch_index_idr, NULL, ch->minor); dev_set_drvdata(dev, NULL); spin_unlock(&ch_index_lock); device_destroy(&ch_sysfs_class, MKDEV(SCSI_CHANGER_MAJOR, ch->minor)); + + spin_lock(&ch_index_lock); + idr_remove(&ch_index_idr, ch->minor); + spin_unlock(&ch_index_lock); scsi_device_put(ch->device); kref_put(&ch->ref, ch_destroy); } From f277230d002d03ed98b814b735f9d3d01b42020a Mon Sep 17 00:00:00 2001 From: Cen Zhang Date: Fri, 30 Oct 2026 12:48:56 +0800 Subject: [PATCH 0803/2102] ocfs2: serialize inode journal access with shutdown The downconvert thread can run inode cleanup until ocfs2_dlm_shutdown() stops it, but unmount shuts down the journal earlier. A final dentry post-unlock put can therefore enter ocfs2_clear_inode() while the journal is being destroyed. ocfs2_ci_fully_checkpointed() loads osb->journal before taking trans_inc_lock. Journal shutdown neither takes that lock for removal nor waits for the downconvert thread before freeing the journal: Downconvert thread Unmount ------------------ ------- dentry post-unlock; final iput() ocfs2_checkpoint_inode() load osb->journal ocfs2_journal_shutdown() free journal; clear pointer read the transaction ID The checkpoint wait queue is embedded in that journal, and the final jbd2_journal_release_jbd_inode() also needs its JBD2 journal to remain alive for the whole call. Protecting only the pointer load would leave those longer uses unprotected. Read and clear osb->journal under trans_inc_lock when checking checkpoint progress. Treat a removed journal as checkpointed. Move checkpoint waiters to the existing mount-owned checkpoint_event and wake it after checkpoint progress and journal removal, so the queue outlives the journal. The commit thread also waits there and rechecks its condition when woken. Serialize the final JBD2 inode release against JBD2 destruction and the journal free with a mount-owned rw_semaphore. Take the write side only after stopping the commit thread, and drop it before the journal inode's final iput(), whose cleanup can take the read side. Inode cleanup holds the read side only around the JBD2 release, outside checkpoint waits and DLM lock teardown. KASAN report as below: Oops: general protection fault, probably for non-canonical address 0xdffffc000000000e: 0000 [#1] SMP KASAN NOPTI KASAN: null-ptr-deref in range [0x0000000000000070-0x0000000000000077] CPU: 0 UID: 0 PID: 587 Comm: ocfs2dc-33CAF04 Not tainted 7.3.0-rc4-next-20260921-pmb-ocfs2-functional-v1+ #1 PREEMPT(lazy) Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 RIP: 0010:ocfs2_clear_inode+0x8ae/0x1630 Code: fc ff df 48 c1 ea 03 80 3c 02 00 0f 85 27 0c 00 00 49 8d 7d 70 48 8b 43 c8 48 ba 00 00 00 00 00 fc ff df 48 89 f9 48 c1 e9 03 <80> 3c 11 00 0f 85 f0 0b 00 00 49 3b 45 70 0f 88 62 03 00 00 e8 49 RSP: 0018:ffff888118d3f878 EFLAGS: 00010212 RAX: 0000000000000001 RBX: ffff88811a5edc60 RCX: 000000000000000e RDX: dffffc0000000000 RSI: 0000000000000001 RDI: 0000000000000070 RBP: ffff888116134000 R08: 0000000000000001 R09: 0000000000000001 R10: ffffffff8965765f R11: 0000000000000001 R12: ffff88811a5ed400 R13: 0000000000000000 R14: ffff88811a5edbf8 R15: ffff88811a5ed408 FS: 0000000000000000(0000) GS:ffff8881fd4dc000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00007ff35b66f2c0 CR3: 00000001092ae005 CR4: 0000000000770ef0 PKRU: 55555554 Call Trace: ? __pfx_ocfs2_clear_inode+0x10/0x10 ? __pfx_ocfs2_inode_is_valid_to_delete+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? __lock_acquire+0x5a3/0x2140 ocfs2_evict_inode+0x1ed/0x11e0 ? inode_wait_for_writeback+0x14c/0x330 ? __pfx_ocfs2_evict_inode+0x10/0x10 ? lock_acquire+0x190/0x300 ? srso_alias_return_thunk+0x5/0xfbef5 ? find_held_lock+0x2b/0x80 ? evict+0x347/0x9f0 ? srso_alias_return_thunk+0x5/0xfbef5 ? lock_release+0xc8/0x290 ? _raw_spin_unlock+0x23/0x40 ? __pfx_ocfs2_evict_inode+0x10/0x10 evict+0x38b/0x9f0 ? __pfx_evict+0x10/0x10 ? lock_acquire+0x190/0x300 ? srso_alias_return_thunk+0x5/0xfbef5 ? lock_release+0xc8/0x290 ? __pfx_inode_just_drop+0x10/0x10 iput+0x680/0xb80 ocfs2_dentry_lock_put+0xc2/0x110 ? __pfx_ocfs2_dentry_post_unlock+0x10/0x10 ocfs2_process_blocked_lock+0x1fb/0x420 ? __pfx_ocfs2_process_blocked_lock+0x10/0x10 ? __pfx_pmbd_probe_hit_cookie+0x10/0x10 ? lock_release+0xc8/0x290 ? srso_alias_return_thunk+0x5/0xfbef5 ? lockdep_hardirqs_on_prepare+0xeb/0x1a0 ? srso_alias_return_thunk+0x5/0xfbef5 ocfs2_downconvert_thread+0x32b/0x780 ? do_raw_spin_lock+0x130/0x270 ? __pfx_ocfs2_downconvert_thread+0x10/0x10 ? __kthread_parkme+0xc1/0x220 ? srso_alias_return_thunk+0x5/0xfbef5 ? lock_release+0xc8/0x290 ? __pfx_autoremove_wake_function+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? srso_alias_return_thunk+0x5/0xfbef5 ? __kthread_parkme+0x177/0x220 ? __pfx_ocfs2_downconvert_thread+0x10/0x10 kthread+0x351/0x460 ? srso_alias_return_thunk+0x5/0xfbef5 ? __pfx_kthread+0x10/0x10 ret_from_fork+0x659/0x940 ? __pfx_ret_from_fork+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? __switch_to+0x74f/0xf70 ? __pfx_kthread+0x10/0x10 ret_from_fork_asm+0x1a/0x30 Modules linked in: ---[ end trace 0000000000000000 ]--- Link: https://lore.kernel.org/pm-ocfs2-objects-candidate-0004-v8-dbcb8f80b8df476084d6@gmail.com Fixes: da5e7c87827e ("ocfs2: cleanup journal init and shutdown") Signed-off-by: Cen Zhang Signed-off-by: Andrew Morton Reviewed-by: Joseph Qi Cc: Mark Fasheh Cc: Joel Becker Cc: Heming Zhao Cc: Jia-Ju Bai Cc: Cc: fs/ocfs2/inode.c | 17 +++++++++-------- fs/ocfs2/journal.c | 30 ++++++++++++++++++++++-------- fs/ocfs2/journal.h | 17 +++++++++-------- fs/ocfs2/ocfs2.h | 1 + fs/ocfs2/super.c | 1 + 5 files changed, 42 insertions(+), 24 deletions(-) --- fs/ocfs2/inode.c | 17 +++++++++-------- fs/ocfs2/journal.c | 30 ++++++++++++++++++++++-------- fs/ocfs2/journal.h | 17 +++++++++-------- fs/ocfs2/ocfs2.h | 1 + fs/ocfs2/super.c | 1 + 5 files changed, 42 insertions(+), 24 deletions(-) diff --git a/fs/ocfs2/inode.c b/fs/ocfs2/inode.c index 80c36c60a8cef9..e225a96d375353 100644 --- a/fs/ocfs2/inode.c +++ b/fs/ocfs2/inode.c @@ -1318,15 +1318,16 @@ static void ocfs2_clear_inode(struct inode *inode) oi->ip_blkno = 0ULL; /* - * ip_jinode is used to track txns against this inode. We ensure that - * the journal is flushed before journal shutdown. Thus it is safe to - * have inodes get cleaned up after journal shutdown. + * ip_jinode is used to track txns against this inode. The journal is + * flushed before it is shut down, so an inode cleaned up after that + * has nothing left to release. Hold the shutdown lock so a journal + * found here stays allocated until the release has finished. */ - if (!osb->journal) - return; - - jbd2_journal_release_jbd_inode(osb->journal->j_journal, - &oi->ip_jinode); + down_read(&osb->journal_shutdown_sem); + if (osb->journal) + jbd2_journal_release_jbd_inode(osb->journal->j_journal, + &oi->ip_jinode); + up_read(&osb->journal_shutdown_sem); } void ocfs2_evict_inode(struct inode *inode) diff --git a/fs/ocfs2/journal.c b/fs/ocfs2/journal.c index cbb44e280d4bb5..9c4a48887c9a3a 100644 --- a/fs/ocfs2/journal.c +++ b/fs/ocfs2/journal.c @@ -352,7 +352,7 @@ static int ocfs2_commit_cache(struct ocfs2_super *osb) trace_ocfs2_commit_cache_end(journal->j_trans_id, flushed); ocfs2_wake_downconvert_thread(osb); - wake_up(&journal->j_checkpointed); + wake_up(&osb->checkpoint_event); finally: return status; } @@ -901,7 +901,6 @@ int ocfs2_journal_alloc(struct ocfs2_super *osb) atomic_set(&journal->j_num_trans, 0); init_rwsem(&journal->j_trans_barrier); - init_waitqueue_head(&journal->j_checkpointed); spin_lock_init(&journal->j_lock); journal->j_trans_id = 1UL; INIT_LIST_HEAD(&journal->j_la_cleanups); @@ -1073,12 +1072,14 @@ void ocfs2_journal_shutdown(struct ocfs2_super *osb) journal = osb->journal; if (!journal) - goto done; + return; inode = journal->j_inode; - if (journal->j_state != OCFS2_JOURNAL_LOADED) - goto done; + if (journal->j_state != OCFS2_JOURNAL_LOADED) { + down_write(&osb->journal_shutdown_sem); + goto free; + } /* need to inc inode use count - jbd2_journal_destroy will iput. */ if (!igrab(inode)) @@ -1114,6 +1115,12 @@ void ocfs2_journal_shutdown(struct ocfs2_super *osb) mlog_errno(status); } + /* + * Exclude the final JBD2 inode cleanup in ocfs2_clear_inode() while + * the journal is destroyed and freed. + */ + down_write(&osb->journal_shutdown_sem); + /* Shutdown the kernel journal system */ if (!jbd2_journal_destroy(journal->j_journal) && !status) { /* @@ -1136,10 +1143,17 @@ void ocfs2_journal_shutdown(struct ocfs2_super *osb) journal->j_state = OCFS2_JOURNAL_FREE; -done: - iput(inode); - kfree(journal); +free: + /* Serialize the removal with ocfs2_ci_fully_checkpointed(). */ + spin_lock(&trans_inc_lock); osb->journal = NULL; + spin_unlock(&trans_inc_lock); + wake_up(&osb->checkpoint_event); + kfree(journal); + up_write(&osb->journal_shutdown_sem); + + /* The journal inode's own cleanup takes the read side. */ + iput(inode); } static void ocfs2_clear_journal_error(struct super_block *sb, diff --git a/fs/ocfs2/journal.h b/fs/ocfs2/journal.h index 4b52bf7b0938e6..f6bfb5d05d3d9c 100644 --- a/fs/ocfs2/journal.h +++ b/fs/ocfs2/journal.h @@ -54,7 +54,6 @@ struct ocfs2_journal { spinlock_t j_lock; unsigned long j_trans_id; struct rw_semaphore j_trans_barrier; - wait_queue_head_t j_checkpointed; /* both fields protected by j_lock*/ struct list_head j_la_cleanups; @@ -91,11 +90,15 @@ static inline void ocfs2_set_ci_lock_trans(struct ocfs2_journal *journal, static inline int ocfs2_ci_fully_checkpointed(struct ocfs2_caching_info *ci) { int ret; - struct ocfs2_journal *journal = - OCFS2_SB(ocfs2_metadata_cache_get_super(ci))->journal; + struct ocfs2_super *osb = + OCFS2_SB(ocfs2_metadata_cache_get_super(ci)); + struct ocfs2_journal *journal; spin_lock(&trans_inc_lock); - ret = time_after(journal->j_trans_id, ci->ci_last_trans); + journal = osb->journal; + /* A NULL journal has already completed checkpointing. */ + ret = !journal || + time_after(journal->j_trans_id, ci->ci_last_trans); spin_unlock(&trans_inc_lock); return ret; } @@ -196,9 +199,6 @@ static inline void ocfs2_checkpoint_inode(struct inode *inode) if (ocfs2_mount_local(osb)) return; - if (!osb->journal) - return; - if (!ocfs2_ci_fully_checkpointed(INODE_CACHE(inode))) { /* WARNING: This only kicks off a single * checkpoint. If someone races you and adds more @@ -208,7 +208,8 @@ static inline void ocfs2_checkpoint_inode(struct inode *inode) * OK. */ ocfs2_start_checkpoint(osb); - wait_event(osb->journal->j_checkpointed, + /* The wait queue must outlive journal shutdown. */ + wait_event(osb->checkpoint_event, ocfs2_ci_fully_checkpointed(INODE_CACHE(inode))); } } diff --git a/fs/ocfs2/ocfs2.h b/fs/ocfs2/ocfs2.h index e3bb3cc0b25a29..8bee145e488877 100644 --- a/fs/ocfs2/ocfs2.h +++ b/fs/ocfs2/ocfs2.h @@ -388,6 +388,7 @@ struct ocfs2_super enum ocfs2_recovery_state recovery_state; wait_queue_head_t checkpoint_event; struct ocfs2_journal *journal; + struct rw_semaphore journal_shutdown_sem; unsigned long osb_commit_interval; /* Journal triggers for checksum */ diff --git a/fs/ocfs2/super.c b/fs/ocfs2/super.c index 3072b0386db892..f7b16ef185c2d3 100644 --- a/fs/ocfs2/super.c +++ b/fs/ocfs2/super.c @@ -2048,6 +2048,7 @@ static int ocfs2_initialize_super(struct super_block *sb, } init_waitqueue_head(&osb->checkpoint_event); + init_rwsem(&osb->journal_shutdown_sem); osb->s_atime_quantum = OCFS2_DEFAULT_ATIME_QUANTUM; From e9e66aa5ef1a76ec92fe41c5eb16fda7a39db279 Mon Sep 17 00:00:00 2001 From: Cen Zhang Date: Thu, 29 Oct 2026 15:00:13 +0800 Subject: [PATCH 0804/2102] ocfs2/dlmfs: keep the superblock alive during lock work Queued dlmfs lock work holds an inode reference, but no active reference to its superblock. The workqueue is drained on module exit rather than on each dlmfs unmount, and an inode reference does not stop superblock shutdown: generic_shutdown_super() reports the busy inode and goes on. DLM callback / worker Unmount --------------------- ------- queue lock work; igrab(inode) worker delayed drop last active superblock ref kill_anon_super() report the busy inode free the superblock finish lock work iput(inode) access the inode's freed superblock Flushing the workqueue from a dlmfs kill_sb would not be enough: a blocking AST can queue new work for an inode that is still alive after the flush and before eviction, and that work again holds only an inode reference. Take an active superblock reference before acquiring the queued inode reference, with the atomic_inc_not_zero() on s_active that grab_super() and the NFS and procfs superblock walkers use. Decline to queue if the superblock is already shutting down; the inode is then being evicted and user_dlm_destroy_lock() tears the lock down. The existing l_lock and USER_LOCK_QUEUED flag serialize this with other queue attempts. Each execution drops its inode reference before releasing the active superblock reference, outside l_lock. If that releases the last active reference, the unmount completes on the worker; it only waits for DLM replies and never for this workqueue. Only the relevant frames of the report are kept: Oops: general protection fault, probably for non-canonical address 0xfbd59c0000000026: 0000 [#1] SMP KASAN NOPTI KASAN: maybe wild-memory-access in range [0xdead000000000130-0xdead000000000137] Workqueue: user_dlm user_dlm_unblock_lock RIP: 0010:iput+0x246/0xc10 Call Trace: user_dlm_unblock_lock+0x503/0xa50 process_one_work+0x9a8/0x1b40 worker_thread+0x65c/0xe40 Link: https://lore.kernel.org/pm-ocfs2-objects-candidate-0054-v6-c3887cceae3b039e591e@gmail.com Fixes: 8df08c89c668 ("[PATCH] OCFS2: The Second Oracle Cluster Filesystem") Signed-off-by: Cen Zhang Signed-off-by: Andrew Morton Reviewed-by: Joseph Qi Cc: Mark Fasheh Cc: Joel Becker Cc: Heming Zhao Cc: Jia-Ju Bai Cc: Cc: fs/ocfs2/dlmfs/userdlm.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) --- fs/ocfs2/dlmfs/userdlm.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/fs/ocfs2/dlmfs/userdlm.c b/fs/ocfs2/dlmfs/userdlm.c index 617c92e7b925d9..516e50a5728dac 100644 --- a/fs/ocfs2/dlmfs/userdlm.c +++ b/fs/ocfs2/dlmfs/userdlm.c @@ -162,7 +162,13 @@ static void user_dlm_unblock_lock(struct work_struct *work); static void __user_dlm_queue_lockres(struct user_lock_res *lockres) { + struct inode *inode = user_dlm_inode_from_user_lockres(lockres); + if (!(lockres->l_flags & USER_LOCK_QUEUED)) { + /* Pin the superblock through the worker's iput(). */ + if (!atomic_inc_not_zero(&inode->i_sb->s_active)) + return; + user_dlm_grab_inode_ref(lockres); INIT_WORK(&lockres->l_work, user_dlm_unblock_lock); @@ -275,9 +281,11 @@ static struct ocfs2_locking_protocol user_dlm_lproto = { static inline void user_dlm_drop_inode_ref(struct user_lock_res *lockres) { - struct inode *inode; - inode = user_dlm_inode_from_user_lockres(lockres); + struct inode *inode = user_dlm_inode_from_user_lockres(lockres); + struct super_block *sb = inode->i_sb; + iput(inode); + deactivate_super(sb); } static void user_dlm_unblock_lock(struct work_struct *work) From fffc86cbe3ebfd7fea3937f8698e4322b3137984 Mon Sep 17 00:00:00 2001 From: Cen Zhang Date: Thu, 29 Oct 2026 14:56:48 +0800 Subject: [PATCH 0805/2102] ocfs2: advance locking_state through the live cursor locking_state copies each lock resource under ocfs2_dlm_tracking_lock so its containing inode or quota object can be freed during the dump. The copied l_debug_list pointers do not have that lifetime protection. Yet ocfs2_dlm_seq_next() follows them to find the next record. Remounting read-only can free a quota-info object while a debugfs read is between the snapshot and the next iterator callback: locking_state reader Quota suspension -------------------- ---------------- snapshot current lock resource copy l_debug_list.next remove next resource from live list free quota-info object seq_next(): follow copied link read freed lock resource Advance through the live dummy cursor instead. List removal updates its links under the tracking lock. Position it after the resource being copied before releasing the lock, and never walk the snapshot's links. Reuse the per-open snapshot for a nonzero seq_start() position, including read continuation and buffer retries. Rewind the live cursor only when seq_file starts at index zero; seq_lseek() traverses from there through seq_next(). Clear the snapshot's l_ops marker at end of list so later reads remain at EOF. This avoids replaying the list prefix under the tracking lock on each read, without adding a new cursor or position field. KASAN report as below: BUG: KASAN: slab-use-after-free in ocfs2_dlm_next_res.isra.0+0x1b1/0x1d0 Read of size 8 at addr ffff888117ea9838 by task python3/489 CPU: 3 UID: 0 PID: 489 Comm: python3 Not tainted 7.3.0-rc4-next-20260921-pmb-bt-functional-v1+ #1 PREEMPT(lazy) Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 Call Trace: dump_stack_lvl+0x93/0xd0 print_report+0xce/0x630 ? ocfs2_dlm_next_res.isra.0+0x1b1/0x1d0 ? srso_alias_return_thunk+0x5/0xfbef5 ? __virt_addr_valid+0x20e/0x420 ? ocfs2_dlm_next_res.isra.0+0x1b1/0x1d0 kasan_report+0xe0/0x110 ? ocfs2_dlm_next_res.isra.0+0x1b1/0x1d0 ocfs2_dlm_next_res.isra.0+0x1b1/0x1d0 ? __pfx_ocfs2_dlm_next_res.isra.0+0x10/0x10 ? __pfx_do_raw_spin_lock+0x10/0x10 ocfs2_dlm_seq_next+0xb8/0x4c0 ? srso_alias_return_thunk+0x5/0xfbef5 seq_read_iter+0x92f/0x1110 ? srso_alias_return_thunk+0x5/0xfbef5 seq_read+0x362/0x5a0 ? __pfx_seq_read+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? srso_alias_return_thunk+0x5/0xfbef5 ? selinux_file_permission+0x11d/0x540 full_proxy_read+0x11f/0x180 ? __pfx_full_proxy_read+0x10/0x10 vfs_read+0x1a0/0xc20 ? srso_alias_return_thunk+0x5/0xfbef5 ? kmem_cache_free+0x242/0x580 ? __pfx_vfs_read+0x10/0x10 ? srso_alias_return_thunk+0x5/0xfbef5 ? putname+0x93/0xe0 ? srso_alias_return_thunk+0x5/0xfbef5 ? do_sys_openat2+0x12a/0x1b0 ? __pfx_do_sys_openat2+0x10/0x10 ksys_read+0x111/0x200 ? __pfx_ksys_read+0x10/0x10 ? irqentry_exit+0xbe/0x820 ? srso_alias_return_thunk+0x5/0xfbef5 ? trace_hardirqs_on_prepare+0x11d/0x150 do_syscall_64+0x114/0x620 entry_SYSCALL_64_after_hwframe+0x77/0x7f RIP: 0033:0x7f0266dbb687 Code: 48 89 fa 4c 89 df e8 58 b3 00 00 8b 93 08 03 00 00 59 5e 48 83 f8 fc 74 1a 5b c3 0f 1f 84 00 00 00 00 00 48 8b 44 24 10 0f 05 <5b> c3 0f 1f 80 00 00 00 00 83 e2 39 83 fa 08 75 de e8 23 ff ff ff RSP: 002b:00007ffccf76fc40 EFLAGS: 00000202 ORIG_RAX: 0000000000000000 RAX: ffffffffffffffda RBX: 00007f0266d27780 RCX: 00007f0266dbb687 RDX: 0000000000000001 RSI: 00007f0266a53200 RDI: 0000000000000004 RBP: 00007f0266d27700 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000202 R12: 0000000000000001 R13: 00007f0266a53200 R14: 0000000000000004 R15: 00007f0266b651e0 Allocated by task 547: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 __kasan_kmalloc+0xaa/0xb0 __kmalloc_cache_noprof+0x28d/0x610 ocfs2_local_read_info+0x181/0x1580 dquot_load_quota_sb+0x68b/0x1000 dquot_load_quota_inode+0x227/0x3e0 ocfs2_enable_quotas+0x27c/0x520 ocfs2_fill_super+0x21f9/0x38f0 get_tree_bdev_flags+0x35d/0x5f0 vfs_get_tree+0x93/0x320 fc_mount+0x1d/0x200 path_mount+0x592/0x1e00 __x64_sys_mount+0x24b/0x2d0 do_syscall_64+0x114/0x620 entry_SYSCALL_64_after_hwframe+0x77/0x7f Freed by task 577: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 kasan_save_free_info+0x3b/0x60 __kasan_slab_free+0x5f/0x80 kfree+0x308/0x580 ocfs2_local_free_info+0x47b/0x800 dquot_disable+0x5d9/0x17a0 ocfs2_susp_quotas.isra.0+0x22c/0x2b0 ocfs2_reconfigure+0x284/0xd00 reconfigure_super+0x3ca/0xa70 path_mount+0x16ae/0x1e00 __x64_sys_mount+0x24b/0x2d0 do_syscall_64+0x114/0x620 entry_SYSCALL_64_after_hwframe+0x77/0x7f The buggy address belongs to the object at ffff888117ea9800 which belongs to the cache kmalloc-1k of size 1024 The buggy address is located 56 bytes inside of freed 1024-byte region [ffff888117ea9800, ffff888117ea9c00) The buggy address belongs to the physical page: page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x117ea8 head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0 flags: 0x200000000000040(head|node=0|zone=2) page_type: f5(slab) raw: 0200000000000040 ffff888100042dc0 dead000000000100 dead000000000122 raw: 0000000000000000 0000000000100010 00000000f5000000 0000000000000000 head: 0200000000000040 ffff888100042dc0 dead000000000100 dead000000000122 head: 0000000000000000 0000000000100010 00000000f5000000 0000000000000000 head: 0200000000000003 fffffffffffffe01 00000000ffffffff 00000000ffffffff head: 0000000000000000 0000000000000000 00000000ffffffff 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff888117ea9700: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc ffff888117ea9780: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc >ffff888117ea9800: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff888117ea9880: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff888117ea9900: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ================================================================== Link: https://lore.kernel.org/pm-ocfs2-objects-candidate-0053-v7-ec41d4bbd38bb4d795a8@gmail.com Fixes: ccd979bdbce9 ("[PATCH] OCFS2: The Second Oracle Cluster Filesystem") Signed-off-by: Cen Zhang Signed-off-by: Andrew Morton Suggested-by: Joseph Qi Reviewed-by: Joseph Qi Cc: Mark Fasheh Cc: Joel Becker Cc: Heming Zhao Cc: Jia-Ju Bai Cc: Cc: fs/ocfs2/dlmglue.c | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) --- fs/ocfs2/dlmglue.c | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/fs/ocfs2/dlmglue.c b/fs/ocfs2/dlmglue.c index c281902e3becec..a4131d4dd95692 100644 --- a/fs/ocfs2/dlmglue.c +++ b/fs/ocfs2/dlmglue.c @@ -3094,9 +3094,17 @@ static void *ocfs2_dlm_seq_start(struct seq_file *m, loff_t *pos) { struct ocfs2_dlm_seq_priv *priv = m->private; struct ocfs2_lock_res *iter; + struct ocfs2_lock_res *dummy = &priv->p_iter_res; + + /* Continue or retry the snapshot left by ->next(). */ + if (*pos) + return priv->p_tmp_res.l_ops ? &priv->p_tmp_res : NULL; + /* Reads from zero and seek traversal start at the list head. */ spin_lock(&ocfs2_dlm_tracking_lock); - iter = ocfs2_dlm_next_res(&priv->p_iter_res, priv); + list_move(&dummy->l_debug_list, + &priv->p_dlm_debug->d_lockres_tracking); + iter = ocfs2_dlm_next_res(dummy, priv); if (iter) { /* Since lockres' have the lifetime of their container * (which can be inodes, ocfs2_supers, etc) we want to @@ -3105,8 +3113,11 @@ static void *ocfs2_dlm_seq_start(struct seq_file *m, loff_t *pos) * trust any pointers on the copy returned, but that's * ok as the information we want isn't typically held * in them. */ + list_move(&dummy->l_debug_list, &iter->l_debug_list); priv->p_tmp_res = *iter; iter = &priv->p_tmp_res; + } else { + priv->p_tmp_res.l_ops = NULL; } spin_unlock(&ocfs2_dlm_tracking_lock); @@ -3120,17 +3131,19 @@ static void ocfs2_dlm_seq_stop(struct seq_file *m, void *v) static void *ocfs2_dlm_seq_next(struct seq_file *m, void *v, loff_t *pos) { struct ocfs2_dlm_seq_priv *priv = m->private; - struct ocfs2_lock_res *iter = v; + struct ocfs2_lock_res *iter; struct ocfs2_lock_res *dummy = &priv->p_iter_res; (*pos)++; spin_lock(&ocfs2_dlm_tracking_lock); - iter = ocfs2_dlm_next_res(iter, priv); + iter = ocfs2_dlm_next_res(dummy, priv); list_del_init(&dummy->l_debug_list); if (iter) { list_add(&dummy->l_debug_list, &iter->l_debug_list); priv->p_tmp_res = *iter; iter = &priv->p_tmp_res; + } else { + priv->p_tmp_res.l_ops = NULL; } spin_unlock(&ocfs2_dlm_tracking_lock); From 27538caf7f72ce93be9c352148dba4f2274cf300 Mon Sep 17 00:00:00 2001 From: Sang-Heon Jeon Date: Fri, 6 Nov 2026 01:01:58 +0900 Subject: [PATCH 0806/2102] fault-inject: fix boot failure with fault injection boot parameters Since commit e9bc360b105c ("fault-inject: use prandom where cryptographically secure randomness is not needed"), setup_fault_attr() calls prandom_init_once(), which calls kmalloc() and schedule_work(). But setup_fault_attr() can be called from __setup handlers before slab and workqueues are initialized, so any fault injection boot parameter leads to boot failure. So use DO_ONCE_LITE() instead. Link: https://lore.kernel.org/20261105160209.1504867-1-ekffu200098@gmail.com Fixes: e9bc360b105c ("fault-inject: use prandom where cryptographically secure randomness is not needed") Signed-off-by: Sang-Heon Jeon Signed-off-by: Andrew Morton Reviewed-by: Akinobu Mita Cc: lib/fault-inject.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) --- lib/fault-inject.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/fault-inject.c b/lib/fault-inject.c index 02916ef2761c60..9182d457baf551 100644 --- a/lib/fault-inject.c +++ b/lib/fault-inject.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only #include #include +#include #include #include #include @@ -50,7 +51,12 @@ int setup_fault_attr(struct fault_attr *attr, char *str) return 0; } - prandom_init_once(&fault_rnd_state); + /* + * __setup handlers run before slab and workqueues are initialized, + * but prandom_init_once() calls kmalloc() and schedule_work(). So use + * DO_ONCE_LITE() instead. + */ + DO_ONCE_LITE(prandom_seed_full_state, &fault_rnd_state); attr->probability = probability; attr->interval = interval; From 5158f371faceb185235ba42882e67a840cfd7f48 Mon Sep 17 00:00:00 2001 From: Zhiyuan Zhang Date: Wed, 11 Nov 2026 02:34:44 +0000 Subject: [PATCH 0807/2102] ocfs2: fix kernel BUG in ocfs2_page_mkwrite() when write_end fails syzbot reported a kernel BUG in the ocfs2 write fault path: (syz.0.17,5578,0):ocfs2_write_end_nolock:1945 ERROR: status = -30 kernel BUG at fs/ocfs2/mmap.c:106! Call Trace: do_page_mkwrite+0x147/0x310 mm/memory.c:3879 do_shared_fault mm/memory.c:6145 [inline] handle_mm_fault+0x1a53/0x3750 mm/memory.c:6943 __ocfs2_page_mkwrite() calls ocfs2_write_begin_nolock() and then ocfs2_write_end_nolock(), and uses BUG_ON() to assert that the latter returns the full length. But ocfs2_write_end_nolock() can fail: since commit 7f27ec978b0e ("ocfs2: call ocfs2_journal_access_di() before ocfs2_journal_dirty() in ocfs2_write_end_nolock()") it gets journal access to the inode buffer again, because the handle may have been restarted since ocfs2_write_begin_nolock(). That fails with -EROFS or -EIO once the journal has been aborted or jbd2 has seen write errors on the device. The syzbot reproducer gets there by shrinking the backing loop device to zero with LOOP_SET_STATUS while writing to a shared file mapping. Handle the failure instead of crashing. ocfs2_write_end_nolock() leaves the mmap folio locked, because ocfs2_unlock_folios() skips it when w_target_locked is set so that it can be returned with VM_FAULT_LOCKED, and do_page_mkwrite() does not unlock it either when ->page_mkwrite() returns an error. So unlock it and fail the fault; the faulting task gets SIGBUS, like for the other errors in this function. For an mmap write ocfs2_write_end_nolock() returns either len or a negative errno: inline data has already been converted to extents by ocfs2_write_begin_nolock(), and copied is equal to len. The BUG matters for local mounts, where the filesystem is expected to go read-only and keep running after a journal abort. On clustered mounts ocfs2_abort() panics the node anyway as soon as it notices the aborted journal. Link: https://lore.kernel.org/20261111023444.22688-1-zhiyuanzhang912@gmail.com Fixes: 7f27ec978b0e ("ocfs2: call ocfs2_journal_access_di() before ocfs2_journal_dirty() in ocfs2_write_end_nolock()") Signed-off-by: Zhiyuan Zhang Signed-off-by: Andrew Morton Reported-by: Closes: https://syzkaller.appspot.com/bug?extid=42984127d45ad96219de Reviewed-by: Joseph Qi Reviewed-by: Heming Zhao Cc: Mark Fasheh Cc: Joel Becker Cc: yangwenfang Cc: fs/ocfs2/mmap.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) --- fs/ocfs2/mmap.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/fs/ocfs2/mmap.c b/fs/ocfs2/mmap.c index 6c570157caf16e..1c03f45e8965d0 100644 --- a/fs/ocfs2/mmap.c +++ b/fs/ocfs2/mmap.c @@ -103,7 +103,17 @@ static vm_fault_t __ocfs2_page_mkwrite(struct file *file, goto out; } err = ocfs2_write_end_nolock(mapping, pos, len, len, fsdata); - BUG_ON(err != len); + if (err != len) { + /* + * ocfs2_write_end_nolock() keeps the mmap folio locked so + * that it can be returned to the VM with VM_FAULT_LOCKED. + * On failure nobody else will unlock it, so do it here. + */ + folio_unlock(locked_folio); + mlog_errno(err); + ret = vmf_error(err); + goto out; + } ret = VM_FAULT_LOCKED; out: return ret; From e00dcd6e54b774a810d28119bad740f317df377c Mon Sep 17 00:00:00 2001 From: Konstantin Ryabitsev Date: Fri, 13 Nov 2026 18:02:45 -0500 Subject: [PATCH 0808/2102] get_maintainer: only use THE REST as a fallback Patch series "get_maintainer: stop sending every patch to LKML", v3. LKML has become mostly a firehose of patches that are already going to a subsystem list. The reason is THE REST: it matches every file in the tree, so get_maintainer.pl adds linux-kernel@vger.kernel.org to every single patch. During the week of Oct 1-7, 2026: - LKML carried 13,641 messages (~1,950/day), 90% of which were also sent to at least one other list; - with ~2,100 subscribers, that is about 29 million deliveries per week for LKML alone. This problem is becoming urgent and untenable. The increased volume of patches sent using AI tooling has resulted in dramatically higher delivery queues and if this change is not implemented, we will have to start force-unsubscribing addresses that do not show any developer activity or use similar drastic measures. This issue came up during the 2026 Maintainer Summit and the consensus was that "always include linux-kernel for every patch" was never the intent. This series makes THE REST a fallback as initially intended: it is only added for a file when no other matching MAINTAINERS section provides a mailing list that get_maintainer.pl would actually output for it. Patch 2 updates submitting-patches.rst, which currently tells submitters to send every patch to LKML. Several v1 reviewers asked for a catch-all list that would keep carrying every patch for those who want to follow all kernel development. That is a worthwhile discussion, but it is separate from this series, which only restores THE REST to its original role. Translation maintainers are Cc'd because the it_IT, ja_JP, sp_SP, zh_CN and zh_TW versions of submitting-patches.rst carry the same "send every patch to LKML" advice and will need a follow-up update once the English text is settled. This patch (of 2): THE REST matches every file in the tree via "F: *" and "F: */", so get_maintainer.pl currently adds linux-kernel@vger.kernel.org to every patch, regardless of whether the touched files already belong to a subsystem with its own mailing list. Only add THE REST for a file when no other matching section provides a mailing list that get_maintainer.pl would actually output. Lists marked "subscribers-only" are omitted unless --s is given, and lists marked "moderated" are omitted with --no-moderated, so such lists don't count as a destination in those cases. Files that match no section, or only sections without such a list, still fall back to THE REST, so every patch keeps reaching at least one known-public mailing list. Link: https://lore.kernel.org/20261113-get-maintainer-the-rest-fallback-v3-0-36ee5a3e8d13@linuxfoundation.org Link: https://lore.kernel.org/20261113-get-maintainer-the-rest-fallback-v3-1-36ee5a3e8d13@linuxfoundation.org Signed-off-by: Konstantin Ryabitsev Signed-off-by: Andrew Morton Acked-by: Joe Perches Cc: Jonathan Corbet Cc: Shuah Khan Cc: Randy Dunlap Cc: Federico Vaga Cc: Akira Yokosawa Cc: Carlos Bilbao Cc: Avadhut Naik Cc: Alex Shi Cc: Yanteng Si Cc: Dongliang Mu Cc: Chen-Yu Yeh Cc: Weijie Yuan Cc: Cc: Petr Pavlu scripts/get_maintainer.pl | 43 ++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) --- scripts/get_maintainer.pl | 43 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/scripts/get_maintainer.pl b/scripts/get_maintainer.pl index 16b80a700d4ac7..265245e568c6d3 100755 --- a/scripts/get_maintainer.pl +++ b/scripts/get_maintainer.pl @@ -959,6 +959,15 @@ sub get_maintainers { $tvi = $end + 1; } + # THE REST matches every file, so only fall back to it when no + # other matching section provides a mailing list for this file + # that we would actually output with the current options. + my ($the_rest) = grep { get_section_name($_) eq "THE REST" } keys %hash; + if (defined($the_rest) && + grep { $_ != $the_rest && section_has_list($_) } keys %hash) { + delete $hash{$the_rest}; + } + foreach my $line (sort {$hash{$b} <=> $hash{$a}} keys %hash) { add_categories($line, ""); if ($sections) { @@ -1295,6 +1304,40 @@ sub find_ending_index { return $index; } +sub get_section_name { + my ($index) = @_; + + return $typevalue[find_starting_index($index)]; +} + +sub section_has_list { + my ($index) = @_; + + my $start = find_starting_index($index); + my $end = find_ending_index($index); + for (my $i = $start; $i < $end; $i++) { + next if ($typevalue[$i] !~ m/^L:\s*(.*)/); + my $list_additional = ""; + if ($1 =~ m/[^\s]+\s+(.*)$/) { + $list_additional = $1; + } + return 1 if (list_is_selected($list_additional)); + } + return 0; +} + +# Must match the list selection in add_categories() +sub list_is_selected { + my ($list_additional) = @_; + + if ($list_additional =~ m/subscribers-only/) { + return $email_subscriber_list; + } elsif ($list_additional =~ m/moderated/) { + return $email_list && $email_moderated_list; + } + return $email_list; +} + sub get_subsystem_name { my ($index) = @_; From 3a198413bb7137907a351f43dbf1c3bf5e956900 Mon Sep 17 00:00:00 2001 From: Konstantin Ryabitsev Date: Fri, 13 Nov 2026 18:02:46 -0500 Subject: [PATCH 0809/2102] docs: submitting-patches: make LKML a list of last resort again Commit 77167b966b7e ("docs: submitting-patches: clarify the role of LKML") changed the documentation to say that all patches should be sent to LKML by default, because get_maintainer.pl always suggested it. Now that get_maintainer.pl only falls back to THE REST when no other matching section provides a mailing list, update the documentation to match: send patches to the subsystem-specific list, and use LKML only when there isn't one. Link: https://lore.kernel.org/20261113-get-maintainer-the-rest-fallback-v3-2-36ee5a3e8d13@linuxfoundation.org Signed-off-by: Konstantin Ryabitsev Signed-off-by: Andrew Morton Suggested-by: Petr Pavlu Acked-by: Randy Dunlap Acked-by: Joe Perches Cc: Jonathan Corbet Cc: Shuah Khan Cc: Federico Vaga Cc: Akira Yokosawa Cc: Carlos Bilbao Cc: Avadhut Naik Cc: Alex Shi Cc: Yanteng Si Cc: Dongliang Mu Cc: Chen-Yu Yeh Cc: Weijie Yuan Cc: Documentation/process/submitting-patches.rst | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) --- Documentation/process/submitting-patches.rst | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Documentation/process/submitting-patches.rst b/Documentation/process/submitting-patches.rst index f271d7413f72cf..85ba046d66fbf9 100644 --- a/Documentation/process/submitting-patches.rst +++ b/Documentation/process/submitting-patches.rst @@ -239,9 +239,12 @@ patches as arguments to scripts/get_maintainer.pl). If you cannot find a maintainer for the subsystem you are working on, Andrew Morton (akpm@linux-foundation.org) serves as a maintainer of last resort. -linux-kernel@vger.kernel.org should be used by default for all patches, but the -volume on that list has caused a number of developers to tune it out. Please -do not spam unrelated lists and unrelated people, though. +You should also normally choose at least one mailing list to receive a copy of +your patch set. Look in the MAINTAINERS file for a subsystem-specific list; +your patch will probably get more attention there. +linux-kernel@vger.kernel.org functions as a list of last resort for patches +that do not have a subsystem-specific list. Please do not spam unrelated lists +and unrelated people, though. Many kernel-related lists are hosted at kernel.org; you can find a list of them at https://subspace.kernel.org. There are kernel-related lists From f5d6f3184eacca5cdf04b39db1e8fc4b244e029e Mon Sep 17 00:00:00 2001 From: Bradley Morgan Date: Mon, 9 Nov 2026 19:19:28 +0000 Subject: [PATCH 0810/2102] mailmap: update email address for Bradley Morgan I switched to bradley.morgan@linux.dev for kernel work, so map the brads@mainlining.org and include@grrlz.net addresses over to keep shortlog and blame from splitting commits between them. Link: https://lore.kernel.org/20261109191928.3222846-1-bradley.morgan@linux.dev Signed-off-by: Bradley Morgan Signed-off-by: Andrew Morton Cc: Bradley Morgan .mailmap | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) --- .mailmap | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.mailmap b/.mailmap index 7fb33babc93122..6f70da175314c1 100644 --- a/.mailmap +++ b/.mailmap @@ -180,7 +180,8 @@ Boris Brezillon Boris Brezillon Boris Brezillon Boris Brezillon -Bradley Morgan +Bradley Morgan +Bradley Morgan Brendan Higgins Brendan Jackman Brian Avery From d61d78af3286548cef8e31ac578c0ed0df090f94 Mon Sep 17 00:00:00 2001 From: Mika Westerberg Date: Wed, 11 Nov 2026 13:39:09 +0100 Subject: [PATCH 0811/2102] mailmap: update Mika Westerberg's email address My @linux.intel.com address will be going away soon so switch to use my @kernel.org address. Link: https://lore.kernel.org/20261111123910.1324579-1-mika.westerberg@linux.intel.com Signed-off-by: Mika Westerberg Signed-off-by: Andrew Morton Cc: Yehezkel Bernat Cc: Lukas Wunner Cc: Andreas Noever .mailmap | 1 + 1 file changed, 1 insertion(+) --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 6f70da175314c1..5700c1179f1db2 100644 --- a/.mailmap +++ b/.mailmap @@ -669,6 +669,7 @@ Michel Lespinasse Michel Lespinasse Mickaël Salaün Miguel Ojeda +Mika Westerberg Mike Leach Mike Rapoport Mike Rapoport From f0bff4871f91501b8d30e787f15865c3f1f08870 Mon Sep 17 00:00:00 2001 From: Miaoqing Pan Date: Mon, 16 Nov 2026 10:32:26 +0800 Subject: [PATCH 0812/2102] mailmap: add entries for Miaoqing Pan MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Map past iterations of my e-mail addresses to the current one. Link: https://lore.kernel.org/20261116023226.17265-1-miaoqing.pan@oss.qualcomm.com Signed-off-by: Miaoqing Pan Signed-off-by: Andrew Morton Cc: Jeff Johnson Cc: Jakub Kicinski Cc: Alexander Sverdlin Cc: Chuck Lever Cc: Eugen Hristev Cc: Stéphane Grosjean Cc: Alice Mikityanska .mailmap | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) --- .mailmap | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.mailmap b/.mailmap index 5700c1179f1db2..ec50d7ee230152 100644 --- a/.mailmap +++ b/.mailmap @@ -656,7 +656,8 @@ Maxwell Doose Maya Erez Mayuresh Janorkar Md Sadre Alam -Miaoqing Pan +Miaoqing Pan +Miaoqing Pan Michael Buesch Michael Chan Michael Grzeschik From a357471e83422c49d1bb7fb8a666f34aa5e52433 Mon Sep 17 00:00:00 2001 From: "Luiz Capitulino (Red Hat)" Date: Mon, 16 Nov 2026 16:57:56 -0500 Subject: [PATCH 0813/2102] mailmap: add entries for Luiz Capitulino Map my previous addresses to my linux.dev address, which I'll be using for kernel work going forward. Link: https://lore.kernel.org/20261116215756.133593-1-luiz.capitulino@linux.dev Signed-off-by: Luiz Capitulino (Red Hat) Signed-off-by: Andrew Morton Acked-by: Nico Pache .mailmap | 3 +++ 1 file changed, 3 insertions(+) --- .mailmap | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.mailmap b/.mailmap index ec50d7ee230152..a188b926033edd 100644 --- a/.mailmap +++ b/.mailmap @@ -587,6 +587,9 @@ Lorenzo Stoakes Luca Ceresoli Luca Weiss Lucas De Marchi +Luiz Capitulino +Luiz Capitulino +Luiz Capitulino Lukasz Luba Luo Jie Luo Jie From 7aa8cba37cfd56e3d08f0391a99b312f9aed4df6 Mon Sep 17 00:00:00 2001 From: Naman Jain Date: Tue, 17 Nov 2026 08:45:42 +0000 Subject: [PATCH 0814/2102] mailmap: update email address for Naman Jain My Qualcomm email address is no longer accessible. Map it to my current Microsoft email address. Link: https://lore.kernel.org/20261117084542.2076622-1-namjain@linux.microsoft.com Signed-off-by: Naman Jain Signed-off-by: Andrew Morton Cc: Jakub Kicinski Cc: Bastien Curutchet (Schneider Electric) Cc: Douglas Anderson Cc: Jesper Dangaard Brouer Cc: Alexander Sverdlin Cc: Chuck Lever Cc: Jeff Johnson .mailmap | 1 + 1 file changed, 1 insertion(+) --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index a188b926033edd..b6c0b70fb2bb17 100644 --- a/.mailmap +++ b/.mailmap @@ -695,6 +695,7 @@ Mythri P K Nadav Amit Nadav Amit Nadia Yvette Chambers William Lee Irwin III +Naman Jain Naoya Horiguchi Naoya Horiguchi Natalie Vock From b5267747764169008da1d5cb88e19ecf0a289b3e Mon Sep 17 00:00:00 2001 From: "Beat M. Liechti" Date: Sun, 1 Nov 2026 13:37:29 +0100 Subject: [PATCH 0815/2102] mailmap: add entry for Beat M. Liechti Map my old address, used for the firedtv fixes in 2009, to my current one. Link: https://lore.kernel.org/20261101123733.10578-1-beat@softbase.tech Signed-off-by: Beat M. Liechti Signed-off-by: Andrew Morton .mailmap | 1 + 1 file changed, 1 insertion(+) --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index b6c0b70fb2bb17..96abae658e213a 100644 --- a/.mailmap +++ b/.mailmap @@ -154,6 +154,7 @@ Bart Van Assche Bart Van Assche Bartosz Golaszewski Bartosz Golaszewski +Beat M. Liechti Ben Dooks Ben Dooks Ben Gardner From 6f7fd2b4c2f1fad4394bae20c59192723a0704fc Mon Sep 17 00:00:00 2001 From: Wang Yibo Date: Mon, 9 Nov 2026 11:06:51 +0800 Subject: [PATCH 0816/2102] mailmap: add Wang Yibo's work email address My kernel work will be signed off with my company address from now on. Add it to .mailmap and map the personal address I used before to it, so that both resolve to the same author in git log and git shortlog. Link: https://lore.kernel.org/20261109030651.2289573-1-wangyibo@kylinos.cn Signed-off-by: Wang Yibo Signed-off-by: Andrew Morton .mailmap | 1 + 1 file changed, 1 insertion(+) --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 96abae658e213a..75d591476332ca 100644 --- a/.mailmap +++ b/.mailmap @@ -1012,6 +1012,7 @@ Vlad Dogaru Vladimir Davydov Vladimir Davydov Vlastimil Babka +Wang Yibo WangYuli WangYuli Wei Wang From 3a1ed9b7ecdcbfadd3529b59938cd706b74149c4 Mon Sep 17 00:00:00 2001 From: Ridong Chen Date: Sun, 8 Nov 2026 20:35:09 +0800 Subject: [PATCH 0817/2102] mailmap: add entries for Ridong Chen Map my former Huawei address and my current Xiaomi address to my personal address, so that all my contributions are attributed to a single identity. Link: https://lore.kernel.org/20261108123509.214127-1-ridong.chen@linux.dev Signed-off-by: Ridong Chen Signed-off-by: Andrew Morton .mailmap | 2 ++ 1 file changed, 2 insertions(+) --- .mailmap | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.mailmap b/.mailmap index 75d591476332ca..61e5eeecd09d35 100644 --- a/.mailmap +++ b/.mailmap @@ -815,6 +815,8 @@ Richard Genoud Richard Leitner Richard Leitner Richard Leitner +Ridong Chen +Ridong Chen Rob Clark Rob Clark Robert Foss From b2ddfc1c1afdd087f5d8bb3a59bdba8cb562ad83 Mon Sep 17 00:00:00 2001 From: Guodong Xu Date: Fri, 6 Nov 2026 16:30:48 -0500 Subject: [PATCH 0818/2102] mailmap: update entry for Guodong Xu Use my linux.dev address for kernel correspondence, including for contributions made with my other email addresses. It is not tied to a personal or employer mailbox. Link: https://lore.kernel.org/7e9369cf1473539bafe9cb90207ba6fe98b534ca.1794001419.git.guodong.xu@linux.dev Signed-off-by: Guodong Xu Signed-off-by: Andrew Morton .mailmap | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) --- .mailmap | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.mailmap b/.mailmap index 61e5eeecd09d35..5357e310d75e73 100644 --- a/.mailmap +++ b/.mailmap @@ -358,8 +358,10 @@ Gokul Sriram Palanisamy Govindaraj Saminathan Guo Ren Guo Ren -Guodong Xu -Guodong Xu +Guodong Xu +Guodong Xu +Guodong Xu +Guodong Xu Guru Das Srinagesh Guru Das Srinagesh Guru Das Srinagesh From 099ed44ed4fb83e5eae85db900aa704142c5d3b9 Mon Sep 17 00:00:00 2001 From: Alex Elder Date: Tue, 10 Nov 2026 08:42:47 -0600 Subject: [PATCH 0819/2102] mailmap: add an alias for Alex Elder Add an entry to .mailmap to indicate that represents the same person as . Link: https://lore.kernel.org/20261110144250.656840-1-elder@riscstar.com Signed-off-by: Alex Elder Signed-off-by: Andrew Morton Cc: Jakub Kicinski Cc: Alex Elder .mailmap | 1 + 1 file changed, 1 insertion(+) --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 5357e310d75e73..a50c1584fcac22 100644 --- a/.mailmap +++ b/.mailmap @@ -64,6 +64,7 @@ Alex Elder Alex Elder Alex Elder Alex Elder +Alex Elder Alex Hung Alex Shi Alex Shi From 971da83016eb6c6d110580d9b2881f7d2bcfe503 Mon Sep 17 00:00:00 2001 From: Sai Teja Aluvala Date: Tue, 17 Nov 2026 19:00:08 +0530 Subject: [PATCH 0820/2102] mailmap: update email address for Sai Teja Aluvala Map my former Qualcomm email address to my current Intel email address. Link: https://lore.kernel.org/20261117133008.2560155-1-aluvala.sai.teja@intel.com Signed-off-by: Sai Teja Aluvala Signed-off-by: Andrew Morton Cc: Jeff Johnson .mailmap | 1 + 1 file changed, 1 insertion(+) --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index a50c1584fcac22..f0db1e540657b6 100644 --- a/.mailmap +++ b/.mailmap @@ -838,6 +838,7 @@ Rui Saraiva Sachin Mokashi Sachin P Sant Sai Prakash Ranjan +Sai Teja Aluvala Sakari Ailus Sam Protsenko Sam Protsenko From 59233c1123c2e800055ec685407a004351ae3f62 Mon Sep 17 00:00:00 2001 From: Andrea Cervesato Date: Mon, 26 Oct 2026 11:47:17 +0100 Subject: [PATCH 0821/2102] MAINTAINERS: update Andrea Cervesato's email for LTP I'm not working for SUSE anymore and I will use linux.dev email to develop and maintain Linux Test Project. Also update .mailmap. Link: https://lore.kernel.org/20261026-acer_maintainers-v2-1-4cf0f350fdf1@linux.dev Signed-off-by: Andrea Cervesato Signed-off-by: Andrew Morton Acked-by: Petr Vorel Reviewed-by: Li Wang (Hieco) Reviewed-by: Cyril Hrubis .mailmap | 1 + MAINTAINERS | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) --- .mailmap | 1 + MAINTAINERS | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.mailmap b/.mailmap index f0db1e540657b6..2ed63c8243305b 100644 --- a/.mailmap +++ b/.mailmap @@ -83,6 +83,7 @@ Amit Blay Amit Nischal Andi Kleen Andi Shyti +Andrea Cervesato Andreas Herrmann Andreas Hindborg Andrej Shadura diff --git a/MAINTAINERS b/MAINTAINERS index 05aa377ca912f3..9bbf5171578f38 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -15933,7 +15933,7 @@ F: Documentation/devicetree/bindings/i2c/i2c-mux-ltc4306.txt F: drivers/i2c/muxes/i2c-mux-ltc4306.c LTP (Linux Test Project) -M: Andrea Cervesato +M: Andrea Cervesato M: Cyril Hrubis M: Jan Stancek M: Petr Vorel From a001666afbf9d2a6096fea95686549b9b1c9d968 Mon Sep 17 00:00:00 2001 From: Joe Perches Date: Sun, 1 Nov 2026 00:41:12 -0700 Subject: [PATCH 0822/2102] MAINTAINERS: DRM DRIVERS AND MISC GPU PATCHES There's a small defect in get_maintainers.pl that allows incomplete file pattern matching. Update the "F: include/drm/drm pattern" to specify only the actual files covered instead of a prefixed partial path to these .h files. Link: https://lore.kernel.org/576e04e1d8f0d5ac0805d450b9c87e69f7f0d2c8.camel@perches.com Signed-off-by: Joe Perches Signed-off-by: Andrew Morton Cc: Maarten Lankhorst Cc: Maxime Ripard Cc: Thomas Zimmermann Cc: Borislav Petkov MAINTAINERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) --- MAINTAINERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index 9bbf5171578f38..b0267529f91f0b 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -8883,7 +8883,7 @@ F: Documentation/devicetree/bindings/gpu/ F: Documentation/gpu/ F: drivers/gpu/drm/ F: drivers/gpu/vga/ -F: include/drm/drm +F: include/drm/drm*.h F: include/linux/vga* F: include/uapi/drm/ X: drivers/gpu/drm/amd/ From 8c417209754a9d2cd8dc1e78c0dfadefd0ad0e82 Mon Sep 17 00:00:00 2001 From: Qiang Han Date: Sun, 8 Nov 2026 06:07:11 +0000 Subject: [PATCH 0823/2102] drm/amdkfd: wait for the queue quiesce in concurrent SVM evictions With XNACK off, svm_range_evict() leaves the GPU page tables in place and relies on the process's queues being stopped before the MMU notifier returns. Only the first eviction (evicted_ranges == 1) calls kgd2kfd_quiesce_mm(). The quiesce preempts every GPU the process has opened and takes milliseconds. Any other range invalidated in the meantime sees evicted_ranges > 1 and returns at once. The core mm then frees, migrates or reuses the page while the queues still run, and an in-flight SDMA or blit copy accesses it through the old GPU PTE. The result is silent corruption of the copy, or of whatever process now owns the page. Hold a new svms->evict_lock across the first evictor's quiesce, so that concurrent evictions return only after the queues have stopped. This is the scheme amdgpu_amdkfd_evict_userptr() uses with process_info->notifier_lock. evict_lock nests inside prange->lock and is taken nowhere else. Under it, the quiesce path takes the dqm lock, which is already used in MMU notifiers (memalloc_noreclaim). One way to reach this: a pageable hipMemcpy() larger than 1 MiB. ROCclr pins the buffer with hsa_amd_memory_lock(), libhsakmt registers it as a KFD SVM range, and host memory pressure (reclaim, compaction, allocator purge) invalidates the range. Fixes: 8a7c184a16d7 ("drm/amdkfd: svm range eviction and restore") Signed-off-by: Qiang Han Signed-off-by: Philip Yang Reviewed-by: Felix Kuehling Signed-off-by: Alex Deucher (cherry picked from commit d443bd2512c04a5d34c4473ce9ce2f2a6f7bf8f5) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_priv.h | 2 ++ drivers/gpu/drm/amd/amdkfd/kfd_svm.c | 35 ++++++++++++++++++--------- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h index 436160549386d6..ccb7bbde112dc4 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h +++ b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h @@ -906,6 +906,8 @@ struct svm_range_list { struct list_head deferred_range_list; struct list_head criu_svm_metadata_list; spinlock_t deferred_list_lock; + /* serializes XNACK-off evictions with the queue quiesce */ + struct mutex evict_lock; atomic_t evicted_ranges; atomic_t drain_pagefaults; struct delayed_work restore_work; diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c index 7fd331612f08cd..e132a0079ea7ef 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c @@ -2116,21 +2116,30 @@ svm_range_evict(struct svm_range *prange, struct mm_struct *mm, if (prange->start <= last && prange->last >= start) atomic_inc(&prange->invalid); + /* The MMU notifier must not return before the GPU has stopped + * accessing the invalidated pages. Only the first eviction stops + * the queues, which takes milliseconds (HWS preemption on every + * GPU of the process). Serialize all evictions of this process so + * that a concurrent invalidation of another range waits until + * that quiesce has completed instead of returning while queues + * still run on stale PTEs. + */ + mutex_lock(&svms->evict_lock); evicted_ranges = atomic_inc_return(&svms->evicted_ranges); - if (evicted_ranges != 1) - return r; - - pr_debug("evicting svms 0x%p range [0x%lx 0x%lx]\n", - prange->svms, prange->start, prange->last); + if (evicted_ranges == 1) { + pr_debug("evicting svms 0x%p range [0x%lx 0x%lx]\n", + prange->svms, prange->start, prange->last); - /* First eviction, stop the queues */ - r = kgd2kfd_quiesce_mm(mm, KFD_QUEUE_EVICTION_TRIGGER_SVM); - if (r) - pr_debug("failed to quiesce KFD\n"); + /* First eviction, stop the queues */ + r = kgd2kfd_quiesce_mm(mm, KFD_QUEUE_EVICTION_TRIGGER_SVM); + if (r) + pr_debug("failed to quiesce KFD\n"); - pr_debug("schedule to restore svm %p ranges\n", svms); - queue_delayed_work(system_freezable_wq, &svms->restore_work, - msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS)); + pr_debug("schedule to restore svm %p ranges\n", svms); + queue_delayed_work(system_freezable_wq, &svms->restore_work, + msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS)); + } + mutex_unlock(&svms->evict_lock); } else { unsigned long s, l; uint32_t trigger; @@ -3412,6 +3421,7 @@ void svm_range_list_fini(struct kfd_process *p) svm_range_free(prange, true); } + mutex_destroy(&p->svms.evict_lock); mutex_destroy(&p->svms.lock); pr_debug("process pid %d svms 0x%p done\n", @@ -3425,6 +3435,7 @@ int svm_range_list_init(struct kfd_process *p) svms->objects = RB_ROOT_CACHED; mutex_init(&svms->lock); + mutex_init(&svms->evict_lock); INIT_LIST_HEAD(&svms->list); atomic_set(&svms->evicted_ranges, 0); atomic_set(&svms->drain_pagefaults, 0); From 7345797c8652c976d18dc4be4bae632557c3bc38 Mon Sep 17 00:00:00 2001 From: Andrey Misiurov Date: Mon, 9 Nov 2026 16:52:15 +0100 Subject: [PATCH 0824/2102] drm/radeon: Bound GPIO I2C table entry count from VBIOS radeon_atombios_i2c_init() derives the number of GPIO I2C entries from the size field of the VBIOS GPIO_I2C_Info table and stores a bus for every valid entry in rdev->i2c_bus[i], which has RADEON_MAX_I2C_BUS (16) slots. A table that claims more than 16 entries makes it write past the end of the array into the rest of struct radeon_device. A size smaller than the common header wraps the subtraction and the loop walks far past the table. radeon_lookup_i2c_gpio() uses the same calculation. Reject undersized tables and cap the entry count at RADEON_MAX_I2C_BUS. Fixes: f376b94fbc0a ("drm/radeon/kms: unify i2c handling") Reviewed-by: Alex Deucher Signed-off-by: Andrey Misiurov Signed-off-by: Alex Deucher (cherry picked from commit ad5ddb2f77ff5e80b3c793f062dc1cad9907a2b9) Cc: stable@vger.kernel.org --- drivers/gpu/drm/radeon/radeon_atombios.c | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/radeon/radeon_atombios.c b/drivers/gpu/drm/radeon/radeon_atombios.c index 3dd9724b331d6d..c4e1272cd843fb 100644 --- a/drivers/gpu/drm/radeon/radeon_atombios.c +++ b/drivers/gpu/drm/radeon/radeon_atombios.c @@ -125,6 +125,22 @@ static struct radeon_i2c_bus_rec radeon_get_bus_rec_for_i2c_gpio(ATOM_GPIO_I2C_A return i2c; } +/* + * The VBIOS table size is not checked against the image; cap the + * entry count to RADEON_MAX_I2C_BUS, the size of rdev->i2c_bus[]. + */ +static int radeon_atombios_gpio_i2c_num_entries(uint16_t size) +{ + u32 bytes; + + if (size < sizeof(ATOM_COMMON_TABLE_HEADER)) + return 0; + + bytes = size - sizeof(ATOM_COMMON_TABLE_HEADER); + return min_t(u32, bytes / sizeof(ATOM_GPIO_I2C_ASSIGMENT), + RADEON_MAX_I2C_BUS); +} + static struct radeon_i2c_bus_rec radeon_lookup_i2c_gpio(struct radeon_device *rdev, uint8_t id) { @@ -142,8 +158,7 @@ static struct radeon_i2c_bus_rec radeon_lookup_i2c_gpio(struct radeon_device *rd if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) { i2c_info = (struct _ATOM_GPIO_I2C_INFO *)(ctx->bios + data_offset); - num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) / - sizeof(ATOM_GPIO_I2C_ASSIGMENT); + num_indices = radeon_atombios_gpio_i2c_num_entries(size); gpio = &i2c_info->asGPIO_Info[0]; for (i = 0; i < num_indices; i++) { @@ -176,8 +191,7 @@ void radeon_atombios_i2c_init(struct radeon_device *rdev) if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) { i2c_info = (struct _ATOM_GPIO_I2C_INFO *)(ctx->bios + data_offset); - num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) / - sizeof(ATOM_GPIO_I2C_ASSIGMENT); + num_indices = radeon_atombios_gpio_i2c_num_entries(size); gpio = &i2c_info->asGPIO_Info[0]; for (i = 0; i < num_indices; i++) { From 11f1080ba1bd3df2b2539dab878b3e2a0a89681f Mon Sep 17 00:00:00 2001 From: Benjamin Cheng Date: Tue, 13 Oct 2026 14:39:44 -0400 Subject: [PATCH 0825/2102] drm/amdgpu: wait for tlb flush before freeing BO MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On gem object close, we previously only attached the fence of its own clear_freed() call to the BO's resv. If an unmap of this BO happened prior to the close call, clear_freed() would be invoked, leaving vm->freed empty, and no meaningful fence to be attached to the resv. Because of that the memory may be freed before the TLB flush is complete, and give a running userq potential access to a stale address translation. Fix this by attaching the last_tlb_inv fence to the BO's resv. Fixes: a1d201e16940 ("drm/amdgpu: enable GFX-V11 userqueue support") Signed-off-by: Benjamin Cheng Reviewed-by: Christian König Signed-off-by: Alex Deucher (cherry picked from commit ab88e18030a1f2c340f64172287af19d1a48d3cc) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c index b190b6c9adf299..f1b06ce28ef612 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c @@ -340,7 +340,7 @@ static void amdgpu_gem_object_close(struct drm_gem_object *obj, drm_exec_init(&exec, DRM_EXEC_IGNORE_DUPLICATES, 0); drm_exec_until_all_locked(&exec) { - r = drm_exec_prepare_obj(&exec, &bo->tbo.base, 1); + r = drm_exec_prepare_obj(&exec, &bo->tbo.base, 2); /* clear_freed + last_tlb_inv */ drm_exec_retry_on_contention(&exec); if (unlikely(r)) goto out_unlock; @@ -371,11 +371,14 @@ static void amdgpu_gem_object_close(struct drm_gem_object *obj, dev_err(adev->dev, "failed to clear page " "tables on GEM object close (%ld)\n", r); if (r || !fence) - goto out_unlock; + goto out_tlb; amdgpu_bo_fence(bo, fence, true); dma_fence_put(fence); +out_tlb: + amdgpu_bo_fence(bo, vm->last_tlb_inv, true); + out_unlock: if (r && !drm_dev_is_unplugged(adev_to_drm(adev))) dev_err(adev->dev, "leaking bo va (%ld)\n", r); From 83876755d089321e426a58f365a31b27b2c77f3b Mon Sep 17 00:00:00 2001 From: Jiaming Fan Date: Tue, 10 Nov 2026 15:19:10 +0000 Subject: [PATCH 0826/2102] drm/radeon: only unregister the ATPX handler if we registered it radeon_register_atpx_handler() registers the ATPX handler with vga_switcheroo only when ATPX is detected, and ignores the result: vga_switcheroo has a single handler slot and refuses a second handler with -EINVAL. radeon_unregister_atpx_handler() calls vga_switcheroo_unregister_handler() in either case, and that clears the slot no matter who set it. So unloading radeon removes a handler registered by another driver, such as apple-gmux. No Radeon GPU is needed for this; loading and unloading radeon is enough. amdgpu is another such driver: when radeon and amdgpu are both loaded and both detect ATPX, only the first one gets the slot, and unloading the other one clears it. Afterwards vga_switcheroo can no longer switch outputs, and a client that uses the vga_switcheroo runtime PM domain, such as nouveau on a non-Optimus machine with a v1 DSM, can dereference the now NULL handler during runtime suspend. Record whether the registration succeeded and unregister only in that case. amdgpu has the same problem and gets the same fix. Fixes: 6a9ee8af344e ("vga_switcheroo: initial implementation (v15)") Reviewed-by: Alex Deucher Signed-off-by: Jiaming Fan Signed-off-by: Alex Deucher (cherry picked from commit f90ef5de500fa47d8e2371d429700f0275e0b88d) Cc: stable@vger.kernel.org --- drivers/gpu/drm/radeon/radeon_atpx_handler.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/radeon/radeon_atpx_handler.c b/drivers/gpu/drm/radeon/radeon_atpx_handler.c index f557535c1d7b3e..9ed75c69c6151a 100644 --- a/drivers/gpu/drm/radeon/radeon_atpx_handler.c +++ b/drivers/gpu/drm/radeon/radeon_atpx_handler.c @@ -34,6 +34,7 @@ struct radeon_atpx { static struct radeon_atpx_priv { bool atpx_detected; bool bridge_pm_usable; + bool handler_registered; /* handle for device - and atpx */ acpi_handle dhandle; struct radeon_atpx atpx; @@ -605,7 +606,8 @@ void radeon_register_atpx_handler(void) if (!r) return; - vga_switcheroo_register_handler(&radeon_atpx_handler, handler_flags); + if (!vga_switcheroo_register_handler(&radeon_atpx_handler, handler_flags)) + radeon_atpx_priv.handler_registered = true; } /** @@ -615,5 +617,14 @@ void radeon_register_atpx_handler(void) */ void radeon_unregister_atpx_handler(void) { + /* + * vga_switcheroo has a single handler slot and unregistering clears it + * no matter who set it, so leave a handler registered by another + * driver, such as amdgpu or apple-gmux, in place. + */ + if (!radeon_atpx_priv.handler_registered) + return; + vga_switcheroo_unregister_handler(); + radeon_atpx_priv.handler_registered = false; } From 70ea88787150cbe514156d7ec49c96d3b8acda76 Mon Sep 17 00:00:00 2001 From: Benjamin Cheng Date: Mon, 9 Nov 2026 09:45:48 -0500 Subject: [PATCH 0827/2102] drm/amdgpu/gem: use dma_resv_add_fence directly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Christian pointed out that amdgpu_bo_fence() is deprecated since it reserves fence slots there outside of the lock. Replace it with a direct dma_resv_add_fence call here (we reserve the correct amount of fences already). Also switch it to use the BOOKKEEP usage since these are both kernel-internal fences. Signed-off-by: Benjamin Cheng Reviewed-by: Christian König Signed-off-by: Alex Deucher (cherry picked from commit 072d03903b17f89280b13e6baaa2f66037fcea4b) --- drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c index f1b06ce28ef612..c1d715749e0203 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c @@ -373,11 +373,11 @@ static void amdgpu_gem_object_close(struct drm_gem_object *obj, if (r || !fence) goto out_tlb; - amdgpu_bo_fence(bo, fence, true); + dma_resv_add_fence(bo->tbo.base.resv, fence, DMA_RESV_USAGE_BOOKKEEP); dma_fence_put(fence); out_tlb: - amdgpu_bo_fence(bo, vm->last_tlb_inv, true); + dma_resv_add_fence(bo->tbo.base.resv, vm->last_tlb_inv, DMA_RESV_USAGE_BOOKKEEP); out_unlock: if (r && !drm_dev_is_unplugged(adev_to_drm(adev))) From 535f6852652e3239c8688491ccd0ed4b6e09d14f Mon Sep 17 00:00:00 2001 From: Joshua Horne Date: Mon, 9 Nov 2026 21:01:45 -0500 Subject: [PATCH 0828/2102] drm/amd/pm: send smu8 sclk level indices, not the level mask smu8_force_clock_level() passes the pp_dpm_sclk level mask straight to PPSMC_MSG_SetSclkSoftMin and PPSMC_MSG_SetSclkSoftMax, which take a level index, as the other smu8 callers do through smu8_get_sclk_level(). In manual mode, "echo 0 > pp_dpm_sclk" thus selects level 1, "echo 2" selects level 4, and masks above the highest level index are out of range for the SMU, so e.g. "echo 3", "echo 7" or "echo 0 1 2 3 4 5 6 7" do not select the requested levels. The original single level version sent 1 << level and had the same problem. Send the lowest and highest level in the mask, as smu10 does, and reject levels above those the SMU has enabled, as smu10 and vega20 do. Fixes: d7341ef66870 ("drm/amd/powerplay: add some hwmgr functions for sysfs interface on Carrizo") Reviewed-by: Alex Deucher Signed-off-by: Joshua Horne Signed-off-by: Alex Deucher (cherry picked from commit 8ff6b368360adb24ccf145047b0261dfae77f28a) Cc: stable@vger.kernel.org --- .../gpu/drm/amd/pm/powerplay/hwmgr/smu8_hwmgr.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/amd/pm/powerplay/hwmgr/smu8_hwmgr.c b/drivers/gpu/drm/amd/pm/powerplay/hwmgr/smu8_hwmgr.c index 8f82d7c07e8c82..5a3f697a37a254 100644 --- a/drivers/gpu/drm/amd/pm/powerplay/hwmgr/smu8_hwmgr.c +++ b/drivers/gpu/drm/amd/pm/powerplay/hwmgr/smu8_hwmgr.c @@ -1483,15 +1483,25 @@ static int smu8_store_cc6_data(struct pp_hwmgr *hwmgr, uint32_t separation_time, static int smu8_force_clock_level(struct pp_hwmgr *hwmgr, enum pp_clock_type type, uint32_t mask) { + struct phm_clock_voltage_dependency_table *table = + hwmgr->dyn_state.vddc_dependency_on_sclk; + uint32_t low, high; + switch (type) { case PP_SCLK: + /* the SMU takes level indices, not a mask of levels */ + low = mask ? (ffs(mask) - 1) : 0; + high = mask ? (fls(mask) - 1) : 0; + if (high >= min(table->count, smu8_get_max_sclk_level(hwmgr))) + return -EINVAL; + smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMin, - mask, + low, NULL); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMax, - mask, + high, NULL); break; default: From 24916f2c98f86c90db617d0e828d930d7a35577e Mon Sep 17 00:00:00 2001 From: Wang Jiang Date: Tue, 10 Nov 2026 16:34:53 +0800 Subject: [PATCH 0829/2102] drm/amdgpu/gfx_v9_0: Add gfxoff quirk for Lenovo Picasso 318F GFXOFF causes gfx ring timeout and desktop freeze on Lenovo 90NYA05DCD (Ryzen 5 3400G, Picasso). Add a quirk entry with ANY_REV marker to disable gfxoff for subsystem 17aa:318f regardless of chip revision. Reviewed-by: Alex Deucher Signed-off-by: Wang Jiang Signed-off-by: Alex Deucher (cherry picked from commit 32a647c3218d8bb5bf03f68784fbc405c1e5fbd3) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c b/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c index 1678015ce5a970..ae1d94c5f52829 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c @@ -1369,6 +1369,9 @@ struct amdgpu_gfxoff_quirk { u8 revision; }; +/* Match any chip revision in amdgpu_gfxoff_quirk.revision */ +#define AMDGPU_GFXOFF_QUIRK_ANY_REV 0xff + static const struct amdgpu_gfxoff_quirk amdgpu_gfxoff_quirk_list[] = { /* https://bugzilla.kernel.org/show_bug.cgi?id=204689 */ { 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 }, @@ -1378,6 +1381,7 @@ static const struct amdgpu_gfxoff_quirk amdgpu_gfxoff_quirk_list[] = { { 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc6 }, /* Apple MacBook Pro (15-inch, 2019) Radeon Pro Vega 20 4 GB */ { 0x1002, 0x69af, 0x106b, 0x019a, 0xc0 }, + { 0x1002, 0x15d8, 0x17aa, 0x318f, AMDGPU_GFXOFF_QUIRK_ANY_REV }, /* https://bbs.openkylin.top/t/topic/171497 */ { 0x1002, 0x15d8, 0x19e5, 0x3e14, 0xc2 }, /* HP 705G4 DM with R5 2400G */ @@ -1394,7 +1398,8 @@ static bool gfx_v9_0_should_disable_gfxoff(struct pci_dev *pdev) pdev->device == p->chip_device && pdev->subsystem_vendor == p->subsys_vendor && pdev->subsystem_device == p->subsys_device && - pdev->revision == p->revision) { + (p->revision == AMDGPU_GFXOFF_QUIRK_ANY_REV || + pdev->revision == p->revision)) { return true; } ++p; From 53fc1be11892a8e695937fdbc24db2699d23dabf Mon Sep 17 00:00:00 2001 From: Jiaming Fan Date: Tue, 10 Nov 2026 15:14:59 +0000 Subject: [PATCH 0830/2102] drm/amdgpu: only unregister the ATPX handler if we registered it amdgpu_register_atpx_handler() registers the ATPX handler with vga_switcheroo only when ATPX is detected, and ignores the result: vga_switcheroo has a single handler slot and refuses a second handler with -EINVAL. amdgpu_unregister_atpx_handler() calls vga_switcheroo_unregister_handler() in either case, and that clears the slot no matter who set it. So unloading amdgpu removes a handler registered by another driver, such as apple-gmux. No AMD GPU is needed for this; loading and unloading amdgpu is enough. Afterwards vga_switcheroo can no longer switch outputs, and a client that uses the vga_switcheroo runtime PM domain, such as nouveau on a non-Optimus machine with a v1 DSM, can dereference the now NULL handler during runtime suspend. Record whether the registration succeeded and unregister only in that case. Fixes: d38ceaf99ed0 ("drm/amdgpu: add core driver (v4)") Reviewed-by: Alex Deucher Signed-off-by: Jiaming Fan Signed-off-by: Alex Deucher (cherry picked from commit fbb6ebeff9d5327e8d06a83a3f7daa88422c9127) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c index e2a4644896ca8b..f9467786aab960 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c @@ -45,6 +45,7 @@ struct amdgpu_atpx { static struct amdgpu_atpx_priv { bool atpx_detected; bool bridge_pm_usable; + bool handler_registered; unsigned int quirks; /* handle for device - and atpx */ acpi_handle dhandle; @@ -663,7 +664,8 @@ void amdgpu_register_atpx_handler(void) if (!r) return; - vga_switcheroo_register_handler(&amdgpu_atpx_handler, handler_flags); + if (!vga_switcheroo_register_handler(&amdgpu_atpx_handler, handler_flags)) + amdgpu_atpx_priv.handler_registered = true; } /** @@ -673,5 +675,14 @@ void amdgpu_register_atpx_handler(void) */ void amdgpu_unregister_atpx_handler(void) { + /* + * vga_switcheroo has a single handler slot and unregistering clears it + * no matter who set it, so leave a handler registered by another + * driver, such as apple-gmux, in place. + */ + if (!amdgpu_atpx_priv.handler_registered) + return; + vga_switcheroo_unregister_handler(); + amdgpu_atpx_priv.handler_registered = false; } From be94997dd5558a0e53bee97306d659e9327dcab9 Mon Sep 17 00:00:00 2001 From: Jiaming Fan Date: Tue, 10 Nov 2026 15:15:26 +0000 Subject: [PATCH 0831/2102] drm/amdgpu: unwind module init on failure amdgpu_init() registers the ATPX handler with vga_switcheroo and allocates the ACPI XCC/NUMA info before it initializes KFD, but its error paths do not undo any of that: - when amdgpu_amdkfd_init() fails, only amdgpu_sync_fini() is called; - when pci_register_driver() fails, its result is returned as is, so KFD, the ATPX handler, the ACPI info and the sync slab cache are all left behind. A failed module init frees the module, so vga_switcheroo keeps a pointer to a handler in freed memory and /dev/kfd keeps file operations that point into it. A later amdgpu load cannot register its own ATPX handler, and vga_switcheroo_enable() calls into the stale one. The KFD path is easy to reach since KFD init failures are no longer ignored: kfd_init() returns -EINVAL for an out of range sched_policy or max_num_of_queues_per_device module parameter. Unwind in the reverse order of initialization, starting from the last step that succeeded, with the same calls and in the same order as amdgpu_exit(). amdgpu_amdkfd_fini() is a no-op when KFD was not initialized, which covers the ignored -ENOENT case, and amdgpu_unregister_atpx_handler() only removes a handler that amdgpu registered itself. Fixes: 4259a25341ab ("amdkfd: Only ignore -ENOENT for KFD init failuires") Fixes: d38ceaf99ed0 ("drm/amdgpu: add core driver (v4)") Reviewed-by: Alex Deucher Signed-off-by: Jiaming Fan Signed-off-by: Alex Deucher (cherry picked from commit c2c34905fb40d3bddae0d2539830975781715e25) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c index 3e5634de077f1a..e3b3a2eebd9547 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c @@ -3221,7 +3221,7 @@ static int __init amdgpu_init(void) /* Ignore KFD init failures when CONFIG_HSA_AMD is not set. */ r = amdgpu_amdkfd_init(); if (r && r != -ENOENT) - goto error_fini_sync; + goto error_release_acpi; if (amdgpu_pp_feature_mask & PP_OVERDRIVE_MASK) { add_taint(TAINT_CPU_OUT_OF_SPEC, LOCKDEP_STILL_OK); @@ -3230,9 +3230,17 @@ static int __init amdgpu_init(void) } /* let modprobe override vga console setting */ - return pci_register_driver(&amdgpu_kms_pci_driver); + r = pci_register_driver(&amdgpu_kms_pci_driver); + if (r) + goto error_fini_kfd; + + return 0; -error_fini_sync: +error_fini_kfd: + amdgpu_amdkfd_fini(); +error_release_acpi: + amdgpu_acpi_release(); + amdgpu_unregister_atpx_handler(); amdgpu_sync_fini(); return r; } From cfb11282e0fbf5bd06e3f329f56dddc93e749679 Mon Sep 17 00:00:00 2001 From: Erhan Bilgili Date: Thu, 12 Nov 2026 12:40:49 +0100 Subject: [PATCH 0832/2102] drm/amdgpu: Fix UserQ slot availability checks The compute and DMA queries check each other's disable_uq flags. When the flags differ, this can hide available slots or report slots for disabled UserQs. Check gfx.disable_uq for compute and sdma.disable_uq for DMA. Fixes: 78d0a27ae0e2 ("drm/amdgpu: Add user queue instance count in HW IP info") Reviewed-by: Alex Deucher Signed-off-by: Erhan Bilgili Signed-off-by: Alex Deucher (cherry picked from commit ed4f6b1f8848ad8890fd188da6b2ddfdd538a036) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c index 335c523592bfa3..6e710e4e24b8fd 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c @@ -474,7 +474,7 @@ static int amdgpu_hw_ip_info(struct amdgpu_device *adev, !adev->gfx.compute_ring[i].no_user_submission) ++num_rings; - if (!adev->sdma.disable_uq) { + if (!adev->gfx.disable_uq) { for (i = 0; i < AMDGPU_MES_MAX_COMPUTE_PIPES; i++) num_slots += hweight32(adev->mes.compute_hqd_mask[i]); } @@ -489,7 +489,7 @@ static int amdgpu_hw_ip_info(struct amdgpu_device *adev, !adev->sdma.instance[i].ring.no_user_submission) ++num_rings; - if (!adev->gfx.disable_uq) { + if (!adev->sdma.disable_uq) { for (i = 0; i < AMDGPU_MES_MAX_SDMA_PIPES; i++) num_slots += hweight32(adev->mes.sdma_hqd_mask[i]); } From 406a850b0dd28d969bdbff726d7841d25d770cb3 Mon Sep 17 00:00:00 2001 From: Fangzhi Zuo Date: Sat, 24 Oct 2026 15:26:56 -0400 Subject: [PATCH 0833/2102] drm/amd/display: Move HDMI FRL Polling Outside dc_lock [Why] amdgpu_dm_commit_streams() started or cancelled the self-rearming HDMI FRL poll under dm->dc_lock. cancel_delayed_work_sync() can wait for a worker that needs the same lock, creating a lock dependency that could deadlock. [How] Release dm->dc_lock after dc_commit_streams() and the idle-optimization update, then scan the committed streams and start or stop FRL polling outside the lock. Cc: Harry Wentland Reviewed-by: ChiaHsuan Chung Signed-off-by: Fangzhi Zuo Signed-off-by: Wayne Lin Tested-by: Dan Wheeler Signed-off-by: Alex Deucher (cherry picked from commit 7a1807cd11a8c2bd26d48de6829d82ae62ad622d) --- drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c index 0ea45ab12119c5..2c5831dde8f699 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c @@ -4733,6 +4733,11 @@ static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state, dc_exit_ips_for_hw_access(dm->dc); WARN_ON(!dc_commit_streams(dm->dc, ¶ms)); + /* Allow idle optimization when vblank count is 0 for display off */ + if (dm->active_vblank_irq_count == 0 && amdgpu_dm_is_headless(dm->adev)) + dc_allow_idle_optimizations(dm->dc, true); + mutex_unlock(&dm->dc_lock); + bool frl_stream_found = false; for (i = 0; i < params.stream_count; i++) { @@ -4743,6 +4748,7 @@ static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state, break; } } + if (frl_stream_found) { if (queue_delayed_work(dm->hdmi_frl_status_polling_wq, &dm->hdmi_frl_status_polling_work, @@ -4752,10 +4758,6 @@ static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state, if (cancel_delayed_work_sync(&dm->hdmi_frl_status_polling_work)) drm_dbg_kms(dev, "200ms frl status polling stops ...\n"); } - /* Allow idle optimization when vblank count is 0 for display off */ - if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev)) - dc_allow_idle_optimizations(dm->dc, true); - mutex_unlock(&dm->dc_lock); for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) { struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc); From 449141afc84a4434db864abf9051dc8beb3b7c81 Mon Sep 17 00:00:00 2001 From: Fangzhi Zuo Date: Sat, 24 Oct 2026 00:51:40 -0400 Subject: [PATCH 0834/2102] drm/amd/display: Stop HDMI FRL status polling on fini MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [Why] The HDMI FRL status polling work re-queues itself and its workqueue was not stopped during amdgpu_dm_fini(). During unbind or unload, the worker could access freed DC state, and the workqueue was leaked. This fixes the FRL polling teardown introduced by the HDMI FRL support change. [How] Cancel the delayed polling work synchronously and destroy the workqueue in amdgpu_dm_fini() before the remaining display state is torn down. Cc: Harry Wentland Reported-by: Eren Özen Link: https://lore.kernel.org/all/20261110-frl-polling-wq-teardown-v1-0-0ff028d5c35b@protonmail.com/ Reviewed-by: ChiaHsuan Chung Signed-off-by: Fangzhi Zuo Signed-off-by: Wayne Lin Tested-by: Dan Wheeler Signed-off-by: Alex Deucher (cherry picked from commit 709b7a5aff3addf2288dedf42bc62c45ae1ab163) --- drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c index 2c5831dde8f699..6584a5f9e34a56 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c @@ -886,6 +886,13 @@ static void amdgpu_dm_fini(struct amdgpu_device *adev) adev->dm.vblank_control_workqueue = NULL; } + /* The poll re-queues itself, so stop it before the wq and dc go away. */ + if (adev->dm.hdmi_frl_status_polling_wq) { + cancel_delayed_work_sync(&adev->dm.hdmi_frl_status_polling_work); + destroy_workqueue(adev->dm.hdmi_frl_status_polling_wq); + adev->dm.hdmi_frl_status_polling_wq = NULL; + } + if (adev->dm.idle_workqueue) { if (adev->dm.idle_workqueue->running) { adev->dm.idle_workqueue->enable = false; From 8bcb6863ac318dfadf622598171c79a020fdd7ff Mon Sep 17 00:00:00 2001 From: Austin Zheng Date: Wed, 23 Sep 2026 14:58:32 -0400 Subject: [PATCH 0835/2102] drm/amd/display: Flip dml2_core_utils_get_segment_horizontal_contiguous() Inputs [Why/How] Parameters for dml2_core_utils_get_segment_horizontal_contiguous() should be flipped. Should be swizzle mode then bytes per pixel. Cc: Dillon Varone Cc: Mario Limonciello Cc: Alex Deucher Reviewed-by: ChiaHsuan Chung Signed-off-by: Austin Zheng Signed-off-by: Wayne Lin Tested-by: Dan Wheeler Signed-off-by: Alex Deucher (cherry picked from commit 8e985b38672c3de9355dd8f166527f96e472706c) Cc: stable@vger.kernel.org --- .../dml21/src/dml2_core/dml2_core_dcn5_calcs_dchub.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn5_calcs_dchub.c b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn5_calcs_dchub.c index f407afefb37fe0..82dbf81defbbcb 100644 --- a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn5_calcs_dchub.c +++ b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn5_calcs_dchub.c @@ -836,7 +836,7 @@ void dcn5_calculate_swath_and_det_configuration(struct dml2_core_internal_scratc p->SwathHeightC[k] = MaximumSwathHeightC[k]; RoundedUpSwathSizeBytesY[k] = p->full_swath_bytes_l[k] / 2; RoundedUpSwathSizeBytesC[k] = p->full_swath_bytes_c[k]; - p->request_size_bytes_luma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->BytePerPixY[k], p->display_cfg->plane_descriptors[k].surface.tiling) + p->request_size_bytes_luma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->display_cfg->plane_descriptors[k].surface.tiling, p->BytePerPixY[k]) == dml2_core_utils_is_vertical_rotation(p->display_cfg->plane_descriptors[k].composition.rotation_angle) ? 64 : 128; p->request_size_bytes_chroma[k] = 256; @@ -846,7 +846,7 @@ void dcn5_calculate_swath_and_det_configuration(struct dml2_core_internal_scratc RoundedUpSwathSizeBytesY[k] = p->full_swath_bytes_l[k]; RoundedUpSwathSizeBytesC[k] = p->full_swath_bytes_c[k] / 2; p->request_size_bytes_luma[k] = 256; - p->request_size_bytes_chroma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->BytePerPixC[k], p->display_cfg->plane_descriptors[k].surface.tiling) + p->request_size_bytes_chroma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->display_cfg->plane_descriptors[k].surface.tiling, p->BytePerPixC[k]) == dml2_core_utils_is_vertical_rotation(p->display_cfg->plane_descriptors[k].composition.rotation_angle) ? 64 : 128; } else { @@ -854,9 +854,9 @@ void dcn5_calculate_swath_and_det_configuration(struct dml2_core_internal_scratc p->SwathHeightC[k] = MaximumSwathHeightC[k] / 2; RoundedUpSwathSizeBytesY[k] = p->full_swath_bytes_l[k] / 2; RoundedUpSwathSizeBytesC[k] = p->full_swath_bytes_c[k] / 2; - p->request_size_bytes_luma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->BytePerPixY[k], p->display_cfg->plane_descriptors[k].surface.tiling) + p->request_size_bytes_luma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->display_cfg->plane_descriptors[k].surface.tiling, p->BytePerPixY[k]) == dml2_core_utils_is_vertical_rotation(p->display_cfg->plane_descriptors[k].composition.rotation_angle) ? 64 : 128; - p->request_size_bytes_chroma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->BytePerPixC[k], p->display_cfg->plane_descriptors[k].surface.tiling) + p->request_size_bytes_chroma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->display_cfg->plane_descriptors[k].surface.tiling, p->BytePerPixC[k]) == dml2_core_utils_is_vertical_rotation(p->display_cfg->plane_descriptors[k].composition.rotation_angle) ? 64 : 128; } From 3846f4542b4ba5a95405527d1e68864a9e9f3fcf Mon Sep 17 00:00:00 2001 From: Wenjing Liu Date: Wed, 4 Nov 2026 14:39:45 -0500 Subject: [PATCH 0836/2102] drm/amd/display: Read DRAM channel width from SMU init table [Why] The channel count came from the SMU init table but the channel width came from VBIOS vram info. Both values need to describe the same memory type. [How] Add DramChannelWidthBytes to MemoryConfig_t, using a reserved slot so the layout is unchanged. Populate the channel width in bw_params from the init table instead of VBIOS vram info. Cc: Dillon Varone Cc: Mario Limonciello Cc: Alex Deucher Reviewed-by: ChiaHsuan Chung Signed-off-by: Wenjing Liu Signed-off-by: Wayne Lin Tested-by: Dan Wheeler Signed-off-by: Alex Deucher (cherry picked from commit 37d64c58f610d771b7ab8cfbf7d9f5606939947b) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dalsmc.h | 3 ++- drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dcn60_clk_mgr.c | 3 +-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dalsmc.h b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dalsmc.h index 234777bdd1831a..ea3927223117e3 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dalsmc.h +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dalsmc.h @@ -77,7 +77,8 @@ typedef struct { typedef struct { uint32_t NumUmcChannels; - uint32_t Reserved[3]; + uint32_t DramChannelWidthBytes; + uint32_t Reserved[2]; } MemoryConfig_t; /** diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dcn60_clk_mgr.c b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dcn60_clk_mgr.c index d8a0a482d98429..e33140d45867f3 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dcn60_clk_mgr.c +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dcn60_clk_mgr.c @@ -815,8 +815,7 @@ static bool dcn60_fetch_dal_init_table(struct clk_mgr_internal *clk_mgr) //dcn60_populate_dc_mode_limit(&bw_params->dc_mode_limit, init_table); bw_params->num_channels = init_table->MemoryConfig.NumUmcChannels; - bw_params->dram_channel_width_bytes = - clk_mgr->base.ctx->dc_bios->vram_info.dram_channel_width_bytes; + bw_params->dram_channel_width_bytes = init_table->MemoryConfig.DramChannelWidthBytes; dcn60_populate_utm_qos_model(clk_mgr, &bw_params->utm_qos_model, init_table); From 007e7bf5692d93535adf943cd93c0e49b4e20e9d Mon Sep 17 00:00:00 2001 From: Allen Pan Date: Mon, 2 Nov 2026 15:52:40 -0500 Subject: [PATCH 0837/2102] drm/amd/display: Update DCN42B stutter latency to match DCN42 [Why] The DCN42B stutter latencies do not match DCN42, which can lead to underflow and stutter issues. [How] Update the DCN42B LPDDR5/LPCAMM2 stutter latencies to the same values DCN42 already uses. Cc: Dillon Varone Cc: Charlene Liu Cc: Mario Limonciello Cc: Alex Deucher Reviewed-by: ChiaHsuan Chung Signed-off-by: Allen Pan Signed-off-by: Wayne Lin Tested-by: Dan Wheeler Signed-off-by: Alex Deucher (cherry picked from commit c6b576ac64cedc990f3885efa85603fe5998da3f) Cc: stable@vger.kernel.org --- .../dc/dml2_0/dml21/inc/bounding_boxes/dcn42b_soc_bb.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/dcn42b_soc_bb.h b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/dcn42b_soc_bb.h index e83a9ac018db2c..07f1bffc75ca85 100644 --- a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/dcn42b_soc_bb.h +++ b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/dcn42b_soc_bb.h @@ -188,8 +188,8 @@ static const struct dml2_soc_bb dml2_socbb_dcn42b = { .dram_clk_change_blackout_us = 36, .fclk_change_blackout_us = 0, .g7_ppt_blackout_us = 0, - .stutter_enter_plus_exit_latency_us = 14, - .stutter_exit_latency_us = 12, + .stutter_enter_plus_exit_latency_us = 15.5, + .stutter_exit_latency_us = 13.5, .z8_stutter_enter_plus_exit_latency_us = 300, .z8_stutter_exit_latency_us = 200, }, From eaf4ff850d97eb608482fa3497f1b89b2e628781 Mon Sep 17 00:00:00 2001 From: Jing Zhou Date: Thu, 5 Nov 2026 23:20:58 +0800 Subject: [PATCH 0838/2102] drm/amd/display: Seed boot clocks to avoid lowering pre-OS display clocks [WHY] USB4 DPIA HPD can arrive early in boot, before the first stream commit. Its link detection runs prepare_phy_clocks(), which goes through clk_mgr_exit_optimized_pwr_state() and clk_mgr_optimize_pwr_state() and calls update_clocks(dc->current_state). At that point both dc->current_state->bw_ctx.bw.dcn.clk and clk_mgr->clks are still zero, because init_clocks() memsets them. On the safe_to_lower path, dcn42_update_clocks() clamps the requested DPPCLK to the 100MHz floor and programs it. This drops DPPCLK below what the GOP-lit eDP pipe needs, and the panel flashes white. [HOW] 1. In dcn42_init_clocks() and dcn42b_init_clocks(), seed clk_mgr->clks dispclk/dppclk from the boot snapshot(10kHz units, x10). 2. Add a DC core helper, sync_current_state_clocks_from_clk_mgr(). After every hwss.init_hw() call (legacy_hardware_init, D0 entry in dc_set_power_state, and dc_reinitialize_hardware), it copies clk_mgr->clks into dc->current_state->bw_ctx.bw.dcn.clk for DCN. A later update_clocks() before the first commit then sees the real pre-OS clocks and does not lower them. Raising clocks is still allowed and does not cause a flash. Cc: Nicholas Kazlauskas Cc: Charlene Liu Cc: Mario Limonciello Cc: Alex Deucher Reviewed-by: ChiaHsuan Chung Signed-off-by: Jing Zhou Signed-off-by: Wayne Lin Tested-by: Dan Wheeler Signed-off-by: Alex Deucher (cherry picked from commit 2f289740a04f08a5ce4b5e3c69af6e32ab4a540e) Cc: stable@vger.kernel.org --- .../amd/display/dc/clk_mgr/dcn42/dcn42_clk_mgr.c | 3 +++ .../display/dc/clk_mgr/dcn42b/dcn42b_clk_mgr.c | 4 ++++ drivers/gpu/drm/amd/display/dc/core/dc.c | 16 +++++++++++++++- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42/dcn42_clk_mgr.c b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42/dcn42_clk_mgr.c index 405145889ba27b..ae3d762955a9b8 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42/dcn42_clk_mgr.c +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42/dcn42_clk_mgr.c @@ -643,6 +643,9 @@ DC_LOGGER_INIT(clk_mgr_base->ctx->logger); DC_LOG_SMU("dp_dto_source_clock %d, dprefclk %d\n", clk_mgr_base->dp_dto_source_clock_in_khz, clk_mgr_base->dprefclk_khz); dcn42_dump_clk_registers(&clk_mgr_base->boot_snapshot, clk_mgr); + /* Snapshot is in 10kHz units; seed clks so update_clocks() does not lower the pre-OS clocks */ + clk_mgr_base->clks.dispclk_khz = clk_mgr_base->boot_snapshot.dispclk * 10; + clk_mgr_base->clks.dppclk_khz = clk_mgr_base->boot_snapshot.dppclk * 10; clk_mgr_base->clks.ref_dtbclk_khz = clk_mgr_base->boot_snapshot.dtbclk * 10; clk_mgr_base->clks.dtbclk_en = clk_mgr_base->boot_snapshot.dtbclk > 59000; } diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42b/dcn42b_clk_mgr.c b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42b/dcn42b_clk_mgr.c index d500a3210eed78..6aacc4f77ae789 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42b/dcn42b_clk_mgr.c +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42b/dcn42b_clk_mgr.c @@ -242,6 +242,10 @@ DC_LOGGER_INIT(clk_mgr_base->ctx->logger); DC_LOG_SMU("dp_dto_source_clock %d, dprefclk %d\n", clk_mgr_base->dp_dto_source_clock_in_khz, clk_mgr_base->dprefclk_khz); dcn42b_dump_clk_registers(&clk_mgr_base->boot_snapshot, clk_mgr); + + /* Snapshot is in 10kHz units; seed clks so update_clocks() does not lower the pre-OS clocks */ + clk_mgr_base->clks.dispclk_khz = clk_mgr_base->boot_snapshot.dispclk * 10; + clk_mgr_base->clks.dppclk_khz = clk_mgr_base->boot_snapshot.dppclk * 10; } static struct clk_bw_params dcn42b_bw_params = { diff --git a/drivers/gpu/drm/amd/display/dc/core/dc.c b/drivers/gpu/drm/amd/display/dc/core/dc.c index 348e8991f8701a..422612da44d38a 100644 --- a/drivers/gpu/drm/amd/display/dc/core/dc.c +++ b/drivers/gpu/drm/amd/display/dc/core/dc.c @@ -1663,12 +1663,25 @@ static void detect_edp_presence(struct dc *dc) } } +static void sync_current_state_clocks_from_clk_mgr(struct dc *dc) +{ + if (!dc->current_state || !dc->clk_mgr) + return; + + if (!(dc->ctx->dce_version == DCN_VERSION_4_2 || dc->ctx->dce_version == DCN_VERSION_4_2B)) + return; + + dc->current_state->bw_ctx.bw.dcn.clk = dc->clk_mgr->clks; +} + void legacy_hardware_init(struct dc *dc) { detect_edp_presence(dc); - if (dc->ctx->dce_environment != DCE_ENV_VIRTUAL_HW) + if (dc->ctx->dce_environment != DCE_ENV_VIRTUAL_HW) { dc->hwss.init_hw(dc); + sync_current_state_clocks_from_clk_mgr(dc); + } dc_dmub_srv_notify_fw_dc_power_state(dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0); } @@ -6312,6 +6325,7 @@ void dc_set_power_state(struct dc *dc, enum dc_acpi_cm_power_state power_state) dc_dmub_srv_notify_fw_dc_power_state(dc->ctx->dmub_srv, power_state); dc->hwss.init_hw(dc); + sync_current_state_clocks_from_clk_mgr(dc); if (dc->hwss.init_sys_ctx != NULL && dc->vm_pa_config.valid) { From 264b67a79010cd3ffa85603d85e594867a45a01d Mon Sep 17 00:00:00 2001 From: Jesse Zhang Date: Tue, 3 Nov 2026 20:12:40 +0800 Subject: [PATCH 0839/2102] drm/amdkfd: don't check the HMM range when getting its pages failed When allocating the PFN array fails, amdgpu_hmm_range_get_pages() returns -ENOMEM before setting the notifier of the range, but svm_range_validate_and_map() still checks the range, as it is not NULL, before looking at the error. On navi48, setting SVM attributes with failslab: KASAN: null-ptr-deref in range [0x0000000000000050-0x0000000000000057] RIP: 0010:amdgpu_hmm_range_valid+0x66/0xa0 [amdgpu] svm_range_validate_and_map+0xaef/0x4e40 [amdgpu] svm_range_set_attr+0x193e/0x4610 [amdgpu] kfd_ioctl_svm+0x137/0x320 [amdgpu] Check the error first; it is only 0 when the pages were taken. Fixes: c0de552910bb ("drm/amdkfd: clean up the code to free hmm_range") Reviewed-by: Felix Kuehling Signed-off-by: Jesse Zhang Signed-off-by: Alex Deucher (cherry picked from commit c7036242655cb2c6d14a0d04138536e1ddb5e42c) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_svm.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c index e132a0079ea7ef..ac40f9a35e8a82 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c @@ -1892,11 +1892,12 @@ static int svm_range_validate_and_map(struct mm_struct *mm, svm_range_lock(prange); - /* Free backing memory of hmm_range if it was initialized - * Override return value to TRY AGAIN only if prior returns - * were successful + /* + * Retry if the pages were invalidated after they were taken. + * Only check that when taking them succeeded: a range can exist + * without a notifier, e.g. when allocating its PFN array failed. */ - if (range && !amdgpu_hmm_range_valid(range) && !r) { + if (!r && !amdgpu_hmm_range_valid(range)) { pr_debug("hmm update the range, need validate again\n"); r = -EAGAIN; } From 09b6bf1a04cc6bbcbb8bb29fa1e38fa8a9f8d1dc Mon Sep 17 00:00:00 2001 From: Hugo Sales Date: Thu, 29 Oct 2026 16:54:20 +0000 Subject: [PATCH 0840/2102] drm/amd/display: Take every stream out of self-refresh before a modeset Commit 3c108046e1d6 ("drm/amd/display: Add power module on Linux") dropped amdgpu_dm_psr_disable_all() and amdgpu_dm_replay_disable_all() from amdgpu_dm_commit_streams(). Since then, a modeset only disables self-refresh on the CRTCs in the commit, so an eDP on another CRTC stays in PSR through dc_commit_streams() Commit 6ee90e88b976 ("drm/amd/display: PSR eDP p-state warning occurs intermittently after unplug DP") added that disable-all for this very case. With it gone, turning off or unplugging an HDMI monitor while the eDP is in PSR hangs DMUB on a Cezanne laptop (DCN 2.1), on the first try: dc_dmub_srv_log_diagnostic_data: DMCUB error Error queueing DMUB command: status=2 The eDP then stays frozen until a GPU reset Do the same through the power module's events. When a CRTC that is or was active needs a modeset, raise the PSR and Replay pause events on every stream mod_power tracks and wait for self-refresh to exit, before amdgpu_dm_mod_power_update_streams() changes the stream set. Clear them on the commit's streams after amdgpu_dm_mod_power_setup_streams(), since enabling a stream clears psr_feature_enabled until then. Use psr_event_pause and replay_event_pause rather than the hw_programming events, which a fast update on the eDP can clear in amdgpu_dm_enable_self_refresh() while the modeset is still running Fixes: 3c108046e1d6 ("drm/amd/display: Add power module on Linux") Reviewed-by: Ray Wu Signed-off-by: Hugo Sales Signed-off-by: Wayne Lin Signed-off-by: Alex Deucher (cherry picked from commit 5d90fdb959505b5f42f2dec699521ac56b4174be) Cc: stable@vger.kernel.org --- .../gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c index 6584a5f9e34a56..807cb4d6150b02 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c @@ -4462,6 +4462,105 @@ STATIC_IFN_KUNIT void dm_clear_writeback(struct amdgpu_display_manager *dm, } EXPORT_IF_KUNIT(dm_clear_writeback); +static bool amdgpu_dm_self_refresh_pause_needed(struct drm_atomic_commit *state) +{ + struct drm_crtc_state *old_crtc_state, *new_crtc_state; + struct drm_crtc *crtc; + int i; + + for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) + if (drm_atomic_crtc_needs_modeset(new_crtc_state) && + (old_crtc_state->active || new_crtc_state->active)) + return true; + + return false; +} + +static bool amdgpu_dm_is_new_modeset_stream(struct drm_atomic_commit *state, + const struct dc_stream_state *stream) +{ + struct drm_crtc_state *new_crtc_state; + struct drm_crtc *crtc; + int i; + + for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) + if (drm_atomic_crtc_needs_modeset(new_crtc_state) && + to_dm_crtc_state(new_crtc_state)->stream == stream) + return true; + + return false; +} + +/* + * A modeset CRTC may have no PSR or Replay, such as an HDMI output being + * turned off, while an eDP on another CRTC is still in self-refresh. Pause + * self-refresh on every stream mod_power tracks before + * amdgpu_dm_mod_power_update_streams() changes the set: the old streams of + * the CRTCs in the commit and the unchanged streams of the new state. + * Unlike hw_programming, which a fast update on another CRTC clears, the + * pause holds until amdgpu_dm_resume_self_refresh() + */ +static void amdgpu_dm_pause_self_refresh(struct drm_atomic_commit *state, + struct amdgpu_display_manager *dm, + struct dc_state *dc_state) +{ + struct drm_crtc_state *old_crtc_state; + struct dc_stream_state *stream; + struct drm_crtc *crtc; + int i; + + if (!amdgpu_dm_self_refresh_pause_needed(state)) + return; + + guard(mutex)(&dm->dc_lock); + dc_exit_ips_for_hw_access(dm->dc); + + for_each_old_crtc_in_state(state, crtc, old_crtc_state, i) { + stream = to_dm_crtc_state(old_crtc_state)->stream; + if (!old_crtc_state->active || !stream) + continue; + + amdgpu_dm_psr_set_event(dm, stream, true, psr_event_pause, true); + amdgpu_dm_replay_set_event(dm, stream, true, replay_event_pause, true); + } + + for (i = 0; i < dc_state->stream_count; i++) { + stream = dc_state->streams[i]; + if (amdgpu_dm_is_new_modeset_stream(state, stream)) + continue; + + amdgpu_dm_psr_set_event(dm, stream, true, psr_event_pause, true); + amdgpu_dm_replay_set_event(dm, stream, true, replay_event_pause, true); + } +} + +/* + * Ends amdgpu_dm_pause_self_refresh() on the streams of the commit, which + * mod_power tracks from amdgpu_dm_mod_power_update_streams() on, even if + * dc_commit_streams() failed. mod_power keeps events across + * mod_power_replace_stream(), so the replaced streams carry the pause too. + * Runs after amdgpu_dm_mod_power_setup_streams(), since enabling a stream + * clears psr_feature_enabled and replay_feature_enabled on its link until + * then, and the set_event helpers skip a link without them + */ +static void amdgpu_dm_resume_self_refresh(struct drm_atomic_commit *state, + struct amdgpu_display_manager *dm, + struct dc_state *dc_state) +{ + int i; + + if (!dc_state || !amdgpu_dm_self_refresh_pause_needed(state)) + return; + + guard(mutex)(&dm->dc_lock); + for (i = 0; i < dc_state->stream_count; i++) { + amdgpu_dm_psr_set_event(dm, dc_state->streams[i], false, + psr_event_pause, false); + amdgpu_dm_replay_set_event(dm, dc_state->streams[i], false, + replay_event_pause, false); + } +} + /** * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset * @state: the drm atomic state @@ -4618,6 +4717,7 @@ static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state, acrtc->wb_enabled = false; } + amdgpu_dm_pause_self_refresh(state, dm, dc_state); amdgpu_dm_mod_power_update_streams(state, dm); for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, @@ -5365,6 +5465,7 @@ static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state) } amdgpu_dm_mod_power_setup_streams(state, dm); + amdgpu_dm_resume_self_refresh(state, dm, dc_state); for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) if (new_crtc_state->async_flip) From 63b42ad2fdd371ae4a86658295943d60a86a519b Mon Sep 17 00:00:00 2001 From: Jesse Zhang Date: Tue, 3 Nov 2026 23:54:21 +0800 Subject: [PATCH 0841/2102] drm/amdkfd: keep the DMA addresses of a range intact if splitting fails svm_range_split_pages() splits the DMA address array of one GPU after the other, and each split replaces the old range's array by a shorter one. If a later GPU's array can't be allocated, the old range is left with the arrays of the earlier GPUs already shortened, but with its old size. Unmapping it then walks past their end. On navi31 with its iGPU, an SVM range accessible by both GPUs, and unmapping a page in its middle with allocations failing in turn through failslab: BUG: KASAN: slab-out-of-bounds in svm_range_dma_unmap_dev+0x13f/0x170 [amdgpu] Read of size 8 at addr ffff88819ac32800 by task kworker/8:1/171 svm_range_dma_unmap_dev+0x13f/0x170 [amdgpu] svm_range_dma_unmap+0x119/0x2c0 [amdgpu] svm_range_free+0x312/0x520 [amdgpu] svm_range_handle_list_op+0x326/0x500 [amdgpu] svm_range_deferred_list_work+0x338/0x790 [amdgpu] Allocated by task 2749: svm_range_copy_array.constprop.0+0x55/0x190 [amdgpu] svm_range_split+0x388/0x17b0 [amdgpu] svm_range_unmap_split+0x254/0x370 [amdgpu] svm_range_cpu_invalidate_pagetables+0xb29/0x11d0 [amdgpu] The buggy address is located 0 bytes to the right of allocated 2048-byte region [ffff88819ac32000, ffff88819ac32800) Split the arrays of all GPUs first and only replace the old ones once all succeeded. With that the 2759 unmaps of the same sweep give no report. Fixes: f80fe9d3c114 ("drm/amdkfd: map svm range to GPUs") Reviewed-by: Felix Kuehling Signed-off-by: Jesse Zhang Signed-off-by: Alex Deucher (cherry picked from commit 3cbd0b498ac18821ec01c08e39050a4d22ea9eeb) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_svm.c | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c index ac40f9a35e8a82..2835c1d73d63f6 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c @@ -1008,7 +1008,7 @@ svm_range_split_array(void *ppnew, void *ppold, size_t size, kvfree(new); return -ENOMEM; } - kvfree(pold); + /* The caller frees pold once all arrays of the range are split */ *(void **)ppold = old; *(void **)ppnew = new; @@ -1019,19 +1019,36 @@ static int svm_range_split_pages(struct svm_range *new, struct svm_range *old, uint64_t start, uint64_t last) { + dma_addr_t *old_dma[MAX_GPU_INSTANCE]; uint64_t npages = last - start + 1; bool has_dma_addr = false; int i, r; + /* + * Split the arrays of all GPUs before replacing any of them, the old + * range must stay intact if one fails. + */ for (i = 0; i < MAX_GPU_INSTANCE; i++) { + old_dma[i] = old->dma_addr[i]; if (old->dma_addr[i]) has_dma_addr = true; - r = svm_range_split_array(&new->dma_addr[i], &old->dma_addr[i], + r = svm_range_split_array(&new->dma_addr[i], &old_dma[i], sizeof(*old->dma_addr[i]), old->start, npages, new->start, new->npages, old->actual_loc ? &new->vram_pages : NULL); - if (r) + if (r) { + /* new->dma_addr[] goes with the new range */ + while (i--) + if (old_dma[i] != old->dma_addr[i]) + kvfree(old_dma[i]); return r; + } + } + for (i = 0; i < MAX_GPU_INSTANCE; i++) { + if (old_dma[i] == old->dma_addr[i]) + continue; + kvfree(old->dma_addr[i]); + old->dma_addr[i] = old_dma[i]; } if (old->actual_loc) { /* From 4aa51b904cac06fe2c82623ce24d80853af730f6 Mon Sep 17 00:00:00 2001 From: Abdulla Bubshait Date: Wed, 28 Oct 2026 16:26:41 -0400 Subject: [PATCH 0842/2102] drm/amd/display: Abort DPMS ON when enabling the link fails Since commit 843049bac7c0 ("drm/amd/display: Split DPMS ON into parts"), link_set_dpms_on_enable_link() returns DC_DPMS_FAILED_HANDSHAKE when enable_link() fails and the stream enable has to be aborted: any failure other than link training, or a link training failure on DP MST. The link has already been disabled at that point. The step loop in link_set_dpms_on() treats DC_DPMS_FAILED_HANDSHAKE like DC_DPMS_SUCCESS and goes on to link_set_dpms_on_post_enable_link(). Before the split, this path returned right after disable_link(), because MST displays can't proceed without link training. Now, for failed MST handshakes MST slots are still allocated. When the link trains again later, the new payload starts after the leaked slots so ACT never completes, and the display stays black until reboot. Replugging or power-cycling the monitor does not recover it. Seen on Navi 33 (DCN 3.2.1) with a DP 2.1 MST monitor (Odyssey Neo G9) at UHBR10 x4 with DSC. Link training sometimes fails on DPMS wake. With this change, the failed attempt leaves no payload behind, and the next modeset after the sink reconnects bring the monitor back up. Return early on DC_DPMS_FAILED_HANDSHAKE, as for DC_DPMS_SKIPPED_HANDSHAKE. This restores the pre-split behaviour. Link training failures on non-MST signals still return DC_DPMS_SUCCESS and continue as before. Closes: https://gitlab.freedesktop.org/drm/amd/-/work_items/6047 Fixes: 843049bac7c0 ("drm/amd/display: Split DPMS ON into parts") Reviewed-by: Wayne Lin Signed-off-by: Abdulla Bubshait Signed-off-by: Wayne Lin Signed-off-by: Alex Deucher (cherry picked from commit ece3dae13fb106684f8248f88387b1fbcfef8206) Cc: stable@vger.kernel.org # 7.3 --- drivers/gpu/drm/amd/display/dc/link/link_dpms.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/amd/display/dc/link/link_dpms.c b/drivers/gpu/drm/amd/display/dc/link/link_dpms.c index 382ad9bd4e57c1..1a5dca9d03ce03 100644 --- a/drivers/gpu/drm/amd/display/dc/link/link_dpms.c +++ b/drivers/gpu/drm/amd/display/dc/link/link_dpms.c @@ -2815,11 +2815,11 @@ enum dc_status link_set_dpms_on( switch (step_result) { case DC_DPMS_SUCCESS: - case DC_DPMS_FAILED_HANDSHAKE: // Enum is ordered from "best" to "worst" results result = max(result, step_result); break; + case DC_DPMS_FAILED_HANDSHAKE: case DC_DPMS_SKIPPED_HANDSHAKE: return step_result; From b265a92b42169a7d22592f61e6fdbcc5efd57d6a Mon Sep 17 00:00:00 2001 From: Kent Russell Date: Wed, 7 Oct 2026 16:46:45 -0400 Subject: [PATCH 0843/2102] drm/amdgpu: Run shader cleaner on all XCCs on faults The previous patch only ran on XCC0, giving us a good chance that we don't clear the right registers on fault handling in MI3. Loop through them all to make sure we clear them all. Also clarify the fail/succeed message to accurately reflect what was done Fixes: 923d09ab1f9a ("drm/amdkfd: Fix TCP XNACK scoreboard reset race on MI300") Signed-off-by: Kent Russell Reviewed-by: Jay Cornwall Signed-off-by: Alex Deucher (cherry picked from commit eb5fa6f22cdb7c7dbdaf792f1206e808739d5887) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c | 82 +++++++++++++++---------- 1 file changed, 49 insertions(+), 33 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c index 54bcb5fdca2421..9ba517311bb392 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c @@ -716,56 +716,72 @@ static int gfx_v9_4_2_do_vgprs_init(struct amdgpu_device *adev) static int gfx_v9_clean_shaders(struct amdgpu_device *adev) { - int r; + int r = 0; /* CU_ID: 0~15, SIMD_ID: 0~3, WAVE_ID: 0 ~ 9 */ int wb_size = adev->gfx.config.max_shader_engines * CU_ID_MAX * SIMD_ID_MAX * WAVE_ID_MAX; struct amdgpu_ib wb_ib; + struct amdgpu_ring *ring; struct dma_fence *fence = NULL; u32 pattern = 0xa; + int xcc_id; - /* bail if the compute ring is not ready */ - if (!adev->gfx.compute_ring[0].sched.ready) + if (adev->gfx.disable_kq) { + dev_warn(adev->dev, "Cannot run shader cleaner with kernel queues disabled"); return 0; - - /* allocate the write-back buffer from IB */ - memset(&wb_ib, 0, sizeof(wb_ib)); - r = amdgpu_ib_get(adev, NULL, (1 + wb_size) * sizeof(uint32_t), - AMDGPU_IB_POOL_DIRECT, &wb_ib); - if (r) { - dev_err(adev->dev, "failed to get ib (%d) for wb.\n", r); - return r; } - memset(wb_ib.ptr, 0, (1 + wb_size) * sizeof(uint32_t)); - r = gfx_v9_4_2_run_shader(adev, - &adev->gfx.compute_ring[0], - fault_cleaner_compute_shader_aldebaran, - sizeof(fault_cleaner_compute_shader_aldebaran), - fault_cleaner_init_regs_aldebaran, - ARRAY_SIZE(fault_cleaner_init_regs_aldebaran), - adev->gfx.cu_info.number * 32, - wb_ib.gpu_addr, pattern, &fence); + for_each_inst(xcc_id, adev->gfx.xcc_mask) { + ring = &adev->gfx.compute_ring[xcc_id * adev->gfx.num_compute_rings]; - if (r) { - dev_err(adev->dev, "failed to clear MI200\n"); - goto pro_end; - } + /* bail if the compute ring is not ready */ + if (!ring->sched.ready) + continue; - /* wait for the GPU to finish processing the IB */ - r = dma_fence_wait(fence, false); - if (r) - dev_err(adev->dev, "timeout to clear MI200\n"); + /* allocate the write-back buffer from IB */ + memset(&wb_ib, 0, sizeof(wb_ib)); + r = amdgpu_ib_get(adev, NULL, (1 + wb_size) * sizeof(uint32_t), + AMDGPU_IB_POOL_DIRECT, &wb_ib); + if (r) { + dev_err(adev->dev, "failed to get ib (%d) for wb.\n", r); + return r; + } + memset(wb_ib.ptr, 0, (1 + wb_size) * sizeof(uint32_t)); + + r = gfx_v9_4_2_run_shader(adev, + ring, + fault_cleaner_compute_shader_aldebaran, + sizeof(fault_cleaner_compute_shader_aldebaran), + fault_cleaner_init_regs_aldebaran, + ARRAY_SIZE(fault_cleaner_init_regs_aldebaran), + adev->gfx.cu_info.number * 32, + wb_ib.gpu_addr, pattern, &fence); + + if (r) { + dev_err(adev->dev, "failed to clear GPR on xcc %d\n", xcc_id); + goto pro_end; + } + + /* wait for the GPU to finish processing the IB */ + r = dma_fence_wait(fence, false); + if (r) + dev_err(adev->dev, "timeout to clear GPR on xcc %d\n", xcc_id); pro_end: - if (fence) - dma_fence_put(fence); - amdgpu_ib_free(&wb_ib, NULL); + if (fence) { + dma_fence_put(fence); + fence = NULL; + } + amdgpu_ib_free(&wb_ib, NULL); + + if (r) + break; + } if (r) - dev_dbg(adev->dev, "Clean GPR Failed\n"); + dev_dbg(adev->dev, "Clearing fault state failed\n"); else - dev_dbg(adev->dev, "Clean GPR Successfully\n"); + dev_dbg(adev->dev, "Fault state cleared Successfully\n"); return r; } From a71cd76b6f1f9bde67dbba948ab9683e7ded2175 Mon Sep 17 00:00:00 2001 From: Kent Russell Date: Mon, 26 Oct 2026 10:42:03 -0400 Subject: [PATCH 0844/2102] drm/amdgpu: Fix fault shader cleaner on MI3 MI300/MI350 have a different register layout, and cannot reuse the same definitions from MI2. The shader cleaner can be reused, but not the initialization steps. Also change the dim_x to ensure that we cover all wave slots per SIMD. Fixes: 923d09ab1f9a ("drm/amdkfd: Fix TCP XNACK scoreboard reset race on MI300") Signed-off-by: Kent Russell Reviewed-by: Jay Cornwall Signed-off-by: Alex Deucher (cherry picked from commit ad884eacf92d19b80cdd723dbbc8472b173685fc) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c | 24 +++++++++++++++++++++--- drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.c | 16 ++++++++++++++++ drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.h | 3 +++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c index 9ba517311bb392..66a389121ad41f 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c @@ -23,12 +23,14 @@ #include "amdgpu.h" #include "soc15.h" #include "soc15d.h" +#include "soc15_common.h" #include "gc/gc_9_4_2_offset.h" #include "gc/gc_9_4_2_sh_mask.h" #include "gfx_v9_0.h" #include "gfx_v9_4_2.h" +#include "gfx_v9_4_3.h" #include "amdgpu_ras.h" #include "amdgpu_gfx.h" @@ -723,6 +725,8 @@ static int gfx_v9_clean_shaders(struct amdgpu_device *adev) struct amdgpu_ib wb_ib; struct amdgpu_ring *ring; struct dma_fence *fence = NULL; + const struct soc15_reg_entry *init_regs; + u32 init_regs_size; u32 pattern = 0xa; int xcc_id; @@ -731,6 +735,20 @@ static int gfx_v9_clean_shaders(struct amdgpu_device *adev) return 0; } + /* gfx943+ has different register layout compared to gfx942.*/ + switch (amdgpu_ip_version(adev, GC_HWIP, 0)) { + case IP_VERSION(9, 4, 3): + case IP_VERSION(9, 4, 4): + case IP_VERSION(9, 5, 0): + init_regs = gfx_v9_4_3_fault_cleaner_init_regs; + init_regs_size = gfx_v9_4_3_fault_cleaner_init_regs_size; + break; + default: + init_regs = fault_cleaner_init_regs_aldebaran; + init_regs_size = ARRAY_SIZE(fault_cleaner_init_regs_aldebaran); + break; + } + for_each_inst(xcc_id, adev->gfx.xcc_mask) { ring = &adev->gfx.compute_ring[xcc_id * adev->gfx.num_compute_rings]; @@ -752,9 +770,9 @@ static int gfx_v9_clean_shaders(struct amdgpu_device *adev) ring, fault_cleaner_compute_shader_aldebaran, sizeof(fault_cleaner_compute_shader_aldebaran), - fault_cleaner_init_regs_aldebaran, - ARRAY_SIZE(fault_cleaner_init_regs_aldebaran), - adev->gfx.cu_info.number * 32, + init_regs, + init_regs_size, + adev->gfx.cu_info.number * SIMD_ID_MAX * WAVE_ID_MAX, wb_ib.gpu_addr, pattern, &fence); if (r) { diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.c b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.c index 01ed1701c781ac..968bf911542d63 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.c @@ -163,6 +163,22 @@ static const struct amdgpu_hwip_reg_entry gc_cp_reg_list_9_4_3[] = { struct amdgpu_gfx_ras gfx_v9_4_3_ras; +const struct soc15_reg_entry gfx_v9_4_3_fault_cleaner_init_regs[] = { + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_RESOURCE_LIMITS), 0x000000000 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_NUM_THREAD_X), 0x40 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_NUM_THREAD_Y), 1 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_NUM_THREAD_Z), 1 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_PGM_RSRC1), 0x00af0000 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_PGM_RSRC2), 0x000000c0 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_PGM_RSRC3), 0x00000000 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_STATIC_THREAD_MGMT_SE0), 0xffffffff }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_STATIC_THREAD_MGMT_SE1), 0xffffffff }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_STATIC_THREAD_MGMT_SE2), 0xffffffff }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_STATIC_THREAD_MGMT_SE3), 0xffffffff }, +}; + +const size_t gfx_v9_4_3_fault_cleaner_init_regs_size = ARRAY_SIZE(gfx_v9_4_3_fault_cleaner_init_regs); + static void gfx_v9_4_3_set_ring_funcs(struct amdgpu_device *adev); static void gfx_v9_4_3_set_irq_funcs(struct amdgpu_device *adev); static void gfx_v9_4_3_set_gds_init(struct amdgpu_device *adev); diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.h b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.h index 42d67ee0e7ef64..81f8805a1fbce2 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.h +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.h @@ -28,4 +28,7 @@ extern const struct amdgpu_ip_block_version gfx_v9_4_3_ip_block; extern struct amdgpu_xcp_ip_funcs gfx_v9_4_3_xcp_funcs; +extern const struct soc15_reg_entry gfx_v9_4_3_fault_cleaner_init_regs[]; +extern const size_t gfx_v9_4_3_fault_cleaner_init_regs_size; + #endif /* __GFX_V9_4_3_H__ */ From 47fecd054adb4ab920faaee7156c632e29971491 Mon Sep 17 00:00:00 2001 From: Kent Russell Date: Tue, 3 Nov 2026 12:21:29 -0500 Subject: [PATCH 0845/2102] drm/amdgpu: Fix fault cleaner race condition clean_process_queues_cpsch would exit early if the memory was evicted, which would skip running the shader cleaner Run the cleaner unconditionally, and track whether the fault was cleaned with a new boolean in the qcd struct. Fixes: 923d09ab1f9a ("drm/amdkfd: Fix TCP XNACK scoreboard reset race on MI300") Signed-off-by: Kent Russell Reviewed-by: Jay Cornwall Signed-off-by: Alex Deucher (cherry picked from commit 24672863a9b9f073ca6fb1508e0a44c7958bf597) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c | 5 ++++- drivers/gpu/drm/amd/amdkfd/kfd_int_process_v9.c | 2 +- drivers/gpu/drm/amd/amdkfd/kfd_priv.h | 5 +++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c b/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c index 61480e9119b8fa..4881684ed88fd1 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c @@ -1534,9 +1534,12 @@ static int clean_process_queues_cpsch(struct device_queue_manager *dqm, int retval = 0; dqm_lock(dqm); - if (qpd->evicted++ > 0) /* already evicted, do nothing */ + if (qpd->fault_cleaned) goto out; + qpd->evicted++; + qpd->fault_cleaned = true; + pdd = qpd_to_pdd(qpd); /* The debugger creates processes that temporarily have not acquired diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_int_process_v9.c b/drivers/gpu/drm/amd/amdkfd/kfd_int_process_v9.c index 2ae1129fea55e7..1b597fab53957c 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_int_process_v9.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_int_process_v9.c @@ -370,7 +370,7 @@ static void gfx_9_clean_fault(uint16_t pasid) if (!pdd) return; - /* To Clean the GFX on the faulting device */ + /* To clean the GFX fault state on the faulting device */ dqm = pdd->dev->dqm; dqm->ops.clean_process_queues_cpsch(dqm, &pdd->qpd); diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h index ccb7bbde112dc4..a7b98a8b8e31ee 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h +++ b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h @@ -695,6 +695,11 @@ struct qcm_process_device { bool is_debug; unsigned int evicted; /* eviction counter, 0=active */ + /* Set after fault clean runs; never cleared. + * Prevents redundant cleaning from pipelined interrupt workers. + */ + bool fault_cleaned; + /* This flag tells if we should reset all wavefronts on * process termination */ From 1ff6e3264ea63f9f171211d685a0da8d6a837ee5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20K=C3=B6nig?= Date: Wed, 23 Sep 2026 15:10:13 +0200 Subject: [PATCH 0846/2102] drm/amdgpu: fix cleared PDE/PTE flag generation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit That was broken since adding the NPA support. Signed-off-by: Christian König Reviewed-by: Timur Kristóf Signed-off-by: Alex Deucher (cherry picked from commit 6250a8342784703e2ee4da14fb16f3cdbf05b4d5) --- drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c | 64 ++++++++++++----------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c index c73eb416c0e26b..a6d389c08524fa 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c @@ -346,6 +346,33 @@ static void amdgpu_vm_pt_next_dfs(struct amdgpu_device *adev, amdgpu_vm_pt_continue_dfs((start), (entry)); \ (entry) = (cursor).entry, amdgpu_vm_pt_next_dfs((adev), &(cursor))) +/* Return the flags used for cleared PDEs/PTES */ +static uint64_t amdgpu_vm_pt_clear_flags(struct amdgpu_device *adev, + struct amdgpu_vm *vm, + unsigned int level) +{ + uint64_t flags; + + if (adev->asic_type < CHIP_VEGA10) + return 0; + + if (level != AMDGPU_VM_PTB) { + uint64_t value = 0; + + flags = AMDGPU_PDE_PTE_FLAG(adev); + if (vm->is_npa) + flags |= adev->gmc.noretry_flags; + amdgpu_gmc_get_vm_pde(adev, level, &value, &flags); + } else if (vm->is_npa) { + flags = adev->gmc.noretry_flags; + } else { + /* Workaround for fault priority problem on GMC9 */ + flags = AMDGPU_PTE_EXECUTABLE | adev->gmc.init_pte_flags; + } + + return flags; +} + /** * amdgpu_vm_pt_clear - initially clear the PDs/PTs * @@ -366,10 +393,9 @@ int amdgpu_vm_pt_clear(struct amdgpu_device *adev, struct amdgpu_vm *vm, struct ttm_operation_ctx ctx = { true, false }; struct amdgpu_vm_update_params params; struct amdgpu_bo *ancestor = &vmbo->bo; - unsigned int entries; struct amdgpu_bo *bo = &vmbo->bo; - uint64_t value = 0, flags = 0; - uint64_t addr; + unsigned int entries; + uint64_t flags; int r, idx; /* Figure out our place in the hierarchy */ @@ -404,26 +430,8 @@ int amdgpu_vm_pt_clear(struct amdgpu_device *adev, struct amdgpu_vm *vm, if (r) goto exit; - addr = 0; - - if (adev->asic_type >= CHIP_VEGA10) { - if (level != AMDGPU_VM_PTB) { - if (vm->is_npa) - flags = adev->gmc.noretry_flags; - /* Handle leaf PDEs as PTEs */ - flags |= AMDGPU_PDE_PTE_FLAG(adev); - amdgpu_gmc_get_vm_pde(adev, level, - &value, &flags); - } else if (vm->is_npa) { - flags = adev->gmc.noretry_flags; - } else { - /* Workaround for fault priority problem on GMC9 */ - flags = AMDGPU_PTE_EXECUTABLE | adev->gmc.init_pte_flags; - } - } - - r = vm->update_funcs->update(¶ms, vmbo, addr, 0, entries, - value, flags); + flags = amdgpu_vm_pt_clear_flags(adev, vm, level); + r = vm->update_funcs->update(¶ms, vmbo, 0, 0, entries, 0, flags); if (r) goto exit; @@ -714,15 +722,9 @@ static void amdgpu_vm_pte_update_flags(struct amdgpu_vm_update_params *params, flags |= AMDGPU_PDE_PTE_FLAG(params->adev); amdgpu_gmc_get_vm_pde(adev, level, &addr, &flags); - } else if (adev->asic_type >= CHIP_VEGA10 && - !(flags & AMDGPU_PTE_VALID) && + } else if (!(flags & AMDGPU_PTE_VALID) && !(flags & AMDGPU_PTE_PRT_FLAG(params->adev))) { - - /* Workaround for fault priority problem on GMC9 and GFX12, - * EXECUTABLE for GMC9 fault priority and init_pte_flags - * (e.g. AMDGPU_PTE_IS_PTE on GFX12) - */ - flags |= AMDGPU_PTE_EXECUTABLE | adev->gmc.init_pte_flags; + flags |= amdgpu_vm_pt_clear_flags(adev, params->vm, level); } /* From 6fd6e75162065c7ac9a4a7f3cf303574f0505d97 Mon Sep 17 00:00:00 2001 From: Adrian Betschart Date: Thu, 29 Oct 2026 08:45:58 +0100 Subject: [PATCH 0847/2102] drm/amd/display: Apply the HDMI RGB range default only to HDMI signals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since d23f735d0eac, Broadcast RGB "Automatic" selects limited range on CTA modes when display_info.is_hdmi is set. That flag comes from an HDMI VSDB in the EDID and says nothing about the link, so a native DisplayPort monitor whose EDID carries an HDMI VSDB now gets limited range on CTA modes too. Monitors that ignore the DP range signal show grey blacks, where 7.2 sent full range. Require an HDMI signal as well, as the original commit intended. DP++ passive adapters drive an HDMI signal and keep the HDMI behaviour; native DP, DP MST and active DP-to-HDMI converters get full range again. Reported and analysed by Andrés Rodríguez in the issue below. Fixes: d23f735d0eac ("drm/amd/display: Default HDMI RGB output to limited range on CTA modes") Closes: https://gitlab.freedesktop.org/drm/amd/-/issues/6052 Reviewed-by: Wayne Lin Signed-off-by: Adrian Betschart Signed-off-by: Wayne Lin Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Alex Deucher (cherry picked from commit 39f37a2346410a33edf4af17a873ac96bb5244ce) Cc: stable@vger.kernel.org # 7.3 --- .../gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c | 14 +-- .../display/amdgpu_dm/amdgpu_dm_connector.c | 16 ++-- .../display/amdgpu_dm/amdgpu_dm_connector.h | 3 +- .../tests/amdgpu_dm_connector_test.c | 90 ++++++++++++++----- 4 files changed, 89 insertions(+), 34 deletions(-) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c index 807cb4d6150b02..1b9f830b1c7561 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c @@ -5309,9 +5309,11 @@ static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state) scaling_changed = is_scaling_state_different(dm_new_con_state, dm_old_con_state); - if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) && - (dm_old_crtc_state->stream->output_color_space != - amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state))) + if (new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb && + dm_old_crtc_state->stream->output_color_space != + amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing, + new_con_state, + dm_new_crtc_state->stream->signal)) output_color_space_changed = true; abm_changed = dm_new_crtc_state->abm_level != @@ -5333,8 +5335,10 @@ static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state) } if (output_color_space_changed) { - dm_new_crtc_state->stream->output_color_space - = amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state); + dm_new_crtc_state->stream->output_color_space = + amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing, + new_con_state, + dm_new_crtc_state->stream->signal); stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space; } diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c index b498fc5fbb140e..69421a3bfc0506 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c @@ -737,7 +737,8 @@ EXPORT_IF_KUNIT(get_aspect_ratio); * With Broadcast RGB left at Automatic follow that default, as i915 does. */ static bool rgb_output_is_limited_range(const struct dc_crtc_timing *dc_crtc_timing, - const struct drm_connector_state *connector_state) + const struct drm_connector_state *connector_state, + enum signal_type signal) { switch (connector_state->hdmi.broadcast_rgb) { case DRM_HDMI_BROADCAST_RGB_FULL: @@ -745,14 +746,16 @@ static bool rgb_output_is_limited_range(const struct dc_crtc_timing *dc_crtc_tim case DRM_HDMI_BROADCAST_RGB_LIMITED: return true; default: - return connector_state->connector->display_info.is_hdmi && + return dc_is_hdmi_signal(signal) && + connector_state->connector->display_info.is_hdmi && dc_crtc_timing->vic > 1; } } enum dc_color_space amdgpu_dm_get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing, - const struct drm_connector_state *connector_state) + const struct drm_connector_state *connector_state, + enum signal_type signal) { enum dc_color_space color_space = COLOR_SPACE_SRGB; @@ -775,7 +778,7 @@ amdgpu_dm_get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing, case DRM_MODE_COLORIMETRY_BT2020_RGB: case DRM_MODE_COLORIMETRY_BT2020_YCC: if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) { - if (rgb_output_is_limited_range(dc_crtc_timing, connector_state)) + if (rgb_output_is_limited_range(dc_crtc_timing, connector_state, signal)) color_space = COLOR_SPACE_2020_RGB_LIMITEDRANGE; else color_space = COLOR_SPACE_2020_RGB_FULLRANGE; @@ -787,7 +790,7 @@ amdgpu_dm_get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing, default: if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) { color_space = COLOR_SPACE_SRGB; - if (rgb_output_is_limited_range(dc_crtc_timing, connector_state)) + if (rgb_output_is_limited_range(dc_crtc_timing, connector_state, signal)) color_space = COLOR_SPACE_SRGB_LIMITED; /* * 27030khz is the separation point between HDTV and SDTV @@ -981,7 +984,8 @@ STATIC_IFN_KUNIT void fill_stream_properties_from_drm_display_mode( if (is_hdmi_ep) adjust_colour_depth_from_display_info(timing_out, info); - stream->output_color_space = amdgpu_dm_get_output_color_space(timing_out, connector_state); + stream->output_color_space = amdgpu_dm_get_output_color_space(timing_out, connector_state, + stream->signal); stream->content_type = get_output_content_type(connector_state); } EXPORT_IF_KUNIT(fill_stream_properties_from_drm_display_mode); diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.h b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.h index 79698deacf616d..1528315d79e435 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.h +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.h @@ -129,7 +129,8 @@ int amdgpu_dm_fill_hdr_info_packet(const struct drm_connector_state *state, enum dc_color_space amdgpu_dm_get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing, - const struct drm_connector_state *connector_state); + const struct drm_connector_state *connector_state, + enum signal_type signal); struct drm_display_mode * amdgpu_dm_get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector, diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_connector_test.c b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_connector_test.c index f09e2a72c53465..5988f62f470961 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_connector_test.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_connector_test.c @@ -422,7 +422,8 @@ static void dm_test_output_color_space_default_rgb_full(struct kunit *test) state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_SRGB); } @@ -439,7 +440,8 @@ static void dm_test_output_color_space_default_rgb_limited(struct kunit *test) state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_SRGB_LIMITED); } @@ -457,7 +459,8 @@ static void dm_test_output_color_space_default_ycbcr709(struct kunit *test) timing.flags.Y_ONLY = 0; state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR709); } @@ -476,7 +479,8 @@ static void dm_test_output_color_space_default_ycbcr601_limited(struct kunit *te timing.flags.Y_ONLY = 1; state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR601_LIMITED); } @@ -492,7 +496,8 @@ static void dm_test_output_color_space_bt601_y_only(struct kunit *test) timing.flags.Y_ONLY = 1; state.colorspace = DRM_MODE_COLORIMETRY_BT601_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR601_LIMITED); } @@ -508,7 +513,8 @@ static void dm_test_output_color_space_bt601(struct kunit *test) timing.flags.Y_ONLY = 0; state.colorspace = DRM_MODE_COLORIMETRY_BT601_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR601); } @@ -524,7 +530,8 @@ static void dm_test_output_color_space_bt709(struct kunit *test) timing.flags.Y_ONLY = 0; state.colorspace = DRM_MODE_COLORIMETRY_BT709_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR709); } @@ -540,7 +547,8 @@ static void dm_test_output_color_space_bt709_y_only(struct kunit *test) timing.flags.Y_ONLY = 1; state.colorspace = DRM_MODE_COLORIMETRY_BT709_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR709_LIMITED); } @@ -555,7 +563,8 @@ static void dm_test_output_color_space_oprgb(struct kunit *test) state.colorspace = DRM_MODE_COLORIMETRY_OPRGB; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_ADOBERGB); } @@ -573,7 +582,8 @@ static void dm_test_output_color_space_bt2020_rgb(struct kunit *test) timing.pixel_encoding = PIXEL_ENCODING_RGB; state.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_RGB_FULLRANGE); } @@ -590,7 +600,8 @@ static void dm_test_output_color_space_bt2020_rgb_limited(struct kunit *test) state.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_RGB_LIMITEDRANGE); } @@ -611,7 +622,8 @@ static void dm_test_output_color_space_default_rgb_auto_hdmi_cta(struct kunit *t state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_SRGB_LIMITED); } @@ -632,7 +644,8 @@ static void dm_test_output_color_space_default_rgb_auto_hdmi_vga(struct kunit *t state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_SRGB); } @@ -652,7 +665,31 @@ static void dm_test_output_color_space_default_rgb_auto_dp_cta(struct kunit *tes state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_DISPLAY_PORT), + (int)COLOR_SPACE_SRGB); +} + +/** + * dm_test_output_color_space_default_rgb_auto_dp_hdmi_vsdb - Automatic on DP stays full range + * even when the EDID has an HDMI VSDB + * @test: The KUnit test context + */ +static void dm_test_output_color_space_default_rgb_auto_dp_hdmi_vsdb(struct kunit *test) +{ + struct dc_crtc_timing timing = {}; + struct drm_connector_state state = {}; + struct drm_connector *connector = kunit_kzalloc(test, sizeof(*connector), GFP_KERNEL); + + connector->display_info.is_hdmi = true; + timing.pixel_encoding = PIXEL_ENCODING_RGB; + timing.vic = 118; + state.connector = connector; + state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; + state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; + + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_DISPLAY_PORT), (int)COLOR_SPACE_SRGB); } @@ -673,7 +710,8 @@ static void dm_test_output_color_space_default_rgb_full_hdmi_cta(struct kunit *t state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_FULL; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_SRGB); } @@ -694,7 +732,8 @@ static void dm_test_output_color_space_bt2020_rgb_auto_hdmi_cta(struct kunit *te state.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_RGB_LIMITEDRANGE); } @@ -710,7 +749,8 @@ static void dm_test_output_color_space_bt2020_ycc(struct kunit *test) timing.pixel_encoding = PIXEL_ENCODING_YCBCR422; state.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_YCBCR_LIMITED); } @@ -729,7 +769,8 @@ static void dm_test_output_color_space_default_ycbcr709_y_only(struct kunit *tes timing.flags.Y_ONLY = 1; state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR709_LIMITED); } @@ -748,7 +789,8 @@ static void dm_test_output_color_space_default_ycbcr601(struct kunit *test) timing.flags.Y_ONLY = 0; state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR601); } @@ -767,7 +809,8 @@ static void dm_test_output_color_space_bt2020_ycc_rgb_encoding(struct kunit *tes timing.pixel_encoding = PIXEL_ENCODING_RGB; state.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_RGB_FULLRANGE); } @@ -785,7 +828,8 @@ static void dm_test_output_color_space_bt2020_ycc_rgb_encoding_limited(struct ku state.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_RGB_LIMITEDRANGE); } @@ -802,7 +846,8 @@ static void dm_test_output_color_space_bt2020_rgb_ycc_encoding(struct kunit *tes timing.pixel_encoding = PIXEL_ENCODING_YCBCR444; state.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_YCBCR_LIMITED); } @@ -10010,6 +10055,7 @@ static struct kunit_case amdgpu_dm_connector_tests[] = { KUNIT_CASE(dm_test_output_color_space_default_rgb_auto_hdmi_cta), KUNIT_CASE(dm_test_output_color_space_default_rgb_auto_hdmi_vga), KUNIT_CASE(dm_test_output_color_space_default_rgb_auto_dp_cta), + KUNIT_CASE(dm_test_output_color_space_default_rgb_auto_dp_hdmi_vsdb), KUNIT_CASE(dm_test_output_color_space_default_rgb_full_hdmi_cta), KUNIT_CASE(dm_test_output_color_space_bt2020_rgb_auto_hdmi_cta), KUNIT_CASE(dm_test_output_color_space_bt2020_ycc), From bd2ea9d0787584209eda39332b40a3cf0f8d6865 Mon Sep 17 00:00:00 2001 From: Prike Liang Date: Tue, 10 Nov 2026 13:56:26 +0800 Subject: [PATCH 0848/2102] drm/amdgpu: keep reading the vblank counter in IRQ context during reset amdgpu_get_vblank_counter_kms() returns the cached vblank->last instead of reading the hardware counter whenever it can't take reset_domain->sem for reading. The vblank interrupt reads the counter through the same callback via drm_crtc_handle_vblank(), so once GPU recovery holds the semaphore for writing, every vblank interrupt sees diff == 0 and the DRM vblank count stops advancing. The CRTCs keep scanning out until dm_suspend() turns vblank off and stops the streams, though, which only happens after the rest of the recovery preparation. Vblank waits in that window don't see a vblank anymore. They only end when dm_suspend() turns vblank off, or after a second with the "vblank wait timed out" warning if that takes longer. The fbdev damage worker is likely to be waiting already, because recovery prints "GPU reset begin!" right before it takes the semaphore. Vblank interrupts only arrive while a CRTC is scanning out, so the interrupt path can read the hardware counter. amdgpu_device_skip_hw_access() likewise only checks the reset semaphore in task context. Only back off in task context, so the interrupt path keeps the count moving until DM turns vblank off. Fixes: 51a4359f7431 ("drm/amdgpu: serialize vblank counter reads against GPU reset") Cc: Vitaly Prosyak Cc: James Lin Cc: Leo Li Assisted-by: Copilot:claude-opus-5.5 Signed-off-by: Prike Liang Reviewed-by: Vitaly Prosyak Signed-off-by: Alex Deucher (cherry picked from commit ff157c5bd3603360f18ed0b427913fb50c043a16) --- drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c index 6e710e4e24b8fd..d442a2d9639455 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c @@ -1688,6 +1688,7 @@ u32 amdgpu_get_vblank_counter_kms(struct drm_crtc *crtc) struct drm_device *dev = crtc->dev; unsigned int pipe = crtc->index; struct amdgpu_device *adev = drm_to_adev(dev); + bool locked = false; int vpos, hpos, stat; u32 count; @@ -1695,9 +1696,26 @@ u32 amdgpu_get_vblank_counter_kms(struct drm_crtc *crtc) DRM_ERROR("Invalid crtc %u\n", pipe); return -EINVAL; } - if (!down_read_trylock(&adev->reset_domain->sem)) - return drm_crtc_vblank_count(crtc); + /* + * A GPU reset is in progress and the display hardware cannot be read + * safely. Return the hardware counter value DRM already cached rather + * than the software vblank count: the core feeds this callback's + * result back into vblank->last, and a software count lives in a + * different numeric domain, which later trips + * drm_WARN_ON_ONCE(cur_vblank != vblank->last) in + * drm_update_vblank_count(). + * + * Only task context has to back off. Vblank interrupts only arrive + * while a CRTC is scanning out, so the interrupt path can read the + * hardware, and it has to keep counting: vblank waits that already + * sleep when a reset takes the semaphore never complete otherwise. + */ + if (in_task()) { + if (!down_read_trylock(&adev->reset_domain->sem)) + return drm_crtc_vblank_crtc(crtc)->last; + locked = true; + } /* The hw increments its frame counter at start of vsync, not at start * of vblank, as is required by DRM core vblank counter handling. @@ -1743,7 +1761,8 @@ u32 amdgpu_get_vblank_counter_kms(struct drm_crtc *crtc) DRM_DEBUG_VBL("NULL mode info! Returned count may be wrong.\n"); } - up_read(&adev->reset_domain->sem); + if (locked) + up_read(&adev->reset_domain->sem); return count; } From 6d8e709912753f175256e4fafb73ba1ea50baf9f Mon Sep 17 00:00:00 2001 From: Mario Limonciello Date: Sat, 14 Nov 2026 10:09:25 -0600 Subject: [PATCH 0849/2102] drm/amd: Select the firmware signing scheme the PSP reports Some platforms ship BIOS with either a default or an alternative trust authority, so firmware for every IP must be signed with the matching scheme. The PSP advertises which one is in use in bit 6 of C2PMSG_63, and in bit 28 whether this is a preproduction part, which needs firmware of its own. Add amdgpu_psp_init_fw_variant() which reads those bits through amdgpu's own MMIO, and keep the result in adev->firmware.sign_type next to load_type, where preproduction is a type of its own. It is initialized once, after IP discovery has populated the register bases and only when firmware is loaded through the front door (the PSP). Only MP0 15.0.0 and 15.0.9 report it. For all other ASICs, SR-IOV VFs and an inaccessible register (all ones) the defaults are kept: AMDGPU_FW_SIGN_DEFAULT. A preproduction part that also reports the alternative scheme is not expected. Mark it AMDGPU_FW_SIGN_UNKNOWN, so that firmware requests warn and fail with -EINVAL rather than load firmware that would be rejected. Firmware for preproduction parts is named with a "_p" suffix before the extension and firmware for the alternative scheme with an "_l" suffix (e.g. "foo.bin" becomes "foo_p.bin" or "foo_l.bin"). Production parts on the default scheme use the plain names. Do the substitution centrally in amdgpu_ucode_request() so it covers every IP that loads firmware through it (PSP, SMU, DMUB, GC, IMU, MES, SDMA, VCN, VPE, ...) without each loader having to care. There is no fallback to the default file: it would be rejected anyway. Declare the variants with MODULE_FIRMWARE() so that initramfs generators include them. Acked-by: Alex Deucher Link: https://patch.msgid.link/20261114160925.390350-1-superm1@kernel.org Signed-off-by: Mario Limonciello Signed-off-by: Alex Deucher (cherry picked from commit 2fe41c5fb704e05ccf2bf00634e1b5ad2db4e5b7) --- drivers/gpu/drm/amd/amdgpu/amdgpu_device.c | 4 ++ drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c | 20 ++++++++ drivers/gpu/drm/amd/amdgpu/amdgpu_psp.h | 1 + drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.c | 35 ++++++++++++++ drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.h | 9 ++++ drivers/gpu/drm/amd/amdgpu/amdgpu_vcn.c | 4 ++ drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c | 16 +++++++ drivers/gpu/drm/amd/amdgpu/imu_v11_0.c | 4 ++ drivers/gpu/drm/amd/amdgpu/mes_v11_0.c | 8 ++++ drivers/gpu/drm/amd/amdgpu/psp_v15_0.c | 47 +++++++++++++++++++ drivers/gpu/drm/amd/amdgpu/psp_v15_0.h | 1 + drivers/gpu/drm/amd/amdgpu/sdma_v6_0.c | 2 + drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c | 2 + .../amd/display/amdgpu_dm/amdgpu_dm_dmub.c | 2 + .../amd/display/amdgpu_dm/amdgpu_dm_dmub.h | 2 + 15 files changed, 157 insertions(+) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c index 19a566187dfb56..b24ccdd958a7fb 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c @@ -2101,6 +2101,10 @@ static int amdgpu_device_ip_early_init(struct amdgpu_device *adev) amdgpu_ip_version((adev), GC_HWIP, 0) == IP_VERSION(9, 4, 4); } + /* Needs the register bases, and must be known before requesting firmware */ + if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) + amdgpu_psp_init_fw_variant(adev); + total = true; for (i = 0; i < adev->num_ip_blocks; i++) { ip_block = &adev->ip_blocks[i]; diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c index 82a2684dbd2e19..6d693b5249ddd9 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c @@ -403,6 +403,26 @@ static uint64_t psp_get_runtime_db_header_pos(struct amdgpu_device *adev) return pos; } +/* + * Which firmware the platform needs, as reported by the PSP in C2PMSG_63: the + * signing scheme and whether this is a preproduction part. The defaults are kept if + * the ASIC doesn't report it or it can't be read. + */ +void amdgpu_psp_init_fw_variant(struct amdgpu_device *adev) +{ + if (amdgpu_sriov_vf(adev)) + return; + + switch (amdgpu_ip_version(adev, MP0_HWIP, 0)) { + case IP_VERSION(15, 0, 0): + case IP_VERSION(15, 0, 9): + psp_v15_0_0_get_fw_variant(adev); + break; + default: + break; + } +} + /* * Helper funciton to query psp runtime database entry * diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.h b/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.h index a4ec60f6c31702..7d8fc8eb2b125d 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.h +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.h @@ -631,6 +631,7 @@ int psp_ta_invoke(struct psp_context *psp, int psp_xgmi_initialize(struct psp_context *psp, bool set_extended_data, bool load_ta); bool psp_is_xgmi_ta_supported(struct psp_context *psp); +void amdgpu_psp_init_fw_variant(struct amdgpu_device *adev); int psp_xgmi_terminate(struct psp_context *psp); int psp_xgmi_invoke(struct psp_context *psp, uint32_t ta_cmd_id); int psp_xgmi_get_hive_id(struct psp_context *psp, uint64_t *hive_id); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.c index d2ce526dd95cc0..1632eda91acd91 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.c @@ -1527,6 +1527,37 @@ void amdgpu_ucode_ip_version_decode(struct amdgpu_device *adev, int block_type, snprintf(ucode_prefix, len, "%s_%d_%d_%d", ip_name, maj, min, rev); } +/* Add the suffix of the firmware variant before the extension: foo.bin -> foo_l.bin */ +static int amdgpu_ucode_set_suffix(struct amdgpu_device *adev, char *fname) +{ + const char *suffix; + size_t base; + + switch (adev->firmware.sign_type) { + case AMDGPU_FW_SIGN_PREPROD: + suffix = "_p.bin"; + break; + case AMDGPU_FW_SIGN_ALT: + suffix = "_l.bin"; + break; + case AMDGPU_FW_SIGN_UNKNOWN: + drm_warn(adev_to_drm(adev), "Unknown firmware signing\n"); + return -EINVAL; + default: + /* Default variant: the name is unchanged */ + return 0; + } + + if (!strends(fname, ".bin")) + return -EINVAL; + + base = strlen(fname) - strlen(".bin"); + if (strscpy(fname + base, suffix, AMDGPU_UCODE_NAME_MAX - base) < 0) + return -EOVERFLOW; + + return 0; +} + /* * amdgpu_ucode_request - Fetch and validate amdgpu microcode * @@ -1555,6 +1586,10 @@ int amdgpu_ucode_request(struct amdgpu_device *adev, const struct firmware **fw, return -EOVERFLOW; } + r = amdgpu_ucode_set_suffix(adev, fname); + if (r) + return r; + if (required == AMDGPU_UCODE_REQUIRED) r = request_firmware(fw, fname, adev->dev); else { diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.h b/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.h index 35277b240f25a9..0b2d1bccb999c8 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.h +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.h @@ -571,6 +571,14 @@ enum amdgpu_firmware_load_type { AMDGPU_FW_LOAD_RLC_BACKDOOR_AUTO, }; +enum amdgpu_firmware_sign_type { + AMDGPU_FW_SIGN_DEFAULT = 0, + AMDGPU_FW_SIGN_ALT, + AMDGPU_FW_SIGN_PREPROD, + /* Unexpected combination of signing bits, default firmware may not work */ + AMDGPU_FW_SIGN_UNKNOWN, +}; + enum amdgpu_ucode_required { AMDGPU_UCODE_OPTIONAL, AMDGPU_UCODE_REQUIRED, @@ -606,6 +614,7 @@ struct amdgpu_firmware_info { struct amdgpu_firmware { struct amdgpu_firmware_info ucode[AMDGPU_UCODE_ID_MAXIMUM]; enum amdgpu_firmware_load_type load_type; + enum amdgpu_firmware_sign_type sign_type; struct amdgpu_bo *fw_buf; unsigned int fw_size; unsigned int max_ucodes; diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vcn.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vcn.c index 6c12d8aa3c7696..1df2725d31e0c9 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vcn.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vcn.c @@ -66,6 +66,8 @@ #define FIRMWARE_VCN5_0_1 "amdgpu/vcn_5_0_1.bin" #define FIRMWARE_VCN5_0_2 "amdgpu/vcn_5_0_2.bin" #define FIRMWARE_VCN5_3_0 "amdgpu/vcn_5_3_0.bin" +#define FIRMWARE_VCN5_3_0_ALT "amdgpu/vcn_5_3_0_l.bin" +#define FIRMWARE_VCN5_3_0_PREPROD "amdgpu/vcn_5_3_0_p.bin" MODULE_FIRMWARE(FIRMWARE_RAVEN); MODULE_FIRMWARE(FIRMWARE_PICASSO); @@ -95,6 +97,8 @@ MODULE_FIRMWARE(FIRMWARE_VCN5_0_0); MODULE_FIRMWARE(FIRMWARE_VCN5_0_1); MODULE_FIRMWARE(FIRMWARE_VCN5_0_2); MODULE_FIRMWARE(FIRMWARE_VCN5_3_0); +MODULE_FIRMWARE(FIRMWARE_VCN5_3_0_ALT); +MODULE_FIRMWARE(FIRMWARE_VCN5_3_0_PREPROD); static void amdgpu_vcn_idle_work_handler(struct work_struct *work); static void amdgpu_vcn_reg_dump_fini(struct amdgpu_device *adev); diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c b/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c index 11388b6660379a..da4e1cf9ed630e 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c @@ -134,13 +134,29 @@ MODULE_FIRMWARE("amdgpu/gc_11_5_6_me.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_6_mec.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_6_rlc.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_pfp.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_pfp_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_pfp_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_me.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_me_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_me_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_mec.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mec_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mec_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_rlc.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_rlc_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_rlc_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_pfp.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_pfp_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_pfp_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_me.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_me_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_me_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_mec.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mec_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mec_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_rlc.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_rlc_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_rlc_p.bin"); static const struct amdgpu_hwip_reg_entry gc_reg_list_11_0[] = { SOC15_REG_ENTRY_STR(GC, 0, regGRBM_STATUS), diff --git a/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c b/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c index 09dc01a425d131..a409911939d381 100644 --- a/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c +++ b/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c @@ -44,7 +44,11 @@ MODULE_FIRMWARE("amdgpu/gc_11_5_3_imu.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_4_imu.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_6_imu.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_imu.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_imu_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_imu_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_imu.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_imu_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_imu_p.bin"); static int imu_v11_0_init_microcode(struct amdgpu_device *adev) { diff --git a/drivers/gpu/drm/amd/amdgpu/mes_v11_0.c b/drivers/gpu/drm/amd/amdgpu/mes_v11_0.c index 0895c29899d2be..c76a6c4e69992a 100644 --- a/drivers/gpu/drm/amd/amdgpu/mes_v11_0.c +++ b/drivers/gpu/drm/amd/amdgpu/mes_v11_0.c @@ -61,9 +61,17 @@ MODULE_FIRMWARE("amdgpu/gc_11_5_4_mes1.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_6_mes_2.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_6_mes1.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes_2.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes_2_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes_2_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes1.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes1_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes1_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes_2.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes_2_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes_2_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes1.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes1_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes1_p.bin"); static int mes_v11_0_hw_init(struct amdgpu_ip_block *ip_block); static int mes_v11_0_hw_fini(struct amdgpu_ip_block *ip_block); diff --git a/drivers/gpu/drm/amd/amdgpu/psp_v15_0.c b/drivers/gpu/drm/amd/amdgpu/psp_v15_0.c index abaa40b6def90d..94b3fce1bc70af 100644 --- a/drivers/gpu/drm/amd/amdgpu/psp_v15_0.c +++ b/drivers/gpu/drm/amd/amdgpu/psp_v15_0.c @@ -32,11 +32,19 @@ #include "mp/mp_15_0_0_sh_mask.h" MODULE_FIRMWARE("amdgpu/psp_15_0_0_toc.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_0_toc_l.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_0_toc_p.bin"); MODULE_FIRMWARE("amdgpu/psp_15_0_0_ta.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_0_ta_l.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_0_ta_p.bin"); MODULE_FIRMWARE("amdgpu/psp_15_0_5_toc.bin"); MODULE_FIRMWARE("amdgpu/psp_15_0_5_ta.bin"); MODULE_FIRMWARE("amdgpu/psp_15_0_9_toc.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_9_toc_l.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_9_toc_p.bin"); MODULE_FIRMWARE("amdgpu/psp_15_0_9_ta.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_9_ta_l.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_9_ta_p.bin"); #define regMPASP_PCRU0_MPASP_C2PMSG_64 0x4280 #define regMPASP_PCRU0_MPASP_C2PMSG_64_BASE_IDX 2 @@ -108,6 +116,45 @@ static int psp_v15_0_0_ring_stop(struct psp_context *psp, return ret; } +/* + * C2PMSG_63 bit 6: 0 = default firmware signing, 1 = alternative + * C2PMSG_63 bit 28: 0 = production part, 1 = preproduction part + */ +#define PSP_V15_0_0_FW_SIGN_ALT BIT(6) +#define PSP_V15_0_0_FW_PREPROD BIT(28) + +void psp_v15_0_0_get_fw_variant(struct amdgpu_device *adev) +{ + bool alt, preprod; + u32 val; + + if (!adev->reg_offset[MP0_HWIP][0]) + return; + + val = RREG32_SOC15(MP0, 0, regMPASP_SMN_C2PMSG_63); + if (val == 0xffffffff) { + drm_warn(adev_to_drm(adev), "Unable to access regMPASP_SMN_C2PMSG_63\n"); + return; + } + + alt = val & PSP_V15_0_0_FW_SIGN_ALT; + preprod = val & PSP_V15_0_0_FW_PREPROD; + + if (alt && preprod) { + adev->firmware.sign_type = AMDGPU_FW_SIGN_UNKNOWN; + return; + } + + if (preprod) + adev->firmware.sign_type = AMDGPU_FW_SIGN_PREPROD; + else if (alt) + adev->firmware.sign_type = AMDGPU_FW_SIGN_ALT; + + dev_info(adev->dev, "PSP firmware: %s signing, %s part (C2PMSG_63=0x%08x)\n", + alt ? "alternative" : "default", + preprod ? "preproduction" : "production", val); +} + static int psp_v15_0_0_ring_create(struct psp_context *psp, enum psp_ring_type ring_type) { diff --git a/drivers/gpu/drm/amd/amdgpu/psp_v15_0.h b/drivers/gpu/drm/amd/amdgpu/psp_v15_0.h index ebd612103526fc..081be8e8268bc1 100644 --- a/drivers/gpu/drm/amd/amdgpu/psp_v15_0.h +++ b/drivers/gpu/drm/amd/amdgpu/psp_v15_0.h @@ -26,5 +26,6 @@ #include "amdgpu_psp.h" void psp_v15_0_0_set_psp_funcs(struct psp_context *psp); +void psp_v15_0_0_get_fw_variant(struct amdgpu_device *adev); #endif diff --git a/drivers/gpu/drm/amd/amdgpu/sdma_v6_0.c b/drivers/gpu/drm/amd/amdgpu/sdma_v6_0.c index 4845588c4c2471..2586d49f1e940f 100644 --- a/drivers/gpu/drm/amd/amdgpu/sdma_v6_0.c +++ b/drivers/gpu/drm/amd/amdgpu/sdma_v6_0.c @@ -56,6 +56,8 @@ MODULE_FIRMWARE("amdgpu/sdma_6_1_1.bin"); MODULE_FIRMWARE("amdgpu/sdma_6_1_2.bin"); MODULE_FIRMWARE("amdgpu/sdma_6_1_3.bin"); MODULE_FIRMWARE("amdgpu/sdma_6_1_4.bin"); +MODULE_FIRMWARE("amdgpu/sdma_6_1_4_l.bin"); +MODULE_FIRMWARE("amdgpu/sdma_6_1_4_p.bin"); MODULE_FIRMWARE("amdgpu/sdma_6_4_0.bin"); #define SDMA1_REG_OFFSET 0x600 diff --git a/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c b/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c index c92c5fc59aeb96..cefb8d739faf86 100644 --- a/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c @@ -31,6 +31,8 @@ #include "vpe/vpe_2_0_0_sh_mask.h" MODULE_FIRMWARE("amdgpu/vpe_2_0_0.bin"); +MODULE_FIRMWARE("amdgpu/vpe_2_0_0_l.bin"); +MODULE_FIRMWARE("amdgpu/vpe_2_0_0_p.bin"); MODULE_FIRMWARE("amdgpu/vpe_2_2_0.bin"); #define VPE_THREAD1_UCODE_OFFSET 0x8000 diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.c index 383c53afd1f676..7cd08a9a957d64 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.c @@ -62,6 +62,8 @@ MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB); MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB); MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB); MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB); +MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB_ALT); +MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB_PREPROD); MODULE_FIRMWARE(FIRMWARE_DCN_42B_DMUB); MODULE_FIRMWARE(FIRMWARE_DCN_60_DMUB); diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.h b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.h index df3e776c1ad14d..219e9c0427441f 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.h +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.h @@ -61,6 +61,8 @@ int dm_init_microcode(struct amdgpu_device *adev); #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin" #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin" #define FIRMWARE_DCN_42_DMUB "amdgpu/dcn_4_2_dmcub.bin" +#define FIRMWARE_DCN_42_DMUB_ALT "amdgpu/dcn_4_2_dmcub_l.bin" +#define FIRMWARE_DCN_42_DMUB_PREPROD "amdgpu/dcn_4_2_dmcub_p.bin" #define FIRMWARE_DCN_42B_DMUB "amdgpu/dcn_4_2_1_dmcub.bin" #define FIRMWARE_DCN_60_DMUB "amdgpu/dcn_6_0_0_dmcub.bin" #define FIRMWARE_RAVEN_DMCU "amdgpu/raven_dmcu.bin" From 2b784f5e78694d4d852053b3eef3de3f0ff1d02e Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Tue, 27 Oct 2026 21:52:22 +0100 Subject: [PATCH 0850/2102] drm/amd/display: Don't warn about vendor infoframe for non-infoframe sinks With an EIZO EV2781 connected over HDMI to an AMD Ryzen 3 2200G (Raven) on an MSI B350M MORTAR (MS-7A37), Linux logs at every boot since v6.16: amdgpu 0000:30:00.0: [drm] Failed to setup vendor infoframe on connector HDMI-A-1: -22 Commit 6027cbee1900 ("drm/amd/display: Add error check for avi and vendor infoframe setup function") started to log the return value of drm_hdmi_vendor_infoframe_from_display_mode(). With `frame` and `mode` being non-NULL, the helper only fails with -EINVAL, if the sink does not support HDMI infoframes, that means, if `connector->display_info.has_hdmi_infoframe` is false, and its kernel-doc says, that this error can be safely ignored. drm_parse_hdmi_vsdb_video() only sets `has_hdmi_infoframe`, if the HDMI VSDB has HDMI_Video_present set, and drm_parse_hdmi_forum_scds() sets it for sinks with an HF-SCDB. So an HDMI sink, whose VSDB lacks HDMI_Video_present, triggers the warning, although nothing failed. The EIZO EV2781 is such a sink. Its HDMI VSDB has a payload of only seven bytes (source physical address, Supports_AI, and a maximum TMDS clock of 250 MHz), so the byte with HDMI_Video_present is absent, and the EDID has no HF-SCDB: 67 03 0c 00 10 00 80 32 Only warn, if the sink supports HDMI infoframes. The infoframe setup itself is unchanged. Fixes: 6027cbee1900 ("drm/amd/display: Add error check for avi and vendor infoframe setup function") Closes: https://gitlab.freedesktop.org/drm/amd/-/work_items/5025 Reviewed-by: Wayne Lin Signed-off-by: Paul Menzel Signed-off-by: Wayne Lin Signed-off-by: Alex Deucher (cherry picked from commit 2abfc667f622eb7132b139db2e175642713662f8) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c index 69421a3bfc0506..8a039ef6e4b766 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c @@ -942,7 +942,8 @@ STATIC_IFN_KUNIT void fill_stream_properties_from_drm_display_mode( err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame, (struct drm_connector *)connector, mode_in); - if (err < 0) + /* Sinks without HDMI infoframe support make it fail with -EINVAL. */ + if (err < 0 && info->has_hdmi_infoframe) drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n", connector->name, err); timing_out->hdmi_vic = hv_frame.vic; From 5b148562d193fd63e5d1ae3c442d3d54403c7e51 Mon Sep 17 00:00:00 2001 From: Jackie Liu Date: Mon, 26 Oct 2026 19:10:47 +0800 Subject: [PATCH 0851/2102] drm/amd/display: Fix logger leak on perf trace allocation failure dc_construct_ctx() allocates a logger and stores an alias in dc->dml.logger before allocating the performance trace object. If dc_perf_trace_create() fails, the function frees dc_ctx without releasing the logger. Since dc->ctx is assigned only after the trace allocation succeeds, dc_destruct() cannot reclaim the logger on this error path. Free the logger before discarding dc_ctx and clear dc->dml.logger to avoid leaving a dangling alias after the failed construction. Fixes: 5d72e247e58c ("drm/amd/display: switch DC over to the new DRM logging macros") Reviewed-by: Wayne Lin Signed-off-by: Jackie Liu Signed-off-by: Wayne Lin Signed-off-by: Alex Deucher (cherry picked from commit ac088505e74932f276ea6e3bbe19713e5770e7a1) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/display/dc/core/dc.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/gpu/drm/amd/display/dc/core/dc.c b/drivers/gpu/drm/amd/display/dc/core/dc.c index 422612da44d38a..98e5aa160b7493 100644 --- a/drivers/gpu/drm/amd/display/dc/core/dc.c +++ b/drivers/gpu/drm/amd/display/dc/core/dc.c @@ -1022,6 +1022,8 @@ static bool dc_construct_ctx(struct dc *dc, dc_ctx->perf_trace = dc_perf_trace_create(); if (!dc_ctx->perf_trace) { + kfree(dc_ctx->logger); + dc->dml.logger = NULL; kfree(dc_ctx); ASSERT_CRITICAL(false); return false; From fff46a322847a54cf11d5af3d7fc7fa07bc71b29 Mon Sep 17 00:00:00 2001 From: Davey Hughes Date: Wed, 28 Oct 2026 15:54:12 -0700 Subject: [PATCH 0852/2102] drm/amd/display: Keep FreeSync flip timing across plane resets dm_update_plane_state() replaces the DC plane with a newly allocated one whenever the plane is reset. The new plane's flip timing is zero, and mod_freesync_handle_preflip() runs before DC stores the new plane's first flip timestamp, so FreeSync takes the 32-bit microsecond timestamp itself as the last render time: the monotonic clock modulo about 71.6 minutes. On a panel with below-the-range compensation (BTR), that engages BTR and pins the frame time at the BTR mid-point (13.447 ms on a 48-165 Hz panel). A panel without BTR (max refresh below twice the min) goes through the fixed refresh path instead and locks to its max refresh after six frames. It takes a reset on every flip to keep the panel there, and color management changes reset the plane. DRM sets color_mgmt_changed whenever a color property is given a different blob, even one with the same contents, and KWin 6.8.1 with HDR enabled and its color accuracy setting at "Prefer efficiency" sets a new GAMMA_LUT blob on every commit (current KWin master no longer does). Plane resets for CRTC color changes, added by commit 7316c4ad2996 ("drm/amd/display: Reset planes for color management changes"), and later for plane color properties and colorops, made this reachable on every flip. Copy the flip timing from the old DC plane into the new one when the plane stays on the same CRTC. Do it in amdgpu_dm_commit_planes() before the preflip, after drm_atomic_helper_wait_for_dependencies() has waited for the previous commit, so the copy holds that commit's flip and does not race with DC writing it. This covers both the BTR and the fixed refresh path. A plane that is newly enabled or moved to another CRTC still starts without history. Fixes: 180db303ff46 ("drm/amd/display: Add below the range support for FreeSync") Reviewed-by: Harry Wentland Signed-off-by: Davey Hughes Signed-off-by: Wayne Lin Signed-off-by: Alex Deucher (cherry picked from commit 4acf82d2a2dcca2d7df8649ecafb3da6c1245003) Cc: stable@vger.kernel.org --- .../gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c index 1b9f830b1c7561..5d1b010bec9bfb 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c @@ -3858,6 +3858,25 @@ STATIC_IFN_KUNIT void dm_arm_vblank_event_pre_programming(struct amdgpu_crtc *ac } EXPORT_IF_KUNIT(dm_arm_vblank_event_pre_programming); +/* + * FreeSync times each frame from the plane's previous flip, and a plane + * reset gives the new DC plane zeroed flip timing, so copy it over. Do + * this at commit time, not in atomic check: by then the previous commit + * has finished writing it. + */ +static void +dm_plane_inherit_flip_time(struct dc_plane_state *dc_plane_state, + struct drm_plane_state *old_plane_state, + struct drm_plane_state *new_plane_state) +{ + struct dc_plane_state *old_dc_plane_state = + to_dm_plane_state(old_plane_state)->dc_state; + + if (old_dc_plane_state && old_dc_plane_state != dc_plane_state && + old_plane_state->crtc == new_plane_state->crtc) + dc_plane_state->time = old_dc_plane_state->time; +} + static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state, struct drm_device *dev, struct amdgpu_display_manager *dm, @@ -3962,6 +3981,9 @@ static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state, if (!dc_plane) continue; + dm_plane_inherit_flip_time(dc_plane, old_plane_state, + new_plane_state); + bundle->surface_updates[planes_count].surface = dc_plane; if (new_pcrtc_state->color_mgmt_changed || new_plane_state->color_mgmt_changed) { bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction; From 988ab04d773ac089588ce17742f491e9ee8b1793 Mon Sep 17 00:00:00 2001 From: Hugo Sales Date: Tue, 3 Nov 2026 13:15:57 +0000 Subject: [PATCH 0853/2102] drm/amd/display: Add the AUX backlight minimum once on the custom curve On an AUX backlight, convert_brightness_from_user() maps the user level through the ATIF custom brightness curve with convert_custom_brightness(), which rescales the result to user_min..user_max. convert_brightness_from_user() then rescales it again, from 0..user_max to user_min..user_max, so the minimum goes in twice. On the 1..512 nits AUX fallback range, a request for 0 gives 1998 millinits instead of 1000 Rescale the curve's output to 0..user_max and leave the offset to the caller Fixes: 8dbd72cb7900 ("drm/amd/display: Export full brightness range to userspace") Reviewed-by: Ray Wu Signed-off-by: Hugo Sales Signed-off-by: Wayne Lin Signed-off-by: Alex Deucher (cherry picked from commit 5f95ef2cfd208ca7efe446abfc9e3144dc5ce4fa) Cc: stable@vger.kernel.org --- .../amd/display/amdgpu_dm/amdgpu_dm_backlight.c | 9 ++++----- .../amdgpu_dm/tests/amdgpu_dm_backlight_test.c | 14 +++++++------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_backlight.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_backlight.c index cb74b00723fdab..8d27c2712c516a 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_backlight.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_backlight.c @@ -122,10 +122,10 @@ static inline u32 scale_input_to_fw(int max, u64 input) return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max); } -/* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */ -static inline u32 scale_fw_to_input(int min, int max, u64 input) +/* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [0..max] */ +static inline u32 scale_fw_to_input(int max, u64 input) { - return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL); + return DIV_ROUND_CLOSEST_ULL(input * max, AMDGPU_MAX_BL_LEVEL); } static u32 backlight_signal_to_luminance(const struct amdgpu_dm_backlight_caps *caps, @@ -251,8 +251,7 @@ void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps, (brightness - lower_signal), upper_signal - lower_signal); scale: - *user_brightness = scale_fw_to_input(min, max, - DIV_ROUND_CLOSEST(lum * brightness, 101)); + *user_brightness = scale_fw_to_input(max, DIV_ROUND_CLOSEST(lum * brightness, 101)); } EXPORT_IF_KUNIT(convert_custom_brightness); diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_backlight_test.c b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_backlight_test.c index 5221050dec2f15..e500c55a067214 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_backlight_test.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_backlight_test.c @@ -1125,10 +1125,10 @@ static void dm_test_custom_brightness_exact_match(struct kunit *test) /* * Exact match: lum=50, brightness_scaled=128 - * result = scale_fw_to_input(min, max, DIV_ROUND_CLOSEST(50*128, 101)) - * = scale_fw_to_input(0, 65535, DIV_ROUND_CLOSEST(6400, 101)) - * = scale_fw_to_input(0, 65535, 63) - * = 0 + DIV_ROUND_CLOSEST(63 * 65535, 255) = 16191 (approx) + * result = scale_fw_to_input(max, DIV_ROUND_CLOSEST(50*128, 101)) + * = scale_fw_to_input(65535, DIV_ROUND_CLOSEST(6400, 101)) + * = scale_fw_to_input(65535, 63) + * = DIV_ROUND_CLOSEST(63 * 65535, 255) = 16191 (approx) */ KUNIT_EXPECT_TRUE(test, brightness != 32896); KUNIT_EXPECT_TRUE(test, brightness < 32896); @@ -1171,9 +1171,9 @@ static void dm_test_custom_brightness_below_first(struct kunit *test) /* * Below first data point: lum = DIV_ROUND_CLOSEST(40 * 50, 100) = 20 - * Then: scale_fw_to_input(0, 65535, DIV_ROUND_CLOSEST(20 * 50, 101)) - * = scale_fw_to_input(0, 65535, DIV_ROUND_CLOSEST(1000, 101)) - * = scale_fw_to_input(0, 65535, 10) + * Then: scale_fw_to_input(65535, DIV_ROUND_CLOSEST(20 * 50, 101)) + * = scale_fw_to_input(65535, DIV_ROUND_CLOSEST(1000, 101)) + * = scale_fw_to_input(65535, 10) * The output should be significantly less than input. */ KUNIT_EXPECT_TRUE(test, brightness < 12850); From fb3d0ee0f7cf41488aff58c45f1b31a8f54f3372 Mon Sep 17 00:00:00 2001 From: Thomas Lamprecht Date: Mon, 2 Nov 2026 12:29:43 +0100 Subject: [PATCH 0854/2102] drm/amd/display: Don't warn about links without an HPD GPIO Since commit def3488eb0fd ("drm/amd/display: refactor HPD to increase flexibility"), the link encoder programs the HPD filter, and dce110_program_hpd_filter() and dcn10_program_hpd_filter() hit ASSERT(0) if the encoder has no HPD GPIO. That is the case if link_get_hpd_gpio() finds no usable HPD info for the connector in the VBIOS, where program_hpd_filter() used to return early without a warning. This logs a warning with a stack trace on every boot of some systems, for example with Ryzen 7 PRO 4750G APUs on ASRock Rack X570D4U and X470D4U2-2T boards: WARNING: drivers/gpu/drm/amd/amdgpu/../display/dc/dio/dcn10/dcn10_link_encoder.c:1514 at dcn10_program_hpd_filter+0x39/0x90 [amdgpu], CPU#7: (udev-worker)/836 Call Trace: program_hpd_filter+0x5d/0xb0 [amdgpu] construct_phy+0x96f/0xe60 [amdgpu] link_create+0x1f0/0x240 [amdgpu] create_links+0x164/0x4f0 [amdgpu] dc_create+0x3ba/0x720 [amdgpu] amdgpu_dm_init+0x2c9/0x420 [amdgpu] Return false without asserting if there is no HPD GPIO, as before, and keep the assertion for failing to lock the pin. Fixes: def3488eb0fd ("drm/amd/display: refactor HPD to increase flexibility") Link: https://forum.proxmox.com/threads/kernel-7-0-14-24-and-7-0-14-25-bug-in-amdgpu.187181/ Reviewed-by: Wayne Lin Signed-off-by: Thomas Lamprecht Signed-off-by: Wayne Lin Signed-off-by: Alex Deucher (cherry picked from commit 62ea146c23e14f958744507c37025f1a7f9c041b) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c | 5 ++++- .../gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c b/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c index c6a20378121b3f..0c1fcfd088bacb 100644 --- a/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c +++ b/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c @@ -1841,8 +1841,11 @@ bool dce110_get_hpd_state(struct link_encoder *enc) bool dce110_program_hpd_filter(struct link_encoder *enc, int delay_on_connect_in_ms, int delay_on_disconnect_in_ms) { + if (!enc->hpd_gpio) + return false; + /* Setup HPD filtering */ - if (enc->hpd_gpio && dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { + if (dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { struct gpio_hpd_config config; config.delay_on_connect = delay_on_connect_in_ms; diff --git a/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c b/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c index 32e12d894e31f6..ddb40e6507b59b 100644 --- a/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c +++ b/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c @@ -1506,8 +1506,11 @@ bool dcn10_get_hpd_state(struct link_encoder *enc) bool dcn10_program_hpd_filter(struct link_encoder *enc, int delay_on_connect_in_ms, int delay_on_disconnect_in_ms) { + if (!enc->hpd_gpio) + return false; + /* Setup HPD filtering */ - if (enc->hpd_gpio && dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { + if (dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { struct gpio_hpd_config config; config.delay_on_connect = delay_on_connect_in_ms; From ad40065dc8bd5a5e16b13523d9fef6ac94cf2b66 Mon Sep 17 00:00:00 2001 From: Hugo Sales Date: Sat, 31 Oct 2026 14:33:51 +0000 Subject: [PATCH 0855/2102] drm/amd/display: Hold the VRR vblank reference only on active CRTCs amdgpu_dm_handle_vrr_transition() takes a vblank reference when a CRTC state turns VRR on and drops it when a later state turns it off. It only looks at freesync_config.state, and disabling a CRTC keeps that state, so a suspend or DPMS off with VRR active keeps the reference On resume, drm_atomic_helper_resume() first calls drm_mode_config_reset(), which swaps the CRTC state for a zeroed one. The restored state then goes from VRR_STATE_UNSUPPORTED to active and takes a second reference, and the first is never dropped. The vblank irq stays on for good, so the CRTC never idles and PSR is never entered A VRR change on a disabled CRTC can't take the reference at all, since vblank is off there and drm_crtc_vblank_get() fails with a WARN On a Cezanne laptop with VRR always on, each suspend added one to the eDP CRTC's vblank refcount, and it stayed at 1 rather than 0 after VRR was turned off again Treat VRR as active for the reference only while the CRTC is active too. Disabling the CRTC then drops it and enabling it takes it again, which balances suspend, resume and DPMS, and the get only happens once manage_dm_interrupts() has turned vblank on Fixes: 66b0c973d7f7 ("drm/amd/display: Prevent vblank irq disable while VRR is active. (v3)") Reviewed-by: Ivan Lipski Signed-off-by: Hugo Sales Signed-off-by: Wayne Lin Signed-off-by: Alex Deucher (cherry picked from commit 4232ec2333ab3ef16520b399b30d50f17ceb9c63) Cc: stable@vger.kernel.org --- .../display/amdgpu_dm/amdgpu_dm_freesync.c | 12 ++- .../amdgpu_dm/tests/amdgpu_dm_freesync_test.c | 98 +++++++++++++++++++ 2 files changed, 108 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c index 0be4506e9ae5b3..2255ee5f8341d7 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c @@ -400,8 +400,16 @@ void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm, struct dm_crtc_state *new_state) { struct amdgpu_device *adev = dm->adev; - bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state); - bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state); + /* + * A disabled CRTC keeps its freesync state, but drm_crtc_vblank_get() + * fails there because vblank is off. Hold the reference only while + * the CRTC is active as well, which also covers resume, where the + * reset state lost track of the reference taken before suspend + */ + bool old_vrr_active = old_state->base.active && + amdgpu_dm_crtc_vrr_active(old_state); + bool new_vrr_active = new_state->base.active && + amdgpu_dm_crtc_vrr_active(new_state); /* Only DCE gates vupdate on VRR, keep it enabled for DCN */ bool vrr_gates_vupdate = amdgpu_ip_version(adev, DCE_HWIP, 0) == 0; diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c index 5ad50bc3161375..658b2630923d12 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c @@ -813,8 +813,10 @@ static void dm_test_handle_vrr_transition_round_trip(struct kunit *test) mutex_init(&adev->dm.dc_lock); old_state.base.crtc = &acrtc->base; + old_state.base.active = true; old_state.stream = stream; new_state.base.crtc = &acrtc->base; + new_state.base.active = true; new_state.stream = stream; new_state.freesync_config.state = VRR_STATE_ACTIVE_VARIABLE; @@ -825,6 +827,99 @@ static void dm_test_handle_vrr_transition_round_trip(struct kunit *test) KUNIT_EXPECT_EQ(test, atomic_read(&vblank->refcount), 0); } +/* + * Runs a transition on a CRTC whose vblank is on with two references held, + * so a get or put never has to enable or disable it, and returns the + * refcount afterwards + */ +static int dm_test_vrr_transition_refcount(struct kunit *test, + bool old_active, enum mod_vrr_state old_vrr, + bool new_active, enum mod_vrr_state new_vrr) +{ + struct amdgpu_device *adev = dm_kunit_alloc_adev(test); + struct amdgpu_display_manager *dm = dm_kunit_alloc_dm(test); + struct dm_crtc_state *old_state, *new_state; + struct drm_crtc *crtc; + int refcount; + + KUNIT_ASSERT_EQ(test, drm_vblank_init(&adev->ddev, 1), 0); + adev->ip_versions[DCE_HWIP][0] = IP_VERSION(2, 1, 0); + dm->adev = adev; + mutex_init(&dm->dc_lock); + + crtc = kunit_kzalloc(test, sizeof(*crtc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, crtc); + crtc->dev = &adev->ddev; + + old_state = kunit_kzalloc(test, sizeof(*old_state), GFP_KERNEL); + new_state = kunit_kzalloc(test, sizeof(*new_state), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, old_state); + KUNIT_ASSERT_NOT_NULL(test, new_state); + old_state->base.crtc = crtc; + old_state->base.active = old_active; + old_state->freesync_config.state = old_vrr; + new_state->base.crtc = crtc; + new_state->base.active = new_active; + new_state->freesync_config.state = new_vrr; + + adev->ddev.vblank[0].enabled = true; + atomic_set(&adev->ddev.vblank[0].refcount, 2); + + amdgpu_dm_handle_vrr_transition(dm, old_state, new_state); + refcount = atomic_read(&adev->ddev.vblank[0].refcount); + + /* drm_vblank_init_release() warns if vblank is still enabled */ + adev->ddev.vblank[0].enabled = false; + atomic_set(&adev->ddev.vblank[0].refcount, 0); + + return refcount; +} + +/** + * dm_test_vrr_transition_crtc_off_drops_ref - Test disabling the CRTC drops the ref + * @test: The KUnit test context + * + * Disabling the CRTC keeps the freesync state, as on suspend or DPMS off. + * The reference must still be dropped, since resume restores the state from + * a reset one and takes a new reference + */ +static void dm_test_vrr_transition_crtc_off_drops_ref(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, + dm_test_vrr_transition_refcount(test, true, VRR_STATE_ACTIVE_VARIABLE, + false, VRR_STATE_ACTIVE_VARIABLE), + 1); +} + +/** + * dm_test_vrr_transition_crtc_on_takes_ref - Test enabling the CRTC takes the ref + * @test: The KUnit test context + * + * Covers resume, where the old state is a reset one, and DPMS on + */ +static void dm_test_vrr_transition_crtc_on_takes_ref(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, + dm_test_vrr_transition_refcount(test, false, VRR_STATE_UNSUPPORTED, + true, VRR_STATE_ACTIVE_VARIABLE), + 3); +} + +/** + * dm_test_vrr_transition_crtc_off_keeps_ref - Test no ref change while off + * @test: The KUnit test context + * + * A disabled CRTC has vblank off, so a VRR change there must neither take + * nor drop a reference + */ +static void dm_test_vrr_transition_crtc_off_keeps_ref(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, + dm_test_vrr_transition_refcount(test, false, VRR_STATE_UNSUPPORTED, + false, VRR_STATE_ACTIVE_VARIABLE), + 2); +} + static struct kunit_case amdgpu_dm_freesync_tests[] = { /* amdgpu_dm_is_timing_unchanged_for_freesync */ KUNIT_CASE(dm_test_timing_unchanged_null_args), @@ -867,6 +962,9 @@ static struct kunit_case amdgpu_dm_freesync_tests[] = { /* amdgpu_dm_handle_vrr_transition */ KUNIT_CASE(dm_test_handle_vrr_transition_inactive), KUNIT_CASE(dm_test_handle_vrr_transition_round_trip), + KUNIT_CASE(dm_test_vrr_transition_crtc_off_drops_ref), + KUNIT_CASE(dm_test_vrr_transition_crtc_on_takes_ref), + KUNIT_CASE(dm_test_vrr_transition_crtc_off_keeps_ref), {} }; From 76850a457474a629dc0ceffaafb3aed78ff5f469 Mon Sep 17 00:00:00 2001 From: Cooper Morgan Date: Fri, 30 Oct 2026 21:18:25 -0700 Subject: [PATCH 0856/2102] drm/amd/display: Saturate refresh rates in v1/v2 FreeSync infopackets The v1 and v2 FreeSync infopackets carry the minimum and maximum refresh rate in one byte each, and build_vrr_infopacket_data_v1() casts the rate in Hz to unsigned char. On a sink whose range goes above 255 Hz the value wraps: a 320 Hz mode is advertised as a 64 Hz maximum. Sinks that treat the field as authoritative misbehave once the wrapped value lands inside their range. An MSI MAG 271QPX32 (48-320 Hz) over native DP looks like a ~720p image upscaled to the full screen at 320 Hz and runs its self-test pattern at 305-315 Hz, while 300 Hz (wrapping to 44 Hz, below its minimum) is fine. Capping the EDID range at 255 Hz, so the packet says 255, gives a correct picture at 320 Hz. Saturate the fields at 255 Hz instead of wrapping. Capping v1 at 255 as a fallback was suggested by oystersuki in the linked issue. Fixes: 98e6436d3af5 ("drm/amd/display: Refactor FreeSync module") Closes: https://gitlab.freedesktop.org/drm/amd/-/issues/5988 Reviewed-by: Harry Wentland Signed-off-by: Cooper Morgan Signed-off-by: Wayne Lin Signed-off-by: Alex Deucher (cherry picked from commit 8f91c13d9a14085216725f60b55546fce5c2dd19) Cc: stable@vger.kernel.org --- .../amdgpu_dm/tests/amdgpu_dm_freesync_test.c | 57 +++++++++++++++++++ .../amd/display/modules/freesync/freesync.c | 12 +++- 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c index 658b2630923d12..bbd2b74f8eaae1 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c @@ -622,6 +622,62 @@ static void dm_test_update_freesync_state_pcon_default(struct kunit *test) dm_test_update_freesync_state_pcon_version(test, 0); } +/* + * Build the VRR infopacket for a non-PCON, non-Replay sink with VRR inactive + * over 48Hz to @mode_hz, the max that mod_freesync_build_vrr_params() clamps + * to the mode's rate. + */ +static struct dc_info_packet +dm_test_freesync_packet(struct kunit *test, enum signal_type signal, + u8 vsdb_version, int sink_max_hz, int mode_hz) +{ + struct amdgpu_device *adev = dm_kunit_alloc_adev(test); + struct dc_link *link = dm_kunit_alloc_link(test); + struct dc_stream_state *stream = dm_kunit_alloc_stream(test, link); + struct amdgpu_dm_connector *aconnector; + struct mod_vrr_params *vrr; + struct amdgpu_crtc *acrtc; + struct dm_crtc_state crtc_state = { 0 }; + + acrtc = kunit_kzalloc(test, sizeof(*acrtc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, acrtc); + aconnector = kunit_kzalloc(test, sizeof(*aconnector), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, aconnector); + crtc_state.base.crtc = &acrtc->base; + stream->timing.h_total = 2200; + stream->timing.v_total = 1125; + stream->signal = signal; + stream->dm_stream_context = aconnector; + aconnector->vsdb_info.amd_vsdb_version = vsdb_version; + aconnector->max_vfreq = sink_max_hz; + vrr = &acrtc->dm_irq_params.vrr_params; + vrr->send_info_frame = true; + vrr->state = VRR_STATE_INACTIVE; + vrr->min_refresh_in_uhz = 48000000; + vrr->max_refresh_in_uhz = mode_hz * 1000000; + adev->dm.adev = adev; + + amdgpu_dm_update_freesync_state_on_stream(&adev->dm, &crtc_state, stream, NULL, 0); + + return crtc_state.vrr_infopacket; +} + +/** + * dm_test_update_freesync_state_dp_v2_saturates - Test v1 saturates above 255Hz + * @test: The KUnit test context + * + * A VSDB v2 sink keeps the v1 packet, which cannot carry 320Hz. + */ +static void dm_test_update_freesync_state_dp_v2_saturates(struct kunit *test) +{ + struct dc_info_packet p = + dm_test_freesync_packet(test, SIGNAL_TYPE_DISPLAY_PORT, 2, 320, 320); + + KUNIT_EXPECT_EQ(test, p.hb3, 0x04); + KUNIT_EXPECT_EQ(test, p.sb[7], 255); + KUNIT_EXPECT_EQ(test, p.sb[8], 255); +} + /* Tests for amdgpu_dm_update_stream_irq_parameters() */ /** @@ -952,6 +1008,7 @@ static struct kunit_case amdgpu_dm_freesync_tests[] = { KUNIT_CASE(dm_test_update_freesync_state_pcon_v2), KUNIT_CASE(dm_test_update_freesync_state_pcon_v3), KUNIT_CASE(dm_test_update_freesync_state_pcon_default), + KUNIT_CASE(dm_test_update_freesync_state_dp_v2_saturates), /* amdgpu_dm_update_stream_irq_parameters */ KUNIT_CASE(dm_test_update_stream_irq_parameters_no_stream), KUNIT_CASE(dm_test_update_stream_irq_parameters_invalid_timing), diff --git a/drivers/gpu/drm/amd/display/modules/freesync/freesync.c b/drivers/gpu/drm/amd/display/modules/freesync/freesync.c index f154a619b53390..21165855cb9276 100644 --- a/drivers/gpu/drm/amd/display/modules/freesync/freesync.c +++ b/drivers/gpu/drm/amd/display/modules/freesync/freesync.c @@ -571,6 +571,12 @@ static bool vrr_settings_require_update(struct core_freesync *core_freesync, return false; } +/* v1/v2 packets hold each rate in one byte; saturate instead of wrapping. */ +static unsigned char vrr_refresh_hz_u8(unsigned int refresh_in_uhz) +{ + return min((refresh_in_uhz + 500000) / 1000000, 255U); +} + static void build_vrr_infopacket_data_v1(const struct mod_vrr_params *vrr, struct dc_info_packet *infopacket, bool freesync_on_desktop) @@ -614,15 +620,15 @@ static void build_vrr_infopacket_data_v1(const struct mod_vrr_params *vrr, /* PB7 = FreeSync Minimum refresh rate (Hz) */ if (vrr->state == VRR_STATE_ACTIVE_VARIABLE || vrr->state == VRR_STATE_ACTIVE_FIXED) { - infopacket->sb[7] = (unsigned char)((vrr->min_refresh_in_uhz + 500000) / 1000000); + infopacket->sb[7] = vrr_refresh_hz_u8(vrr->min_refresh_in_uhz); } else { - infopacket->sb[7] = (unsigned char)((vrr->max_refresh_in_uhz + 500000) / 1000000); + infopacket->sb[7] = vrr_refresh_hz_u8(vrr->max_refresh_in_uhz); } /* PB8 = FreeSync Maximum refresh rate (Hz) * Note: We should never go above the field rate of the mode timing set. */ - infopacket->sb[8] = (unsigned char)((vrr->max_refresh_in_uhz + 500000) / 1000000); + infopacket->sb[8] = vrr_refresh_hz_u8(vrr->max_refresh_in_uhz); } static void build_vrr_infopacket_data_v3(const struct mod_vrr_params *vrr, From 6a9d5e2f06cd6f5c6aa0acb223a1c0a9dbadfce6 Mon Sep 17 00:00:00 2001 From: Cooper Morgan Date: Fri, 30 Oct 2026 21:18:26 -0700 Subject: [PATCH 0857/2102] drm/amd/display: Use FreeSync v3 infopacket for sinks above 255 Hz Native DP, eDP, and HDMI sinks get the v1 FreeSync infopacket unless they are a whitelisted PCON or support Replay. v1 holds each refresh rate in one byte, so a sink whose range goes above 255 Hz cannot be told its real maximum. The v3 packet carries the high bits in PB11/PB12. The AMD VSDB version is already stored for every DP, eDP, and HDMI sink. Send v3 when the sink advertises AMD VSDB v3 and its maximum refresh rate is above 255 Hz. The choice follows the sink's maximum rather than the current mode, so such a sink gets v3 at every mode and the packet version stays fixed per sink. Sinks whose maximum is 255 Hz or less are unchanged. Tested with this series backported to v7.2.13 on an MSI MAG 271QPX32 (AMD VSDB v3, 48-320 Hz) over DP 1.4 on an RX 9070 XT: 320 Hz shows a correct picture, and with VRR active the refresh rate tracks frame caps of 300, 270, and 100 Hz. At 240 Hz, where the sink now gets v3 instead of v1, the picture is correct and VRR tracks a 100 Hz cap. Link: https://gitlab.freedesktop.org/drm/amd/-/issues/5988 Reviewed-by: Harry Wentland Signed-off-by: Cooper Morgan Signed-off-by: Wayne Lin Signed-off-by: Alex Deucher (cherry picked from commit e1c2682397f2f8f40eada17c817b5d3b300124b6) Cc: stable@vger.kernel.org --- .../display/amdgpu_dm/amdgpu_dm_freesync.c | 7 +++ .../amdgpu_dm/tests/amdgpu_dm_freesync_test.c | 59 +++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c index 2255ee5f8341d7..f2539bcf824fc6 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c @@ -251,6 +251,13 @@ void amdgpu_dm_update_freesync_state_on_stream( mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL, &new_stream->adaptive_sync_infopacket); + } else if (aconn && aconn->vsdb_info.amd_vsdb_version == 3 && + aconn->max_vfreq > 255) { + /* + * v1 saturates at 255 Hz. Keyed on the sink's max, not the mode's + * rate, so the packet version stays fixed per sink. + */ + packet_type = PACKET_TYPE_FS_V3; } app_tf = dm_dp_in_hdr_mode(new_stream) ? diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c index bbd2b74f8eaae1..8f219f08cd55b6 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c @@ -678,6 +678,61 @@ static void dm_test_update_freesync_state_dp_v2_saturates(struct kunit *test) KUNIT_EXPECT_EQ(test, p.sb[8], 255); } +/** + * dm_test_update_freesync_state_dp_v3_above_255 - Test v3 for a VSDB v3 sink above 255Hz + * @test: The KUnit test context + */ +static void dm_test_update_freesync_state_dp_v3_above_255(struct kunit *test) +{ + struct dc_info_packet p = + dm_test_freesync_packet(test, SIGNAL_TYPE_DISPLAY_PORT, 3, 320, 320); + + KUNIT_EXPECT_EQ(test, p.hb3, 3 << 2); + KUNIT_EXPECT_EQ(test, p.sb[8], 320 & 0xff); + KUNIT_EXPECT_EQ(test, p.sb[12], 320 >> 8); +} + +/** + * dm_test_update_freesync_state_dp_v3_mode_240 - Test v3 follows the sink max, not the mode + * @test: The KUnit test context + */ +static void dm_test_update_freesync_state_dp_v3_mode_240(struct kunit *test) +{ + struct dc_info_packet p = + dm_test_freesync_packet(test, SIGNAL_TYPE_DISPLAY_PORT, 3, 320, 240); + + KUNIT_EXPECT_EQ(test, p.hb3, 3 << 2); + KUNIT_EXPECT_EQ(test, p.sb[8], 240); + KUNIT_EXPECT_EQ(test, p.sb[12], 0); +} + +/** + * dm_test_update_freesync_state_dp_v3_at_255 - Test a VSDB v3 sink at 255Hz keeps v1 + * @test: The KUnit test context + */ +static void dm_test_update_freesync_state_dp_v3_at_255(struct kunit *test) +{ + struct dc_info_packet p = + dm_test_freesync_packet(test, SIGNAL_TYPE_DISPLAY_PORT, 3, 255, 255); + + KUNIT_EXPECT_EQ(test, p.hb3, 0x04); + KUNIT_EXPECT_EQ(test, p.sb[8], 255); +} + +/** + * dm_test_update_freesync_state_hdmi_v3_above_255 - Test v3 for a VSDB v3 HDMI sink + * @test: The KUnit test context + */ +static void dm_test_update_freesync_state_hdmi_v3_above_255(struct kunit *test) +{ + struct dc_info_packet p = + dm_test_freesync_packet(test, SIGNAL_TYPE_HDMI_TYPE_A, 3, 320, 320); + + KUNIT_EXPECT_EQ(test, p.hb1, 3); + KUNIT_EXPECT_EQ(test, p.sb[8], 320 & 0xff); + KUNIT_EXPECT_EQ(test, p.sb[12], 320 >> 8); +} + /* Tests for amdgpu_dm_update_stream_irq_parameters() */ /** @@ -1009,6 +1064,10 @@ static struct kunit_case amdgpu_dm_freesync_tests[] = { KUNIT_CASE(dm_test_update_freesync_state_pcon_v3), KUNIT_CASE(dm_test_update_freesync_state_pcon_default), KUNIT_CASE(dm_test_update_freesync_state_dp_v2_saturates), + KUNIT_CASE(dm_test_update_freesync_state_dp_v3_above_255), + KUNIT_CASE(dm_test_update_freesync_state_dp_v3_mode_240), + KUNIT_CASE(dm_test_update_freesync_state_dp_v3_at_255), + KUNIT_CASE(dm_test_update_freesync_state_hdmi_v3_above_255), /* amdgpu_dm_update_stream_irq_parameters */ KUNIT_CASE(dm_test_update_stream_irq_parameters_no_stream), KUNIT_CASE(dm_test_update_stream_irq_parameters_invalid_timing), From 57decaa0e378bf2481eae5f49293a5202976a19e Mon Sep 17 00:00:00 2001 From: Egor Perevoshchikov Date: Sat, 31 Oct 2026 07:00:50 +0300 Subject: [PATCH 0858/2102] drm/amd/display: Restore PSR-SU guard in power module Commit a5ce8695d6d1 ("drm/amd/display: Avoid configuring PSR granularity if PSR-SU not supported") restricted DSC slice-height configuration to PSR-SU. The power-module integration removed that guarded caller. Its replacement in mod_power_psr_notify_mode_change() calls psr_su_set_dsc_slice_height() unconditionally and ignores its return value. On PSR1 links with a DSC slice configuration, this applies a PSR-SU-only alignment check even though selective update is not enabled. If the calculated DSC slice height is not a multiple of the nonzero advertised SU Y granularity, the helper triggers an assertion. It also sets dsc_slice_height before failing the check, so the caller passes this SU-specific value into PSR1 setup despite the failure. Restore the PSR version guard and failure handling in the new caller. PSR1 proceeds with the zero-initialized DSC slice height, while PSR-SU retains its alignment validation and stops setup if that validation fails. Fixes: 3c108046e1d6 ("drm/amd/display: Add power module on Linux") Closes: https://gitlab.freedesktop.org/drm/amd/-/work_items/3027 Reviewed-by: Ray Wu Signed-off-by: Egor Perevoshchikov Signed-off-by: Wayne Lin Signed-off-by: Alex Deucher (cherry picked from commit 83558fcf83cc911e09962ea17c883add596766c0) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/display/modules/power/power_psr.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/display/modules/power/power_psr.c b/drivers/gpu/drm/amd/display/modules/power/power_psr.c index 96bb77fff05b86..7139395b5c0066 100644 --- a/drivers/gpu/drm/amd/display/modules/power/power_psr.c +++ b/drivers/gpu/drm/amd/display/modules/power/power_psr.c @@ -94,9 +94,12 @@ bool mod_power_psr_notify_mode_change(struct mod_power *mod_power, * The value of DSC slice height is determined in DSC Driver but it does not * propagated out here, so we need to calculate it as below 'slice_height'. */ - psr_su_set_dsc_slice_height(dc, link, - (struct dc_stream_state *) stream, - &psr_config); + if (link->psr_settings.psr_version == DC_PSR_VERSION_SU_1) { + if (!psr_su_set_dsc_slice_height(dc, link, + (struct dc_stream_state *)stream, + &psr_config)) + return false; + } dc_link_setup_psr(link, stream, &psr_config, &psr_context); From a23e1f240f4309013e8e7d877944748f24a64a73 Mon Sep 17 00:00:00 2001 From: Tomeu Vizoso Date: Wed, 18 Nov 2026 11:18:58 +0100 Subject: [PATCH 0859/2102] accel/rocket: Fix up sched array handling on open and close Don't WARN when drm_sched_entity_init() fails in rocket_job_open(). It can return -ENOMEM, which is an allocation failure and not a driver bug, so it doesn't deserve a stack trace. Also free the scheduler array in rocket_job_close() only after the entity has been destroyed, so that entity->sched_list never points to freed memory. Fixes: d341ef030f3c ("accel/rocket: Check allocations before use") Fixes: 9bca2b5f1a4f ("accel/rocket: Keep scheduler allocation in rocket_file_priv") Suggested-by: Sidong Yang Link: https://lore.kernel.org/all/20260826113538.42111-1-sidong.yang@furiosa.ai/ Link: https://lore.kernel.org/all/20260826113538.42111-2-sidong.yang@furiosa.ai/ Reviewed-by: Heiko Stuebner Link: https://patch.msgid.link/20261118101901.253550-1-tomeu@tomeuvizoso.net Signed-off-by: Tomeu Vizoso --- drivers/accel/rocket/rocket_job.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/accel/rocket/rocket_job.c b/drivers/accel/rocket/rocket_job.c index 7b798a90bc492e..454d465a39e371 100644 --- a/drivers/accel/rocket/rocket_job.c +++ b/drivers/accel/rocket/rocket_job.c @@ -572,7 +572,7 @@ int rocket_job_open(struct rocket_file_priv *rocket_priv) DRM_SCHED_PRIORITY_NORMAL, scheds, rdev->num_cores, NULL); - if (WARN_ON(ret)) + if (ret) kfree(scheds); else rocket_priv->scheds = scheds; @@ -584,8 +584,8 @@ void rocket_job_close(struct rocket_file_priv *rocket_priv) { struct drm_sched_entity *entity = &rocket_priv->sched_entity; - kfree(rocket_priv->scheds); drm_sched_entity_destroy(entity); + kfree(rocket_priv->scheds); } int rocket_job_is_idle(struct rocket_core *core) From d1d36ae6751f851d2db8dbd0a9ef472404cb0529 Mon Sep 17 00:00:00 2001 From: HyeongJun An Date: Wed, 18 Nov 2026 10:28:30 +0900 Subject: [PATCH 0860/2102] MAINTAINERS: Add myself as a reviewer for the virtual PCM test driver I added the control fault injection to pcmtest and several checks to its selftest. Add myself as a reviewer so that I see changes to the driver and the test. Signed-off-by: HyeongJun An Link: https://patch.msgid.link/20261118012830.3117724-1-sammiee5311@gmail.com Signed-off-by: Takashi Iwai --- MAINTAINERS | 1 + 1 file changed, 1 insertion(+) diff --git a/MAINTAINERS b/MAINTAINERS index 222b7fc2c3aab8..e35521327ffc0e 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -29856,6 +29856,7 @@ F: fs/vboxsf/* VIRTUAL PCM TEST DRIVER M: Ivan Orlov +R: HyeongJun An L: linux-sound@vger.kernel.org S: Maintained F: Documentation/sound/cards/pcmtest.rst From 66ffe55a5d3b7d47f372b3c31fa3d9c3f080c6fb Mon Sep 17 00:00:00 2001 From: Zhang Heng Date: Wed, 18 Nov 2026 09:55:49 +0800 Subject: [PATCH 0861/2102] ALSA: hda/realtek: Add quirk for THUNDEROBOT Gravity16G2Pro After S3 resume the ALC256 on this model has COEF 0x10 bit 9 set (0x0220 instead of 0x0020) and the internal speaker stays silent. Reuse ALC256_FIXUP_XIAOMI_PRO15_RESUME, which clears that bit on every init, including resume. Closes: https://bugzilla.kernel.org/show_bug.cgi?id=222028 Signed-off-by: Zhang Heng Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261118015552.201306-2-zhangheng@kylinos.cn --- sound/hda/codecs/realtek/alc269.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 2c541c68ff5b6b..77f1a9bce756b6 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -8361,6 +8361,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1462, 0xb171, "Cubi N 8GL (MS-B171)", ALC283_FIXUP_HEADSET_MIC), SND_PCI_QUIRK(0x152d, 0x1082, "Quanta NL3", ALC269_FIXUP_LIFEBOOK), SND_PCI_QUIRK(0x152d, 0x1262, "Huawei NBLB-WAX9N", ALC2XX_FIXUP_HEADSET_MIC), + SND_PCI_QUIRK(0x152d, 0x1577, "THUNDEROBOT Gravity16G2Pro", ALC256_FIXUP_XIAOMI_PRO15_RESUME), SND_PCI_QUIRK(0x1558, 0x0353, "Clevo V35[05]SN[CDE]Q", ALC256_FIXUP_SYSTEM76_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1558, 0x1323, "Clevo N130ZU", ALC293_FIXUP_SYSTEM76_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1558, 0x1325, "Clevo N15[01][CW]U", ALC293_FIXUP_SYSTEM76_MIC_NO_PRESENCE), From 26868f2e598b01d728473f1dbf4695627b8d02f5 Mon Sep 17 00:00:00 2001 From: Zhang Heng Date: Wed, 18 Nov 2026 09:55:50 +0800 Subject: [PATCH 0862/2102] ALSA: hda/realtek: Add quirk for HP Pavilion 15-cw1xxx HP Pavilion 15-cw1034la (ALC295, SSID 103c:8615) has silent internal speakers with the generic fixup. Add ALC295_FIXUP_HP_CW1XXX to set COEF 0x0d=0xa023 and chain to ALC295_FIXUP_HP_X360. Reported-by: jmoises Closes: https://bugzilla.kernel.org/show_bug.cgi?id=221534 Signed-off-by: Zhang Heng Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261118015552.201306-3-zhangheng@kylinos.cn --- sound/hda/codecs/realtek/alc269.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 77f1a9bce756b6..53d621983b5264 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -4334,6 +4334,7 @@ enum { ALC298_FIXUP_HUAWEI_MBX_STEREO, ALC295_FIXUP_HP_X360, ALC295_FIXUP_HP_PAVILION_X360, + ALC295_FIXUP_HP_CW1XXX, ALC221_FIXUP_HP_HEADSET_MIC, ALC285_FIXUP_LENOVO_HEADPHONE_NOISE, ALC295_FIXUP_HP_AUTO_MUTE, @@ -5834,6 +5835,16 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC295_FIXUP_HP_X360 }, + [ALC295_FIXUP_HP_CW1XXX] = { + .type = HDA_FIXUP_VERBS, + .v.verbs = (const struct hda_verb[]) { + { 0x20, AC_VERB_SET_COEF_INDEX, 0x0d }, + { 0x20, AC_VERB_SET_PROC_COEF, 0xa023 }, + {} + }, + .chained = true, + .chain_id = ALC295_FIXUP_HP_X360 + }, [ALC221_FIXUP_HP_HEADSET_MIC] = { .type = HDA_FIXUP_PINS, .v.pins = (const struct hda_pintbl[]) { @@ -7747,6 +7758,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8603, "HP Omen 17-cb0xxx", ALC285_FIXUP_HP_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x860c, "HP ZBook 17 G6", ALC285_FIXUP_HP_GPIO_AMP_INIT), SND_PCI_QUIRK(0x103c, 0x860f, "HP ZBook 15 G6", ALC285_FIXUP_HP_GPIO_AMP_INIT), + SND_PCI_QUIRK(0x103c, 0x8615, "HP Pavilion 15-cw1xxx", ALC295_FIXUP_HP_CW1XXX), SND_PCI_QUIRK(0x103c, 0x861f, "HP Elite Dragonfly G1", ALC285_FIXUP_HP_GPIO_AMP_INIT), SND_PCI_QUIRK(0x103c, 0x864f, "HP Laptop 15-dy0xxx", ALC236_FIXUP_HP_MUTE_LED_COEFBIT2), SND_PCI_QUIRK(0x103c, 0x869d, "HP", ALC236_FIXUP_HP_MUTE_LED), From 8837de32d316e17f9e78df642457614eeb600956 Mon Sep 17 00:00:00 2001 From: Zhang Heng Date: Wed, 18 Nov 2026 09:55:51 +0800 Subject: [PATCH 0863/2102] ALSA: hda/realtek: Add quirk for Lenovo Yoga Pro 7 14ASP9 Lenovo Yoga Pro 7 14ASP9 (ALC287, codec SSID 17aa:3903) has a silent bass speaker. Its PCI SSID 17aa:38a7 is shared with Y780P AMD YG dual, so it matches ALC287_FIXUP_TAS2781_I2C instead of the bass-speaker fixup. Match on codec SSID to apply ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN. Reported-by: Brett Closes: https://bugzilla.kernel.org/show_bug.cgi?id=222007 Signed-off-by: Zhang Heng Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261118015552.201306-4-zhangheng@kylinos.cn --- sound/hda/codecs/realtek/alc269.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 53d621983b5264..94434adf330e55 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -8605,6 +8605,8 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x17aa, 0x3886, "Y780 VECO DUAL", ALC287_FIXUP_TAS2781_I2C), SND_PCI_QUIRK(0x17aa, 0x3891, "Lenovo Yoga Pro 7 14AHP9", ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN), SND_PCI_QUIRK(0x17aa, 0x38a5, "Y580P AMD dual", ALC287_FIXUP_TAS2781_I2C), + /* Yoga Pro 7 14ASP9 shares PCI SSID 17aa:38a7 with Y780P; match on codec SSID */ + HDA_CODEC_QUIRK(0x17aa, 0x3903, "Lenovo Yoga Pro 7 14ASP9", ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN), SND_PCI_QUIRK(0x17aa, 0x38a7, "Y780P AMD YG dual", ALC287_FIXUP_TAS2781_I2C), SND_PCI_QUIRK(0x17aa, 0x38a8, "Y780P AMD VECO dual", ALC287_FIXUP_TAS2781_I2C), SND_PCI_QUIRK(0x17aa, 0x38a9, "Thinkbook 16P", ALC287_FIXUP_MG_RTKC_CSAMP_CS35L41_I2C_THINKPAD), From 1777f64fe0b20b7d478a7e4ccf6ceb6ca7547f6f Mon Sep 17 00:00:00 2001 From: Zhang Heng Date: Wed, 18 Nov 2026 09:55:52 +0800 Subject: [PATCH 0864/2102] ALSA: hda/realtek: Enable mute LEDs on HP Laptop 15-fd1xxx The HP Laptop 15-fd1xxx (ALC236, subsystem 103c:8cac) has no working mute or mic-mute LED. Both are driven by the existing ALC236_FIXUP_HP_MUTE_LED_MICMUTE_GPIO quirk (COEF 0x07 bit 0 and GPIO0, active low), as confirmed by hda-verb tests. Add the SSID entry. Link: https://bugzilla.kernel.org/show_bug.cgi?id=195827 Signed-off-by: Zhang Heng Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261118015552.201306-5-zhangheng@kylinos.cn --- sound/hda/codecs/realtek/alc269.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 94434adf330e55..0d76f9c0c10059 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -8027,6 +8027,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8ca2, "HP ZBook Power", ALC236_FIXUP_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8ca4, "HP ZBook Fury", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8ca7, "HP ZBook Fury", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), + SND_PCI_QUIRK(0x103c, 0x8cac, "HP Laptop 15-fd1xxx", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_GPIO), SND_PCI_QUIRK(0x103c, 0x8caf, "HP Elite mt645 G8 Mobile Thin Client", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_VREF), SND_PCI_QUIRK(0x103c, 0x8cbc, "HP Pavilion Laptop 16-ag0xxx", ALC245_FIXUP_HP_X360_MUTE_LEDS), SND_PCI_QUIRK(0x103c, 0x8cbd, "HP Pavilion Aero Laptop 13-bg0xxx", ALC245_FIXUP_HP_X360_MUTE_LEDS), From 83fb5e67c75cd27ca673121b02bf7491849bbbf4 Mon Sep 17 00:00:00 2001 From: Dustin Tacy Date: Tue, 17 Nov 2026 21:02:54 -0600 Subject: [PATCH 0865/2102] ALSA: hda/realtek: Add mute LED quirk for HP OMEN 15t-ek000 HP OMEN 15t-ek000 with PCI subsystem ID 103c:878a uses an ALC245 codec. The mute LED requires a quirk to work. Enabling ALC245_FIXUP_HP_MUTE_LED_COEFBIT on this SSID. Verified on my HP Omen 15t-ek000. Signed-off-by: Dustin Tacy Link: https://patch.msgid.link/20261118030254.29314-1-tacydustin@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 0d76f9c0c10059..e4b6304d3feb1f 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -7791,6 +7791,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8786, "HP OMEN 15", ALC285_FIXUP_HP_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x8787, "HP OMEN 15", ALC285_FIXUP_HP_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x8788, "HP OMEN 15", ALC285_FIXUP_HP_MUTE_LED), + SND_PCI_QUIRK(0x103c, 0x878a, "HP OMEN 15t-ek000", ALC245_FIXUP_HP_MUTE_LED_COEFBIT), SND_PCI_QUIRK(0x103c, 0x87b2, "HP Pavilion Gaming Laptop 15-ec1xxx", ALC285_FIXUP_HP_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x87b7, "HP Laptop 14-fq0xxx", ALC236_FIXUP_HP_MUTE_LED_COEFBIT2), SND_PCI_QUIRK(0x103c, 0x87c8, "HP", ALC287_FIXUP_HP_GPIO_LED), From c7096486dc64d5226177f1f4f648ab2c0fa82d74 Mon Sep 17 00:00:00 2001 From: Zhang Heng Date: Wed, 18 Nov 2026 11:39:01 +0800 Subject: [PATCH 0866/2102] ALSA: hda/realtek: Fix quiet speakers on HP 250 G6 The HP 250 G6 (ALC3227, subsystem 103c:832e) has much quieter internal speakers than on Windows. The Windows driver writes coef 0x6d = 0x0900 and four EQ coefficients framed by 0x22 writes, while Linux leaves the high nibble of 0x6d at its hardware default (0xe900) and never writes the EQ coefficients. Add a fixup to apply the same coefficients on init. Closes: https://bugzilla.kernel.org/show_bug.cgi?id=222283 Tested-by: Shredrum Signed-off-by: Zhang Heng Link: https://patch.msgid.link/20261118033901.322505-1-zhangheng@kylinos.cn Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index e4b6304d3feb1f..1fac17b623046b 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -2688,6 +2688,23 @@ static void asus_tx300_automute(struct hda_codec *codec) spec->gen.mute_bits |= (1ULL << 0x14); } +static void alc282_fixup_hp_250g6(struct hda_codec *codec, + const struct hda_fixup *fix, int action) +{ + if (action != HDA_FIXUP_ACT_INIT) + return; + + alc_write_coef_idx(codec, 0x6d, 0x0900); + + /* filter block: disable, load coefficients, re-enable */ + alc_write_coef_idx(codec, 0x22, 0x400a); + alc_write_coef_idx(codec, 0x24, 0x1ec4); + alc_write_coef_idx(codec, 0x39, 0x1ea9); + alc_write_coef_idx(codec, 0x44, 0x1f61); + alc_write_coef_idx(codec, 0x4f, 0x1fb0); + alc_write_coef_idx(codec, 0x22, 0xe04a); +} + static void alc282_fixup_asus_tx300(struct hda_codec *codec, const struct hda_fixup *fix, int action) { @@ -4232,6 +4249,7 @@ enum { ALC269VB_FIXUP_ORDISSIMO_EVE2, ALC283_FIXUP_CHROME_BOOK, ALC283_FIXUP_SENSE_COMBO_JACK, + ALC282_FIXUP_HP_250G6_EQ, ALC282_FIXUP_ASUS_TX300, ALC283_FIXUP_INT_MIC, ALC290_FIXUP_MONO_SPEAKERS, @@ -5200,6 +5218,10 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC283_FIXUP_CHROME_BOOK, }, + [ALC282_FIXUP_HP_250G6_EQ] = { + .type = HDA_FIXUP_FUNC, + .v.func = alc282_fixup_hp_250g6, + }, [ALC282_FIXUP_ASUS_TX300] = { .type = HDA_FIXUP_FUNC, .v.func = alc282_fixup_asus_tx300, @@ -7734,6 +7756,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x827f, "HP x360", ALC269_FIXUP_HP_MUTE_LED_MIC3), SND_PCI_QUIRK(0x103c, 0x82bf, "HP G3 mini", ALC221_FIXUP_HP_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x103c, 0x82c0, "HP G3 mini premium", ALC221_FIXUP_HP_MIC_NO_PRESENCE), + SND_PCI_QUIRK(0x103c, 0x832e, "HP 250 G6", ALC282_FIXUP_HP_250G6_EQ), SND_PCI_QUIRK(0x103c, 0x83b9, "HP Spectre x360", ALC269_FIXUP_HP_MUTE_LED_MIC3), SND_PCI_QUIRK(0x103c, 0x841c, "HP Pavilion 15-CK0xx", ALC269_FIXUP_HP_MUTE_LED_MIC3), HDA_CODEC_QUIRK(0x103c, 0x8486, "HP Pavilion x360", ALC295_FIXUP_HP_PAVILION_X360), From 2aa774d278af74143e979ceaafe2f5dad9aba06f Mon Sep 17 00:00:00 2001 From: Stefan Binding Date: Wed, 18 Nov 2026 12:09:27 +0000 Subject: [PATCH 0867/2102] ALSA: hda: cs35l41: Correct Boost values for several laptops with overridden ACPI Four laptops have incorrect Peak Boost values: - 103C8CDD - 103C8CDE - 103C8E60 - 103C8F07 Update the values to the correct settings. Signed-off-by: Stefan Binding Link: https://patch.msgid.link/20261118120932.61495-1-sbinding@opensource.cirrus.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/side-codecs/cs35l41_hda_property.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sound/hda/codecs/side-codecs/cs35l41_hda_property.c b/sound/hda/codecs/side-codecs/cs35l41_hda_property.c index a2e6b302482075..5ab19b1351af7e 100644 --- a/sound/hda/codecs/side-codecs/cs35l41_hda_property.c +++ b/sound/hda/codecs/side-codecs/cs35l41_hda_property.c @@ -83,18 +83,18 @@ static const struct cs35l41_config cs35l41_config_table[] = { { "103C8C4F", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4100, 24 }, { "103C8C50", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4100, 24 }, { "103C8C51", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4100, 24 }, - { "103C8CDD", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4100, 24 }, - { "103C8CDE", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 3900, 24 }, + { "103C8CDD", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, + { "103C8CDE", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E11", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E12", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E13", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E3A", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E3B", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, - { "103C8E60", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, + { "103C8E60", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 3500, 24 }, { "103C8E61", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E62", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E75", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, - { "103C8F07", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 3900, 24 }, + { "103C8F07", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8F57", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "104312AF", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 1, 2, 0, 1000, 4500, 24 }, { "10431433", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4500, 24 }, From 0b4d69e8d2b53907ea8640bf7aa8543ae9e7a0c0 Mon Sep 17 00:00:00 2001 From: Takashi Iwai Date: Wed, 18 Nov 2026 13:50:23 +0100 Subject: [PATCH 0868/2102] ALSA: hda/realtek: Fix regression on Lenovo Legion 16IRX9H Lenovo Legion 16IRX9H has the very same PCI SSID (17aa:3842) as the recently added quirk for Lenovo Thinkpad X G2 IAH, but it needs a different qurik. Although the quirk for Legion 16IRX9H is present, it's not applied because the PCI SSID 17aa:3842 matches at first and the new quirk for Thinkpad X G2 is taken instead. As a workaround, put the codec SSID matching (17aa:38cd) for Legion before the conflicting PCI SSID quirk entry. Fixes: f2293e7b2ddd ("ALSA: hda/realtek: Enable all four speaker amps on Lenovo ThinkBook X G2 IAH") Cc: Closes: https://lore.kernel.org/CAFjFWEjt+DPJ_gM1uTBZ_NoV6-3mi57ArjZ_Qdah2DqY-GCD1w@mail.gmail.com Link: https://patch.msgid.link/20261118125024.1900126-1-tiwai@suse.de Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 1fac17b623046b..a43bfcf9705b54 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -8580,6 +8580,8 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x17aa, 0x3827, "Ideapad S740", ALC285_FIXUP_IDEAPAD_S740_COEF), SND_PCI_QUIRK(0x17aa, 0x3834, "Lenovo IdeaPad Slim 9i 14ITL5", ALC287_FIXUP_YOGA7_14ITL_SPEAKERS), SND_PCI_QUIRK(0x17aa, 0x383d, "Legion Y9000X 2019", ALC285_FIXUP_LEGION_Y9000X_SPEAKERS), + /* Legion 16IRX9H shares PCI SSID 17aa:3842 with Thinkpad X G2 below */ + HDA_CODEC_QUIRK(0x17aa, 0x38cd, "Lenovo Legion 16IRX9H", ALC287_FIXUP_TAS2781_I2C), SND_PCI_QUIRK(0x17aa, 0x3842, "ThinkBook X G2 IAH", ALC287_FIXUP_MG_RTKC_CSAMP_CS35L41_I2C_4_THINKPAD), /* IdeaPad Pro 5 14IAH10 shares PCI SSID 17aa:3843 with Yoga Book 9i; * use codec SSID to distinguish them From 9a92f776dfa6a88fc16fe0512c725734190bf9d0 Mon Sep 17 00:00:00 2001 From: Peter Zijlstra Date: Thu, 5 Nov 2026 17:55:26 +0100 Subject: [PATCH 0869/2102] sched/fair: Use guard in sched_group_set_idle() Cleanup the code by using guards; prepares for further changes in this function. Signed-off-by: Peter Zijlstra (Intel) Reviewed-by: Kayra Cizmeci Reviewed-by: Vincent Guittot Reviewed-by: Josh Don Link: https://patch.msgid.link/20261105170157.453569788@infradead.org --- kernel/sched/fair.c | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index 0c8af1cac2d5bb..95fd7560d97084 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -15803,12 +15803,9 @@ int sched_group_set_idle(struct task_group *tg, long idle) if (idle < 0 || idle > 1) return -EINVAL; - mutex_lock(&shares_mutex); - - if (tg->idle == idle) { - mutex_unlock(&shares_mutex); + guard(mutex)(&shares_mutex); + if (tg->idle == idle) return 0; - } tg->idle = idle; @@ -15818,13 +15815,12 @@ int sched_group_set_idle(struct task_group *tg, long idle) struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, i); bool was_idle = cfs_rq_is_idle(grp_cfs_rq); long idle_task_delta; - struct rq_flags rf; - rq_lock_irqsave(rq, &rf); + guard(rq_lock_irqsave)(rq); grp_cfs_rq->idle = idle; if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq))) - goto next_cpu; + continue; idle_task_delta = grp_cfs_rq->h_nr_queued - grp_cfs_rq->h_nr_idle; @@ -15843,9 +15839,6 @@ int sched_group_set_idle(struct task_group *tg, long idle) if (cfs_rq_is_idle(cfs_rq)) break; } - -next_cpu: - rq_unlock_irqrestore(rq, &rf); } /* Idle groups have minimum weight. */ @@ -15854,7 +15847,6 @@ int sched_group_set_idle(struct task_group *tg, long idle) else __sched_group_set_shares(tg, NICE_0_LOAD); - mutex_unlock(&shares_mutex); return 0; } From 75545668ae0fd80c08fe8fd0c6799b2ba9284557 Mon Sep 17 00:00:00 2001 From: Peter Zijlstra Date: Sat, 7 Nov 2026 12:36:39 +0100 Subject: [PATCH 0870/2102] sched/fair: Make cfs_rq::idle the sum of ancestor tg::idle Rather than keeping cfs_rq::idle as a copy of tg::idle, make it the sum of all ancestor tg::idle. This makes it trivial to tell if the current cgroup is marked idle somewhere along its ancestral path. This makes se_is_idle() behave differently. Notably is will now be true when there is a idle cgroup anywhere in the ancestor path. This addresses an issue where preemption of cgroup::idle was overlooked when flattening the runqueue. Fixes: 85570f10a4c6 ("sched/eevdf: Move to a single runqueue") Signed-off-by: Peter Zijlstra (Intel) Reviewed-by: Kayra Cizmeci Reviewed-by: Vincent Guittot Reviewed-by: Josh Don Link: https://patch.msgid.link/20261107113639.GK2668200@noisy.programming.kicks-ass.net --- kernel/sched/debug.c | 1 + kernel/sched/fair.c | 88 +++++++++++++++++++++++++++----------------- kernel/sched/sched.h | 2 +- 3 files changed, 56 insertions(+), 35 deletions(-) diff --git a/kernel/sched/debug.c b/kernel/sched/debug.c index e6a3b516c703ba..dcf9b1daf3d06b 100644 --- a/kernel/sched/debug.c +++ b/kernel/sched/debug.c @@ -1112,6 +1112,7 @@ void print_cfs_rq(struct seq_file *m, int cpu, struct cfs_rq *cfs_rq) atomic_long_read(&cfs_rq->tg->load_avg)); SEQ_printf(m, " .%-30s: %lu\n", "h_load", cfs_rq->h_load); + SEQ_printf(m, " .%-30s: %d\n", "idle", cfs_rq->idle); #endif /* CONFIG_FAIR_GROUP_SCHED */ #ifdef CONFIG_CFS_BANDWIDTH SEQ_printf(m, " .%-30s: %d\n", "throttled", diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index 95fd7560d97084..4e21cda53b198e 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -445,8 +445,10 @@ static int cfs_rq_is_idle(struct cfs_rq *cfs_rq) static int se_is_idle(struct sched_entity *se) { - if (entity_is_task(se)) - return task_has_idle_policy(task_of(se)); + if (entity_is_task(se)) { + return task_has_idle_policy(task_of(se)) || + cfs_rq_is_idle(cfs_rq_of(se)); + } return cfs_rq_is_idle(group_cfs_rq(se)); } @@ -15672,19 +15674,20 @@ int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) void online_fair_sched_group(struct task_group *tg) { - struct sched_entity *se; - struct rq_flags rf; - struct rq *rq; int i; for_each_possible_cpu(i) { - rq = cpu_rq(i); - se = tg_se(tg, i); - rq_lock_irq(rq, &rf); + struct cfs_rq *cfs_rq = tg_cfs_rq(tg, i); + struct sched_entity *se = tg_se(tg, i); + struct rq *rq = cpu_rq(i); + + guard(rq_lock_irq)(rq); + update_rq_clock(rq); attach_entity_cfs_rq(se); sync_throttle(tg, i); - rq_unlock_irq(rq, &rf); + + cfs_rq->idle = tg_cfs_rq(tg->parent, i)->idle; } } @@ -15793,6 +15796,43 @@ int sched_group_set_shares(struct task_group *tg, unsigned long shares) return ret; } +struct tg_set_idle_struct { + long idle; + int cpu; +}; + +static int tg_set_idle_up(struct task_group *tg, void *data) +{ + struct tg_set_idle_struct *tsi = data; + struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, tsi->cpu); + struct sched_entity *se = tg_se(tg, tsi->cpu); + int old_idle = grp_cfs_rq->idle; + int task_delta; + + grp_cfs_rq->idle += tsi->idle; + + if (!!old_idle == !!grp_cfs_rq->idle) + return 0; + + task_delta = grp_cfs_rq->h_nr_queued - grp_cfs_rq->h_nr_idle; + if (!task_delta) + return 0; + + task_delta *= tsi->idle; + for_each_sched_entity(se) { + struct cfs_rq *cfs_rq = cfs_rq_of(se); + + if (!se->on_rq) + break; + + cfs_rq->h_nr_idle += task_delta; + + if (cfs_rq_is_idle(cfs_rq)) + break; + } + return 0; +} + int sched_group_set_idle(struct task_group *tg, long idle) { int i; @@ -15811,34 +15851,14 @@ int sched_group_set_idle(struct task_group *tg, long idle) for_each_possible_cpu(i) { struct rq *rq = cpu_rq(i); - struct sched_entity *se = tg_se(tg, i); - struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, i); - bool was_idle = cfs_rq_is_idle(grp_cfs_rq); - long idle_task_delta; guard(rq_lock_irqsave)(rq); - grp_cfs_rq->idle = idle; - if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq))) - continue; - - idle_task_delta = grp_cfs_rq->h_nr_queued - - grp_cfs_rq->h_nr_idle; - if (!cfs_rq_is_idle(grp_cfs_rq)) - idle_task_delta *= -1; - - for_each_sched_entity(se) { - struct cfs_rq *cfs_rq = cfs_rq_of(se); - - if (!se->on_rq) - break; - - cfs_rq->h_nr_idle += idle_task_delta; - - /* Already accounted at parent level and above. */ - if (cfs_rq_is_idle(cfs_rq)) - break; - } + struct tg_set_idle_struct tsi = { + .idle = idle ? 1 : -1, + .cpu = i, + }; + walk_tg_tree_from(tg, tg_nop, tg_set_idle_up, &tsi); } /* Idle groups have minimum weight. */ diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index 220927453a8892..36a94920bdff40 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -751,7 +751,7 @@ struct cfs_rq { struct list_head leaf_cfs_rq_list; struct task_group *tg; /* Group that "owns" this runqueue */ - /* Locally cached copy of our task_group's idle value */ + /* Sum of all ancestor tg->idle. */ int idle; # ifdef CONFIG_CFS_BANDWIDTH From 486c3d06b90240860e99686d29ed9f15637dc314 Mon Sep 17 00:00:00 2001 From: K Prateek Nayak Date: Thu, 12 Nov 2026 08:34:47 +0000 Subject: [PATCH 0871/2102] sched/fair: Avoid transient double accounting for delayed tasks When a task is delayed, h_nr_runnable is adjusted via set_delayed(). A dequeue of delayed task with DEQUEUE_DELAYED would decrement cfs_rq->h_nr_runnable again in dequeue_hierarchy() and then correct it immediately in __dequeue_task() via clear_delayed(). Adding: WARN_ON_ONCE(((int)cfs_rq->h_nr_runnable) < 0); in dequeue_hierarchy() after h_nr_runnable accounting is tripped reliably during early boot. Although the cfs_rq->h_nr_runnable accounting is transient, this incorrect value gets cached in se->runnable_weight and can affect PELT calculation until the next enqueue / dequeue adjusts the runnable weight. Similarly, a task enqueue should never reach enqueue_hierarchy() for just ENQUEUE_WAKEUP && se->sched_delayed. Wakeup of delayed tasks must couple ENQUEUE_DELAYED which gets correctly handled in enqueue_task_fair(). Avoid incorrect accounting in __dequeue_task() and warn for incorrect wakeup flags if delayed tasks reaches enqueue with just ENQUEUE_WAKEUP. Fixes: 85570f10a4c6 ("sched/eevdf: Move to a single runqueue") Signed-off-by: K Prateek Nayak Signed-off-by: Peter Zijlstra (Intel) Reviewed-by: Vincent Guittot Link: https://patch.msgid.link/20261112083447.25603-1-kprateek.nayak@amd.com --- kernel/sched/fair.c | 57 ++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 32 deletions(-) diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index 4e21cda53b198e..3b0b0ebe3cf069 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -6549,19 +6549,8 @@ static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq); static void set_delayed(struct sched_entity *se) { - /* - * Delayed se of cfs_rq have no tasks queued on them. - * Do not adjust h_nr_runnable since __dequeue_task() - * will account it for blocked tasks. - * - * This check can be removed because when flat pick - * patches get merged as only task can get delayed, - * same for clear_delayed(). - */ - if (!entity_is_task(se)) { - se->sched_delayed = 1; - return; - } + /* Only tasks can be delayed. */ + WARN_ON_ONCE(!entity_is_task(se)); /* * Drop a task leaving the runnable set. @@ -6578,18 +6567,16 @@ static void set_delayed(struct sched_entity *se) } } -static void clear_delayed(struct sched_entity *se) +static void __clear_delayed(struct sched_entity *se) { + /* Only tasks can be delayed. */ + WARN_ON_ONCE(!entity_is_task(se)); se->sched_delayed = 0; +} - /* - * Delayed se of cfs_rq have no tasks queued on them. - * Do not adjust h_nr_runnable since a dequeue has - * already accounted for it or an enqueue of a task - * below it will account for it in enqueue_task_fair(). - */ - if (!entity_is_task(se)) - return; +static void clear_delayed(struct sched_entity *se) +{ + __clear_delayed(se); /* * Re-add on wake, after sched_delayed is cleared. On a final delayed @@ -8113,12 +8100,15 @@ requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) static unsigned long enqueue_hierarchy(struct task_struct *p, int flags) { unsigned long weight = NICE_0_LOAD; - int task_new = !(flags & ENQUEUE_WAKEUP); struct sched_entity *se = &p->se; int h_nr_idle = task_has_idle_policy(p); int h_nr_runnable = 1; - if (task_new && se->sched_delayed) + /* + * Accounted via requeue_delayed_entity() calling + * clear_delayed() when delayed task wakes up. + */ + if (se->sched_delayed) h_nr_runnable = 0; for_each_sched_entity(se) { @@ -8192,6 +8182,9 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) return; } + /* Wakeup of delayed tasks must be handled above. */ + WARN_ON_ONCE(!task_new && se->sched_delayed); + /* * If in_iowait is set, the code below may not trigger any cpufreq * utilization updates, so do it here explicitly with the IOWAIT flag @@ -8209,9 +8202,6 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) if (curr) place_entity(cfs_rq, se, flags); - if (se->on_rq && se->sched_delayed) - requeue_delayed_entity(cfs_rq, se); - weight = enqueue_hierarchy(p, flags); if (!curr) { @@ -8251,15 +8241,14 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) static void dequeue_hierarchy(struct task_struct *p, int flags) { struct sched_entity *se = &p->se; - bool task_sleep = flags & DEQUEUE_SLEEP; - bool task_delayed = flags & DEQUEUE_DELAYED; bool task_throttled = flags & DEQUEUE_THROTTLE; int h_nr_runnable = 0; int h_nr_idle = task_has_idle_policy(p); bool dequeue = true; - if (task_sleep || task_delayed || !se->sched_delayed) - h_nr_runnable = 1; + /* Already accounted via set_delayed(). */ + if (se->sched_delayed) + h_nr_runnable = 0; for_each_sched_entity(se) { struct cfs_rq *cfs_rq = cfs_rq_of(se); @@ -8349,7 +8338,11 @@ static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags) rq->next_balance = jiffies; if (task_delayed) { - clear_delayed(se); + /* + * Skip accounting since set_delayed() has already + * adjusted it. Just clear se->sched_delayed. + */ + __clear_delayed(se); WARN_ON_ONCE(!task_sleep); WARN_ON_ONCE(p->on_rq != 1); From 342fe98c34311969950fa58a840fd0b95a16c9dd Mon Sep 17 00:00:00 2001 From: Michal Blaszczyk Date: Tue, 10 Nov 2026 15:18:57 +0000 Subject: [PATCH 0872/2102] sched: Lift cgroup update locking to core to prevent CFS/SCX divergence Concurrent writes to cgroup control files (such as cpu.shares or cpu.weight) can lead to state divergence between CFS and SCX. For instance, in cpu_shares_write_u64(), the CFS update is serialized by shares_mutex (internal to fair.c), but this lock is dropped before scx_group_set_weight() is called. The latter only acquires a read semaphore (scx_cgroup_ops_rwsem), allowing multiple threads to evaluate and act on the sched_ext update concurrently. This serialization gap allows concurrent writes to interleave. As a result, the recorded state in CFS, the SCX internal bookkeeping (e.g., tg->scx.weight), and the BPF scheduler itself can end up operating on completely distinct parameters (pairwise distinct values). Similar races are present in tg_set_bandwidth(), cpu_idle_write_s64(), cpu_weight_write_u64(), and cpu_weight_nice_write_s64(). Fix this by moving the CFS locking up into the core layer in `kernel/sched/core.c`. By acquiring these locks directly in the core write handlers, both the CFS and SCX callbacks are executed atomically under the same lock. Fixes: 819513666966 ("sched_ext: Add cgroup support") Signed-off-by: Michal Blaszczyk Signed-off-by: Peter Zijlstra (Intel) Reviewed-by: Andrea Righi Acked-by: Tejun Heo Link: https://patch.msgid.link/20261110151857.1864222-1-michalblk@google.com --- kernel/sched/core.c | 35 +++++++++++++++++++++++------------ kernel/sched/fair.c | 19 ++++++++++++------- kernel/sched/sched.h | 7 +++++++ 3 files changed, 42 insertions(+), 19 deletions(-) diff --git a/kernel/sched/core.c b/kernel/sched/core.c index 5ed660f099a55a..515b9d0353ce9e 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -9776,6 +9776,8 @@ static int cpu_uclamp_max_show(struct seq_file *sf, void *v) } #endif /* CONFIG_UCLAMP_TASK_GROUP */ +DEFINE_MUTEX(cpu_weight_mutex); + #ifdef CONFIG_GROUP_SCHED_WEIGHT static unsigned long tg_weight(struct task_group *tg) { @@ -9793,7 +9795,10 @@ static int cpu_shares_write_u64(struct cgroup_subsys_state *css, if (shareval > scale_load_down(ULONG_MAX)) shareval = MAX_SHARES; - ret = sched_group_set_shares(css_tg(css), scale_load(shareval)); + + guard(mutex)(&cpu_weight_mutex); + + ret = sched_group_set_shares_locked(css_tg(css), scale_load(shareval)); if (!ret) scx_group_set_weight(css_tg(css), sched_weight_to_cgroup(shareval)); @@ -9808,8 +9813,6 @@ static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css, #endif /* CONFIG_GROUP_SCHED_WEIGHT */ #ifdef CONFIG_CFS_BANDWIDTH -static DEFINE_MUTEX(cfs_constraints_mutex); - static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime); static int tg_set_cfs_bandwidth(struct task_group *tg, @@ -9828,13 +9831,6 @@ static int tg_set_cfs_bandwidth(struct task_group *tg, burst = (u64)burst_us * NSEC_PER_USEC; - /* - * Prevent race between setting of cfs_rq->runtime_enabled and - * unthrottle_offline_cfs_rqs(). - */ - guard(cpus_read_lock)(); - guard(mutex)(&cfs_constraints_mutex); - ret = __cfs_schedulable(tg, period, quota); if (ret) return ret; @@ -10086,6 +10082,8 @@ static u64 cpu_period_read_u64(struct cgroup_subsys_state *css, return period_us; } +static DEFINE_MUTEX(cpu_max_mutex); + static int tg_set_bandwidth(struct task_group *tg, u64 period_us, u64 quota_us, u64 burst_us) { @@ -10128,6 +10126,13 @@ static int tg_set_bandwidth(struct task_group *tg, burst_us + quota_us > max_bw_runtime_us)) return -EINVAL; + /* + * Prevent race between setting of cfs_rq->runtime_enabled and + * unthrottle_offline_cfs_rqs(). + */ + guard(cpus_read_lock)(); + guard(mutex)(&cpu_max_mutex); + #ifdef CONFIG_CFS_BANDWIDTH ret = tg_set_cfs_bandwidth(tg, period_us, quota_us, burst_us); #endif /* CONFIG_CFS_BANDWIDTH */ @@ -10226,6 +10231,8 @@ static int cpu_idle_write_s64(struct cgroup_subsys_state *css, { int ret; + guard(mutex)(&cpu_weight_mutex); + ret = sched_group_set_idle(css_tg(css), idle); if (!ret) scx_group_set_idle(css_tg(css), idle); @@ -10402,7 +10409,9 @@ static int cpu_weight_write_u64(struct cgroup_subsys_state *css, weight = sched_weight_from_cgroup(cgrp_weight); - ret = sched_group_set_shares(css_tg(css), scale_load(weight)); + guard(mutex)(&cpu_weight_mutex); + + ret = sched_group_set_shares_locked(css_tg(css), scale_load(weight)); if (!ret) scx_group_set_weight(css_tg(css), cgrp_weight); return ret; @@ -10439,7 +10448,9 @@ static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css, idx = array_index_nospec(idx, 40); weight = sched_prio_to_weight[idx]; - ret = sched_group_set_shares(css_tg(css), scale_load(weight)); + guard(mutex)(&cpu_weight_mutex); + + ret = sched_group_set_shares_locked(css_tg(css), scale_load(weight)); if (!ret) scx_group_set_weight(css_tg(css), sched_weight_to_cgroup(weight)); diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index 3b0b0ebe3cf069..da0d9e19c45772 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -15737,13 +15737,11 @@ void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, se->parent = parent; } -static DEFINE_MUTEX(shares_mutex); - static int __sched_group_set_shares(struct task_group *tg, unsigned long shares) { int i; - lockdep_assert_held(&shares_mutex); + lockdep_assert_held(&cpu_weight_mutex); /* * We can't change the weight of the root cgroup. @@ -15775,16 +15773,16 @@ static int __sched_group_set_shares(struct task_group *tg, unsigned long shares) return 0; } -int sched_group_set_shares(struct task_group *tg, unsigned long shares) +int sched_group_set_shares_locked(struct task_group *tg, unsigned long shares) { int ret; - mutex_lock(&shares_mutex); + lockdep_assert_held(&cpu_weight_mutex); + if (tg_is_idle(tg)) ret = -EINVAL; else ret = __sched_group_set_shares(tg, shares); - mutex_unlock(&shares_mutex); return ret; } @@ -15826,17 +15824,24 @@ static int tg_set_idle_up(struct task_group *tg, void *data) return 0; } +int sched_group_set_shares(struct task_group *tg, unsigned long shares) +{ + guard(mutex)(&cpu_weight_mutex); + return sched_group_set_shares_locked(tg, shares); +} + int sched_group_set_idle(struct task_group *tg, long idle) { int i; + lockdep_assert_held(&cpu_weight_mutex); + if (tg == &root_task_group) return -EINVAL; if (idle < 0 || idle > 1) return -EINVAL; - guard(mutex)(&shares_mutex); if (tg->idle == idle) return 0; diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index 36a94920bdff40..a4e6696e3a516c 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -599,7 +599,10 @@ extern void sched_release_group(struct task_group *tg); extern void sched_move_task(struct task_struct *tsk, bool for_autogroup); #ifdef CONFIG_FAIR_GROUP_SCHED +extern struct mutex cpu_weight_mutex; + extern int sched_group_set_shares(struct task_group *tg, unsigned long shares); +extern int sched_group_set_shares_locked(struct task_group *tg, unsigned long shares); extern int sched_group_set_idle(struct task_group *tg, long idle); @@ -607,6 +610,10 @@ extern void set_task_rq_fair(struct sched_entity *se, struct cfs_rq *prev, struct cfs_rq *next); #else /* !CONFIG_FAIR_GROUP_SCHED: */ static inline int sched_group_set_shares(struct task_group *tg, unsigned long shares) { return 0; } +static inline int sched_group_set_shares_locked(struct task_group *tg, unsigned long shares) +{ + return 0; +} static inline int sched_group_set_idle(struct task_group *tg, long idle) { return 0; } #endif /* !CONFIG_FAIR_GROUP_SCHED */ From db9a489077cbe9217b7bc2b47ebf0fabc5f1a56f Mon Sep 17 00:00:00 2001 From: Henry Zhang Date: Tue, 17 Nov 2026 15:41:07 -0800 Subject: [PATCH 0873/2102] drm/vc4: dsi: Register the PHY clock provider with devm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit vc4_dsi_init_phy_clocks() is called from the component bind. It allocates the clock data with devm_kzalloc() and registers the clocks with devm_clk_hw_register(), so both are released with the devres group that the component framework opens for the bind, when the bind fails later or the component is unbound. The OF clock provider that points at that data is added with of_clk_add_hw_provider() and never removed: after an unbind it stays registered with the freed data, and each new bind adds another provider for the same node. A later lookup of one of these clocks, such as <&dsi1 0>, would call of_clk_hw_onecell_get() on freed memory. Use devm_of_clk_add_hw_provider(), so that the provider is removed with the same devres group, before the clocks and their data. Fixes: 4078f5757144 ("drm/vc4: Add DSI driver") Signed-off-by: Henry Zhang Reviewed-by: Maíra Canal Link: https://patch.msgid.link/20261117234107.1298575-1-henryzhang62@gmail.com Signed-off-by: Maíra Canal --- drivers/gpu/drm/vc4/vc4_dsi.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/vc4/vc4_dsi.c b/drivers/gpu/drm/vc4/vc4_dsi.c index 0148f2befed14a..aff50b2c5846de 100644 --- a/drivers/gpu/drm/vc4/vc4_dsi.c +++ b/drivers/gpu/drm/vc4/vc4_dsi.c @@ -1599,9 +1599,8 @@ vc4_dsi_init_phy_clocks(struct vc4_dsi *dsi) dsi->clk_onecell->hws[i] = &fix->hw; } - return of_clk_add_hw_provider(dev->of_node, - of_clk_hw_onecell_get, - dsi->clk_onecell); + return devm_of_clk_add_hw_provider(dev, of_clk_hw_onecell_get, + dsi->clk_onecell); } static void vc4_dsi_dma_mem_release(void *ptr) From 9fcdf40e0d7c58478d88d3e1ca69fec8badda0fd Mon Sep 17 00:00:00 2001 From: Joel Granados Date: Tue, 17 Nov 2026 11:03:47 +0100 Subject: [PATCH 0874/2102] sysctl: Do jiffy / ms conversion in ulong space Replace jiffies_to_msecs & msecs_to_jiffies calls with sysctl specific converters. Removes the need to handle overflow corner cases when moving to and from the unsigned int and the unsigned long spaces. Handle the unsigned long overflow in the sysctl specific converters (sysctl_jiffies_to_msecs & sysctl_msecs_to_jiffies). The unsigned int overflow is handled in the generic sysctl int converters (e.g. proc_int_u2k_conv_uop). Round up on writes and down on reads for both unsigned int and unsigned long types. This is the behavior being fixed: SUL="/proc/sys/net/rxrpc/idle_conn_fast_expiry" SSI="/proc/sys/debug/test_sysctl/int_ms_jiffies" 1. Before # HZ = 300, CONFIG_TEST_SYSCTL=y & CONFIG_AF_RXRPC=y echo 1 > $SSI; cat $SSI # -> 4 echo 4 > $SSI; cat $SSI # -> 7 echo 7 > $SSI; cat $SSI # -> 10 echo 10 > $SSI; cat $SSI # -> 10 echo 4 > $SUL; cat $SUL # -> 3 echo 3 > $SUL; cat $SUL # echo: write error: Invalid argument # HZ = 100, CONFIG_TEST_SYSCTL=y & CONFIG_AF_RXRPC=y echo 2147483648 > $SUL; cat $SUL # -> 4294967276 echo 5000000000 > $SUL; cat $SUL # -> 4294967276 2. Now # HZ = 300, CONFIG_TEST_SYSCTL=y & CONFIG_AF_RXRPC=y echo 1 > $SSI; cat $SSI # -> 3 echo 3 > $SSI; cat $SSI # -> 3 echo 4 > $SSI; cat $SSI # -> 6 echo 6 > $SSI; cat $SSI # -> 6 echo 7 > $SSI; cat $SSI # -> 10 echo 10 > $SSI; cat $SSI # -> 10 echo 4 > $SUL; cat $SUL # -> 6 echo 6 > $SUL; cat $SUL # -> 6 # HZ = 100, CONFIG_TEST_SYSCTL=y & CONFIG_AF_RXRPC=y echo 2147483648 > $SUL; cat $SUL # -> 2147483650 echo 5000000000 > $SUL; cat $SUL # -> 5000000000 Fixes: afdf35cfae0d ("sysctl: Fix type truncation in sysctl_msec_to_jiffies") Fixes: b96b5c6708ea ("sysctl: Replace do_proc_do{int,ulong,uint}vec with do_proc_vec") Reported-by: Avi Weiss Link: https://lore.kernel.org/all/20261102111516.1398262-2-thnkslprpt@gmail.com Signed-off-by: Joel Granados --- kernel/time/jiffies.c | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/kernel/time/jiffies.c b/kernel/time/jiffies.c index af1c69bf0c23db..b861dc860d3452 100644 --- a/kernel/time/jiffies.c +++ b/kernel/time/jiffies.c @@ -137,11 +137,19 @@ static int sysctl_k2u_int_conv_userhz(bool *negp, ulong *u_ptr, const int *k_ptr return proc_int_k2u_conv_kop(u_ptr, k_ptr, negp, sysctl_jiffies_to_clock_t); } +/* + * Calc ms <-> jiffies conversions for sysctls in unsigned long arithmetic. + * Think hard about using the non-sysctl converters (msecs_to_jiffies & + * jiffies_to_msecs) as the interaction between ulong and uint is not trivial. + */ static ulong sysctl_msecs_to_jiffies(const ulong val) { - if (val > jiffies_to_msecs(MAX_JIFFY_OFFSET)) - return MAX_JIFFY_OFFSET; - return msecs_to_jiffies(val); + ulong secs = val / MSEC_PER_SEC; + + if (secs >= ULONG_MAX / HZ) + return ULONG_MAX; + + return secs * HZ + DIV_ROUND_UP((val % MSEC_PER_SEC) * HZ, MSEC_PER_SEC); } static int sysctl_u2k_int_conv_ms(const bool *negp, const ulong *u_ptr, int *k_ptr) @@ -151,7 +159,12 @@ static int sysctl_u2k_int_conv_ms(const bool *negp, const ulong *u_ptr, int *k_p static ulong sysctl_jiffies_to_msecs(const ulong val) { - return jiffies_to_msecs(val); + ulong secs = val / HZ; + + if (secs >= ULONG_MAX / MSEC_PER_SEC) + return ULONG_MAX; + + return secs * MSEC_PER_SEC + (val % HZ) * MSEC_PER_SEC / HZ; } static int sysctl_k2u_int_conv_ms(bool *negp, ulong *u_ptr, const int *k_ptr) From 80ac6d197218c3399d66674167a4d7c9051a25e2 Mon Sep 17 00:00:00 2001 From: Henry Zhang Date: Wed, 28 Oct 2026 09:45:26 -0700 Subject: [PATCH 0875/2102] drm/vc4: dsi: Set the transfer result before completing the transfer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On an HSTX timeout the interrupt handler completes the transfer and only then sets xfer_result to -ETIMEDOUT. The waiter, which may run on another CPU, can wake up and read xfer_result in between, still 0 from the start of the transfer, and report the timed-out transfer as a success. Set xfer_result first. complete() orders the store before the wake-up. Fixes: 4078f5757144 ("drm/vc4: Add DSI driver") Signed-off-by: Henry Zhang Link: https://patch.msgid.link/20261028164539.3471833-2-henryzhang62@gmail.com Reviewed-by: Maíra Canal Signed-off-by: Maíra Canal --- drivers/gpu/drm/vc4/vc4_dsi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/vc4/vc4_dsi.c b/drivers/gpu/drm/vc4/vc4_dsi.c index aff50b2c5846de..762929ec471f84 100644 --- a/drivers/gpu/drm/vc4/vc4_dsi.c +++ b/drivers/gpu/drm/vc4/vc4_dsi.c @@ -1527,8 +1527,8 @@ static irqreturn_t vc4_dsi_irq_handler(int irq, void *data) complete(&dsi->xfer_completion); ret = IRQ_HANDLED; } else if (stat & DSI_PORT_BIT(INT_HSTX_TO)) { - complete(&dsi->xfer_completion); dsi->xfer_result = -ETIMEDOUT; + complete(&dsi->xfer_completion); ret = IRQ_HANDLED; } From 63714f698ffa52563a8978636c2e05929736b608 Mon Sep 17 00:00:00 2001 From: Christian Aurich Zanettini Martins Date: Wed, 4 Nov 2026 19:25:58 -0300 Subject: [PATCH 0876/2102] ring-buffer: Do not WARN when trace_rb_cpu_prepare() fails to allocate Creating a tracing instance allocates the buffers of the other CPUs through trace_rb_cpu_prepare(), which WARNs if the allocation fails. But __rb_allocate_pages() bails out on purpose when si_mem_available() is too low or the task gets killed, so a mkdir in instances/ with a large trace_buf_size is enough to trigger it: WARNING: kernel/trace/ring_buffer.c:8094 at trace_rb_cpu_prepare+0xf1/0x100 The same failure for the current CPU, or in ring_buffer_resize(), just returns -ENOMEM. Use pr_warn() here instead. Link: https://patch.msgid.link/20261104222558.863948-1-christian.aurichzm@gmail.com Fixes: b32614c03413 ("tracing/rb: Convert to hotplug state machine") Reported-by: syzbot+fbe07bcf949966f3c00f@syzkaller.appspotmail.com Closes: https://lore.kernel.org/all/6a707c4f.13bfb6d0.1ecdd5.027e.GAE@google.com/ Signed-off-by: Christian Aurich Zanettini Martins Signed-off-by: Steven Rostedt --- kernel/trace/ring_buffer.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c index 75cd8df23c1b9c..ed267d62882650 100644 --- a/kernel/trace/ring_buffer.c +++ b/kernel/trace/ring_buffer.c @@ -8091,8 +8091,7 @@ int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node) buffer->buffers[cpu] = rb_allocate_cpu_buffer(buffer, nr_pages, cpu); if (!buffer->buffers[cpu]) { - WARN(1, "failed to allocate ring buffer on CPU %u\n", - cpu); + pr_warn("failed to allocate ring buffer on CPU %u\n", cpu); return -ENOMEM; } From cea5f91daa3ac86c98b63b3a2e89da622670ccf6 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Tue, 17 Nov 2026 11:42:03 -0800 Subject: [PATCH 0877/2102] wait-event: clean up the internal helper arguments The ___wait_event() helper for historical reasons took a "0/1" argument for whether the wait-queue entry should be marked WQ_FLAG_EXCLUSIVE or not. That didn't really help readability, but it also limited the wq_flags for that helper to only that one flag. Just make that macro argument be the actual 'wq_flags' value, which simplifies the helper, and makes it more generic. It also happens to make the users of this macro more obvious when an unexplained '1' argument becomes a more self-explanatory 'WQ_FLAG_EXCLUSIVE'. Also change the existing users that use that raw ___wait_event() interface with just a plain schedule() to use the pre-existing helpers macros: __wait_event_state() and __wait_event_state_exclusive(). [ This is not a bug-fix: it was prep-work for a bug report that turned out to be just a "don't do that" situation instead. But I also didn't want to just throw it away or leave it pending, since it just made some of that grotty code much clearer - Linus] Reviewed-by: Oleg Nesterov Link: https://lore.kernel.org/all/20261111-pipe-epollexclusive-wakeup-v1-1-0af6283e9fda@columbia.edu/ Signed-off-by: Linus Torvalds --- include/linux/wait.h | 36 +++++++++++++++--------------------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/include/linux/wait.h b/include/linux/wait.h index c2af98b0074dcb..b3e94c71cd3e66 100644 --- a/include/linux/wait.h +++ b/include/linux/wait.h @@ -299,13 +299,13 @@ extern void init_wait_entry(struct wait_queue_entry *wq_entry, int flags); * otherwise. */ -#define ___wait_event(wq_head, condition, state, exclusive, ret, cmd) \ +#define ___wait_event(wq_head, condition, state, wq_flag, ret, cmd) \ ({ \ __label__ __out; \ struct wait_queue_entry __wq_entry; \ long __ret = ret; /* explicit shadow */ \ \ - init_wait_entry(&__wq_entry, exclusive ? WQ_FLAG_EXCLUSIVE : 0); \ + init_wait_entry(&__wq_entry, wq_flag); \ for (;;) { \ long __int = prepare_to_wait_event(&wq_head, &__wq_entry, state);\ \ @@ -327,8 +327,7 @@ __out: __ret; \ }) #define __wait_event(wq_head, condition) \ - (void)___wait_event(wq_head, condition, TASK_UNINTERRUPTIBLE, 0, 0, \ - schedule()) + (void)__wait_event_state(wq_head, condition, TASK_UNINTERRUPTIBLE) /** * wait_event - sleep until a condition gets true @@ -366,8 +365,7 @@ do { \ } while (0) #define __wait_event_freezable(wq_head, condition) \ - ___wait_event(wq_head, condition, (TASK_INTERRUPTIBLE|TASK_FREEZABLE), \ - 0, 0, schedule()) + __wait_event_state(wq_head, condition, (TASK_INTERRUPTIBLE|TASK_FREEZABLE)) /** * wait_event_freezable - sleep (or freeze) until a condition gets true @@ -442,8 +440,8 @@ do { \ }) #define __wait_event_exclusive_cmd(wq_head, condition, cmd1, cmd2) \ - (void)___wait_event(wq_head, condition, TASK_UNINTERRUPTIBLE, 1, 0, \ - cmd1; schedule(); cmd2) + (void)___wait_event(wq_head, condition, TASK_UNINTERRUPTIBLE, \ + WQ_FLAG_EXCLUSIVE, 0, cmd1; schedule(); cmd2) /* * Just like wait_event_cmd(), except it sets exclusive flag */ @@ -480,8 +478,7 @@ do { \ } while (0) #define __wait_event_interruptible(wq_head, condition) \ - ___wait_event(wq_head, condition, TASK_INTERRUPTIBLE, 0, 0, \ - schedule()) + __wait_event_state(wq_head, condition, TASK_INTERRUPTIBLE) /** * wait_event_interruptible - sleep until a condition gets true @@ -620,8 +617,7 @@ do { \ }) #define __wait_event_interruptible_exclusive(wq, condition) \ - ___wait_event(wq, condition, TASK_INTERRUPTIBLE, 1, 0, \ - schedule()) + __wait_event_state_exclusive(wq, condition, TASK_INTERRUPTIBLE) #define wait_event_interruptible_exclusive(wq, condition) \ ({ \ @@ -633,8 +629,7 @@ do { \ }) #define __wait_event_killable_exclusive(wq, condition) \ - ___wait_event(wq, condition, TASK_KILLABLE, 1, 0, \ - schedule()) + __wait_event_state_exclusive(wq, condition, TASK_KILLABLE) #define wait_event_killable_exclusive(wq, condition) \ ({ \ @@ -647,8 +642,7 @@ do { \ #define __wait_event_freezable_exclusive(wq, condition) \ - ___wait_event(wq, condition, (TASK_INTERRUPTIBLE|TASK_FREEZABLE), 1, 0,\ - schedule()) + __wait_event_state_exclusive(wq, condition, (TASK_INTERRUPTIBLE|TASK_FREEZABLE)) #define wait_event_freezable_exclusive(wq, condition) \ ({ \ @@ -676,7 +670,7 @@ do { \ do { \ might_sleep(); \ if (!(condition)) \ - ___wait_event(wq_head, condition, TASK_IDLE, 0, 0, schedule()); \ + __wait_event_state(wq_head, condition, TASK_IDLE); \ } while (0) /** @@ -700,7 +694,7 @@ do { \ do { \ might_sleep(); \ if (!(condition)) \ - ___wait_event(wq_head, condition, TASK_IDLE, 1, 0, schedule()); \ + __wait_event_state_exclusive(wq_head, condition, TASK_IDLE); \ } while (0) #define __wait_event_idle_timeout(wq_head, condition, timeout) \ @@ -738,7 +732,7 @@ do { \ #define __wait_event_idle_exclusive_timeout(wq_head, condition, timeout) \ ___wait_event(wq_head, ___wait_cond_timeout(condition), \ - TASK_IDLE, 1, timeout, \ + TASK_IDLE, WQ_FLAG_EXCLUSIVE, timeout, \ __ret = schedule_timeout(__ret)) /** @@ -911,7 +905,7 @@ extern int do_wait_intr_irq(wait_queue_head_t *, wait_queue_entry_t *); #define __wait_event_killable(wq, condition) \ - ___wait_event(wq, condition, TASK_KILLABLE, 0, 0, schedule()) + __wait_event_state(wq, condition, TASK_KILLABLE) /** * wait_event_killable - sleep until a condition gets true @@ -981,7 +975,7 @@ extern int do_wait_intr_irq(wait_queue_head_t *, wait_queue_entry_t *); }) #define __wait_event_state_exclusive(wq, condition, state) \ - ___wait_event(wq, condition, state, 1, 0, schedule()) + ___wait_event(wq, condition, state, WQ_FLAG_EXCLUSIVE, 0, schedule()) #define wait_event_state_exclusive(wq, condition, state) \ ({ \ From e735de71a2d9403fa1e2d134d1e9aa0a24f4eaff Mon Sep 17 00:00:00 2001 From: Donghui Zhao Date: Wed, 18 Nov 2026 17:26:03 +0800 Subject: [PATCH 0878/2102] MAINTAINERS: Add Donghui Zhao as ESWIN PCIe maintainer Senchuan Zhang has left ESWIN Computing, so replace him with Donghui Zhao as the maintainer of the ESWIN PCIe controller driver. Signed-off-by: Donghui Zhao Signed-off-by: Bjorn Helgaas Link: https://patch.msgid.link/20261118092603.1331-1-zhaodonghui@eswincomputing.com --- MAINTAINERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index 93abbb315065de..056a32d80c2f42 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -21674,7 +21674,7 @@ S: Odd Fixes F: drivers/pci/controller/pci-thunder-* PCIE DRIVER FOR ESWIN -M: Senchuan Zhang +M: Donghui Zhao L: linux-pci@vger.kernel.org S: Maintained F: Documentation/devicetree/bindings/pci/eswin,pcie.yaml From 06b6fbe05f5c81654815ec8d864d792a226cbdac Mon Sep 17 00:00:00 2001 From: Nguyen Ngoc Thang Date: Wed, 18 Nov 2026 09:21:18 -0500 Subject: [PATCH 0879/2102] Bluetooth: L2CAP: Use a reserved ident for L2CAP_LE_CREDITS L2CAP_LE_CREDITS has no response, so an ident taken from conn->tx_ida for it is never released by l2cap_put_ident() and l2cap_chan_le_send_credits() has to free it right away after sending, otherwise the range is exhausted after 254 packets and credits would be sent with the invalid ident 0, which some remote stacks ignore, stalling the channel. tx_ida only exists to track requests awaiting a response, so a command without one has no business in it: every credit update allocates and frees an ident, and the ident is visible in tx_ida while the credits are in flight, so an answer to them (a L2CAP_COMMAND_REJ) is processed by l2cap_put_ident() like the answer to a request. Using a counter that doesn't consult tx_ida is not an option either, it can return the ident of a request still outstanding, and a reject of the credits would then release that request's ident and close its channel in l2cap_le_command_rej(). Reserve ident 255 for L2CAP_LE_CREDITS instead: l2cap_get_ident() never returns it (the BR/EDR range already ends at 128), so it can't collide with any request, it doesn't have to be tracked in conn->tx_ida, and a reject of it matches no outstanding request. Fixes: 6e1930ece855 ("Bluetooth: L2CAP: fix tx ident leak for commands without a response") Reported-by: syzbot+9dc8780713b11155dd74@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=9dc8780713b11155dd74 Signed-off-by: Nguyen Ngoc Thang Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- include/net/bluetooth/l2cap.h | 5 +++++ net/bluetooth/l2cap_core.c | 28 +++++++++++----------------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/include/net/bluetooth/l2cap.h b/include/net/bluetooth/l2cap.h index bb2839972cf3ff..9f18e70f09bb95 100644 --- a/include/net/bluetooth/l2cap.h +++ b/include/net/bluetooth/l2cap.h @@ -45,6 +45,11 @@ #define L2CAP_DEFAULT_ACC_LAT 0xFFFFFFFF #define L2CAP_BREDR_MAX_PAYLOAD 1019 /* 3-DH5 packet */ #define L2CAP_LE_MIN_MTU 23 + +/* Identifier used by L2CAP_LE_CREDITS, it has no response so it is not + * tracked in conn->tx_ida and is never allocated for any other command. + */ +#define L2CAP_IDENT_LE_CREDITS 255 #define L2CAP_ECRED_CONN_SCID_MAX 5 #define L2CAP_DISC_TIMEOUT msecs_to_jiffies(100) diff --git a/net/bluetooth/l2cap_core.c b/net/bluetooth/l2cap_core.c index 686e86c04d7ea1..133641c44e692d 100644 --- a/net/bluetooth/l2cap_core.c +++ b/net/bluetooth/l2cap_core.c @@ -1033,9 +1033,11 @@ static int l2cap_get_ident(struct l2cap_conn *conn) u8 max; int ident; - /* LE link does not support tools like l2ping so use the full range */ + /* LE link does not support tools like l2ping so use the full range, + * except for L2CAP_IDENT_LE_CREDITS which is reserved. + */ if (conn->hcon->type == LE_LINK) - max = 255; + max = L2CAP_IDENT_LE_CREDITS - 1; /* Get next available identificator. * 1 - 128 are used by kernel. * 129 - 199 are reserved. @@ -7132,7 +7134,6 @@ static void l2cap_chan_le_send_credits(struct l2cap_chan *chan) struct l2cap_conn *conn = chan->conn; struct l2cap_le_credits pkt; u16 return_credits = l2cap_le_rx_credits(chan); - int ident; if (chan->mode != L2CAP_MODE_LE_FLOWCTL && chan->mode != L2CAP_MODE_EXT_FLOWCTL) @@ -7150,21 +7151,14 @@ static void l2cap_chan_le_send_credits(struct l2cap_chan *chan) pkt.cid = cpu_to_le16(chan->scid); pkt.credits = cpu_to_le16(return_credits); - /* Keeps l2cap_put_ident() from releasing ident before we do */ - lockdep_assert_held(&conn->lock); - - ident = l2cap_get_ident(conn); - - l2cap_send_cmd(conn, ident, L2CAP_LE_CREDITS, sizeof(pkt), &pkt); - - /* L2CAP_LE_CREDITS has no response so the ident is never released by - * l2cap_put_ident() - release it right away, otherwise the tx_ida - * range is exhausted after 254 packets and from then on credits are - * sent with the invalid ident 0, which some remote stacks ignore, - * stalling the channel. + /* L2CAP_LE_CREDITS has no response so it uses the reserved ident rather + * than one from conn->tx_ida, which would have to be released right + * away or would be exhausted after 254 packets, and could otherwise + * collide with the ident of a request still outstanding. A reject of it + * can't match any request either. */ - if (ident > 0) - ida_free(&conn->tx_ida, ident); + l2cap_send_cmd(conn, L2CAP_IDENT_LE_CREDITS, L2CAP_LE_CREDITS, + sizeof(pkt), &pkt); } void l2cap_chan_rx_avail(struct l2cap_chan *chan, ssize_t rx_avail) From 657d7c48b84f2ef0bf885b47cf2318823bc72970 Mon Sep 17 00:00:00 2001 From: Stanley Jhu Date: Wed, 4 Nov 2026 19:27:44 +0800 Subject: [PATCH 0880/2102] block: Keep RPM_ACTIVE in blk_pre_runtime_resume() when already active Since commit eef1d74bf88f ("PM: runtime: Only set runtime_error on suspend callback failures"), a failed runtime resume leaves dev->power.runtime_error at 0 with runtime_status set to RPM_SUSPENDED, so later runtime resume requests run sdev_runtime_resume() again: 1. A runtime suspend increments q->pm_only from 0 to 1 and sets q->rpm_status to RPM_SUSPENDED. 2. The first runtime resume fails in the driver callback, and blk_post_runtime_resume() sets q->rpm_status to RPM_ACTIVE and calls blk_clear_pm_only(), decrementing q->pm_only from 1 to 0 so recovery commands can enter the queue (intended since commit 6e1fcab00a23 ("scsi: block: pm: Always set request queue runtime active in blk_post_runtime_resume()")). 3. A retried runtime resume calls blk_pre_runtime_resume(), which overwrites q->rpm_status from RPM_ACTIVE to RPM_RESUMING, so blk_post_runtime_resume() sees old_status != RPM_ACTIVE and calls blk_clear_pm_only() a second time without a matching blk_set_pm_only(). 4. q->pm_only underflows from 0 to -1 (triggering WARN_ON_ONCE in blk_clear_pm_only()), blocking non-PM requests in blk_queue_enter() and __bio_queue_enter() while the device is RPM_ACTIVE, and the next runtime suspend increments q->pm_only from -1 to 0, letting non-PM requests dispatch while RPM_SUSPENDED. This hits the UFS device well-known LUN by default and SCSI disks with manage_runtime_start_stop enabled (ATA and FireWire sbp2 defaults). Transition q->rpm_status to RPM_RESUMING in blk_pre_runtime_resume() only when it is RPM_SUSPENDED, and call blk_clear_pm_only() in blk_post_runtime_resume() only when old_status is RPM_RESUMING, pairing each clear with a completed runtime suspend. Tested on QEMU ARM64 UFS in SDB and MCQ modes by injecting runtime-resume START STOP UNIT failures on the UFS device well-known LUN, confirming zero pm_only underflows and balanced runtime PM cycles. Fixes: eef1d74bf88f ("PM: runtime: Only set runtime_error on suspend callback failures") Cc: stable@vger.kernel.org # v7.3+ Reviewed-by: Bart Van Assche Signed-off-by: Stanley Jhu Acked-by: Rafael J. Wysocki (Intel) Link: https://patch.msgid.link/20261104112744.1630864-1-stanleyjhu@google.com Signed-off-by: Jens Axboe --- block/blk-pm.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/block/blk-pm.c b/block/blk-pm.c index 8d3e052f91da16..34cc7c5ca04e23 100644 --- a/block/blk-pm.c +++ b/block/blk-pm.c @@ -142,7 +142,8 @@ EXPORT_SYMBOL(blk_post_runtime_suspend); * * Description: * Update the queue's runtime status to RESUMING in preparation for the - * runtime resume of the device. + * runtime resume of the device if the queue is runtime suspended, or keep + * RPM_ACTIVE if a previous failed runtime resume already reactivated it. * * This function should be called near the start of the device's * runtime_resume callback. @@ -153,7 +154,9 @@ void blk_pre_runtime_resume(struct request_queue *q) return; spin_lock_irq(&q->queue_lock); - q->rpm_status = RPM_RESUMING; + /* Keep RPM_ACTIVE if a prior failed resume reactivated the queue. */ + if (q->rpm_status == RPM_SUSPENDED) + q->rpm_status = RPM_RESUMING; spin_unlock_irq(&q->queue_lock); } EXPORT_SYMBOL(blk_pre_runtime_resume); @@ -168,8 +171,8 @@ EXPORT_SYMBOL(blk_pre_runtime_resume); * driver or error handler will need to communicate with the device. * * This function should be called near the end of the device's - * runtime_resume callback to correct queue runtime PM status and re-enable - * peeking requests from the queue. + * runtime_resume callback to mark the queue runtime active and clear + * pm_only if the queue was resuming. */ void blk_post_runtime_resume(struct request_queue *q) { @@ -185,7 +188,7 @@ void blk_post_runtime_resume(struct request_queue *q) pm_request_autosuspend(q->dev); spin_unlock_irq(&q->queue_lock); - if (old_status != RPM_ACTIVE) + if (old_status == RPM_RESUMING) blk_clear_pm_only(q); } EXPORT_SYMBOL(blk_post_runtime_resume); From 553d28925fdea4044bad4ae1e2bf9484ad21f758 Mon Sep 17 00:00:00 2001 From: Guilherme Giacomo Simoes Date: Thu, 12 Nov 2026 07:59:39 -0300 Subject: [PATCH 0881/2102] nbd: Reclassify sockets in the reconnect path Commit d532cddb6c60 ("nbd: Reclassify sockets to avoid lockdep circular dependency") introduced nbd_reclassify_socket() to prevent lockdep false positives when NBD sockets are used in memory reclaim paths. While nbd_add_socket() reclassifies newly added sockets, nbd_genl_reconnect_sock_cb() omitted this call when replacing dead sockets during reconnection. Consequently, reconnected sockets retain the generic socket lockdep class and trigger false-positive lockdep reports. Fix this by reclassifying the replacement socket in nbd_genl_reconnect_sock_cb(). Fixes: d532cddb6c60 ("nbd: Reclassify sockets to avoid lockdep circular dependency") Reported-by: syzbot+d7d72f3d467710442af0@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=d7d72f3d467710442af0 Signed-off-by: Guilherme Giacomo Simoes Reviewed-by: Bart Van Assche Link: https://patch.msgid.link/20261112105939.260856-1-trintaeoitogc@gmail.com Signed-off-by: Jens Axboe --- drivers/block/nbd.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c index ffce519bf00879..b2b27f90a7ed4d 100644 --- a/drivers/block/nbd.c +++ b/drivers/block/nbd.c @@ -1356,6 +1356,7 @@ static int nbd_genl_reconnect_sock_cb(struct nbd_device *nbd, unsigned long arg) sock = nbd_get_socket(nbd, arg, &err); if (!sock) return err; + nbd_reclassify_socket(sock); args = kzalloc_obj(*args); if (!args) { From 495f22c5a99ac38e527294cdc4f3972718b9bee0 Mon Sep 17 00:00:00 2001 From: Mani Tofigh Date: Fri, 6 Nov 2026 11:53:21 -0500 Subject: [PATCH 0882/2102] blk-mq: take quiesce_lock when removing a queue from the tag set Unquiescing a tag set can run the hw queues of a queue whose hctxs were already freed. blk_mq_unquiesce_tagset() walks the tag set's queues under quiesce_lock and rcu_read_lock(). Commit 71ec3c7d6db8 ("blk-mq: quiesce a queue that joins a quiesced tag set") added quiesce_lock to the walks and to adding a queue, but blk_mq_del_queue_tag_set() still removes a queue without it. The hctxs are then freed right away since RCU only keeps the request_queue itself alive: Task A (controller reset) Task B (namespace removal) blk_mq_unquiesce_tagset() /* finds q */ blk_mq_del_queue_tag_set(q) blk_mq_release(q) /* frees the hctxs */ blk_mq_run_hw_queues(q) /* reads freed hctxs */ The window is short. On PREEMPT_RT quiesce_lock is a sleeping lock and the walk can be preempted inside it, which is how it's hit here: [ 399.851277] BUG: KASAN: slab-use-after-free in blk_mq_run_hw_queues+0x4bd/0x550 [ 399.851328] Read of size 8 at addr ff11000003014148 by task kworker/u9:2/116 [ 399.851352] CPU: 1 UID: 0 PID: 116 Comm: kworker/u9:2 Not tainted 7.3.0-16299-g81cb9aa43246 #1 PREEMPT_RT [ 399.851425] Workqueue: nvme-reset-wq nvme_loop_reset_ctrl_work [ 399.851441] Call Trace: [ 399.851457] [ 399.851551] blk_mq_run_hw_queues+0x4bd/0x550 [ 399.851564] blk_mq_unquiesce_tagset+0x128/0x210 [ 399.851576] nvme_loop_reset_ctrl_work+0x78/0x4c0 [ 399.851600] process_one_work+0x92b/0x16d0 [ 399.851660] worker_thread+0x4e6/0xd60 [ 399.851707] kthread+0x300/0x3e0 [ 399.851727] ret_from_fork+0x4f0/0x6f0 [ 399.851776] ret_from_fork_asm+0x1a/0x30 [ 399.851793] ... [ 399.851988] Freed by task 111: [ 399.852040] kfree+0x1b3/0x4b0 [ 399.852050] blk_mq_release+0x400/0x550 [ 399.852060] blk_put_queue+0x94/0x120 [ 399.852068] disk_release+0x1bd/0x3f0 [ 399.852102] nvme_free_ns+0x39/0x270 [ 399.852113] nvme_remove_nsid_range+0x2d1/0x4a0 [ 399.852123] nvme_scan_ns_list+0x2cc/0x390 [ 399.852134] nvme_scan_work+0x421/0x9f0 ... With BLK_CGROUP the disk's root blkg holds the queue until a grace period later, which hides this for NVMe namespaces. It's still open without BLK_CGROUP, and from reading the code also for queues freed without a disk (e.g., SCSI device queues on a UFS host). Take quiesce_lock around the list_del_rcu() as well so that the walk either finishes with a queue before it leaves the list or never sees it, and say so in the comment of quiesce_lock. With the fix, KASAN doesn't report the use-after-free anymore. This bug was identified and confirmed with the help of a deterministic hypervisor currently under development. The C reproducer below however hits it about once every 20 minutes on a PREEMPT_RT kernel. Fixes: 59e25ef2b413 ("block: Use RCU in blk_mq_[un]quiesce_tagset() instead of set->tag_list_lock") Cc: stable@vger.kernel.org Reviewed-by: Mohamed Khalfella Signed-off-by: Mani Tofigh Reviewed-by: Christoph Hellwig Reviewed-by: Nilay Shroff Link: https://patch.msgid.link/20261106-blk-mq-del-quiesce-lock-v2-1-cd4f72a6eb03@columbia.edu Signed-off-by: Jens Axboe --- block/blk-mq.c | 3 +++ include/linux/blk-mq.h | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/block/blk-mq.c b/block/blk-mq.c index 5ae22d55654044..54ccfc43c27c2e 100644 --- a/block/blk-mq.c +++ b/block/blk-mq.c @@ -4354,7 +4354,10 @@ static void blk_mq_del_queue_tag_set(struct request_queue *q) lockdep_assert_held(&set->tag_list_lock); + /* blk_mq_unquiesce_tagset() runs the hctxs, which are not RCU freed */ + spin_lock(&set->quiesce_lock); list_del_rcu(&q->tag_set_list); + spin_unlock(&set->quiesce_lock); if (list_is_singular(&set->tag_list)) { /* just transitioned to unshared */ set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED; diff --git a/include/linux/blk-mq.h b/include/linux/blk-mq.h index 1a2f8d48adc4d7..3c9667854c4650 100644 --- a/include/linux/blk-mq.h +++ b/include/linux/blk-mq.h @@ -524,7 +524,8 @@ enum hctx_type { * @tag_list: List of the request queues that use this tag set. See also * request_queue.tag_set_list. * @quiesce_lock: Serializes blk_mq_[un]quiesce_tagset() against each other - * and against a request queue being added to @tag_list. + * and against a request queue being added to or removed from + * @tag_list. * @quiesce_depth: How often blk_mq_quiesce_tagset() has been called without * blk_mq_unquiesce_tagset(). * @srcu: Use as lock when type of the request queue is blocking From 0659e44ce739ecd856164c75a5325b7959a2921d Mon Sep 17 00:00:00 2001 From: Mikhail Malyshev Date: Wed, 11 Nov 2026 16:27:05 +0000 Subject: [PATCH 0883/2102] io_uring/io-wq: apply the current cpuset to new workers Since commit 84eacf177faa ("io_uring/io-wq: inherit cpuset of cgroup in io worker"), io_wq_create() copies the cpuset of the creating task into wq->cpu_mask, and io_init_new_worker() gives each new worker that copy. A cpuset change, or a move of the task to another cgroup, updates the workers that exist but not the copy, so workers started later run on the CPUs the cgroup had when the io-wq was created, which may since have been given to other tasks. Workers come and go for the life of the io-wq, and a worker that cpuset moved is also retired at its next idle timeout and replaced on the old CPUs. Keep wq->cpu_mask for the affinity of the io-wq itself, all CPUs or the mask set with IORING_REGISTER_IOWQ_AFF, and intersect it with the cpuset of the worker when the worker starts, falling back to the cpuset if the two do not intersect, as __set_cpus_allowed_ptr() does. Use the same mask in the idle exit test, and go back to all CPUs when the registered affinity is removed. Fixes: 84eacf177faa ("io_uring/io-wq: inherit cpuset of cgroup in io worker") Cc: stable@vger.kernel.org Signed-off-by: Mikhail Malyshev Link: https://patch.msgid.link/20261111162705.1150983-1-mike.malyshev@gmail.com Signed-off-by: Jens Axboe --- io_uring/io-wq.c | 44 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/io_uring/io-wq.c b/io_uring/io-wq.c index 52ba4b06b5af3d..9609ae50dbd7a4 100644 --- a/io_uring/io-wq.c +++ b/io_uring/io-wq.c @@ -742,6 +742,34 @@ static bool io_worker_retire(struct io_wq_acct *acct, struct io_worker *worker) return false; } +/* + * The CPUs a worker of @wq runs on: those of the io-wq affinity that the + * worker's cpuset allows, or the cpuset if they have none in common, as the + * scheduler does with a task's requested affinity when its cpuset changes. + * Read the cpuset each time: it can change while the io-wq exists. + */ +static void io_wq_worker_cpus(struct io_wq *wq, struct task_struct *tsk, + struct cpumask *cpus) +{ + cpuset_cpus_allowed(tsk, cpus); + if (cpumask_intersects(cpus, wq->cpu_mask)) + cpumask_and(cpus, cpus, wq->cpu_mask); +} + +/* Is the current worker on a CPU that a new worker would not get? */ +static bool io_wq_worker_off_cpus(struct io_wq *wq) +{ + cpumask_var_t cpus; + bool off; + + if (!alloc_cpumask_var(&cpus, GFP_KERNEL)) + return false; + io_wq_worker_cpus(wq, current, cpus); + off = !cpumask_test_cpu(raw_smp_processor_id(), cpus); + free_cpumask_var(cpus); + return off; +} + static int io_wq_worker(void *data) { struct io_worker *worker = data; @@ -820,8 +848,7 @@ static int io_wq_worker(void *data) } if (!ret) { last_timeout = true; - exit_mask = !cpumask_test_cpu(raw_smp_processor_id(), - wq->cpu_mask); + exit_mask = io_wq_worker_off_cpus(wq); } } @@ -871,9 +898,16 @@ void io_wq_worker_sleeping(struct task_struct *tsk) static void io_init_new_worker(struct io_wq *wq, struct io_wq_acct *acct, struct io_worker *worker, struct task_struct *tsk) { + cpumask_var_t cpus; + tsk->worker_private = worker; worker->task = tsk; - set_cpus_allowed_ptr(tsk, wq->cpu_mask); + /* Without a mask, the worker keeps its creator's CPUs. */ + if (alloc_cpumask_var(&cpus, GFP_KERNEL)) { + io_wq_worker_cpus(wq, tsk, cpus); + set_cpus_allowed_ptr(tsk, cpus); + free_cpumask_var(cpus); + } raw_spin_lock(&acct->workers_lock); hlist_nulls_add_head_rcu(&worker->nulls_node, &acct->free_list); @@ -1370,7 +1404,7 @@ struct io_wq *io_wq_create(unsigned bounded, struct io_wq_data *data) if (!alloc_cpumask_var(&wq->cpu_mask, GFP_KERNEL)) goto err; - cpuset_cpus_allowed(data->task, wq->cpu_mask); + cpumask_copy(wq->cpu_mask, cpu_possible_mask); wq->acct[IO_WQ_ACCT_BOUND].max_workers = bounded; wq->acct[IO_WQ_ACCT_UNBOUND].max_workers = task_rlimit(current, RLIMIT_NPROC); @@ -1592,7 +1626,7 @@ int io_wq_cpu_affinity(struct io_uring_task *tctx, cpumask_var_t mask) else ret = -EINVAL; } else { - cpumask_copy(tctx->io_wq->cpu_mask, allowed_mask); + cpumask_copy(tctx->io_wq->cpu_mask, cpu_possible_mask); } rcu_read_unlock(); From d239710cf3e6bd5fec66766957c3752d9cfbd2c5 Mon Sep 17 00:00:00 2001 From: Md Haris Iqbal Date: Wed, 11 Nov 2026 22:58:36 +0100 Subject: [PATCH 0884/2102] block: Reject unknown status tags in error injection rules tag_to_blk_status() returns BLK_STS_OK both for the "OK" tag and for a tag it does not recognize, so a caller cannot tell the two apart. The block error injection code (which is the sole user of this function currently) relies on error_inject_add() later to reject adding a rule with status=BLK_STS_OK. This is okay for the current state of error injection. The delay option added in the next commit makes the rule with status=OK valid, meaning the function tag_to_blk_status() now needs to explicitly match BLK_STS_OK for it, and fail for a tag it does not recognize. Hence make tag_to_blk_status() take a second param to update the matched status, and return true in case of a successful match. If a match is not found, the function tag_to_blk_status() returns false and *status remains unchanged. A repeated status= where an invalid tag comes first is now rejected instead of being overridden by the later one. Cc: Christoph Hellwig Signed-off-by: Md Haris Iqbal Reviewed-by: Christoph Hellwig Link: https://patch.msgid.link/20261111215838.103356-2-haris.iqbal@linux.dev Signed-off-by: Jens Axboe --- block/blk-core.c | 14 ++++++-------- block/blk.h | 2 +- block/error-injection.c | 7 ++++--- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/block/blk-core.c b/block/blk-core.c index 8836c7028568b0..2ee079c1ce150e 100644 --- a/block/blk-core.c +++ b/block/blk-core.c @@ -226,21 +226,19 @@ const char *blk_status_to_tag(blk_status_t status) return blk_errors[idx].tag; } -blk_status_t tag_to_blk_status(const char *tag) +bool tag_to_blk_status(const char *tag, blk_status_t *status) { int i; for (i = 0; i < ARRAY_SIZE(blk_errors); i++) { if (blk_errors[i].tag && - !strcmp(blk_errors[i].tag, tag)) - return (__force blk_status_t)i; + !strcmp(blk_errors[i].tag, tag)) { + *status = (__force blk_status_t)i; + return true; + } } - /* - * Return BLK_STS_OK for mismatches as this function is intended to - * parse error status values. - */ - return BLK_STS_OK; + return false; } /** diff --git a/block/blk.h b/block/blk.h index 0e38e4b88cf544..105fff157bfbd4 100644 --- a/block/blk.h +++ b/block/blk.h @@ -52,7 +52,7 @@ void blk_free_flush_queue(struct blk_flush_queue *q); const char *blk_status_to_str(blk_status_t status); const char *blk_status_to_tag(blk_status_t status); -blk_status_t tag_to_blk_status(const char *tag); +bool tag_to_blk_status(const char *tag, blk_status_t *status); enum req_op str_to_blk_op(const char *op); bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic); diff --git a/block/error-injection.c b/block/error-injection.c index e14bc4b723efb0..db543fe276308e 100644 --- a/block/error-injection.c +++ b/block/error-injection.c @@ -171,15 +171,16 @@ static int match_op(substring_t *args, enum req_op *op) static int match_status(substring_t *args, blk_status_t *status) { const char *tag; + bool found; tag = match_strdup(args); if (!tag) return -ENOMEM; - *status = tag_to_blk_status(tag); - if (!*status) + found = tag_to_blk_status(tag, status); + if (!found) pr_warn("invalid status '%s'\n", tag); kfree(tag); - return 0; + return found ? 0 : -EINVAL; } static ssize_t blk_error_injection_parse_options(struct gendisk *disk, From 6bd856cc99963b786cb530141745ef733de76cc3 Mon Sep 17 00:00:00 2001 From: Md Haris Iqbal Date: Wed, 11 Nov 2026 22:58:37 +0100 Subject: [PATCH 0885/2102] block: allow error injection rules to delay bios Error injection can only fail a bio today. Add a delay_us option so that a rule can hold a bio back first, to model a slow device. If a matching rule has delay_us set, the bio is held for that long. It is then failed if the rule also has a status, or resubmitted otherwise. The resubmission is done through submit_bio_noacct_nocheck(), which is where the injection hook sits. To avoid the same delay rule being applied to it again, mark the bio with the BIO_ERROR_INJECTED flag as soon as a rule matches. This also prevents bios that are split later and resubmitted from being evaluated for delay (or error injection) again. __bio_clone() does not propagate the flag, so a clone a stacking driver aims at a lower device is still evaluated. The bio is submitted from a workqueue rather than from the timer, because submitting a bio can sleep. A REQ_NOWAIT bio is failed with BLK_STS_AGAIN instead of being delayed. Values above 600 seconds are rejected. Cc: Christoph Hellwig Signed-off-by: Md Haris Iqbal Link: https://patch.msgid.link/20261111215838.103356-3-haris.iqbal@linux.dev Signed-off-by: Jens Axboe --- block/error-injection.c | 143 ++++++++++++++++++++++++++++++++++---- block/error-injection.h | 1 + include/linux/blk_types.h | 1 + 3 files changed, 130 insertions(+), 15 deletions(-) diff --git a/block/error-injection.c b/block/error-injection.c index db543fe276308e..a6de52229ef3be 100644 --- a/block/error-injection.c +++ b/block/error-injection.c @@ -6,9 +6,17 @@ #include #include #include +#include #include "blk.h" #include "error-injection.h" +/* + * Cap the delay so that a typo can't wedge a device for good. This is still + * well beyond the default hung task timeout, which is one of the things a + * delay is useful for triggering. + */ +#define BLK_ERROR_INJECT_MAX_DELAY_US (600 * USEC_PER_SEC) + struct blk_error_inject { struct list_head entry; sector_t start; @@ -18,14 +26,97 @@ struct blk_error_inject { /* only inject every 1 / chance times */ unsigned int chance; + + /* hold the bio for this long before submitting or failing it */ + unsigned int delay_us; +}; + +/* + * A bio held by a delay rule. It does not point back at the rule, so rules + * can be removed while delayed bios are outstanding. The submitter holds the + * bdev open until the bio completes, so the disk and queue stay allocated. + * A delayed bio holds no queue usage counter reference, so it does not hold + * up a queue freeze either. + */ +struct blk_error_inject_delay { + struct delayed_work dwork; + struct bio *bio; + blk_status_t status; }; +static struct workqueue_struct *blk_error_inject_wq; + DEFINE_STATIC_KEY_FALSE(blk_error_injection_enabled); +static void blk_error_inject_fail(struct bio *bio, blk_status_t status) +{ + pr_info_ratelimited("%pg: injecting %s error for %s at sector %llu:%u\n", + bio->bi_bdev->bd_disk->part0, blk_status_to_str(status), + blk_op_str(bio_op(bio)), bio->bi_iter.bi_sector, + bio_sectors(bio)); + bio_endio_status(bio, status); +} + +static void blk_error_inject_delay_work(struct work_struct *work) +{ + struct blk_error_inject_delay *d = container_of(to_delayed_work(work), + struct blk_error_inject_delay, dwork); + struct bio *bio = d->bio; + blk_status_t status = d->status; + + kfree(d); + + if (status != BLK_STS_OK) { + blk_error_inject_fail(bio, status); + return; + } + + /* + * Resubmit. The BIO_ERROR_INJECTED flag ensures that a bio that was + * delayed once skips error injection entirely from here on, including + * any other rule that covers it. + */ + submit_bio_noacct_nocheck(bio, false); +} + +static bool blk_error_inject_delay(struct gendisk *disk, struct bio *bio, + blk_status_t status, unsigned int delay_us) +{ + struct blk_error_inject_delay *d; + + /* fail a bio that can't block, as a real queue would */ + if (bio->bi_opf & REQ_NOWAIT) { + bio_wouldblock_error(bio); + return true; + } + + d = kmalloc_obj(*d, GFP_NOIO); + if (!d) { + pr_warn_ratelimited("%pg: failed to delay %s at sector %llu:%u\n", + disk->part0, blk_op_str(bio_op(bio)), + bio->bi_iter.bi_sector, bio_sectors(bio)); + return false; + } + + pr_info_ratelimited("%pg: delaying %s at sector %llu:%u by %uus\n", + disk->part0, blk_op_str(bio_op(bio)), + bio->bi_iter.bi_sector, bio_sectors(bio), delay_us); + + d->bio = bio; + d->status = status; + INIT_DELAYED_WORK(&d->dwork, blk_error_inject_delay_work); + + queue_delayed_work(blk_error_inject_wq, &d->dwork, + usecs_to_jiffies(delay_us)); + return true; +} + bool __blk_error_inject(struct bio *bio) { struct gendisk *disk = bio->bi_bdev->bd_disk; struct blk_error_inject *inj; + blk_status_t status = BLK_STS_OK; + unsigned int delay_us = 0; rcu_read_lock(); list_for_each_entry_rcu(inj, &disk->error_injection_list, entry) { @@ -45,29 +136,34 @@ bool __blk_error_inject(struct bio *bio) if (inj->chance > 1 && (get_random_u32() % inj->chance) != 0) continue; - pr_info_ratelimited("%pg: injecting %s error for %s at sector %llu:%u\n", - disk->part0, blk_status_to_str(inj->status), - blk_op_str(inj->op), bio->bi_iter.bi_sector, - bio_sectors(bio)); - bio->bi_status = inj->status; - rcu_read_unlock(); - bio_endio(bio); - return true; + status = inj->status; + delay_us = inj->delay_us; + bio_set_flag(bio, BIO_ERROR_INJECTED); + break; } rcu_read_unlock(); - return false; + + if (delay_us && blk_error_inject_delay(disk, bio, status, delay_us)) + return true; + if (status == BLK_STS_OK) + return false; + + blk_error_inject_fail(bio, status); + return true; } static int error_inject_add(struct gendisk *disk, enum req_op op, sector_t start, u64 nr_sectors, blk_status_t status, - unsigned int chance) + unsigned int chance, unsigned int delay_us) { struct blk_error_inject *inj; int error = -EINVAL; if (op == REQ_OP_LAST) return -EINVAL; - if (status == BLK_STS_OK) + if (status == BLK_STS_OK && !delay_us) + return -EINVAL; + if (delay_us > BLK_ERROR_INJECT_MAX_DELAY_US) return -EINVAL; inj = kzalloc_obj(*inj); @@ -86,6 +182,7 @@ static int error_inject_add(struct gendisk *disk, enum req_op op, inj->start = start; inj->status = status; inj->chance = chance; + inj->delay_us = delay_us; pr_debug_ratelimited("%pg: adding %s injection for %s at sector %llu:%llu\n", disk->part0, blk_status_to_str(status), @@ -139,6 +236,7 @@ enum options { Opt_nr_sectors = (1u << 18), Opt_status = (1u << 19), Opt_chance = (1u << 20), + Opt_delay_us = (1u << 21), Opt_invalid, }; @@ -151,6 +249,7 @@ static const match_table_t opt_tokens = { { Opt_nr_sectors, "nr_sectors=%u" }, { Opt_status, "status=%s" }, { Opt_chance, "chance=%u" }, + { Opt_delay_us, "delay_us=%u" }, { Opt_invalid, NULL, }, }; @@ -187,7 +286,7 @@ static ssize_t blk_error_injection_parse_options(struct gendisk *disk, char *options) { enum { Unset, Add, Removeall } action = Unset; - unsigned int option_mask = 0, chance = 1; + unsigned int option_mask = 0, chance = 1, delay_us = 0; enum req_op op = REQ_OP_LAST; u64 start = 0, nr_sectors = 0; blk_status_t status = BLK_STS_OK; @@ -230,6 +329,9 @@ static ssize_t blk_error_injection_parse_options(struct gendisk *disk, if (!error && chance == 0) error = -EINVAL; break; + case Opt_delay_us: + error = match_uint(args, &delay_us); + break; default: pr_warn("unknown parameter or missing value '%s'\n", p); error = -EINVAL; @@ -241,7 +343,7 @@ static ssize_t blk_error_injection_parse_options(struct gendisk *disk, switch (action) { case Add: return error_inject_add(disk, op, start, nr_sectors, status, - chance); + chance, delay_us); case Removeall: if (option_mask & ~Opt_removeall) return -EINVAL; @@ -277,10 +379,11 @@ static int blk_error_injection_show(struct seq_file *s, void *private) rcu_read_lock(); list_for_each_entry_rcu(inj, &disk->error_injection_list, entry) { - seq_printf(s, "%llu:%llu op=%s,status=%s,chance=%u", + seq_printf(s, "%llu:%llu op=%s,status=%s,chance=%u,delay_us=%u", inj->start, inj->end, blk_op_str(inj->op), - blk_status_to_tag(inj->status), inj->chance); + blk_status_to_tag(inj->status), inj->chance, + inj->delay_us); seq_putc(s, '\n'); } rcu_read_unlock(); @@ -315,3 +418,13 @@ void blk_error_injection_exit(struct gendisk *disk) { error_inject_removeall(disk); } + +static int __init blk_error_injection_init_wq(void) +{ + blk_error_inject_wq = alloc_workqueue("blk_error_inject", + WQ_MEM_RECLAIM | WQ_UNBOUND, 0); + if (!blk_error_inject_wq) + panic("Failed to create blk_error_inject wq\n"); + return 0; +} +subsys_initcall(blk_error_injection_init_wq); diff --git a/block/error-injection.h b/block/error-injection.h index 9821d773abab87..8b3809d85e83ea 100644 --- a/block/error-injection.h +++ b/block/error-injection.h @@ -13,6 +13,7 @@ static inline bool blk_error_inject(struct bio *bio) { if (IS_ENABLED(CONFIG_BLK_ERROR_INJECTION) && static_branch_unlikely(&blk_error_injection_enabled) && + !bio_flagged(bio, BIO_ERROR_INJECTED) && test_bit(GD_ERROR_INJECT, &bio->bi_bdev->bd_disk->state)) return __blk_error_inject(bio); return false; diff --git a/include/linux/blk_types.h b/include/linux/blk_types.h index 0cc09b975d8ffb..1a5812fa405299 100644 --- a/include/linux/blk_types.h +++ b/include/linux/blk_types.h @@ -328,6 +328,7 @@ enum { BIO_ZONE_WRITE_PLUGGING, /* bio handled through zone write plugging */ BIO_EMULATES_ZONE_APPEND, /* bio emulates a zone append operation */ BIO_COMPLETE_IN_TASK, /* complete bi_end_io() in task context */ + BIO_ERROR_INJECTED, /* error injection rules already applied */ BIO_FLAG_LAST }; From 5a29cfaf51105039d156dd8a61d2783e8b653667 Mon Sep 17 00:00:00 2001 From: Md Haris Iqbal Date: Wed, 11 Nov 2026 22:58:38 +0100 Subject: [PATCH 0886/2102] Documentation: block: document error injection delay feature Document the delay_us option: the delay happens above the driver, a delayed bio is not run through the rules again, and holding a bio back reorders it against bios submitted later. Cc: Christoph Hellwig Signed-off-by: Md Haris Iqbal Reviewed-by: Christoph Hellwig Link: https://patch.msgid.link/20261111215838.103356-4-haris.iqbal@linux.dev Signed-off-by: Jens Axboe --- Documentation/block/error-injection.rst | 39 +++++++++++++++++++++---- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/Documentation/block/error-injection.rst b/Documentation/block/error-injection.rst index 81f31af82e65db..3c86defddb806a 100644 --- a/Documentation/block/error-injection.rst +++ b/Documentation/block/error-injection.rst @@ -7,9 +7,9 @@ Configurable Error Injection Overview -------- -Configurable error injection allows injecting specific block layer status codes -for sector ranges of a block device. Errors can be injected unconditionally, or -with a given probability. +Configurable error injection allows injecting delays and/or specific block +layer status codes for sector ranges of a block device by adding rules. The +rules can be configured to trigger unconditionally, or with a given probability. To use configurable error injection, CONFIG_BLK_ERROR_INJECTION must be enabled. @@ -34,15 +34,36 @@ op= block layer operation this rule applies to. This uses the XYZ for each REQ_OP_XYZ operation, e.g. READ, WRITE or DISCARD. Mandatory. status= Status to return. This uses XYZ for each BLK_STS_XYZ - code, e.g. IOERR or MEDIUM. Mandatory. + code, e.g. IOERR or MEDIUM. Mandatory unless delay_us + is given. start= First block layer sector the rule applies to. Optional, defaults to 0. nr_sectors= Number of sectors this rule applies. Optional, defaults to the remainder of the device. -chance= Only return a failure with a likelihood of 1/chance. +chance= Only apply the rule with a likelihood of 1/chance. Optional, defaults to 1 (always). +delay_us= Hold the bio back for this many microseconds. Without + status the bio is then submitted to the device as + usual. With status it is failed once the delay has + expired. Bios with REQ_NOWAIT set fail with + BLK_STS_AGAIN. Optional, defaults to 0 (no delay). + Values above 600 seconds are rejected. =================== ======================================================= +Delays +------ + +A delayed bio is held above the driver, so the device never sees a slow I/O. +A delay does not reach the blk-mq timeout handler or SCSI error handling. + +A bio that matched a delay rule is not evaluated against the rules again, even +after it is split and resubmitted internally. Removing a rule does not release +bios it is already delaying. + +Holding a bio back reorders it against bios submitted later. On zoned devices +this breaks sequential write ordering and the block layer fails the +out-of-order writes, so only delay reads there. + Example ------- @@ -54,6 +75,14 @@ Return BLK_STS_MEDIUM for every write to /dev/nvme0n1: $ echo 'add,op=WRITE,start=0,status=MEDIUM' > /sys/kernel/debug/block/nvme0n1/error_injection +Delay every read of /dev/nvme0n1 by 10 milliseconds, then issue it normally: + + $ echo 'add,op=READ,delay_us=10000' > /sys/kernel/debug/block/nvme0n1/error_injection + +Fail one in 100 writes with BLK_STS_TIMEOUT, but only after 30 seconds: + + $ echo 'add,op=WRITE,status=TIMEOUT,chance=100,delay_us=30000000' > /sys/kernel/debug/block/nvme0n1/error_injection + Remove all rules for /dev/nvme0n1: $ echo 'removeall' > /sys/kernel/debug/block/nvme0n1/error_injection From 69a040c424309f8c18cbb8009c4ca0536af58611 Mon Sep 17 00:00:00 2001 From: Ovidiu Bunea Date: Tue, 27 Oct 2026 09:49:59 -0400 Subject: [PATCH 0887/2102] drm/amd/display: Add support for more PSP footer sizes [why & how] PSP footer size may be as big as 1932 bytes. Add a check for this size so that the DMUB FW meta can be properly located. Cc: Michael Strauss Signed-off-by: Ovidiu Bunea Signed-off-by: Roman Li Reviewed-by: Mario Limonciello (AMD) Tested-by: Mario Limonciello (AMD) Signed-off-by: Alex Deucher (cherry picked from commit a6836fcbb5b22968019256025321d655b78bc49c) --- drivers/gpu/drm/amd/display/dmub/dmub_srv.h | 2 + .../gpu/drm/amd/display/dmub/src/dmub_srv.c | 41 ++++++++++++------- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/amd/display/dmub/dmub_srv.h b/drivers/gpu/drm/amd/display/dmub/dmub_srv.h index 17579ff2e1bf7e..84f825c924bc1f 100644 --- a/drivers/gpu/drm/amd/display/dmub/dmub_srv.h +++ b/drivers/gpu/drm/amd/display/dmub/dmub_srv.h @@ -76,6 +76,8 @@ #define PSP_HEADER_BYTES_256 0x100 // 256 bytes #define PSP_FOOTER_BYTES_256 0x100 // 256 bytes +#define PSP_FOOTER_BYTES_512 0x200 // 512 bytes +#define PSP_FOOTER_BYTES_1932 0x78C // 1932 bytes /* Forward declarations */ struct dmub_srv; diff --git a/drivers/gpu/drm/amd/display/dmub/src/dmub_srv.c b/drivers/gpu/drm/amd/display/dmub/src/dmub_srv.c index 41b14b137643d5..72fc28feefb26f 100644 --- a/drivers/gpu/drm/amd/display/dmub/src/dmub_srv.c +++ b/drivers/gpu/drm/amd/display/dmub/src/dmub_srv.c @@ -173,30 +173,43 @@ dmub_srv_get_fw_meta_info_from_raw_fw(struct dmub_srv_fw_meta_info_params *param uint32_t inst_const_size_temp = params->inst_const_size; /* First try custom psp footer size, if present */ - if (params->custom_psp_footer_size) { - params->inst_const_size -= params->custom_psp_footer_size; + if (params->custom_psp_footer_size && inst_const_size_temp > params->custom_psp_footer_size) { + params->inst_const_size = inst_const_size_temp - params->custom_psp_footer_size; fw_info = dmub_get_fw_meta_info(params); if (fw_info) { memcpy(fw_info_out, fw_info, sizeof(*fw_info)); return DMUB_STATUS_OK; } - params->inst_const_size = inst_const_size_temp; } /* Try 256-byte psp footer size */ - params->inst_const_size -= PSP_FOOTER_BYTES_256; - fw_info = dmub_get_fw_meta_info(params); - if (fw_info) { - memcpy(fw_info_out, fw_info, sizeof(*fw_info)); - return DMUB_STATUS_OK; + if (inst_const_size_temp > PSP_FOOTER_BYTES_256) { + params->inst_const_size = inst_const_size_temp - PSP_FOOTER_BYTES_256; + fw_info = dmub_get_fw_meta_info(params); + if (fw_info) { + memcpy(fw_info_out, fw_info, sizeof(*fw_info)); + return DMUB_STATUS_OK; + } } - /* Try 512-byte psp footer size - final attempt */ - params->inst_const_size -= PSP_FOOTER_BYTES_256; // 256 bytes already subtracted, subtract 256 again - fw_info = dmub_get_fw_meta_info(params); - if (fw_info) { - memcpy(fw_info_out, fw_info, sizeof(*fw_info)); - return DMUB_STATUS_OK; + /* Try 512-byte psp footer size */ + if (inst_const_size_temp > PSP_FOOTER_BYTES_512) { + params->inst_const_size = inst_const_size_temp - PSP_FOOTER_BYTES_512; + fw_info = dmub_get_fw_meta_info(params); + if (fw_info) { + memcpy(fw_info_out, fw_info, sizeof(*fw_info)); + return DMUB_STATUS_OK; + } + } + + /* Try 1932-byte psp footer size */ + if (inst_const_size_temp > PSP_FOOTER_BYTES_1932) { + params->inst_const_size = inst_const_size_temp - PSP_FOOTER_BYTES_1932; + fw_info = dmub_get_fw_meta_info(params); + if (fw_info) { + memcpy(fw_info_out, fw_info, sizeof(*fw_info)); + return DMUB_STATUS_OK; + } } /* Restore original inst_const_size and subtract default PSP footer size - default behaviour */ From b99cc7665fc83c0418a5f0d4af59ea120de84e38 Mon Sep 17 00:00:00 2001 From: Suresh Guttula Date: Wed, 11 Nov 2026 21:09:38 +0530 Subject: [PATCH 0888/2102] drm/amdgpu: bypass IMU ucode loading for GC 11 APU For GC 11,IMU ucode is part of IFWI and ASP would load it by default. Signed-off-by: Suresh Guttula Reviewed-by: Mario Limonciello (AMD) Tested-by: Mario Limonciello (AMD) # gfx1170, gfx1103 Signed-off-by: Alex Deucher (cherry picked from commit 68107f081efeac9eaeaade028e55a5facef1c5b3) --- drivers/gpu/drm/amd/amdgpu/imu_v11_0.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c b/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c index a409911939d381..b6c4ae35ca03a4 100644 --- a/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c +++ b/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c @@ -56,16 +56,25 @@ static int imu_v11_0_init_microcode(struct amdgpu_device *adev) int err; const struct imu_firmware_header_v1_0 *imu_hdr; struct amdgpu_firmware_info *info = NULL; + bool imu_in_ifwi; + enum amdgpu_ucode_required required; DRM_DEBUG("\n"); + /* On GFX 11 APUs, ASP loads the IFWI IMU ucode by default. */ + imu_in_ifwi = adev->firmware.load_type == AMDGPU_FW_LOAD_PSP && + (adev->flags & AMD_IS_APU); + required = imu_in_ifwi ? AMDGPU_UCODE_OPTIONAL : AMDGPU_UCODE_REQUIRED; + amdgpu_ucode_ip_version_decode(adev, GC_HWIP, ucode_prefix, sizeof(ucode_prefix)); if (amdgpu_is_kicker_fw(adev)) - err = amdgpu_ucode_request(adev, &adev->gfx.imu_fw, AMDGPU_UCODE_REQUIRED, + err = amdgpu_ucode_request(adev, &adev->gfx.imu_fw, required, "amdgpu/%s_imu_kicker.bin", ucode_prefix); else - err = amdgpu_ucode_request(adev, &adev->gfx.imu_fw, AMDGPU_UCODE_REQUIRED, + err = amdgpu_ucode_request(adev, &adev->gfx.imu_fw, required, "amdgpu/%s_imu.bin", ucode_prefix); + if (err == -ENODEV && imu_in_ifwi) + return 0; if (err) goto out; From 4f9280c8db69bc807c6c6c616f1b9853ca9144c7 Mon Sep 17 00:00:00 2001 From: Ryan Roberts Date: Fri, 13 Nov 2026 14:50:15 +0000 Subject: [PATCH 0889/2102] arm64: cpufeature: Remove Neoverse-V3/AE from the BBML3 allow list Neoverse-V3 and Neoverse-V3AE erratum 3053180 can cause a load or store to livelock when mapping size changes without break-before-make or when contiguous hints are programmed inconsistently. The erratum was previously reported as fixed in r0p2. On that basis, commit 5aa4b625762e ("arm64: Add BBM Level 2 cpu feature") allowed Neoverse-V3 from r0p2, and commit 8fca3852e33d ("arm64: cpufeature: add Neoverse-V3AE to BBML2 allow list") did the same for Neoverse-V3AE. The updated SDENs, MP168 v11 for Neoverse-V3 and MP172 v12 for Neoverse-V3AE, dated 9 June 2026, list r0p0, r0p1 and r0p2 as affected and the erratum as open. There is no fixed revision on which to base either allow-list entry. Remove both entries so these CPUs observe break-before-make, and record the workaround in the silicon errata registry. Fixes: 5aa4b625762e ("arm64: Add BBM Level 2 cpu feature") Fixes: 8fca3852e33d ("arm64: cpufeature: add Neoverse-V3AE to BBML2 allow list") Cc: stable@vger.kernel.org Link: https://support.arm.com/documentation/109231/11-0/?lang=en Link: https://support.arm.com/documentation/109704/12-0/?lang=en Signed-off-by: Ryan Roberts Signed-off-by: Catalin Marinas --- Documentation/arch/arm64/silicon-errata.rst | 4 ++++ arch/arm64/kernel/cpufeature.c | 2 -- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Documentation/arch/arm64/silicon-errata.rst b/Documentation/arch/arm64/silicon-errata.rst index dc4144ac895bf9..598acae27f9bc7 100644 --- a/Documentation/arch/arm64/silicon-errata.rst +++ b/Documentation/arch/arm64/silicon-errata.rst @@ -253,10 +253,14 @@ stable kernels. +----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V2 | #4193787 | ARM64_ERRATUM_4118414 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Neoverse-V3 | #3053180 | N/A | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V3 | #3312417 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V3 | #4193784 | ARM64_ERRATUM_4118414 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Neoverse-V3AE | #3053180 | N/A | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V3AE | #3312417 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V3AE | #4193784 | ARM64_ERRATUM_4118414 | diff --git a/arch/arm64/kernel/cpufeature.c b/arch/arm64/kernel/cpufeature.c index c9c9a6889455c2..a79f010fb54750 100644 --- a/arch/arm64/kernel/cpufeature.c +++ b/arch/arm64/kernel/cpufeature.c @@ -2013,8 +2013,6 @@ bool cpu_supports_bbml3(void) /* CPUs that support BBML3 but dont advertise through ID_AA64MMFR2_EL1 */ static const struct midr_range supports_bbml3_list[] = { MIDR_REV_RANGE(MIDR_CORTEX_X4, 0, 3, 0xf), - MIDR_REV_RANGE(MIDR_NEOVERSE_V3, 0, 2, 0xf), - MIDR_REV_RANGE(MIDR_NEOVERSE_V3AE, 0, 2, 0xf), MIDR_ALL_VERSIONS(MIDR_NVIDIA_OLYMPUS), MIDR_ALL_VERSIONS(MIDR_NVIDIA_RIGEL), MIDR_ALL_VERSIONS(MIDR_AMPERE1), From c6ba16d8157b05e0a05b773422f5d3c5941e22de Mon Sep 17 00:00:00 2001 From: Ryan Roberts Date: Fri, 13 Nov 2026 14:50:16 +0000 Subject: [PATCH 0890/2102] arm64: cpufeature: Remove Cortex-X4 from the BBML3 allow list Cortex-X4 erratum 3043263 can cause a load or store to livelock when mapping size changes without break-before-make or when contiguous hints are programmed inconsistently. The erratum was previously reported as fixed in r0p3. On that basis, commit 5aa4b625762e ("arm64: Add BBM Level 2 cpu feature") added Cortex-X4 from r0p3. The updated Cortex-X4 SDEN v13, dated 18 June 2026, lists r0p0, r0p1, r0p2 and r0p3 as affected and the erratum as open. Remove the entry so Cortex-X4 observes break-before-make, and record the workaround in the silicon errata registry. Fixes: 5aa4b625762e ("arm64: Add BBM Level 2 cpu feature") Cc: stable@vger.kernel.org Link: https://support.arm.com/documentation/109148/13-0/?lang=en Signed-off-by: Ryan Roberts Signed-off-by: Catalin Marinas --- Documentation/arch/arm64/silicon-errata.rst | 2 ++ arch/arm64/kernel/cpufeature.c | 1 - 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Documentation/arch/arm64/silicon-errata.rst b/Documentation/arch/arm64/silicon-errata.rst index 598acae27f9bc7..bffaa46c664b3a 100644 --- a/Documentation/arch/arm64/silicon-errata.rst +++ b/Documentation/arch/arm64/silicon-errata.rst @@ -209,6 +209,8 @@ stable kernels. +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-X3 | #4193786 | ARM64_ERRATUM_4118414 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-X4 | #3043263 | N/A | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-X4 | #3194386 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-X4 | #4118414 | ARM64_ERRATUM_4118414 | diff --git a/arch/arm64/kernel/cpufeature.c b/arch/arm64/kernel/cpufeature.c index a79f010fb54750..a8a1a73ba1b801 100644 --- a/arch/arm64/kernel/cpufeature.c +++ b/arch/arm64/kernel/cpufeature.c @@ -2012,7 +2012,6 @@ bool cpu_supports_bbml3(void) { /* CPUs that support BBML3 but dont advertise through ID_AA64MMFR2_EL1 */ static const struct midr_range supports_bbml3_list[] = { - MIDR_REV_RANGE(MIDR_CORTEX_X4, 0, 3, 0xf), MIDR_ALL_VERSIONS(MIDR_NVIDIA_OLYMPUS), MIDR_ALL_VERSIONS(MIDR_NVIDIA_RIGEL), MIDR_ALL_VERSIONS(MIDR_AMPERE1), From b059e957d07b3cab92eef4656988244043f5769a Mon Sep 17 00:00:00 2001 From: Ben Cressey Date: Wed, 11 Nov 2026 15:26:04 -0800 Subject: [PATCH 0891/2102] arm64: kexec: use a typed entry to fix kCFI oops An arm64 Linux kernel built with CONFIG_CFI=y oopses after "Bye!" on every kexec that relocates the image. Crash images load in place and are not affected. The oops reproduces under QEMU: Unable to handle kernel paging request at virtual address 00000000544bfffc pc : machine_kexec+0x104/0x274 Code: d5182008 d5033fdf aa1303e0 f9418a68 (b85fc110) b85fc110 is "ldur w16, [x8, #-4]", the kCFI check's load of the type hash in front of the callee. Commit efc2d0f20a9d ("arm64: kexec: keep MMU enabled during kexec relocation") made machine_kexec() call the control page's copy of arm64_relocate_new_kernel() indirectly, while TTBR0 maps only that page. The copy starts at the page's first byte, so the load faults. SYM_CODE_START() also gives the routine no hash. SYM_TYPED_FUNC_START() emits the hash inside .kexec_relocate.text, and machine_kexec_post_load() already copies that whole section, at most 4 KiB, to the page's start, so the mapped page holds both hash and entry. The ASSERT from commit dc4824faa265 ("arm64: avoid executing padding bytes during kexec / hibernation") kept the entry first, since C branched to the page's start. Relax it, so the entry need only be in the section. Fix by typing the routine with SYM_TYPED_FUNC_START() and a C prototype, and entering the copy at the symbol's offset in the section. The code is Kees Cook's, as posted in review, with two comments and the ASSERT message reworded. An LLM diagnosed the oops. Fixes: efc2d0f20a9d ("arm64: kexec: keep MMU enabled during kexec relocation") Cc: stable@vger.kernel.org Suggested-by: Kees Cook Link: https://lore.kernel.org/linux-arm-kernel/202609241804.BB23BF10@keescook/ Signed-off-by: Ben Cressey Signed-off-by: Catalin Marinas --- arch/arm64/include/asm/kexec.h | 2 ++ arch/arm64/kernel/machine_kexec.c | 7 +++++-- arch/arm64/kernel/relocate_kernel.S | 11 +++++++---- arch/arm64/kernel/vmlinux.lds.S | 5 +++-- 4 files changed, 17 insertions(+), 8 deletions(-) diff --git a/arch/arm64/include/asm/kexec.h b/arch/arm64/include/asm/kexec.h index 892e5bebda957b..0be042ec22c1fc 100644 --- a/arch/arm64/include/asm/kexec.h +++ b/arch/arm64/include/asm/kexec.h @@ -100,6 +100,8 @@ void cpu_soft_restart(unsigned long el2_switch, unsigned long entry, unsigned long arg0, unsigned long arg1, unsigned long arg2); +void arm64_relocate_new_kernel(struct kimage *kimage); + int machine_kexec_post_load(struct kimage *image); #define machine_kexec_post_load machine_kexec_post_load #endif diff --git a/arch/arm64/kernel/machine_kexec.c b/arch/arm64/kernel/machine_kexec.c index 48f343704cb540..24366b5b325969 100644 --- a/arch/arm64/kernel/machine_kexec.c +++ b/arch/arm64/kernel/machine_kexec.c @@ -147,9 +147,12 @@ int machine_kexec_post_load(struct kimage *kimage) kimage->arch.ttbr1 = __pa(trans_pgd); kimage->arch.zero_page = __pa_symbol(empty_zero_page); + /* Copy the whole section: a kCFI hash may precede the entry point */ reloc_size = __relocate_new_kernel_end - __relocate_new_kernel_start; memcpy(reloc_code, __relocate_new_kernel_start, reloc_size); - kimage->arch.kern_reloc = __pa(reloc_code); + kimage->arch.kern_reloc = __pa(reloc_code) + + ((unsigned long)arm64_relocate_new_kernel - + (unsigned long)__relocate_new_kernel_start); rc = trans_pgd_idmap_page(&info, &kimage->arch.ttbr0, &kimage->arch.t0sz, reloc_code); if (rc) @@ -204,7 +207,7 @@ void machine_kexec(struct kimage *kimage) restart(is_hyp_nvhe(), kimage->start, kimage->arch.dtb_mem, 0, 0); } else { - void (*kernel_reloc)(struct kimage *kimage); + typeof(arm64_relocate_new_kernel) *kernel_reloc; if (is_hyp_nvhe()) __hyp_set_vectors(kimage->arch.el2_vectors); diff --git a/arch/arm64/kernel/relocate_kernel.S b/arch/arm64/kernel/relocate_kernel.S index 6cb4209f5dab56..064db5856bba30 100644 --- a/arch/arm64/kernel/relocate_kernel.S +++ b/arch/arm64/kernel/relocate_kernel.S @@ -8,6 +8,7 @@ * Pasha Tatashin */ +#include #include #include @@ -32,11 +33,13 @@ * new image to its final location. To assure that the * arm64_relocate_new_kernel routine which does that copy is not overwritten, * all code and data needed by arm64_relocate_new_kernel must be between the - * symbols arm64_relocate_new_kernel and arm64_relocate_new_kernel_end. The - * machine_kexec() routine will copy arm64_relocate_new_kernel to the kexec + * symbols __relocate_new_kernel_start and __relocate_new_kernel_end. The + * machine_kexec_post_load() routine will copy that whole region to the kexec * safe memory that has been set up to be preserved during the copy operation. + * + * Called indirectly by machine_kexec(), this routine needs a kCFI type hash. */ -SYM_CODE_START(arm64_relocate_new_kernel) +SYM_TYPED_FUNC_START(arm64_relocate_new_kernel) /* * The kimage structure isn't allocated specially and may be clobbered * during relocation. We must load any values we need from it prior to @@ -98,4 +101,4 @@ SYM_CODE_START(arm64_relocate_new_kernel) mov x2, xzr mov x3, xzr br x28 /* Jumps from el1 */ -SYM_CODE_END(arm64_relocate_new_kernel) +SYM_FUNC_END(arm64_relocate_new_kernel) diff --git a/arch/arm64/kernel/vmlinux.lds.S b/arch/arm64/kernel/vmlinux.lds.S index 1869b44ae19095..c95243a8b24ec0 100644 --- a/arch/arm64/kernel/vmlinux.lds.S +++ b/arch/arm64/kernel/vmlinux.lds.S @@ -440,6 +440,7 @@ ASSERT(swapper_pg_dir - tramp_pg_dir == TRAMP_SWAPPER_OFFSET, ASSERT(__relocate_new_kernel_end - __relocate_new_kernel_start <= SZ_4K, "kexec relocation code is bigger than 4 KiB") ASSERT(KEXEC_CONTROL_PAGE_SIZE >= SZ_4K, "KEXEC_CONTROL_PAGE_SIZE is broken") -ASSERT(__relocate_new_kernel_start == arm64_relocate_new_kernel, - "kexec control page does not start with arm64_relocate_new_kernel") +ASSERT(arm64_relocate_new_kernel >= __relocate_new_kernel_start && + arm64_relocate_new_kernel < __relocate_new_kernel_end, + "kexec relocation code does not contain arm64_relocate_new_kernel") #endif From fe779a359d40ece9060932467b5dbe464d43f00e Mon Sep 17 00:00:00 2001 From: Guangshuo Li Date: Wed, 8 Jul 2026 18:46:17 +0800 Subject: [PATCH 0892/2102] zonefs: check multiplication overflow in zonefs_fname_to_fno() The change referenced by the Fixes tag added overflow checking for the addition used while converting a zone file name to a zone number. However, the digit value and decimal shift are still computed with unchecked signed long multiplications. For sufficiently long numeric names, shift or digit can overflow before check_add_overflow() sees the value, leaving the parser with an already corrupted intermediate result. Check the digit and shift multiplications as well. Only advance the shift when another digit remains, so valid boundary values are not rejected due to an unused final shift update. Fixes: 3a8389d42bdf ("zonefs: handle integer overflow in zonefs_fname_to_fno") Signed-off-by: Guangshuo Li Signed-off-by: Damien Le Moal --- fs/zonefs/super.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/fs/zonefs/super.c b/fs/zonefs/super.c index b97f1f2b8dda24..0fe2d277dcda07 100644 --- a/fs/zonefs/super.c +++ b/fs/zonefs/super.c @@ -615,10 +615,12 @@ static long zonefs_fname_to_fno(const struct qstr *fname) c = *rname; if (!isdigit(c)) return -ENOENT; - digit = (c - '0') * shift; + if (check_mul_overflow((long)(c - '0'), shift, &digit)) + return -ENOENT; if (check_add_overflow(fno, digit, &fno)) return -ENOENT; - shift *= 10; + if (i + 1 < len && check_mul_overflow(shift, 10L, &shift)) + return -ENOENT; } return fno; From 2a5bd7a2bbb787483cd69ecf099e2b591e3633b2 Mon Sep 17 00:00:00 2001 From: Suyuan Wang Date: Mon, 16 Nov 2026 04:06:23 +0000 Subject: [PATCH 0893/2102] smb: client: fail SMB2 responses with a bad signature smb2_check_receive() checks the response signature when signing is on, but a failed check is only logged: rc = smb2_verify_signature(&rqst, server); if (rc) cifs_server_dbg(VFS, "SMB signature verification returned ...", rc); ... return map_smb2_to_linux_error(mid->resp_buf, log_error); The status from the response is returned as usual, and the caller goes on to use a response whose signature is wrong. This is the path for synchronous and compound requests and for smb2_writev_callback(). On a signed but unencrypted connection, anyone who can modify the traffic can change e.g. a directory listing or file attributes, and the client accepts it. Return the verification error instead. That alone is not enough for compound_send_recv(), which still hands the response buffer to the caller after check_receive() fails. smb2_compound_op() then maps the status from that buffer again and copies the payload out, and other callers look at the buffer on error too, e.g. smb2_open_file() parses a symlink target out of a STATUS_STOPPED_ON_SYMLINK response. So also mark the mid MID_RESPONSE_MALFORMED, and have compound_send_recv() handle it like a mid in a bad state: mark the earlier mids cancelled, so that a CREATE which did succeed gets its handle closed, and don't pass any response on. Unlike the SMB1 fix in commit dc96f01d54cc ("smb: client: terminate session upon failed client required signing"), don't reconnect: this runs in the thread that sent the request, and only cifsd should call cifs_reconnect(). And fail the request whichever side required signing, since a response with a bad signature can't be trusted either way. Found with a static analysis tool and checked by hand. Reported-by: Daniel Birtwhistle Closes: https://lore.kernel.org/linux-cifs/SN4PR22MB28883DAF57E0B4D4BFB1C22AEEC42@SN4PR22MB2888.namprd22.prod.outlook.com/ Fixes: 3c1bf7e48e9e ("CIFS: Enable signing in SMB2") Cc: stable@vger.kernel.org Co-developed-by: Kaixuan Li Signed-off-by: Kaixuan Li Signed-off-by: Suyuan Wang Signed-off-by: Paulo Alcantara --- fs/smb/client/smb2transport.c | 7 +++++-- fs/smb/client/transport.c | 5 +++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/fs/smb/client/smb2transport.c b/fs/smb/client/smb2transport.c index 080864b24a0c50..c63d66b01bda2d 100644 --- a/fs/smb/client/smb2transport.c +++ b/fs/smb/client/smb2transport.c @@ -711,9 +711,12 @@ smb2_check_receive(struct mid_q_entry *mid, struct TCP_Server_Info *server, int rc; rc = smb2_verify_signature(&rqst, server); - if (rc) + if (rc) { cifs_server_dbg(VFS, "SMB signature verification returned error = %d\n", - rc); + rc); + mid->mid_state = MID_RESPONSE_MALFORMED; + return rc; + } } return map_smb2_to_linux_error(mid->resp_buf, log_error); diff --git a/fs/smb/client/transport.c b/fs/smb/client/transport.c index c51f99d7be4b31..375b821ab3eacd 100644 --- a/fs/smb/client/transport.c +++ b/fs/smb/client/transport.c @@ -1124,6 +1124,11 @@ compound_send_recv(const unsigned int xid, struct cifs_ses *ses, rc = server->ops->check_receive(mid[i], server, flags & CIFS_LOG_ERROR); + if (mid[i]->mid_state != MID_RESPONSE_READY) { + cifs_mark_compound_mids_cancelled(mid, i); + num_processed = 0; + goto out; + } num_processed = i + 1; } From c966757ff80fe8407e2e3acdd720964769ddf937 Mon Sep 17 00:00:00 2001 From: Zhan Xusheng Date: Thu, 6 Aug 2026 10:20:43 +0800 Subject: [PATCH 0894/2102] ext4: fix readdir position truncation on 32-bit kernels In ext4_readdir(), the directory cookie position is rebuilt with ctx->pos = (ctx->pos & ~(sb->s_blocksize - 1)) | offset; `ctx->pos` is loff_t (signed 64-bit), while `sb->s_blocksize` is unsigned long. On 32-bit kernels unsigned long is 32-bit, so the mask ~(sb->s_blocksize - 1) is computed as a 32-bit unsigned value (e.g. 0xfffff000 for a 4 KiB block size). In the AND expression with the 64-bit `ctx->pos`, that unsigned operand is zero-extended to 64 bits per the usual arithmetic conversions, yielding 0x00000000fffff000. The high 32 bits of `ctx->pos` are silently cleared, even though directory size is allowed to exceed 4 GiB on 32-bit (s_maxbytes for ext4 is many TiB). When readdir() crosses the 4 GiB boundary on a 32-bit kernel the position is reset back into the first 4 GiB block, making the re-validation path re-enumerate already-returned dirents indefinitely. ext4_readdir() reaches this linear path for non-indexed directories, and as the fallback after ext4_dx_readdir() returns ERR_BAD_DX_DIR, so a directory large enough to cross 4 GiB can hit it. This is the same class of bug that commit 3dce5bb82c97 ("exfat: Fix bitwise operation having different size") fixed in exfat. Cast the operand to loff_t so the mask is 64-bit before the AND: ctx->pos = (ctx->pos & ~((loff_t)sb->s_blocksize - 1)) | offset; 64-bit kernels are unaffected (unsigned long is 64-bit there, no truncation occurs). The truncation was confirmed with a freestanding 32-bit test program mirroring the kernel expression: input ctx->pos = 0x100000100 produces output 0x100 with the unfixed expression and 0x100000100 with the cast. Fixes: ac27a0ec112a ("[PATCH] ext4: initial copy of files from ext3") Cc: stable@vger.kernel.org Signed-off-by: Zhan Xusheng Reviewed-by: Jan Kara Link: https://patch.msgid.link/20260806022044.167962-2-zhanxusheng@xiaomi.com Signed-off-by: Theodore Ts'o --- fs/ext4/dir.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/ext4/dir.c b/fs/ext4/dir.c index 8d7b81e6948e72..e921e12acbd749 100644 --- a/fs/ext4/dir.c +++ b/fs/ext4/dir.c @@ -256,7 +256,7 @@ static int ext4_readdir(struct file *file, struct dir_context *ctx) sb->s_blocksize); } offset = i; - ctx->pos = (ctx->pos & ~(sb->s_blocksize - 1)) + ctx->pos = (ctx->pos & ~((loff_t)sb->s_blocksize - 1)) | offset; info->cookie = inode_query_iversion(inode); } From ef7ad718020c6af4c5f62015e0d02407e5faf8a5 Mon Sep 17 00:00:00 2001 From: Hemanth Selam Date: Mon, 7 Sep 2026 12:10:46 +0530 Subject: [PATCH 0895/2102] ext4: fix typos in comments Fix typos in comments, reported by scripts/checkpatch.pl using the misspelling list in scripts/spelling.txt. Only touches comments, no code changes. Assisted-by: Cursor:claude-opus-5 Signed-off-by: Hemanth Selam Reviewed-by: Jan Kara Link: https://patch.msgid.link/20260907064046.36515-1-hemanth.selam@gmail.com Signed-off-by: Theodore Ts'o --- fs/ext4/extents.c | 2 +- fs/ext4/inode.c | 2 +- fs/ext4/mballoc.c | 8 ++++---- fs/ext4/mballoc.h | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index ad0d80e33f6090..3fa93db7e7ee3d 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -3186,7 +3186,7 @@ int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex) * @handle: the journal handle * @inode: the file inode * @path: the path to the extent - * @split: the logical block where the extent is splitted. + * @split: the logical block where the extent is split. * @flags: flags used to insert new extent to extent tree. * * diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 10cd85d4c721b2..52cddb88a0929a 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -2289,7 +2289,7 @@ static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk, * @bh - buffer we should start processing from * @lblk - logical number of the block in the file corresponding to @bh * - * Walk through page buffers from @bh upto @head (exclusive) and either submit + * Walk through page buffers from @bh up to @head (exclusive) and either submit * the page for IO if all buffers in this page were mapped and there's no * accumulated extent of buffers to map or add buffers in the page to the * extent of buffers to map. The function returns 1 if the caller can continue diff --git a/fs/ext4/mballoc.c b/fs/ext4/mballoc.c index a15285224cdf6e..3fe0bad560fce9 100644 --- a/fs/ext4/mballoc.c +++ b/fs/ext4/mballoc.c @@ -234,7 +234,7 @@ * * there are two types of preallocations: * - inode - * assiged to specific inode and can be used for this inode only. + * assigned to specific inode and can be used for this inode only. * it describes part of inode's space preallocated to specific * physical blocks. any block from that preallocated can be used * independent. the descriptor just tracks number of blocks left @@ -2324,11 +2324,11 @@ static void ext4_mb_check_limits(struct ext4_allocation_context *ac, * stop the scan and use it immediately * * * If free extent found is smaller than goal, then keep retrying - * upto a max of sbi->s_mb_max_to_scan times (default 200). After + * up to a max of sbi->s_mb_max_to_scan times (default 200). After * that stop scanning and use whatever we have. * * * If free extent found is bigger than goal, then keep retrying - * upto a max of sbi->s_mb_min_to_scan times (default 10) before + * up to a max of sbi->s_mb_min_to_scan times (default 10) before * stopping the scan and using the extent. * * @@ -3027,7 +3027,7 @@ ext4_mb_regular_allocator(struct ext4_allocation_context *ac) * is greater than equal to the sbi_s_mb_order2_reqs * You can tune it via /sys/fs/ext4//mb_order2_req * We also support searching for power-of-two requests only for - * requests upto maximum buddy size we have constructed. + * requests up to maximum buddy size we have constructed. */ if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) { if (is_power_of_2(ac->ac_g_ex.fe_len)) diff --git a/fs/ext4/mballoc.h b/fs/ext4/mballoc.h index 39333ce72cbd50..571d9bd9381070 100644 --- a/fs/ext4/mballoc.h +++ b/fs/ext4/mballoc.h @@ -86,9 +86,9 @@ #define MB_DEFAULT_LINEAR_SCAN_THRESHOLD 16 /* - * The maximum order upto which CR_BEST_AVAIL_LEN can trim a particular + * The maximum order up to which CR_BEST_AVAIL_LEN can trim a particular * allocation request. Example, if we have an order 7 request and max trim order - * of 3, we can trim this request upto order 4. + * of 3, we can trim this request up to order 4. */ #define MB_DEFAULT_BEST_AVAIL_TRIM_ORDER 3 From bb94c7a5d31b9a5ea2237ef53d050ddd29e2cf74 Mon Sep 17 00:00:00 2001 From: ThangNN99 Date: Mon, 7 Sep 2026 22:50:17 +0700 Subject: [PATCH 0896/2102] ext4: avoid buffer/folio lock inversion in __ext4_get_inode_loc() __ext4_get_inode_loc() looks up the inode bitmap bh while holding the lock on the inode table bh: __ext4_get_inode_loc() lock_buffer(itable block) sb_getblk(inode bitmap block) __find_get_block_nonatomic() folio_lock(bdev folio for bitmap block) whereas block_read_full_folio() (e.g. userspace reading the bdev inode directly) takes the same two locks in the opposite order: block_read_full_folio() folio_lock(some folio) lock_buffer(bh in folio) With blocksize == foliosize this can't overlap, but once foliosize > blocksize the inode table block can land in the same folio as the inode bitmap block, and the two orders deadlock on each other's lock. Use the non-blocking cache lookup for the bitmap probe instead; a miss already falls back to make_io exactly as before. Only ext4_reserve_inode_write() reaches this probe with a real inode (ext4_iget() passes NULL, which skips it), and it normally runs right after the read that loaded that same inode, so the itable buffer is still warm and the early "already uptodate" return skips the probe. The window needs the folio reclaimed between load and writeback, which is why this is rare and why syzbot's bisection could not pin it down. Reproduction status: root-caused from source and confirmed against both syzbot stacks (inode.c:__ext4_get_inode_loc vs. buffer.c:block_read_full_folio); the lock_buffer()/reserve_inode_write path was exercised live (orphan cleanup on mount) to confirm reachability and to confirm this patch introduces no regression there. The deadlock itself was not reproduced locally -- doing so needs the itable buffer genuinely reclaimed between inode load and writeback, which a small single-shot QEMU test doesn't naturally produce. Reported-by: syzbot+03afbb29537f0336b7ad@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=03afbb29537f0336b7ad Reviewed-by: Jan Kara Signed-off-by: ThangNN99 Link: https://patch.msgid.link/20260907155017.75543-1-ngocthang2710.1999@gmail.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/inode.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 52cddb88a0929a..b23280198bc776 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -5759,8 +5759,12 @@ static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino, start = inode_offset & ~(inodes_per_block - 1); - /* Is the inode bitmap in cache? */ - bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp)); + /* + * Is the inode bitmap in cache? Non-blocking lookup: bh above + * is locked, and blocking here would folio_lock() against a + * block_read_full_folio() that locks bh the other way round. + */ + bitmap_bh = sb_find_get_block(sb, ext4_inode_bitmap(sb, gdp)); if (unlikely(!bitmap_bh)) goto make_io; From 3b6aee59883c3056bb0a5e7491f9dc995bbac964 Mon Sep 17 00:00:00 2001 From: Yichong Chen Date: Wed, 9 Sep 2026 11:35:42 +0800 Subject: [PATCH 0897/2102] ext4: clear journal restart indication after inserting extent ext4_datasem_ensure_credits() returns 1 when it successfully restarts the transaction. finish_range() leaves that value in retval when the subsequent ext4_ext_insert_extent() succeeds. Its callers interpret any nonzero return as a migration failure, so they stop building the extent tree and take the cleanup path instead of completing the migration. Before ext4_ext_insert_extent() was changed to return a path, its integer return value overwrote the restart indication. Restore that behavior with PTR_ERR_OR_ZERO(), preserving insertion errors and returning zero on success. Fixes: f7d1331f16a8 ("ext4: get rid of ppath in ext4_ext_insert_extent()") Signed-off-by: Yichong Chen Reviewed-by: Jan Kara Link: https://patch.msgid.link/20260909033542.3087876-1-chenyichong@uniontech.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/migrate.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/fs/ext4/migrate.c b/fs/ext4/migrate.c index 09931d3ba2c6a8..8ad1fe0a5d6a7f 100644 --- a/fs/ext4/migrate.c +++ b/fs/ext4/migrate.c @@ -53,8 +53,7 @@ static int finish_range(handle_t *handle, struct inode *inode, if (retval < 0) goto err_out; path = ext4_ext_insert_extent(handle, inode, path, &newext, 0); - if (IS_ERR(path)) - retval = PTR_ERR(path); + retval = PTR_ERR_OR_ZERO(path); err_out: up_write((&EXT4_I(inode)->i_data_sem)); ext4_free_ext_path(path); From 7d7c94601664d19cea230601f377e5fb8a2ec4fe Mon Sep 17 00:00:00 2001 From: Fan Wu Date: Wed, 9 Sep 2026 11:37:03 +0000 Subject: [PATCH 0898/2102] ext4: fix discard work use-after-free on failed mount ext4_put_super() shuts the journal down before it releases the mballoc structures, but the failure unwind of __ext4_fill_super() runs the two steps in the opposite order: failed_mount6 calls ext4_mb_release(), which flushes sbi->s_discard_work, and the journal is destroyed only later, just above failed_mount3a. With -o discard, that journal destroy re-arms the work after the flush: ext4_journal_destroy() calls ext4_force_commit(), and the commit callback, registered once mballoc is initialized, queues s_discard_work whenever the discard option is set, even with an empty freed-data list. A running transaction can be live at that point: replaying the orphan list is the easiest way to get one, and the quota paths on failed_mount8/failed_mount9 can leave one too. The final force commit is not necessarily a no-op. Nothing drains s_discard_work after that point: failed_mount3 flushes only s_sb_upd_work and the s_err_report timer, and ext4_fill_super() then frees sbi with a plain kfree() through ext4_free_sbi(). If the system_dfl_wq worker is delayed across the rest of the unwind, ext4_discard_work() then accesses the freed sbi, first through sbi->s_sb and then while taking sbi->s_md_lock. This is the pattern fixed for the s_err_report timer in commit 0ce160c5bdb6 ("ext4: fix timer use-after-free on failed mount"): async state armed after the unwind's last drain point. Force the commit at failed_mount6, before ext4_mb_release(), so that the discard work its commit callback queues is normally already pending when the flush_work() in ext4_mb_release() runs. disable_work_sync() there then makes this airtight: it also drains an instance the flush missed, and no later commit, including the force commit inside the journal destroy further down the unwind, can requeue the work. The journal destroy stays at its existing position. This issue was found by an in-house static analysis tool. Fixes: 55cdd0af2bc5 ("ext4: get discard out of jbd2 commit kthread contex") Cc: stable@vger.kernel.org # v6.10+ Reviewed-by: Jan Kara Assisted-by: Codex:gpt-5.6 Co-developed-by: Song Li Signed-off-by: Song Li Signed-off-by: Fan Wu Link: https://patch.msgid.link/20260909113703.698544-1-fanwu01@zju.edu.cn Signed-off-by: Theodore Ts'o --- fs/ext4/mballoc.c | 2 ++ fs/ext4/super.c | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/fs/ext4/mballoc.c b/fs/ext4/mballoc.c index 3fe0bad560fce9..cf728da45ad741 100644 --- a/fs/ext4/mballoc.c +++ b/fs/ext4/mballoc.c @@ -3896,6 +3896,8 @@ void ext4_mb_release(struct super_block *sb) * wait the discard work to drain all of ext4_free_data */ flush_work(&sbi->s_discard_work); + /* Prevent the later journal teardown from requeueing discard work. */ + disable_work_sync(&sbi->s_discard_work); WARN_ON_ONCE(!list_empty(&sbi->s_discard_list)); group_info = rcu_access_pointer(sbi->s_group_info); diff --git a/fs/ext4/super.c b/fs/ext4/super.c index 9cae52471dee95..f0c46d50d15a19 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -5819,6 +5819,12 @@ failed_mount8: __maybe_unused failed_mount7: ext4_unregister_li_request(sb); failed_mount6: + /* + * We can have a running transaction from orphan replay or quota + * setup. Commit it so that discard work after commit runs before + * we shutdown mballoc. + */ + ext4_force_commit(sb); ext4_mb_release(sb); ext4_flex_groups_free(sbi); failed_mount5: From 1f4899b2b822ece9204517be61855a203cdd59b5 Mon Sep 17 00:00:00 2001 From: shuo chen <1289151713@qq.com> Date: Thu, 10 Sep 2026 11:26:14 +0800 Subject: [PATCH 0899/2102] ext4: update the pre-check in ext4_find_inline_data_nolock The pre-check in ext4_find_inline_data_nolock should be kept consistent with that in ext4_xattr_ibody_find, so as to avoid unnecessary operations. Signed-off-by: shuo chen <1289151713@qq.com> Reviewed-by: Jan Kara Link: https://patch.msgid.link/tencent_0EDE840F0C8186D030DEAF5A95B8BE54350A@qq.com Signed-off-by: Theodore Ts'o --- fs/ext4/inline.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/ext4/inline.c b/fs/ext4/inline.c index ceee69a66482bc..9f6a4d13b9abc6 100644 --- a/fs/ext4/inline.c +++ b/fs/ext4/inline.c @@ -151,7 +151,7 @@ int ext4_find_inline_data_nolock(struct inode *inode) }; int error; - if (EXT4_I(inode)->i_extra_isize == 0) + if (!EXT4_INODE_HAS_XATTR_SPACE(inode)) return 0; error = ext4_get_inode_loc(inode, &is.iloc); From b0a3f2c102e8c718e03be45f831e279ba9f6b112 Mon Sep 17 00:00:00 2001 From: Yichong Chen Date: Thu, 10 Sep 2026 11:40:00 +0800 Subject: [PATCH 0900/2102] ext4: cap migration extent length at EXT_INIT_MAX_LEN update_extent_range() keeps merging physically and logically contiguous blocks without limiting the accumulated range. The maximum length of an initialized extent is EXT_INIT_MAX_LEN, because the MSB of the 16-bit ee_len field is used to mark unwritten extents. finish_range() can therefore store a range longer than EXT_INIT_MAX_LEN in ee_len. A range of 32769 blocks is stored as 0x8001, which ext4_ext_is_unwritten() treats as an unwritten extent and ext4_ext_get_actual_len() reports as 1 block, so the migrated file silently loses its data. Stop merging once the accumulated range reaches EXT_INIT_MAX_LEN, so migration creates several valid extents instead. Fixes: c14c6fd5c56a ("ext4: Add EXT4_IOC_MIGRATE ioctl") Signed-off-by: Yichong Chen Reviewed-by: Jan Kara Link: https://patch.msgid.link/20260910034000.3155420-1-chenyichong@uniontech.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/migrate.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fs/ext4/migrate.c b/fs/ext4/migrate.c index 8ad1fe0a5d6a7f..e053b5ab0a8c91 100644 --- a/fs/ext4/migrate.c +++ b/fs/ext4/migrate.c @@ -70,7 +70,8 @@ static int update_extent_range(handle_t *handle, struct inode *inode, */ if (lb->first_pblock && (lb->last_pblock+1 == pblock) && - (lb->last_block+1 == lb->curr_block)) { + (lb->last_block+1 == lb->curr_block) && + (lb->last_block - lb->first_block + 1 < EXT_INIT_MAX_LEN)) { lb->last_pblock = pblock; lb->last_block = lb->curr_block; lb->curr_block++; From 82e2a5743b6ada7c77e072ca67c9ec55e9e18923 Mon Sep 17 00:00:00 2001 From: Yichong Chen Date: Thu, 10 Sep 2026 13:29:27 +0800 Subject: [PATCH 0901/2102] ext4: don't clobber the migration error in ext4_ext_migrate() ext4_ext_migrate() records the failure of the migration in retval, but ext4_journal_ensure_credits() overwrites it: it returns 0 when the handle has enough credits or the transaction could be extended, and 1 when the transaction had to be restarted. A failed migration is therefore reported as success, and a restart leaks the internal value 1 to userspace through EXT4_IOC_MIGRATE and FS_IOC_SETFLAGS. Fixes: a413036791d0 ("ext4: Provide function to handle transaction restarts") Signed-off-by: Yichong Chen Reviewed-by: Jan Kara Link: https://patch.msgid.link/20260910052927.3161092-1-chenyichong@uniontech.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/migrate.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/fs/ext4/migrate.c b/fs/ext4/migrate.c index e053b5ab0a8c91..e2ae57cdc71862 100644 --- a/fs/ext4/migrate.c +++ b/fs/ext4/migrate.c @@ -410,7 +410,7 @@ static int free_ext_block(handle_t *handle, struct inode *inode) int ext4_ext_migrate(struct inode *inode) { handle_t *handle; - int retval = 0, i; + int retval = 0, err, i; __le32 *i_data; struct ext4_inode_info *ei; struct inode *tmp_inode = NULL; @@ -567,9 +567,12 @@ int ext4_ext_migrate(struct inode *inode) } /* We mark the tmp_inode dirty via ext4_ext_tree_init. */ - retval = ext4_journal_ensure_credits(handle, 1, 0); - if (retval < 0) + err = ext4_journal_ensure_credits(handle, 1, 0); + if (err < 0) { + if (!retval) + retval = err; goto out_stop; + } /* * Mark the tmp_inode as of size zero */ From 291cccad437eafafab0357c5a3a990f995c96e67 Mon Sep 17 00:00:00 2001 From: Pankaj Raghav Date: Thu, 10 Sep 2026 12:08:29 +0200 Subject: [PATCH 0902/2102] ext4: set awu_max_opt to awu_max commit 5d894321c49e ("fs: add atomic write unit max opt to statx") added atomic write max optimal to statx. As XFS can support large atomic writes through SW, max_opt exposes the value that will be HW accelerated atomics. As ext4 does not support SW atomics, set awu_max_opt to awu_max. Signed-off-by: Pankaj Raghav Reviewed-by: Jan Kara Reviewed-by: Ritesh Harjani (IBM) Reviewed-by: Ojaswin Mujoo Link: https://patch.msgid.link/20260910100829.2532894-1-p.raghav@samsung.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/inode.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index b23280198bc776..f3c3e6d03f5247 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -7248,7 +7248,8 @@ int ext4_getattr(const struct mnt_idmap *idmap, const struct path *path, awu_max = sbi->s_awu_max; } - generic_fill_statx_atomic_writes(stat, awu_min, awu_max, 0); + generic_fill_statx_atomic_writes(stat, awu_min, awu_max, + awu_max); } flags = ei->i_flags & EXT4_FL_USER_VISIBLE; From 2a837444e911ae75e24e71b1c2a32b6d6e1ef8b9 Mon Sep 17 00:00:00 2001 From: Jonas Zhou Date: Fri, 11 Sep 2026 11:31:13 +0800 Subject: [PATCH 0903/2102] ext4: move orphan tracking away from journal state In the tested x86-64 layout, s_journal and s_ext4_flags share a cache line with s_orphan_lock and s_orphan. Legacy orphan-list updates invalidate the same line used by unrelated journal and inode paths. Move s_orphan_lock, s_orphan and s_orphan_info together below s_journal_triggers. This separates orphan-list writes from journal and flag readers while keeping the related fields in logical groups. Add a comment identifying the orphan tracking group and preserve the existing member comments. On a system with two Xeon Silver 4208 processors and a filesystem without orphan_file enabled, repeated tests against v7.3-rc2 recorded mean throughput increases of 11.06% for stress-ng dnotify and 35.93% for unlink. Tests with orphan_file enabled showed no clear throughput change within the observed boot-to-boot variation. perf c2c shows remote HITM samples on the original shared line, but none on the separate journal line after the change. Local HITM samples and orphan-lock contention remain. Suggested-by: Jan Kara Link: https://lore.kernel.org/all/575wyoks3ldokhrg6v43rxwsegaecod4bgrpbii6jeczy7czbi@a3yq26u52orp/ Signed-off-by: Jonas Zhou Reviewed-by: Jan Kara Link: https://patch.msgid.link/67ae57ef2ee3ac27ab844c22594351c83142d86f.1789097450.git.jonaszhou@zhaoxin.com Signed-off-by: Theodore Ts'o --- fs/ext4/ext4.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index f38fec3167fbd0..8386e85d29644c 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -1647,10 +1647,6 @@ struct ext4_sb_info { /* Journaling */ struct journal_s *s_journal; unsigned long s_ext4_flags; /* Ext4 superblock flags */ - struct mutex s_orphan_lock; /* Protects on disk list changes */ - struct list_head s_orphan; /* List of orphaned inodes in on disk - list */ - struct ext4_orphan_info s_orphan_info; unsigned long s_commit_interval; u32 s_max_batch_time; u32 s_min_batch_time; @@ -1791,6 +1787,12 @@ struct ext4_sb_info { /* Journal triggers for checksum computation */ struct ext4_journal_trigger s_journal_triggers[EXT4_JOURNAL_TRIGGER_COUNT]; + /* Orphan inode tracking */ + struct mutex s_orphan_lock; /* Protects on disk list changes */ + struct list_head s_orphan; /* List of orphaned inodes in on disk + list */ + struct ext4_orphan_info s_orphan_info; + /* Ratelimit ext4 messages. */ struct ratelimit_state s_err_ratelimit_state; struct ratelimit_state s_warning_ratelimit_state; From b91ad39f29ceeee3e3d37eedff6b7c912855623c Mon Sep 17 00:00:00 2001 From: "Rafael J. Wysocki" Date: Tue, 17 Nov 2026 20:09:45 +0100 Subject: [PATCH 0904/2102] ACPI: PM: Avoid initializing power management for absent devices Commit 2f4ddf2bd1ba ("ACPI: scan: Stop calling acpi_bus_init_power() early") removed a device presence check from acpi_bus_init_power() which in some cases causes power management to be initialized for an ACPI device object and never used going forward. That in turn may prevent power management from working as expected for other devices. Namely, if a given ACPI device object is not enabled according to its _STA, find_child_checks() will return an error for it which will prevent it from being used as an ACPI companion for a PCI device. Thus if acpi_device_init_power() initializes power management for it and its initial power state turns out to be different from D3cold, it may stay in that power state forever. If it has power resources and they are "on" during the initialization, they may be reference-counted and never turned off. If they are shared with other devices, they will prevent power from going down after attempting to put the other devices into low-power states. To prevent that from happening, restore the device presence check in acpi_bus_init_power(), but also adjust find_child_checks() to return an error for absent devices (instead of doing that for disabled devices) in accordance with acpi_bus_init_power() and the existing check in acpi_bus_attach(). Fixes: 2f4ddf2bd1ba ("ACPI: scan: Stop calling acpi_bus_init_power() early") Reported-by: Alan Borzeszkowski Tested-by: Alan Borzeszkowski Signed-off-by: Rafael J. Wysocki Tested-by: Mika Westerberg Reviewed-by: Mika Westerberg Link: https://patch.msgid.link/13013440.O9o76ZdvQC@rafael.j.wysocki Signed-off-by: Rafael J. Wysocki --- drivers/acpi/device_pm.c | 15 +++++++++++++-- drivers/acpi/glue.c | 8 ++------ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/drivers/acpi/device_pm.c b/drivers/acpi/device_pm.c index 76104f715efa11..d975700936e87f 100644 --- a/drivers/acpi/device_pm.c +++ b/drivers/acpi/device_pm.c @@ -365,14 +365,25 @@ int acpi_bus_init_power(struct acpi_device *device) * fails, ACPI power management will not be used for the device going * forward. */ + if (!acpi_device_is_present(device)) { + acpi_handle_debug(device->handle, + "Device not present, ACPI PM disabled\n"); + result = -ENXIO; + goto fail; + } + result = acpi_device_init_power(device); if (result) { - device->flags.power_manageable = 0; - device->power.state = ACPI_D_STATE_INVALID; acpi_handle_info(device->handle, "Initial power state undetermined, ACPI PM disabled\n"); + goto fail; } + return 0; + +fail: + device->flags.power_manageable = 0; + device->power.state = ACPI_D_STATE_INVALID; return result; } diff --git a/drivers/acpi/glue.c b/drivers/acpi/glue.c index 0959f58cb77c65..4e8616d2e5c8dd 100644 --- a/drivers/acpi/glue.c +++ b/drivers/acpi/glue.c @@ -108,14 +108,10 @@ static bool acpi_dev_has_children(struct acpi_device *adev) static int find_child_checks(struct acpi_device *adev, bool check_children) { - unsigned long long sta; - acpi_status status; - if (check_children && !acpi_dev_has_children(adev)) return -ENODEV; - status = acpi_evaluate_integer(adev->handle, "_STA", NULL, &sta); - if (status == AE_NOT_FOUND) { + if (!acpi_has_method(adev->handle, METHOD_NAME__STA)) { /* * Special case: backlight device objects without _STA are * preferred to other objects with the same _ADR value, because @@ -127,7 +123,7 @@ static int find_child_checks(struct acpi_device *adev, bool check_children) return FIND_CHILD_MIN_SCORE; } - if (ACPI_FAILURE(status) || !(sta & ACPI_STA_DEVICE_ENABLED)) + if (!acpi_device_is_present(adev)) return -ENODEV; /* From a739c9192173c0437ed3c76f87f5a39532ef9fe1 Mon Sep 17 00:00:00 2001 From: Karl Mehltretter Date: Sun, 8 Nov 2026 20:20:41 +0100 Subject: [PATCH 0905/2102] parisc: irq: Trace hardirq state in do_cpu_irq_mask() intr_extint calls do_cpu_irq_mask() with PSW[I] already clear. Since commit 044d0d6de9f5 ("lockdep: Only trace IRQ edges"), its local_irq_disable() then skips trace_hardirqs_off(), and lockdep assertions fail in the timer tick: WARNING: kernel/rcu/tree.c:2739 at rcu_sched_clock_irq+0x618/0x1f84 The return to a context with PSW[I] set has not been annotated since TRACE_IRQFLAGS_SUPPORT was enabled. Annotate both transitions. Fixes: 366dd4ea9d5f ("parisc: Fix ftrace function tracer") Signed-off-by: Karl Mehltretter Cc: stable@vger.kernel.org # v5.9+ Signed-off-by: Helge Deller --- arch/parisc/kernel/irq.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/arch/parisc/kernel/irq.c b/arch/parisc/kernel/irq.c index dff66be65d2900..d9f6cb04e4bcf6 100644 --- a/arch/parisc/kernel/irq.c +++ b/arch/parisc/kernel/irq.c @@ -497,7 +497,7 @@ asmlinkage void do_cpu_irq_mask(struct pt_regs *regs) #endif old_regs = set_irq_regs(regs); - local_irq_disable(); + trace_hardirqs_off(); irq_enter_rcu(); eirr_val = mfctl(23) & cpu_eiem & per_cpu(local_ack_eiem, cpu); @@ -535,6 +535,8 @@ asmlinkage void do_cpu_irq_mask(struct pt_regs *regs) out: irq_exit_rcu(); set_irq_regs(old_regs); + if (!irqs_disabled_flags(regs->gr[0])) + trace_hardirqs_on(); return; set_out: From e9c14351f84f2ddf4aae2914979c0378bc14460a Mon Sep 17 00:00:00 2001 From: Karl Mehltretter Date: Sat, 14 Nov 2026 19:02:50 +0100 Subject: [PATCH 0906/2102] parisc: Fix register corruption in 32-bit dynamic ftrace The 32-bit dynamic ftrace trampoline allocates a 64-byte frame. ftrace_caller() saves %r26 at offset 20, which overlaps the third argument's spill slot for ftrace_function_trampoline(). In the failing build, GCC spills org_sp_gr3 into that slot, overwriting saved %r26 with the original stack pointer. Tracing preempt_count_add() then passes that pointer as val and corrupts the preempt count. Allocate two frames on 32-bit, as 64-bit already does, and update the generated trampoline instruction to match. Fixes: 6ca6366220ed ("parisc: add dynamic ftrace") Cc: stable@vger.kernel.org Signed-off-by: Karl Mehltretter Signed-off-by: Helge Deller --- arch/parisc/kernel/entry.S | 4 ---- arch/parisc/kernel/ftrace.c | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/arch/parisc/kernel/entry.S b/arch/parisc/kernel/entry.S index e04c5d806c1051..b0728dbee53d71 100644 --- a/arch/parisc/kernel/entry.S +++ b/arch/parisc/kernel/entry.S @@ -1949,11 +1949,7 @@ ENDPROC_CFI(mcount) #ifdef CONFIG_DYNAMIC_FTRACE -#ifdef CONFIG_64BIT #define FTRACE_FRAME_SIZE (2*FRAME_SIZE) -#else -#define FTRACE_FRAME_SIZE FRAME_SIZE -#endif ENTRY_CFI(ftrace_caller, caller,frame=FTRACE_FRAME_SIZE,CALLS,SAVE_RP,SAVE_SP) ftrace_caller: .global ftrace_caller diff --git a/arch/parisc/kernel/ftrace.c b/arch/parisc/kernel/ftrace.c index 10fd5b3e63e757..963a741faa42d9 100644 --- a/arch/parisc/kernel/ftrace.c +++ b/arch/parisc/kernel/ftrace.c @@ -146,7 +146,7 @@ int ftrace_make_call(struct dyn_ftrace *rec, unsigned long addr) #else u32 ftrace_trampoline[] = { (u32)addr, - 0x6fc10080, /* stw,ma r1,40(sp) */ + 0x6fc10100, /* stw,ma r1,80(sp) */ 0x48213fd1, /* ldw -18(r1),r1 */ 0xe820c002, /* bv,n r0(r1) */ 0xe83f1fdf, /* b,l,n .-c,r1 */ From b1939b201353d803f09a8eb07aa69e44f8441701 Mon Sep 17 00:00:00 2001 From: Mohamed Ahmed Date: Wed, 18 Nov 2026 01:43:50 +0400 Subject: [PATCH 0907/2102] drm/nouveau: do not return early from a synchronous VM_BIND A synchronous VM_BIND waits for its job with an interruptible wait and ignores the result. On a signal the ioctl returns 0 while the job is still queued. Userspace can then use the new mappings before the page tables are written, and the channel can take an MMU fault. Wait uninterruptibly. A synchronous job takes no syncobjs, so only the jobs queued before it on the same scheduler can delay it. Fixes: b88baab82871 ("drm/nouveau: implement new VM_BIND uAPI") Cc: stable@vger.kernel.org Signed-off-by: Mohamed Ahmed Tested-by: Thomas Andersen Reviewed-by: Dave Airlie Signed-off-by: Dave Airlie Link: https://patch.msgid.link/20261117214352.337961-2-mohamedahmedegypt2001@gmail.com --- drivers/gpu/drm/nouveau/nouveau_sched.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/nouveau/nouveau_sched.c b/drivers/gpu/drm/nouveau/nouveau_sched.c index b3f02c490ecb67..680ddffefca1ee 100644 --- a/drivers/gpu/drm/nouveau/nouveau_sched.c +++ b/drivers/gpu/drm/nouveau/nouveau_sched.c @@ -328,7 +328,11 @@ nouveau_job_submit(struct nouveau_job *job) mutex_unlock(&sched->mutex); if (done_fence) { - dma_fence_wait(done_fence, true); + /* The job is queued and its VA space changes are applied. It + * can neither be restarted nor reported as failed, so wait + * until it has run. + */ + dma_fence_wait(done_fence, false); dma_fence_put(done_fence); } From 4ffab70118f8691ee68c1a24091a36c16957b6dd Mon Sep 17 00:00:00 2001 From: Mohamed Ahmed Date: Wed, 18 Nov 2026 01:43:51 +0400 Subject: [PATCH 0908/2102] drm/nouveau/bar: take the GSP-RM flush pointer from the BAR2 io_mapping r535_bar_new_() maps the first page of BAR2 with ioremap(), to flush BAR2 writes with a read while flushFBZero is not mapped. On x86 with PAT, a mapping that overlaps an existing one gets its type. The instmem io_mapping is created later, so with GSP-RM it is also mapped UC- and its writes are not write-combined. Take the flush pointer from the io_mapping. A new bar2.oneinit hook sets it up once the BAR2 page tables are bootstrapped and the io_mapping exists. Fixes: 34e27b90552a ("nouveau/instmem: use iomapping interface for instmem handling") Cc: stable@vger.kernel.org Signed-off-by: Mohamed Ahmed Tested-by: Thomas Andersen Reviewed-by: Dave Airlie Signed-off-by: Dave Airlie Link: https://patch.msgid.link/20261117214352.337961-3-mohamedahmedegypt2001@gmail.com --- .../gpu/drm/nouveau/nvkm/subdev/bar/gf100.c | 6 ++++ .../gpu/drm/nouveau/nvkm/subdev/bar/priv.h | 1 + .../drm/nouveau/nvkm/subdev/gsp/rm/r535/bar.c | 32 ++++++++++++++----- .../drm/nouveau/nvkm/subdev/instmem/nv50.c | 8 +++++ .../drm/nouveau/nvkm/subdev/instmem/priv.h | 3 ++ 5 files changed, 42 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/bar/gf100.c b/drivers/gpu/drm/nouveau/nvkm/subdev/bar/gf100.c index a1fa1b0c895437..6950801d2e0304 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/bar/gf100.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/bar/gf100.c @@ -133,6 +133,12 @@ gf100_bar_oneinit(struct nvkm_bar *base) if (ret) return ret; + if (bar->base.func->bar2.oneinit) { + ret = bar->base.func->bar2.oneinit(&bar->base); + if (ret) + return ret; + } + bar->base.subdev.oneinit = true; nvkm_bar_bar2_init(bar->base.subdev.device); } diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/bar/priv.h b/drivers/gpu/drm/nouveau/nvkm/subdev/bar/priv.h index d0168e0b78fb74..5774bfa8d96d5d 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/bar/priv.h +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/bar/priv.h @@ -16,6 +16,7 @@ struct nvkm_bar_func { void (*init)(struct nvkm_bar *); struct { + int (*oneinit)(struct nvkm_bar *); void (*init)(struct nvkm_bar *); void (*fini)(struct nvkm_bar *); void (*wait)(struct nvkm_bar *); diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/bar.c b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/bar.c index fae08ac3b18c73..9b907d9e80afee 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/bar.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/bar.c @@ -24,9 +24,11 @@ #include #include #include -#include +#include #include +#include + #include "nvrm/bar.h" #include "nvrm/rpcfn.h" @@ -65,6 +67,25 @@ r535_bar_bar2_update_pde(struct nvkm_gsp *gsp, u8 page_shift, u64 pdbe) return nvkm_gsp_rpc_wr(gsp, rpc, NVKM_GSP_RPC_REPLY_RECV); } +static int +r535_bar_bar2_oneinit(struct nvkm_bar *bar) +{ + struct io_mapping *iomap = nv50_instmem_bar2_iomap(bar->subdev.device->imem); + + if (!iomap) + return -ENOMEM; + + /* BAR2 writes are flushed by a read. While flushFBZero is not mapped, + * read the first page of the BAR2 io_mapping. + */ + bar->flushBAR2PhysMode = io_mapping_map_wc(iomap, 0, PAGE_SIZE); + if (!bar->flushBAR2PhysMode) + return -ENOMEM; + + bar->flushBAR2 = bar->flushBAR2PhysMode; + return 0; +} + static void r535_bar_bar2_fini(struct nvkm_bar *bar) { @@ -155,7 +176,7 @@ r535_bar_dtor(struct nvkm_bar *bar) nvkm_memory_unref(&bar->flushFBZero); if (bar->flushBAR2PhysMode) - iounmap(bar->flushBAR2PhysMode); + io_mapping_unmap(bar->flushBAR2PhysMode); kfree(bar->func); return data; @@ -178,6 +199,7 @@ r535_bar_new_(const struct nvkm_bar_func *hw, struct nvkm_device *device, rm->bar1.fini = r535_bar_bar1_fini; rm->bar1.wait = r535_bar_bar1_wait; rm->bar1.vmm = hw->bar1.vmm; + rm->bar2.oneinit = r535_bar_bar2_oneinit; rm->bar2.init = r535_bar_bar2_init; rm->bar2.fini = r535_bar_bar2_fini; rm->bar2.wait = r535_bar_bar2_wait; @@ -191,12 +213,6 @@ r535_bar_new_(const struct nvkm_bar_func *hw, struct nvkm_device *device, } *pbar = bar; - bar->flushBAR2PhysMode = ioremap(device->func->resource_addr(device, NVKM_BAR2_INST), PAGE_SIZE); - if (!bar->flushBAR2PhysMode) - return -ENOMEM; - - bar->flushBAR2 = bar->flushBAR2PhysMode; - gf100_bar(*pbar)->bar2_halve = true; return 0; } diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c b/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c index 22b0fde6ba346d..1b4be4b1f0bb3c 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c @@ -436,6 +436,14 @@ nv50_instmem_dtor(struct nvkm_instmem *base) return imem; } +struct io_mapping * +nv50_instmem_bar2_iomap(struct nvkm_instmem *base) +{ + struct nv50_instmem *imem = nv50_instmem(base); + + return imem->iomap.size ? &imem->iomap : NULL; +} + static const struct nvkm_instmem_func nv50_instmem = { .dtor = nv50_instmem_dtor, diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/priv.h b/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/priv.h index b423f01f5fcd1f..88990adda76651 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/priv.h +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/priv.h @@ -4,6 +4,8 @@ #define nvkm_instmem(p) container_of((p), struct nvkm_instmem, subdev) #include +struct io_mapping; + struct nvkm_instmem_func { void *(*dtor)(struct nvkm_instmem *); int (*oneinit)(struct nvkm_instmem *); @@ -27,6 +29,7 @@ int nv50_instobj_new(struct nvkm_instmem *, u32 size, u32 align, bool zero, int nv50_instobj_wrap(struct nvkm_instmem *, struct nvkm_memory *vram, struct nvkm_memory **bar2); void *nv50_instmem_dtor(struct nvkm_instmem *base); +struct io_mapping *nv50_instmem_bar2_iomap(struct nvkm_instmem *base); void nvkm_instmem_ctor(const struct nvkm_instmem_func *, struct nvkm_device *, enum nvkm_subdev_type, int, struct nvkm_instmem *); From 7488ee210542b918b9c5749a29fd1502c49a0665 Mon Sep 17 00:00:00 2001 From: Mohamed Ahmed Date: Wed, 18 Nov 2026 01:43:52 +0400 Subject: [PATCH 0909/2102] drm/nouveau/instmem: map only the part of BAR2 that is used The io_mapping covers the whole BAR2 resource. With GSP-RM and with NvBar2Halve the BAR2 address space covers only its lower half. The driver maps nothing in the upper half, and a mapping that already exists there would give the io_mapping its type. Size the io_mapping to the BAR2 address space. The range does not change where BAR2 is not halved. Fixes: 34e27b90552a ("nouveau/instmem: use iomapping interface for instmem handling") Cc: stable@vger.kernel.org Signed-off-by: Mohamed Ahmed Tested-by: Thomas Andersen Reviewed-by: Dave Airlie Signed-off-by: Dave Airlie Link: https://patch.msgid.link/20261117214352.337961-4-mohamedahmedegypt2001@gmail.com --- drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c b/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c index 1b4be4b1f0bb3c..1e7d439c2d592c 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c @@ -191,16 +191,17 @@ nv50_instobj_map(struct nvkm_memory *memory, u64 offset, struct nvkm_vmm *vmm, } static bool -check_io_mapping(struct nv50_instmem *imem) +check_io_mapping(struct nv50_instmem *imem, struct nvkm_vmm *vmm) { struct nvkm_device *device = imem->base.subdev.device; if (imem->iomap.size) return true; + /* Map the part of BAR2 that its address space covers. */ return io_mapping_init_wc(&imem->iomap, device->func->resource_addr(device, NVKM_BAR2_INST), - device->func->resource_size(device, NVKM_BAR2_INST)) != NULL; + vmm->limit - vmm->start) != NULL; } static void @@ -293,10 +294,10 @@ nv50_instobj_boot(struct nvkm_memory *memory, struct nvkm_vmm *vmm) } /* - * boot is only called on BAR2, if we can't remap the complete - * BAR it's unlikely things are functioning well. + * boot is only called on BAR2. If we can't map it, it's unlikely + * things are functioning well. */ - if (check_io_mapping(iobj->imem)) + if (check_io_mapping(iobj->imem, vmm)) nv50_instobj_kmap(iobj, vmm); nvkm_instmem_boot(imem); mutex_unlock(&imem->mutex); From d61480a622be17e5aa981f7ef4e6a0230b1d9049 Mon Sep 17 00:00:00 2001 From: Changyul Lee Date: Thu, 12 Nov 2026 23:03:23 -0500 Subject: [PATCH 0910/2102] net/mlx5e: Hold sync_lock while resetting VXLAN ports mlx5_vxlan_reset_to_default() walks vxlan->htable without sync_lock and calls mlx5_vxlan_del_port() for each user port. mlx5e_nic_disable() and mlx5e_uplink_rep_disable() call it after rtnl_unlock(), so the udp_tunnel_nic work can run mlx5e_vxlan_unset_port() at the same time. If that removes and frees the entry saved as the next one in hash_for_each_safe(), the walk then reads freed memory. Hold sync_lock over the whole walk, and add __mlx5_vxlan_del_port() for callers that already hold it. Fixes: c5eb51adf06b ("net/mlx5e: Fix VXLAN synchronization after function reload") Signed-off-by: Changyul Lee Reviewed-by: Tariq Toukan Link: https://patch.msgid.link/20261113040323.2090829-1-lcy8047@gmail.com Signed-off-by: Jakub Kicinski --- .../ethernet/mellanox/mlx5/core/lib/vxlan.c | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/vxlan.c b/drivers/net/ethernet/mellanox/mlx5/core/lib/vxlan.c index c2292cab4592d3..b953bbc4925c55 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/vxlan.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/vxlan.c @@ -121,25 +121,29 @@ int mlx5_vxlan_add_port(struct mlx5_vxlan *vxlan, u16 port) return 0; } -int mlx5_vxlan_del_port(struct mlx5_vxlan *vxlan, u16 port) +static int __mlx5_vxlan_del_port(struct mlx5_vxlan *vxlan, u16 port) { struct mlx5_vxlan_port *vxlanp; - int ret = 0; - mutex_lock(&vxlan->sync_lock); + lockdep_assert_held(&vxlan->sync_lock); vxlanp = vxlan_lookup_port(vxlan, port); - if (WARN_ON(!vxlanp)) { - ret = -ENOENT; - goto out_unlock; - } + if (WARN_ON(!vxlanp)) + return -ENOENT; hash_del_rcu(&vxlanp->hlist); synchronize_rcu(); mlx5_vxlan_core_del_port_cmd(vxlan->mdev, port); kfree(vxlanp); + return 0; +} + +int mlx5_vxlan_del_port(struct mlx5_vxlan *vxlan, u16 port) +{ + int ret; -out_unlock: + mutex_lock(&vxlan->sync_lock); + ret = __mlx5_vxlan_del_port(vxlan, port); mutex_unlock(&vxlan->sync_lock); return ret; } @@ -185,12 +189,14 @@ void mlx5_vxlan_reset_to_default(struct mlx5_vxlan *vxlan) if (!mlx5_vxlan_allowed(vxlan)) return; + mutex_lock(&vxlan->sync_lock); hash_for_each_safe(vxlan->htable, bkt, tmp, vxlanp, hlist) { /* Don't delete default UDP port added by the HW. * Remove only user configured ports */ if (vxlanp->udp_port == IANA_VXLAN_UDP_PORT) continue; - mlx5_vxlan_del_port(vxlan, vxlanp->udp_port); + __mlx5_vxlan_del_port(vxlan, vxlanp->udp_port); } + mutex_unlock(&vxlan->sync_lock); } From ece404eac250fc4be7aa4cec82e8c248cca83c28 Mon Sep 17 00:00:00 2001 From: Arun Iyengar Date: Fri, 13 Nov 2026 17:13:40 +0000 Subject: [PATCH 0911/2102] net: stmmac: drop the rest of the frame when napi_build_skb() fails If napi_build_skb() fails on the first buffer of a frame that spans several descriptors, stmmac_rx() drops that buffer but goes on with the next descriptor of the same frame as if a new frame started there. The rest of the frame is then passed up the stack as a frame of its own. A frame spans several descriptors when it does not fit in the RX buffers of one descriptor. Mark the frame as errored instead, so that its remaining descriptors are discarded like those of a frame with a receive error. The frame is counted once in rx_dropped and once against the NAPI budget. Found while working on the sun8i EMAC jumbo frame series, where frames over 2032 bytes span several descriptors. Tested on an Orange Pi Zero2 (dwmac-sun8i, MTU 4070), w/ jumbo series and error injection. Fixes: ec222003bd94 ("net: stmmac: Prepare to add Split Header support") Cc: stable@vger.kernel.org Signed-off-by: Arun Iyengar Reviewed-by: Maxime Chevallier Link: https://patch.msgid.link/20261113-stmmac-rx-skb-fail-v1-1-fcaae89f2d2c@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c index ee63f5ecf57018..9a9c44aab2e44c 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c @@ -6045,7 +6045,7 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) buf->page); buf->page = NULL; rx_dropped++; - count++; + error = 1; goto drain_data; } @@ -6081,7 +6081,7 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) if (likely(status & rx_not_ls)) goto read_again; if (!skb) - continue; + goto next; /* Got entire packet into SKB. Finish it. */ From 3d10dc3ae1f7c85375fb25f5e32bde0adb75089e Mon Sep 17 00:00:00 2001 From: Alexey Charkov Date: Fri, 13 Nov 2026 17:01:05 +0400 Subject: [PATCH 0912/2102] net: via-rhine: Stop the NIC on platform device shutdown Close a running interface on platform device shutdown, so that the chip stops its receive DMA before kexec hands its memory to the next kernel. Do it in the driver, as the platform (OF) variant lacks a .shutdown callback and nothing else stops it, unlike for PCI, where the core clears bus mastering ahead of kexec. Keep incoming frames from landing in receive buffers the old kernel had allocated: on a WonderMedia WM8950 board, broadcast traffic alone corrupts the next kernel at random points as it decompresses and boots, hanging about a third of kexec attempts early on, e.g. with "unrecognized/unsupported processor variant". Fixes: 2d283862dc62 ("net: via-rhine: add OF bus binding") Signed-off-by: Alexey Charkov Link: https://patch.msgid.link/20261113-vt8500-rhine-shutdown-v1-1-9448ea9548ec@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/via/via-rhine.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/drivers/net/ethernet/via/via-rhine.c b/drivers/net/ethernet/via/via-rhine.c index e56ebbdd428d53..dbbbaf7f20ac95 100644 --- a/drivers/net/ethernet/via/via-rhine.c +++ b/drivers/net/ethernet/via/via-rhine.c @@ -2461,6 +2461,17 @@ static void rhine_remove_one_platform(struct platform_device *pdev) free_netdev(dev); } +static void rhine_shutdown_platform(struct platform_device *pdev) +{ + struct net_device *dev = platform_get_drvdata(pdev); + + rtnl_lock(); + netif_device_detach(dev); + if (netif_running(dev)) + dev_close(dev); + rtnl_unlock(); +} + static void rhine_shutdown_pci(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); @@ -2580,6 +2591,7 @@ static struct pci_driver rhine_driver_pci = { static struct platform_driver rhine_driver_platform = { .probe = rhine_init_one_platform, .remove = rhine_remove_one_platform, + .shutdown = rhine_shutdown_platform, .driver = { .name = DRV_NAME, .of_match_table = rhine_of_tbl, From ff049836f05f5e46f702858a7cb949998e85a310 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 29 Oct 2026 14:50:21 +0100 Subject: [PATCH 0913/2102] lib/crc: Don't include in NEON intrinsics code The kernel's definitions of uint64_t and int64_t in are based on [unsigned] long long, whereas the ones provided by , which is included by , are based on [unsigned] long on arm64. On 32-bit ARM, a similar mismatch exists for intptr_t. Including both into the same compilation unit currently only works because asm/neon-intrinsics.h overrides the predefined macros that the compiler's freestanding uses to define these types. In order to be able to get rid of those overrides, stop including into the CRC64 NEON intrinsics code. Instead, use for the definition of size_t, and rely on to provide the u8 and u64 types used in the prototype of crc64_nvme_neon(), which is shared with code that does include . Use uint64_t for the arrays of constants that are passed to vld1q_u64(), so that they match its prototype regardless of how uint64_t is defined. No change in generated code. Signed-off-by: Ard Biesheuvel Reviewed-by: Thomas Huth Tested-by: Nathan Chancellor Reviewed-by: Eric Biggers Cc: Signed-off-by: Catalin Marinas --- lib/crc/crc64-neon.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/crc/crc64-neon.c b/lib/crc/crc64-neon.c index 4753fb94a4beb8..1267df1310bedf 100644 --- a/lib/crc/crc64-neon.c +++ b/lib/crc/crc64-neon.c @@ -3,7 +3,7 @@ * Accelerated CRC64 (NVMe) using ARM NEON C intrinsics */ -#include +#include #include #include "crc64-neon.h" @@ -11,11 +11,11 @@ u64 crc64_nvme_neon(u64 crc, const u8 *p, size_t len); /* x^191 mod G, x^127 mod G */ -static const u64 fold_consts_val[2] = { 0xeadc41fd2ba3d420ULL, - 0x21e9761e252621acULL }; +static const uint64_t fold_consts_val[2] = { 0xeadc41fd2ba3d420ULL, + 0x21e9761e252621acULL }; /* floor(x^127 / G), (G - x^64) / x */ -static const u64 bconsts_val[2] = { 0x27ecfa329aef9f77ULL, - 0x34d926535897936aULL }; +static const uint64_t bconsts_val[2] = { 0x27ecfa329aef9f77ULL, + 0x34d926535897936aULL }; u64 crc64_nvme_neon(u64 crc, const u8 *p, size_t len) { From 14e3460321430a3f9ed2260f3c6198bdeaba5792 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 29 Oct 2026 14:50:22 +0100 Subject: [PATCH 0914/2102] xor: arm/arm64: Move NEON xor_gen() dispatch into the glue code The NEON intrinsics code in xor-neon.c and arm64/xor-eor3.c includes xor_impl.h for the definition of __DO_XOR_BLOCKS(), which pulls in via and . This only works because asm/neon-intrinsics.h overrides the compiler's predefined macros that uses to define the C99 types, so that they match the kernel's definitions in . So instead, follow the approach taken by LoongArch, and instantiate the dispatch routines using DO_XOR_BLOCKS() in the glue code, which already includes the kernel headers, and does not use NEON intrinsics itself. This requires the NEON routines that handle a fixed number of sources to be exposed to the glue code, which means that the arm64 glue code can use __xor_neon_2() directly for the EOR3 flavor as well, and so the __xor_eor3_2() alias can be dropped. This makes the NEON intrinsics code independent of the kernel's own headers, which will allow the macro overrides in asm/neon-intrinsics.h to be removed. Signed-off-by: Ard Biesheuvel Tested-by: Nathan Chancellor Reviewed-by: Eric Biggers Cc: Signed-off-by: Catalin Marinas --- lib/raid/xor/arm/xor-neon-glue.c | 3 +++ lib/raid/xor/arm/xor-neon.h | 16 +++++++++++++-- lib/raid/xor/arm64/xor-eor3.c | 15 +++------------ lib/raid/xor/arm64/xor-neon-glue.c | 5 +++++ lib/raid/xor/arm64/xor-neon.h | 31 ++++++++++++++++++++++++++---- lib/raid/xor/xor-neon.c | 16 ++++----------- 6 files changed, 56 insertions(+), 30 deletions(-) diff --git a/lib/raid/xor/arm/xor-neon-glue.c b/lib/raid/xor/arm/xor-neon-glue.c index cea39e0199048e..783474bfe81e01 100644 --- a/lib/raid/xor/arm/xor-neon-glue.c +++ b/lib/raid/xor/arm/xor-neon-glue.c @@ -5,6 +5,9 @@ #include "xor_impl.h" #include "xor_arch.h" +DO_XOR_BLOCKS(neon_inner, __xor_neon_2, __xor_neon_3, __xor_neon_4, + __xor_neon_5); + static void xor_gen_neon(void *dest, void **srcs, unsigned int src_cnt, unsigned int bytes) { diff --git a/lib/raid/xor/arm/xor-neon.h b/lib/raid/xor/arm/xor-neon.h index 406e0356f05bb4..5592dec4de5016 100644 --- a/lib/raid/xor/arm/xor-neon.h +++ b/lib/raid/xor/arm/xor-neon.h @@ -3,5 +3,17 @@ extern struct xor_block_template xor_block_arm4regs; extern struct xor_block_template xor_block_neon; -void xor_gen_neon_inner(void *dest, void **srcs, unsigned int src_cnt, - unsigned int bytes); +void __xor_neon_2(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2); +void __xor_neon_3(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3); +void __xor_neon_4(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4); +void __xor_neon_5(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4, + const unsigned long * __restrict p5); diff --git a/lib/raid/xor/arm64/xor-eor3.c b/lib/raid/xor/arm64/xor-eor3.c index e44016c363f1c7..41bb577b63ebdf 100644 --- a/lib/raid/xor/arm64/xor-eor3.c +++ b/lib/raid/xor/arm64/xor-eor3.c @@ -1,14 +1,8 @@ // SPDX-License-Identifier: GPL-2.0-only -#include #include -#include "xor_impl.h" -#include "xor_arch.h" #include "xor-neon.h" -extern void __xor_eor3_2(unsigned long bytes, unsigned long * __restrict p1, - const unsigned long * __restrict p2); - static inline uint64x2_t eor3(uint64x2_t p, uint64x2_t q, uint64x2_t r) { uint64x2_t res; @@ -19,7 +13,7 @@ static inline uint64x2_t eor3(uint64x2_t p, uint64x2_t q, uint64x2_t r) return res; } -static void __xor_eor3_3(unsigned long bytes, unsigned long * __restrict p1, +void __xor_eor3_3(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3) { @@ -53,7 +47,7 @@ static void __xor_eor3_3(unsigned long bytes, unsigned long * __restrict p1, } while (--lines > 0); } -static void __xor_eor3_4(unsigned long bytes, unsigned long * __restrict p1, +void __xor_eor3_4(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3, const unsigned long * __restrict p4) @@ -96,7 +90,7 @@ static void __xor_eor3_4(unsigned long bytes, unsigned long * __restrict p1, } while (--lines > 0); } -static void __xor_eor3_5(unsigned long bytes, unsigned long * __restrict p1, +void __xor_eor3_5(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3, const unsigned long * __restrict p4, @@ -141,6 +135,3 @@ static void __xor_eor3_5(unsigned long bytes, unsigned long * __restrict p1, dp5 += 8; } while (--lines > 0); } - -__DO_XOR_BLOCKS(eor3_inner, __xor_eor3_2, __xor_eor3_3, __xor_eor3_4, - __xor_eor3_5); diff --git a/lib/raid/xor/arm64/xor-neon-glue.c b/lib/raid/xor/arm64/xor-neon-glue.c index f0284f86feb4c8..ae133d69964936 100644 --- a/lib/raid/xor/arm64/xor-neon-glue.c +++ b/lib/raid/xor/arm64/xor-neon-glue.c @@ -9,6 +9,11 @@ #include "xor_arch.h" #include "xor-neon.h" +DO_XOR_BLOCKS(neon_inner, __xor_neon_2, __xor_neon_3, __xor_neon_4, + __xor_neon_5); +DO_XOR_BLOCKS(eor3_inner, __xor_neon_2, __xor_eor3_3, __xor_eor3_4, + __xor_eor3_5); + #define XOR_TEMPLATE(_name) \ static void xor_gen_##_name(void *dest, void **srcs, unsigned int src_cnt, \ unsigned int bytes) \ diff --git a/lib/raid/xor/arm64/xor-neon.h b/lib/raid/xor/arm64/xor-neon.h index 514699ba8f5f8e..7d7fb96343df32 100644 --- a/lib/raid/xor/arm64/xor-neon.h +++ b/lib/raid/xor/arm64/xor-neon.h @@ -1,6 +1,29 @@ /* SPDX-License-Identifier: GPL-2.0-only */ -void xor_gen_neon_inner(void *dest, void **srcs, unsigned int src_cnt, - unsigned int bytes); -void xor_gen_eor3_inner(void *dest, void **srcs, unsigned int src_cnt, - unsigned int bytes); +void __xor_neon_2(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2); +void __xor_neon_3(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3); +void __xor_neon_4(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4); +void __xor_neon_5(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4, + const unsigned long * __restrict p5); + +void __xor_eor3_3(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3); +void __xor_eor3_4(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4); +void __xor_eor3_5(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4, + const unsigned long * __restrict p5); diff --git a/lib/raid/xor/xor-neon.c b/lib/raid/xor/xor-neon.c index c7c3cf634e23ac..6b2fd14f50419e 100644 --- a/lib/raid/xor/xor-neon.c +++ b/lib/raid/xor/xor-neon.c @@ -4,12 +4,11 @@ * Copyright (C) 2018,Tianjin KYLIN Information Technology Co., Ltd. */ -#include "xor_impl.h" #include "xor-neon.h" #include -static void __xor_neon_2(unsigned long bytes, unsigned long * __restrict p1, +void __xor_neon_2(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2) { uint64_t *dp1 = (uint64_t *)p1; @@ -36,7 +35,7 @@ static void __xor_neon_2(unsigned long bytes, unsigned long * __restrict p1, } while (--lines > 0); } -static void __xor_neon_3(unsigned long bytes, unsigned long * __restrict p1, +void __xor_neon_3(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3) { @@ -72,7 +71,7 @@ static void __xor_neon_3(unsigned long bytes, unsigned long * __restrict p1, } while (--lines > 0); } -static void __xor_neon_4(unsigned long bytes, unsigned long * __restrict p1, +void __xor_neon_4(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3, const unsigned long * __restrict p4) @@ -117,7 +116,7 @@ static void __xor_neon_4(unsigned long bytes, unsigned long * __restrict p1, } while (--lines > 0); } -static void __xor_neon_5(unsigned long bytes, unsigned long * __restrict p1, +void __xor_neon_5(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3, const unsigned long * __restrict p4, @@ -170,10 +169,3 @@ static void __xor_neon_5(unsigned long bytes, unsigned long * __restrict p1, dp5 += 8; } while (--lines > 0); } - -__DO_XOR_BLOCKS(neon_inner, __xor_neon_2, __xor_neon_3, __xor_neon_4, - __xor_neon_5); - -#ifdef CONFIG_ARM64 -extern typeof(__xor_neon_2) __xor_eor3_2 __alias(__xor_neon_2); -#endif From a041bdbe1f3a8efa8a527a89c84d3771232b4942 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 29 Oct 2026 14:50:23 +0100 Subject: [PATCH 0915/2102] arm64: Drop stdint.h type overrides from asm/neon-intrinsics.h None of the users of NEON intrinsics include anymore, and so there is no longer a need to override __INT64_TYPE__ and __UINT64_TYPE__ in order to make the definitions of int64_t and uint64_t provided by the compiler's freestanding compatible with the kernel's. So drop the overrides. This also means that uint64_t now matches the type that Clang uses for 64-bit quantities in the prototypes of its NEON builtins, and so the -Wincompatible-pointer-types warnings that are currently being disabled for all NEON intrinsics code will no longer occur. So drop the pragma that disables them as well. Signed-off-by: Ard Biesheuvel Tested-by: Nathan Chancellor Reviewed-by: Eric Biggers Cc: Signed-off-by: Catalin Marinas --- arch/arm64/include/asm/neon-intrinsics.h | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/arch/arm64/include/asm/neon-intrinsics.h b/arch/arm64/include/asm/neon-intrinsics.h index 5f13505d39fc75..43cdf4d1617098 100644 --- a/arch/arm64/include/asm/neon-intrinsics.h +++ b/arch/arm64/include/asm/neon-intrinsics.h @@ -6,23 +6,13 @@ #ifndef __ASM_NEON_INTRINSICS_H #define __ASM_NEON_INTRINSICS_H -#include - /* - * In the kernel, u64/s64 are [un]signed long long, not [un]signed long. - * So by redefining these macros to the former, we can force gcc-stdint.h - * to define uint64_t / in64_t in a compatible manner. + * includes , which defines some C99 types differently + * from , so the latter must not be included into code that uses + * NEON intrinsics. The kernel's u8/u16/u32/u64 types can be used alongside the + * C99 ones, so provide those instead. */ - -#ifdef __INT64_TYPE__ -#undef __INT64_TYPE__ -#define __INT64_TYPE__ long long -#endif - -#ifdef __UINT64_TYPE__ -#undef __UINT64_TYPE__ -#define __UINT64_TYPE__ unsigned long long -#endif +#include /* * genksyms chokes on the ARM NEON instrinsics system header, but we @@ -33,8 +23,4 @@ #include #endif -#ifdef CONFIG_CC_IS_CLANG -#pragma clang diagnostic ignored "-Wincompatible-pointer-types" -#endif - #endif /* __ASM_NEON_INTRINSICS_H */ From bcb42672751a8786dce871a35bde363b041cb2f7 Mon Sep 17 00:00:00 2001 From: Theodor Arsenij Larionov Trichkine Date: Mon, 16 Nov 2026 14:38:45 +0300 Subject: [PATCH 0916/2102] fou: reserve headroom before pushing the encap header ip_tunnel_xmit() and ip_md_tunnel_xmit() push the encap header before reserving headroom. A packet redirected into the tunnel (tc mirred, nft fwd/dup) keeps the headroom of its original device, so fou_build_udp() panics: kernel BUG at net/core/skbuff.c:214! Call Trace: skb_push+0xcc/0xf0 fou_build_udp+0x2f/0x380 gue_build_header+0xfa/0x150 ip_tunnel_xmit+0x87f/0x21c0 With a mirred mirror, the push overwrites the original packet instead. Reachable with CAP_NET_ADMIN in a user namespace. Reserve the headroom in fou_build_header() and gue_build_header(); GUE sizes and builds the header from one copy of the encap fields. The skb head may move, so reload inner_iph after ip_tunnel_encap() and read tnl_params, which points into the head for GRE with header_ops, before the call. sit's ipip6_tunnel_xmit() holds no head pointer across it. Fixes: 56328486539d ("net: Changes to ip_tunnel to support foo-over-udp encapsulation") Fixes: ac931d4cdec3 ("ipip,ip_tunnel,sit: Add FOU support for externally controlled ipip devices") Reported-by: Chengfeng Ye Closes: https://lore.kernel.org/netdev/20260801060115.3538849-1-nicoyip.dev@gmail.com/ Cc: stable@vger.kernel.org Signed-off-by: Theodor Arsenij Larionov Trichkine Reviewed-by: Ido Schimmel Link: https://patch.msgid.link/20261116113845.166280-1-theodorlarionov@gmail.com Signed-off-by: Jakub Kicinski --- net/ipv4/fou_core.c | 19 +++++++++++++++---- net/ipv4/ip_tunnel.c | 6 ++++-- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/net/ipv4/fou_core.c b/net/ipv4/fou_core.c index 5c3c8f55d05704..bff4dc488def79 100644 --- a/net/ipv4/fou_core.c +++ b/net/ipv4/fou_core.c @@ -1071,6 +1071,9 @@ static int fou_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, __be16 sport; int err; + if (skb_cow_head(skb, fou_encap_hlen(e))) + return -ENOMEM; + err = __fou_build_header(skb, e, protocol, &sport, type); if (err) return err; @@ -1083,16 +1086,24 @@ static int fou_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, static int gue_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, u8 *protocol, struct flowi4 *fl4) { - int type = e->flags & TUNNEL_ENCAP_FLAG_CSUM ? SKB_GSO_UDP_TUNNEL_CSUM : - SKB_GSO_UDP_TUNNEL; + struct ip_tunnel_encap encap = { + .flags = READ_ONCE(e->flags), + .sport = READ_ONCE(e->sport), + .dport = READ_ONCE(e->dport), + }; + int type = encap.flags & TUNNEL_ENCAP_FLAG_CSUM ? + SKB_GSO_UDP_TUNNEL_CSUM : SKB_GSO_UDP_TUNNEL; __be16 sport; int err; - err = __gue_build_header(skb, e, protocol, &sport, type); + if (skb_cow_head(skb, gue_encap_hlen(&encap))) + return -ENOMEM; + + err = __gue_build_header(skb, &encap, protocol, &sport, type); if (err) return err; - fou_build_udp(skb, e, fl4, protocol, sport); + fou_build_udp(skb, &encap, fl4, protocol, sport); return 0; } diff --git a/net/ipv4/ip_tunnel.c b/net/ipv4/ip_tunnel.c index 0875474a578a4a..1052af6245df53 100644 --- a/net/ipv4/ip_tunnel.c +++ b/net/ipv4/ip_tunnel.c @@ -610,6 +610,7 @@ void ip_md_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, if (ip_tunnel_encap(skb, &tun_info->encap, &proto, &fl4) < 0) goto tx_error; + inner_iph = (const struct iphdr *)skb_inner_network_header(skb); use_cache = ip_tunnel_dst_cache_usable(skb, tun_info); if (use_cache) @@ -753,6 +754,8 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, } tos = tnl_params->tos; + df = tnl_params->frag_off; + ttl = tnl_params->ttl; if (tos & 0x1) { tos &= ~0x1; if (payload_protocol == htons(ETH_P_IP)) { @@ -771,6 +774,7 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, if (ip_tunnel_encap(skb, &tunnel->encap, &protocol, &fl4) < 0) goto tx_error; + inner_iph = (const struct iphdr *)skb_inner_network_header(skb); if (connected && md) { use_cache = ip_tunnel_dst_cache_usable(skb, tun_info); @@ -803,7 +807,6 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, goto tx_error; } - df = tnl_params->frag_off; if (payload_protocol == htons(ETH_P_IP) && !tunnel->ignore_df) df |= (inner_iph->frag_off & htons(IP_DF)); @@ -825,7 +828,6 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, } tos = ip_tunnel_ecn_encap(tos, inner_iph, skb); - ttl = tnl_params->ttl; if (ttl == 0) { if (payload_protocol == htons(ETH_P_IP)) ttl = inner_iph->ttl; From f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Jo=C5=84czyk?= Date: Sun, 15 Nov 2026 22:40:45 +0100 Subject: [PATCH 0917/2102] net: phy: realtek: fix listing of sysfs directory tree MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On git master, listing the contents of sysfs produces an error: root@mateusz-debian:/sys# LANG=C find -iname foobar find: './module/realtek/drivers': Input/output error root@mateusz-debian:/sys# LANG=C ls -1 ./module/realtek/drivers ls: reading directory './module/realtek/drivers': Input/output error 'mdio_bus:Generic FE-GE Realtek PHY' 'mdio_bus:RTL8201CP Ethernet' 'mdio_bus:RTL8201F Fast Ethernet' 'mdio_bus:RTL8208 Fast Ethernet' 'mdio_bus:RTL8211B Gigabit Ethernet' [...] Investigation shows that the forward slash in the driver name is the culprit. Fix it. Cc: stable@vger.kernel.org Fixes: f0667918d5fc ("net: phy: realtek: add support for RTL8261D") Signed-off-by: Mateusz Jończyk Reviewed-by: Andrew Lunn Link: https://patch.msgid.link/20261115214045.3704-1-mat.jonczyk@o2.pl Signed-off-by: Jakub Kicinski --- drivers/net/phy/realtek/realtek_main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/phy/realtek/realtek_main.c b/drivers/net/phy/realtek/realtek_main.c index ca2d515b77b36b..a39ad18382f254 100644 --- a/drivers/net/phy/realtek/realtek_main.c +++ b/drivers/net/phy/realtek/realtek_main.c @@ -3483,7 +3483,7 @@ static struct phy_driver realtek_drvs[] = { .write_mmd = genphy_write_mmd_unsupported, }, { PHY_ID_MATCH_EXACT(RTL_8261C_CG), - .name = "Realtek RTL8261C/D 10Gbps PHY", + .name = "Realtek RTL8261C_RTL8261D 10Gbps PHY", .probe = rtl8261x_probe, .config_init = rtl8261x_config_init, .get_features = rtl8261x_get_features, From 342e62fd34c2674e82bffc89cb5c7091924986d9 Mon Sep 17 00:00:00 2001 From: Eric Dumazet Date: Sat, 14 Nov 2026 12:12:47 +0100 Subject: [PATCH 0918/2102] tcp: purge Fast Open RST queue when listen() fails inet_csk_listen_start() moves the socket to TCP_LISTEN before calling ->get_port() and ->hash(). If one of them fails, the socket goes back to TCP_CLOSE without going through inet_csk_listen_stop(). If the socket was a Fast Open listener in a previous life, and was stopped with shutdown(SHUT_RD) or connect(AF_UNSPEC) while an accepted Fast Open child was still in TCP_SYN_RECV state, the request_sock of this child still points to the listener. A valid RST received for this child while the listener is transiently in TCP_LISTEN state makes reqsk_fastopen_remove() queue the request_sock in rskq_rst_head. When listen() fails, for instance with -EADDRINUSE because another SO_REUSEADDR socket started listening on the same port, nothing reclaims it: - __tcp_close(), tcp_disconnect() and tcp_abort() only call inet_csk_listen_stop() for sockets in TCP_LISTEN state. - A later successful listen() overwrites rskq_rst_head in reqsk_queue_alloc(). The request_sock is leaked, together with the reference it holds on the listener. Move the rskq_rst_head purge to a helper, and call it from the inet_csk_listen_start() error path as well, after the socket state has been set back to TCP_CLOSE: reqsk_fastopen_remove() checks sk_state under fastopenq.lock, so it either queued the request before the purge acquires the lock, or does not queue it at all. Reported-by: Sashiko AI review Closes: https://lore.kernel.org/netdev/179450310167.2199510.18107423940014989443@kernel.org/ Fixes: 0536fcc039a8 ("tcp: prepare fastopen code for upcoming listener changes") Signed-off-by: Eric Dumazet Reviewed-by: Hyunwoo Kim Reviewed-by: Kuniyuki Iwashima Link: https://patch.msgid.link/20261114111247.21995-1-edumazet@kernel.org Signed-off-by: Jakub Kicinski --- net/ipv4/inet_connection_sock.c | 35 ++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/net/ipv4/inet_connection_sock.c b/net/ipv4/inet_connection_sock.c index d1c864b4252fae..9a3b05edb62bfc 100644 --- a/net/ipv4/inet_connection_sock.c +++ b/net/ipv4/inet_connection_sock.c @@ -1340,6 +1340,22 @@ static int inet_ulp_can_listen(const struct sock *sk) return 0; } +/* Free all the reqs queued in rskq_rst_head. */ +static void reqsk_fastopen_purge_rst(struct request_sock_queue *queue) +{ + struct request_sock *next, *req; + + spin_lock_bh(&queue->fastopenq.lock); + req = queue->fastopenq.rskq_rst_head; + queue->fastopenq.rskq_rst_head = NULL; + spin_unlock_bh(&queue->fastopenq.lock); + while (req != NULL) { + next = req->dl_next; + reqsk_put(req); + req = next; + } +} + static void reqsk_queue_alloc(struct request_sock_queue *queue) { queue->fastopenq.rskq_rst_head = NULL; @@ -1382,6 +1398,12 @@ int inet_csk_listen_start(struct sock *sk) } inet_sk_set_state(sk, TCP_CLOSE); + + /* A Fast Open child accepted before a previous shutdown() of this + * listener might have queued its request in rskq_rst_head while + * we were transiently in TCP_LISTEN state. + */ + reqsk_fastopen_purge_rst(&icsk->icsk_accept_queue); return err; } @@ -1486,7 +1508,7 @@ void inet_csk_listen_stop(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); struct request_sock_queue *queue = &icsk->icsk_accept_queue; - struct request_sock *next, *req; + struct request_sock *req; /* Following specs, it would be better either to send FIN * (and enter FIN-WAIT-1, it is normal close) @@ -1542,16 +1564,7 @@ void inet_csk_listen_stop(struct sock *sk) if (!has_current_bpf_ctx()) cond_resched(); } - /* Free all the reqs queued in rskq_rst_head. */ - spin_lock_bh(&queue->fastopenq.lock); - req = queue->fastopenq.rskq_rst_head; - queue->fastopenq.rskq_rst_head = NULL; - spin_unlock_bh(&queue->fastopenq.lock); - while (req != NULL) { - next = req->dl_next; - reqsk_put(req); - req = next; - } + reqsk_fastopen_purge_rst(queue); WARN_ON_ONCE(sk->sk_ack_backlog); } From cd057fd9c742cd37a210452c8ffff1777a3fd205 Mon Sep 17 00:00:00 2001 From: Omar Ramadan Date: Tue, 10 Nov 2026 21:05:32 +0000 Subject: [PATCH 0919/2102] amt: stop receiving before amt_dev_stop() tears down its state amt_dev_stop() clears amt->sk and waits in synchronize_net(), but the socket's sk_user_data still points at the device until udp_tunnel_sock_release() clears it afterwards, and nothing waits for readers then. An amt_rcv() that loads the pointer after the grace period can still be running once amt_dev_stop() has cancelled event_wq and torn down the relay's tunnels. A gateway can then queue a received Advertisement or Membership Query on event_wq again, and a relay can link a new tunnel from a Request and arm its gc_wq. Either work can then run after the device has been freed. Clear sk_user_data before the grace period, so synchronize_net() also waits for every amt_rcv() that can still see the device. Once it is NULL, amt_rcv() drops the packet and amt_err_lookup() ignores the ICMP error. The race is as old as amt_rcv(). From commit 3cf7203ca620 ("net/tunnel: wait until all sk_user_data reader finish before releasing the sock") until commit 72d3b9a4c2b1 ("udp_tunnel: Remove synchronize_rcu() in udp_tunnel_sock_release()."), udp_tunnel_sock_release() waited for those readers after clearing sk_user_data, which hid it. The wait was removed because each tunnel driver frees its fast-path state only after a grace period, but amt_rcv() does more than read that state: it queues work and links tunnels that amt_dev_stop() must already have stopped. Found by code inspection; not triggered. Fixes: cbc21dc1cfe9 ("amt: add data plane of amt interface") Fixes: 72d3b9a4c2b1 ("udp_tunnel: Remove synchronize_rcu() in udp_tunnel_sock_release().") Signed-off-by: Omar Ramadan Link: https://patch.msgid.link/20261110210538.217936-2-omar@blockcast.net Signed-off-by: Jakub Kicinski --- drivers/net/amt.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/net/amt.c b/drivers/net/amt.c index 8b9fc3d11eceec..989cabee0dfa9f 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -3072,9 +3072,14 @@ static int amt_dev_stop(struct net_device *dev) disable_delayed_work_sync(&amt->discovery_wq); cancel_delayed_work_sync(&amt->secret_wq); - /* shutdown */ + /* shutdown. Detach the receive path as well, so that once the + * grace period ends no amt_rcv() can still see the device and queue + * work after the teardown below. + */ sk = rtnl_dereference(amt->sk); RCU_INIT_POINTER(amt->sk, NULL); + if (sk) + rcu_assign_sk_user_data(sk, NULL); synchronize_net(); if (sk) udp_tunnel_sock_release(sk); From 5931fd2440de6ade0b0017d718635c6dceb0d95a Mon Sep 17 00:00:00 2001 From: Omar Ramadan Date: Tue, 10 Nov 2026 21:05:33 +0000 Subject: [PATCH 0920/2102] amt: fix use-after-free when a Membership Update re-arms a freed tunnel amt_update_handler() refreshes a relay tunnel's garbage-collection timer with mod_delayed_work() on a tunnel found by an RCU walk. A concurrent amt_tunnel_expire() can unlink and free that tunnel while the Update path still has the cached pointer, leaving gc_wq armed in freed memory. A tunnel can also be freed twice. amt_dev_stop() unlinks and frees tunnels without amt->lock, while amt_tunnel_expire() unlinks and frees them under it, so an ifdown that races a tunnel timeout can run list_del_rcu() and kfree_rcu() on the same tunnel twice. Group and source nodes have lifetime bugs of their own: - __amt_source_gc_work() frees a source, and amt_del_group() a group, after only cancel_delayed_work(), which does not wait for a timer work that is already running. amt_source_work() or amt_group_work() can then run on the freed node. - amt_source_work() reads snode->gnode and gnode->tunnel_list, and amt_group_work() gnode->tunnel_list, before taking tunnel->lock or the RCU read lock, so either can follow a pointer to a group or tunnel that has already been freed. - A timer work that waits for tunnel->lock while its node is deleted can then act on the deleted node: amt_source_work() destroys the source again, or amt_group_work() deletes the group again. Either decrements nr_sources or nr_groups a second time and unlinks, queues or frees the node a second time. Make amt_tunnel_expire() the only timeout-path freer. The Update path records last_seen under tunnel->lock, and expire reads it under tunnel->lock and, in the same section, either re-arms gc_wq from it or marks the tunnel dead for freeing, so an Update either keeps the tunnel alive or finds it dead. Protect the dead state with tunnel->lock so report handling cannot add multicast state after teardown begins. Device stop marks tunnels dead under amt->lock, unlinks them one at a time under it, synchronously cancels their work, and frees them after lockless readers have passed. Apply the same lifetime rules to group and source timer work: mark nodes dead under tunnel->lock, keep RCU held while workers resolve their parents, clear the parent pointers before a node is queued for freeing, defer node freeing, and synchronously cancel each node's timer before freeing that node. Park sources and groups through a gc_node of their own. A destroyed source used to reuse snode->node, its link into the group's hash; no lockless reader is known to follow it onto the GC list, so this is hardening. Run the deferred GC directly before freeing a tunnel so nodes are reclaimed promptly. Do not flush the GC work instead: flush_delayed_work() queues the work and waits for it to run, which needs a free amt_wq active slot, so amt_tunnel_expire() and the group GC, both amt_wq work, can deadlock once every slot is held by such a waiter. The cancel_delayed_work_sync() calls the GC makes need no slot: each takes a pending timer work off its timer or queue, or waits for a running one on a barrier that max_active does not count. Lifetime does not rest on that GC run, which misses nodes a concurrent run has already spliced off: it rests on kfree_rcu() and on the parent pointers being cleared, and the dead checks made, under tunnel->lock. Release the group timer's device reference on every exit. A node on a GC list is no longer charged to max_groups or max_sources, and unless a tunnel expires or the device stops, only the periodic GC drains the lists, every 30 seconds. Sources were already parked that way; groups, which went to kfree_rcu() before, now are too, so Report/Leave churn from one gateway could pin memory without bound in between. Count the nodes parked on both lists, under the one lock that now protects both, and when the count reaches AMT_GC_KICK (2048) queue the drain of both lists at once. A parked group still holds its AMT_HSIZE (256) source hash heads, so it is a kmalloc-4k object, and 2048 of them is about 8 MiB; the kick keeps the backlog near that instead of letting it grow for up to 30 seconds. A periodic drain that ends with that many parked again runs again at once rather than after the interval. This also bounds what amt_dev_stop() has to free in its drain under RTNL, and both drains now call cond_resched() after each node. A Request-only tunnel retains the original GMI timeout. Its last_seen stays 0, a value an Update never stores, and only a valid, authenticated Membership Update refreshes last_seen and gives the tunnel the longer lifetime: an Update whose encapsulated message fails ip_mc_check_igmp() or ipv6_mc_check_mld() no longer extends the tunnel. amt_tunnel_expire() reads jiffies once, so the re-arm delay comes from the value it compared. The Sashiko AI review of an earlier posting of this series pointed out the gc_wq re-arm, and reading amt_update_handler() against amt_tunnel_expire() and amt_dev_stop() confirms it. It is theoretical: it needs a Membership Update that has already found the tunnel under RCU to arrive while amt_tunnel_expire() is freeing that tunnel. Review of later postings raised the races in the group and source timer work, the amt_dev_stop() double free and the unbounded GC lists. I have not triggered any of them, so there is no trace to include. Fixes: cbc21dc1cfe9 ("amt: add data plane of amt interface") Fixes: bc54e49c140b ("amt: add multicast(IGMP) report message handler") Signed-off-by: Omar Ramadan Link: https://patch.msgid.link/20261110210538.217936-3-omar@blockcast.net Signed-off-by: Jakub Kicinski --- drivers/net/amt.c | 239 +++++++++++++++++++++++++++++++++++++++++----- include/net/amt.h | 18 ++++ 2 files changed, 232 insertions(+), 25 deletions(-) diff --git a/drivers/net/amt.c b/drivers/net/amt.c index 989cabee0dfa9f..70eabc523b2f68 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -35,9 +35,19 @@ static struct workqueue_struct *amt_wq; static HLIST_HEAD(source_gc_list); -/* Lock for source_gc_list */ +/* Lock for source_gc_list, group_gc_list and the counts below */ static spinlock_t source_gc_lock; static struct delayed_work source_gc_wq; +static HLIST_HEAD(group_gc_list); +static struct delayed_work group_gc_wq; +/* Nodes parked on source_gc_list and group_gc_list, and the sources among + * them, so that a drain of either list can take its nodes off the count. + * Parked nodes are not charged to max_groups or max_sources, so + * Report/Leave churn could park them faster than the AMT_GC_INTERVAL tick + * frees them: once AMT_GC_KICK are parked, the drain runs at once. + */ +static unsigned int amt_gc_queued; +static unsigned int amt_gc_sources; static char *status_str[] = { "AMT_STATUS_INIT", "AMT_STATUS_SENT_DISCOVERY", @@ -88,11 +98,15 @@ static void __amt_source_gc_work(void) spin_lock_bh(&source_gc_lock); hlist_move_list(&source_gc_list, &gc_list); + amt_gc_queued -= amt_gc_sources; + amt_gc_sources = 0; spin_unlock_bh(&source_gc_lock); - hlist_for_each_entry_safe(snode, t, &gc_list, node) { - hlist_del_rcu(&snode->node); + hlist_for_each_entry_safe(snode, t, &gc_list, gc_node) { + cancel_delayed_work_sync(&snode->source_timer); + hlist_del_init(&snode->gc_node); kfree_rcu(snode, rcu); + cond_resched(); } } @@ -106,6 +120,62 @@ static void amt_source_gc_work(struct work_struct *work) spin_unlock_bh(&source_gc_lock); } +static void __amt_group_gc_work(void) +{ + struct amt_group_node *gnode; + struct hlist_head gc_list; + struct hlist_node *t; + + spin_lock_bh(&source_gc_lock); + hlist_move_list(&group_gc_list, &gc_list); + amt_gc_queued = amt_gc_sources; + spin_unlock_bh(&source_gc_lock); + + /* Group deletion queues all of its sources first. Reclaim them now + * rather than at the next periodic run; a source callback cannot + * reach a freed group because it resolves snode->gnode under RCU and + * the pointer is cleared before the source is queued. Call the GC + * here rather than flush source_gc_wq: a flush queues the work and + * waits for it to run, which needs a free amt_wq active slot, and + * when this runs on amt_wq every slot can be held by such waiters. + * The cancel_delayed_work_sync() calls in the GC need no slot: each + * takes a pending timer work off its timer or queue, or waits for a + * running one on a barrier that max_active does not count. + */ + __amt_source_gc_work(); + + hlist_for_each_entry_safe(gnode, t, &gc_list, gc_node) { + cancel_delayed_work_sync(&gnode->group_timer); + hlist_del_init(&gnode->gc_node); + kfree_rcu(gnode, rcu); + cond_resched(); + } +} + +static void amt_group_gc_work(struct work_struct *work) +{ + __amt_group_gc_work(); + + /* Run again at once if AMT_GC_KICK nodes were parked meanwhile: a + * kick that landed during the drain must not be pushed back to the + * interval. + */ + spin_lock_bh(&source_gc_lock); + mod_delayed_work(amt_wq, &group_gc_wq, + amt_gc_queued >= AMT_GC_KICK ? 0 : + msecs_to_jiffies(AMT_GC_INTERVAL)); + spin_unlock_bh(&source_gc_lock); +} + +/* Caller holds source_gc_lock and has just parked one node. This runs + * under tunnel->lock, often in softirq; mod_delayed_work() does not sleep. + */ +static void amt_gc_parked(void) +{ + if (++amt_gc_queued == AMT_GC_KICK) + mod_delayed_work(amt_wq, &group_gc_wq, 0); +} + static bool amt_addr_equal(union amt_addr *a, union amt_addr *b) { return !memcmp(a, b, sizeof(union amt_addr)); @@ -215,8 +285,13 @@ static struct amt_group_node *amt_lookup_group(struct amt_tunnel_list *tunnel, static void amt_destroy_source(struct amt_source_node *snode) { - struct amt_group_node *gnode = snode->gnode; struct amt_tunnel_list *tunnel; + struct amt_group_node *gnode; + + if (snode->dead) + return; + snode->dead = true; + gnode = snode->gnode; tunnel = gnode->tunnel_list; @@ -238,8 +313,11 @@ static void amt_destroy_source(struct amt_source_node *snode) hlist_del_init_rcu(&snode->node); tunnel->nr_sources--; gnode->nr_sources--; + WRITE_ONCE(snode->gnode, NULL); spin_lock_bh(&source_gc_lock); - hlist_add_head_rcu(&snode->node, &source_gc_list); + hlist_add_head(&snode->gc_node, &source_gc_list); + amt_gc_sources++; + amt_gc_parked(); spin_unlock_bh(&source_gc_lock); } @@ -249,6 +327,9 @@ static void amt_del_group(struct amt_dev *amt, struct amt_group_node *gnode) struct hlist_node *t; int i; + if (gnode->dead) + return; + gnode->dead = true; if (cancel_delayed_work(&gnode->group_timer)) dev_put(amt->dev); hlist_del_rcu(&gnode->node); @@ -266,10 +347,11 @@ static void amt_del_group(struct amt_dev *amt, struct amt_group_node *gnode) hlist_for_each_entry_safe(snode, t, &gnode->sources[i], node) amt_destroy_source(snode); - /* tunnel->lock was acquired outside of amt_del_group() - * But rcu_read_lock() was acquired too so It's safe. - */ - kfree_rcu(gnode, rcu); + WRITE_ONCE(gnode->tunnel_list, NULL); + spin_lock_bh(&source_gc_lock); + hlist_add_head(&gnode->gc_node, &group_gc_list); + amt_gc_parked(); + spin_unlock_bh(&source_gc_lock); } /* If a source timer expires with a router filter-mode for the group of @@ -282,13 +364,28 @@ static void amt_source_work(struct work_struct *work) struct amt_source_node *snode = container_of(to_delayed_work(work), struct amt_source_node, source_timer); - struct amt_group_node *gnode = snode->gnode; - struct amt_dev *amt = gnode->amt; struct amt_tunnel_list *tunnel; + struct amt_group_node *gnode; + struct amt_dev *amt; - tunnel = gnode->tunnel_list; - spin_lock_bh(&tunnel->lock); rcu_read_lock(); + gnode = READ_ONCE(snode->gnode); + if (!gnode) { + rcu_read_unlock(); + return; + } + amt = gnode->amt; + tunnel = READ_ONCE(gnode->tunnel_list); + if (!tunnel) { + rcu_read_unlock(); + return; + } + spin_lock_bh(&tunnel->lock); + if (snode->dead || gnode->dead) { + spin_unlock_bh(&tunnel->lock); + rcu_read_unlock(); + return; + } if (gnode->filter_mode == MCAST_INCLUDE) { amt_destroy_source(snode); if (!gnode->nr_sources) @@ -299,8 +396,8 @@ static void amt_source_work(struct work_struct *work) */ snode->status = AMT_SOURCE_STATUS_D_FWD; } - rcu_read_unlock(); spin_unlock_bh(&tunnel->lock); + rcu_read_unlock(); } static void amt_act_src(struct amt_tunnel_list *tunnel, @@ -368,6 +465,7 @@ static struct amt_source_node *amt_alloc_snode(struct amt_group_node *gnode, snode->status = AMT_SOURCE_STATUS_NONE; snode->flags = AMT_SOURCE_NEW; INIT_HLIST_NODE(&snode->node); + INIT_HLIST_NODE(&snode->gc_node); INIT_DELAYED_WORK(&snode->source_timer, amt_source_work); return snode; @@ -403,23 +501,31 @@ static void amt_group_work(struct work_struct *work) struct amt_group_node *gnode = container_of(to_delayed_work(work), struct amt_group_node, group_timer); - struct amt_tunnel_list *tunnel = gnode->tunnel_list; - struct amt_dev *amt = gnode->amt; + struct amt_tunnel_list *tunnel; struct amt_source_node *snode; bool delete_group = true; struct hlist_node *t; + struct amt_dev *amt; int i, buckets; + rcu_read_lock(); + tunnel = READ_ONCE(gnode->tunnel_list); + amt = gnode->amt; + if (!tunnel) + goto out; buckets = amt->hash_buckets; spin_lock_bh(&tunnel->lock); + if (gnode->dead) { + spin_unlock_bh(&tunnel->lock); + goto out; + } if (gnode->filter_mode == MCAST_INCLUDE) { /* Not Used */ spin_unlock_bh(&tunnel->lock); goto out; } - rcu_read_lock(); for (i = 0; i < buckets; i++) { hlist_for_each_entry_safe(snode, t, &gnode->sources[i], node) { @@ -436,9 +542,9 @@ static void amt_group_work(struct work_struct *work) amt_del_group(amt, gnode); else gnode->filter_mode = MCAST_INCLUDE; - rcu_read_unlock(); spin_unlock_bh(&tunnel->lock); out: + rcu_read_unlock(); dev_put(amt->dev); } @@ -479,6 +585,7 @@ static struct amt_group_node *amt_add_group(struct amt_dev *amt, gnode->tunnel_list = tunnel; gnode->filter_mode = MCAST_INCLUDE; INIT_HLIST_NODE(&gnode->node); + INIT_HLIST_NODE(&gnode->gc_node); INIT_DELAYED_WORK(&gnode->group_timer, amt_group_work); for (i = 0; i < amt->hash_buckets; i++) INIT_HLIST_HEAD(&gnode->sources[i]); @@ -1342,14 +1449,51 @@ static void amt_tunnel_expire(struct work_struct *work) struct amt_tunnel_list, gc_wq); struct amt_dev *amt = tunnel->amt; + unsigned long deadline, now; spin_lock_bh(&amt->lock); + spin_lock_bh(&tunnel->lock); + /* amt_dev_stop() has taken ownership of the teardown. */ + if (READ_ONCE(tunnel->dead)) { + spin_unlock_bh(&tunnel->lock); + spin_unlock_bh(&amt->lock); + return; + } + /* A Membership Update may have refreshed the tunnel after this work + * was queued. Re-arm from last_seen rather than letting + * amt_update_handler() re-arm gc_wq: this handler is then the only + * context that frees the tunnel on the timeout path; amt_dev_stop() + * still owns teardown during device shutdown. last_seen is read and + * dead is set under tunnel->lock, which the Update path holds while + * it refreshes last_seen, so an Update either keeps the tunnel alive + * or finds it dead. + */ + now = jiffies; + deadline = tunnel->last_seen; + /* No Update yet: the Request armed gc_wq for one GMI. */ + if (!deadline) + deadline = now; + else + deadline += msecs_to_jiffies(amt_gmi(amt)) * 3; + if (time_before(now, deadline)) { + mod_delayed_work(amt_wq, &tunnel->gc_wq, deadline - now); + spin_unlock_bh(&tunnel->lock); + spin_unlock_bh(&amt->lock); + return; + } + WRITE_ONCE(tunnel->dead, true); + spin_unlock_bh(&tunnel->lock); rcu_read_lock(); list_del_rcu(&tunnel->list); amt->nr_tunnels--; amt_clear_groups(tunnel); rcu_read_unlock(); spin_unlock_bh(&amt->lock); + /* Free now, rather than at the next periodic run, the nodes that + * amt_clear_groups() queued. Call the GC rather than flush + * group_gc_wq, as explained in __amt_group_gc_work(). + */ + __amt_group_gc_work(); kfree_rcu(tunnel, rcu); } @@ -2507,9 +2651,6 @@ static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) if (tunnel->ip4 == saddr) { if ((nonce == tunnel->nonce && response_mac == tunnel->mac)) { - mod_delayed_work(amt_wq, &tunnel->gc_wq, - msecs_to_jiffies(amt_gmi(amt)) - * 3); goto report; } else { netdev_dbg(amt->dev, "Invalid MAC\n"); @@ -2535,6 +2676,18 @@ static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) } spin_lock_bh(&tunnel->lock); + if (READ_ONCE(tunnel->dead)) { + spin_unlock_bh(&tunnel->lock); + return true; + } + /* Refresh liveness under tunnel->lock, where + * amt_tunnel_expire() reads it; 0 is kept for a tunnel no + * Update has refreshed. gc_wq is re-armed by + * amt_tunnel_expire() itself from last_seen, never from + * here, so this cannot re-queue the work of a tunnel that is + * being freed. + */ + tunnel->last_seen = jiffies ?: 1; amt_igmp_report_handler(amt, skb, tunnel); spin_unlock_bh(&tunnel->lock); @@ -2555,6 +2708,11 @@ static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) } spin_lock_bh(&tunnel->lock); + if (READ_ONCE(tunnel->dead)) { + spin_unlock_bh(&tunnel->lock); + return true; + } + tunnel->last_seen = jiffies ?: 1; amt_mld_report_handler(amt, skb, tunnel); spin_unlock_bh(&tunnel->lock); @@ -3063,7 +3221,7 @@ static int amt_dev_open(struct net_device *dev) static int amt_dev_stop(struct net_device *dev) { struct amt_dev *amt = netdev_priv(dev); - struct amt_tunnel_list *tunnel, *tmp; + struct amt_tunnel_list *tunnel; struct sk_buff *skb; struct sock *sk; int i; @@ -3097,11 +3255,37 @@ static int amt_dev_stop(struct net_device *dev) amt->req_cnt = 0; WRITE_ONCE(amt->remote_ip, 0); - list_for_each_entry_safe(tunnel, tmp, &amt->tunnel_list, list) { - list_del_rcu(&tunnel->list); - amt->nr_tunnels--; + /* Mark every tunnel dead first, so a concurrent amt_tunnel_expire() + * sees ->dead and bails instead of freeing a tunnel in parallel; this + * path is then the sole freer. + */ + spin_lock_bh(&amt->lock); + list_for_each_entry(tunnel, &amt->tunnel_list, list) { + spin_lock_bh(&tunnel->lock); + WRITE_ONCE(tunnel->dead, true); + spin_unlock_bh(&tunnel->lock); + } + spin_unlock_bh(&amt->lock); + + /* Unlink one tunnel at a time with list_del_rcu() rather than splicing + * the list onto a local head: a lockless reader walking tunnel_list + * must always terminate at &amt->tunnel_list, never at a stack head. + */ + for (;;) { + spin_lock_bh(&amt->lock); + tunnel = list_first_entry_or_null(&amt->tunnel_list, + struct amt_tunnel_list, list); + if (tunnel) { + list_del_rcu(&tunnel->list); + amt->nr_tunnels--; + } + spin_unlock_bh(&amt->lock); + if (!tunnel) + break; + cancel_delayed_work_sync(&tunnel->gc_wq); amt_clear_groups(tunnel); + __amt_group_gc_work(); kfree_rcu(tunnel, rcu); } @@ -3475,6 +3659,9 @@ static int __init amt_init(void) INIT_DELAYED_WORK(&source_gc_wq, amt_source_gc_work); mod_delayed_work(amt_wq, &source_gc_wq, msecs_to_jiffies(AMT_GC_INTERVAL)); + INIT_DELAYED_WORK(&group_gc_wq, amt_group_gc_work); + mod_delayed_work(amt_wq, &group_gc_wq, + msecs_to_jiffies(AMT_GC_INTERVAL)); spin_unlock_bh(&source_gc_lock); return 0; @@ -3495,6 +3682,8 @@ static void __exit amt_fini(void) unregister_netdevice_notifier(&amt_notifier_block); cancel_delayed_work_sync(&source_gc_wq); __amt_source_gc_work(); + cancel_delayed_work_sync(&group_gc_wq); + __amt_group_gc_work(); destroy_workqueue(amt_wq); } module_exit(amt_fini); diff --git a/include/net/amt.h b/include/net/amt.h index 2846dde0cadce3..dedf328d841540 100644 --- a/include/net/amt.h +++ b/include/net/amt.h @@ -240,6 +240,17 @@ struct amt_tunnel_list { u32 nr_sources; enum amt_status status; struct delayed_work gc_wq; + /* Last time a Membership Update refreshed this tunnel, under ->lock. + * gc_wq re-arms itself from this rather than being re-armed by the + * Update path, so the Update path cannot re-queue the work of a + * tunnel that amt_tunnel_expire() is freeing. + */ + unsigned long last_seen; + /* Set under amt->lock and tunnel->lock by whichever freer reaches the + * tunnel first; the other then leaves it alone, so the tunnel is freed + * exactly once. + */ + bool dead; __be16 source_port; __be32 ip4; __be32 nonce; @@ -275,6 +286,7 @@ enum amt_source_status { /* protected by gnode->lock */ struct amt_source_node { struct hlist_node node; + struct hlist_node gc_node; struct amt_group_node *gnode; struct delayed_work source_timer; union amt_addr source_addr; @@ -282,6 +294,8 @@ struct amt_source_node { #define AMT_SOURCE_OLD 0 #define AMT_SOURCE_NEW 1 u8 flags; + /* Protected by gnode->tunnel_list->lock. */ + bool dead; struct rcu_head rcu; }; @@ -295,7 +309,10 @@ struct amt_group_node { u32 nr_sources; struct amt_tunnel_list *tunnel_list; struct hlist_node node; + struct hlist_node gc_node; struct delayed_work group_timer; + /* Protected by tunnel_list->lock. */ + bool dead; struct rcu_head rcu; struct hlist_head sources[]; }; @@ -370,6 +387,7 @@ struct amt_dev { #define AMT_IPHDR_OPTS 4 #define AMT_IP6HDR_OPTS 8 #define AMT_GC_INTERVAL (30 * 1000) +#define AMT_GC_KICK 2048 #define AMT_MAX_GROUP 32 #define AMT_MAX_SOURCE 128 #define AMT_HSIZE_SHIFT 8 From b4fa7f8daed658c122bf0407dca9d5a26863f37c Mon Sep 17 00:00:00 2001 From: Omar Ramadan Date: Tue, 10 Nov 2026 21:05:34 +0000 Subject: [PATCH 0921/2102] amt: reject a gateway Query or Data from 0.0.0.0 before a relay is learned A gateway's amt_rcv() admits a Membership Query or Multicast Data message when "saddr != remote_ip" is false. remote_ip is 0 before discovery has learned a relay (and is reset to 0 by amt_dev_open(), by amt_dev_stop(), and when the gateway gives up after its Requests go unanswered), so a packet whose source is 0.0.0.0 would otherwise pass the equality check and could spoof a Query or inject multicast data. IPv4 input accepts a 0.0.0.0 source only on a limited broadcast or a link-local (224.0.0.0/24) multicast destination, so the sender has to be on the gateway's link. A forged Query must also carry the gateway's nonce. That is 0 until the next discovery tick re-randomizes it, because amt_dev_open() and the give-up path in amt_event_send_request() zero amt->nonce along with remote_ip. The Query handler then sets ready4 or ready6, mac and qi, and moves the gateway to AMT_STATUS_RECEIVED_QUERY. From there amt_event_send_discovery() returns early and amt_advertisement_handler() rejects every Advertisement, so discovery stays blocked until the Request retries run out and the device is back in AMT_STATUS_INIT with nonce 0. The Data check is defense in depth: amt_multicast_data_handler() already requires AMT_STATUS_SENT_UPDATE, which a gateway with no relay reaches only after such a forged Query, or in the short window in which the give-up path has cleared remote_ip but not yet reset the status. Reject both when no relay is learned: a 0 remote_ip must match nothing, so guard the check with !remote_ip. A Query is queued before its event worker processes it, so the relay address can also change in that window. Recheck the packet source against the current remote_ip in the handler and discard stale Queries. Discovery is unaffected because Relay Advertisements are validated against discovery_ip, not remote_ip. Found by code inspection while writing the IPv6 receive path for the AMT IPv6 outer transport; not triggered at runtime. The Sashiko AI review of an earlier posting pointed out the nonce condition, the blocked discovery and that the Data check is defense in depth. Fixes: cbc21dc1cfe9 ("amt: add data plane of amt interface") Fixes: 30e22a6ebca0 ("amt: use workqueue for gateway side message handling") Signed-off-by: Omar Ramadan Link: https://patch.msgid.link/20261110210538.217936-4-omar@blockcast.net Signed-off-by: Jakub Kicinski --- drivers/net/amt.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/drivers/net/amt.c b/drivers/net/amt.c index 70eabc523b2f68..13f689af6b51cd 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -2526,6 +2526,10 @@ static bool amt_membership_query_handler(struct amt_dev *amt, if (amtmq->reserved || amtmq->version) return true; + /* A deferred query may outlive a relay address change. */ + if (ip_hdr(skb)->saddr != READ_ONCE(amt->remote_ip)) + return true; + if (amtmq->nonce != amt->nonce) return true; @@ -3004,7 +3008,7 @@ static int amt_rcv(struct sock *sk, struct sk_buff *skb) } goto out; case AMT_MSG_MULTICAST_DATA: - if (saddr != remote_ip) { + if (!remote_ip || saddr != remote_ip) { netdev_dbg(amt->dev, "Invalid Relay IP\n"); err = true; goto drop; @@ -3015,7 +3019,7 @@ static int amt_rcv(struct sock *sk, struct sk_buff *skb) else goto out; case AMT_MSG_MEMBERSHIP_QUERY: - if (saddr != remote_ip) { + if (!remote_ip || saddr != remote_ip) { netdev_dbg(amt->dev, "Invalid Relay IP\n"); err = true; goto drop; From 144183ab4b053460ccbe7ca462e1b0527a617cb7 Mon Sep 17 00:00:00 2001 From: Omar Ramadan Date: Tue, 10 Nov 2026 21:05:35 +0000 Subject: [PATCH 0922/2102] amt: require an exact IPv4-sized IFLA_AMT_{LOCAL,DISCOVERY}_IP The netlink policy for IFLA_AMT_LOCAL_IP and IFLA_AMT_DISCOVERY_IP is an untyped entry with .len set to the size of an IPv4 address, which netlink validation treats as a minimum length only. Any longer payload passes, and nla_get_in_addr() then reads just its first four bytes: an iproute2 that puts a 16-byte IPv6 literal in one of these IPv4 attributes turns "2001:db8::" into 32.1.13.184, and the device is created with an address the user never asked for. Use NLA_POLICY_EXACT_LEN(sizeof(__be32)) for both, so every payload that is not exactly four bytes long is refused with a standard extack instead of being truncated. The range check this expands to fails the attribute even under the liberal parsing rtnetlink applies to IFLA_INFO_DATA. amt_get_size() and amt_fill_info() already emit exactly four bytes for these attributes. IFLA_AMT_REMOTE_IP is only ever reported, never read from a request, so it is left unchanged. Triggered while writing a selftest for the AMT IPv6 outer transport: an iproute2 without the IPv6 attributes put all 16 bytes of "discovery 2001:db8:a::2" into IFLA_AMT_DISCOVERY_IP. On a stock kernel the command exited 0 with no error or warning, and the device came up as an IPv4 gateway with discovery address 32.1.13.184, the first four bytes. There is no oops or trace; the symptom is the silently wrong address, which fooled the selftest's capability probe. Fixes: b9022b53adad ("amt: add control plane of amt interface") Signed-off-by: Omar Ramadan Link: https://patch.msgid.link/20261110210538.217936-5-omar@blockcast.net Signed-off-by: Jakub Kicinski --- drivers/net/amt.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/net/amt.c b/drivers/net/amt.c index 13f689af6b51cd..716451a4f250ae 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -3358,9 +3358,9 @@ static const struct nla_policy amt_policy[IFLA_AMT_MAX + 1] = { [IFLA_AMT_RELAY_PORT] = { .type = NLA_U16 }, [IFLA_AMT_GATEWAY_PORT] = { .type = NLA_U16 }, [IFLA_AMT_LINK] = { .type = NLA_U32 }, - [IFLA_AMT_LOCAL_IP] = { .len = sizeof_field(struct iphdr, daddr) }, + [IFLA_AMT_LOCAL_IP] = NLA_POLICY_EXACT_LEN(sizeof(__be32)), [IFLA_AMT_REMOTE_IP] = { .len = sizeof_field(struct iphdr, daddr) }, - [IFLA_AMT_DISCOVERY_IP] = { .len = sizeof_field(struct iphdr, daddr) }, + [IFLA_AMT_DISCOVERY_IP] = NLA_POLICY_EXACT_LEN(sizeof(__be32)), [IFLA_AMT_MAX_TUNNELS] = { .type = NLA_U32 }, }; From ee58008edb995de5f19222e4aa9a2acf74e80185 Mon Sep 17 00:00:00 2001 From: Omar Ramadan Date: Tue, 10 Nov 2026 21:05:36 +0000 Subject: [PATCH 0923/2102] amt: make pre-query report drops visible A gateway cannot forward an IGMP or MLD report until it has received the relay's Membership Query for that family. The Query supplies the response MAC the Update echoes, so dropping an early report is required, but doing so silently leaves operators with a dark multicast path and no indication why the join never happened. Emit a family-specific debug message before taking the drop path. tx_dropped could not show these drops either: amt_dev_xmit() reaches the same tx_dropped increment after amt_send_membership_update() has handed the report to the tunnel, so in gateway mode every forwarded report was also counted as a drop. Return NETDEV_TX_OK directly once the report has been sent, so a report the tunnel accepted is no longer counted in tx_dropped. The device is LLTX, so amt_dev_xmit() can run on several CPUs at once; use DEV_STATS_INC() for tx_dropped and tx_errors, there and in the control-message senders that update the same counters, so concurrent increments are not lost. Found by code inspection while debugging an IPv6-in-IPv6 forwarding failure in a selftest for the AMT IPv6 outer transport. This drop can leave one address family dark, so it was a suspect, but that was not confirmed: the failure was later traced to the selftest, which sent a single datagram without waiting for the relay's multicast routes to converge. The drop has not been observed in production, and there is no oops or trace. The Sashiko AI review of an earlier posting found the tx_dropped miscount and the non-atomic counter updates. Fixes: cbc21dc1cfe9 ("amt: add data plane of amt interface") Signed-off-by: Omar Ramadan Link: https://patch.msgid.link/20261110210538.217936-6-omar@blockcast.net Signed-off-by: Jakub Kicinski --- drivers/net/amt.c | 42 +++++++++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 17 deletions(-) diff --git a/drivers/net/amt.c b/drivers/net/amt.c index 716451a4f250ae..b7be685d8401f2 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -735,7 +735,7 @@ static void amt_send_discovery(struct amt_dev *amt) IPPROTO_UDP, 0, amt->stream_dev->ifindex); if (IS_ERR(rt)) { - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -745,7 +745,7 @@ static void amt_send_discovery(struct amt_dev *amt) skb = netdev_alloc_skb_ip_align(amt->dev, len); if (!skb) { ip_rt_put(rt); - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -790,7 +790,7 @@ static void amt_send_discovery(struct amt_dev *amt) ip_send_check(iph); err = ip_local_out(amt->net, sk, skb); if (unlikely(net_xmit_eval(err))) - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); amt_update_gw_status(amt, AMT_STATUS_SENT_DISCOVERY, true); out: @@ -826,7 +826,7 @@ static void amt_send_request(struct amt_dev *amt, bool v6) IPPROTO_UDP, 0, amt->stream_dev->ifindex); if (IS_ERR(rt)) { - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -836,7 +836,7 @@ static void amt_send_request(struct amt_dev *amt, bool v6) skb = netdev_alloc_skb_ip_align(amt->dev, len); if (!skb) { ip_rt_put(rt); - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -883,7 +883,7 @@ static void amt_send_request(struct amt_dev *amt, bool v6) ip_send_check(iph); err = ip_local_out(amt->net, sk, skb); if (unlikely(net_xmit_eval(err))) - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); out: rcu_read_unlock(); @@ -905,7 +905,7 @@ static void amt_send_igmp_gq(struct amt_dev *amt, skb_pull(skb, sizeof(struct ethhdr)); if (amt_send_membership_query(amt, skb, tunnel, false)) { - amt->dev->stats.tx_dropped++; + DEV_STATS_INC(amt->dev, tx_dropped); kfree_skb(skb); } } @@ -949,7 +949,7 @@ static struct sk_buff *amt_build_mld_gq(struct amt_dev *amt) if (ipv6_dev_get_saddr(amt->net, amt->dev, &ip6h->daddr, 0, &ip6h->saddr)) { - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); kfree_skb(skb); return NULL; } @@ -993,7 +993,7 @@ static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel) skb_pull(skb, sizeof(struct ethhdr)); if (amt_send_membership_query(amt, skb, tunnel, true)) { - amt->dev->stats.tx_dropped++; + DEV_STATS_INC(amt->dev, tx_dropped); kfree_skb(skb); } } @@ -1353,7 +1353,7 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev) group.ip6 = ipv6_hdr(skb)->daddr; #endif } else { - dev->stats.tx_errors++; + DEV_STATS_INC(dev, tx_errors); goto free; } @@ -1366,12 +1366,21 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev) /* Gateway only passes IGMP/MLD packets */ if (!report) goto free; + /* A validated report can only be forwarded after the relay's + * family-specific Membership Query supplies the state echoed + * by the Membership Update. Log this readiness failure before + * the shared drop path accounts it. + */ if ((!v6 && !READ_ONCE(amt->ready4)) || - (v6 && !READ_ONCE(amt->ready6))) + (v6 && !READ_ONCE(amt->ready6))) { + netdev_dbg(dev, "drop %s report: waiting for Membership Query\n", + v6 ? "MLD" : "IGMP"); goto free; + } if (amt_send_membership_update(amt, skb, v6)) goto free; - goto unlock; + /* Sent: the tunnel consumed the skb. Not a drop. */ + return NETDEV_TX_OK; } else if (amt->mode == AMT_MODE_RELAY) { if (!data) goto free; @@ -1400,8 +1409,7 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev) return NETDEV_TX_OK; free: dev_kfree_skb(skb); -unlock: - dev->stats.tx_dropped++; + DEV_STATS_INC(dev, tx_dropped); return NETDEV_TX_OK; } @@ -2776,7 +2784,7 @@ static void amt_send_advertisement(struct amt_dev *amt, __be32 nonce, IPPROTO_UDP, 0, amt->stream_dev->ifindex); if (IS_ERR(rt)) { - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -2786,7 +2794,7 @@ static void amt_send_advertisement(struct amt_dev *amt, __be32 nonce, skb = netdev_alloc_skb_ip_align(amt->dev, len); if (!skb) { ip_rt_put(rt); - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -2832,7 +2840,7 @@ static void amt_send_advertisement(struct amt_dev *amt, __be32 nonce, ip_send_check(iph); err = ip_local_out(amt->net, sk, skb); if (unlikely(net_xmit_eval(err))) - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); out: rcu_read_unlock(); From 8ddd3a1c207f2f777f01d02110e556a187da73c6 Mon Sep 17 00:00:00 2001 From: Omar Ramadan Date: Tue, 10 Nov 2026 21:05:37 +0000 Subject: [PATCH 0924/2102] amt: create relay tunnels only from authenticated Updates An AMT Request has an unauthenticated, spoofable source address. Allocating tunnel state from that path allowed spoofed Requests to consume tunnel slots or overwrite the nonce and MAC of an established gateway. Keep Requests stateless by deriving the Query MAC from the source address, source port, nonce, and current secret, and retain four secret generations so a gateway can renew its MAC across rotations. Authenticate the Membership Update before decapsulation, and create or refresh tunnel state only once ip_mc_check_igmp() or ipv6_mc_check_mld() has accepted the encapsulated message. Key verified state by the address/port endpoint, enforce global and per-source limits, and silently reject an endpoint that cannot be admitted: withhold the Query rather than send ICMP Host Unreachable to a source address nothing has authenticated yet. A MAC is now accepted only for a bounded time after the Query that carried it. Before, a tunnel copied the secret when a Request created it and never saw it rotate, so its MAC never expired. Now the secret rotates every 60 seconds and four generations are kept, so a MAC is accepted for 180 to 240 seconds. RFC 7450 section 5.2.3.5.4 has a gateway start a query timer when it accepts a Query, with a duration it SHOULD compute from the Query's QQIC (125 seconds here), and section 5.2.3.5.5 has it send a new Request when that timer expires, so a gateway that times its next Request from QQIC renews its MAC inside the window. The in-tree gateway re-Requests every two seconds while its Requests are answered. A gateway that never sends another Request kept working before; now its Updates are dropped as Invalid MAC once the window has passed. So is the first Update after a new join from a gateway that, as section 5.2.3.5.4 also allows, uses a longer timer while it has no group subscriptions to report: it is dropped until that gateway's next Request. Which MACs are accepted changes too. Before, an Update had to carry the nonce and MAC of the latest Request from its address; now any pair minted for its address and port within the window is accepted. The MAC never covered the encapsulated report, so this changes only how long a pair seen by an on-path observer stays usable: off-path senders still cannot produce a valid pair. The secret is now seeded before amt_socket_create() enables the receive path. It was seeded after the socket was created since commit b9022b53adad ("amt: add control plane of amt interface"), when there was no receive path yet, and commit cbc21dc1cfe9 ("amt: add data plane of amt interface") added amt_rcv() and the per-tunnel copy of the key without moving it. Since then a Request that arrived during amt_dev_open() could get a tunnel whose MAC used an all-zero key (on the first open) or the previous key for the tunnel's whole life. amt_update_tunnel() retries once when it finds its tunnel dead, and the lookup skips dead tunnels, so an Update that races amt_tunnel_expire() creates the replacement instead of being dropped. The Request path's per-source count and the re-check under amt->lock in amt_tunnel_get_or_create() skip them too. Every tunnel is now created by an Update, which stamps last_seen, so amt_tunnel_expire() no longer treats a last_seen of 0 as never refreshed. amt_tunnel_get_or_create() also rechecks netif_running() under amt->lock before it links a tunnel. dev_close() clears the running state before it calls amt_dev_stop(), which drains the list under amt->lock, so an Update still being received while the device goes down cannot link a tunnel after the drain. Every Membership Update, forged ones included, reads the secret generations to check its MAC. Their writers hold amt->lock and update them inside a seqcount, amt->key_seq. The Update path copies them in a key_seq read loop, so reading them takes amt->lock only on PREEMPT_RT, to wait for a writer. Keying by address and port lets one address hold several tunnels; before this patch the Request path looked tunnels up by address alone, so an address normally held only one. amt_max_tunnels_per_src() bounds that at an eighth of max_tunnels, at least one tunnel and at most AMT_MAX_TUNNELS_PER_SRC (16): 16 at the default 128 slots, 2 at 16. One address then holds at most an eighth of a table of eight or more slots, while gateways behind NAT still get several tunnels once the table has 16 or more slots. A configurable limit needs new uAPI, so it is left for net-next. Found by code inspection against RFC 7450; not triggered at runtime. The Sashiko AI review of an earlier posting pointed out the undocumented behaviour changes and that a fixed per-source cap let one address fill a small table. Fixes: cbc21dc1cfe9 ("amt: add data plane of amt interface") Signed-off-by: Omar Ramadan Link: https://patch.msgid.link/20261110210538.217936-7-omar@blockcast.net Signed-off-by: Jakub Kicinski --- drivers/net/amt.c | 405 ++++++++++++++++++++++++++++++++-------------- include/net/amt.h | 14 +- 2 files changed, 294 insertions(+), 125 deletions(-) diff --git a/drivers/net/amt.c b/drivers/net/amt.c index b7be685d8401f2..b145ed3ca6ede2 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -700,14 +700,6 @@ static void __amt_update_relay_status(struct amt_tunnel_list *tunnel, tunnel->status = status; } -static void amt_update_relay_status(struct amt_tunnel_list *tunnel, - enum amt_status status, bool validate) -{ - spin_lock_bh(&tunnel->lock); - __amt_update_relay_status(tunnel, status, validate); - spin_unlock_bh(&tunnel->lock); -} - static void amt_send_discovery(struct amt_dev *amt) { struct amt_header_discovery *amtd; @@ -891,11 +883,16 @@ static void amt_send_request(struct amt_dev *amt, bool v6) static bool amt_send_membership_query(struct amt_dev *amt, struct sk_buff *skb, - struct amt_tunnel_list *tunnel, + __be32 daddr, __be16 dport, + __be32 nonce, u64 mac, bool v6); -static void amt_send_igmp_gq(struct amt_dev *amt, - struct amt_tunnel_list *tunnel) +/* The destination is passed by value rather than as a tunnel: a Request is + * unauthenticated, so no tunnel state is created or changed for it - see + * amt_request_handler(). + */ +static void amt_send_igmp_gq(struct amt_dev *amt, __be32 daddr, __be16 dport, + __be32 nonce, u64 mac) { struct sk_buff *skb; @@ -904,7 +901,8 @@ static void amt_send_igmp_gq(struct amt_dev *amt, return; skb_pull(skb, sizeof(struct ethhdr)); - if (amt_send_membership_query(amt, skb, tunnel, false)) { + if (amt_send_membership_query(amt, skb, daddr, dport, nonce, mac, + false)) { DEV_STATS_INC(amt->dev, tx_dropped); kfree_skb(skb); } @@ -983,7 +981,8 @@ static struct sk_buff *amt_build_mld_gq(struct amt_dev *amt) return skb; } -static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel) +static void amt_send_mld_gq(struct amt_dev *amt, __be32 daddr, __be16 dport, + __be32 nonce, u64 mac) { struct sk_buff *skb; @@ -992,13 +991,15 @@ static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel) return; skb_pull(skb, sizeof(struct ethhdr)); - if (amt_send_membership_query(amt, skb, tunnel, true)) { + if (amt_send_membership_query(amt, skb, daddr, dport, nonce, mac, + true)) { DEV_STATS_INC(amt->dev, tx_dropped); kfree_skb(skb); } } #else -static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel) +static void amt_send_mld_gq(struct amt_dev *amt, __be32 daddr, __be16 dport, + __be32 nonce, u64 mac) { } #endif @@ -1032,7 +1033,16 @@ static void amt_secret_work(struct work_struct *work) secret_wq); spin_lock_bh(&amt->lock); - get_random_bytes(&amt->key, sizeof(siphash_key_t)); + write_seqcount_begin(&amt->key_seq); + /* Keep three previous generations for a 180-240s MAC lifetime. + * Its 180s floor exceeds the advertised QQIC (amt->qi, 125s), + * allowing the gateway to renew its MAC with a periodic Request. + */ + amt->key[3] = amt->key[2]; + amt->key[2] = amt->key[1]; + amt->key[1] = amt->key[0]; + get_random_bytes(&amt->key[0], sizeof(siphash_key_t)); + write_seqcount_end(&amt->key_seq); spin_unlock_bh(&amt->lock); mod_delayed_work(amt_wq, &amt->secret_wq, msecs_to_jiffies(AMT_SECRET_TIMEOUT)); @@ -1232,9 +1242,16 @@ static void amt_send_multicast_data(struct amt_dev *amt, 0); } +/* Send a Membership Query in reply to an unauthenticated Request. + * + * No per-source state is read or created: the gateway echoes the nonce and + * the keyed MAC in its Membership Update, where the MAC is recomputed, so + * everything this needs is passed by value. + */ static bool amt_send_membership_query(struct amt_dev *amt, struct sk_buff *skb, - struct amt_tunnel_list *tunnel, + __be32 daddr, __be16 dport, + __be32 nonce, u64 mac, bool v6) { struct amt_header_membership_query *amtmq; @@ -1255,13 +1272,13 @@ static bool amt_send_membership_query(struct amt_dev *amt, skb_reset_inner_headers(skb); memset(&fl4, 0, sizeof(struct flowi4)); fl4.flowi4_oif = amt->stream_dev->ifindex; - fl4.daddr = tunnel->ip4; + fl4.daddr = daddr; fl4.saddr = amt->local_ip; fl4.flowi4_dscp = inet_dsfield_to_dscp(AMT_TOS); fl4.flowi4_proto = IPPROTO_UDP; rt = ip_route_output_key(amt->net, &fl4); if (IS_ERR(rt)) { - netdev_dbg(amt->dev, "no route to %pI4\n", &tunnel->ip4); + netdev_dbg(amt->dev, "no route to %pI4\n", &daddr); return true; } @@ -1271,8 +1288,8 @@ static bool amt_send_membership_query(struct amt_dev *amt, amtmq->reserved = 0; amtmq->l = 0; amtmq->g = 0; - amtmq->nonce = tunnel->nonce; - amtmq->response_mac = tunnel->mac; + amtmq->nonce = nonce; + amtmq->response_mac = mac; if (!v6) skb_set_inner_protocol(skb, htons(ETH_P_IP)); @@ -1285,11 +1302,10 @@ static bool amt_send_membership_query(struct amt_dev *amt, ip4_dst_hoplimit(&rt->dst), 0, amt->relay_port, - tunnel->source_port, + dport, false, false, 0); - amt_update_relay_status(tunnel, AMT_STATUS_SENT_QUERY, true); return false; } @@ -1477,12 +1493,7 @@ static void amt_tunnel_expire(struct work_struct *work) * or finds it dead. */ now = jiffies; - deadline = tunnel->last_seen; - /* No Update yet: the Request armed gc_wq for one GMI. */ - if (!deadline) - deadline = now; - else - deadline += msecs_to_jiffies(amt_gmi(amt)) * 3; + deadline = tunnel->last_seen + msecs_to_jiffies(amt_gmi(amt)) * 3; if (time_before(now, deadline)) { mod_delayed_work(amt_wq, &tunnel->gc_wq, deadline - now); spin_unlock_bh(&tunnel->lock); @@ -2630,16 +2641,165 @@ static bool amt_membership_query_handler(struct amt_dev *amt, return false; } +/* The live tunnel of the gateway endpoint @saddr:@sport, or NULL. Dead + * tunnels are skipped, so the retry in amt_update_tunnel() after losing a + * race with amt_tunnel_expire() creates the replacement. + */ +static struct amt_tunnel_list *amt_tunnel_lookup(struct amt_dev *amt, + __be32 saddr, __be16 sport) +{ + struct amt_tunnel_list *tunnel; + + list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) { + if (tunnel->ip4 == saddr && tunnel->source_port == sport && + !READ_ONCE(tunnel->dead)) + return tunnel; + } + return NULL; +} + +/* Most tunnels one source address may hold: an eighth of the table, at + * least one and at most AMT_MAX_TUNNELS_PER_SRC. + */ +static u32 amt_max_tunnels_per_src(const struct amt_dev *amt) +{ + return clamp_t(u32, amt->max_tunnels / 8, 1, + AMT_MAX_TUNNELS_PER_SRC); +} + +/* Look up the tunnel for a source whose Membership Update has already been + * authenticated, creating it on first contact. + * + * This is the only place tunnel state is allocated, so amt->max_tunnels + * bounds the number of *verified* gateways rather than the number of + * unverified Requests anyone can send. A per-source cap derived from the + * table, amt_max_tunnels_per_src(), additionally limits the tunnels one + * verified source address may hold. + */ +static struct amt_tunnel_list *amt_tunnel_get_or_create(struct amt_dev *amt, + __be32 saddr, + __be16 sport) +{ + struct amt_tunnel_list *tunnel; + u32 per_src = 0; + int i; + + tunnel = amt_tunnel_lookup(amt, saddr, sport); + if (tunnel) + return tunnel; + + spin_lock_bh(&amt->lock); + + /* Re-check under the lock in case a concurrent Update won the race, and + * count how many tunnels this source already holds on the same walk. + * Skip dead tunnels, as amt_tunnel_lookup() and the Request path do, so + * a tunnel being freed neither stands in for its endpoint nor counts + * against its address. + */ + list_for_each_entry(tunnel, &amt->tunnel_list, list) { + if (tunnel->ip4 != saddr || READ_ONCE(tunnel->dead)) + continue; + if (tunnel->source_port == sport) { + spin_unlock_bh(&amt->lock); + return tunnel; + } + per_src++; + } + + if (amt->nr_tunnels >= amt->max_tunnels || + per_src >= amt_max_tunnels_per_src(amt)) { + spin_unlock_bh(&amt->lock); + return NULL; + } + + if (!netif_running(amt->dev)) { + spin_unlock_bh(&amt->lock); + return NULL; + } + + tunnel = kzalloc(sizeof(*tunnel) + + (sizeof(struct hlist_head) * amt->hash_buckets), + GFP_ATOMIC); + if (!tunnel) { + spin_unlock_bh(&amt->lock); + return NULL; + } + + tunnel->source_port = sport; + tunnel->ip4 = saddr; + tunnel->amt = amt; + spin_lock_init(&tunnel->lock); + for (i = 0; i < amt->hash_buckets; i++) + INIT_HLIST_HEAD(&tunnel->groups[i]); + + tunnel->last_seen = jiffies; + INIT_DELAYED_WORK(&tunnel->gc_wq, amt_tunnel_expire); + __amt_update_relay_status(tunnel, AMT_STATUS_RECEIVED_UPDATE, false); + + /* Publish only once the entry is fully initialised. */ + list_add_tail_rcu(&tunnel->list, &amt->tunnel_list); + amt->nr_tunnels++; + mod_delayed_work(amt_wq, &tunnel->gc_wq, + msecs_to_jiffies(amt_gmi(amt)) * 3); + spin_unlock_bh(&amt->lock); + + return tunnel; +} + +/* Apply a valid, authenticated Membership Update to the tunnel of its + * endpoint, creating the tunnel on first contact. Returns false if the + * Update is dropped. + * + * amt_tunnel_expire() reads last_seen and sets dead under tunnel->lock, so + * the refresh below either keeps the tunnel alive or finds it dead. A + * tunnel that expired between the lookup and the lock is skipped by the + * second amt_tunnel_get_or_create() call, which creates its replacement. + */ +static bool amt_update_tunnel(struct amt_dev *amt, struct sk_buff *skb, + __be32 saddr, __be16 sport, bool v6) +{ + struct amt_tunnel_list *tunnel; + int i; + + for (i = 0; i < 2; i++) { + tunnel = amt_tunnel_get_or_create(amt, saddr, sport); + if (!tunnel) + return false; + + spin_lock_bh(&tunnel->lock); + if (!READ_ONCE(tunnel->dead)) { + /* gc_wq is re-armed by amt_tunnel_expire() itself + * from last_seen, never from here, so this cannot + * re-queue the work of a tunnel that is being freed. + */ + tunnel->last_seen = jiffies; +#if IS_ENABLED(CONFIG_IPV6) + if (v6) + amt_mld_report_handler(amt, skb, tunnel); + else +#endif + amt_igmp_report_handler(amt, skb, tunnel); + spin_unlock_bh(&tunnel->lock); + return true; + } + spin_unlock_bh(&tunnel->lock); + } + return false; +} + static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) { struct amt_header_membership_update *amtmu; - struct amt_tunnel_list *tunnel; + bool verified = false; + siphash_key_t key[4]; + int len, hdr_size, i; struct ethhdr *eth; struct iphdr *iph; - int len, hdr_size; + unsigned int seq; u64 response_mac; __be32 saddr; __be32 nonce; + __be16 sport; saddr = ip_hdr(skb)->saddr; @@ -2653,27 +2813,45 @@ static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) nonce = amtmu->nonce; response_mac = amtmu->response_mac; + /* Snapshot the tunnel endpoint port before the encap is stripped. */ + sport = udp_hdr(skb)->source; + /* Recompute the MAC handed out in the Membership Query. Four live + * secrets cover 180-240s, exceeding the advertised QQIC (amt->qi, + * 125s), so a periodic Request can renew the MAC before it expires. + * Authenticate before decapsulation or allocating tunnel state. + */ + do { + seq = read_seqcount_begin(&amt->key_seq); + for (i = 0; i < ARRAY_SIZE(key); i++) + key[i] = amt->key[i]; + } while (read_seqcount_retry(&amt->key_seq, seq)); + + for (i = 0; i < ARRAY_SIZE(key); i++) { + u64 mac = siphash_3u32((__force u32)saddr, + (__force u32)sport, + (__force u32)nonce, + &key[i]) >> 16; + + if (response_mac == mac) { + verified = true; + break; + } + } + + if (!verified) { + netdev_dbg(amt->dev, "Invalid MAC\n"); + return true; + } + + /* Create or refresh a tunnel only once the encapsulated message has + * passed ip_mc_check_igmp() or ipv6_mc_check_mld(). + */ if (iptunnel_pull_header(skb, hdr_size, skb->protocol, false)) return true; skb_reset_network_header(skb); - list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) { - if (tunnel->ip4 == saddr) { - if ((nonce == tunnel->nonce && - response_mac == tunnel->mac)) { - goto report; - } else { - netdev_dbg(amt->dev, "Invalid MAC\n"); - return true; - } - } - } - - return true; - -report: if (!pskb_may_pull(skb, sizeof(*iph))) return true; @@ -2687,21 +2865,8 @@ static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) return true; } - spin_lock_bh(&tunnel->lock); - if (READ_ONCE(tunnel->dead)) { - spin_unlock_bh(&tunnel->lock); + if (!amt_update_tunnel(amt, skb, saddr, sport, false)) return true; - } - /* Refresh liveness under tunnel->lock, where - * amt_tunnel_expire() reads it; 0 is kept for a tunnel no - * Update has refreshed. gc_wq is re-armed by - * amt_tunnel_expire() itself from last_seen, never from - * here, so this cannot re-queue the work of a tunnel that is - * being freed. - */ - tunnel->last_seen = jiffies ?: 1; - amt_igmp_report_handler(amt, skb, tunnel); - spin_unlock_bh(&tunnel->lock); skb_push(skb, sizeof(struct ethhdr)); skb_reset_mac_header(skb); @@ -2719,14 +2884,8 @@ static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) return true; } - spin_lock_bh(&tunnel->lock); - if (READ_ONCE(tunnel->dead)) { - spin_unlock_bh(&tunnel->lock); + if (!amt_update_tunnel(amt, skb, saddr, sport, true)) return true; - } - tunnel->last_seen = jiffies ?: 1; - amt_mld_report_handler(amt, skb, tunnel); - spin_unlock_bh(&tunnel->lock); skb_push(skb, sizeof(struct ethhdr)); skb_reset_mac_header(skb); @@ -2745,13 +2904,10 @@ static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) skb->pkt_type = PACKET_MULTICAST; skb->ip_summed = CHECKSUM_NONE; len = skb->len; - if (__netif_rx(skb) == NET_RX_SUCCESS) { - amt_update_relay_status(tunnel, AMT_STATUS_RECEIVED_UPDATE, - true); + if (__netif_rx(skb) == NET_RX_SUCCESS) dev_sw_netstats_rx_add(amt->dev, len); - } else { + else amt->dev->stats.rx_dropped++; - } return false; } @@ -2867,15 +3023,30 @@ static bool amt_discovery_handler(struct amt_dev *amt, struct sk_buff *skb) return false; } +/* Handle an AMT Request. + * + * The source of a Request is unauthenticated: it is a bare UDP datagram with a + * trivially spoofable source address. Allocating tunnel state here would let + * an attacker fill the table from spoofed addresses, or let one spoofed packet + * overwrite the nonce/MAC of an established tunnel and cut that gateway off. + * + * Nothing needs to be remembered at this point. Every input to the keyed MAC + * is carried in the packet or is device state, so the MAC is generated here, + * echoed back by the gateway in its Membership Update, and recomputed and + * verified there - see amt_update_handler(). Tunnel state is created only once + * that verification succeeds and the encapsulated message passes its IGMP or + * MLD check. + */ static bool amt_request_handler(struct amt_dev *amt, struct sk_buff *skb) { struct amt_header_request *amtrh; struct amt_tunnel_list *tunnel; - unsigned long long key; + bool full, have = false; struct udphdr *udph; struct iphdr *iph; + siphash_key_t key; + u32 per_src = 0; u64 mac; - int i; if (!pskb_may_pull(skb, sizeof(*udph) + sizeof(*amtrh))) return true; @@ -2887,59 +3058,45 @@ static bool amt_request_handler(struct amt_dev *amt, struct sk_buff *skb) if (amtrh->reserved1 || amtrh->reserved2 || amtrh->version) return true; - list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) - if (tunnel->ip4 == iph->saddr) - goto send; - - spin_lock_bh(&amt->lock); - if (amt->nr_tunnels >= amt->max_tunnels) { - spin_unlock_bh(&amt->lock); - icmp_ndo_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0); - return true; - } - - tunnel = kzalloc(sizeof(*tunnel) + - (sizeof(struct hlist_head) * amt->hash_buckets), - GFP_ATOMIC); - if (!tunnel) { - spin_unlock_bh(&amt->lock); + if (!netif_running(amt->dev) || !netif_running(amt->stream_dev)) return true; - } - - tunnel->source_port = udph->source; - tunnel->ip4 = iph->saddr; - - memcpy(&key, &tunnel->key, sizeof(unsigned long long)); - tunnel->amt = amt; - spin_lock_init(&tunnel->lock); - for (i = 0; i < amt->hash_buckets; i++) - INIT_HLIST_HEAD(&tunnel->groups[i]); - INIT_DELAYED_WORK(&tunnel->gc_wq, amt_tunnel_expire); - - list_add_tail_rcu(&tunnel->list, &amt->tunnel_list); - tunnel->key = amt->key; - __amt_update_relay_status(tunnel, AMT_STATUS_RECEIVED_REQUEST, true); - amt->nr_tunnels++; - mod_delayed_work(amt_wq, &tunnel->gc_wq, - msecs_to_jiffies(amt_gmi(amt))); + /* Snapshot the secret and the table-full state under the lock and walk + * the endpoints outside it, so a Request holds amt->lock only for this + * O(1) snapshot. + */ + spin_lock_bh(&amt->lock); + key = amt->key[0]; + full = amt->nr_tunnels >= amt->max_tunnels; spin_unlock_bh(&amt->lock); -send: - tunnel->nonce = amtrh->nonce; - mac = siphash_3u32((__force u32)tunnel->ip4, - (__force u32)tunnel->source_port, - (__force u32)tunnel->nonce, - &tunnel->key); - tunnel->mac = mac >> 16; + /* Skip dead tunnels, as amt_tunnel_lookup() does: each is already + * being torn down, so it must not count against a new endpoint. + */ + rcu_read_lock(); + list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) { + if (tunnel->ip4 != iph->saddr || READ_ONCE(tunnel->dead)) + continue; + per_src++; + if (tunnel->source_port == udph->source) + have = true; + } + rcu_read_unlock(); - if (!netif_running(amt->dev) || !netif_running(amt->stream_dev)) + /* Withhold the Query when a new endpoint cannot get a tunnel. */ + if (!have && (full || per_src >= amt_max_tunnels_per_src(amt))) return true; + mac = siphash_3u32((__force u32)iph->saddr, + (__force u32)udph->source, + (__force u32)amtrh->nonce, + &key) >> 16; if (!amtrh->p) - amt_send_igmp_gq(amt, tunnel); + amt_send_igmp_gq(amt, iph->saddr, udph->source, amtrh->nonce, + mac); else - amt_send_mld_gq(amt, tunnel); + amt_send_mld_gq(amt, iph->saddr, udph->source, amtrh->nonce, + mac); return false; } @@ -3207,6 +3364,16 @@ static int amt_dev_open(struct net_device *dev) enable_delayed_work(&amt->discovery_wq); enable_delayed_work(&amt->req_wq); + /* Seed the keys before amt_socket_create() enables the encap receive + * path, so no Query MAC is generated, and no Update verified, with an + * all-zero (predictable) secret. + */ + spin_lock_bh(&amt->lock); + write_seqcount_begin(&amt->key_seq); + get_random_bytes(&amt->key, sizeof(amt->key)); + write_seqcount_end(&amt->key_seq); + spin_unlock_bh(&amt->lock); + err = amt_socket_create(amt); if (err) { disable_delayed_work(&amt->req_wq); @@ -3217,7 +3384,6 @@ static int amt_dev_open(struct net_device *dev) amt->req_cnt = 0; WRITE_ONCE(amt->remote_ip, 0); amt->nonce = 0; - get_random_bytes(&amt->key, sizeof(siphash_key_t)); amt->status = AMT_STATUS_INIT; if (amt->mode == AMT_MODE_GATEWAY) { @@ -3435,6 +3601,7 @@ static int amt_newlink(struct net_device *dev, amt->max_tunnels = AMT_MAX_TUNNELS; spin_lock_init(&amt->lock); + seqcount_spinlock_init(&amt->key_seq, &amt->lock); amt->max_groups = AMT_MAX_GROUP; amt->max_sources = AMT_MAX_SOURCE; amt->hash_buckets = AMT_HSIZE; diff --git a/include/net/amt.h b/include/net/amt.h index dedf328d841540..9ba09712731da9 100644 --- a/include/net/amt.h +++ b/include/net/amt.h @@ -253,10 +253,6 @@ struct amt_tunnel_list { bool dead; __be16 source_port; __be32 ip4; - __be32 nonce; - siphash_key_t key; - u64 mac:48, - reserved:16; struct rcu_head rcu; struct hlist_head groups[]; }; @@ -342,8 +338,12 @@ struct amt_dev { struct work_struct event_wq; /* AMT status */ enum amt_status status; - /* Generated key */ - siphash_key_t key; + /* Current key and three previous generations keep MACs valid for + * 180-240s, beyond the advertised QQIC (see amt_secret_work()). + */ + siphash_key_t key[4]; + /* For lockless readers of key; writers hold lock */ + seqcount_spinlock_t key_seq; struct sock __rcu *sk; u32 max_groups; u32 max_sources; @@ -401,6 +401,8 @@ struct amt_dev { #define AMT_SECRET_TIMEOUT 60000 #define IANA_AMT_UDP_PORT 2268 #define AMT_MAX_TUNNELS 128 +/* Upper bound of amt_max_tunnels_per_src(), the per-address tunnel cap */ +#define AMT_MAX_TUNNELS_PER_SRC 16 #define AMT_MAX_REQS 128 #define AMT_GW_HLEN (sizeof(struct iphdr) + \ sizeof(struct udphdr) + \ From 4957f668681a2e1e2dab4731d75a2c53c6017319 Mon Sep 17 00:00:00 2001 From: Filip Balluch Date: Thu, 12 Nov 2026 16:45:56 -0800 Subject: [PATCH 0925/2102] i40e: fix freeing of TX rings on RX allocation failure When ethtool -G is used to change ring buffer sizes while the interface is up, i40e_set_ringparam() allocates temporary TX and RX rings. If the RX ring allocation fails, the error path at the free_tx label incorrectly calls i40e_free_tx_resources(vsi->tx_rings[i]), freeing the live TX rings instead of the temporary tx_rings[i]. Since the interface is still up, the next TX completion interrupt causes i40e_clean_tx_irq() to dereference the freed ring descriptors, resulting in a NULL pointer dereference in IRQ context and a kernel panic. This can be reproduced on systems with Intel X710 NICs under memory pressure, where the second port's DMA allocation fails after the first port succeeds. Fix by freeing the temporary tx_rings[i] in the error path instead of the live vsi->tx_rings[i]. Fixes: 74608d17fe29 ("i40e: add support for XDP_TX action") Signed-off-by: Filip Balluch Reviewed-by: Aleksandr Loktionov Tested-by: Alexander Nowlin Signed-off-by: Tony Nguyen Link: https://patch.msgid.link/20261113004602.129864-3-anthony.l.nguyen@intel.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/intel/i40e/i40e_ethtool.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/ethernet/intel/i40e/i40e_ethtool.c b/drivers/net/ethernet/intel/i40e/i40e_ethtool.c index 6a992df06fa11b..ef756487d6684e 100644 --- a/drivers/net/ethernet/intel/i40e/i40e_ethtool.c +++ b/drivers/net/ethernet/intel/i40e/i40e_ethtool.c @@ -2249,7 +2249,7 @@ static int i40e_set_ringparam(struct net_device *netdev, if (tx_rings) { for (i = 0; i < tx_alloc_queue_pairs; i++) { if (i40e_active_tx_ring_index(vsi, i)) - i40e_free_tx_resources(vsi->tx_rings[i]); + i40e_free_tx_resources(&tx_rings[i]); } kfree(tx_rings); tx_rings = NULL; From e3916fa03f4d300be91468a7b7a608d38b6b3277 Mon Sep 17 00:00:00 2001 From: Aleksandr Loktionov Date: Thu, 12 Nov 2026 16:45:57 -0800 Subject: [PATCH 0926/2102] i40e: avoid resetting BQL state when freeing temporary Tx rings in set_ringparam Temporary Tx rings built by i40e_set_ringparam() while resizing descriptor counts are shallow struct copies of the live vsi->tx_rings[] entries, so they retain the same ring->netdev and ring->queue_index as the live ring they are staged to replace. If an error path frees one of these clones with i40e_free_tx_resources() before i40e_down() has run - either the i40e_setup_tx_descriptors() failure unwind loop, or the free_tx: error label - i40e_clean_tx_ring() will call netdev_tx_reset_queue() on txring_txq(tx_ring), which resolves to the *same* netdev_queue as the live ring because netdev/queue_index alias. That call resets the queue's BQL/dql state (dql_reset(): num_queued = num_completed = 0) while the live ring is still actively transmitting and completing Tx on that same queue. The next time the live ring reports completions for bytes that were queued before the reset, dql_completed() can underflow its own sanity check and hit: BUG_ON(count > num_queued - dql->num_completed); i.e. a guaranteed kernel panic, not just a warning, given a queue with outstanding (queued but not yet completed) Tx traffic at the moment the clone is freed. Reproduced on real hardware by forcing i40e_setup_tx_descriptors() to fail partway through building tx_rings[] while flooding real Tx traffic on the affected queues: kernel BUG at lib/dynamic_queue_limits.c:99! RIP: 0010:dql_completed+0x285/0x2a0 Call Trace: i40e_napi_poll+0x74b/0x1700 [i40e] __napi_poll+0x10a/0x200 net_rx_action+0x2f7/0x380 handle_softirqs+0xcc/0x270 Confirmed the same trigger no longer panics with this fix applied, including repeated resize/traffic cycles. Clear the clone ring netdev before freeing it in both error paths, so i40e_clean_tx_ring()'s existing `if (!tx_ring->netdev) return;` guard skips the netdev_tx_reset_queue() call for the clone. This mirrors the same idiom i40e already uses for XDP Tx rings, which also have no netdev_queue of their own (ring->netdev = NULL in i40e_vsi_setup_tx()). Only the temporary, about-to-be-freed clone is touched; the live ring in vsi->tx_rings[] keeps its netdev. Fixes: 9f65e15b4f98 ("i40e: Move rings from pointer to array to array of pointers") Cc: stable@vger.kernel.org Signed-off-by: Aleksandr Loktionov Tested-by: Alexander Nowlin Signed-off-by: Tony Nguyen Link: https://patch.msgid.link/20261113004602.129864-4-anthony.l.nguyen@intel.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/intel/i40e/i40e_ethtool.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/intel/i40e/i40e_ethtool.c b/drivers/net/ethernet/intel/i40e/i40e_ethtool.c index ef756487d6684e..58d842d6764223 100644 --- a/drivers/net/ethernet/intel/i40e/i40e_ethtool.c +++ b/drivers/net/ethernet/intel/i40e/i40e_ethtool.c @@ -2143,6 +2143,8 @@ static int i40e_set_ringparam(struct net_device *netdev, i--; if (!i40e_active_tx_ring_index(vsi, i)) continue; + /* not live yet, skip its BQL reset on free */ + tx_rings[i].netdev = NULL; i40e_free_tx_resources(&tx_rings[i]); } kfree(tx_rings); @@ -2248,8 +2250,11 @@ static int i40e_set_ringparam(struct net_device *netdev, /* error cleanup if the Rx allocations failed after getting Tx */ if (tx_rings) { for (i = 0; i < tx_alloc_queue_pairs; i++) { - if (i40e_active_tx_ring_index(vsi, i)) + if (i40e_active_tx_ring_index(vsi, i)) { + /* not live yet, skip its BQL reset on free */ + tx_rings[i].netdev = NULL; i40e_free_tx_resources(&tx_rings[i]); + } } kfree(tx_rings); tx_rings = NULL; From 65f6ffb9001bf539aebd478798460477980b60c4 Mon Sep 17 00:00:00 2001 From: Xuanqiang Luo Date: Thu, 12 Nov 2026 16:45:58 -0800 Subject: [PATCH 0927/2102] iavf: fix QoS capabilities memory leak Commit 4c1a457cb8b0 ("iavf: add support to exchange qos capabilities") allocates adapter->qos_caps during probe, but iavf_remove() does not free it. This leaks the allocation whenever an iavf device is removed. Free adapter->qos_caps in iavf_remove(). Fixes: 4c1a457cb8b0 ("iavf: add support to exchange qos capabilities") Cc: stable@vger.kernel.org Reviewed-by: Jedrzej Jagielski Signed-off-by: Xuanqiang Luo Reviewed-by: Aleksandr Loktionov Signed-off-by: Tony Nguyen Link: https://patch.msgid.link/20261113004602.129864-5-anthony.l.nguyen@intel.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/intel/iavf/iavf_main.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/net/ethernet/intel/iavf/iavf_main.c b/drivers/net/ethernet/intel/iavf/iavf_main.c index 2f8a80a1133626..4de3ea8525b3fa 100644 --- a/drivers/net/ethernet/intel/iavf/iavf_main.c +++ b/drivers/net/ethernet/intel/iavf/iavf_main.c @@ -5638,6 +5638,7 @@ static void iavf_remove(struct pci_dev *pdev) iounmap(hw->hw_addr); pci_release_regions(pdev); kfree(adapter->vf_res); + kfree(adapter->qos_caps); spin_lock_bh(&adapter->mac_vlan_list_lock); /* If we got removed before an up/down sequence, we've got a filter * hanging out there that we need to get rid of. From 2a1f106379a90ce7ac63f96a57c241a4cf20a983 Mon Sep 17 00:00:00 2001 From: Xuanqiang Luo Date: Thu, 12 Nov 2026 16:45:59 -0800 Subject: [PATCH 0928/2102] iavf: fix ASQ command buffer leak on init failure iavf_alloc_adminq_asq_ring() allocates cmd_buf before the remaining ASQ resources. If iavf_alloc_asq_bufs() or iavf_config_asq_regs() fails, the unwind path elides cmd_buf while freeing the other allocations. The ASQ count is not set until initialization succeeds, so the shutdown path cannot reclaim the buffer. Free cmd_buf in the common unwind path. Fixes: d358aa9a7a2d ("i40evf: init code and hardware support") Cc: stable@vger.kernel.org Signed-off-by: Xuanqiang Luo Reviewed-by: Jedrzej Jagielski Reviewed-by: Aleksandr Loktionov Signed-off-by: Tony Nguyen Link: https://patch.msgid.link/20261113004602.129864-6-anthony.l.nguyen@intel.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/intel/iavf/iavf_adminq.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/net/ethernet/intel/iavf/iavf_adminq.c b/drivers/net/ethernet/intel/iavf/iavf_adminq.c index 6937b7dd44cbb6..40f76f9507f4bb 100644 --- a/drivers/net/ethernet/intel/iavf/iavf_adminq.c +++ b/drivers/net/ethernet/intel/iavf/iavf_adminq.c @@ -60,6 +60,7 @@ static enum iavf_status iavf_alloc_adminq_arq_ring(struct iavf_hw *hw) **/ static void iavf_free_adminq_asq(struct iavf_hw *hw) { + iavf_free_virt_mem(hw, &hw->aq.asq.cmd_buf); iavf_free_dma_mem(hw, &hw->aq.asq.desc_buf); } From adbc4d0fff640541d7071421ac59dbd70da33b18 Mon Sep 17 00:00:00 2001 From: Xuanqiang Luo Date: Thu, 12 Nov 2026 16:46:00 -0800 Subject: [PATCH 0929/2102] iavf: add missing PTP adjustment callbacks The PTP hardware clock documentation requires drivers to implement all callbacks and return -EOPNOTSUPP for unsupported features. The iavf driver registers a PHC without adjtime or adjfine callbacks. A userspace clock_adjtime(2) request reaches ptp_clock_adjtime(), where ADJ_SETOFFSET calls adjtime and ADJ_FREQUENCY calls adjfine. The missing callbacks can therefore cause a NULL dereference. Provide both callbacks and return -EOPNOTSUPP for the unsupported operations. Fixes: d734223b2f0d ("iavf: add initial framework for registering PTP clock") Link: https://docs.kernel.org/driver-api/ptp.html#writing-clock-drivers Link: https://lore.kernel.org/all/20260826101004.100979-1-xuanqiang.luo@linux.dev/ Cc: stable@vger.kernel.org Signed-off-by: Xuanqiang Luo Reviewed-by: Vadim Fedorenko Acked-by: Jacob Keller Tested-by: Rafal Romanowski Signed-off-by: Tony Nguyen Link: https://patch.msgid.link/20261113004602.129864-7-anthony.l.nguyen@intel.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/intel/iavf/iavf_ptp.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/drivers/net/ethernet/intel/iavf/iavf_ptp.c b/drivers/net/ethernet/intel/iavf/iavf_ptp.c index 87b97e09df14a9..fcb273828bc1b6 100644 --- a/drivers/net/ethernet/intel/iavf/iavf_ptp.c +++ b/drivers/net/ethernet/intel/iavf/iavf_ptp.c @@ -252,6 +252,16 @@ static int iavf_ptp_gettimex64(struct ptp_clock_info *info, return iavf_read_phc_indirect(adapter, ts, sts); } +static int iavf_ptp_adjfine(struct ptp_clock_info *info, long scaled_ppm) +{ + return -EOPNOTSUPP; +} + +static int iavf_ptp_adjtime(struct ptp_clock_info *info, s64 delta) +{ + return -EOPNOTSUPP; +} + static int iavf_ptp_settime64(struct ptp_clock_info *info, const struct timespec64 *ts) { @@ -326,6 +336,8 @@ static int iavf_ptp_register_clock(struct iavf_adapter *adapter) KBUILD_MODNAME, dev_name(dev)); ptp_info->owner = THIS_MODULE; ptp_info->gettimex64 = iavf_ptp_gettimex64; + ptp_info->adjfine = iavf_ptp_adjfine; + ptp_info->adjtime = iavf_ptp_adjtime; ptp_info->settime64 = iavf_ptp_settime64; ptp_info->do_aux_work = iavf_ptp_do_aux_work; From e83cac046ded56962ad4d4eb6ebd7910d62c287b Mon Sep 17 00:00:00 2001 From: Tony Luck Date: Fri, 13 Nov 2026 09:41:45 -0800 Subject: [PATCH 0930/2102] x86/cpu: Add Intel Coral Rapids and Razor Lake CPU models November 2026 "Intel Architecture Instruction Set Extensions and Future Features" published the model numbers for the upcoming Coral Rapids server and four Razor Lake (two desktops, two mobile). Signed-off-by: Tony Luck Signed-off-by: Borislav Petkov (AMD) Link: https://patch.msgid.link/20261113174145.13513-1-tony.luck@intel.com --- arch/x86/include/asm/intel-family.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/arch/x86/include/asm/intel-family.h b/arch/x86/include/asm/intel-family.h index 66d964afe18a45..2a5761d475b85c 100644 --- a/arch/x86/include/asm/intel-family.h +++ b/arch/x86/include/asm/intel-family.h @@ -129,6 +129,8 @@ #define INTEL_DIAMONDRAPIDS_X IFM(19, 0x01) /* Panther Cove */ +#define INTEL_CORALRAPIDS_X IFM(19, 0x08) + #define INTEL_BARTLETTLAKE IFM(6, 0xD7) /* Raptor Cove */ /* "Hybrid" Processors (P-Core/E-Core) */ @@ -159,6 +161,11 @@ #define INTEL_NOVALAKE IFM(18, 0x01) /* Coyote Cove / Arctic Wolf */ #define INTEL_NOVALAKE_L IFM(18, 0x03) /* Coyote Cove / Arctic Wolf */ +#define INTEL_RAZORLAKE IFM(18, 0x06) +#define INTEL_RAZORLAKE_L IFM(18, 0x07) +#define INTEL_RAZORLAKE_U IFM(18, 0x09) +#define INTEL_RAZORLAKE_S IFM(18, 0x0A) + /* "Small Core" Processors (Atom/E-Core) */ #define INTEL_ATOM_BONNELL IFM(6, 0x1C) /* Diamondville, Pineview */ From ffb03b2068bdc3bc11b61b7b3fb2c46735b0e859 Mon Sep 17 00:00:00 2001 From: Riana Tauro Date: Thu, 12 Nov 2026 11:37:06 +0530 Subject: [PATCH 0931/2102] drm/xe/ras: Treat non-fatal PCIe errors as recovered On systems lacking RAS capability, only PCIe errors are reported, via AER, not device errors. Non-fatal PCIe errors reported at the Upstream Switch Port (USP) have no impact on link or device state, so treat them as recovered without requiring a secondary bus reset (SBR). Fixes: 25913a062cd4 ("drm/xe/xe_ras: Add support for uncorrectable core-compute errors") Reviewed-by: Mallesh Koujalagi Link: https://patch.msgid.link/20261112060701.3327125-14-riana.tauro@intel.com Signed-off-by: Riana Tauro (cherry picked from commit f416c3899d2a0fe5f05921567164c10e5e36dbde) Signed-off-by: Matthew Brost --- drivers/gpu/drm/xe/xe_ras.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/xe/xe_ras.c b/drivers/gpu/drm/xe/xe_ras.c index fe16a41060607c..53cfbb9a3bac51 100644 --- a/drivers/gpu/drm/xe/xe_ras.c +++ b/drivers/gpu/drm/xe/xe_ras.c @@ -496,7 +496,7 @@ enum xe_ras_recovery_action xe_ras_process_errors(struct xe_device *xe) } if (!xe->info.has_sysctrl) - return XE_RAS_RECOVERY_ACTION_RESET; + return XE_RAS_RECOVERY_ACTION_RECOVERED; BUILD_BUG_ON(BITS_PER_TYPE(sent) < XE_RAS_COMP_MAX); /* Default action */ From 65ef9dec511c018bcbe5993e9749c52c26e573e2 Mon Sep 17 00:00:00 2001 From: Sanjay Yadav Date: Wed, 11 Nov 2026 14:34:02 +0530 Subject: [PATCH 0932/2102] drm/xe/query: Use ordered clock reads for engine cycles cpu_delta cpu_delta is meant to bound the time taken to read the engine timestamp register, but it is measured with local_clock(), which on x86 is a plain RDTSC that is not ordered against loads. Either end of the window can thus be sampled while an earlier MMIO read is still in flight. A reproducer looping on DRM_XE_DEVICE_QUERY_ENGINE_CYCLES on BMG reports cpu_delta as low as 18 ns, while the MMIO read alone takes > 1.5 us. Use ktime_get_raw_ns() at both ends instead. Its clocksource read is ordered (rdtsc_ordered() on x86). With this, the reproducer reports min/median cpu_delta of 1567/1745 ns and no short values. Fixes: 7793d00d1bf5 ("drm/xe: Correlate engine and cpu timestamps with better accuracy") Cc: # v6.8+ Cc: Umesh Nerlige Ramappa Cc: Matthew Brost Cc: Rodrigo Vivi Suggested-by: Aleksander Czerwionka Signed-off-by: Sanjay Yadav Reviewed-by: Umesh Nerlige Ramappa Signed-off-by: Umesh Nerlige Ramappa Link: https://patch.msgid.link/20261111090401.975803-2-sanjay.kumar.yadav@intel.com (cherry picked from commit 146dec4ce1f0794fefe5ad1d549655745358b515) Signed-off-by: Matthew Brost --- drivers/gpu/drm/xe/xe_query.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/xe/xe_query.c b/drivers/gpu/drm/xe/xe_query.c index dc975f5953683a..9cc35fc83954ff 100644 --- a/drivers/gpu/drm/xe/xe_query.c +++ b/drivers/gpu/drm/xe/xe_query.c @@ -6,7 +6,6 @@ #include "xe_query.h" #include -#include #include #include @@ -97,13 +96,14 @@ hwe_read_timestamp(struct xe_hw_engine *hwe, u64 *engine_ts, u64 *cpu_ts, u32 upper, lower, old_upper, loop = 0; struct xe_reg upper_reg = RING_TIMESTAMP_UDW(hwe->mmio_base), lower_reg = RING_TIMESTAMP(hwe->mmio_base); + u64 delta_start; upper = xe_mmio_read32(mmio, upper_reg); do { - *cpu_delta = local_clock(); + delta_start = ktime_get_raw_ns(); *cpu_ts = cpu_clock(); lower = xe_mmio_read32(mmio, lower_reg); - *cpu_delta = local_clock() - *cpu_delta; + *cpu_delta = ktime_get_raw_ns() - delta_start; old_upper = upper; upper = xe_mmio_read32(mmio, upper_reg); } while (upper != old_upper && loop++ < 2); From 6ba5651b46864f38c0a58afce458744b565a31c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Pi=C3=B3rkowski?= Date: Fri, 6 Nov 2026 12:06:20 +0100 Subject: [PATCH 0933/2102] drm/xe/guc: Reset TLB invalidation state in submit fini MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit guc_submit_fini() stops the CT but does not complete pending TLB invalidation fences. If an invalidation was sent right before the stop, its done message from GuC is dropped and the fence only completes when it times out, leaving its waiter stuck for several seconds. We hit this while disabling VFs, where the VF removal was blocked until the TLB invalidation fence timed out. Let's reset the TLB invalidation state right after stopping the CT, as is already done on GT reset. Fixes: a6ab444a111a ("drm/xe: Forcefully tear down exec queues in GuC submit fini") Reviewed-by: Fei Yang Link: https://patch.msgid.link/20261106110620.2065903-1-piotr.piorkowski@intel.com Signed-off-by: Piotr Piórkowski (cherry picked from commit c20678d43df7666c9493832a03677e735bbc374c) Signed-off-by: Matthew Brost --- drivers/gpu/drm/xe/xe_guc_submit.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/gpu/drm/xe/xe_guc_submit.c b/drivers/gpu/drm/xe/xe_guc_submit.c index 01f79f8883ba68..dd970e6b1b9dcb 100644 --- a/drivers/gpu/drm/xe/xe_guc_submit.c +++ b/drivers/gpu/drm/xe/xe_guc_submit.c @@ -47,6 +47,7 @@ #include "xe_ring_ops_types.h" #include "xe_sched_job.h" #include "xe_sleep.h" +#include "xe_tlb_inval.h" #include "xe_trace.h" #include "xe_uc_fw.h" #include "xe_vm.h" @@ -264,6 +265,7 @@ static void guc_submit_fini(void *arg) /* Forcefully kill any remaining exec queues */ xe_guc_ct_stop(&guc->ct); + xe_tlb_inval_reset(&guc_to_gt(guc)->tlb_inval); guc_submit_reset_prepare(guc); xe_guc_softreset(guc); xe_guc_submit_stop(guc); From 388cdd4571edff6942e7c794540b347b4c04ec2c Mon Sep 17 00:00:00 2001 From: Arvind Yadav Date: Tue, 20 Oct 2026 09:32:11 +0530 Subject: [PATCH 0934/2102] drm/xe/irq: Always free requested IRQs on uninstall MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit xe_irq_suspend() clears irq.enabled after disabling and synchronizing the interrupts. irq_uninstall() currently returns when that flag is clear, so a suspended device can skip free_irq() during teardown. The managed uninstall action is registered only after the IRQ request succeeds. Reset the interrupt registers only when interrupts are still enabled, but always free the requested IRQs. Fixes: dd08ebf6c352 ("drm/xe: Introduce a new DRM driver for Intel GPUs") Cc: Matthew Brost Cc: Thomas Hellström Cc: Himal Prasad Ghimiray Cc: Rodrigo Vivi Reviewed-by: Himal Prasad Ghimiray Reviewed-by: Thomas Hellström Signed-off-by: Arvind Yadav Link: https://patch.msgid.link/20261020040211.496778-1-arvind.yadav@intel.com Signed-off-by: Tejas Upadhyay (cherry picked from commit 54dcaa48768b6e7761692f0fa10284d6b13636d1) Signed-off-by: Matthew Brost --- drivers/gpu/drm/xe/xe_irq.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/xe/xe_irq.c b/drivers/gpu/drm/xe/xe_irq.c index b394c8edf89c91..f3964c6eca17c9 100644 --- a/drivers/gpu/drm/xe/xe_irq.c +++ b/drivers/gpu/drm/xe/xe_irq.c @@ -786,10 +786,8 @@ static void irq_uninstall(void *arg) { struct xe_device *xe = arg; - if (!atomic_xchg(&xe->irq.enabled, 0)) - return; - - xe_irq_reset(xe); + if (atomic_xchg(&xe->irq.enabled, 0)) + xe_irq_reset(xe); if (xe_device_has_msix(xe)) xe_irq_msix_free(xe); From 22e05ee854e1bdacebcfa36ecd3f33ec80cf897a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Hellstr=C3=B6m?= Date: Wed, 11 Nov 2026 11:09:29 +0100 Subject: [PATCH 0935/2102] drm/xe/dma-buf: Validate BOs on export to charge the exporter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit xe_gem_prime_export() calls ttm_bo_setup_export() to make sure the exporter is charged for the memory backing an exported BO. However, that only populates a TTM_PL_SYSTEM tt. A BO that has been evicted, or that has deferred backing, will instead get its memory allocated when the importer maps it. For p2p imports this happens through xe_bo_validate() in xe_dma_buf_map(), so the importer, not the exporter, is charged for the allocation. Call xe_bo_validate() at export time instead, so that the BO is moved into its preferred placement and the exporter is charged. Do the purgeable checks and the validation in the same xe_validation_guard() transaction, to avoid locking the BO twice. The commit message and code was drafted using LLM. Link: https://patchwork.freedesktop.org/patch/747480/?series=172524&rev=1 Fixes: 91494dee1091 ("xe: populate buffers before exporting them.") Cc: Matthew Brost Cc: Matthew Auld Cc: Dave Airlie Cc: Rodrigo Vivi Cc: intel-xe@lists.freedesktop.org Cc: stable@vger.kernel.org # v6.18+ Reviewed-by: Matthew Auld Link: https://patch.msgid.link/20261111100929.2228-1-thomas.hellstrom@linux.intel.com Signed-off-by: Thomas Hellström (cherry picked from commit 451162b9f6570d19da1c5944aa0a0e3e8f17773d) Signed-off-by: Matthew Brost --- drivers/gpu/drm/xe/xe_dma_buf.c | 76 +++++++++++++++++---------------- 1 file changed, 39 insertions(+), 37 deletions(-) diff --git a/drivers/gpu/drm/xe/xe_dma_buf.c b/drivers/gpu/drm/xe/xe_dma_buf.c index 6a85b292dee7b8..97299ca8f83165 100644 --- a/drivers/gpu/drm/xe/xe_dma_buf.c +++ b/drivers/gpu/drm/xe/xe_dma_buf.c @@ -242,60 +242,62 @@ static const struct dma_buf_ops xe_dmabuf_ops = { struct dma_buf *xe_gem_prime_export(struct drm_gem_object *obj, int flags) { struct xe_bo *bo = gem_to_xe_bo(obj); + struct xe_validation_ctx ctx; + struct drm_exec exec; struct dma_buf *buf; - struct ttm_operation_ctx ctx = { - .interruptible = true, - .no_wait_gpu = true, - /* We opt to avoid OOM on system pages allocations */ - .gfp_retry_mayfail = true, - .allow_res_evict = false, - }; - int ret; + int ret = 0; if (bo->vm) return ERR_PTR(-EPERM); - /* - * Reject exporting purgeable BOs. DONTNEED BOs can be purged - * at any time, making the exported dma-buf unusable. Purged BOs - * have no backing store and are permanently invalid. - */ - ret = xe_bo_lock(bo, true); - if (ret) - return ERR_PTR(ret); + xe_validation_guard(&ctx, &xe_bo_device(bo)->val, &exec, + (struct xe_val_flags) {.interruptible = true}, ret) { + ret = drm_exec_lock_obj(&exec, &bo->ttm.base); + drm_exec_retry_on_contention(&exec); + if (ret) + break; - if (xe_bo_madv_is_dontneed(bo)) { - ret = -EBUSY; - goto out_unlock; - } + /* + * Reject exporting purgeable BOs. DONTNEED BOs can be purged + * at any time, making the exported dma-buf unusable. Purged BOs + * have no backing store and are permanently invalid. + */ + if (xe_bo_madv_is_dontneed(bo)) { + ret = -EBUSY; + break; + } - if (xe_bo_is_purged(bo)) { - ret = -EINVAL; - goto out_unlock; - } + if (xe_bo_is_purged(bo)) { + ret = -EINVAL; + break; + } - xe_bo_willneed_get_locked(bo); - xe_bo_unlock(bo); + /* + * Make sure the BO is backed in its preferred placement so that + * the exporter, rather than the importer, is charged for the + * memory allocation. + */ + ret = xe_bo_validate(bo, NULL, false, &exec); + drm_exec_retry_on_contention(&exec); + xe_validation_retry_on_oom(&ctx, &ret); + if (ret) + break; - ret = ttm_bo_setup_export(&bo->ttm, &ctx); + xe_bo_willneed_get_locked(bo); + } if (ret) - goto out_put; + return ERR_PTR(ret); buf = drm_gem_prime_export(obj, flags); if (IS_ERR(buf)) { - ret = PTR_ERR(buf); - goto out_put; + xe_bo_lock(bo, false); + xe_bo_willneed_put_locked(bo); + xe_bo_unlock(bo); + return buf; } buf->ops = &xe_dmabuf_ops; return buf; - -out_put: - xe_bo_lock(bo, false); - xe_bo_willneed_put_locked(bo); -out_unlock: - xe_bo_unlock(bo); - return ERR_PTR(ret); } static struct drm_gem_object * From b865310c41f5b68c7de3bec86f205ba8cd284fd1 Mon Sep 17 00:00:00 2001 From: Zongyao Bai Date: Mon, 16 Nov 2026 11:22:19 -0800 Subject: [PATCH 0936/2102] drm/xe/guc: Treat CT-disabled TLB invalidation as cancelled During a GT reset the GuC CT channel goes through two states before it is enabled again: gt_reset_worker() xe_uc_stop() ENABLED -> STOPPED send: -ECANCELED xe_tlb_inval_reset() do_gt_reset() do_gt_restart() xe_uc_sanitize_reset() STOPPED -> DISABLED send: -ENODEV GuC load, CT enable DISABLED -> ENABLED xe_tlb_inval_issue() treats -ECANCELED as "undelivered, report done", but -ENODEV is propagated to the caller. A userptr invalidation from an MMU notifier (e.g. munmap() on a fault-mode VM) issued in the DISABLED window thus trips the XE_WARN_ON() in xe_vma_userptr_do_inval() and taints the kernel: Tile0: GT1: GT: reset started WARNING: drivers/gpu/drm/xe/xe_userptr.c:133 at xe_vma_userptr_do_inval+0x340/0x4a0 [xe] RAX: 00000000ffffffed xe_vma_userptr_invalidate_start+0x4b7/0x7c0 [xe] __mmu_notifier_invalidate_range_start+0x247/0x370 unmap_vmas+0x1af/0x1c0 unmap_region+0x91/0xf0 ... The TLB invalidation ops contract is that the backend returns -ECANCELED when it is mid-reset. The reset invalidates all TLBs, so there is nothing left to do. Map -ENODEV to -ECANCELED in send_tlb_inval() so that every GuC TLB invalidation type handles it the same way, instead of only send_tlb_inval_ggtt_full() as done so far. The CT is also DISABLED across system suspend and runtime suspend. On resume from system suspend the GuC is reloaded with all TLBs invalid, so nothing is lost there either; user space and the MM kernel threads are frozen by then, so such a request is not expected anyway. A request issued while runtime suspended violates the PM rules and is still reported by the "Missing outer runtime PM protection" warning in xe_tlb_inval_fence_init(). Fixes: db16f9d90c1d ("drm/xe: Split TLB invalidation code in frontend and backend") Cc: stable@vger.kernel.org # v6.18+ Cc: Matthew Brost Signed-off-by: Zongyao Bai Reviewed-by: Shuicheng Lin Link: https://patch.msgid.link/20261116192220.3872267-2-zongyao.bai@intel.com Signed-off-by: Shuicheng Lin (cherry picked from commit c17474e39028c7fb5cd6b2fb0f0413d07b1bf232) Signed-off-by: Matthew Brost --- drivers/gpu/drm/xe/xe_guc_tlb_inval.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/xe/xe_guc_tlb_inval.c b/drivers/gpu/drm/xe/xe_guc_tlb_inval.c index 111fef781b2abb..0945d9711e1734 100644 --- a/drivers/gpu/drm/xe/xe_guc_tlb_inval.c +++ b/drivers/gpu/drm/xe/xe_guc_tlb_inval.c @@ -31,12 +31,22 @@ static int send_tlb_inval(struct xe_guc *guc, const u32 *action, int len) { struct xe_gt *gt = guc_to_gt(guc); + int ret; xe_gt_assert(gt, action[1]); /* Seqno */ xe_gt_stats_incr(gt, XE_GT_STATS_ID_TLB_INVAL, 1); - return xe_guc_ct_send(&guc->ct, action, len, - G2H_LEN_DW_TLB_INVALIDATE, 1); + ret = xe_guc_ct_send(&guc->ct, action, len, G2H_LEN_DW_TLB_INVALIDATE, 1); + + /* + * A disabled CT can't deliver the request, and the GuC is reloaded + * with all TLBs invalid before the CT is enabled again, so there is + * nothing left to invalidate. Report it as cancelled, like a stopped CT. + */ + if (ret == -ENODEV) + return -ECANCELED; + + return ret; } #define MAKE_INVAL_OP_FLUSH(type, flush_cache) ((type << XE_GUC_TLB_INVAL_TYPE_SHIFT) | \ From ca2a839d0f50e214b71fd30bc949d6d173fae53f Mon Sep 17 00:00:00 2001 From: Dnyaneshwar Bhadane Date: Mon, 12 Oct 2026 17:55:10 +0530 Subject: [PATCH 0937/2102] drm/xe/log: Add VRAM, PAT, and HWMON DRIVER_HARDWARE components Register new DRIVER_HARDWARE log components for hardware I/O subsystems that currently lack structured error reporting: - VRAM (ID 6): Video RAM/Local Memory access and BAR visibility errors - PAT (ID 7): Page Attribute Table programming errors - HWMON (ID 8): Hardware monitor registration and sensor errors All three use IO_BUS as their default SIGID since they interact with hardware through MMIO or PCode register paths. Signed-off-by: Dnyaneshwar Bhadane Reviewed-by: Mallesh Koujalagi Link: https://patch.msgid.link/20261012122522.2307625-2-dnyaneshwar.bhadane@intel.com Signed-off-by: Matt Roper Signed-off-by: Matthew Brost --- drivers/gpu/drm/xe/abi/xe_log_abi.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/gpu/drm/xe/abi/xe_log_abi.h b/drivers/gpu/drm/xe/abi/xe_log_abi.h index 526aadf85fe938..d7bd85ea96736f 100644 --- a/drivers/gpu/drm/xe/abi/xe_log_abi.h +++ b/drivers/gpu/drm/xe/abi/xe_log_abi.h @@ -151,6 +151,9 @@ enum xe_log_location_bits { define(DRIVER_HARDWARE, 3, GT, GT_TDR, "Graphics Technology") \ define(DRIVER_HARDWARE, 4, LMTT, IO_BUS, "LMEM Translation Table") \ define(DRIVER_HARDWARE, 5, MEMIRQ, IO_BUS, "Memory Based IRQ") \ + define(DRIVER_HARDWARE, 6, VRAM, IO_BUS, "Video Memory/Local Memory") \ + define(DRIVER_HARDWARE, 7, PAT, IO_BUS, "Page Attribute Table") \ + define(DRIVER_HARDWARE, 8, HWMON, IO_BUS, "Hardware Monitoring") \ /* */ \ define(DRIVER_FEATURE, 1, PF, SW, "SR-IOV Physical Function") \ define(DRIVER_FEATURE, 2, VF, SW, "SR-IOV Virtual Function") \ From 808951ee16738f7629804e58dd34f1be6a036882 Mon Sep 17 00:00:00 2001 From: Dnyaneshwar Bhadane Date: Mon, 12 Oct 2026 17:55:12 +0530 Subject: [PATCH 0938/2102] drm/xe/hwmon: Report errors using structured xe_log API Replace drm_err() calls with xe_log_err() using the HWMON component tag to enable structured error reporting with SIGID for hardware monitor failures: Signed-off-by: Dnyaneshwar Bhadane Reviewed-by: Mallesh Koujalagi Link: https://patch.msgid.link/20261012122522.2307625-4-dnyaneshwar.bhadane@intel.com Signed-off-by: Matt Roper Signed-off-by: Matthew Brost --- drivers/gpu/drm/xe/xe_hwmon.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/xe/xe_hwmon.c b/drivers/gpu/drm/xe/xe_hwmon.c index 20c1cfffc5a03c..7dd765a5f5d4e3 100644 --- a/drivers/gpu/drm/xe/xe_hwmon.c +++ b/drivers/gpu/drm/xe/xe_hwmon.c @@ -15,6 +15,7 @@ #include "regs/xe_pcode_regs.h" #include "xe_device.h" #include "xe_hwmon.h" +#include "xe_log.h" #include "xe_mmio.h" #include "xe_pcode.h" #include "xe_pcode_api.h" @@ -602,9 +603,9 @@ xe_hwmon_power_max_interval_show(struct device *dev, struct device_attribute *at if (hwmon->xe->info.has_mbx_power_limits) { ret = xe_hwmon_pcode_read_power_limit(hwmon, power_attr, channel, ®_val); if (ret) { - drm_err(&hwmon->xe->drm, - "power interval read fail, ch %d, attr %d, val 0x%08x, ret %d\n", - channel, power_attr, reg_val, ret); + xe_log_err(hwmon->xe, HWMON, ret, + "Power interval read fail, ch %d, attr %d, val 0x%08x\n", + channel, power_attr, reg_val); reg_val = 0; } } else { @@ -1649,7 +1650,7 @@ int xe_hwmon_register(struct xe_device *xe) { struct device *dev = xe->drm.dev; struct xe_hwmon *hwmon; - int ret; + int ret, err; /* hwmon is available only for dGfx */ if (!IS_DGFX(xe)) @@ -1680,9 +1681,11 @@ int xe_hwmon_register(struct xe_device *xe) &hwmon_chip_info, hwmon_groups); if (IS_ERR(hwmon->hwmon_dev)) { - drm_err(&xe->drm, "Failed to register xe hwmon (%pe)\n", hwmon->hwmon_dev); + err = PTR_ERR(hwmon->hwmon_dev); + xe_log_err(xe, HWMON, err, + "Failed to register xe hwmon\n"); xe->hwmon = NULL; - return PTR_ERR(hwmon->hwmon_dev); + return err; } return 0; From 58417a6534dd3c190203a50541aa34b4a98bf275 Mon Sep 17 00:00:00 2001 From: Karthik Poosa Date: Thu, 15 Oct 2026 12:44:34 +0530 Subject: [PATCH 0939/2102] drm/xe/hwmon: Propagate all hardware read errors Propagate all failures from pcode and mailbox accesses and fix missed return-value checks found by Sashiko in https://patchwork.freedesktop.org/patch/758843/?series=174898&rev=6. Fixes: 7596d839f622 ("drm/xe/hwmon: Add support to manage power limits though mailbox") Fixes: 0c5405d3aa4ad ("drm/xe/hwmon: Read energy status from PMT") Fixes: 25e963a09e059 ("drm/xe/hwmon: Move card reactive critical power under channel card") Signed-off-by: Karthik Poosa Reviewed-by: Rodrigo Vivi Link: https://patch.msgid.link/20261015071434.1063785-17-karthik.poosa@intel.com Signed-off-by: Rodrigo Vivi Signed-off-by: Matthew Brost --- drivers/gpu/drm/xe/xe_hwmon.c | 47 +++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/drivers/gpu/drm/xe/xe_hwmon.c b/drivers/gpu/drm/xe/xe_hwmon.c index 7dd765a5f5d4e3..daa3f61617a028 100644 --- a/drivers/gpu/drm/xe/xe_hwmon.c +++ b/drivers/gpu/drm/xe/xe_hwmon.c @@ -376,17 +376,20 @@ static struct xe_reg xe_hwmon_get_reg(struct xe_hwmon *hwmon, enum xe_hwmon_reg * same pattern for sysfs, allow arbitrary PL1 limits to be set but display * clamped values when read. */ -static void xe_hwmon_power_max_read(struct xe_hwmon *hwmon, u32 attr, int channel, long *value) +static int xe_hwmon_power_max_read(struct xe_hwmon *hwmon, u32 attr, int channel, long *value) { u32 reg_val = 0; struct xe_device *xe = hwmon->xe; struct xe_reg rapl_limit, pkg_power_sku; struct xe_mmio *mmio = xe_root_tile_mmio(xe); + int ret = 0; mutex_lock(&hwmon->hwmon_lock); if (hwmon->xe->info.has_mbx_power_limits) { - xe_hwmon_pcode_read_power_limit(hwmon, attr, channel, ®_val); + ret = xe_hwmon_pcode_read_power_limit(hwmon, attr, channel, ®_val); + if (ret) + goto unlock; } else { rapl_limit = xe_hwmon_get_reg(hwmon, REG_PKG_RAPL_LIMIT, channel); pkg_power_sku = xe_hwmon_get_reg(hwmon, REG_PKG_POWER_SKU, channel); @@ -418,6 +421,7 @@ static void xe_hwmon_power_max_read(struct xe_hwmon *hwmon, u32 attr, int channe } unlock: mutex_unlock(&hwmon->hwmon_lock); + return ret; } static int xe_hwmon_power_max_write(struct xe_hwmon *hwmon, u32 attr, int channel, long value) @@ -440,7 +444,9 @@ static int xe_hwmon_power_max_write(struct xe_hwmon *hwmon, u32 attr, int channe ret = xe_hwmon_pcode_rmw_power_limit(hwmon, attr, channel, PWR_LIM_EN, 0); if (ret) goto unlock; - xe_hwmon_pcode_read_power_limit(hwmon, attr, channel, ®_val); + ret = xe_hwmon_pcode_read_power_limit(hwmon, attr, channel, ®_val); + if (ret) + goto unlock; } else { reg_val = xe_mmio_rmw32(mmio, rapl_limit, PWR_LIM_EN, 0); reg_val = xe_mmio_read32(mmio, rapl_limit); @@ -497,15 +503,18 @@ static int xe_hwmon_power_max_write(struct xe_hwmon *hwmon, u32 attr, int channe return ret; } -static void xe_hwmon_power_rated_max_read(struct xe_hwmon *hwmon, u32 attr, int channel, - long *value) +static int xe_hwmon_power_rated_max_read(struct xe_hwmon *hwmon, u32 attr, int channel, + long *value) { struct xe_mmio *mmio = xe_root_tile_mmio(hwmon->xe); u32 reg_val; + int ret = 0; if (hwmon->xe->info.has_mbx_power_limits) { /* PL1 is rated max if supported. */ - xe_hwmon_pcode_read_power_limit(hwmon, PL1_HWMON_ATTR, channel, ®_val); + ret = xe_hwmon_pcode_read_power_limit(hwmon, PL1_HWMON_ATTR, channel, ®_val); + if (ret) + return ret; } else { /* * This sysfs file won't be visible if REG_PKG_POWER_SKU is invalid, so valid check @@ -519,6 +528,7 @@ static void xe_hwmon_power_rated_max_read(struct xe_hwmon *hwmon, u32 attr, int reg_val = REG_FIELD_GET(PKG_TDP, reg_val); *value = mul_u64_u32_shr(reg_val, SF_POWER, hwmon->scl_shift_power); + return ret; } /* @@ -541,7 +551,7 @@ static void xe_hwmon_power_rated_max_read(struct xe_hwmon *hwmon, u32 attr, int * hwmon->scl_shift_energy of 14 bits we have 57 (63 - 20 + 14) bits before * energyN_input overflows. This at 1000 W is an overflow duration of 278 years. */ -static void +static int xe_hwmon_energy_get(struct xe_hwmon *hwmon, int channel, long *energy) { struct xe_mmio *mmio = xe_root_tile_mmio(hwmon->xe); @@ -552,7 +562,7 @@ xe_hwmon_energy_get(struct xe_hwmon *hwmon, int channel, long *energy) /* Energy is supported only for card and pkg */ if (channel > CHANNEL_PKG) { *energy = 0; - return; + return 0; } if (hwmon->xe->info.platform == XE_BATTLEMAGE) { @@ -564,7 +574,7 @@ xe_hwmon_energy_get(struct xe_hwmon *hwmon, int channel, long *energy) if (ret != sizeof(pmt_val)) { drm_warn(&hwmon->xe->drm, "energy read from pmt failed, ret %d\n", ret); *energy = 0; - return; + return ret < 0 ? ret : -EIO; } if (channel == CHANNEL_PKG) @@ -581,6 +591,7 @@ xe_hwmon_energy_get(struct xe_hwmon *hwmon, int channel, long *energy) *energy = mul_u64_u32_shr(ei->accum_energy, SF_ENERGY, hwmon->scl_shift_energy); + return 0; } static ssize_t @@ -606,7 +617,8 @@ xe_hwmon_power_max_interval_show(struct device *dev, struct device_attribute *at xe_log_err(hwmon->xe, HWMON, ret, "Power interval read fail, ch %d, attr %d, val 0x%08x\n", channel, power_attr, reg_val); - reg_val = 0; + mutex_unlock(&hwmon->hwmon_lock); + return ret; } } else { reg_val = xe_mmio_read32(mmio, xe_hwmon_get_reg(hwmon, REG_PKG_RAPL_LIMIT, @@ -1230,7 +1242,8 @@ xe_hwmon_power_is_visible(struct xe_hwmon *hwmon, u32 attr, int channel) } case hwmon_power_crit: if (channel == CHANNEL_CARD) { - xe_hwmon_pcode_read_i1(hwmon, &uval); + if (xe_hwmon_pcode_read_i1(hwmon, &uval)) + return 0; return (uval & POWER_SETUP_I1_WATTS) ? 0644 : 0; } break; @@ -1249,7 +1262,8 @@ xe_hwmon_power_is_visible(struct xe_hwmon *hwmon, u32 attr, int channel) } } if ((!(uval & PWR_LIM_EN)) && channel == CHANNEL_CARD) { - xe_hwmon_pcode_read_i1(hwmon, &uval); + if (xe_hwmon_pcode_read_i1(hwmon, &uval)) + return 0; return (uval & POWER_SETUP_I1_WATTS) ? 0444 : 0; } return (uval) ? 0444 : 0; @@ -1265,11 +1279,9 @@ xe_hwmon_power_read(struct xe_hwmon *hwmon, u32 attr, int channel, long *val) switch (attr) { case hwmon_power_max: case hwmon_power_cap: - xe_hwmon_power_max_read(hwmon, attr, channel, val); - return 0; + return xe_hwmon_power_max_read(hwmon, attr, channel, val); case hwmon_power_rated_max: - xe_hwmon_power_rated_max_read(hwmon, attr, channel, val); - return 0; + return xe_hwmon_power_rated_max_read(hwmon, attr, channel, val); case hwmon_power_crit: return xe_hwmon_power_curr_crit_read(hwmon, channel, val, SF_POWER); default: @@ -1386,8 +1398,7 @@ xe_hwmon_energy_read(struct xe_hwmon *hwmon, u32 attr, int channel, long *val) { switch (attr) { case hwmon_energy_input: - xe_hwmon_energy_get(hwmon, channel, val); - return 0; + return xe_hwmon_energy_get(hwmon, channel, val); default: return -EOPNOTSUPP; } From b438bb88f65a8b464ad08057873db9605cdae945 Mon Sep 17 00:00:00 2001 From: Weiming Shi Date: Mon, 26 Oct 2026 08:46:05 -0700 Subject: [PATCH 0940/2102] fbdev: vfb: Validate framebuffer geometry and memory size FBIOPUT_VSCREENINFO can supply a virtual width large enough to overflow get_line_length()'s int multiplication and bypass the video-memory limit, allowing fbcon to write past the framebuffer. The offset additions can also wrap, while an excessive videomemorysize module parameter can be truncated when PAGE_ALIGN() is assigned to unsigned int. Limit virtual geometry and offsets to 8192 x 8192 and cap video memory at 512 MiB, keeping the stride, framebuffer-size, and generic fbdev drawing calculations within their destination types. KASAN reports: BUG: KASAN: vmalloc-out-of-bounds in sys_fillrect drivers/video/fbdev/core/sysfillrect.c:24 Write of size 8 at addr ffa0000001671000 by task poc/198 sys_fillrect drivers/video/fbdev/core/sysfillrect.c:24 bit_clear_margins drivers/video/fbdev/core/bitblit.c:247 fbcon_clear_margins.constprop.0 drivers/video/fbdev/core/fbcon.c:1410 fbcon_switch drivers/video/fbdev/core/fbcon.c:2261 redraw_screen drivers/tty/vt/vt.c:994 fbcon_modechanged drivers/video/fbdev/core/fbcon.c:2693 fbcon_update_vcs drivers/video/fbdev/core/fbcon.c:2732 Cc: stable@vger.kernel.org Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Reported-by: co+b0df61d49532b2ee@bugs.sh Suggested-by: Helge Deller Assisted-by: LLM Signed-off-by: Weiming Shi Signed-off-by: Helge Deller --- drivers/video/fbdev/vfb.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/drivers/video/fbdev/vfb.c b/drivers/video/fbdev/vfb.c index de137b2bdaedc6..721c70962503f8 100644 --- a/drivers/video/fbdev/vfb.c +++ b/drivers/video/fbdev/vfb.c @@ -30,7 +30,10 @@ * The default can be overridden if the driver is compiled as a module */ -#define VIDEOMEMSIZE (1*1024*1024) /* 1 MB */ +#define MAX_XRES 8192 +#define MAX_YRES 8192 +#define VIDEOMEMSIZE (1 * 1024 * 1024) /* 1 MB */ +#define MAX_VIDEOMEMSIZE (8192 * 8192 * sizeof(u32)) static void *videomemory; static u_long videomemorysize = VIDEOMEMSIZE; @@ -159,6 +162,14 @@ static int vfb_check_var(struct fb_var_screeninfo *var, else return -EINVAL; + if (var->xres_virtual > MAX_XRES || + var->yres_virtual > MAX_YRES) + return -EINVAL; + + if (var->xoffset > MAX_XRES - var->xres || + var->yoffset > MAX_YRES - var->yres) + return -EINVAL; + if (var->xres_virtual < var->xoffset + var->xres) var->xres_virtual = var->xoffset + var->xres; if (var->yres_virtual < var->yoffset + var->yres) @@ -434,9 +445,12 @@ static int __init vfb_setup(char *options) static int vfb_probe(struct platform_device *dev) { struct fb_info *info; - unsigned int size = PAGE_ALIGN(videomemorysize); + unsigned int size; int retval = -ENOMEM; + videomemorysize = min(videomemorysize, MAX_VIDEOMEMSIZE); + size = PAGE_ALIGN(videomemorysize); + /* * For real video cards we use ioremap. */ From b3a3f241dace3d4a775e1401b53a3f6d304534f0 Mon Sep 17 00:00:00 2001 From: Yao Yiqi Date: Tue, 10 Nov 2026 21:59:59 +0800 Subject: [PATCH 0941/2102] fbcon: Avoid cancel_delayed_work_sync() in atomic context fbcon_cursor() can be reached from the console printing path, which runs in atomic context. When the VT software cursor is enabled (vc_cursor_type & CUR_SW), it calls fbcon_del_cursor_work(), which uses cancel_delayed_work_sync() and therefore may sleep. With CONFIG_DEBUG_ATOMIC_SLEEP enabled, the following is reported: BUG: sleeping function called from invalid context at kernel/workqueue.c:4722 in_atomic(): 1, irqs_disabled(): 1, non_block: 0 ... __cancel_work_sync fbcon_del_cursor_work fbcon_cursor hide_cursor vt_console_print console_unlock ... Make the default helper safe: fbcon_del_cursor_work() only stops blinking, using cancel_delayed_work(), which is allowed in any context. Every "stop blinking" call site keeps using it, including fbcon_cursor(). Only fbcon_release(), which is about to free @par and must ensure that no callback is still using it, calls the separate fbcon_del_cursor_work_sync(). New call sites therefore get the safe variant by default. cancel_delayed_work() does not wait for a callback that is already running. Since fb_flashcursor() re-arms itself, a callback that has already been dequeued by process_one_work() can queue the work again after fbcon_del_cursor_work() returns. Add a cursor_blink_on flag to struct fbcon_par: fbcon_add_cursor_work() sets it, fbcon_del_cursor_work() clears it, and fb_flashcursor() checks it after taking console_lock and returns without drawing or re-arming once blinking has been stopped. Keep the requeue inside the console_lock section so that the flag check and the requeue are not split by a concurrent stop. Fixes: 3b0fb6ab25dd ("fbcon: Use delayed work for cursor") Cc: stable@vger.kernel.org Assisted-by: Opencode:deepseek-v4.1-flash Signed-off-by: Yao Yiqi Signed-off-by: Helge Deller --- drivers/video/fbdev/core/fbcon.c | 41 +++++++++++++++++++++++++++----- drivers/video/fbdev/core/fbcon.h | 1 + 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/drivers/video/fbdev/core/fbcon.c b/drivers/video/fbdev/core/fbcon.c index 7720dfc80c165c..d7890e119dc7d0 100644 --- a/drivers/video/fbdev/core/fbcon.c +++ b/drivers/video/fbdev/core/fbcon.c @@ -410,7 +410,8 @@ static void fb_flashcursor(struct work_struct *work) if (par->currcon != -1) vc = vc_cons[par->currcon].d; - if (!vc || !con_is_visible(vc) || + if (!par->cursor_blink_on || + !vc || !con_is_visible(vc) || fbcon_info_from_console(vc->vc_num) != info || vc->vc_deccm != 1) { console_unlock(); @@ -422,25 +423,53 @@ static void fb_flashcursor(struct work_struct *work) par->bitops->cursor(vc, info, enable, get_fg_color(vc, info, c), get_bg_color(vc, info, c)); - console_unlock(); + /* + * Re-arm under console_lock so that a concurrent + * fbcon_del_cursor_work() cannot race with this requeue. + */ queue_delayed_work(system_power_efficient_wq, &par->cursor_work, par->cur_blink_jiffies); + console_unlock(); } static void fbcon_add_cursor_work(struct fb_info *info) { struct fbcon_par *par = info->fbcon_par; - if (fbcon_cursor_blink) - queue_delayed_work(system_power_efficient_wq, &par->cursor_work, - par->cur_blink_jiffies); + if (!fbcon_cursor_blink) + return; + + par->cursor_blink_on = true; + queue_delayed_work(system_power_efficient_wq, &par->cursor_work, + par->cur_blink_jiffies); } +/* + * Stop the cursor blink. + * + * Does not wait for a callback that is already running, so it is safe to + * call from any context. + * + * console_lock serializes this with the requeue in fb_flashcursor(); + * otherwise a running callback could re-arm the work. + */ static void fbcon_del_cursor_work(struct fb_info *info) { struct fbcon_par *par = info->fbcon_par; + par->cursor_blink_on = false; + cancel_delayed_work(&par->cursor_work); +} + +/* + * Stop the cursor blink and wait for a running callback to finish before + * @par is freed. May sleep, only for teardown paths. + */ +static void fbcon_del_cursor_work_sync(struct fb_info *info) +{ + struct fbcon_par *par = info->fbcon_par; + cancel_delayed_work_sync(&par->cursor_work); } @@ -765,7 +794,7 @@ static void fbcon_release(struct fb_info *info) if (info->fbcon_par) { struct fbcon_par *par = info->fbcon_par; - fbcon_del_cursor_work(info); + fbcon_del_cursor_work_sync(info); kfree(par->cursor_state.mask); kfree(par->cursor_data); kfree(par->cursor_src); diff --git a/drivers/video/fbdev/core/fbcon.h b/drivers/video/fbdev/core/fbcon.h index d93a89877d0433..6a2f7f6e5a8c32 100644 --- a/drivers/video/fbdev/core/fbcon.h +++ b/drivers/video/fbdev/core/fbcon.h @@ -97,6 +97,7 @@ struct fbcon_par { int blank_state; int graphics; bool initialized; + bool cursor_blink_on; int rotate; char *cursor_data; #ifdef CONFIG_FRAMEBUFFER_CONSOLE_ROTATION From e3512c7628621f7048a9615d21fd7cf63173c518 Mon Sep 17 00:00:00 2001 From: Matt Turner Date: Wed, 11 Nov 2026 19:28:56 -0500 Subject: [PATCH 0942/2102] vgacon: Fall back to the dummy console if mapping VGA memory fails On Alpha, setup_arch() registers vgacon whenever CONFIG_VGA_CONSOLE is enabled. On Marvel (EV7) systems whose SRM console is serial, no VGA hose is set, so marvel_ioremap() finds no hose for 0xb8000 and returns NULL. vgacon_startup() then probes video memory through that NULL pointer and oopses in console_init(): Unable to handle kernel paging request at virtual address 0000000000000000 pc is at vgacon_startup+0x174/0x910 VGA_MAP_MEM() is ioremap() on Alpha and powerpc and can fail. Treat failure like a failed probe and fall back to the dummy console. If a VGA card is present, locate_and_init_vga() still switches to vgacon once PCI is up. Cc: stable@vger.kernel.org Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Matt Turner Reviewed-by: Magnus Lindholm Tested-by: Magnus Lindholm Signed-off-by: Helge Deller --- drivers/video/console/vgacon.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/video/console/vgacon.c b/drivers/video/console/vgacon.c index e7e6750f1f8737..09f7c376b46890 100644 --- a/drivers/video/console/vgacon.c +++ b/drivers/video/console/vgacon.c @@ -324,6 +324,8 @@ static const char *vgacon_startup(void) } vga_vram_base = VGA_MAP_MEM(vga_vram_base, vga_vram_size); + if (!vga_vram_base) + goto no_vga; vga_vram_end = vga_vram_base + vga_vram_size; /* From 7d4a8a804cd1a3bcaa1a9a38e87517ead3130ca1 Mon Sep 17 00:00:00 2001 From: "Steffen A. Mork" Date: Sun, 1 Nov 2026 15:13:27 +0100 Subject: [PATCH 0943/2102] fbdev: fm2fb: Fix iomem access This driver has not been tested for at least twenty years. In the meantime, the frame buffer API has been updated. This patch addresses this issue and makes the driver functional again. Signed-off-by: Steffen A. Mork Cc: stable@vger.kernel.org Signed-off-by: Helge Deller --- drivers/video/fbdev/fm2fb.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/video/fbdev/fm2fb.c b/drivers/video/fbdev/fm2fb.c index 25d2e716edf2d4..ed4457df7707a9 100644 --- a/drivers/video/fbdev/fm2fb.c +++ b/drivers/video/fbdev/fm2fb.c @@ -257,7 +257,7 @@ static int fm2fb_probe(struct zorro_dev *z, const struct zorro_device_id *id) strcpy(fb_fix.id, is_fm ? "FrameMaster II" : "Rainbow II"); /* make EBU color bars on display */ - ptr = (unsigned long *)fb_fix.smem_start; + ptr = (unsigned long *)info->screen_base; for (y = 0; y < 576; y++) { for (x = 0; x < 96; x++) *ptr++ = 0xffffff;/* white */ for (x = 0; x < 96; x++) *ptr++ = 0xffff00;/* yellow */ From f0486dd91e27d2eaf62abbd0c2af73a9c04eac48 Mon Sep 17 00:00:00 2001 From: Miro Kropacek Date: Fri, 13 Nov 2026 10:56:16 +1000 Subject: [PATCH 0944/2102] fbdev: atafb: Restrict SuperVidel handling to the Falcon A framebuffer at 0xa0000000 or above is taken as being in SuperVidel RAM. A TT with a VME graphics card such as the Nova has its framebuffer there too, so in 8bpp it gets the Falcon palette registers instead of the card's VGA DAC, and in 8, 16 and 32bpp the SuperBlitter, which it does not have. The SuperVidel exists only for the Falcon, so check for the Falcon video hardware as well. Fixes: 51df976c3268 ("fbdev: atafb: Add support for further video bit depths on atafb:external") Fixes: d463633d63e6 ("fbdev: atafb: Add support for SuperVidel's SuperBlitter") Cc: stable@vger.kernel.org # v7.3+ Reported-by: Christian Zietz Signed-off-by: Miro Kropacek Signed-off-by: Helge Deller --- drivers/video/fbdev/atafb.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/drivers/video/fbdev/atafb.c b/drivers/video/fbdev/atafb.c index c32576cb172029..5d9265caa9abfb 100644 --- a/drivers/video/fbdev/atafb.c +++ b/drivers/video/fbdev/atafb.c @@ -2065,6 +2065,15 @@ static void st_ovsc_switch(void) #ifdef ATAFB_EXT +/* + * Only a Falcon can have a SuperVidel; a TT with a VME graphics card can + * have its framebuffer in the same address range. + */ +static bool ext_is_supervidel(void) +{ + return ATARIHW_PRESENT(VIDEL_SHIFTER) && external_addr >= 0xa0000000; +} + static int ext_encode_fix(struct fb_fix_screeninfo *fix, struct atafb_par *par) { strcpy(fix->id, "Unknown Extern"); @@ -2083,8 +2092,7 @@ static int ext_encode_fix(struct fb_fix_screeninfo *fix, struct atafb_par *par) * SuperVidel 8bpp chunky (fb in SV RAM) uses the Falcon palette */ int visual = (external_vgaiobase || - (external_depth == 8 && - external_addr >= 0xa0000000)) ? + (external_depth == 8 && ext_is_supervidel())) ? FB_VISUAL_PSEUDOCOLOR : FB_VISUAL_STATIC_PSEUDOCOLOR; switch (external_pmode) { @@ -2181,7 +2189,7 @@ static int ext_encode_var(struct fb_var_screeninfo *var, struct atafb_par *par) var->transp.offset = 24; var->transp.length = 8; } else if (external_pmode == FB_TYPE_PACKED_PIXELS && - external_depth == 8 && external_addr >= 0xa0000000) { + external_depth == 8 && ext_is_supervidel()) { /* SuperVidel 8bpp chunky: palette has 8 bits per channel. * Without this, fb_get_color_depth() sees length 0 and * fbcon falls back to its 2-color palette — the console @@ -2245,7 +2253,7 @@ static int ext_setcolreg(unsigned int regno, unsigned int red, return 0; } if (external_pmode == FB_TYPE_PACKED_PIXELS && external_depth == 8 && - external_addr >= 0xa0000000) { + ext_is_supervidel()) { /* SuperVidel native 8bpp chunky scans out via the Falcon * palette registers, honoring all 8 bits per channel */ @@ -3336,7 +3344,7 @@ static int __init atafb_probe(struct platform_device *pdev) memset (screen_base, 0, external_len); /* framebuffer in SV RAM: enable the SuperBlitter */ - if (external_addr >= 0xa0000000 && + if (ext_is_supervidel() && ((external_pmode == FB_TYPE_PACKED_PIXELS && external_depth == 8) || (external_pmode == -1 && From f37d206e145d25607c6a8e920d7bb643d203a1f7 Mon Sep 17 00:00:00 2001 From: Xue Haolin Date: Tue, 17 Nov 2026 11:17:14 +0800 Subject: [PATCH 0945/2102] fbdev: sstfb: Error out if pixclock equals zero The userspace program could pass any values to the driver through ioctl() interface. If the driver doesn't check the value of pixclock, it may cause divide-by-zero error. sstfb_check_var() calls PICOS2KHZ(var->pixclock) which expands to 1000000000UL / var->pixclock. If var->pixclock is zero, this causes a divide-by-zero exception. Fix this by checking whether pixclock is zero at the beginning of sstfb_check_var(), before it is used as a divisor. This is similar to CVE-2022-3061 in i740fb which was fixed by commit 15cf0b82271b ("video: fbdev: i740fb: Error out if 'pixclock' equals zero"), and the fix in savagefb by commit 04e5eac8f3ab ("fbdev: savage: Error out if pixclock equals zero"). Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Signed-off-by: Xue Haolin Signed-off-by: Helge Deller --- drivers/video/fbdev/sstfb.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/video/fbdev/sstfb.c b/drivers/video/fbdev/sstfb.c index 8e2c2421028df7..de0769eb4a2fa7 100644 --- a/drivers/video/fbdev/sstfb.c +++ b/drivers/video/fbdev/sstfb.c @@ -359,6 +359,9 @@ static int sstfb_check_var(struct fb_var_screeninfo *var, int tiles_in_X, real_length; unsigned int freq; + if (!var->pixclock) + return -EINVAL; + if (sst_calc_pll(PICOS2KHZ(var->pixclock), &freq, &par->pll)) { printk(KERN_ERR "sstfb: Pixclock at %ld KHZ out of range\n", PICOS2KHZ(var->pixclock)); From 3e973ab62c86d620b2db9e90eb8fc3b065929e6e Mon Sep 17 00:00:00 2001 From: Tim Douglas Date: Tue, 17 Nov 2026 20:25:57 -0500 Subject: [PATCH 0946/2102] fbdev: macmodes: compare the pixel clock of each candidate mode In the second pass through the mode table in mac_var_to_vmode(), the requested pixel clock period was compared with the first mode's period at every step. The last mode at that resolution was therefore returned even when its period was too short. Compare against the current candidate's period. Tested on a Performa 6200CD using a kernel with local platform support. With video=valkyriefb:vmode:10 (800x600 at 60 Hz), the measured refresh rate was about 72 Hz before the fix and 60 Hz afterward. At 640x480, 67 Hz was also selected for a 60 Hz request before the fix. AI assistance was used to investigate the mode-table walk and draft the fix. Signed-off-by: Tim Douglas Fixes: d876c11a0fd4 ("fbdev: mac_var_to_mode() fix") Cc: stable@vger.kernel.org Signed-off-by: Helge Deller --- drivers/video/fbdev/macmodes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/video/fbdev/macmodes.c b/drivers/video/fbdev/macmodes.c index b16a9d9bef982f..7ea40fd34a10a5 100644 --- a/drivers/video/fbdev/macmodes.c +++ b/drivers/video/fbdev/macmodes.c @@ -342,7 +342,7 @@ int mac_var_to_vmode(const struct fb_var_screeninfo *var, int *vmode, if (mode->xres != clk_mode->xres || mode->yres != clk_mode->yres) break; - if (var->pixclock > mode->pixclock) + if (var->pixclock > clk_mode->pixclock) break; if (mode->vmode != clk_mode->vmode) continue; From fa9bebccf45571bd710b0591359b28d5354e7e7a Mon Sep 17 00:00:00 2001 From: Tim Douglas Date: Tue, 17 Nov 2026 20:58:59 -0500 Subject: [PATCH 0947/2102] fbdev: valkyriefb: keep the framebuffer mapping size fixed When /dev/fb0 is mapped before a depth change, as with Xorg's fbdev driver, the mapping may be too short for the new mode. At 640x480, a full frame at 16 bpp is 600 KiB, so drawing it through the original 300 KiB mapping from 8 bpp can fault. Set smem_len to the usable video RAM by subtracting the 4 KiB offset already applied to smem_start, then keep that size across mode changes. On a Performa 6200CD using a kernel with local platform support, a write past the mapping caused a fault during an Xorg test at 16 bpp. With the corrected mapping size in the test kernel, twm and xterm were displayed successfully in Xorg at 640x480 and 16 bpp. In a test on a Quadra 630 in MAME with Linux v7.4-rc3, /dev/fb0 was mapped at 8 bpp and the depth was changed to 16 bpp with the original mapping still in place. A SIGSEGV was reported during the 16 bpp draw before the fix, and all 480 lines were drawn afterward. AI assistance was used to investigate the mapping size and draft the fix. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Signed-off-by: Tim Douglas Cc: stable@vger.kernel.org Signed-off-by: Helge Deller --- drivers/video/fbdev/valkyriefb.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/video/fbdev/valkyriefb.c b/drivers/video/fbdev/valkyriefb.c index ec3cf45890567f..e067c89c91bfce 100644 --- a/drivers/video/fbdev/valkyriefb.c +++ b/drivers/video/fbdev/valkyriefb.c @@ -510,7 +510,7 @@ static void valkyrie_init_fix(struct fb_fix_screeninfo *fix, struct fb_info_valk fix->mmio_len = sizeof(struct valkyrie_regs); fix->type = FB_TYPE_PACKED_PIXELS; fix->smem_start = p->frame_buffer_phys + 0x1000; - fix->smem_len = p->total_vram; + fix->smem_len = p->total_vram - 0x1000; fix->type_aux = 0; fix->ywrapstep = 0; @@ -523,7 +523,6 @@ static void valkyrie_init_fix(struct fb_fix_screeninfo *fix, struct fb_info_valk static void valkyrie_par_to_fix(struct fb_par_valkyrie *par, struct fb_fix_screeninfo *fix) { - fix->smem_len = valkyrie_vram_reqd(par->vmode, par->cmode); fix->visual = (par->cmode == CMODE_8) ? FB_VISUAL_PSEUDOCOLOR : FB_VISUAL_DIRECTCOLOR; fix->line_length = par->vxres << par->cmode; From 2c8b0da3209955b42280ef60d8e0470dc788c0d8 Mon Sep 17 00:00:00 2001 From: Suyuan Wang Date: Wed, 18 Nov 2026 14:07:31 +0000 Subject: [PATCH 0948/2102] fbdev: cobalt_lcdfb: Don't read info after framebuffer_release() When devm_platform_get_and_ioremap_resource() fails, cobalt_lcdfb_probe() releases the framebuffer and then dereferences it for the return value: framebuffer_release(info); return PTR_ERR(info->screen_base); framebuffer_release() frees info, so info->screen_base is read from freed memory. Save the error code before releasing info. Found with a static analysis tool and checked by hand. Fixes: d2386d9e3eb4 ("fbdev: cobalt_lcdfb: Request memory region") Cc: stable@vger.kernel.org Co-developed-by: Kaixuan Li Signed-off-by: Kaixuan Li Signed-off-by: Suyuan Wang Signed-off-by: Helge Deller --- drivers/video/fbdev/cobalt_lcdfb.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/video/fbdev/cobalt_lcdfb.c b/drivers/video/fbdev/cobalt_lcdfb.c index f7faa95fefd3ca..e90f45c91725b6 100644 --- a/drivers/video/fbdev/cobalt_lcdfb.c +++ b/drivers/video/fbdev/cobalt_lcdfb.c @@ -297,8 +297,9 @@ static int cobalt_lcdfb_probe(struct platform_device *dev) info->screen_base = devm_platform_get_and_ioremap_resource(dev, 0, &res); if (IS_ERR(info->screen_base)) { + retval = PTR_ERR(info->screen_base); framebuffer_release(info); - return PTR_ERR(info->screen_base); + return retval; } info->screen_size = resource_size(res); From 8e156b9218f9f1f8b866d8e253145afdb01cf289 Mon Sep 17 00:00:00 2001 From: Kuba Piecuch Date: Wed, 18 Nov 2026 10:24:52 +0000 Subject: [PATCH 0949/2102] sched_ext: Don't route tasks to SCX before __scx_enabled is fully patched scx_root_enable_workfn() sets scx_switching_all and calls static_branch_enable(&__scx_enabled) before switching tasks, and task_should_scx() gates only on scx_enabled(). static_branch_enable() patches jump-label sites in address order rather than atomically: task_should_scx() may be patched before __schedule(). If a concurrent fork or sched_setscheduler() runs in that window, task_should_scx() observes scx_enabled() and moves the running task from fair_sched_class to ext_sched_class, setting need_resched on the class degradation. The following __schedule() can still observe !scx_enabled() in next_active_class(), skip ext_sched_class, and pick rq->idle while the runnable SCX task is still rq->donor: WARNING: kernel/sched/ext/ext.c:3840 at put_prev_task_scx+0x405/0x7a0 Sched_ext: enq_select_cpu (enabling+all), task: runnable_at=+0ms Call Trace: __schedule+0x5cc/0x1100 preempt_schedule_common+0x12/0x40 preempt_schedule_thunk+0x16/0x40 __sched_setscheduler+0x8d8/0x920 Gate task_should_scx() on a scx_task_switch_enabled flag that is set with release semantics only after static_branch_enable(&__scx_enabled) has finished patching all call sites and scx_switching_all is updated, and cleared on disable alongside scx_switching_all. This bug was found and the patch was written with the help of an AI coding assistant. Fixes: f0e1a0643a59 ("sched_ext: Implement BPF extensible scheduler class") Cc: stable@vger.kernel.org # v6.12+ Signed-off-by: Kuba Piecuch Reviewed-by: Andrea Righi Tested-by: Tao Cui Reviewed-by: Tao Cui Signed-off-by: Tejun Heo --- kernel/sched/ext/ext.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c index 10de6bd865e82a..e8c30a21e03e3f 100644 --- a/kernel/sched/ext/ext.c +++ b/kernel/sched/ext/ext.c @@ -134,6 +134,7 @@ DEFINE_PERCPU_RWSEM(scx_fork_rwsem); static atomic_t scx_enable_state_var = ATOMIC_INIT(SCX_DISABLED); static DEFINE_RAW_SPINLOCK(scx_bypass_lock); static bool scx_init_task_enabled; +static bool scx_task_switch_enabled; static bool scx_switching_all; DEFINE_STATIC_KEY_FALSE(__scx_switched_all); static DEFINE_STATIC_KEY_FALSE(__scx_tid_to_task_enabled); @@ -6493,6 +6494,15 @@ bool task_should_scx(int policy) if (!scx_enabled()) return false; + /* + * static_branch_enable(&__scx_enabled) patches call sites one by one. + * Wait until all sites are patched before routing tasks to SCX, so + * __schedule() never sees !scx_enabled() when a task is on SCX. Pairs + * with smp_store_release() in scx_root_enable_workfn(). + */ + if (unlikely(!smp_load_acquire(&scx_task_switch_enabled))) + return false; + /* scx is taking over all SCHED_OTHER and SCHED_EXT tasks */ if (READ_ONCE(scx_switching_all)) return true; @@ -7568,6 +7578,7 @@ static void scx_root_disable(struct scx_sched *sch) static_branch_disable(&__scx_switched_all); WRITE_ONCE(scx_switching_all, false); + WRITE_ONCE(scx_task_switch_enabled, false); /* * Shut down cgroup support before tasks so that the cgroup attach and @@ -8965,11 +8976,14 @@ static void scx_root_enable_workfn(struct kthread_work *work) percpu_up_write(&scx_fork_rwsem); /* - * All tasks are READY. It's safe to turn on scx_enabled() and switch - * all eligible tasks. + * All tasks are READY. Finish patching all scx_enabled() sites before + * opening task_should_scx() and switching eligible tasks. */ - WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL)); + WARN_ON_ONCE(scx_task_switch_enabled); static_branch_enable(&__scx_enabled); + WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL)); + /* pairs with smp_load_acquire() in task_should_scx() */ + smp_store_release(&scx_task_switch_enabled, true); /* * We're fully committed and can't fail. The task READY -> ENABLED From cf2212fd3053857f800cc22d903118d522131ca8 Mon Sep 17 00:00:00 2001 From: Peder Bergan Date: Tue, 17 Nov 2026 18:57:06 +0100 Subject: [PATCH 0950/2102] rust: str: tie Formatter to its backing buffer Formatter::new() returns a Formatter whose lifetime is independent of the borrow of its backing buffer. Safe code can therefore drop the buffer and then write through the formatter, causing a use-after-free. Tie the buffer borrow to the formatter's lifetime so that the borrow checker rejects such callers and prevents overlapping mutable access. Fixes: 87482d6d9104 ("rust: str: allow `str::Formatter` to format into `&mut [u8]`.") Cc: stable@vger.kernel.org Reported-by: Georgios Androutsopoulos Closes: https://github.com/Rust-for-Linux/linux/issues/1261 Signed-off-by: Peder Bergan Reviewed-by: Gary Guo Reviewed-by: Andreas Hindborg Reviewed-by: Alice Ryhl Link: https://patch.msgid.link/20261117-formatter-lifetime-v2-1-e216d86ffb57@gmail.com Signed-off-by: Miguel Ojeda --- rust/kernel/str.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 644b4279a11601..e5fe84eeb5c905 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -645,7 +645,7 @@ impl fmt::Write for RawFormatter { /// Fails if callers attempt to write more than will fit in the buffer. pub struct Formatter<'a>(RawFormatter, PhantomData<&'a mut ()>); -impl Formatter<'_> { +impl<'a> Formatter<'a> { /// Creates a new instance of [`Formatter`] with the given buffer. /// /// # Safety @@ -658,7 +658,7 @@ impl Formatter<'_> { } /// Create a new [`Self`] instance. - pub fn new(buffer: &mut [u8]) -> Self { + pub fn new(buffer: &'a mut [u8]) -> Self { // SAFETY: `buffer` is valid for writes for the entire length for // the lifetime of `Self`. unsafe { Formatter::from_buffer(buffer.as_mut_ptr(), buffer.len()) } From 88fa0c91640ce163190531bf3e975c73c77d7c7b Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Wed, 18 Nov 2026 18:29:51 +0300 Subject: [PATCH 0951/2102] KVM: arm64: nv: Forward PIR_EL2, PIRE0_EL2 and POR_EL2 traps These registers were added to KVM, but not to the encoding_to_cgt[] table which decides when a trap is forwarded to a nested hypervisor. The result is that if an L1 hypervisor runs its L2 with HCR_EL2.NV set (meaning the L2 is itself a hypervisor), and the L2 accesses these registers, KVM handles the access itself and it goes to the L1's own registers instead of being emulated on L1. This is quite a serious bug because it lets the L2 change the permissions of the L1's own stage 1 translations. It could mark everything as no-access and cause a crash in L1 or mark everything as read-write-execute which weakens the protections in L1. Add the three registers with CGT_HCR_NV, MAIR_EL2 and AMAIR_EL2. Fixes: 874ae1d48e60 ("KVM: arm64: Handle PIR{,E0}_EL2 traps") Fixes: 5970e9903f03 ("KVM: arm64: Add basic support for POR_EL2") Cc: stable@vger.kernel.org Signed-off-by: Dan Carpenter Link: https://patch.msgid.link/79097fe98499631673fd536ef2f1b8cfc92b979d.1795014776.git.dan@pereq.eu Signed-off-by: Marc Zyngier --- arch/arm64/kvm/emulate-nested.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/arm64/kvm/emulate-nested.c b/arch/arm64/kvm/emulate-nested.c index 2bec8166836148..bf4b8a44b9c44f 100644 --- a/arch/arm64/kvm/emulate-nested.c +++ b/arch/arm64/kvm/emulate-nested.c @@ -889,6 +889,9 @@ static const struct encoding_to_trap_config encoding_to_cgt[] __initconst = { SR_TRAP(SYS_PMSCR_EL2, CGT_HCR_NV), SR_TRAP(SYS_MAIR_EL2, CGT_HCR_NV), SR_TRAP(SYS_AMAIR_EL2, CGT_HCR_NV), + SR_TRAP(SYS_PIR_EL2, CGT_HCR_NV), + SR_TRAP(SYS_PIRE0_EL2, CGT_HCR_NV), + SR_TRAP(SYS_POR_EL2, CGT_HCR_NV), SR_TRAP(SYS_MPAMHCR_EL2, CGT_HCR_NV), SR_TRAP(SYS_MPAMVPMV_EL2, CGT_HCR_NV), SR_TRAP(SYS_MPAM2_EL2, CGT_HCR_NV), From fb32e91ac511101f528fa2f33cb1904b3796f5c3 Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Wed, 18 Nov 2026 18:30:02 +0300 Subject: [PATCH 0952/2102] KVM: arm64: nv: Forward CNTP_TVAL_EL02 and CNTV_TVAL_EL02 traps There are a couple timer related entries messing in the nested virtualization traps. With nested virtualization you can run a hypervisor in L1 and then you can run another hypervisor under that one in L2 and a guest under that in L3. Without these then if L2 tries to read or write L3's timers it instead reads and writes to its own timers. Fixes: c271269e3570 ("KVM: arm64: nv: Add trap routing for CNTHCTL_EL2.EL1{NVPCT,NVVCT,TVT,TVCT}") Cc: stable@vger.kernel.org Signed-off-by: Dan Carpenter Link: https://patch.msgid.link/80eb37d600ee6fa51f4c5fb478a31e8f0be180ef.1795014776.git.dan@pereq.eu Signed-off-by: Marc Zyngier --- arch/arm64/kvm/emulate-nested.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/arch/arm64/kvm/emulate-nested.c b/arch/arm64/kvm/emulate-nested.c index bf4b8a44b9c44f..9e0c15e6be473c 100644 --- a/arch/arm64/kvm/emulate-nested.c +++ b/arch/arm64/kvm/emulate-nested.c @@ -942,8 +942,10 @@ static const struct encoding_to_trap_config encoding_to_cgt[] __initconst = { sys_reg(3, 5, 14, 1, 0), CGT_HCR_NV), SR_TRAP(SYS_CNTP_CTL_EL02, CGT_CNTHCTL_EL1NVPCT), SR_TRAP(SYS_CNTP_CVAL_EL02, CGT_CNTHCTL_EL1NVPCT), + SR_TRAP(SYS_CNTP_TVAL_EL02, CGT_HCR_NV), SR_TRAP(SYS_CNTV_CTL_EL02, CGT_CNTHCTL_EL1NVVCT), SR_TRAP(SYS_CNTV_CVAL_EL02, CGT_CNTHCTL_EL1NVVCT), + SR_TRAP(SYS_CNTV_TVAL_EL02, CGT_HCR_NV), SR_TRAP(OP_AT_S1E2R, CGT_HCR_NV), SR_TRAP(OP_AT_S1E2W, CGT_HCR_NV), SR_TRAP(OP_AT_S12E1R, CGT_HCR_NV), From 2fec206f37582b9295185a86e43a08ac74e149d2 Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Wed, 18 Nov 2026 18:30:08 +0300 Subject: [PATCH 0953/2102] KVM: arm64: nv: Report EL2 registers with no trap forwarding One of the recurring issues we run into is that people add a trap to KVM but they forget to add a matching trap for nested virtualization. Add a boot time warning to print a warning for missing traps. Signed-off-by: Dan Carpenter Link: https://patch.msgid.link/5a7235e9adff42aa043ac9473dbeb0354dca0967.1795014776.git.dan@pereq.eu Signed-off-by: Marc Zyngier --- arch/arm64/include/asm/kvm_host.h | 2 +- arch/arm64/kvm/emulate-nested.c | 5 ++++- arch/arm64/kvm/sys_regs.c | 23 +++++++++++++++++++++-- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/arch/arm64/include/asm/kvm_host.h b/arch/arm64/include/asm/kvm_host.h index 97332ffcb1300e..adbcf66ec42478 100644 --- a/arch/arm64/include/asm/kvm_host.h +++ b/arch/arm64/include/asm/kvm_host.h @@ -1376,7 +1376,7 @@ void kvm_reset_sys_regs(struct kvm_vcpu *vcpu); int __init kvm_sys_reg_table_init(void); struct sys_reg_desc; int __init populate_sysreg_config(const struct sys_reg_desc *sr, - unsigned int idx); + unsigned int idx, bool needs_nv_trap); int __init populate_nv_trap_config(void); void kvm_calculate_traps(struct kvm_vcpu *vcpu); diff --git a/arch/arm64/kvm/emulate-nested.c b/arch/arm64/kvm/emulate-nested.c index 9e0c15e6be473c..39136a89d74bb6 100644 --- a/arch/arm64/kvm/emulate-nested.c +++ b/arch/arm64/kvm/emulate-nested.c @@ -2434,7 +2434,7 @@ int __init populate_nv_trap_config(void) } int __init populate_sysreg_config(const struct sys_reg_desc *sr, - unsigned int idx) + unsigned int idx, bool needs_nv_trap) { union trap_config tc; u32 encoding; @@ -2452,6 +2452,9 @@ int __init populate_sysreg_config(const struct sys_reg_desc *sr, encoding = sys_reg(sr->Op0, sr->Op1, sr->CRn, sr->CRm, sr->Op2); tc = get_trap_config(encoding); + if (needs_nv_trap && !tc.val) + kvm_err("sysreg %s has no NV trap configuration\n", sr->name); + if (tc.sri) { kvm_err("sysreg %s (%d) duplicate entry (%d)\n", sr->name, idx - 1, tc.sri); diff --git a/arch/arm64/kvm/sys_regs.c b/arch/arm64/kvm/sys_regs.c index 850eba167aad6a..352d5c89494111 100644 --- a/arch/arm64/kvm/sys_regs.c +++ b/arch/arm64/kvm/sys_regs.c @@ -5949,6 +5949,23 @@ int kvm_vcpu_finalize_sys_regs(struct kvm_vcpu *vcpu) return 0; } +/* Keep the nested virtualization traps in sync with the KVM traps. */ +static bool __init needs_nv_trap(const struct sys_reg_desc *r) +{ + /* op1 4 is the EL2 encodings, op1 5 the _EL12 and _EL02 aliases */ + if (r->Op1 != 4 && r->Op1 != 5) + return false; + + if (!r->access || + r->access == bad_vncr_trap || + r->access == trap_raz_wi || + r->access == bad_redir_trap || + r->access == undef_access) + return false; + + return true; +} + int __init kvm_sys_reg_table_init(void) { const struct sys_reg_desc *gicv3_regs, *gicv5_regs; @@ -5981,10 +5998,12 @@ int __init kvm_sys_reg_table_init(void) check_feature_map(); for (i = 0; !ret && i < ARRAY_SIZE(sys_reg_descs); i++) - ret = populate_sysreg_config(sys_reg_descs + i, i); + ret = populate_sysreg_config(sys_reg_descs + i, i, + needs_nv_trap(sys_reg_descs + i)); for (i = 0; !ret && i < ARRAY_SIZE(sys_insn_descs); i++) - ret = populate_sysreg_config(sys_insn_descs + i, i); + ret = populate_sysreg_config(sys_insn_descs + i, i, + needs_nv_trap(sys_insn_descs + i)); return ret; } From 50e9e6b6eb3d9b2c318babce60abdf3b300cfb35 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Mon, 9 Nov 2026 08:48:36 +0000 Subject: [PATCH 0954/2102] KVM: arm64: Hide generic ptrauth from protected VMs without ptrauth A protected VM without the ptrauth vCPU features shouldn't have pointer authentication in its ID registers. Commit 3d7ff00700d1 ("KVM: arm64: Rework specifying restricted features for protected VMs") gated APA, API, APA3 and GPA3 on vm_has_ptrauth(), but left GPA and GPI capped at IMP. So generic authentication is advertised to a protected guest without ptrauth, and PACGA UNDEFs. Gate GPA and GPI on vm_has_ptrauth() too. Fixes: 3d7ff00700d1 ("KVM: arm64: Rework specifying restricted features for protected VMs") Signed-off-by: Fuad Tabba Link: https://patch.msgid.link/20261109084854.840576-2-fuad.tabba@linux.dev Signed-off-by: Marc Zyngier --- arch/arm64/kvm/hyp/nvhe/sys_regs.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/arch/arm64/kvm/hyp/nvhe/sys_regs.c b/arch/arm64/kvm/hyp/nvhe/sys_regs.c index 32e82653ebf7e7..e5502d5651b058 100644 --- a/arch/arm64/kvm/hyp/nvhe/sys_regs.c +++ b/arch/arm64/kvm/hyp/nvhe/sys_regs.c @@ -157,8 +157,8 @@ static const struct pvm_ftr_bits pvmid_aa64isar1[] = { MAX_FEAT(ID_AA64ISAR1_EL1, JSCVT, IMP), MAX_FEAT(ID_AA64ISAR1_EL1, FCMA, IMP), MAX_FEAT(ID_AA64ISAR1_EL1, LRCPC, LRCPC3), - MAX_FEAT(ID_AA64ISAR1_EL1, GPA, IMP), - MAX_FEAT(ID_AA64ISAR1_EL1, GPI, IMP), + MAX_FEAT_FUNC(ID_AA64ISAR1_EL1, GPA, IMP, vm_has_ptrauth), + MAX_FEAT_FUNC(ID_AA64ISAR1_EL1, GPI, IMP, vm_has_ptrauth), MAX_FEAT(ID_AA64ISAR1_EL1, FRINTTS, IMP), MAX_FEAT(ID_AA64ISAR1_EL1, SB, IMP), MAX_FEAT(ID_AA64ISAR1_EL1, SPECRES, COSP_RCTX), From 80e03f76f00c092377708da697a103b903026452 Mon Sep 17 00:00:00 2001 From: Mahesh Salgaonkar Date: Thu, 22 Oct 2026 15:43:42 +0530 Subject: [PATCH 0955/2102] MAINTAINERS: Update EEH maintainer details I no longer have the bandwidth to maintain EEH. Sourabh Jain has graciously agreed to take over as the new maintainer. - Add Sourabh Jain as EEH maintainer - Remove myself from the EEH maintainer role Thank you Sourabh for stepping up and ensuring continued support for EEH. Signed-off-by: Mahesh Salgaonkar Acked-by: Sourabh Jain Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261022101342.2962384-1-mahesh@linux.ibm.com --- MAINTAINERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index ca1c59e1fc5928..4387bfa677b81b 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -21619,7 +21619,7 @@ F: drivers/pci/endpoint/ F: tools/testing/selftests/pci_endpoint/ PCI ENHANCED ERROR HANDLING (EEH) FOR POWERPC -M: Mahesh J Salgaonkar +M: Sourabh Jain R: Oliver O'Halloran L: linuxppc-dev@lists.ozlabs.org S: Supported From 73bdf8773de4af2c2b7f49370191ae6d5aeddea5 Mon Sep 17 00:00:00 2001 From: Alice Ryhl Date: Wed, 18 Nov 2026 13:09:18 +0000 Subject: [PATCH 0956/2102] kbuild: rust: disable function merging unconditionally Function merging causes various different issues: * For CONFIG_CFI there's an LLVM bug causing functions with different CFI hashes to get merged. This can lead to crashes at runtime. * For gendwarfksyms it causes functions with different CRCs to get merged. This leads to broken MODVERSIONS information if the function changes in the future so that it can no longer be merged. * Wrong backtraces when a crash occurs in a merged function. * Possibly also issues with pahole/BTF as the merged function's debug info is lost. These issues are new to Rust because in clang, function merging is off by default, so these things have never come up before. Because of this, turn this option off for all configurations. [ The LLVM bug is tracked at [1]. Nick asked what function merging refers to here, and Alice writes [2]: No, this isn't linker ICF. rustc doesn't pass --icf, and in any case kbuild invokes rustc with --emit=obj and does the final link itself, so rustc's linker arguments never come into play. What I'm referring to is LLVM's MergeFunctions IR pass (llvm/lib/Transforms/IPO/MergeFunctions.cpp). It runs as part of the optimization pipeline, within a single codegen unit, before any object file is emitted. Clang only enables it with the cc1-only flag -fmerge-functions, which the kernel never passes, so C code in the kernel never sees it. rustc, however, enables it by default whenever optimizing for speed or size (opt-level 2, 3, s or z), which covers both kernel configurations. It uses the "aliases" mode: when two functions have identical bodies, one is deleted and its symbol becomes a GlobalAlias to the other. You can turn it off with -Zmerge-functions=disabled. - Miguel ] Link: https://lore.kernel.org/all/avy_9SPRaPSKD8b4@google.com/ Fixes: ac61506bf2d1 ("rust: Use gendwarfksyms + extended modversions for CONFIG_MODVERSIONS") Signed-off-by: Alice Ryhl Cc: stable@vger.kernel.org Reviewed-by: Gary Guo Reviewed-by: Sami Tolvanen Link: https://github.com/llvm/llvm-project/issues/217629 [1] Link: https://lore.kernel.org/rust-for-linux/CAH5fLgidhnPbP=xXQ3162w6q0U6rWHPZ9Mu6-E5va4_CXyanOg@mail.gmail.com/ [2] Link: https://patch.msgid.link/20261118-rust-merge-functions-v1-1-fe86126522b9@google.com Signed-off-by: Miguel Ojeda --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 5aac6f1b011e1b..17b7ac3afbc4a4 100644 --- a/Makefile +++ b/Makefile @@ -622,6 +622,7 @@ KBUILD_RUSTFLAGS := $(rust_common_flags) \ -Csymbol-mangling-version=v0 \ -Crelocation-model=static \ -Zfunction-sections=n \ + -Zmerge-functions=disabled \ -Wclippy::float_arithmetic KBUILD_RUSTFLAGS_OPTION_CHKS := @@ -1136,8 +1137,7 @@ endif ifdef CONFIG_RUST # Always pass -Zsanitizer-cfi-normalize-integers as CONFIG_RUST selects # CONFIG_CFI_ICALL_NORMALIZE_INTEGERS. - # Disable function merging as LLVM incorrectly merges functions with different KCFI types. - RUSTC_FLAGS_CFI := -Zsanitizer=kcfi -Zsanitizer-cfi-normalize-integers -Zmerge-functions=disabled + RUSTC_FLAGS_CFI := -Zsanitizer=kcfi -Zsanitizer-cfi-normalize-integers KBUILD_RUSTFLAGS += $(RUSTC_FLAGS_CFI) export RUSTC_FLAGS_CFI endif From d836398542f1e11a8b5191f9e50c0e4ee9b0b13b Mon Sep 17 00:00:00 2001 From: Mahesh Salgaonkar Date: Wed, 28 Oct 2026 09:42:17 +0530 Subject: [PATCH 0957/2102] MAINTAINERS: Update OCXL maintainer details I no longer have the bandwidth to maintain OCXL. The powerpc maintainer, Madhavan Srinivasan, has kindly agreed to take over. - Add Madhavan Srinivasan as the OCXL maintainer - Remove myself from the OCXL maintainer role Signed-off-by: Mahesh Salgaonkar Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261028041217.499673-1-mahesh@linux.ibm.com --- MAINTAINERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index 4387bfa677b81b..04bfd23968ae78 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -20476,7 +20476,7 @@ F: drivers/net/dsa/ocelot/ocelot_ext.c F: include/linux/mfd/ocelot.h OCXL (Open Coherent Accelerator Processor Interface OpenCAPI) DRIVER -M: Mahesh J Salgaonkar +M: Madhavan Srinivasan R: Andrew Donnellan L: linuxppc-dev@lists.ozlabs.org S: Odd Fixes From 0f1bdabb82be5d1b5401364cd828caf0985dad48 Mon Sep 17 00:00:00 2001 From: Colton Lewis Date: Wed, 18 Nov 2026 20:36:24 +0000 Subject: [PATCH 0958/2102] KVM: arm64: Force HCR_EL2.NV1 to RES0 unconditionally ID_AA64MMFR4_EL1.E2H0 is a signed 4-bit field where: - 0b0000 (IMP, 0): FEAT_E2H0 is implemented. - 0b1111 (NI, -1): FEAT_E2H0 is not implemented, except HCR_EL2.NV1 is implemented. - 0b1110 (NI_NV1, -2): Neither HCR_EL2.E2H == 0 nor HCR_EL2.NV1 is implemented, and HCR_EL2.NV1 is RES0. When commit b2a324ff01fe ("KVM: arm64: Use HCR_EL2 feature map to drive fixed-value bits") converted HCR_EL2 to hcr_feat_map[], feat_nv2_e2h0_ni() was written as !kvm_has_feat(kvm, FEAT_E2H0), where FEAT_E2H0 checks E2H0 >= IMP (0). This inverted the condition: feat_nv2_e2h0_ni() evaluates to true when E2H0 < 0 (including NI_NV1), leaving HCR_EL2.NV1 writable instead of RES0 for VHE-only nested guests where KVM advertises ID_AA64MMFR4_EL1.E2H0 = NI_NV1. In practice, KVM cannot handle HCR_EL2.NV1 being non-RES0 in any configuration: limit_nv_id_reg() exposes either VHE-only EL2 with ID_AA64MMFR4_EL1.E2H0 = NI_NV1 (and E2H0 is not userspace-writable), or FEAT_E2H0 without FEAT_VHE or FEAT_NV. Checking E2H0 in a feature helper is therefore unnecessary. Drop feat_nv2_e2h0_ni() and mark HCR_EL2_NV1 as an unconditional RES0 bit using NEEDS_FEAT_FLAG(HCR_EL2_NV1, FORCE_RESx) in hcr_feat_map[] (shared by HCR_EL2 and NVHCR_EL2). Because HCR_EL2_NV1 is not part of the architectural HCR_EL2_RES0 mask, check_feat_map() accounts for it as an implementation-defined FORCE_RESx bit. Fixes: b2a324ff01fe ("KVM: arm64: Use HCR_EL2 feature map to drive fixed-value bits") Suggested-by: Marc Zyngier Signed-off-by: Colton Lewis Link: https://patch.msgid.link/20261118203625.743428-2-coltonlewis@google.com Signed-off-by: Marc Zyngier --- arch/arm64/kvm/config.c | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/arch/arm64/kvm/config.c b/arch/arm64/kvm/config.c index adaf26ab93b857..2e81f45dc99219 100644 --- a/arch/arm64/kvm/config.c +++ b/arch/arm64/kvm/config.c @@ -256,11 +256,6 @@ static bool feat_nv2(struct kvm *kvm) kvm_has_feat(kvm, ID_AA64MMFR2_EL1, NV, NV2)); } -static bool feat_nv2_e2h0_ni(struct kvm *kvm) -{ - return feat_nv2(kvm) && !kvm_has_feat(kvm, FEAT_E2H0); -} - static bool feat_rasv1p1(struct kvm *kvm) { return (kvm_has_feat(kvm, ID_AA64PFR0_EL1, RAS, V1P1) || @@ -1034,7 +1029,7 @@ static const struct reg_bits_to_feat_map hcr_feat_map[] = { HCR_EL2_NV2 | HCR_EL2_NV, feat_nv2), - NEEDS_FEAT(HCR_EL2_NV1, feat_nv2_e2h0_ni), /* Missing from JSON */ + NEEDS_FEAT_FLAG(HCR_EL2_NV1, FORCE_RESx), /* Missing from JSON, RES0 as an IMPDEF choice */ NEEDS_FEAT(HCR_EL2_API | HCR_EL2_APK, feat_pauth), From accc93b77267b739b48ab34cb5bcaffd1fbb5db9 Mon Sep 17 00:00:00 2001 From: Colton Lewis Date: Wed, 18 Nov 2026 20:36:25 +0000 Subject: [PATCH 0959/2102] KVM: arm64: selftests: Verify HCR_EL2.NV1 is RES0 when E2H0 is NI_NV1 In a VHE-only EL2 guest (KVM_ARM_VCPU_HAS_EL2 without KVM_ARM_VCPU_HAS_EL2_E2H0), KVM advertises ID_AA64MMFR4_EL1.E2H0 as NI_NV1, making HCR_EL2.E2H RES1 and HCR_EL2.NV1 RES0. Extend hello_el2 to attempt clearing HCR_EL2.E2H and setting HCR_EL2.NV1 from userspace via KVM_SET_ONE_REG, verifying that HCR_EL2.E2H remains RES1 and HCR_EL2.NV1 is masked to RES0. Add a comment explaining why the check is performed from userspace rather than inside the guest. Signed-off-by: Colton Lewis Link: https://patch.msgid.link/20261118203625.743428-3-coltonlewis@google.com Signed-off-by: Marc Zyngier --- tools/testing/selftests/kvm/arm64/hello_el2.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tools/testing/selftests/kvm/arm64/hello_el2.c b/tools/testing/selftests/kvm/arm64/hello_el2.c index bbe6862c6ab16e..3bd3596f5fb1e4 100644 --- a/tools/testing/selftests/kvm/arm64/hello_el2.c +++ b/tools/testing/selftests/kvm/arm64/hello_el2.c @@ -45,6 +45,7 @@ int main(void) struct kvm_vcpu *vcpu; struct kvm_vm *vm; struct ucall uc; + u64 hcr; TEST_REQUIRE(kvm_check_cap(KVM_CAP_ARM_EL2)); @@ -66,6 +67,20 @@ int main(void) TEST_FAIL("Unhandled ucall: %ld\n", uc.cmd); } + /* + * Verify RES0/RES1 enforcement from userspace rather than inside + * the guest. From the guest's perspective RESx bits may be + * stateful (reading back as written) even though their value is + * ignored, whereas KVM_SET_ONE_REG applies the effective masks + * directly. + */ + hcr = vcpu_get_reg(vcpu, KVM_ARM64_SYS_REG(SYS_HCR_EL2)); + vcpu_set_reg(vcpu, KVM_ARM64_SYS_REG(SYS_HCR_EL2), + (hcr & ~HCR_EL2_E2H) | HCR_EL2_NV1); + hcr = vcpu_get_reg(vcpu, KVM_ARM64_SYS_REG(SYS_HCR_EL2)); + TEST_ASSERT(hcr & HCR_EL2_E2H, "HCR_EL2.E2H should be RES1"); + TEST_ASSERT(!(hcr & HCR_EL2_NV1), "HCR_EL2.NV1 should be RES0"); + kvm_vm_free(vm); return 0; } From f94f85f82e042c89a1e64ed3ff1d591a2bccfa7b Mon Sep 17 00:00:00 2001 From: Hyunjung Ko Date: Tue, 17 Nov 2026 19:41:10 +0900 Subject: [PATCH 0960/2102] gpio: mpsse: reject bulk-in endpoints smaller than 3 bytes mpsse_read() reads min(len + 2, wMaxPacketSize) bytes and then copies len_actual - 2 bytes to the caller. A device that declares a bulk-in endpoint with wMaxPacketSize 1 completes the read with len_actual 1, so the copy length becomes -1 and memcpy() runs far past the one byte buffer on the caller's stack and past bulk_in_buf: memcpy: detected buffer overflow: 18446744073709551615 byte write of buffer size 1 WARNING: lib/string_helpers.c:1036 at __fortify_report+0x6e/0xc0 Call Trace: __fortify_panic+0xd/0x10 gpio_mpsse_get_multiple+0x767/0x780 gpio_mpsse_gpio_get+0xa2/0xf0 gpiod_get_raw_value_commit+0xf8/0x1f0 gpiod_get_value_cansleep+0x1e/0xa0 value_show+0x42/0x90 Reproduced with dummy_hcd and raw-gadget. A read needs room for the two status bytes plus at least one data byte, so refuse to bind otherwise. Fixes: c46a74ff05c0 ("gpio: add support for FTDI's MPSSE as GPIO") Cc: stable@vger.kernel.org Signed-off-by: Hyunjung Ko Link: https://patch.msgid.link/20261117104110.240112-1-hj351016@gmail.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-mpsse.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/gpio/gpio-mpsse.c b/drivers/gpio/gpio-mpsse.c index a16b6875b2e20c..393c537c1d2753 100644 --- a/drivers/gpio/gpio-mpsse.c +++ b/drivers/gpio/gpio-mpsse.c @@ -676,6 +676,10 @@ static int gpio_mpsse_probe(struct usb_interface *interface, if (err) return err; + /* Every read carries two status bytes ahead of the data */ + if (usb_endpoint_maxp(priv->bulk_in) < 3) + return -EINVAL; + priv->bulk_in_buf = devm_kmalloc(dev, usb_endpoint_maxp(priv->bulk_in), GFP_KERNEL); if (!priv->bulk_in_buf) From 9df982f1f283d2f2a9aad764dff92e36ed764e16 Mon Sep 17 00:00:00 2001 From: Jiawen Liu <1298662399@qq.com> Date: Mon, 9 Nov 2026 17:42:04 +0400 Subject: [PATCH 0961/2102] gpio: omap: handle debounce clock preparation failure omap_gpio_probe() ignores the return value of clk_prepare() for the debounce clock. If preparation fails, the driver still treats debounce as available and may use or unprepare a clock that was not prepared. Use devm_clk_get_prepared() and disable debounce if the clock cannot be obtained or prepared. This keeps the existing behavior for clock lookup failures. Remove both manual clk_unprepare() calls because the managed clock is released on probe failure and device removal. Fixes: 5d9452e7c52a ("gpio: omap: fix clk_prepare/unprepare usage") Suggested-by: Andreas Kemnade Link: https://lore.kernel.org/r/tencent_B4F504456790E8BA3C4EAB80F4BFB6954E08@qq.com Link: https://lkml.rescloud.iu.edu/hypermail/linux/kernel/2412.2/00414.html Signed-off-by: Jiawen Liu <1298662399@qq.com> Reviewed-by: Linus Walleij Reviewed-by: Alexander Sverdlin Tested-by: Alexander Sverdlin Link: https://patch.msgid.link/tencent_D8A4B6EE90931660EB6F586543FD58110E06@qq.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-omap.c | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/drivers/gpio/gpio-omap.c b/drivers/gpio/gpio-omap.c index 585c2784bb7552..0da628ae77bedc 100644 --- a/drivers/gpio/gpio-omap.c +++ b/drivers/gpio/gpio-omap.c @@ -1449,13 +1449,11 @@ static int omap_gpio_probe(struct platform_device *pdev) } if (bank->dbck_flag) { - bank->dbck = devm_clk_get(dev, "dbclk"); + bank->dbck = devm_clk_get_prepared(dev, "dbclk"); if (IS_ERR(bank->dbck)) { dev_err(dev, - "Could not get gpio dbck. Disable debounce\n"); + "Could not get or prepare gpio dbck. Disable debounce\n"); bank->dbck_flag = false; - } else { - clk_prepare(bank->dbck); } } @@ -1479,8 +1477,6 @@ static int omap_gpio_probe(struct platform_device *pdev) if (ret) { pm_runtime_put_sync(dev); pm_runtime_disable(dev); - if (bank->dbck_flag) - clk_unprepare(bank->dbck); return ret; } @@ -1501,8 +1497,6 @@ static void omap_gpio_remove(struct platform_device *pdev) cpu_pm_unregister_notifier(&bank->nb); gpiochip_remove(&bank->chip); pm_runtime_disable(&pdev->dev); - if (bank->dbck_flag) - clk_unprepare(bank->dbck); } static int omap_gpio_runtime_suspend(struct device *dev) From 8a0b03058ff700deb74f4b38f5a254238bdf4e07 Mon Sep 17 00:00:00 2001 From: Simon Schippers Date: Fri, 13 Nov 2026 11:46:47 +0100 Subject: [PATCH 0962/2102] veth: wake a stopped peer txq beyond real_num_tx_queues Since commit dc82a33297fc ("veth: apply qdisc backpressure on full ptr_ring to reduce TX drops"), only the peer's veth_poll() wakes a txq that veth_xmit() stopped on a full ptr_ring. veth_poll() skips txqs at or above the peer's real_num_tx_queues. If the peer shrinks its TX channels while such a txq is stopped, nothing wakes it. netif_set_real_num_tx_queues() keeps its state, so once the channels are grown back, its first skb is requeued forever. With a single root qdisc this blocks all transmission of the device. Look the txq up below num_tx_queues instead. Waking a txq that is not in use is harmless. Reproduced in virtme-ng with a UDP flood from veth0 into veth1, which has GRO, while switching veth0 between one and two TX channels: without this patch veth0 stopped transmitting within 11 cycles in 3 of 3 runs, with it veth0 kept transmitting through 30 cycles in 3 of 3 runs. Fixes: 08f566e8f83b ("veth: fix OOB txq access in veth_poll() with asymmetric queue counts") Signed-off-by: Simon Schippers Reviewed-by: Tianyi Gao Tested-by: Tianyi Gao Link: https://patch.msgid.link/20261113104648.225983-2-simon.schippers@tu-dortmund.de Signed-off-by: Paolo Abeni --- drivers/net/veth.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/veth.c b/drivers/net/veth.c index a61842b2585bfa..62a60a033675de 100644 --- a/drivers/net/veth.c +++ b/drivers/net/veth.c @@ -984,7 +984,7 @@ static int veth_poll(struct napi_struct *napi, int budget) /* NAPI functions as RCU section */ peer_dev = rcu_dereference_check(priv->peer, rcu_read_lock_bh_held()); - peer_txq = (peer_dev && queue_idx < peer_dev->real_num_tx_queues) ? + peer_txq = (peer_dev && queue_idx < peer_dev->num_tx_queues) ? netdev_get_tx_queue(peer_dev, queue_idx) : NULL; xdp_set_return_frame_no_direct(); From b2f4c44d7d83770ee1f235a732d8e1fd831c4926 Mon Sep 17 00:00:00 2001 From: Simon Schippers Date: Fri, 13 Nov 2026 11:46:48 +0100 Subject: [PATCH 0963/2102] veth: wake the peer txq when deleting NAPI Since commit dc82a33297fc ("veth: apply qdisc backpressure on full ptr_ring to reduce TX drops"), only the peer's veth_poll() wakes a txq that veth_xmit() stopped on a full ptr_ring. If veth_xmit() stops the txq after the last poll before napi_disable(), its __veth_xdp_flush() can no longer schedule NAPI. Nothing wakes the txq, also not after NAPI is added back, so the device stops transmitting for good. This can happen whenever the peer deletes its NAPI: when it goes down, turns GRO off, detaches XDP or reduces its RX channels. Wake the peer txq in veth_napi_del_range() once NAPI is deleted, also when the peer is down, as opening it does not restart its queues. Reproduced in virtme-ng with a pktgen flood while toggling GRO on the peer, with a udelay() before netif_tx_stop_queue() to widen the race: the txq got stuck within four toggles without this patch, and not in 300 with it. Without the udelay() it was not hit in 1200 toggles. Fixes: dc82a33297fc ("veth: apply qdisc backpressure on full ptr_ring to reduce TX drops") Signed-off-by: Simon Schippers Reviewed-by: Tianyi Gao Tested-by: Tianyi Gao Link: https://patch.msgid.link/20261113104648.225983-3-simon.schippers@tu-dortmund.de Signed-off-by: Paolo Abeni --- drivers/net/veth.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/net/veth.c b/drivers/net/veth.c index 62a60a033675de..faa837acea7b7e 100644 --- a/drivers/net/veth.c +++ b/drivers/net/veth.c @@ -1087,6 +1087,7 @@ static int __veth_napi_enable(struct net_device *dev) static void veth_napi_del_range(struct net_device *dev, int start, int end) { struct veth_priv *priv = netdev_priv(dev); + struct net_device *peer; int i; for (i = start; i < end; i++) { @@ -1099,11 +1100,17 @@ static void veth_napi_del_range(struct net_device *dev, int start, int end) } synchronize_net(); + peer = rtnl_dereference(priv->peer); + for (i = start; i < end; i++) { struct veth_rq *rq = &priv->rq[i]; rq->rx_notify_masked = false; ptr_ring_cleanup(&rq->xdp_ring, veth_ptr_free); + + /* veth_poll() can no longer wake a txq stopped on a full ring */ + if (peer && i < peer->num_tx_queues) + netif_wake_subqueue(peer, i); } for (i = start; i < end; i++) { From 591bdbafeead9ae8458687cd873e277e6a87949a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 15:52:05 +0100 Subject: [PATCH 0964/2102] landlock: Factor out capability denial checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit commoncap also makes capability decisions from LSM hooks other than capable, and the following commits add Landlock counterparts for them. Move the check and its denial logging from hook_capable() into check_cap() so that these hooks share it. No functional change. Cc: Günther Noack Acked-by: Serge Hallyn (AMD) Reviewed-by: Günther Noack Link: https://patch.msgid.link/20261118145217.2551053-2-mic@digikod.net Signed-off-by: Mickaël Salaün --- security/landlock/cap.c | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/security/landlock/cap.c b/security/landlock/cap.c index b4f491b09baa79..fa59118e3486fd 100644 --- a/security/landlock/cap.c +++ b/security/landlock/cap.c @@ -24,25 +24,21 @@ static const struct access_masks cap_permission = { }; /** - * hook_capable - Deny capability use for Landlock-sandboxed processes + * check_cap - Check a capability use against the domain of @cred * * @cred: Credentials being checked. - * @ns: Target user namespace (intentionally ignored; policy depends on the - * acting credentials and @cap, not namespace ownership). * @cap: Capability number (CAP_*). * @opts: Capability check options. CAP_OPT_NOAUDIT skips the denial record: * no audit record, no trace event, and no denial count. * * Pure bitmask check: denies the capability if it is not in the layer's allowed - * set. This hook is purely restrictive: commoncap is registered with - * LSM_ORDER_FIRST so cap_capable() always runs first, which means Landlock can - * deny capabilities that commoncap would allow, but never grant capabilities - * that commoncap denied. + * set. It does not check that @cred holds @cap: only call it for a capability + * that commoncap already granted. * * Return: 0 if allowed, -EPERM if capability use is denied. */ -static int hook_capable(const struct cred *cred, struct user_namespace *ns, - int cap, unsigned int opts) +static int check_cap(const struct cred *const cred, const int cap, + const unsigned int opts) { const struct landlock_cred_security *subject; size_t denied_layer; @@ -72,6 +68,28 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns, return -EPERM; } +/** + * hook_capable - Deny capability use for Landlock-sandboxed processes + * + * @cred: Credentials being checked. + * @ns: Target user namespace (intentionally ignored; policy depends on the + * acting credentials and @cap, not namespace ownership). + * @cap: Capability number (CAP_*). + * @opts: Capability check options, see check_cap(). + * + * This hook is purely restrictive: commoncap is registered with LSM_ORDER_FIRST + * so cap_capable() always runs first, which means Landlock can deny + * capabilities that commoncap would allow, but never grant capabilities that + * commoncap denied. + * + * Return: 0 if allowed, -EPERM if capability use is denied. + */ +static int hook_capable(const struct cred *cred, struct user_namespace *ns, + int cap, unsigned int opts) +{ + return check_cap(cred, cap, opts); +} + static struct security_hook_list landlock_hooks[] __ro_after_init = { LSM_HOOK_INIT(capable, hook_capable), }; From 25590e68c40753e28e4713d2dbfde6ba10a7daeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 15:52:06 +0100 Subject: [PATCH 0965/2102] landlock: Mediate CAP_SYS_RAWIO for mappings below mmap_min_addr MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit commoncap's mmap_addr hook checks CAP_SYS_RAWIO for mappings below vm.mmap_min_addr with cap_capable(), which skips the capable hook, so a domain denying CAP_SYS_RAWIO cannot prevent these mappings. Mapping the lowest pages helps to exploit kernel NULL pointer dereferences. Add a Landlock mmap_addr hook that checks CAP_SYS_RAWIO against the domain under the same condition, as SELinux checks its own mmap_zero permission in this hook. commoncap runs first, so the hook only sees mappings that commoncap allowed. This also covers the x86 vm86(2) and vm86old(2) system calls. Calling capable() from cap_mmap_addr() would instead expose this check to the capable hook of all LSMs. Cc: Günther Noack Cc: Paul Moore Cc: Serge Hallyn Acked-by: Serge Hallyn (AMD) Reviewed-by: Günther Noack Fixes: 97c8386f1d74 ("landlock: Enforce capability restrictions") Link: https://patch.msgid.link/20261118145217.2551053-3-mic@digikod.net Signed-off-by: Mickaël Salaün --- security/landlock/cap.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/security/landlock/cap.c b/security/landlock/cap.c index fa59118e3486fd..10e1ca772b9ce4 100644 --- a/security/landlock/cap.c +++ b/security/landlock/cap.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include "cap.h" @@ -90,8 +91,29 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns, return check_cap(cred, cap, opts); } +/** + * hook_mmap_addr - Restrict mappings below dac_mmap_min_addr + * + * @addr: Address of the new mapping. + * + * cap_mmap_addr() requires CAP_SYS_RAWIO to map below dac_mmap_min_addr, but + * calls cap_capable() directly, which skips hook_capable(). Check the same + * condition against the domain. commoncap runs first, so this only sees + * mappings that commoncap allowed. + * + * Return: 0 if allowed, -EPERM if CAP_SYS_RAWIO use is denied. + */ +static int hook_mmap_addr(unsigned long addr) +{ + if (addr >= dac_mmap_min_addr) + return 0; + + return check_cap(current_cred(), CAP_SYS_RAWIO, CAP_OPT_NONE); +} + static struct security_hook_list landlock_hooks[] __ro_after_init = { LSM_HOOK_INIT(capable, hook_capable), + LSM_HOOK_INIT(mmap_addr, hook_mmap_addr), }; __init void landlock_add_cap_hooks(void) From 6b8fc8ab1801660b0441e5cc19a14d61f38df921 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 15:52:07 +0100 Subject: [PATCH 0966/2102] landlock: Mediate CAP_SETPCAP for inheritable capabilities MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cap_capset() checks CAP_SETPCAP with cap_capable() (through cap_inh_is_capped()), which skips the capable hook, so a domain denying CAP_SETPCAP cannot prevent adding capabilities outside of the old inheritable and permitted sets to the inheritable set. Without no_new_privs (possible when a task with CAP_SYS_ADMIN enforced the domain), file inheritable capabilities can then grant permitted capabilities on execve(). Add a Landlock capset hook that checks CAP_SETPCAP against the domain under the same condition, as SELinux checks its own setcap permission in this hook. Cc: Günther Noack Cc: Paul Moore Cc: Serge Hallyn Acked-by: Serge Hallyn (AMD) Reviewed-by: Günther Noack Fixes: 97c8386f1d74 ("landlock: Enforce capability restrictions") Link: https://patch.msgid.link/20261118145217.2551053-4-mic@digikod.net Signed-off-by: Mickaël Salaün --- security/landlock/cap.c | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/security/landlock/cap.c b/security/landlock/cap.c index 10e1ca772b9ce4..cdb95b979eaa2c 100644 --- a/security/landlock/cap.c +++ b/security/landlock/cap.c @@ -91,6 +91,36 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns, return check_cap(cred, cap, opts); } +/** + * hook_capset - Restrict inheritable capability changes + * + * @new: New credentials (unused). + * @old: Current credentials. + * @effective: New effective set (unused). + * @inheritable: New inheritable set. + * @permitted: New permitted set (unused). + * + * cap_capset() denies a new inheritable set that is not a subset of the old + * inheritable and permitted sets, unless cap_inh_is_capped() finds CAP_SETPCAP. + * This check uses cap_capable(), which skips hook_capable(). commoncap runs + * first, so such a set reaching this hook means that commoncap granted + * CAP_SETPCAP: check it against the domain. capset(2) discards @new if this + * hook fails, so nothing is committed. + * + * Return: 0 if allowed, -EPERM if CAP_SETPCAP use is denied. + */ +static int hook_capset(struct cred *new, const struct cred *old, + const kernel_cap_t *effective, + const kernel_cap_t *inheritable, + const kernel_cap_t *permitted) +{ + if (cap_issubset(*inheritable, + cap_combine(old->cap_inheritable, old->cap_permitted))) + return 0; + + return check_cap(old, CAP_SETPCAP, CAP_OPT_NONE); +} + /** * hook_mmap_addr - Restrict mappings below dac_mmap_min_addr * @@ -113,6 +143,7 @@ static int hook_mmap_addr(unsigned long addr) static struct security_hook_list landlock_hooks[] __ro_after_init = { LSM_HOOK_INIT(capable, hook_capable), + LSM_HOOK_INIT(capset, hook_capset), LSM_HOOK_INIT(mmap_addr, hook_mmap_addr), }; From a338ad4cc5b95e53f3e49c434235c09732740dbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 15:52:08 +0100 Subject: [PATCH 0967/2102] landlock: Mediate CAP_SYS_ADMIN for the admin memory reserve MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With vm.overcommit_memory=2, __vm_enough_memory() keeps the admin reserve for callers with CAP_SYS_ADMIN, which cap_vm_enough_memory() checks with cap_capable(), so a domain denying CAP_SYS_ADMIN cannot withhold this reserve, meant for an administrator to recover from memory exhaustion. Add a Landlock vm_enough_memory hook that withholds the reserve when the domain denies CAP_SYS_ADMIN. Like commoncap and SELinux, do not audit this check: it runs for every accounted mapping and only selects a limit. Cc: Günther Noack Cc: Paul Moore Cc: Serge Hallyn Acked-by: Serge Hallyn (AMD) Reviewed-by: Günther Noack Fixes: 97c8386f1d74 ("landlock: Enforce capability restrictions") Link: https://patch.msgid.link/20261118145217.2551053-5-mic@digikod.net Signed-off-by: Mickaël Salaün --- security/landlock/cap.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/security/landlock/cap.c b/security/landlock/cap.c index cdb95b979eaa2c..caf514be3df048 100644 --- a/security/landlock/cap.c +++ b/security/landlock/cap.c @@ -141,10 +141,32 @@ static int hook_mmap_addr(unsigned long addr) return check_cap(current_cred(), CAP_SYS_RAWIO, CAP_OPT_NONE); } +/** + * hook_vm_enough_memory - Restrict the admin memory reserve + * + * @mm: Address space being charged (unused). + * @pages: Number of pages being charged (unused). + * + * cap_vm_enough_memory() lets CAP_SYS_ADMIN use the vm.admin_reserve_kbytes + * reserve, but calls cap_capable() directly, which skips hook_capable(). Check + * the same capability against the domain. commoncap runs first, so this only + * sees tasks that commoncap let use the reserve. Like commoncap, do not log + * denials: this only selects a memory limit. + * + * Return: 0 if the domain does not withhold the reserve, -EPERM if + * CAP_SYS_ADMIN use is denied. An error does not fail the allocation by + * itself, but without the reserve, the allocation may fail with -ENOMEM. + */ +static int hook_vm_enough_memory(struct mm_struct *mm, long pages) +{ + return check_cap(current_cred(), CAP_SYS_ADMIN, CAP_OPT_NOAUDIT); +} + static struct security_hook_list landlock_hooks[] __ro_after_init = { LSM_HOOK_INIT(capable, hook_capable), LSM_HOOK_INIT(capset, hook_capset), LSM_HOOK_INIT(mmap_addr, hook_mmap_addr), + LSM_HOOK_INIT(vm_enough_memory, hook_vm_enough_memory), }; __init void landlock_add_cap_hooks(void) From 2c709fccbac59ac66774ef06b4bff56eab9311c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 15:52:09 +0100 Subject: [PATCH 0968/2102] selftests/landlock: Test capability checks outside the capable hook MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Test the commoncap checks that the previous commits make Landlock restrict: mapping below vm.mmap_min_addr (CAP_SYS_RAWIO) and adding inheritable capabilities (CAP_SETPCAP). Each test checks that the operation needs the capability, then runs it with the capability in four variants: unsandboxed, denied, allowed and unhandled. The mmap_addr tests skip if the architecture rejects the low page before the hook (e.g. 32-bit ARM). Audit tests check that these denials are logged, and that the admin reserve check and allowed uses are not. The admin reserve has no functional test because it depends on vm.overcommit_memory=2, a system-wide setting. Add CAP_SETPCAP and CAP_SYS_RAWIO to the capabilities that the tests may raise. Without the mmap_addr and capset fixes, their denied variants and the denial audit test fail. Cc: Günther Noack Cc: Paul Moore Cc: Serge Hallyn Acked-by: Serge Hallyn (AMD) Link: https://patch.msgid.link/20261118145217.2551053-6-mic@digikod.net Signed-off-by: Mickaël Salaün --- tools/testing/selftests/landlock/cap_test.c | 328 ++++++++++++++++++++ tools/testing/selftests/landlock/common.h | 4 +- 2 files changed, 331 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/landlock/cap_test.c b/tools/testing/selftests/landlock/cap_test.c index 3d7fd02e21ed9f..7c58ece1c6f039 100644 --- a/tools/testing/selftests/landlock/cap_test.c +++ b/tools/testing/selftests/landlock/cap_test.c @@ -12,7 +12,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -738,6 +740,247 @@ TEST(cap_target_userns_independent) EXPECT_EQ(0, close(target_userns_fd)); } +/* + * Capability checks that commoncap makes from hooks other than the capable + * hook. Each test first checks that the operation needs the capability, then + * checks it with the capability effective. Variants cover an unsandboxed + * baseline, a domain that denies the capability, a domain that allows it, and a + * domain that does not handle capabilities. + */ +/* clang-format off */ +FIXTURE(cap_other_hooks) {}; +/* clang-format on */ + +FIXTURE_VARIANT(cap_other_hooks) +{ + const bool is_sandboxed; + const bool handle_caps; + const bool is_allowed; +}; + +/* clang-format off */ +FIXTURE_VARIANT_ADD(cap_other_hooks, unsandboxed) { + .is_sandboxed = false, + .handle_caps = false, + .is_allowed = true, +}; +/* clang-format on */ + +/* clang-format off */ +FIXTURE_VARIANT_ADD(cap_other_hooks, denied) { + .is_sandboxed = true, + .handle_caps = true, + .is_allowed = false, +}; +/* clang-format on */ + +/* clang-format off */ +FIXTURE_VARIANT_ADD(cap_other_hooks, allowed) { + .is_sandboxed = true, + .handle_caps = true, + .is_allowed = true, +}; +/* clang-format on */ + +/* clang-format off */ +FIXTURE_VARIANT_ADD(cap_other_hooks, unhandled) { + .is_sandboxed = true, + .handle_caps = false, + .is_allowed = true, +}; +/* clang-format on */ + +FIXTURE_SETUP(cap_other_hooks) +{ + disable_caps(_metadata); +} + +FIXTURE_TEARDOWN(cap_other_hooks) +{ +} + +/* + * Creates a ruleset that handles capabilities and allows @cap if @allow_cap, + * or, if !@handle_caps, a ruleset that only handles a filesystem access right. + * Returns the ruleset FD, or -1 with errno set. + */ +static int create_variant_ruleset(const bool handle_caps, const bool allow_cap, + const int cap) +{ + const struct landlock_ruleset_attr fs_attr = { + .handled_access_fs = LANDLOCK_ACCESS_FS_READ_FILE, + }; + int ruleset_fd, err; + + if (!handle_caps) + return landlock_create_ruleset(&fs_attr, sizeof(fs_attr), 0); + + ruleset_fd = create_cap_ruleset(); + if (ruleset_fd < 0 || !allow_cap) + return ruleset_fd; + + if (add_cap_rule(ruleset_fd, cap)) { + err = errno; + close(ruleset_fd); + errno = err; + return -1; + } + return ruleset_fd; +} + +static void +enforce_cap_variant(struct __test_metadata *const _metadata, + const FIXTURE_VARIANT(cap_other_hooks) *const variant, + const int cap) +{ + int ruleset_fd; + + if (!variant->is_sandboxed) + return; + + ruleset_fd = create_variant_ruleset(variant->handle_caps, + variant->is_allowed, cap); + ASSERT_LE(0, ruleset_fd); + enforce_ruleset(_metadata, ruleset_fd); + EXPECT_EQ(0, close(ruleset_fd)); +} + +static unsigned long read_sysctl(struct __test_metadata *const _metadata, + const char *const path) +{ + char buf[32]; + ssize_t len; + int fd; + + fd = open(path, O_RDONLY | O_CLOEXEC); + ASSERT_LE(0, fd) + { + TH_LOG("Failed to open %s: %s", path, strerror(errno)); + } + len = read(fd, buf, sizeof(buf) - 1); + ASSERT_LT(0, len); + EXPECT_EQ(0, close(fd)); + + buf[len] = '\0'; + return strtoul(buf, NULL, 10); +} + +/* + * Returns the last page below the vm.mmap_min_addr sysctl, or MAP_FAILED if + * there is none or if the architecture rejects it before the mmap_addr hook + * (e.g. below FIRST_USER_ADDRESS on 32-bit ARM). The caller must not have + * CAP_SYS_RAWIO in its effective set. + */ +static void *get_low_page(struct __test_metadata *const _metadata) +{ + const size_t page_size = sysconf(_SC_PAGESIZE); + unsigned long min_addr; + void *addr, *ret; + + min_addr = read_sysctl(_metadata, "/proc/sys/vm/mmap_min_addr"); + if (!min_addr) + return MAP_FAILED; + + addr = (void *)((min_addr - 1) & ~(page_size - 1)); + ret = mmap(addr, page_size, PROT_READ, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + ASSERT_EQ(MAP_FAILED, ret); + if (errno == EINVAL) + return MAP_FAILED; + + ASSERT_EQ(EPERM, errno); + return addr; +} + +/* + * cap_mmap_addr() requires CAP_SYS_RAWIO to map below the vm.mmap_min_addr + * sysctl (dac_mmap_min_addr). + */ +TEST_F(cap_other_hooks, mmap_min_addr) +{ + const size_t page_size = sysconf(_SC_PAGESIZE); + void *low_page, *addr; + + low_page = get_low_page(_metadata); + if (low_page == MAP_FAILED) + SKIP(return, "Cannot map below vm.mmap_min_addr"); + + enforce_cap_variant(_metadata, variant, CAP_SYS_RAWIO); + + addr = mmap(low_page, page_size, PROT_READ, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + ASSERT_EQ(MAP_FAILED, addr); + EXPECT_EQ(EPERM, errno); + + set_cap(_metadata, CAP_SYS_RAWIO); + addr = mmap(low_page, page_size, PROT_READ, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + if (variant->is_allowed) { + ASSERT_EQ(low_page, addr) + { + TH_LOG("Failed to map below vm.mmap_min_addr: %s", + strerror(errno)); + } + } else { + ASSERT_EQ(MAP_FAILED, addr); + EXPECT_EQ(EPERM, errno); + } + clear_cap(_metadata, CAP_SYS_RAWIO); +} + +static int add_inheritable_cap(const cap_value_t cap) +{ + cap_t cap_p; + int ret, err; + + cap_p = cap_get_proc(); + if (!cap_p) + return -1; + + ret = cap_set_flag(cap_p, CAP_INHERITABLE, 1, &cap, CAP_SET); + if (!ret) + ret = cap_set_proc(cap_p); + err = errno; + cap_free(cap_p); + errno = err; + return ret; +} + +/* + * cap_capset() requires CAP_SETPCAP to add an inheritable capability that is + * not in the permitted set. CAP_NET_RAW is in the bounding set, but + * disable_caps() does not put it in the permitted set. + */ +TEST_F(cap_other_hooks, capset_inheritable) +{ + enforce_cap_variant(_metadata, variant, CAP_SETPCAP); + + ASSERT_EQ(-1, add_inheritable_cap(CAP_NET_RAW)); + EXPECT_EQ(EPERM, errno); + + set_cap(_metadata, CAP_SETPCAP); + if (variant->is_allowed) { + EXPECT_EQ(0, add_inheritable_cap(CAP_NET_RAW)) + { + TH_LOG("Failed to raise CAP_NET_RAW: %s", + strerror(errno)); + } + } else { + ASSERT_EQ(-1, add_inheritable_cap(CAP_NET_RAW)); + EXPECT_EQ(EPERM, errno); + } + clear_cap(_metadata, CAP_SETPCAP); +} + +/* + * cap_vm_enough_memory() lets CAP_SYS_ADMIN use the vm.admin_reserve_kbytes + * reserve, but only with vm.overcommit_memory=2. The Landlock check of this + * reserve has no functional test: it would have to change these system-wide + * settings and set a tight commit limit, which could make allocations of other + * processes fail and would race with them. cap_audit.other_hooks checks that + * this check is not logged. + */ + /* Audit tests */ static int matches_log_cap(int audit_fd, int cap_number) @@ -828,6 +1071,91 @@ TEST_F(cap_audit, denied) EXPECT_EQ(0, records.domain); } +/* + * Denials in the capset and mmap_addr paths are audited like capable hook + * denials. The vm_enough_memory hook only withholds the admin reserve, with + * CAP_OPT_NOAUDIT, so an accounted mapping made with CAP_SYS_ADMIN effective + * leaves no record. + */ +TEST_F(cap_audit, other_hooks) +{ + const size_t page_size = sysconf(_SC_PAGESIZE); + struct audit_records records = {}; + void *low_page, *addr; + int ruleset_fd; + __u64 domain_id; + + low_page = get_low_page(_metadata); + ruleset_fd = create_cap_ruleset(); + ASSERT_LE(0, ruleset_fd); + /* Allow CAP_AUDIT_CONTROL for child-side audit cleanup. */ + ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL)); + enforce_ruleset(_metadata, ruleset_fd); + EXPECT_EQ(0, close(ruleset_fd)); + + set_cap(_metadata, CAP_SETPCAP); + ASSERT_EQ(-1, add_inheritable_cap(CAP_NET_RAW)); + EXPECT_EQ(EPERM, errno); + clear_cap(_metadata, CAP_SETPCAP); + EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SETPCAP)); + EXPECT_EQ(0, matches_log_domain_allocated(self->audit_fd, getpid(), + &domain_id)); + + if (low_page != MAP_FAILED) { + set_cap(_metadata, CAP_SYS_RAWIO); + addr = mmap(low_page, page_size, PROT_READ, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + ASSERT_EQ(MAP_FAILED, addr); + EXPECT_EQ(EPERM, errno); + clear_cap(_metadata, CAP_SYS_RAWIO); + EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SYS_RAWIO)); + } + + set_cap(_metadata, CAP_SYS_ADMIN); + addr = mmap(NULL, page_size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + ASSERT_NE(MAP_FAILED, addr); + clear_cap(_metadata, CAP_SYS_ADMIN); + + ASSERT_EQ(0, audit_count_records(self->audit_fd, &records)); + EXPECT_EQ(0, records.access); + EXPECT_EQ(0, records.domain); +} + +/* Allowed capability uses in the capset and mmap_addr paths. */ +TEST_F(cap_audit, other_hooks_allowed) +{ + const size_t page_size = sysconf(_SC_PAGESIZE); + struct audit_records records = {}; + void *low_page, *addr; + int ruleset_fd; + + low_page = get_low_page(_metadata); + ruleset_fd = create_cap_ruleset(); + ASSERT_LE(0, ruleset_fd); + ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_SETPCAP)); + ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_SYS_RAWIO)); + /* Allow CAP_AUDIT_CONTROL for child-side audit cleanup. */ + ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL)); + enforce_ruleset(_metadata, ruleset_fd); + EXPECT_EQ(0, close(ruleset_fd)); + + set_cap(_metadata, CAP_SETPCAP); + EXPECT_EQ(0, add_inheritable_cap(CAP_NET_RAW)); + clear_cap(_metadata, CAP_SETPCAP); + + if (low_page != MAP_FAILED) { + set_cap(_metadata, CAP_SYS_RAWIO); + addr = mmap(low_page, page_size, PROT_READ, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + ASSERT_EQ(low_page, addr); + clear_cap(_metadata, CAP_SYS_RAWIO); + } + + ASSERT_EQ(0, audit_count_records(self->audit_fd, &records)); + EXPECT_EQ(0, records.access); +} + TEST_F(cap_audit, allowed) { struct audit_records records = {}; diff --git a/tools/testing/selftests/landlock/common.h b/tools/testing/selftests/landlock/common.h index e29406900c04a6..a6fdfb422fad57 100644 --- a/tools/testing/selftests/landlock/common.h +++ b/tools/testing/selftests/landlock/common.h @@ -36,7 +36,7 @@ static const char bin_wait_pipe_sandbox[] = "./wait-pipe-sandbox"; static void _init_caps(struct __test_metadata *const _metadata, bool drop_all) { cap_t cap_p; - /* Only these three capabilities are useful for the tests. */ + /* Only these capabilities are useful for the tests. */ const cap_value_t caps[] = { /* clang-format off */ CAP_AUDIT_CONTROL, @@ -44,9 +44,11 @@ static void _init_caps(struct __test_metadata *const _metadata, bool drop_all) CAP_MKNOD, CAP_NET_ADMIN, CAP_NET_BIND_SERVICE, + CAP_SETPCAP, CAP_SETUID, CAP_SYS_ADMIN, CAP_SYS_CHROOT, + CAP_SYS_RAWIO, /* clang-format on */ }; const unsigned int noroot = SECBIT_NOROOT | SECBIT_NOROOT_LOCKED; From c0aa8acdd94e9ec0ea2fefe8fa5b31c03c271c4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 15:52:10 +0100 Subject: [PATCH 0969/2102] landlock: Fix capability restriction documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Some documented claims about LANDLOCK_PERMISSION_CAPABILITY_USE do not hold for every capability check. Remove them instead of listing their exceptions, and stop calling this permission a hook. Cc: Günther Noack Cc: Paul Moore Cc: Serge Hallyn Acked-by: Serge Hallyn (AMD) Reviewed-by: Günther Noack Fixes: 97c8386f1d74 ("landlock: Enforce capability restrictions") Link: https://patch.msgid.link/20261118145217.2551053-7-mic@digikod.net Signed-off-by: Mickaël Salaün --- Documentation/security/landlock.rst | 8 ++++---- Documentation/userspace-api/landlock.rst | 8 ++++---- include/uapi/linux/landlock.h | 7 +++---- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/Documentation/security/landlock.rst b/Documentation/security/landlock.rst index d81f1c2cd23683..98c2e7139e8d48 100644 --- a/Documentation/security/landlock.rst +++ b/Documentation/security/landlock.rst @@ -8,7 +8,7 @@ Landlock LSM: kernel documentation ================================== :Author: Mickaël Salaün -:Date: October 2026 +:Date: November 2026 Landlock's goal is to create scoped access-control (i.e. sandboxing). To harden a whole system, this feature should be available to any process, @@ -359,9 +359,9 @@ framework in ``log.c``, compiled under ``CONFIG_SECURITY_LANDLOCK_LOG`` (automatically selected by ``CONFIG_AUDIT`` or ``CONFIG_TRACEPOINTS``). Audit records respect audit configuration, the domain's Landlock log -flags, and ``LANDLOCK_LOG_DISABLED``. Tracepoints fire unconditionally, -independent of these settings. The denial counter (``num_denials``) is -always incremented regardless of logging configuration. +flags, and ``LANDLOCK_LOG_DISABLED``. Tracepoints fire independently of +these settings. The denial counter (``num_denials``) is +incremented regardless of logging configuration. Each denial tracepoint carries a ``logged`` field reporting the audit-logging verdict: whether the denial would be written to the audit diff --git a/Documentation/userspace-api/landlock.rst b/Documentation/userspace-api/landlock.rst index 24cfc2c23cb2c4..7cc5fde482623e 100644 --- a/Documentation/userspace-api/landlock.rst +++ b/Documentation/userspace-api/landlock.rst @@ -8,7 +8,7 @@ Landlock: unprivileged access control ===================================== :Author: Mickaël Salaün -:Date: October 2026 +:Date: November 2026 The goal of Landlock is to enable restriction of ambient rights (e.g. global filesystem or network access) for a set of processes. Because Landlock @@ -532,7 +532,7 @@ acquisition via :manpage:`open_tree(2)` / :manpage:`fsmount(2)`. Namespaces the process is already a member of when the domain is enforced are implicitly allowed (the process could not continue running otherwise); rules describe which new namespace types the process may acquire. -``LANDLOCK_PERMISSION_CAPABILITY_USE`` gates every exercise of a capability +``LANDLOCK_PERMISSION_CAPABILITY_USE`` gates the exercise of capabilities after the domain is enforced, regardless of how the capability was obtained (inherited credentials, ``CLONE_NEWUSER`` grant, ``setuid``/file-cap-bearing :manpage:`execve(2)`, etc.). Configuring @@ -641,9 +641,9 @@ after a domain is enforced through user namespace entry or :manpage:`capset(2)`; privileged sandboxes that did not set ``PR_SET_NO_NEW_PRIVS`` may also gain capabilities through :manpage:`execve(2)` of binaries with file capabilities. In all cases, :manpage:`capget(2)` will report the credential's capability sets, -but any denied capability will fail with ``EPERM`` when exercised. Do not rely +but any denied capability will fail when exercised. Do not rely on :manpage:`capget(2)` to determine whether the policy permits a given -capability; only the actual operation will return ``EPERM`` upon denial. +capability. Truncating files ---------------- diff --git a/include/uapi/linux/landlock.h b/include/uapi/linux/landlock.h index 7e38b9d1bf1279..8ce0406ba54360 100644 --- a/include/uapi/linux/landlock.h +++ b/include/uapi/linux/landlock.h @@ -623,10 +623,9 @@ struct landlock_capability_attr { * - %LANDLOCK_PERMISSION_CAPABILITY_USE: Restrict the use of specific Linux * capabilities. A process in a Landlock domain that handles this permission * is denied from exercising capabilities that are not explicitly allowed by a - * %LANDLOCK_RULE_CAPABILITY rule. This hook is purely restrictive: it can - * deny capabilities that the kernel would otherwise grant, but it can never - * grant capabilities that the kernel already denied. Support added in - * Landlock ABI version 12. + * %LANDLOCK_RULE_CAPABILITY rule. Landlock only reduces the capabilities + * that processes can use: it does not let them use capabilities that they + * would not have without Landlock. Support added in Landlock ABI version 12. */ #define LANDLOCK_PERMISSION_NAMESPACE_USE (1ULL << 0) #define LANDLOCK_PERMISSION_CAPABILITY_USE (1ULL << 1) From 2ff5a29db0f542226d5bd029459de9703fc2a2ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 15:54:28 +0100 Subject: [PATCH 0970/2102] capabilities: Check PR_SET_SECUREBITS with ns_capable() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR_SET_SECUREBITS checks CAP_SETPCAP with cap_capable(), which skips the LSM capable hooks, so a task can change privileged securebits despite an LSM denial. Use ns_capable() instead, as PR_CAPBSET_DROP already does. Move the check to a helper that only requires CAP_SETPCAP when needed, so that changes limited to the unprivileged securebits still do not reach the LSMs or set PF_SUPERPRIV. Cc: Christian Brauner Cc: Günther Noack Cc: James Morris Cc: John Johansen Cc: KP Singh Cc: Matt Bobrowski Cc: Paul Moore Cc: Serge Hallyn Cc: Stephen Smalley Cc: stable@vger.kernel.org Reviewed-by: Serge Hallyn (AMD) Fixes: 3898b1b4ebff ("capabilities: implement per-process securebits") Link: https://patch.msgid.link/20261118145431.2551578-2-mic@digikod.net Signed-off-by: Mickaël Salaün --- security/commoncap.c | 45 ++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/security/commoncap.c b/security/commoncap.c index d47ab30223435b..9794a594bdd925 100644 --- a/security/commoncap.c +++ b/security/commoncap.c @@ -1283,6 +1283,26 @@ static int cap_prctl_drop(unsigned long cap) return commit_creds(new); } +/* + * Doing anything with securebits requires privilege (go read about the + * "sendmail capabilities bug"), except for unprivileged bits. Indeed, the + * SECURE_ALL_UNPRIVILEGED bits are not restrictions enforced by the kernel but + * by user space on itself. Only checking CAP_SETPCAP when it is needed keeps + * LSMs from seeing (and logging) a capability check for unprivileged changes. + */ +static bool securebits_need_setpcap(unsigned long old, unsigned long new) +{ + const unsigned long unpriv_and_locks = SECURE_ALL_UNPRIVILEGED | + SECURE_ALL_UNPRIVILEGED << 1; + const unsigned long changed = old ^ new; + + /* For legacy reasons, a non-change requires privilege. */ + if (!changed) + return true; + + return changed & ~unpriv_and_locks; +} + /** * cap_task_prctl - Implement process control functions for this security module * @option: The process control function requested @@ -1346,28 +1366,9 @@ int cap_task_prctl(int option, unsigned long arg2, unsigned long arg3, /* cannot change a locked bit */ return -EPERM; - /* - * Doing anything requires privilege (go read about the - * "sendmail capabilities bug"), except for unprivileged bits. - * Indeed, the SECURE_ALL_UNPRIVILEGED bits are not - * restrictions enforced by the kernel but by user space on - * itself. - */ - if (cap_capable(current_cred(), current_cred()->user_ns, - CAP_SETPCAP, CAP_OPT_NONE) != 0) { - const unsigned long unpriv_and_locks = - SECURE_ALL_UNPRIVILEGED | - SECURE_ALL_UNPRIVILEGED << 1; - const unsigned long changed = old->securebits ^ arg2; - - /* For legacy reason, denies non-change. */ - if (!changed) - return -EPERM; - - /* Denies privileged changes. */ - if (changed & ~unpriv_and_locks) - return -EPERM; - } + if (securebits_need_setpcap(old->securebits, arg2) && + !ns_capable(current_user_ns(), CAP_SETPCAP)) + return -EPERM; new = prepare_creds(); if (!new) From 102143984d542ef7f3bff6bcfd886d3940e17ca7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 15:54:29 +0100 Subject: [PATCH 0971/2102] selftests/landlock: Test PR_SET_SECUREBITS mediation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Test that Landlock denies and logs a privileged PR_SET_SECUREBITS change, now that the previous commit routes its CAP_SETPCAP check through the capable hooks, and that an unprivileged change still succeeds. The domain deallocation record must then report exactly one denial, which proves that the unprivileged change was not denied, without relying on a no-record timeout. The check-exec selftests already cover commoncap's securebits semantics. Without the previous commit, this test fails. Cc: Christian Brauner Cc: Günther Noack Cc: Paul Moore Cc: Serge Hallyn Link: https://patch.msgid.link/20261118145431.2551578-3-mic@digikod.net Signed-off-by: Mickaël Salaün --- tools/testing/selftests/landlock/cap_test.c | 69 +++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/tools/testing/selftests/landlock/cap_test.c b/tools/testing/selftests/landlock/cap_test.c index 7c58ece1c6f039..35a419c46764d4 100644 --- a/tools/testing/selftests/landlock/cap_test.c +++ b/tools/testing/selftests/landlock/cap_test.c @@ -1071,6 +1071,75 @@ TEST_F(cap_audit, denied) EXPECT_EQ(0, records.domain); } +/* + * A privileged denial allocates the domain ID. The following unprivileged-only + * change must not create a hidden Landlock denial, so the domain's deallocation + * record must report exactly one denial. + */ +TEST_F(cap_audit, securebits) +{ + const unsigned long unpriv = SECBIT_EXEC_RESTRICT_FILE | + SECBIT_EXEC_RESTRICT_FILE_LOCKED; + __u64 *domain_id, deallocated_dom = 0; + unsigned long bits; + int err, ruleset_fd, status; + pid_t child; + + domain_id = mmap(NULL, sizeof(*domain_id), PROT_READ | PROT_WRITE, + MAP_SHARED | MAP_ANONYMOUS, -1, 0); + ASSERT_NE(MAP_FAILED, domain_id); + *domain_id = 0; + + ruleset_fd = create_cap_ruleset(); + ASSERT_LE(0, ruleset_fd); + /* Allow the child to replace the audit filter before exiting. */ + ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL)); + + child = fork(); + ASSERT_LE(0, child); + if (child == 0) { + enforce_ruleset(_metadata, ruleset_fd); + EXPECT_EQ(0, close(ruleset_fd)); + + set_cap(_metadata, CAP_SETPCAP); + bits = prctl(PR_GET_SECUREBITS); + ASSERT_EQ(-1, prctl(PR_SET_SECUREBITS, + bits | SECBIT_NO_CAP_AMBIENT_RAISE)); + EXPECT_EQ(EPERM, errno); + + EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SETPCAP)); + EXPECT_EQ(0, matches_log_domain_allocated(self->audit_fd, + getpid(), domain_id)); + + EXPECT_EQ(0, prctl(PR_SET_SECUREBITS, bits | unpriv)); + clear_cap(_metadata, CAP_SETPCAP); + + /* Receive the asynchronous domain deallocation record. */ + set_cap(_metadata, CAP_AUDIT_CONTROL); + EXPECT_EQ(0, audit_filter_drop(self->audit_fd, AUDIT_ADD_RULE)); + EXPECT_EQ(0, + audit_filter_exe(self->audit_fd, &self->audit_filter, + AUDIT_DEL_RULE)); + clear_cap(_metadata, CAP_AUDIT_CONTROL); + + _exit(_metadata->exit_code); + return; + } + + ASSERT_EQ(child, waitpid(child, &status, 0)); + if (WIFSIGNALED(status) || !WIFEXITED(status) || + WEXITSTATUS(status) != EXIT_SUCCESS) + _metadata->exit_code = KSFT_FAIL; + + EXPECT_NE(0, *domain_id); + err = matches_log_domain_deallocated(self->audit_fd, 1, *domain_id, + &deallocated_dom); + EXPECT_EQ(0, err); + EXPECT_EQ(*domain_id, deallocated_dom); + EXPECT_EQ(0, munmap(domain_id, sizeof(*domain_id))); + EXPECT_EQ(0, close(ruleset_fd)); +} + /* * Denials in the capset and mmap_addr paths are audited like capable hook * denials. The vm_enough_memory hook only withholds the admin reserve, with From a873f3c213a6fc09aaa2bb389fba49f9bbe9d589 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 17:32:49 +0100 Subject: [PATCH 0972/2102] landlock: Distinguish namespace creation and entry denials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Landlock reports denied namespace creation and entry with the same internal request type. Before commit 08471914d6bb ("ns: allocate the namespace id before the namespace_init hook"), denied creation carried ID zero and could be distinguished from entry by ID alone. That commit moved ID allocation before namespace_init(), so creation now carries the ID of an unreachable new namespace while entry carries the existing target ID. Namespace IDs are object context, not operation discriminators. Split the request type into creation and entry. Keep the two namespace values together before capability; this renumbers the unreleased capability request in raw and typed trace context. Report namespace_op=create or namespace_op=enter immediately after blockers in namespace audit records and trace event text. Placing the operation before namespace_type and namespace_id lets consumers establish the semantics before interpreting the following namespace context, especially whether namespace_id is the creation-time value or identifies an existing entry target. Keep namespace.use as the policy blocker: the new value only describes the semantic hook context and does not add a policy control. Cc: Günther Noack Fixes: 15dd86021b57 ("landlock: Enforce namespace use restrictions") Link: https://patch.msgid.link/20261118163254.2554413-2-mic@digikod.net Signed-off-by: Mickaël Salaün --- include/trace/events/landlock.h | 25 ++++++++++++++-------- security/landlock/audit.c | 10 +++++++-- security/landlock/log.c | 6 ++++-- security/landlock/log.h | 3 ++- security/landlock/ns.c | 10 +++++---- security/landlock/trace.c | 3 ++- tools/testing/selftests/landlock/ns_test.c | 18 +++++++++++----- tools/testing/selftests/landlock/trace.h | 1 + 8 files changed, 52 insertions(+), 24 deletions(-) diff --git a/include/trace/events/landlock.h b/include/trace/events/landlock.h index b6fdc6e2eef871..9b3e24a613d8d1 100644 --- a/include/trace/events/landlock.h +++ b/include/trace/events/landlock.h @@ -36,7 +36,8 @@ static_assert(sizeof(access_mask_t) <= sizeof(u64)); TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY); TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_FS_ACCESS); TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_NET_ACCESS); -TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_NAMESPACE); +TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_NAMESPACE_CREATE); +TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_NAMESPACE_ENTER); TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_CAPABILITY); #ifdef CREATE_TRACE_POINTS @@ -990,7 +991,8 @@ TRACE_EVENT(landlock_deny_access_net, * @namespace_id: Namespace ID, not directly visible from user space when * creation was denied. * - * Emitted when a Landlock domain denies namespace use. + * Emitted when a Landlock domain denies namespace creation or entry. The + * namespace_op field distinguishes these operations. */ TRACE_EVENT(landlock_deny_permission_namespace, @@ -1021,13 +1023,18 @@ TRACE_EVENT(landlock_deny_permission_namespace, __entry->namespace_id = namespace_id; ), - TP_printk("domain=%llx same_exec=%d logged=%d blockers=%s namespace_type=0x%x namespace_id=%llu", - __entry->domain_id, __entry->same_exec, __entry->logged, - __entry->blockers_type == LANDLOCK_REQUEST_NAMESPACE ? - __print_flags(__entry->blockers_access, "|", - _LANDLOCK_PERMISSION_BLOCKER_NAMES) : - "unknown", - __entry->namespace_type, __entry->namespace_id) + TP_printk("domain=%llx same_exec=%d logged=%d blockers=%s namespace_op=%s namespace_type=0x%x namespace_id=%llu", + __entry->domain_id, __entry->same_exec, __entry->logged, + (__entry->blockers_type == LANDLOCK_REQUEST_NAMESPACE_CREATE || + __entry->blockers_type == LANDLOCK_REQUEST_NAMESPACE_ENTER) ? + __print_flags(__entry->blockers_access, "|", + _LANDLOCK_PERMISSION_BLOCKER_NAMES) : + "unknown", + __entry->blockers_type == LANDLOCK_REQUEST_NAMESPACE_CREATE ? + "create" : + __entry->blockers_type == LANDLOCK_REQUEST_NAMESPACE_ENTER ? + "enter" : "unknown", + __entry->namespace_type, __entry->namespace_id) ); /** diff --git a/security/landlock/audit.c b/security/landlock/audit.c index be49ef47b4eacc..6d9e54f5deedfb 100644 --- a/security/landlock/audit.c +++ b/security/landlock/audit.c @@ -80,7 +80,8 @@ get_blocker(const enum landlock_request_type type, WARN_ON_ONCE(access_bit != -1); return scope_strings[BIT_INDEX(LANDLOCK_SCOPE_SIGNAL)]; - case LANDLOCK_REQUEST_NAMESPACE: + case LANDLOCK_REQUEST_NAMESPACE_CREATE: + case LANDLOCK_REQUEST_NAMESPACE_ENTER: case LANDLOCK_REQUEST_CAPABILITY: if (WARN_ON_ONCE(access_bit >= ARRAY_SIZE(permission_strings))) return "unknown"; @@ -115,7 +116,8 @@ blocker_prefix(const enum landlock_request_type type) case LANDLOCK_REQUEST_SCOPE_SIGNAL: return "scope."; - case LANDLOCK_REQUEST_NAMESPACE: + case LANDLOCK_REQUEST_NAMESPACE_CREATE: + case LANDLOCK_REQUEST_NAMESPACE_ENTER: return _LANDLOCK_PERMISSION_NAMESPACE_NAME "."; case LANDLOCK_REQUEST_CAPABILITY: @@ -212,6 +214,10 @@ void landlock_audit_denial(const struct landlock_request *const request, audit_log_format(ab, "domain=%llx blockers=", youngest_denied->id); log_blockers(ab, request->type, missing); + if (request->type == LANDLOCK_REQUEST_NAMESPACE_CREATE) + audit_log_format(ab, " namespace_op=create"); + else if (request->type == LANDLOCK_REQUEST_NAMESPACE_ENTER) + audit_log_format(ab, " namespace_op=enter"); audit_log_lsm_data(ab, &request->audit); audit_log_end(ab); diff --git a/security/landlock/log.c b/security/landlock/log.c index 43efbb95725c37..c132b343f0ee06 100644 --- a/security/landlock/log.c +++ b/security/landlock/log.c @@ -388,7 +388,8 @@ static bool is_valid_request(const struct landlock_request *const request) return false; switch (request->type) { - case LANDLOCK_REQUEST_NAMESPACE: + case LANDLOCK_REQUEST_NAMESPACE_CREATE: + case LANDLOCK_REQUEST_NAMESPACE_ENTER: if (WARN_ON_ONCE(request->permission != LANDLOCK_PERMISSION_NAMESPACE_USE) || WARN_ON_ONCE(request->audit.type != LSM_AUDIT_DATA_NS)) @@ -485,7 +486,8 @@ is_denial_quieted(const struct landlock_request *const request, case LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET: return !!(youngest_denied->quiet_access.scope & LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET); - case LANDLOCK_REQUEST_NAMESPACE: + case LANDLOCK_REQUEST_NAMESPACE_CREATE: + case LANDLOCK_REQUEST_NAMESPACE_ENTER: return !!(youngest_denied->quiet_permission.ns_types & landlock_ns_type_to_bit(request->audit.u.ns.ns_type)); case LANDLOCK_REQUEST_CAPABILITY: diff --git a/security/landlock/log.h b/security/landlock/log.h index 596feeeb7aa61a..641a2c3c78ed04 100644 --- a/security/landlock/log.h +++ b/security/landlock/log.h @@ -25,7 +25,8 @@ enum landlock_request_type { LANDLOCK_REQUEST_NET_ACCESS, LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET, LANDLOCK_REQUEST_SCOPE_SIGNAL, - LANDLOCK_REQUEST_NAMESPACE, + LANDLOCK_REQUEST_NAMESPACE_CREATE, + LANDLOCK_REQUEST_NAMESPACE_ENTER, LANDLOCK_REQUEST_CAPABILITY, }; diff --git a/security/landlock/ns.c b/security/landlock/ns.c index 06d9784746fe9e..3d443599b16f42 100644 --- a/security/landlock/ns.c +++ b/security/landlock/ns.c @@ -90,6 +90,7 @@ static const struct access_masks ns_permission = { * check_ns_type - Check namespace use permission * * @ns: The namespace being allocated or installed. + * @request_type: Namespace operation reported on denial. * * Shared check for namespace_init (creation via clone(2), unshare(2), * open_tree(2), or fsmount(2)) and namespace_install (use via setns(2)): denies @@ -99,7 +100,8 @@ static const struct access_masks ns_permission = { * * Return: 0 if allowed, -EPERM if denied. */ -static int check_ns_type(struct ns_common *const ns) +static int check_ns_type(struct ns_common *const ns, + const enum landlock_request_type request_type) { const struct landlock_cred_security *subject; size_t denied_layer; @@ -117,7 +119,7 @@ static int check_ns_type(struct ns_common *const ns) landlock_log_denial(subject, &(struct landlock_request){ - .type = LANDLOCK_REQUEST_NAMESPACE, + .type = request_type, .audit.type = LSM_AUDIT_DATA_NS, .permission = LANDLOCK_PERMISSION_NAMESPACE_USE, @@ -130,13 +132,13 @@ static int check_ns_type(struct ns_common *const ns) static int hook_namespace_init(struct ns_common *const ns) { - return check_ns_type(ns); + return check_ns_type(ns, LANDLOCK_REQUEST_NAMESPACE_CREATE); } static int hook_namespace_install(const struct nsset *const nsset, struct ns_common *const ns) { - return check_ns_type(ns); + return check_ns_type(ns, LANDLOCK_REQUEST_NAMESPACE_ENTER); } static struct security_hook_list landlock_hooks[] __ro_after_init = { diff --git a/security/landlock/trace.c b/security/landlock/trace.c index 995c6b948e16eb..00cb497eaffbfc 100644 --- a/security/landlock/trace.c +++ b/security/landlock/trace.c @@ -81,7 +81,8 @@ void landlock_trace_denial( const access_mask_t missing, const bool same_exec, const bool logged) { switch (request->type) { - case LANDLOCK_REQUEST_NAMESPACE: + case LANDLOCK_REQUEST_NAMESPACE_CREATE: + case LANDLOCK_REQUEST_NAMESPACE_ENTER: if (trace_landlock_deny_permission_namespace_enabled()) { const struct landlock_blockers blockers = { .access = missing, diff --git a/tools/testing/selftests/landlock/ns_test.c b/tools/testing/selftests/landlock/ns_test.c index 8f387fc47e2171..d4a85cbebeaeba 100644 --- a/tools/testing/selftests/landlock/ns_test.c +++ b/tools/testing/selftests/landlock/ns_test.c @@ -1897,11 +1897,14 @@ TEST(setns_inherited_fd) /* Audit tests */ +#define REGEX_LANDLOCK_NS_CREATE \ + REGEX_LANDLOCK_PREFIX " blockers=namespace\\.use namespace_op=create" + static int matches_log_ns_create(int audit_fd, __u64 ns_type) { /* A denied creation logs the ID allocated for the new namespace. */ - static const char log_template[] = REGEX_LANDLOCK_PREFIX - " blockers=namespace\\.use namespace_type=0x%x namespace_id=[1-9][0-9]*$"; + static const char log_template[] = REGEX_LANDLOCK_NS_CREATE + " namespace_type=0x%x namespace_id=[1-9][0-9]*$"; char log_match[sizeof(log_template) + 10]; int log_match_len; @@ -1917,12 +1920,12 @@ static int matches_log_ns_create(int audit_fd, __u64 ns_type) static int matches_log_ns_setns(int audit_fd, __u64 ns_type, __u64 ns_id) { static const char log_template[] = REGEX_LANDLOCK_PREFIX - " blockers=namespace\\.use namespace_type=0x%x namespace_id=%llu$"; + " blockers=namespace\\.use namespace_op=%s namespace_type=0x%x namespace_id=%llu$"; char log_match[sizeof(log_template) + 32]; int log_match_len; log_match_len = snprintf(log_match, sizeof(log_match), log_template, - (unsigned int)ns_type, + "enter", (unsigned int)ns_type, (unsigned long long)ns_id); if (log_match_len >= sizeof(log_match)) return -E2BIG; @@ -1958,7 +1961,7 @@ FIXTURE_TEARDOWN(ns_audit) /* * Verifies that a denied namespace creation produces the expected audit record - * with the namespace.use blocker string and namespace_type. + * with the namespace.use blocker string, namespace type, and create operation. */ TEST_F(ns_audit, create_denied) { @@ -2542,6 +2545,11 @@ static void test_ns_trace_denial(struct __test_metadata *const _metadata, EXPECT_STRNE("0", field); if (use_setns) EXPECT_EQ(expected_ns_id, strtoull(field, NULL, 10)); + ret = tracefs_extract_field(buf, + REGEX_DENY_PERMISSION_NAMESPACE(TRACE_TASK), + "namespace_op", field, sizeof(field)); + ASSERT_EQ(0, ret); + EXPECT_STREQ(use_setns ? "enter" : "create", field); free(buf); } diff --git a/tools/testing/selftests/landlock/trace.h b/tools/testing/selftests/landlock/trace.h index 36e8f16171b0b5..e67f239a85076b 100644 --- a/tools/testing/selftests/landlock/trace.h +++ b/tools/testing/selftests/landlock/trace.h @@ -185,6 +185,7 @@ "same_exec=[01] " \ "logged=[01] " \ "blockers=[a-z_|]* " \ + "namespace_op=\\(create\\|enter\\) " \ "namespace_type=0x[0-9a-f]\\+ " \ "namespace_id=[0-9]\\+$" From 36ff564b8039d65cddc854b8ad7c14851a490616 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 17:32:50 +0100 Subject: [PATCH 0973/2102] landlock: Add capability objects to denial tracing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The capability denial tracepoint identifies the capability number but not the credentials or user namespace against which it was checked. Typed BPF consumers therefore cannot reconstruct the authoritative hook context, especially when a check targets a user namespace other than the caller's current namespace. Carry the exact cred and user_ns used by each commoncap check through check_cap() to the tracepoint's BTF prototype. The capable hook forwards its arguments. Other callers mirror old->user_ns for CAP_SETPCAP, and init_user_ns for CAP_SYS_RAWIO and CAP_SYS_ADMIN. The latter checks protect global hardening and the global admin memory reserve, so nested user-namespace capabilities must not authorize them. Keep these pointers out of TP_STRUCT__entry and TP_printk so the raw ring-buffer layout and textual format remain unchanged. They provide context only and do not participate in Landlock's verdict. Do not carry the capability options. CAP_OPT_NOAUDIT already suppresses the complete denial record, and the remaining option bits do not explain the checked security relationship. Cc: Günther Noack Fixes: 97c8386f1d74 ("landlock: Enforce capability restrictions") Link: https://patch.msgid.link/20261118163254.2554413-3-mic@digikod.net Signed-off-by: Mickaël Salaün --- Documentation/trace/events-landlock.rst | 6 ++-- include/trace/events/landlock.h | 11 ++++-- security/landlock/cap.c | 45 ++++++++++++++++++------- security/landlock/log.h | 9 +++++ security/landlock/trace.c | 9 ++++- 5 files changed, 61 insertions(+), 19 deletions(-) diff --git a/Documentation/trace/events-landlock.rst b/Documentation/trace/events-landlock.rst index dc5f05a17c2ccd..1ddc123df59ea4 100644 --- a/Documentation/trace/events-landlock.rst +++ b/Documentation/trace/events-landlock.rst @@ -303,9 +303,9 @@ event prototypes in `Event reference`_ document their argument layouts. The arguments include both standard kernel objects and Landlock-internal objects: -- Standard kernel objects (``struct task_struct``, ``struct sock``, - ``struct path``, ``struct dentry``) can be used with existing BPF - helpers. +- Standard kernel objects (for example ``struct task_struct``, ``struct cred``, + ``struct user_namespace``, ``struct sock``, ``struct path``, and + ``struct dentry``) can be used with existing BPF helpers. - Landlock-internal objects (``struct landlock_domain``, ``struct landlock_ruleset``, ``struct landlock_rule``, ``struct landlock_hierarchy``) can be read via ``BPF_CORE_READ``. diff --git a/include/trace/events/landlock.h b/include/trace/events/landlock.h index 9b3e24a613d8d1..09e90e4a9cd7bd 100644 --- a/include/trace/events/landlock.h +++ b/include/trace/events/landlock.h @@ -21,6 +21,7 @@ #include enum landlock_request_type; +struct cred; struct dentry; struct landlock_blockers; struct landlock_domain; @@ -30,6 +31,7 @@ struct landlock_ruleset; struct path; struct sock; struct task_struct; +struct user_namespace; static_assert(sizeof(access_mask_t) <= sizeof(u64)); @@ -1046,6 +1048,9 @@ TRACE_EVENT(landlock_deny_permission_namespace, * @logged: Whether this denial was selected for audit logging. * @blockers: Request type and final missing permission subset (never NULL). * @capability: CAP_* number that was denied. + * @cred: Credentials used by commoncap's capability check (never NULL). + * @user_ns: Target user namespace used by commoncap's capability check (never + * NULL). * * Emitted when a Landlock domain denies capability use, except for checks * made with CAP_OPT_NOAUDIT, which are denied without emitting this event. @@ -1054,9 +1059,11 @@ TRACE_EVENT(landlock_deny_permission_capability, TP_PROTO(const struct landlock_hierarchy *hierarchy, bool same_exec, bool logged, const struct landlock_blockers *blockers, - int capability), + int capability, const struct cred *cred, + const struct user_namespace *user_ns), - TP_ARGS(hierarchy, same_exec, logged, blockers, capability), + TP_ARGS(hierarchy, same_exec, logged, blockers, capability, cred, + user_ns), TP_STRUCT__entry( __field( u64, domain_id ) diff --git a/security/landlock/cap.c b/security/landlock/cap.c index caf514be3df048..ae3acd13a367ad 100644 --- a/security/landlock/cap.c +++ b/security/landlock/cap.c @@ -28,6 +28,10 @@ static const struct access_masks cap_permission = { * check_cap - Check a capability use against the domain of @cred * * @cred: Credentials being checked. + * @ns: Target user namespace used by commoncap's capability check, which is + * not necessarily @cred->user_ns. It is forwarded unchanged to typed + * trace context but is not used for the verdict (policy depends on @cred + * and @cap). * @cap: Capability number (CAP_*). * @opts: Capability check options. CAP_OPT_NOAUDIT skips the denial record: * no audit record, no trace event, and no denial count. @@ -38,7 +42,8 @@ static const struct access_masks cap_permission = { * * Return: 0 if allowed, -EPERM if capability use is denied. */ -static int check_cap(const struct cred *const cred, const int cap, +static int check_cap(const struct cred *const cred, + struct user_namespace *const ns, const int cap, const unsigned int opts) { const struct landlock_cred_security *subject; @@ -64,6 +69,13 @@ static int check_cap(const struct cred *const cred, const int cap, .permission = LANDLOCK_PERMISSION_CAPABILITY_USE, .layer_plus_one = denied_layer, +#ifdef CONFIG_TRACEPOINTS + .trace_cap = + &(struct landlock_cap_trace){ + .cred = cred, + .user_ns = ns, + }, +#endif /* CONFIG_TRACEPOINTS */ }); return -EPERM; @@ -73,8 +85,7 @@ static int check_cap(const struct cred *const cred, const int cap, * hook_capable - Deny capability use for Landlock-sandboxed processes * * @cred: Credentials being checked. - * @ns: Target user namespace (intentionally ignored; policy depends on the - * acting credentials and @cap, not namespace ownership). + * @ns: Target user namespace, used only as typed trace context. * @cap: Capability number (CAP_*). * @opts: Capability check options, see check_cap(). * @@ -88,7 +99,7 @@ static int check_cap(const struct cred *const cred, const int cap, static int hook_capable(const struct cred *cred, struct user_namespace *ns, int cap, unsigned int opts) { - return check_cap(cred, cap, opts); + return check_cap(cred, ns, cap, opts); } /** @@ -118,7 +129,7 @@ static int hook_capset(struct cred *new, const struct cred *old, cap_combine(old->cap_inheritable, old->cap_permitted))) return 0; - return check_cap(old, CAP_SETPCAP, CAP_OPT_NONE); + return check_cap(old, old->user_ns, CAP_SETPCAP, CAP_OPT_NONE); } /** @@ -127,8 +138,11 @@ static int hook_capset(struct cred *new, const struct cred *old, * @addr: Address of the new mapping. * * cap_mmap_addr() requires CAP_SYS_RAWIO to map below dac_mmap_min_addr, but - * calls cap_capable() directly, which skips hook_capable(). Check the same - * condition against the domain. commoncap runs first, so this only sees + * calls cap_capable() directly, which skips hook_capable(). It checks the + * acting task's credentials against init_user_ns because this global limit must + * not be bypassed with a capability only held in a nested user namespace. + * Mirror the condition, using the same credential for the domain check and both + * objects for typed trace context. commoncap runs first, so this only sees * mappings that commoncap allowed. * * Return: 0 if allowed, -EPERM if CAP_SYS_RAWIO use is denied. @@ -138,7 +152,8 @@ static int hook_mmap_addr(unsigned long addr) if (addr >= dac_mmap_min_addr) return 0; - return check_cap(current_cred(), CAP_SYS_RAWIO, CAP_OPT_NONE); + return check_cap(current_cred(), &init_user_ns, CAP_SYS_RAWIO, + CAP_OPT_NONE); } /** @@ -148,10 +163,13 @@ static int hook_mmap_addr(unsigned long addr) * @pages: Number of pages being charged (unused). * * cap_vm_enough_memory() lets CAP_SYS_ADMIN use the vm.admin_reserve_kbytes - * reserve, but calls cap_capable() directly, which skips hook_capable(). Check - * the same capability against the domain. commoncap runs first, so this only - * sees tasks that commoncap let use the reserve. Like commoncap, do not log - * denials: this only selects a memory limit. + * reserve, but calls cap_capable() directly, which skips hook_capable(). It + * checks the acting task's credentials against init_user_ns because a + * capability only held in a nested user namespace must not grant access to the + * global reserve. Mirror the check, using the same credential for the domain + * check and both objects for typed trace context. commoncap runs first, so + * this only sees tasks that commoncap let use the reserve. Like commoncap, do + * not log denials: this only selects a memory limit. * * Return: 0 if the domain does not withhold the reserve, -EPERM if * CAP_SYS_ADMIN use is denied. An error does not fail the allocation by @@ -159,7 +177,8 @@ static int hook_mmap_addr(unsigned long addr) */ static int hook_vm_enough_memory(struct mm_struct *mm, long pages) { - return check_cap(current_cred(), CAP_SYS_ADMIN, CAP_OPT_NOAUDIT); + return check_cap(current_cred(), &init_user_ns, CAP_SYS_ADMIN, + CAP_OPT_NOAUDIT); } static struct security_hook_list landlock_hooks[] __ro_after_init = { diff --git a/security/landlock/log.h b/security/landlock/log.h index 641a2c3c78ed04..5ca87870c7b788 100644 --- a/security/landlock/log.h +++ b/security/landlock/log.h @@ -13,10 +13,12 @@ #include "access.h" +struct cred; struct landlock_cred_security; struct landlock_hierarchy; struct sockaddr; struct task_struct; +struct user_namespace; enum landlock_request_type { LANDLOCK_REQUEST_PTRACE = 1, @@ -54,6 +56,11 @@ struct landlock_signal_trace { int signal; }; +struct landlock_cap_trace { + const struct cred *cred; + const struct user_namespace *user_ns; +}; + #endif /* CONFIG_TRACEPOINTS */ /* @@ -104,6 +111,8 @@ struct landlock_request { const struct landlock_ptrace_trace *trace_ptrace; /* Synchronous context for a signal denial. */ const struct landlock_signal_trace *trace_signal; + /* Synchronous context for a capability denial. */ + const struct landlock_cap_trace *trace_cap; }; #endif /* CONFIG_TRACEPOINTS */ }; diff --git a/security/landlock/trace.c b/security/landlock/trace.c index 00cb497eaffbfc..a47fb10dec459e 100644 --- a/security/landlock/trace.c +++ b/security/landlock/trace.c @@ -97,14 +97,21 @@ void landlock_trace_denial( break; case LANDLOCK_REQUEST_CAPABILITY: if (trace_landlock_deny_permission_capability_enabled()) { + const struct landlock_cap_trace *const trace_cap = + request->trace_cap; const struct landlock_blockers blockers = { .access = missing, .type = request->type, }; + if (WARN_ON_ONCE(!trace_cap || !trace_cap->cred || + !trace_cap->user_ns)) + return; + trace_landlock_deny_permission_capability( youngest_denied, same_exec, logged, &blockers, - request->audit.u.cap); + request->audit.u.cap, trace_cap->cred, + trace_cap->user_ns); } break; case LANDLOCK_REQUEST_FS_ACCESS: From 3b70d866e9355dd3210cb47d51ed9e5a5e2c7ccc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 17:32:51 +0100 Subject: [PATCH 0974/2102] selftests/landlock: Test namespace denial operations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The namespace trace tests cover creation and entry denials, but only creation exercises the quiet path. This leaves the new ENTER request tag untested through quiet selection and trace dispatch when audit logging is suppressed. Add the missing quiet setns(2) case. Together with the existing cases, this exercises all four combinations of CREATE and ENTER with logged and quieted denials, including each exact namespace_op value. Test coverage for security/landlock is 91.6% of 2894 lines according to LLVM 23. Cc: Günther Noack Link: https://patch.msgid.link/20261118163254.2554413-4-mic@digikod.net Signed-off-by: Mickaël Salaün --- tools/testing/selftests/landlock/ns_test.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tools/testing/selftests/landlock/ns_test.c b/tools/testing/selftests/landlock/ns_test.c index d4a85cbebeaeba..52206ad94ecad2 100644 --- a/tools/testing/selftests/landlock/ns_test.c +++ b/tools/testing/selftests/landlock/ns_test.c @@ -2575,6 +2575,13 @@ TEST_F(ns_trace, deny_setns) test_ns_trace_denial(_metadata, true, false); } +TEST_F(ns_trace, deny_setns_quiet) +{ + if (!self->tracefs_ok) + SKIP(return, "tracefs not available"); + test_ns_trace_denial(_metadata, true, true); +} + /* clang-format off */ FIXTURE(ns_proc_open) { /* clang-format on */ From 74656cdfc01c0fe5d7cb2488c05007911cfac916 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 18 Nov 2026 17:32:52 +0100 Subject: [PATCH 0975/2102] landlock: Document namespace denial operations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Namespace denial records now distinguish creation from entry. Document the namespace_op field in the audit and trace references, and clarify that it describes the semantic namespace hook rather than exact syscall provenance. Creation reports the ID allocated for a namespace that never becomes reachable, whereas entry reports the existing target ID. Cc: Günther Noack Link: https://patch.msgid.link/20261118163254.2554413-5-mic@digikod.net Signed-off-by: Mickaël Salaün --- Documentation/admin-guide/LSM/landlock.rst | 21 ++++++++++++--------- Documentation/trace/events-landlock.rst | 20 +++++++++++++------- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/Documentation/admin-guide/LSM/landlock.rst b/Documentation/admin-guide/LSM/landlock.rst index 946f3bf8965003..a79912e8a684c7 100644 --- a/Documentation/admin-guide/LSM/landlock.rst +++ b/Documentation/admin-guide/LSM/landlock.rst @@ -7,7 +7,7 @@ Landlock: system-wide management ================================ :Author: Mickaël Salaün -:Date: October 2026 +:Date: November 2026 Landlock can leverage the audit framework to log events. @@ -72,10 +72,13 @@ AUDIT_LANDLOCK_ACCESS :manpage:`unshare(2)`, :manpage:`clone(2)`, :manpage:`clone3(2)`, :manpage:`open_tree(2)`, or :manpage:`fsmount(2)`, or joining via :manpage:`setns(2)`); - ``namespace_type`` indicates the type (hex ``CLONE_NEW*`` bitmask), - and ``namespace_id`` identifies the target namespace (for a denied - creation, the namespace never becomes reachable so its ID is not - directly visible from user space) + ``namespace_op`` is ``create`` for construction or ``enter`` for + :manpage:`setns(2)`. These values describe semantic namespace hooks, + not exact system calls. ``namespace_type`` indicates the type (hex + ``CLONE_NEW*`` bitmask), and ``namespace_id`` identifies the namespace + object. For a denied creation, the new namespace never becomes + reachable, so its ID is not directly visible from user space. For a + denied entry, this is the exact existing target ID. **capability.*** - Capability restrictions (ABI 12+): - capability.use - Capability use was denied; @@ -86,10 +89,10 @@ AUDIT_LANDLOCK_ACCESS in a directory that lacks both ``make_reg`` and ``refer`` rights would show ``blockers=fs.make_reg,fs.refer``. - The object identification fields depend on the type of access being blocked: - ``path``, ``dev``, ``ino`` for filesystem; ``opid``, ``ocomm`` for signals; - ``namespace_type`` and ``namespace_id`` for namespace operations; - ``capability`` for capability use. + The operation and object context fields depend on the type of access being + blocked: ``path``, ``dev``, ``ino`` for filesystem; ``opid``, ``ocomm`` for + signals; ``namespace_op``, ``namespace_type``, and ``namespace_id`` for + namespace operations; ``capability`` for capability use. AUDIT_LANDLOCK_DOMAIN diff --git a/Documentation/trace/events-landlock.rst b/Documentation/trace/events-landlock.rst index 1ddc123df59ea4..0647a87677a132 100644 --- a/Documentation/trace/events-landlock.rst +++ b/Documentation/trace/events-landlock.rst @@ -6,7 +6,7 @@ Landlock Trace Events ===================== :Author: Mickaël Salaün -:Date: October 2026 +:Date: November 2026 Landlock emits trace events for sandbox lifecycle operations and access denials. These events can be consumed by ftrace (for human-readable @@ -186,13 +186,19 @@ known allowed and quiet member masks. Capability masks and the raw therefore appears as zero while still advancing the ruleset version, and adding a member already present still emits an event. -``landlock_deny_permission_namespace`` reports the denied raw -``CLONE_NEW*`` value. ``namespace_id`` is the exact target namespace ID. For -a denied namespace creation, the namespace never becomes reachable so its ID -is not directly visible from user space. +``landlock_deny_permission_namespace`` reports ``namespace_op`` as ``create`` +for namespace construction, for example through :manpage:`clone(2)`, +:manpage:`clone3(2)`, :manpage:`unshare(2)`, :manpage:`open_tree(2)`, or +:manpage:`fsmount(2)`, and ``enter`` for :manpage:`setns(2)`. These values +describe the semantic namespace hook, not the exact system call. +``namespace_type`` is the denied raw ``CLONE_NEW*`` value. For a denied +creation, ``namespace_id`` is allocated for the new namespace, which never +becomes reachable, so its ID is not directly visible from user space. For a +denied entry, ``namespace_id`` is the exact existing target ID. + ``landlock_deny_permission_capability`` reports the denied ``CAP_*`` number. -Like every denial event, both include the denying domain, ``same_exec``, and -``logged``. +Like every denial event, the namespace and capability events include the +denying domain, ``same_exec``, and ``logged``. Per-member quiet masks suppress audit submission but never these trace events, which report ``logged=0``. From 5651590be08a6dc7e36cbef415c8f23af1cda4d9 Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Wed, 18 Nov 2026 16:05:44 +0300 Subject: [PATCH 0976/2102] KVM: arm64: Load the vcpu in KVM_SET_VCPU_EVENTS Nested virtualization can trigger a NULL pointer dereference of vcpu->arch.hw_mmu in kvm_inject_nested(): Unable to handle kernel NULL pointer dereference at virtual address 0000000000000084 kvm_vcpu_put_hw_mmu (arch/arm64/kvm/nested.c:1046) (P) vhe_vcpu_put (arch/arm64/kvm/arm.c:827) kvm_arch_vcpu_put (arch/arm64/kvm/arm.c:860) kvm_inject_nested (arch/arm64/kvm/emulate-nested.c:2903) kvm_inject_nested_serror (arch/arm64/kvm/emulate-nested.c:2976) kvm_inject_serror_esr (arch/arm64/kvm/inject_fault.c:365) __kvm_arm_vcpu_set_events (arch/arm64/kvm/guest.c:827) kvm_arch_vcpu_ioctl (arch/arm64/kvm/arm.c:2017 arch/arm64/kvm/arm.c:2157) kvm_vcpu_ioctl (arch/arm64/kvm/../../../virt/kvm/kvm_main.c:4772) The KVM_SET_VCPU_EVENTS ioctl does not load the vcpu, it just injects a pending SError or external abort straight away. If the vcpu is in L2 context and L1 has asked for the exception, kvm_inject_nested() puts and loads a vcpu that is not loaded which leads to a NULL pointer dereference. Load the vcpu in kvm_arm_vcpu_set_events() so that kvm_inject_nested() always finds a loaded vcpu. Fixes: 9aba641b9ec2 ("KVM: arm64: nv: Respect exception routing rules for SEAs") Fixes: 77ee70a07357 ("KVM: arm64: nv: Honor SError exception routing / masking") Cc: stable@vger.kernel.org Signed-off-by: Dan Carpenter Link: https://patch.msgid.link/033a2d49e0f48426281b46eb1131ae64012aba18.1795006659.git.dan@pereq.eu Signed-off-by: Marc Zyngier --- arch/arm64/kvm/arm.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/arch/arm64/kvm/arm.c b/arch/arm64/kvm/arm.c index 157bf4b8120201..8fe7072092586d 100644 --- a/arch/arm64/kvm/arm.c +++ b/arch/arm64/kvm/arm.c @@ -1999,7 +1999,7 @@ static int kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu, static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu, struct kvm_vcpu_events *events) { - int i; + int i, ret; /* check whether the reserved field is zero */ for (i = 0; i < ARRAY_SIZE(events->reserved); i++) @@ -2011,7 +2011,11 @@ static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu, if (events->exception.pad[i]) return -EINVAL; - return __kvm_arm_vcpu_set_events(vcpu, events); + vcpu_load(vcpu); + ret = __kvm_arm_vcpu_set_events(vcpu, events); + vcpu_put(vcpu); + + return ret; } /* From 09edd2a7ed8a1aaae8e472ab11313faab9f401cc Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Wed, 18 Nov 2026 16:05:54 +0300 Subject: [PATCH 0977/2102] KVM: arm64: nv: Fix NULL dereference in kvm_pmu_nested_transition() With the KVM_ARM_VCPU_PMU_V3_STRICT feature, kvm->arch.arm_pmu stays NULL until userspace selects a PMU with the KVM_ARM_VCPU_PMU_V3_SET_PMU attribute. The KVM_SET_VCPU_EVENTS ioctl can inject an SError or external abort before that which leads to a NULL pointer dereference. Unable to handle kernel NULL pointer dereference at virtual address 00000000000001e8 kvm_pmu_create_perf_event (arch/arm64/kvm/pmu-emul.c:710) (P) kvm_pmu_nested_transition (arch/arm64/kvm/pmu-emul.c:1357) kvm_inject_nested (arch/arm64/kvm/emulate-nested.c:2927) kvm_inject_nested_serror (arch/arm64/kvm/emulate-nested.c:2979) kvm_inject_serror_esr (arch/arm64/kvm/inject_fault.c:365) __kvm_arm_vcpu_set_events (arch/arm64/kvm/guest.c:827) kvm_arch_vcpu_ioctl (arch/arm64/kvm/arm.c:2161) kvm_vcpu_ioctl (arch/arm64/kvm/../../../virt/kvm/kvm_main.c:4772) Return early if the PMU hasn't been initialized to fix this. After all, we can't transition a PMU that doesn't exist. Reported-by: Sashiko Closes: https://lore.kernel.org/all/sashiko-outbox-217134@kernel.org/ Fixes: ad220e275c39 ("KVM: arm64: Add KVM_ARM_VCPU_PMU_V3_STRICT vCPU feature") Cc: stable@vger.kernel.org Signed-off-by: Dan Carpenter Link: https://patch.msgid.link/0f35f6e21bec19774e23c991370488fa99fb37da.1795006659.git.dan@pereq.eu Signed-off-by: Marc Zyngier --- arch/arm64/kvm/pmu-emul.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/arm64/kvm/pmu-emul.c b/arch/arm64/kvm/pmu-emul.c index e2b28dbc0451b0..388a6244e7b242 100644 --- a/arch/arm64/kvm/pmu-emul.c +++ b/arch/arm64/kvm/pmu-emul.c @@ -1342,6 +1342,9 @@ void kvm_pmu_nested_transition(struct kvm_vcpu *vcpu) unsigned long mask; int i; + if (!vcpu->arch.pmu.created) + return; + mask = __vcpu_sys_reg(vcpu, PMCNTENSET_EL0); for_each_set_bit(i, &mask, 32) { struct kvm_pmc *pmc = kvm_vcpu_idx_to_pmc(vcpu, i); From 5f9cc7dcda69ed881a3041ad992afaac2a39d687 Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Wed, 18 Nov 2026 18:35:32 +0300 Subject: [PATCH 0978/2102] KVM: arm64: nv: Ignore TLBI IPAS2E1 above the IPA limit In theory, an L1 hypervisor could issue a TLBI IPAS2E1 for an IPA above the host's IPA limit. The s2_mmu_unmap_ipa() function would pass it to kvm_stage2_unmap_range(), the page table walk would fail with -ERANGE, and that would trigger the WARN_ON() in kvm_vm_stage2_unmap_range(): WARN_ON(stage2_apply_range(mmu, start, start + size, fn, may_block)); The TLBI's IPA field goes up to 48 bits, so this needs a host whose IPA limit (its PARange) is below 48 bits, and it would also need to support nested virtualization. There are very few CPUs which meet both these requirements. The fix for this is to return early. Since there is nothing mapped above the limit, there is nothing to do. This matches how handle_ripas2e1is() also ignores TLBIs that start outside the PA_bits range. Fixes: 70109bcd701e ("KVM: arm64: nv: Handle TLBI IPAS2E1{,IS} operations") Signed-off-by: Dan Carpenter Link: https://patch.msgid.link/av3FxJpUvpb_8qMC@stanley.mountain Signed-off-by: Marc Zyngier --- arch/arm64/kvm/sys_regs.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/arm64/kvm/sys_regs.c b/arch/arm64/kvm/sys_regs.c index 82b0313a3dce93..37a511d6d1e63b 100644 --- a/arch/arm64/kvm/sys_regs.c +++ b/arch/arm64/kvm/sys_regs.c @@ -4218,6 +4218,9 @@ static void s2_mmu_unmap_ipa(struct kvm_s2_mmu *mmu, max_size = compute_tlb_inval_range(mmu, info->ipa.addr); base_addr &= ~(max_size - 1); + if (base_addr >= kvm_phys_size(mmu)) + return; + /* * See comment in s2_mmu_unmap_range() for why this is allowed to * reschedule. From fa1c0f103fd68558613d3df76e222463c6e4fc37 Mon Sep 17 00:00:00 2001 From: Long Wei Date: Thu, 19 Nov 2026 17:59:37 +0800 Subject: [PATCH 0979/2102] kho: do not expose incoming sub-blob contents in debugfs Incoming sub-blob pages are owned by their consumers and have independent lifetimes. Some consumers, such as LUO, restore and free their state in early_initcall, i.e. before kho_init() (fs_initcall) builds the debugfs view: early_initcall: luo_early_startup() -> kho_retrieve_subtree("LUO") -> kho_restore_free(luo_ser) /* page is freed */ fs_initcall: kho_init() -> kho_in_debugfs_init() -> phys_to_virt(luo_ser_phys) -> debugfs_create_blob("LUO", ...) debugfs therefore ends up pointing at a page that was already handed back to the page allocator, and reading the file triggers a use-after-free: # cat /sys/kernel/debug/kho/in/sub_fdts/LUO ================================================================== BUG: KASAN: use-after-free in _copy_to_user+0x37/0x60 Read of size 32 at addr ffff88810309c000 by task cat/27436 Call Trace: kasan_report+0xb9/0xf0 kasan_check_range+0x100/0x1b0 _copy_to_user+0x37/0x60 simple_read_from_buffer+0x77/0xd0 read_file_blob+0x75/0xa0 vfs_read+0x12d/0x520 ksys_read+0xc3/0x160 do_syscall_64+0x97/0x4b0 entry_SYSCALL_64_after_hwframe+0x76/0x7e The buggy address belongs to the physical page: page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x1fd pfn:0x10309c flags: 0x17ffffc0000000(node=0|zone=2|lastcpupid=0x1fffff) page_type: f0(buddy) ================================================================== The page is already in the buddy allocator (page_type: f0(buddy), refcount 0), which confirms it was freed before the debugfs view was created. KHO does not own these pages, so it cannot safely expose their contents at all. Drop the in/sub_fdts directory. The incoming FDT is reserved by KHO and remains exposed as in/fdt, where the same metadata is available. The incoming sub-blob debugfs directory is gone, so remove its description from the KHO admin guide as well. Note that in/sub_fdts has exposed memory KHO does not own since commit c609c144b0e8 ("kexec: add KHO parsing support"), but the use-after-free only became reachable after commit d376e4b55c9a0 ("liveupdate: centralize state management into struct luo_ser") which added kho_restore_free() Fixes: d376e4b55c9a0 ("liveupdate: centralize state management into struct luo_ser") Acked-by: Pasha Tatashin Signed-off-by: Long Wei Reviewed-by: Pratyush Yadav Link: https://patch.msgid.link/20261119095937.826980-1-longwei27@huawei.com Signed-off-by: Mike Rapoport (Microsoft) --- Documentation/admin-guide/mm/kho.rst | 4 -- kernel/liveupdate/kexec_handover_debugfs.c | 47 +--------------------- 2 files changed, 2 insertions(+), 49 deletions(-) diff --git a/Documentation/admin-guide/mm/kho.rst b/Documentation/admin-guide/mm/kho.rst index 902d171a780afc..4281da6be5faa7 100644 --- a/Documentation/admin-guide/mm/kho.rst +++ b/Documentation/admin-guide/mm/kho.rst @@ -117,7 +117,3 @@ stabilized. kernel's state is in this file in the format of flattened device tree. This file may disappear when all consumers of it finished to interpret their metadata. - -``/sys/kernel/debug/kho/in/sub_fdts/`` - Similar to ``kho/out/sub_fdts/``, but contains sub blobs - of KHO producers passed from the old kernel. diff --git a/kernel/liveupdate/kexec_handover_debugfs.c b/kernel/liveupdate/kexec_handover_debugfs.c index 7d74477da0b799..3a91c47ad7a6d1 100644 --- a/kernel/liveupdate/kexec_handover_debugfs.c +++ b/kernel/liveupdate/kexec_handover_debugfs.c @@ -10,7 +10,6 @@ #define pr_fmt(fmt) "KHO: " fmt #include -#include #include #include #include @@ -97,8 +96,8 @@ DEFINE_SHOW_ATTRIBUTE(bootmem_len); __init void kho_in_debugfs_init(struct kho_debugfs *dbg, const void *fdt) { - struct dentry *dir, *sub_fdt_dir; - int err, child; + struct dentry *dir; + int err; INIT_LIST_HEAD(&dbg->fdt_list); @@ -108,54 +107,12 @@ __init void kho_in_debugfs_init(struct kho_debugfs *dbg, const void *fdt) goto err_out; } - sub_fdt_dir = debugfs_create_dir("sub_fdts", dir); - if (IS_ERR(sub_fdt_dir)) { - err = PTR_ERR(sub_fdt_dir); - goto err_rmdir; - } - err = __kho_debugfs_blob_add(&dbg->fdt_list, dir, "fdt", fdt, fdt_totalsize(fdt)); if (err) goto err_rmdir; - fdt_for_each_subnode(child, fdt, 0) { - int len = 0; - const char *name = fdt_get_name(fdt, child, NULL); - const u64 *blob_phys; - const u64 *blob_size; - void *blob; - - blob_phys = fdt_getprop(fdt, child, - KHO_SUB_TREE_PROP_NAME, &len); - if (!blob_phys) - continue; - if (len != sizeof(*blob_phys)) { - pr_warn("node %s prop %s has invalid length: %d\n", - name, KHO_SUB_TREE_PROP_NAME, len); - continue; - } - - blob_size = fdt_getprop(fdt, child, - KHO_SUB_TREE_SIZE_PROP_NAME, &len); - if (!blob_size || len != sizeof(*blob_size)) { - pr_warn("node %s missing or invalid %s property\n", - name, KHO_SUB_TREE_SIZE_PROP_NAME); - continue; - } - - blob = phys_to_virt(*blob_phys); - err = __kho_debugfs_blob_add(&dbg->fdt_list, sub_fdt_dir, name, - blob, *blob_size); - if (err) { - pr_warn("failed to add blob %s to debugfs: %pe\n", - name, ERR_PTR(err)); - continue; - } - } - dbg->dir = dir; - dbg->sub_fdt_dir = sub_fdt_dir; return; err_rmdir: From fcfc52fcf89a3076c3a9afbbc70c0fecd2b5fc8d Mon Sep 17 00:00:00 2001 From: Christian Schmidbauer Date: Sat, 14 Nov 2026 14:36:37 +0100 Subject: [PATCH 0980/2102] net: stmmac: honour Rx checksum errors in the AF_XDP zero-copy path Commit ee0aace5f844 ("net: stmmac: Correctly handle Rx checksum offload errors") taught stmmac_rx() to honour the csum_none status, but stmmac_dispatch_skb_zc() still ignores it and sets CHECKSUM_UNNECESSARY for every IP frame whenever the checksum offload engine (CoE) is enabled. Since commit fe4042797651 ("net: stmmac: dwmac4: stop hardware from dropping checksum-error packets") dwmac4 delivers such frames instead of dropping them, so this path receives them. Mark the skb CHECKSUM_NONE when csum_none is set, as stmmac_rx() does. Fixes: bba2556efad6 ("net: stmmac: Enable RX via AF_XDP zero-copy") Cc: Signed-off-by: Christian Schmidbauer Reviewed-by: Maxime Chevallier Link: https://patch.msgid.link/20261114133640.3285413-2-opensource@grische.xyz Signed-off-by: Paolo Abeni --- drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c index 9a9c44aab2e44c..a685ce4638f61a 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c @@ -5563,7 +5563,7 @@ static struct sk_buff *stmmac_construct_skb_zc(struct stmmac_channel *ch, static void stmmac_dispatch_skb_zc(struct stmmac_priv *priv, u32 queue, struct dma_desc *p, struct dma_desc *np, - struct xdp_buff *xdp) + struct xdp_buff *xdp, int status) { struct stmmac_rxq_stats *rxq_stats = &priv->xstats.rxq_stats[queue]; struct stmmac_channel *ch = &priv->channel[queue]; @@ -5591,7 +5591,8 @@ static void stmmac_dispatch_skb_zc(struct stmmac_priv *priv, u32 queue, skb->protocol = eth_type_trans(skb, priv->dev); - if (unlikely(!coe) || !stmmac_has_ip_ethertype(skb)) + if (unlikely(!coe) || !stmmac_has_ip_ethertype(skb) || + (status & csum_none)) skb_checksum_none_assert(skb); else skb->ip_summed = CHECKSUM_UNNECESSARY; @@ -5805,7 +5806,8 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) switch (res) { case STMMAC_XDP_PASS: - stmmac_dispatch_skb_zc(priv, queue, p, np, buf->xdp); + stmmac_dispatch_skb_zc(priv, queue, p, np, buf->xdp, + status); xsk_buff_free(buf->xdp); break; case STMMAC_XDP_CONSUMED: From 596c9408682feba536d7f39de97959807eb3ba1c Mon Sep 17 00:00:00 2001 From: Christian Schmidbauer Date: Sat, 14 Nov 2026 14:36:38 +0100 Subject: [PATCH 0981/2102] net: stmmac: dwmac1000: don't discard frames with only a checksum error On dwmac1000 with enhanced descriptors, the hardware sets the Error Summary (ES) bit of the Rx descriptor not only for L2 errors but also for an L3/L4 checksum error. enh_desc_get_rx_status() returns discard_frame whenever ES is set, and since commit 1b746ce8b397 ("net: stmmac: don't overwrite discard_frame status") the checksum status is only evaluated for good frames. Return discard_frame only when ES comes with one of the L2 error bits. A frame with only a checksum error is then reported as csum_none and reaches the stack as CHECKSUM_NONE, so the stack verifies the checksum itself. This matches dwmac4, whose Error Summary bit does not cover checksum errors. RDES0 bit 7 is not in the mask, because depending on the core and on Rx checksum offload it reports a timestamp, an IP header checksum error or a giant frame, and enh_desc_get_rx_status() cannot tell which. In threshold Rx mode, a giant frame that fits one buffer therefore reaches the stack with a verified FCS. Also remove the pr_err that enh_desc_get_rx_status() prints when bit 7 is set. Once the MAC stops dropping checksum-error frames, any host on the link can flood the kernel log by sending frames with a bad IPv4 header checksum. This prepares for setting DMA_CONTROL_DT, which makes the MAC deliver checksum-error frames instead of dropping them in its Rx FIFO. Fixes: 1b746ce8b397 ("net: stmmac: don't overwrite discard_frame status") Cc: # 6.6.x: ee0aace5f844: net: stmmac: Correctly handle Rx checksum offload errors Cc: # 6.6.x Signed-off-by: Christian Schmidbauer Reviewed-by: Maxime Chevallier Tested-by: Maxime Chevallier Link: https://patch.msgid.link/20261114133640.3285413-3-opensource@grische.xyz Signed-off-by: Paolo Abeni --- drivers/net/ethernet/stmicro/stmmac/enh_desc.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/net/ethernet/stmicro/stmmac/enh_desc.c b/drivers/net/ethernet/stmicro/stmmac/enh_desc.c index 7ece8d4157a869..d0622f2605aaae 100644 --- a/drivers/net/ethernet/stmicro/stmmac/enh_desc.c +++ b/drivers/net/ethernet/stmicro/stmmac/enh_desc.c @@ -216,9 +216,6 @@ static int enh_desc_get_rx_status(struct stmmac_extra_stats *x, if (unlikely(rdes0 & RDES0_OVERFLOW_ERROR)) x->rx_gmac_overflow++; - if (unlikely(rdes0 & RDES0_IPC_CSUM_ERROR)) - pr_err("\tIPC Csum Error/Giant frame\n"); - if (unlikely(rdes0 & RDES0_COLLISION)) x->rx_collision++; if (unlikely(rdes0 & RDES0_RECEIVE_WATCHDOG)) @@ -230,7 +227,10 @@ static int enh_desc_get_rx_status(struct stmmac_extra_stats *x, if (unlikely(rdes0 & RDES0_CRC_ERROR)) { x->rx_crc_errors++; } - ret = discard_frame; + if (rdes0 & (RDES0_DESCRIPTOR_ERROR | RDES0_OVERFLOW_ERROR | + RDES0_COLLISION | RDES0_RECEIVE_WATCHDOG | + RDES0_MII_ERROR | RDES0_CRC_ERROR)) + ret = discard_frame; } /* After a payload csum error, the ES bit is set. From 2dd48c4615a67ebb1762c2b0d79801be1949fcfb Mon Sep 17 00:00:00 2001 From: Christian Schmidbauer Date: Sat, 14 Nov 2026 14:36:39 +0100 Subject: [PATCH 0982/2102] net: stmmac: dwmac1000: stop hardware from dropping checksum-error packets When the checksum offload engine (CoE) is enabled, the dwmac1000 MAC silently drops any frame for which the engine detects a checksum error, before the driver sees it. This breaks VXLAN over IPv6 with zero UDP checksums, which RFC 6935 and RFC 6936 allow for tunnels. Set DMA_CONTROL_DT so that such frames are delivered instead of dropped, as commit fe4042797651 ("net: stmmac: dwmac4: stop hardware from dropping checksum-error packets") did for dwmac4. CoE remains enabled, so the driver still sees the error status and marks the skb CHECKSUM_NONE for the stack to verify. Set the bit only with enhanced descriptors. The normal descriptor parser does not report a checksum-only error to the stack, so cores that use it keep dropping such frames in hardware anyway. Tested on an Aruba AP-325 (ipq806x-gmac-dwmac) with Rx checksum offload on. Link: https://lore.kernel.org/all/20250625132117.1b3264e8@kernel.org/ Link: https://github.com/freifunk-gluon/gluon/issues/3783 Fixes: 47dd7a540b8a ("net: add support for STMicroelectronics Ethernet controllers.") Cc: # 6.6.x: ee0aace5f844: net: stmmac: Correctly handle Rx checksum offload errors Cc: # 6.6.x Signed-off-by: Christian Schmidbauer Reviewed-by: Maxime Chevallier Tested-by: Maxime Chevallier Link: https://patch.msgid.link/20261114133640.3285413-4-opensource@grische.xyz Signed-off-by: Paolo Abeni --- drivers/net/ethernet/stmicro/stmmac/dwmac1000.h | 2 +- drivers/net/ethernet/stmicro/stmmac/dwmac1000_dma.c | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/stmicro/stmmac/dwmac1000.h b/drivers/net/ethernet/stmicro/stmmac/dwmac1000.h index 1de1f929d61cdd..55d9c39287f1ff 100644 --- a/drivers/net/ethernet/stmicro/stmmac/dwmac1000.h +++ b/drivers/net/ethernet/stmicro/stmmac/dwmac1000.h @@ -162,7 +162,7 @@ enum rx_tx_priority_ratio { /* DMA CRS Control and Status Register Mapping */ /* DMA operation mode defines (start/stop tx/rx are placed in common header)*/ -/* Disable Drop TCP/IP csum error */ +#define DMA_CONTROL_DT 0x04000000 /* Disable Drop of TCP/IP csum errors */ #define DMA_CONTROL_RSF 0x02000000 /* Receive Store and Forward */ #define DMA_CONTROL_DFF 0x01000000 /* Disaable flushing */ /* Threshold for Activating the FC */ diff --git a/drivers/net/ethernet/stmicro/stmmac/dwmac1000_dma.c b/drivers/net/ethernet/stmicro/stmmac/dwmac1000_dma.c index 3ac7a7949529c8..31d5f79ef5602d 100644 --- a/drivers/net/ethernet/stmicro/stmmac/dwmac1000_dma.c +++ b/drivers/net/ethernet/stmicro/stmmac/dwmac1000_dma.c @@ -15,6 +15,7 @@ #include #include "dwmac1000.h" #include "dwmac_dma.h" +#include "stmmac.h" static void dwmac1000_dma_axi(void __iomem *ioaddr, struct stmmac_axi *axi) { @@ -129,6 +130,13 @@ static void dwmac1000_dma_operation_mode_rx(struct stmmac_priv *priv, { u32 csr6 = readl(ioaddr + DMA_CHAN_CONTROL(channel)); + /* Deliver checksum-error frames only with enhanced + * descriptors, because the normal descriptor parser does not + * report a checksum-only error. + */ + if (priv->plat->enh_desc) + csr6 |= DMA_CONTROL_DT; + if (mode == SF_DMA_MODE) { pr_debug("GMAC: enable RX store and forward mode\n"); csr6 |= DMA_CONTROL_RSF | DMA_CONTROL_DFF; From 050f2adb60434a2b4dee2cf3350269379a32cf72 Mon Sep 17 00:00:00 2001 From: Eric Dumazet Date: Fri, 13 Nov 2026 13:46:21 +0100 Subject: [PATCH 0983/2102] ipv6: gro: limit the number of extension headers Hyunwoo Kim reported that a long chain of IPv6 extension headers can push the transport header offset of a GRO packet beyond what the 16-bit skb->transport_header can store. The truncated offset is later used by gro_receive_network_flush() to locate the network header of a packet held in the GRO list, leading to an out-of-bounds read. Since commit 3744b0964d52 ("ipv6: Implement limits on extension header parsing"), ip6_protocol_deliver_rcu() drops packets carrying more than IP6_MAX_EXT_HDRS_CNT extension headers, but ipv6_gro_pull_exthdrs() was left unbounded. There is no point trying to aggregate packets that the stack is going to drop anyway if they are locally delivered. Apply the same limit in ipv6_gro_pull_exthdrs(). When the limit is hit, @proto still designates an extension header. Extension header offloads have no gro_receive() callback, so ipv6_gro_receive() takes its existing "goto out" path with flush set, and the packet is given to the normal receive path. Local delivery drops it with SKB_DROP_REASON_IPV6_TOO_MANY_EXTHDRS, while forwarded packets are simply not aggregated. An extension header being at most 2048 bytes, this bounds a chain to 24576 bytes. Note that offsets can still accumulate over nested encapsulations, so the places storing them should be hardened separately. Fixes: 4b0ebbca3e16 ("net: gro: move L3 flush checks to tcp_gro_receive and udp_gro_receive_segment") Cc: stable@vger.kernel.org Reported-by: Hyunwoo Kim Link: https://lore.kernel.org/netdev/avTTQNyvwPP6LtGx@v4bel/ Signed-off-by: Eric Dumazet Cc: Daniel Borkmann Cc: David Ahern Cc: Ido Schimmel Tested-by: Hyunwoo Kim Reviewed-by: Ido Schimmel Reviewed-by: Aaron Conole Link: https://patch.msgid.link/20261113124625.4010206-2-edumazet@kernel.org Reviewed-by: Justin Iurman Signed-off-by: Paolo Abeni --- net/ipv6/ip6_offload.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/net/ipv6/ip6_offload.c b/net/ipv6/ip6_offload.c index 700f1861d8eb7d..01642900c0fa33 100644 --- a/net/ipv6/ip6_offload.c +++ b/net/ipv6/ip6_offload.c @@ -26,6 +26,7 @@ static int ipv6_gro_pull_exthdrs(struct sk_buff *skb, int off, int proto) { const struct net_offload *ops = NULL; struct ipv6_opt_hdr *opth; + int exthdr_cnt = 0; for (;;) { int len; @@ -38,6 +39,13 @@ static int ipv6_gro_pull_exthdrs(struct sk_buff *skb, int off, int proto) if (!(ops->flags & INET6_PROTO_GSO_EXTHDR)) break; + /* Same limit as ip6_protocol_deliver_rcu(). + * @proto is left pointing to an extension header, + * so that the caller does not aggregate this packet. + */ + if (unlikely(exthdr_cnt++ >= IP6_MAX_EXT_HDRS_CNT)) + break; + opth = skb_gro_header(skb, off + sizeof(*opth), off); if (unlikely(!opth)) break; From 425b1fe50b71628299d33faff28057e7fa4c60c7 Mon Sep 17 00:00:00 2001 From: Eric Dumazet Date: Fri, 13 Nov 2026 13:46:22 +0100 Subject: [PATCH 0984/2102] ipv6: mcast: use skb_set_transport_header_careful() in ipv6_mc_check_exthdrs() skb->transport_header is a 16-bit offset from skb->head, and U16_MAX is reserved as the "not set" value. skb_set_transport_header() silently truncates an offset that does not fit. ipv6_mc_check_exthdrs() stores the offset returned by ipv6_skip_exthdr(), which depends on the extension headers found in the packet. Should the value be truncated, ipv6_mc_check_icmpv6() and ipv6_mc_check_mld_msg() would then validate and parse the MLD message at the wrong place. Since commit 3744b0964d52 ("ipv6: Implement limits on extension header parsing") a single chain is bounded to IP6_MAX_EXT_HDRS_CNT headers (24576 bytes), so this needs a large skb->data - skb->head on top of it, for instance after several nested decapsulations, each of them possibly pulling its own extension header chain. No reproducer was written, this is hardening. Use skb_set_transport_header_careful() and treat such a packet as broken (-EINVAL). Fixes: 9afd85c9e455 ("net: Export IGMP/MLD message validation code") Cc: stable@vger.kernel.org Signed-off-by: Eric Dumazet Reviewed-by: Ido Schimmel Link: https://patch.msgid.link/20261113124625.4010206-3-edumazet@kernel.org Reviewed-by: Justin Iurman Signed-off-by: Paolo Abeni --- net/ipv6/mcast_snoop.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/net/ipv6/mcast_snoop.c b/net/ipv6/mcast_snoop.c index 04d5fcdfa6e00b..7abf79815aa233 100644 --- a/net/ipv6/mcast_snoop.c +++ b/net/ipv6/mcast_snoop.c @@ -56,7 +56,8 @@ static int ipv6_mc_check_exthdrs(struct sk_buff *skb) if (nexthdr != IPPROTO_ICMPV6) return -ENOMSG; - skb_set_transport_header(skb, offset); + if (!skb_set_transport_header_careful(skb, offset)) + return -EINVAL; return 0; } From b9b77e2430032c21cc82b7da3a0bc0d8e74e6c26 Mon Sep 17 00:00:00 2001 From: Eric Dumazet Date: Fri, 13 Nov 2026 13:46:23 +0100 Subject: [PATCH 0985/2102] net: openvswitch: use skb_set_transport_header_careful() in parse_ipv6hdr() skb->transport_header is a 16-bit offset from skb->head, and U16_MAX is reserved as the "not set" value. skb_set_transport_header() silently truncates an offset that does not fit. parse_ipv6hdr() stores the payload offset found by ipv6_find_hdr(), which depends on the extension headers found in the packet. Should the value be truncated, key_extract_l3l4() would parse the L4 header at the wrong place. Since commit 3744b0964d52 ("ipv6: Implement limits on extension header parsing") a single chain is bounded to IP6_MAX_EXT_HDRS_CNT headers (24576 bytes), so this needs a large skb->data - skb->head on top of it, for instance after several nested decapsulations, each of them possibly pulling its own extension header chain. No reproducer was written, this is hardening. Use skb_set_transport_header_careful() and return -EPROTO if the offset can not be stored. As for other ipv6_find_hdr() failures, the caller then sets the transport header to the network header and does not parse L4. While at it, use payload_ofs directly, since nh_ofs + nh_len == payload_ofs. Fixes: 1a37e412a022 ("net: Use 16bits for *_headers fields of struct skbuff") Cc: stable@vger.kernel.org Signed-off-by: Eric Dumazet Reviewed-by: Ilya Maximets Reviewed-by: Aaron Conole Link: https://patch.msgid.link/20261113124625.4010206-4-edumazet@kernel.org Reviewed-by: Justin Iurman Signed-off-by: Paolo Abeni --- net/openvswitch/flow.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/net/openvswitch/flow.c b/net/openvswitch/flow.c index 3734416b518d71..5fbeb0cca9dce6 100644 --- a/net/openvswitch/flow.c +++ b/net/openvswitch/flow.c @@ -438,7 +438,8 @@ static int parse_ipv6hdr(struct sk_buff *skb, struct sw_flow_key *key) return -EPROTO; nh_len = payload_ofs - nh_ofs; - skb_set_transport_header(skb, nh_ofs + nh_len); + if (unlikely(!skb_set_transport_header_careful(skb, payload_ofs))) + return -EPROTO; key->ip.proto = nexthdr; return nh_len; } From 13391f1a8c584e7c1addaea3fd47105d92cc724c Mon Sep 17 00:00:00 2001 From: Eric Dumazet Date: Fri, 13 Nov 2026 13:46:24 +0100 Subject: [PATCH 0986/2102] sctp: use skb_set_transport_header_careful() in sctp_v6_err() skb->transport_header is a 16-bit offset from skb->head, and U16_MAX is reserved as the "not set" value. skb_set_transport_header() silently truncates an offset that does not fit. sctp_v6_err() stores @offset, computed by icmpv6_notify() from the extension headers of the packet embedded in an ICMPv6 error. Should the value be truncated, sctp_err_lookup() would read the SCTP header at the wrong place. Since commit 3744b0964d52 ("ipv6: Implement limits on extension header parsing") a single chain is bounded to IP6_MAX_EXT_HDRS_CNT headers (24576 bytes), so this needs a large skb->data - skb->head on top of it, for instance after several nested decapsulations, each of them possibly pulling its own extension header chain, since @offset is relative to the IPv6 header embedded in the ICMPv6 error. No reproducer was written, this is hardening. Use skb_set_transport_header_careful() and ignore the ICMPv6 error if the offset can not be stored. Do this before changing the network header, so that nothing has to be restored on failure. Fixes: 1a37e412a022 ("net: Use 16bits for *_headers fields of struct skbuff") Cc: stable@vger.kernel.org Signed-off-by: Eric Dumazet Link: https://patch.msgid.link/20261113124625.4010206-5-edumazet@kernel.org Reviewed-by: Justin Iurman Signed-off-by: Paolo Abeni --- net/sctp/ipv6.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/net/sctp/ipv6.c b/net/sctp/ipv6.c index 97390569c4bdc3..ad5c951efdf064 100644 --- a/net/sctp/ipv6.c +++ b/net/sctp/ipv6.c @@ -170,8 +170,11 @@ static int sctp_v6_err(struct sk_buff *skb, struct inet6_skb_parm *opt, /* Fix up skb to look at the embedded net header. */ saveip = skb->network_header; savesctp = skb->transport_header; + if (unlikely(!skb_set_transport_header_careful(skb, offset))) { + __ICMP6_INC_STATS(net, __in6_dev_get(skb->dev), ICMP6_MIB_INERRORS); + return -EINVAL; + } skb_reset_network_header(skb); - skb_set_transport_header(skb, offset); sk = sctp_err_lookup(net, AF_INET6, skb, sctp_hdr(skb), &asoc, &transport); /* Put back, the original pointers. */ skb->network_header = saveip; From 02f578b736f1524ed73ef879fb1cf1ba4a875aa4 Mon Sep 17 00:00:00 2001 From: Eric Dumazet Date: Fri, 13 Nov 2026 13:46:25 +0100 Subject: [PATCH 0987/2102] udp: use skb_set_transport_header_careful() in __udp6_lib_err_encap() skb->transport_header is a 16-bit offset from skb->head, and U16_MAX is reserved as the "not set" value. skb_set_transport_header() silently truncates an offset that does not fit. __udp6_lib_err_encap() stores @offset, computed by icmpv6_notify() from the extension headers of the packet embedded in an ICMPv6 error. Should the value be truncated, the tunnel encap_err_lookup() and err_handler() callbacks would read the UDP header at the wrong place. Since commit 3744b0964d52 ("ipv6: Implement limits on extension header parsing") a single chain is bounded to IP6_MAX_EXT_HDRS_CNT headers (24576 bytes), so this needs a large skb->data - skb->head on top of it, for instance after several nested decapsulations, each of them possibly pulling its own extension header chain, since @offset is relative to the IPv6 header embedded in the ICMPv6 error. No reproducer was written, this is hardening. Use skb_set_transport_header_careful() and return an error if the offset can not be stored, in which case udpv6_err() ignores the ICMPv6 error. Do this before changing the network header, so that nothing has to be restored on failure. Fixes: a36e185e8c85 ("udp: Handle ICMP errors for tunnels with same destination port on both endpoints") Cc: stable@vger.kernel.org Signed-off-by: Eric Dumazet Reviewed-by: Stefano Brivio Link: https://patch.msgid.link/20261113124625.4010206-6-edumazet@kernel.org Reviewed-by: Justin Iurman Signed-off-by: Paolo Abeni --- net/ipv6/udp.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/net/ipv6/udp.c b/net/ipv6/udp.c index 9dcefa16252235..a6886a0432f973 100644 --- a/net/ipv6/udp.c +++ b/net/ipv6/udp.c @@ -651,12 +651,13 @@ static struct sock *__udp6_lib_err_encap(struct net *net, network_offset = skb_network_offset(skb); transport_offset = skb_transport_offset(skb); + /* Transport header needs to point to the UDP header */ + if (unlikely(!skb_set_transport_header_careful(skb, offset))) + return ERR_PTR(-EINVAL); + /* Network header needs to point to the outer IPv6 header inside ICMP */ skb_reset_network_header(skb); - /* Transport header needs to point to the UDP header */ - skb_set_transport_header(skb, offset); - if (sk) { up = udp_sk(sk); From 029266e696205a85ec0de3ed823ada03055d0f99 Mon Sep 17 00:00:00 2001 From: Dirk Su Date: Thu, 19 Nov 2026 14:05:49 +0800 Subject: [PATCH 0988/2102] ALSA: hda/realtek: Add LED fixup for HP ZBook Ultra G1a Laptops The HP ZBook Ultra G1a laptops requires specific LED control method ALC285_FIXUP_HP_GPIO_LED to work Signed-off-by: Dirk Su Link: https://patch.msgid.link/20261119060604.31205-1-dirk.su@canonical.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index a43bfcf9705b54..d38be4d500b213 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -8167,6 +8167,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1043, 0x1024, "ASUS Zephyrus G14 2025", ALC285_FIXUP_ASUS_GA403U_HEADSET_MIC), SND_PCI_QUIRK(0x1043, 0x1032, "ASUS VivoBook X513EA", ALC256_FIXUP_ASUS_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1043, 0x1034, "ASUS GU605C", ALC285_FIXUP_ASUS_GU605_SPI_SPEAKER2_TO_DAC1), + SND_PCI_QUIRK(0x103c, 0x900c, "HP ZBook Ultra G1a 14", ALC285_FIXUP_HP_GPIO_LED), SND_PCI_QUIRK(0x1043, 0x103e, "ASUS X540SA", ALC256_FIXUP_ASUS_MIC), SND_PCI_QUIRK(0x1043, 0x103f, "ASUS TX300", ALC282_FIXUP_ASUS_TX300), SND_PCI_QUIRK(0x1043, 0x1044, "ASUS GA403UM", ALC285_FIXUP_ASUS_GA403U_HEADSET_MIC), From abccf171fa8e97954e74934bde811d76a5410cbd Mon Sep 17 00:00:00 2001 From: Julius Bairaktaris Date: Sat, 14 Nov 2026 19:26:57 +0100 Subject: [PATCH 0989/2102] net: make room for the tunnel header in skb_segment_list() skb_segment_list() pushes each frag_list member back to the outer MAC header and copies the tunnel headers in front of it, but never checks that the member has the headroom. A fraglist GRO packet forwarded into a tunnel and segmented in software then hits skb_under_panic() on IPIP, and on VXLAN the copy writes before the member's head (KASAN: slab-out-of-bounds write in skb_segment_list()). Call skb_cow_head() on each member before pushing it. Fixes: 3a1296a38d0c ("net: Support GRO/GSO fraglist chaining.") Tested-by: Henry Martin Reviewed-by: Simon Horman Reviewed-by: Eric Dumazet Signed-off-by: Julius Bairaktaris Link: https://patch.msgid.link/c976a72586cda383b3e42486ee3d0176033b973c.1794151759.git.julius@bairaktaris.de Signed-off-by: Paolo Abeni --- net/core/skbuff.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/net/core/skbuff.c b/net/core/skbuff.c index 1ac1e327ac4c62..74e9a96bc5df08 100644 --- a/net/core/skbuff.c +++ b/net/core/skbuff.c @@ -4789,6 +4789,10 @@ struct sk_buff *skb_segment_list(struct sk_buff *skb, } } + if (!err) + err = skb_cow_head(nskb, offset + tnl_hlen - + skb_network_offset(nskb)); + if (!tail) skb->next = nskb; else From 9a4a81718b057eb8768ea87aceacafdfaf3a8b38 Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Thu, 19 Nov 2026 10:48:59 +0000 Subject: [PATCH 0990/2102] ALSA: memalloc: Fix DMA allocation retry cleanup do_alloc_pages() retries allocation with lower DMA zones when the allocated address exceeds the device's coherent DMA mask. However, the previous allocation is not freed before retrying, leaking the allocated pages. Also, if no suitable DMA zone is available, the function can return an allocation outside the device's DMA mask. Avoid retrying GFP_DMA32 after GFP_DMA has been selected, and skip the DMA mask check when the coherent DMA mask is unset. Free the allocated pages before retrying and return NULL when no suitable allocation can be obtained. Fixes: dd164fbfdc20 ("ALSA: memalloc: Drop special handling of GFP for CONTINUOUS allocation") Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261119104859.2807-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/core/memalloc.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sound/core/memalloc.c b/sound/core/memalloc.c index 5986e9b84ac0a2..8fec4a8fd219e9 100644 --- a/sound/core/memalloc.c +++ b/sound/core/memalloc.c @@ -294,17 +294,21 @@ static void *do_alloc_pages(struct device *dev, size_t size, dma_addr_t *addr, if (!p) return NULL; *addr = page_to_phys(virt_to_page(p)); - if (!dev) + if (!dev || !dev->coherent_dma_mask) return p; if ((*addr + size - 1) & ~dev->coherent_dma_mask) { - if (IS_ENABLED(CONFIG_ZONE_DMA32) && !(gfp & GFP_DMA32)) { + if (IS_ENABLED(CONFIG_ZONE_DMA32) && !(gfp & (GFP_DMA32 | GFP_DMA))) { + free_pages_exact(p, size); gfp |= GFP_DMA32; goto again; } if (IS_ENABLED(CONFIG_ZONE_DMA) && !(gfp & GFP_DMA)) { + free_pages_exact(p, size); gfp = (gfp & ~GFP_DMA32) | GFP_DMA; goto again; } + free_pages_exact(p, size); + return NULL; } #ifdef CONFIG_X86 if (wc) From 3271e518ed7f786ee7fe8dcc97bc51493127b79d Mon Sep 17 00:00:00 2001 From: Maxime Ripard Date: Thu, 5 Nov 2026 15:21:21 +0100 Subject: [PATCH 0991/2102] MAINTAINERS: Move armada DRM under drm-misc The armada DRM driver has its own tree entries in MAINTAINERS, pointing to Russell King's drm-armada-devel and drm-armada-fixes branches. However, the last pull request from that tree was sent in July 2019, and more than 80 patches have been merged through drm-misc since then. The driver is de facto maintained through drm-misc already. Remove the dedicated tree entries and the drm-misc exclusion for armada to reflect the actual maintenance path. Reviewed-by: Thomas Zimmermann Reviewed-by: Luca Ceresoli Link: https://lore.kernel.org/r/20261105142127.708219-1-mripard@kernel.org Signed-off-by: Maxime Ripard --- MAINTAINERS | 3 --- 1 file changed, 3 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index d40d8ef0188f2e..7b9b44d52e6e72 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -8886,7 +8886,6 @@ F: include/drm/drm F: include/linux/vga* F: include/uapi/drm/ X: drivers/gpu/drm/amd/ -X: drivers/gpu/drm/armada/ X: drivers/gpu/drm/etnaviv/ X: drivers/gpu/drm/exynos/ X: drivers/gpu/drm/i915/ @@ -16147,8 +16146,6 @@ F: drivers/tty/serial/mvebu-uart.c MARVELL ARMADA DRM SUPPORT M: Russell King S: Maintained -T: git git://git.armlinux.org.uk/~rmk/linux-arm.git drm-armada-devel -T: git git://git.armlinux.org.uk/~rmk/linux-arm.git drm-armada-fixes F: Documentation/devicetree/bindings/display/armada/ F: drivers/gpu/drm/armada/ F: include/uapi/drm/armada_drm.h From cc2b377111c158d8559498102fc81ebe74c184b6 Mon Sep 17 00:00:00 2001 From: Maxime Ripard Date: Thu, 5 Nov 2026 15:21:22 +0100 Subject: [PATCH 0992/2102] MAINTAINERS: Move Keem Bay DRM under drm-misc The Intel Keem Bay DRM driver is excluded from drm-misc in MAINTAINERS, implying it is maintained through a separate tree. However, no dedicated tree is documented in the MAINTAINERS entry, no pull request has ever been sent, and around 60 patches have been merged through drm-misc. The driver is de facto maintained through drm-misc already. Remove the drm-misc exclusion for kmb to reflect the actual maintenance path. Reviewed-by: Thomas Zimmermann Reviewed-by: Luca Ceresoli Link: https://lore.kernel.org/r/20261105142127.708219-2-mripard@kernel.org Signed-off-by: Maxime Ripard --- MAINTAINERS | 1 - 1 file changed, 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index 7b9b44d52e6e72..d9f05663bb8f63 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -8889,7 +8889,6 @@ X: drivers/gpu/drm/amd/ X: drivers/gpu/drm/etnaviv/ X: drivers/gpu/drm/exynos/ X: drivers/gpu/drm/i915/ -X: drivers/gpu/drm/kmb/ X: drivers/gpu/drm/mediatek/ X: drivers/gpu/drm/msm/ X: drivers/gpu/drm/nova/ From 7ee2d18acb3f5a770b6bc96d45cd18a1dfccecf0 Mon Sep 17 00:00:00 2001 From: Maxime Ripard Date: Thu, 5 Nov 2026 15:21:23 +0100 Subject: [PATCH 0993/2102] MAINTAINERS: Move Tegra DRM under drm-misc The Tegra DRM driver is excluded from drm-misc in MAINTAINERS, with a dedicated tree at gitlab.freedesktop.org/drm/tegra.git. However, the last pull request from that tree was sent in April 2023, and about 150 patches have been merged through drm-misc since, most of them applied by the maintainers directly. The driver is de facto maintained through drm-misc already. Remove the dedicated tree entry and the drm-misc exclusion for tegra to reflect the actual maintenance path. Reviewed-by: Thomas Zimmermann Reviewed-by: Luca Ceresoli Link: https://lore.kernel.org/r/20261105142127.708219-3-mripard@kernel.org Signed-off-by: Maxime Ripard --- MAINTAINERS | 2 -- 1 file changed, 2 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index d9f05663bb8f63..4bad64f45589f0 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -8893,7 +8893,6 @@ X: drivers/gpu/drm/mediatek/ X: drivers/gpu/drm/msm/ X: drivers/gpu/drm/nova/ X: drivers/gpu/drm/radeon/ -X: drivers/gpu/drm/tegra/ X: drivers/gpu/drm/tyr/ X: drivers/gpu/drm/xe/ @@ -9076,7 +9075,6 @@ M: Mikko Perttunen L: dri-devel@lists.freedesktop.org L: linux-tegra@vger.kernel.org S: Supported -T: git https://gitlab.freedesktop.org/drm/tegra.git F: Documentation/devicetree/bindings/display/tegra/nvidia,tegra20-host1x.yaml F: Documentation/devicetree/bindings/gpu/host1x/ F: drivers/gpu/drm/tegra/ From bbc18d8620a6ad7011a43bebf9e48037393177e2 Mon Sep 17 00:00:00 2001 From: Maxime Ripard Date: Thu, 5 Nov 2026 15:21:24 +0100 Subject: [PATCH 0994/2102] MAINTAINERS: Remove Jonas Karlman from bridge reviewers Jonas Karlman's last review for the DRM bridge subsystem dates back to 2019, and he has never committed to drm-misc. The bridge subsystem has been de facto reviewed without his involvement since. Remove the reviewer entry to match the current situation. Reviewed-by: Thomas Zimmermann Reviewed-by: Luca Ceresoli Link: https://lore.kernel.org/r/20261105142127.708219-4-mripard@kernel.org Signed-off-by: Maxime Ripard --- MAINTAINERS | 1 - 1 file changed, 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index 4bad64f45589f0..a4bd4f2e4c829e 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -8947,7 +8947,6 @@ M: Andrzej Hajda M: Neil Armstrong M: Robert Foss R: Laurent Pinchart -R: Jonas Karlman R: Jernej Skrabec R: Luca Ceresoli S: Maintained From 6d62f036a554c60131d7872914fa752e08e9b527 Mon Sep 17 00:00:00 2001 From: Maxime Ripard Date: Thu, 5 Nov 2026 15:21:25 +0100 Subject: [PATCH 0995/2102] MAINTAINERS: Remove Andrzej Hajda from bridge maintainers Andrzej Hajda's last commit to the DRM bridge subsystem dates back to 2021, and his last bridge review to 2023. His focus has since moved to the Intel GPU drivers. Remove the maintainer entry to match the current situation. Reviewed-by: Thomas Zimmermann Reviewed-by: Luca Ceresoli Link: https://lore.kernel.org/r/20261105142127.708219-5-mripard@kernel.org Signed-off-by: Maxime Ripard --- MAINTAINERS | 1 - 1 file changed, 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index a4bd4f2e4c829e..0086542acd5463 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -8943,7 +8943,6 @@ F: Documentation/devicetree/bindings/display/atmel/ F: drivers/gpu/drm/atmel-hlcdc/ DRM DRIVERS FOR BRIDGE CHIPS -M: Andrzej Hajda M: Neil Armstrong M: Robert Foss R: Laurent Pinchart From 7620e93a9d5a5c36636bd97c1fc734bbb27132f6 Mon Sep 17 00:00:00 2001 From: Maxime Ripard Date: Thu, 5 Nov 2026 15:21:26 +0100 Subject: [PATCH 0996/2102] MAINTAINERS: Remove myself for VC4 DRM driver MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I have not been actively involved in VC4 maintenance for a while. The driver is in good hands with Dave and Maíra. Remove my maintainer entry to match the current situation. Reviewed-by: Maíra Canal Reviewed-by: Thomas Zimmermann Reviewed-by: Luca Ceresoli Link: https://lore.kernel.org/r/20261105142127.708219-6-mripard@kernel.org Signed-off-by: Maxime Ripard --- MAINTAINERS | 1 - 1 file changed, 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index 0086542acd5463..ed0d381b0eea47 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -9205,7 +9205,6 @@ F: drivers/gpu/drm/v3d/ F: include/uapi/drm/v3d_drm.h DRM DRIVERS FOR VC4 -M: Maxime Ripard M: Dave Stevenson R: Maíra Canal R: Raspberry Pi Kernel Maintenance From 8f4557137542a343ce12ea5ca02b63e36f933cac Mon Sep 17 00:00:00 2001 From: Maxime Ripard Date: Thu, 5 Nov 2026 15:21:27 +0100 Subject: [PATCH 0997/2102] MAINTAINERS: Add Dmitry Baryshkov as bridge maintainer Dmitry has been one of the most active reviewers of the DRM bridge subsystem without having the maintainer status. Add him as a maintainer to match the current situation. Reviewed-by: Thomas Zimmermann Reviewed-by: Luca Ceresoli Link: https://lore.kernel.org/r/20261105142127.708219-7-mripard@kernel.org Signed-off-by: Maxime Ripard --- MAINTAINERS | 1 + 1 file changed, 1 insertion(+) diff --git a/MAINTAINERS b/MAINTAINERS index ed0d381b0eea47..58afe23cea516d 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -8944,6 +8944,7 @@ F: drivers/gpu/drm/atmel-hlcdc/ DRM DRIVERS FOR BRIDGE CHIPS M: Neil Armstrong +M: Dmitry Baryshkov M: Robert Foss R: Laurent Pinchart R: Jernej Skrabec From 11cb7e479a15b631cbe5f9038a28de0a1966853b Mon Sep 17 00:00:00 2001 From: Francesco Dolcini Date: Mon, 16 Nov 2026 17:24:08 +0100 Subject: [PATCH 0998/2102] phy: Revert "phy: freescale: fsl-samsung-hdmi: initialize default rate" This reverts commit c01ccf91b257741e9edc374a465126bae9ae4711. Programming the 74.25 MHz configuration at probe fails on i.MX8MP boards, the PHY probe aborts and HDMI is no longer available: fsl-samsung-hdmi-phy 32fdff00.phy: PLL failed to lock fsl-samsung-hdmi-phy 32fdff00.phy: error -ETIMEDOUT: failed to configure default rate fsl-samsung-hdmi-phy 32fdff00.phy: probe with driver fsl-samsung-hdmi-phy failed with error -110 Reported-by: Alexander Stein Closes: https://lore.kernel.org/all/13219248.O9o76ZdvQC@steina-w/ Fixes: c01ccf91b257 ("phy: freescale: fsl-samsung-hdmi: initialize default rate") Signed-off-by: Francesco Dolcini Tested-by: Luca Ceresoli Reviewed-by: Alexander Stein Link: https://patch.msgid.link/20261116162409.218059-1-francesco@dolcini.it Signed-off-by: Vinod Koul --- drivers/phy/freescale/phy-fsl-samsung-hdmi.c | 59 +++++--------------- 1 file changed, 15 insertions(+), 44 deletions(-) diff --git a/drivers/phy/freescale/phy-fsl-samsung-hdmi.c b/drivers/phy/freescale/phy-fsl-samsung-hdmi.c index 02539ad0b0fedf..ded142020e725f 100644 --- a/drivers/phy/freescale/phy-fsl-samsung-hdmi.c +++ b/drivers/phy/freescale/phy-fsl-samsung-hdmi.c @@ -44,8 +44,6 @@ #define MHZ (1000UL * 1000UL) #endif -#define PHY_DEFAULT_RATE 74250000 - #define PHY_PLL_DIV_REGS_NUM 7 struct phy_config { @@ -491,6 +489,17 @@ static int fsl_samsung_hdmi_phy_configure(struct fsl_samsung_hdmi_phy *phy, return ret; } +static unsigned long phy_clk_recalc_rate(struct clk_hw *hw, + unsigned long parent_rate) +{ + struct fsl_samsung_hdmi_phy *phy = to_fsl_samsung_hdmi_phy(hw); + + if (!phy->cur_cfg) + return 74250000; + + return phy->cur_cfg->pixclk; +} + /* Helper function to lookup the available fractional-divider rate */ static const struct phy_config *fsl_samsung_hdmi_phy_lookup_rate(unsigned long rate) { @@ -511,14 +520,6 @@ static const struct phy_config *fsl_samsung_hdmi_phy_lookup_rate(unsigned long r &phy_pll_cfg[i] : &phy_pll_cfg[i+1]); } -static unsigned long phy_clk_recalc_rate(struct clk_hw *hw, - unsigned long parent_rate) -{ - struct fsl_samsung_hdmi_phy *phy = to_fsl_samsung_hdmi_phy(hw); - - return phy->cur_cfg->pixclk; -} - static void fsl_samsung_hdmi_calculate_phy(struct phy_config *cal_phy, unsigned long rate, u8 p, u16 m, u8 s) { @@ -639,7 +640,6 @@ static int phy_clk_register(struct fsl_samsung_hdmi_phy *phy) static int fsl_samsung_hdmi_phy_probe(struct platform_device *pdev) { - const struct phy_config *default_cfg; struct fsl_samsung_hdmi_phy *phy; int ret; @@ -664,23 +664,6 @@ static int fsl_samsung_hdmi_phy_probe(struct platform_device *pdev) return dev_err_probe(phy->dev, PTR_ERR(phy->refclk), "failed to get ref clk\n"); - /* - * Establish the rate reported by recalc_rate() before registering the - * clock. Otherwise CCF may skip the first set_rate() when it requests - * the assumed default rate, leaving the PHY unconfigured. - */ - ret = clk_prepare_enable(phy->refclk); - if (ret) - return dev_err_probe(phy->dev, ret, - "failed to enable ref clk\n"); - - default_cfg = fsl_samsung_hdmi_phy_lookup_rate(PHY_DEFAULT_RATE); - ret = fsl_samsung_hdmi_phy_configure(phy, default_cfg); - clk_disable_unprepare(phy->refclk); - if (ret) - return dev_err_probe(phy->dev, ret, - "failed to configure default rate\n"); - pm_runtime_get_noresume(phy->dev); pm_runtime_set_active(phy->dev); pm_runtime_enable(phy->dev); @@ -719,7 +702,7 @@ static int __maybe_unused fsl_samsung_hdmi_phy_suspend(struct device *dev) static int __maybe_unused fsl_samsung_hdmi_phy_resume(struct device *dev) { struct fsl_samsung_hdmi_phy *phy = dev_get_drvdata(dev); - int ret; + int ret = 0; ret = clk_prepare_enable(phy->apbclk); if (ret) { @@ -727,23 +710,11 @@ static int __maybe_unused fsl_samsung_hdmi_phy_resume(struct device *dev) return ret; } - if (!phy->cur_cfg) - return 0; - - ret = clk_prepare_enable(phy->refclk); - if (ret) { - dev_err(phy->dev, "failed to enable ref clk\n"); - goto disable_apbclk; - } - - ret = fsl_samsung_hdmi_phy_configure(phy, phy->cur_cfg); - clk_disable_unprepare(phy->refclk); - if (!ret) - return 0; + if (phy->cur_cfg) + ret = fsl_samsung_hdmi_phy_configure(phy, phy->cur_cfg); -disable_apbclk: - clk_disable_unprepare(phy->apbclk); return ret; + } static DEFINE_RUNTIME_DEV_PM_OPS(fsl_samsung_hdmi_phy_pm_ops, From a10ec8dba77799a0460a4b3dfcac040ac452a325 Mon Sep 17 00:00:00 2001 From: Siddharth Chintamaneni Date: Tue, 17 Nov 2026 00:17:32 +0000 Subject: [PATCH 0999/2102] smb: client: fix busy dentry and inode on unmount from late oplock break During unmount, cifs_kill_sb() flushes cifsoplockd_wq and deferredclose_wq before waiting on cifs_sb->outstanding_rreq for in-flight netfs I/O requests to finish their cleanup_work in cifs_free_request(). While cifs_kill_sb() is waiting on outstanding_rreq, any cifsFileInfo referenced by an in-flight request (req->cfile) still has cfile->count >= 1 and remains on tcon->openFileList. If the SMB server sends a lease or oplock break for that file during this window, the demultiplex thread (cifsd) finds cfile on tcon->openFileList and calls cifs_queue_oplock_break(cfile), which takes a new reference on cfile and queues cfile->oplock_break onto cifsoplockd_wq after cifsoplockd_wq was already flushed: Thread 1 (umount) Thread 2 (cifsd) Thread 3 (workers) ----------------- ---------------- ------------------ cifs_kill_sb() flush(cifsoplockd_wq) flush(deferredclose_wq) wait(outstanding_rreq) [blocks: rreq == 1] SMB2 Lease Break finds cfile on list cifs_queue_oplock_break() queue(cifsoplockd_wq) cifsFileInfo_get(cfile) [cfile->count: 1 -> 2] cifs_oplock_break() ihold(inode) cifs_free_request() cifsFileInfo_put() [cfile->count: 2 -> 1] dec(outstanding_rreq) [wakes: rreq == 0] flush(serverclose_wq) flush(fileinfo_put_wq) kill_anon_super(sb) -> generic_shutdown_super() BUG: Dentry still in use (1) VFS: Busy inodes after unmount! Furthermore, cifs_oplock_break() itself holds the inode via ihold() after dropping cfile and may initiate writeback via filemap_fdatawrite(), spawning new netfs I/O requests. Fix this by counting queued oplock breaks in cifs_sb->outstanding_rreq from when cifs_queue_oplock_break() queues the work until cifs_oplock_break() finishes, so wait_var_event() in cifs_kill_sb() waits for both in-flight I/O requests and any late oplock breaks to complete. Fixes: 340cea84f691 ("cifs: open files should not hold ref on superblock") Cc: stable@vger.kernel.org Reported-by: Adam Kim Signed-off-by: Siddharth Chintamaneni Signed-off-by: Paulo Alcantara --- fs/smb/client/cifsfs.c | 10 +++++----- fs/smb/client/file.c | 2 ++ fs/smb/client/misc.c | 6 +++++- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/fs/smb/client/cifsfs.c b/fs/smb/client/cifsfs.c index 8cff7857b45095..9faba158f8b6a3 100644 --- a/fs/smb/client/cifsfs.c +++ b/fs/smb/client/cifsfs.c @@ -418,11 +418,11 @@ static void cifs_kill_sb(struct super_block *sb) flush_workqueue(deferredclose_wq); /* - * Wait for all in-flight netfs I/O requests to finish their - * cleanup_work so that any cifsFileInfo final puts they queue - * to fileinfo_put_wq/serverclose_wq have been queued, then - * drain the workqueue so the cfile dentry refs are dropped to - * avoid the busy dentry warning. + * Wait for all in-flight netfs I/O requests and oplock breaks + * to finish so that any cifsFileInfo final puts they queue to + * fileinfo_put_wq/serverclose_wq have been queued, then drain + * the workqueue so the cfile dentry refs are dropped to avoid + * the busy dentry warning. */ wait_var_event(&cifs_sb->outstanding_rreq, !atomic_read(&cifs_sb->outstanding_rreq)); diff --git a/fs/smb/client/file.c b/fs/smb/client/file.c index f51653cb6432a7..146ff2adfa2448 100644 --- a/fs/smb/client/file.c +++ b/fs/smb/client/file.c @@ -4023,6 +4023,8 @@ void cifs_oplock_break(struct work_struct *work) out: cifs_done_oplock_break(cinode); iput(inode); + if (atomic_dec_and_test(&cifs_sb->outstanding_rreq)) + wake_up_var(&cifs_sb->outstanding_rreq); } #ifdef CONFIG_SWAP diff --git a/fs/smb/client/misc.c b/fs/smb/client/misc.c index 4d0df73d15d7ac..a8f4c8644562fd 100644 --- a/fs/smb/client/misc.c +++ b/fs/smb/client/misc.c @@ -371,6 +371,8 @@ void cifs_put_writer(struct cifsInodeInfo *cinode) */ void cifs_queue_oplock_break(struct cifsFileInfo *cfile) { + struct cifs_sb_info *cifs_sb = CIFS_SB(cfile->dentry); + /* * Bump the handle refcount now while we hold the * open_file_lock to enforce the validity of it for the oplock @@ -379,8 +381,10 @@ void cifs_queue_oplock_break(struct cifsFileInfo *cfile) * * Only take a reference if the work is actually queued. */ - if (queue_work(cifsoplockd_wq, &cfile->oplock_break)) + if (queue_work(cifsoplockd_wq, &cfile->oplock_break)) { cifsFileInfo_get(cfile); + atomic_inc(&cifs_sb->outstanding_rreq); + } } void cifs_done_oplock_break(struct cifsInodeInfo *cinode) From 1fbbd14add401c70c178f0fa13016a3a53ef0de5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 18 Nov 2026 18:47:28 -0300 Subject: [PATCH 1000/2102] drm/vc4: Fix off-by-one in the shader record BO handle check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit validate_gl_shader_rec() accepts a shader BO handle equal to exec->bo_count, reading one entry past the end of exec->bo[] and using it as a GEM object. Reject handles that aren't below exec->bo_count. Cc: stable@vger.kernel.org Fixes: d5b1a78a772f ("drm/vc4: Add support for drawing 3D frames.") Reviewed-by: Iago Toral Quiroga Link: https://patch.msgid.link/20261118-vc4-icache-workaround-v1-1-5b8adc2c84fe@igalia.com Signed-off-by: Maíra Canal --- drivers/gpu/drm/vc4/vc4_validate.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/vc4/vc4_validate.c b/drivers/gpu/drm/vc4/vc4_validate.c index 565227657b43b4..0d2b08abf1ad0f 100644 --- a/drivers/gpu/drm/vc4/vc4_validate.c +++ b/drivers/gpu/drm/vc4/vc4_validate.c @@ -815,7 +815,7 @@ validate_gl_shader_rec(struct drm_device *dev, exec->shader_rec_size -= packet_size; for (i = 0; i < shader_reloc_count; i++) { - if (src_handles[i] > exec->bo_count) { + if (src_handles[i] >= exec->bo_count) { DRM_DEBUG("Shader handle %d too big\n", src_handles[i]); return -EINVAL; } From 15da41dff1f66a389d238db60a1c19fa83582d07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 18 Nov 2026 18:47:29 -0300 Subject: [PATCH 1001/2102] drm/vc4: Check for a validated shader before reading its thread mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit validate_gl_shader_rec() reads the thread mode from the validated_shader of the FS, VS and CS BOs before checking it for NULL. A shader record pointing at a BO not created by DRM_IOCTL_VC4_CREATE_SHADER_BO has no validated_shader, so userspace can trigger a NULL pointer dereference. Check that every shader BO has a validated shader before using it. Cc: stable@vger.kernel.org Fixes: c778cc5df944 ("drm/vc4: Add fragment shader threading support") Reviewed-by: Iago Toral Quiroga Link: https://patch.msgid.link/20261118-vc4-icache-workaround-v1-2-5b8adc2c84fe@igalia.com Signed-off-by: Maíra Canal --- drivers/gpu/drm/vc4/vc4_validate.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/vc4/vc4_validate.c b/drivers/gpu/drm/vc4/vc4_validate.c index 0d2b08abf1ad0f..4fe7e09dfe8eb8 100644 --- a/drivers/gpu/drm/vc4/vc4_validate.c +++ b/drivers/gpu/drm/vc4/vc4_validate.c @@ -823,6 +823,9 @@ validate_gl_shader_rec(struct drm_device *dev, bo[i] = to_drm_gem_dma_obj(exec->bo[src_handles[i]]); if (!bo[i]) return -EINVAL; + + if (!to_vc4_bo(&bo[i]->base)->validated_shader) + return -EINVAL; } for (i = shader_reloc_count; i < nr_relocs; i++) { bo[i] = vc4_use_bo(exec, src_handles[i]); @@ -843,7 +846,8 @@ validate_gl_shader_rec(struct drm_device *dev, } for (i = 0; i < shader_reloc_count; i++) { - struct vc4_validated_shader_info *validated_shader; + struct vc4_validated_shader_info *validated_shader = + to_vc4_bo(&bo[i]->base)->validated_shader; uint32_t o = shader_reloc_offsets[i]; uint32_t src_offset = *(uint32_t *)(pkt_u + o); uint32_t *texture_handles_u; @@ -858,10 +862,6 @@ validate_gl_shader_rec(struct drm_device *dev, return -EINVAL; } - validated_shader = to_vc4_bo(&bo[i]->base)->validated_shader; - if (!validated_shader) - return -EINVAL; - if (validated_shader->uniforms_src_size > exec->uniforms_size) { DRM_DEBUG("Uniforms src buffer overflow\n"); From c0e1ed41ad86cf5230d64dc5f2c6d2e3aeb59937 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 18 Nov 2026 18:47:30 -0300 Subject: [PATCH 1002/2102] drm/vc4: Start shader code at varying offsets in its BO MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit VC4 is affected by the HW erratum GFXH-16: the QPUs can get stuck in a loop where instruction cache loads are evicted before they are used. The QPUs of a slice share one instruction cache. Shader BOs are page aligned and the code always starts at offset 0, so instructions at the same position in different shaders end up mapping to the same cache sets. When the four QPUs of a slice run four different shaders, their fills evict each other, no instruction executes and the hangcheck resets the GPU. Place each shader's code at one of four offsets, 256 bytes apart, inside its BO, and add the offset when relocating the shader record. Shader code is position independent, as the validator only accepts relative branches. The offsets are tracked per client, so shaders a given client creates in sequence (which tend to run together) start in different sets. Notice that this approach makes the livelock unlikely, but not impossible. The next commit will address the remaining cases. On a Raspberry Pi 3 running the issue's reproducer, GPU resets went from dozens in an hour to none. Cc: stable@vger.kernel.org Fixes: 463873d57014 ("drm/vc4: Add an API for creating GPU shaders in GEM BOs.") Closes: https://gitlab.freedesktop.org/mesa/mesa/-/issues/16652 Reviewed-by: Iago Toral Quiroga Link: https://patch.msgid.link/20261118-vc4-icache-workaround-v1-3-5b8adc2c84fe@igalia.com Signed-off-by: Maíra Canal --- drivers/gpu/drm/vc4/vc4_bo.c | 43 +++++++++++++++++----- drivers/gpu/drm/vc4/vc4_drv.h | 10 ++++- drivers/gpu/drm/vc4/vc4_validate.c | 3 +- drivers/gpu/drm/vc4/vc4_validate_shaders.c | 7 ++-- 4 files changed, 48 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/vc4/vc4_bo.c b/drivers/gpu/drm/vc4/vc4_bo.c index da4b11b7ce9f79..2ab7c158b7ff44 100644 --- a/drivers/gpu/drm/vc4/vc4_bo.c +++ b/drivers/gpu/drm/vc4/vc4_bo.c @@ -17,6 +17,7 @@ */ #include +#include #include #include @@ -836,6 +837,19 @@ int vc4_mmap_bo_ioctl(struct drm_device *dev, void *data, return 0; } +/* + * QPUs sharing a slice's instruction cache can livelock evicting each + * other's fills. Considering that shader BOs are page aligned, any code + * at offset 0 maps every shader to the same cache sets. This makes a + * livelock more likely to happen due to GFXH-16. + * + * Start each shader at one of four offsets, cycled per client, to spread + * them across sets. The use of four different offsets is motivated by the + * number of QPUs per slice (4 QPUs). + */ +#define VC4_SHADER_OFFSET_STEP 256 +#define VC4_SHADER_OFFSET_NUM 4 + int vc4_create_shader_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) @@ -844,6 +858,7 @@ vc4_create_shader_bo_ioctl(struct drm_device *dev, void *data, struct vc4_file *vc4file = file_priv->driver_priv; struct vc4_dev *vc4 = to_vc4_dev(dev); struct vc4_bo *bo = NULL; + u32 offset, size; int ret; if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4)) @@ -865,29 +880,37 @@ vc4_create_shader_bo_ioctl(struct drm_device *dev, void *data, return -EINVAL; } + offset = ((u32)atomic_inc_return(&vc4file->shader_offset_idx) % + VC4_SHADER_OFFSET_NUM) * VC4_SHADER_OFFSET_STEP; + + if (check_add_overflow(offset, args->size, &size)) + return -EINVAL; + ret = vc4_grab_bin_bo(vc4, vc4file); if (ret) return ret; - bo = vc4_bo_create(dev, args->size, true, VC4_BO_TYPE_V3D_SHADER); + bo = vc4_bo_create(dev, size, true, VC4_BO_TYPE_V3D_SHADER); if (IS_ERR(bo)) return PTR_ERR(bo); bo->madv = VC4_MADV_WILLNEED; + bo->shader_offset = offset; - if (copy_from_user(bo->base.vaddr, - (void __user *)(uintptr_t)args->data, - args->size)) { + /* Clear the memory around the code, which may come from the BO + * cache. + */ + memset(bo->base.vaddr, 0, offset); + if (copy_from_user(bo->base.vaddr + offset, + (void __user *)(uintptr_t)args->data, + args->size)) { ret = -EFAULT; goto fail; } - /* Clear the rest of the memory from allocating from the BO - * cache. - */ - memset(bo->base.vaddr + args->size, 0, - bo->base.base.size - args->size); + memset(bo->base.vaddr + offset + args->size, 0, + bo->base.base.size - offset - args->size); - bo->validated_shader = vc4_validate_shader(&bo->base); + bo->validated_shader = vc4_validate_shader(&bo->base, offset); if (!bo->validated_shader) { ret = -EINVAL; goto fail; diff --git a/drivers/gpu/drm/vc4/vc4_drv.h b/drivers/gpu/drm/vc4/vc4_drv.h index f68486be08a6f4..62ce83322d1b29 100644 --- a/drivers/gpu/drm/vc4/vc4_drv.h +++ b/drivers/gpu/drm/vc4/vc4_drv.h @@ -255,6 +255,9 @@ struct vc4_bo { */ struct vc4_validated_shader_info *validated_shader; + /* Byte offset of the shader code in the BO. */ + u32 shader_offset; + /* One of enum vc4_kernel_bo_type, or VC4_BO_TYPE_COUNT + i * for user-allocated labels. */ @@ -802,6 +805,11 @@ struct vc4_file { struct xarray perfmons; bool bin_bo_used; + + /* Counter picking the start offset of the next shader BO's code, + * see vc4_create_shader_bo_ioctl(). + */ + atomic_t shader_offset_idx; }; static inline struct vc4_exec_info * @@ -1089,7 +1097,7 @@ bool vc4_check_tex_size(struct vc4_exec_info *exec, /* vc4_validate_shader.c */ struct vc4_validated_shader_info * -vc4_validate_shader(struct drm_gem_dma_object *shader_obj); +vc4_validate_shader(struct drm_gem_dma_object *shader_obj, u32 offset); /* vc4_perfmon.c */ void vc4_perfmon_get(struct vc4_perfmon *perfmon); diff --git a/drivers/gpu/drm/vc4/vc4_validate.c b/drivers/gpu/drm/vc4/vc4_validate.c index 4fe7e09dfe8eb8..b67ac1b212652e 100644 --- a/drivers/gpu/drm/vc4/vc4_validate.c +++ b/drivers/gpu/drm/vc4/vc4_validate.c @@ -854,7 +854,8 @@ validate_gl_shader_rec(struct drm_device *dev, void *uniform_data_u; uint32_t tex, uni; - *(uint32_t *)(pkt_v + o) = bo[i]->dma_addr + src_offset; + *(uint32_t *)(pkt_v + o) = bo[i]->dma_addr + src_offset + + to_vc4_bo(&bo[i]->base)->shader_offset; if (src_offset != 0) { DRM_DEBUG("Shaders must be at offset 0 of " diff --git a/drivers/gpu/drm/vc4/vc4_validate_shaders.c b/drivers/gpu/drm/vc4/vc4_validate_shaders.c index 66502a6a4a8e7b..a5a1c78eb73d63 100644 --- a/drivers/gpu/drm/vc4/vc4_validate_shaders.c +++ b/drivers/gpu/drm/vc4/vc4_validate_shaders.c @@ -779,7 +779,7 @@ vc4_handle_branch_target(struct vc4_shader_validation_state *validation_state) } struct vc4_validated_shader_info * -vc4_validate_shader(struct drm_gem_dma_object *shader_obj) +vc4_validate_shader(struct drm_gem_dma_object *shader_obj, u32 offset) { struct vc4_dev *vc4 = to_vc4_dev(shader_obj->base.dev); bool found_shader_end = false; @@ -793,8 +793,9 @@ vc4_validate_shader(struct drm_gem_dma_object *shader_obj) return NULL; memset(&validation_state, 0, sizeof(validation_state)); - validation_state.shader = shader_obj->vaddr; - validation_state.max_ip = shader_obj->base.size / sizeof(uint64_t); + validation_state.shader = shader_obj->vaddr + offset; + validation_state.max_ip = (shader_obj->base.size - offset) / + sizeof(uint64_t); reset_validation_state(&validation_state); From af1cf92e8617a7f7aa24b415596cbf64b76a12e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 18 Nov 2026 18:47:31 -0300 Subject: [PATCH 1003/2102] drm/vc4: Clear the slice caches before resetting a stalled GPU MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Starting shader code at varying offsets makes the GFXH-16 icache livelock unlikely, but not impossible. When the livelock happens, the QPUs make no progress and the hangcheck resets the GPU, losing the job. When the hangcheck finds no progress, clear the slice instruction and uniforms caches and check again before resetting. If the stall is a livelock, clearing the caches can break it and let the job continue. Drop round_jiffies_up() from the hangcheck timer, so checks run every 100 ms instead of at the next whole second. This shortens the screen freeze before the caches are cleared. Long jobs are unaffected: while the control lists advance, the hangcheck won't clear the caches or reset the GPU. Cc: stable@vger.kernel.org Fixes: d5b1a78a772f ("drm/vc4: Add support for drawing 3D frames.") Closes: https://gitlab.freedesktop.org/mesa/mesa/-/issues/16652 Reviewed-by: Iago Toral Quiroga Link: https://patch.msgid.link/20261118-vc4-icache-workaround-v1-4-5b8adc2c84fe@igalia.com Signed-off-by: Maíra Canal --- drivers/gpu/drm/vc4/vc4_drv.h | 5 +++++ drivers/gpu/drm/vc4/vc4_gem.c | 20 ++++++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/vc4/vc4_drv.h b/drivers/gpu/drm/vc4/vc4_drv.h index 62ce83322d1b29..dae325a3854d23 100644 --- a/drivers/gpu/drm/vc4/vc4_drv.h +++ b/drivers/gpu/drm/vc4/vc4_drv.h @@ -218,6 +218,11 @@ struct vc4_dev { struct { struct timer_list timer; struct work_struct reset_work; + + /* The instruction and uniforms caches were cleared at the + * last check that found no progress. + */ + bool caches_cleared; } hangcheck; struct drm_modeset_lock ctm_state_lock; diff --git a/drivers/gpu/drm/vc4/vc4_gem.c b/drivers/gpu/drm/vc4/vc4_gem.c index 956be198f8a7c8..9898eb1ef0774a 100644 --- a/drivers/gpu/drm/vc4/vc4_gem.c +++ b/drivers/gpu/drm/vc4/vc4_gem.c @@ -43,8 +43,7 @@ vc4_queue_hangcheck(struct drm_device *dev) { struct vc4_dev *vc4 = to_vc4_dev(dev); - mod_timer(&vc4->hangcheck.timer, - round_jiffies_up(jiffies + msecs_to_jiffies(100))); + mod_timer(&vc4->hangcheck.timer, jiffies + msecs_to_jiffies(100)); } struct vc4_hang_state { @@ -355,6 +354,7 @@ vc4_hangcheck_elapsed(struct timer_list *t) /* If idle, we can stop watching for hangs. */ if (!bin_exec && !render_exec) { + vc4->hangcheck.caches_cleared = false; spin_unlock_irqrestore(&vc4->job_lock, irqflags); return; } @@ -371,11 +371,27 @@ vc4_hangcheck_elapsed(struct timer_list *t) bin_exec->last_ct0ca = ct0ca; if (render_exec) render_exec->last_ct1ca = ct1ca; + + vc4->hangcheck.caches_cleared = false; + spin_unlock_irqrestore(&vc4->job_lock, irqflags); vc4_queue_hangcheck(dev); return; } + /* Clear the slice caches to workaround GFXH-16 */ + if (!vc4->hangcheck.caches_cleared) { + V3D_WRITE(V3D_SLCACTL, VC4_SET_FIELD(0xf, V3D_SLCACTL_ICC) | + VC4_SET_FIELD(0xf, V3D_SLCACTL_UCC)); + + vc4->hangcheck.caches_cleared = true; + spin_unlock_irqrestore(&vc4->job_lock, irqflags); + vc4_queue_hangcheck(dev); + return; + } + + vc4->hangcheck.caches_cleared = false; + spin_unlock_irqrestore(&vc4->job_lock, irqflags); /* We've gone too long with no progress, reset. This has to From 340ca61e9d31c31403013dc9190550d615844828 Mon Sep 17 00:00:00 2001 From: Siddharth Chintamaneni Date: Tue, 17 Nov 2026 00:17:33 +0000 Subject: [PATCH 1004/2102] smb: client: fix busy dentry on unmount from persistent handle reopen During unmount, cifs_kill_sb() waits on cifs_sb->outstanding_rreq for in-flight netfs I/O requests and oplock breaks to complete before flushing serverclose_wq and fileinfo_put_wq. While cifs_kill_sb() is waiting on outstanding_rreq, any cifsFileInfo referenced by an in-flight request (req->cfile) remains on tcon->openFileList. On a mount using persistent handles, if a reconnect runs on cifsiod_wq during this window, smb2_reconnect_server() calls cifs_reopen_persistent_handles(), which walks tcon->openFileList and takes a new reference on open_file via cifsFileInfo_get() to reopen the handle over the network: Thread 1 (umount) Thread 2 (cifsiod_wq) Thread 3 (workers) ----------------- --------------------- ------------------ cifs_kill_sb() wait(outstanding_rreq) [blocks: rreq == 1] smb2_reconnect_server() cifs_reopen_persistent_handles() finds open_file on list cifsFileInfo_get(open_file) [cfile->count: 1 -> 2] cifs_reopen_file() cifs_free_request() cifsFileInfo_put() [cfile->count: 2 -> 1] dec(outstanding_rreq) [wakes: rreq == 0] flush(serverclose_wq) flush(fileinfo_put_wq) kill_anon_super(sb) -> generic_shutdown_super() BUG: Dentry still in use (1) VFS: Busy inodes after unmount! Fix this by incrementing cifs_sb->outstanding_rreq when cifs_reopen_persistent_handles() takes a reference on open_file and decrementing it after cifsFileInfo_put(open_file), so wait_var_event() in cifs_kill_sb() waits for any in-progress persistent handle reopen to finish and queue its final put before draining fileinfo_put_wq. Fixes: 340cea84f691 ("cifs: open files should not hold ref on superblock") Cc: stable@vger.kernel.org Reported-by: Adam Kim Signed-off-by: Siddharth Chintamaneni Signed-off-by: Paulo Alcantara --- fs/smb/client/file.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/fs/smb/client/file.c b/fs/smb/client/file.c index 146ff2adfa2448..d272320436b3b2 100644 --- a/fs/smb/client/file.c +++ b/fs/smb/client/file.c @@ -2044,6 +2044,7 @@ bool cifs_reopen_persistent_handles(struct cifs_tcon *tcon) { struct cifsFileInfo *open_file, *tmp; + struct cifs_sb_info *cifs_sb; LIST_HEAD(tmp_list); bool retry = false; int rc; @@ -2060,12 +2061,15 @@ cifs_reopen_persistent_handles(struct cifs_tcon *tcon) list_for_each_entry(open_file, &tcon->openFileList, tlist) { if (!open_file->invalidHandle) continue; + cifs_sb = CIFS_SB(open_file->dentry); cifsFileInfo_get(open_file); + atomic_inc(&cifs_sb->outstanding_rreq); list_add_tail(&open_file->rlist, &tmp_list); } spin_unlock(&tcon->open_file_lock); list_for_each_entry_safe(open_file, tmp, &tmp_list, rlist) { + cifs_sb = CIFS_SB(open_file->dentry); /* do not flush */ rc = cifs_reopen_file(open_file, false, CIFS_REOPEN_BOUND | CIFS_REOPEN_NOWAIT); @@ -2075,6 +2079,8 @@ cifs_reopen_persistent_handles(struct cifs_tcon *tcon) } list_del_init(&open_file->rlist); cifsFileInfo_put(open_file); + if (atomic_dec_and_test(&cifs_sb->outstanding_rreq)) + wake_up_var(&cifs_sb->outstanding_rreq); } return retry; } From f834c81f108f8bdb0e3aa8375a536fb6dda56c70 Mon Sep 17 00:00:00 2001 From: ozgun kultekin Date: Tue, 17 Nov 2026 16:21:59 -0800 Subject: [PATCH 1005/2102] smb: client: do not let the server grow a write subrequest smb2_writev_callback() takes the byte count from the SMB2 WRITE response, masks it with 0xFFFF if it is larger than the request (for old OS/2 servers), and then copies it into wdata->subreq.len. A server can return a count that is still larger than the request after the mask, for example 0x8002 for a 5-byte write or 0xFFFF for a 4 KiB write, and the subrequest then covers data that was never sent. netfs uses the subrequest length to decide how far the write collector may advance. With a grown subrequest the collector moves collected_to past the data that was issued: netfs_writeback_unlock_folios() walks folio_queue slots that were never filled, and rolling_buffer_delete_spent() frees folio_queue segments that later in-flight subrequests still use. This is a use-after-free that a malicious or broken server triggers from an ordinary write: BUG: KASAN: slab-use-after-free in netfs_limit_iter+0xed4/0x1040 Read of size 1 at addr ff11000010561511 by task kworker/u8:4/63 Workqueue: events_unbound netfs_write_collection_worker netfs_limit_iter+0xed4/0x1040 netfs_retry_writes+0x1410/0x1e90 netfs_write_collection+0x2647/0x3880 netfs_write_collection_worker+0x1cd/0x3e0 Allocated by task 141: netfs_folioq_alloc+0x39a/0x470 rolling_buffer_init+0x29/0xc0 netfs_create_write_req+0x12f/0x840 Freed by task 42: rolling_buffer_delete_spent+0xb1/0x220 netfs_write_collection+0x1f62/0x3880 Never change the subrequest length from the response. If the count is still larger than the request after the mask, fail the write with -EIO and record it with a new write_overlarge trace point, like the read path does with read_overlarge. A short count still returns -ENOSPC as before. The folio_queue form of the use-after-free exists since commit cd0277ed0c18 ("netfs: Use new folio_queue data type and iterator instead of xarray iter"). Fixes: 3ee1a1fc3981 ("cifs: Cut over to using netfslib") Cc: stable@vger.kernel.org Signed-off-by: ozgun kultekin Reviewed-by: Namjae Jeon Signed-off-by: Paulo Alcantara --- fs/smb/client/smb2pdu.c | 17 +++++++++++++---- fs/smb/client/trace.h | 1 + 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/fs/smb/client/smb2pdu.c b/fs/smb/client/smb2pdu.c index b26bfb4bd91ae4..2f05ba613f34b5 100644 --- a/fs/smb/client/smb2pdu.c +++ b/fs/smb/client/smb2pdu.c @@ -5181,14 +5181,23 @@ smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) if (written > wdata->subreq.len) written &= 0xFFFF; + /* + * The server must not report more bytes than were sent. netfs + * uses the subrequest length to work out which folios this + * write has finished with, so it must not be changed here. + */ + if (written > wdata->subreq.len) { + result = smb_EIO2(smb_eio_trace_write_overlarge, + written, wdata->subreq.len); + break; + } + cifs_stats_bytes_written(tcon, written); - if (written < wdata->subreq.len) { + if (written < wdata->subreq.len) result = -ENOSPC; - } else if (written > 0) { - wdata->subreq.len = written; + else if (written > 0) __set_bit(NETFS_SREQ_MADE_PROGRESS, &wdata->subreq.flags); - } break; case MID_REQUEST_SUBMITTED: trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_req_submitted); diff --git a/fs/smb/client/trace.h b/fs/smb/client/trace.h index 5331ce6dc8b36c..18760a81949c82 100644 --- a/fs/smb/client/trace.h +++ b/fs/smb/client/trace.h @@ -153,6 +153,7 @@ EM(smb_eio_trace_user_iter, "user_iter") \ EM(smb_eio_trace_write_bad_buf_type, "write_bad_buf_type") \ EM(smb_eio_trace_write_mid_state_unknown, "write_mid_state_unknown") \ + EM(smb_eio_trace_write_overlarge, "write_overlarge") \ EM(smb_eio_trace_write_rsp_malformed, "write_rsp_malformed") \ E_(smb_eio_trace_write_too_far, "write_too_far") From 7c2a2268bd3ddf3b2c674ebb7557ae24c22309d7 Mon Sep 17 00:00:00 2001 From: Shawn Lin Date: Mon, 2 Nov 2026 08:51:29 +0800 Subject: [PATCH 1006/2102] phy: rockchip: snps-pcie3: Raise the SRAM init timeout The SRAM initialization of the PCIe3 PHY may take longer than the 500us currently allowed, especially on a slow power-up such as at low temperature. In that case the driver reports lock failed 0x..., check input refclk and power supply even though the input refclk and power supply are fine. Raise the timeout to 20ms and use a named constant for it, applied to both the RK3568 and RK3588 paths. A non-zero sleep interval (1ms) is passed to the polling helpers so the CPU is yielded between reads. With sleep_us == 0 the helpers tight-loop, which would otherwise burn the CPU during the now much longer wait. Fixes: 2e9bffc4f713 ("phy: rockchip: Support PCIe v3") Reviewed-by: Sebastian Reichel Reviewed-by: Manivannan Sadhasivam Signed-off-by: Shawn Lin Link: https://patch.msgid.link/20261102005129.3745527-1-shawn.lin@rock-chips.com Signed-off-by: Vinod Koul --- drivers/phy/rockchip/phy-rockchip-snps-pcie3.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/drivers/phy/rockchip/phy-rockchip-snps-pcie3.c b/drivers/phy/rockchip/phy-rockchip-snps-pcie3.c index 4e8ffd173096a4..ce7d8db2a7c5f6 100644 --- a/drivers/phy/rockchip/phy-rockchip-snps-pcie3.c +++ b/drivers/phy/rockchip/phy-rockchip-snps-pcie3.c @@ -18,6 +18,9 @@ #include #include #include +#include + +#define RK_PCIE_SRAM_INIT_TIMEOUT_US (20 * USEC_PER_MSEC) /* Register for RK3568 */ #define GRF_PCIE30PHY_CON1 0x4 @@ -127,7 +130,7 @@ static int rockchip_p3phy_rk3568_init(struct rockchip_p3phy_priv *priv) ret = regmap_read_poll_timeout(priv->phy_grf, GRF_PCIE30PHY_STATUS0, reg, SRAM_INIT_DONE(reg), - 0, 500); + 1000, RK_PCIE_SRAM_INIT_TIMEOUT_US); if (ret) dev_err(&priv->phy->dev, "%s: lock failed 0x%x, check input refclk and power supply\n", __func__, reg); @@ -187,11 +190,11 @@ static int rockchip_p3phy_rk3588_init(struct rockchip_p3phy_priv *priv) ret = regmap_read_poll_timeout(priv->phy_grf, RK3588_PCIE3PHY_GRF_PHY0_STATUS1, reg, RK3588_SRAM_INIT_DONE(reg), - 0, 500); + 1000, RK_PCIE_SRAM_INIT_TIMEOUT_US); ret |= regmap_read_poll_timeout(priv->phy_grf, RK3588_PCIE3PHY_GRF_PHY1_STATUS1, reg, RK3588_SRAM_INIT_DONE(reg), - 0, 500); + 1000, RK_PCIE_SRAM_INIT_TIMEOUT_US); if (ret) dev_err(&priv->phy->dev, "lock failed 0x%x, check input refclk and power supply\n", reg); From 5d2a5ad0367725f2833bbfcec25aae1e69d71ba1 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Wed, 18 Nov 2026 10:51:45 -0500 Subject: [PATCH 1007/2102] tcp: don't let __tcp_set_rto() return 0 tcp_retransmit_timer() backs off by doubling icsk_rto, so the backoff only works if icsk_rto is nonzero. __tcp_set_rto() adds srtt_us >> 3 and rttvar_us with no lower bound, and relies on tcp_rtt_estimator() to keep rttvar_us at tcp_rto_min() or above. But tcp_rto_min() returns 0 for a route with a locked RTAX_RTO_MIN of 0. A first RTT sample of 0 usec, which usec TS allows, then gives: srtt_us = max(1U, 0 << 3) = 1 rttvar_us = max(mdev_us, tcp_rto_min_us(sk)) = 0 __tcp_set_rto() = usecs_to_jiffies((1 >> 3) + 0) = 0 Keep the result from 0, so that the backoff recovers from any state of the RTT estimator. Do it in __tcp_set_rto() and not in tcp_set_rto(), since tcp_ld_RTO_revert() uses the same sum. The third caller, the linear timeouts of thin streams in tcp_retransmit_timer(), already clamps the result to tcp_rto_min(). Found by code inspection (Eric Dumazet), not reproduced. Fixed by LLM, and tested with existing kernel selftests. Fixes: 05bb1fad1cde ("[TCP]: Allow minimum RTO to be configurable via routing metrics.") Suggested-by: Eric Dumazet Signed-off-by: Chris Mason Link: https://patch.msgid.link/20261118155144.18393-2-mason@kernel.org Signed-off-by: Paolo Abeni --- include/net/tcp.h | 4 +++- net/ipv4/tcp_input.c | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/include/net/tcp.h b/include/net/tcp.h index 5c9203aae83417..6a714189bcc7fa 100644 --- a/include/net/tcp.h +++ b/include/net/tcp.h @@ -910,7 +910,9 @@ static inline void tcp_bound_rto(struct sock *sk) static inline u32 __tcp_set_rto(const struct tcp_sock *tp) { - return usecs_to_jiffies((tp->srtt_us >> 3) + tp->rttvar_us); + u32 rto = usecs_to_jiffies((tp->srtt_us >> 3) + tp->rttvar_us); + + return max(rto, 1U); } static inline unsigned long tcp_reqsk_timeout(struct request_sock *req) diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c index a2074a1af42228..f65697bc96c9da 100644 --- a/net/ipv4/tcp_input.c +++ b/net/ipv4/tcp_input.c @@ -1221,8 +1221,9 @@ void tcp_set_rto(struct sock *sk) * with correct one. It is exactly, which we pretend to do. */ - /* NOTE: clamping at TCP_RTO_MIN is not required, current algo - * guarantees that rto is higher. + /* NOTE: clamping at tcp_rto_min() is not required, tcp_rtt_estimator() + * applies it to rttvar_us. But rto must never be 0, which exponential + * backoff could not leave: __tcp_set_rto() takes care of that. */ tcp_bound_rto(sk); } From fa472d53d9b7aaff384d25f4ca86540d63815113 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Wed, 18 Nov 2026 10:51:46 -0500 Subject: [PATCH 1008/2102] tcp: clamp RTT samples in tcp_rtt_estimator() tcp_rtt_estimator() keeps its state in u32 fields, in microseconds. srtt_us holds 8 times the smoothed RTT, so it wraps at an RTT of 536.9 s. Samples can be larger than that: - For an ACK of retransmitted data, the sample is the timestamp clock minus TSecr, and tcp_rtt_tsopt_us() accepts a sample of up to 2,147 s. - For a SACK of a segment that was never retransmitted, the sample is the age of that segment. Samples from TSecr could wrap these fields when they still held jiffies. The age of a segment can wrap them since commit 740b0f1841f6 ("tcp: switch rtt estimations to usec resolution"), which took the wrap of the smoothed RTT from 2^29 jiffies to 2^29 us. The fix used here is to clamp each sample to 120 s, the largest possible RTO, in tcp_rtt_estimator(), where the samples of all sources meet. The smoothed RTT now saturates at 120 s. A path with a larger real RTT sees that in TCP_INFO, in the pacing rate and in the metrics cache. BPF programs on the RTT callback get the clamped sample too. Found by code inspection (Eric Dumazet), and confirmed with LLM generated reproducers on an unmodified kernel. Fixed by LLM, and tested with the reproducers and existing kernel selftests. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Fixes: 740b0f1841f6 ("tcp: switch rtt estimations to usec resolution") Signed-off-by: Chris Mason Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261118155144.18393-3-mason@kernel.org Signed-off-by: Paolo Abeni --- include/net/tcp.h | 7 +++++++ net/ipv4/tcp_input.c | 5 ++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/include/net/tcp.h b/include/net/tcp.h index 6a714189bcc7fa..a617a72ee2c6b4 100644 --- a/include/net/tcp.h +++ b/include/net/tcp.h @@ -164,6 +164,13 @@ static_assert((1 << ATO_BITS) > TCP_DELACK_MAX); #define TCP_TIMEOUT_MIN_US (2*USEC_PER_MSEC) /* Min TCP timeout in microsecs */ +/* Max RTT sample for tcp_rtt_estimator(). srtt_us holds 8 times the RTT, and + * mdev_us and rttvar_us up to 4 times its deviation, all in u32, like the sum + * in __tcp_set_rto(). A larger sample could not raise the RTO, which + * TCP_RTO_MAX bounds. + */ +#define TCP_RTT_MAX_US (TCP_RTO_MAX_SEC * USEC_PER_SEC) + #define TCP_TIMEOUT_INIT ((unsigned)(1*HZ)) /* RFC6298 2.1 initial RTO value */ #define TCP_TIMEOUT_FALLBACK ((unsigned)(3*HZ)) /* RFC 1122 initial RTO value, now * used as a fallback RTO for the diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c index f65697bc96c9da..e796497b84be84 100644 --- a/net/ipv4/tcp_input.c +++ b/net/ipv4/tcp_input.c @@ -1098,8 +1098,11 @@ static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb) static void tcp_rtt_estimator(struct sock *sk, long mrtt_us) { struct tcp_sock *tp = tcp_sk(sk); - long m = mrtt_us; /* RTT */ u32 srtt = tp->srtt_us; + long m; /* RTT */ + + mrtt_us = min(mrtt_us, TCP_RTT_MAX_US); + m = mrtt_us; /* The following amusing code comes from Jacobson's * article in SIGCOMM '88. Note that rtt and mdev From 1b91d9c09aa703d19995412ad41f23b8886bc608 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Wed, 18 Nov 2026 10:51:47 -0500 Subject: [PATCH 1009/2102] tcp: reject RTT samples from TSecr above 120 s tcp_rtt_tsopt_us() returns the timestamp clock minus TSecr as an RTT sample, and accepts up to 2,147 s. If TSecr echoes an old timestamp, the sample is the age of that timestamp, not an RTT. tcp_ack_update_rtt() takes this sample for an ACK of retransmitted data. tcp_rtt_estimator() clamps it to 120 s. The congestion control gets the sample unclamped, in rs->rtt_us. tcp_rcv_rtt_measure_ts() takes the same sample for the RTT estimate of the receive side. The fix used here is to reject a sample from TSecr above 120 s, for both callers of tcp_rtt_tsopt_us(). An ACK of retransmitted data whose TSecr is more than 120 s old now gives no RTT sample. So it no longer resets the backoff, as on a connection without timestamps. Found by LLM code inspection, and confirmed with LLM generated reproducers on an unmodified kernel. Fixed by LLM, and tested with the reproducers and existing kernel selftests. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Signed-off-by: Chris Mason Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261118155144.18393-4-mason@kernel.org Signed-off-by: Paolo Abeni --- net/ipv4/tcp_input.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c index e796497b84be84..69e038b9389aec 100644 --- a/net/ipv4/tcp_input.c +++ b/net/ipv4/tcp_input.c @@ -901,15 +901,16 @@ static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp) tp->rcv_rtt_est.time = tp->tcp_mstamp; } +/* A sample from TSecr above TCP_RTT_MAX_US is bogus, not large. */ static s32 tcp_rtt_tsopt_us(const struct tcp_sock *tp, u32 min_delta) { u32 delta, delta_us; delta = tcp_time_stamp_ts(tp) - tp->rx_opt.rcv_tsecr; if (tp->tcp_usec_ts) - return delta; + return delta <= TCP_RTT_MAX_US ? delta : -1; - if (likely(delta < INT_MAX / (USEC_PER_SEC / TCP_TS_HZ))) { + if (likely(delta <= TCP_RTT_MAX_US / (USEC_PER_SEC / TCP_TS_HZ))) { if (!delta) delta = min_delta; delta_us = delta * (USEC_PER_SEC / TCP_TS_HZ); From f22d5042faa6b03df9586074e0322db60973933b Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Wed, 18 Nov 2026 10:51:48 -0500 Subject: [PATCH 1010/2102] tcp: clamp the samples in tcp_rcv_rtt_update() tcp_rcv_rtt_update() starts with sample << 3 in u32 arithmetic, so a sample of 536.9 s or more wraps. tcp_rcv_rtt_measure() can hand it one. Its sample is the time the sender took to fill one receive window, and a low rate flow can take longer than that. This caller only looks for a minimum, so the wrapped value is kept whenever it is below the current estimate. A 540 s sample ends up as an estimate of about 3.1 s. Clamp the sample to TCP_RTT_MAX_US in tcp_rcv_rtt_update(), like tcp_rtt_estimator() does on the send side. That covers both callers, and the smoothed estimate now tops out at 8 * 120 s, which fits in a u32. Found by code inspection (Eric Dumazet), who also suggested the fix. Confirmed with an LLM generated reproducer on an unmodified kernel, and tested with the reproducer and existing kernel selftests. Fixes: 645f4c6f2ebd ("tcp: switch rcv_rtt_est and rcvq_space to high resolution timestamps") Suggested-by: Eric Dumazet Signed-off-by: Chris Mason Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261118155144.18393-5-mason@kernel.org Signed-off-by: Paolo Abeni --- net/ipv4/tcp_input.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c index 69e038b9389aec..d9a66a1342efdd 100644 --- a/net/ipv4/tcp_input.c +++ b/net/ipv4/tcp_input.c @@ -857,7 +857,11 @@ void tcp_initialize_rcv_mss(struct sock *sk) static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep) { u32 new_sample, old_sample = tp->rcv_rtt_est.rtt_us; - long m = sample << 3; + long m; + + /* Keep sample << 3 and the smoothed estimate within u32. */ + sample = min(sample, TCP_RTT_MAX_US); + m = sample << 3; if (old_sample == 0 || m < old_sample) { new_sample = m; From 314b35c8173cb5726ae4c3dd401d982e16de9482 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Wed, 18 Nov 2026 10:51:49 -0500 Subject: [PATCH 1011/2102] tcp: bound the rto_min of a route in tcp_rto_min() For a route with a locked RTAX_RTO_MIN, tcp_rto_min() returns the metric as it is, and that can be any 32-bit number of milliseconds. All other ways to set the minimum RTO have a nonzero floor: the tcp_rto_min_us sysctl, TCP_RTO_MIN_US and TCP_BPF_RTO_MIN. Both ends of that range give us trouble. With an rto_min of 0, tcp_init_metrics() can start a connection with an RTO of 0, if the cached RTT is below one jiffy: icsk_rto = crtt + max(2 * crtt, tcp_rto_min(sk)) = 0 It sets icsk_rto itself, so the lower bound in __tcp_set_rto() does not help here. At the other end, tcp_rto_min_us() and the sum in __tcp_set_rto() are u32 values in usec, so an rto_min of more than about 71 minutes does not fit. Clamp a locked rto_min to the range from one jiffy to TCP_RTO_MAX in tcp_rto_min(). ip_metrics_convert() could reject these values instead, as it does for a locked cwnd of 0. But a route with "rto_min lock 0" is accepted today and mostly works, so that would break existing setups. A route still shows the rto_min that it was given, while TCP uses one jiffy or 120 s. Found by LLM code inspection, and confirmed with LLM generated reproducers on an unmodified kernel. Fixed by LLM, and tested with the reproducers and existing kernel selftests. Fixes: 05bb1fad1cde ("[TCP]: Allow minimum RTO to be configurable via routing metrics.") Signed-off-by: Chris Mason Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261118155144.18393-6-mason@kernel.org Signed-off-by: Paolo Abeni --- include/net/tcp.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/include/net/tcp.h b/include/net/tcp.h index a617a72ee2c6b4..27de546dc802de 100644 --- a/include/net/tcp.h +++ b/include/net/tcp.h @@ -939,7 +939,8 @@ static inline u32 tcp_rto_min(const struct sock *sk) u32 rto_min = READ_ONCE(inet_csk(sk)->icsk_rto_min); if (dst && dst_metric_locked(dst, RTAX_RTO_MIN)) - rto_min = dst_metric_rtt(dst, RTAX_RTO_MIN); + rto_min = clamp(dst_metric_rtt(dst, RTAX_RTO_MIN), + 1, TCP_RTO_MAX); return rto_min; } From b10c986f1769287270de248548476f6dc2275d59 Mon Sep 17 00:00:00 2001 From: Chris J Arges Date: Wed, 18 Nov 2026 08:32:27 -0600 Subject: [PATCH 1012/2102] net: prevent receive header offset overflow during decapsulation Repeated decapsulation can leave skb->data far from skb->head while the remaining packet data is still valid. Since the skb header positions are 16-bit offsets, a later header update can truncate and make header access use unrelated bytes and eventually crash. Limit receive headroom to 32 KiB. This is well beyond the headroom of normal packets while allowing the networking stack to pull enough headers in a single pass without overflowing 16-bit header offsets. Tunnel decapsulation re-enters __netif_receive_skb_core(), so its check protects nested IPIP and GRE. FOU and GUE bypass receive core, so check their IPv4 and IPv6 resubmission paths too. Together, these checks prevent 16-bit header-offset truncation in cases of repeated decapsulation. Report these rejections with the SKB_RX_HEADROOM drop reason. Fixes: 1a37e412a022 ("net: Use 16bits for *_headers fields of struct skbuff") Cc: stable@kernel.org Suggested-by: Eric Dumazet Signed-off-by: Chris J Arges Reviewed-by: Ido Schimmel Link: https://patch.msgid.link/20261118-prevent_rx_header_offset_overflow-v1-1-92a5be55f994@cloudflare.com Signed-off-by: Paolo Abeni --- include/linux/skbuff.h | 1 + include/net/dropreason-core.h | 6 ++++++ net/core/dev.c | 4 ++++ net/ipv4/ip_input.c | 6 ++++++ net/ipv6/ip6_input.c | 4 ++++ 5 files changed, 21 insertions(+) diff --git a/include/linux/skbuff.h b/include/linux/skbuff.h index 6787fcf6ac3e43..adc61f5e3e850f 100644 --- a/include/linux/skbuff.h +++ b/include/linux/skbuff.h @@ -268,6 +268,7 @@ SKB_WITH_OVERHEAD((PAGE_SIZE << (ORDER)) - (X)) #define SKB_MAX_HEAD(X) (SKB_MAX_ORDER((X), 0)) #define SKB_MAX_ALLOC (SKB_MAX_ORDER(0, 2)) +#define SKB_MAX_RX_HEADROOM (U16_MAX / 2) /* return minimum truesize of one skb containing X bytes of data */ #define SKB_TRUESIZE(X) ((X) + \ diff --git a/include/net/dropreason-core.h b/include/net/dropreason-core.h index fa2fe89905573a..903d6a3a0ff198 100644 --- a/include/net/dropreason-core.h +++ b/include/net/dropreason-core.h @@ -128,6 +128,7 @@ FN(PSP_INPUT) \ FN(PSP_OUTPUT) \ FN(RECURSION_LIMIT) \ + FN(SKB_RX_HEADROOM) \ FNe(MAX) /** @@ -612,6 +613,11 @@ enum skb_drop_reason { * itself. */ SKB_DROP_REASON_RECURSION_LIMIT, + /** + * @SKB_DROP_REASON_SKB_RX_HEADROOM: accumulated receive headroom + * exceeds the header-offset budget. + */ + SKB_DROP_REASON_SKB_RX_HEADROOM, /** * @SKB_DROP_REASON_MAX: the maximum of core drop reasons, which * shouldn't be used as a real 'reason' - only for tracing code gen diff --git a/net/core/dev.c b/net/core/dev.c index 3c58db732761a6..6140fd9d11cd0e 100644 --- a/net/core/dev.c +++ b/net/core/dev.c @@ -6223,6 +6223,10 @@ static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc, trace_netif_receive_skb(skb); orig_dev = skb->dev; + if (unlikely(skb_headroom(skb) > SKB_MAX_RX_HEADROOM)) { + drop_reason = SKB_DROP_REASON_SKB_RX_HEADROOM; + goto drop; + } skb_reset_network_header(skb); #if !defined(CONFIG_DEBUG_NET) diff --git a/net/ipv4/ip_input.c b/net/ipv4/ip_input.c index 9860178752b8cc..c74886b1f4453d 100644 --- a/net/ipv4/ip_input.c +++ b/net/ipv4/ip_input.c @@ -207,6 +207,12 @@ void ip_protocol_deliver_rcu(struct net *net, struct sk_buff *skb, int protocol) ret = INDIRECT_CALL_2(ipprot->handler, tcp_v4_rcv, udp_rcv, skb); if (ret < 0) { + if (unlikely(skb_headroom(skb) > SKB_MAX_RX_HEADROOM)) { + __IP_INC_STATS(net, IPSTATS_MIB_INDISCARDS); + kfree_skb_reason(skb, + SKB_DROP_REASON_SKB_RX_HEADROOM); + return; + } protocol = -ret; goto resubmit; } diff --git a/net/ipv6/ip6_input.c b/net/ipv6/ip6_input.c index d332ec60f9150e..6dc1211eade6ac 100644 --- a/net/ipv6/ip6_input.c +++ b/net/ipv6/ip6_input.c @@ -479,6 +479,10 @@ void ip6_protocol_deliver_rcu(struct net *net, struct sk_buff *skb, int nexthdr, ret = INDIRECT_CALL_2(ipprot->handler, tcp_v6_rcv, udpv6_rcv, skb); if (ret > 0) { + if (unlikely(skb_headroom(skb) > SKB_MAX_RX_HEADROOM)) { + SKB_DR_SET(reason, SKB_RX_HEADROOM); + goto discard; + } if (ipprot->flags & INET6_PROTO_FINAL) { /* Not an extension header, most likely UDP * encapsulation. Use return value as nexthdr From cfdd650c5dabbd2f59a0e916aa8ef3f1965a3b4b Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:16:07 -0500 Subject: [PATCH 1013/2102] Bluetooth: mgmt: Fix read_index_list() buffer overflow The first pass counts only configured controllers, but HCI_UNCONFIGURED can change before the second pass, which may then write more entries than were allocated. Size the buffer from the total number of controllers as read_unconf_index_list() already does. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-7841362e-9b8f-465f-aa22-e99c315231e2 Fixes: 73d1df2a7a10 ("Bluetooth: Add support for Read Unconfigured Index List command") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/mgmt.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c index 260ef2a45719b6..aad9e1b00e66b7 100644 --- a/net/bluetooth/mgmt.c +++ b/net/bluetooth/mgmt.c @@ -444,10 +444,8 @@ static int read_index_list(struct sock *sk, struct hci_dev *hdev, void *data, read_lock(&hci_dev_list_lock); count = 0; - list_for_each_entry(d, &hci_dev_list, list) { - if (!hci_dev_test_flag(d, HCI_UNCONFIGURED)) - count++; - } + list_for_each_entry(d, &hci_dev_list, list) + count++; rp_len = sizeof(*rp) + (2 * count); rp = kmalloc(rp_len, GFP_ATOMIC); From 6a296a4658124490d7dddd2b751e5f9ae5c5aec7 Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:16:07 -0500 Subject: [PATCH 1014/2102] Bluetooth: hci_core: Take req_sync lock in hci_power_on() hci_powered_update_sync() issues synchronous HCI commands but was called without hci_req_sync_lock(), racing with other request users. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-1baf7393-3aeb-4fa5-806f-19cea743b9f3 Fixes: cf75ad8b41d2 ("Bluetooth: hci_sync: Convert MGMT_SET_POWERED") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_core.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/net/bluetooth/hci_core.c b/net/bluetooth/hci_core.c index 846e6eb2d1bc8c..f0e23b59b60001 100644 --- a/net/bluetooth/hci_core.c +++ b/net/bluetooth/hci_core.c @@ -915,7 +915,9 @@ static void hci_power_on(struct work_struct *work) hci_dev_test_flag(hdev, HCI_MGMT) && hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF)) { cancel_delayed_work(&hdev->power_off); + hci_req_sync_lock(hdev); err = hci_powered_update_sync(hdev); + hci_req_sync_unlock(hdev); mgmt_power_on(hdev, err); return; } From 8984b72f9508b2d03c58a82d73881b5e1e5f5bc4 Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:16:19 -0500 Subject: [PATCH 1015/2102] Bluetooth: hci_sync: Lock the lookup in hci_disable_ext_adv_instance_sync() hci_disable_ext_adv_instance_sync() calls hci_find_adv_instance() and dereferences the instance without hdev->lock, racing with the removal of the instance. Look the instance up under the lock and only use the values copied while it is held. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-a364929c-cd00-492a-a83c-5425d042b09f Fixes: cba6b758711c ("Bluetooth: hci_sync: Make use of hci_cmd_sync_queue set 2") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_sync.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index 44ce776890d162..919c15efe91d2e 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -1226,16 +1226,26 @@ static int hci_disable_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance) struct hci_cp_ext_adv_set *set; u8 data[sizeof(*cp) + sizeof(*set) * 1]; u8 size; - struct adv_info *adv = NULL; + u8 handle = instance; /* If request specifies an instance that doesn't exist, fail */ if (instance > 0) { + struct adv_info *adv; + bool enabled = false; + + hci_dev_lock(hdev); adv = hci_find_adv_instance(hdev, instance); + if (adv) { + enabled = adv->enabled; + handle = adv->handle; + } + hci_dev_unlock(hdev); + if (!adv) return -EINVAL; /* If not enabled there is nothing to do */ - if (!adv->enabled) + if (!enabled) return 0; } @@ -1248,7 +1258,7 @@ static int hci_disable_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance) cp->num_of_sets = !!instance; cp->enable = 0x00; - set->handle = adv ? adv->handle : instance; + set->handle = handle; size = sizeof(*cp) + sizeof(*set) * cp->num_of_sets; From c592dfe9637c65eeaff4c9f6fd869f39ad7ae472 Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:16:32 -0500 Subject: [PATCH 1016/2102] Bluetooth: hci_sync: Hold hdev->lock in hci_schedule_adv_instance_sync() The advertising instance returned by hci_find_adv_instance() was dereferenced without hdev->lock and could be freed concurrently. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-616b1f8e-06ec-4634-a907-5eb4e82f66df Fixes: cba6b758711c ("Bluetooth: hci_sync: Make use of hci_cmd_sync_queue set 2") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_sync.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index 919c15efe91d2e..9aac6c3e8b29c7 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -2207,9 +2207,13 @@ int hci_schedule_adv_instance_sync(struct hci_dev *hdev, u8 instance, if (hdev->adv_instance_timeout) return -EBUSY; + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); - if (!adv) + if (!adv) { + hci_dev_unlock(hdev); return -ENOENT; + } /* A zero timeout means unlimited advertising. As long as there is * only one instance, duration should be ignored. We still set a timeout @@ -2239,6 +2243,8 @@ int hci_schedule_adv_instance_sync(struct hci_dev *hdev, u8 instance, secs_to_jiffies(timeout)); } + hci_dev_unlock(hdev); + /* If we're just re-scheduling the same instance again then do not * execute any HCI commands. This happens when a single instance is * being advertised. From e428ab70fb3398e835e5d70ba4839e7c06583b83 Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:16:33 -0500 Subject: [PATCH 1017/2102] Bluetooth: SMP: Serialize link key updates from smp_notify_keys() smp_notify_keys() runs from the L2CAP RX path without hdev->lock, yet hci_add_link_key() and the debug key removal modify hdev->link_keys and dereference entries returned by hci_find_link_key(), so a concurrent unpair or Load Link Keys can free the entry being updated. hdev->lock can't be taken there since it is ordered before the l2cap channel lock held by the SMP receive path (see smp_user_confirm_reply()). Add a dedicated link_keys_lock protecting the writers of hdev->link_keys (add, remove and clear). SMP holds it while it adds the key, notifies mgmt and removes a debug key, so the key can't go away meanwhile, and the debug key removed by hci_link_key_notify_evt() is deleted by reference with hci_del_link_key() since a lookup by address skips the keys that are blocked. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-7482a666-d2a0-44a4-9e0d-05354860a5fa Fixes: 6a77083af57f ("Bluetooth: Add support for LE SC key generation") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- include/net/bluetooth/hci_core.h | 6 ++++ net/bluetooth/hci_core.c | 62 +++++++++++++++++++++++++++++--- net/bluetooth/hci_event.c | 3 +- net/bluetooth/smp.c | 11 ++++-- 4 files changed, 74 insertions(+), 8 deletions(-) diff --git a/include/net/bluetooth/hci_core.h b/include/net/bluetooth/hci_core.h index fd4da751a24fc4..db6397a0d9f5f1 100644 --- a/include/net/bluetooth/hci_core.h +++ b/include/net/bluetooth/hci_core.h @@ -561,6 +561,8 @@ struct hci_dev { struct list_head accept_list; struct list_head uuids; struct list_head link_keys; + /* Serializes the writers of link_keys, see hci_add_link_key() */ + struct mutex link_keys_lock; struct list_head long_term_keys; struct list_head identity_resolving_keys; struct mutex remote_oob_lock; @@ -1921,6 +1923,10 @@ struct hci_conn_params *hci_pend_le_action_lookup(struct list_head *list, void hci_uuids_clear(struct hci_dev *hdev); void hci_link_keys_clear(struct hci_dev *hdev); +struct link_key *__hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, + bdaddr_t *bdaddr, u8 *val, u8 type, + u8 pin_len, bool *persistent); +void hci_del_link_key(struct hci_dev *hdev, struct link_key *key); u8 *hci_conn_key_enc_size(struct hci_conn *conn); struct link_key *hci_find_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr); struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, diff --git a/net/bluetooth/hci_core.c b/net/bluetooth/hci_core.c index f0e23b59b60001..9a3b1e36e69190 100644 --- a/net/bluetooth/hci_core.c +++ b/net/bluetooth/hci_core.c @@ -1017,10 +1017,14 @@ void hci_link_keys_clear(struct hci_dev *hdev) { struct link_key *key, *tmp; + mutex_lock(&hdev->link_keys_lock); + list_for_each_entry_safe(key, tmp, &hdev->link_keys, list) { list_del_rcu(&key->list); kfree_rcu(key, rcu); } + + mutex_unlock(&hdev->link_keys_lock); } void hci_smp_ltks_clear(struct hci_dev *hdev) @@ -1237,13 +1241,16 @@ struct smp_irk *hci_find_irk_by_addr(struct hci_dev *hdev, bdaddr_t *bdaddr, return irk_to_return; } -struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, - bdaddr_t *bdaddr, u8 *val, u8 type, - u8 pin_len, bool *persistent) +/* This function requires the caller holds hdev->link_keys_lock */ +struct link_key *__hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, + bdaddr_t *bdaddr, u8 *val, u8 type, + u8 pin_len, bool *persistent) { struct link_key *key, *old_key; u8 old_key_type; + lockdep_assert_held(&hdev->link_keys_lock); + old_key = hci_find_link_key(hdev, bdaddr); if (old_key) { old_key_type = old_key->type; @@ -1286,6 +1293,26 @@ struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, return key; } +/* The writers of hdev->link_keys are serialized with hdev->link_keys_lock + * so the list can be modified without hdev->lock (e.g. from SMP, where it + * can't be taken after the l2cap channel lock). The returned key is only + * safe to use while hdev->lock is held, callers without it must use + * __hci_add_link_key() and keep hdev->link_keys_lock while using the key. + */ +struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, + bdaddr_t *bdaddr, u8 *val, u8 type, + u8 pin_len, bool *persistent) +{ + struct link_key *key; + + mutex_lock(&hdev->link_keys_lock); + key = __hci_add_link_key(hdev, conn, bdaddr, val, type, pin_len, + persistent); + mutex_unlock(&hdev->link_keys_lock); + + return key; +} + struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 addr_type, u8 type, u8 authenticated, u8 tk[16], u8 enc_size, __le16 ediv, __le64 rand) @@ -1347,18 +1374,44 @@ int hci_remove_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr) { struct link_key *key; + mutex_lock(&hdev->link_keys_lock); + key = hci_find_link_key(hdev, bdaddr); - if (!key) + if (!key) { + mutex_unlock(&hdev->link_keys_lock); return -ENOENT; + } BT_DBG("%s removing %pMR", hdev->name, bdaddr); list_del_rcu(&key->list); kfree_rcu(key, rcu); + mutex_unlock(&hdev->link_keys_lock); + return 0; } +/* Remove a key previously returned by hci_add_link_key(), unlike + * hci_remove_link_key() this also works for keys that are blocked. + */ +void hci_del_link_key(struct hci_dev *hdev, struct link_key *key) +{ + struct link_key *k; + + mutex_lock(&hdev->link_keys_lock); + + list_for_each_entry(k, &hdev->link_keys, list) { + if (k == key) { + list_del_rcu(&key->list); + kfree_rcu(key, rcu); + break; + } + } + + mutex_unlock(&hdev->link_keys_lock); +} + int hci_remove_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 bdaddr_type) { struct smp_ltk *k, *tmp; @@ -2507,6 +2560,7 @@ struct hci_dev *hci_alloc_dev_priv(int sizeof_priv) hdev->def_page_scan_window = 0x0012; mutex_init(&hdev->lock); + mutex_init(&hdev->link_keys_lock); mutex_init(&hdev->req_lock); mutex_init(&hdev->mgmt_pending_lock); mutex_init(&hdev->remote_oob_lock); diff --git a/net/bluetooth/hci_event.c b/net/bluetooth/hci_event.c index 10c8b7b8e3299d..638576aab15774 100644 --- a/net/bluetooth/hci_event.c +++ b/net/bluetooth/hci_event.c @@ -4960,8 +4960,7 @@ static void hci_link_key_notify_evt(struct hci_dev *hdev, void *data, */ if (key->type == HCI_LK_DEBUG_COMBINATION && !hci_dev_test_flag(hdev, HCI_KEEP_DEBUG_KEYS)) { - list_del_rcu(&key->list); - kfree_rcu(key, rcu); + hci_del_link_key(hdev, key); goto unlock; } diff --git a/net/bluetooth/smp.c b/net/bluetooth/smp.c index 6ccb38b1d56d3c..6e25b3b65094dd 100644 --- a/net/bluetooth/smp.c +++ b/net/bluetooth/smp.c @@ -1092,8 +1092,13 @@ static void smp_notify_keys(struct l2cap_conn *conn) else type = HCI_LK_UNAUTH_COMBINATION_P256; - key = hci_add_link_key(hdev, smp->conn->hcon, &hcon->dst, - smp->link_key, type, 0, &persistent); + /* hdev->lock can't be taken here since it is ordered before + * the l2cap channel lock held by the caller. + */ + mutex_lock(&hdev->link_keys_lock); + + key = __hci_add_link_key(hdev, smp->conn->hcon, &hcon->dst, + smp->link_key, type, 0, &persistent); if (key) { mgmt_new_link_key(hdev, key, persistent); @@ -1106,6 +1111,8 @@ static void smp_notify_keys(struct l2cap_conn *conn) kfree_rcu(key, rcu); } } + + mutex_unlock(&hdev->link_keys_lock); } } From e8764a6946341e9ee809393386e7b815179c5f5f Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:16:34 -0500 Subject: [PATCH 1018/2102] Bluetooth: SMP: Check smp_data before using SMP_DEV() hdev->smp_data is NULL when the SMP channel could not be registered, so receiving a Pairing Request/Response with the OOB flag set would dereference NULL through SMP_DEV(). Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-9bc9da90-02a8-4a87-a603-87d0a4cf464c Fixes: 94f14e472812 ("Bluetooth: SMP: Fix trying to use non-existent local OOB data") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/smp.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/net/bluetooth/smp.c b/net/bluetooth/smp.c index 6e25b3b65094dd..02ca45b21c3431 100644 --- a/net/bluetooth/smp.c +++ b/net/bluetooth/smp.c @@ -1761,7 +1761,8 @@ static u8 smp_cmd_pairing_req(struct l2cap_conn *conn, struct sk_buff *skb) * successfully received our local OOB data - therefore set the * flag to indicate that local OOB is in use. */ - if (req->oob_flag == SMP_OOB_PRESENT && SMP_DEV(hdev)->local_oob) + if (req->oob_flag == SMP_OOB_PRESENT && hdev->smp_data && + SMP_DEV(hdev)->local_oob) set_bit(SMP_FLAG_LOCAL_OOB, &smp->flags); /* SMP over BR/EDR requires special treatment */ @@ -1957,7 +1958,8 @@ static u8 smp_cmd_pairing_rsp(struct l2cap_conn *conn, struct sk_buff *skb) * successfully received our local OOB data - therefore set the * flag to indicate that local OOB is in use. */ - if (rsp->oob_flag == SMP_OOB_PRESENT && SMP_DEV(hdev)->local_oob) + if (rsp->oob_flag == SMP_OOB_PRESENT && hdev->smp_data && + SMP_DEV(hdev)->local_oob) set_bit(SMP_FLAG_LOCAL_OOB, &smp->flags); smp->prsp[0] = SMP_CMD_PAIRING_RSP; From 8a119ba64f33dd9ab265d3b978f7811a80b7fe8a Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:16:34 -0500 Subject: [PATCH 1019/2102] Bluetooth: SMP: Don't create the BR/EDR channel while unregistered smp_force_bredr() created a BR/EDR SMP channel even when the controller was powered off or not LE capable, leaving a stale channel that smp_register() later warns about and leaks. Only create it when SMP is registered and guard the removal; smp_register() creates it on power on if the flag is set. Since smp_unregister() runs with hdev->lock take it around smp_register() as well so they can't race with each other nor with smp_force_bredr(). Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-a921c99c-0b41-485c-91a4-1c6e54b45b0b Fixes: 300acfdec916 ("Bluetooth: Introduce force_bredr_smp debugfs option for testing") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_sync.c | 2 ++ net/bluetooth/smp.c | 20 ++++++++++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index 9aac6c3e8b29c7..89a65d7c7b5426 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -3892,7 +3892,9 @@ int hci_powered_update_sync(struct hci_dev *hdev) * registration is required so that LE SMP can clearly decide if * the public address or static address is used. */ + hci_dev_lock(hdev); smp_register(hdev); + hci_dev_unlock(hdev); err = hci_write_ssp_mode_sync(hdev, 0x01); if (err) diff --git a/net/bluetooth/smp.c b/net/bluetooth/smp.c index 02ca45b21c3431..1caebdd8e0a66b 100644 --- a/net/bluetooth/smp.c +++ b/net/bluetooth/smp.c @@ -3381,20 +3381,28 @@ int smp_force_bredr(struct hci_dev *hdev, bool enable) if (enable == hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP)) return -EALREADY; + /* The channels are only registered while the controller is powered + * and LE capable. Otherwise just record the flag, smp_register() will + * create the BR/EDR channel on the next power on. + */ if (enable) { struct l2cap_chan *chan; - chan = smp_add_cid(hdev, L2CAP_CID_SMP_BREDR); - if (IS_ERR(chan)) - return PTR_ERR(chan); + if (hdev->smp_data && !hdev->smp_bredr_data) { + chan = smp_add_cid(hdev, L2CAP_CID_SMP_BREDR); + if (IS_ERR(chan)) + return PTR_ERR(chan); - hdev->smp_bredr_data = chan; + hdev->smp_bredr_data = chan; + } } else { struct l2cap_chan *chan; chan = hdev->smp_bredr_data; - hdev->smp_bredr_data = NULL; - smp_del_chan(chan); + if (chan) { + hdev->smp_bredr_data = NULL; + smp_del_chan(chan); + } } hci_dev_change_flag(hdev, HCI_FORCE_BREDR_SMP); From ad7c1f067df2772d73a3a34218a8f5db57ceb41c Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:16:35 -0500 Subject: [PATCH 1020/2102] Bluetooth: hci_event: Validate sent command length in LE Set Ext Adv Enable hci_cc_le_set_ext_adv_enable() read num_of_sets and the set entries from the last sent command without checking its length. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-42bcc244-62e6-4295-802c-f9a512ca49a3 Fixes: de181e887ac2 ("Bluetooth: Impmlement extended adv enable") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_event.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/net/bluetooth/hci_event.c b/net/bluetooth/hci_event.c index 638576aab15774..039bcea98a5adf 100644 --- a/net/bluetooth/hci_event.c +++ b/net/bluetooth/hci_event.c @@ -1671,14 +1671,16 @@ static u8 hci_cc_le_set_ext_adv_enable(struct hci_dev *hdev, void *data, struct hci_cp_ext_adv_set *set; struct adv_info *adv = NULL, *n; struct hci_ev_status *rp = data; + size_t len; bt_dev_dbg(hdev, "status 0x%2.2x", rp->status); if (rp->status) return rp->status; - cp = hci_sent_cmd_data(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE); - if (!cp) + cp = hci_sent_cmd_data_len(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE, &len); + if (!cp || len < sizeof(*cp) || + len < sizeof(*cp) + cp->num_of_sets * sizeof(*set)) return rp->status; set = (void *)cp->data; From a1a0ef3ba8e802060bfc2b0ebf131a2cf98c3b71 Mon Sep 17 00:00:00 2001 From: Suyuan Wang Date: Thu, 19 Nov 2026 04:00:48 +0000 Subject: [PATCH 1021/2102] smb: client: don't use read data that failed signature verification When smb2_readv_callback() finds a bad signature, it sets the error in rdata->result but leaves rdata->got_bytes alone. Further down, a short read that reaches the remote EOF clears the error again: size_t trans = rdata->subreq.transferred + rdata->got_bytes; if (trans < rdata->subreq.len && rdata->subreq.start + trans >= netfs_read_remote_i_size(inode)) { rdata->result = 0; and got_bytes is then added to subreq.transferred. So the last part of a file, or all of a small one, is returned even though its signature is wrong. Clearing got_bytes is not enough on its own. If the read starts at or past the cached remote size, for example because the file has grown on the server since the size was last fetched, the check above still matches and the error turns into EOF, or into a zero-filled tail when NETFS_SREQ_CLEAR_TAIL is set. Clear got_bytes when the signature check fails, as the retry path in the same function already does, and only treat a short read as hitting the remote EOF when the read itself succeeded. That is what commit 1da29f2c39b6 ("netfs, cifs: Fix handling of short DIO read") describes: "clear the error if a short read occurred without error and the read-to file position is now at the remote inode size". Found with a static analysis tool and checked by hand. Fixes: 1da29f2c39b6 ("netfs, cifs: Fix handling of short DIO read") Cc: stable@vger.kernel.org Co-developed-by: Kaixuan Li Signed-off-by: Kaixuan Li Signed-off-by: Suyuan Wang Signed-off-by: Paulo Alcantara --- fs/smb/client/smb2pdu.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/fs/smb/client/smb2pdu.c b/fs/smb/client/smb2pdu.c index 2f05ba613f34b5..7b7d25364e2072 100644 --- a/fs/smb/client/smb2pdu.c +++ b/fs/smb/client/smb2pdu.c @@ -4819,6 +4819,8 @@ smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) rc); rdata->subreq.error = rc; rdata->result = rc; + /* the data can't be trusted, don't count it */ + rdata->got_bytes = 0; if (is_replayable_error(rc)) { trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed); @@ -4898,9 +4900,8 @@ smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) __set_bit(NETFS_SREQ_CLEAR_TAIL, &rdata->subreq.flags); } else { size_t trans = rdata->subreq.transferred + rdata->got_bytes; - if (trans < rdata->subreq.len && + if (!rdata->result && trans < rdata->subreq.len && rdata->subreq.start + trans >= netfs_read_remote_i_size(inode)) { - rdata->result = 0; if (rdata->subreq.start + trans >= i_size_read(inode)) __set_bit(NETFS_SREQ_HIT_EOF, &rdata->subreq.flags); else From b2a9f2d43bbdf6dcf178e300c815816a4fe4447d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= Date: Wed, 8 Jul 2026 12:57:10 +0200 Subject: [PATCH 1022/2102] clang-format: Fix formatting of guard() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous fix was overzealous and included guard() along with scoped_guard(), but only the later takes curly braces. The original fix introduced this issue: - guard(rcu)(); + guard(rcu) + (); This is especially visible with security/landlock/*.[ch] which is fully formatted with clang-format. Cc: Andrew Morton Cc: Günther Noack Cc: Ingo Molnar Cc: Miguel Ojeda Cc: Peter Zijlstra Cc: stable@vger.kernel.org Fixes: 99df2a8eba34 ("clang-format: fix formatting of guard() and scoped_guard() statements") Closes: https://lore.kernel.org/r/20260702.Eibibi4the9j@digikod.net Reviewed-by: Bart Van Assche Link: https://patch.msgid.link/20260708105713.2073335-1-mic@digikod.net Signed-off-by: Mickaël Salaün --- .clang-format | 1 - 1 file changed, 1 deletion(-) diff --git a/.clang-format b/.clang-format index 395292ab2ac634..ce170c0af7179b 100644 --- a/.clang-format +++ b/.clang-format @@ -481,7 +481,6 @@ ForEachMacros: - 'genradix_for_each' - 'genradix_for_each_from' - 'genradix_for_each_reverse' - - 'guard' - 'hash_for_each' - 'hash_for_each_possible' - 'hash_for_each_possible_rcu' From 008b903f55eb4bdb1af77070bb93e6e1dfa9145d Mon Sep 17 00:00:00 2001 From: Jarkko Sakkinen Date: Mon, 16 Nov 2026 15:35:20 +0100 Subject: [PATCH 1023/2102] s390/cert_store: Hold keyring->sem while reading the keyring invalidate_keyring_keys() does not hold keyring->sem while calling keyring_read(), which is contrary to what keyring assumes from its callers, and can lead to recurring bugs. KEY_FLAG_KEEP alone does not protect from e.g. the following call path: 1. keyctl_keyring_move() 2. key_move() 3. __key_unlink() Address the issue by guarding the critical section. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Acked-by: Alexander Gordeev Signed-off-by: Jarkko Sakkinen Signed-off-by: Heiko Carstens Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index 998f2da5617500..d35b1ea22507df 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -320,13 +321,17 @@ static int invalidate_keyring_keys(struct key *keyring) struct key *current_key; int rc; - keyring_payload_len = key_type_keyring.read(keyring, NULL, 0); - num_keys = keyring_payload_len / sizeof(key_serial_t); - key_array = kzalloc_objs(key_serial_t, num_keys); - if (!key_array) - return -ENOMEM; + scoped_guard(rwsem_read, &keyring->sem) { + keyring_payload_len = key_type_keyring.read(keyring, NULL, 0); + num_keys = keyring_payload_len / sizeof(key_serial_t); + + key_array = kzalloc_objs(key_serial_t, num_keys); + if (!key_array) + return -ENOMEM; + + rc = key_type_keyring.read(keyring, (char *)key_array, keyring_payload_len); + } - rc = key_type_keyring.read(keyring, (char *)key_array, keyring_payload_len); if (rc != keyring_payload_len) { pr_dbf_msg("Couldn't read keyring payload"); goto out; From 1be070c4dc6edbfb015e72156fadb49fbaef47b9 Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:21 +0100 Subject: [PATCH 1024/2102] s390/cert_store: Fix return code handling in invalidate_keyring_keys() Add missing error handling in case key_type_keyring.read() returns an error. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Heiko Carstens Reviewed-by: Jarkko Sakkinen Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index d35b1ea22507df..89cc3a1683a325 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -316,15 +316,16 @@ static struct key *get_user_session_keyring(void) static int invalidate_keyring_keys(struct key *keyring) { unsigned long num_keys, key_index; - size_t keyring_payload_len; + long keyring_payload_len, rc; key_serial_t *key_array; struct key *current_key; - int rc; scoped_guard(rwsem_read, &keyring->sem) { keyring_payload_len = key_type_keyring.read(keyring, NULL, 0); - num_keys = keyring_payload_len / sizeof(key_serial_t); + if (keyring_payload_len <= 0) + return keyring_payload_len; + num_keys = keyring_payload_len / sizeof(key_serial_t); key_array = kzalloc_objs(key_serial_t, num_keys); if (!key_array) return -ENOMEM; @@ -334,6 +335,7 @@ static int invalidate_keyring_keys(struct key *keyring) if (rc != keyring_payload_len) { pr_dbf_msg("Couldn't read keyring payload"); + rc = rc < 0 ? rc : -EINVAL; goto out; } @@ -345,7 +347,7 @@ static int invalidate_keyring_keys(struct key *keyring) key_put(current_key); rc = key_unlink(keyring, current_key); if (rc) { - pr_dbf_msg("Couldn't unlink key %08x: %d", current_key->serial, rc); + pr_dbf_msg("Couldn't unlink key %08x: %ld", current_key->serial, rc); break; } } From 69e0c49331475082e0b92cbf320e3e5a1deb889e Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:22 +0100 Subject: [PATCH 1025/2102] s390/cert_store: Fix potential use-after-free in invalidate_keyring_keys() Drop the refcount of current_key behind all users of current_key which dereference it, like e.g. error logging. Fixes a potential use-after-free bug. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Heiko Carstens Reviewed-by: Jarkko Sakkinen Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index 89cc3a1683a325..e5060777ce6f5e 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -344,12 +344,12 @@ static int invalidate_keyring_keys(struct key *keyring) pr_dbf_msg("Invalidating key %08x", current_key->serial); key_invalidate(current_key); - key_put(current_key); rc = key_unlink(keyring, current_key); - if (rc) { + if (rc) pr_dbf_msg("Couldn't unlink key %08x: %ld", current_key->serial, rc); + key_put(current_key); + if (rc) break; - } } out: kfree(key_array); From 2a102f513a68ef6771e1cf107c7f98985686ad71 Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:23 +0100 Subject: [PATCH 1026/2102] s390/cert_store: Check key_lookup() return code in invalidate_keyring_keys() keyring->sem is released after writing the key serial numbers into key_array. Keys corresponding to those serial numbers may have been removed before key_lookup() is called. Therefore check the return code of key_lookup() before dereferencing it. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Heiko Carstens Reviewed-by: Jarkko Sakkinen Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index e5060777ce6f5e..8eb32497ca24d0 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -339,8 +339,11 @@ static int invalidate_keyring_keys(struct key *keyring) goto out; } + rc = 0; for (key_index = 0; key_index < num_keys; key_index++) { current_key = key_lookup(key_array[key_index]); + if (IS_ERR(current_key)) + continue; pr_dbf_msg("Invalidating key %08x", current_key->serial); key_invalidate(current_key); From a1e3a45cac3d847e8ae81cc7e9db1b7b2c547a0e Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:24 +0100 Subject: [PATCH 1027/2102] s390/cert_store: Unlink before invalidate in invalidate_keyring_keys() If a key is invalidated, the key garbage collector may remove its link from the keyring at any time. If that happens the subsequent key_unlink() fails. invalidate_keyring_keys() would then incorrectly return an error, which would lead to unregistering the cert_store key type. Unlink the key first and invalidate it afterwards to avoid this race. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Heiko Carstens Reviewed-by: Jarkko Sakkinen Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index 8eb32497ca24d0..a69eccf6affd35 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -346,10 +346,10 @@ static int invalidate_keyring_keys(struct key *keyring) continue; pr_dbf_msg("Invalidating key %08x", current_key->serial); - key_invalidate(current_key); rc = key_unlink(keyring, current_key); if (rc) pr_dbf_msg("Couldn't unlink key %08x: %ld", current_key->serial, rc); + key_invalidate(current_key); key_put(current_key); if (rc) break; From f992716c4c767a89b6be32e24ee6e4e41ad99da4 Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:25 +0100 Subject: [PATCH 1028/2102] s390/cert_store: Fix cs_keyring reference leak in fill_cs_keyring() create_cs_keyring() returns cs_keyring with a reference held. On the success path fill_cs_keyring() never drops it, leaking the reference. The keyring is kept alive by its link to the session keyring. Drop the reference after add_certificates_to_keyring() returns. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Heiko Carstens Reviewed-by: Jarkko Sakkinen Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index a69eccf6affd35..386fe39fe8bd1f 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -723,6 +723,7 @@ static int fill_cs_keyring(void) if (rc) goto cleanup_cs_keyring; + key_put(cs_keyring); goto out; cleanup_cs_keyring: From 92d377a611766f6ab7b9a63a530aa7bbd434abbb Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:26 +0100 Subject: [PATCH 1029/2102] s390/cert_store: Fix potential use-after-free caused by find_cs_keyring() find_cs_keyring() drops the refcount of cs_keyring before returning it. Which means that callers operate on potentially already freed memory. Let find_cs_keyring() return cs_keyring with a reference. Since cleanup_cs_keys() now performs a balanced put via find_cs_keyring(), remove the separate cleanup_cs_keyring error label in fill_cs_keyring() and drop the reference unconditionally instead. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Heiko Carstens Reviewed-by: Jarkko Sakkinen Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index 386fe39fe8bd1f..b720dd26a5578b 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -367,17 +367,13 @@ static struct key *find_cs_keyring(void) cs_keyring_ref = keyring_search(make_key_ref(get_user_session_keyring(), true), &key_type_keyring, CERT_STORE_KEYRING_NAME, false); - if (!IS_ERR(cs_keyring_ref)) { - cs_keyring = key_ref_to_ptr(cs_keyring_ref); - key_ref_put(cs_keyring_ref); - goto found; - } + if (!IS_ERR(cs_keyring_ref)) + return key_ref_to_ptr(cs_keyring_ref); + /* Search default locations: thread, process, session keyrings */ cs_keyring = request_key(&key_type_keyring, CERT_STORE_KEYRING_NAME, NULL); if (IS_ERR(cs_keyring)) return NULL; - key_put(cs_keyring); -found: return cs_keyring; } @@ -720,14 +716,12 @@ static int fill_cs_keyring(void) goto cleanup_keys; rc = add_certificates_to_keyring(vcssb, cs_keyring); + key_put(cs_keyring); if (rc) - goto cleanup_cs_keyring; + goto cleanup_keys; - key_put(cs_keyring); goto out; -cleanup_cs_keyring: - key_put(cs_keyring); cleanup_keys: cleanup_cs_keys(); out: From 1a58d930c82fcaf3a6a9e9daf21c7ae9ee088d7e Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:27 +0100 Subject: [PATCH 1030/2102] s390/cert_store: Remove unnecessary static specifier in create_cs_keyring() The local variable cs_keyring in create_cs_keyring() never reuses its assigned value, therefore remove the static specifier. Callers are serialized by cs_refresh_lock, so this does not fix a bug. Even though this is not a bug fix, this contains a Fixes tag since other commits require this as a prereq. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Heiko Carstens Reviewed-by: Jarkko Sakkinen Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index b720dd26a5578b..aefbefb40c74e9 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -401,7 +401,7 @@ static void cleanup_cs_keys(void) static struct key *create_cs_keyring(void) { - static struct key *cs_keyring; + struct key *cs_keyring; /* Cleanup previous cs_keyring and all associated keys if any. */ cleanup_cs_keys(); From 8256791b74e701361398a8d0e43c55bdabadc5ca Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:28 +0100 Subject: [PATCH 1031/2102] s390/cert_store: Fix error handling of get_user_session_keyring() create_cs_keyring(), cleanup_cs_keys(), and find_cs_keyring() all pass the return value of get_user_session_keyring() to other functions without checking it. This can lead to dereferencing an error pointer. Check the return value before using it. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Heiko Carstens Reviewed-by: Jarkko Sakkinen Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index aefbefb40c74e9..d11637c8506371 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -361,15 +361,18 @@ static int invalidate_keyring_keys(struct key *keyring) static struct key *find_cs_keyring(void) { + struct key *cs_keyring, *us_keyring; key_ref_t cs_keyring_ref; - struct key *cs_keyring; - - cs_keyring_ref = keyring_search(make_key_ref(get_user_session_keyring(), true), - &key_type_keyring, CERT_STORE_KEYRING_NAME, - false); - if (!IS_ERR(cs_keyring_ref)) - return key_ref_to_ptr(cs_keyring_ref); + us_keyring = get_user_session_keyring(); + if (!IS_ERR(us_keyring)) { + cs_keyring_ref = keyring_search(make_key_ref(us_keyring, true), + &key_type_keyring, + CERT_STORE_KEYRING_NAME, + false); + if (!IS_ERR(cs_keyring_ref)) + return key_ref_to_ptr(cs_keyring_ref); + } /* Search default locations: thread, process, session keyrings */ cs_keyring = request_key(&key_type_keyring, CERT_STORE_KEYRING_NAME, NULL); if (IS_ERR(cs_keyring)) @@ -379,7 +382,7 @@ static struct key *find_cs_keyring(void) static void cleanup_cs_keys(void) { - struct key *cs_keyring; + struct key *cs_keyring, *us_keyring; cs_keyring = find_cs_keyring(); if (!cs_keyring) @@ -395,21 +398,26 @@ static void cleanup_cs_keys(void) keyring_clear(cs_keyring); key_invalidate(cs_keyring); + us_keyring = get_user_session_keyring(); + if (!IS_ERR(us_keyring)) + key_unlink(us_keyring, cs_keyring); key_put(cs_keyring); - key_unlink(get_user_session_keyring(), cs_keyring); } static struct key *create_cs_keyring(void) { - struct key *cs_keyring; + struct key *cs_keyring, *us_keyring; /* Cleanup previous cs_keyring and all associated keys if any. */ cleanup_cs_keys(); + us_keyring = get_user_session_keyring(); + if (IS_ERR(us_keyring)) + return NULL; cs_keyring = keyring_alloc(CERT_STORE_KEYRING_NAME, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(), (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_SET_KEEP, - NULL, get_user_session_keyring()); + NULL, us_keyring); if (IS_ERR(cs_keyring)) { pr_dbf_msg("Can't allocate cert_store keyring"); return NULL; From aa7ee9e9cf17fcc7b0af55424aba6f0abd065fa7 Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:29 +0100 Subject: [PATCH 1032/2102] s390/cert_store: Fix keyring refcount handling in get_user_session_keyring() get_user_session_keyring() drops the reference of the looked up keyring before returning it. Callers therefore use the keyring without holding a reference. Return the keyring with the reference and let callers drop the reference. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Heiko Carstens Reviewed-by: Jarkko Sakkinen Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index d11637c8506371..ec6352528a2baa 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -308,7 +308,6 @@ static struct key *get_user_session_keyring(void) PTR_ERR(us_keyring_ref)); return ERR_PTR(-ENOKEY); } - key_ref_put(us_keyring_ref); return key_ref_to_ptr(us_keyring_ref); } @@ -370,6 +369,7 @@ static struct key *find_cs_keyring(void) &key_type_keyring, CERT_STORE_KEYRING_NAME, false); + key_put(us_keyring); if (!IS_ERR(cs_keyring_ref)) return key_ref_to_ptr(cs_keyring_ref); } @@ -399,8 +399,10 @@ static void cleanup_cs_keys(void) keyring_clear(cs_keyring); key_invalidate(cs_keyring); us_keyring = get_user_session_keyring(); - if (!IS_ERR(us_keyring)) + if (!IS_ERR(us_keyring)) { key_unlink(us_keyring, cs_keyring); + key_put(us_keyring); + } key_put(cs_keyring); } @@ -418,6 +420,7 @@ static struct key *create_cs_keyring(void) (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_SET_KEEP, NULL, us_keyring); + key_put(us_keyring); if (IS_ERR(cs_keyring)) { pr_dbf_msg("Can't allocate cert_store keyring"); return NULL; From 5ac71bb84e34337d7be280d2c06ff9cae77b7bcf Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:30 +0100 Subject: [PATCH 1033/2102] s390/cert_store: Do not search the process keyrings for the cert_store keyring find_cs_keyring() first searches the user session keyring for the cert_store keyring, and falls back to request_key(), which searches the thread, process and session keyrings of the calling task. Any keyring named "cert_store" found this way is accepted. cleanup_cs_keys() then invalidates and unlinks all of its keys, and clears and invalidates the keyring itself, without checking permissions. If the refresh is triggered by a task which inherited a session keyring that contains a keyring named "cert_store" not created by this code, this keyring and its keys are destroyed. create_cs_keyring() always links the keyring into the user session keyring, so the first search is sufficient. Remove the request_key() fallback. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Heiko Carstens Reviewed-by: Jarkko Sakkinen Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index ec6352528a2baa..551b538ea930f4 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -360,7 +360,7 @@ static int invalidate_keyring_keys(struct key *keyring) static struct key *find_cs_keyring(void) { - struct key *cs_keyring, *us_keyring; + struct key *us_keyring; key_ref_t cs_keyring_ref; us_keyring = get_user_session_keyring(); @@ -373,11 +373,7 @@ static struct key *find_cs_keyring(void) if (!IS_ERR(cs_keyring_ref)) return key_ref_to_ptr(cs_keyring_ref); } - /* Search default locations: thread, process, session keyrings */ - cs_keyring = request_key(&key_type_keyring, CERT_STORE_KEYRING_NAME, NULL); - if (IS_ERR(cs_keyring)) - return NULL; - return cs_keyring; + return NULL; } static void cleanup_cs_keys(void) From 8b4e340f7742c8c3b12353e882ad5d4d25c7acc9 Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:31 +0100 Subject: [PATCH 1034/2102] s390/cert_store: Validate hash length in check_certificate_valid() Validate that vc_hash_length is SHA256_DIGEST_SIZE before checking the hash and use sizeof(hash) in memcmp(). This avoids an out-of-bounds read if vc_hash_length is incorrect. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Acked-by: Alexander Gordeev Signed-off-by: Heiko Carstens Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index 551b538ea930f4..ecfb7641d42744 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -261,13 +261,11 @@ static int diag320(unsigned long subcode, void *addr) static int check_certificate_hash(const struct vce *vce) { u8 hash[SHA256_DIGEST_SIZE]; - u16 vc_hash_length; u8 *vce_hash; vce_hash = (u8 *)vce + vce->vce_hdr.vc_hash_offset; - vc_hash_length = vce->vce_hdr.vc_hash_length; sha256((u8 *)vce + vce->vce_hdr.vc_offset, vce->vce_hdr.vc_length, hash); - if (memcmp(vce_hash, hash, vc_hash_length) == 0) + if (memcmp(vce_hash, hash, sizeof(hash)) == 0) return 0; pr_dbf_msg("SHA256 hash of received certificate does not match"); @@ -293,6 +291,10 @@ static int check_certificate_valid(const struct vce *vce) pr_dbf_msg("Hash type is not supported"); return -EINVAL; } + if (vce->vce_hdr.vc_hash_length != SHA256_DIGEST_SIZE) { + pr_dbf_msg("Hash length is not supported"); + return -EINVAL; + } return check_certificate_hash(vce); } From 9d263bd8ddc31c9c3ebe3612df575d70848f5772 Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:32 +0100 Subject: [PATCH 1035/2102] s390/cert_store: Fix max_vcxe_length output in pr_dbf_vcssb() Print the correct value for max_vcxe_length. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Acked-by: Alexander Gordeev Signed-off-by: Heiko Carstens Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index ecfb7641d42744..996ca30256292a 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -225,7 +225,7 @@ static void pr_dbf_vcssb(const struct vcssb *s) pr_dbf_msg("total_vc_index_count: %u", s->total_vc_index_count); pr_dbf_msg("max_vc_index_count: %u", s->max_vc_index_count); pr_dbf_msg("max_vce_length: %u", s->max_vce_length); - pr_dbf_msg("max_vcxe_length: %u", s->max_vce_length); + pr_dbf_msg("max_vcxe_length: %u", s->max_vcxe_length); pr_dbf_msg("max_single_vcb_length: %u", s->max_single_vcb_length); pr_dbf_msg("total_vcb_length: %u", s->total_vcb_length); pr_dbf_msg("max_single_vcxb_length: %u", s->max_single_vcxb_length); From 539cf27f0b090d84438b7da9045a271a947192ed Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:33 +0100 Subject: [PATCH 1036/2102] s390/cert_store: Fix out-of-bounds read in pr_dbf_vce() pr_dbf_vce() dumps the last 128 bytes of the certificate data of a Verification Certificate Entry (VCE) into a debug area. However the address calculation is wrong: vce_length is the length of the whole entry including the header, while cert_data_buf starts behind the header. Therefore the dump starts at the end of the entry and starts reading behind it. Dump the last 128 bytes of the entry like intended. Limit dumps to the data length. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Acked-by: Alexander Gordeev Signed-off-by: Heiko Carstens Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index 996ca30256292a..12fc0ee87f3b0a 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -181,6 +181,7 @@ static void pr_dbf_vce(const struct vce *e) { unsigned char vc_name[VC_NAME_LEN_BYTES + 1]; char log_string[VC_NAME_LEN_BYTES + 40]; + u32 data_len = 0; pr_dbf_msg("VCE Header:"); pr_dbf_msg("vce_hdr.vce_length: %d", e->vce_hdr.vce_length); @@ -206,11 +207,13 @@ static void pr_dbf_vce(const struct vce *e) debug_text_event(cert_store_hexdump, 3, log_string); /* Certificate data. */ + if (e->vce_hdr.vce_length > sizeof(e->vce_hdr)) + data_len = e->vce_hdr.vce_length - sizeof(e->vce_hdr); debug_text_event(cert_store_hexdump, 3, "VCE: Certificate data start"); - debug_event(cert_store_hexdump, 3, (u8 *)e->cert_data_buf, 128); + debug_event(cert_store_hexdump, 3, (u8 *)e->cert_data_buf, min(data_len, 128U)); debug_text_event(cert_store_hexdump, 3, "VCE: Certificate data end"); - debug_event(cert_store_hexdump, 3, - (u8 *)e->cert_data_buf + e->vce_hdr.vce_length - 128, 128); + if (data_len > 128) + debug_event(cert_store_hexdump, 3, (u8 *)e + e->vce_hdr.vce_length - 128, 128); } static void pr_dbf_vcssb(const struct vcssb *s) From 2c1f57bce05244165f406e45982bbcd036071d3b Mon Sep 17 00:00:00 2001 From: Heiko Carstens Date: Mon, 16 Nov 2026 15:35:34 +0100 Subject: [PATCH 1037/2102] s390/cert_store: Initialize ism array in query_diag320_subcodes() The Installed Subcode Block returned by DIAG 320 subcode 0 may be smaller than the ism array. Initialize it to avoid copying uninitialized data to the debug area. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Acked-by: Alexander Gordeev Signed-off-by: Heiko Carstens Signed-off-by: Alexander Gordeev --- arch/s390/kernel/cert_store.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index 12fc0ee87f3b0a..e3cc9389a50a46 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -670,7 +670,7 @@ static int add_certificates_to_keyring(struct vcssb *vcssb, struct key *keyring) */ static int query_diag320_subcodes(void) { - unsigned long ism[ISM_LEN_DWORDS]; + unsigned long ism[ISM_LEN_DWORDS] = {}; int rc; rc = diag320(0, ism); From 1ecc5b7c95ae585042ccbf3c587897dd99e2ddb5 Mon Sep 17 00:00:00 2001 From: orkunsari Date: Wed, 4 Nov 2026 14:56:15 +0300 Subject: [PATCH 1038/2102] nfsd: unlock the locked parent after crossing a mount in CREATE Since commit f58a48389c14 ("nfsd: correctly handle CREATE of mounted-on files"), nfsd_proc_create() and nfsd3_create_file() call nfsd_cross_mnt() on the dentry returned by start_creating(). When the name refers to a file that has something mounted on it, nfsd_cross_mnt() replaces that dentry with the root of the mounted filesystem and drops its reference to the original one. The replacement is later passed to end_creating(), which unlocks the d_parent of the dentry it is given. That is the parent of the mount source, not the directory start_creating() locked, so the directory being created in is left locked and another directory's i_rwsem is released without being held. Do the crossing on a separate reference that is only used for fh_compose(), so that the dentry returned by start_creating() is the one passed to end_creating(). Only positive regular files are crossed, so the later checks on the child dentry give the same result. This was found by AI-assisted code review (Claude Code). The fix has been build-tested with W=1 only; no reproducer was run. Fixes: f58a48389c14 ("nfsd: correctly handle CREATE of mounted-on files") Signed-off-by: orkunsari Link: https://patch.msgid.link/20261104-nfsd-cross-mnt-v1-1-5ec5fca0a553@gmail.com Signed-off-by: Chuck Lever --- fs/nfsd/nfs3proc.c | 14 +++++++++++--- fs/nfsd/nfsproc.c | 16 +++++++++++----- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/fs/nfsd/nfs3proc.c b/fs/nfsd/nfs3proc.c index 60cd01b6a37d24..0711e93c996350 100644 --- a/fs/nfsd/nfs3proc.c +++ b/fs/nfsd/nfs3proc.c @@ -334,7 +334,7 @@ nfsd3_create_file(struct svc_rqst *rqstp, struct svc_fh *fhp, struct svc_fh *resfhp, struct nfsd3_createargs *argp) { struct iattr *iap = &argp->attrs; - struct dentry *parent, *child; + struct dentry *parent, *child, *mnt_child; struct nfsd_attrs attrs = { .na_iattr = iap, }; @@ -378,21 +378,29 @@ nfsd3_create_file(struct svc_rqst *rqstp, struct svc_fh *fhp, } exp = exp_get(fhp->fh_export); + /* + * Cross on a separate reference: child must remain the dentry + * start_creating() returned so that end_creating() unlocks the + * right directory. + */ + mnt_child = dget(child); if (argp->createmode == NFS3_CREATE_UNCHECKED) { /* * If name is already in dcache we need to check for mountpoints */ if (d_is_reg(child) && unlikely(nfsd_mountpoint(child, exp))) { - status = nfsd_cross_mnt(rqstp, &child, &exp); + status = nfsd_cross_mnt(rqstp, &mnt_child, &exp); if (status != nfs_ok) { + dput(mnt_child); exp_put(exp); goto out; } } } - status = fh_compose(resfhp, exp, child, fhp); + status = fh_compose(resfhp, exp, mnt_child, fhp); + dput(mnt_child); exp_put(exp); if (status != nfs_ok) goto out; diff --git a/fs/nfsd/nfsproc.c b/fs/nfsd/nfsproc.c index 1f74008bc06ad8..2cecae4e0cdfa8 100644 --- a/fs/nfsd/nfsproc.c +++ b/fs/nfsd/nfsproc.c @@ -682,7 +682,7 @@ nfsd_create_file(struct svc_rqst *rqstp, struct svc_fh *fhp, .na_iattr = attr, }; struct svc_export *exp; - struct dentry *dchild; + struct dentry *dchild, *dmnt; struct inode *inode; int type, mode; __be32 status; @@ -705,20 +705,26 @@ nfsd_create_file(struct svc_rqst *rqstp, struct svc_fh *fhp, status = nfserrno(PTR_ERR(dchild)); goto out_drop_write; } + exp = exp_get(fhp->fh_export); /* - * If name exists we need to check for mountpoints + * If name exists we need to check for mountpoints. Cross on a + * separate reference: end_creating() unlocks the parent of the + * dentry it is given, and only dchild has the locked directory + * as its parent. */ - exp = exp_get(fhp->fh_export); + dmnt = dget(dchild); if (d_is_reg(dchild) && unlikely(nfsd_mountpoint(dchild, exp))) { - status = nfsd_cross_mnt(rqstp, &dchild, &exp); + status = nfsd_cross_mnt(rqstp, &dmnt, &exp); if (status != nfs_ok) { + dput(dmnt); exp_put(exp); goto out; } } - status = fh_compose(resfhp, exp, dchild, fhp); + status = fh_compose(resfhp, exp, dmnt, fhp); + dput(dmnt); exp_put(exp); if (!status && d_really_is_negative(dchild)) status = nfserr_noent; From 4e0dc0523bd98adbd45ce1c66dd1a96d4f6a3ec9 Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:16:35 -0500 Subject: [PATCH 1039/2102] Bluetooth: mgmt: Reject zero multi advertising rotation duration A zero def_multi_adv_rotation_duration makes hci_schedule_adv_instance_sync() requeue itself with no delay, spinning the request workqueue. Reject it in Set Default System Configuration. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-24ecb695-0c5c-408a-a016-a980c3115e95 Fixes: 17896406ff35 ("Bluetooth: implement read/set default system parameters mgmt") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/mgmt_config.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/net/bluetooth/mgmt_config.c b/net/bluetooth/mgmt_config.c index 6a617656bfbe06..834220072450fd 100644 --- a/net/bluetooth/mgmt_config.c +++ b/net/bluetooth/mgmt_config.c @@ -224,6 +224,14 @@ int set_def_system_config(struct sock *sk, struct hci_dev *hdev, void *data, MGMT_STATUS_INVALID_PARAMS); } + /* A zero rotation duration would make the advertising instance + * scheduler requeue itself with no delay. + */ + if (type == 0x000c && !TLV_GET_LE16(buffer)) + return mgmt_cmd_status(sk, hdev->id, + MGMT_OP_SET_DEF_SYSTEM_CONFIG, + MGMT_STATUS_INVALID_PARAMS); + buffer_left -= exp_len; buffer += exp_len; } From cb3251457da29ac1118f130bf45ac696421594a8 Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:16:36 -0500 Subject: [PATCH 1040/2102] Bluetooth: L2CAP: Don't use uninitialized EFS in l2cap_parse_conf_rsp() The local EFS values were copied from an on-stack struct even when the response carried no EFS option. Track whether it was received. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-089f015e-6251-4fea-85ef-7d6761e8c457 Fixes: 66af7aaf9edf ("Bluetooth: EFS: parse L2CAP config response") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/l2cap_core.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/net/bluetooth/l2cap_core.c b/net/bluetooth/l2cap_core.c index 133641c44e692d..da947b65d26a7e 100644 --- a/net/bluetooth/l2cap_core.c +++ b/net/bluetooth/l2cap_core.c @@ -3860,6 +3860,7 @@ static int l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len, unsigned long val; struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC }; struct l2cap_conf_efs efs; + bool remote_efs = false; BT_DBG("chan %p, rsp %p, len %d, req %p", chan, rsp, len, data); @@ -3915,6 +3916,7 @@ static int l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len, if (olen != sizeof(efs)) break; memcpy(&efs, (void *)val, olen); + remote_efs = true; if (chan->local_stype != L2CAP_SERV_NOTRAFIC && efs.stype != L2CAP_SERV_NOTRAFIC && efs.stype != chan->local_stype) @@ -3953,7 +3955,8 @@ static int l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len, chan->ack_win = min_t(u16, chan->ack_win, rfc.txwin_size); - if (test_bit(FLAG_EFS_ENABLE, &chan->flags)) { + if (remote_efs && + test_bit(FLAG_EFS_ENABLE, &chan->flags)) { chan->local_msdu = le16_to_cpu(efs.msdu); chan->local_sdu_itime = le32_to_cpu(efs.sdu_itime); From 1d7a527788584e4a88ccc532ed73bfdacd0b1e74 Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:30:35 -0500 Subject: [PATCH 1041/2102] Bluetooth: mgmt: Fix mesh transmission locking and lifetime The mesh_pending list is modified under hdev->lock by Mesh Send, but the cmd_sync callbacks and Mesh Send Cancel add/remove entries and touch hdev->adv_instances without it, which corrupts the list and the advertising instances. In addition the queued mesh_send_sync entry holds a raw pointer to the mesh_tx which a cancel of the transmission can free while the entry is running, leading to use-after-free. Fix this by: - taking hdev->lock around every mesh_pending/adv_instances access in the cmd_sync callbacks and Mesh Send Cancel, but never across HCI commands; - queueing the cmd_sync entries with the transmission handle and looking it up under the lock instead of passing the pointer; - always sending the first transmission, tracked by HCI_MESH_SENDING which is only cleared together with the removal of the transmission so Mesh Send can't start another one in between, and making sure none is left stranded if queueing fails; - cancelling a transmission by dequeuing its entry, and the done entry if it is the one in progress, stopping the done timer, which is queued with hdev->lock held so a cancel can't miss it; - not taking hdev->lock from callbacks invoked with -ECANCELED since those run with the cmd_sync lock held, the transmission is removed by whoever cancelled the entry; - flushing the transmissions left, dequeuing the entries still queued for them and clearing HCI_MESH_SENDING, when the controller is closed (also when auto powered off) or the index is removed, as nothing is going to send them and the stale entries would act on the ones started after the controller is powered on again, and not accepting Mesh Send while the controller is not powered so none can be left behind; - not reporting the completion of a transmission that failed to be queued by Mesh Send itself since userspace wasn't told about its handle; - not reusing the handle of a transmission still pending when the handle counter wraps around, now that it is what identifies a transmission. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-4ab89465-fc27-4d91-a870-a8ed49b22e91 Link: https://sashiko.dev/#/bug/linux-ab941894-dbe1-49da-8bac-c52efda6eaee Link: https://sashiko.dev/#/bug/linux-4016f774-7ac7-4b8a-916f-587ec9d597d4 Fixes: b338d91703fa ("Bluetooth: Implement support for Mesh") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- include/net/bluetooth/hci_core.h | 1 + net/bluetooth/hci_sync.c | 5 + net/bluetooth/mgmt.c | 301 +++++++++++++++++++++++++------ net/bluetooth/mgmt_util.c | 23 ++- 4 files changed, 267 insertions(+), 63 deletions(-) diff --git a/include/net/bluetooth/hci_core.h b/include/net/bluetooth/hci_core.h index db6397a0d9f5f1..7cf63bc0f46685 100644 --- a/include/net/bluetooth/hci_core.h +++ b/include/net/bluetooth/hci_core.h @@ -2519,6 +2519,7 @@ void mgmt_index_removed(struct hci_dev *hdev); void mgmt_set_powered_failed(struct hci_dev *hdev, int err); void mgmt_power_on(struct hci_dev *hdev, int err); void __mgmt_power_off(struct hci_dev *hdev); +void mgmt_mesh_flush(struct hci_dev *hdev); void mgmt_new_link_key(struct hci_dev *hdev, struct link_key *key, bool persistent); void mgmt_device_connected(struct hci_dev *hdev, struct hci_conn *conn, diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index 89a65d7c7b5426..d7ca28f9c13552 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -5885,6 +5885,11 @@ int hci_dev_close_sync(struct hci_dev *hdev) auto_off = hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF); + /* Nothing is going to send the mesh transmissions left, whether or not + * mgmt is told about the controller being powered off. + */ + mgmt_mesh_flush(hdev); + if (!auto_off && !hci_dev_test_flag(hdev, HCI_USER_CHANNEL) && hci_dev_test_flag(hdev, HCI_MGMT)) __mgmt_power_off(hdev); diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c index aad9e1b00e66b7..7f2452e16c54e6 100644 --- a/net/bluetooth/mgmt.c +++ b/net/bluetooth/mgmt.c @@ -1081,6 +1081,7 @@ static void discov_off(struct work_struct *work) static int send_settings_rsp(struct sock *sk, u16 opcode, struct hci_dev *hdev); +/* This function requires the caller holds hdev->lock */ static void mesh_send_complete(struct hci_dev *hdev, struct mgmt_mesh_tx *mesh_tx, bool silent) { @@ -1093,37 +1094,95 @@ static void mesh_send_complete(struct hci_dev *hdev, mgmt_mesh_remove(mesh_tx); } -static int mesh_send_done_sync(struct hci_dev *hdev, void *data) +/* The cmd_sync entries identify the transmission by handle rather than by + * pointer since the mesh_tx can be removed while the entry is queued or + * running. + */ +#define MESH_TX_DATA(_handle) ((void *)(unsigned long)(_handle)) +#define MESH_TX_HANDLE(_data) ((u8)(unsigned long)(_data)) + +static int mesh_send_sync(struct hci_dev *hdev, void *data); +static void mesh_send_start_complete(struct hci_dev *hdev, void *data, int err); + +/* Start sending the first transmission unless one is already in progress, + * HCI_MESH_SENDING is set while the first transmission is being sent. + * Completion is not reported for @new, the handle of a transmission userspace + * wasn't told about yet. + * + * This function requires the caller holds hdev->lock. + */ +static void __mesh_next(struct hci_dev *hdev, u8 new) { struct mgmt_mesh_tx *mesh_tx; + int err; - hci_dev_clear_flag(hdev, HCI_MESH_SENDING); - if (list_empty(&hdev->adv_instances)) - hci_disable_advertising_sync(hdev); - mesh_tx = mgmt_mesh_next(hdev, NULL); - - if (mesh_tx) - mesh_send_complete(hdev, mesh_tx, false); + while (!hci_dev_test_flag(hdev, HCI_MESH_SENDING)) { + mesh_tx = mgmt_mesh_next(hdev, NULL); + if (!mesh_tx) + return; - return 0; + err = hci_cmd_sync_queue(hdev, mesh_send_sync, + MESH_TX_DATA(mesh_tx->handle), + mesh_send_start_complete); + if (err < 0) + mesh_send_complete(hdev, mesh_tx, + mesh_tx->handle == new); + else + hci_dev_set_flag(hdev, HCI_MESH_SENDING); + } } -static int mesh_send_sync(struct hci_dev *hdev, void *data); -static void mesh_send_start_complete(struct hci_dev *hdev, void *data, int err); static void mesh_next(struct hci_dev *hdev, void *data, int err) { - struct mgmt_mesh_tx *mesh_tx = mgmt_mesh_next(hdev, NULL); - - if (!mesh_tx) + /* The entry is being cancelled with the cmd_sync lock held, which + * can't be taken before hdev->lock. + */ + if (err == -ECANCELED) return; - err = hci_cmd_sync_queue(hdev, mesh_send_sync, mesh_tx, - mesh_send_start_complete); + hci_dev_lock(hdev); + __mesh_next(hdev, 0); + hci_dev_unlock(hdev); +} - if (err < 0) +static int mesh_send_done_sync(struct hci_dev *hdev, void *data) +{ + struct mgmt_mesh_tx *mesh_tx; + u8 handle; + bool disable; + + hci_dev_lock(hdev); + + mesh_tx = mgmt_mesh_next(hdev, NULL); + if (!mesh_tx || !hci_dev_test_flag(hdev, HCI_MESH_SENDING)) { + hci_dev_unlock(hdev); + return 0; + } + + handle = mesh_tx->handle; + disable = list_empty(&hdev->adv_instances); + + hci_dev_unlock(hdev); + + if (disable) + hci_disable_advertising_sync(hdev); + + hci_dev_lock(hdev); + + /* The transmission can be cancelled meanwhile, in which case whoever + * did so already moved on to the next one. HCI_MESH_SENDING is only + * cleared with the transmission removed so Mesh Send doesn't start + * another one in between. + */ + mesh_tx = mgmt_mesh_find(hdev, handle); + if (mesh_tx) { mesh_send_complete(hdev, mesh_tx, false); - else - hci_dev_set_flag(hdev, HCI_MESH_SENDING); + hci_dev_clear_flag(hdev, HCI_MESH_SENDING); + } + + hci_dev_unlock(hdev); + + return 0; } static void mesh_send_done(struct work_struct *work) @@ -1137,6 +1196,33 @@ static void mesh_send_done(struct work_struct *work) hci_cmd_sync_queue(hdev, mesh_send_done_sync, NULL, mesh_next); } +/* Nothing is going to send the transmissions left, e.g. when the controller + * is powered off. + * + * This function requires the caller holds hdev->lock. + */ +static void mesh_flush(struct hci_dev *hdev, bool silent) +{ + struct mgmt_mesh_tx *mesh_tx; + + /* Stop the timer first, it checks HCI_MESH_SENDING without hdev->lock + * so once it is clear and the work is not running anymore nothing can + * queue mesh_send_done_sync behind the dequeue below. + */ + hci_dev_clear_flag(hdev, HCI_MESH_SENDING); + cancel_delayed_work_sync(&hdev->mesh_send_done); + + /* Entries still queued would otherwise run after the controller is + * powered on again and act on the transmissions started by then. The + * destroy callbacks don't take hdev->lock when cancelled. + */ + hci_cmd_sync_dequeue(hdev, mesh_send_sync, NULL, NULL); + hci_cmd_sync_dequeue(hdev, mesh_send_done_sync, NULL, NULL); + + while ((mesh_tx = mgmt_mesh_next(hdev, NULL))) + mesh_send_complete(hdev, mesh_tx, silent); +} + static void mgmt_init_hdev(struct sock *sk, struct hci_dev *hdev) { if (hci_dev_test_flag(hdev, HCI_MGMT)) @@ -2304,38 +2390,71 @@ static int set_mesh(struct sock *sk, struct hci_dev *hdev, void *data, u16 len) static void mesh_send_start_complete(struct hci_dev *hdev, void *data, int err) { - struct mgmt_mesh_tx *mesh_tx = data; - struct mgmt_cp_mesh_send *send = (void *)mesh_tx->param; - unsigned long mesh_send_interval; + struct mgmt_mesh_tx *mesh_tx; + struct mgmt_cp_mesh_send *send; u8 mgmt_err = mgmt_status(err); + /* The entry is being cancelled with the cmd_sync lock held, which + * can't be taken before hdev->lock, so leave the removal of the + * transmission, and HCI_MESH_SENDING, to whoever cancelled it or to + * mgmt_power_off() if the controller is going down. + */ + if (err == -ECANCELED) + return; + + hci_dev_lock(hdev); + + /* Cancelled while the entry was running, whoever did so already moved + * on to the next transmission. + */ + mesh_tx = mgmt_mesh_find(hdev, MESH_TX_HANDLE(data)); + if (!mesh_tx) { + hci_dev_unlock(hdev); + return; + } + /* Report any errors here, but don't report completion */ if (mgmt_err) { - hci_dev_clear_flag(hdev, HCI_MESH_SENDING); /* Send Complete Error Code for handle */ mesh_send_complete(hdev, mesh_tx, false); - if (err != -ECANCELED) - mesh_next(hdev, NULL, 0); + hci_dev_clear_flag(hdev, HCI_MESH_SENDING); + __mesh_next(hdev, 0); + hci_dev_unlock(hdev); return; } - mesh_send_interval = msecs_to_jiffies((send->cnt) * 25); + /* Queued with hdev->lock held so a cancel can't miss it */ + send = (void *)mesh_tx->param; queue_delayed_work(hdev->req_workqueue, &hdev->mesh_send_done, - mesh_send_interval); + msecs_to_jiffies((send->cnt) * 25)); + + hci_dev_unlock(hdev); } static int mesh_send_sync(struct hci_dev *hdev, void *data) { - struct mgmt_mesh_tx *mesh_tx = data; - struct mgmt_cp_mesh_send *send = (void *)mesh_tx->param; + struct mgmt_mesh_tx *mesh_tx; + struct mgmt_cp_mesh_send *send; struct adv_info *adv, *next_instance; u8 instance = hdev->le_num_of_adv_sets + 1; u16 timeout, duration; int err = 0; - if (hdev->le_num_of_adv_sets <= hdev->adv_instance_cnt) + hci_dev_lock(hdev); + + mesh_tx = mgmt_mesh_find(hdev, MESH_TX_HANDLE(data)); + if (!mesh_tx) { + hci_dev_unlock(hdev); + return -ENOENT; + } + + send = (void *)mesh_tx->param; + + if (hdev->le_num_of_adv_sets <= hdev->adv_instance_cnt) { + hci_dev_unlock(hdev); return MGMT_STATUS_BUSY; + } timeout = 1000; duration = send->cnt * INTERVAL_TO_MS(hdev->le_adv_max_interval); @@ -2373,6 +2492,8 @@ static int mesh_send_sync(struct hci_dev *hdev, void *data) instance = 0; } + hci_dev_unlock(hdev); + if (instance) return hci_schedule_adv_instance_sync(hdev, instance, true); @@ -2416,37 +2537,80 @@ static int mesh_features(struct sock *sk, struct hci_dev *hdev, return 0; } +/* Cancel a single transmission, the handle is looked up again after the + * entry has been dequeued since it may be gone or have completed meanwhile. + */ +static void mesh_cancel_tx(struct hci_dev *hdev, u8 handle) +{ + struct mgmt_mesh_tx *mesh_tx; + bool in_progress; + + hci_cmd_sync_dequeue(hdev, mesh_send_sync, MESH_TX_DATA(handle), NULL); + + hci_dev_lock(hdev); + mesh_tx = mgmt_mesh_find(hdev, handle); + in_progress = mesh_tx && hci_dev_test_flag(hdev, HCI_MESH_SENDING) && + mesh_tx == mgmt_mesh_next(hdev, NULL); + hci_dev_unlock(hdev); + + /* The done timer may have fired already and be waiting to complete + * the transmission in progress, which is being cancelled. + */ + if (in_progress) + hci_cmd_sync_dequeue(hdev, mesh_send_done_sync, NULL, NULL); + + hci_dev_lock(hdev); + + mesh_tx = mgmt_mesh_find(hdev, handle); + if (mesh_tx) { + /* If it is the transmission in progress make sure the timer + * doesn't complete the next one in its place. + */ + if (hci_dev_test_flag(hdev, HCI_MESH_SENDING) && + mesh_tx == mgmt_mesh_next(hdev, NULL)) { + cancel_delayed_work(&hdev->mesh_send_done); + hci_dev_clear_flag(hdev, HCI_MESH_SENDING); + } + + mesh_send_complete(hdev, mesh_tx, false); + } + + hci_dev_unlock(hdev); +} + static int send_cancel(struct hci_dev *hdev, void *data) { struct mgmt_pending_cmd *cmd = data; struct mgmt_cp_mesh_send_cancel *cancel = (void *)cmd->param; struct mgmt_mesh_tx *mesh_tx; + u8 handle; if (!cancel->handle) { - do { + for (;;) { + hci_dev_lock(hdev); mesh_tx = mgmt_mesh_next(hdev, cmd->sk); + handle = mesh_tx ? mesh_tx->handle : 0; + hci_dev_unlock(hdev); - if (mesh_tx) { - if (!hci_cmd_sync_dequeue(hdev, mesh_send_sync, - mesh_tx, NULL)) - mesh_send_complete(hdev, mesh_tx, false); - } - } while (mesh_tx); + if (!mesh_tx) + break; + + mesh_cancel_tx(hdev, handle); + } } else { + hci_dev_lock(hdev); mesh_tx = mgmt_mesh_find(hdev, cancel->handle); + handle = mesh_tx && mesh_tx->sk == cmd->sk ? mesh_tx->handle : 0; + hci_dev_unlock(hdev); - if (mesh_tx && mesh_tx->sk == cmd->sk) { - if (!hci_cmd_sync_dequeue(hdev, mesh_send_sync, - mesh_tx, NULL)) - mesh_send_complete(hdev, mesh_tx, false); - } + if (handle) + mesh_cancel_tx(hdev, handle); } mgmt_cmd_complete(cmd->sk, hdev->id, MGMT_OP_MESH_SEND_CANCEL, 0, NULL, 0); - if (!hci_dev_test_flag(hdev, HCI_MESH_SENDING)) - mesh_next(hdev, NULL, 0); + mesh_next(hdev, NULL, 0); return 0; } @@ -2497,7 +2661,6 @@ static int mesh_send(struct sock *sk, struct hci_dev *hdev, void *data, u16 len) struct mgmt_cp_mesh_send *send = data; struct mgmt_rp_mesh_read_features rp; u16 expected_len; - bool sending; int err = 0; if (!lmp_le_capable(hdev) || @@ -2519,6 +2682,15 @@ static int mesh_send(struct sock *sk, struct hci_dev *hdev, void *data, u16 len) hci_dev_lock(hdev); + /* Transmissions are flushed when the controller is closed, which is + * serialized with this by hdev->lock, so none can be left behind. + */ + if (!hdev_is_powered(hdev)) { + err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_MESH_SEND, + MGMT_STATUS_NOT_POWERED); + goto done; + } + memset(&rp, 0, sizeof(rp)); rp.max_handles = MESH_HANDLES_MAX; @@ -2530,27 +2702,27 @@ static int mesh_send(struct sock *sk, struct hci_dev *hdev, void *data, u16 len) goto done; } - sending = hci_dev_test_flag(hdev, HCI_MESH_SENDING); mesh_tx = mgmt_mesh_add(sk, hdev, send, len); - - if (!mesh_tx) + if (!mesh_tx) { err = -ENOMEM; - else if (!sending) - err = hci_cmd_sync_queue(hdev, mesh_send_sync, mesh_tx, - mesh_send_start_complete); + } else { + u8 handle = mesh_tx->handle; + + /* The first transmission is the one queued, which may not be + * the one just added. + */ + __mesh_next(hdev, handle); + + /* Queueing failed, the transmission was removed */ + if (!mgmt_mesh_find(hdev, handle)) + err = -EIO; + } if (err < 0) { bt_dev_err(hdev, "Send Mesh Failed %d", err); err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_MESH_SEND, MGMT_STATUS_FAILED); - - if (mesh_tx) { - if (sending) - mgmt_mesh_remove(mesh_tx); - } } else { - hci_dev_set_flag(hdev, HCI_MESH_SENDING); - mgmt_cmd_complete(sk, hdev->id, MGMT_OP_MESH_SEND, 0, &mesh_tx->handle, 1); } @@ -9914,7 +10086,8 @@ void mgmt_index_removed(struct hci_dev *hdev) cancel_delayed_work_sync(&hdev->discov_off); cancel_delayed_work_sync(&hdev->service_cache); cancel_delayed_work_sync(&hdev->rpa_expired); - cancel_delayed_work_sync(&hdev->mesh_send_done); + + mesh_flush(hdev, true); } void mgmt_power_on(struct hci_dev *hdev, int err) @@ -9941,6 +10114,16 @@ void mgmt_power_on(struct hci_dev *hdev, int err) hci_dev_unlock(hdev); } +/* This function requires the caller holds hdev->lock */ +void mgmt_mesh_flush(struct hci_dev *hdev) +{ + /* The mesh work is only initialized once mgmt is used */ + if (!hci_dev_test_flag(hdev, HCI_MGMT)) + return; + + mesh_flush(hdev, false); +} + void __mgmt_power_off(struct hci_dev *hdev) { struct cmd_lookup match = { NULL, hdev }; diff --git a/net/bluetooth/mgmt_util.c b/net/bluetooth/mgmt_util.c index 6ea107c0e05433..d502e6b933e811 100644 --- a/net/bluetooth/mgmt_util.c +++ b/net/bluetooth/mgmt_util.c @@ -409,16 +409,31 @@ struct mgmt_mesh_tx *mgmt_mesh_add(struct sock *sk, struct hci_dev *hdev, void *data, u16 len) { struct mgmt_mesh_tx *mesh_tx; + u8 handle = hdev->mesh_send_ref; + int i; + + /* The handle is all that identifies a transmission, so it must not be + * in use by one still pending when the counter wraps around. + */ + for (i = 0; i < 255; i++) { + handle++; + if (!handle) + handle++; + + if (!mgmt_mesh_find(hdev, handle)) + break; + } + + if (i == 255) + return NULL; mesh_tx = kzalloc_obj(*mesh_tx); if (!mesh_tx) return NULL; - hdev->mesh_send_ref++; - if (!hdev->mesh_send_ref) - hdev->mesh_send_ref++; + hdev->mesh_send_ref = handle; - mesh_tx->handle = hdev->mesh_send_ref; + mesh_tx->handle = handle; mesh_tx->index = hdev->id; memcpy(mesh_tx->param, data, len); mesh_tx->param_len = len; From 7c8dcf322b0d978c80001632c1206d5fe1ee9ba7 Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:31:19 -0500 Subject: [PATCH 1042/2102] Bluetooth: MGMT: Fix use-after-free in mgmt_powering_down() mgmt_powering_down() looked up the Set Powered command and read its parameters after mgmt_pending_find() dropped mgmt_pending_lock, so the command could be unlinked and freed in between. Do the lookup and read the parameters while holding the lock. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-e45413fa-48a6-43f1-90be-638841567534 Fixes: 302a1f674c00 ("Bluetooth: MGMT: Fix possible UAFs") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/mgmt.c | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c index 7f2452e16c54e6..4ef2f1fd763634 100644 --- a/net/bluetooth/mgmt.c +++ b/net/bluetooth/mgmt.c @@ -10399,19 +10399,27 @@ bool mgmt_powering_down(struct hci_dev *hdev) { struct mgmt_pending_cmd *cmd; struct mgmt_mode *cp; + bool powering_down = false; if (hci_dev_test_flag(hdev, HCI_POWERING_DOWN)) return true; - cmd = pending_find(MGMT_OP_SET_POWERED, hdev); - if (!cmd) - return false; + mutex_lock(&hdev->mgmt_pending_lock); - cp = cmd->param; - if (!cp->val) - return true; + list_for_each_entry(cmd, &hdev->mgmt_pending, list) { + if (hci_sock_get_channel(cmd->sk) != HCI_CHANNEL_CONTROL || + cmd->opcode != MGMT_OP_SET_POWERED) + continue; - return false; + /* cmd can only be freed after it is unlinked under the lock */ + cp = cmd->param; + powering_down = !cp->val; + break; + } + + mutex_unlock(&hdev->mgmt_pending_lock); + + return powering_down; } u8 hci_to_mgmt_reason(u8 err) From 0434cd10518c1b58ca3f5366341f0b1c469afbca Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:31:53 -0500 Subject: [PATCH 1043/2102] Bluetooth: MSFT: Protect the event prefix with hdev->lock msft_vendor_evt() read msft->evt_prefix_len and compared evt_prefix before taking hdev->lock, while msft_do_open() (and the supported features reply) free and reallocate the prefix without it, so an event received while the controller is being opened could access freed memory. Take hdev->lock for the whole event processing and while updating the prefix. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-246df501-f32c-46fd-8779-7fa755ed7f9d Fixes: 5031ffcc79b8 ("Bluetooth: Keep MSFT ext info throughout a hci_dev's life cycle") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/msft.c | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/net/bluetooth/msft.c b/net/bluetooth/msft.c index 2559c5b1bef020..ab63fee3ef5974 100644 --- a/net/bluetooth/msft.c +++ b/net/bluetooth/msft.c @@ -170,11 +170,16 @@ static bool read_supported_features(struct hci_dev *hdev, goto failed; } + /* The event prefix is used by msft_vendor_evt() with hdev->lock held */ + hci_dev_lock(hdev); + if (rp->evt_prefix_len > 0) { msft->evt_prefix = kmemdup(rp->evt_prefix, rp->evt_prefix_len, GFP_KERNEL); - if (!msft->evt_prefix) + if (!msft->evt_prefix) { + hci_dev_unlock(hdev); goto failed; + } } msft->evt_prefix_len = rp->evt_prefix_len; @@ -183,6 +188,8 @@ static bool read_supported_features(struct hci_dev *hdev, if (msft->features & MSFT_FEATURE_MASK_CURVE_VALIDITY) hdev->msft_curve_validity = true; + hci_dev_unlock(hdev); + kfree_skb(skb); return true; @@ -648,10 +655,12 @@ void msft_do_open(struct hci_dev *hdev) bt_dev_dbg(hdev, "Initialize MSFT extension"); /* Reset existing MSFT data before re-reading */ + hci_dev_lock(hdev); kfree(msft->evt_prefix); msft->evt_prefix = NULL; msft->evt_prefix_len = 0; msft->features = 0; + hci_dev_unlock(hdev); if (!read_supported_features(hdev, msft)) { hci_dev_lock(hdev); @@ -1078,12 +1087,15 @@ static void msft_monitor_device_evt(struct hci_dev *hdev, struct sk_buff *skb) void msft_vendor_evt(struct hci_dev *hdev, void *data, struct sk_buff *skb) { - struct msft_data *msft = hdev->msft_data; + struct msft_data *msft; u8 *evt_prefix; u8 *evt; + hci_dev_lock(hdev); + + msft = hdev->msft_data; if (!msft) - return; + goto unlock; /* When the extension has defined an event prefix, check that it * matches, and otherwise just return. @@ -1091,23 +1103,21 @@ void msft_vendor_evt(struct hci_dev *hdev, void *data, struct sk_buff *skb) if (msft->evt_prefix_len > 0) { evt_prefix = msft_skb_pull(hdev, skb, 0, msft->evt_prefix_len); if (!evt_prefix) - return; + goto unlock; if (memcmp(evt_prefix, msft->evt_prefix, msft->evt_prefix_len)) - return; + goto unlock; } /* Every event starts at least with an event code and the rest of * the data is variable and depends on the event code. */ if (skb->len < 1) - return; + goto unlock; evt = msft_skb_pull(hdev, skb, 0, sizeof(*evt)); if (!evt) - return; - - hci_dev_lock(hdev); + goto unlock; switch (*evt) { case MSFT_EV_LE_MONITOR_DEVICE: @@ -1121,6 +1131,7 @@ void msft_vendor_evt(struct hci_dev *hdev, void *data, struct sk_buff *skb) break; } +unlock: hci_dev_unlock(hdev); } From b49abf5f92ea0e03ebc0fe41ce4af87b094fe9b5 Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:32:15 -0500 Subject: [PATCH 1044/2102] Bluetooth: hci_debugfs: Fix racy toggling of debugfs controlled flags The debugfs writers checked the current state of the flag, then blindly inverted it with hci_dev_change_flag(). Two concurrent writers both pass the check and the second inversion undoes the first one, leaving the flag out of sync with the actual controller/SMP channel state (e.g. DUT mode flag vs controller, or the BR/EDR SMP channel being leaked or removed twice). Set or clear the flag explicitly instead, redo the dut_mode check under hci_req_sync_lock() and serialize smp_force_bredr() with hdev->lock. The same applies to the quirk attributes. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-442108d5-76ce-44a1-a84d-16b44d6a26a6 Fixes: 4b4148e9acc1 ("Bluetooth: Add support for setting DUT mode") Fixes: b55d1abf568c ("Bluetooth: Expose quirks through debugfs") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_debugfs.c | 32 +++++++++++++++++++++++++------- net/bluetooth/smp.c | 25 +++++++++++++++++++------ 2 files changed, 44 insertions(+), 13 deletions(-) diff --git a/net/bluetooth/hci_debugfs.c b/net/bluetooth/hci_debugfs.c index cd5ef398f23821..1af68bfc2257ad 100644 --- a/net/bluetooth/hci_debugfs.c +++ b/net/bluetooth/hci_debugfs.c @@ -59,7 +59,7 @@ static ssize_t __name ## _write(struct file *file, \ if (enable == test_bit(__quirk, hdev->quirk_flags)) \ return -EALREADY; \ \ - change_bit(__quirk, hdev->quirk_flags); \ + assign_bit(__quirk, hdev->quirk_flags, enable); \ \ return count; \ } \ @@ -777,7 +777,10 @@ static ssize_t force_static_address_write(struct file *file, if (enable == hci_dev_test_flag(hdev, HCI_FORCE_STATIC_ADDR)) return -EALREADY; - hci_dev_change_flag(hdev, HCI_FORCE_STATIC_ADDR); + if (enable) + hci_dev_set_flag(hdev, HCI_FORCE_STATIC_ADDR); + else + hci_dev_clear_flag(hdev, HCI_FORCE_STATIC_ADDR); return count; } @@ -1177,7 +1180,10 @@ static ssize_t force_no_mitm_write(struct file *file, if (enable == hci_dev_test_flag(hdev, HCI_FORCE_NO_MITM)) return -EALREADY; - hci_dev_change_flag(hdev, HCI_FORCE_NO_MITM); + if (enable) + hci_dev_set_flag(hdev, HCI_FORCE_NO_MITM); + else + hci_dev_clear_flag(hdev, HCI_FORCE_NO_MITM); return count; } @@ -1303,20 +1309,32 @@ static ssize_t dut_mode_write(struct file *file, const char __user *user_buf, return -EALREADY; hci_req_sync_lock(hdev); + + /* Check again now that concurrent writers are excluded */ + if (enable == hci_dev_test_flag(hdev, HCI_DUT_MODE)) { + hci_req_sync_unlock(hdev); + return -EALREADY; + } + if (enable) skb = __hci_cmd_sync(hdev, HCI_OP_ENABLE_DUT_MODE, 0, NULL, HCI_CMD_TIMEOUT); else skb = __hci_cmd_sync(hdev, HCI_OP_RESET, 0, NULL, HCI_CMD_TIMEOUT); - hci_req_sync_unlock(hdev); - - if (IS_ERR(skb)) + if (IS_ERR(skb)) { + hci_req_sync_unlock(hdev); return PTR_ERR(skb); + } kfree_skb(skb); - hci_dev_change_flag(hdev, HCI_DUT_MODE); + if (enable) + hci_dev_set_flag(hdev, HCI_DUT_MODE); + else + hci_dev_clear_flag(hdev, HCI_DUT_MODE); + + hci_req_sync_unlock(hdev); return count; } diff --git a/net/bluetooth/smp.c b/net/bluetooth/smp.c index 1caebdd8e0a66b..2538096cae0601 100644 --- a/net/bluetooth/smp.c +++ b/net/bluetooth/smp.c @@ -3378,8 +3378,14 @@ static void smp_del_chan(struct l2cap_chan *chan) int smp_force_bredr(struct hci_dev *hdev, bool enable) { - if (enable == hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP)) - return -EALREADY; + int err = 0; + + hci_dev_lock(hdev); + + if (enable == hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP)) { + err = -EALREADY; + goto unlock; + } /* The channels are only registered while the controller is powered * and LE capable. Otherwise just record the flag, smp_register() will @@ -3390,8 +3396,10 @@ int smp_force_bredr(struct hci_dev *hdev, bool enable) if (hdev->smp_data && !hdev->smp_bredr_data) { chan = smp_add_cid(hdev, L2CAP_CID_SMP_BREDR); - if (IS_ERR(chan)) - return PTR_ERR(chan); + if (IS_ERR(chan)) { + err = PTR_ERR(chan); + goto unlock; + } hdev->smp_bredr_data = chan; } @@ -3405,9 +3413,14 @@ int smp_force_bredr(struct hci_dev *hdev, bool enable) } } - hci_dev_change_flag(hdev, HCI_FORCE_BREDR_SMP); + if (enable) + hci_dev_set_flag(hdev, HCI_FORCE_BREDR_SMP); + else + hci_dev_clear_flag(hdev, HCI_FORCE_BREDR_SMP); - return 0; +unlock: + hci_dev_unlock(hdev); + return err; } int smp_register(struct hci_dev *hdev) From 7f08b6ef44fa17f1a5ad3926663ddb5abe6ff68a Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Mon, 9 Nov 2026 16:32:57 -0500 Subject: [PATCH 1045/2102] Bluetooth: hci_core: Hold hdev->lock when removing advertisement monitors hci_remove_single_adv_monitor() and hci_remove_all_adv_monitor() only require hci_req_sync_lock, yet they look up and free monitors, modifying hdev->adv_monitors_idr and adv_monitors_cnt, which Read Advertisement Monitor Features iterates under hdev->lock. Take hdev->lock around the IDR accesses and the freeing, but not across the HCI commands sent to the controller. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-8b358899-5ac9-4687-af16-58420a4d9bba Fixes: 7cf5c2978f23 ("Bluetooth: hci_sync: Refactor remove Adv Monitor") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_core.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/net/bluetooth/hci_core.c b/net/bluetooth/hci_core.c index 9a3b1e36e69190..c7310fcb58b32b 100644 --- a/net/bluetooth/hci_core.c +++ b/net/bluetooth/hci_core.c @@ -2034,7 +2034,10 @@ static int hci_remove_adv_monitor(struct hci_dev *hdev, if (status == -ENOENT) bt_dev_warn(hdev, "Removing monitor with no matching handle %d", monitor->handle); + + hci_dev_lock(hdev); hci_free_adv_monitor(hdev, monitor); + hci_dev_unlock(hdev); return status; } @@ -2042,7 +2045,11 @@ static int hci_remove_adv_monitor(struct hci_dev *hdev, /* This function requires the caller holds hci_req_sync_lock */ int hci_remove_single_adv_monitor(struct hci_dev *hdev, u16 handle) { - struct adv_monitor *monitor = idr_find(&hdev->adv_monitors_idr, handle); + struct adv_monitor *monitor; + + hci_dev_lock(hdev); + monitor = idr_find(&hdev->adv_monitors_idr, handle); + hci_dev_unlock(hdev); if (!monitor) return -EINVAL; @@ -2058,7 +2065,10 @@ int hci_remove_all_adv_monitor(struct hci_dev *hdev) int status = 0; while (1) { + hci_dev_lock(hdev); monitor = idr_get_next(&hdev->adv_monitors_idr, &idr_next_id); + hci_dev_unlock(hdev); + if (!monitor) break; From 775eca0c3df2f0272f21ebc8c812ad010fd47243 Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Tue, 17 Nov 2026 15:00:11 -0500 Subject: [PATCH 1046/2102] Bluetooth: MSFT: Free the response of the monitor commands msft_add_monitor_sync() and msft_remove_monitor_sync() send the MSFT command with __hci_cmd_sync() and pass the returned skb to the callbacks, which only parse it, so it is never freed. Free it once the callback returns. While at it initialize the RSSI fields of the handle data when it is created instead of after the command completed, so they are never exposed uninitialized, and do the lookup of the handle map in msft_remove_monitor_sync() with hdev->lock held. Found by the sashiko.dev review of the previous revision of this series. Reported-by: Sashiko Link: https://sashiko.dev/#/patchset/20261117185737.3758255-1-luiz.dentz%40gmail.com Fixes: b747a83690c8 ("Bluetooth: hci_sync: Refactor add Adv Monitor") Fixes: 7cf5c2978f23 ("Bluetooth: hci_sync: Refactor remove Adv Monitor") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/msft.c | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/net/bluetooth/msft.c b/net/bluetooth/msft.c index ab63fee3ef5974..7a06c2b8974b7e 100644 --- a/net/bluetooth/msft.c +++ b/net/bluetooth/msft.c @@ -297,6 +297,10 @@ static int msft_le_monitor_advertisement_cb(struct hci_dev *hdev, u16 opcode, handle_data->mgmt_handle = monitor->handle; handle_data->msft_handle = rp->handle; handle_data->cond_type = MSFT_MONITOR_ADVERTISEMENT_TYPE_PATTERN; + handle_data->rssi_high = monitor->rssi.high_threshold; + handle_data->rssi_low = monitor->rssi.low_threshold; + handle_data->rssi_low_interval = (u8)monitor->rssi.low_threshold_timeout; + handle_data->rssi_sampling_period = monitor->rssi.sampling_period; INIT_LIST_HEAD(&handle_data->list); list_add(&handle_data->list, &msft->handle_map); @@ -438,23 +442,30 @@ static int msft_remove_monitor_sync(struct hci_dev *hdev, struct msft_cp_le_cancel_monitor_advertisement cp; struct msft_monitor_advertisement_handle_data *handle_data; struct sk_buff *skb; + int err; + hci_dev_lock(hdev); handle_data = msft_find_handle_data(hdev, monitor->handle, true); + if (handle_data) + cp.handle = handle_data->msft_handle; + hci_dev_unlock(hdev); /* If no matched handle, just remove without telling controller */ if (!handle_data) return -ENOENT; cp.sub_opcode = MSFT_OP_LE_CANCEL_MONITOR_ADVERTISEMENT; - cp.handle = handle_data->msft_handle; skb = __hci_cmd_sync(hdev, hdev->msft_opcode, sizeof(cp), &cp, HCI_CMD_TIMEOUT); if (IS_ERR(skb)) return PTR_ERR(skb); - return msft_le_cancel_monitor_advertisement_cb(hdev, hdev->msft_opcode, - monitor, skb); + err = msft_le_cancel_monitor_advertisement_cb(hdev, hdev->msft_opcode, + monitor, skb); + kfree_skb(skb); + + return err; } /* This function requires the caller holds hci_req_sync_lock */ @@ -519,7 +530,6 @@ static int msft_add_monitor_sync(struct hci_dev *hdev, { struct msft_cp_le_monitor_advertisement *cp; struct msft_le_monitor_advertisement_pattern_data *pattern_data; - struct msft_monitor_advertisement_handle_data *handle_data; struct msft_le_monitor_advertisement_pattern *pattern; struct adv_pattern *entry; size_t total_size = sizeof(*cp) + sizeof(*pattern_data); @@ -571,19 +581,7 @@ static int msft_add_monitor_sync(struct hci_dev *hdev, err = msft_le_monitor_advertisement_cb(hdev, hdev->msft_opcode, monitor, skb); - if (err) - goto out_free; - - handle_data = msft_find_handle_data(hdev, monitor->handle, true); - if (!handle_data) { - err = -ENODATA; - goto out_free; - } - - handle_data->rssi_high = cp->rssi_high; - handle_data->rssi_low = cp->rssi_low; - handle_data->rssi_low_interval = cp->rssi_low_interval; - handle_data->rssi_sampling_period = cp->rssi_sampling_period; + kfree_skb(skb); out_free: kfree(cp); From 8d3e5e6fe6d0be5634b28788abf5685d571b13a4 Mon Sep 17 00:00:00 2001 From: Luiz Augusto von Dentz Date: Tue, 17 Nov 2026 15:00:12 -0500 Subject: [PATCH 1047/2102] Bluetooth: hci_core: Don't fail removing a monitor unknown to the controller hci_remove_adv_monitor() frees the monitor when the controller has no matching handle for it but still returned -ENOENT, so callers took it for a failure of a monitor that is gone, and hci_remove_all_adv_monitor() stopped at the first one leaving the others behind. Return success since the monitor was removed. Found by the sashiko.dev review of the previous revision of this series. Reported-by: Sashiko Link: https://sashiko.dev/#/patchset/20261117185737.3758255-1-luiz.dentz%40gmail.com Fixes: 7cf5c2978f23 ("Bluetooth: hci_sync: Refactor remove Adv Monitor") Assisted-by: OpenCode:claude-fable-5.2 Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_core.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/net/bluetooth/hci_core.c b/net/bluetooth/hci_core.c index c7310fcb58b32b..255005916f3751 100644 --- a/net/bluetooth/hci_core.c +++ b/net/bluetooth/hci_core.c @@ -2039,7 +2039,10 @@ static int hci_remove_adv_monitor(struct hci_dev *hdev, hci_free_adv_monitor(hdev, monitor); hci_dev_unlock(hdev); - return status; + /* The monitor is gone, not having been known by the controller is not + * an error for the caller. + */ + return status == -ENOENT ? 0 : status; } /* This function requires the caller holds hci_req_sync_lock */ From 449cdc5e29c63aa66b41ce8c2783f6b0d84c62b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADtor=20Hugo=20Silva?= Date: Wed, 18 Nov 2026 09:29:28 +0000 Subject: [PATCH 1048/2102] hwmon: (ads7871) Add error handle from spi_setup() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ads7871 probe() ignores the spi_setup() error return value and it attempts to write to registers even if spi_setup() fails. Return the setup error before accessing any registers. AI was used for peer-review the patch. Fixes: e0c70b8078629 ("hwmon: add TI ads7871 a/d converter driver") Cc: stable@vger.kernel.org Signed-off-by: Vítor Hugo Silva Link: https://patch.msgid.link/20261118092928.163553-1-vitorhg20080@gmail.com Signed-off-by: Guenter Roeck --- drivers/hwmon/ads7871.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/hwmon/ads7871.c b/drivers/hwmon/ads7871.c index 36297bc6d047eb..a1ffc35d9272f9 100644 --- a/drivers/hwmon/ads7871.c +++ b/drivers/hwmon/ads7871.c @@ -187,7 +187,9 @@ static int ads7871_probe(struct spi_device *spi) /* Configure the SPI bus */ spi->mode = (SPI_MODE_0); spi->bits_per_word = 8; - spi_setup(spi); + ret = spi_setup(spi); + if (ret) + return ret; pdata = devm_kzalloc_obj(dev, *pdata); if (!pdata) From 4feb6879b9ab42cacb905f27a44160b7f1f49d85 Mon Sep 17 00:00:00 2001 From: Tingmao Wang Date: Mon, 16 Nov 2026 23:31:37 +0000 Subject: [PATCH 1049/2102] landlock: Add missing EINVAL case in the doc for landlock_add_rule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is another way it can return EINVAL but is not documented. Documenting it is useful to help rule out errors. Signed-off-by: Tingmao Wang Link: https://patch.msgid.link/20261116233139.206924-1-m@maowtm.org Signed-off-by: Mickaël Salaün --- security/landlock/syscalls.c | 1 + 1 file changed, 1 insertion(+) diff --git a/security/landlock/syscalls.c b/security/landlock/syscalls.c index fb5af318b69bb4..29e9d5d7399d64 100644 --- a/security/landlock/syscalls.c +++ b/security/landlock/syscalls.c @@ -629,6 +629,7 @@ static int add_rule_capability(struct landlock_ruleset *const ruleset, * - %EAFNOSUPPORT: @rule_type is %LANDLOCK_RULE_NET_PORT but TCP/IP is not * supported by the running kernel; * - %EINVAL: @flags is not valid; + * - %EINVAL: @rule_type is not valid; * - %EINVAL: The rule accesses are inconsistent (i.e. * &landlock_path_beneath_attr.allowed_access or * &landlock_net_port_attr.allowed_access is not a subset of the ruleset From ed52e47133f72195f246a9f70c98e47431bb566d Mon Sep 17 00:00:00 2001 From: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Date: Mon, 2 Nov 2026 16:48:30 +0800 Subject: [PATCH 1050/2102] fbdev: smscufx: don't free registered framebuffer on probe error register_framebuffer() can return an error after the framebuffer has already been installed: do_register_framebuffer() bumps info->count, creates /dev/fbN and stores the fb_info in registered_fb[] before it returns the result of the console takeover, and that takeover may fail. ufx_usb_probe() treats any error as "nothing was registered" and unwinds through reset_active, which releases the fb_info and drops both references to struct ufx_data, freeing @dev. The framebuffer stays registered and can still be opened, so the next open() of /dev/fbN reaches ufx_ops_open() with info->par pointing at freed memory: refcount_t: addition on 0; use-after-free. WARNING: lib/refcount.c:25 at refcount_warn_saturate Call Trace: kref_get ufx_ops_open drivers/video/fbdev/smscufx.c:1033 fb_open drivers/video/fbdev/core/fb_chrdev.c:351 chrdev_open ... refcount_t: underflow; use-after-free. WARNING: lib/refcount.c:28 at refcount_warn_saturate Call Trace: ufx_ops_release drivers/video/fbdev/smscufx.c:1135 fb_release drivers/video/fbdev/core/fb_chrdev.c:378 __fput Reuse the "has this fb_info been registered" test that ufx_setup_modes() already uses: take the error path only when refcount_read(&info->count) says the core did not register the framebuffer. A failed console takeover is not fatal for the driver, so report it and keep the framebuffer registered; the disconnect callback will unregister it normally. Fixes: 3c8a63e22a08 ("Add support for SMSC UFX6000/7000 USB display adapters") Signed-off-by: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Cc: stable@vger.kernel.org Signed-off-by: Helge Deller --- drivers/video/fbdev/smscufx.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/drivers/video/fbdev/smscufx.c b/drivers/video/fbdev/smscufx.c index 34d8abd5b35447..2a605ca94936a1 100644 --- a/drivers/video/fbdev/smscufx.c +++ b/drivers/video/fbdev/smscufx.c @@ -1700,8 +1700,16 @@ static int ufx_usb_probe(struct usb_interface *interface, dev_dbg(dev->gdev, "registering framebuffer"); retval = register_framebuffer(info); if (retval < 0) { - dev_err(dev->gdev, "error %d register_framebuffer", retval); - goto reset_active; + /* + * info is installed before the takeover can fail; freeing @dev + * here would leave registered_fb[] and /dev/fbN pointing at + * freed memory. + */ + if (!refcount_read(&info->count)) { /* not registered */ + dev_err(dev->gdev, "error %d register_framebuffer", retval); + goto reset_active; + } + dev_warn(dev->gdev, "console takeover failed: %d\n", retval); } dev_info(dev->gdev, "SMSC UDX USB device /dev/fb%d attached. %dx%d resolution." From e8645fe7419828fd95a90171149c565c1bb72911 Mon Sep 17 00:00:00 2001 From: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Date: Mon, 2 Nov 2026 16:57:24 +0800 Subject: [PATCH 1051/2102] fbdev: smscufx: keep the usb_device alive while ufx_data is in use ufx_usb_probe() stores the usb_device pointer in dev->udev without taking a reference, and ufx_usb_disconnect() does not wait for in-flight control transfers. A mode set or blank request that runs while the device is being unplugged - through ufx_ops_set_par() or ufx_ops_blank() on an open /dev/fbN file - keeps issuing synchronous control messages for the whole ufx_set_vid_mode() sequence, including two msleep(1) delays in ufx_config_pix_clk(). Once the disconnect callback returns, the USB core may release the usb_device, and the next ufx_reg_write()/ufx_reg_read() dereferences dev->udev through __create_pipe(): general protection fault, probably for non-canonical address 0xdffffc0000000006: 0000 [#1] SMP KASAN: null-ptr-deref in range [0x0000000000000030-0x0000000000000037] RIP: __create_pipe include/linux/usb.h:2031 Call Trace: ufx_set_vid_mode ufx_ops_set_par fb_set_var fb_set_var_from_user store_rotate Take a reference to the usb_device in ufx_usb_probe() and drop it in ufx_free(), so dev->udev and dev->gdev stay valid until the last ufx_data user is gone. The control transfers then fail with -ENODEV instead of dereferencing freed memory. Also return early from ufx_set_vid_mode() while the device is inactive, matching the other transmit paths. That check alone is not enough, because it is not serialized against ufx_usb_disconnect() and the transfer sequence continues after it; it only avoids a long series of failing transfers. Fixes: 3c8a63e22a08 ("Add support for SMSC UFX6000/7000 USB display adapters") Signed-off-by: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Cc: stable@vger.kernel.org Signed-off-by: Helge Deller --- drivers/video/fbdev/smscufx.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/drivers/video/fbdev/smscufx.c b/drivers/video/fbdev/smscufx.c index 2a605ca94936a1..61b5a09acf1675 100644 --- a/drivers/video/fbdev/smscufx.c +++ b/drivers/video/fbdev/smscufx.c @@ -661,8 +661,12 @@ static int ufx_set_vid_mode(struct ufx_data *dev, struct fb_var_screeninfo *var) u32 temp; u16 h_total, h_active, h_blank_start, h_blank_end, h_sync_start, h_sync_end; u16 v_total, v_active, v_blank_start, v_blank_end, v_sync_start, v_sync_end; + int status; + + if (!atomic_read(&dev->usb_active)) + return -ENODEV; - int status = ufx_reg_write(dev, 0x8028, 0); + status = ufx_reg_write(dev, 0x8028, 0); check_warn_return(status, "ufx_set_vid_mode error disabling RGB pad"); status = ufx_reg_write(dev, 0x8024, 0); @@ -1067,6 +1071,7 @@ static void ufx_free(struct kref *kref) { struct ufx_data *dev = container_of(kref, struct ufx_data, kref); + usb_put_dev(dev->udev); kfree(dev); } @@ -1609,6 +1614,8 @@ static int ufx_usb_probe(struct usb_interface *interface, dev->udev = usbdev; dev->gdev = &usbdev->dev; /* our generic struct device * */ + /* keep the device alive until the last ufx_data user is gone */ + usb_get_dev(usbdev); usb_set_intfdata(interface, dev); dev_dbg(dev->gdev, "%s %s - serial #%s\n", From ae14fe6f367a9779e108449b4af41791bd6aaa47 Mon Sep 17 00:00:00 2001 From: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Date: Mon, 2 Nov 2026 17:29:25 +0800 Subject: [PATCH 1052/2102] fbdev: smscufx: allocate the size advertised in smem_len ufx_realloc_framebuffer() allocates line_length * yres bytes but records PAGE_ALIGN(line_length * yres) in info->fix.smem_len. ufx_ops_set_par() clears the framebuffer by writing smem_len bytes, so the write runs past the end of the vmalloc() allocation whenever the mode size is not page aligned: BUG: KASAN: vmalloc-out-of-bounds in ufx_ops_set_par Write of size 2 at addr ffffc90005518600 Call Trace: ufx_ops_set_par ufx_usb_probe usb_probe_interface This runs from the probe path, before any client can open the device: with the fallback mode of 800x600 at 16 bpp the framebuffer is 960000 bytes and PAGE_ALIGN() adds 2560 bytes that were never allocated. Allocate the page aligned size that is published in smem_len instead, so the buffer covers every byte the driver and the framebuffer core can reach through smem_start and smem_len. Fixes: 3c8a63e22a08 ("Add support for SMSC UFX6000/7000 USB display adapters") Signed-off-by: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Cc: stable@vger.kernel.org Signed-off-by: Helge Deller --- drivers/video/fbdev/smscufx.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/video/fbdev/smscufx.c b/drivers/video/fbdev/smscufx.c index 61b5a09acf1675..ad3288b0d4df79 100644 --- a/drivers/video/fbdev/smscufx.c +++ b/drivers/video/fbdev/smscufx.c @@ -1285,9 +1285,10 @@ static int ufx_realloc_framebuffer(struct ufx_data *dev, struct fb_info *info) if (PAGE_ALIGN(new_len) > old_len) { /* - * Alloc system memory for virtual framebuffer + * Alloc system memory for virtual framebuffer. smem_len is + * rounded up to a page, so allocate that much as well. */ - new_fb = vmalloc(new_len); + new_fb = vmalloc(PAGE_ALIGN(new_len)); if (!new_fb) return -ENOMEM; From b3f1631d362539cfe14571ccfd7db919ffbc08c7 Mon Sep 17 00:00:00 2001 From: Jianqiang Zou Date: Sun, 1 Nov 2026 10:41:42 +0000 Subject: [PATCH 1053/2102] fbdev: radeonfb: reject a zero pixclock in radeonfb_check_var() radeonfb_set_par() derives the dot clock from the user supplied struct fb_var_screeninfo: dotClock = 1000000000 / pixClock; where pixClock is copied from mode->pixclock. A zero pixclock bypasses the existing validation and makes the kernel divide by zero in radeonfb_set_par(). The driver does have a check for this: fb_validate_mode() returns -EINVAL when pixclock is 0, but radeon_match_mode() only calls it when the output has no scaler and an EDID-derived mode database is available: if (has_rmx == 0 && rinfo->mon1_modedb) if (fb_validate_mode(...)) return -EINVAL; mon1_modedb is only filled in when an EDID is read, so when no EDID-derived mode database is available the validation is skipped and the invalid mode reaches radeonfb_set_par(). Reject a zero pixclock in radeonfb_check_var() before matching the mode. fb_set_var() calls it on the FBIOPUT_VSCREENINFO path before ->fb_set_par(), so the invalid value is rejected before the mode is applied. This is the same check other fbdev drivers use (i740fb, arkfb, s3fb). Reproduced on Linux 7.3.0 using a custom QEMU PCI stub device with vendor/device ID 1002:5955; no physical Radeon hardware was used. A single FBIOPUT_VSCREENINFO with pixclock = 0 is enough to trigger the divide error. Signed-off-by: Jianqiang Zou Cc: stable@vger.kernel.org Signed-off-by: Helge Deller --- drivers/video/fbdev/aty/radeon_base.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/video/fbdev/aty/radeon_base.c b/drivers/video/fbdev/aty/radeon_base.c index 387bc5f9676517..45dd42134e813a 100644 --- a/drivers/video/fbdev/aty/radeon_base.c +++ b/drivers/video/fbdev/aty/radeon_base.c @@ -836,6 +836,9 @@ static int radeonfb_check_var (struct fb_var_screeninfo *var, struct fb_info *in int nom, den; unsigned int pitch; + if (!var->pixclock) + return -EINVAL; + if (radeon_match_mode(rinfo, &v, var)) return -EINVAL; From ef925fd700ea8f64ce34225f9fea1d20ae3f3cab Mon Sep 17 00:00:00 2001 From: Miklos Szeredi Date: Tue, 3 Nov 2026 16:31:39 +0100 Subject: [PATCH 1054/2102] fuse: derive short read EOF from the request offset fuse_short_read() computed the new file size as folio_pos(ap->folios[0]) + num_read which assumes that the read started at the beginning of the first folio. That is not true in general: fuse_do_readfolio() may be asked to read part of a folio only, in which case it passes the offset within the folio in descs[0].offset and correctly adds it to the position of the request. If such a read came back short, the EOF derived from it would be descs[0].offset bytes too low and i_size would be truncated accordingly. fuse_send_readpages() made the same assumption for the position of the read request itself, even though fuse_copy_folios() fills the first folio starting at descs[0].offset. Neither is reachable today: sub-folio reads only originate from the iomap buffered write path, which requires fc->writeback_cache, and in that case fuse_short_read() does not update the size at all; readahead always starts on a folio boundary. Don't rely on that, though. Add fuse_folios_pos() to compute the position of the first byte covered by a folio array and use it for both read requests. Make fuse_short_read() take the fuse_io_args and derive EOF from ia->read.in.offset, i.e. the offset the request was actually sent with, so that the two can no longer disagree. fuse_do_readfolio() now keeps the attribute version in ia.read.attr_ver, as the readahead path already did. No functional change intended. Signed-off-by: Miklos Szeredi --- fs/fuse/file.c | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/fs/fuse/file.c b/fs/fuse/file.c index f09a0a348a1f5e..2242df3654bfc2 100644 --- a/fs/fuse/file.c +++ b/fs/fuse/file.c @@ -845,8 +845,19 @@ static void fuse_read_update_size(struct inode *inode, loff_t size, spin_unlock(&fi->lock); } -static void fuse_short_read(struct inode *inode, u64 attr_ver, size_t num_read, - struct fuse_args_pages *ap) +/* + * Position of the first byte covered by the folios in @ap. + * + * The first folio may be read partially, so the descriptor offset is part of + * the position. + */ +static loff_t fuse_folios_pos(struct fuse_args_pages *ap) +{ + return folio_pos(ap->folios[0]) + ap->descs[0].offset; +} + +static void fuse_short_read(struct inode *inode, struct fuse_io_args *ia, + size_t num_read) { struct fuse_conn *fc = get_fuse_conn(inode); @@ -856,8 +867,13 @@ static void fuse_short_read(struct inode *inode, u64 attr_ver, size_t num_read, * reached the client fs yet. So the hole is not present there. */ if (!fc->writeback_cache) { - loff_t pos = folio_pos(ap->folios[0]) + num_read; - fuse_read_update_size(inode, pos, attr_ver); + /* + * Derive EOF from the offset the request was sent with, which + * is not necessarily the start of the first folio. + */ + loff_t pos = ia->read.in.offset + num_read; + + fuse_read_update_size(inode, pos, ia->read.attr_ver); } } @@ -866,7 +882,6 @@ static int fuse_do_readfolio(struct file *file, struct folio *folio, { struct inode *inode = folio->mapping->host; struct fuse_mount *fm = get_fuse_mount(inode); - loff_t pos = folio_pos(folio) + off; struct fuse_folio_desc desc = { .offset = off, .length = len, @@ -878,10 +893,10 @@ static int fuse_do_readfolio(struct file *file, struct folio *folio, .ap.folios = &folio, .ap.descs = &desc, }; + loff_t pos = fuse_folios_pos(&ia.ap); ssize_t res; - u64 attr_ver; - attr_ver = fuse_get_attr_version(fm->fc); + ia.read.attr_ver = fuse_get_attr_version(fm->fc); /* * Don't overflow end offset. @@ -906,7 +921,7 @@ static int fuse_do_readfolio(struct file *file, struct folio *folio, * Short read means EOF. If file size is larger, truncate it */ if (res < len) - fuse_short_read(inode, attr_ver, res, &ia.ap); + fuse_short_read(inode, &ia, res); return 0; } @@ -1069,7 +1084,7 @@ static void fuse_readpages_end(struct fuse_args *args, int err) * Short read means EOF. If file size is larger, truncate it */ if (!err && num_read < count) - fuse_short_read(inode, ia->read.attr_ver, num_read, ap); + fuse_short_read(inode, ia, num_read); fuse_invalidate_atime(inode); @@ -1090,7 +1105,7 @@ static void fuse_send_readpages(struct fuse_io_args *ia, struct file *file, struct fuse_file *ff = file->private_data; struct fuse_mount *fm = ff->fm; struct fuse_args_pages *ap = &ia->ap; - loff_t pos = folio_pos(ap->folios[0]); + loff_t pos = fuse_folios_pos(ap); ssize_t res; int err; From 6df984631391616dafd9b989a3505d93ca4fd235 Mon Sep 17 00:00:00 2001 From: Miklos Szeredi Date: Tue, 3 Nov 2026 17:19:10 +0100 Subject: [PATCH 1055/2102] virtiofs: fix use-after-free of fs->tag on device removal The virtio_fs object is refcounted via its kobject, so a mount can keep it alive well beyond the lifetime of the virtio device binding. The tag string, however, was allocated with devm_kmalloc() and is therefore freed by devres_release_all() as soon as the device is unbound, i.e. right after virtio_fs_remove() returns (see device_unbind_cleanup() in drivers/base/dd.c). virtio_fs_get_tree() looks up the instance, takes a kobject reference and then drops virtio_fs_mutex before doing the sleepable part of the mount (allocations, fuse_conn_init(), sget_fc()). A concurrent device removal can complete in that window: CPU 0 (mount) CPU 1 (remove) ------------- -------------- virtio_fs_get_tree() virtio_fs_find_instance() // reference taken, mutex dropped virtio_fs_remove() list_del_init(&fs->list); // driver core unbinds device // devres frees fs->tag virtio_fs_fill_super() mutex_lock(&virtio_fs_mutex); if (list_empty(&fs->list)) pr_info(... fs->tag); <-- use-after-free The virtio_fs object itself is still valid here, only its tag has been freed behind its back. Fix the lifetime mismatch at the source: allocate the tag with kmalloc() and free it from virtio_fs_ktype_release(), so that it lives exactly as long as the object embedding it. All probe error paths already drop the final kobject reference, so they are covered. Merely dropping the tag from the error message would paper over this instance while leaving a devres pointer embedded in an object that routinely outlives its device. The other readers of fs->tag are unaffected: tag_show() is fenced off by the kobject_del() in virtio_fs_remove(), the automatic KOBJ_REMOVE uevent is emitted from __kobject_del() while the device is still bound, and both virtio_fs_add_instance() and virtio_fs_find_instance() only walk instances still on virtio_fs_instances. Fixes: a62a8ef9d97d ("virtio-fs: add virtiofs filesystem") Cc: Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-0328b3a1-043b-468e-8425-6a613d91b5ef Signed-off-by: Miklos Szeredi --- fs/fuse/virtio_fs.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/fs/fuse/virtio_fs.c b/fs/fuse/virtio_fs.c index ba8d79c4bcac6f..ef58bedc3941b3 100644 --- a/fs/fuse/virtio_fs.c +++ b/fs/fuse/virtio_fs.c @@ -193,6 +193,7 @@ static void virtio_fs_ktype_release(struct kobject *kobj) { struct virtio_fs *vfs = container_of(kobj, struct virtio_fs, kobj); + kfree(vfs->tag); kfree(vfs->mq_map); kfree(vfs->vqs); kfree(vfs); @@ -489,7 +490,11 @@ static void virtio_fs_free_devs(struct virtio_fs *fs) } } -/* Read filesystem name from virtio config into fs->tag (must kfree()). */ +/* + * Read filesystem name from virtio config into fs->tag. Freed by + * virtio_fs_ktype_release() so that it stays valid for as long as the + * virtio_fs object itself, which may outlive the virtio device. + */ static int virtio_fs_read_tag(struct virtio_device *vdev, struct virtio_fs *fs) { char tag_buf[sizeof_field(struct virtio_fs_config, tag)]; @@ -505,7 +510,7 @@ static int virtio_fs_read_tag(struct virtio_device *vdev, struct virtio_fs *fs) end = &tag_buf[sizeof(tag_buf)]; len = end - tag_buf; - fs->tag = devm_kmalloc(&vdev->dev, len + 1, GFP_KERNEL); + fs->tag = kmalloc(len + 1, GFP_KERNEL); if (!fs->tag) return -ENOMEM; memcpy(fs->tag, tag_buf, len); From 16fabae51accb1057582dcfe758fb1a8a852a07c Mon Sep 17 00:00:00 2001 From: Miklos Szeredi Date: Wed, 4 Nov 2026 09:54:59 +0100 Subject: [PATCH 1056/2102] virtiofs: disable request timeout The request timeout is implemented by aborting the connection: fuse_check_timeout() calls fuse_chan_abort(), which splices fpq->processing onto a local list and ends those requests. Ending a request wakes the waiting caller, which then drops the last reference and frees it. That is safe for /dev/fuse, where the request has already been copied out to userspace and nothing outside the kernel retains a pointer to it. It is not safe for virtiofs. virtio_fs_enqueue_req() passes the bare req as the virtqueue token, and the scatterlists point at req->in.h, req->out.h, req->argbuf and the request's folios; the device still owns all of that after the abort. When the device eventually completes the request, virtio_fs_requests_done_work() gets the freed req back from virtqueue_get_buf() and passes it to virtio_fs_verify_response() and virtio_fs_request_complete(), which dereference req->args - the caller's stack frame, long gone - and kfree() whatever req->argbuf now reads as. The device may also have written the reply into the freed request or into folios that have since been reused. This is precisely why virtio_fs_conn_destroy() drains all queues down to in_flight == 0 before calling fuse_conn_destroy(): once buffers are in a virtqueue, the only ways to reclaim them are to wait for completion or to reset the device. virtiofs already disables the other two paths that could abort a live connection, via ctx->no_control and ctx->no_force_umount; the timeout is the one that was left. Timeouts make little sense for virtiofs in the first place. A timeout is a guest-side reaction to a wedged host, and the guest has no recourse: it can neither take the buffers back nor make the host answer. So add fuse_conn::no_req_timeout for transports that cannot revoke a request once it has been handed to the server, set it from virtiofs, and use it to skip both fuse_init_server_timeout() and the FUSE_REQUEST_TIMEOUT negotiation flag. Skipping the former matters on its own: without it the fs/fuse/default_request_timeout sysctl would arm the timer even though FUSE_REQUEST_TIMEOUT was never offered to the server. Note that this is not a security issue. virtiofs inverts the usual fuse trust relationship - the server is the privileged, trusted side and the guest kernel is the untrusted one - so a server intent on corrupting guest memory has far more direct means at its disposal. Fixes: 0f6439f61a6e ("fuse: add kernel-enforced timeout option for requests") Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-8171ebf0-ef01-4ccd-943e-8633a8d54239 Signed-off-by: Miklos Szeredi --- fs/fuse/fuse_i.h | 10 ++++++++++ fs/fuse/inode.c | 9 ++++++--- fs/fuse/virtio_fs.c | 7 +++++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/fs/fuse/fuse_i.h b/fs/fuse/fuse_i.h index ec5ccdf18a255b..a033b0bc457626 100644 --- a/fs/fuse/fuse_i.h +++ b/fs/fuse/fuse_i.h @@ -418,6 +418,7 @@ struct fuse_fs_context { bool destroy:1; bool no_control:1; bool no_force_umount:1; + bool no_req_timeout:1; bool legacy_opts_show:1; bool syncfs_capable:1; enum fuse_vdax_mode vdax_mode; @@ -698,6 +699,15 @@ struct fuse_conn { /** @no_force_umount: Do not allow MNT_FORCE umount */ unsigned int no_force_umount:1; + /** + * @no_req_timeout: Do not enforce a request timeout + * + * Set by transports that cannot revoke a request once it has been + * handed to the server, since the timeout is implemented by aborting + * the connection. + */ + unsigned int no_req_timeout:1; + /** @auto_submounts: Auto-mount submounts announced by the server */ unsigned int auto_submounts:1; diff --git a/fs/fuse/inode.c b/fs/fuse/inode.c index 1341b681d0ed3a..3c0a629cc2fe49 100644 --- a/fs/fuse/inode.c +++ b/fs/fuse/inode.c @@ -1451,7 +1451,8 @@ static void process_init_reply(struct fuse_args *args, int error) fc->no_flock = 1; } - fuse_init_server_timeout(fc->chan, timeout); + if (!fc->no_req_timeout) + fuse_init_server_timeout(fc->chan, timeout); fm->sb->s_bdi->ra_pages = min(fm->sb->s_bdi->ra_pages, ra_pages); @@ -1502,8 +1503,9 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm) FUSE_HANDLE_KILLPRIV_V2 | FUSE_SETXATTR_EXT | FUSE_INIT_EXT | FUSE_SECURITY_CTX | FUSE_CREATE_SUPP_GROUP | FUSE_HAS_EXPIRE_ONLY | FUSE_DIRECT_IO_ALLOW_MMAP | - FUSE_NO_EXPORT_SUPPORT | FUSE_HAS_RESEND | FUSE_ALLOW_IDMAP | - FUSE_REQUEST_TIMEOUT; + FUSE_NO_EXPORT_SUPPORT | FUSE_HAS_RESEND | FUSE_ALLOW_IDMAP; + if (!fm->fc->no_req_timeout) + flags |= FUSE_REQUEST_TIMEOUT; #ifdef CONFIG_FUSE_VDAX if (fm->fc->vdax) flags |= FUSE_MAP_ALIGNMENT; @@ -1820,6 +1822,7 @@ int fuse_fill_super_common(struct super_block *sb, struct fuse_fs_context *ctx) fc->destroy = ctx->destroy; fc->no_control = ctx->no_control; fc->no_force_umount = ctx->no_force_umount; + fc->no_req_timeout = ctx->no_req_timeout; err = -ENOMEM; root = fuse_get_root_inode(sb, ctx->rootmode); diff --git a/fs/fuse/virtio_fs.c b/fs/fuse/virtio_fs.c index ef58bedc3941b3..c824916f0a9b41 100644 --- a/fs/fuse/virtio_fs.c +++ b/fs/fuse/virtio_fs.c @@ -1592,6 +1592,13 @@ static inline void virtio_fs_ctx_set_defaults(struct fuse_fs_context *ctx) ctx->destroy = true; ctx->no_control = true; ctx->no_force_umount = true; + /* + * A request handed to the device stays referenced by the virtqueue + * until the device completes it. The request timeout works by + * aborting the connection, which ends and frees such requests behind + * the device's back, so it must not be enabled here. + */ + ctx->no_req_timeout = true; } static int virtio_fs_fill_super(struct super_block *sb, struct fs_context *fsc) From 0d2eb896e634c5c843600780164a9fc0f0cedf72 Mon Sep 17 00:00:00 2001 From: Miklos Szeredi Date: Wed, 4 Nov 2026 11:03:39 +0100 Subject: [PATCH 1057/2102] virtiofs: zero the reply region of the argument buffer copy_args_to_argbuf() allocates one buffer for the fixed in- and out-args and fills only the in-arg part. The remainder is handed to the server as a device-writable buffer, and the server is under no obligation to write it: the used length it reports is its own claim and virtio_fs_verify_response() has nothing to cross-check it against. A reply that declares its full length without filling the buffer makes copy_args_from_argbuf() copy the uninitialized remainder to the caller, so a server that fails partway through writing a reply returns stale heap contents from e.g. fuse_statfs() or fuse_getxattr() instead of an error. Commit 5364d081125a ("virtiofs: validate fixed-output response length") covers the case where the declared length is short. Zero the reply region so that the remaining case yields zeroes rather than whatever the allocator last held. Only that region is zeroed; the in-arg part is overwritten by the copy below and the buffer can be as large as XATTR_SIZE_MAX. Fixes: a62a8ef9d97d ("virtio-fs: add virtiofs filesystem") Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-f0d6d4a3-f5df-4f72-ab09-802e5aab49a6 Signed-off-by: Miklos Szeredi --- fs/fuse/virtio_fs.c | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/fs/fuse/virtio_fs.c b/fs/fuse/virtio_fs.c index c824916f0a9b41..cdd6f5c50d6dbc 100644 --- a/fs/fuse/virtio_fs.c +++ b/fs/fuse/virtio_fs.c @@ -701,15 +701,16 @@ static int copy_args_to_argbuf(struct fuse_req *req, gfp_t gfp) unsigned int offset = 0; unsigned int num_in; unsigned int num_out; - unsigned int len; + unsigned int in_len; + unsigned int out_len; unsigned int i; num_in = args->in_numargs - args->in_pages; num_out = args->out_numargs - args->out_pages; - len = fuse_len_args(num_in, (struct fuse_arg *) args->in_args) + - fuse_len_args(num_out, args->out_args); + in_len = fuse_len_args(num_in, (struct fuse_arg *) args->in_args); + out_len = fuse_len_args(num_out, args->out_args); - req->argbuf = kmalloc(len, gfp); + req->argbuf = kmalloc(in_len + out_len, gfp); if (!req->argbuf) return -ENOMEM; @@ -720,6 +721,14 @@ static int copy_args_to_argbuf(struct fuse_req *req, gfp_t gfp) offset += args->in_args[i].size; } + /* + * The server is not required to fill the reply region and the length + * it reports in the used ring cannot confirm that it did. Zero the + * region so that an unwritten reply yields zeroes rather than stale + * heap contents. + */ + memset(req->argbuf + in_len, 0, out_len); + return 0; } From a8fdb9d75e7988e637816492ff08d51cff5dabd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Orkun=20Emin=20Sar=C4=B1?= Date: Thu, 5 Nov 2026 16:23:41 +0300 Subject: [PATCH 1058/2102] fuse: don't pass a NULL inode to fuse_inode_backing() on release MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cuse_release() and the error path of fuse_create_open() call fuse_prepare_release() with a NULL fuse_inode. Since commit bbe2d73a8231 ("fuse: don't assume ff->passthrough is set for FOPEN_PASSTHROUGH"), fuse_prepare_release() calls fuse_inode_backing(fi) whenever the open reply had FOPEN_PASSTHROUGH set, not only when ff->passthrough was set up. A CUSE server that sets FOPEN_PASSTHROUGH thus makes the kernel dereference a NULL pointer when the device is closed. Pass a NULL backing when there is no inode. fuse_passthrough_release() only prints it. Found with AI-assisted code review (Claude Code). Fixes: bbe2d73a8231 ("fuse: don't assume ff->passthrough is set for FOPEN_PASSTHROUGH") Signed-off-by: Orkun Emin Sarı Signed-off-by: Miklos Szeredi --- fs/fuse/file.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/fuse/file.c b/fs/fuse/file.c index 2242df3654bfc2..35e912b9851445 100644 --- a/fs/fuse/file.c +++ b/fs/fuse/file.c @@ -320,7 +320,7 @@ static void fuse_prepare_release(struct fuse_inode *fi, struct fuse_file *ff, struct fuse_release_args *ra = &ff->args->release_args; if (fuse_is_passthrough(ff)) - fuse_passthrough_release(ff, fuse_inode_backing(fi)); + fuse_passthrough_release(ff, fi ? fuse_inode_backing(fi) : NULL); /* Inode is NULL on error path of fuse_create_open() */ if (likely(fi)) { From f7e0ed317736fb33d18e0b903743c2d7f9faa92c Mon Sep 17 00:00:00 2001 From: Miklos Szeredi Date: Mon, 9 Nov 2026 15:45:55 +0100 Subject: [PATCH 1059/2102] fuse: don't mark inode DAX without CONFIG_FS_DAX fuse_init_inode() installs fuse_dax_aops and sets S_DAX for any regular file whose lookup reply carries FUSE_ATTR_DAX. Without CONFIG_FS_DAX, S_DAX is zero and IS_DAX() is constant false, so all of the checks that keep such inodes away from the page cache are compiled out: the "DAX inode without FOPEN_PASSTHROUGH" rejection in fuse_file_io_open(), the O_TRUNC check in fuse_open(), the truncate check in fuse_do_setattr(), the check in fuse_file_fallocate() and the one in fuse_passthrough_open(). The address space operations are installed regardless, so the inode ends up in caching I/O mode with aops that have neither ->read_folio nor ->readahead, and a buffered read, mmap fault or splice oopses on a NULL callback. Any user able to mount a fuse filesystem can trigger this. Only honor FUSE_ATTR_DAX if DAX can work at all. Fixes: 2fbe4586cff3 ("fuse: add support for opening dax device as backing") Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-bb232f07-d992-4dc6-a6c5-400e98e7133f Signed-off-by: Miklos Szeredi --- fs/fuse/inode.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/fs/fuse/inode.c b/fs/fuse/inode.c index 3c0a629cc2fe49..c6bfc66317ad4c 100644 --- a/fs/fuse/inode.c +++ b/fs/fuse/inode.c @@ -418,7 +418,14 @@ static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr, fuse_init_common(inode); fuse_init_file_inode(inode, attr->flags); - if ((attr->flags & FUSE_ATTR_DAX) && !fuse_inode_vdax(inode)) { + /* + * Without CONFIG_FS_DAX, S_DAX is zero and IS_DAX() is + * constant false, so all the checks that keep DAX inodes away + * from the page cache are compiled out. Don't install address + * space operations that have no ->read_folio in that case. + */ + if (IS_ENABLED(CONFIG_FS_DAX) && (attr->flags & FUSE_ATTR_DAX) && + !fuse_inode_vdax(inode)) { inode->i_flags |= S_DAX; inode->i_data.a_ops = &fuse_dax_aops; } From 6704a78171aa20caab2cd16da9ae2ff8edd4bb1d Mon Sep 17 00:00:00 2001 From: Miklos Szeredi Date: Tue, 10 Nov 2026 11:26:55 +0100 Subject: [PATCH 1060/2102] fuse: advertise support for DAX mappings Reuse the FUSE_HAS_INODE_DAX flag, which previously was only used for the virtiofs case. The two uses are unrelated: for virtiofs the flag means that host memory can be mapped directly into the guest, while here it means that the server may back an inode with a dax device opened via FUSE_DEV_IOC_BACKING_OPEN. Gate the advertisement on IS_REACHABLE(CONFIG_DEV_DAX_FSDEV), which is what fuse_backing_open_file() requires before it accepts a dax device as backing; CONFIG_FS_DAX alone is not sufficient. Plain fuse servers should check both FUSE_HAS_INODE_DAX and FUSE_PASSTHROUGH_V2 before enabling passthrough dax support. Stop advertising FUSE_PASSTHROUGH(_V2) in the virtiofs case, which doesn't support passthrough mode. Note: FUSE_HAS_INODE_DAX flag in the INIT reply is ignored, so it's handled slightly differently from the virtiofs case. This is deliberate. The server needs to check both FUSE_PASSTHROUGH_V2 and FUSE_HAS_INODE_DAX before enabling DAX based extent map if it wants to bail or fall back to plain I/O mode on kernels not supporting this feature. A broken server that does not check the features yet sets FUSE_ATTR_DAX will result in an error on open. This is not backward compatible, since this flag was silently ignored previously, but unlikely to be an issue in real life. Fixes: 2fbe4586cff3 ("fuse: add support for opening dax device as backing") Signed-off-by: Miklos Szeredi --- fs/fuse/fuse_i.h | 13 +++++++++++++ fs/fuse/inode.c | 32 +++++++++++++++++++++++++------- fs/fuse/virtio_fs.c | 1 + include/uapi/linux/fuse.h | 10 ++++++++-- 4 files changed, 47 insertions(+), 9 deletions(-) diff --git a/fs/fuse/fuse_i.h b/fs/fuse/fuse_i.h index a033b0bc457626..e0992fcbcc554f 100644 --- a/fs/fuse/fuse_i.h +++ b/fs/fuse/fuse_i.h @@ -421,6 +421,7 @@ struct fuse_fs_context { bool no_req_timeout:1; bool legacy_opts_show:1; bool syncfs_capable:1; + bool is_virtiofs:1; enum fuse_vdax_mode vdax_mode; unsigned int max_read; unsigned int blksize; @@ -761,6 +762,9 @@ struct fuse_conn { /** @sync_init: Is synchronous FUSE_INIT allowed? */ unsigned int sync_init:1; + /** @is_virtiofs: Is this a virtio-fs connection? */ + unsigned int is_virtiofs:1; + /** @max_stack_depth: Maximum stack depth for passthrough backing files */ int max_stack_depth; @@ -1273,6 +1277,15 @@ void fuse_free_conn(struct fuse_conn *fc); /* dax.c */ +static inline bool fuse_conn_vdax(struct fuse_conn *fc) +{ +#ifdef CONFIG_FUSE_VDAX + return fc->vdax; +#else + return false; +#endif +} + static inline bool fuse_inode_vdax(struct inode *inode) { #ifdef CONFIG_FUSE_VDAX diff --git a/fs/fuse/inode.c b/fs/fuse/inode.c index c6bfc66317ad4c..af6d9e0af190b0 100644 --- a/fs/fuse/inode.c +++ b/fs/fuse/inode.c @@ -385,7 +385,7 @@ static void fuse_change_attributes_i(struct inode *inode, struct fuse_attr *attr invalidate_inode_pages2(inode->i_mapping); } - if (IS_ENABLED(CONFIG_FUSE_VDAX)) + if (fuse_conn_vdax(fc)) fuse_vdax_dontcache(inode, attr->flags); } @@ -419,13 +419,18 @@ static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr, fuse_init_file_inode(inode, attr->flags); /* + * FUSE_ATTR_DAX means a passthrough extent map on a dax + * device, which only exists on a plain fuse connection. On + * virtiofs the same bit means per inode virtiofs DAX, which + * is handled by fuse_vdax_inode_init() instead. + * * Without CONFIG_FS_DAX, S_DAX is zero and IS_DAX() is * constant false, so all the checks that keep DAX inodes away * from the page cache are compiled out. Don't install address * space operations that have no ->read_folio in that case. */ - if (IS_ENABLED(CONFIG_FS_DAX) && (attr->flags & FUSE_ATTR_DAX) && - !fuse_inode_vdax(inode)) { + if (IS_ENABLED(CONFIG_FS_DAX) && !fc->is_virtiofs && + (attr->flags & FUSE_ATTR_DAX)) { inode->i_flags |= S_DAX; inode->i_data.a_ops = &fuse_dax_aops; } @@ -1394,7 +1399,7 @@ static void process_init_reply(struct fuse_args *args, int error) !fuse_vdax_check_alignment(fc, arg->map_alignment)) { ok = false; } - if (flags & FUSE_HAS_INODE_DAX) + if (fuse_conn_vdax(fc) && (flags & FUSE_HAS_INODE_DAX)) fc->inode_vdax = 1; } if (flags & FUSE_HANDLE_KILLPRIV_V2) { @@ -1423,7 +1428,7 @@ static void process_init_reply(struct fuse_args *args, int error) * and FUSE_WRITEBACK_CACHE, current design doesn't handle * them together. */ - if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH) && + if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH) && !fm->fc->is_virtiofs && (flags & (FUSE_PASSTHROUGH | FUSE_PASSTHROUGH_V2)) && arg->max_stack_depth > 0 && arg->max_stack_depth <= FILESYSTEM_MAX_STACK_DEPTH && @@ -1516,13 +1521,25 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm) #ifdef CONFIG_FUSE_VDAX if (fm->fc->vdax) flags |= FUSE_MAP_ALIGNMENT; - if (fuse_is_inode_vdax_mode(fm->fc->vdax_mode)) + if (fm->fc->vdax && fuse_is_inode_vdax_mode(fm->fc->vdax_mode)) flags |= FUSE_HAS_INODE_DAX; #endif if (fm->fc->auto_submounts) flags |= FUSE_SUBMOUNTS; - if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH)) + /* + * Passthrough requires a backing file registered with + * FUSE_DEV_IOC_BACKING_OPEN on the fuse device, which a virtiofs + * server has no way to do. + */ + if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH) && !fm->fc->is_virtiofs) { flags |= FUSE_PASSTHROUGH | FUSE_PASSTHROUGH_V2; + /* + * Per inode DAX needs a dax device opened as backing, which + * is unrelated to how virtiofs uses the same flag above. + */ + if (IS_REACHABLE(CONFIG_DEV_DAX_FSDEV)) + flags |= FUSE_HAS_INODE_DAX; + } /* Only offered to sufficiently privileged servers; see * fuse_syncfs_enable(). */ @@ -1830,6 +1847,7 @@ int fuse_fill_super_common(struct super_block *sb, struct fuse_fs_context *ctx) fc->no_control = ctx->no_control; fc->no_force_umount = ctx->no_force_umount; fc->no_req_timeout = ctx->no_req_timeout; + fc->is_virtiofs = ctx->is_virtiofs; err = -ENOMEM; root = fuse_get_root_inode(sb, ctx->rootmode); diff --git a/fs/fuse/virtio_fs.c b/fs/fuse/virtio_fs.c index cdd6f5c50d6dbc..e17c96fa876e4c 100644 --- a/fs/fuse/virtio_fs.c +++ b/fs/fuse/virtio_fs.c @@ -1827,6 +1827,7 @@ static int virtio_fs_init_fs_context(struct fs_context *fsc) ctx = kzalloc_obj(struct fuse_fs_context); if (!ctx) return -ENOMEM; + ctx->is_virtiofs = true; fsc->fs_private = ctx; fsc->ops = &virtio_fs_context_ops; return 0; diff --git a/include/uapi/linux/fuse.h b/include/uapi/linux/fuse.h index 616430a2973c6e..cb9e9554f0efc0 100644 --- a/include/uapi/linux/fuse.h +++ b/include/uapi/linux/fuse.h @@ -257,6 +257,7 @@ * - add backing_id_64 to fuse_open_out * - add FUSE_NOTIFY_BACKING_MAP, fuse_notify_backing_map_out, fuse_extent * - add FUSE_BACKING_MAP_CREATE, FUSE_BACKING_MAP_CYCLIC + * - extend the meaning of FUSE_HAS_INODE_DAX and FUSE_ATTR_DAX */ #ifndef _LINUX_FUSE_H @@ -460,7 +461,11 @@ struct fuse_file_lock { * FUSE_INIT_RESERVED: reserved, do not use * FUSE_SECURITY_CTX: add security context to create, mkdir, symlink, and * mknod - * FUSE_HAS_INODE_DAX: use per inode DAX + * FUSE_HAS_INODE_DAX: use per inode DAX. The meaning depends on the + * transport: on virtio-fs it indicates per-inode DAX + * support, while on /dev/fuse (where FUSE_PASSTHROUGH_V2 + * is also offered) it indicates support for passthrough + * extent maps on a DAX device. * FUSE_CREATE_SUPP_GROUP: add supplementary group info to create, mkdir, * symlink and mknod (single group that matches parent) * FUSE_HAS_EXPIRE_ONLY: kernel supports expiry-only entry invalidation @@ -612,7 +617,8 @@ struct fuse_file_lock { * fuse_attr flags * * FUSE_ATTR_SUBMOUNT: Object is a submount root - * FUSE_ATTR_DAX: Enable DAX for this file in per inode DAX mode + * FUSE_ATTR_DAX: Enable DAX for this file in per inode DAX mode and in + * extent mapping passthrough mode */ #define FUSE_ATTR_SUBMOUNT (1 << 0) #define FUSE_ATTR_DAX (1 << 1) From fea42fae07822cd717ba4b3082834bb5908bf911 Mon Sep 17 00:00:00 2001 From: Leon Ming Date: Wed, 28 Oct 2026 20:37:00 -0700 Subject: [PATCH 1061/2102] fuse: set dentry epoch before making the dentry visible fuse_lookup(), create_new_entry(), fuse_create_open() and fuse_direntplus_link() set the dentry epoch only after d_splice_alias() or d_instantiate() has made the dentry visible. A new dentry starts at epoch 0 and the connection at epoch 1, so in that window a concurrent lookup can find the dentry, fail fuse_dentry_revalidate() and d_invalidate() it. The original lookup then returns an unhashed dentry, and readlink() of /proc/self/fd/N on an O_PATH fd for it says " (deleted)" for a file that exists. Anything that resolves real paths with open(O_PATH) + readlink() can pick up the bogus path; TypeScript's native compiler (tsgo) intermittently fails to find installed packages this way. It got much more common after commit 5a6baf204610 ("fuse: fix uninit-value in fuse_dentry_revalidate()") zeroed the initial epoch; before that, slab garbage usually passed the check. Set the epoch before the dentry is published, and keep setting it on any alias that d_splice_alias() returns; the dentry that loses to an alias is dropped without ever being visible, so setting it too is harmless. With 32 processes making concurrent first lookups of 6000 files on a fresh squashfuse_ll mount (UML, 16 CPUs), 1652 of 10.75M lookups came back "(deleted)" before this patch and none after. Fixes: 2396356a945b ("fuse: add more control over cache invalidation behaviour") Cc: stable@vger.kernel.org Signed-off-by: Leon Ming Signed-off-by: Miklos Szeredi --- fs/fuse/dir.c | 12 ++++++++---- fs/fuse/readdir.c | 5 ++++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/fs/fuse/dir.c b/fs/fuse/dir.c index da23ccd8685cfe..a04d93d5fc4473 100644 --- a/fs/fuse/dir.c +++ b/fs/fuse/dir.c @@ -644,13 +644,17 @@ static struct dentry *fuse_lookup(struct inode *dir, struct dentry *entry, if (inode && get_node_id(inode) == FUSE_ROOT_ID) goto out_iput; + /* Set before the dentry is visible, or a racing lookup invalidates it */ + fuse_dentry_set_epoch(entry, epoch); newent = d_splice_alias(inode, entry); err = PTR_ERR(newent); if (IS_ERR(newent)) goto out_err; - entry = newent ? newent : entry; - fuse_dentry_set_epoch(entry, epoch); + if (newent) { + entry = newent; + fuse_dentry_set_epoch(entry, epoch); + } if (outarg_valid) fuse_change_entry_timeout(entry, &outarg); else @@ -907,8 +911,8 @@ static int fuse_create_open(const struct mnt_idmap *idmap, struct inode *dir, goto out_err; } kfree(forget); - d_instantiate(entry, inode); fuse_dentry_set_epoch(entry, epoch); + d_instantiate(entry, inode); fuse_change_entry_timeout(entry, &outentry); fuse_dir_changed(dir); err = generic_file_open(inode, file); @@ -1030,6 +1034,7 @@ static struct dentry *create_new_entry(const struct mnt_idmap *idmap, struct fus fuse_chan_queue_forget(fm->fc->chan, forget, outarg.nodeid, 1); return ERR_PTR(-ENOMEM); } + fuse_dentry_set_epoch(entry, epoch); kfree(forget); d = d_splice_alias(inode, entry); @@ -1040,7 +1045,6 @@ static struct dentry *create_new_entry(const struct mnt_idmap *idmap, struct fus fuse_dentry_set_epoch(d, epoch); fuse_change_entry_timeout(d, &outarg); } else { - fuse_dentry_set_epoch(entry, epoch); fuse_change_entry_timeout(entry, &outarg); } fuse_dir_changed(dir); diff --git a/fs/fuse/readdir.c b/fs/fuse/readdir.c index f4f9590f8ae534..e56cdd88513a3b 100644 --- a/fs/fuse/readdir.c +++ b/fs/fuse/readdir.c @@ -228,6 +228,7 @@ static int fuse_direntplus_link(struct file *file, fuse_change_attributes(inode, &o->attr, NULL, ATTR_TIMEOUT(o), attr_version); + fuse_dentry_set_epoch(dentry, epoch); /* * The other branch comes via fuse_iget() * which bumps nlookup inside @@ -242,6 +243,7 @@ static int fuse_direntplus_link(struct file *file, return -ENOMEM; } + fuse_dentry_set_epoch(dentry, epoch); ihold(inode); /* d_splice_alias() eats a reference */ alias = d_splice_alias(inode, dentry); d_lookup_done(dentry); @@ -258,11 +260,12 @@ static int fuse_direntplus_link(struct file *file, iput(inode); return PTR_ERR(dentry); } + if (alias) + fuse_dentry_set_epoch(dentry, epoch); iput(inode); } if (fc->readdirplus_auto) set_bit(FUSE_I_INIT_RDPLUS, &get_fuse_inode(inode)->state); - fuse_dentry_set_epoch(dentry, epoch); fuse_change_entry_timeout(dentry, o); dput(dentry); From 2eb2329f9ce7f29f227656cc2686fe6f1879d11c Mon Sep 17 00:00:00 2001 From: Hengyu Liang Date: Sat, 17 Oct 2026 05:46:01 -0400 Subject: [PATCH 1062/2102] fuse: preserve ENOTCONN after failed initialization and disconnect Commit 794e811d1443 ("fuse: split out filesystem part of request sending") moved the INIT failure check into fuse_req_prep(), before the channel checks whether it is still connected. If a daemon closes /dev/fuse before replying to INIT, aborting the channel completes INIT with an error. stat() and open() on the mount then return ECONNREFUSED instead of the previous ENOTCONN. The same change occurs when INIT is rejected before the daemon closes the fd. Record INIT failure in the channel before publishing initialized, and check it in fuse_get_req() after waiting for initialization and checking for disconnection. This preserves ECONNREFUSED for failed INIT while the device remains open, and restores ENOTCONN after disconnection. Set the failure flag only while the channel is connected, since abort also marks it initialized to wake waiters after a successful INIT. Fixes: 794e811d1443 ("fuse: split out filesystem part of request sending") Cc: stable@vger.kernel.org Signed-off-by: Hengyu Liang Signed-off-by: Miklos Szeredi --- fs/fuse/dev.c | 8 ++++++++ fs/fuse/fuse_dev_i.h | 3 +++ fs/fuse/req.c | 15 +++------------ 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/fs/fuse/dev.c b/fs/fuse/dev.c index 3641abb90d6bb3..ec2306c63d0d7b 100644 --- a/fs/fuse/dev.c +++ b/fs/fuse/dev.c @@ -80,6 +80,10 @@ void fuse_chan_set_initialized(struct fuse_chan *fch, struct fuse_chan_param *pa fuse_uring_conn_init(fch); } + /* An aborted channel is also marked initialized to wake waiters. */ + if (!param && fch->connected) + fch->conn_refused = true; + /* Pairs with smp_load_acquire() readers of fch->initialized */ smp_store_release(&fch->initialized, 1); wake_up_all(&fch->blocked_waitq); @@ -130,6 +134,10 @@ static struct fuse_req *fuse_get_req(struct fuse_chan *fch, bool for_background) if (!fch->connected) goto out; + err = -ECONNREFUSED; + if (fch->conn_refused) + goto out; + req = fuse_request_alloc(fch, GFP_KERNEL); err = -ENOMEM; if (!req) { diff --git a/fs/fuse/fuse_dev_i.h b/fs/fuse/fuse_dev_i.h index 4b412a76225f86..0c078bdc270c51 100644 --- a/fs/fuse/fuse_dev_i.h +++ b/fs/fuse/fuse_dev_i.h @@ -245,6 +245,9 @@ struct fuse_chan { /** Is interrupt not implemented by fs? */ bool no_interrupt; + /** @conn_refused: INIT failed while the channel was still connected. */ + bool conn_refused; + /* Use io_uring for communication */ unsigned int io_uring; diff --git a/fs/fuse/req.c b/fs/fuse/req.c index 6274a23af445c1..d96b947c61e6ad 100644 --- a/fs/fuse/req.c +++ b/fs/fuse/req.c @@ -49,20 +49,11 @@ static int fuse_fill_creds(struct fuse_mount *fm, struct fuse_args *args, return 0; } -static int fuse_req_prep(struct fuse_mount *fm, struct fuse_args *args, - const struct mnt_idmap *idmap) -{ - if (!args->force && fm->fc->conn_error) - return -ECONNREFUSED; - - return fuse_fill_creds(fm, args, idmap); -} - ssize_t __fuse_simple_request(const struct mnt_idmap *idmap, struct fuse_mount *fm, struct fuse_args *args) { struct fuse_conn *fc = fm->fc; - int err = fuse_req_prep(fm, args, idmap); + int err = fuse_fill_creds(fm, args, idmap); if (err) return err; @@ -77,7 +68,7 @@ int fuse_simple_background(struct fuse_mount *fm, struct fuse_args *args, gfp_t WARN_ON(args->force && !args->nocreds); - err = fuse_req_prep(fm, args, &invalid_mnt_idmap); + err = fuse_fill_creds(fm, args, &invalid_mnt_idmap); if (err) return err; @@ -92,7 +83,7 @@ int fuse_simple_notify_reply(struct fuse_mount *fm, struct fuse_args *args, u64 WARN_ON(args->force && !args->nocreds); - err = fuse_req_prep(fm, args, &invalid_mnt_idmap); + err = fuse_fill_creds(fm, args, &invalid_mnt_idmap); if (err) return err; From ae932b1f5727004f585d603e0cbab7e0725c04cf Mon Sep 17 00:00:00 2001 From: Junyoung Jang Date: Tue, 17 Nov 2026 22:51:35 +0900 Subject: [PATCH 1063/2102] fuse: skip dcache instantiation for readdirplus names with embedded NUL FUSE READDIRPLUS can pass a length-bearing qstr with an embedded NUL to d_splice_alias(). Unlike verify_dirent_name() in fs/readdir.c, this path can create a dentry whose d_name.len extends past the NUL. For such a name, strscpy() in inotify_handle_inode_event() and the fanotify name-copy helpers stop early. The kmalloc() and kvmalloc() event-name buffers retain uninitialized bytes within the recorded name length, which copy_event_to_user() and copy_fid_info_to_user() can expose. Some FUSE servers include a terminating NUL in namelen. Follow nfs_prime_dcache() in commit 78d04af4995a1 ("NFS: nfs_prime_dcache must validate the filename") by skipping dcache instantiation without failing getdents(). Return -EIO from fuse_direntplus_link() so parse_dirplusfile() sends FUSE_FORGET for the unused lookup reference and continues readdir. Fixes: 0b05b18381ee ("fuse: implement NFS-like readdirplus support") Cc: stable@vger.kernel.org Co-developed-by: Gwanhyun Lee Signed-off-by: Gwanhyun Lee Signed-off-by: Junyoung Jang Reviewed-by: Amir Goldstein Signed-off-by: Miklos Szeredi --- fs/fuse/readdir.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/fs/fuse/readdir.c b/fs/fuse/readdir.c index e56cdd88513a3b..c1e2a8fd834e93 100644 --- a/fs/fuse/readdir.c +++ b/fs/fuse/readdir.c @@ -192,6 +192,8 @@ static int fuse_direntplus_link(struct file *file, return -EIO; if (fuse_invalid_attr(&o->attr)) return -EIO; + if (memchr(name.name, '\0', name.len)) + return -EIO; fc = get_fuse_conn(dir); epoch = atomic_read(&fc->epoch); From 6008a6e34ca0446739abfff189902af2214cfff1 Mon Sep 17 00:00:00 2001 From: Carlos Song Date: Thu, 19 Nov 2026 18:15:39 +0800 Subject: [PATCH 1064/2102] spi: fsl-lpspi: expand FCR TWATER and RXWATER bit fields to 4 bits The original FCR[TWATER|RXWATER] fields were defined as 3-bit values, limiting the FIFO watermark to values 0-7. This is sufficient for LPSPI instances with 8-word FIFOs (like i.MX93) where watermark = FIFO_SIZE/2. However, platforms like i.MX95 feature 16-word FIFOs requiring watermark values up to 8, which exceeds the 3-bit field capacity. Expands both TXWATER and RXWATER fields from 3 bits to 4 bits to support larger FIFO configurations across various IMX platforms while maintaining backward compatibility with existing 8-word FIFO implementations. Fixes: 732b903ea3e2 ("spi: spi-fsl-lpspi: fsl_lpspi_set_watermark(): use FIELD_PREP() to encode FIFO Control register") Signed-off-by: Carlos Song Reviewed-by: Marc Kleine-Budde Link: https://patch.msgid.link/20261119101539.2536367-1-carlos.song@oss.nxp.com Signed-off-by: Mark Brown --- drivers/spi/spi-fsl-lpspi.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/spi/spi-fsl-lpspi.c b/drivers/spi/spi-fsl-lpspi.c index b25f94b2ef738f..cea72d0340357c 100644 --- a/drivers/spi/spi-fsl-lpspi.c +++ b/drivers/spi/spi-fsl-lpspi.c @@ -75,8 +75,8 @@ #define CFGR1_PCSPOL_MASK GENMASK(11, 8) #define CFGR1_NOSTALL BIT(3) #define CFGR1_HOST BIT(0) -#define FCR_RXWATER GENMASK(18, 16) -#define FCR_TXWATER GENMASK(2, 0) +#define FCR_RXWATER GENMASK(19, 16) +#define FCR_TXWATER GENMASK(3, 0) #define FSR_TXCOUNT (0xFF) #define RSR_RXEMPTY BIT(1) #define TCR_CPOL BIT(31) From d7e77168da348d8ac0fdb3b3aa7ce1ccc83208a7 Mon Sep 17 00:00:00 2001 From: Cen Zhang Date: Thu, 19 Nov 2026 08:32:45 +0800 Subject: [PATCH 1065/2102] Bluetooth: hci_sync: Fix remaining advertising instance UAFs hci_enable_ext_advertising_sync() looks up the advertising instance without hdev->lock and then reads it, while HCI event processing can free the instance under the lock: Request work HCI event work hci_enable_ext_advertising_sync() adv = hci_find_adv_instance() hci_cc_le_clear_adv_sets() hci_dev_lock(hdev) hci_remove_adv_instance() kfree(adv) hci_dev_unlock(hdev) reads adv->enabled Since the conversion to hci_sync, the advertising request paths run without hdev->lock, and the periodic advertising, advertising timeout and mesh code added later does the same, while management commands and HCI event processing still add and free instances under the lock. The same unlocked use exists in: - hci_set_adv_data_sync(), hci_disable_ext_adv_instance_sync(), the periodic advertising enable and disable helpers, hci_schedule_adv_instance_sync(), adv_expire_sync() and set_advertising_complete() - hci_enable_advertising_sync() and hci_start_per_adv_sync(), which keep the instance across HCI commands - hci_remove_advertising_sync() and hci_clear_adv_instance_sync(), which keep the next instance as a pointer - mesh_send_sync(), which adds the mesh instance - the walks of hdev->adv_instances in hci_dev_open_sync(), hci_dev_close_sync(), hci_resume_advertising_sync() and hci_powered_update_adv_sync() Fix them as commit cdc36db204ff ("Bluetooth: hci_sync: Fix advertising data UAFs") does for the extended advertising data paths: look the instance up under hdev->lock, copy what is needed, and release the lock before a command is sent, since command completion handlers take it. Keep the next instance as an instance number. Walks that send no command hold the lock, as hci_clear_adv_sync() does. The resume and power on walks send a command per instance and cannot hold it, so they copy the instance numbers under the lock into a fixed stack array first. Instance identifiers are nonzero u8 values, so 255 bytes cover the whole namespace. This preserves list order without adding an allocation failure after the resume path consumes its pause state. Use a u32 for the timeout-to-milliseconds conversion before converting to the controller's 10 ms units, and clamp the result to U16_MAX. The old u16 intermediate wrapped timeouts longer than 65 seconds. KASAN report as below: BUG: KASAN: slab-use-after-free in hci_enable_ext_advertising_sync+0x2fd/0x330 Read of size 1 at addr ffff88811673b810 by task kworker/u17:0/492 Workqueue: hci0 hci_cmd_sync_work Call Trace: hci_enable_ext_advertising_sync+0x2fd/0x330 add_ext_adv_data_sync+0x1f8/0x250 hci_cmd_sync_work+0x1b3/0x450 Allocated by task 490: hci_add_adv_instance+0x627/0x960 add_ext_adv_params+0x4d4/0xaf0 hci_sock_sendmsg+0x128b/0x22e0 Freed by task 495: kfree+0x307/0x580 hci_remove_adv_instance+0x226/0x4f0 hci_cc_le_clear_adv_sets+0x2a5/0x400 hci_cmd_complete_evt+0x373/0xab0 hci_event_packet+0x4e8/0xc70 hci_rx_work+0x367/0xf00 The buggy address belongs to the object at ffff88811673b800 which belongs to the cache kmalloc-1k of size 1024 The buggy address is located 16 bytes inside of freed 1024-byte region [ffff88811673b800, ffff88811673bc00) Fixes: cba6b758711c ("Bluetooth: hci_sync: Make use of hci_cmd_sync_queue set 2") Fixes: eca0ae4aea66 ("Bluetooth: Add initial implementation of BIS connections") Fixes: c249ea9b4309 ("Bluetooth: Move Adv Instance timer to hci_sync") Fixes: b338d91703fa ("Bluetooth: Implement support for Mesh") Signed-off-by: Cen Zhang Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_sync.c | 245 +++++++++++++++++++++++++++++---------- net/bluetooth/mgmt.c | 29 +++-- 2 files changed, 203 insertions(+), 71 deletions(-) diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index d7ca28f9c13552..d15e95e75d61cf 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -501,7 +501,8 @@ static void cancel_adv_timeout(struct hci_dev *hdev) int hci_clear_adv_instance_sync(struct hci_dev *hdev, struct sock *sk, u8 instance, bool force) { - struct adv_info *adv_instance, *n, *next_instance = NULL; + struct adv_info *adv_instance, *n; + u8 next_instance = 0; int err; u8 rem_inst; @@ -509,12 +510,20 @@ int hci_clear_adv_instance_sync(struct hci_dev *hdev, struct sock *sk, if (!instance || hdev->cur_adv_instance == instance) cancel_adv_timeout(hdev); + /* This is safe as long as there is no command send while the + * lock is held. + */ + hci_dev_lock(hdev); + /* Get the next instance to advertise BEFORE we remove * the current one. This can be the same instance again * if there is only one instance. */ - if (instance && hdev->cur_adv_instance == instance) - next_instance = hci_get_next_instance(hdev, instance); + if (instance && hdev->cur_adv_instance == instance) { + adv_instance = hci_get_next_instance(hdev, instance); + if (adv_instance) + next_instance = adv_instance->instance; + } if (instance == 0x00) { list_for_each_entry_safe(adv_instance, n, &hdev->adv_instances, @@ -533,9 +542,8 @@ int hci_clear_adv_instance_sync(struct hci_dev *hdev, struct sock *sk, if (force || (adv_instance && adv_instance->timeout && !adv_instance->remaining_time)) { /* Don't advertise a removed instance. */ - if (next_instance && - next_instance->instance == instance) - next_instance = NULL; + if (next_instance == instance) + next_instance = 0; err = hci_remove_adv_instance(hdev, instance); if (!err) @@ -543,12 +551,13 @@ int hci_clear_adv_instance_sync(struct hci_dev *hdev, struct sock *sk, } } + hci_dev_unlock(hdev); + if (!hdev_is_powered(hdev) || hci_dev_test_flag(hdev, HCI_ADVERTISING)) return 0; if (next_instance && !ext_adv_capable(hdev)) - return hci_schedule_adv_instance_sync(hdev, - next_instance->instance, + return hci_schedule_adv_instance_sync(hdev, next_instance, false); return 0; @@ -1429,14 +1438,21 @@ static int hci_set_ext_adv_data_sync(struct hci_dev *hdev, u8 instance) } static int hci_set_adv_data_sync(struct hci_dev *hdev, u8 instance) + __context_unsafe(/* conditional locking */) { struct hci_cp_le_set_adv_data cp; u8 len; memset(&cp, 0, sizeof(cp)); + if (instance) + hci_dev_lock(hdev); + len = eir_create_adv_data(hdev, instance, cp.data, sizeof(cp.data)); + if (instance) + hci_dev_unlock(hdev); + /* There's nothing to do if the data hasn't changed */ if (hdev->adv_data_len == len && memcmp(cp.data, hdev->adv_data, len) == 0) @@ -1725,17 +1741,33 @@ int hci_enable_ext_advertising_sync(struct hci_dev *hdev, u8 instance) struct hci_cp_le_set_ext_adv_enable *cp; struct hci_cp_ext_adv_set *set; u8 data[sizeof(*cp) + sizeof(*set) * 1]; - struct adv_info *adv; + u8 handle = instance; + u32 duration = 0; if (instance > 0) { + struct adv_info *adv; + + hci_dev_lock(hdev); adv = hci_find_adv_instance(hdev, instance); - if (!adv) + if (!adv) { + hci_dev_unlock(hdev); return -EINVAL; + } /* If already enabled there is nothing to do */ - if (adv->enabled) + if (adv->enabled) { + hci_dev_unlock(hdev); return 0; - } else { - adv = NULL; + } + + handle = adv->handle; + + /* Set duration per instance since controller is + * responsible for scheduling it. + */ + if (adv->timeout) + duration = adv->mesh ? adv->timeout : + adv->timeout * MSEC_PER_SEC; + hci_dev_unlock(hdev); } cp = (void *)data; @@ -1748,18 +1780,10 @@ int hci_enable_ext_advertising_sync(struct hci_dev *hdev, u8 instance) memset(set, 0, sizeof(*set)); - set->handle = adv ? adv->handle : instance; - - /* Set duration per instance since controller is responsible for - * scheduling it. - */ - if (adv && adv->timeout) { - u16 duration = adv->mesh ? adv->timeout : - adv->timeout * MSEC_PER_SEC; + set->handle = handle; - /* Time = N * 10 ms */ - set->duration = cpu_to_le16(duration / 10); - } + /* Time = N * 10 ms */ + set->duration = cpu_to_le16(min_t(u32, duration / 10, U16_MAX)); /* Track which instance owns the advertising set since the handle * alone is ambiguous when instances share handle 0x00, see @@ -1791,11 +1815,15 @@ int hci_start_ext_adv_sync(struct hci_dev *hdev, u8 instance) int hci_disable_per_advertising_sync(struct hci_dev *hdev, u8 instance) { struct hci_cp_le_set_per_adv_enable cp; - struct adv_info *adv = NULL; + struct adv_info *adv; + bool enabled; /* If periodic advertising already disabled there is nothing to do. */ + hci_dev_lock(hdev); adv = hci_find_adv_instance(hdev, instance); - if (!adv || !adv->periodic_enabled) + enabled = adv && adv->periodic_enabled; + hci_dev_unlock(hdev); + if (!enabled) return 0; memset(&cp, 0, sizeof(cp)); @@ -1864,11 +1892,15 @@ static int hci_set_per_adv_data_sync(struct hci_dev *hdev, u8 instance) static int hci_enable_per_advertising_sync(struct hci_dev *hdev, u8 instance) { struct hci_cp_le_set_per_adv_enable cp; - struct adv_info *adv = NULL; + struct adv_info *adv; + bool enabled; /* If periodic advertising already enabled there is nothing to do. */ + hci_dev_lock(hdev); adv = hci_find_adv_instance(hdev, instance); - if (adv && adv->periodic_enabled) + enabled = adv && adv->periodic_enabled; + hci_dev_unlock(hdev); + if (enabled) return 0; memset(&cp, 0, sizeof(cp)); @@ -1883,25 +1915,36 @@ static int hci_enable_per_advertising_sync(struct hci_dev *hdev, u8 instance) /* Checks if periodic advertising data contains a Basic Announcement and if it * does generates a Broadcast ID and add Broadcast Announcement. */ -static int hci_adv_bcast_annoucement(struct hci_dev *hdev, struct adv_info *adv) +static int hci_adv_bcast_annoucement(struct hci_dev *hdev, u8 instance) { + struct adv_info *adv; u8 bid[3]; u8 ad[HCI_MAX_EXT_AD_LENGTH]; u8 len; + int err = 0; - /* Skip if NULL adv as instance 0x00 is used for general purpose + /* Skip if instance 0x00 as it is used for general purpose * advertising so it cannot used for the likes of Broadcast Announcement * as it can be overwritten at any point. */ - if (!adv) + if (!instance) return 0; + hci_dev_lock(hdev); + + /* The instance may have been removed while waiting for the + * controller, in which case there is nothing to announce. + */ + adv = hci_find_adv_instance(hdev, instance); + if (!adv) + goto unlock; + /* Check if PA data doesn't contains a Basic Audio Announcement then * there is nothing to do. */ if (!eir_get_service_data(adv->per_adv_data, adv->per_adv_data_len, 0x1851, NULL)) - return 0; + goto unlock; /* Check if advertising data already has a Broadcast Announcement since * the process may want to control the Broadcast ID directly and in that @@ -1909,34 +1952,44 @@ static int hci_adv_bcast_annoucement(struct hci_dev *hdev, struct adv_info *adv) */ if (eir_get_service_data(adv->adv_data, adv->adv_data_len, 0x1852, NULL)) - return 0; + goto unlock; /* Generate Broadcast ID */ get_random_bytes(bid, sizeof(bid)); len = eir_append_service_data(ad, 0, 0x1852, bid, sizeof(bid)); if (adv->adv_data_len > sizeof(ad) - len) { bt_dev_err(hdev, "No room for Broadcast Announcement"); - return -EINVAL; + err = -EINVAL; + goto unlock; } memcpy(ad + len, adv->adv_data, adv->adv_data_len); - hci_set_adv_instance_data(hdev, adv->instance, len + adv->adv_data_len, + hci_set_adv_instance_data(hdev, instance, len + adv->adv_data_len, ad, 0, NULL); - return hci_update_adv_data_sync(hdev, adv->instance); + hci_dev_unlock(hdev); + + return hci_update_adv_data_sync(hdev, instance); + +unlock: + hci_dev_unlock(hdev); + return err; } int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 sid, u8 data_len, u8 *data, u32 flags, u16 min_interval, u16 max_interval, u16 sync_interval) { - struct adv_info *adv = NULL; + struct adv_info *adv; + u8 bcast_instance = 0; int err; bool added = false; hci_disable_per_advertising_sync(hdev, instance); if (instance) { + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); if (adv) { if (sid != HCI_SID_INVALID && adv->sid != sid) { @@ -1945,6 +1998,7 @@ int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 sid, */ adv = hci_find_adv_sid(hdev, sid); if (!adv) { + hci_dev_unlock(hdev); bt_dev_err(hdev, "Unable to find adv_info"); return -EINVAL; @@ -1963,11 +2017,17 @@ int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 sid, data_len, data, sync_interval, sync_interval); - if (IS_ERR(adv)) + if (IS_ERR(adv)) { + hci_dev_unlock(hdev); return PTR_ERR(adv); + } adv->pending = false; added = true; } + + bcast_instance = adv->instance; + + hci_dev_unlock(hdev); } /* Start advertising */ @@ -1975,7 +2035,7 @@ int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 sid, if (err < 0) goto fail; - err = hci_adv_bcast_annoucement(hdev, adv); + err = hci_adv_bcast_annoucement(hdev, bcast_instance); if (err < 0) goto fail; @@ -1995,8 +2055,11 @@ int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 sid, return 0; fail: - if (added) + if (added) { + hci_dev_lock(hdev); hci_remove_adv_instance(hdev, instance); + hci_dev_unlock(hdev); + } return err; } @@ -2026,6 +2089,7 @@ int hci_enable_advertising_sync(struct hci_dev *hdev) u8 own_addr_type, enable = 0x01; bool connectable; u16 adv_min_interval, adv_max_interval; + bool scannable; u32 flags; u8 status; @@ -2033,8 +2097,25 @@ int hci_enable_advertising_sync(struct hci_dev *hdev) return hci_enable_ext_advertising_sync(hdev, hdev->cur_adv_instance); + /* Snapshot the instance under hdev->lock since it may be removed + * while waiting for the commands below to complete. + */ + hci_dev_lock(hdev); + flags = hci_adv_instance_flags(hdev, hdev->cur_adv_instance); + scannable = hci_adv_instance_is_scannable(hdev, + hdev->cur_adv_instance); + adv_instance = hci_find_adv_instance(hdev, hdev->cur_adv_instance); + if (adv_instance) { + adv_min_interval = adv_instance->min_interval; + adv_max_interval = adv_instance->max_interval; + } else { + adv_min_interval = hdev->le_adv_min_interval; + adv_max_interval = hdev->le_adv_max_interval; + } + + hci_dev_unlock(hdev); /* If the "connectable" instance flag was not set, then choose between * ADV_IND and ADV_NONCONN_IND based on the global connectable setting. @@ -2068,18 +2149,10 @@ int hci_enable_advertising_sync(struct hci_dev *hdev) memset(&cp, 0, sizeof(cp)); - if (adv_instance) { - adv_min_interval = adv_instance->min_interval; - adv_max_interval = adv_instance->max_interval; - } else { - adv_min_interval = hdev->le_adv_min_interval; - adv_max_interval = hdev->le_adv_max_interval; - } - if (connectable) { cp.type = LE_ADV_IND; } else { - if (hci_adv_instance_is_scannable(hdev, hdev->cur_adv_instance)) + if (scannable) cp.type = LE_ADV_SCAN_IND; else cp.type = LE_ADV_NONCONN_IND; @@ -2342,7 +2415,7 @@ static int hci_remove_adv_sync(struct hci_dev *hdev, u8 instance, int hci_remove_advertising_sync(struct hci_dev *hdev, struct sock *sk, u8 instance, bool force) { - struct adv_info *next = NULL; + u8 next_instance = 0; int err; /* Cancel any timeout concerning the removed instance(s). */ @@ -2353,20 +2426,34 @@ int hci_remove_advertising_sync(struct hci_dev *hdev, struct sock *sk, * the current one. This can be the same instance again * if there is only one instance. */ - if (hdev->cur_adv_instance == instance) + if (hdev->cur_adv_instance == instance) { + struct adv_info *next; + + hci_dev_lock(hdev); next = hci_get_next_instance(hdev, instance); + if (next) + next_instance = next->instance; + hci_dev_unlock(hdev); + } if (!instance) { err = hci_clear_adv_sync(hdev, sk, force); if (err) return err; } else { - struct adv_info *adv = hci_find_adv_instance(hdev, instance); + struct adv_info *adv; + bool remove; - if (force || (adv && adv->timeout && !adv->remaining_time)) { + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); + remove = force || + (adv && adv->timeout && !adv->remaining_time); + hci_dev_unlock(hdev); + + if (remove) { /* Don't advertise a removed instance. */ - if (next && next->instance == instance) - next = NULL; + if (next_instance == instance) + next_instance = 0; err = hci_remove_adv_sync(hdev, instance, sk); if (err) @@ -2377,8 +2464,8 @@ int hci_remove_advertising_sync(struct hci_dev *hdev, struct sock *sk, if (!hdev_is_powered(hdev) || hci_dev_test_flag(hdev, HCI_ADVERTISING)) return 0; - if (next && !ext_adv_capable(hdev)) - hci_schedule_adv_instance_sync(hdev, next->instance, false); + if (next_instance && !ext_adv_capable(hdev)) + hci_schedule_adv_instance_sync(hdev, next_instance, false); return 0; } @@ -2843,10 +2930,28 @@ static int hci_pause_advertising_sync(struct hci_dev *hdev) return 0; } +/* Copy the instance identifiers in list order under hdev->lock. + * There are at most U8_MAX instances, with identifiers 1..U8_MAX. + * Callers can then wait for commands without retaining list pointers. + */ +static size_t adv_instance_list_copy(struct hci_dev *hdev, u8 *ids) +{ + struct adv_info *adv; + size_t n = 0; + + hci_dev_lock(hdev); + + list_for_each_entry(adv, &hdev->adv_instances, list) + ids[n++] = adv->instance; + + hci_dev_unlock(hdev); + + return n; +} + /* This function enables all user advertising instances */ static int hci_resume_advertising_sync(struct hci_dev *hdev) { - struct adv_info *adv, *tmp; int err = 0; /* If advertising has not been paused there is nothing to do. */ @@ -2863,15 +2968,20 @@ static int hci_resume_advertising_sync(struct hci_dev *hdev) bt_dev_dbg(hdev, "Resuming advertising instances"); if (ext_adv_capable(hdev)) { + u8 ids[U8_MAX]; + size_t i, n; + + n = adv_instance_list_copy(hdev, ids); + /* Call for each tracked instance to be re-enabled */ - list_for_each_entry_safe(adv, tmp, &hdev->adv_instances, list) { + for (i = 0; i < n; i++) { err = hci_enable_ext_advertising_sync(hdev, - adv->instance); + ids[i]); if (!err) continue; /* If the instance cannot be resumed remove it */ - hci_remove_ext_adv_instance_sync(hdev, adv->instance, + hci_remove_ext_adv_instance_sync(hdev, ids[i], NULL); } @@ -3696,7 +3806,8 @@ int hci_write_le_host_supported_sync(struct hci_dev *hdev, u8 le, u8 simul) static int hci_powered_update_adv_sync(struct hci_dev *hdev) { - struct adv_info *adv, *tmp; + u8 ids[U8_MAX]; + size_t i, n; int err; if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED)) @@ -3732,9 +3843,11 @@ static int hci_powered_update_adv_sync(struct hci_dev *hdev) hci_enable_advertising_sync(hdev); } + n = adv_instance_list_copy(hdev, ids); + /* Call for each tracked instance to be scheduled */ - list_for_each_entry_safe(adv, tmp, &hdev->adv_instances, list) - hci_schedule_adv_instance_sync(hdev, adv->instance, true); + for (i = 0; i < n; i++) + hci_schedule_adv_instance_sync(hdev, ids[i], true); return 0; } @@ -5710,7 +5823,9 @@ int hci_dev_open_sync(struct hci_dev *hdev) if (!ret) { hci_dev_hold(hdev); hci_dev_set_flag(hdev, HCI_RPA_EXPIRED); + hci_dev_lock(hdev); hci_adv_instances_set_rpa_expired(hdev, true); + hci_dev_unlock(hdev); set_bit(HCI_UP, &hdev->flags); hci_sock_dev_event(hdev, HCI_DEV_UP); hci_leds_update_powered(hdev, true); @@ -5854,8 +5969,10 @@ int hci_dev_close_sync(struct hci_dev *hdev) cancel_delayed_work_sync(&hdev->rpa_expired); + hci_dev_lock(hdev); list_for_each_entry(adv_instance, &hdev->adv_instances, list) cancel_delayed_work_sync(&adv_instance->rpa_expired_cb); + hci_dev_unlock(hdev); } /* A delayed work whose timer was armed before close would queue diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c index 4ef2f1fd763634..f35af20f135f40 100644 --- a/net/bluetooth/mgmt.c +++ b/net/bluetooth/mgmt.c @@ -4183,22 +4183,34 @@ static int user_passkey_neg_reply(struct sock *sk, struct hci_dev *hdev, static int adv_expire_sync(struct hci_dev *hdev, u32 flags) { struct adv_info *adv_instance; + u8 instance; + + hci_dev_lock(hdev); adv_instance = hci_find_adv_instance(hdev, hdev->cur_adv_instance); if (!adv_instance) - return 0; + goto unlock; /* stop if current instance doesn't need to be changed */ if (!(adv_instance->flags & flags)) - return 0; + goto unlock; cancel_adv_timeout(hdev); adv_instance = hci_get_next_instance(hdev, adv_instance->instance); if (!adv_instance) - return 0; + goto unlock; - hci_schedule_adv_instance_sync(hdev, adv_instance->instance, true); + instance = adv_instance->instance; + + hci_dev_unlock(hdev); + + hci_schedule_adv_instance_sync(hdev, instance, true); + + return 0; + +unlock: + hci_dev_unlock(hdev); return 0; } @@ -6797,12 +6809,15 @@ static void set_advertising_complete(struct hci_dev *hdev, void *data, int err) instance = hdev->cur_adv_instance; if (!instance) { + hci_dev_lock(hdev); adv_instance = list_first_entry_or_null(&hdev->adv_instances, struct adv_info, list); - if (!adv_instance) - return; + if (adv_instance) + instance = adv_instance->instance; + hci_dev_unlock(hdev); - instance = adv_instance->instance; + if (!instance) + return; } err = hci_schedule_adv_instance_sync(hdev, instance, true); From a7d2c94ba2995b5fb766d5ec7086f5e6a2774745 Mon Sep 17 00:00:00 2001 From: Cen Zhang Date: Thu, 19 Nov 2026 08:32:46 +0800 Subject: [PATCH 1066/2102] Bluetooth: hci_sync: Use controller handles for periodic advertising Management instance numbers and controller advertising handles differ on controllers with a single set: instance 1 uses handle 0x00. Periodic advertising data already sends adv->handle, but the parameters and enable commands send the instance number. The completion handler also treats the command's handle as an instance number: Request worker Controller / completion create instance 1 on handle 0 send periodic parameters for 1 Unknown Advertising Identifier Snapshot the handle under hdev->lock for periodic parameters, enable and disable. For instance 1 using handle 0, update periodic_enabled under the mutex after the command succeeds. Its completion handler cannot distinguish that instance from global advertising by the handle alone; keep the software instance number in the request, as the existing remove-set and random-address paths do. Use the same mapping for the advertising set in periodic transfer and both BIG creation commands, which obtain the instance number from the same broadcast QoS field as hci_start_per_adv_sync(). Keep the instance number in software state, and send no HCI command with the mutex held. Fixes: eca0ae4aea66 ("Bluetooth: Add initial implementation of BIS connections") Signed-off-by: Cen Zhang Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/hci_sync.c | 68 +++++++++++++++++++++++++++++++++++----- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index d15e95e75d61cf..638589f770815e 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -1817,11 +1817,15 @@ int hci_disable_per_advertising_sync(struct hci_dev *hdev, u8 instance) struct hci_cp_le_set_per_adv_enable cp; struct adv_info *adv; bool enabled; + u8 handle = instance; + int err; /* If periodic advertising already disabled there is nothing to do. */ hci_dev_lock(hdev); adv = hci_find_adv_instance(hdev, instance); enabled = adv && adv->periodic_enabled; + if (adv) + handle = adv->handle; hci_dev_unlock(hdev); if (!enabled) return 0; @@ -1829,10 +1833,39 @@ int hci_disable_per_advertising_sync(struct hci_dev *hdev, u8 instance) memset(&cp, 0, sizeof(cp)); cp.enable = 0x00; - cp.handle = instance; + cp.handle = handle; - return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE, - sizeof(cp), &cp, HCI_CMD_TIMEOUT); + err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE, + sizeof(cp), &cp, HCI_CMD_TIMEOUT); + if (err || handle == instance) + return err; + + /* Handle 0 is shared with global advertising, so the completion + * cannot identify the software instance from the command alone. + */ + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); + if (adv) + adv->periodic_enabled = false; + hci_dev_unlock(hdev); + + return 0; +} + +/* Map a management instance number to its controller handle. */ +static u8 hci_adv_instance_handle(struct hci_dev *hdev, u8 instance) + __must_not_hold(&hdev->lock) +{ + struct adv_info *adv; + u8 handle = instance; + + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); + if (adv) + handle = adv->handle; + hci_dev_unlock(hdev); + + return handle; } static int hci_set_per_adv_params_sync(struct hci_dev *hdev, u8 instance, @@ -1848,7 +1881,7 @@ static int hci_set_per_adv_params_sync(struct hci_dev *hdev, u8 instance, if (!max_interval) max_interval = DISCOV_LE_PER_ADV_INT_MAX; - cp.handle = instance; + cp.handle = hci_adv_instance_handle(hdev, instance); cp.min_interval = cpu_to_le16(min_interval); cp.max_interval = cpu_to_le16(max_interval); cp.periodic_properties = 0x0000; @@ -1894,11 +1927,15 @@ static int hci_enable_per_advertising_sync(struct hci_dev *hdev, u8 instance) struct hci_cp_le_set_per_adv_enable cp; struct adv_info *adv; bool enabled; + u8 handle = instance; + int err; /* If periodic advertising already enabled there is nothing to do. */ hci_dev_lock(hdev); adv = hci_find_adv_instance(hdev, instance); enabled = adv && adv->periodic_enabled; + if (adv) + handle = adv->handle; hci_dev_unlock(hdev); if (enabled) return 0; @@ -1906,10 +1943,23 @@ static int hci_enable_per_advertising_sync(struct hci_dev *hdev, u8 instance) memset(&cp, 0, sizeof(cp)); cp.enable = 0x01; - cp.handle = instance; + cp.handle = handle; - return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE, - sizeof(cp), &cp, HCI_CMD_TIMEOUT); + err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE, + sizeof(cp), &cp, HCI_CMD_TIMEOUT); + if (err || handle == instance) + return err; + + /* Handle 0 is shared with global advertising, so the completion + * cannot identify the software instance from the command alone. + */ + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); + if (adv) + adv->periodic_enabled = true; + hci_dev_unlock(hdev); + + return 0; } /* Checks if periodic advertising data contains a Basic Announcement and if it @@ -8237,6 +8287,7 @@ static int hci_le_past_set_info_sync(struct hci_dev *hdev, void *data) { struct past_data *past = data; struct hci_cp_le_past_set_info cp; + struct adv_info *adv; hci_dev_lock(hdev); @@ -8249,6 +8300,9 @@ static int hci_le_past_set_info_sync(struct hci_dev *hdev, void *data) memset(&cp, 0, sizeof(cp)); cp.handle = cpu_to_le16(past->le->handle); cp.adv_handle = past->conn->iso_qos.bcast.bis; + adv = hci_find_adv_instance(hdev, cp.adv_handle); + if (adv) + cp.adv_handle = adv->handle; hci_dev_unlock(hdev); From b544ca82abb46f2f870d32b3d7cae6ff9d9d1311 Mon Sep 17 00:00:00 2001 From: Alexandre Mergnat Date: Fri, 13 Nov 2026 05:29:02 +0000 Subject: [PATCH 1067/2102] regulator: mt6363: Serialize BUCK_TOP key access The bits that select the FAST mode of the bucks only accept writes while the BUCK_TOP key is unlocked. mt6363_regulator_set_mode() unlocks the key, updates the bit and locks the key again, but the regulator core only locks the buck being changed. When two bucks change mode at the same time, one of them can lock the key between the unlock and the mode write of the other. The PMIC then ignores that write, and regulator_set_mode() returns 0 while the buck stays in its previous mode. mt6363_va15_set_voltage_sel() unlocks and locks the same key, so it can also lock it during a buck mode change. Hold a mutex from each unlock of the key to its relock, in the FAST bit writes and in the VA15 voltage setter. Fixes: 3c36965df808 ("regulator: Add support for MediaTek MT6363 SPMI PMIC Regulators") Signed-off-by: Alexandre Mergnat Link: https://patch.msgid.link/20261113-rgp-91-mt6363-key-lock-v2-1-adbd48f0f830@baylibre.com Signed-off-by: Mark Brown --- drivers/regulator/mt6363-regulator.c | 53 ++++++++++++++++------------ 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/drivers/regulator/mt6363-regulator.c b/drivers/regulator/mt6363-regulator.c index e6c4bd851fef54..b4f5f33779b574 100644 --- a/drivers/regulator/mt6363-regulator.c +++ b/drivers/regulator/mt6363-regulator.c @@ -4,6 +4,7 @@ // Copyright (c) 2025 Collabora Ltd // AngeloGioacchino Del Regno +#include #include #include #include @@ -12,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -114,6 +116,8 @@ struct mt6363_regulator_info { int virq; }; +static DEFINE_MUTEX(mt6363_buck_top_lock); + #define MT6363_BUCK(match, vreg, min, max, step, en_reg, lp_reg, \ mset_reg, ocp_intn) \ [MT6363_ID_##vreg] = { \ @@ -388,6 +392,23 @@ static int mt6363_buck_unlock(struct regmap *map, bool unlock) return regmap_bulk_write(map, MT6363_BUCK_TOP_KEY_PROT_LO, &buf, sizeof(buf)); } +static int mt6363_buck_top_update_bits(struct regmap *map, unsigned int reg, + unsigned int mask, unsigned int val) +{ + int ret; + + guard(mutex)(&mt6363_buck_top_lock); + + ret = mt6363_buck_unlock(map, true); + if (ret) + return ret; + + ret = regmap_update_bits(map, reg, mask, val); + + mt6363_buck_unlock(map, false); + return ret; +} + static int mt6363_regulator_set_mode(struct regulator_dev *rdev, unsigned int mode) { @@ -400,13 +421,9 @@ static int mt6363_regulator_set_mode(struct regulator_dev *rdev, switch (mode) { case REGULATOR_MODE_FAST: - ret = mt6363_buck_unlock(regmap, true); - if (ret) - break; - - ret = regmap_set_bits(regmap, info->modeset_reg, info->modeset_mask); - - mt6363_buck_unlock(regmap, false); + ret = mt6363_buck_top_update_bits(regmap, info->modeset_reg, + info->modeset_mask, + info->modeset_mask); break; case REGULATOR_MODE_NORMAL: cur_mode = mt6363_regulator_get_mode(rdev); @@ -416,13 +433,8 @@ static int mt6363_regulator_set_mode(struct regulator_dev *rdev, } if (cur_mode == REGULATOR_MODE_FAST) { - ret = mt6363_buck_unlock(regmap, true); - if (ret) - break; - - ret = regmap_clear_bits(regmap, info->modeset_reg, info->modeset_mask); - - mt6363_buck_unlock(regmap, false); + ret = mt6363_buck_top_update_bits(regmap, info->modeset_reg, + info->modeset_mask, 0); break; } else if (cur_mode == REGULATOR_MODE_IDLE) { ret = regmap_clear_bits(regmap, info->lp_mode_reg, info->lp_mode_mask); @@ -508,20 +520,17 @@ static int mt6363_va15_set_voltage_sel(struct regulator_dev *rdev, unsigned int struct regmap *regmap = rdev->regmap; int ret; + guard(mutex)(&mt6363_buck_top_lock); + ret = mt6363_buck_unlock(regmap, true); if (ret) return ret; ret = regulator_set_voltage_sel_pickable_regmap(rdev, sel); - if (ret) - goto va15_unlock; - - ret = regmap_update_bits(regmap, MT6363_RG_BUCK_EFUSE_RSV1, - MT6363_RG_BUCK_EFUSE_RSV1_MASK, sel); - if (ret) - goto va15_unlock; + if (!ret) + ret = regmap_update_bits(regmap, MT6363_RG_BUCK_EFUSE_RSV1, + MT6363_RG_BUCK_EFUSE_RSV1_MASK, sel); -va15_unlock: mt6363_buck_unlock(rdev->regmap, false); return ret; } From c3cdaaa5cb5bd4c256fd0944a5df938529eb8dce Mon Sep 17 00:00:00 2001 From: Tzung-Bi Shih Date: Thu, 19 Nov 2026 03:24:14 +0000 Subject: [PATCH 1068/2102] Bluetooth: btrtl: Propagate errors if btrtl_vendor_read_reg16() fails A NULL pointer dereference is observed in btrtl_download_firmware(): [ 2592.730992] Bluetooth: btrtl_vendor_read_reg16() hci0: RTL: RTL: Read reg16 failed (-110) [ 2592.731005] Bluetooth: btusb_rtl_alloc_devcoredump() hci0: RTL: Failed to generate devcoredump [ 2592.731060] BUG: kernel NULL pointer dereference, address: 0000000000000000 ... [ 2592.731906] RIP: 0010:btrtl_download_firmware+0x19/0xb10 [btrtl] ... [ 2592.732791] Call Trace: [ 2592.732883] [ 2592.732935] btrtl_setup_realtek+0x30/0x60 [btrtl] When btrtl_vendor_read_reg16() for RTL_SEC_PROJ fails in btrtl_initialize(), the error code is stored in `rc` instead of `ret`, causing the err_free path to return ERR_PTR(0) (NULL). As a result, IS_ERR(btrtl_dev) in btrtl_setup_realtek() evaluates to false and NULL is passed to btrtl_download_firmware(), leading to a NULL pointer dereference. Store the return value in `ret` so the error is properly propagated to the caller. Fixes: cd8dbd9ef600 ("Bluetooth: btrtl: Avoid loading the config file on security chips") Cc: stable@vger.kernel.org Signed-off-by: Tzung-Bi Shih Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/btrtl.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/drivers/bluetooth/btrtl.c b/drivers/bluetooth/btrtl.c index d29813331603ba..d2c2e79800fcdd 100644 --- a/drivers/bluetooth/btrtl.c +++ b/drivers/bluetooth/btrtl.c @@ -1073,7 +1073,6 @@ struct btrtl_device_info *btrtl_initialize(struct hci_dev *hdev, u16 hci_rev, lmp_subver; u8 hci_ver, lmp_ver, chip_type = 0; int ret; - int rc; u8 key_id; u8 reg_val[2]; @@ -1185,8 +1184,8 @@ struct btrtl_device_info *btrtl_initialize(struct hci_dev *hdev, goto err_free; } - rc = btrtl_vendor_read_reg16(hdev, RTL_SEC_PROJ, reg_val); - if (rc < 0) + ret = btrtl_vendor_read_reg16(hdev, RTL_SEC_PROJ, reg_val); + if (ret < 0) goto err_free; key_id = reg_val[0]; From fc4527d1e1b655a61824cb02a9e07753d90fdf47 Mon Sep 17 00:00:00 2001 From: Tzung-Bi Shih Date: Thu, 19 Nov 2026 03:24:15 +0000 Subject: [PATCH 1069/2102] Bluetooth: btrtl: Return -ENOMEM if bt_skb_alloc() fails If bt_skb_alloc() fails in btrtl_initialize(), it jumps to `err_free` without updating `ret` (which is 0 from earlier calls). As a result, it returns ERR_PTR(0) (NULL) to its caller, leading to a NULL pointer dereference in btrtl_download_firmware(). Set `ret` to `-ENOMEM` before jumping to `err_free`. Fixes: 9a24ce5e29b1 ("Bluetooth: btrtl: Firmware format v2 support") Cc: stable@vger.kernel.org Signed-off-by: Tzung-Bi Shih Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/btrtl.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/bluetooth/btrtl.c b/drivers/bluetooth/btrtl.c index d2c2e79800fcdd..35a2c9d3380c50 100644 --- a/drivers/bluetooth/btrtl.c +++ b/drivers/bluetooth/btrtl.c @@ -1143,8 +1143,10 @@ struct btrtl_device_info *btrtl_initialize(struct hci_dev *hdev, if (btrtl_dev->drop_fw) { skb = bt_skb_alloc(sizeof(*cmd), GFP_KERNEL); - if (!skb) + if (!skb) { + ret = -ENOMEM; goto err_free; + } cmd = skb_put(skb, HCI_COMMAND_HDR_SIZE); cmd->opcode = cpu_to_le16(0xfc66); From 5052141b19fe0ab2863a12a0dcffac9aac6c8006 Mon Sep 17 00:00:00 2001 From: Zhao Li Date: Thu, 19 Nov 2026 19:23:59 +0800 Subject: [PATCH 1070/2102] Bluetooth: MGMT: Retain the selected legacy advertising schedule ID Updating the currently advertised legacy instance can schedule that same instance again instead of the next selected instance. Add Advertising stores the selected ID in the original request after mgmt_pending_new() has copied it, so the queued callback still reads the requested ID. Add Extended Advertising Data never passes the selected ID to its callback. Pass the selected ID to both callbacks in the pending command's user data, and keep the request ID for the replies and completion cleanup. Extended advertising controllers do not rotate instances in software, so keep scheduling the requested instance there, as both callbacks do now, without cancelling the rotation timeout or looking up the next one. Found by code review. Fixes: cba6b758711c ("Bluetooth: hci_sync: Make use of hci_cmd_sync_queue set 2") Cc: stable@vger.kernel.org # needs adjustments for <= 6.5 Signed-off-by: Zhao Li Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/mgmt.c | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c index f35af20f135f40..f5f32860782d25 100644 --- a/net/bluetooth/mgmt.c +++ b/net/bluetooth/mgmt.c @@ -9278,9 +9278,9 @@ static void add_advertising_complete(struct hci_dev *hdev, void *data, int err) static int add_advertising_sync(struct hci_dev *hdev, void *data) { struct mgmt_pending_cmd *cmd = data; - struct mgmt_cp_add_advertising *cp = cmd->param; + u8 instance = PTR_UINT(cmd->user_data); - return hci_schedule_adv_instance_sync(hdev, cp->instance, true); + return hci_schedule_adv_instance_sync(hdev, instance, true); } static int add_advertising(struct sock *sk, struct hci_dev *hdev, @@ -9364,7 +9364,9 @@ static int add_advertising(struct sock *sk, struct hci_dev *hdev, if (hdev->adv_instance_cnt > prev_instance_cnt) mgmt_advertising_added(sk, hdev, cp->instance); - if (hdev->cur_adv_instance == cp->instance) { + if (ext_adv_capable(hdev)) { + schedule_instance = cp->instance; + } else if (hdev->cur_adv_instance == cp->instance) { /* If the currently advertised instance is being changed then * cancel the current advertising and schedule the next * instance. If there is only one instance then the overridden @@ -9411,7 +9413,7 @@ static int add_advertising(struct sock *sk, struct hci_dev *hdev, goto unlock; } - cp->instance = schedule_instance; + cmd->user_data = UINT_PTR(schedule_instance); err = hci_cmd_sync_queue(hdev, add_advertising_sync, cmd, add_advertising_complete); @@ -9640,6 +9642,7 @@ static int add_ext_adv_data_sync(struct hci_dev *hdev, void *data) { struct mgmt_pending_cmd *cmd = data; struct mgmt_cp_add_ext_adv_data *cp = cmd->param; + u8 instance = PTR_UINT(cmd->user_data); int err; if (ext_adv_capable(hdev)) { @@ -9654,7 +9657,7 @@ static int add_ext_adv_data_sync(struct hci_dev *hdev, void *data) return hci_enable_ext_advertising_sync(hdev, cp->instance); } - return hci_schedule_adv_instance_sync(hdev, cp->instance, true); + return hci_schedule_adv_instance_sync(hdev, instance, true); } static int add_ext_adv_data(struct sock *sk, struct hci_dev *hdev, void *data, @@ -9716,7 +9719,9 @@ static int add_ext_adv_data(struct sock *sk, struct hci_dev *hdev, void *data, cp->data + cp->adv_data_len); /* If using software rotation, determine next instance to use */ - if (hdev->cur_adv_instance == cp->instance) { + if (ext_adv_capable(hdev)) { + schedule_instance = cp->instance; + } else if (hdev->cur_adv_instance == cp->instance) { /* If the currently advertised instance is being changed * then cancel the current advertising and schedule the * next instance. If there is only one instance then the @@ -9758,6 +9763,8 @@ static int add_ext_adv_data(struct sock *sk, struct hci_dev *hdev, void *data, goto clear_new_instance; } + cmd->user_data = UINT_PTR(schedule_instance); + err = hci_cmd_sync_queue(hdev, add_ext_adv_data_sync, cmd, add_ext_adv_data_complete); if (err < 0) { From cc8d022e8679e34b4892fa6c0a3fa2db917a6283 Mon Sep 17 00:00:00 2001 From: Danish Khateeb Date: Fri, 4 Sep 2026 11:15:31 -0500 Subject: [PATCH 1071/2102] HID: corsair: use disable_work_sync() to tear down the LED workers Tearing down the K90 LEDs races with their brightness workers in two different ways, and swapping cancel_work_sync() and led_classdev_unregister() around only trades one for the other. Cancelling before the unregister, as k90_cleanup_backlight() and k90_cleanup_macro_functions() have done since commit eb51c9f8cb4f ("HID: corsair: cancel worker before unregistering LED to fix use-after-free"), leaves led_classdev_unregister() free to re-arm the worker: it calls led_set_brightness(led_cdev, LED_OFF), which reaches k90_brightness_set() and schedule_work()s the item again. The structure holding that work is then freed while it is still linked into the worklist: BUG: KASAN: slab-use-after-free in __list_add_valid_or_report+0x186/0x210 Read of size 8 at addr ffff888102a1ead0 by task kworker/0:1/11 __queue_work+0xade/0x1350 queue_work_on+0xb6/0xc0 led_classdev_unregister+0x26b/0x340 corsair_remove+0x1c2/0x2d0 hid_device_remove+0xba/0x1e0 usbhid_disconnect+0xa0/0xe0 Allocated by task 129: corsair_probe+0x560/0xd50 Freed by task 11: corsair_remove+0xec/0x2d0 Cancelling after the unregister avoids that, but reintroduces precisely the use-after-free that commit set out to fix: a worker that has already tested led->removed and found it false goes on to dereference led->cdev.dev, which led_classdev_unregister() has meanwhile freed via device_unregister(). Use disable_work_sync(), which provides both halves at once. It waits for a worker that is already executing, so nothing can be sitting between the led->removed test and the led->cdev.dev dereference when the device goes away, and it makes the subsequent schedule_work() from the LED_OFF callback fail rather than queue, so nothing is left on the worklist to be freed. The ordering then stops mattering. The removed flag is left alone; it is redundant for these paths now but harmless. The fail_sysfs error path in k90_init_macro_functions() unregisters before cancelling, and so still carries the dereference-after-free that was fixed in the teardown paths, so convert it too. Fixes: eb51c9f8cb4f ("HID: corsair: cancel worker before unregistering LED to fix use-after-free") Reported-by: syzbot+abcedffc9201f2bb66c2@syzkaller.appspotmail.com Link: https://syzkaller.appspot.com/bug?extid=abcedffc9201f2bb66c2 Assisted-by: LLM Signed-off-by: Danish Khateeb Reviewed-by: Chen Changcheng Signed-off-by: Jiri Kosina --- drivers/hid/hid-corsair.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/hid/hid-corsair.c b/drivers/hid/hid-corsair.c index 278c6efb565dfe..f966005d69dd62 100644 --- a/drivers/hid/hid-corsair.c +++ b/drivers/hid/hid-corsair.c @@ -507,8 +507,8 @@ static int k90_init_macro_functions(struct hid_device *dev) fail_sysfs: k90->record_led.removed = true; + disable_work_sync(&k90->record_led.work); led_classdev_unregister(&k90->record_led.cdev); - cancel_work_sync(&k90->record_led.work); fail_record_led: kfree(k90->record_led.cdev.name); fail_record_led_alloc: @@ -524,7 +524,7 @@ static void k90_cleanup_backlight(struct hid_device *dev) if (drvdata->backlight) { drvdata->backlight->removed = true; - cancel_work_sync(&drvdata->backlight->work); + disable_work_sync(&drvdata->backlight->work); led_classdev_unregister(&drvdata->backlight->cdev); kfree(drvdata->backlight->cdev.name); kfree(drvdata->backlight); @@ -540,7 +540,7 @@ static void k90_cleanup_macro_functions(struct hid_device *dev) sysfs_remove_group(&dev->dev.kobj, &k90_attr_group); k90->record_led.removed = true; - cancel_work_sync(&k90->record_led.work); + disable_work_sync(&k90->record_led.work); led_classdev_unregister(&k90->record_led.cdev); kfree(k90->record_led.cdev.name); From 348597b22005a8f20d267cdcc503a41dcc658acf Mon Sep 17 00:00:00 2001 From: Myeonghun Pak Date: Mon, 9 Nov 2026 23:30:01 -0500 Subject: [PATCH 1072/2102] HID: magicmouse: disable the multitouch work on removal During USB runtime reset-resume, usbhid can call magicmouse_reset_resume() without serialization against HID driver unbind. The USB interface remains bound to usbhid, so this callback can queue msc->work after magicmouse_remove() cancels it. The delayed work can then run after devres frees msc. Use disable_delayed_work_sync() to drain the work and reject later queueing. Probe initializes fresh work on rebind. Found by a static analysis tool under development. Fixes: 4253fe22b137 ("HID: magicmouse: re-enable multitouch after reset-resume") Co-developed-by: Ijae Kim Signed-off-by: Ijae Kim Signed-off-by: Myeonghun Pak Signed-off-by: Jiri Kosina --- drivers/hid/hid-magicmouse.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index e6d4d493052684..0448cb2d071154 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -1032,7 +1032,7 @@ static void magicmouse_remove(struct hid_device *hdev) struct magicmouse_sc *msc = hid_get_drvdata(hdev); if (msc) { - cancel_delayed_work_sync(&msc->work); + disable_delayed_work_sync(&msc->work); if (is_usb_magicmouse2(hdev->vendor, hdev->product) || is_usb_magictrackpad2(hdev->vendor, hdev->product)) timer_delete_sync(&msc->battery_timer); From 02f677683b46e65979dc4267b346029f953f6162 Mon Sep 17 00:00:00 2001 From: Vicki Pfau Date: Tue, 10 Nov 2026 22:49:54 -0800 Subject: [PATCH 1073/2102] HID: nintendo-switch2-usb: Fix potential deadlock on teardown As reported by Sashiko, there is a narrow window in which cancel_work_sync on the message in work can block due to the work waiting on the mutex that the canceling thread holds. By moving the pointer clearing and unlocking the mutex before calling cfg->shutdown we can avoid this deadlock. Reported-by: Sashiko Link: https://sashiko.dev/#/patchset/20261006061619.2005967-1-vi%40endrift.com?part=1 Fixes: 9417132df63e ("HID: nintendo: Add preliminary Switch 2 controller driver") Signed-off-by: Vicki Pfau Signed-off-by: Jiri Kosina --- drivers/hid/hid-nintendo.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/drivers/hid/hid-nintendo.c b/drivers/hid/hid-nintendo.c index 4d40f67f3e6401..d235de6868a227 100644 --- a/drivers/hid/hid-nintendo.c +++ b/drivers/hid/hid-nintendo.c @@ -4292,6 +4292,7 @@ int switch2_controller_attach_cfg(const char *phys, struct switch2_cfg_intf *cfg mutex_lock(&ns2->lock); if (ns2->cfg) { ret = -EBUSY; + mutex_unlock(&ns2->lock); goto out; } cfg->parent = ns2; @@ -4301,15 +4302,16 @@ int switch2_controller_attach_cfg(const char *phys, struct switch2_cfg_intf *cfg ret = switch2_init_controller(ns2); if (ret < 0) { + ns2->cfg = NULL; + mutex_unlock(&ns2->lock); if (cfg->shutdown) cfg->shutdown(cfg); cfg->parent = NULL; - ns2->cfg = NULL; + } else { + mutex_unlock(&ns2->lock); } out: - mutex_unlock(&ns2->lock); - if (ret < 0) kref_put(&ns2->refcount, switch2_kref_put); return ret; From c97cd6badc96050a7eebb63ecbcd18212f06b52e Mon Sep 17 00:00:00 2001 From: Vicki Pfau Date: Tue, 10 Nov 2026 22:49:55 -0800 Subject: [PATCH 1074/2102] HID: nintendo-switch2-usb: Improve shutdown logic with inbound message work When detaching the USB interface the driver marks the interface as shutdown to prevent work that may be executing in parallel from attempting to use the URBs before freeing the URBs. There is theoretically a very narrow window in which the work could be scheduled while the shutdown is running in a separate thread, starting to execute before the shutdown cancels the work. By ensuring the scheduling happens within the locked scope and adding an additional shutdown check, this closes the window entirely. Reported-by: Noah Weinberger Link: https://lore.kernel.org/linux-input/a2dc00e7-9cab-4315-87a4-795f256c1e03@endrift.com/T/ Fixes: 9417132df63e ("HID: nintendo: Add preliminary Switch 2 controller driver") Signed-off-by: Vicki Pfau Signed-off-by: Jiri Kosina --- drivers/hid/hid-nintendo-switch2-usb.c | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/drivers/hid/hid-nintendo-switch2-usb.c b/drivers/hid/hid-nintendo-switch2-usb.c index 8b3b6841035d06..f53cbf0a3e15e9 100644 --- a/drivers/hid/hid-nintendo-switch2-usb.c +++ b/drivers/hid/hid-nintendo-switch2-usb.c @@ -52,12 +52,10 @@ static void switch2_bulk_in(struct urb *urb) { struct switch2_usb *ns2_usb = urb->context; int i; - bool schedule = false; unsigned long flags; switch (urb->status) { case 0: - schedule = true; break; case -ECONNRESET: case -ENOENT: @@ -71,16 +69,14 @@ static void switch2_bulk_in(struct urb *urb) } spin_lock_irqsave(&ns2_usb->bulk_in_lock, flags); - if (ns2_usb->shutdown) - schedule = false; - for (i = 0; i < NS2_IN_URBS; i++) { int err; struct switch2_urb *ns2_urb; if (ns2_usb->bulk_in[i].urb == urb) { - if (schedule) { + if (urb->status == 0 && !ns2_usb->shutdown) { ns2_usb->bulk_in[i].state = NS2_URB_IN; + schedule_work(&ns2_usb->message_in_work); continue; } else { ns2_usb->bulk_in[i].state = NS2_URB_FREE; @@ -115,9 +111,6 @@ static void switch2_bulk_in(struct urb *urb) } } spin_unlock_irqrestore(&ns2_usb->bulk_in_lock, flags); - - if (schedule) - schedule_work(&ns2_usb->message_in_work); } static void switch2_bulk_out(struct urb *urb) @@ -295,6 +288,9 @@ static void switch2_usb_message_in_work(struct work_struct *work) spin_lock_irqsave(&ns2_usb->bulk_in_lock, flags); for (i = 0; i < NS2_IN_URBS; i++) { + if (ns2_usb->shutdown) + break; + urb = &ns2_usb->bulk_in[i]; if (urb->state != NS2_URB_IN) continue; @@ -311,7 +307,7 @@ static void switch2_usb_message_in_work(struct work_struct *work) } spin_lock_irqsave(&ns2_usb->bulk_in_lock, flags); - if (!urb->urb) + if (ns2_usb->shutdown || !urb->urb) /* We're shutting down and this URB was freed */ break; From 5c4595963229397da8bd362ea93266197b16c7ab Mon Sep 17 00:00:00 2001 From: Vicki Pfau Date: Tue, 10 Nov 2026 22:49:56 -0800 Subject: [PATCH 1075/2102] HID: nintendo-switch2-usb: Clean up urb in probe error path In switch2_usb_probe the error path if the initial urb submission fails forgets to unanchor the urb. This patch adds that in. Reported-by: Sashiko Link: https://sashiko.dev/#/patchset/20261111032125.2888320-1-vi%40endrift.com?part=1 Signed-off-by: Vicki Pfau Fixes: 9417132df63e ("HID: nintendo: Add preliminary Switch 2 controller driver") Signed-off-by: Jiri Kosina --- drivers/hid/hid-nintendo-switch2-usb.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/hid/hid-nintendo-switch2-usb.c b/drivers/hid/hid-nintendo-switch2-usb.c index f53cbf0a3e15e9..8524cc68d5a25d 100644 --- a/drivers/hid/hid-nintendo-switch2-usb.c +++ b/drivers/hid/hid-nintendo-switch2-usb.c @@ -427,6 +427,8 @@ static int switch2_usb_probe(struct usb_interface *intf, const struct usb_device ns2_usb->bulk_in[0].state = NS2_URB_OUT; usb_anchor_urb(ns2_usb->bulk_in[0].urb, &ns2_usb->bulk_in_anchor); ret = usb_submit_urb(ns2_usb->bulk_in[0].urb, GFP_ATOMIC); + if (ret < 0) + usb_unanchor_urb(ns2_usb->bulk_in[0].urb); spin_unlock_irqrestore(&ns2_usb->bulk_in_lock, flags); if (ret < 0) From e624a56578e551b77ee66eef74dc2efcd42deb08 Mon Sep 17 00:00:00 2001 From: Andreas Claesson Date: Mon, 9 Nov 2026 19:55:52 +0000 Subject: [PATCH 1076/2102] HID: corsair: cancel LED work again after unregistering the LED Commit eb51c9f8cb4f ("HID: corsair: cancel worker before unregistering LED to fix use-after-free") moved cancel_work_sync() in front of led_classdev_unregister() in k90_cleanup_backlight() and k90_cleanup_macro_functions(). led_classdev_unregister() turns the LED off unless LED_RETAIN_AT_SHUTDOWN is set. That calls k90_brightness_set(), which unconditionally does schedule_work() on the same work item. The work is therefore queued again after it was cancelled, and the structure that embeds it is freed right afterwards: k90_cleanup_macro_functions() cancel_work_sync(&k90->record_led.work) led_classdev_unregister(&k90->record_led.cdev) led_set_brightness(LED_OFF) k90_brightness_set() schedule_work(&led->work) <-- re-queued kfree(k90) <-- frees the queued work_struct When the work later runs, the workqueue dereferences the freed work_struct and k90_record_led_work() reads led->removed from freed memory. A USB device that enumerates as a K90 and is then unplugged triggers this reliably. With CONFIG_DEBUG_OBJECTS_WORK it shows up as: ODEBUG: free active (active state 0) object: ffff88803b8772c8 object type: work_struct hint: k90_record_led_work+0x0/0x1e0 WARNING: lib/debugobjects.c:632 at debug_print_object+0xec/0x230 Workqueue: usb_hub_wq hub_event Call Trace: debug_check_no_obj_freed+0x2e3/0x450 lib/debugobjects.c:1201 kfree+0x13e/0x650 mm/slub.c:6923 k90_cleanup_macro_functions drivers/hid/hid-corsair.c:547 [inline] corsair_remove+0xfd/0x260 drivers/hid/hid-corsair.c:602 hid_device_remove+0xc5/0x1c0 drivers/hid/hid-core.c:2897 ... usbhid_disconnect+0x9f/0xc0 drivers/hid/usbhid/hid-core.c:1486 (with ODEBUG enabled, work_fixup_free() cancels the work and hides the use-after-free. Without it, the freed work item is executed.) Keep the existing cancel_work_sync() before unregistering, which waits for a worker that may already be past the 'removed' check, and cancel the work once more after led_classdev_unregister() so the work queued by the LED-off request is gone before the memory is freed. A re-queued work that manages to run before the second cancel still sees 'removed == true' while the structure is alive and returns early. Fixes: eb51c9f8cb4f ("HID: corsair: cancel worker before unregistering LED to fix use-after-free") Cc: stable@vger.kernel.org Signed-off-by: Andreas Claesson Signed-off-by: Jiri Kosina --- drivers/hid/hid-corsair.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/hid/hid-corsair.c b/drivers/hid/hid-corsair.c index f966005d69dd62..a9f2a0447f2d7a 100644 --- a/drivers/hid/hid-corsair.c +++ b/drivers/hid/hid-corsair.c @@ -526,6 +526,8 @@ static void k90_cleanup_backlight(struct hid_device *dev) drvdata->backlight->removed = true; disable_work_sync(&drvdata->backlight->work); led_classdev_unregister(&drvdata->backlight->cdev); + /* unregister turns the LED off, which re-queues the work */ + cancel_work_sync(&drvdata->backlight->work); kfree(drvdata->backlight->cdev.name); kfree(drvdata->backlight); } @@ -542,6 +544,8 @@ static void k90_cleanup_macro_functions(struct hid_device *dev) k90->record_led.removed = true; disable_work_sync(&k90->record_led.work); led_classdev_unregister(&k90->record_led.cdev); + /* unregister turns the LED off, which re-queues the work */ + cancel_work_sync(&k90->record_led.work); kfree(k90->record_led.cdev.name); kfree(k90); From abe10ad9c5fd868553b1262df403d5aaea3eff64 Mon Sep 17 00:00:00 2001 From: Srinivas Pandruvada Date: Mon, 9 Nov 2026 11:59:43 -0800 Subject: [PATCH 1077/2102] HID: sensor-hub: Synchronize callback removal with raw events Raw-event processing holds pdata->lock across callback lookup and invocation, and takes dyn_callback_lock during lookup. Removal must prevent both active callbacks and future lookups before client state can be released. Take pdata->lock before dyn_callback_lock, matching raw-event order, and unlink the callback while holding both locks. This ensures active raw-event callbacks have finished and prevents future lookups. Fixes: 401ca24fb34a ("HID: sensors: introduce sensor framework") Reported-by: Semyon Maryasin Closes: https://lore.kernel.org/all/CAM2dg7ewfVJSP4rFyhkCB1Rmd1+X56sAg=eUdbPthG2xrLqwQQ@mail.gmail.com/ Reviewed-by: Joshua Crofts Tested-by: Semyon Maryasin Tested-by: Zhang Lixu Signed-off-by: Srinivas Pandruvada Reviewed-by: Jonathan Cameron Signed-off-by: Jiri Kosina --- drivers/hid/hid-sensor-hub.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/hid/hid-sensor-hub.c b/drivers/hid/hid-sensor-hub.c index 6470a290ebfc5b..0c4884c5821fd5 100644 --- a/drivers/hid/hid-sensor-hub.c +++ b/drivers/hid/hid-sensor-hub.c @@ -173,7 +173,9 @@ int sensor_hub_remove_callback(struct hid_sensor_hub_device *hsdev, struct sensor_hub_data *pdata = hid_get_drvdata(hsdev->hdev); unsigned long flags; - spin_lock_irqsave(&pdata->dyn_callback_lock, flags); + /* Serialize callback removal with raw-event callback execution. */ + spin_lock_irqsave(&pdata->lock, flags); + spin_lock(&pdata->dyn_callback_lock); list_for_each_entry(callback, &pdata->dyn_callback_list, list) if (callback->usage_id == usage_id && callback->hsdev == hsdev) { @@ -181,7 +183,8 @@ int sensor_hub_remove_callback(struct hid_sensor_hub_device *hsdev, kfree(callback); break; } - spin_unlock_irqrestore(&pdata->dyn_callback_lock, flags); + spin_unlock(&pdata->dyn_callback_lock); + spin_unlock_irqrestore(&pdata->lock, flags); return 0; } From 452a24b2c2ed95aa246fcb3fcaf74a97a95c02a4 Mon Sep 17 00:00:00 2001 From: Srinivas Pandruvada Date: Mon, 9 Nov 2026 11:59:44 -0800 Subject: [PATCH 1078/2102] HID: sensor: custom: Set owner for misc device Set .owner in the misc-device file operations so open file descriptors keep the module loaded until their release callbacks have completed. Fixes: 4a7de0519df5 ("HID: sensor: Custom and Generic sensor support") Reported-by: Semyon Maryasin Closes: https://lore.kernel.org/all/CAM2dg7ewfVJSP4rFyhkCB1Rmd1+X56sAg=eUdbPthG2xrLqwQQ@mail.gmail.com/ Reviewed-by: Joshua Crofts Tested-by: Semyon Maryasin Tested-by: Zhang Lixu Signed-off-by: Srinivas Pandruvada Reviewed-by: Jonathan Cameron Signed-off-by: Jiri Kosina --- drivers/hid/hid-sensor-custom.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/hid/hid-sensor-custom.c b/drivers/hid/hid-sensor-custom.c index c2b425afd951be..72e5639cb1d9aa 100644 --- a/drivers/hid/hid-sensor-custom.c +++ b/drivers/hid/hid-sensor-custom.c @@ -719,6 +719,7 @@ static __poll_t hid_sensor_custom_poll(struct file *file, } static const struct file_operations hid_sensor_custom_fops = { + .owner = THIS_MODULE, .open = hid_sensor_custom_open, .read = hid_sensor_custom_read, .release = hid_sensor_custom_release, From 6e66d69837cf07a00cbcdeb6198e08332b422b6c Mon Sep 17 00:00:00 2001 From: Srinivas Pandruvada Date: Mon, 9 Nov 2026 11:59:45 -0800 Subject: [PATCH 1079/2102] HID: sensor: custom: Disable sensor before hub close on removal When removing an enabled sensor, set its power and reporting states to off before closing the hub. Keep the field descriptors alive until the state update has completed, and release the hub's open reference. Fixes: 4a7de0519df5 ("HID: sensor: Custom and Generic sensor support") Reported-by: Semyon Maryasin Closes: https://lore.kernel.org/all/CAM2dg7ewfVJSP4rFyhkCB1Rmd1+X56sAg=eUdbPthG2xrLqwQQ@mail.gmail.com/ Reviewed-by: Joshua Crofts Tested-by: Semyon Maryasin Tested-by: Zhang Lixu Signed-off-by: Srinivas Pandruvada Reviewed-by: Jonathan Cameron Signed-off-by: Jiri Kosina --- drivers/hid/hid-sensor-custom.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/hid/hid-sensor-custom.c b/drivers/hid/hid-sensor-custom.c index 72e5639cb1d9aa..8375697b459daa 100644 --- a/drivers/hid/hid-sensor-custom.c +++ b/drivers/hid/hid-sensor-custom.c @@ -1053,6 +1053,13 @@ static void hid_sensor_custom_remove(struct platform_device *pdev) /* Remove enable_sensor first as it uses fields via power_state/report_state. */ sysfs_remove_group(&sensor_inst->pdev->dev.kobj, &enable_sensor_attr_group); + mutex_lock(&sensor_inst->mutex); + if (sensor_inst->enable) { + set_power_report_state(sensor_inst, false); + sensor_hub_device_close(hsdev); + sensor_inst->enable = false; + } + mutex_unlock(&sensor_inst->mutex); hid_sensor_custom_remove_attributes(sensor_inst); sensor_hub_remove_callback(hsdev, hsdev->usage); } From 5e2976e52671e35bbd47cf5e53a9bf34df105b7e Mon Sep 17 00:00:00 2001 From: Elad Nachman Date: Wed, 18 Nov 2026 14:31:26 +0200 Subject: [PATCH 1080/2102] MAINTAINERS: update prestera switchdev e-mail address Update the Prestera SwitchDev subsystem maintainer e-mail for Elad Nachman. Signed-off-by: Elad Nachman Link: https://patch.msgid.link/20261118123126.326686-1-enachman@marvell.com Signed-off-by: Jakub Kicinski --- MAINTAINERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index 3ed1991cac468b..c45561d8a785eb 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -16286,7 +16286,7 @@ S: Supported F: drivers/perf/marvell_pem_pmu.c MARVELL PRESTERA ETHERNET SWITCH DRIVER -M: Elad Nachman +M: Elad Nachman S: Supported W: https://github.com/Marvell-switching/switchdev-prestera F: drivers/net/ethernet/marvell/prestera/ From 2ae35f090d029d2d8491b0a7f98a04c5c05d0a44 Mon Sep 17 00:00:00 2001 From: Dmitry Torokhov Date: Wed, 11 Nov 2026 18:33:45 -0800 Subject: [PATCH 1081/2102] Input: destroy force-feedback device on input unregistration When an input device is unregistered while userspace holds an open file descriptor to its event node, input_dev_release() is deferred until the last file descriptor is closed. Because input_ff_destroy() was only called from input_dev_release(), force-feedback teardown (ff->destroy and freeing ff->private) could run after the parent driver had already unbound, freed its device state, or even been unloaded via rmmod, causing use-after-free errors or page faults in unmapped module text. Commit ef166ce08801 ("Input: stop force-feedback timer when unregistering input devices") added a separate ff->stop callback for ff-memless, but left ff->destroy invoked from input_dev_release(). Once __input_unregister_device() has disconnected all input handlers (which flushes effects, closes the device, and marks evdev dead) and deleted the device from sysfs, nothing accesses dev->ff anymore. Call input_ff_destroy() directly in __input_unregister_device() so that ff->destroy() always runs synchronously while the driver and its module are still active, and remove the now-redundant ff->stop callback. Keep input_ff_destroy() in input_dev_release() (where it is a no-op once dev->ff is NULL) to handle input_free_device() on devices that were never registered. Fixes: 509ca1a93836 ("Input: implement new force feedback interface") Reported-by: Gideon Heinz Closes: https://lore.kernel.org/r/CAPb1+K2BxnfQ7VUQ15td5f9pVhn-ARSM9EjfOU8WuW72o+cvPg@mail.gmail.com Tested-by: Gideon Heinz Link: https://patch.msgid.link/2f722967b6db0692d4dd4164aff39b62@gmail.com Cc: stable@vger.kernel.org Signed-off-by: Dmitry Torokhov --- drivers/input/ff-core.c | 2 +- drivers/input/ff-memless.c | 23 ----------------------- drivers/input/input.c | 5 ++--- include/linux/input.h | 3 --- 4 files changed, 3 insertions(+), 30 deletions(-) diff --git a/drivers/input/ff-core.c b/drivers/input/ff-core.c index 0e5d1d1ceb4604..133b4622dc49ad 100644 --- a/drivers/input/ff-core.c +++ b/drivers/input/ff-core.c @@ -338,7 +338,7 @@ EXPORT_SYMBOL_GPL(input_ff_create); * * This function is only needed in error path as input core will * automatically free force feedback structures when device is - * destroyed. + * unregistered or destroyed. */ void input_ff_destroy(struct input_dev *dev) { diff --git a/drivers/input/ff-memless.c b/drivers/input/ff-memless.c index d1fefd1dfc0de1..3069436148ec16 100644 --- a/drivers/input/ff-memless.c +++ b/drivers/input/ff-memless.c @@ -483,32 +483,10 @@ static void ml_ff_destroy(struct ff_device *ff) { struct ml_device *ml = ff->private; - /* - * The timer is normally shut down in ml_ff_stop() when the device - * is unregistered. However, we still shut it down here as a safety - * net and for cases where the device was never registered (e.g. - * error paths during probe). - */ timer_shutdown_sync(&ml->timer); - kfree(ml->private); } -static void ml_ff_stop(struct ff_device *ff) -{ - struct ml_device *ml = ff->private; - - /* - * Even though we stop all playing effects when tearing down an - * input device (by the way of evdev calling input_flush_device() - * that calls into input_ff_flush() that stops and erases all - * effects), we do not actually shutdown the timer, and therefore - * we should do it here to prevent it firing after the input - * device is unregistered and its associated resources are freed. - */ - timer_shutdown_sync(&ml->timer); -} - /** * input_ff_create_memless() - create memoryless force-feedback device * @dev: input device supporting force-feedback @@ -543,7 +521,6 @@ int input_ff_create_memless(struct input_dev *dev, void *data, ff->playback = ml_ff_playback; ff->set_gain = ml_ff_set_gain; ff->destroy = ml_ff_destroy; - ff->stop = ml_ff_stop; /* we can emulate periodic effects with RUMBLE */ if (test_bit(FF_RUMBLE, ff->ffbit)) { diff --git a/drivers/input/input.c b/drivers/input/input.c index 3e6af517c596b7..030103e0a26704 100644 --- a/drivers/input/input.c +++ b/drivers/input/input.c @@ -2265,10 +2265,9 @@ static void __input_unregister_device(struct input_dev *dev) input_wakeup_procfs_readers(); } - if (dev->ff && dev->ff->stop) - dev->ff->stop(dev->ff); - device_del(&dev->dev); + + input_ff_destroy(dev); } static void devm_input_device_unregister(struct device *dev, void *res) diff --git a/include/linux/input.h b/include/linux/input.h index 3381608127f72d..02047cc45d04c7 100644 --- a/include/linux/input.h +++ b/include/linux/input.h @@ -549,8 +549,6 @@ extern const struct class input_class; * @set_autocenter: Called to auto-center device * @destroy: called by input core when parent input device is being * destroyed - * @stop: called by input core when parent input device is being - * unregistered * @private: driver-specific data, will be freed automatically * @ffbit: bitmap of force feedback capabilities truly supported by * device (not emulated like ones in input_dev->ffbit) @@ -579,7 +577,6 @@ struct ff_device { void (*set_autocenter)(struct input_dev *dev, u16 magnitude); void (*destroy)(struct ff_device *); - void (*stop)(struct ff_device *); void *private; From 7543d8d314b222452258b30e5c7a40c6f4cbfcda Mon Sep 17 00:00:00 2001 From: Jiayuan Chen Date: Tue, 17 Nov 2026 20:24:13 +0800 Subject: [PATCH 1082/2102] selftests/bpf: Fix bpf-gcc CO-RE relocation in verifier_sockmap_mutate bpf-gcc fails to load test_trace_iter_unix: Error: #766/6 verifier_sockmap_mutate/test_trace_iter_unix libbpf: elf: skipping section(3) .data (size 0) libbpf: elf: skipping unrecognized data section(18) .comment run_subtest:PASS:obj_open_mem 0 nsec libbpf: prog 'test_trace_iter_unix': relo #0: insn #0 (LDX/ST/STX) accesses field incorrectly. ... libbpf: prog 'test_trace_iter_unix': BPF program load failed: -EINVAL libbpf: prog 'test_trace_iter_unix': failed to load: -EINVAL libbpf: failed to load object 'verifier_sockmap_mutate' run_subtest:PASS:unexpected_load_success 0 nsec validate_msgs:FAIL:1014 expect_msg VERIFIER LOG: ============= 0: R1=ctx() R10=fp0 ; @ verifier_sockmap_mutate.c:124 0: failed to resolve CO-RE relocation [4] struct bpf_iter__unix (0:0 @ offset 0) processed 1 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0 ============= EXPECTED SUBSTR: 'cannot update sockmap in this context' GCC only applies preserve_access_index to types that carry the attribute themselves. The anonymous union holding the sock pointer doesn't, so the CO-RE access stops at the union ("0:0") instead of reaching the pointer ("0:0:0"), and libbpf rejects the relocation. Fixes: e16c83fa764f ("selftests/bpf: Add negative test for sockmap update from non-sockmap iter") Signed-off-by: Jiayuan Chen Signed-off-by: Alexei Starovoitov Acked-by: Ihor Solodrai Link: https://patch.msgid.link/20261117122417.340562-1-jiayuan.chen@linux.dev --- .../selftests/bpf/progs/verifier_sockmap_mutate.c | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c b/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c index 1516fe1524bba6..0dbbc5ad1de949 100644 --- a/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c +++ b/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c @@ -10,19 +10,12 @@ char _license[] SEC("license") = "GPL"; -struct sock { -} __attribute__((preserve_access_index)); - struct bpf_iter__sockmap { - union { - struct sock *sk; - }; + struct sock *sk; } __attribute__((preserve_access_index)); struct bpf_iter__unix { - union { - struct sock *unix_sk; - }; + struct sock *unix_sk; } __attribute__((preserve_access_index)); struct { From 4fdfed6d0990c82ce3c268814ba1b2c6ad0ce49d Mon Sep 17 00:00:00 2001 From: Tianyi Gao Date: Mon, 16 Nov 2026 16:28:34 +0000 Subject: [PATCH 1083/2102] xsk: reject TX checksum requests that overflow skb->csum_start xsk_skb_metadata() sets the u16 skb->csum_start to hr + csum_start. With 64K pages, csum_start can be close to U16_MAX, so the sum can overflow. The checksum offset then becomes negative. With XDP_UMEM_TX_SW_CSUM, skb_checksum_help() triggers a warning. Without it, the device gets a CHECKSUM_PARTIAL skb with a negative offset. Reject this with -EINVAL. Use the limit of skb_partial_csum_set(), which also rejects U16_MAX, the "not set" value of transport_header. That helper cannot be used here, as the skb built for an IFF_TX_SKB_NO_LINEAR device has no linear data. Fixes: 48eb03dd2630 ("xsk: Add TX timestamp and TX checksum offload support") Reported-by: Sashiko Closes: https://lore.kernel.org/all/sashiko-outbox-203545@kernel.org/ Signed-off-by: Tianyi Gao Acked-by: Stanislav Fomichev Link: https://patch.msgid.link/20261116162834.30087-1-tianyi@cloudflare.com Signed-off-by: Jakub Kicinski --- net/xdp/xsk.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/net/xdp/xsk.c b/net/xdp/xsk.c index f22f9a2cdbbeae..ab2e4fa87a4f00 100644 --- a/net/xdp/xsk.c +++ b/net/xdp/xsk.c @@ -1006,7 +1006,8 @@ static int xsk_skb_metadata(struct sk_buff *skb, void *buffer, csum_offset = READ_ONCE(meta->request.csum_offset); if (unlikely(csum_start + csum_offset + - sizeof(__sum16) > desc->len)) + sizeof(__sum16) > desc->len || + hr + csum_start >= U16_MAX)) return -EINVAL; skb->csum_start = hr + csum_start; From 6ada0c2769666140dff8e808ff21e8f9544ddc99 Mon Sep 17 00:00:00 2001 From: Alexander Duyck Date: Fri, 13 Nov 2026 12:41:27 -0800 Subject: [PATCH 1084/2102] fbnic: Wait for in-flight PTP timestamps before treating Tx as idle The fbnic_wait_all_queues_idle function treats the Tx path as idle once the QM idle registers report every queue idle. Those registers do not cover the TMI completion path, so they can report idle while a PTP timestamp request is still outstanding in the MAC or queued in the TMI completion FIFO. The check can then pass without a flush, and the completion arrives after the rings have been flushed, where the fbnic_clean_tsq function either reports "Tx timestamp without matching packet" or, if the interface has come back up and a new timestamped frame is already waiting, matches the stale completion to that frame and hands an SO_TIMESTAMPING user the wrong Tx timestamp. After a forced flush it can also turn FBNIC_TMI_DROP_CTRL_CMPL_DIS back off before the queued completions have drained, as the completion FIFO is only drained while that bit is set. Split the Tx wait out into the fbnic_wait_tx_idle function and have its idle check require the TCE PTP in-flight count to read zero in addition to the QM idle registers. The count tracks each timestamp request from when its frame enters the TCE until its completion leaves the TMI completion FIFO, so the Tx path is only treated as idle once none are outstanding, and a forced flush keeps the completion disable set until they have drained. The Rx wait still checks only the QM idle registers. The count is printed with the other Tx idle registers on failure. Waiting on the in-flight count means the Tx idle check can now keep reading the full set of QM idle registers for the whole timeout, and the poll timeout only counts the delay between polls, not the time spent in the register reads. Raise the delay between polls of the Tx and Rx waits from 2us to 20us so the PCIe read latency stays a small part of each interval and the 500ms timeout stays close to wall time. Define the register inside the TCE CSR section and move FBNIC_CSR_END_TCE to the last register of the TCE block (0x040B4, TCE_SPARE2 in the CSR map), so that the ethtool register dump covers it. The section previously ended at 0x04050, short of the TXB, PTP and TCAM status registers. Per the CSR map, every register in the added range is read-only or read/write, so reading them for the dump has no side effects. A device that has dropped off the bus, or whose CSR access the driver has disabled after a failed read, reads all ones. The QM idle bits treat that as idle, and so does the in-flight check: the count is bounded by the timestamp requests the Tx path can hold and can never reach all ones, so teardown of a lost device, or during DPC recovery, does not wait out the idle timeouts. The issue was found by code review and confirmed against the RTL. Fixes: ad3d9f8bc66c ("eth: fbnic: add TX packets timestamping support") Fixes: 7d4568edce74 ("fbnic: Disable PTP completions during the Tx force-flush") Signed-off-by: Alexander Duyck Link: https://patch.msgid.link/179460248693.8819.282933709034208845.stgit@ahduyck-xeon-server.home.arpa Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/meta/fbnic/fbnic_csr.h | 3 +- drivers/net/ethernet/meta/fbnic/fbnic_txrx.c | 73 ++++++++++++++++---- 2 files changed, 62 insertions(+), 14 deletions(-) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_csr.h b/drivers/net/ethernet/meta/fbnic/fbnic_csr.h index c371ac9f78c182..dc234f4d24f663 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_csr.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic_csr.h @@ -422,7 +422,8 @@ enum { #define FBNIC_TCE_TXB_NTWRK_DWRR_CTRL_EXT \ 0x0404E /* 0x10138 */ #define FBNIC_TCE_TXB_BMC_DWRR_CTRL_EXT 0x0404F /* 0x1013c */ -#define FBNIC_CSR_END_TCE 0x04050 /* CSR section delimiter */ +#define FBNIC_TCE_PTP_INFLIGHT 0x040A7 /* 0x1029c */ +#define FBNIC_CSR_END_TCE 0x040B4 /* CSR section delimiter */ /* TCE RAM registers */ #define FBNIC_CSR_START_TCE_RAM 0x04200 /* CSR section delimiter */ diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c index 07d4b2e923627b..c75c5683b724e8 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c @@ -2398,38 +2398,85 @@ static void fbnic_idle_dump(struct fbnic_dev *fbd, fbnic_rd32(fbd, regs[i].reg_base + j)); } -int fbnic_wait_all_queues_idle(struct fbnic_dev *fbd, bool may_fail) +/* The poll timeout only accounts for the delay between polls, not for + * the time spent in the poll itself, and each poll is a series of + * non-posted PCIe register reads that take on the order of a + * microsecond each. Space the polls out so that the reads stay a small + * part of each interval and the timeout stays close to wall time. + */ +#define FBNIC_IDLE_POLL_US 20 +#define FBNIC_IDLE_TIMEOUT_US 500000 + +static bool fbnic_tx_idle(struct fbnic_dev *fbd, + const struct fbnic_idle_regs *regs, + unsigned int nregs) +{ + u32 inflight; + + if (!fbnic_all_idle(fbd, regs, nregs)) + return false; + + /* The QM idle bits do not cover the TMI completion path, so a + * timestamp request can still be waiting on its completion. The + * count is bounded by the timestamp requests the Tx path can hold, + * so all ones is a failed read, as for the idle bits, not a count. + */ + inflight = fbnic_rd32(fbd, FBNIC_TCE_PTP_INFLIGHT); + + return !inflight || !~inflight; +} + +static int fbnic_wait_tx_idle(struct fbnic_dev *fbd) { static const struct fbnic_idle_regs tx[] = { { FBNIC_QM_TWQ_IDLE(0), FBNIC_QM_TWQ_IDLE_CNT, }, { FBNIC_QM_TQS_IDLE(0), FBNIC_QM_TQS_IDLE_CNT, }, { FBNIC_QM_TDE_IDLE(0), FBNIC_QM_TDE_IDLE_CNT, }, { FBNIC_QM_TCQ_IDLE(0), FBNIC_QM_TCQ_IDLE_CNT, }, - }, rx[] = { - { FBNIC_QM_HPQ_IDLE(0), FBNIC_QM_HPQ_IDLE_CNT, }, - { FBNIC_QM_PPQ_IDLE(0), FBNIC_QM_PPQ_IDLE_CNT, }, - { FBNIC_QM_RCQ_IDLE(0), FBNIC_QM_RCQ_IDLE_CNT, }, }; bool idle; int err; - err = read_poll_timeout_atomic(fbnic_all_idle, idle, idle, 2, 500000, - false, fbd, tx, ARRAY_SIZE(tx)); + err = read_poll_timeout_atomic(fbnic_tx_idle, idle, idle, + FBNIC_IDLE_POLL_US, + FBNIC_IDLE_TIMEOUT_US, false, + fbd, tx, ARRAY_SIZE(tx)); if (err == -ETIMEDOUT) { fbnic_tx_flush(fbd); - err = read_poll_timeout_atomic(fbnic_all_idle, idle, idle, - 2, 500000, false, + err = read_poll_timeout_atomic(fbnic_tx_idle, idle, idle, + FBNIC_IDLE_POLL_US, + FBNIC_IDLE_TIMEOUT_US, false, fbd, tx, ARRAY_SIZE(tx)); fbnic_tx_flush_off(fbd); } if (err) { fbnic_idle_dump(fbd, tx, ARRAY_SIZE(tx), "Tx", err); - if (may_fail) - return err; + netdev_err(fbd->netdev, "0x%04x: %08x\n", + FBNIC_TCE_PTP_INFLIGHT, + fbnic_rd32(fbd, FBNIC_TCE_PTP_INFLIGHT)); } - err = read_poll_timeout_atomic(fbnic_all_idle, idle, idle, 2, 500000, - false, fbd, rx, ARRAY_SIZE(rx)); + return err; +} + +int fbnic_wait_all_queues_idle(struct fbnic_dev *fbd, bool may_fail) +{ + static const struct fbnic_idle_regs rx[] = { + { FBNIC_QM_HPQ_IDLE(0), FBNIC_QM_HPQ_IDLE_CNT, }, + { FBNIC_QM_PPQ_IDLE(0), FBNIC_QM_PPQ_IDLE_CNT, }, + { FBNIC_QM_RCQ_IDLE(0), FBNIC_QM_RCQ_IDLE_CNT, }, + }; + bool idle; + int err; + + err = fbnic_wait_tx_idle(fbd); + if (err && may_fail) + return err; + + err = read_poll_timeout_atomic(fbnic_all_idle, idle, idle, + FBNIC_IDLE_POLL_US, + FBNIC_IDLE_TIMEOUT_US, false, + fbd, rx, ARRAY_SIZE(rx)); if (err) fbnic_idle_dump(fbd, rx, ARRAY_SIZE(rx), "Rx", err); return err; From 52a64e64230e03b45c13c615d7cdf0aeea39b210 Mon Sep 17 00:00:00 2001 From: Alexander Duyck Date: Fri, 13 Nov 2026 12:41:43 -0800 Subject: [PATCH 1085/2102] fbnic: Cover all of the HW stats with the stats lock The hw_stats lock covers the PHY, TMI, TTI, RPC, RXB, queue and PCIe stats, but the MAC stats are left to RTNL: the fbnic_reset_hw_stats function resets them outside the lock and asserts RTNL, on the grounds that the ethtool API is their only other user and holds RTNL. That is no longer the case. ethtool only takes RTNL on the Netlink path for the operations a driver lists in op_needs_rtnl, and fbnic lists only the pause getter among the stats ones, so the eth-mac, eth-ctrl and rmon getters update the MAC stats with only the netdev instance lock held, racing each other and the reset. Take the stats lock around the MAC stats updates in those getters and in the reset, and drop the RTNL assertion. Take it in the pause getter as well: it still runs under RTNL, but that no longer serializes it against the reset once the reset does not rely on RTNL. The PCIe stats debugfs read never needed RTNL, as the fbnic_get_hw_stats function updates those stats under the stats lock, so drop it there too. The values are printed from their 64-bit fields without the lock, as the counters keep changing during the read anyway. The issue was found by code review. Fixes: 45079e00133e ("net: ethtool: optionally skip rtnl_lock on Netlink path for GET ops") Signed-off-by: Alexander Duyck Link: https://patch.msgid.link/179460250360.8819.2203630667210523871.stgit@ahduyck-xeon-server.home.arpa Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/meta/fbnic/fbnic_debugfs.c | 3 --- drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c | 8 ++++++++ drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c | 13 +------------ 3 files changed, 9 insertions(+), 15 deletions(-) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_debugfs.c b/drivers/net/ethernet/meta/fbnic/fbnic_debugfs.c index f9e879be254dac..65bea571c0cc1a 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_debugfs.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_debugfs.c @@ -3,7 +3,6 @@ #include #include -#include #include #include "fbnic.h" @@ -607,7 +606,6 @@ static int fbnic_dbg_pcie_stats_show(struct seq_file *s, void *v) { struct fbnic_dev *fbd = s->private; - rtnl_lock(); fbnic_get_hw_stats(fbd); seq_printf(s, "ob_rd_tlp: %llu\n", fbd->hw_stats.pcie.ob_rd_tlp.value); @@ -626,7 +624,6 @@ static int fbnic_dbg_pcie_stats_show(struct seq_file *s, void *v) fbd->hw_stats.pcie.ob_rd_no_cpl_cred.value); seq_printf(s, "ob_rd_no_np_cred: %llu\n", fbd->hw_stats.pcie.ob_rd_no_np_cred.value); - rtnl_unlock(); return 0; } diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c b/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c index e774740fcb5d81..b300017b53d4a4 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c @@ -1867,12 +1867,14 @@ fbnic_get_pause_stats(struct net_device *netdev, mac_stats = &fbd->hw_stats.mac; + spin_lock(&fbd->hw_stats.lock); fbd->mac->get_pause_stats(fbd, false, &mac_stats->pause); pause_stats->tx_pause_frames = mac_stats->pause.tx_pause_frames.value; pause_stats->rx_pause_frames = mac_stats->pause.rx_pause_frames.value; tx_ps_events = mac_stats->pause.tx_pause_storm_events.value; pause_stats->tx_pause_storm_events = tx_ps_events; + spin_unlock(&fbd->hw_stats.lock); } static void @@ -1928,6 +1930,7 @@ fbnic_get_eth_mac_stats(struct net_device *netdev, mac_stats = &fbd->hw_stats.mac; mac = fbd->mac; + spin_lock(&fbd->hw_stats.lock); mac->get_eth_mac_stats(fbd, false, &mac_stats->eth_mac); fbnic_set_counter(ð_mac_stats->FramesTransmittedOK, @@ -1956,6 +1959,7 @@ fbnic_get_eth_mac_stats(struct net_device *netdev, &mac_stats->eth_mac.BroadcastFramesReceivedOK); fbnic_set_counter(ð_mac_stats->FrameTooLongErrors, &mac_stats->eth_mac.FrameTooLongErrors); + spin_unlock(&fbd->hw_stats.lock); } static void @@ -1968,12 +1972,14 @@ fbnic_get_eth_ctrl_stats(struct net_device *netdev, mac_stats = &fbd->hw_stats.mac; + spin_lock(&fbd->hw_stats.lock); fbd->mac->get_eth_ctrl_stats(fbd, false, &mac_stats->eth_ctrl); eth_ctrl_stats->MACControlFramesReceived = mac_stats->eth_ctrl.MACControlFramesReceived.value; eth_ctrl_stats->MACControlFramesTransmitted = mac_stats->eth_ctrl.MACControlFramesTransmitted.value; + spin_unlock(&fbd->hw_stats.lock); } static const struct ethtool_rmon_hist_range fbnic_rmon_ranges[] = { @@ -2003,6 +2009,7 @@ fbnic_get_rmon_stats(struct net_device *netdev, mac_stats = &fbd->hw_stats.mac; + spin_lock(&fbd->hw_stats.lock); fbd->mac->get_rmon_stats(fbd, false, &mac_stats->rmon); rmon_stats->undersize_pkts = @@ -2018,6 +2025,7 @@ fbnic_get_rmon_stats(struct net_device *netdev, rmon_stats->hist[i] = mac_stats->rmon.hist[i].value; rmon_stats->hist_tx[i] = mac_stats->rmon.hist_tx[i].value; } + spin_unlock(&fbd->hw_stats.lock); *ranges = fbnic_rmon_ranges; } diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c b/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c index 8b9b2076beecd4..c3b9e8fae396f1 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c @@ -1,8 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 /* Copyright (c) Meta Platforms, Inc. and affiliates. */ -#include - #include "fbnic.h" static void fbnic_hw_stat_rst32(struct fbnic_dev *fbd, u32 reg, @@ -551,17 +549,8 @@ void fbnic_reset_hw_stats(struct fbnic_dev *fbd) fbnic_reset_rxb_stats(fbd, &fbd->hw_stats.rxb); fbnic_reset_hw_rxq_stats(fbd, fbd->hw_stats.hw_q); fbnic_reset_pcie_stats_asic(fbd, &fbd->hw_stats.pcie); - spin_unlock(&fbd->hw_stats.lock); - - /* Once registered, the only other access to MAC stats is via the - * ethtool API which is protected by the rtnl_lock. The call to - * fbnic_reset_hw_stats() during PCI recovery is also protected - * by the rtnl_lock hence, we don't need the spinlock to access - * the MAC stats. - */ - if (fbd->netdev) - ASSERT_RTNL(); fbnic_reset_hw_mac_stats(fbd, &fbd->hw_stats.mac); + spin_unlock(&fbd->hw_stats.lock); } void fbnic_init_hw_stats(struct fbnic_dev *fbd) From 4b5153b389627d81f80eef49a5f27032c36378f6 Mon Sep 17 00:00:00 2001 From: Alexander Duyck Date: Fri, 13 Nov 2026 12:41:52 -0800 Subject: [PATCH 1086/2102] fbnic: Initialize and reset the HW stats before they can be read The HW stats are kept as running totals that advance by the difference between each counter and the value last read, so the last values have to be captured before the first read, and rebased whenever the hardware counters are reset. Three paths get the ordering wrong. The fbnic_probe function creates the debugfs directory, including the pcie_stats file, before it calls the fbnic_init_hw_stats function. A read in that window takes the stats lock before it has been initialized, and accumulates deltas against baselines that have not been captured. On resume, the __fbnic_pm_attach function rebases the stats only after it has returned early for a device in init failure mode, though such a device still exposes the PCIe stats through debugfs. And during PCI error recovery it runs from the resume callback, after the __fbnic_pm_resume function has already restored MMIO access from the slot_reset callback, so a debugfs read in between takes its delta against the values from before the reset and the totals jump by close to the full width of each counter. Initialize the stats before the debugfs directory and the devlink instance are registered. Rebase them in the __fbnic_pm_resume function, in the same stats lock section that restores MMIO access, so no read can see the reset counters first, ahead of its init failure check. The issue was found by code review, and the recovery case confirmed by hardware testing with forced AER/DPC recovery. Fixes: 25ba596d137d ("eth: fbnic: add PCIe hardware statistics") Fixes: 9f61eb2d185b ("eth: fbnic: add locking support for hw stats") Fixes: 05ec5504ff69 ("fbnic: Fix service task races with ndo_stop and PM suspend") Signed-off-by: Alexander Duyck Link: https://patch.msgid.link/179460251204.8819.12233374584808838528.stgit@ahduyck-xeon-server.home.arpa Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c | 11 +++++++++-- drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.h | 1 + drivers/net/ethernet/meta/fbnic/fbnic_pci.c | 16 ++++++++++------ 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c b/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c index c3b9e8fae396f1..076bfcac47d67c 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c @@ -539,9 +539,10 @@ static void fbnic_reset_hw_mac_stats(struct fbnic_dev *fbd, mac->get_rmon_stats(fbd, true, &mac_stats->rmon); } -void fbnic_reset_hw_stats(struct fbnic_dev *fbd) +void __fbnic_reset_hw_stats(struct fbnic_dev *fbd) { - spin_lock(&fbd->hw_stats.lock); + lockdep_assert_held(&fbd->hw_stats.lock); + fbnic_reset_phy_stats(fbd, &fbd->hw_stats.phy); fbnic_reset_tmi_stats(fbd, &fbd->hw_stats.tmi); fbnic_reset_tti_stats(fbd, &fbd->hw_stats.tti); @@ -550,6 +551,12 @@ void fbnic_reset_hw_stats(struct fbnic_dev *fbd) fbnic_reset_hw_rxq_stats(fbd, fbd->hw_stats.hw_q); fbnic_reset_pcie_stats_asic(fbd, &fbd->hw_stats.pcie); fbnic_reset_hw_mac_stats(fbd, &fbd->hw_stats.mac); +} + +void fbnic_reset_hw_stats(struct fbnic_dev *fbd) +{ + spin_lock(&fbd->hw_stats.lock); + __fbnic_reset_hw_stats(fbd); spin_unlock(&fbd->hw_stats.lock); } diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.h b/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.h index caea4be46762af..5eb1e8b29ef9d6 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.h @@ -154,6 +154,7 @@ struct fbnic_hw_stats { u64 fbnic_stat_rd64(struct fbnic_dev *fbd, u32 reg, u32 offset); +void __fbnic_reset_hw_stats(struct fbnic_dev *fbd); void fbnic_reset_hw_stats(struct fbnic_dev *fbd); void fbnic_init_hw_stats(struct fbnic_dev *fbd); void fbnic_get_hw_q_stats(struct fbnic_dev *fbd, diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_pci.c b/drivers/net/ethernet/meta/fbnic/fbnic_pci.c index 09ae797b1f0dc6..cb0191b6520496 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_pci.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_pci.c @@ -350,13 +350,13 @@ static int fbnic_probe(struct pci_dev *pdev, const struct pci_device_id *ent) */ fbnic_fw_log_enable(fbd, true); + /* Capture snapshot of hardware stats so netdev can calculate delta */ + fbnic_init_hw_stats(fbd); + fbnic_devlink_register(fbd); fbnic_devlink_otp_check(fbd, "error detected during probe"); fbnic_dbg_fbd_init(fbd); - /* Capture snapshot of hardware stats so netdev can calculate delta */ - fbnic_init_hw_stats(fbd); - fbnic_hwmon_register(fbd); if (!fbd->dsn) { @@ -498,10 +498,16 @@ static int __fbnic_pm_resume(struct device *dev) struct fbnic_net *fbn; int err; - /* Restore MMIO access */ + /* Restore MMIO access and rebase the HW stats in one step, so that + * no stats read can take its delta from counters the reset cleared + * against the values read before it. + */ iomap_table = pcim_iomap_table(to_pci_dev(dev)); + spin_lock(&fbd->hw_stats.lock); fbd->uc_addr0 = iomap_table[0]; fbd->uc_addr4 = iomap_table[4]; + __fbnic_reset_hw_stats(fbd); + spin_unlock(&fbd->hw_stats.lock); /* Rerequest the IRQs */ err = fbnic_alloc_irqs(fbd); @@ -582,8 +588,6 @@ static void __fbnic_pm_attach(struct device *dev) rtnl_lock(); netdev_lock(netdev); - fbnic_reset_hw_stats(fbd); - if (netif_running(netdev)) fbnic_up(fbn); From ad2c7240a3981fd5f0142b61ca913b02ab476ede Mon Sep 17 00:00:00 2001 From: Artemii Mashanov Date: Tue, 17 Nov 2026 12:06:08 +0300 Subject: [PATCH 1087/2102] cxgb4: allocate the full ethtool filter location array The ethtool filter location array stores nentries u32 values, but cxgb4_init_ethtool_filters() passes nentries to kvzalloc() as a byte count. The insertion and lookup paths allow indices below nentries, which can address memory beyond the requested allocation. Allocate nentries elements with kvcalloc() and the element size. The array remains compatible with the existing kvfree() calls. The size mismatch was found by reviewing the allocation, the array declaration and the indexed accesses in the filter handlers. Fixes: d915c299f1da ("cxgb4: add skeleton for ethtool n-tuple filters") Signed-off-by: Artemii Mashanov Reviewed-by: Potnuri Bharat Teja Link: https://patch.msgid.link/20261117090608.33178-1-ralerrdirsardx@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/chelsio/cxgb4/cxgb4_ethtool.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/chelsio/cxgb4/cxgb4_ethtool.c b/drivers/net/ethernet/chelsio/cxgb4/cxgb4_ethtool.c index 0092bc16f88709..c72c0bcd45c80a 100644 --- a/drivers/net/ethernet/chelsio/cxgb4/cxgb4_ethtool.c +++ b/drivers/net/ethernet/chelsio/cxgb4/cxgb4_ethtool.c @@ -2269,7 +2269,9 @@ int cxgb4_init_ethtool_filters(struct adapter *adap) eth_filter->nentries = nentries; for (i = 0; i < adap->params.nports; i++) { - eth_filter->port[i].loc_array = kvzalloc(nentries, GFP_KERNEL); + eth_filter->port[i].loc_array = + kvcalloc(nentries, sizeof(*eth_filter->port[i].loc_array), + GFP_KERNEL); if (!eth_filter->port[i].loc_array) { ret = -ENOMEM; goto free_eth_finfo; From 0833bc1d4ad71144500f6ca8601672580624f24f Mon Sep 17 00:00:00 2001 From: Tony Luck Date: Thu, 19 Nov 2026 10:45:24 -0800 Subject: [PATCH 1088/2102] x86/resctrl: Add SNC support for Granite Rapids "D" CPU Sub-NUMA Cluster (SNC) mode divides available RMID counters between NUMA nodes that share an instance of an L3 cache. Granite Rapids "D" CPUs can enable SNC mode, so Linux must adjust when SNC is enabled. Update the table of SNC capable CPU models. Signed-off-by: Tony Luck Signed-off-by: Borislav Petkov (AMD) Cc: Link: https://patch.msgid.link/20261119184524.12846-1-tony.luck@intel.com --- arch/x86/kernel/cpu/resctrl/monitor.c | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/x86/kernel/cpu/resctrl/monitor.c b/arch/x86/kernel/cpu/resctrl/monitor.c index a6a9090c4808ce..eee76570cf6ac9 100644 --- a/arch/x86/kernel/cpu/resctrl/monitor.c +++ b/arch/x86/kernel/cpu/resctrl/monitor.c @@ -381,6 +381,7 @@ static const struct x86_cpu_id snc_cpu_ids[] __initconst = { X86_MATCH_VFM(INTEL_GRANITERAPIDS_X, 0), X86_MATCH_VFM(INTEL_ATOM_CRESTMONT_X, 0), X86_MATCH_VFM(INTEL_ATOM_DARKMONT_X, 0), + X86_MATCH_VFM(INTEL_GRANITERAPIDS_D, 0), {} }; From 4f8b1a7cf7548ebefae959486c3acc33799d1116 Mon Sep 17 00:00:00 2001 From: Kordian Chmielewski Date: Sat, 14 Nov 2026 00:58:41 +0100 Subject: [PATCH 1089/2102] net: bcm4908_enet: fix the TX ring wrap start_xmit() wraps write_idx at length - 1 and sets WRAP on the descriptor at length - 2, while poll_tx() wraps read_idx at length, and the free descriptor count is taken from length. With read_idx at 0 and write_idx at length - 2 the count comes out as 2, the frame is queued and write_idx wraps to 0 == read_idx: a full ring looks empty. The following frames overwrite slots whose skbs were never unmapped or freed, their bytes stay in BQL, and the queue stops for good with nothing left to wake it. On a TP-Link Archer AX6000 this stopped everything the CPU sent to the switch under sustained TX load (about 1.3 Gbit/s through the switch's CPU port): tx_packets froze, nothing was logged, and BQL showed about 185 KB in flight against a limit of about 10 KB. The same mismatch also lets poll_tx() step onto slot length - 1, which start_xmit() never fills: once per lap it completes that slot, unmapping address 0 with length 0 and counting a packet that was never sent. That one is from reading the code. Use every descriptor, with WRAP on the last one, wrap both indexes at length and keep one descriptor free, so that read_idx == write_idx can only mean an empty ring. Stop and wake the queue with the netdev_queues.h helpers: start_xmit() stops it when the ring is full, also when it finds the ring full on entry, and poll_tx() wakes it once there is room again. Fixes: 4feffeadbcb2 ("net: broadcom: bcm4908enet: add BCM4908 controller driver") Reviewed-by: Florian Fainelli Signed-off-by: Kordian Chmielewski Link: https://patch.msgid.link/20261113235847.517308-2-kudzo51@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/broadcom/bcm4908_enet.c | 57 ++++++++++++-------- 1 file changed, 35 insertions(+), 22 deletions(-) diff --git a/drivers/net/ethernet/broadcom/bcm4908_enet.c b/drivers/net/ethernet/broadcom/bcm4908_enet.c index fd2715f84af979..60f711e8ce1892 100644 --- a/drivers/net/ethernet/broadcom/bcm4908_enet.c +++ b/drivers/net/ethernet/broadcom/bcm4908_enet.c @@ -13,6 +13,7 @@ #include #include #include +#include #include "bcm4908_enet.h" #include "unimac.h" @@ -518,30 +519,34 @@ static int bcm4908_enet_stop(struct net_device *netdev) return 0; } +/* One descriptor always stays unused, so read_idx == write_idx can only + * mean an empty ring + */ +static int bcm4908_enet_tx_free_descs(struct bcm4908_enet_dma_ring *ring) +{ + int free = READ_ONCE(ring->read_idx) - READ_ONCE(ring->write_idx) - 1; + + return free < 0 ? free + ring->length : free; +} + static netdev_tx_t bcm4908_enet_start_xmit(struct sk_buff *skb, struct net_device *netdev) { + struct netdev_queue *txq = netdev_get_tx_queue(netdev, 0); struct bcm4908_enet *enet = netdev_priv(netdev); struct bcm4908_enet_dma_ring *ring = &enet->tx_ring; struct bcm4908_enet_dma_ring_slot *slot; struct device *dev = enet->dev; struct bcm4908_enet_dma_ring_bd *buf_desc; - int free_buf_descs; u32 tmp; /* Free transmitted skbs */ if (enet->irq_tx < 0 && - !(le32_to_cpu(ring->buf_desc[ring->read_idx].ctl) & DMA_CTL_STATUS_OWN)) + !(le32_to_cpu(ring->buf_desc[READ_ONCE(ring->read_idx)].ctl) & + DMA_CTL_STATUS_OWN)) napi_schedule(&enet->tx_ring.napi); - /* Don't use the last empty buf descriptor */ - if (ring->read_idx <= ring->write_idx) - free_buf_descs = ring->read_idx - ring->write_idx + ring->length; - else - free_buf_descs = ring->read_idx - ring->write_idx; - if (free_buf_descs < 2) { - netif_stop_queue(netdev); + if (!netif_txq_maybe_stop(txq, bcm4908_enet_tx_free_descs(ring), 1, 1)) return NETDEV_TX_BUSY; - } /* Hardware removes OWN bit after sending data */ buf_desc = &ring->buf_desc[ring->write_idx]; @@ -562,7 +567,7 @@ static netdev_tx_t bcm4908_enet_start_xmit(struct sk_buff *skb, struct net_devic tmp |= DMA_CTL_STATUS_SOP; tmp |= DMA_CTL_STATUS_EOP; tmp |= DMA_CTL_STATUS_APPEND_CRC; - if (ring->write_idx + 1 == ring->length - 1) + if (ring->write_idx == ring->length - 1) tmp |= DMA_CTL_STATUS_WRAP; netdev_sent_queue(enet->netdev, skb->len); @@ -572,8 +577,13 @@ static netdev_tx_t bcm4908_enet_start_xmit(struct sk_buff *skb, struct net_devic bcm4908_enet_dma_tx_ring_enable(enet, &enet->tx_ring); - if (++ring->write_idx == ring->length - 1) - ring->write_idx = 0; + if (ring->write_idx == ring->length - 1) + WRITE_ONCE(ring->write_idx, 0); + else + WRITE_ONCE(ring->write_idx, ring->write_idx + 1); + + /* poll_tx() wakes the queue once there is room again */ + netif_txq_maybe_stop(txq, bcm4908_enet_tx_free_descs(ring), 1, 1); return NETDEV_TX_OK; } @@ -652,17 +662,19 @@ static int bcm4908_enet_poll_tx(struct napi_struct *napi, int weight) { struct bcm4908_enet_dma_ring *tx_ring = container_of(napi, struct bcm4908_enet_dma_ring, napi); struct bcm4908_enet *enet = container_of(tx_ring, struct bcm4908_enet, tx_ring); + struct netdev_queue *txq = netdev_get_tx_queue(enet->netdev, 0); struct bcm4908_enet_dma_ring_bd *buf_desc; struct bcm4908_enet_dma_ring_slot *slot; struct device *dev = enet->dev; + int read_idx = tx_ring->read_idx; unsigned int bytes = 0; int handled = 0; - while (handled < weight && tx_ring->read_idx != tx_ring->write_idx) { - buf_desc = &tx_ring->buf_desc[tx_ring->read_idx]; + while (handled < weight && read_idx != READ_ONCE(tx_ring->write_idx)) { + buf_desc = &tx_ring->buf_desc[read_idx]; if (le32_to_cpu(buf_desc->ctl) & DMA_CTL_STATUS_OWN) break; - slot = &tx_ring->slots[tx_ring->read_idx]; + slot = &tx_ring->slots[read_idx]; dma_unmap_single(dev, slot->dma_addr, slot->len, DMA_TO_DEVICE); dev_kfree_skb(slot->skb); @@ -670,22 +682,23 @@ static int bcm4908_enet_poll_tx(struct napi_struct *napi, int weight) handled++; bytes += slot->len; - if (++tx_ring->read_idx == tx_ring->length) - tx_ring->read_idx = 0; + if (++read_idx == tx_ring->length) + read_idx = 0; } + WRITE_ONCE(tx_ring->read_idx, read_idx); - netdev_completed_queue(enet->netdev, handled, bytes); enet->netdev->stats.tx_packets += handled; enet->netdev->stats.tx_bytes += bytes; + /* Reports to BQL, and wakes the queue if start_xmit() stopped it */ + netif_txq_completed_wake(txq, handled, bytes, + bcm4908_enet_tx_free_descs(tx_ring), 1); + if (handled < weight) { napi_complete_done(napi, handled); bcm4908_enet_dma_ring_intrs_on(enet, tx_ring); } - if (netif_queue_stopped(enet->netdev)) - netif_wake_queue(enet->netdev); - return handled; } From e1d4683fb4cb9d7f45a17c43a56ba2d26ab91ec6 Mon Sep 17 00:00:00 2001 From: Kordian Chmielewski Date: Sat, 14 Nov 2026 00:58:42 +0100 Subject: [PATCH 1090/2102] net: bcm4908_enet: drop a TX frame whose DMA mapping failed When dma_map_single() fails, start_xmit() returns NETDEV_TX_BUSY with the queue still running, after it has already stored the skb in the slot. Documentation/networking/driver.rst treats NETDEV_TX_BUSY under normal circumstances as a hard error, and a driver that returns it must not keep any reference to the skb. Here the stack requeues the frame and retries it while the slot still points at it. Drop the frame instead: free the skb, count it as dropped and return NETDEV_TX_OK. Map the buffer before the slot is touched. Found by reading the code. Fixes: 4feffeadbcb2 ("net: broadcom: bcm4908enet: add BCM4908 controller driver") Reviewed-by: Florian Fainelli Signed-off-by: Kordian Chmielewski Link: https://patch.msgid.link/20261113235847.517308-3-kudzo51@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/broadcom/bcm4908_enet.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/drivers/net/ethernet/broadcom/bcm4908_enet.c b/drivers/net/ethernet/broadcom/bcm4908_enet.c index 60f711e8ce1892..b1738d954b91ab 100644 --- a/drivers/net/ethernet/broadcom/bcm4908_enet.c +++ b/drivers/net/ethernet/broadcom/bcm4908_enet.c @@ -537,6 +537,7 @@ static netdev_tx_t bcm4908_enet_start_xmit(struct sk_buff *skb, struct net_devic struct bcm4908_enet_dma_ring_slot *slot; struct device *dev = enet->dev; struct bcm4908_enet_dma_ring_bd *buf_desc; + dma_addr_t dma_addr; u32 tmp; /* Free transmitted skbs */ @@ -555,12 +556,17 @@ static netdev_tx_t bcm4908_enet_start_xmit(struct sk_buff *skb, struct net_devic return NETDEV_TX_BUSY; } + dma_addr = dma_map_single(dev, skb->data, skb->len, DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, dma_addr))) { + dev_kfree_skb_any(skb); + netdev->stats.tx_dropped++; + return NETDEV_TX_OK; + } + slot = &ring->slots[ring->write_idx]; slot->skb = skb; slot->len = skb->len; - slot->dma_addr = dma_map_single(dev, skb->data, skb->len, DMA_TO_DEVICE); - if (unlikely(dma_mapping_error(dev, slot->dma_addr))) - return NETDEV_TX_BUSY; + slot->dma_addr = dma_addr; tmp = skb->len << DMA_CTL_LEN_DESC_BUFLENGTH_SHIFT; tmp |= DMA_CTL_STATUS_OWN; From e2785f0ff0a210158933221e86ea5bd066992870 Mon Sep 17 00:00:00 2001 From: Kordian Chmielewski Date: Sat, 14 Nov 2026 00:58:43 +0100 Subject: [PATCH 1091/2102] net: bcm4908_enet: release the TX ring on stop bcm4908_enet_stop() disables the TX DMA but leaves the ring as it is: the skbs that poll_tx() has not freed yet stay mapped and are never freed, and the descriptors the DMA has not sent yet keep DMA_CTL_STATUS_OWN. The skbs, the socket memory they hold and their mappings leak. The next open starts the indexes from 0 again over those descriptors, so the DMA may send stale frames from before the stop, and if the first descriptor still has OWN, start_xmit() stops the queue before it enables the DMA, with nothing left to wake it. Wait for the TX DMA channel to stop, as is already done for RX, then unmap and free the skbs between read_idx and write_idx and leave the ring empty, so that nothing can free them a second time. If the channel does not stop in time, leave the skbs alone rather than free them while the DMA may still read them. Clear the TX descriptors when the ring is initialised. A descriptor that start_xmit() is about to use then never carries OWN, so drop the check that stopped the queue on one. The RX helper's timeout warning said TX; make it say RX. Found by reading the code; I have not seen these on the hardware. Fixes: 4feffeadbcb2 ("net: broadcom: bcm4908enet: add BCM4908 controller driver") Signed-off-by: Kordian Chmielewski Link: https://patch.msgid.link/20261113235847.517308-4-kudzo51@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/broadcom/bcm4908_enet.c | 55 ++++++++++++++++---- 1 file changed, 44 insertions(+), 11 deletions(-) diff --git a/drivers/net/ethernet/broadcom/bcm4908_enet.c b/drivers/net/ethernet/broadcom/bcm4908_enet.c index b1738d954b91ab..bb42b6ecde16a9 100644 --- a/drivers/net/ethernet/broadcom/bcm4908_enet.c +++ b/drivers/net/ethernet/broadcom/bcm4908_enet.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -313,6 +314,11 @@ static void bcm4908_enet_dma_ring_init(struct bcm4908_enet *enet, enet_write(enet, ring->st_ram_block + ENET_DMA_CH_STATE_RAM_BASE_DESC_PTR, (uint32_t)ring->dma_addr); + /* A descriptor the stopped DMA never completed still carries OWN */ + if (ring->is_tx) + memset(ring->buf_desc, 0, + ring->length * sizeof(*ring->buf_desc)); + ring->read_idx = 0; ring->write_idx = 0; } @@ -362,10 +368,22 @@ static void bcm4908_enet_dma_tx_ring_enable(struct bcm4908_enet *enet, enet_write(enet, ring->cfg_block + ENET_DMA_CH_CFG, ENET_DMA_CH_CFG_ENABLE); } -static void bcm4908_enet_dma_tx_ring_disable(struct bcm4908_enet *enet, - struct bcm4908_enet_dma_ring *ring) +static int bcm4908_enet_dma_tx_ring_disable(struct bcm4908_enet *enet, + struct bcm4908_enet_dma_ring *ring) { + u32 tmp; + int err; + enet_write(enet, ring->cfg_block + ENET_DMA_CH_CFG, 0); + + /* Wait for the channel to stop, as for RX, before freeing buffers */ + err = read_poll_timeout(enet_read, tmp, !(tmp & ENET_DMA_CH_CFG_ENABLE), + 10, 2000, false, enet, + ring->cfg_block + ENET_DMA_CH_CFG); + if (err) + dev_warn(enet->dev, "Timeout waiting for DMA TX stop\n"); + + return err; } static void bcm4908_enet_dma_rx_ring_enable(struct bcm4908_enet *enet, @@ -391,7 +409,7 @@ static void bcm4908_enet_dma_rx_ring_disable(struct bcm4908_enet *enet, usleep_range(10, 30); } while (!time_after_eq(jiffies, deadline)); - dev_warn(enet->dev, "Timeout waiting for DMA TX stop\n"); + dev_warn(enet->dev, "Timeout waiting for DMA RX stop\n"); } /*** @@ -496,6 +514,25 @@ static int bcm4908_enet_open(struct net_device *netdev) return 0; } +static void bcm4908_enet_tx_ring_clean(struct bcm4908_enet *enet) +{ + struct bcm4908_enet_dma_ring *tx_ring = &enet->tx_ring; + struct device *dev = enet->dev; + int i; + + for (i = tx_ring->read_idx; i != tx_ring->write_idx; + i = i == tx_ring->length - 1 ? 0 : i + 1) { + struct bcm4908_enet_dma_ring_slot *slot = &tx_ring->slots[i]; + + dma_unmap_single(dev, slot->dma_addr, slot->len, DMA_TO_DEVICE); + dev_kfree_skb_any(slot->skb); + } + + /* Leave the ring empty, so that nothing frees these skbs again */ + tx_ring->read_idx = 0; + tx_ring->write_idx = 0; +} + static int bcm4908_enet_stop(struct net_device *netdev) { struct bcm4908_enet *enet = netdev_priv(netdev); @@ -509,8 +546,10 @@ static int bcm4908_enet_stop(struct net_device *netdev) netdev_reset_queue(netdev); bcm4908_enet_dma_rx_ring_disable(enet, &enet->rx_ring); - bcm4908_enet_dma_tx_ring_disable(enet, &enet->tx_ring); + /* Leave the TX buffers alone if the channel may still read them */ + if (!bcm4908_enet_dma_tx_ring_disable(enet, &enet->tx_ring)) + bcm4908_enet_tx_ring_clean(enet); bcm4908_enet_dma_uninit(enet); free_irq(enet->irq_tx, enet); @@ -549,13 +588,6 @@ static netdev_tx_t bcm4908_enet_start_xmit(struct sk_buff *skb, struct net_devic if (!netif_txq_maybe_stop(txq, bcm4908_enet_tx_free_descs(ring), 1, 1)) return NETDEV_TX_BUSY; - /* Hardware removes OWN bit after sending data */ - buf_desc = &ring->buf_desc[ring->write_idx]; - if (unlikely(le32_to_cpu(buf_desc->ctl) & DMA_CTL_STATUS_OWN)) { - netif_stop_queue(netdev); - return NETDEV_TX_BUSY; - } - dma_addr = dma_map_single(dev, skb->data, skb->len, DMA_TO_DEVICE); if (unlikely(dma_mapping_error(dev, dma_addr))) { dev_kfree_skb_any(skb); @@ -563,6 +595,7 @@ static netdev_tx_t bcm4908_enet_start_xmit(struct sk_buff *skb, struct net_devic return NETDEV_TX_OK; } + buf_desc = &ring->buf_desc[ring->write_idx]; slot = &ring->slots[ring->write_idx]; slot->skb = skb; slot->len = skb->len; From 1b48d619448c8425bd907722784f08e4e8fa4c5b Mon Sep 17 00:00:00 2001 From: Kordian Chmielewski Date: Sat, 14 Nov 2026 00:58:44 +0100 Subject: [PATCH 1092/2102] net: bcm4908_enet: unmap the buffer of a dropped RX frame When poll_rx() drops a frame (too short, or not in a single buffer), it frees the buffer without unmapping it first, so the memory goes back to the page allocator while still mapped for the device. Unmap it as the path for good frames does. Found by reading the code. Fixes: 4dc7f09b8bec ("net: broadcom: bcm4908_enet: fix RX path possible mem leak") Reviewed-by: Florian Fainelli Signed-off-by: Kordian Chmielewski Link: https://patch.msgid.link/20261113235847.517308-5-kudzo51@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/broadcom/bcm4908_enet.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/net/ethernet/broadcom/bcm4908_enet.c b/drivers/net/ethernet/broadcom/bcm4908_enet.c index bb42b6ecde16a9..03de65d9bbfd69 100644 --- a/drivers/net/ethernet/broadcom/bcm4908_enet.c +++ b/drivers/net/ethernet/broadcom/bcm4908_enet.c @@ -661,6 +661,8 @@ static int bcm4908_enet_poll_rx(struct napi_struct *napi, int weight) if (len < ETH_ZLEN || (ctl & (DMA_CTL_STATUS_SOP | DMA_CTL_STATUS_EOP)) != (DMA_CTL_STATUS_SOP | DMA_CTL_STATUS_EOP)) { + dma_unmap_single(dev, slot.dma_addr, + ENET_RX_BUF_DMA_SIZE, DMA_FROM_DEVICE); skb_free_frag(slot.buf); enet->netdev->stats.rx_dropped++; break; From 1da02595e8d2647a04c2cdd4f668dee0b8ac1ae9 Mon Sep 17 00:00:00 2001 From: Kordian Chmielewski Date: Sat, 14 Nov 2026 00:58:45 +0100 Subject: [PATCH 1093/2102] net: bcm4908_enet: unmap RX buffers on stop with their mapped size Since the switch to build_skb() the RX buffers are mapped with ENET_RX_BUF_DMA_SIZE and slot->len is no longer set for them, but bcm4908_enet_dma_uninit() still unmaps them with slot->len. Use the size they were mapped with. Found by reading the code. Fixes: 3a1cc23a75ab ("net: broadcom: bcm4908_enet: use build_skb()") Reviewed-by: Florian Fainelli Signed-off-by: Kordian Chmielewski Link: https://patch.msgid.link/20261113235847.517308-6-kudzo51@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/broadcom/bcm4908_enet.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/broadcom/bcm4908_enet.c b/drivers/net/ethernet/broadcom/bcm4908_enet.c index 03de65d9bbfd69..4065769da96606 100644 --- a/drivers/net/ethernet/broadcom/bcm4908_enet.c +++ b/drivers/net/ethernet/broadcom/bcm4908_enet.c @@ -334,7 +334,8 @@ static void bcm4908_enet_dma_uninit(struct bcm4908_enet *enet) slot = &rx_ring->slots[i]; if (!slot->buf) continue; - dma_unmap_single(dev, slot->dma_addr, slot->len, DMA_FROM_DEVICE); + dma_unmap_single(dev, slot->dma_addr, ENET_RX_BUF_DMA_SIZE, + DMA_FROM_DEVICE); skb_free_frag(slot->buf); slot->buf = NULL; } From 4d47e6c2f3ceb638d4ea5c21e304b20f526255bd Mon Sep 17 00:00:00 2001 From: Kordian Chmielewski Date: Sat, 14 Nov 2026 00:58:46 +0100 Subject: [PATCH 1094/2102] net: bcm4908_enet: publish the buffer address before OWN bcm4908_enet_dma_alloc_rx_buf() hands a descriptor to the DMA by writing its control word, with DMA_CTL_STATUS_OWN, first and the new buffer address second. If the DMA read the descriptor between the two stores, it would write the next frame into the old buffer, which poll_rx() is turning into an skb. start_xmit() writes the address first, but nothing orders the two stores, and the descriptors live in coherent memory, where arm64 may make them visible in either order. Write the address first on both paths and order it before the control word with dma_wmb(). In poll_rx(), read what the DMA wrote only after seeing OWN clear (dma_rmb()), as Documentation/memory-barriers.txt describes for descriptors shared with a device. Found by reading the code; I have no test that shows the DMA reading a descriptor while it is being refilled. Fixes: 4feffeadbcb2 ("net: broadcom: bcm4908enet: add BCM4908 controller driver") Reviewed-by: Florian Fainelli Signed-off-by: Kordian Chmielewski Link: https://patch.msgid.link/20261113235847.517308-7-kudzo51@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/broadcom/bcm4908_enet.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/broadcom/bcm4908_enet.c b/drivers/net/ethernet/broadcom/bcm4908_enet.c index 4065769da96606..4139dad3a18d0c 100644 --- a/drivers/net/ethernet/broadcom/bcm4908_enet.c +++ b/drivers/net/ethernet/broadcom/bcm4908_enet.c @@ -291,8 +291,10 @@ static int bcm4908_enet_dma_alloc_rx_buf(struct bcm4908_enet *enet, unsigned int tmp |= DMA_CTL_STATUS_OWN; if (idx == enet->rx_ring.length - 1) tmp |= DMA_CTL_STATUS_WRAP; - buf_desc->ctl = cpu_to_le32(tmp); buf_desc->addr = cpu_to_le32(slot->dma_addr); + /* Hand the descriptor to the DMA only once it holds the new buffer */ + dma_wmb(); + buf_desc->ctl = cpu_to_le32(tmp); return 0; } @@ -613,6 +615,8 @@ static netdev_tx_t bcm4908_enet_start_xmit(struct sk_buff *skb, struct net_devic netdev_sent_queue(enet->netdev, skb->len); buf_desc->addr = cpu_to_le32((uint32_t)slot->dma_addr); + /* The DMA must not see OWN before the buffer address */ + dma_wmb(); buf_desc->ctl = cpu_to_le32(tmp); bcm4908_enet_dma_tx_ring_enable(enet, &enet->tx_ring); @@ -647,6 +651,8 @@ static int bcm4908_enet_poll_rx(struct napi_struct *napi, int weight) ctl = le32_to_cpu(buf_desc->ctl); if (ctl & DMA_CTL_STATUS_OWN) break; + /* Read the rest only after the DMA gave the descriptor back */ + dma_rmb(); slot = enet->rx_ring.slots[enet->rx_ring.read_idx]; From ebe31472ad0a08e19a31a6647b99c6b51f90026c Mon Sep 17 00:00:00 2001 From: Kordian Chmielewski Date: Sat, 14 Nov 2026 00:58:47 +0100 Subject: [PATCH 1095/2102] net: bcm4908_enet: order the TX ring index accesses Since the TX interrupt was added, poll_tx() runs in its own NAPI and does not take the TX queue lock, so it and start_xmit() share the TX ring with only the two indexes between them. Nothing orders the accesses around those indexes: - poll_tx() reads write_idx, then the descriptor and the slot. On arm64 the later loads may be satisfied first, so poll_tx() may see the new write_idx together with the previous lap's descriptor, which has no OWN, and the previous lap's slot. It would then unmap and free a frame the DMA has not sent yet, or free the old skb a second time. - poll_tx() publishes read_idx once it is done with the slots it freed, but that store is not ordered after its loads from those slots, so start_xmit() may refill a slot before poll_tx() has read it. Publish each index with smp_store_release() and read the other side's index with smp_load_acquire() before touching the slots. start_xmit() now publishes write_idx right after the descriptor, before the MMIO write that kicks the DMA rather than after it, which narrows the window in which the DMA can complete a frame that poll_tx() cannot see yet. Sashiko's review of the previous version of this series pointed this out; I have not seen it on the hardware. Fixes: 12bb508bfe5a ("net: broadcom: bcm4908_enet: support TX interrupt") Signed-off-by: Kordian Chmielewski Link: https://patch.msgid.link/20261113235847.517308-8-kudzo51@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/broadcom/bcm4908_enet.c | 26 ++++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/drivers/net/ethernet/broadcom/bcm4908_enet.c b/drivers/net/ethernet/broadcom/bcm4908_enet.c index 4139dad3a18d0c..8bc620de2ef0d5 100644 --- a/drivers/net/ethernet/broadcom/bcm4908_enet.c +++ b/drivers/net/ethernet/broadcom/bcm4908_enet.c @@ -566,7 +566,9 @@ static int bcm4908_enet_stop(struct net_device *netdev) */ static int bcm4908_enet_tx_free_descs(struct bcm4908_enet_dma_ring *ring) { - int free = READ_ONCE(ring->read_idx) - READ_ONCE(ring->write_idx) - 1; + /* Pairs with smp_store_release() in bcm4908_enet_poll_tx() */ + int free = smp_load_acquire(&ring->read_idx) - + READ_ONCE(ring->write_idx) - 1; return free < 0 ? free + ring->length : free; } @@ -619,12 +621,14 @@ static netdev_tx_t bcm4908_enet_start_xmit(struct sk_buff *skb, struct net_devic dma_wmb(); buf_desc->ctl = cpu_to_le32(tmp); - bcm4908_enet_dma_tx_ring_enable(enet, &enet->tx_ring); + /* Publish the slot and the descriptor before the index; pairs with + * smp_load_acquire() in bcm4908_enet_poll_tx() + */ + smp_store_release(&ring->write_idx, + ring->write_idx < ring->length - 1 ? + ring->write_idx + 1 : 0); - if (ring->write_idx == ring->length - 1) - WRITE_ONCE(ring->write_idx, 0); - else - WRITE_ONCE(ring->write_idx, ring->write_idx + 1); + bcm4908_enet_dma_tx_ring_enable(enet, &enet->tx_ring); /* poll_tx() wakes the queue once there is room again */ netif_txq_maybe_stop(txq, bcm4908_enet_tx_free_descs(ring), 1, 1); @@ -718,7 +722,10 @@ static int bcm4908_enet_poll_tx(struct napi_struct *napi, int weight) unsigned int bytes = 0; int handled = 0; - while (handled < weight && read_idx != READ_ONCE(tx_ring->write_idx)) { + while (handled < weight) { + /* Pairs with the release in bcm4908_enet_start_xmit() */ + if (read_idx == smp_load_acquire(&tx_ring->write_idx)) + break; buf_desc = &tx_ring->buf_desc[read_idx]; if (le32_to_cpu(buf_desc->ctl) & DMA_CTL_STATUS_OWN) break; @@ -733,7 +740,10 @@ static int bcm4908_enet_poll_tx(struct napi_struct *napi, int weight) if (++read_idx == tx_ring->length) read_idx = 0; } - WRITE_ONCE(tx_ring->read_idx, read_idx); + /* Be done with the slots before start_xmit() may reuse them; pairs + * with smp_load_acquire() in bcm4908_enet_tx_free_descs() + */ + smp_store_release(&tx_ring->read_idx, read_idx); enet->netdev->stats.tx_packets += handled; enet->netdev->stats.tx_bytes += bytes; From d0c28729c10f4d34c9f91ade3b1dcc130e472d54 Mon Sep 17 00:00:00 2001 From: Jakub Kicinski Date: Wed, 18 Nov 2026 11:55:25 -0800 Subject: [PATCH 1096/2102] MAINTAINERS: add Willem de Bruijn to networking maintainers Willem is one of the pillars of the community and already maintains a bunch of core protocols and pieces of the stack. Make Willem a maintainer of all of networking. Acked-by: Andrew Lunn Acked-by: Willem de Bruijn Acked-by: Simon Horman Acked-by: Paolo Abeni Acked-by: Eric Dumazet Link: https://patch.msgid.link/20261118195525.3449546-1-kuba@kernel.org Signed-off-by: Jakub Kicinski --- MAINTAINERS | 1 + 1 file changed, 1 insertion(+) diff --git a/MAINTAINERS b/MAINTAINERS index c45561d8a785eb..bde216003f428b 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -19547,6 +19547,7 @@ M: "David S. Miller" M: Eric Dumazet M: Jakub Kicinski M: Paolo Abeni +M: Willem de Bruijn R: Simon Horman L: netdev@vger.kernel.org S: Maintained From 3ad578b22f7a34a2391ca8910dfc931b01cc94f6 Mon Sep 17 00:00:00 2001 From: Terrence Adams Date: Wed, 18 Nov 2026 10:03:44 -0800 Subject: [PATCH 1097/2102] scsi: pm8001: Offset hardware queue index for MSI-X pre-vector When MSI-X interrupt vectors are configured in pm8001_setup_msix(), the driver requests vector affinity with .pre_vectors = 1 to reserve Vector 0 for non-affinitized housekeeping interrupts. blk_mq_map_hw_queues() maps hardware queues (hwq 0 to nr_hw_queues - 1) with an offset of 1, mapping hwq 0 to Vector 1, hwq 1 to Vector 2, etc. However, pm80xx_chip_get_q_index() retrieves the queue index directly from blk_mq_unique_tag_to_hwq(tag) without adding 1 for the pre-vector offset. Consequently, commands on hwq 0 are issued with responseQueue 0 (firing unmanaged Vector 0 on CPU 0), while hwq k fires Vector k (the CPU affinitized to hwq k-1). This results in 100% of I/O completion interrupts being delivered to the wrong CPU core, causing heavy cross-CPU IPIs, cache line bouncing, and increased kernel and IRQ CPU processing overhead. Define PM8001_PRE_VECTORS for the reserved housekeeping vector and use it consistently across MSI-X vector allocation, hardware queue setup and mapping, and queue index lookup. Update pm80xx_chip_get_q_index() to accept pm8001_ha and add PM8001_PRE_VECTORS to blk_mq_unique_tag_to_hwq() whenever multi-queue is enabled (number_of_intr > PM8001_PRE_VECTORS), routing completion interrupts to their affinitized CPU cores. Note that offsetting completions by PM8001_PRE_VECTORS routes the highest hardware queue to outbound queue max_q_num - 1, which pm80xx_chip_init() also programs as the fatal error interrupt vector. As a result, process_oq() now reads MSGU_SCRATCH_PAD_1 (and MSGU_SCRATCH_PAD_RSVD_0 when no fatal error is reported) on every interrupt for that queue, matching the behavior before commit 42f22fe36d51 ("scsi: pm8001: Expose hardware queues for pm80xx"). Fixes: 42f22fe36d51 ("scsi: pm8001: Expose hardware queues for pm80xx") Signed-off-by: Terrence Adams Reviewed-by: Bart Van Assche Link: https://patch.msgid.link/20261118180344.1159617-1-tadamsjr@google.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/pm8001/pm8001_defs.h | 1 + drivers/scsi/pm8001/pm8001_init.c | 15 +++++++++------ drivers/scsi/pm8001/pm80xx_hwi.c | 13 +++++++++---- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/drivers/scsi/pm8001/pm8001_defs.h b/drivers/scsi/pm8001/pm8001_defs.h index a9605ca317f341..9b37a76d8b7443 100644 --- a/drivers/scsi/pm8001/pm8001_defs.h +++ b/drivers/scsi/pm8001/pm8001_defs.h @@ -178,6 +178,7 @@ enum port_type { #define PM8001_MAX_INB_NUM 64 #define PM8001_MAX_OUTB_NUM 64 #define PM8001_CAN_QUEUE 508 /* SCSI Queue depth */ +#define PM8001_PRE_VECTORS 1 /* non-affinitized housekeeping vector */ /* Inbound/Outbound queue size */ #define IOMB_SIZE_SPC 64 diff --git a/drivers/scsi/pm8001/pm8001_init.c b/drivers/scsi/pm8001/pm8001_init.c index 5af81c73a8f875..b1788788b7ed9b 100644 --- a/drivers/scsi/pm8001/pm8001_init.c +++ b/drivers/scsi/pm8001/pm8001_init.c @@ -104,8 +104,9 @@ static void pm8001_map_queues(struct Scsi_Host *shost) struct pm8001_hba_info *pm8001_ha = sha->lldd_ha; struct blk_mq_queue_map *qmap = &shost->tag_set.map[HCTX_TYPE_DEFAULT]; - if (pm8001_ha->number_of_intr > 1) { - blk_mq_map_hw_queues(qmap, &pm8001_ha->pdev->dev, 1); + if (pm8001_ha->number_of_intr > PM8001_PRE_VECTORS) { + blk_mq_map_hw_queues(qmap, &pm8001_ha->pdev->dev, + PM8001_PRE_VECTORS); return; } @@ -977,10 +978,11 @@ static u32 pm8001_setup_msix(struct pm8001_hba_info *pm8001_ha) * include in the affinity spreading. */ struct irq_affinity desc = { - .pre_vectors = 1, + .pre_vectors = PM8001_PRE_VECTORS, }; rc = pci_alloc_irq_vectors_affinity( - pm8001_ha->pdev, 2, PM8001_MAX_MSIX_VEC, + pm8001_ha->pdev, PM8001_PRE_VECTORS + 1, + PM8001_MAX_MSIX_VEC, PCI_IRQ_MSIX | PCI_IRQ_AFFINITY, &desc); } @@ -1183,8 +1185,9 @@ static int pm8001_pci_probe(struct pci_dev *pdev, PM8001_CHIP_DISP->chip_post_init(pm8001_ha); - if (pm8001_ha->number_of_intr > 1) { - shost->nr_hw_queues = pm8001_ha->number_of_intr - 1; + if (pm8001_ha->number_of_intr > PM8001_PRE_VECTORS) { + shost->nr_hw_queues = pm8001_ha->number_of_intr - + PM8001_PRE_VECTORS; /* * For now, ensure we're not sent too many commands by setting * host_tagset. This is also required if we start using request diff --git a/drivers/scsi/pm8001/pm80xx_hwi.c b/drivers/scsi/pm8001/pm80xx_hwi.c index d2572dd66071f1..1d4f5ee861c1f0 100644 --- a/drivers/scsi/pm8001/pm80xx_hwi.c +++ b/drivers/scsi/pm8001/pm80xx_hwi.c @@ -4328,14 +4328,19 @@ static int check_enc_sat_cmd(struct sas_task *task) return ret; } -static u32 pm80xx_chip_get_q_index(struct sas_task *task) +static u32 pm80xx_chip_get_q_index(struct pm8001_hba_info *pm8001_ha, + struct sas_task *task) { struct request *rq = sas_task_find_rq(task); if (!rq) return 0; - return blk_mq_unique_tag_to_hwq(blk_mq_unique_tag(rq)); + if (pm8001_ha->number_of_intr > PM8001_PRE_VECTORS) + return blk_mq_unique_tag_to_hwq(blk_mq_unique_tag(rq)) + + PM8001_PRE_VECTORS; + + return 0; } /** @@ -4371,7 +4376,7 @@ static int pm80xx_chip_ssp_io_req(struct pm8001_hba_info *pm8001_ha, ssp_cmd.ssp_iu.efb_prio_attr |= (task->ssp_task.task_attr & 7); memcpy(ssp_cmd.ssp_iu.cdb, task->ssp_task.cmd->cmnd, task->ssp_task.cmd->cmd_len); - q_index = pm80xx_chip_get_q_index(task); + q_index = pm80xx_chip_get_q_index(pm8001_ha, task); /* Check if encryption is set */ if (pm8001_ha->chip->encrypt && @@ -4510,7 +4515,7 @@ static int pm80xx_chip_sata_req(struct pm8001_hba_info *pm8001_ha, u32 opc = OPC_INB_SATA_HOST_OPSTART; memset(&sata_cmd, 0, sizeof(sata_cmd)); - q_index = pm80xx_chip_get_q_index(task); + q_index = pm80xx_chip_get_q_index(pm8001_ha, task); if (task->data_dir == DMA_NONE && !task->ata_task.use_ncq) { ATAP = 0x04; /* no data*/ From 3bf0ed5695638db7e57b0d42768754bf29c3bb4c Mon Sep 17 00:00:00 2001 From: Hyunjung Ko Date: Tue, 17 Nov 2026 18:21:57 +0900 Subject: [PATCH 1098/2102] l2tp: reject short IPv6 address attributes L2TP_ATTR_IP6_SADDR and L2TP_ATTR_IP6_DADDR are NLA_BINARY with .len set to sizeof(struct in6_addr), which only bounds the attribute from above. l2tp_tunnel_sock_create() then copies a full in6_addr out of each one, so a shorter attribute makes it read past the payload. If the attribute is the last one in the message this picks up whatever lies behind the skb tail (stale heap data unless init_on_alloc is set), which ends up in the socket address and can be read back with L2TP_CMD_TUNNEL_GET. The commands are GENL_UNS_ADMIN_PERM, so this is reachable from a user namespace. Require the exact length. Fixes: f9bac8df908d ("l2tp: netlink api for l2tpv3 ipv6 unmanaged tunnels") Cc: stable@vger.kernel.org Signed-off-by: Hyunjung Ko Reviewed-by: Hangbin Liu Link: https://patch.msgid.link/20261117092157.85513-1-hj351016@gmail.com Signed-off-by: Jakub Kicinski --- net/l2tp/l2tp_netlink.c | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/net/l2tp/l2tp_netlink.c b/net/l2tp/l2tp_netlink.c index 89ef04c78787df..a07009d4cb0099 100644 --- a/net/l2tp/l2tp_netlink.c +++ b/net/l2tp/l2tp_netlink.c @@ -910,14 +910,8 @@ static const struct nla_policy l2tp_nl_policy[L2TP_ATTR_MAX + 1] = { [L2TP_ATTR_MTU] = { .type = NLA_U16, }, [L2TP_ATTR_MRU] = { .type = NLA_U16, }, [L2TP_ATTR_STATS] = { .type = NLA_NESTED, }, - [L2TP_ATTR_IP6_SADDR] = { - .type = NLA_BINARY, - .len = sizeof(struct in6_addr), - }, - [L2TP_ATTR_IP6_DADDR] = { - .type = NLA_BINARY, - .len = sizeof(struct in6_addr), - }, + [L2TP_ATTR_IP6_SADDR] = NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)), + [L2TP_ATTR_IP6_DADDR] = NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)), [L2TP_ATTR_IFNAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ - 1, From ec7cb74c1a7e6c81d8647f73be2b711b5fc1a7a4 Mon Sep 17 00:00:00 2001 From: "Matthieu Baerts (NGI0)" Date: Mon, 16 Nov 2026 23:06:08 +0100 Subject: [PATCH 1099/2102] mptcp: do not use a raised snd_wnd for the send window ack_update_msk() sets the right edge of the MPTCP send window from the DATA_ACK and tcp_sk(ssk)->snd_wnd, but this is not always what the peer announced: mptcp_check_allowed_size() raises it to window_end - data_seq, so that TCP lets through what the MPTCP-level window allows. That is fine for new data. For data sent again, data_seq can be below snd_una, and snd_wnd ends up too large by the difference. TCP only overwrites it when an ACK moves things forward on this subflow, see tcp_may_update_window(). If a DATA_ACK moved by another subflow comes in on this subflow before that, wnd_end goes past what the peer offered. It only moves forward, so it stays there. The sender then transmits data beyond the peer's window: the peer drops it (MPTCP_MIB_NODSSWINDOW) after TCP acked it, and only an MPTCP-level retransmission can recover it, which raises snd_wnd again. The connection can then stay stuck at a low rate for several seconds, with nothing in flight on any subflow. This raise has been added by commit b713d0067574 ("mptcp: really share subflow snd_wnd"), but snd_wnd could already be too large before: when nothing moves at the TCP level, tcp_may_update_window() ignores a lower non-zero window, while the peer can announce one with a DATA_ACK that moved, keeping the same right edge. Use the window announced in the packet carrying the DATA_ACK instead. In my case with BBR, a small TCP rmem, and a second path with a much higher latency, a lower throughput and some losses, this small change can double the throughput in the worst cases. The issue has been reproduced with a new Packetdrill test, on a single subflow: the data is acked by TCP, then by MPTCP with a lower window, keeping the same right edge. Without this patch, the 2000 bytes written next were sent, instead of the 1280 bytes up to this right edge: dss_dack_window_server.pkt:23: error handling packet: live packet payload: expected 1280 bytes vs actual 2000 bytes Fixes: 6f8a612a33e4 ("mptcp: keep track of advertised windows right edge") Cc: stable@vger.kernel.org Signed-off-by: Matthieu Baerts (NGI0) Link: https://patch.msgid.link/20261116-net-mptcp-misc-fixes-7-4-rc4-v1-1-bf7656de653e@kernel.org Signed-off-by: Jakub Kicinski --- net/mptcp/options.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/net/mptcp/options.c b/net/mptcp/options.c index 02e785a14b8a5c..a1e65309171e13 100644 --- a/net/mptcp/options.c +++ b/net/mptcp/options.c @@ -1120,9 +1120,11 @@ static void rwin_update(struct mptcp_sock *msk, struct sock *ssk, static void ack_update_msk(struct mptcp_sock *msk, struct sock *ssk, + const struct sk_buff *skb, struct mptcp_options_received *mp_opt) { u64 new_wnd_end, new_snd_una, old_snd_una; + u32 win = ntohs(tcp_hdr(skb)->window); struct sock *sk = (struct sock *)msk; u64 snd_nxt; @@ -1143,7 +1145,12 @@ static void ack_update_msk(struct mptcp_sock *msk, after64(new_snd_una, snd_nxt))) new_snd_una = old_snd_una; - new_wnd_end = new_snd_una + tcp_sk(ssk)->snd_wnd; + /* What the peer announced: tcp_sk(ssk)->snd_wnd can be larger, see + * mptcp_check_allowed_size(), and is not always updated. + */ + if (likely(!tcp_hdr(skb)->syn)) + win <<= tcp_sk(ssk)->rx_opt.snd_wscale; + new_wnd_end = new_snd_una + win; if (after64(new_wnd_end, msk->wnd_end)) WRITE_ONCE(msk->wnd_end, new_wnd_end); @@ -1313,7 +1320,7 @@ bool mptcp_incoming_options(struct sock *sk, struct sk_buff *skb) * monodirectional flows will stuck */ if (mp_opt.use_ack) - ack_update_msk(msk, sk, &mp_opt); + ack_update_msk(msk, sk, skb, &mp_opt); rwin_update(msk, sk, skb); /* Zero-data-length packets are dropped by the caller and not From 68f465e3d9ce46bf78c8543aadf147eefa9f9cf4 Mon Sep 17 00:00:00 2001 From: Quanye Yang Date: Mon, 16 Nov 2026 23:06:09 +0100 Subject: [PATCH 1100/2102] mptcp: push pending data after a sendmsg copy fault mptcp_sendmsg() copies into the msk write queue first, then __mptcp_push_pending() on the success path. tcp_sendmsg_locked() does the opposite: its do_error path jumps to out, and out calls tcp_push() when copied > 0. A later iovec fault (copy_from_iter / -EFAULT) after a successful iteration therefore returns the partial byte count but leaves the already-queued dfrag on rtx_queue. No subflow packet is sent, no retransmission timer is armed, and DATA_FIN stays blocked on first_pending. Push in do_error when copied is already non-zero. Do not move the push to out: copied is a size_t, and sk_stream_error() stores a negative errno there. The issue was spot by Sashiko, but easy to reproduce with Packetdrill: writev(4, [{..., 32728}, {NULL, 4096}], 2) = 32728 Fixes: d9ca1de8c0cd ("mptcp: move page frag allocation in mptcp_sendmsg()") Cc: stable@vger.kernel.org Closes: https://github.com/multipath-tcp/mptcp_net-next/issues/640 Signed-off-by: Quanye Yang Reviewed-by: Matthieu Baerts (NGI0) Signed-off-by: Matthieu Baerts (NGI0) Fixes: d9ca1de8c0cd ("mptcp: move page frag allocation in mptcp_sendmsg()") Link: https://patch.msgid.link/20261116-net-mptcp-misc-fixes-7-4-rc4-v1-2-bf7656de653e@kernel.org Signed-off-by: Jakub Kicinski --- net/mptcp/protocol.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/net/mptcp/protocol.c b/net/mptcp/protocol.c index 8a9efebf34979b..b375da1f17feda 100644 --- a/net/mptcp/protocol.c +++ b/net/mptcp/protocol.c @@ -2130,8 +2130,10 @@ static int mptcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) return copied; do_error: - if (copied) + if (copied) { + __mptcp_push_pending(sk, msg->msg_flags); goto out; + } copied = sk_stream_error(sk, msg->msg_flags, ret); goto out; From bb6081907c60fd49c56715bd231ac2d92f62967d Mon Sep 17 00:00:00 2001 From: "Matthieu Baerts (NGI0)" Date: Mon, 16 Nov 2026 23:06:10 +0100 Subject: [PATCH 1101/2102] mptcp: use sk instead of casting msk in check_fully_established() The MPTCP socket is cast to a struct sock in check_fully_established(), to take its data lock. The next commits need it more, to push the pending data. Add a local 'sk' variable instead of casting msk each time: no functional change. The 'Fixes' tag here below is the same as the one from the next commits: this patch is needed to fix the issues introduced by this commit ID. Fixes: 36b122baf6a8 ("mptcp: add subflow_v(4,6)_send_synack()") Cc: stable@vger.kernel.org Signed-off-by: Matthieu Baerts (NGI0) Link: https://patch.msgid.link/20261116-net-mptcp-misc-fixes-7-4-rc4-v1-3-bf7656de653e@kernel.org Signed-off-by: Jakub Kicinski --- net/mptcp/options.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/net/mptcp/options.c b/net/mptcp/options.c index a1e65309171e13..1c58468b985b6f 100644 --- a/net/mptcp/options.c +++ b/net/mptcp/options.c @@ -982,6 +982,8 @@ static bool check_fully_established(struct mptcp_sock *msk, struct sock *ssk, struct sk_buff *skb, struct mptcp_options_received *mp_opt) { + struct sock *sk = (struct sock *)msk; + /* here we can process OoO, in-window pkts, only in-sequence 4th ack * will make the subflow fully established */ @@ -1043,9 +1045,9 @@ static bool check_fully_established(struct mptcp_sock *msk, struct sock *ssk, if (mp_opt->deny_join_id0) WRITE_ONCE(msk->pm.remote_deny_join_id0, true); - mptcp_data_lock((struct sock *)msk); + mptcp_data_lock(sk); __mptcp_subflow_fully_established(msk, subflow, mp_opt); - mptcp_data_unlock((struct sock *)msk); + mptcp_data_unlock(sk); check_notify: /* if the subflow is not already linked into the conn_list, we can't From d7c650916aa1db338b39aa527594d18d557436fe Mon Sep 17 00:00:00 2001 From: "Matthieu Baerts (NGI0)" Date: Mon, 16 Nov 2026 23:06:11 +0100 Subject: [PATCH 1102/2102] mptcp: push queued data on passive TFO subflows becoming established With TCP Fast Open, the data written by an MPTCP server before the 3rd ACK is not sent when this ACK arrives, but only when another event triggers a push, e.g. new data from the peer. With a request/response protocol, the client waits for the reply, which can then stay stuck. A SYN with a valid TFO cookie creates a child socket right away, which can be accepted while its subflow is still in the SYN_RECV state. The MPTCP socket is already in the ESTABLISHED state: send() puts the data in its write queue, but this data cannot be pushed to the subflow before it is established, see __mptcp_subflow_active(). When the third ACK, with the MP_CAPABLE option, arrives, check_fully_established() marks the subflow as fully established, but nothing pushes the pending data: this ACK has no DSS option, so ack_update_msk() is not called. The fix used here is to push the pending data when a passive TFO subflow becomes fully established. Checking subflow->is_mptfo is not enough: since commit e00b63056fb4 ("mptcp: fastopen: only mark MPTFO subflows with SYN data"), it is not set when the SYN has no data, while a child is also created in this case. syn_fastopen_child is then used instead. This issue has been reported by a user of proxies over MPTCP: the clients put their requests in the SYN, and the replies from the targets close to the server were stuck. It has been reproduced with new Packetdrill tests, where the server writes data before the third ACK, after a SYN with and without data. Without this patch, and before the earlier commit "mptcp: arm the rtx timer if a push leaves data behind", this data was not sent: server-tfo-write-before-3rd-ack.pkt:24: error handling packet: Timed out waiting for packet Since this earlier commit, this data is sent, but only when the MPTCP retransmission timer fires, here after one second, as the tests increase its interval: server-tfo-write-before-3rd-ack.pkt:24: error handling packet: timing error: expected outbound packet at 0.237174 sec but happened at 1.181857 sec; tolerance 0.100000 sec Fixes: 36b122baf6a8 ("mptcp: add subflow_v(4,6)_send_synack()") Cc: stable@vger.kernel.org Suggested-by: Petar Sakic Suggested-by: T S Rameshkumar Reported-by: Petar Sakic Closes: https://lore.kernel.org/mptcp/CAFPPu1gU2Y-D+d4i3F0MoNkYK+e1U+=X3qf6QycjfKBw+8snPg@mail.gmail.com/ Signed-off-by: Matthieu Baerts (NGI0) Link: https://patch.msgid.link/20261116-net-mptcp-misc-fixes-7-4-rc4-v1-4-bf7656de653e@kernel.org Signed-off-by: Jakub Kicinski --- net/mptcp/options.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/net/mptcp/options.c b/net/mptcp/options.c index 1c58468b985b6f..bcf3440d1901b9 100644 --- a/net/mptcp/options.c +++ b/net/mptcp/options.c @@ -1047,6 +1047,8 @@ static bool check_fully_established(struct mptcp_sock *msk, struct sock *ssk, mptcp_data_lock(sk); __mptcp_subflow_fully_established(msk, subflow, mp_opt); + if (tcp_sk(ssk)->syn_fastopen_child) + __mptcp_check_push(sk, ssk); mptcp_data_unlock(sk); check_notify: From 595b7d49d4f1295a2be554d1048d6b5cff8d81a4 Mon Sep 17 00:00:00 2001 From: "Matthieu Baerts (NGI0)" Date: Mon, 16 Nov 2026 23:06:12 +0100 Subject: [PATCH 1103/2102] mptcp: push queued data on subflows falling back at the handshake With TCP Fast Open, the data written by an MPTCP server before the 3rd ACK is not sent when this ACK arrives without MPTCP options, but only when another event triggers a push, e.g. new data from the peer. The previous commit pushes this data when the third ACK, with the MP_CAPABLE option, makes a passive TFO subflow fully established. If this ACK has no MPTCP options, e.g. because a middlebox removed them, check_fully_established() falls back to TCP, and returns before this push. The fallback case of mptcp_incoming_options(), which pushes the pending data, is only reached with the next packets. The fix used here is to push the pending data after this fallback too. Not only for the passive TFO subflows: data can also be pending on the client side, when the first ACK from the server has no MPTCP options, e.g. if the window announced by the SYN+ACK was too small for it. Same here, this data was then only sent when another event triggered a push. This issue has been found by an AI code review agent (Clashiko), while reviewing an earlier version of the previous commit. It has been reproduced with a new Packetdrill test, where the MPTCP options are removed from the third ACK. Without this patch, and before the earlier commit "mptcp: arm the rtx timer if a push leaves data behind", this data was not sent: server-tfo-fallback-write-before-3rd-ack.pkt:26: error handling packet: Timed out waiting for packet Since this earlier commit, this data is sent, but only when the MPTCP retransmission timer fires, here after one second, as the test increases its interval: server-tfo-fallback-write-before-3rd-ack.pkt:26: error handling packet: timing error: expected outbound packet at 0.235869 sec but happened at 1.144189 sec; tolerance 0.100000 sec The client side case has been reported by Sashiko, while reviewing an earlier version of this commit, and confirmed with another new Packetdrill test, where the client writes more data than the window of the SYN+ACK, before an ACK without MPTCP options. Without this patch: v1_connect_fallback_pending_data.pkt:30: error handling packet: timing error: expected outbound packet at 0.251394 sec but happened at 1.195904 sec; tolerance 0.100000 sec Two Fixes tags: the passive TFO case comes from the first commit, and the client side one from the second one. Fixes: 36b122baf6a8 ("mptcp: add subflow_v(4,6)_send_synack()") Fixes: 6f8a612a33e4 ("mptcp: keep track of advertised windows right edge") Cc: stable@vger.kernel.org Signed-off-by: Matthieu Baerts (NGI0) Link: https://patch.msgid.link/20261116-net-mptcp-misc-fixes-7-4-rc4-v1-5-bf7656de653e@kernel.org Signed-off-by: Jakub Kicinski --- net/mptcp/options.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/net/mptcp/options.c b/net/mptcp/options.c index bcf3440d1901b9..617358ff7f990c 100644 --- a/net/mptcp/options.c +++ b/net/mptcp/options.c @@ -1035,6 +1035,10 @@ static bool check_fully_established(struct mptcp_sock *msk, struct sock *ssk, MPTCP_INC_STATS(sock_net(ssk), MPTCP_MIB_FALLBACKFAILED); goto reset; } + /* this ACK will not reach the fallback path: push from here */ + mptcp_data_lock(sk); + __mptcp_check_push(sk, ssk); + mptcp_data_unlock(sk); return false; } From d0e88ecfae68043ac9ed2c6991f001830af7ebdd Mon Sep 17 00:00:00 2001 From: "Matthieu Baerts (NGI0)" Date: Mon, 16 Nov 2026 23:06:13 +0100 Subject: [PATCH 1104/2102] mptcp: don't send a FIN before the pending data on fallback When an MPTCP connection falls back to TCP after having been shut down, the data that is still in the write queue of the MPTCP socket is lost: a FIN is sent at fallback time, and this data cannot be sent after it. This can happen with TCP Fast Open (TFO), when a server writes data and shuts the connection down before the third ACK, and this ACK has no MPTCP options. When the MPTCP socket has been shut down, mptcp_try_fallback() also shuts the subflow down: if the DATA_FIN had already been sent, nothing would send a FIN on this subflow otherwise. The commit introducing this only considered the case where all the data had already been pushed to the subflow. The fix used here is to only shut the subflow down at fallback time if no new data is pending, i.e. if all the data before the DATA_FIN has already been sent. Otherwise, mptcp_check_send_data_fin() will do it once this data has been pushed, e.g. by the previous commit. Pending data that has been reinjected, e.g. after the failure of another subflow, is not new: it is already in this subflow. This issue has been found by an AI code review agent, while reviewing the code of the previous commit, and confirmed with a new Packetdrill test, where the server writes data and shuts the connection down before the third ACK, from which the MPTCP options are removed. Without this patch, a FIN was sent right after this ACK, and the data was never sent: inbound injected packet: 0.240127 . 501:501(0) ack 4103187975 win 450 outbound sniffed packet: 0.240207 F. 4103187975:4103187975(0) ack 501 win 1050 outbound sniffed packet: 1.347800 F. 4103187975:4103187975(0) ack 501 win 1050 outbound sniffed packet: 2.499829 F. 4103187975:4103187975(0) ack 501 win 1050 outbound sniffed packet: 4.739843 F. 4103187975:4103187975(0) ack 501 win 1050 server-tfo-fallback-shutdown-before-3rd-ack.pkt:27: error handling packet: Timed out waiting for packet Fixes: d51991e2e314 ("mptcp: fix shutdown vs fallback race") Cc: stable@vger.kernel.org Signed-off-by: Matthieu Baerts (NGI0) Link: https://patch.msgid.link/20261116-net-mptcp-misc-fixes-7-4-rc4-v1-6-bf7656de653e@kernel.org Signed-off-by: Jakub Kicinski --- net/mptcp/protocol.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/net/mptcp/protocol.h b/net/mptcp/protocol.h index 011e73d04ee604..7d226ee38315da 100644 --- a/net/mptcp/protocol.h +++ b/net/mptcp/protocol.h @@ -1333,7 +1333,11 @@ static inline bool mptcp_try_fallback(struct sock *ssk, int fb_mib) msk = mptcp_sk(sk); if (!__mptcp_try_fallback(msk, fb_mib)) return false; - if (READ_ONCE(msk->snd_data_fin_enable) && !(ssk->sk_shutdown & SEND_SHUTDOWN)) { + + /* no FIN before new data: see mptcp_check_send_data_fin() */ + if (READ_ONCE(msk->snd_data_fin_enable) && + !before64(READ_ONCE(msk->snd_nxt) + 1, READ_ONCE(msk->write_seq)) && + !(ssk->sk_shutdown & SEND_SHUTDOWN)) { gfp_t saved_allocation = ssk->sk_allocation; /* we are in a atomic (BH) scope, override ssk default for data From 3d064436b2872fa08537419e62d96951da6e96dd Mon Sep 17 00:00:00 2001 From: Geliang Tang Date: Mon, 16 Nov 2026 23:06:14 +0100 Subject: [PATCH 1105/2102] mptcp: fix dummy mapping of overlapping segments An MPTCP socket that has fallen back to TCP can silently lose received data if a segment partly overlaps data received earlier, and recv() then blocks, returning neither later data nor end of file. After a fallback, subflow_check_data_avail() makes up a dummy mapping for the skb at the head of the subflow's receive queue, in which map_seq and map_subflow_seq must describe the same byte. But since commit 2834f8edd74d ("mptcp: cleanup fallback dummy mapping generation"), it computes map_seq from the first byte of the skb, while map_subflow_seq is still computed from copied_seq, the next unread byte. mptcp_subflow_get_mapped_dsn() then returns the data sequence number (DSN) of the first byte of the skb, instead of the one of copied_seq. These two bytes differ for a segment that starts before rcv_nxt and ends after it, since TCP does not trim it. mptcp_init_skb() then gives the new bytes of this skb a DSN that is too low, and __mptcp_move_skb() skips some of them as old data, leaving a hole in the stream: bytes 0 to 999 are received, the skb holds bytes 900 to 1499 byte 1000 gets the DSN of byte 900: too low by the 100 old bytes that is 100 below ack_seq, the next DSN that MPTCP expects __mptcp_move_skb() skips bytes 1000 to 1099 as old data ack_seq is the DSN of byte 1400, copied_seq is byte 1500 later data starts at the DSN of byte 1500: out of order the TCP FIN becomes a dummy DATA_FIN after the last byte ack_seq does not reach it, so there is no end of file Fix this by computing map_subflow_seq from the first byte of the skb as well: mptcp_subflow_get_mapped_dsn() then returns the DSN of copied_seq. Chris Mason sent the same fix in private, and found this issue with the help of an LLM. It has been reproduced in a VM, with the reproducer he shared, and with a new Packetdrill test: after a fallback to TCP, a segment overlapping data already received is injected. Without this patch, the new bytes at the beginning of this segment were lost, and the connection stalled, with no end of file: reader 30.64: conn 1 BREAK: at my offset 1000 the bytes claim offset 1100: A GAP OF 100 BYTES reader 30.64: READ-TOTAL conn 1 outcome iii-gap-or-repeat bytes 1400 of 2500 [...] [...] end: hang: no data and no end of file for 30 s And with the Packetdrill test: dss_fallback_overlap_client.pkt:24: runtime error in read call: Expected result 2500 but got 1400 with errno 115 (Operation now in progress) Fixes: 2834f8edd74d ("mptcp: cleanup fallback dummy mapping generation") Cc: stable@vger.kernel.org Link: https://lore.kernel.org/4c48d016490d43b6892c622cbae858b48f176cff.1794304840.git.tanggeliang@kylinos.cn [1] Co-developed-by: Chris Mason Signed-off-by: Chris Mason Signed-off-by: Geliang Tang [ Combine the commit messages of Geliang's [1] and Chris's versions. Commit message: how the issue was found, and its symptoms. ] Signed-off-by: Matthieu Baerts (NGI0) Link: https://patch.msgid.link/20261116-net-mptcp-misc-fixes-7-4-rc4-v1-7-bf7656de653e@kernel.org Signed-off-by: Jakub Kicinski --- net/mptcp/subflow.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/mptcp/subflow.c b/net/mptcp/subflow.c index 00677fb3efcdc9..6f07544bfe40bc 100644 --- a/net/mptcp/subflow.c +++ b/net/mptcp/subflow.c @@ -1496,7 +1496,7 @@ static bool subflow_check_data_avail(struct sock *ssk) skb = skb_peek(&ssk->sk_receive_queue); subflow->map_valid = 1; subflow->map_data_len = skb->len; - subflow->map_subflow_seq = tcp_sk(ssk)->copied_seq - subflow->ssn_offset; + subflow->map_subflow_seq = TCP_SKB_CB(skb)->seq - subflow->ssn_offset; subflow->map_seq = __mptcp_expand_seq(subflow->map_seq, subflow->iasn + TCP_SKB_CB(skb)->seq - From ca44731a7009da1dbcdf1979438d1985d93331d1 Mon Sep 17 00:00:00 2001 From: Jiri Olsa Date: Wed, 18 Nov 2026 09:44:49 +0100 Subject: [PATCH 1106/2102] bpf: Restrict uprobe ctx writes to the registers ptrace can set Since commit 7384893d970e ("bpf: Allow uprobe program to change context registers") a uprobe program can write any field of struct pt_regs. Some of those fields are not plain user registers. The exit to user space loads them into the CPU: arch field exit path ptrace ------ ------ ------------------------------- ------------------ riscv status csrw CSR_STATUS, a0 not in the regset arm64 pstate msr spsr_el1, x22 valid_user_regs() x86-64 cs, ss (cs & 3) == 0: iretq to ring 0 set_segment_reg() x86-64 flags iretq loads IF and IOPL set_flags() On riscv a program that sets sstatus.SPP in pt_regs.status makes ret_from_exception return to user code in supervisor mode. On x86-64 a program that writes a kernel selector to cs makes iretq return to ring 0. ptrace guards these fields, but the bpf verifier does not. Add arch_uprobe_regs_writable(). Each arch lists the registers that ptrace can set to any value, and kprobe_prog_is_valid_access() rejects writes to any other offset when the program is loaded: arm64: x0 to x30, sp, pc riscv: epc, ra to t6 x86-64: r15 to di, ip, sp The default is no writes, so arches without a list (and 32-bit x86) lose ctx writes for uprobe programs. Reads are not affected. flags on x86-64 and pstate on arm64 become read-only, including the condition bits that ptrace would let a debugger change. orig_ax is read-only too. Kprobe programs that write ctx were already rejected when they were attached. Those that write one of these fields now fail to load. Fixes: 7384893d970e ("bpf: Allow uprobe program to change context registers") Reported-by: rtm@csail.mit.edu Suggested-by: Alexei Starovoitov Signed-off-by: Jiri Olsa Signed-off-by: Alexei Starovoitov Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261118084451.12590-2-jolsa@kernel.org Closes: https://lore.kernel.org/bpf/30318.1794850523@30-11-166.wireless.csail.mit.edu/ --- arch/arm64/kernel/probes/uprobes.c | 6 ++++++ arch/riscv/kernel/probes/uprobes.c | 6 ++++++ arch/x86/kernel/uprobes.c | 15 +++++++++++++++ include/linux/uprobes.h | 5 +++++ kernel/events/uprobes.c | 9 +++++++++ kernel/trace/bpf_trace.c | 10 +++++++++- 6 files changed, 50 insertions(+), 1 deletion(-) diff --git a/arch/arm64/kernel/probes/uprobes.c b/arch/arm64/kernel/probes/uprobes.c index 2a9b0bc083a3b4..1e6ac4785a5338 100644 --- a/arch/arm64/kernel/probes/uprobes.c +++ b/arch/arm64/kernel/probes/uprobes.c @@ -152,6 +152,12 @@ bool arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx, return regs->sp < ret->stack; } +bool arch_uprobe_regs_writable(int off, int size) +{ + /* From x0 to x30, sp, pc. */ + return off + size <= offsetof(struct pt_regs, pstate); +} + unsigned long arch_uretprobe_hijack_return_addr(unsigned long trampoline_vaddr, struct pt_regs *regs) diff --git a/arch/riscv/kernel/probes/uprobes.c b/arch/riscv/kernel/probes/uprobes.c index eb177d0ce8ab0e..dbb15346319729 100644 --- a/arch/riscv/kernel/probes/uprobes.c +++ b/arch/riscv/kernel/probes/uprobes.c @@ -126,6 +126,12 @@ bool arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx, return regs->sp < ret->stack; } +bool arch_uprobe_regs_writable(int off, int size) +{ + /* epc, from ra to t6. */ + return off + size <= offsetof(struct pt_regs, status); +} + unsigned long arch_uretprobe_hijack_return_addr(unsigned long trampoline_vaddr, struct pt_regs *regs) diff --git a/arch/x86/kernel/uprobes.c b/arch/x86/kernel/uprobes.c index 0f60c0d076b620..fc07bcd0f4627c 100644 --- a/arch/x86/kernel/uprobes.c +++ b/arch/x86/kernel/uprobes.c @@ -1888,6 +1888,21 @@ bool arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx, return regs->sp <= ret->stack; } +bool arch_uprobe_regs_writable(int off, int size) +{ + int end = off + size; + + /* The 32-bit pt_regs has segments in front of orig_ax. */ + if (!IS_ENABLED(CONFIG_X86_64)) + return false; + /* From r15 to di. Not orig_ax, cs, flags, ss. */ + if (end <= offsetof(struct pt_regs, orig_ax)) + return true; + if (off >= offsetof(struct pt_regs, ip) && end <= offsetofend(struct pt_regs, ip)) + return true; + return off >= offsetof(struct pt_regs, sp) && end <= offsetofend(struct pt_regs, sp); +} + /* * Heuristic-based check if uprobe is installed at the function entry. * diff --git a/include/linux/uprobes.h b/include/linux/uprobes.h index d34dbc0fbbfe1a..43b250bff16251 100644 --- a/include/linux/uprobes.h +++ b/include/linux/uprobes.h @@ -239,6 +239,7 @@ extern void uprobe_copy_from_page(struct page *page, unsigned long vaddr, void * extern void handle_syscall_uprobe(struct pt_regs *regs, unsigned long bp_vaddr); extern void arch_uprobe_optimize(struct arch_uprobe *auprobe, unsigned long vaddr); extern unsigned long arch_uprobe_get_xol_area(void); +extern bool arch_uprobe_regs_writable(int off, int size); #else /* !CONFIG_UPROBES */ struct uprobes_state { }; @@ -300,5 +301,9 @@ static inline void uprobe_copy_process(struct task_struct *t, u64 flags) static inline void uprobe_clear_state(struct mm_struct *mm) { } +static inline bool arch_uprobe_regs_writable(int off, int size) +{ + return false; +} #endif /* !CONFIG_UPROBES */ #endif /* _LINUX_UPROBES_H */ diff --git a/kernel/events/uprobes.c b/kernel/events/uprobes.c index caf444762a274b..c47b1ee266d515 100644 --- a/kernel/events/uprobes.c +++ b/kernel/events/uprobes.c @@ -2703,6 +2703,15 @@ void __weak arch_uprobe_optimize(struct arch_uprobe *auprobe, unsigned long vadd { } +/* + * Can a bpf prog write these bytes of pt_regs? An arch opts in and lists the + * registers that ptrace can set to any value. + */ +bool __weak arch_uprobe_regs_writable(int off, int size) +{ + return false; +} + /* * Run handler and ask thread to singlestep. * Ensure all non-fatal signals cannot interrupt thread while it singlesteps. diff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c index 2aec56d7f3d3ef..636c9849e07f72 100644 --- a/kernel/trace/bpf_trace.c +++ b/kernel/trace/bpf_trace.c @@ -1397,8 +1397,16 @@ static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type if (off + size > sizeof(struct pt_regs)) return false; - if (type == BPF_WRITE) + if (type == BPF_WRITE) { + /* + * pt_regs also holds what the kernel restores on the way to + * user space: cs and flags on x86, pstate on arm64, status on + * riscv. A prog can write the registers of the task only. + */ + if (!arch_uprobe_regs_writable(off, size)) + return false; prog->aux->kprobe_write_ctx = true; + } return true; } From c21b0f82ca96750e81a38b041c037de6b5dab60a Mon Sep 17 00:00:00 2001 From: Jiri Olsa Date: Wed, 18 Nov 2026 09:44:50 +0100 Subject: [PATCH 1107/2102] selftests/bpf: Test which ctx registers a uprobe prog can write A uprobe program can write only the pt_regs fields that ptrace can set to any value. Add verifier tests for x86-64, arm64 and riscv: - writes to the general registers, the stack pointer and the instruction pointer load - writes to cs, ss, flags and orig_ax on x86-64, to pstate and orig_x0 on arm64, and to status, badaddr and cause on riscv fail with "invalid bpf_context access" - a 4-byte write to the low half of a read-only field fails too - reading a read-only field still works - on x86-64, a kprobe program that writes ctx->flags fails to load Other arches get one test that just loads. Signed-off-by: Jiri Olsa Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261118084451.12590-3-jolsa@kernel.org --- .../selftests/bpf/prog_tests/verifier.c | 2 + .../bpf/progs/verifier_uprobe_write_ctx.c | 196 ++++++++++++++++++ 2 files changed, 198 insertions(+) create mode 100644 tools/testing/selftests/bpf/progs/verifier_uprobe_write_ctx.c diff --git a/tools/testing/selftests/bpf/prog_tests/verifier.c b/tools/testing/selftests/bpf/prog_tests/verifier.c index 6a494c38126601..5a31f04677e0f1 100644 --- a/tools/testing/selftests/bpf/prog_tests/verifier.c +++ b/tools/testing/selftests/bpf/prog_tests/verifier.c @@ -131,6 +131,7 @@ #include "verifier_unpriv.skel.h" #include "verifier_unwind.skel.h" #include "verifier_unpriv_perf.skel.h" +#include "verifier_uprobe_write_ctx.skel.h" #include "verifier_value_adj_spill.skel.h" #include "verifier_value.skel.h" #include "verifier_value_illegal_alu.skel.h" @@ -321,6 +322,7 @@ void test_verifier_uninit(void) { RUN(verifier_uninit); } void test_verifier_unpriv(void) { RUN(verifier_unpriv); } void test_verifier_unwind(void) { RUN(verifier_unwind); } void test_verifier_unpriv_perf(void) { RUN(verifier_unpriv_perf); } +void test_verifier_uprobe_write_ctx(void) { RUN(verifier_uprobe_write_ctx); } void test_verifier_value_adj_spill(void) { RUN(verifier_value_adj_spill); } void test_verifier_value(void) { RUN(verifier_value); } void test_verifier_value_illegal_alu(void) { RUN(verifier_value_illegal_alu); } diff --git a/tools/testing/selftests/bpf/progs/verifier_uprobe_write_ctx.c b/tools/testing/selftests/bpf/progs/verifier_uprobe_write_ctx.c new file mode 100644 index 00000000000000..f5ed453b179823 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/verifier_uprobe_write_ctx.c @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "vmlinux.h" +#include +#include "bpf_misc.h" + +/* + * A uprobe prog can write only the registers that ptrace can set to any + * value. The fields the kernel restores on the way to user space (segments, + * flags, privilege state) are read-only. + */ + +#define WRITE_CTX(name, field, sz) \ +__naked void name(void) \ +{ \ + asm volatile (" \ + r2 = 0; \ + *(" #sz " *)(r1 + %[off]) = r2; \ + r0 = 0; \ + exit; \ +" : \ + : __imm_const(off, offsetof(struct pt_regs, field)) \ + : __clobber_all); \ +} + +#define READ_CTX(name, field) \ +__naked void name(void) \ +{ \ + asm volatile (" \ + r0 = *(u64 *)(r1 + %[off]); \ + r0 = 0; \ + exit; \ +" : \ + : __imm_const(off, offsetof(struct pt_regs, field)) \ + : __clobber_all); \ +} + +#if defined(__TARGET_ARCH_x86) + +SEC("uprobe") +__description("uprobe: write ctx->ax") +__success +WRITE_CTX(write_ax, ax, u64) + +SEC("uprobe") +__description("uprobe: write ctx->r15") +__success +WRITE_CTX(write_r15, r15, u64) + +SEC("uprobe") +__description("uprobe: write ctx->di") +__success +WRITE_CTX(write_di, di, u64) + +SEC("uprobe") +__description("uprobe: write ctx->ip") +__success +WRITE_CTX(write_ip, ip, u64) + +SEC("uprobe") +__description("uprobe: write ctx->sp") +__success +WRITE_CTX(write_sp, sp, u64) + +SEC("uprobe") +__description("uprobe: write lower half of ctx->ax") +__success +WRITE_CTX(write_ax_u32, ax, u32) + +SEC("uprobe") +__description("uprobe: write ctx->orig_ax") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_orig_ax, orig_ax, u64) + +SEC("uprobe") +__description("uprobe: write ctx->cs") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_cs, cs, u64) + +SEC("uprobe") +__description("uprobe: write lower half of ctx->cs") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_cs_u32, cs, u32) + +SEC("uprobe") +__description("uprobe: write ctx->flags") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_flags, flags, u64) + +SEC("uprobe") +__description("uprobe: write ctx->ss") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_ss, ss, u64) + +SEC("uprobe") +__description("uprobe: read ctx->flags") +__success +READ_CTX(read_flags, flags) + +SEC("kprobe") +__description("kprobe: write ctx->flags") +__failure __msg("invalid bpf_context access") +WRITE_CTX(kprobe_write_flags, flags, u64) + +#elif defined(__TARGET_ARCH_arm64) + +SEC("uprobe") +__description("uprobe: write ctx->regs[0]") +__success +WRITE_CTX(write_x0, regs[0], u64) + +SEC("uprobe") +__description("uprobe: write ctx->regs[30]") +__success +WRITE_CTX(write_x30, regs[30], u64) + +SEC("uprobe") +__description("uprobe: write ctx->sp") +__success +WRITE_CTX(write_sp, sp, u64) + +SEC("uprobe") +__description("uprobe: write ctx->pc") +__success +WRITE_CTX(write_pc, pc, u64) + +SEC("uprobe") +__description("uprobe: write ctx->pstate") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_pstate, pstate, u64) + +SEC("uprobe") +__description("uprobe: write lower half of ctx->pstate") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_pstate_u32, pstate, u32) + +SEC("uprobe") +__description("uprobe: write ctx->orig_x0") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_orig_x0, orig_x0, u64) + +SEC("uprobe") +__description("uprobe: read ctx->pstate") +__success +READ_CTX(read_pstate, pstate) + +#elif defined(__TARGET_ARCH_riscv) + +SEC("uprobe") +__description("uprobe: write ctx->epc") +__success +WRITE_CTX(write_epc, epc, u64) + +SEC("uprobe") +__description("uprobe: write ctx->a0") +__success +WRITE_CTX(write_a0, a0, u64) + +SEC("uprobe") +__description("uprobe: write ctx->t6") +__success +WRITE_CTX(write_t6, t6, u64) + +SEC("uprobe") +__description("uprobe: write ctx->status") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_status, status, u64) + +SEC("uprobe") +__description("uprobe: write ctx->badaddr") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_badaddr, badaddr, u64) + +SEC("uprobe") +__description("uprobe: write ctx->cause") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_cause, cause, u64) + +SEC("uprobe") +__description("uprobe: read ctx->status") +__success +READ_CTX(read_status, status) + +#else + +SEC("uprobe") +__description("uprobe: ctx writes not checked on this arch") +__success +__naked void unsupported(void) +{ + asm volatile ("r0 = 0; exit;" ::: __clobber_all); +} + +#endif + +char _license[] SEC("license") = "GPL"; From 14bc5d239dddb3ce1264de74b8460c0a61745563 Mon Sep 17 00:00:00 2001 From: Louis Sautier Date: Wed, 18 Nov 2026 21:13:16 +0100 Subject: [PATCH 1108/2102] scsi: mpt3sas: Fix out-of-bounds cpu_msix_table read on CPU hotplug mpt3sas_base_attach() allocates cpu_msix_table based on the highest CPU online at probe time, but _base_get_msix_index() indexes it with raw_smp_processor_id() without a bounds check. Once a CPU with a higher id comes online, I/O submitted from it causes an out-of-bounds read of the table. The value read is sent to the firmware as the reply queue index. When it is not a valid queue, the IOC faults and I/O fails. On a SAS3224 (FW 16.00.01.00) running v7.4-rc3 with KASAN, booted with maxcpus=1 and CPUs 1-95 onlined later, read-only fio pinned to each CPU in turn triggers, on CPU 1: BUG: KASAN: slab-out-of-bounds in _base_get_msix_index+0x1de/0x230 [mpt3sas] Read of size 1 at addr ffff88812fdf51c1 by task kworker/1:1H/1528 and, on CPU 16: mpt3sas_cm0: fault_state(0x1500)! mpt3sas_cm0: sending diag reset !! I/O error, dev sda, sector 3873068048 op 0x0:(READ) flags 0x800000 phys_seg 1 prio class 2 mpt3sas_cm0: removing unresponding devices: start sd 0:0:0:0: [sda] Synchronizing SCSI cache Allocate the table based on nr_cpu_ids instead, and map every CPU in each reply queue's affinity mask, including offline ones. Managed IRQ affinity already spreads the vectors over all possible CPUs, so a CPU onlined later uses the queue whose affinity mask contains it. The online-mask restriction and the bounds check added by commit 4a8842de8db4 ("scsi: mpt3sas: fix an out of bound write") are no longer needed, since the table now has an entry for every possible CPU. When smp_affinity_enable=0 or a reply queue has no affinity mask, the fallback path still sets only the entries of the CPUs online at probe time. A CPU onlined later then reads 0 from the zeroed table, and queue 0 is always a valid queue. With the change, the same fio test runs without errors, also while CPUs 1-95 are taken offline and back online in a loop. With maxcpus=12 (12 reply queues), I/O from each of the 96 CPUs completes on the vector whose affinity mask contains that CPU. Fixes: f92363d12359 ("[SCSI] mpt3sas: add new driver supporting 12GB SAS") Cc: stable@vger.kernel.org Signed-off-by: Louis Sautier Link: https://patch.msgid.link/20261118201316.326943-1-sautier.louis@gmail.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/mpt3sas/mpt3sas_base.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/drivers/scsi/mpt3sas/mpt3sas_base.c b/drivers/scsi/mpt3sas/mpt3sas_base.c index 1af25a22611a13..3df792a906c16c 100644 --- a/drivers/scsi/mpt3sas/mpt3sas_base.c +++ b/drivers/scsi/mpt3sas/mpt3sas_base.c @@ -3264,11 +3264,8 @@ _base_assign_reply_queues(struct MPT3SAS_ADAPTER *ioc) goto fall_back; } - for_each_cpu_and(cpu, mask, cpu_online_mask) { - if (cpu >= ioc->cpu_msix_table_sz) - break; + for_each_cpu(cpu, mask) ioc->cpu_msix_table[cpu] = reply_q->msix_index; - } } return; } @@ -8410,15 +8407,18 @@ int mpt3sas_base_attach(struct MPT3SAS_ADAPTER *ioc) { int r, i, rc; - int cpu_id, last_cpu_id = 0; dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__)); /* setup cpu_msix_table */ ioc->cpu_count = num_online_cpus(); - for_each_online_cpu(cpu_id) - last_cpu_id = cpu_id; - ioc->cpu_msix_table_sz = last_cpu_id + 1; + /* + * Allocate an entry for every possible CPU, because + * _base_get_msix_index() indexes the table with + * raw_smp_processor_id(), which can be a CPU brought online after + * the adapter was attached. + */ + ioc->cpu_msix_table_sz = nr_cpu_ids; ioc->cpu_msix_table = kzalloc(ioc->cpu_msix_table_sz, GFP_KERNEL); ioc->reply_queue_count = 1; if (!ioc->cpu_msix_table) { From e421df3c838692c0c3503768ec3c9183f6df77aa Mon Sep 17 00:00:00 2001 From: Tariq Toukan Date: Wed, 18 Nov 2026 16:40:42 +0200 Subject: [PATCH 1109/2102] net/mlx5e: SHAMPO: Do not merge packets with different kTLS RX state HW-GRO (SHAMPO) sessions are not terminated by HW when the kTLS RX offload indication in the CQE changes. The driver applies the offload metadata of the first packet in the session only, so ciphertext and plaintext can end up in the same skb under a single skb->decrypted indication, and resync requests carried by non-first packets are lost. Do not merge a CQE whose decryption state differs from skb->decrypted, which the first packet of the session sets. Never merge a CQE that carries a resync request or a TLS error, so that each of them starts a session and is handled. The failure was reproduced on ConnectX-7 with HW GRO and kTLS RX offload on and 0.3% loss added by netem on the sender's egress: TlsDecryptError increased and the receiving sockets failed with EBADMSG. With this patch, TlsDecryptError stays 0. Fixes: 92552d3abd32 ("net/mlx5e: HW_GRO cqe handler implementation") Signed-off-by: Tariq Toukan Reviewed-by: Gal Pressman Reviewed-by: Cosmin Ratiu Link: https://patch.msgid.link/20261118144042.1916204-1-tariqt@nvidia.com Signed-off-by: Jakub Kicinski --- .../mellanox/mlx5/core/en_accel/en_accel.h | 5 +++-- .../mellanox/mlx5/core/en_accel/ktls_txrx.h | 21 +++++++++++++++++++ .../net/ethernet/mellanox/mlx5/core/en_rx.c | 2 +- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/en_accel.h b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/en_accel.h index 5a340f1435e6be..554c225f73767f 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/en_accel.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/en_accel.h @@ -219,9 +219,10 @@ static inline void mlx5e_accel_tx_finish(struct mlx5e_txqsq *sq, } static inline bool -mlx5e_accel_shampo_can_merge(struct mlx5e_rq *rq, struct mlx5_cqe64 *cqe) +mlx5e_accel_shampo_can_merge(struct sk_buff *skb, struct mlx5_cqe64 *cqe) { - return mlx5e_psp_shampo_can_merge(rq->hw_gro_data->skb, cqe); + return mlx5e_psp_shampo_can_merge(skb, cqe) && + mlx5e_ktls_shampo_can_merge(skb, cqe); } static inline int mlx5e_accel_init_rx(struct mlx5e_priv *priv) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls_txrx.h b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls_txrx.h index 93bd383a23d8c2..20e5dc6a718e10 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls_txrx.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls_txrx.h @@ -60,6 +60,21 @@ mlx5e_ktls_handle_tx_wqe(struct mlx5_wqe_ctrl_seg *cseg, { cseg->tis_tir_num = cpu_to_be32(state->tls_tisn << 8); } + +/* The first CQE of a HW-GRO session sets skb->decrypted. A resync request or + * a TLS error is handled on the first CQE only, so it starts a new session. + */ +static inline bool +mlx5e_ktls_shampo_can_merge(struct sk_buff *skb, struct mlx5_cqe64 *cqe) +{ + u8 tls_offload = get_cqe_tls_offload(cqe); + + if (unlikely(tls_offload > CQE_TLS_OFFLOAD_DECRYPTED)) + return false; + + return (tls_offload == CQE_TLS_OFFLOAD_DECRYPTED) == + skb_is_decrypted(skb); +} #else static inline bool mlx5e_ktls_tx_try_handle_resync_dump_comp(struct mlx5e_txqsq *sq, @@ -93,6 +108,12 @@ static inline void mlx5e_ktls_handle_rx_skb(struct mlx5e_rq *rq, u32 *cqe_bcnt) { } + +static inline bool +mlx5e_ktls_shampo_can_merge(struct sk_buff *skb, struct mlx5_cqe64 *cqe) +{ + return true; +} #endif /* CONFIG_MLX5_EN_TLS */ #endif /* __MLX5E_TLS_TXRX_H__ */ diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c index 22fea4739a2c97..1586cb2404c01d 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c @@ -2271,7 +2271,7 @@ static void mlx5e_handle_rx_cqe_mpwrq_shampo(struct mlx5e_rq *rq, struct mlx5_cq if (*skb && !(match && mlx5e_hw_gro_skb_has_enough_space(*skb, data_bcnt, page_size) && - mlx5e_accel_shampo_can_merge(rq, cqe))) { + mlx5e_accel_shampo_can_merge(*skb, cqe))) { match = false; mlx5e_shampo_flush_skb(rq, cqe, match); } From b30d7199af282be0a0db7f92fd8916a8ffa3d3aa Mon Sep 17 00:00:00 2001 From: Yehyeong Lee Date: Wed, 18 Nov 2026 06:13:46 +0900 Subject: [PATCH 1110/2102] scsi: target: iscsi: Run the Time2Retain handler in process context iscsit_handle_time2retain_timeout() is a timer callback, so it runs in timer softirq context, and from there it closes the session: iscsit_handle_time2retain_timeout() <- timer softirq iscsit_close_session(sess, false) transport_deregister_session() target_for_each_device(target_release_res, se_sess) mutex_lock(&device_mutex) transport_deregister_session() has walked the device list under device_mutex since commit 80647a89eaf3f2 ("scsi: target: core: Release SPC-2 reservations when closing a session"). The can_sleep argument that the handler passes as false only guards iscsit_check_session_usage_count(); the transport_deregister_session() call below it runs either way. The callback also takes se_tpg->session_lock in softirq context, and it is the only code that does, which makes that lock SOFTIRQ-safe. iscsit_start_time2retain_handler() takes tpg->tpg_state_lock with plain spin_lock() under it, so lockdep reports an inversion as well. Both the softirq acquisition and the plain spin_lock() are as old as the driver, commit e48354ce078c ("iscsi-target: Add iSCSI fabric support for target v4.1"). An initiator needs nothing but a session to get there: log in, then send a Logout with reason CLOSE_CONNECTION. iscsit_close_connection() leaves session_fall_back_to_erl0 clear for a Logout, so instead of closing the session it arms the Time2Retain handler, which runs DefaultTime2Retain seconds later because the session is never resumed. Three such logouts on a KASAN + PROVE_LOCKING + DEBUG_ATOMIC_SLEEP guest give three of these: BUG: sleeping function called from invalid context at kernel/locking/mutex.c:623 in_atomic(): 1, irqs_disabled(): 0, non_block: 0, pid: 0, name: swapper/0 preempt_count: 101, expected: 0 RCU nest depth: 0, expected: 0 INFO: lockdep is turned off. CPU: 0 UID: 0 PID: 0 Comm: swapper/0 Not tainted 7.4.0-rc2-00563-g97d73c825122 #1 PREEMPT(lazy) Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 Call Trace: dump_stack_lvl+0x80/0xa0 __might_resched+0x31c/0x520 ? __pfx___might_resched+0x10/0x10 __mutex_lock+0x10e/0x24e0 ? target_for_each_device+0x6c/0xc0 ? __irq_work_queue_local+0x18e/0x370 ? __pfx___irq_work_queue_local+0x10/0x10 ? lock_acquire+0x2c8/0x300 ? __pfx___mutex_lock+0x10/0x10 ? lock_release+0x1de/0x280 ? vprintk_emit+0x2dd/0x3d0 ? __pfx_vprintk_emit+0x10/0x10 ? target_for_each_device+0x6c/0xc0 target_for_each_device+0x6c/0xc0 ? __pfx_target_for_each_device+0x10/0x10 ? __pfx_target_release_res+0x10/0x10 ? trace_hardirqs_on+0x18/0x160 transport_deregister_session+0x19c/0x250 ? iscsit_check_session_usage_count+0xa4/0xd0 ? __local_bh_enable_ip+0xa7/0x120 iscsit_close_session+0x20c/0x540 ? __pfx_iscsit_handle_time2retain_timeout+0x10/0x10 call_timer_fn+0x15a/0x4b0 ? __pfx_call_timer_fn+0x10/0x10 ? lock_acquire+0x18d/0x300 ? __run_timer_base.part.0+0x5d4/0x930 ? lock_release+0xc6/0x280 ? timer_recalc_next_expiry+0x6e/0x210 ? lockdep_hardirqs_on_prepare+0xa9/0x190 ? __pfx_iscsit_handle_time2retain_timeout+0x10/0x10 __run_timer_base.part.0+0x5e3/0x930 ? __pfx___run_timer_base.part.0+0x10/0x10 ? __lock_acquire+0x570/0x1b00 ? find_held_lock+0x2b/0x80 ? clockevents_program_event+0x1b8/0x860 ? lock_release+0xc6/0x280 run_timer_softirq+0x12c/0x210 ? __pfx_run_timer_softirq+0x10/0x10 ? lock_acquire+0x18d/0x300 ? lockdep_hardirqs_on_prepare+0xa9/0x190 handle_softirqs+0x1ff/0x8e0 ? __irq_exit_rcu+0x1b8/0x1e0 ? __pfx_handle_softirqs+0x10/0x10 __irq_exit_rcu+0x153/0x1e0 irq_exit_rcu+0x9/0x20 sysvec_apic_timer_interrupt+0x6b/0x80 and, once per boot, this: WARNING: possible irq lock inversion dependency detected 7.4.0-rc2-00563-g97d73c825122 #1 Not tainted -------------------------------------------------------- swapper/0/0 just changed the state of lock: ffff88800ec7c148 (&se_tpg->session_lock){+.-.}-{3:3}, at: iscsit_handle_time2retain_timeout+0x46/0x1a0 but this lock took another, SOFTIRQ-unsafe lock in the past: (&tpg->tpg_state_lock){+.+.}-{3:3} and interrupts could create inverse lock ordering between them. other info that might help us debug this: Chain exists of: &se_tpg->session_lock --> &sess->conn_lock --> &tpg->tpg_state_lock Keep the timer and move only its body into a work item, so that nothing in iscsi_target takes se_tpg->session_lock in softirq context any more and the invalid sleep goes away with the inversion. Arming and stopping do not change: mod_timer() queues on the timer base of the CPU that arms it, which a caller holding a spinlock with softirqs disabled cannot let expire under itself, and iscsit_stop_time2retain_timer() still ends in timer_delete_sync(). What a stop can no longer wait for is the work. Every caller holds se_tpg->session_lock with softirqs disabled, so it must not sleep in cancel_work_sync(), and a work that has started but not yet taken that lock would outlive the stop: ISCSI_TF_STOP does not hold it back, because a later iscsit_start_time2retain_handler() clears the flag again and the work would then close a session that has been resumed. So the expiry itself is handed over. The timer sets ->time2retain_fired, the work takes it back under se_tpg->session_lock and returns without it, and a stop clears it. Only an expiry that no stop has overtaken closes a session. iscsit_close_session() must leave neither behind. The stop above can return before deleting the timer - on ISCSI_TF_EXPIRED it is the work itself that is closing the session - so delete it there, which also waits for a callback that has set the flag but not yet queued the work. Then cancel the work: wait for it where this may sleep; where it may not, it is that work, and because a work never runs twice at once the only one it can have is queued, which a non-sync cancel drops. What the restart in iscsit_close_session() does when a session usage count is held is unchanged and still wrong: iscsit_start_time2retain_handler() returns without arming anything because ISCSI_TF_RUNNING is still set. Waiting for the count instead is not an answer either, because the thread that closes the session waits on the same single completion. Fixes: e48354ce078c ("iscsi-target: Add iSCSI fabric support for target v4.1") Fixes: 80647a89eaf3 ("scsi: target: core: Release SPC-2 reservations when closing a session") Cc: stable@vger.kernel.org Signed-off-by: Yehyeong Lee Link: https://patch.msgid.link/20261117211346.2132827-1-yhlee@isslab.korea.ac.kr Signed-off-by: Martin K. Petersen (Oracle) --- drivers/target/iscsi/iscsi_target.c | 14 ++++++++++++-- drivers/target/iscsi/iscsi_target_erl0.c | 20 ++++++++++++++++---- drivers/target/iscsi/iscsi_target_erl0.h | 1 + drivers/target/iscsi/iscsi_target_login.c | 1 + include/target/iscsi/iscsi_target_core.h | 3 +++ 5 files changed, 33 insertions(+), 6 deletions(-) diff --git a/drivers/target/iscsi/iscsi_target.c b/drivers/target/iscsi/iscsi_target.c index 03d618cd767218..2b4956f46c132e 100644 --- a/drivers/target/iscsi/iscsi_target.c +++ b/drivers/target/iscsi/iscsi_target.c @@ -4485,8 +4485,8 @@ int iscsit_close_session(struct iscsit_session *sess, bool can_sleep) /* * If any other processes are accessing this session pointer we must - * wait until they have completed. If we are in an interrupt (the - * time2retain handler) and contain and active session usage count we + * wait until they have completed. If we are the Time2Retain work + * (can_sleep is false) and contain and active session usage count we * restart the timer and exit. */ if (iscsit_check_session_usage_count(sess, can_sleep)) { @@ -4516,6 +4516,16 @@ int iscsit_close_session(struct iscsit_session *sess, bool can_sleep) sess->sess_ops = NULL; spin_unlock_bh(&se_tpg->session_lock); + /* + * Neither the Time2Retain timer nor its work may outlive the session; + * a work never runs twice at once, so this work finds a queued one. + */ + timer_delete_sync(&sess->time2retain_timer); + if (can_sleep) + cancel_work_sync(&sess->time2retain_work); + else + cancel_work(&sess->time2retain_work); + kfree(sess); return 0; } diff --git a/drivers/target/iscsi/iscsi_target_erl0.c b/drivers/target/iscsi/iscsi_target_erl0.c index 24db6b07493e62..036ddc1002f6ca 100644 --- a/drivers/target/iscsi/iscsi_target_erl0.c +++ b/drivers/target/iscsi/iscsi_target_erl0.c @@ -741,15 +741,17 @@ int iscsit_check_post_dataout( } } -void iscsit_handle_time2retain_timeout(struct timer_list *t) +void iscsit_time2retain_work(struct work_struct *work) { - struct iscsit_session *sess = timer_container_of(sess, t, - time2retain_timer); + struct iscsit_session *sess = container_of(work, struct iscsit_session, + time2retain_work); struct iscsi_portal_group *tpg = sess->tpg; struct se_portal_group *se_tpg = &tpg->tpg_se_tpg; spin_lock_bh(&se_tpg->session_lock); - if (sess->time2retain_timer_flags & ISCSI_TF_STOP) { + /* A stop after the timer fired takes ->time2retain_fired back. */ + if (!atomic_xchg(&sess->time2retain_fired, 0) || + (sess->time2retain_timer_flags & ISCSI_TF_STOP)) { spin_unlock_bh(&se_tpg->session_lock); return; } @@ -769,6 +771,15 @@ void iscsit_handle_time2retain_timeout(struct timer_list *t) iscsit_close_session(sess, false); } +void iscsit_handle_time2retain_timeout(struct timer_list *t) +{ + struct iscsit_session *sess = timer_container_of(sess, t, + time2retain_timer); + + atomic_set(&sess->time2retain_fired, 1); + queue_work(system_dfl_wq, &sess->time2retain_work); +} + void iscsit_start_time2retain_handler(struct iscsit_session *sess) { int tpg_active; @@ -814,6 +825,7 @@ int iscsit_stop_time2retain_timer(struct iscsit_session *sess) timer_delete_sync(&sess->time2retain_timer); spin_lock(&se_tpg->session_lock); + atomic_set(&sess->time2retain_fired, 0); sess->time2retain_timer_flags &= ~ISCSI_TF_RUNNING; pr_debug("Stopped Time2Retain Timer for SID: %u\n", sess->sid); diff --git a/drivers/target/iscsi/iscsi_target_erl0.h b/drivers/target/iscsi/iscsi_target_erl0.h index 2a877d13977d24..f0e157b0a2f5c3 100644 --- a/drivers/target/iscsi/iscsi_target_erl0.h +++ b/drivers/target/iscsi/iscsi_target_erl0.h @@ -13,6 +13,7 @@ extern int iscsit_check_pre_dataout(struct iscsit_cmd *, unsigned char *); extern int iscsit_check_post_dataout(struct iscsit_cmd *, unsigned char *, u8); extern void iscsit_start_time2retain_handler(struct iscsit_session *); extern void iscsit_handle_time2retain_timeout(struct timer_list *t); +void iscsit_time2retain_work(struct work_struct *work); extern int iscsit_stop_time2retain_timer(struct iscsit_session *); extern void iscsit_connection_reinstatement_rcfr(struct iscsit_conn *); extern void iscsit_cause_connection_reinstatement(struct iscsit_conn *, int); diff --git a/drivers/target/iscsi/iscsi_target_login.c b/drivers/target/iscsi/iscsi_target_login.c index c282b6a7029684..fda04eb15d3a27 100644 --- a/drivers/target/iscsi/iscsi_target_login.c +++ b/drivers/target/iscsi/iscsi_target_login.c @@ -250,6 +250,7 @@ static int iscsi_login_zero_tsih_s1( timer_setup(&sess->time2retain_timer, iscsit_handle_time2retain_timeout, 0); + INIT_WORK(&sess->time2retain_work, iscsit_time2retain_work); ret = ida_alloc(&sess_ida, GFP_KERNEL); if (ret < 0) { diff --git a/include/target/iscsi/iscsi_target_core.h b/include/target/iscsi/iscsi_target_core.h index 51ca80abacf7ba..5cc688b3f7d148 100644 --- a/include/target/iscsi/iscsi_target_core.h +++ b/include/target/iscsi/iscsi_target_core.h @@ -7,6 +7,7 @@ #include #include /* struct sockaddr_storage */ #include /* u8 */ +#include /* struct work_struct */ #include /* itt_t */ #include /* struct se_cmd */ @@ -682,6 +683,8 @@ struct iscsit_session { struct completion session_wait_comp; struct completion session_waiting_on_uc_comp; struct timer_list time2retain_timer; + struct work_struct time2retain_work; + atomic_t time2retain_fired; struct iscsi_sess_ops *sess_ops; struct se_session *se_sess; struct iscsi_portal_group *tpg; From 325e921a7aa170181e1cce235d9c652cb0ad3a5b Mon Sep 17 00:00:00 2001 From: Haiyang Zhang Date: Fri, 13 Nov 2026 12:44:04 -0800 Subject: [PATCH 1111/2102] net: mana: Set 1 usec / 1 comp as default and minimum interrupt moderation The existing code sets interrupt moderation defaults to 0 usec and 0 completions, which may cause CQ starvation of our NIC HW, and TX time out error like: mana 7870:00:00.0 ens1: NETDEV WATCHDOG: CPU: 14: transmit queue 4 timed out 63434 ms To fix, change the default and minimal rx/tx usecs and frames to 1. When the HW supports interrupt moderation, reject ethtool rx/tx usecs and frames below 1. Also clamp the values written by mana_gd_ring_dim() to [1, max], so no caller, including the DIM work, programs a zero value. On the HW without interrupt moderation support, do not request CQ moderation, the usecs and frames stay at 0, and cannot be modified by ethtool. The PF capability is queried again when the device resumes from a reset or suspend, so re-initialize these settings before re-attaching the vPorts. Advertise this change to the PF with the new driver capability flag GDMA_DRV_CAP_FLAG_1_SET_MIN_INTR_MOD_VALUE. Cc: stable@vger.kernel.org Fixes: 433f482add31 ("net: mana: Add Interrupt Moderation support") Signed-off-by: Haiyang Zhang Reviewed-by: Hamza Mahfooz Reviewed-by: Simon Horman Reviewed-by: Sahil Chandna Link: https://patch.msgid.link/20261113204427.1922848-1-haiyangz@linux.microsoft.com Signed-off-by: Jakub Kicinski --- .../net/ethernet/microsoft/mana/gdma_main.c | 5 ++ drivers/net/ethernet/microsoft/mana/mana_en.c | 76 +++++++++++++------ .../ethernet/microsoft/mana/mana_ethtool.c | 26 +++++-- include/net/mana/gdma.h | 6 +- include/net/mana/mana.h | 9 ++- 5 files changed, 88 insertions(+), 34 deletions(-) diff --git a/drivers/net/ethernet/microsoft/mana/gdma_main.c b/drivers/net/ethernet/microsoft/mana/gdma_main.c index ab942d5bfe0585..10be69e97ceb9c 100644 --- a/drivers/net/ethernet/microsoft/mana/gdma_main.c +++ b/drivers/net/ethernet/microsoft/mana/gdma_main.c @@ -646,6 +646,11 @@ void mana_gd_ring_dim(struct gdma_queue *cq, u32 mod_usec, bool mod_usec_vld, struct gdma_context *gc = cq->gdma_dev->gdma_context; u32 dim_val; + mod_usec = clamp_t(u32, mod_usec, MANA_INTR_MODR_USEC_MIN, + MANA_INTR_MODR_USEC_MAX); + mod_comps = clamp_t(u32, mod_comps, MANA_INTR_MODR_COMP_MIN, + MANA_INTR_MODR_COMP_MAX); + /* Convert the DIM values to doorbell parameters */ dim_val = FIELD_PREP(MANA_INTR_MODR_USEC_MAX, mod_usec) | FIELD_PREP(MANA_INTR_MODR_COMP_MASK, mod_comps); diff --git a/drivers/net/ethernet/microsoft/mana/mana_en.c b/drivers/net/ethernet/microsoft/mana/mana_en.c index 7e9223143fc75f..95bf153c3e1a86 100644 --- a/drivers/net/ethernet/microsoft/mana/mana_en.c +++ b/drivers/net/ethernet/microsoft/mana/mana_en.c @@ -2515,9 +2515,6 @@ static void mana_rx_dim_work(struct work_struct *work) cur_moder = net_dim_get_rx_moderation(dim->mode, dim->profile_ix); cq = container_of(dim, struct mana_cq, dim); - cur_moder.usec = min_t(u16, cur_moder.usec, MANA_INTR_MODR_USEC_MAX); - cur_moder.pkts = min_t(u16, cur_moder.pkts, MANA_INTR_MODR_COMP_MAX); - mana_gd_ring_dim(cq->gdma_cq, cur_moder.usec, true, cur_moder.pkts, true); @@ -2533,9 +2530,6 @@ static void mana_tx_dim_work(struct work_struct *work) cur_moder = net_dim_get_tx_moderation(dim->mode, dim->profile_ix); cq = container_of(dim, struct mana_cq, dim); - cur_moder.usec = min_t(u16, cur_moder.usec, MANA_INTR_MODR_USEC_MAX); - cur_moder.pkts = min_t(u16, cur_moder.pkts, MANA_INTR_MODR_COMP_MAX); - mana_gd_ring_dim(cq->gdma_cq, cur_moder.usec, true, cur_moder.pkts, true); @@ -2871,10 +2865,15 @@ static int mana_create_txq(struct mana_port_context *apc, cq_spec.modr_ctx_id = 0; cq_spec.attached_eq = cq->gdma_cq->cq.parent->id; - /* DIM setting can be changed at runtime */ - cq_spec.req_cq_moderation = true; - cq_spec.cq_moderation_usec = apc->intr_modr_tx_usec; - cq_spec.cq_moderation_comp = apc->intr_modr_tx_comp; + /* Request CQ moderation only if HW supports it. + * DIM setting can be changed at runtime. + */ + if (gc->pf_cap_flags1 & + GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION) { + cq_spec.req_cq_moderation = true; + cq_spec.cq_moderation_usec = apc->intr_modr_tx_usec; + cq_spec.cq_moderation_comp = apc->intr_modr_tx_comp; + } err = mana_create_wq_obj(apc, apc->port_handle, GDMA_SQ, &wq_spec, &cq_spec, @@ -3206,10 +3205,14 @@ static struct mana_rxq *mana_create_rxq(struct mana_port_context *apc, cq_spec.modr_ctx_id = 0; cq_spec.attached_eq = cq->gdma_cq->cq.parent->id; - /* DIM setting can be changed at runtime */ - cq_spec.req_cq_moderation = true; - cq_spec.cq_moderation_usec = apc->intr_modr_rx_usec; - cq_spec.cq_moderation_comp = apc->intr_modr_rx_comp; + /* Request CQ moderation only if HW supports it. + * DIM setting can be changed at runtime. + */ + if (gc->pf_cap_flags1 & GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION) { + cq_spec.req_cq_moderation = true; + cq_spec.cq_moderation_usec = apc->intr_modr_rx_usec; + cq_spec.cq_moderation_comp = apc->intr_modr_rx_comp; + } err = mana_create_wq_obj(apc, apc->port_handle, GDMA_RQ, &wq_spec, &cq_spec, &rxq->rxobj); @@ -3894,6 +3897,40 @@ int mana_detach(struct net_device *ndev, bool from_close) return 0; } +/* Match the interrupt moderation settings to the PF capability, which is + * queried again when the device resumes from a reset or suspend. Must be + * called before the queues are created. + */ +static void mana_init_intr_modr(struct mana_port_context *apc) +{ + struct gdma_context *gc = apc->ac->gdma_dev->gdma_context; + + if (!(gc->pf_cap_flags1 & + GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION)) { + apc->intr_modr_rx_usec = 0; + apc->intr_modr_rx_comp = 0; + apc->intr_modr_tx_usec = 0; + apc->intr_modr_tx_comp = 0; + apc->rx_dim_enabled = false; + apc->tx_dim_enabled = false; + return; + } + + /* Keep the current settings, unless they were never initialized + * because the port was probed without the capability. + */ + if (apc->intr_modr_rx_usec && apc->intr_modr_rx_comp && + apc->intr_modr_tx_usec && apc->intr_modr_tx_comp) + return; + + apc->intr_modr_rx_usec = MANA_INTR_MODR_USEC_DEF; + apc->intr_modr_rx_comp = MANA_INTR_MODR_COMP_DEF; + apc->intr_modr_tx_usec = MANA_INTR_MODR_USEC_DEF; + apc->intr_modr_tx_comp = MANA_INTR_MODR_COMP_DEF; + apc->rx_dim_enabled = MANA_ADAPTIVE_RX_DEF; + apc->tx_dim_enabled = MANA_ADAPTIVE_TX_DEF; +} + static int mana_probe_port(struct mana_context *ac, int port_idx, struct net_device **ndev_storage) { @@ -3924,15 +3961,7 @@ static int mana_probe_port(struct mana_context *ac, int port_idx, apc->cqe_coalescing_enable = 0; apc->cqe8_coalescing_enable = 0; - /* Initialize interrupt moderation settings if supported by HW */ - if (gc->pf_cap_flags1 & GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION) { - apc->intr_modr_rx_usec = MANA_INTR_MODR_USEC_DEF; - apc->intr_modr_rx_comp = MANA_INTR_MODR_COMP_DEF; - apc->intr_modr_tx_usec = MANA_INTR_MODR_USEC_DEF; - apc->intr_modr_tx_comp = MANA_INTR_MODR_COMP_DEF; - apc->rx_dim_enabled = MANA_ADAPTIVE_RX_DEF; - apc->tx_dim_enabled = MANA_ADAPTIVE_TX_DEF; - } + mana_init_intr_modr(apc); mutex_init(&apc->vport_mutex); apc->vport_use_count = 0; @@ -4256,6 +4285,7 @@ int mana_probe(struct gdma_dev *gd, bool resuming) enable_work(&apc->queue_reset_work); netdev_lock(ac->ports[i]); apc->link_cfg_error = 1; + mana_init_intr_modr(apc); netdev_unlock(ac->ports[i]); err = mana_attach(ac->ports[i]); rtnl_unlock(); diff --git a/drivers/net/ethernet/microsoft/mana/mana_ethtool.c b/drivers/net/ethernet/microsoft/mana/mana_ethtool.c index 4068e08acb1667..96aabf7a8f08b0 100644 --- a/drivers/net/ethernet/microsoft/mana/mana_ethtool.c +++ b/drivers/net/ethernet/microsoft/mana/mana_ethtool.c @@ -505,9 +505,12 @@ static int mana_set_coalesce(struct net_device *ndev, bool dim_changed = false; struct gdma_context *gc; u32 max_cqe_frames; + bool modr_sup; int err; gc = apc->ac->gdma_dev->gdma_context; + modr_sup = gc->pf_cap_flags1 & + GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION; max_cqe_frames = gc->cqe8_coalescing_sup ? MANA_CQE_COAL_PKTS_8 : MANA_RXCOMP_OOB_NUM_PPI; @@ -517,7 +520,7 @@ static int mana_set_coalesce(struct net_device *ndev, if ((ec->use_adaptive_rx_coalesce || ec->use_adaptive_tx_coalesce || ec->rx_coalesce_usecs || ec->tx_coalesce_usecs || ec->rx_max_coalesced_frames || ec->tx_max_coalesced_frames) && - !(gc->pf_cap_flags1 & GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION)) { + !modr_sup) { NL_SET_ERR_MSG(extack, "Interrupt Moderation is not supported by HW"); return -EOPNOTSUPP; @@ -534,18 +537,27 @@ static int mana_set_coalesce(struct net_device *ndev, return -EINVAL; } - if (ec->rx_coalesce_usecs > MANA_INTR_MODR_USEC_MAX || - ec->tx_coalesce_usecs > MANA_INTR_MODR_USEC_MAX) { + /* Without the HW capability, only zero values pass the check above */ + if (modr_sup && + (ec->rx_coalesce_usecs < MANA_INTR_MODR_USEC_MIN || + ec->tx_coalesce_usecs < MANA_INTR_MODR_USEC_MIN || + ec->rx_coalesce_usecs > MANA_INTR_MODR_USEC_MAX || + ec->tx_coalesce_usecs > MANA_INTR_MODR_USEC_MAX)) { NL_SET_ERR_MSG_FMT(extack, - "coalesce usecs must be <= %lu", + "coalesce usecs must be between %d and %lu", + MANA_INTR_MODR_USEC_MIN, MANA_INTR_MODR_USEC_MAX); return -EINVAL; } - if (ec->rx_max_coalesced_frames > MANA_INTR_MODR_COMP_MAX || - ec->tx_max_coalesced_frames > MANA_INTR_MODR_COMP_MAX) { + if (modr_sup && + (ec->rx_max_coalesced_frames < MANA_INTR_MODR_COMP_MIN || + ec->tx_max_coalesced_frames < MANA_INTR_MODR_COMP_MIN || + ec->rx_max_coalesced_frames > MANA_INTR_MODR_COMP_MAX || + ec->tx_max_coalesced_frames > MANA_INTR_MODR_COMP_MAX)) { NL_SET_ERR_MSG_FMT(extack, - "coalesce frames must be <= %lu", + "coalesce frames must be between %d and %lu", + MANA_INTR_MODR_COMP_MIN, MANA_INTR_MODR_COMP_MAX); return -EINVAL; } diff --git a/include/net/mana/gdma.h b/include/net/mana/gdma.h index 29d152e185967e..6191ddddc27f9a 100644 --- a/include/net/mana/gdma.h +++ b/include/net/mana/gdma.h @@ -776,6 +776,9 @@ enum { /* Driver supports handling throttled EQEs */ #define GDMA_DRV_CAP_FLAG_1_THROTTLED_EVENT_QUEUE BIT_ULL(32) +/* Enforce min 1 usec, 1 frames for Interrupt Moderation */ +#define GDMA_DRV_CAP_FLAG_1_SET_MIN_INTR_MOD_VALUE BIT_ULL(33) + /* Capabilities in the PCI-only group below rely on dynamic MSI-X allocation * and on the servicing and reset paths reached through * mana_schedule_serv_work(). Transports that provide neither leave @@ -801,7 +804,8 @@ enum { GDMA_DRV_CAP_FLAG_1_EQ_MSI_UNSHARE_MULTI_VPORT | \ GDMA_DRV_CAP_FLAG_1_DYN_INTERRUPT_MODERATION | \ GDMA_DRV_CAP_FLAG_1_NON_CONTIGUOUS_BUFFERS | \ - GDMA_DRV_CAP_FLAG_1_THROTTLED_EVENT_QUEUE) + GDMA_DRV_CAP_FLAG_1_THROTTLED_EVENT_QUEUE | \ + GDMA_DRV_CAP_FLAG_1_SET_MIN_INTR_MOD_VALUE) #define GDMA_DRV_CAP_FLAGS2 0 diff --git a/include/net/mana/mana.h b/include/net/mana/mana.h index 218d540bc99404..84afc4199e8768 100644 --- a/include/net/mana/mana.h +++ b/include/net/mana/mana.h @@ -74,9 +74,12 @@ enum mana_priv_flag_bits { /* 8-pkt mode packs up to 2 packets per PPI entry */ #define MANA_CQE_COAL_PKTS_8 8 -/* Default/max interrupt moderation settings */ -#define MANA_INTR_MODR_USEC_DEF 0 -#define MANA_INTR_MODR_COMP_DEF 0 +/* Default/min interrupt moderation settings */ +#define MANA_INTR_MODR_USEC_DEF 1 +#define MANA_INTR_MODR_COMP_DEF 1 + +#define MANA_INTR_MODR_USEC_MIN 1 +#define MANA_INTR_MODR_COMP_MIN 1 #define MANA_ADAPTIVE_RX_DEF true #define MANA_ADAPTIVE_TX_DEF true From 7411fb1929075884648e9db0b9ec7e424c095185 Mon Sep 17 00:00:00 2001 From: Thaison Phan Date: Wed, 18 Nov 2026 21:09:32 +0000 Subject: [PATCH 1112/2102] tcp: initialize ir_rmt_addr and ir_loc_addr in cookie_v6_check() Commit a3a128f611a9 ("inet: consolidate inet_csk_clone_lock()") moved the LOOPBACK4_IPV6 initialization for passive IPv6 TCP sockets from tcp_v6_syn_recv_sock() to tcp_v6_init_req(). IPv6 SYN cookie connections allocate a fresh request_sock without __GFP_ZERO and call tcp_v6_syn_recv_sock() without tcp_v6_init_req(), leaving ireq->ir_rmt_addr and ireq->ir_loc_addr uninitialized in cookie_v6_check(). inet_csk_clone_lock() then copies uninitialized slab bytes into sk_daddr, sk_rcv_saddr, and inet_saddr, exposing them to tracepoints and bpf_sock and causing inet_daddr != LOOPBACK4_IPV6 checks (such as IP_OPTIONS in do_ip_setsockopt()) to misclassify native IPv6 child sockets as IPv4-mapped. This was originally noticed via an out-of-tree socket hook observing inet_sk(sk)->inet_saddr != LOOPBACK4_IPV6 on KASAN test runs. KASAN enables SLUB_RCU_DEBUG by default, introducing an RCU grace period that prevents cookie_v6_check() from reusing the warm request_sock initialized during the initial SYN. Upstream, with tcp_syncookies=2, SLUB_RCU_DEBUG=y, and slub_debug=P, sock:inet_sock_set_state shows slab poison instead of 127.0.0.6: ... sock:inet_sock_set_state: family=AF_INET6 protocol=IPPROTO_TCP \ sport=59839 dport=41050 \ saddr=90.90.90.90 daddr=90.90.90.90 \ saddrv6=::1 daddrv6=::1 \ oldstate=TCP_LISTEN newstate=TCP_SYN_RECV Initialize ireq->ir_rmt_addr and ireq->ir_loc_addr to LOOPBACK4_IPV6 in cookie_v6_check() to match tcp_v6_init_req(). Tested against a QEMU reproducer checking inet_sock_set_state and IP_OPTIONS, as well as the packetdrill syncookie selftests. Fixes: a3a128f611a9 ("inet: consolidate inet_csk_clone_lock()") Signed-off-by: Thaison Phan Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261118210933.2477423-2-thaisonphan@google.com Signed-off-by: Jakub Kicinski --- net/ipv6/syncookies.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/net/ipv6/syncookies.c b/net/ipv6/syncookies.c index b581cb1ee2e8a9..b33011b71fff66 100644 --- a/net/ipv6/syncookies.c +++ b/net/ipv6/syncookies.c @@ -17,6 +17,7 @@ #include #include #include +#include #define COOKIEBITS 24 /* Upper bits store count */ #define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1) @@ -205,6 +206,8 @@ struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; + ireq->ir_rmt_addr = LOOPBACK4_IPV6; + ireq->ir_loc_addr = LOOPBACK4_IPV6; if (security_inet_conn_request(sk, skb, req)) { SKB_DR_SET(reason, SECURITY_HOOK); From ce28b1a4d137842e428a578269c35d6c84109438 Mon Sep 17 00:00:00 2001 From: Thaison Phan Date: Wed, 18 Nov 2026 21:09:33 +0000 Subject: [PATCH 1113/2102] tcp: accecn: initialize AccECN fields in syncookie path cookie_tcp_reqsk_alloc() and bpf_sk_assign_tcp_reqsk() allocate struct request_sock without __GFP_ZERO, leaving saw_accecn_opt, accecn_fail_mode, syn_ect_rcv, and syn_ect_snt uninitialized. When accecn_ok is negotiated in cookie_{v4,v6}_check(), tcp_ecn_openreq_child() reads all four fields to initialize the child socket's AccECN state. In addition, because the temporary request_sock used to send a cookie SYN-ACK is immediately freed, treq->syn_ect_snt is lost. For AccECN connections where the listener marks ECT on the SYN-ACK, leaving syn_ect_snt as 0 causes tcp_accecn_third_ack() to see a mismatch between the expected Not-ECT and the peer's reflected ECT in the ACE field, erroneously flagging TCP_ACCECN_ACE_FAIL_RECV in accecn_fail_mode. Refer to Table 4 of RFC 9768 for more details. Initialize the AccECN fields in cookie_tcp_reqsk_init() to match tcp_openreq_init(). For kernel-generated cookies (!req->syncookie), set syn_ect_snt from the listener's TOS/tclass in cookie_{v4,v6}_check() to match tcp_{v4,v6}_send_synack(); for BPF custom syncookies (req->syncookie), leave syn_ect_snt at 0 (Not-ECT) since the SYN-ACK was built by the BPF program rather than the kernel and bpf_tcp_req_attrs does not report the SYN-ACK ECN codepoint. Found by AI-assisted code inspection comparing tcp_openreq_init() and cookie_tcp_reqsk_init() while investigating the cookie_v6_check() LOOPBACK4_IPV6 bug. Reproduced in a QEMU VM with tcp_syncookies=2, tcp_ecn=3, SLUB_RCU_DEBUG=y, and slub_debug=P, observing bogus tcpi_accecn_fail_mode and tcpi_accecn_opt_seen values in TCP_INFO on the accepted child socket (and tcpi_accecn_fail_mode=0x2 on ECT(0) listeners), and tested with packetdrill AccECN and syncookie selftests. Fixes: 3cae34274c79 ("tcp: accecn: AccECN negotiation") Fixes: b40671b5ee58 ("tcp: accecn: AccECN option failure handling") Signed-off-by: Thaison Phan Reviewed-by: Matthieu Baerts (NGI0) Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261118210933.2477423-3-thaisonphan@google.com Signed-off-by: Jakub Kicinski --- net/ipv4/syncookies.c | 7 +++++++ net/ipv6/syncookies.c | 3 +++ 2 files changed, 10 insertions(+) diff --git a/net/ipv4/syncookies.c b/net/ipv4/syncookies.c index 4e0ff3b820627e..89169c82431c12 100644 --- a/net/ipv4/syncookies.c +++ b/net/ipv4/syncookies.c @@ -290,6 +290,10 @@ static int cookie_tcp_reqsk_init(struct sock *sk, struct sk_buff *skb, */ treq->txhash = treq->snt_isn; treq->syn_tos = TCP_SKB_CB(skb)->ip_dsfield; + treq->saw_accecn_opt = TCP_ACCECN_OPT_NOT_SEEN; + treq->accecn_fail_mode = 0; + treq->syn_ect_rcv = 0; + treq->syn_ect_snt = 0; #if IS_ENABLED(CONFIG_MPTCP) treq->is_mptcp = sk_is_mptcp(sk); @@ -502,6 +506,9 @@ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb) ireq->rcv_wscale = rcv_wscale; ireq->ecn_ok &= cookie_ecn_ok(net, &rt->dst); treq->accecn_ok = ireq->ecn_ok && cookie_accecn_ok(th); + /* SYN-ACK was not sent by the kernel if req->syncookie is set. */ + if (!req->syncookie) + treq->syn_ect_snt = READ_ONCE(inet_sk(sk)->tos) & INET_ECN_MASK; ret = tcp_get_cookie_sock(sk, skb, req, &rt->dst); /* ip_queue_xmit() depends on our flow being setup diff --git a/net/ipv6/syncookies.c b/net/ipv6/syncookies.c index b33011b71fff66..e8d45a627ca266 100644 --- a/net/ipv6/syncookies.c +++ b/net/ipv6/syncookies.c @@ -276,6 +276,9 @@ struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) ireq->rcv_wscale = rcv_wscale; ireq->ecn_ok &= cookie_ecn_ok(net, dst); tcp_rsk(req)->accecn_ok = ireq->ecn_ok && cookie_accecn_ok(th); + /* SYN-ACK was not sent by the kernel if req->syncookie is set. */ + if (!req->syncookie) + tcp_rsk(req)->syn_ect_snt = READ_ONCE(np->tclass) & INET_ECN_MASK; ret = tcp_get_cookie_sock(sk, skb, req, dst); if (!ret) { From 6b745a4ae88a38871421eef2fd995cd308abce0a Mon Sep 17 00:00:00 2001 From: yong liu Date: Wed, 11 Nov 2026 11:05:43 +0800 Subject: [PATCH 1114/2102] scsi: target: core: Disable protection processing for zero-block transfers A READ(10) with its TRANSFER LENGTH field set to zero on a PI-enabled LUN can select TARGET_PROT_DIN_STRIP while leaving cmd->prot_length at zero. transport_generic_new_cmd() then allocates an empty protection scatterlist, causing a target-side Oops, which can also lead to use-after-free during subsequent iSCSI connection cleanup. A logged-in iSCSI initiator can trigger this on a FILEIO LUN with protection information enabled. After validating PROTECT, reset the protection operation, type and checks for zero-block commands in sbc_check_prot(). This avoids the empty allocation and prevents backends and fabrics from selecting PI processing without a protection payload. Preserve the existing data-length adjustment for commands carrying PI over the wire. The issue was discovered and fixed by Qihoo 360's Tulongfeng multi-agent system. Fixes: 5835812f13e5 ("target: ensure se_cmd->t_prot_sg is allocated when required") Cc: stable@vger.kernel.org Signed-off-by: yong liu Link: https://patch.msgid.link/20261111030544.1216434-1-pkfxxxing@gmail.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/target/target_core_sbc.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/target/target_core_sbc.c b/drivers/target/target_core_sbc.c index 21f5cb86d70c00..560e62cef7dd3a 100644 --- a/drivers/target/target_core_sbc.c +++ b/drivers/target/target_core_sbc.c @@ -721,6 +721,12 @@ sbc_check_prot(struct se_device *dev, struct se_cmd *cmd, unsigned char protect, if (sbc_set_prot_op_checks(protect, fabric_prot, pi_prot_type, is_write, cmd)) return TCM_INVALID_CDB_FIELD; + if (!sectors) { + cmd->prot_op = TARGET_PROT_NORMAL; + cmd->prot_checks = 0; + pi_prot_type = TARGET_DIF_TYPE0_PROT; + } + cmd->prot_type = pi_prot_type; cmd->prot_length = dev->prot_length * sectors; From fb8fd1da808feef6af8686986fedcfe45c693dc8 Mon Sep 17 00:00:00 2001 From: Ciro Iriarte Date: Mon, 9 Nov 2026 11:31:01 -0300 Subject: [PATCH 1115/2102] scsi: target: core: Compare all six ISID bytes when identifying a nexus lio_sess_get_initiator_sid() reports the ISID as twelve hex digits, and iSCSI TransportIDs carry the same digits. __transport_register_session(), __core_scsi3_do_alloc_registration() and core_scsi3_alloc_aptpl_registration() turn that text into sess_bin_isid and pr_reg_bin_isid with get_unaligned_be64(), which takes the first eight characters, i.e. the first four ISID bytes. open-iscsi ISIDs start with 00023d00 and differ only in the qualifier in the last two bytes, so every session of one initiator gets the same binary ISID. target_scsi2_reservation_check() and target_scsi3_pr_reservation_check() then treat any session of the reservation holder's initiator as the holder: - after RESERVE(6) on one session, another session of the same initiator can still write; - with a Write Exclusive persistent reservation, another session that is not registered, or registered but not the holder, can still write. Reproduced with two open-iscsi sessions (ifaces default and if2) to a ramdisk LUN: on v6.12.113 every TEST UNIT READY, READ(10) and WRITE(10) the test sent from the second session completed with GOOD, under RESERVE(6) and under each persistent reservation type, whether or not that session was registered. Convert all six bytes. Text that is not exactly twelve hex digits keeps the old conversion of its first eight characters, now copied into a zeroed buffer so that a shorter string, such as an initiator_sid written to res_aptpl_metadata, is not read past its end. An all-zero ISID now converts to 0, which target_scsi2_reservation_reserve() took to mean "no ISID". Set DRF_SPC2_RESERVATIONS_WITH_ISID when the fabric reports ISIDs instead. Also update the TransportID parser comment that referred to the get_unaligned_be64() read. With distinct ISIDs, target_scsi3_pr_reservation_check() now sets isid_mismatch for the holder initiator's other sessions, and core_scsi3_pr_seq_non_holder() treated every such session as unregistered: DEF_PR_REG_ACTIVE is kept per se_dev_entry, which all sessions of the initiator share, so it cannot tell them apart. A session that registered its own key would then get RESERVATION CONFLICT for writes under a Registrants Only or All Registrants reservation, and for PREEMPT, CLEAR and RELEASE. Look up that session's own registration with core_scsi3_locate_pr_reg() instead. With this patch, TEST UNIT READY and WRITE(10) from the second session under RESERVE(6) return RESERVATION CONFLICT. Under Write Exclusive, WRITE(10) from the second session conflicts whether or not it is registered, and READ(10) is allowed. Under the Registrants Only and All Registrants types, WRITE(10) from the second session conflicts until it registers, as does READ(10) under the Exclusive Access types; once registered it has access and can PREEMPT the holder. Initiators that relied on the old behaviour, reserving through one session and writing through another without registering it, will now see RESERVATION CONFLICT, as SPC requires. Fixes: c66ac9db8d4a ("[SCSI] target: Add LIO target core v4.0.0-rc6") Cc: stable@vger.kernel.org Signed-off-by: Ciro Iriarte Link: https://patch.msgid.link/8b1ac7d9-b0e4-42ac-b8a2-c4c70cccdddc@gmail.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/target/target_core_fabric_lib.c | 9 ++--- drivers/target/target_core_pr.c | 46 ++++++++++++++++++++++--- drivers/target/target_core_pr.h | 1 + drivers/target/target_core_transport.c | 2 +- 4 files changed, 49 insertions(+), 9 deletions(-) diff --git a/drivers/target/target_core_fabric_lib.c b/drivers/target/target_core_fabric_lib.c index ad024009df56bb..ccfeba64518c28 100644 --- a/drivers/target/target_core_fabric_lib.c +++ b/drivers/target/target_core_fabric_lib.c @@ -372,10 +372,11 @@ static bool iscsi_parse_pr_out_transport_id( return false; } /* - * The registration code reads the ISID as a C string, - * and its first 8 bytes with get_unaligned_be64(), so - * require 8 bytes after the separator and a NUL inside - * the rest of the descriptor. + * The registration code reads the ISID as a C string, so + * require a NUL inside the rest of the descriptor. Keep the + * existing minimum of 8 bytes after the separator: a valid + * ISID is twelve hex digits, and target_isid_to_bin() falls + * back to the first eight characters of anything else. */ if (buf + tid_len - p < 8 || !memchr(p, '\0', buf + tid_len - p)) { pr_err("Incomplete or unterminated ISID in iSCSI Initiator port TransportID\n"); diff --git a/drivers/target/target_core_pr.c b/drivers/target/target_core_pr.c index ca1a2802aa228c..0f2ff9d42150ba 100644 --- a/drivers/target/target_core_pr.c +++ b/drivers/target/target_core_pr.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -30,6 +31,28 @@ #include "target_core_pr.h" #include "target_core_ua.h" +/* + * lio_sess_get_initiator_sid() prints the six ISID bytes as twelve hex + * digits, and iSCSI TransportIDs carry the same digits. Convert all six + * bytes: reading the first eight digits as a big-endian u64 keeps only the + * first four ISID bytes, so two sessions of one initiator that differ only + * in the qualifier, the usual case, would compare equal. Text in any other + * format keeps the old conversion of its first eight characters, without + * reading past the end of a shorter string. + */ +u64 target_isid_to_bin(const char *isid) +{ + u8 bin[6]; + char raw[8] = {}; + + if (strnlen(isid, 2 * sizeof(bin) + 1) == 2 * sizeof(bin) && + !hex2bin(bin, isid, sizeof(bin))) + return get_unaligned_be48(bin); + + memcpy(raw, isid, strnlen(isid, sizeof(raw))); + return get_unaligned_be64(raw); +} + /* * Used for Specify Initiator Ports Capable Bit (SPEC_I_PT) */ @@ -285,7 +308,11 @@ target_scsi2_reservation_reserve(struct se_cmd *cmd) dev->reservation_holder = sess; dev->dev_reservation_flags |= DRF_SPC2_RESERVATIONS; - if (sess->sess_bin_isid != 0) { + /* + * An all-zero ISID converts to 0, so test whether the fabric has + * ISIDs rather than the value. + */ + if (tpg->se_tpg_tfo->sess_get_initiator_sid) { dev->dev_res_bin_isid = sess->sess_bin_isid; dev->dev_reservation_flags |= DRF_SPC2_RESERVATIONS_WITH_ISID; } @@ -323,7 +350,18 @@ static int core_scsi3_pr_seq_non_holder(struct se_cmd *cmd, u32 pr_reg_type, * RESERVATION CONFLICT on some CDBs */ if (isid_mismatch) { - registered_nexus = 0; + struct t10_pr_registration *pr_reg; + + /* + * Another I_T nexus of the holder's initiator. DEF_PR_REG_ACTIVE + * is shared by all of its sessions, so look for a registration + * made through this one. + */ + pr_reg = core_scsi3_locate_pr_reg(cmd->se_dev, nacl, se_sess); + if (pr_reg) { + registered_nexus = 1; + core_scsi3_put_pr_reg(pr_reg); + } } else { struct se_dev_entry *se_deve; @@ -674,7 +712,7 @@ static struct t10_pr_registration *__core_scsi3_do_alloc_registration( * save it to the registration now. */ if (isid != NULL) { - pr_reg->pr_reg_bin_isid = get_unaligned_be64(isid); + pr_reg->pr_reg_bin_isid = target_isid_to_bin(isid); snprintf(pr_reg->pr_reg_isid, PR_REG_ISID_LEN, "%s", isid); pr_reg->isid_present_at_reg = 1; } @@ -866,7 +904,7 @@ int core_scsi3_alloc_aptpl_registration( * SCSI Initiator Port, restore it now. */ if (isid != NULL) { - pr_reg->pr_reg_bin_isid = get_unaligned_be64(isid); + pr_reg->pr_reg_bin_isid = target_isid_to_bin(isid); snprintf(pr_reg->pr_reg_isid, PR_REG_ISID_LEN, "%s", isid); pr_reg->isid_present_at_reg = 1; } diff --git a/drivers/target/target_core_pr.h b/drivers/target/target_core_pr.h index b793c99637ab91..4debfe4be4d698 100644 --- a/drivers/target/target_core_pr.h +++ b/drivers/target/target_core_pr.h @@ -72,6 +72,7 @@ extern void core_scsi3_free_pr_reg_from_nacl(struct se_device *, struct se_node_acl *); extern void core_scsi3_free_all_registrations(struct se_device *); extern unsigned char *core_scsi3_pr_dump_type(int); +u64 target_isid_to_bin(const char *isid); extern sense_reason_t target_scsi3_emulate_pr_in(struct se_cmd *); extern sense_reason_t target_scsi3_emulate_pr_out(struct se_cmd *); diff --git a/drivers/target/target_core_transport.c b/drivers/target/target_core_transport.c index 927861c30afc44..4629c9343bb6c3 100644 --- a/drivers/target/target_core_transport.c +++ b/drivers/target/target_core_transport.c @@ -419,7 +419,7 @@ void __transport_register_session( memset(&buf[0], 0, PR_REG_ISID_LEN); se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess, &buf[0], PR_REG_ISID_LEN); - se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]); + se_sess->sess_bin_isid = target_isid_to_bin(buf); } spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags); From 068d82afd070beb8ea32c8ee64d685af7d3f36e2 Mon Sep 17 00:00:00 2001 From: WeitaoWang-oc Date: Sat, 17 Oct 2026 02:10:16 +0800 Subject: [PATCH 1116/2102] x86/apic/msi: Fix MSI interrupt affinity configuration The two step update sequence in msi_set_affinity() is required for MSI interrupts which cannot be migrated atomically, i.e. devices which do not provide MSI masking. The MSI message update writes address and data registers separately, so such a device can raise an interrupt in between, which results in a message built from half updated state: a stray interrupt on a stale vector and a possibly lost device interrupt. The update sequence is selected by a per interrupt quirk flag, which is set for interrupts which cannot use reservation mode. Reservation mode is only enabled for maskable interrupts, i.e. devices which provide MSI-X or mask support, so the quirk flag is the inverse of the reservation mode bit. The removal of the quirk flag replaced the flag check with a reservation mode check, but dropped the negation of the removed condition: - if (!irqd_msi_nomask_quirk(irqd) || ...) + if (!irqd_can_reserve(irqd) || ...) As the quirk flag is the inverse of the reservation mode bit, the replacement inverted the condition and selects the wrong update path for every interrupt: non-maskable interrupts take the direct update path again, which reopens the race, while maskable interrupts needlessly go through the two step update. Restore the original condition so that the direct update path is selected when reservation mode is enabled, which also matches the comment above the check: direct update is possible when the MSI is maskable, which is the case when the reservation mode bit is set. [ bp: Massage commit message. ] Fixes: b56ebe7c896d ("x86/apic/msi: Fix misconfigured non-maskable MSI quirk") Signed-off-by: Weitao Wang Signed-off-by: Borislav Petkov (AMD) Reviewed-by: Koichiro Den Acked-by: Thomas Gleixner Cc: stable@vger.kernel.org # v6.1+ Link: https://patch.msgid.link/20261016181016.3850-1-WeitaoWang-oc@zhaoxin.com --- arch/x86/kernel/apic/msi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/x86/kernel/apic/msi.c b/arch/x86/kernel/apic/msi.c index 66bc5d3e79db3f..da5f44a80313f8 100644 --- a/arch/x86/kernel/apic/msi.c +++ b/arch/x86/kernel/apic/msi.c @@ -62,7 +62,7 @@ msi_set_affinity(struct irq_data *irqd, const struct cpumask *mask, bool force) * - The interrupt is not yet started up * - The new destination CPU is the same as the old destination CPU */ - if (!irqd_can_reserve(irqd) || + if (irqd_can_reserve(irqd) || cfg->vector == old_cfg.vector || old_cfg.vector == MANAGED_IRQ_SHUTDOWN_VECTOR || !irqd_is_started(irqd) || From 29b74cf57f432d60da2b79c827f1379125409611 Mon Sep 17 00:00:00 2001 From: Adrian Schlegel Date: Mon, 12 Oct 2026 21:33:05 +0200 Subject: [PATCH 1117/2102] x86/mce: Do not treat cache hierarchy errors as memory errors On Intel and Zhaoxin, mce_is_memory_error() also returns true for cache hierarchy errors. All callers expect it to report memory errors only. The CEC uses it to count corrected DRAM errors. A corrected cache error only names the cache line that was affected, not a faulty DRAM page. With a faulty CPU core, the CEC therefore soft-offlines healthy pages. On an i9-9900K this caused about 500 soft-offline attempts per hour. Report only memory controller errors on Intel and Zhaoxin, as is already done for AMD. Fixes: fa92c5869426 ("x86, mce: Support memory error recovery for both UCNA and Deferred error in machine_check_poll") Signed-off-by: Adrian Schlegel Signed-off-by: Borislav Petkov (AMD) Reviewed-by: Qiuxu Zhuo Reviewed-by: Tony Luck Reviewed-by: Yazen Ghannam Reviewed-by: Sohil Mehta Cc: Link: https://patch.msgid.link/20261012193305.38931-1-me@adrianschlegel.com --- arch/x86/kernel/cpu/mce/core.c | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/arch/x86/kernel/cpu/mce/core.c b/arch/x86/kernel/cpu/mce/core.c index 50b1614968be6a..eb0e51ac80fc25 100644 --- a/arch/x86/kernel/cpu/mce/core.c +++ b/arch/x86/kernel/cpu/mce/core.c @@ -540,21 +540,13 @@ bool mce_is_memory_error(struct mce *m) case X86_VENDOR_INTEL: case X86_VENDOR_ZHAOXIN: /* - * Intel SDM Volume 3B - 15.9.2 Compound Error Codes + * Intel SDM Volume 3B "Compound Error Codes". * - * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for - * indicating a memory error. Bit 8 is used for indicating a - * cache hierarchy error. The combination of bit 2 and bit 3 - * is used for indicating a `generic' cache hierarchy error - * But we can't just blindly check the above bits, because if - * bit 11 is set, then it is a bus/interconnect error - and - * either way the above bits just gives more detail on what - * bus/interconnect error happened. Note that bit 12 can be - * ignored, as it's the "filter" bit. + * Memory controller errors have an MCACOD of 000F 0000 1MMM CCCC: + * bit 7 set, bits 8-11 and 13-15 clear. Bit 12 is the "filter" + * bit and is ignored. */ - return (m->status & 0xef80) == BIT(7) || - (m->status & 0xef00) == BIT(8) || - (m->status & 0xeffc) == 0xc; + return (m->status & 0xef80) == BIT(7); default: return false; From e721359e5ad0292d93bb9779c4b09fbeb681c266 Mon Sep 17 00:00:00 2001 From: Haoxiang Li Date: Wed, 18 Nov 2026 18:20:12 +0800 Subject: [PATCH 1118/2102] KVM: PPC: Book3S HV: Clean up on uvmem initialization failure When kvmppc_uvmem_init() fails, kvmppc_book3s_init_hv() returns directly, bypassing the existing error path. Jump to the existing error path to clean up before returning the error. Fixes: 175be7e5800e ("KVM: PPC: Book3S HV: Free allocated memory if module init fails") Signed-off-by: Haoxiang Li Reviewed-by: Fabiano Rosas Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261118102012.2252221-1-haoxiang_li2024@163.com --- arch/powerpc/kvm/book3s_hv.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/powerpc/kvm/book3s_hv.c b/arch/powerpc/kvm/book3s_hv.c index bafe9546087b28..4f45b1b3356159 100644 --- a/arch/powerpc/kvm/book3s_hv.c +++ b/arch/powerpc/kvm/book3s_hv.c @@ -6745,7 +6745,7 @@ static int kvmppc_book3s_init_hv(void) r = kvmppc_uvmem_init(); if (r < 0) { pr_err("KVM-HV: kvmppc_uvmem_init failed %d\n", r); - return r; + goto err; } #if defined(CONFIG_KVM_XICS) From 2672bdcc7857073722c4772831a24b14832ee88a Mon Sep 17 00:00:00 2001 From: Shrikanth Hegde Date: Wed, 18 Nov 2026 10:44:17 +0530 Subject: [PATCH 1119/2102] PPC32: Fix hard_irq_disable to follow tracing and lockdep state On PPC32, the code for hard_irq_disable has diverged and it doesn't do lockdep/tracing anymore, leading to use of both local_irq_disable and hard_irq_disable on PPC32 to overcome those. That is un-necessary, instead simply calling local_irq_disable is enough. It disables EE bit and does lockdep tracking. Subsequent patch uses this API in KVM code to avoid the warnings. Wider use of it is possible, but it will be taken subsequently. Cc: stable@vger.kernel.org # v7.2+ Suggested-by: Ritesh Harjani (IBM) Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Shrikanth Hegde Reviewed-by: Mukesh Kumar Chaurasiya (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261118051419.783878-2-sshegde@linux.ibm.com --- arch/powerpc/include/asm/hw_irq.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/powerpc/include/asm/hw_irq.h b/arch/powerpc/include/asm/hw_irq.h index b7eee6385ae5c6..ddb850e62abd69 100644 --- a/arch/powerpc/include/asm/hw_irq.h +++ b/arch/powerpc/include/asm/hw_irq.h @@ -464,7 +464,7 @@ static inline bool arch_irqs_disabled(void) return arch_irqs_disabled_flags(arch_local_save_flags()); } -#define hard_irq_disable() arch_local_irq_disable() +#define hard_irq_disable() local_irq_disable() static inline bool regs_irqs_disabled(struct pt_regs *regs) { From cf2e6ef0a39e0682d22292f1b9e9cd865482e86d Mon Sep 17 00:00:00 2001 From: Shrikanth Hegde Date: Wed, 18 Nov 2026 10:44:18 +0530 Subject: [PATCH 1120/2102] KVM: PPC: BookE: Load FP and Altivec before enabling the interrupts Christian reported that booting preemptible kernel on FSL Cyrus+ board causes boot hang. The logs pointed that system was busy in printing below warning. WARNING: at .enable_kernel_fp+0x30/0x78, CPU#3: qemu-system-ppc/4884 Modules linked in: CPU: 3 UID: 1000 PID: 4884 Comm: qemu-system-ppc Not tainted 7.3.0-rc1-powerpc64-smp-preempt #1 PREEMPT NIP [c000000000003338] .enable_kernel_fp+0x30/0x78 LR [c00000000005de84] .kvmppc_load_guest_fp+0x30/0x80 Call Trace: [c000000085ca7700] [c00000000005de84] .kvmppc_load_guest_fp+0x30/0x80 [c000000085ca7780] [c00000000005f2a0] .kvmppc_handle_exit+0x5bc/0x5cc [c000000085ca7830] [c00000000006204c] .kvmppc_resume_host+0xb8/0x10c Which is... void enable_kernel_fp(void) { unsigned long cpumsr; WARN_ON(preemptible()); And... Though irq's are hard disabled after kvmppc_prepare_to_enter, but kvmppc_fix_ee_before_entry enables the softmask's IRQ state. That causes the irqs_disabled to return false. Hence leading to the warnings. Fix it by re-ordering the code to load the FP and Altivec before enabling the softmask IRQ state. Suggested-by: Narayana Murty N Fixes: 3efc7da61f6c ("KVM: PPC: Book3E: Increase FPU laziness") Reported-by: Christian Zigotzky Closes: https://lore.kernel.org/all/33342fbf-eb7b-bde6-2c8c-254fe8bfb993@xenosoft.de/ Tested-by: Christian Zigotzky Reviewed-by: Narayana Murty N Reviewed-by: Ritesh Harjani (IBM) Reviewed-by: Mukesh Kumar Chaurasiya (IBM) Signed-off-by: Shrikanth Hegde Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261118051419.783878-3-sshegde@linux.ibm.com --- arch/powerpc/kvm/booke.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/arch/powerpc/kvm/booke.c b/arch/powerpc/kvm/booke.c index 13ad4cf5fa71f8..aed7b476b7ebe1 100644 --- a/arch/powerpc/kvm/booke.c +++ b/arch/powerpc/kvm/booke.c @@ -1404,10 +1404,9 @@ int kvmppc_handle_exit(struct kvm_vcpu *vcpu, unsigned int exit_nr) if (s <= 0) r = (s << 2) | RESUME_HOST | (r & RESUME_FLAG_NV); else { - /* interrupts now hard-disabled */ - kvmppc_fix_ee_before_entry(); kvmppc_load_guest_fp(vcpu); kvmppc_load_guest_altivec(vcpu); + kvmppc_fix_ee_before_entry(); } } From d0160f6470d1b8a4ce25d98bb8d1b0495a922d4f Mon Sep 17 00:00:00 2001 From: Shrikanth Hegde Date: Wed, 18 Nov 2026 10:44:19 +0530 Subject: [PATCH 1121/2102] KVM: PPC: Hard disable interrupts before guest entry After applying preempt disable patch, i.e PATCH 2/3, Christian reported a subsequent warning stopping his board to boot properly. WARNING: at .kvmppc_fix_ee_before_entry+0x10/0x28, CPU#0: qemu-system-ppc/4667 CPU: 0 UID: 1000 PID: 4667 Comm: qemu-system-ppc Tainted: G W 7.3.0-rc4-2-powerpc64-smp #1 PREEMPT Tainted: [W]=WARN Hardware name: varisys,CYRUS5040 e5500 0x80240012 CoreNet Generic NIP [c00000000005dc3c] .kvmppc_fix_ee_before_entry+0x10/0x28 LR [c00000000005f298] .kvmppc_handle_exit+0x5b4/0x5e8 Call Trace: [c000000086587780] [c00000000005ee10] .kvmppc_handle_exit+0x12c/0x5e8 (unreliable) [c000000086587830] [c000000000062068] .kvmppc_resume_host+0xb8/0x10c It triggers below warning... static inline void kvmppc_fix_ee_before_entry(void) { trace_hardirqs_on(); /* * To avoid races, the caller must have gone directly from having * interrupts fully-enabled to hard-disabled. */ WARN_ON(local_paca->irq_happened != PACA_IRQ_HARD_DIS); This happens since kvmppc_prepare_to_enter does first local_irq_disable followed by hard_irq_disable. This leaves a small window where interrupt may occur and it could set the irq pending bit in PACA. That local_irq_disable was necessary for PPC32 to track the lockdep state etc. On PPC64 hard_irq_disable is good enough. There is no need to do both. With now hard_irq_disable, doing local_irq_disable for PPC32, just calling that is enough. Suggested-by: Ritesh Harjani (IBM) Fixes: 12013e3d4695 ("KVM: powerpc: Use generic xfer to guest work function") Reported-by: Christian Zigotzky Closes: https://lore.kernel.org/all/b8f82519-9ae5-c247-e020-e79c627e57df@xenosoft.de/ Tested-by: Christian Zigotzky Reviewed-by: Mukesh Kumar Chaurasiya (IBM) Reviewed-by: Narayana Murty N Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Shrikanth Hegde Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261118051419.783878-4-sshegde@linux.ibm.com --- arch/powerpc/kvm/booke.c | 1 - arch/powerpc/kvm/powerpc.c | 8 -------- 2 files changed, 9 deletions(-) diff --git a/arch/powerpc/kvm/booke.c b/arch/powerpc/kvm/booke.c index aed7b476b7ebe1..2593f7ae6c0909 100644 --- a/arch/powerpc/kvm/booke.c +++ b/arch/powerpc/kvm/booke.c @@ -722,7 +722,6 @@ int kvmppc_core_prepare_to_enter(struct kvm_vcpu *vcpu) if (vcpu->arch.shared->msr & MSR_WE) { local_irq_enable(); kvm_vcpu_halt(vcpu); - local_irq_disable(); hard_irq_disable(); kvmppc_set_exit_type(vcpu, EMULATED_MTMSRWE_EXITS); diff --git a/arch/powerpc/kvm/powerpc.c b/arch/powerpc/kvm/powerpc.c index 9194cf492d1ca2..f4db7dea57b3c8 100644 --- a/arch/powerpc/kvm/powerpc.c +++ b/arch/powerpc/kvm/powerpc.c @@ -81,12 +81,6 @@ int kvmppc_prepare_to_enter(struct kvm_vcpu *vcpu) int r; WARN_ON(irqs_disabled()); - /* - * local_irq_disable() first: on 32-bit, hard_irq_disable() alone is a - * raw MSR[EE] clear that bypasses the lockdep/irq-tracing state, and - * the xfer_to_guest_mode helpers assert IRQs are seen as disabled. - */ - local_irq_disable(); hard_irq_disable(); while (true) { @@ -101,7 +95,6 @@ int kvmppc_prepare_to_enter(struct kvm_vcpu *vcpu) */ local_irq_enable(); r = kvm_xfer_to_guest_mode_handle_work(vcpu); - local_irq_disable(); hard_irq_disable(); if (r) { /* @@ -134,7 +127,6 @@ int kvmppc_prepare_to_enter(struct kvm_vcpu *vcpu) local_irq_enable(); trace_kvm_check_requests(vcpu); r = kvmppc_core_check_requests(vcpu); - local_irq_disable(); hard_irq_disable(); if (r > 0) continue; From 9ea01307e6c824eb0b8934d95d52bbacae17887d Mon Sep 17 00:00:00 2001 From: Nathan Chancellor Date: Sun, 15 Nov 2026 14:18:07 -0700 Subject: [PATCH 1122/2102] powerpc/xmon: Avoid unsequenced accesses to tsk in show_task() After a recent improvement in clang to warn on unsequenced accesses to volatile variables [1], an instance appears in show_task(), which can break the build with CONFIG_PPC_WERROR=y / CONFIG_WERROR=y / W=e: arch/powerpc/xmon/xmon.c:3262:3: error: unsequenced accesses to volatile qualified 'tsk' [-Werror,-Wunsequenced] 3261 | printf("%16px %16lx %16px %6d %6d %c %2d %s\n", tsk, | ~~~ 3262 | tsk->thread.ksp, tsk->thread.regs, | ^ Per C11 5.1.2.3.2, accessing a volatile object is a side effect. Per C11 6.5.2, unsequenced side effects on the same scalar object are undefined behavior. Per C11 6.5.2.2.10/12, the evaluation of arguments in a function call is indeterminately sequenced, meaning any side effects in the arguments are unsequenced. tsk was made volatile in commit a2305e3de819 ("powerpc: mark local variables around longjmp as volatile") to ensure its value in show_tasks() was properly restored after returning from a potential longjmp(). Aside from that, the value is not being modified through other means, so rename the volatile parameter and add a local variable named tsk to hold its value throughout show_task(), clearing up the warning. Cc: stable@vger.kernel.org Fixes: a2305e3de819 ("powerpc: mark local variables around longjmp as volatile") Closes: https://github.com/ClangBuiltLinux/linux/issues/2199 Link: https://github.com/llvm/llvm-project/commit/955715460eaf9188c241c74750637fc82dfcc423 [1] Signed-off-by: Nathan Chancellor Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261115-xmon-wunsequenced-v1-1-42ae3fe45bf4@kernel.org --- arch/powerpc/xmon/xmon.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/arch/powerpc/xmon/xmon.c b/arch/powerpc/xmon/xmon.c index cb3a3244ae6ff9..90a8d7a8f42daf 100644 --- a/arch/powerpc/xmon/xmon.c +++ b/arch/powerpc/xmon/xmon.c @@ -3240,8 +3240,9 @@ memzcan(void) printf("%.8lx\n", a - mskip); } -static void show_task(struct task_struct *volatile tsk) +static void show_task(struct task_struct *volatile vol_tsk) { + struct task_struct *tsk = vol_tsk; unsigned int p_state = READ_ONCE(tsk->__state); char state; From b282541b555b9ddc64b85fbe00bbc39522aaa911 Mon Sep 17 00:00:00 2001 From: "Ritesh Harjani (IBM)" Date: Sun, 1 Nov 2026 20:58:06 +0530 Subject: [PATCH 1123/2102] KVM: PPC: Book3S HV: Read EX_DSISR as a 32-bit field on guest exit kvmhv_vcpu_entry_p9() recovers the guest fault state from the paca exception save area with vcpu->arch.fault_dsisr = exsave[EX_DSISR/sizeof(u64)]; but EX_DSISR is not a doubleword. It is a 32-bit field at offset 48 that shares a doubleword with EX_CCR at offset 52 and the exception entry in exceptions-64s.S stores it accordingly. For e.g. stw r10,IAREA+EX_DSISR(r13) This issue was caught when running kvm selftests on big-endian, where this read would land in the high half and the truncation yields EX_CCR instead - KVM acts on the guest's condition register as if it were HDSISR. The result is that every HDSI on a big-endian host is evaluated against a bogus fault status i.e. it fails with below error: KVM: Got radix HV page fault with DSISR=84004840 Let's fix this by reading this field at it's natural width. Fixes: 89d35b239101 ("KVM: PPC: Book3S HV P9: Implement the rest of the P9 path in C") Signed-off-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/4e883269c887f68f4d9d54f2675799df147a5db5.1793546707.git.ritesh.list@gmail.com --- arch/powerpc/kvm/book3s_hv_p9_entry.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/arch/powerpc/kvm/book3s_hv_p9_entry.c b/arch/powerpc/kvm/book3s_hv_p9_entry.c index 34bc0a8a128856..16aa8582b88804 100644 --- a/arch/powerpc/kvm/book3s_hv_p9_entry.c +++ b/arch/powerpc/kvm/book3s_hv_p9_entry.c @@ -529,6 +529,15 @@ unsigned long kvmppc_msr_hard_disable_set_facilities(struct kvm_vcpu *vcpu, unsi } EXPORT_SYMBOL_GPL(kvmppc_msr_hard_disable_set_facilities); +/* + * EX_DSISR is a 32-bit field that shares a doubleword with EX_CCR. + * Small helper for reading it back at its natural width. + */ +static u32 exsave_dsisr(u64 *exsave) +{ + return *(u32 *)((void *)exsave + EX_DSISR); +} + int kvmhv_vcpu_entry_p9(struct kvm_vcpu *vcpu, u64 time_limit, unsigned long lpcr, u64 *tb) { struct p9_host_os_sprs host_os_sprs; @@ -770,7 +779,7 @@ int kvmhv_vcpu_entry_p9(struct kvm_vcpu *vcpu, u64 time_limit, unsigned long lpc if (unlikely(trap == BOOK3S_INTERRUPT_MACHINE_CHECK)) { vcpu->arch.fault_dar = exsave[EX_DAR/sizeof(u64)]; - vcpu->arch.fault_dsisr = exsave[EX_DSISR/sizeof(u64)]; + vcpu->arch.fault_dsisr = exsave_dsisr(exsave); kvmppc_realmode_machine_check(vcpu); } else if (unlikely(trap == BOOK3S_INTERRUPT_HMI)) { @@ -781,7 +790,7 @@ int kvmhv_vcpu_entry_p9(struct kvm_vcpu *vcpu, u64 time_limit, unsigned long lpc } else if (trap == BOOK3S_INTERRUPT_H_DATA_STORAGE) { vcpu->arch.fault_dar = exsave[EX_DAR/sizeof(u64)]; - vcpu->arch.fault_dsisr = exsave[EX_DSISR/sizeof(u64)]; + vcpu->arch.fault_dsisr = exsave_dsisr(exsave); vcpu->arch.fault_gpa = mfspr(SPRN_ASDR); } else if (trap == BOOK3S_INTERRUPT_H_INST_STORAGE) { From 3aa91029dedaa00780f5aa15763e88d31c43eac5 Mon Sep 17 00:00:00 2001 From: "Ritesh Harjani (IBM)" Date: Sun, 1 Nov 2026 20:58:07 +0530 Subject: [PATCH 1124/2102] KVM: PPC: Book3S: Don't call __ffs() on an empty pending_exceptions bitmap This problem was caught when running KVM PPC selftests on big-endian. __ffs() doc clearly says: "Undefined if no bit exists, so code should check against 0 first" This cause KVM to deliever an arbitary interrupt to the guest and was causing guest to hang up while running these selftests. On checking further - GCC was emitting 0 in this case, which caused System Reset in guest while running kvm selftests. Use find_first_bit() instead, which reads the word once and returns the bitmap size when no bit is set, instead of reading *pending twice thereby causing TOCTOU as pointed by Sashiko. Signed-off-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/aa74d5ca5ad53a2fa03a7224126f28899ca9b308.1793546707.git.ritesh.list@gmail.com --- arch/powerpc/kvm/book3s.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/powerpc/kvm/book3s.c b/arch/powerpc/kvm/book3s.c index 2efbe05caed760..5de4b6e86656f4 100644 --- a/arch/powerpc/kvm/book3s.c +++ b/arch/powerpc/kvm/book3s.c @@ -401,7 +401,7 @@ int kvmppc_core_prepare_to_enter(struct kvm_vcpu *vcpu) if (vcpu->arch.pending_exceptions) printk(KERN_EMERG "KVM: Check pending: %lx\n", vcpu->arch.pending_exceptions); #endif - priority = __ffs(*pending); + priority = find_first_bit(pending, BITS_PER_BYTE * sizeof(*pending)); while (priority < BOOK3S_IRQPRIO_MAX) { if (kvmppc_book3s_irqprio_deliver(vcpu, priority) && clear_irqprio(vcpu, priority)) { From d9801c9fa4a4befc512b43c6b3406fb0bddb00d4 Mon Sep 17 00:00:00 2001 From: "Ritesh Harjani (IBM)" Date: Sun, 1 Nov 2026 20:58:08 +0530 Subject: [PATCH 1125/2102] KVM: PPC: BookE: Don't call __ffs() on an empty pending_exceptions bitmap kvmppc_core_check_exceptions() has the same pattern as the Book3S code: it starts the scan of the pending exception bitmap with __ffs(*pending) and is called from kvmppc_core_prepare_to_enter() on every guest entry, so it routinely passes 0 to __ffs(), which is undefined. To be safe here, let's use find_first_bit(), which returns the bitmap size when no bit is set. Signed-off-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/9d5d92e93197ea43468312c82417b2f24159cca6.1793546707.git.ritesh.list@gmail.com --- arch/powerpc/kvm/booke.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/powerpc/kvm/booke.c b/arch/powerpc/kvm/booke.c index 2593f7ae6c0909..d14eb4f56dab5a 100644 --- a/arch/powerpc/kvm/booke.c +++ b/arch/powerpc/kvm/booke.c @@ -692,7 +692,7 @@ static void kvmppc_core_check_exceptions(struct kvm_vcpu *vcpu) unsigned long *pending = &vcpu->arch.pending_exceptions; unsigned int priority; - priority = __ffs(*pending); + priority = find_first_bit(pending, BITS_PER_BYTE * sizeof(*pending)); while (priority < BOOKE_IRQPRIO_MAX) { if (kvmppc_booke_irqprio_deliver(vcpu, priority)) break; From 2b1e236cb3dba4353feb9c77116645e57ba91669 Mon Sep 17 00:00:00 2001 From: "Ritesh Harjani (IBM)" Date: Sun, 1 Nov 2026 20:58:09 +0530 Subject: [PATCH 1126/2102] KVM: PPC: Book3S HV nestedv2: cap max vcpus to PAPR limit PAPR spec for H_GUEST_CREATE_VCPU says: "Only 2048 VCPUs can be created, and the specified ID must be in the range of 0 to 2047" However, KVM reports KVM_CAP_MAX_VCPUS as NR_CPUS and KVM_CAP_MAX_VCPU_ID as 8 * NR_CPUS. It also passes the userspace vCPU id through to the hcall unchanged. On a nestedv2 host (KVM on PowerVM / pseries nested PAPR) built with NR_CPUS > 2048, kvm selftest e.g. kvm_create_max_vcpus will create vCPU 2048 and fail with EINVAL when the hypervisor returns H_P3. Following error gets reported (with a debug print added to selftest to print failed vcpu_id number): ./kvm_create_max_vcpus Random seed: 0x6ec3f539 KVM_CAP_MAX_VCPU_ID: 65536 KVM_CAP_MAX_VCPUS: 8192 Testing creating 8192 vCPUs, with IDs 0...8191. [ 62.655458][ T302] KVM: Create Guest vcpu hcall failed, rc=-56 [ 62.655458][ T302] KVM: Create Guest vcpu hcall failed, rc=-56 Failed KVM_CREATE_VCPU for vcpu_id 2048 with errno 22 ==== Test Assertion Failure ==== lib/kvm_util.c:1395: vcpu->fd >= 0 pid=302 tid=302 errno=22 - Invalid argument 1 0x00000000100061d3: __vm_vcpu_add at kvm_util.c:1395 (discriminator 6) 2 0x0000000010001a6b: test_vcpu_creation at kvm_create_max_vcpus.c:32 (discriminator 3) 3 0x000000001000160b: main at kvm_create_max_vcpus.c:59 4 0x000000001001b713: __libc_start_call_main at libc-start.o:? 5 0x000000001001bb47: __libc_start_main_impl at ??:? KVM_CREATE_VCPU failed, rc: -1 errno: 22 (Invalid argument) [ 65.316986][ T302] KVM: TLB LPID invalidation hcall failed, rc=-2 [ 65.316986][ T302] KVM: TLB LPID invalidation hcall failed, rc=-2 Cap both extensions at 2048 when kvmhv_is_nestedv2() is set, so userspace never requests an id the L0 cannot create. PowerNV and nestedv1 are unchanged. The issue is only seen with nestedv2. While at it, this also fixes the limit for KVM_CAP_NR_VCPUS. Signed-off-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/f9c26aefa325bb4b6a3222718d6d605aa4993dff.1793546707.git.ritesh.list@gmail.com --- arch/powerpc/include/asm/kvm_host.h | 1 + arch/powerpc/kvm/powerpc.c | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/arch/powerpc/include/asm/kvm_host.h b/arch/powerpc/include/asm/kvm_host.h index 708a32f8977652..c068cc1dd51fc7 100644 --- a/arch/powerpc/include/asm/kvm_host.h +++ b/arch/powerpc/include/asm/kvm_host.h @@ -35,6 +35,7 @@ #define KVM_MAX_VCPUS NR_CPUS #define KVM_MAX_VCORES NR_CPUS +#define KVM_MAX_VCPU_IDS_NESTEDv2 2048 /* PAPR H_GUEST_CREATE_VCPU vcpuId */ #include diff --git a/arch/powerpc/kvm/powerpc.c b/arch/powerpc/kvm/powerpc.c index f4db7dea57b3c8..0dff273e9c1323 100644 --- a/arch/powerpc/kvm/powerpc.c +++ b/arch/powerpc/kvm/powerpc.c @@ -655,12 +655,18 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext) r = min(num_present_cpus(), KVM_MAX_VCPUS); else r = min(num_online_cpus(), KVM_MAX_VCPUS); + if (kvmhv_is_nestedv2()) + r = min(r, KVM_MAX_VCPU_IDS_NESTEDv2); break; case KVM_CAP_MAX_VCPUS: r = KVM_MAX_VCPUS; + if (kvmhv_is_nestedv2()) + r = min(r, KVM_MAX_VCPU_IDS_NESTEDv2); break; case KVM_CAP_MAX_VCPU_ID: r = KVM_MAX_VCPU_IDS; + if (kvmhv_is_nestedv2()) + r = min(r, KVM_MAX_VCPU_IDS_NESTEDv2); break; #ifdef CONFIG_PPC_BOOK3S_64 case KVM_CAP_PPC_GET_SMMU_INFO: From b8c0f82d60c7d149b271cec9364ffb815866cc80 Mon Sep 17 00:00:00 2001 From: "Ritesh Harjani (IBM)" Date: Sun, 1 Nov 2026 20:58:10 +0530 Subject: [PATCH 1127/2102] KVM: PPC: Book3S HV nestedv2: reject vCPU ids beyond the PAPR limit The previous patch caps KVM_CAP_MAX_VCPU_ID at 2048 on nestedv2 but nothing actually enforces it. The generic KVM_CREATE_VCPU path only checks the id against KVM_MAX_VCPU_IDS, which is 8 * NR_CPUS on HV. That means a VMM that ignores the capability can still pass a larger id. That id goes all the way down to H_GUEST_CREATE_VCPU, where the L0 rejects it and prints, ... KVM: Create Guest vcpu hcall failed, rc=-56 ...for every such attempt before failing the ioctl with -EINVAL anyway. Check the id in kvm_arch_vcpu_precreate() instead so it fails early with the same -EINVAL. Note that PowerNV and nestedv1 are not affected. Signed-off-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/3b233fa135d54d3ffb569d7febdc1cb8e0ed406a.1793546707.git.ritesh.list@gmail.com --- arch/powerpc/kvm/powerpc.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/powerpc/kvm/powerpc.c b/arch/powerpc/kvm/powerpc.c index 0dff273e9c1323..9eb5a944abe81f 100644 --- a/arch/powerpc/kvm/powerpc.c +++ b/arch/powerpc/kvm/powerpc.c @@ -770,6 +770,9 @@ void kvm_arch_flush_shadow_memslot(struct kvm *kvm, int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id) { + if (kvmhv_is_nestedv2() && id >= KVM_MAX_VCPU_IDS_NESTEDv2) + return -EINVAL; + return 0; } From d76620d9e2ce87963b993a44acae7ce1a47eca24 Mon Sep 17 00:00:00 2001 From: "Ritesh Harjani (IBM)" Date: Sun, 1 Nov 2026 20:58:11 +0530 Subject: [PATCH 1128/2102] KVM: PPC: Book3S HV: Fix error handling during vcore create kvmppc_vcore_create() can fail and return NULL, this patch fixes the error handling when this happens. vcore and online_vcores count should only be updated when vcore was actually created, otherwise it's state gets messed up for the VM run. Signed-off-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20f3d8cc8d5dc36872873cec4c8cb48a68e46354.1793546707.git.ritesh.list@gmail.com --- arch/powerpc/kvm/book3s_hv.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/arch/powerpc/kvm/book3s_hv.c b/arch/powerpc/kvm/book3s_hv.c index 4f45b1b3356159..c054030665e65f 100644 --- a/arch/powerpc/kvm/book3s_hv.c +++ b/arch/powerpc/kvm/book3s_hv.c @@ -3092,10 +3092,12 @@ static int kvmppc_core_vcpu_create_hv(struct kvm_vcpu *vcpu) err = -ENOMEM; vcore = kvmppc_vcore_create(kvm, id & ~(kvm->arch.smt_mode - 1)); - mutex_lock(&kvm->arch.mmu_setup_lock); - kvm->arch.vcores[core] = vcore; - kvm->arch.online_vcores++; - mutex_unlock(&kvm->arch.mmu_setup_lock); + if (vcore) { + mutex_lock(&kvm->arch.mmu_setup_lock); + kvm->arch.vcores[core] = vcore; + kvm->arch.online_vcores++; + mutex_unlock(&kvm->arch.mmu_setup_lock); + } } } From f6f88b0aa156a7df2477950fddf6b413d1c76a31 Mon Sep 17 00:00:00 2001 From: "Ritesh Harjani (IBM)" Date: Sun, 1 Nov 2026 20:58:12 +0530 Subject: [PATCH 1129/2102] KVM: PPC: Book3s: nestedv2: Free the guest state buffers if vcpu create fails On a nestedv2 host, kvmppc_core_vcpu_create_hv() first creates the vCPU in the L0 with kvmhv_nestedv2_vcpu_create(), which also allocates the guest state messages and the run input/output buffers. Only after that it picks a vcore for the vCPU - which can actually fail. This patch therefore takes care of freeing the GSM abd GSB for nestedv2 if an error occurs later as part of the cleanup routine. Signed-off-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/082c338c69773a73a48cd4e0d0885ee0f6ef5326.1793546707.git.ritesh.list@gmail.com --- arch/powerpc/kvm/book3s_hv.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/arch/powerpc/kvm/book3s_hv.c b/arch/powerpc/kvm/book3s_hv.c index c054030665e65f..89a1e0cd35afb1 100644 --- a/arch/powerpc/kvm/book3s_hv.c +++ b/arch/powerpc/kvm/book3s_hv.c @@ -3101,8 +3101,11 @@ static int kvmppc_core_vcpu_create_hv(struct kvm_vcpu *vcpu) } } - if (!vcore) + if (!vcore) { + if (kvmhv_is_nestedv2()) + kvmhv_nestedv2_vcpu_free(vcpu, &vcpu->arch.nestedv2_io); return err; + } spin_lock(&vcore->lock); ++vcore->num_threads; From ba4564fc66ae796f5070925b803e8f3039423ffb Mon Sep 17 00:00:00 2001 From: Karl Mehltretter Date: Sat, 3 Oct 2026 20:42:26 +0200 Subject: [PATCH 1130/2102] powerpc32/bpf: return false from bpf_jit_supports_fsession() on ppc32 bpf_jit_supports_fsession() returns bool. Commit 92258b5bf1ec ("powerpc32/bpf: Add fsession support") made it return -EOPNOTSUPP on ppc32 until fsession is validated there. The negative value converts to true, so the verifier does not reject fsession programs on ppc32. Such a program loads, and only attaching it fails because __arch_prepare_bpf_trampoline() returns -EOPNOTSUPP on ppc32. Return false instead. The load then fails with "JIT does not support fsession". Tested with a ppc32 kernel on QEMU g3beige. Fixes: 92258b5bf1ec ("powerpc32/bpf: Add fsession support") Reported-by: kernel test robot Reported-by: Dan Carpenter Closes: https://lore.kernel.org/r/202608010958.cYfBCQAC-lkp@intel.com/ Assisted-by: LLM Signed-off-by: Karl Mehltretter Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20261003184226.76740-1-kmehltretter@gmail.com --- arch/powerpc/net/bpf_jit_comp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/powerpc/net/bpf_jit_comp.c b/arch/powerpc/net/bpf_jit_comp.c index ce2966c52ac500..c246709a15ce10 100644 --- a/arch/powerpc/net/bpf_jit_comp.c +++ b/arch/powerpc/net/bpf_jit_comp.c @@ -586,7 +586,7 @@ bool bpf_jit_supports_fsession(void) * for fsession and trampoline on ppc32. */ if (IS_ENABLED(CONFIG_PPC32)) - return -EOPNOTSUPP; + return false; return true; } From 54efc2e1e9af9e3a14264db5686330e4fd477286 Mon Sep 17 00:00:00 2001 From: Gaurav Yadav Date: Fri, 7 Aug 2026 14:10:50 +0530 Subject: [PATCH 1131/2102] KVM: PPC: BookE: Use vcpu_err() instead of printk() in kvmppc_dump_vcpu() Replace generic printk() calls in kvmppc_dump_vcpu() with vcpu_err() and remove the corresponding TODO comment. Using vcpu_err() provides vCPU-aware logging context, making it easier to associate register dumps with specific vCPU instances in logs. Signed-off-by: Gaurav Yadav Reviewed-by: Ritesh Harjani (IBM) Signed-off-by: Madhavan Srinivasan Link: https://patch.msgid.link/20260807084050.25216-1-yadavgaurav386@gmail.com --- arch/powerpc/kvm/booke.c | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/arch/powerpc/kvm/booke.c b/arch/powerpc/kvm/booke.c index d14eb4f56dab5a..d328e94c26dbef 100644 --- a/arch/powerpc/kvm/booke.c +++ b/arch/powerpc/kvm/booke.c @@ -86,26 +86,25 @@ const struct kvm_stats_header kvm_vcpu_stats_header = { sizeof(kvm_vcpu_stats_desc), }; -/* TODO: use vcpu_printf() */ void kvmppc_dump_vcpu(struct kvm_vcpu *vcpu) { int i; - printk("pc: %08lx msr: %08llx\n", vcpu->arch.regs.nip, - vcpu->arch.shared->msr); - printk("lr: %08lx ctr: %08lx\n", vcpu->arch.regs.link, - vcpu->arch.regs.ctr); - printk("srr0: %08llx srr1: %08llx\n", vcpu->arch.shared->srr0, - vcpu->arch.shared->srr1); + vcpu_err(vcpu, "pc: %08lx msr: %08llx\n", vcpu->arch.regs.nip, + vcpu->arch.shared->msr); + vcpu_err(vcpu, "lr: %08lx ctr: %08lx\n", vcpu->arch.regs.link, + vcpu->arch.regs.ctr); + vcpu_err(vcpu, "srr0: %08llx srr1: %08llx\n", vcpu->arch.shared->srr0, + vcpu->arch.shared->srr1); - printk("exceptions: %08lx\n", vcpu->arch.pending_exceptions); + vcpu_err(vcpu, "exceptions: %08lx\n", vcpu->arch.pending_exceptions); for (i = 0; i < 32; i += 4) { - printk("gpr%02d: %08lx %08lx %08lx %08lx\n", i, - kvmppc_get_gpr(vcpu, i), - kvmppc_get_gpr(vcpu, i+1), - kvmppc_get_gpr(vcpu, i+2), - kvmppc_get_gpr(vcpu, i+3)); + vcpu_err(vcpu, "gpr%02d: %08lx %08lx %08lx %08lx\n", i, + kvmppc_get_gpr(vcpu, i), + kvmppc_get_gpr(vcpu, i+1), + kvmppc_get_gpr(vcpu, i+2), + kvmppc_get_gpr(vcpu, i+3)); } } From f55a3f02ab4162121d275125a96d74e6e96d721c Mon Sep 17 00:00:00 2001 From: Cheng Yongkang Date: Thu, 29 Oct 2026 07:12:20 -0700 Subject: [PATCH 1132/2102] usbip: clear actual_length after a failed receive vhci_recv_ret_submit() receives the transfer buffer for an IN URB. When usbip_recv_xbuff() fails, it sets urb->status to -EPROTO and gives the URB back, but leaves urb->actual_length at the value supplied by the usbip peer. A malicious peer can set actual_length larger than transfer_buffer_length; usbfs then copies that many bytes from the kmalloc(transfer_buffer_length) buffer to userspace: BUG: KASAN: slab-out-of-bounds in _copy_to_user+0x79/0xb0 Read of size 88 at addr ... copy_urb_data_to_user+0x36f/0x480 Clear actual_length on the failure path so the failed URB never carries a peer-controlled length. The URB is completed with -EPROTO and userspace observes a zero-length, failed transfer. Fixes: aabb5b833872 ("usbip: Fix error path of vhci_recv_ret_submit()") Cc: stable Assisted-by: LLM Signed-off-by: Cheng Yongkang Reviewed-by: Shuah Khan Link: https://patch.msgid.link/179328314074.648427.388274461758949120@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/usbip/vhci_rx.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/usb/usbip/vhci_rx.c b/drivers/usb/usbip/vhci_rx.c index a678e7c8983752..741107a9646603 100644 --- a/drivers/usb/usbip/vhci_rx.c +++ b/drivers/usb/usbip/vhci_rx.c @@ -79,6 +79,7 @@ static void vhci_recv_ret_submit(struct vhci_device *vdev, /* recv transfer buffer */ if (usbip_recv_xbuff(ud, urb) < 0) { urb->status = -EPROTO; + urb->actual_length = 0; goto error; } From 640c2b7b2d5f215d76a670048ab1dc174400097f Mon Sep 17 00:00:00 2001 From: Anuj Bolewar Date: Tue, 4 Aug 2026 22:50:54 +0530 Subject: [PATCH 1133/2102] usb: gadget: uvc: fix use-after-free in uvcg_extension_drop uvcg_extension_drop() releases the configfs item reference with config_item_put() and then removes the extension unit from the list and frees its dynamic descriptor fields. When the put is the last reference, config_item_cleanup() runs uvcg_extension_release(), which kfree()s the struct uvcg_extension, so the subsequent list_del() and kfree() calls dereference freed memory. The configfs mkdir error path calls drop_item() on an item whose only reference is the one held by the configfs hierarchy, so the put inside drop_item() frees the unit synchronously and list_del() reads freed memory (KASAN: slab-use-after-free Read in uvcg_extension_drop). Do all the list and field cleanup while the item is still alive, and release the reference as the last step. Reported-by: syzbot+f093afc4e90b1908abdc@syzkaller.appspotmail.com Cc: stable Closes: https://syzkaller.appspot.com/bug?extid=f093afc4e90b1908abdc Fixes: 0525210c9840 ("usb: gadget: uvc: Allow definition of XUs in configfs") Assisted-by: deepseek:v4-pro Signed-off-by: Anuj Bolewar Link: https://patch.msgid.link/20260804-uvc-extension-drop-uaf-v1-1-4a5db42150af@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/uvc_configfs.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/usb/gadget/function/uvc_configfs.c b/drivers/usb/gadget/function/uvc_configfs.c index b9af49940d5f21..88d78edec4b219 100644 --- a/drivers/usb/gadget/function/uvc_configfs.c +++ b/drivers/usb/gadget/function/uvc_configfs.c @@ -1256,11 +1256,12 @@ static void uvcg_extension_drop(struct config_group *group, struct config_item * mutex_lock(&opts->lock); - config_item_put(item); list_del(&xu->list); kfree(xu->desc.baSourceID); kfree(xu->desc.bmControls); + config_item_put(item); + mutex_unlock(&opts->lock); } From 34c8c2ea213aab7b452df93e5b7547f4459a49e9 Mon Sep 17 00:00:00 2001 From: Xiangwu Lai Date: Mon, 2 Nov 2026 18:44:31 +0800 Subject: [PATCH 1134/2102] dmaengine: stm32-mdma: Fix runtime PM reference leak in pm_suspend stm32_mdma_pm_suspend() increments the runtime PM usage counter with pm_runtime_resume_and_get(), but when a channel is still enabled it returns -EBUSY directly without dropping the reference. The matching pm_runtime_put_sync() only runs on the success path. Each failed suspend attempt therefore leaks one runtime PM reference, so the device can never runtime suspend afterwards. Drop the reference before returning -EBUSY. Fixes: 7cb819c856d9 ("dmaengine: stm32-mdma: add suspend/resume power management support") Signed-off-by: Xiangwu Lai Reviewed-by: Frank Li Reviewed-by: Amelie Delaunay Link: https://patch.msgid.link/20261102104432.873-1-laixiangwu@cmss.chinamobile.com Signed-off-by: Vinod Koul --- drivers/dma/stm32/stm32-mdma.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/dma/stm32/stm32-mdma.c b/drivers/dma/stm32/stm32-mdma.c index 04639e4b554ea0..0a5749021f6bb9 100644 --- a/drivers/dma/stm32/stm32-mdma.c +++ b/drivers/dma/stm32/stm32-mdma.c @@ -1779,6 +1779,7 @@ static int stm32_mdma_pm_suspend(struct device *dev) ccr = stm32_mdma_read(dmadev, STM32_MDMA_CCR(id)); if (ccr & STM32_MDMA_CCR_EN) { dev_warn(dev, "Suspend is prevented by Chan %i\n", id); + pm_runtime_put_sync(dev); return -EBUSY; } } From 8709574b038995b47a473dd4073ee62baf02f87c Mon Sep 17 00:00:00 2001 From: Priyanka Mani Date: Tue, 3 Nov 2026 06:29:25 +0000 Subject: [PATCH 1135/2102] usb: gadget: uvc: fix dwFrameInterval array leak on frame removal uvcg_frame_dw_frame_interval_store() allocates the frame interval array and stores it in uvcg_frame::dw_frame_interval. The array is only freed when it is replaced by a later write to the dwFrameInterval attribute. Frame items use the generic uvcg_config_item_release(), which frees the frame itself but not the interval array, so the array is leaked every time a frame directory is removed after dwFrameInterval was written. This happens on every normal teardown of a configfs UVC gadget, and kmemleak reports it as: unreferenced object 0xffff8881027f5040 (size 8): comm "uvc-frame-inter", pid 281, jiffies 4294827366 hex dump (first 8 bytes): 15 16 05 00 00 00 00 00 ........ backtrace (crc 60980708): __kmalloc_noprof+0x4ca/0x7a0 uvcg_frame_dw_frame_interval_store+0x299/0x440 [usb_f_uvc] configfs_write_iter+0x2ac/0x490 vfs_write+0x60f/0x1100 ksys_write+0xf9/0x1d0 do_syscall_64+0xfa/0x5e0 Give frames their own release callback that frees the interval array together with the frame. The leak was found with kmemleak while exercising configfs gadget functions in a VM. Fixes: 46919a23ee87 ("usb: gadget: uvc: configfs support in uvc function") Cc: stable Signed-off-by: Priyanka Mani Link: https://patch.msgid.link/7f7db2bcb2c5d248cf72a270bd18afc71cf01559.1793687064.git.priyankamani2100@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/uvc_configfs.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/drivers/usb/gadget/function/uvc_configfs.c b/drivers/usb/gadget/function/uvc_configfs.c index 88d78edec4b219..a8717c95e5edfc 100644 --- a/drivers/usb/gadget/function/uvc_configfs.c +++ b/drivers/usb/gadget/function/uvc_configfs.c @@ -2143,14 +2143,26 @@ static struct configfs_attribute *uvcg_frame_attrs2[] = { NULL, }; +static void uvcg_frame_release(struct config_item *item) +{ + struct uvcg_frame *frm = to_uvcg_frame(item); + + kfree(frm->dw_frame_interval); + kfree(frm); +} + +static const struct configfs_item_operations uvcg_frame_item_ops = { + .release = uvcg_frame_release, +}; + static const struct config_item_type uvcg_frame_type1 = { - .ct_item_ops = &uvcg_config_item_ops, + .ct_item_ops = &uvcg_frame_item_ops, .ct_attrs = uvcg_frame_attrs1, .ct_owner = THIS_MODULE, }; static const struct config_item_type uvcg_frame_type2 = { - .ct_item_ops = &uvcg_config_item_ops, + .ct_item_ops = &uvcg_frame_item_ops, .ct_attrs = uvcg_frame_attrs2, .ct_owner = THIS_MODULE, }; From 5bca7b3fc800ebd33692b8b444ca134a3d1e6f08 Mon Sep 17 00:00:00 2001 From: Yingjie Wang Date: Tue, 17 Nov 2026 03:31:52 +0000 Subject: [PATCH 1136/2102] usb: gadget: midi2: copy configfs strings for live functions f_midi2_alloc() shallow-copies the card, endpoint, and block string pointers from configfs. Dynamic ep.* and block.* groups may be removed after the function has been allocated. Their release callbacks then free strings still used by live USB string descriptors and UMP discovery replies. Copy the optional strings while opts->lock is held, so configfs release cannot free the source strings during the copy. Free the private copies with the live function and build the USB string table from those copies. On x86_64 with KASAN and dummy_hcd, USB string descriptor requests made after removing a dynamic block and endpoint trigger two slab-use-after-free reports on the unpatched kernel. With this change, the same requests complete without a KASAN report. Fixes: 29ee7a4dddd5 ("usb: gadget: midi2: Add configfs support") Cc: stable Reviewed-by: Takashi Iwai Signed-off-by: Yingjie Wang Link: https://patch.msgid.link/279d2387232d774116d674f718f381438abc90fe.1794886308.git.x-professor@outlook.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_midi2.c | 57 +++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/drivers/usb/gadget/function/f_midi2.c b/drivers/usb/gadget/function/f_midi2.c index d693de427641dd..c02d6f11be14f8 100644 --- a/drivers/usb/gadget/function/f_midi2.c +++ b/drivers/usb/gadget/function/f_midi2.c @@ -171,6 +171,31 @@ static const char *ump_fb_name(const struct f_midi2_block_info *info) return info->name ? info->name : "MIDI 2.0 Gadget I/O"; } +static int f_midi2_copy_string(const char **dst, const char *src) +{ + *dst = NULL; + if (!src) + return 0; + + *dst = kstrdup(src, GFP_KERNEL); + return *dst ? 0 : -ENOMEM; +} + +static void f_midi2_free_strings(struct f_midi2 *midi2) +{ + int i, blk; + + kfree(midi2->info.iface_name); + for (i = 0; i < midi2->num_eps; i++) { + struct f_midi2_ep *ep = &midi2->midi2_eps[i]; + + kfree(ep->info.ep_name); + kfree(ep->info.product_id); + for (blk = 0; blk < ep->num_blks; blk++) + kfree(ep->blks[blk].info.name); + } +} + /* * USB Descriptor Definitions */ @@ -2701,6 +2726,7 @@ static void do_f_midi2_free(struct f_midi2 *midi2, struct f_midi2_opts *opts) --opts->refcnt; mutex_unlock(&opts->lock); kfree(midi2->string_defs); + f_midi2_free_strings(midi2); kfree(midi2); } @@ -2811,7 +2837,7 @@ static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi) struct f_midi2_opts *opts; struct f_midi2_ep *ep; struct f_midi2_block *bp; - int i, num_eps, blk; + int i, num_eps, blk, ret; midi2 = kzalloc_obj(*midi2); if (!midi2) @@ -2826,7 +2852,6 @@ static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi) return ERR_PTR(num_eps); } ++opts->refcnt; - mutex_unlock(&opts->lock); spin_lock_init(&midi2->queue_lock); @@ -2841,19 +2866,38 @@ static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi) midi2->info = opts->info; midi2->num_eps = num_eps; + ret = f_midi2_copy_string(&midi2->info.iface_name, + opts->info.iface_name); + if (ret) + goto err_unlock; for (i = 0; i < num_eps; i++) { ep = &midi2->midi2_eps[i]; ep->info = opts->eps[i]->info; + ep->info.ep_name = NULL; + ep->info.product_id = NULL; + ret = f_midi2_copy_string(&ep->info.ep_name, + opts->eps[i]->info.ep_name); + if (ret) + goto err_unlock; + ret = f_midi2_copy_string(&ep->info.product_id, + opts->eps[i]->info.product_id); + if (ret) + goto err_unlock; ep->card = midi2; for (blk = 0; blk < SNDRV_UMP_MAX_BLOCKS && opts->eps[i]->blks[blk]; blk++) { bp = &ep->blks[blk]; ep->num_blks++; bp->info = opts->eps[i]->blks[blk]->info; + ret = f_midi2_copy_string(&bp->info.name, + opts->eps[i]->blks[blk]->info.name); + if (ret) + goto err_unlock; bp->gtb_id = ++midi2->total_blocks; } } + mutex_unlock(&opts->lock); midi2->string_defs = kzalloc_objs(*midi2->string_defs, midi2->total_blocks + 1); @@ -2862,8 +2906,8 @@ static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi) return ERR_PTR(-ENOMEM); } - if (opts->info.iface_name && *opts->info.iface_name) - midi2->string_defs[STR_IFACE].s = opts->info.iface_name; + if (midi2->info.iface_name && *midi2->info.iface_name) + midi2->string_defs[STR_IFACE].s = midi2->info.iface_name; else midi2->string_defs[STR_IFACE].s = ump_ep_name(&midi2->midi2_eps[0]); @@ -2885,6 +2929,11 @@ static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi) } return &midi2->func; + +err_unlock: + mutex_unlock(&opts->lock); + do_f_midi2_free(midi2, opts); + return ERR_PTR(ret); } DECLARE_USB_FUNCTION_INIT(midi2, f_midi2_alloc_inst, f_midi2_alloc); From 087ed08145e406535a6613aef5607ceef2ade518 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Thu, 17 Sep 2026 18:31:22 +0800 Subject: [PATCH 1137/2102] usb: gadget: uvc: reject zero interval in uvc_v4l2_s_parm() v4l2_fraction_to_interval() returns 0 when the caller passes numerator == 0 with a non-zero denominator. If this zero value is stored in video->interval, the isoc path in uvc_video_prep_requests() computes: nreq = DIV_ROUND_UP(video->interval, interval_duration); /* 0 */ req_size = DIV_ROUND_UP(video->imagesize + header_size, nreq); The second DIV_ROUND_UP divides by zero, crashing the kernel. Any local process that can open the UVC gadget's /dev/videoN and issue VIDIOC_S_PARM with timeperframe.numerator = 0 followed by VIDIOC_STREAMON triggers this immediately. Reject a zero interval in uvc_v4l2_s_parm() before it is stored. Cc: stable Reviewed-by: Weibin Liu Signed-off-by: Liu Chao Link: https://patch.msgid.link/20260917103122.3045458-1-liuc63@xiaopeng.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/uvc_v4l2.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/drivers/usb/gadget/function/uvc_v4l2.c b/drivers/usb/gadget/function/uvc_v4l2.c index dfa0521a243ac0..e9b9288c5c2a3d 100644 --- a/drivers/usb/gadget/function/uvc_v4l2.c +++ b/drivers/usb/gadget/function/uvc_v4l2.c @@ -368,6 +368,11 @@ static int uvc_v4l2_s_parm(struct file *file, void *fh, video->interval = v4l2_fraction_to_interval(timeperframe.numerator, timeperframe.denominator); + if (!video->interval) { + uvcg_dbg(&uvc->func, "Invalid zero interval, rejecting\n"); + return -EINVAL; + } + uvcg_dbg(&uvc->func, "Setting frame interval to %u/%u (%u)\n", timeperframe.numerator, timeperframe.denominator, video->interval); From 56cbd7f69ce6037738410a5c50efb7cacf52b0ae Mon Sep 17 00:00:00 2001 From: SeungUk Nam Date: Thu, 10 Sep 2026 16:48:32 +0900 Subject: [PATCH 1138/2102] dmaengine: idxd: Free the minor number when cdev setup fails idxd_wq_add_cdev() allocates a minor number from cdev_ctx->minor_ida for the new struct idxd_cdev. When dev_set_name() or cdev_device_add() fails, the error path calls put_device(), and the release callback idxd_cdev_dev_release() only frees idxd_cdev, so the minor number is never returned to the ida. Leaked numbers accumulate across bind/unbind cycles, up to MINORMASK, for as long as the module stays loaded. Free the minor number before put_device() drops the last reference on that path. Fixes: c311f5e92484 ("dmaengine: idxd: Fix freeing the allocated ida too late") Signed-off-by: SeungUk Nam Reviewed-by: Frank Li Link: https://patch.msgid.link/20260910074832.15729-1-tmddnr49449@gmail.com Signed-off-by: Vinod Koul --- drivers/dma/idxd/cdev.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/dma/idxd/cdev.c b/drivers/dma/idxd/cdev.c index 82b07cf942ef82..f1af7f0d25d347 100644 --- a/drivers/dma/idxd/cdev.c +++ b/drivers/dma/idxd/cdev.c @@ -573,6 +573,7 @@ int idxd_wq_add_cdev(struct idxd_wq *wq) return 0; err: + ida_free(&cdev_ctx->minor_ida, minor); put_device(dev); wq->idxd_cdev = NULL; return rc; From 6f85b686fce9dd00202f5c687ab836682b3bdaa7 Mon Sep 17 00:00:00 2001 From: Karl Mehltretter Date: Sat, 12 Sep 2026 00:57:37 +0200 Subject: [PATCH 1139/2102] Documentation: ABI: sysfs-driver-dma-idxd: Fix the kernel version 6.20.0 There is no kernel 6.20: the release after 6.19 was 7.0. The entry came in with commit 8308510b9365 ("dmaengine: idxd: Expose DSA3.0 capabilities through sysfs"), first released in v7.0-rc1. Say 7.0. Fixes: 8308510b9365 ("dmaengine: idxd: Expose DSA3.0 capabilities through sysfs") Assisted-by: LLM Signed-off-by: Karl Mehltretter Reviewed-by: Frank Li Reviewed-by: Dave Jiang Link: https://patch.msgid.link/20260911225737.11411-1-kmehltretter@gmail.com Signed-off-by: Vinod Koul --- Documentation/ABI/stable/sysfs-driver-dma-idxd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/ABI/stable/sysfs-driver-dma-idxd b/Documentation/ABI/stable/sysfs-driver-dma-idxd index 08d030159f0921..5be4e2d5775ff4 100644 --- a/Documentation/ABI/stable/sysfs-driver-dma-idxd +++ b/Documentation/ABI/stable/sysfs-driver-dma-idxd @@ -138,7 +138,7 @@ Description: The last executed device administrative command's status/error. What: /sys/bus/dsa/devices/dsa/dsacaps Date: April 5, 2026 -KernelVersion: 6.20.0 +KernelVersion: 7.0 Contact: dmaengine@vger.kernel.org Description: The DSA3 specification introduces three new capability registers: dsacap[0-2]. User components (e.g., configuration From 826d8fe80db5450d5f526d57f33eaf3111428cca Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:59 +0100 Subject: [PATCH 1140/2102] usb: dwc2: wait for the TT clear in endpoint_disable When a split transaction fails, dwc2_hc_handle_tt_clear() sets qh->tt_buffer_dirty and calls usb_hub_clear_tt_buffer(). The hub driver stores urb->ep in its list and hub_tt_work() hands it back to _dwc2_hcd_clear_tt_buffer_complete() after the CLEAR_TT_BUFFER request to the hub, which can take up to a second if the hub does not answer. Nothing keeps the endpoint until then. dwc2_hcd_endpoint_disable() only waits for the QTD list to drain and frees the QH. If the full or low speed device is unplugged, usb_disconnect() goes on to free the usb_device and its configurations, which hold the struct usb_host_endpoint. The callback then reads ep->hcpriv from freed memory and, if it is not NULL, clears a bit in whatever it points to. A change of the configuration or altsetting only frees the QH, under a callback which has loaded ep->hcpriv without the lock. A device which contains a hub can provoke this: fail a transaction of the downstream device, report its disconnection and hold back the answer to CLEAR_TT_BUFFER. The HCD has to wait, like ehci_endpoint_disable(), xhci_endpoint_disable() and fotg210_endpoint_disable() do. hub_tt_work() calls the callback for every entry, also if the request failed, and hub_quiesce() flushes the work, so the wait ends. Fixes: 7359d482eb4d ("staging: HCD files for the DWC2 driver") Cc: stable Cc: Minas Harutyunyan Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261027-llm-usb-v1-19-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc2/hcd.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/drivers/usb/dwc2/hcd.c b/drivers/usb/dwc2/hcd.c index 2e1927dfa34f1f..40ab50538334af 100644 --- a/drivers/usb/dwc2/hcd.c +++ b/drivers/usb/dwc2/hcd.c @@ -1993,6 +1993,21 @@ static int dwc2_hcd_endpoint_disable(struct dwc2_hsotg *hsotg, } } + /* + * The hub driver still has a pointer to the endpoint. Wait until it + * has called _dwc2_hcd_clear_tt_buffer_complete(). + */ + while (qh->tt_buffer_dirty) { + spin_unlock_irqrestore(&hsotg->lock, flags); + msleep(20); + spin_lock_irqsave(&hsotg->lock, flags); + qh = ep->hcpriv; + if (!qh) { + rc = -EINVAL; + goto err; + } + } + dwc2_hcd_qh_unlink(hsotg, qh); /* Free each QTD in the QH's QTD list */ From 6068ddadca55c8cdddb9e0d846101709a87fc0ee Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:46 +0100 Subject: [PATCH 1141/2102] usb: gadget: snps_udc_plat: lock out the interrupt stop_udc() is called from a work item, when the extcon device reports that the cable has been unplugged. It takes udc->lock with interrupts enabled. udc_irq(), the hard interrupt handler of the controller, takes the same lock. If the controller raises an interrupt on the CPU which is in stop_udc(), and it is likely to have something to report when the cable is pulled, the handler spins on a lock which the interrupted work holds: the CPU is stuck. Disable interrupts while the lock is held. They are enabled again for the ->disconnect() callback of the gadget driver, for which the lock is dropped as before. Fixes: 1b9f35adb0ff ("usb: gadget: udc: Add Synopsys UDC Platform driver") Cc: stable Cc: Neill Kapron Cc: Ijae Kim Cc: Herve Codina Signed-off-by: Josef Bacik Reviewed-by: Herve Codina Link: https://patch.msgid.link/20261027-llm-usb-v1-6-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/udc/snps_udc_plat.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/usb/gadget/udc/snps_udc_plat.c b/drivers/usb/gadget/udc/snps_udc_plat.c index 3687690ca33da4..79fccdd52790e5 100644 --- a/drivers/usb/gadget/udc/snps_udc_plat.c +++ b/drivers/usb/gadget/udc/snps_udc_plat.c @@ -34,7 +34,7 @@ static void stop_udc(struct udc *udc) int tmp; u32 reg; - spin_lock(&udc->lock); + spin_lock_irq(&udc->lock); /* Flush the receieve fifo */ reg = readl(&udc->regs->ctl); @@ -53,9 +53,9 @@ static void stop_udc(struct udc *udc) /* Disconnect gadget driver */ if (udc->driver) { - spin_unlock(&udc->lock); + spin_unlock_irq(&udc->lock); udc->driver->disconnect(&udc->gadget); - spin_lock(&udc->lock); + spin_lock_irq(&udc->lock); /* empty queues */ for (tmp = 0; tmp < UDC_EP_NUM; tmp++) @@ -63,7 +63,7 @@ static void stop_udc(struct udc *udc) } udc->connected = 0; - spin_unlock(&udc->lock); + spin_unlock_irq(&udc->lock); dev_info(udc->dev, "Device disconnected\n"); } From 7907f2113796db7ef156911255e18976ec5db83e Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:53 +0100 Subject: [PATCH 1142/2102] usb: typec: anx7411: zero on-stack alt mode descriptors typec_port_register_altmodes() and anx7411_typec_register_altmode() fill a struct typec_altmode_desc on the stack member by member: svid, vdo, mode. typec_register_altmode() reads three more members: - inactive: a port alternate mode is registered with active = !inactive. If the byte of stack garbage is not 0, the mode starts disabled and typec_altmode_enter() refuses it with -EPERM until somebody writes to the "active" attribute of the port; - mode_selection: the DisplayPort and Thunderbolt drivers enter the mode on their own only if it is false. For the partner alternate modes of anx7411, garbage there means that the mode is never entered; - roles: decides what supported_roles of the port alternate mode shows. typec_port_register_altmodes() is what tcpm and anx7411 register the alternate modes of their ports with. CONFIG_INIT_STACK_ALL_ZERO=y hides the problem. Fixes: 183b194d8fb6 ("usb: typec: Make active on port altmode writable") Fixes: be727d400066 ("usb: typec: Introduce mode_selection bit") Fixes: 7b458a4c5d73 ("usb: typec: Add typec_port_register_altmodes()") Cc: stable Signed-off-by: Josef Bacik Reviewed-by: Heikki Krogerus Reviewed-by: Benson Leung Link: https://patch.msgid.link/20261027-llm-usb-v1-13-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/typec/anx7411.c | 2 +- drivers/usb/typec/class.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/usb/typec/anx7411.c b/drivers/usb/typec/anx7411.c index 6f9c15ee0d8699..c4730b96e696e8 100644 --- a/drivers/usb/typec/anx7411.c +++ b/drivers/usb/typec/anx7411.c @@ -552,7 +552,7 @@ static int anx7411_typec_register_altmode(struct anx7411_data *ctx, int svid, int vdo) { struct device *dev = &ctx->spi_client->dev; - struct typec_altmode_desc desc; + struct typec_altmode_desc desc = {}; int err; int i; diff --git a/drivers/usb/typec/class.c b/drivers/usb/typec/class.c index 54c7810b563beb..9d9703c708209e 100644 --- a/drivers/usb/typec/class.c +++ b/drivers/usb/typec/class.c @@ -2684,7 +2684,7 @@ void typec_port_register_altmodes(struct typec_port *port, struct typec_altmode **altmodes, size_t n) { struct fwnode_handle *child; - struct typec_altmode_desc desc; + struct typec_altmode_desc desc = {}; struct typec_altmode *alt; size_t index = 0; u16 svid; From b1c46affc9961efabd8548013cd4197688ee489e Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:51 +0100 Subject: [PATCH 1143/2102] usb: typec: tcpm: don't wait for the VDM discovery work mod_vdm_discovery_cancel_delayed_work() calls kthread_cancel_work_sync() with port->lock held, and tcpm_vdm_discovery_work() starts by taking that lock. This is fine as long as the caller runs on the kthread worker of the port, like the work. But tcpm_reset_port() is also reached from tcpm_tcpc_reset(), which tcpci_irq() calls from its interrupt thread. If the work is running, it waits for the lock while the holder of the lock waits for the work. Use a flag instead, protected by port->lock, which is set when the work is scheduled and cleared when it is cancelled. The work returns at once if the flag is not set. tcpm_unregister_port() calls tcpm_reset_port() after it has destroyed the worker. Commit 98d00deb6ae4 ("usb: typec: tcpm: fix use-after-free of the kthread worker on port unregister") put a test of port->wq in front of the cancel for that case. Nothing is cancelled any more, so the test goes. Fixes: 205dc9cb39f5 ("usb: typec: tcpm: implement retry mechanism for Discover Identity VDMs") Cc: stable Cc: Badhri Jagan Sridharan Signed-off-by: Josef Bacik Reviewed-by: Heikki Krogerus Link: https://patch.msgid.link/20261027-llm-usb-v1-11-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/typec/tcpm/tcpm.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/drivers/usb/typec/tcpm/tcpm.c b/drivers/usb/typec/tcpm/tcpm.c index bb90211660cae3..bf7fd632d815ee 100644 --- a/drivers/usb/typec/tcpm/tcpm.c +++ b/drivers/usb/typec/tcpm/tcpm.c @@ -542,6 +542,7 @@ struct tcpm_port { struct kthread_work enable_frs; struct hrtimer vdm_discovery_timer; struct kthread_work vdm_discovery_work; + bool vdm_discovery_armed; bool state_machine_running; /* Set to true when VDM State Machine has following actions. */ bool vdm_sm_running; @@ -1768,15 +1769,20 @@ static void mod_enable_frs_delayed_work(struct tcpm_port *port, unsigned int del } } +/* + * Called with port->lock held, which the work takes, and not only from the + * worker: the work cannot be waited for. It does nothing unless it is armed. + */ static void mod_vdm_discovery_cancel_delayed_work(struct tcpm_port *port) { hrtimer_cancel(&port->vdm_discovery_timer); - if (port->wq) - kthread_cancel_work_sync(&port->vdm_discovery_work); + port->vdm_discovery_armed = false; } static void mod_vdm_discovery_delayed_work(struct tcpm_port *port, unsigned int delay_ms) { + port->vdm_discovery_armed = true; + if (delay_ms) { hrtimer_start(&port->vdm_discovery_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL); } else { @@ -7295,6 +7301,10 @@ static void tcpm_vdm_discovery_work(struct kthread_work *work) mutex_lock(&port->lock); + if (!port->vdm_discovery_armed) + goto unlock; + port->vdm_discovery_armed = false; + tcpm_log_force(port, "%s state [%s]", __func__, vdm_discovery_state_strings[port->vdm_discovery_state]); From 9ec58903a6edd763948653d1b04d3515804fccbe Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:50 +0100 Subject: [PATCH 1144/2102] usb: host: ehci-orion: fix the probe without DT The Orion5x, MV78xx0 and Dove board files register the controllers as platform devices called "orion-ehci" (arch/arm/plat-orion/common.c), which are bound by name. of_device_get_match_data() returns NULL for them, and ehci_orion_drv_probe() dereferences it to get the DMA mask. Use the 32 bit mask, as before, if there is no match data. Fixes: c63fe1cc7093 ("usb: host: Add ac5 to EHCI Orion") Cc: Elad Nachman Cc: stable Signed-off-by: Josef Bacik Acked-by: Alan Stern Link: https://patch.msgid.link/20261027-llm-usb-v1-10-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/host/ehci-orion.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/usb/host/ehci-orion.c b/drivers/usb/host/ehci-orion.c index eaaa49712a8c64..2071c3d6e582c9 100644 --- a/drivers/usb/host/ehci-orion.c +++ b/drivers/usb/host/ehci-orion.c @@ -218,7 +218,7 @@ static int ehci_orion_drv_probe(struct platform_device *pdev) int irq, err; enum orion_ehci_phy_ver phy_version; struct orion_ehci_hcd *priv; - u64 *dma_mask_ptr; + const u64 *dma_mask_ptr; if (usb_disabled()) return -ENODEV; @@ -236,7 +236,9 @@ static int ehci_orion_drv_probe(struct platform_device *pdev) * set. Since shared usb code relies on it, set it here for * now. Once we have dma capability bindings this can go away. */ - dma_mask_ptr = (u64 *)of_device_get_match_data(&pdev->dev); + dma_mask_ptr = of_device_get_match_data(&pdev->dev); + if (!dma_mask_ptr) + dma_mask_ptr = &dma_mask_orion; err = dma_coerce_mask_and_coherent(&pdev->dev, *dma_mask_ptr); if (err) goto err; From 49d3668edddfb442836558963de2797ab5ee076e Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:58 +0100 Subject: [PATCH 1145/2102] usb: isp1760: wait for the TT clear in endpoint_disable The driver sets qh->tt_buffer_dirty and calls usb_hub_clear_tt_buffer() when a transfer to a full or low speed device fails or is unlinked while it is running. The hub driver stores urb->ep in its list and hub_tt_work() hands it back to isp1760_clear_tt_buffer_complete() after the CLEAR_TT_BUFFER request to the hub. Nothing keeps the endpoint until then. isp1760_endpoint_disable() frees the QH at once. If the device is unplugged, the unlink of a running URB queues such a request, and usb_disconnect() goes on to free the usb_device and its configurations, which hold the struct usb_host_endpoint. The callback then reads ep->hcpriv from freed memory and, if it is not NULL, writes to whatever it points to. A change of the configuration or altsetting only frees the QH, under a callback which has loaded ep->hcpriv without the lock. The HCD has to wait, like ehci_endpoint_disable(), xhci_endpoint_disable() and fotg210_endpoint_disable() do. hub_tt_work() calls the callback for every entry, also if the request failed, and hub_quiesce() flushes the work, so the wait ends. Fixes: 74ad60292bf0 ("usb/isp1760: Clear TT buffer on interrupted low & full speed transfers") Cc: stable Signed-off-by: Josef Bacik Acked-by: Rui Miguel Silva Link: https://patch.msgid.link/20261027-llm-usb-v1-18-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/isp1760/isp1760-hcd.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/drivers/usb/isp1760/isp1760-hcd.c b/drivers/usb/isp1760/isp1760-hcd.c index 6c52c6f59d693c..3cbf5fe3ed3434 100644 --- a/drivers/usb/isp1760/isp1760-hcd.c +++ b/drivers/usb/isp1760/isp1760-hcd.c @@ -2071,12 +2071,23 @@ static void isp1760_endpoint_disable(struct usb_hcd *hcd, struct isp1760_qh *qh, *qh_iter; int i; +rescan: spin_lock_irqsave(&priv->lock, spinflags); qh = ep->hcpriv; if (!qh) goto out; + /* + * The hub driver still has a pointer to the endpoint. Wait until it + * has called isp1760_clear_tt_buffer_complete(). + */ + if (qh->tt_buffer_dirty) { + spin_unlock_irqrestore(&priv->lock, spinflags); + schedule_timeout_uninterruptible(1); + goto rescan; + } + WARN_ON(!list_empty(&qh->qtd_list)); for (i = 0; i < QH_END; i++) From 97002d33afe7c66aea1c76c783fbb2e8712a9564 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:44 +0100 Subject: [PATCH 1146/2102] usb: host: oxu210hp-hcd: fix oxu_qh_alloc() deadlock oxu_qh_alloc() calls ehci_qtd_alloc() with mem_lock held, and that function takes the same spinlock. Allocate the dummy qtd before taking the lock, and give it back, without the lock, if there is no free queue head. Fixes: b92a78e582b1 ("usb host: Oxford OXU210HP HCD driver.") Cc: stable Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261027-llm-usb-v1-4-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/host/oxu210hp-hcd.c | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/drivers/usb/host/oxu210hp-hcd.c b/drivers/usb/host/oxu210hp-hcd.c index d12cf85bbf22f6..a0fade1a54ba9e 100644 --- a/drivers/usb/host/oxu210hp-hcd.c +++ b/drivers/usb/host/oxu210hp-hcd.c @@ -1034,6 +1034,14 @@ static struct ehci_qh *oxu_qh_alloc(struct oxu_hcd *oxu) { int i; struct ehci_qh *qh = NULL; + struct ehci_qtd *dummy; + + /* dummy td enables safe urb queuing; this takes mem_lock */ + dummy = ehci_qtd_alloc(oxu); + if (!dummy) { + oxu_dbg(oxu, "no dummy td\n"); + return NULL; + } spin_lock(&oxu->mem_lock); @@ -1049,21 +1057,16 @@ static struct ehci_qh *oxu_qh_alloc(struct oxu_hcd *oxu) qh->oxu = oxu; qh->qh_dma = virt_to_phys(qh); INIT_LIST_HEAD(&qh->qtd_list); - - /* dummy td enables safe urb queuing */ - qh->dummy = ehci_qtd_alloc(oxu); - if (qh->dummy == NULL) { - oxu_dbg(oxu, "no dummy td\n"); - oxu->qh_used[i] = 0; - qh = NULL; - goto unlock; - } + qh->dummy = dummy; oxu->qh_used[i] = 1; } -unlock: + spin_unlock(&oxu->mem_lock); + if (!qh) + oxu_qtd_free(oxu, dummy); + return qh; } From f859addb3f88d69e2a27c7361a3178e33951a99a Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:47 +0100 Subject: [PATCH 1147/2102] usb: gadget: bdc: the resume callback is optional handle_link_state_change() tests gadget_driver->suspend before it calls it and sets DEVICE_SUSPENDED, but calls gadget_driver->resume untested when the link comes back. gadgetfs has a suspend callback and no resume callback: with it the first bus resume ends in a call of NULL. Fixes: efed421a94e6 ("usb: gadget: Add UDC driver for Broadcom USB3.0 device controller IP BDC") Cc: stable Cc: Justin Chen Cc: Al Cooper Cc: Broadcom internal kernel review list Cc: Neill Kapron Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261027-llm-usb-v1-7-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/udc/bdc/bdc_udc.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/usb/gadget/udc/bdc/bdc_udc.c b/drivers/usb/gadget/udc/bdc/bdc_udc.c index 7a12219edac6fd..88a8f6550e02f3 100644 --- a/drivers/usb/gadget/udc/bdc/bdc_udc.c +++ b/drivers/usb/gadget/udc/bdc/bdc_udc.c @@ -218,7 +218,8 @@ static void handle_link_state_change(struct bdc *bdc, u32 uspc) case BDC_LINK_STATE_RESUME: dev_dbg(bdc->dev, "Resumed from Suspend\n"); if (bdc->devstatus & DEVICE_SUSPENDED) { - bdc->gadget_driver->resume(&bdc->gadget); + if (bdc->gadget_driver->resume) + bdc->gadget_driver->resume(&bdc->gadget); bdc->devstatus &= ~DEVICE_SUSPENDED; } break; From 12b2057f6e6f5d7887cb9c3b3d2466514fee0f61 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:43 +0100 Subject: [PATCH 1148/2102] usbip: vudc: free the unlink item if the send fails v_send_ret() takes an item off udc->tx_queue, hands what it carries to v_send_ret_submit() or v_send_ret_unlink(), and frees only the item itself. v_send_ret_submit() releases its urbp on all paths behind the first check; v_send_ret_unlink() frees the struct v_unlink only after a complete send. When the connection breaks while a RET_UNLINK is being sent, the v_unlink is leaked. The reply has been built from it before the send: free it right after kernel_sendmsg(). Fixes: d62ba981a9de ("usbip: vudc: Add vudc_tx") Cc: stable Cc: Valentina Manea Cc: Shuah Khan Cc: Hongren Zheng Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261027-llm-usb-v1-3-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/usbip/vudc_tx.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/usb/usbip/vudc_tx.c b/drivers/usb/usbip/vudc_tx.c index 88edfbcc00350e..d78ff29e9654ba 100644 --- a/drivers/usb/usbip/vudc_tx.c +++ b/drivers/usb/usbip/vudc_tx.c @@ -59,13 +59,13 @@ static int v_send_ret_unlink(struct vudc *udc, struct v_unlink *unlink) ret = kernel_sendmsg(udc->ud.tcp_socket, &msg, iov, 1, txsize); + kfree(unlink); if (ret != txsize) { usbip_event_add(&udc->ud, VUDC_EVENT_ERROR_TCP); if (ret >= 0) return -EPIPE; return ret; } - kfree(unlink); return txsize; } From 0baf734efbcc833225e087a4b71bce5c9f402beb Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:55 +0100 Subject: [PATCH 1149/2102] usb: typec: mux: tusb1046: fix oops on accessory modes typec_set_mode() passes a state without an alternate mode, and the USB and accessory modes (TYPEC_MODE_USB2 ... TYPEC_MODE_DEBUG) start at TYPEC_STATE_MODAL like the states of the alternate modes. TCPM and UCSI set TYPEC_MODE_AUDIO or TYPEC_MODE_DEBUG when such an accessory is attached. tusb1046_mux_set() then reads state->alt->svid: plugging in an analog audio adapter is a NULL pointer dereference. The numbers must not reach the switch either: TYPEC_MODE_AUDIO has the value of TYPEC_DP_STATE_D. Without an alternate mode connect the SuperSpeed lanes for TYPEC_MODE_USB3 and disconnect them for the rest. Fixes: 7c561b8c3e83 ("usb: typec: mux: Add support for the TUSB1046 crosspoint switch") Cc: stable Cc: Romain Gantois Cc: Heikki Krogerus Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261027-llm-usb-v1-15-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/typec/mux/tusb1046.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/drivers/usb/typec/mux/tusb1046.c b/drivers/usb/typec/mux/tusb1046.c index 55a7b246f3f999..1e071e9193d82b 100644 --- a/drivers/usb/typec/mux/tusb1046.c +++ b/drivers/usb/typec/mux/tusb1046.c @@ -43,11 +43,17 @@ static int tusb1046_mux_set(struct typec_mux_dev *mux, struct tusb1046_priv *priv = typec_mux_get_drvdata(mux); struct i2c_client *client = priv->client; struct device *dev = &client->dev; + unsigned long req = state->mode; int mode, val, ret = 0; - if (state->mode >= TYPEC_STATE_MODAL && - state->alt->svid != USB_TYPEC_DP_SID) - return -EINVAL; + if (req >= TYPEC_STATE_MODAL) { + /* USB and accessory modes: not the DP pin assignments */ + if (!state->alt) + req = req == TYPEC_MODE_USB3 ? TYPEC_STATE_USB : + TYPEC_STATE_SAFE; + else if (state->alt->svid != USB_TYPEC_DP_SID) + return -EINVAL; + } dev_dbg(dev, "mux mode requested: %lu\n", state->mode); @@ -60,7 +66,7 @@ static int tusb1046_mux_set(struct typec_mux_dev *mux, goto out_unlock; } - switch (state->mode) { + switch (req) { case TYPEC_STATE_USB: mode = TUSB1046_CTLSEL_USB3; break; From ac78c8297a09ad31fae8020fbe8b51c0416c5a52 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:49 +0100 Subject: [PATCH 1150/2102] usb: gadget: f_fs: let the request keep its fence ffs_dmabuf_transfer() stores a plain pointer to the fence in the context of the USB request, and since the fix for the fence leak it drops the initial reference right after dma_resv_add_fence(). The only reference left is the one of the reservation object. That one does not last until the fence is signalled. dma_resv_add_fence() replaces and puts a fence as soon as a later fence of the same context and the same usage is added. All the fences of an attachment share a context, and a transfer on an IN endpoint only waits for the writers, not for the read fence of the transfer before it. So the second FUNCTIONFS_DMABUF_TRANSFER of a buffer which is still queued frees the fence of the first. When the first request completes, ffs_dmabuf_signal_done() signals a fence in freed memory and queues the work item in it. The leak came from the reference which ffs_dmabuf_signal_done() takes and ffs_dmabuf_cleanup() drops: with it nobody dropped the initial one. Do not take it, and leave the initial reference to the request until the cleanup. Fixes: baa6b6068a3f ("usb: gadget: f_fs: Fix DMA fence leak") Cc: stable Cc: Neill Kapron Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261027-llm-usb-v1-9-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_fs.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/drivers/usb/gadget/function/f_fs.c b/drivers/usb/gadget/function/f_fs.c index c64a268e98a433..26f511794d6fdb 100644 --- a/drivers/usb/gadget/function/f_fs.c +++ b/drivers/usb/gadget/function/f_fs.c @@ -1447,13 +1447,12 @@ static void ffs_dmabuf_signal_done(struct ffs_dma_fence *dma_fence, int ret) struct dma_fence *fence = &dma_fence->base; bool cookie = dma_fence_begin_signalling(); - dma_fence_get(fence); fence->error = ret; dma_fence_signal(fence); dma_fence_end_signalling(cookie); /* - * The fence will be unref'd in ffs_dmabuf_cleanup. + * The reference of the request will be dropped in ffs_dmabuf_cleanup. * It can't be done here, as the unref functions might try to lock * the resv object, which would deadlock. */ @@ -1737,8 +1736,13 @@ static int ffs_dmabuf_transfer(struct file *file, resv_dir = epfile->in ? DMA_RESV_USAGE_READ : DMA_RESV_USAGE_WRITE; + /* + * The reservation object takes a reference of its own, and drops it as + * soon as a later fence of this attachment takes the place of this + * one. The initial reference stays with the request, which points to + * the fence until ffs_dmabuf_cleanup() has run. + */ dma_resv_add_fence(dmabuf->resv, &fence->base, resv_dir); - dma_fence_put(&fence->base); dma_resv_unlock(dmabuf->resv); /* Now that the dma_fence is in place, queue the transfer. */ From 7b7f7dd39b967156dfbd49631a8ca3ff641b3653 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Tue, 27 Oct 2026 15:57:56 +0100 Subject: [PATCH 1151/2102] usb: renesas_usbhs: link URBs with interrupts disabled usb_hcd_link_urb_to_ep() and usb_hcd_unlink_urb_from_ep() are to be called under the lock of the host controller driver, with interrupts disabled. They take hcd_urb_list_lock with a plain spin_lock(). usbhsh_urb_enqueue() calls the first one without any lock, with interrupts enabled if the URB was submitted from process context. usbhsh_queue_done() calls the second one, mostly from the interrupt handler of the controller. The host mode is used on a uniprocessor board, where the spinlock is nothing. There the interrupt for a finished URB can come in the middle of the list_add_tail() for the next URB of the same endpoint, and its list_del_init() leaves the list of the endpoint corrupted. On an SMP kernel the CPU would wait for itself instead. usbhsh_queue_done() is also called from usbhsh_urb_dequeue() with interrupts enabled. Take the lock of the driver around both calls. Fixes: 034d7c13a79c ("usb: gadget: renesas_usbhs: add mod_host support") Cc: stable Signed-off-by: Josef Bacik Link: https://patch.msgid.link/20261027-llm-usb-v1-16-b9751ddb9c7c@linuxfoundation.org Signed-off-by: Greg Kroah-Hartman --- drivers/usb/renesas_usbhs/mod_host.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/usb/renesas_usbhs/mod_host.c b/drivers/usb/renesas_usbhs/mod_host.c index f7ef3a9f82a4b2..0652525d06feca 100644 --- a/drivers/usb/renesas_usbhs/mod_host.c +++ b/drivers/usb/renesas_usbhs/mod_host.c @@ -633,6 +633,7 @@ static void usbhsh_queue_done(struct usbhs_priv *priv, struct usbhs_pkt *pkt) struct usb_hcd *hcd = usbhsh_hpriv_to_hcd(hpriv); struct urb *urb = ureq->urb; struct device *dev = usbhs_priv_to_dev(priv); + unsigned long flags; int status = 0; dev_dbg(dev, "%s\n", __func__); @@ -652,7 +653,10 @@ static void usbhsh_queue_done(struct usbhs_priv *priv, struct usbhs_pkt *pkt) usbhsh_pipe_detach(hpriv, usbhsh_ep_to_uep(urb->ep)); + usbhs_lock(priv, flags); usb_hcd_unlink_urb_from_ep(hcd, urb); + usbhs_unlock(priv, flags); + usb_hcd_giveback_urb(hcd, urb, status); } @@ -955,6 +959,7 @@ static int usbhsh_urb_enqueue(struct usb_hcd *hcd, struct usb_host_endpoint *ep = urb->ep; struct usbhsh_device *new_udev = NULL; int is_dir_in = usb_pipein(urb->pipe); + unsigned long flags; int ret; dev_dbg(dev, "%s (%s)\n", __func__, is_dir_in ? "in" : "out"); @@ -965,7 +970,9 @@ static int usbhsh_urb_enqueue(struct usb_hcd *hcd, goto usbhsh_urb_enqueue_error_not_linked; } + usbhs_lock(priv, flags); ret = usb_hcd_link_urb_to_ep(hcd, urb); + usbhs_unlock(priv, flags); if (ret) { dev_err(dev, "urb link failed\n"); goto usbhsh_urb_enqueue_error_not_linked; From e0ae3c49e0b3d6b586da5257ffbb94895235dff0 Mon Sep 17 00:00:00 2001 From: Daniele Palmas Date: Mon, 12 Oct 2026 11:27:30 +0200 Subject: [PATCH 1152/2102] USB: cdc-acm: add control line state quirk for Telit QCX216 modems Add control line state quirk for the diagnostic port of the compositions exposed by Telit QCX216-based modems, since the control line state requests prevent the modem from sending the diagnostic data. Signed-off-by: Daniele Palmas Link: https://patch.msgid.link/20261012092730.332531-1-dnlplm@gmail.com Cc: stable Signed-off-by: Greg Kroah-Hartman --- drivers/usb/class/cdc-acm.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/drivers/usb/class/cdc-acm.c b/drivers/usb/class/cdc-acm.c index 666969ffd19449..4a0c7806fc0b45 100644 --- a/drivers/usb/class/cdc-acm.c +++ b/drivers/usb/class/cdc-acm.c @@ -2049,6 +2049,18 @@ static const struct usb_device_id acm_ids[] = { { USB_DEVICE(0x1bc7, 0x0023), /* Telit 3G ACM + ECM composition */ .driver_info = SEND_ZERO_PACKET, }, + { USB_DEVICE_INTERFACE_NUMBER(0x1bc7, 0x7020, 4), /* Telit LE910Q1 (RNDIS) diag port */ + .driver_info = QUIRK_CONTROL_LINE_STATE, + }, + { USB_DEVICE_INTERFACE_NUMBER(0x1bc7, 0x7021, 4), /* Telit LE910Q1 (ECM) diag port */ + .driver_info = QUIRK_CONTROL_LINE_STATE, + }, + { USB_DEVICE_INTERFACE_NUMBER(0x1bc7, 0x7028, 4), /* Telit LE310Q1 (RNDIS) diag port */ + .driver_info = QUIRK_CONTROL_LINE_STATE, + }, + { USB_DEVICE_INTERFACE_NUMBER(0x1bc7, 0x7029, 4), /* Telit LE310Q1 (ECM) diag port */ + .driver_info = QUIRK_CONTROL_LINE_STATE, + }, /* Exclude Goodix Fingerprint Reader */ { USB_DEVICE(0x27c6, 0x5395), From b92566b2648c5661a571f693336dba7a32d5dc3b Mon Sep 17 00:00:00 2001 From: "William A. Kennington III" Date: Fri, 20 Nov 2026 07:03:53 +0000 Subject: [PATCH 1153/2102] USB: cdc-acm: refuse writes after disconnect Commit 7fb57a019f94 ("USB: cdc-acm: Fix potential deadlock (lockdep warning)") stopped clearing acm->dev in acm_disconnect() and replaced ACM_READY() with acm->disconnected, but left the write path checking !acm->dev and dropped the disconnect check from acm_tty_write_room(). Because acm_disconnect() frees the write buffers with usb_free_coherent() and acm_probe() only pins acm->control, a late acm_tty_write() call dereferences freed memory. This can happen when a CDC-ACM device disconnects while a file descriptor remains open with a line discipline such as mctp-serial attached. Hangup closes the line discipline, but a subsequent reopen of the hung-up TTY calls tty_reopen() -> tty_ldisc_reinit() from the saved c_line before acm_tty_open() fails with -ENODEV. Because the original descriptor keeps tty->count non-zero, the reinitialized mctp-serial instance stays attached and faults in memcpy() inside acm_tty_write() on the freed wb->buf when transmitting. Pin acm->data alongside acm->control until acm_port_destruct() so the unlocked dev_vdbg() in acm_tty_write() stays valid across disconnect, check acm->disconnected at the start of the write_lock critical section, report zero room in acm_tty_write_room() once disconnected, and set acm->disconnected under write_lock in acm_disconnect() so any concurrent writer finishes before the URBs are poisoned and the buffers are freed. Fixes: 7fb57a019f94 ("USB: cdc-acm: Fix potential deadlock (lockdep warning)") Cc: stable Signed-off-by: William A. Kennington III Acked-by: Oliver Neukum Link: https://patch.msgid.link/20261120070353.956978-1-william@wkennington.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/class/cdc-acm.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/drivers/usb/class/cdc-acm.c b/drivers/usb/class/cdc-acm.c index 4a0c7806fc0b45..44f69016238433 100644 --- a/drivers/usb/class/cdc-acm.c +++ b/drivers/usb/class/cdc-acm.c @@ -762,6 +762,7 @@ static void acm_port_destruct(struct tty_port *port) if (acm->minor != ACM_MINOR_INVALID) acm_release_minor(acm); usb_put_intf(acm->control); + usb_put_intf(acm->data); kfree(acm->country_codes); kfree(acm); } @@ -848,6 +849,11 @@ static ssize_t acm_tty_write(struct tty_struct *tty, const u8 *buf, dev_vdbg(&acm->data->dev, "%zu bytes from tty layer\n", count); spin_lock_irqsave(&acm->write_lock, flags); + if (acm->disconnected) { + spin_unlock_irqrestore(&acm->write_lock, flags); + return -ENODEV; + } + wbn = acm_wb_alloc(acm); if (wbn < 0) { spin_unlock_irqrestore(&acm->write_lock, flags); @@ -855,12 +861,6 @@ static ssize_t acm_tty_write(struct tty_struct *tty, const u8 *buf, } wb = &acm->wb[wbn]; - if (!acm->dev) { - wb->use = false; - spin_unlock_irqrestore(&acm->write_lock, flags); - return -ENODEV; - } - count = (count > acm->writesize) ? acm->writesize : count; dev_vdbg(&acm->data->dev, "writing %zu bytes\n", count); memcpy(wb->buf, buf, count); @@ -890,6 +890,9 @@ static ssize_t acm_tty_write(struct tty_struct *tty, const u8 *buf, static unsigned int acm_tty_write_room(struct tty_struct *tty) { struct acm *acm = tty->driver_data; + + if (acm->disconnected) + return 0; /* * Do not let the line discipline to know that we have a reserve, * or it might get too enthusiastic. @@ -1400,6 +1403,7 @@ static int acm_probe(struct usb_interface *intf, acm->data = data_interface; usb_get_intf(acm->control); /* undone in destruct() */ + usb_get_intf(acm->data); minor = acm_alloc_minor(acm); if (minor < 0) { @@ -1627,7 +1631,9 @@ static void acm_disconnect(struct usb_interface *intf) if (!acm) return; + spin_lock_irq(&acm->write_lock); acm->disconnected = true; + spin_unlock_irq(&acm->write_lock); /* * there is a circular dependency. acm_softint() can resubmit * the URBs in error handling so we need to block any From 187b32cd9db4d514b3062ac6647c105ef6a12d15 Mon Sep 17 00:00:00 2001 From: Haowen Bai Date: Mon, 14 Sep 2026 10:27:43 +0800 Subject: [PATCH 1154/2102] usb: pci-quirks: abort xHCI handoff if MMIO is inaccessible The xHCI early handoff quirk polls the BIOS ownership, CNR, and HALT bits with readl_poll_timeout_atomic(). Unlike xhci_handshake(), handshake() does not treat an all-ones read as an inaccessible controller. If the controller becomes inaccessible, readl() can return U32_MAX. The CNR bit then never clears, and the atomic poll keeps retrying. The atomic poll budget is decremented using the requested delay and loop iterations, but not the time spent in readl(). Slow failed MMIO reads can therefore keep the PCI hotplug thread spinning far beyond the nominal timeout and trigger a soft lockup. The 26-second value in the first warning is the watchdog threshold, not the handshake timeout; repeated warnings showed the thread still stuck up to 260 seconds before a controlled reboot, leaving the system unavailable to normal management. Comparing the watchdog timestamps with the RBP loop counter in the dumps (about 1,372 iterations in 26 s and 15,638 in 260 s) implies roughly 16-19 ms per polling iteration, despite configured 10 us delay; these values are inferred, not direct measurements of an individual readl(). Return -ENODEV when the polled register reads U32_MAX and stop the handoff before issuing further accesses. This prevents an inaccessible xHCI from keeping the PCI hotplug thread busy and making the system unavailable. An eGPU may still fail to enumerate, but that failure must remain controlled rather than causing a kernel Soft Lockup and taking down SSH or desktop management. The existing timeout behavior for non-all-ones reads is preserved, matching xhci_handshake(). A Thunderbolt-attached AMD Radeon Pro W5700 in a Razer Core X enclosure reproduced this on an x86_64 UGREEN DXP8800 Plus with an Intel Core i5-1235U. The GPU's xHCI function 0000:06:00.2 (1002:7316) triggered the soft lockup in irq/123-pciehp; the register dump contained RAX=U32_MAX: watchdog: BUG: soft lockup - CPU#6 stuck for 26s! [irq/123-pciehp:139] RIP: 0010:quirk_usb_early_handoff+0x552/0x7e0 register state: RAX=00000000ffffffff The call trace was: pci_do_fixups pci_bus_add_device pci_bus_add_devices pciehp_configure_device pciehp_handle_presence_or_link_change pciehp_ist irq_thread_fn The failure reproduced on two hot-plug attempts and did not occur when the enclosure was connected before boot. Fixes: 66d4eadd8d06 ("USB: xhci: BIOS handoff and HW initialization.") Cc: stable Acked-by: Mathias Nyman Signed-off-by: Haowen Bai Link: https://patch.msgid.link/02C44DCEA968C75D+20260914022743.30852-1-calvin.bai@ugreen.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/host/pci-quirks.c | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/drivers/usb/host/pci-quirks.c b/drivers/usb/host/pci-quirks.c index 1dbfd697a58200..6a40d3ab43b597 100644 --- a/drivers/usb/host/pci-quirks.c +++ b/drivers/usb/host/pci-quirks.c @@ -1026,15 +1026,22 @@ static void quirk_usb_disable_ehci(struct pci_dev *pdev) * Returns 0 when the mask bits have the value done. * Returns -ETIMEDOUT if this condition is not true after * wait_usec microseconds have passed. + * Returns -ENODEV if the register reads as all-ones (hardware removed). */ static int handshake(void __iomem *ptr, u32 mask, u32 done, int wait_usec, int delay_usec) { u32 result; + int ret; - return readl_poll_timeout_atomic(ptr, result, - ((result & mask) == done), - delay_usec, wait_usec); + ret = readl_poll_timeout_atomic(ptr, result, + (result & mask) == done || + PCI_POSSIBLE_ERROR(result), + delay_usec, wait_usec); + if (PCI_POSSIBLE_ERROR(result)) + return -ENODEV; + + return ret; } /* @@ -1206,6 +1213,9 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) timeout = handshake(base + ext_cap_offset, XHCI_HC_BIOS_OWNED, 0, 1000000, 10); + if (timeout == -ENODEV) + goto iounmap; + /* Assume a buggy BIOS and take HC ownership anyway */ if (timeout) { dev_warn(&pdev->dev, @@ -1236,6 +1246,9 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) */ timeout = handshake(op_reg_base + XHCI_STS_OFFSET, XHCI_STS_CNR, 0, 5000000, 10); + if (timeout == -ENODEV) + goto iounmap; + /* Assume a buggy HC and start HC initialization anyway */ if (timeout) { val = readl(op_reg_base + XHCI_STS_OFFSET); @@ -1252,6 +1265,9 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) /* Wait for the HC to halt - poll every 125 usec (one microframe). */ timeout = handshake(op_reg_base + XHCI_STS_OFFSET, XHCI_STS_HALT, 1, XHCI_MAX_HALT_USEC, 125); + if (timeout == -ENODEV) + goto iounmap; + if (timeout) { val = readl(op_reg_base + XHCI_STS_OFFSET); dev_warn(&pdev->dev, From d3c108c095712a3b7eab292ef7ea9a57ff5cd5d7 Mon Sep 17 00:00:00 2001 From: Zhang Shurong Date: Mon, 12 Oct 2026 14:30:21 +0200 Subject: [PATCH 1155/2102] dmaengine: rcar-dmac: Fix PM usage counter imbalance pm_runtime_get_sync will increment pm usage counter even it failed. Forgetting to putting operation will result in reference leak here. We fix it by replacing it with pm_runtime_resume_and_get to keep usage counter balanced. Fixes: 87244fe5abdf ("dmaengine: rcar-dmac: Add Renesas R-Car Gen2 DMA Controller (DMAC) driver") Signed-off-by: Zhang Shurong Reviewed-by: Geert Uytterhoeven Reviewed-by: Frank Li Reviewed-by: Laurent Pinchart Signed-off-by: Wolfram Sang Link: https://patch.msgid.link/20261012123020.11320-6-wsa+renesas@sang-engineering.com Signed-off-by: Vinod Koul --- drivers/dma/sh/rcar-dmac.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/dma/sh/rcar-dmac.c b/drivers/dma/sh/rcar-dmac.c index 3ad8aba5dcd403..5b54f1c4ce153c 100644 --- a/drivers/dma/sh/rcar-dmac.c +++ b/drivers/dma/sh/rcar-dmac.c @@ -1070,7 +1070,7 @@ static int rcar_dmac_alloc_chan_resources(struct dma_chan *chan) if (ret < 0) return -ENOMEM; - return pm_runtime_get_sync(chan->device->dev); + return pm_runtime_resume_and_get(chan->device->dev); } static void rcar_dmac_free_chan_resources(struct dma_chan *chan) From 0ca154b10168d8874b871edf5510640c51b326c3 Mon Sep 17 00:00:00 2001 From: Koichiro Den Date: Mon, 12 Oct 2026 14:30:22 +0200 Subject: [PATCH 1156/2102] dmaengine: rcar-dmac: Add missing dma_descriptor_unmap() Call dma_descriptor_unmap() right before dma_cookie_complete() in the threaded IRQ completion path. Without this, streaming DMA mappings attached to the descriptor are never released and may eventually exhaust DMA mapping resources (e.g. IOVA with an IOMMU or bounce-buffer slots with SWIOTLB), leading to dma_map_* failures. Also ensure dma_descriptor_unmap() is called in rcar_dmac_chan_reinit() (error/terminate path) to avoid the same type of leaks. Fixes: 87244fe5abdf ("dmaengine: rcar-dmac: Add Renesas R-Car Gen2 DMA Controller (DMAC) driver") Signed-off-by: Koichiro Den [wsa: moved unmap before cookie completion, added Fixes tag] Signed-off-by: Wolfram Sang Reviewed-by: Frank Li Link: https://patch.msgid.link/20261012123020.11320-7-wsa+renesas@sang-engineering.com Signed-off-by: Vinod Koul --- drivers/dma/sh/rcar-dmac.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/dma/sh/rcar-dmac.c b/drivers/dma/sh/rcar-dmac.c index 5b54f1c4ce153c..78a913c4c0d81b 100644 --- a/drivers/dma/sh/rcar-dmac.c +++ b/drivers/dma/sh/rcar-dmac.c @@ -844,6 +844,7 @@ static void rcar_dmac_chan_reinit(struct rcar_dmac_chan *chan) list_for_each_entry_safe(desc, _desc, &descs, node) { list_del(&desc->node); + dma_descriptor_unmap(&desc->async_tx); rcar_dmac_desc_put(chan, desc); } } @@ -1653,6 +1654,7 @@ static irqreturn_t rcar_dmac_isr_channel_thread(int irq, void *dev) while (!list_empty(&chan->desc.done)) { desc = list_first_entry(&chan->desc.done, struct rcar_dmac_desc, node); + dma_descriptor_unmap(&desc->async_tx); dma_cookie_complete(&desc->async_tx); list_del(&desc->node); From d460a02aa0ac6ba9e5d87f8462f75d78be83146e Mon Sep 17 00:00:00 2001 From: Pan Chuang Date: Mon, 12 Oct 2026 14:30:23 +0200 Subject: [PATCH 1157/2102] dmaengine: rcar-dmac: Remove redundant dev_err()/dev_err_probe() The devm_request_threaded_irq() now automatically logs detailed error messages on failure. This eliminates the need for driver-specific dev_err() and dev_err_probe() calls that previously printed generic messages. Signed-off-by: Pan Chuang Reviewed-by: Geert Uytterhoeven Reviewed-by: Frank Li Signed-off-by: Wolfram Sang Link: https://patch.msgid.link/20261012123020.11320-8-wsa+renesas@sang-engineering.com Signed-off-by: Vinod Koul --- drivers/dma/sh/rcar-dmac.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/drivers/dma/sh/rcar-dmac.c b/drivers/dma/sh/rcar-dmac.c index 78a913c4c0d81b..73b15045ad9230 100644 --- a/drivers/dma/sh/rcar-dmac.c +++ b/drivers/dma/sh/rcar-dmac.c @@ -1797,11 +1797,8 @@ static int rcar_dmac_chan_probe(struct rcar_dmac *dmac, rcar_dmac_isr_channel, rcar_dmac_isr_channel_thread, 0, irqname, rchan); - if (ret) { - dev_err(dmac->dev, "failed to request IRQ %u (%d)\n", - rchan->irq, ret); + if (ret) return ret; - } return 0; } From 00f445721c7f0e48aaff9813cfe1c065c6eb3b71 Mon Sep 17 00:00:00 2001 From: Sergio Lopez Date: Fri, 13 Nov 2026 18:04:40 +0100 Subject: [PATCH 1158/2102] vsock/vmci: reject datagram binds in local network namespaces VMCI already rejects datagram sends from local network namespaces, but a datagram bind still creates a receive handle in VMCI's global port space. A VMCI sender outside the namespace can therefore deliver to the local socket. Its handle also prevents a global-namespace socket from binding the same port. Reject VMCI datagram binds in local namespaces. No namespace-local datagram transport exists, so EOPNOTSUPP reflects the available receive paths. The receive callback also rejects any local-mode socket as a defensive check. In a KASAN/lockdep QEMU guest, a reproducer observed cross-namespace delivery and the global port collision before the fix. After the fix, local bind returns EOPNOTSUPP, the global bind succeeds, and a global VMCI datagram still reaches the global socket. Fixes: eafb64f40ca4 ("vsock: add netns to vsock core") Cc: stable@vger.kernel.org Link: https://lore.kernel.org/all/sashiko-outbox-212907@kernel.org/ Signed-off-by: Sergio Lopez Acked-by: Bobby Eshleman Signed-off-by: Dave Miller --- net/vmw_vsock/vmci_transport.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/net/vmw_vsock/vmci_transport.c b/net/vmw_vsock/vmci_transport.c index 1f186e8f83640a..282131544c42ba 100644 --- a/net/vmw_vsock/vmci_transport.c +++ b/net/vmw_vsock/vmci_transport.c @@ -627,6 +627,8 @@ static int vmci_transport_recv_dgram_cb(void *data, struct vmci_datagram *dg) * outside of the create and destruct socket functions. */ vsk = vsock_sk(sk); + if (!vsock_net_mode_global(vsk)) + return VMCI_ERROR_NO_ACCESS; if (!vmci_transport_allow_dgram(vsk, dg->src.context)) return VMCI_ERROR_NO_ACCESS; @@ -1697,6 +1699,10 @@ static int vmci_transport_dgram_bind(struct vsock_sock *vsk, u32 flags; int err; + /* VMCI handles are global and cannot serve local namespaces. */ + if (!vsock_net_mode_global(vsk)) + return -EOPNOTSUPP; + /* VMCI will select a resource ID for us if we provide * VMCI_INVALID_ID. */ From 32797261f6cb66c3b4cf4f20ace750064801084e Mon Sep 17 00:00:00 2001 From: Neill Kapron Date: Fri, 24 Jul 2026 21:56:14 +0000 Subject: [PATCH 1159/2102] usb: gadget: f_fs: Fix -Wformat-truncation in proxy endpoint names When using the functionfs rw_proxy feature, proxy endpoint names are generated by appending "_rw" to the base endpoint name. The base endpoint name is copied via `snprintf` into an 8-byte buffer (`comp->name`). On some architectures (e.g., s390), the compiler flags a `-Wformat-truncation` warning because `%s_rw` could potentially overflow if the source string is unexpectedly long. Fix this by specifying a maximum field width of 4 characters when formatting the endpoint name string. This guarantees that at most 4 characters plus the 3 characters "_rw" (and null terminator) will be written, fitting within the 8-byte limit. Note that this is purely to address the compiler static analysis. In practice, `FFS_MAX_EPS_COUNT` is limited to 31, meaning the longest possible base endpoint name is "ep30", and therefore the resulting proxy name, "ep30_rw", is exactly 7 characters. Fixes: 0f0ea552cd21 ("usb: gadget: f_fs: Introduce rw_proxy file descriptors") Cc: stable Reported-by: kernel test robot Closes: https://lore.kernel.org/oe-kbuild-all/202607111052.PRRGX3Jq-lkp@intel.com/ Assisted-by: Antigravity:gemini-3.1-pro Signed-off-by: Neill Kapron Link: https://patch.msgid.link/20260724215615.4160303-1-nkapron@google.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_fs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/usb/gadget/function/f_fs.c b/drivers/usb/gadget/function/f_fs.c index 26f511794d6fdb..2d5646da15a662 100644 --- a/drivers/usb/gadget/function/f_fs.c +++ b/drivers/usb/gadget/function/f_fs.c @@ -2466,7 +2466,7 @@ static int ffs_epfiles_create(struct ffs_data *ffs) mutex_init(&comp->mutex); mutex_init(&comp->dmabufs_mutex); INIT_LIST_HEAD(&comp->dmabufs); - snprintf(comp->name, sizeof(comp->name), "%s_rw", + snprintf(comp->name, sizeof(comp->name), "%.4s_rw", epfiles[i].name); err = ffs_sb_create_file(ffs->sb, comp->name, comp, &ffs_epfile_operations); From cb1c6d7e59eb120dcc4e81c50019111572f69fb0 Mon Sep 17 00:00:00 2001 From: Yu Zhang Date: Tue, 20 Oct 2026 15:14:46 +1000 Subject: [PATCH 1160/2102] usb: gadget: f_hid: avoid copy_from_user() under get_report_spinlock f_hidg_get_report() copies the userspace report into a freshly allocated 'entry' before taking get_report_spinlock. When the report id is already present in the list it then copies the same userspace buffer a second time into the existing entry, this time while holding get_report_spinlock (acquired with spin_lock_irqsave()): spin_lock_irqsave(&hidg->get_report_spinlock, flags); ptr = f_hidg_search_for_report(hidg, report_id); if (ptr) { if (copy_from_user(&ptr->report_data, buffer, sizeof(struct usb_hidg_report))) { copy_from_user() may fault and sleep, which is not allowed while holding a spinlock with interrupts disabled: BUG: sleeping function called from invalid context at ./include/linux/uaccess.h:169 in_atomic(): 1, irqs_disabled(): 1, non_block: 0, pid: 3481, name: hidg_getreport __might_fault+0x4d/0x60 f_hidg_get_report+0x155/0x310 f_hidg_ioctl+0xbd/0xe0 __x64_sys_ioctl+0x120/0x170 do_syscall_64+0xf9/0x540 This is reached by issuing GADGET_HID_WRITE_GET_REPORT twice for the same report id (the first call inserts the entry, the second takes the update path). On a non-debug kernel a userspace buffer crafted to fault (e.g. via userfaultfd) would sleep with the spinlock held and interrupts disabled. The data has already been copied into 'entry' before the lock is taken, so reuse it instead of copying from userspace again under the lock. This also drops a redundant second read of the user buffer. Fixes: a139c98f760e ("USB: gadget: f_hid: Add GET_REPORT via userspace IOCTL") Cc: stable@vger.kernel.org Signed-off-by: Yu Zhang Reviewed-by: Neill Kapron Link: https://patch.msgid.link/20261020051446.92179-1-yuz08559@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_hid.c | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/drivers/usb/gadget/function/f_hid.c b/drivers/usb/gadget/function/f_hid.c index 3c6b43d06a6d1d..520892bbfbef68 100644 --- a/drivers/usb/gadget/function/f_hid.c +++ b/drivers/usb/gadget/function/f_hid.c @@ -668,13 +668,7 @@ static int f_hidg_get_report(struct file *file, struct usb_hidg_report __user *b if (ptr) { /* Report already exists in list - update it */ - if (copy_from_user(&ptr->report_data, buffer, - sizeof(struct usb_hidg_report))) { - spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); - ERROR(cdev, "copy_from_user error\n"); - kfree(entry); - return -EINVAL; - } + ptr->report_data = entry->report_data; kfree(entry); } else { /* Report does not exist in list - add it */ From cea2b866edae835cc272cb7ac5b4cc5f99db3ae3 Mon Sep 17 00:00:00 2001 From: Chengyu Liu Date: Fri, 13 Nov 2026 14:34:06 +0800 Subject: [PATCH 1161/2102] usb: musb: cancel the delayed works after quiescing the interrupt musb_remove() cancels finish_resume_work and deassert_reset_work up front, while the interrupt is still enabled and the root hub is still registered, and cancels irq_work only later. All three works can be armed past their cancel: - musb_handle_intr_resume() schedules finish_resume_work from interrupt context (RESUME in OTG_STATE_A_SUSPEND, via musb_stage0_irq()); - musb_hub_control() schedules finish_resume_work (ClearPortFeature SUSPEND -> musb_port_suspend()) and deassert_reset_work (SetPortFeature RESET -> musb_port_reset()) from process context, and the root hub is only torn down by musb_host_cleanup(); - musb_stage0_irq() schedules irq_work, which can also re-arm itself from the session recheck path (musb_pm_runtime_check_session()). A work armed after its cancel runs musb_host_finish_resume(), musb_deassert_reset() or musb_irq_work() after musb_free() has released the struct. Tear down the host and gadget sides first so no process-context producer remains, mask the interrupts and synchronize the IRQ line so no interrupt handler can be running, and only then cancel all three works. This also restores the pre-f730f205cc51 ordering, which had the cancels behind the interrupt masking. Found by static analysis. Suggested-by: Neill Kapron Fixes: f730f205cc51 ("usb: musb: Split PM runtime between wrapper IP and musb core") Cc: stable@vger.kernel.org Signed-off-by: Chengyu Liu Reviewed-by: Neill Kapron Link: https://patch.msgid.link/20261113063409.47485-2-lui2012qwq@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/musb/musb_core.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/drivers/usb/musb/musb_core.c b/drivers/usb/musb/musb_core.c index 9b63b56edc4531..25115217e0af6e 100644 --- a/drivers/usb/musb/musb_core.c +++ b/drivers/usb/musb/musb_core.c @@ -2630,9 +2630,6 @@ static void musb_remove(struct platform_device *pdev) */ musb_exit_debugfs(musb); - cancel_delayed_work_sync(&musb->irq_work); - cancel_delayed_work_sync(&musb->finish_resume_work); - cancel_delayed_work_sync(&musb->deassert_reset_work); pm_runtime_get_sync(musb->controller); musb_host_cleanup(musb); musb_gadget_cleanup(musb); @@ -2642,6 +2639,18 @@ static void musb_remove(struct platform_device *pdev) musb_disable_interrupts(musb); musb_writeb(musb->mregs, MUSB_DEVCTL, 0); spin_unlock_irqrestore(&musb->lock, flags); + + /* + * musb_stage0_irq() arms irq_work (and finish_resume_work on + * remote wakeup) from interrupt context, so the works can only be + * cancelled for good once interrupts are masked and any in-flight + * handler has completed. + */ + synchronize_irq(musb->nIrq); + cancel_delayed_work_sync(&musb->irq_work); + cancel_delayed_work_sync(&musb->finish_resume_work); + cancel_delayed_work_sync(&musb->deassert_reset_work); + musb_platform_exit(musb); pm_runtime_dont_use_autosuspend(musb->controller); From 689f6a638d2e0dd977ac1fe0986a9399ba242504 Mon Sep 17 00:00:00 2001 From: Chengyu Liu Date: Fri, 13 Nov 2026 14:34:07 +0800 Subject: [PATCH 1162/2102] usb: musb: dsps: free the VBUS interrupt before the child teardown dsps_remove() unregisters the musb child, which deletes musb->dev_timer and frees the structure, while the glue's VBUS interrupt is devm-managed and only freed after dsps_remove() returns. dsps_vbus_threaded_irq() re-arms the timer via dsps_mod_timer(), so a VBUS event in between re-arms dev_timer past its deletion and otg_timer() runs on freed memory. Free the VBUS interrupt first, which also waits for any in-flight handler, so nothing can re-arm the timer once the child teardown runs. Found by static analysis. Fixes: 369469a92393 ("usb: musb: Add support for optional VBUS irq to dsps glue layer") Cc: stable@vger.kernel.org Reviewed-by: Neill Kapron Signed-off-by: Chengyu Liu Link: https://patch.msgid.link/20261113063409.47485-3-lui2012qwq@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/musb/musb_dsps.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/drivers/usb/musb/musb_dsps.c b/drivers/usb/musb/musb_dsps.c index 91d8712efa41b1..69c8b4b3ffa76a 100644 --- a/drivers/usb/musb/musb_dsps.c +++ b/drivers/usb/musb/musb_dsps.c @@ -942,6 +942,17 @@ static void dsps_remove(struct platform_device *pdev) { struct dsps_glue *glue = platform_get_drvdata(pdev); + /* + * The VBUS interrupt handler re-arms musb->dev_timer via + * dsps_mod_timer(); the IRQ is devm-managed and would only be + * freed after this function returns, while the child teardown + * below deletes the timer and frees the musb structure. Free + * the interrupt first so no VBUS event can re-arm the timer + * past that point. + */ + if (glue->vbus_irq) + devm_free_irq(glue->dev, glue->vbus_irq, glue); + platform_device_unregister(glue->musb); pm_runtime_disable(&pdev->dev); From e1af5eba00a4fd13a8e638eefaa00e00e3d7fa1c Mon Sep 17 00:00:00 2001 From: Chengyu Liu Date: Fri, 13 Nov 2026 14:34:08 +0800 Subject: [PATCH 1163/2102] usb: gadget: r8a66597: free the IRQ before deleting the timer r8a66597_remove() deletes r8a66597->timer while the interrupt is still live: the IRQ is devm-managed and only freed at detach, and r8a66597_irq() re-arms the timer when sampling VBUS (VBINT). An interrupt landing after timer_delete_sync() re-arms the timer, and r8a66597_timer() then runs on freed memory. Store the requested IRQ number at probe time and free it before deleting the timer; freeing also waits for any running handler, so nothing can re-arm the timer past the delete. Found by static analysis. Fixes: c41442474a26 ("usb: gadget: R8A66597 peripheral controller support.") Cc: stable@vger.kernel.org Reviewed-by: Neill Kapron Signed-off-by: Chengyu Liu Link: https://patch.msgid.link/20261113063409.47485-4-lui2012qwq@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/udc/r8a66597-udc.c | 8 ++++++++ drivers/usb/gadget/udc/r8a66597-udc.h | 1 + 2 files changed, 9 insertions(+) diff --git a/drivers/usb/gadget/udc/r8a66597-udc.c b/drivers/usb/gadget/udc/r8a66597-udc.c index 469075b064baf2..bfccc6565e0a3a 100644 --- a/drivers/usb/gadget/udc/r8a66597-udc.c +++ b/drivers/usb/gadget/udc/r8a66597-udc.c @@ -1810,6 +1810,13 @@ static void r8a66597_remove(struct platform_device *pdev) struct r8a66597 *r8a66597 = platform_get_drvdata(pdev); usb_del_gadget_udc(&r8a66597->gadget); + + /* + * The interrupt handler re-arms the timer on VBUS changes; the + * IRQ is devm-managed and freed only at detach, so free it + * before deleting the timer. + */ + devm_free_irq(&pdev->dev, r8a66597->irq, r8a66597); timer_delete_sync(&r8a66597->timer); r8a66597_free_request(&r8a66597->ep[0].ep, r8a66597->ep0_req); @@ -1896,6 +1903,7 @@ static int r8a66597_probe(struct platform_device *pdev) udc_name, r8a66597); if (ret < 0) goto clean_up2; + r8a66597->irq = irq; INIT_LIST_HEAD(&r8a66597->gadget.ep_list); r8a66597->gadget.ep0 = &r8a66597->ep[0].ep; diff --git a/drivers/usb/gadget/udc/r8a66597-udc.h b/drivers/usb/gadget/udc/r8a66597-udc.h index 9a115caba66107..08acabe02421de 100644 --- a/drivers/usb/gadget/udc/r8a66597-udc.h +++ b/drivers/usb/gadget/udc/r8a66597-udc.h @@ -110,6 +110,7 @@ struct r8a66597 { unsigned char interrupt; unsigned char isochronous; unsigned char num_dma; + int irq; unsigned irq_sense_low:1; }; From cee5aea1d1e98c1e29d74a72058013eb1cfec4f4 Mon Sep 17 00:00:00 2001 From: Chengyu Liu Date: Fri, 13 Nov 2026 14:34:09 +0800 Subject: [PATCH 1164/2102] usb: phy: gpio-vbus: free the interrupt before cancelling the work gpio_vbus_remove() cancels gpio_vbus->work while the VBUS sensing GPIO interrupt is still live: it is devm-managed and freed only at detach, and gpio_vbus_irq() schedules the work with a 100 ms debounce delay. A plug event landing after the cancel re-arms the work, and its timer then fires on the freed gpio_vbus_data. Free the interrupt first, which also waits for any running handler, so nothing can re-arm the work past the cancel. Found by static analysis and confirmed with a KASAN reproducer: slab-use-after-free write in __run_timer_base() within one debounce interval of unregistering the device while its VBUS GPIO is toggled (object allocated by gpio_vbus_probe() via devm_kmalloc(), freed by devres_release_all() at unbind). Fixes: c2344f13b59e ("USB: gpio_vbus: add delayed vbus_session calls") Cc: stable@vger.kernel.org Reviewed-by: Neill Kapron Signed-off-by: Chengyu Liu Link: https://patch.msgid.link/20261113063409.47485-5-lui2012qwq@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/phy/phy-gpio-vbus-usb.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/usb/phy/phy-gpio-vbus-usb.c b/drivers/usb/phy/phy-gpio-vbus-usb.c index 60b7c1219dd2c7..82d2301c380422 100644 --- a/drivers/usb/phy/phy-gpio-vbus-usb.c +++ b/drivers/usb/phy/phy-gpio-vbus-usb.c @@ -325,6 +325,14 @@ static void gpio_vbus_remove(struct platform_device *pdev) struct gpio_vbus_data *gpio_vbus = platform_get_drvdata(pdev); device_init_wakeup(&pdev->dev, 0); + + /* + * The VBUS sensing GPIO interrupt is devm-managed and freed only + * at detach, and its handler schedules the work with a 100ms + * delay; free the interrupt before cancelling the work so a + * late plug event cannot re-arm it past the cancel. + */ + devm_free_irq(&pdev->dev, gpio_vbus->irq, pdev); cancel_delayed_work_sync(&gpio_vbus->work); usb_remove_phy(&gpio_vbus->phy); From 101813b8015a53f0e7d118f4e201ec368e7902fa Mon Sep 17 00:00:00 2001 From: Ingo Rohloff Date: Mon, 9 Nov 2026 11:37:14 +0100 Subject: [PATCH 1165/2102] usb: gadget: f_fs: Fix mmgrab()/mmdrop() balance. This fixes commit 5eb5c72c72fe ("USB: gadget: ffs: fix mm lifetime handling"). The problem is that the previous patch calls mmgrab() for reads and writes, but it only calls mmdrop() for reads. So with each completed async IO write (via an USB IN endpoint) the number of mm_count increases. Signed-off-by: Ingo Rohloff Link: https://lore.kernel.org/r/20260901120908.14386-4-ingo.rohloff@lauterbach.com Fixes: 5eb5c72c72fe ("USB: gadget: ffs: fix mm lifetime handling") Cc: stable Acked-by: Neill Kapron Reviewed-by: Hongyu Xie Reviewed-by: Neill Kapron Link: https://patch.msgid.link/20261109103714.4000-1-ingo.rohloff@lauterbach.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_fs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/usb/gadget/function/f_fs.c b/drivers/usb/gadget/function/f_fs.c index 2d5646da15a662..282f6dc88b1c67 100644 --- a/drivers/usb/gadget/function/f_fs.c +++ b/drivers/usb/gadget/function/f_fs.c @@ -884,8 +884,8 @@ static void ffs_user_copy_worker(struct work_struct *work) } else { ret = -EFAULT; } - mmdrop(io_data->mm); } + mmdrop(io_data->mm); io_data->kiocb->ki_complete(io_data->kiocb, ret); From 7d242cc34b6f96e5f726754d746721ffc40318bb Mon Sep 17 00:00:00 2001 From: Ingo Rohloff Date: Thu, 19 Nov 2026 16:19:41 +0100 Subject: [PATCH 1166/2102] usb: gadget: f_fs: register cancellation handler only after request queueing Call kiocb_set_cancel_fn() only after usb_ep_queue() completes successfully. This also undoes commit e78dcb1f7ec2 ("usb: gadget: f_fs: Fix Use-After-Free in AIO error path"): The described error is avoided by making sure the cancellation handler is only registered, if there is something to cancel. Registering the cancellation handler adds the kiocb to the context's active request list (active_reqs in aio.c). If usb_ep_queue() fails, the request was never actually submitted to the hardware, which means the request is not active. The aio framework already deals with calling the completion function ki_complete() automatically if you do not return -EIOCBQUEUED. Fixes: e78dcb1f7ec2 ("usb: gadget: f_fs: Fix Use-After-Free in AIO error path") Link: https://lore.kernel.org/linux-usb/20261110171222.22633-3-ingo.rohloff@lauterbach.com/ Cc: stable@vger.kernel.org Signed-off-by: Ingo Rohloff Link: https://patch.msgid.link/20261119151942.44304-2-ingo.rohloff@lauterbach.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_fs.c | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/drivers/usb/gadget/function/f_fs.c b/drivers/usb/gadget/function/f_fs.c index 282f6dc88b1c67..5408931464f3e4 100644 --- a/drivers/usb/gadget/function/f_fs.c +++ b/drivers/usb/gadget/function/f_fs.c @@ -246,6 +246,7 @@ struct ffs_buffer { struct ffs_io_data { bool aio; bool read; + bool aio_active; struct kiocb *kiocb; struct iov_iter data; @@ -887,6 +888,8 @@ static void ffs_user_copy_worker(struct work_struct *work) } mmdrop(io_data->mm); + /* Make sure kiocb_set_cancel_fn() was already called. */ + smp_cond_load_acquire(&io_data->aio_active, VAL == true); io_data->kiocb->ki_complete(io_data->kiocb, ret); if (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd) @@ -1014,8 +1017,11 @@ static struct ffs_ep *ffs_epfile_wait_ep(struct ffs_epfile *epfile, struct file return ep; } +static int ffs_aio_cancel(struct kiocb *kiocb); + static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data) { + struct kiocb *kiocb = io_data->kiocb; struct ffs_epfile *epfile = file->private_data; struct usb_request *req; struct ffs_ep *ep; @@ -1205,6 +1211,14 @@ static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data) usb_ep_free_request(ep->ep, req); goto error_lock; } + kiocb->private = io_data; + kiocb_set_cancel_fn(kiocb, ffs_aio_cancel); + /* + * prevent ffs_user_copy_worker() from calling + * io_data->kiocb->ki_complete() + * before kiocb_set_cancel_fn() was called. + */ + smp_store_release(&io_data->aio_active, true); ret = -EIOCBQUEUED; /* @@ -1285,21 +1299,15 @@ static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from) p->data = *from; p->mm = current->mm; - kiocb->private = p; - - if (p->aio) { + if (p->aio) mmgrab(p->mm); - kiocb_set_cancel_fn(kiocb, ffs_aio_cancel); - } res = ffs_epfile_io(kiocb->ki_filp, p); if (res == -EIOCBQUEUED) return res; if (p->aio) { - kiocb->ki_complete(kiocb, res); mmdrop(p->mm); kfree(p); - return -EIOCBQUEUED; } else { *from = p->data; } @@ -1335,23 +1343,17 @@ static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to) } p->mm = current->mm; - kiocb->private = p; - - if (p->aio) { + if (p->aio) mmgrab(p->mm); - kiocb_set_cancel_fn(kiocb, ffs_aio_cancel); - } res = ffs_epfile_io(kiocb->ki_filp, p); if (res == -EIOCBQUEUED) return res; if (p->aio) { - kiocb->ki_complete(kiocb, res); mmdrop(p->mm); kfree(p->to_free); kfree(p); - return -EIOCBQUEUED; } else { *to = p->data; } From 85a9adf2a2943c55cb5f26eb320693f701381dfb Mon Sep 17 00:00:00 2001 From: Ingo Rohloff Date: Thu, 19 Nov 2026 16:19:42 +0100 Subject: [PATCH 1167/2102] usb: gadget: f_fs: simplify error handling using goto Refactor conditional checks to use direct error returns/gotos instead of a long if/else chain. This makes failure paths more obvious. At the end of the function AIO request handling is done. Signed-off-by: Ingo Rohloff Link: https://patch.msgid.link/20261119151942.44304-3-ingo.rohloff@lauterbach.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_fs.c | 98 ++++++++++++++++-------------- 1 file changed, 54 insertions(+), 44 deletions(-) diff --git a/drivers/usb/gadget/function/f_fs.c b/drivers/usb/gadget/function/f_fs.c index 5408931464f3e4..c4fba4d11570a1 100644 --- a/drivers/usb/gadget/function/f_fs.c +++ b/drivers/usb/gadget/function/f_fs.c @@ -1019,9 +1019,10 @@ static struct ffs_ep *ffs_epfile_wait_ep(struct ffs_epfile *epfile, struct file static int ffs_aio_cancel(struct kiocb *kiocb); -static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data) +static ssize_t ffs_epfile_io(struct ffs_io_data *io_data) { struct kiocb *kiocb = io_data->kiocb; + struct file *file = kiocb->ki_filp; struct ffs_epfile *epfile = file->private_data; struct usb_request *req; struct ffs_ep *ep; @@ -1110,11 +1111,17 @@ static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data) if (epfile->ep != ep) { /* In the meantime, endpoint got disabled or changed. */ ret = -ESHUTDOWN; - } else if (halt) { + goto error_lock; + } + + if (halt) { ret = usb_ep_set_halt(ep->ep); if (!ret) ret = -EBADMSG; - } else if (data_len == -EINVAL) { + goto error_lock; + } + + if (data_len == -EINVAL) { /* * Sanity Check: even though data_len can't be used * uninitialized at the time I write this comment, some @@ -1128,7 +1135,10 @@ static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data) */ WARN(1, "%s: data_len == -EINVAL\n", __func__); ret = -EINVAL; - } else if (!io_data->aio) { + goto error_lock; + } + + if (!io_data->aio) { bool interrupted = false; req = ep->req; @@ -1182,51 +1192,51 @@ static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data) else ret = io_data->status; goto error_mutex; - } else if (!(req = usb_ep_alloc_request(ep->ep, GFP_ATOMIC))) { + } + + /* It's an AIO request */ + req = usb_ep_alloc_request(ep->ep, GFP_ATOMIC); + if (!req) { ret = -ENOMEM; - } else { - if (io_data->use_sg) { - req->buf = NULL; - req->sg = io_data->sgt.sgl; - req->num_sgs = io_data->sgt.nents; - } else { - req->buf = data; - req->num_sgs = 0; - } + goto error_lock; + } - req->zero = !io_data->read ? epfile->zlp_enabled : 0; - req->length = data_len; + if (io_data->use_sg) { + req->buf = NULL; + req->sg = io_data->sgt.sgl; + req->num_sgs = io_data->sgt.nents; + } else { + req->buf = data; + req->num_sgs = 0; + } - io_data->buf = data; - io_data->ep = ep->ep; - io_data->req = req; - io_data->ffs = epfile->ffs; + req->zero = !io_data->read ? epfile->zlp_enabled : 0; + req->length = data_len; - req->context = io_data; - req->complete = ffs_epfile_async_io_complete; + io_data->buf = data; + io_data->ep = ep->ep; + io_data->req = req; + io_data->ffs = epfile->ffs; - ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC); - if (ret) { - io_data->req = NULL; - usb_ep_free_request(ep->ep, req); - goto error_lock; - } - kiocb->private = io_data; - kiocb_set_cancel_fn(kiocb, ffs_aio_cancel); - /* - * prevent ffs_user_copy_worker() from calling - * io_data->kiocb->ki_complete() - * before kiocb_set_cancel_fn() was called. - */ - smp_store_release(&io_data->aio_active, true); + req->context = io_data; + req->complete = ffs_epfile_async_io_complete; - ret = -EIOCBQUEUED; - /* - * Do not kfree the buffer in this function. It will be freed - * by ffs_user_copy_worker. - */ - data = NULL; + ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC); + if (ret) { + io_data->req = NULL; + usb_ep_free_request(ep->ep, req); + goto error_lock; } + kiocb->private = io_data; + kiocb_set_cancel_fn(kiocb, ffs_aio_cancel); + /* + * prevent ffs_user_copy_worker() from calling + * io_data->kiocb->ki_complete() + * before kiocb_set_cancel_fn() was called. + */ + smp_store_release(&io_data->aio_active, true); + + ret = -EIOCBQUEUED; error_lock: spin_unlock_irq(&epfile->ffs->eps_lock); @@ -1302,7 +1312,7 @@ static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from) if (p->aio) mmgrab(p->mm); - res = ffs_epfile_io(kiocb->ki_filp, p); + res = ffs_epfile_io(p); if (res == -EIOCBQUEUED) return res; if (p->aio) { @@ -1346,7 +1356,7 @@ static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to) if (p->aio) mmgrab(p->mm); - res = ffs_epfile_io(kiocb->ki_filp, p); + res = ffs_epfile_io(p); if (res == -EIOCBQUEUED) return res; From d16f1dbf64a44271f6d247148fd602299edb09c2 Mon Sep 17 00:00:00 2001 From: Yaohan Li Date: Thu, 5 Nov 2026 19:43:09 +0800 Subject: [PATCH 1168/2102] usb: gadget: u_audio: call period elapsed under the stream lock u_audio_iso_complete() drops the substream stream lock before calling snd_pcm_period_elapsed(), which re-acquires it internally. Between the unlock and the re-acquire, a concurrent close can run through snd_pcm_drop(), finish the PCM release and free the runtime, leaving the period notification to dereference a freed runtime (runtime->fasync in snd_pcm_period_elapsed()). Keep the stream lock across the period notification and use snd_pcm_period_elapsed_under_stream_lock(), the API for exactly this caller-held-lock case, so the callback's runtime access happens inside a single locked section. On final PCM release, snd_pcm_drop() takes the stream lock before runtime detachment: an in-flight completion holding that lock finishes before STOP can proceed. The STOP trigger clears prm->ss, so subsequent callbacks do not enter the running PCM path. Runtime detachment happens later and is not itself protected by the stream lock. On the gadget side, u_audio_stop_*() dequeues the requests before the endpoint is freed. KASAN reported the use-after-free in u_audio_iso_complete() on the unmodified kernel. With the callback stalled inside the locked section while a concurrent close ran, no use-after-free was reported after this change. This issue was investigated and the fix was developed with AI assistance (ZCode/GLM-4). Fixes: 773e53d50e227 ("usb: gadget: u_audio: remove cached period bytes value") Cc: stable Signed-off-by: Yaohan Li Link: https://patch.msgid.link/20261105114309.970899-1-shunsheng1218@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/u_audio.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/drivers/usb/gadget/function/u_audio.c b/drivers/usb/gadget/function/u_audio.c index f0ee83abcebc70..7da4032e3a203e 100644 --- a/drivers/usb/gadget/function/u_audio.c +++ b/drivers/usb/gadget/function/u_audio.c @@ -156,6 +156,7 @@ static void u_audio_iso_complete(struct usb_ep *ep, struct usb_request *req) struct uac_rtd_params *prm = req->context; struct snd_uac_chip *uac = prm->uac; unsigned int frames, p_pktsize; + unsigned int period_bytes; unsigned long long pitched_rate_mil, p_pktsize_residue_mil, residue_frames_mil, div_result; @@ -267,10 +268,12 @@ static void u_audio_iso_complete(struct usb_ep *ep, struct usb_request *req) /* update hw_ptr after data is copied to memory */ prm->hw_ptr = (hw_ptr + req->actual) % runtime->dma_bytes; hw_ptr = prm->hw_ptr; - snd_pcm_stream_unlock(substream); + period_bytes = snd_pcm_lib_period_bytes(substream); + + if ((hw_ptr % period_bytes) < req->actual) + snd_pcm_period_elapsed_under_stream_lock(substream); - if ((hw_ptr % snd_pcm_lib_period_bytes(substream)) < req->actual) - snd_pcm_period_elapsed(substream); + snd_pcm_stream_unlock(substream); exit: if (usb_ep_queue(ep, req, GFP_ATOMIC)) From d14ac98f16a6bcb9d0b8ec49bfd39e4eef793c7d Mon Sep 17 00:00:00 2001 From: Kyle Farrell Date: Mon, 26 Oct 2026 16:10:26 -0700 Subject: [PATCH 1169/2102] usb: gadget: u_audio: don't exceed maxpacket when adding a residue frame u_audio_iso_complete() clamps the base packet size to ep->maxpacket and accumulates fractional-frame residue in p_residue_mil. Once a whole frame has accumulated, it is appended to the packet without checking whether it fits within ep->maxpacket. Only append the extra frame if it fits. Consume the accumulated residue whether or not the frame is sent, preventing it from growing when the additional frame cannot fit. When the frame fits, behavior is unchanged. Otherwise, the stream cannot sustain the requested sample rate. For example, with 27 channels of 32-bit samples at 19200 Hz on a high-speed link with p_hs_bint=3, the required packet size of 1080 bytes is capped at 1024. The base packet is 972 bytes, but appending a residue frame increases it to 1080 bytes, exceeding the allocated request buffer by 56 bytes. Fixes: 9bb87f168931 ("usb: gadget: f_uac2: send reasonably sized packets") Cc: stable Link: https://lore.kernel.org/linux-usb/sashiko-outbox-174688@kernel.org/ Signed-off-by: Kyle Farrell Reviewed-by: Neill Kapron Link: https://patch.msgid.link/20261026231026.721536-1-kaf@nwlink.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/u_audio.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/drivers/usb/gadget/function/u_audio.c b/drivers/usb/gadget/function/u_audio.c index 7da4032e3a203e..83019d359c8d19 100644 --- a/drivers/usb/gadget/function/u_audio.c +++ b/drivers/usb/gadget/function/u_audio.c @@ -231,9 +231,13 @@ static void u_audio_iso_complete(struct usb_ep *ep, struct usb_request *req) do_div(div_result, uac->p_interval); do_div(div_result, 1000000); if ((unsigned int) div_result >= uac->p_framesize) { - req->length += uac->p_framesize; + /* req->length is bounded by ep->maxpacket above. */ + if (uac->p_framesize <= ep->maxpacket - req->length) { + req->length += uac->p_framesize; + pr_debug("increased req length to %d\n", req->length); + } + uac->p_residue_mil -= uac->p_framesize * p_interval_mil; - pr_debug("increased req length to %d\n", req->length); } pr_debug("remains uac->p_residue_mil %llu\n", uac->p_residue_mil); From d44e9ddadf4ef9a8ee72da8350d3f3cdef1830b0 Mon Sep 17 00:00:00 2001 From: Kyle Farrell Date: Wed, 28 Oct 2026 15:28:00 -0700 Subject: [PATCH 1170/2102] usb: gadget: f_uac2: prevent invalid bInterval auto-selection When p_hs_bint or c_hs_bint is 0, the driver selects the largest bInterval from 4 down to 1 for which the required bandwidth fits the maximum packet size. The original implementation intends to keep bInterval at 1 when required bandwidth exceeds the single-packet maximum, but the search loop instead decrements bInterval to 0 in that case. A bInterval of 0 is invalid for an isochronous endpoint. A Linux host reports it and substitutes a default: usb 3-8: ... endpoint 0x1 has an invalid bInterval 0, changing to 7 Stop the search at bInterval=1. Maintain existing clamping of wMaxPacketSize and warning about possible data loss when the required bandwidth cannot be accommodated. Fixes: 355a05dc8367 ("usb: gadget: f_uac2: Optionally determine bInterval for HS and SS") Signed-off-by: Kyle Farrell Cc: stable Reviewed-by: Neill Kapron Link: https://patch.msgid.link/20261028222800.782988-1-kaf@nwlink.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_uac2.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/usb/gadget/function/f_uac2.c b/drivers/usb/gadget/function/f_uac2.c index d8cf710085a05e..9bd59ea5f7fbc8 100644 --- a/drivers/usb/gadget/function/f_uac2.c +++ b/drivers/usb/gadget/function/f_uac2.c @@ -728,11 +728,11 @@ static int set_ep_max_packet_size_bint(struct device *dev, const struct f_uac2_o bint = opts_bint; max_size_bw = get_max_bw_for_bint(uac2_opts, bint, 8000, is_playback); } else { - /* checking bInterval from 4 to 1 whether the required bandwidth fits */ - for (bint = 4; bint > 0; --bint) { + /* select the largest bInterval that fits, or 1 if none fit */ + for (bint = 4; ; --bint) { max_size_bw = get_max_bw_for_bint( uac2_opts, bint, 8000, is_playback); - if (max_size_bw <= max_size_ep) + if (max_size_bw <= max_size_ep || bint == 1) break; } } From b9fdbe5124cf609d1ba10083a2a68c8266fc643c Mon Sep 17 00:00:00 2001 From: Keisuke Tsukuda Date: Wed, 9 Sep 2026 10:28:11 +0000 Subject: [PATCH 1171/2102] usb: gadget: f_hid: keep GET_REPORT request across disable hidg_disable() frees hidg->get_req when a GET_REPORT is waiting for userspace. A USB reset disables and re-enables the existing function without calling hidg_bind(), so the request remains NULL. Every later GET_REPORT then times out until the gadget is unbound and bound again. Keep the request allocated for the lifetime of the bound function and free it from hidg_unbind(). Cancel and wake a pending operation during disable, and use a request generation counter to stop work from an old configuration from replying to a newer control request. A pending get_req leak fix also adds cleanup at unbind, but it leaves the early free in hidg_disable() and therefore does not address this reset failure. The failure was reproduced on usb-testing with dummy_hcd: the interrupted request failed with ESHUTDOWN and subsequent requests timed out. It was also reproduced with a Linux xHCI host issuing a USB reset to a Raspberry Pi 4 using DWC2. The change passed eight reset timings under KASAN and the same physical Linux-host test. Fixes: a139c98f760e ("USB: gadget: f_hid: Add GET_REPORT via userspace IOCTL") Link: https://lore.kernel.org/all/tencent_F5AB9201DDA25D8E1925CF818D87258B8D07@qq.com/ Cc: stable Signed-off-by: Keisuke Tsukuda Link: https://patch.msgid.link/20260909102802.26181-1-tkdkei@outlook.jp Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_hid.c | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/drivers/usb/gadget/function/f_hid.c b/drivers/usb/gadget/function/f_hid.c index 520892bbfbef68..cf9d415f5631e3 100644 --- a/drivers/usb/gadget/function/f_hid.c +++ b/drivers/usb/gadget/function/f_hid.c @@ -96,6 +96,9 @@ struct f_hidg { struct usb_request *get_req; struct usb_hidg_report get_report; bool get_report_returned; + /* Cancel pending work and distinguish requests across reconfiguration. */ + bool get_report_cancelled; + unsigned int get_report_req_tag; int get_report_req_report_id; int get_report_req_report_length; spinlock_t get_report_spinlock; @@ -562,10 +565,16 @@ static void get_report_workqueue_handler(struct work_struct *work) struct usb_request *req; struct report_entry *ptr; unsigned long flags; + unsigned int req_tag; int status = 0; spin_lock_irqsave(&hidg->get_report_spinlock, flags); + if (hidg->get_report_cancelled) { + spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); + return; + } + req_tag = hidg->get_report_req_tag; req = hidg->get_req; if (!req) { spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); @@ -598,6 +607,11 @@ static void get_report_workqueue_handler(struct work_struct *work) status = wait_event_interruptible_timeout(hidg->get_queue, !GET_REPORT_COND, msecs_to_jiffies(GET_REPORT_TIMEOUT_MS)); spin_lock_irqsave(&hidg->get_report_spinlock, flags); + if (hidg->get_report_cancelled || + req_tag != hidg->get_report_req_tag) { + spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); + return; + } req = hidg->get_req; if (!req) { spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); @@ -858,6 +872,8 @@ static int hidg_setup(struct usb_function *f, * GET_REPORT the request was actually for. */ spin_lock_irqsave(&hidg->get_report_spinlock, flags); + hidg->get_report_cancelled = false; + hidg->get_report_req_tag++; hidg->get_report_req_report_id = value & 0xff; hidg->get_report_req_report_length = length; spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); @@ -991,12 +1007,11 @@ static void hidg_disable(struct usb_function *f) } spin_lock_irqsave(&hidg->get_report_spinlock, flags); - if (!hidg->get_report_returned) { - usb_ep_free_request(f->config->cdev->gadget->ep0, hidg->get_req); - hidg->get_req = NULL; - hidg->get_report_returned = true; - } + hidg->get_report_cancelled = true; + hidg->get_report_req_tag++; + hidg->get_report_returned = true; spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); + wake_up(&hidg->get_queue); spin_lock_irqsave(&hidg->read_spinlock, flags); hidg->disabled = true; @@ -1582,6 +1597,7 @@ static void hidg_unbind(struct usb_configuration *c, struct usb_function *f) cdev_device_del(hidg->cdev, &hidg->dev); destroy_workqueue(hidg->workqueue); + usb_ep_free_request(c->cdev->gadget->ep0, hidg->get_req); usb_free_all_descriptors(f); } From 19e8981057fb5947697f99a3c6a3f6ff4a2d85a1 Mon Sep 17 00:00:00 2001 From: Shunbo Shi Date: Tue, 17 Nov 2026 12:50:49 +0000 Subject: [PATCH 1172/2102] usb: gadget: f_hid: fix report_list entries leak Each GADGET_HID_WRITE_GET_REPORT ioctl for a report ID that is not yet in hidg->report_list allocates a report_entry and adds it to the list. hidg_release() frees report_desc and set_report_buf, but never walks report_list, so every accumulated entry leaks on function destroy (e.g. when the HID gadget is unbound and the device is removed). Free the entries in hidg_release(). This is safe without extra locking: at release time the function is unbound (the workqueue is already destroyed and userspace has no way to reach the ioctl). Fixes: a139c98f760e ("USB: gadget: f_hid: Add GET_REPORT via userspace IOCTL") Signed-off-by: Shunbo Shi Link: https://patch.msgid.link/20261117125051.5646-2-shishunbo@cmss.chinamobile.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_hid.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/usb/gadget/function/f_hid.c b/drivers/usb/gadget/function/f_hid.c index cf9d415f5631e3..de0dd0bcfcfbfe 100644 --- a/drivers/usb/gadget/function/f_hid.c +++ b/drivers/usb/gadget/function/f_hid.c @@ -124,6 +124,12 @@ static inline struct f_hidg *func_to_hidg(struct usb_function *f) static void hidg_release(struct device *dev) { struct f_hidg *hidg = container_of(dev, struct f_hidg, dev); + struct report_entry *entry, *tmp; + + list_for_each_entry_safe(entry, tmp, &hidg->report_list, node) { + list_del(&entry->node); + kfree(entry); + } kfree(hidg->report_desc); kfree(hidg->set_report_buf); From 07ec204e8aecbfee425008832b18d5d720daca6d Mon Sep 17 00:00:00 2001 From: Shunbo Shi Date: Tue, 17 Nov 2026 12:50:50 +0000 Subject: [PATCH 1173/2102] usb: gadget: f_hid: fix race between userspace report update and GET_REPORT response The GET_REPORT response is served by pointing get_req->buf at the data[] array of a report_list entry and calling usb_ep_queue(). The request completes asynchronously, so the controller may still be reading the entry's buffer after get_report_workqueue_handler() drops get_report_spinlock. At the same time, userspace can update that same entry via the GADGET_HID_WRITE_GET_REPORT ioctl: f_hidg_get_report() copies new report data into the entry while holding the spinlock, but the transfer reading the entry is not serialized against that update (the lock was already released by the work handler). The result is that the host can receive a GET_REPORT response that mixes bytes of the old and the new report (a torn write), with no memory-safety violation but corrupted report data on the wire. Serve the response from a dedicated buffer allocated once in hidg_alloc() and freed in hidg_release(). This also removes the now unused get_report member from struct f_hidg. Fixes: a139c98f760e ("USB: gadget: f_hid: Add GET_REPORT via userspace IOCTL") Signed-off-by: Shunbo Shi Link: https://patch.msgid.link/20261117125051.5646-3-shishunbo@cmss.chinamobile.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_hid.c | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/drivers/usb/gadget/function/f_hid.c b/drivers/usb/gadget/function/f_hid.c index de0dd0bcfcfbfe..714f217c8fbe0f 100644 --- a/drivers/usb/gadget/function/f_hid.c +++ b/drivers/usb/gadget/function/f_hid.c @@ -94,7 +94,7 @@ struct f_hidg { /* get report */ struct usb_request *get_req; - struct usb_hidg_report get_report; + void *get_req_buf; bool get_report_returned; /* Cancel pending work and distinguish requests across reconfiguration. */ bool get_report_cancelled; @@ -131,6 +131,7 @@ static void hidg_release(struct device *dev) kfree(entry); } + kfree(hidg->get_req_buf); kfree(hidg->report_desc); kfree(hidg->set_report_buf); kfree(hidg); @@ -596,7 +597,7 @@ static void get_report_workqueue_handler(struct work_struct *work) ptr = f_hidg_search_for_report(hidg, hidg->get_report_req_report_id); if (ptr && !ptr->report_data.userspace_req) { /* Report exists in list and it is to be used for immediate response */ - req->buf = ptr->report_data.data; + memcpy(req->buf, ptr->report_data.data, req->length); status = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC); hidg->get_report_returned = true; spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); @@ -636,10 +637,9 @@ static void get_report_workqueue_handler(struct work_struct *work) * Either get an updated response just serviced by userspace * or send the latest response in the list */ - req->buf = ptr->report_data.data; + memcpy(req->buf, ptr->report_data.data, req->length); } else { /* If there are no prevoiusly sent reports send empty report */ - req->buf = hidg->get_report.data; memset(req->buf, 0x0, req->length); } @@ -1170,6 +1170,15 @@ static int hidg_bind(struct usb_configuration *c, struct usb_function *f) if (!hidg->get_req) return -ENOMEM; + /* + * The GET_REPORT response is served from a dedicated buffer + * (allocated in hidg_alloc()), not from the report_list + * entries: userspace may update an entry while the controller + * is still reading the previous response, which would corrupt + * the data on the wire. + */ + hidg->get_req->buf = hidg->get_req_buf; + hidg->get_req->zero = 0; hidg->get_req->complete = hidg_get_report_complete; hidg->get_req->context = hidg; @@ -1657,6 +1666,18 @@ static struct usb_function *hidg_alloc(struct usb_function_instance *fi) } hidg->use_out_ep = !opts->no_out_endpoint; + /* + * Dedicated buffer for GET_REPORT responses, allocated once for + * the whole lifetime of this function instance: hidg_release() + * is the only safe free point, as it runs after all USB + * activity has ceased and all file references are gone. + */ + hidg->get_req_buf = kmalloc(MAX_REPORT_LENGTH, GFP_KERNEL); + if (!hidg->get_req_buf) { + ret = -ENOMEM; + goto err_put_device; + } + ++opts->refcnt; mutex_unlock(&opts->lock); From f11175ece1250557ec595ea7a2854f0391cab53d Mon Sep 17 00:00:00 2001 From: Shunbo Shi Date: Tue, 17 Nov 2026 12:50:51 +0000 Subject: [PATCH 1174/2102] usb: gadget: f_hid: fix get_req leak when usb_gstrings_attach() fails In hidg_bind(), hidg->get_req is allocated early; if usb_gstrings_attach() subsequently fails, the function returns directly without freeing the request, leaking it. Unwind through the fail path instead. Fixes: a139c98f760e ("USB: gadget: f_hid: Add GET_REPORT via userspace IOCTL") Signed-off-by: Shunbo Shi Link: https://patch.msgid.link/20261117125051.5646-4-shishunbo@cmss.chinamobile.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_hid.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/usb/gadget/function/f_hid.c b/drivers/usb/gadget/function/f_hid.c index 714f217c8fbe0f..428635e580bb7e 100644 --- a/drivers/usb/gadget/function/f_hid.c +++ b/drivers/usb/gadget/function/f_hid.c @@ -1187,8 +1187,10 @@ static int hidg_bind(struct usb_configuration *c, struct usb_function *f) /* maybe allocate device-global string IDs, and patch descriptors */ us = usb_gstrings_attach(c->cdev, ct_func_strings, ARRAY_SIZE(ct_func_string_defs)); - if (IS_ERR(us)) - return PTR_ERR(us); + if (IS_ERR(us)) { + status = PTR_ERR(us); + goto fail; + } hidg_interface_desc.iInterface = us[CT_FUNC_HID_IDX].id; /* allocate instance-specific interface IDs, and patch descriptors */ From 69b3b657087f9e85ac6c50c36561bf6165f15f1c Mon Sep 17 00:00:00 2001 From: Yehyeong Lee Date: Wed, 18 Nov 2026 21:40:02 +0900 Subject: [PATCH 1175/2102] usb: gadget: f_tcm: queue the BOT status requests with GFP_ATOMIC bot_send_bad_status() and bot_send_status() run from endpoint completion callbacks - bot_send_bad_status() via usbg_data_write_cmpl()'s cleanup path, and both of them via bot_read_compl() after a BOT read. Those callbacks are called with interrupts disabled and must not sleep, but both functions queue the status or drain request with GFP_KERNEL, which can. Queue with GFP_ATOMIC, like the other usb_ep_queue() calls reached from the same callbacks (bot_enqueue_sense_code() and bot_err_compl()). Fixes: c52661d60f63 ("usb-gadget: Initial merge of target module for UASP + BOT") Cc: stable Signed-off-by: Yehyeong Lee Link: https://patch.msgid.link/20261118124005.2428068-2-yhlee@isslab.korea.ac.kr Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_tcm.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/usb/gadget/function/f_tcm.c b/drivers/usb/gadget/function/f_tcm.c index 9e6d4f39900a27..12e2b20e33b921 100644 --- a/drivers/usb/gadget/function/f_tcm.c +++ b/drivers/usb/gadget/function/f_tcm.c @@ -139,7 +139,7 @@ static void bot_send_bad_status(struct usbg_cmd *cmd) req->complete = bot_err_compl; req->context = cmd; req->buf = fu->cmd[0].buf; - usb_ep_queue(ep, req, GFP_KERNEL); + usb_ep_queue(ep, req, GFP_ATOMIC); } else { bot_enqueue_sense_code(fu, cmd); } @@ -167,7 +167,7 @@ static int bot_send_status(struct usbg_cmd *cmd, bool moved_data) csw->Status = US_BULK_STAT_OK; fu->bot_status.req->context = cmd; - ret = usb_ep_queue(fu->ep_in, fu->bot_status.req, GFP_KERNEL); + ret = usb_ep_queue(fu->ep_in, fu->bot_status.req, GFP_ATOMIC); if (ret) pr_err("%s(%d) ERR: %d\n", __func__, __LINE__, ret); } else { From a784e99201af43d07fcd5cebd4ac00c1c7865443 Mon Sep 17 00:00:00 2001 From: Rafael Alejandro Diaz Cruz Date: Fri, 4 Sep 2026 17:35:58 -0700 Subject: [PATCH 1176/2102] USB: gadget: Fix UAF in gadgetfs_fill_super() When gadgetfs_fill_super() fails, it's error path calls put_dev() which drops refcount inside the_device to 0 and frees the objet. But the_device pointer is not cleared, leading to point at freed memory. VFS will then call gadgetfs_kill_sb() after mount failure leading to put_dev() to be called on the already freed pointer. Fix by setting the_device = NULL during error path before calling put_dev() inside gadgetfs_fill_super() so that gadgetfs_kill_sb() skips put_dev(). Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable Reported-by: syzbot+4a5c87a01894ca37f25c@syzkaller.appspotmail.com Link: https://syzkaller.appspot.com/bug?extid=4a5c87a01894ca37f25c Signed-off-by: Rafael Alejandro Diaz Cruz Reviewed-by: Alan Stern Link: https://patch.msgid.link/20260905003558.1686039-1-rafad900@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/legacy/inode.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c index 7f6d8460152f90..9950008db12162 100644 --- a/drivers/usb/gadget/legacy/inode.c +++ b/drivers/usb/gadget/legacy/inode.c @@ -2191,6 +2191,7 @@ gadgetfs_fill_super (struct super_block *sb, struct fs_context *fc) rc = gadgetfs_create_file(sb, CHIP, dev, &ep0_operations); if (rc) { put_dev(dev); + the_device = NULL; goto Enomem; } From ee7b2cade62ff4565049b0abdd6359645fb7999b Mon Sep 17 00:00:00 2001 From: Alexander Bendezu Date: Sun, 13 Sep 2026 00:05:46 +0000 Subject: [PATCH 1177/2102] usb: gadget: f_phonet: don't call gether_get_ifname() on a non-u_ether netdev The f_phonet_ifname_show() function incorrectly used gether_get_ifname(), which casts the net_device private data to 'struct eth_dev'. Since the Phonet gadget only allocates a small 'struct phonet_port' for its private data, this resulted in a KASAN slab-out-of-bounds read when accessing dev->ifname_set. BUG: KASAN: slab-out-of-bounds in gether_get_ifname+0xda/0x100 Read of size 1 at addr ffff8880091feaea by task cat/190 Call Trace: dump_stack_lvl+0x4d/0x70 print_report+0x153/0x4c6 kasan_report+0xda/0x110 gether_get_ifname+0xda/0x100 f_phonet_ifname_show+0x3a/0x60 configfs_read_iter+0x2ea/0x600 vfs_read+0x6da/0xa40 ksys_read+0xfd/0x200 do_syscall_64+0xe0/0x5a0 entry_SYSCALL_64_after_hwframe+0x77/0x7f Allocated by task 189: kasan_save_stack+0x30/0x50 kasan_save_track+0x14/0x30 __kasan_kmalloc+0x7f/0x90 __kvmalloc_node_noprof+0x1c2/0x5b0 alloc_netdev_mqs+0x78/0x12d0 phonet_alloc_inst+0x9e/0x1d0 try_get_usb_function_instance+0xf9/0x1a0 usb_get_function_instance+0xd/0x50 function_make+0x163/0x340 configfs_mkdir+0x47d/0xfc0 The buggy address is located 154 bytes to the right of allocated 2640-byte region [ffff8880091fe000, ffff8880091fea50) Fix this by reading the network device name directly with sysfs_emit(), avoiding the invalid struct cast. The u_ether.h include is no longer needed and is dropped. No locking is needed: opts->net is established before the config group is initialised, so the attribute cannot exist without a valid netdev, and holding rtnl_lock() across the read would not prevent a rename from taking effect before userspace sees the buffer. It went unnoticed because the helper function is reached only through USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(), which is used exclusively by u_ether functions, so phonet was the only caller passing a netdev u_ether did not create. Fixes: 83408745b202 ("usb: gadget: f_phonet: add configfs support") Cc: stable Reported-by: syzbot+3a0d6aa450317f25e501@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=3a0d6aa450317f25e501 Signed-off-by: Alexander Bendezu Link: https://patch.msgid.link/20260913000546.99778-1-alexanderbendezu10@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_phonet.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/usb/gadget/function/f_phonet.c b/drivers/usb/gadget/function/f_phonet.c index b1ee9a7c2e9440..2c6558b1a2ff2d 100644 --- a/drivers/usb/gadget/function/f_phonet.c +++ b/drivers/usb/gadget/function/f_phonet.c @@ -23,7 +23,6 @@ #include #include "u_phonet.h" -#include "u_ether.h" #define PN_MEDIA_USB 0x1B #define MAXPACKET 512 @@ -600,7 +599,9 @@ static const struct configfs_item_operations phonet_item_ops = { static ssize_t f_phonet_ifname_show(struct config_item *item, char *page) { - return gether_get_ifname(to_f_phonet_opts(item)->net, page, PAGE_SIZE); + struct net_device *net = to_f_phonet_opts(item)->net; + + return sysfs_emit(page, "%s\n", netdev_name(net)); } CONFIGFS_ATTR_RO(f_phonet_, ifname); From b1b2382b2df42e5ea347b952ea7211aed7853cd3 Mon Sep 17 00:00:00 2001 From: Aldo Ariel Panzardo Date: Tue, 15 Sep 2026 09:56:57 -0300 Subject: [PATCH 1178/2102] usb: gadget: f_printer: use the active RX list in soft reset printer_soft_reset() tests rx_reqs_active in its second draining loop but retrieves the next entry from rx_buffers. If rx_reqs_active is non-empty after endpoint shutdown, this operates on the wrong list and never removes the active entry, leading to list corruption and a non-terminating loop. Retrieve the request from the list named by the loop condition. Fixes: 25a010c8c1a5 ("USB: add Printer Gadget Driver") Cc: stable Signed-off-by: Aldo Ariel Panzardo Link: https://patch.msgid.link/20260915125657.2849779-1-qwe.aldo@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_printer.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/usb/gadget/function/f_printer.c b/drivers/usb/gadget/function/f_printer.c index 1857d786110b4f..e3dc5d810a6f57 100644 --- a/drivers/usb/gadget/function/f_printer.c +++ b/drivers/usb/gadget/function/f_printer.c @@ -940,8 +940,8 @@ static void printer_soft_reset(struct printer_dev *dev) } while (likely(!(list_empty(&dev->rx_reqs_active)))) { - req = container_of(dev->rx_buffers.next, struct usb_request, - list); + req = list_first_entry(&dev->rx_reqs_active, + struct usb_request, list); list_del_init(&req->list); list_add(&req->list, &dev->rx_reqs); } From 018e3bf95e6360b7d528d3094b5302fb4e2fbed0 Mon Sep 17 00:00:00 2001 From: Kuen-Han Tsai Date: Wed, 23 Sep 2026 15:58:35 +0800 Subject: [PATCH 1179/2102] usb: gadget: u_ether: Fix NULL pointer deref in debug logging Commit ec35c1969650 ("usb: gadget: f_ncm: Fix net_device lifecycle with device_move") and its counterparts reparent the net_device to /sys/devices/virtual during unbind and clear dev->gadget. However, the DBG(), VDBG(), ERROR(), and INFO() macros from dereference &dev->gadget->dev. When dynamic debug or CONFIG_USB_GADGET_DEBUG is enabled, any logging on the surviving net_device after unbind causes a NULL pointer dereference, such as in eth_stop() during function instance teardown: Unable to handle kernel NULL pointer dereference Call trace: dev_driver_string from __dynamic_dev_dbg+0x8c/0x118 __dynamic_dev_dbg from eth_stop+0x70/0x134 [u_ether] ... unregister_netdev from gether_cleanup+0x14/0x28 [u_ether] gether_cleanup [u_ether] from rndis_free_inst+0x2c/0x48 [usb_f_rndis] Replace the composite.h logging macros in u_ether.c with the standard netdev_*() helpers. Because dev->net remains valid for the entire lifetime of struct eth_dev and netdev_printk() natively handles unparented network devices, messages are logged safely both when attached and when detached from the gadget. Reported-by: Ivaylo Dimitrov Closes: https://lore.kernel.org/all/89e19e6e-7ee7-4bb0-abd6-60971b7fd601@gmail.com/ Fixes: ec35c1969650 ("usb: gadget: f_ncm: Fix net_device lifecycle with device_move") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Kuen-Han Tsai Reviewed-by: Aldo Ariel Panzardo Suggested-by: Ivaylo Dimitrov Link: https://patch.msgid.link/20260923-u-ether-gadget-npe-v1-1-ff466c55ecc0@google.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/u_ether.c | 61 +++++++++++++-------------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/drivers/usb/gadget/function/u_ether.c b/drivers/usb/gadget/function/u_ether.c index 59d85d6a84a896..043b4ec8080814 100644 --- a/drivers/usb/gadget/function/u_ether.c +++ b/drivers/usb/gadget/function/u_ether.c @@ -135,9 +135,9 @@ static void defer_kevent(struct eth_dev *dev, int flag) if (test_and_set_bit(flag, &dev->todo)) return; if (!schedule_work(&dev->work)) - ERROR(dev, "kevent %d may have been dropped\n", flag); + netdev_err(dev->net, "kevent %d may have been dropped\n", flag); else - DBG(dev, "kevent %d scheduled\n", flag); + netdev_dbg(dev->net, "kevent %d scheduled\n", flag); } static void rx_complete(struct usb_ep *ep, struct usb_request *req); @@ -190,7 +190,7 @@ rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags) skb = __netdev_alloc_skb(dev->net, size + NET_IP_ALIGN, gfp_flags); if (skb == NULL) { - DBG(dev, "no rx skb\n"); + netdev_dbg(dev->net, "no rx skb\n"); goto enomem; } @@ -211,7 +211,7 @@ rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags) enomem: defer_kevent(dev, WORK_RX_MEMORY); if (retval) { - DBG(dev, "rx submit --> %d\n", retval); + netdev_dbg(dev->net, "rx submit --> %d\n", retval); if (skb) dev_kfree_skb_any(skb); spin_lock_irqsave(&dev->req_lock, flags); @@ -258,7 +258,7 @@ static void rx_complete(struct usb_ep *ep, struct usb_request *req) || skb2->len > GETHER_MAX_ETH_FRAME_LEN) { dev->net->stats.rx_errors++; dev->net->stats.rx_length_errors++; - DBG(dev, "rx length %d\n", skb2->len); + netdev_dbg(dev->net, "rx length %d\n", skb2->len); dev_kfree_skb_any(skb2); goto next_frame; } @@ -278,12 +278,12 @@ static void rx_complete(struct usb_ep *ep, struct usb_request *req) /* software-driven interface shutdown */ case -ECONNRESET: /* unlink */ case -ESHUTDOWN: /* disconnect etc */ - VDBG(dev, "rx shutdown, code %d\n", status); + netdev_vdbg(dev->net, "rx shutdown, code %d\n", status); goto quiesce; /* for hardware automagic (such as pxa) */ case -ECONNABORTED: /* endpoint reset */ - DBG(dev, "rx %s reset\n", ep->name); + netdev_dbg(dev->net, "rx %s reset\n", ep->name); defer_kevent(dev, WORK_RX_MEMORY); quiesce: dev_kfree_skb_any(skb); @@ -296,7 +296,7 @@ static void rx_complete(struct usb_ep *ep, struct usb_request *req) default: dev->net->stats.rx_errors++; - DBG(dev, "rx status %d\n", status); + netdev_dbg(dev->net, "rx status %d\n", status); break; } @@ -365,7 +365,7 @@ static int alloc_requests(struct eth_dev *dev, struct gether *link, unsigned n) goto fail; goto done; fail: - DBG(dev, "can't alloc requests\n"); + netdev_dbg(dev->net, "can't alloc requests\n"); done: spin_unlock(&dev->req_lock); return status; @@ -403,7 +403,7 @@ static void eth_work(struct work_struct *work) } if (dev->todo) - DBG(dev, "work done, flags = 0x%lx\n", dev->todo); + netdev_dbg(dev->net, "work done, flags = 0x%lx\n", dev->todo); } static void tx_complete(struct usb_ep *ep, struct usb_request *req) @@ -414,7 +414,7 @@ static void tx_complete(struct usb_ep *ep, struct usb_request *req) switch (req->status) { default: dev->net->stats.tx_errors++; - VDBG(dev, "tx err %d\n", req->status); + netdev_vdbg(dev->net, "tx err %d\n", req->status); fallthrough; case -ECONNRESET: /* unlink */ case -ESHUTDOWN: /* disconnect etc */ @@ -475,7 +475,7 @@ static netdev_tx_t eth_start_xmit(struct sk_buff *skb, } if (dev->port_usb && dev->port_usb->is_suspend) { - DBG(dev, "Port suspended. Triggering wakeup\n"); + netdev_dbg(dev->net, "Port suspended. Triggering wakeup\n"); netif_stop_queue(net); spin_unlock_irqrestore(&dev->lock, flags); ether_wakeup_host(dev->port_usb); @@ -579,7 +579,7 @@ static netdev_tx_t eth_start_xmit(struct sk_buff *skb, retval = usb_ep_queue(in, req, GFP_ATOMIC); switch (retval) { default: - DBG(dev, "tx queue err %d\n", retval); + netdev_dbg(dev->net, "tx queue err %d\n", retval); break; case 0: netif_trans_update(net); @@ -604,7 +604,7 @@ static netdev_tx_t eth_start_xmit(struct sk_buff *skb, static void eth_start(struct eth_dev *dev, gfp_t gfp_flags) { - DBG(dev, "%s\n", __func__); + netdev_dbg(dev->net, "%s\n", __func__); /* fill the rx queue */ rx_fill(dev, gfp_flags); @@ -619,7 +619,7 @@ static int eth_open(struct net_device *net) struct eth_dev *dev = netdev_priv(net); struct gether *link; - DBG(dev, "%s\n", __func__); + netdev_dbg(dev->net, "%s\n", __func__); if (netif_carrier_ok(dev->net)) eth_start(dev, GFP_KERNEL); @@ -637,13 +637,12 @@ static int eth_stop(struct net_device *net) struct eth_dev *dev = netdev_priv(net); unsigned long flags; - VDBG(dev, "%s\n", __func__); + netdev_vdbg(dev->net, "%s\n", __func__); netif_stop_queue(net); - DBG(dev, "stop stats: rx/tx %ld/%ld, errs %ld/%ld\n", - dev->net->stats.rx_packets, dev->net->stats.tx_packets, - dev->net->stats.rx_errors, dev->net->stats.tx_errors - ); + netdev_dbg(dev->net, "stop stats: rx/tx %ld/%ld, errs %ld/%ld\n", + dev->net->stats.rx_packets, dev->net->stats.tx_packets, + dev->net->stats.rx_errors, dev->net->stats.tx_errors); /* ensure there are no more active requests */ spin_lock_irqsave(&dev->lock, flags); @@ -669,7 +668,7 @@ static int eth_stop(struct net_device *net) usb_ep_disable(link->in_ep); usb_ep_disable(link->out_ep); if (netif_carrier_ok(net)) { - DBG(dev, "host still using in/out endpoints\n"); + netdev_dbg(dev->net, "host still using in/out endpoints\n"); link->in_ep->desc = in; link->out_ep->desc = out; usb_ep_enable(link->in_ep); @@ -799,8 +798,8 @@ struct eth_dev *gether_setup_name(struct usb_gadget *g, free_netdev(net); dev = ERR_PTR(status); } else { - INFO(dev, "MAC %pM\n", net->dev_addr); - INFO(dev, "HOST MAC %pM\n", dev->host_mac); + netdev_info(net, "MAC %pM\n", net->dev_addr); + netdev_info(net, "HOST MAC %pM\n", dev->host_mac); /* * two kinds of host-initiated state changes: @@ -875,8 +874,8 @@ int gether_register_netdev(struct net_device *net) dev_dbg(&g->dev, "register_netdev failed, %d\n", status); return status; } else { - INFO(dev, "HOST MAC %pM\n", dev->host_mac); - INFO(dev, "MAC %pM\n", dev->dev_mac); + netdev_info(net, "HOST MAC %pM\n", dev->host_mac); + netdev_info(net, "MAC %pM\n", dev->dev_mac); /* two kinds of host-initiated state changes: * - iff DATA transfer is active, carrier is "on" @@ -1147,16 +1146,16 @@ struct net_device *gether_connect(struct gether *link) link->in_ep->driver_data = dev; result = usb_ep_enable(link->in_ep); if (result != 0) { - DBG(dev, "enable %s --> %d\n", - link->in_ep->name, result); + netdev_dbg(dev->net, "enable %s --> %d\n", + link->in_ep->name, result); goto fail0; } link->out_ep->driver_data = dev; result = usb_ep_enable(link->out_ep); if (result != 0) { - DBG(dev, "enable %s --> %d\n", - link->out_ep->name, result); + netdev_dbg(dev->net, "enable %s --> %d\n", + link->out_ep->name, result); goto fail1; } @@ -1167,7 +1166,7 @@ struct net_device *gether_connect(struct gether *link) if (result == 0) { dev->zlp = link->is_zlp_ok; dev->no_skb_reserve = gadget_avoids_skb_reserve(dev->gadget); - DBG(dev, "qlen %d\n", qlen(dev->gadget, dev->qmult)); + netdev_dbg(dev->net, "qlen %d\n", qlen(dev->gadget, dev->qmult)); dev->header_len = link->header_len; dev->unwrap = link->unwrap; @@ -1223,7 +1222,7 @@ void gether_disconnect(struct gether *link) if (!dev) return; - DBG(dev, "%s\n", __func__); + netdev_dbg(dev->net, "%s\n", __func__); spin_lock(&dev->lock); dev->port_usb = NULL; From e6beabd9982c0e36a87d4741aa3b95acba3bc120 Mon Sep 17 00:00:00 2001 From: Kuen-Han Tsai Date: Wed, 23 Sep 2026 15:58:36 +0800 Subject: [PATCH 1180/2102] usb: gadget: u_ether: Protect dev->gadget access with dev->lock Commit e002e92e88e1 ("usb: gadget: u_ether: Fix NULL pointer deref in eth_get_drvinfo") added a NULL check for dev->gadget in eth_get_drvinfo(), but the check and subsequent dereferences are not serialized against gether_detach_gadget(). If unbind clears dev->gadget concurrently after the NULL check, eth_get_drvinfo() can still dereference a NULL or freed gadget pointer. Extend dev->lock to protect dev->gadget across gether_set_gadget(), gether_detach_gadget(), eth_get_drvinfo(), and rx_submit(). Also use gether_set_gadget() in gether_setup_name() for consistency. Reported-by: Faqiang Zhu Fixes: e002e92e88e1 ("usb: gadget: u_ether: Fix NULL pointer deref in eth_get_drvinfo") Fixes: ec35c1969650 ("usb: gadget: f_ncm: Fix net_device lifecycle with device_move") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Kuen-Han Tsai Reviewed-by: Aldo Ariel Panzardo Link: https://patch.msgid.link/20260923-u-ether-gadget-npe-v1-2-ff466c55ecc0@google.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/u_ether.c | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/drivers/usb/gadget/function/u_ether.c b/drivers/usb/gadget/function/u_ether.c index 043b4ec8080814..2a9ae598e61266 100644 --- a/drivers/usb/gadget/function/u_ether.c +++ b/drivers/usb/gadget/function/u_ether.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -54,8 +55,7 @@ #define GETHER_MAX_ETH_FRAME_LEN (GETHER_MAX_MTU_SIZE + ETH_HLEN) struct eth_dev { - /* lock is held while accessing port_usb - */ + /* lock is held while accessing port_usb and gadget */ spinlock_t lock; struct gether *port_usb; @@ -113,6 +113,8 @@ static void eth_get_drvinfo(struct net_device *net, struct ethtool_drvinfo *p) strscpy(p->driver, "g_ether", sizeof(p->driver)); strscpy(p->version, UETH__VERSION, sizeof(p->version)); + + guard(spinlock_irqsave)(&dev->lock); if (dev->gadget) { strscpy(p->fw_version, dev->gadget->name, sizeof(p->fw_version)); strscpy(p->bus_info, dev_name(&dev->gadget->dev), sizeof(p->bus_info)); @@ -145,7 +147,7 @@ static void rx_complete(struct usb_ep *ep, struct usb_request *req); static int rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags) { - struct usb_gadget *g = dev->gadget; + struct usb_gadget *g; struct sk_buff *skb; int retval = -ENOMEM; size_t size = 0; @@ -153,6 +155,7 @@ rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags) unsigned long flags; spin_lock_irqsave(&dev->lock, flags); + g = dev->gadget; if (dev->port_usb) out = dev->port_usb->out_ep; else @@ -788,8 +791,7 @@ struct eth_dev *gether_setup_name(struct usb_gadget *g, net->min_mtu = ETH_HLEN; net->max_mtu = GETHER_MAX_MTU_SIZE; - dev->gadget = g; - SET_NETDEV_DEV(net, &g->dev); + gether_set_gadget(net, g); SET_NETDEV_DEVTYPE(net, &gadget_type); status = register_netdev(net); @@ -890,10 +892,11 @@ EXPORT_SYMBOL_GPL(gether_register_netdev); void gether_set_gadget(struct net_device *net, struct usb_gadget *g) { - struct eth_dev *dev; + struct eth_dev *dev = netdev_priv(net); + + scoped_guard(spinlock_irqsave, &dev->lock) + dev->gadget = g; - dev = netdev_priv(net); - dev->gadget = g; SET_NETDEV_DEV(net, &g->dev); } EXPORT_SYMBOL_GPL(gether_set_gadget); @@ -915,8 +918,10 @@ void gether_detach_gadget(struct net_device *net) { struct eth_dev *dev = netdev_priv(net); + scoped_guard(spinlock_irqsave, &dev->lock) + dev->gadget = NULL; + device_move(&net->dev, NULL, DPM_ORDER_NONE); - dev->gadget = NULL; } EXPORT_SYMBOL_GPL(gether_detach_gadget); From 3cd2ba6950de2c3fa8eea06b394c511b19144dc4 Mon Sep 17 00:00:00 2001 From: Yu Zhang Date: Thu, 15 Oct 2026 18:46:58 +1000 Subject: [PATCH 1181/2102] usb: gadget: f_printer: fix pnp_string use-after-free on reconfigure f_printer_opts_pnp_string_store() replaces opts->pnp_string with kfree(old) + kstrndup(new) under opts->lock only, with no opts->refcnt guard, so the IEEE-1284 ID string can be changed while the function is bound and the gadget is enumerated. printer_func_setup() answers the host GET_DEVICE_ID class request from (soft)irq context and reads the string with no lock: value = strlen(*dev->pnp_string); ... memcpy(buf + 2, *dev->pnp_string, value); dev->pnp_string points at &opts->pnp_string, so a concurrent configfs write that frees the old string races the setup read -> use-after-free. KASAN, a configfs writer racing a host GET_DEVICE_ID (reproduced over dummy_hcd): BUG: KASAN: slab-use-after-free in strlen+0xe/0x40 Read of size 1 at addr ffff888005036000 by task swapper/1/0 Call Trace: strlen+0xe/0x40 printer_func_setup+0x410/0x890 composite_setup+0x67e/0x4690 configfs_composite_setup+0xbb/0xd0 dummy_timer+0x1934/0x1e40 __hrtimer_run_queues+0x1b6/0x410 hrtimer_run_softirq+0x13a/0x260 Allocated by task 3486: kstrndup+0xb2/0x130 f_printer_opts_pnp_string_store+0x3f/0xf0 configfs_write_iter+0x1a7/0x250 vfs_write+0x5df/0x940 ksys_write+0xfd/0x1e0 The setup path runs in atomic context and cannot take opts->lock, so serialize by refusing to change pnp_string while the function is instantiated, exactly as the sibling f_printer_opts_q_len_store() already does for q_len. While the function is bound the string is then stable for the lifetime of the live reader; it can still be changed when the function is not linked into a gadget. Fixes: 24b7ba2f88e0 ("usb: gadget: function: fix dangling pnp_string in f_printer.c") Cc: stable Signed-off-by: Yu Zhang Tested-by: Yu Zhang Link: https://patch.msgid.link/20261015084658.70918-1-yuz08559@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_printer.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/drivers/usb/gadget/function/f_printer.c b/drivers/usb/gadget/function/f_printer.c index e3dc5d810a6f57..20ef59ef8af1c6 100644 --- a/drivers/usb/gadget/function/f_printer.c +++ b/drivers/usb/gadget/function/f_printer.c @@ -1269,6 +1269,11 @@ static ssize_t f_printer_opts_pnp_string_store(struct config_item *item, mutex_lock(&opts->lock); + if (opts->refcnt) { + result = -EBUSY; + goto unlock; + } + new_pnp = kstrndup(page, len, GFP_KERNEL); if (!new_pnp) { result = -ENOMEM; From 2e46e41432edc540bb5e47a3e0b76a5892cd7ec9 Mon Sep 17 00:00:00 2001 From: Fang Xieyan Date: Thu, 5 Nov 2026 17:27:12 +0800 Subject: [PATCH 1182/2102] usb: gadget: f_printer: clamp GET_DEVICE_ID pnp_string to ep0 buffer The GET_DEVICE_ID request handler in printer_func_setup() copies the configfs-provided pnp_string into the EP0 request buffer. The pnp_string length is bounded by the configfs page size, but is not limited by the size of the EP0 buffer. Since the first two bytes of the buffer are used for the length field, a pnp_string longer than USB_COMP_EP0_BUFSIZ - 2 causes memcpy() to write beyond the end of the EP0 buffer. Limit the copied string length to USB_COMP_EP0_BUFSIZ - 2, ensuring that both the length field and the string fit within the EP0 buffer. Fixes: 24b7ba2f88e0 ("usb: gadget: function: fix dangling pnp_string in f_printer.c") Cc: stable Reviewed-by: Weibin Liu Signed-off-by: Fang Xieyan Link: https://patch.msgid.link/20261105092712.27838-1-fangxy@xiaopeng.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_printer.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/usb/gadget/function/f_printer.c b/drivers/usb/gadget/function/f_printer.c index 20ef59ef8af1c6..00e82c3d079e12 100644 --- a/drivers/usb/gadget/function/f_printer.c +++ b/drivers/usb/gadget/function/f_printer.c @@ -1034,7 +1034,8 @@ static int printer_func_setup(struct usb_function *f, value = 0; break; } - value = strlen(*dev->pnp_string); + value = min_t(int, strlen(*dev->pnp_string), + USB_COMP_EP0_BUFSIZ - 2); buf[0] = (value >> 8) & 0xFF; buf[1] = value & 0xFF; memcpy(buf + 2, *dev->pnp_string, value); From da946f52ce0f548db158e9863cdd2c1cca8fc218 Mon Sep 17 00:00:00 2001 From: Xu Rao Date: Tue, 10 Nov 2026 11:18:32 +0800 Subject: [PATCH 1183/2102] usb: gadget: f_printer: Fix fsync waiting for active transfers printer_fsync() checks the list of free TX requests before deciding whether to wait for all data to be sent. Once a write queues a request, it is removed from the free list and placed on tx_reqs_active, so the free list can be empty while a USB transfer is still in progress. This allows fsync() to return before the queued data has completed. Check tx_reqs_active instead, matching the wait condition and the completion callback that wakes tx_flush_wait. Signed-off-by: Xu Rao Cc: stable Link: https://patch.msgid.link/09D38BF2C904A309+20261110031832.219431-1-raoxu@uniontech.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_printer.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/usb/gadget/function/f_printer.c b/drivers/usb/gadget/function/f_printer.c index 00e82c3d079e12..10eeeedb8bcbac 100644 --- a/drivers/usb/gadget/function/f_printer.c +++ b/drivers/usb/gadget/function/f_printer.c @@ -736,7 +736,7 @@ printer_fsync(struct file *fd, loff_t start, loff_t end, int datasync) return -ENODEV; } - tx_list_empty = (likely(list_empty(&dev->tx_reqs))); + tx_list_empty = (likely(list_empty(&dev->tx_reqs_active))); spin_unlock_irqrestore(&dev->lock, flags); if (!tx_list_empty) { From 9c655fa88d2948929c34a94efffe9abf57813ff2 Mon Sep 17 00:00:00 2001 From: Yehyeong Lee Date: Thu, 19 Nov 2026 23:06:40 +0900 Subject: [PATCH 1184/2102] usb: gadget: f_tcm: put the overlapped command's request back on ep_cmd When usbg_cmd_work() confirms an overlapped command tag it returns the duplicate command's slot to the session tag pool and cancels the active command's transfer, but it never hands the duplicate's own request back to ep_cmd. The two sanity exits just above it pass that request to usbg_submit_command(), and the status path gives the active command's request back once its response has been sent, so only this path drops one. The request is not leaked - it stays in fu->cmd[] until uasp_free_cmdreq() frees it - but it stops being posted, so the gadget can receive one COMMAND IU fewer for the rest of the alternate setting. There are USBG_NUM_CMDS of them, and a host spends one by sending two COMMAND IUs with the same tag, so the command endpoint ends up with nothing posted and no command is received at all. There is no memory error to catch here, so count the posted requests instead: on a dummy_hcd gadget in UAS mode the count falls by one per overlap and reaches 0 after 32, and the gadget then answers none of four following commands, while with this patch 33 overlaps leave the count at 33 and all four are answered. Three fresh boots per arm. Take the request pointer before the slot goes back to the pool, because from then on it can belong to a new command, and queue it after the abort so that nothing else in the path moves. A queue that fails leaves the request in fu->cmd[] for uasp_free_cmdreq(), as at the other two sites that post to ep_cmd after setup. Fixes: 29ed17053872 ("usb: gadget: f_tcm: Check overlapped command") Cc: stable Signed-off-by: Yehyeong Lee Link: https://patch.msgid.link/20261119140641.2768465-1-yhlee@isslab.korea.ac.kr Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_tcm.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/drivers/usb/gadget/function/f_tcm.c b/drivers/usb/gadget/function/f_tcm.c index 12e2b20e33b921..3af28419a8bca9 100644 --- a/drivers/usb/gadget/function/f_tcm.c +++ b/drivers/usb/gadget/function/f_tcm.c @@ -1275,6 +1275,7 @@ static void usbg_cmd_work(struct work_struct *work) struct uas_stream *stream = NULL; struct hlist_node *tmp; struct usbg_cmd *active_cmd = NULL; + struct usb_request *req; se_sess = cmd->fu->tpg->tpg_nexus->tvn_se_sess; @@ -1318,6 +1319,12 @@ static void usbg_cmd_work(struct work_struct *work) return; } + /* + * Take the request before the slot goes back to the pool; it + * is queued on ep_cmd below. + */ + req = cmd->req; + /* * The command isn't submitted to the target core, so we're safe * to remove the bitmap index from the session tag pool. @@ -1333,6 +1340,8 @@ static void usbg_cmd_work(struct work_struct *work) active_cmd->tmr_rsp = RC_OVERLAPPED_TAG; usbg_aborted_task(&active_cmd->se_cmd); + usb_ep_queue(fu->ep_cmd, req, GFP_ATOMIC); + /* Send the response after the transfer is aborted. */ return; } From ba4bbac98e65c6998cac4ea2b63baf2159d00a8c Mon Sep 17 00:00:00 2001 From: Vasileios Almpanis Date: Fri, 31 Jul 2026 20:26:45 +0200 Subject: [PATCH 1185/2102] usb: gadget: f_uac1_legacy: fix double close of the ALSA devices f_audio_bind() records that the ALSA files are open in the function instance flag opts->bound, but keeps the file pointers in the per-function gaudio card. Its error path calls gaudio_cleanup(), which closes the files without clearing the filp pointers or opts->bound. A failed bind does not destroy the usb_function, configfs_composite_bind() puts it back on cfg->func_list, so the next write to UDC binds the same f_audio, skips gaudio_setup() because opts->bound is still set, and on failure closes the files a second time. Dropping the config symlink after a failed bind closes them again via f_audio_free(). BUG: KASAN: slab-use-after-free in filp_flush+0x31/0x190 fs/open.c:1464 Read of size 8 at addr ffff888045f01990 by task syz-executor659/5617 Call Trace: filp_close+0x1d/0x40 fs/open.c:1484 gaudio_close_snd_dev drivers/usb/gadget/function/u_uac1_legacy.c:263 [inline] gaudio_cleanup+0x54/0xf0 drivers/usb/gadget/function/u_uac1_legacy.c:305 f_audio_bind+0x4a0/0x630 drivers/usb/gadget/function/f_uac1_legacy.c:792 usb_add_function+0x290/0x930 drivers/usb/gadget/composite.c:333 configfs_composite_bind+0xde0/0x1410 drivers/usb/gadget/configfs.c:1802 gadget_bind_driver+0x2ca/0x9e0 drivers/usb/gadget/udc/core.c:1662 gadget_dev_desc_UDC_store+0x1c9/0x2f0 drivers/usb/gadget/configfs.c:300 Clear filp, substream and card in gaudio_close_snd_dev() so cleanup is idempotent, and close the devices on the bind error path only if that bind opened them, resetting opts->bound as well. Fixes: f3a3406b3f56 ("usb: gadget: f_uac1: convert to new function interface with backward compatibility") Cc: stable Reported-by: syzbot+df868600fe111c5ff79f@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=df868600fe111c5ff79f Signed-off-by: Vasileios Almpanis Link: https://patch.msgid.link/20260731-alsa-v1-1-95eb93ba32ec@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_uac1_legacy.c | 8 +++++++- drivers/usb/gadget/function/u_uac1_legacy.c | 17 ++++++++++++++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/drivers/usb/gadget/function/f_uac1_legacy.c b/drivers/usb/gadget/function/f_uac1_legacy.c index 7c8d60c7e87d12..e183251ec25999 100644 --- a/drivers/usb/gadget/function/f_uac1_legacy.c +++ b/drivers/usb/gadget/function/f_uac1_legacy.c @@ -732,6 +732,7 @@ f_audio_bind(struct usb_configuration *c, struct usb_function *f) int status; struct usb_ep *ep = NULL; struct f_uac1_legacy_opts *audio_opts; + bool bound_here = false; audio_opts = container_of(f->fi, struct f_uac1_legacy_opts, func_inst); audio->card.gadget = c->cdev->gadget; @@ -741,6 +742,7 @@ f_audio_bind(struct usb_configuration *c, struct usb_function *f) if (status < 0) return status; audio_opts->bound = true; + bound_here = true; } us = usb_gstrings_attach(cdev, uac1_strings, ARRAY_SIZE(strings_uac1)); if (IS_ERR(us)) @@ -789,7 +791,11 @@ f_audio_bind(struct usb_configuration *c, struct usb_function *f) return 0; fail: - gaudio_cleanup(&audio->card); + /* Only tear down the ALSA devices if this bind opened them; the */ + if (bound_here) { + gaudio_cleanup(&audio->card); + audio_opts->bound = false; + } return status; } diff --git a/drivers/usb/gadget/function/u_uac1_legacy.c b/drivers/usb/gadget/function/u_uac1_legacy.c index 01016102fa1728..c2b6c88b0bdc99 100644 --- a/drivers/usb/gadget/function/u_uac1_legacy.c +++ b/drivers/usb/gadget/function/u_uac1_legacy.c @@ -259,18 +259,29 @@ static int gaudio_close_snd_dev(struct gaudio *gau) /* Close control device */ snd = &gau->control; - if (snd->filp) + if (snd->filp) { filp_close(snd->filp, NULL); + snd->filp = NULL; + snd->card = NULL; + } /* Close PCM playback device and setup substream */ snd = &gau->playback; - if (snd->filp) + if (snd->filp) { filp_close(snd->filp, NULL); + snd->filp = NULL; + snd->substream = NULL; + snd->card = NULL; + } /* Close PCM capture device and setup substream */ snd = &gau->capture; - if (snd->filp) + if (snd->filp) { filp_close(snd->filp, NULL); + snd->filp = NULL; + snd->substream = NULL; + snd->card = NULL; + } return 0; } From 04aed9e674be821274b78d8a9c42ecba8ddd9471 Mon Sep 17 00:00:00 2001 From: Thomas Touhey Date: Thu, 5 Nov 2026 16:13:48 +0100 Subject: [PATCH 1186/2102] usb: storage: add quirks for CASIO calculators CASIO calculators using USB Mass Storage, bearing product IDs 6102 and 6103, always report non-zero dCSWDataResidue for requested transfer length >4096 bytes while bCSWStatus == 0. Information about an fx-CG50 (OS 3.11): T: Bus=03 Lev=01 Prnt=01 Port=06 Cnt=03 Dev#= 24 Spd=480 MxCh= 0 D: Ver= 2.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs= 1 P: Vendor=07cf ProdID=6102 Rev= 1.00 S: Manufacturer=CASIO MassStorage Device S: Product=CASIO MassStorage Device S: SerialNumber=0000xdPUBVUq C:* #Ifs= 1 Cfg#= 1 Atr=c0 MxPwr=100mA I:* If#= 0 Alt= 0 #EPs= 2 Cls=08(stor.) Sub=06 Prot=50 Driver=usb-storage E: Ad=01(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms E: Ad=82(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms Information about an fx-9750GIII (OS 3.71): T: Bus=03 Lev=01 Prnt=01 Port=06 Cnt=03 Dev#= 25 Spd=480 MxCh= 0 D: Ver= 2.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs= 1 P: Vendor=07cf ProdID=6103 Rev= 1.00 S: Manufacturer=CASIO MassStorage Device S: Product=CASIO MassStorage Device S: SerialNumber=000000000001 C:* #Ifs= 1 Cfg#= 1 Atr=c0 MxPwr=100mA I:* If#= 0 Alt= 0 #EPs= 2 Cls=08(stor.) Sub=06 Prot=50 Driver=usb-storage E: Ad=01(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms E: Ad=82(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms Cc: stable Signed-off-by: Thomas Touhey Tested-by: Artem Novak Link: https://patch.msgid.link/20261105151348.19009-1-thomas@touhey.fr Signed-off-by: Greg Kroah-Hartman --- drivers/usb/storage/unusual_devs.h | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/drivers/usb/storage/unusual_devs.h b/drivers/usb/storage/unusual_devs.h index ac22fa31873439..492b5f050f0b2f 100644 --- a/drivers/usb/storage/unusual_devs.h +++ b/drivers/usb/storage/unusual_devs.h @@ -1168,6 +1168,25 @@ UNUSUAL_DEV( 0x07cf, 0x1167, 0x0100, 0x0100, "EX-N1 DigitalCamera", USB_SC_8070, USB_PR_DEVICE, NULL, 0), +/* + * CASIO calculators using UMS for "USB Key" mode always + * reports non-zero residue when the transfer length is larger + * than 4096 bytes. + * + * Reported by Thomas Touhey + * and augmented by 0v0katai <0v0katai@gmail.com> + */ +UNUSUAL_DEV( 0x07cf, 0x6102, 0x0100, 0x0100, + "Casio", + "fx-CP400", + USB_SC_DEVICE, USB_PR_DEVICE, NULL, + US_FL_IGNORE_RESIDUE ), +UNUSUAL_DEV( 0x07cf, 0x6103, 0x0100, 0x0100, + "Casio", + "fx-CG50", + USB_SC_DEVICE, USB_PR_DEVICE, NULL, + US_FL_IGNORE_RESIDUE ), + /* Submitted by Hartmut Wahl */ UNUSUAL_DEV( 0x0839, 0x000a, 0x0001, 0x0001, "Samsung", From d3edf3c408198df8c8acd8dd3fe6a7a85881ec4e Mon Sep 17 00:00:00 2001 From: Guangshuo Li Date: Wed, 11 Nov 2026 20:23:03 +0800 Subject: [PATCH 1187/2102] usb-storage: onetouch: Fix potential use-after-free on input failure If input_register_device() fails, onetouch_connect_input() frees the onetouch state but leaves it installed in ss->extra. USB-storage cleanup then calls onetouch_release_input() on the freed state. Install the extra state and callbacks only after input registration succeeds. This issue was found by our static analysis tool under development. Fixes: 17efe155253e ("USB: onetouch - handle errors from input_register_device()") Cc: stable Signed-off-by: Guangshuo Li Acked-by: Alan Stern Link: https://patch.msgid.link/20261111-e5624093d6-usb-storage@mail.sdu.edu.cn Signed-off-by: Greg Kroah-Hartman --- drivers/usb/storage/onetouch.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/usb/storage/onetouch.c b/drivers/usb/storage/onetouch.c index 49d281f7bef693..e09b3c6b9a6a51 100644 --- a/drivers/usb/storage/onetouch.c +++ b/drivers/usb/storage/onetouch.c @@ -237,16 +237,16 @@ static int onetouch_connect_input(struct us_data *ss) onetouch->irq->transfer_dma = onetouch->data_dma; onetouch->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; + error = input_register_device(onetouch->dev); + if (error) + goto fail3; + ss->extra_destructor = onetouch_release_input; ss->extra = onetouch; #ifdef CONFIG_PM ss->suspend_resume_hook = usb_onetouch_pm_hook; #endif - error = input_register_device(onetouch->dev); - if (error) - goto fail3; - return 0; fail3: usb_free_urb(onetouch->irq); From 5d6194c28dcdb736b64061c3ede5fe594bdd71db Mon Sep 17 00:00:00 2001 From: Hongyu Xie Date: Fri, 13 Nov 2026 15:36:37 +0800 Subject: [PATCH 1188/2102] usb-storage: add usb_stor_bulk_transfer_buf_timeout() usb_stor_bulk_transfer_buf() waits for URB completion without a timeout. That is correct for transfers belonging to a SCSI command, whose timeout and abort handling terminate the wait, but not for transfers issued outside a SCSI command. Add a variant which takes a timeout, in jiffies; zero means no limit. usb_stor_bulk_transfer_buf() becomes a wrapper with a zero timeout, so existing callers are unchanged. Signed-off-by: Hongyu Xie Reviewed-by: Alan Stern Cc: stable Link: https://patch.msgid.link/20261113073638.1225998-2-xiehongyu1@kylinos.cn Signed-off-by: Greg Kroah-Hartman --- drivers/usb/storage/transport.c | 31 ++++++++++++++++++++++++------- drivers/usb/storage/transport.h | 5 +++++ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/drivers/usb/storage/transport.c b/drivers/usb/storage/transport.c index 8de3015bce0502..424293658918a5 100644 --- a/drivers/usb/storage/transport.c +++ b/drivers/usb/storage/transport.c @@ -378,12 +378,17 @@ static int usb_stor_intr_transfer(struct us_data *us, void *buf, } /* - * Transfer one buffer via bulk pipe, without timeouts, but allowing early - * termination. Return codes are USB_STOR_XFER_xxx. If the bulk pipe - * stalls during the transfer, the halt is automatically cleared. + * Transfer one buffer via bulk pipe, allowing early termination. Return + * codes are USB_STOR_XFER_xxx. If the bulk pipe stalls during the + * transfer, the halt is automatically cleared. + * + * A nonzero @timeout bounds the wait for URB completion, in jiffies. It + * must only be used for transfers which are not part of a SCSI command: + * those rely on the command's timeout and abort handling. */ -int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe, - void *buf, unsigned int length, unsigned int *act_len) +int usb_stor_bulk_transfer_buf_timeout(struct us_data *us, unsigned int pipe, + void *buf, unsigned int length, + unsigned int *act_len, int timeout) { int result; @@ -392,14 +397,26 @@ int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe, /* fill and submit the URB */ usb_fill_bulk_urb(us->current_urb, us->pusb_dev, pipe, buf, length, usb_stor_blocking_completion, NULL); - result = usb_stor_msg_common(us, 0); + result = usb_stor_msg_common(us, timeout); /* store the actual length of the data transferred */ if (act_len) *act_len = us->current_urb->actual_length; - return interpret_urb_result(us, pipe, length, result, + return interpret_urb_result(us, pipe, length, result, us->current_urb->actual_length); } +EXPORT_SYMBOL_GPL(usb_stor_bulk_transfer_buf_timeout); + +/* + * Same as usb_stor_bulk_transfer_buf_timeout() with an unbounded wait. + */ +int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe, + void *buf, unsigned int length, + unsigned int *act_len) +{ + return usb_stor_bulk_transfer_buf_timeout(us, pipe, buf, length, + act_len, 0); +} EXPORT_SYMBOL_GPL(usb_stor_bulk_transfer_buf); /* diff --git a/drivers/usb/storage/transport.h b/drivers/usb/storage/transport.h index 74ffd0d7e7b6cf..361dbd77f15e38 100644 --- a/drivers/usb/storage/transport.h +++ b/drivers/usb/storage/transport.h @@ -77,6 +77,11 @@ extern int usb_stor_clear_halt(struct us_data *us, unsigned int pipe); extern int usb_stor_ctrl_transfer(struct us_data *us, unsigned int pipe, u8 request, u8 requesttype, u16 value, u16 index, void *data, u16 size); +extern int usb_stor_bulk_transfer_buf_timeout(struct us_data *us, + unsigned int pipe, void *buf, + unsigned int length, + unsigned int *act_len, + int timeout); extern int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe, void *buf, unsigned int length, unsigned int *act_len); extern int usb_stor_bulk_transfer_sg(struct us_data *us, unsigned int pipe, From 0b2b2a995660491223fb117067278cb9f3de8d35 Mon Sep 17 00:00:00 2001 From: Hongyu Xie Date: Fri, 13 Nov 2026 15:36:38 +0800 Subject: [PATCH 1189/2102] usb-storage: ene_ub6250: don't let the card-type probe hang forever ene_ub6250_probe() reads the card type with ene_get_card_type() right after usb_stor_probe2() has added the SCSI host. The query is a bulk-only transaction (CBW, one-byte data-in, CSW) sent through ene_send_scsi_cmd(), which uses usb_stor_bulk_transfer_buf() and therefore waits for URB completion without any timeout. That is safe only for transfers belonging to a SCSI command, where the command's timeout and abort handling terminate the wait. A card-type query has no SCSI command behind it, so a device which enumerates but never services bulk transfers blocks the probe forever. commit 445fc368c6bc ("usb-storage: ene_ub6250: fix race between scan work and probe") added us->dev_mutex around the query to keep it from racing with the scan work for us->current_urb. usb_stor_probe2() queues that work with a one-second delay, so it now waits for a transfer which may never finish. The query itself has been unbounded since commit 41e568d14ec0 ("Staging: Merge ENE UB6250 SD card codes from keucr to drivers/usb/storage"), but only the latter turns the hang into the lockup reported here, hence the Fixes tag. syzbot reports: INFO: task kworker/0:2:53 blocked for more than 143 seconds. Workqueue: events_freezable usb_stor_scan_dwork Call Trace: __mutex_lock+0x7c4/0x15a0 usb_stor_scan_dwork+0xec/0x2c0 ... INFO: task syz-executor339:5675 blocked for more than 143 seconds. Call Trace: __mutex_lock+0x7c4/0x15a0 device_lock usbdev_open+0x151/0x760 with the hub worker holding both locks stalled in ene_ub6250_probe() -> ene_get_card_type() -> usb_stor_msg_common(). Run the query from ->initFunction instead. usb_stor_acquire_resources() calls it before the control thread is started and before the scan work is queued, so nothing else can be using us->current_urb and the dev_mutex from that commit can go away. A failed query now unwinds through usb_stor_probe2() before the SCSI host is registered, instead of going through usb_stor_disconnect() and cancel_delayed_work_sync() on a scan work which is itself stuck on the dead device. Also give each transfer of the query a 10-second timeout. A timeout at any stage fails the query immediately, so the probe cannot block forever. The retry chain can run five transfers at most (CBW, data, CSW and the two CSW retries), which bounds the query to about 50 seconds without keeping a shared budget. Reported-by: syzbot+30552b4cbe99d6d91306@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=30552b4cbe99d6d91306 Fixes: 445fc368c6bc ("usb-storage: ene_ub6250: fix race between scan work and probe") Cc: Liu Qi Cc: stable@kernel.org Signed-off-by: Hongyu Xie Reviewed-by: Alan Stern Link: https://patch.msgid.link/20261113073638.1225998-3-xiehongyu1@kylinos.cn Signed-off-by: Greg Kroah-Hartman --- drivers/usb/storage/ene_ub6250.c | 110 +++++++++++++++-------- drivers/usb/storage/unusual_ene_ub6250.h | 2 +- 2 files changed, 73 insertions(+), 39 deletions(-) diff --git a/drivers/usb/storage/ene_ub6250.c b/drivers/usb/storage/ene_ub6250.c index fea2614e767c70..bf661d8e2c5405 100644 --- a/drivers/usb/storage/ene_ub6250.c +++ b/drivers/usb/storage/ene_ub6250.c @@ -24,6 +24,9 @@ #define DRV_NAME "ums_eneub6250" +/* Timeout for each transfer of the probe-time card-type query, in jiffies. */ +#define ENE_PROBE_TIMEOUT (10 * HZ) + MODULE_DESCRIPTION("Driver for ENE UB6250 reader"); MODULE_LICENSE("GPL"); MODULE_IMPORT_NS("USB_STORAGE"); @@ -34,6 +37,8 @@ MODULE_FIRMWARE(MS_INIT_FIRMWARE); MODULE_FIRMWARE(MSP_RW_FIRMWARE); MODULE_FIRMWARE(MS_RW_FIRMWARE); +static int ene_ub6250_init(struct us_data *us); + /* * The table of devices */ @@ -487,7 +492,12 @@ static void ene_ub6250_info_destructor(void *extra) kfree(info->bbuf); } -static int ene_send_scsi_cmd(struct us_data *us, u8 fDir, void *buf, int use_sg) +/* + * Send an ENE SCSI command. @timeout bounds the wait for each transfer of + * the transaction, in jiffies; zero means no limit. + */ +static int ene_send_scsi_cmd_timeout(struct us_data *us, u8 fdir, void *buf, + int use_sg, unsigned int timeout) { struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap *) us->iobuf; struct bulk_cs_wrap *bcs = (struct bulk_cs_wrap *) us->iobuf; @@ -499,27 +509,33 @@ static int ene_send_scsi_cmd(struct us_data *us, u8 fDir, void *buf, int use_sg) /* usb_stor_dbg(us, "transport --- ene_send_scsi_cmd\n"); */ /* send cmd to out endpoint */ - result = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, - bcb, US_BULK_CB_WRAP_LEN, NULL); + result = usb_stor_bulk_transfer_buf_timeout(us, us->send_bulk_pipe, + bcb, US_BULK_CB_WRAP_LEN, + NULL, timeout); if (result != USB_STOR_XFER_GOOD) { usb_stor_dbg(us, "send cmd to out endpoint fail ---\n"); return USB_STOR_TRANSPORT_ERROR; } if (buf) { - unsigned int pipe = fDir; + unsigned int pipe; - if (fDir == FDIR_READ) + if (fdir == FDIR_READ) pipe = us->recv_bulk_pipe; else pipe = us->send_bulk_pipe; /* Bulk */ if (use_sg) { + /* + * Scatter-gather transfers belong to SCSI commands, + * whose timeout and abort machinery bound the wait. + */ result = usb_stor_bulk_srb(us, pipe, us->srb); } else { - result = usb_stor_bulk_transfer_sg(us, pipe, buf, - transfer_length, 0, &partial); + result = usb_stor_bulk_transfer_buf_timeout(us, pipe, + buf, transfer_length, + &partial, timeout); } if (result != USB_STOR_XFER_GOOD) { usb_stor_dbg(us, "data transfer fail ---\n"); @@ -528,20 +544,25 @@ static int ene_send_scsi_cmd(struct us_data *us, u8 fDir, void *buf, int use_sg) } /* Get CSW for device status */ - result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, bcs, - US_BULK_CS_WRAP_LEN, &cswlen); + result = usb_stor_bulk_transfer_buf_timeout(us, us->recv_bulk_pipe, + bcs, US_BULK_CS_WRAP_LEN, + &cswlen, timeout); if (result == USB_STOR_XFER_SHORT && cswlen == 0) { usb_stor_dbg(us, "Received 0-length CSW; retrying...\n"); - result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, - bcs, US_BULK_CS_WRAP_LEN, &cswlen); + result = usb_stor_bulk_transfer_buf_timeout(us, + us->recv_bulk_pipe, bcs, + US_BULK_CS_WRAP_LEN, + &cswlen, timeout); } if (result == USB_STOR_XFER_STALLED) { /* get the status again */ usb_stor_dbg(us, "Attempting to get CSW (2nd try)...\n"); - result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, - bcs, US_BULK_CS_WRAP_LEN, NULL); + result = usb_stor_bulk_transfer_buf_timeout(us, + us->recv_bulk_pipe, bcs, + US_BULK_CS_WRAP_LEN, NULL, + timeout); } if (result != USB_STOR_XFER_GOOD) @@ -567,6 +588,15 @@ static int ene_send_scsi_cmd(struct us_data *us, u8 fDir, void *buf, int use_sg) return USB_STOR_TRANSPORT_GOOD; } +/* + * Unbounded variant for the command path: a SCSI command's timeout and + * abort machinery terminate the transfer if the device stops responding. + */ +static int ene_send_scsi_cmd(struct us_data *us, u8 fdir, void *buf, int use_sg) +{ + return ene_send_scsi_cmd_timeout(us, fdir, buf, use_sg, 0); +} + static int do_scsi_request_sense(struct us_data *us, struct scsi_cmnd *srb) { struct ene_ub6250_info *info = (struct ene_ub6250_info *) us->extra; @@ -1824,7 +1854,8 @@ static int ms_scsi_write(struct us_data *us, struct scsi_cmnd *srb) * ENE MS Card */ -static int ene_get_card_type(struct us_data *us, u16 index, void *buf) +static int ene_get_card_type(struct us_data *us, u16 index, void *buf, + unsigned int timeout) { struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap *) us->iobuf; int result; @@ -1837,7 +1868,7 @@ static int ene_get_card_type(struct us_data *us, u16 index, void *buf) bcb->CDB[2] = (unsigned char)(index>>8); bcb->CDB[3] = (unsigned char)index; - result = ene_send_scsi_cmd(us, FDIR_READ, buf, 0); + result = ene_send_scsi_cmd_timeout(us, FDIR_READ, buf, 0, timeout); return result; } @@ -2191,7 +2222,7 @@ static int ene_init(struct us_data *us) struct ene_ub6250_info *info = (struct ene_ub6250_info *)(us->extra); u8 *bbuf = info->bbuf; - result = ene_get_card_type(us, REG_CARD_STATUS, bbuf); + result = ene_get_card_type(us, REG_CARD_STATUS, bbuf, 0); if (result != USB_STOR_XFER_GOOD) return USB_STOR_TRANSPORT_ERROR; @@ -2319,13 +2350,35 @@ static int ene_transport(struct scsi_cmnd *srb, struct us_data *us) static struct scsi_host_template ene_ub6250_host_template; +/* + * Probe-time card-type query. It runs from usb_stor_acquire_resources(), + * before the usb-storage control thread and the SCSI scan work exist, so + * nothing else can be using us->current_urb. Give every transfer a + * timeout: there is no SCSI command whose timeout or abort handling could + * end the wait, and a timeout at any stage fails the whole query. + */ +static int ene_ub6250_init(struct us_data *us) +{ + struct ene_ub6250_info *info = (struct ene_ub6250_info *)us->extra; + int result; + + result = ene_get_card_type(us, REG_CARD_STATUS, info->bbuf, + ENE_PROBE_TIMEOUT); + if (result != USB_STOR_XFER_GOOD) + return -EIO; + + if (!(info->bbuf[0] & 0x01)) + pr_info("ums_eneub6250: SM cards are not supported\n"); + + return 0; +} + static int ene_ub6250_probe(struct usb_interface *intf, const struct usb_device_id *id) { - int result; - u8 misc_reg03; struct us_data *us; struct ene_ub6250_info *info; + int result; result = usb_stor_probe1(&us, intf, id, (id - ene_ub6250_usb_ids) + ene_ub6250_unusual_dev_list, @@ -2352,26 +2405,7 @@ static int ene_ub6250_probe(struct usb_interface *intf, us->transport_reset = usb_stor_Bulk_reset; us->max_lun = 0; - result = usb_stor_probe2(us); - if (result) - return result; - - /* probe card type */ - mutex_lock(&us->dev_mutex); - result = ene_get_card_type(us, REG_CARD_STATUS, info->bbuf); - mutex_unlock(&us->dev_mutex); - if (result != USB_STOR_XFER_GOOD) { - usb_stor_disconnect(intf); - return USB_STOR_TRANSPORT_ERROR; - } - - misc_reg03 = info->bbuf[0]; - if (!(misc_reg03 & 0x01)) { - pr_info("ums_eneub6250: This driver only supports SD/MS cards. " - "It does not support SM cards.\n"); - } - - return result; + return usb_stor_probe2(us); } diff --git a/drivers/usb/storage/unusual_ene_ub6250.h b/drivers/usb/storage/unusual_ene_ub6250.h index a3b32abc2b2fff..bc9d7ea4e398ba 100644 --- a/drivers/usb/storage/unusual_ene_ub6250.h +++ b/drivers/usb/storage/unusual_ene_ub6250.h @@ -5,6 +5,6 @@ UNUSUAL_DEV(0x0cf2, 0x6250, 0x0000, 0x9999, "ENE", "ENE UB6250 reader", - USB_SC_DEVICE, USB_PR_DEVICE, NULL, 0), + USB_SC_DEVICE, USB_PR_DEVICE, ene_ub6250_init, 0), #endif /* defined(CONFIG_USB_STORAGE_ENE_UB6250) || ... */ From e0d798033b357be40bb9dd20d3e9548751b86826 Mon Sep 17 00:00:00 2001 From: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Date: Tue, 17 Nov 2026 00:39:46 +0800 Subject: [PATCH 1190/2102] usb-storage: reject too small values in max_sectors_store() Writing a value that is smaller than a page worth of sectors, or smaller than one logical block, to /sys/class/scsi_device/.../device/max_sectors passes an invalid max_hw_sectors to queue_limits_commit_update_frozen(). The block layer requires max_hw_sectors to cover at least one page and at least one logical block, and treats a smaller value as a driver bug: WARNING: block/blk-settings.c:389 at blk_validate_limits+0xeb9/0x14b0 Call Trace: queue_limits_commit_update queue_limits_commit_update_frozen max_sectors_store dev_attr_store sysfs_kf_write Before commit 70a7949335e5 ("scsi: usb-storage: Switch to using ->device_configure") the store called blk_queue_max_hw_sectors(), which silently raised values below PAGE_SECTORS to that minimum. The conversion to the queue_limits API lost the clamping, so a single sysfs write from user space can now trigger the warning. Reject such values with -EINVAL on the limits snapshot returned by queue_limits_start_update(), cancelling the update. This keeps the return value for values below a page unchanged, as the block layer already returned -EINVAL for them, and also rejects zero, which blk_validate_limits() would otherwise replace with BLK_SAFE_MAX_SECTORS without the user asking for it. Checking the logical block size as well covers devices that report a block size larger than a page, where a value above PAGE_SECTORS can still be smaller than one logical block. Fixes: 70a7949335e5 ("scsi: usb-storage: Switch to using ->device_configure") Cc: stable Co-developed-by: Bin Yu Signed-off-by: Bin Yu Co-developed-by: Cheng Wen Signed-off-by: Cheng Wen Signed-off-by: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Acked-by: Alan Stern Link: https://patch.msgid.link/20261116163946.2502-1-25031212351@stu.xidian.edu.cn Signed-off-by: Greg Kroah-Hartman --- drivers/usb/storage/scsiglue.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/usb/storage/scsiglue.c b/drivers/usb/storage/scsiglue.c index 97de28e8556263..7a55cfc18236dc 100644 --- a/drivers/usb/storage/scsiglue.c +++ b/drivers/usb/storage/scsiglue.c @@ -593,6 +593,10 @@ static ssize_t max_sectors_store(struct device *dev, struct device_attribute *at return -EINVAL; lim = queue_limits_start_update(sdev->request_queue); + if (ms < PAGE_SECTORS || ms < lim.logical_block_size >> SECTOR_SHIFT) { + queue_limits_cancel_update(sdev->request_queue); + return -EINVAL; + } lim.max_hw_sectors = ms; ret = queue_limits_commit_update_frozen(sdev->request_queue, &lim); if (ret) From 39cbb13df4c3eebd3285407ea3c6df0ad7f22136 Mon Sep 17 00:00:00 2001 From: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Date: Tue, 17 Nov 2026 09:27:07 +0800 Subject: [PATCH 1191/2102] usb: storage: shuttle_usbat: set the ATA sector size at device init usbat_flash_read_data() and usbat_flash_write_data() divide the transfer length by info->ssize to turn it into an ATA sector count. info->ssize is only assigned in the READ CAPACITY handler, so it is still zero when a read request arrives earlier. Such a request is sent during device scan: sd_probe() starts with media_present set and usb-storage sets read_before_ms for every device, so sd_revalidate_disk() calls sd_read_block_zero() right after sd_read_capacity(), even when READ CAPACITY failed, because read_capacity_error() deliberately keeps media_present set for drives that fail it with media loaded. A CompactFlash reader that does not complete the READ CAPACITY sequence, for example because a register access is stalled, therefore reaches usbat_flash_read_data() with info->ssize == 0: Oops: divide error RIP: 0010:usbat_flash_read_data+0x2a4/0x5c0 The ATA sector size of these readers is fixed at 512 bytes, so record it when the USBAT flash transport is selected, instead of waiting for a READ CAPACITY command to succeed. The datafab and jumpshot drivers, which share this code, already set it during device identification for the same reason. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable Co-developed-by: Bin Yu Signed-off-by: Bin Yu Co-developed-by: Cheng Wen Signed-off-by: Cheng Wen Signed-off-by: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Acked-by: Alan Stern Link: https://patch.msgid.link/20261117012707.5858-1-25031212351@stu.xidian.edu.cn Signed-off-by: Greg Kroah-Hartman --- drivers/usb/storage/shuttle_usbat.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/usb/storage/shuttle_usbat.c b/drivers/usb/storage/shuttle_usbat.c index 7e5424268c733c..267c823814656f 100644 --- a/drivers/usb/storage/shuttle_usbat.c +++ b/drivers/usb/storage/shuttle_usbat.c @@ -1038,6 +1038,8 @@ static int usbat_set_transport(struct us_data *us, break; case USBAT_DEV_FLASH: + /* The ATA sector size of these readers is fixed at 512 bytes */ + info->ssize = 0x200; us->transport = usbat_flash_transport; break; } @@ -1703,8 +1705,6 @@ static int usbat_flash_transport(struct scsi_cmnd * srb, struct us_data *us) if (rc != USB_STOR_TRANSPORT_GOOD) return rc; - /* hard coded 512 byte sectors as per ATA spec */ - info->ssize = 0x200; usb_stor_dbg(us, "READ_CAPACITY: %ld sectors, %ld bytes per sector\n", info->sectors, info->ssize); From 5bb5661e5317decdefc728431c2d46d1924a8ef8 Mon Sep 17 00:00:00 2001 From: Miao Li Date: Tue, 28 Jul 2026 10:05:00 +0800 Subject: [PATCH 1192/2102] usb: quirks: Add DELAY_INIT quirk for Kingston DataTraveler 3.0 The Kingston DataTraveler 3.0 flash drive fails to initialize randomly during reboot stress tests on the Huawei HiSilicon platform. Adding the USB_QUIRK_DELAY_INIT quirk resolves the initialization failure, this has been verified to survive over 1000 reboot cycles without error. Signed-off-by: Miao Li Cc: stable Link: https://patch.msgid.link/20260728020500.94492-1-limiao870622@163.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/core/quirks.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/usb/core/quirks.c b/drivers/usb/core/quirks.c index a4bcbe9c913cf5..98544785e4627f 100644 --- a/drivers/usb/core/quirks.c +++ b/drivers/usb/core/quirks.c @@ -423,7 +423,8 @@ static const struct usb_device_id usb_quirk_list[] = { USB_QUIRK_CONFIG_INTF_STRINGS }, /* Kingston DataTraveler 3.0 */ - { USB_DEVICE(0x0951, 0x1666), .driver_info = USB_QUIRK_NO_LPM }, + { USB_DEVICE(0x0951, 0x1666), .driver_info = USB_QUIRK_NO_LPM | + USB_QUIRK_DELAY_INIT }, /* TOSHIBA TransMemory-Mx */ { USB_DEVICE(0x0930, 0x1408), .driver_info = USB_QUIRK_NO_LPM }, From 03f220903fa4b0c2adb4f342ed46e9fd91cac86c Mon Sep 17 00:00:00 2001 From: Haobo Cheng Date: Tue, 4 Aug 2026 16:34:34 +0800 Subject: [PATCH 1193/2102] usb: typec: mux: initialize orientation switch array Commit a53b4f9c51a9 ("usb: typec: mux: avoid duplicated orientation switches") started using the orientation switch result array as state for duplicate detection, but left the array uninitialized. The first match therefore scans indeterminate stack contents before any result has been stored. A valid orientation switch may be incorrectly discarded as a duplicate, causing fwnode_typec_switch_get() to return no switch. Zero-initialize the array before collecting matches. Fixes: a53b4f9c51a9 ("usb: typec: mux: avoid duplicated orientation switches") Cc: stable Signed-off-by: Haobo Cheng Reviewed-by: Sebastian Reichel Link: https://patch.msgid.link/20260804083434.20885-1-i@4t.pw Signed-off-by: Greg Kroah-Hartman --- drivers/usb/typec/mux.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/usb/typec/mux.c b/drivers/usb/typec/mux.c index afa6fc18139781..57149f53769298 100644 --- a/drivers/usb/typec/mux.c +++ b/drivers/usb/typec/mux.c @@ -81,7 +81,7 @@ static void *typec_switch_match(const struct fwnode_handle *fwnode, */ struct typec_switch *fwnode_typec_switch_get(struct fwnode_handle *fwnode) { - struct typec_switch_dev *sw_devs[TYPEC_MUX_MAX_DEVS]; + struct typec_switch_dev *sw_devs[TYPEC_MUX_MAX_DEVS] = { }; struct typec_switch *sw; int count; int err; From 54d2414e0af19c2812590991335f8f0ed8c2e64d Mon Sep 17 00:00:00 2001 From: Vasileios Almpanis Date: Tue, 11 Aug 2026 18:02:03 +0200 Subject: [PATCH 1194/2102] usb: gadget: pch_udc: don't call pch_udc_remove() from the probe error path Probe error paths go to finished label which calls phc_udc_remove. It in turn starts with an unconditional usb_del_gadget_udc(). If probe fails before the gadget is added then we put a non-initialized kobject (gadget.dev) and a WARN is triggered in kobject_put(). WARNING: lib/kobject.c:734 at kobject_put+0x252/0x640 lib/kobject.c:734 Call Trace: put_device+0x1f/0x30 drivers/base/core.c:3880 pch_udc_remove+0x47/0x510 drivers/usb/gadget/udc/pch_udc.c:2986 pch_udc_probe+0xcc6/0x1130 drivers/usb/gadget/udc/pch_udc.c:3109 If usb_add_gadget_udc() in turn fails, it has already dropped the gadget reference, so the extra usb_del_gadget_udc() is a double put. Split the hardware/DMA teardown out into pch_udc_cleanup() and call only that from the probe error path. Fixes: 0f91349b89f3 ("usb: gadget: convert all users to the new udc infrastructure") Cc: stable Reported-by: syzbot+3e2e533aa1b2a75525e7@syzkaller.appspotmail.com Link: https://syzkaller.appspot.com/bug?extid=3e2e533aa1b2a75525e7 Tested-by: syzbot+3e2e533aa1b2a75525e7@syzkaller.appspotmail.com Signed-off-by: Vasileios Almpanis Link: https://patch.msgid.link/20260811-pch-v1-1-f79801c1cd91@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/udc/pch_udc.c | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/drivers/usb/gadget/udc/pch_udc.c b/drivers/usb/gadget/udc/pch_udc.c index 78183eff931846..0199b75a4d4e1f 100644 --- a/drivers/usb/gadget/udc/pch_udc.c +++ b/drivers/usb/gadget/udc/pch_udc.c @@ -2978,16 +2978,8 @@ static void pch_udc_shutdown(struct pci_dev *pdev) pch_udc_set_disconnect(dev); } -static void pch_udc_remove(struct pci_dev *pdev) +static void pch_udc_cleanup(struct pch_udc_dev *dev) { - struct pch_udc_dev *dev = pci_get_drvdata(pdev); - - usb_del_gadget_udc(&dev->gadget); - - /* gadget driver must not be registered */ - if (dev->driver) - dev_err(&pdev->dev, - "%s: gadget driver still bound!!!\n", __func__); /* dma pool cleanup */ dma_pool_destroy(dev->data_requests); @@ -3015,6 +3007,20 @@ static void pch_udc_remove(struct pci_dev *pdev) pch_udc_exit(dev); } +static void pch_udc_remove(struct pci_dev *pdev) +{ + struct pch_udc_dev *dev = pci_get_drvdata(pdev); + + usb_del_gadget_udc(&dev->gadget); + + /* gadget driver must not be registered */ + if (dev->driver) + dev_err(&pdev->dev, + "%s: gadget driver still bound!!!\n", __func__); + + pch_udc_cleanup(dev); +} + static int __maybe_unused pch_udc_suspend(struct device *d) { struct pch_udc_dev *dev = dev_get_drvdata(d); @@ -3105,7 +3111,7 @@ static int pch_udc_probe(struct pci_dev *pdev, const struct pci_device_id *id) return 0; finished: - pch_udc_remove(pdev); + pch_udc_cleanup(dev); return retval; } From b5ffda46ae0d8713963dffdb1caac82275edc3d8 Mon Sep 17 00:00:00 2001 From: Myeonghun Pak Date: Thu, 17 Sep 2026 14:38:56 -0500 Subject: [PATCH 1195/2102] usb: gadget: pch_udc: Disable VBUS work before removing the gadget The GPIO IRQ can queue irq_work_fall and irq_work_rise, and the PCI IRQ can also queue irq_work_fall. Neither work is drained during removal, so its callback can access the gadget driver or controller state after teardown has started, or the device structure after it has been freed. Disable and drain both works before unregistering the gadget. Disabling also prevents the IRQ handlers from requeuing them while their IRQs are still registered. Initialize both works unconditionally before requesting the GPIO IRQ so removal can disable them even without a GPIO IRQ. This issue was identified during our ongoing static-analysis research while reviewing kernel code. Fixes: dd63180b758d ("usb: gadget: pch_udc: Detecting VBUS through GPIO") Fixes: 637b78eb31e0 ("usb: gadget: pch_udc: Detecting VBUS through GPIO with interrupt") Cc: stable@kernel.org # 6.10+ Assisted-by: LLM Co-developed-by: Ijae Kim Signed-off-by: Ijae Kim Signed-off-by: Myeonghun Pak Reviewed-by: Ivy Lopez Link: https://patch.msgid.link/CAGEsz8GQR2vJ8ddedaLg=Yq_RoeTxgoXTQ4-QS8mJpDXNn36qA@mail.gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/udc/pch_udc.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/drivers/usb/gadget/udc/pch_udc.c b/drivers/usb/gadget/udc/pch_udc.c index 0199b75a4d4e1f..ef966c8e84f6d8 100644 --- a/drivers/usb/gadget/udc/pch_udc.c +++ b/drivers/usb/gadget/udc/pch_udc.c @@ -1372,6 +1372,8 @@ static int pch_vbus_gpio_init(struct pch_udc_dev *dev) dev->vbus_gpio.port = NULL; dev->vbus_gpio.intr = 0; + INIT_WORK(&dev->vbus_gpio.irq_work_fall, pch_vbus_gpio_work_fall); + INIT_WORK(&dev->vbus_gpio.irq_work_rise, pch_vbus_gpio_work_rise); /* Retrieve the GPIO line from the USB gadget device */ gpiod = devm_gpiod_get_optional(d, NULL, GPIOD_IN); @@ -1380,7 +1382,6 @@ static int pch_vbus_gpio_init(struct pch_udc_dev *dev) gpiod_set_consumer_name(gpiod, "pch_vbus"); dev->vbus_gpio.port = gpiod; - INIT_WORK(&dev->vbus_gpio.irq_work_fall, pch_vbus_gpio_work_fall); irq_num = gpiod_to_irq(gpiod); if (irq_num > 0) { @@ -1389,8 +1390,6 @@ static int pch_vbus_gpio_init(struct pch_udc_dev *dev) "vbus_detect", dev); if (!err) { dev->vbus_gpio.intr = irq_num; - INIT_WORK(&dev->vbus_gpio.irq_work_rise, - pch_vbus_gpio_work_rise); } else { pr_err("%s: can't request irq %d, err: %d\n", __func__, irq_num, err); @@ -3011,6 +3010,9 @@ static void pch_udc_remove(struct pci_dev *pdev) { struct pch_udc_dev *dev = pci_get_drvdata(pdev); + disable_work_sync(&dev->vbus_gpio.irq_work_fall); + disable_work_sync(&dev->vbus_gpio.irq_work_rise); + usb_del_gadget_udc(&dev->gadget); /* gadget driver must not be registered */ From 814360eb865c185bc01fe1ce7df7c8c7d5bb7375 Mon Sep 17 00:00:00 2001 From: Myeonghun Pak Date: Mon, 21 Sep 2026 23:23:59 -0400 Subject: [PATCH 1196/2102] usb: mtu3: Prevent dr_work rearm during teardown ssusb_otg_switch_exit() drains otg_sx->dr_work with cancel_work_sync(). A later queue_work() from ssusb_set_mode() arms it again. Callers that outlive the cancel are the role-switch store, ssusb_id_notifier(), and the manual-DRD debugfs mode file. The role switch is unregistered on the next line. The extcon notifier is devm-managed, and extcon_sync() invokes it after dropping edev->lock, so unregister is not a barrier. The mode file is removed only after ssusb_gadget_exit(), ssusb_host_exit() and ssusb_rscs_exit(). The late work calls mtu3_stop() or mtu3_start(), writes IPPC registers and calls pm_runtime_get_sync(). dr_work is embedded in the devm_kzalloc()ed struct ssusb_mtk. disable_work_sync() rejects a later queue_work() and drains an item already pending or running. Exit does not enable the work again. This issue was identified during our ongoing static-analysis research while reviewing kernel code. Fixes: 18cfd7b85ced ("usb: mtu3: rebuild role switch flow of extcon") Cc: stable@kernel.org # 6.10+ Assisted-by: LLM Co-developed-by: Ijae Kim Signed-off-by: Ijae Kim Signed-off-by: Myeonghun Pak Link: https://patch.msgid.link/20260922032359.687286-1-mhun512@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/mtu3/mtu3_dr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/usb/mtu3/mtu3_dr.c b/drivers/usb/mtu3/mtu3_dr.c index ffa5b9401dad0a..262922057b13b6 100644 --- a/drivers/usb/mtu3/mtu3_dr.c +++ b/drivers/usb/mtu3/mtu3_dr.c @@ -326,6 +326,6 @@ void ssusb_otg_switch_exit(struct ssusb_mtk *ssusb) { struct otg_switch_mtk *otg_sx = &ssusb->otg_switch; - cancel_work_sync(&otg_sx->dr_work); + disable_work_sync(&otg_sx->dr_work); usb_role_switch_unregister(otg_sx->role_sw); } From 625dd9076e35268f3eedab32391027cf7bd9c6a2 Mon Sep 17 00:00:00 2001 From: Ryan Brue Date: Sun, 13 Sep 2026 17:21:25 -0500 Subject: [PATCH 1197/2102] usb: mtu3: don't run gadget completion callbacks with interrupts disabled mtu3_irq() is a threaded handler, so it runs in process context, but it takes mtu->lock with spin_lock_irqsave(). mtu3_req_complete() then drops the lock with a plain spin_unlock() around usb_gadget_giveback_request(), which leaves hardware interrupts disabled across the gadget function's completion callback. That breaks any callback that reaches netif_rx(). Since the threaded handler is in neither hardirq nor softirq context, netif_rx() takes its local_bh_disable()/local_bh_enable() path, and enabling softirqs with interrupts disabled is not allowed: WARNING: kernel/softirq.c:430 at __local_bh_enable_ip+0x17c/0x188 __local_bh_enable_ip netif_rx rx_complete [u_ether] usb_gadget_giveback_request mtu3_req_complete mtu3_qmu_isr mtu3_irq irq_thread_fn With CONFIG_TRACE_IRQFLAGS, __local_bh_enable_ip() ends with an unconditional local_irq_enable(), so the plain spin_lock() re-taking mtu->lock afterwards runs with interrupts on and is recorded SOFTIRQ-ON-W, while mtu3_gadget_queue() takes the same lock from a softirq (ncm's tx hrtimer), and lockdep follows up with an inconsistent lock state report naming mtu->lock. The locking was right when mtu3_irq() was a hardirq handler. It stopped being right when the handler became threaded without a primary handler; dwc3 hit the same thing the same way and fixed it in the controller driver, in commit 84918a89d6ef ("usb: dwc3: gadget: Let the interrupt handler disable bottom halves."). mtu->lock is never taken in hardirq context: the only handler is threaded and has no primary handler, so disabling softirqs is enough. Take it with spin_lock_bh() in mtu3_irq(). The completion callback then runs with interrupts enabled and softirqs disabled, which is the context netif_rx() expects. The other sites keep spin_lock_irqsave(), which is strictly stronger and still correct; several of them really can be reached from softirq context. Both reports need lockdep to be seen, but the context violation is real: netif_rx() wants either hardirq/softirq context or interrupts enabled, and mtu3 gives it neither. The fallout on a PROVE_LOCKING kernel is not cosmetic either - copying a 21 MB file over USB ethernet hung and reset this board repeatedly before this change. Once interrupts have been left enabled while the thread holds mtu->lock, the tx hrtimer softirq on the same CPU spins on it forever, which is the "CPU0: lock(&mtu->lock); lock(&mtu->lock);" scenario lockdep names. The same copy is reliable after it. Fixes: 13118959cb1a ("usb: mtu3: register mtu3_irq by threaded irq") Cc: stable@kernel.org Assisted-by: LLM Signed-off-by: Ryan Brue Link: https://patch.msgid.link/20260913-usb-mtu3-gadget-completion-callback-fix-v1-1-e3480004fe23@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/mtu3/mtu3_core.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/drivers/usb/mtu3/mtu3_core.c b/drivers/usb/mtu3/mtu3_core.c index 386fcb5d628e8c..fc274646fcdebb 100644 --- a/drivers/usb/mtu3/mtu3_core.c +++ b/drivers/usb/mtu3/mtu3_core.c @@ -790,10 +790,9 @@ static irqreturn_t mtu3_u2_common_isr(struct mtu3 *mtu) static irqreturn_t mtu3_irq(int irq, void *data) { struct mtu3 *mtu = (struct mtu3 *)data; - unsigned long flags; u32 level1; - spin_lock_irqsave(&mtu->lock, flags); + spin_lock_bh(&mtu->lock); /* U3D_LV1ISR is RU */ level1 = mtu3_readl(mtu->mac_base, U3D_LV1ISR); @@ -814,7 +813,7 @@ static irqreturn_t mtu3_irq(int irq, void *data) if (level1 & QMU_INTR) mtu3_qmu_isr(mtu); - spin_unlock_irqrestore(&mtu->lock, flags); + spin_unlock_bh(&mtu->lock); return IRQ_HANDLED; } From 31678e68f82636a27fbad58ae40054557da4fd7e Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Wed, 18 Nov 2026 13:45:19 +0100 Subject: [PATCH 1198/2102] gpio: shared-proxy: propagate -ENOTSUPP from .set_config() The gpio-shared-proxy driver does not propagate -ENOTSUPP returned from the set_config() callback by real GPIO drivers controlling the shared GPIOs. This can lead to a situation where for an open-drain, shared GPIO, we take the emulation path on request - ending up setting the direction to input for the initial user - and then fail to allow simulated output direction for the second user if the driver in question does not support using "real" open-drain. Propagate all errors from the underlying .set_config() call in gpio_shared_proxy_set_config(). Reported-by: Igor Velkov Closes: https://lore.kernel.org/all/20261115-hc4-gpio-shared-od-1@iav.lv/ Fixes: e992d54c6f97 ("gpio: shared-proxy: implement the shared GPIO proxy driver") Tested-by: Igor Velkov Link: https://patch.msgid.link/20261118-gpio-shared-proxy-enotsupp-v1-1-39d3fe4d3aa7@oss.qualcomm.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-shared-proxy.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpio/gpio-shared-proxy.c b/drivers/gpio/gpio-shared-proxy.c index 80412bd4ef2502..60973acc709c0f 100644 --- a/drivers/gpio/gpio-shared-proxy.c +++ b/drivers/gpio/gpio-shared-proxy.c @@ -186,7 +186,7 @@ static int gpio_shared_proxy_set_config(struct gpio_chip *gc, } ret = gpiod_set_config(desc, cfg); - if (ret && ret != -ENOTSUPP) + if (ret) return ret; shared_desc->cfg = cfg; From 71b2cafb76c62c0f800daa94fc4c8f32936a4fbb Mon Sep 17 00:00:00 2001 From: Shunbo Shi Date: Tue, 3 Nov 2026 03:22:10 +0000 Subject: [PATCH 1199/2102] fuse: fix UBSAN warning in fuse_iomap_writeback_range() In fuse_iomap_writeback_range() 'ap' is initialized to '&wpa->ia.ap' unconditionally, but 'wpa' (== data->wpa) is NULL when the writeback of the first folio of a batch starts: 'data' is zero-initialized in fuse_writepages() and fuse_launder_folio(), and fuse_writepages_send() resets data->wpa to NULL after every batch. Taking the address of a member of a NULL pointer is undefined behavior. The bogus initial value of 'ap' is never actually dereferenced: all uses are either guarded by 'if (wpa)' or run after 'ap' has been reassigned in the 'data->wpa == NULL' branch, where a new 'wpa' is allocated first. Still, the expression lets the compiler assume that 'wpa' is non-NULL for the whole function, which could break the 'if (wpa)' check below and turn the latent UB into a real NULL pointer dereference. This can be observed with a kernel built with -fsanitize=null (not part of the default CONFIG_UBSAN flag set) when writeback of an mmap dirty region is triggered, e.g. via msync()/fsync(): UBSAN: member access within null pointer of type 'struct fuse_writepage_args' Call Trace: __ubsan_handle_type_mismatch_v1+0x3f/0x50 fuse_iomap_writeback_range+0x79c/0xbd0 iomap_writepages+0x64/0x140 fuse_writepages+0xe0/0x260 do_writepages+0xaa/0x360 Initialize 'ap' to NULL when 'wpa' is NULL. With this change the warning above is gone while the writeback path is exercised identically. Signed-off-by: Shunbo Shi Signed-off-by: Miklos Szeredi --- fs/fuse/file.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/fuse/file.c b/fs/fuse/file.c index 35e912b9851445..dcf333aaec1798 100644 --- a/fs/fuse/file.c +++ b/fs/fuse/file.c @@ -2272,7 +2272,7 @@ static ssize_t fuse_iomap_writeback_range(struct iomap_writepage_ctx *wpc, { struct fuse_fill_wb_data *data = wpc->wb_ctx; struct fuse_writepage_args *wpa = data->wpa; - struct fuse_args_pages *ap = &wpa->ia.ap; + struct fuse_args_pages *ap = wpa ? &wpa->ia.ap : NULL; struct inode *inode = wpc->inode; struct fuse_inode *fi = get_fuse_inode(inode); struct fuse_conn *fc = get_fuse_conn(inode); From d9013d15b9379b323f1bcdfff7e7d96df537268a Mon Sep 17 00:00:00 2001 From: Hungyu Lin Date: Tue, 3 Nov 2026 08:34:25 +0000 Subject: [PATCH 1200/2102] fuse: clear the old EOF tail before writeback-cache writes Buffered writeback-cache writes go through iomap_file_buffered_write(), but do not clear cached data between the old EOF and the write position. If a shared mapping dirtied the tail of the old EOF page, an extending write can expose those bytes as file contents instead of zeros. A later writeback can also send them to the server. Clear the gap under the existing inode lock before the buffered write. Use the same page-cache cleanup as fuse_perform_write() does for write-through writes, leaving the write range itself untouched. Fixes: 4d99ff8f12eb ("fuse: Turn writeback cache on") Cc: stable@vger.kernel.org Signed-off-by: Hungyu Lin Signed-off-by: Miklos Szeredi --- fs/fuse/file.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/fs/fuse/file.c b/fs/fuse/file.c index dcf333aaec1798..9e64fe040277ab 100644 --- a/fs/fuse/file.c +++ b/fs/fuse/file.c @@ -1580,6 +1580,11 @@ static ssize_t fuse_cache_write_iter(struct kiocb *iocb, struct iov_iter *from) written = direct_write_fallback(iocb, from, written, fuse_perform_write(iocb, from)); } else if (writeback) { + loff_t old_size = i_size_read(inode); + + if (iocb->ki_pos > old_size) + truncate_pagecache_range(inode, old_size, iocb->ki_pos - 1); + /* * Use iomap so that we can do granular uptodate reads * and granular dirty tracking for large folios. From 7f7b822d09c5590defcc61a37ffbd5a3533ed518 Mon Sep 17 00:00:00 2001 From: Miklos Szeredi Date: Fri, 20 Nov 2026 11:33:01 +0100 Subject: [PATCH 1201/2102] fuse: limit name size in listxattr Limit the size of names to XATTR_NAME_MAX. Return -EIO to the listxattr() caller if the server exceeds this limit. Fixes: 92a8780e1136 ("[PATCH] FUSE - extended attribute operations") Cc: stable@vger.kernel.org Signed-off-by: Miklos Szeredi --- fs/fuse/xattr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/fuse/xattr.c b/fs/fuse/xattr.c index 53e3c5e6fff0dd..02f780e7426d31 100644 --- a/fs/fuse/xattr.c +++ b/fs/fuse/xattr.c @@ -94,7 +94,7 @@ static int fuse_verify_xattr_list(char *list, size_t size) while (size) { size_t thislen = strnlen(list, size); - if (!thislen || thislen == size) + if (!thislen || thislen == size || thislen > XATTR_NAME_MAX) return -EIO; size -= thislen + 1; From 7a7d9a926501ff2c7a11d5cbd86d20b305b71bea Mon Sep 17 00:00:00 2001 From: Aldo Ariel Panzardo Date: Tue, 15 Sep 2026 01:07:25 -0300 Subject: [PATCH 1202/2102] usb: gadget: configfs: zero-terminate Unicode property data Unicode extended properties account for a trailing UTF-16 NUL in data_len. The show and descriptor paths consequently consume one more source byte than ext_prop_data_store() allocates, exposing the byte immediately after the allocation. Allocate an additional zeroed byte for the source string. This preserves the descriptor length, supplies the terminator expected by both consumers, and prevents the one-byte out-of-bounds read. Fixes: 7419485f197c ("usb: gadget: configfs: OS Extended Properties descriptors support") Reported-by: Bingquan Chen Link: https://lore.kernel.org/all/20260421141010.5607-1-patzilla007@gmail.com/ Cc: stable Signed-off-by: Aldo Ariel Panzardo Link: https://patch.msgid.link/20260915040725.2421387-1-qwe.aldo@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/configfs.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/usb/gadget/configfs.c b/drivers/usb/gadget/configfs.c index 51df6d1d1487af..568b2a0a6df812 100644 --- a/drivers/usb/gadget/configfs.c +++ b/drivers/usb/gadget/configfs.c @@ -1351,9 +1351,10 @@ static ssize_t ext_prop_data_store(struct config_item *item, if (page[len - 1] == '\n' || page[len - 1] == '\0') --len; - new_data = kmemdup(page, len, GFP_KERNEL); + new_data = kzalloc(len + 1, GFP_KERNEL); if (!new_data) return -ENOMEM; + memcpy(new_data, page, len); if (desc->opts_mutex) mutex_lock(desc->opts_mutex); From 21fcab32394fed89c89e2a2a80e81b6af315b7c1 Mon Sep 17 00:00:00 2001 From: Myeonghun Pak Date: Mon, 21 Sep 2026 19:08:47 -0400 Subject: [PATCH 1203/2102] usb: gadget: tegra-xudc: Unregister VBUS notifier tegra_xudc_vbus_notify() queues usb_role_sw_work. The notifier is registered with usb_register_notifier(), while devm_usb_get_phy_by_node() is passed NULL, so devres never unregisters it. vbus_nb lives in the devm allocation, so a later PHY event calls it after xudc is freed. Unregister the notifier before cancel_work_sync(). That waits for in-flight callbacks, and the existing cancel drains the last work. This issue was identified during our ongoing static-analysis research while reviewing kernel code. Fixes: 2582d629c9e0 ("usb: gadget: xudc: Refactor update data role work") Cc: stable@kernel.org Assisted-by: LLM Co-developed-by: Ijae Kim Signed-off-by: Ijae Kim Signed-off-by: Myeonghun Pak Link: https://patch.msgid.link/20260921230849.502492-2-mhun512@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/udc/tegra-xudc.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/usb/gadget/udc/tegra-xudc.c b/drivers/usb/gadget/udc/tegra-xudc.c index a7736627e6e214..b1f09d70dac690 100644 --- a/drivers/usb/gadget/udc/tegra-xudc.c +++ b/drivers/usb/gadget/udc/tegra-xudc.c @@ -3923,6 +3923,12 @@ static void tegra_xudc_remove(struct platform_device *pdev) pm_runtime_get_sync(xudc->dev); + for (i = 0; i < xudc->soc->num_phys; i++) { + if (xudc->usbphy[i]) + usb_unregister_notifier(xudc->usbphy[i], + &xudc->vbus_nb); + } + cancel_delayed_work_sync(&xudc->plc_reset_work); cancel_work_sync(&xudc->usb_role_sw_work); From e2fe662f2f10f1f46a1b00611b73411760609ed4 Mon Sep 17 00:00:00 2001 From: Myeonghun Pak Date: Mon, 21 Sep 2026 19:08:48 -0400 Subject: [PATCH 1204/2102] usb: gadget: tegra-xudc: Disable reset delayed works The devm port-status IRQ stays registered through remove() and can queue port_reset_war_work and plc_reset_work after cancel_delayed_work_sync() returns. remove() never stops the first. disable_delayed_work_sync() drains both and rejects a later queue. usb_role_sw_work stays on cancel_work_sync(). The PHY notifier is its producer and is unregistered before this cancel. This issue was identified during our ongoing static-analysis research while reviewing kernel code. Fixes: 49db427232fe ("usb: gadget: Add UDC driver for tegra XUSB device mode controller") Cc: stable@kernel.org # 6.10+ Assisted-by: LLM Co-developed-by: Ijae Kim Signed-off-by: Ijae Kim Signed-off-by: Myeonghun Pak Link: https://patch.msgid.link/20260921230849.502492-3-mhun512@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/udc/tegra-xudc.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/usb/gadget/udc/tegra-xudc.c b/drivers/usb/gadget/udc/tegra-xudc.c index b1f09d70dac690..f696b9bf222f5c 100644 --- a/drivers/usb/gadget/udc/tegra-xudc.c +++ b/drivers/usb/gadget/udc/tegra-xudc.c @@ -3929,7 +3929,8 @@ static void tegra_xudc_remove(struct platform_device *pdev) &xudc->vbus_nb); } - cancel_delayed_work_sync(&xudc->plc_reset_work); + disable_delayed_work_sync(&xudc->port_reset_war_work); + disable_delayed_work_sync(&xudc->plc_reset_work); cancel_work_sync(&xudc->usb_role_sw_work); usb_del_gadget_udc(&xudc->gadget); From 878c885830ef004a32e8974c4d1ae14e2ea30c5a Mon Sep 17 00:00:00 2001 From: Philipp Stanner Date: Fri, 20 Nov 2026 12:16:16 +0100 Subject: [PATCH 1205/2102] dma-buf/dma-fence: Prevent misordering for error checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Many users of dma_fence do things like: // Thread A dma_fence_set_error(f, -EINVAL); dma_fence_signal(f); // <- test_and_set_bit() orders against the above. // Thread B if (dma_fence_is_signaled(f)) // <- Does test_bit(), no ordering. pr_info("err: %i\n", f->error); // <- Can be loaded first. There is no memory ordering between reading of the signaled-bit and reading of the error code. This can result in outdated, wrong error codes being evaluated by the user. That's a significant bug when we consider that fences' purpose is to propagate the state of jobs running on hardware. dma_fence_get_status() does take the fence lock, presumably to ensure ordering, but it is broken, too, because the read misordering can simply happen within the critical section. It's not entirely clear since when this bug exists, but at least since dma_fence_get_status() was added, which is why its birth commit is marked as the Fixes commit here. Ensure ordering for everyone evaluating the error code centrally by using test_bit_acquire() in dma_fence_test_signaled_flag(). Cc: stable@vger.kernel.org Fixes: d6c99f4bf093 ("dma-fence: Wrap querying the fence->status") Reviewed-by: Christian König Signed-off-by: Philipp Stanner Link: https://patch.msgid.link/20261120111615.2940647-2-phasta@kernel.org --- include/linux/dma-fence.h | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/include/linux/dma-fence.h b/include/linux/dma-fence.h index dd07d128adc3b0..64330bf5256139 100644 --- a/include/linux/dma-fence.h +++ b/include/linux/dma-fence.h @@ -487,16 +487,23 @@ const char __rcu *dma_fence_timeline_name(struct dma_fence *fence); * with the fence in any way. The user must, therefore, ensure through other * means that fences get signaled eventually. * - * This function uses test_bit(), which is thread-safe. Naturally, this function - * should be used opportunistically; a fence could get signaled at any moment - * after the check is done. + * Naturally, this function should be used opportunistically; a fence could get + * signaled at any moment after the check is done. + * + * This function provides acquire ordering. This means that all stores + * preceding the signaling of a fence are visible in correct order to users of + * this function. * * Return: true if signaled, false otherwise. */ static inline bool dma_fence_test_signaled_flag(struct dma_fence *fence) { - return test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags); + /* + * The release counterpart is the test_and_set_bit() in + * dma_fence_signal_timestamp_locked(). + */ + return test_bit_acquire(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags); } /** From 599210e5544d34ee36a2dbdf7f22797951a97a5e Mon Sep 17 00:00:00 2001 From: Paolo Bonzini Date: Fri, 20 Nov 2026 14:29:15 +0100 Subject: [PATCH 1206/2102] KVM: PPC: remove unnecessary #ifdef booke.o is only built as part of kvm-e500-objs (which is conditional on $(CONFIG_KVM_E500V2)) or kvm-e500mc-objs (likewise conditional on $(CONFIG_KVM_E500MC)). Thus, the #ifdef in kvmppc_core_check_requests is always true. Remove it. Signed-off-by: Paolo Bonzini --- arch/powerpc/kvm/booke.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/arch/powerpc/kvm/booke.c b/arch/powerpc/kvm/booke.c index fd7f24a68b31a1..ba762ac1fb569c 100644 --- a/arch/powerpc/kvm/booke.c +++ b/arch/powerpc/kvm/booke.c @@ -738,10 +738,8 @@ int kvmppc_core_check_requests(struct kvm_vcpu *vcpu) if (kvm_check_request(KVM_REQ_PENDING_TIMER, vcpu)) update_timer_ints(vcpu); -#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC) if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) kvmppc_core_flush_tlb(vcpu); -#endif if (kvm_check_request(KVM_REQ_WATCHDOG, vcpu)) { vcpu->run->exit_reason = KVM_EXIT_WATCHDOG; From b076667f98ae16366ac6612cb535e4675d81d9b3 Mon Sep 17 00:00:00 2001 From: Paolo Bonzini Date: Fri, 20 Nov 2026 14:33:37 +0100 Subject: [PATCH 1207/2102] KVM: PPC: implement .flush_memslot for BookE and Book3S-PR kvm_arch_flush_shadow_memslot() is called when memslots are deleted and moved, with no MMU notifier invalidation. This means that the shadow pages (HPTEs for PR, TLB entries for e500) retain mappings from host pfns to the old slot's gfns. Implement the callback by unmapping the GFNs in the same way that Book3S-HV does it. Note that kvmppc_core_flush_memslot_pr() does not need TLB invalidation, because kvmppc_mmu_pte_pflush() calls invalidate_pte() on the entries, and that in turn invalidates the entry through either the tlbie instruction or mmu_hash_ops.hpte_invalidate(). Signed-off-by: Paolo Bonzini --- arch/powerpc/kvm/book3s_pr.c | 8 +++++++- arch/powerpc/kvm/booke.c | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/arch/powerpc/kvm/book3s_pr.c b/arch/powerpc/kvm/book3s_pr.c index 1894968f2c25c4..66a9e446ab6483 100644 --- a/arch/powerpc/kvm/book3s_pr.c +++ b/arch/powerpc/kvm/book3s_pr.c @@ -1893,7 +1893,13 @@ static int kvm_vm_ioctl_get_dirty_log_pr(struct kvm *kvm, static void kvmppc_core_flush_memslot_pr(struct kvm *kvm, struct kvm_memory_slot *memslot) { - return; + struct kvm_gfn_range range = { + .slot = memslot, + .start = memslot->base_gfn, + .end = memslot->base_gfn + memslot->npages, + }; + + kvm_unmap_gfn_range_pr(kvm, &range); } static int kvmppc_core_prepare_memory_region_pr(struct kvm *kvm, diff --git a/arch/powerpc/kvm/booke.c b/arch/powerpc/kvm/booke.c index ba762ac1fb569c..fffb28fe9a0f98 100644 --- a/arch/powerpc/kvm/booke.c +++ b/arch/powerpc/kvm/booke.c @@ -1844,6 +1844,14 @@ void kvmppc_core_commit_memory_region(struct kvm *kvm, void kvmppc_core_flush_memslot(struct kvm *kvm, struct kvm_memory_slot *memslot) { + struct kvm_gfn_range range = { + .slot = memslot, + .start = memslot->base_gfn, + .end = memslot->base_gfn + memslot->npages, + }; + + if (kvm_unmap_gfn_range(kvm, &range)) + kvm_flush_remote_tlbs(kvm); } void kvmppc_set_epcr(struct kvm_vcpu *vcpu, u32 new_epcr) From 031ef175269d11b6368a9bff71a6a14aaa52b3f4 Mon Sep 17 00:00:00 2001 From: Paolo Bonzini Date: Tue, 17 Nov 2026 19:59:22 +0100 Subject: [PATCH 1208/2102] KVM: SEV: never emulate after #NPF on paging structures KVM cannot walk the encrypted page tables of SEV guests, so there is no point in emulating the instruction if the #NPF fault was caused by either data or code. In the latter case the instruction buffer is going to be empty, so emulation was avoided by resuming the guest, but in the data case KVM attempted emulation which is pointless. Apply the existing check for PFERR_GUEST_PAGE_MASK even if the instruction buffer was filled. Reported-by: Sasha Levin Signed-off-by: Paolo Bonzini Link: https://patch.msgid.link/20261117185922.466255-1-pbonzini@redhat.com Cc: stable@vger.kernel.org Signed-off-by: Paolo Bonzini --- arch/x86/kvm/svm/svm.c | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c index afb45431734793..2dd05cd6b75714 100644 --- a/arch/x86/kvm/svm/svm.c +++ b/arch/x86/kvm/svm/svm.c @@ -5346,19 +5346,29 @@ static int svm_check_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type, } /* - * Emulate for SEV guests if the insn buffer is not empty. The buffer - * will be empty if the DecodeAssist microcode cannot fetch bytes for - * the faulting instruction because the code fetch itself faulted, e.g. - * the guest attempted to fetch from emulated MMIO or a guest page - * table used to translate CS:RIP resides in emulated MMIO. + * Under SEV, page tables are encrypted and cannot be read by the + * hypervisor, so there is no way to resolve a fault on page tables. */ + error_code = svm->vmcb->control.exit_info_1; + if (error_code & PFERR_GUEST_PAGE_MASK) + goto resume_guest; + if (likely(insn_len)) return X86EMUL_CONTINUE; /* - * Detect and workaround Errata 1096 Fam_17h_00_0Fh. + * The insn buffer was empty; the DecodeAssist microcode could not fetch + * bytes for the faulting instruction because the code fetch itself faulted, + * e.g. the guest attempted to fetch from emulated MMIO or a guest page + * table used to translate CS:RIP resides in emulated MMIO. * - * Errata: + * A data fault instead could be Errata 1096 Fam_17h_00_0Fh, so only + * retry for a fetch fault and otherwise try to workaround it. + */ + if (error_code & PFERR_FETCH_MASK) + goto resume_guest; + + /* * When CPU raises #NPF on guest data access and vCPU CR4.SMAP=1, it is * possible that CPU microcode implementing DecodeAssist will fail to * read guest memory at CS:RIP and vmcb.GuestIntrBytes will incorrectly @@ -5385,12 +5395,8 @@ static int svm_check_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type, * retrieve the instruction bytes is legitimate (see abvoe). * * In addition, don't apply the erratum workaround if the #NPF occurred - * while translating guest page tables (see below). + * while translating guest page tables (see above). */ - error_code = svm->vmcb->control.exit_info_1; - if (error_code & (PFERR_GUEST_PAGE_MASK | PFERR_FETCH_MASK)) - goto resume_guest; - smep = kvm_is_cr4_bit_set(vcpu, X86_CR4_SMEP); smap = kvm_is_cr4_bit_set(vcpu, X86_CR4_SMAP); is_user = svm_get_cpl(vcpu) == 3; From 35b44c7f0c7ac06c53c8e7a70cb57a7ca000b88c Mon Sep 17 00:00:00 2001 From: Greg Kroah-Hartman Date: Fri, 20 Nov 2026 14:46:00 +0100 Subject: [PATCH 1209/2102] Revert "USB: cdc-acm: refuse writes after disconnect" This reverts commit b92566b2648c5661a571f693336dba7a32d5dc3b. It's not the correct fix. Reported-by: Johan Hovold Link: https://lore.kernel.org/r/awAtdlEpSLc1ges1@hovoldconsulting.com Fixes: b92566b2648c ("USB: cdc-acm: refuse writes after disconnect") Cc: William A. Kennington III Cc: Oliver Neukum Signed-off-by: Greg Kroah-Hartman --- drivers/usb/class/cdc-acm.c | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/drivers/usb/class/cdc-acm.c b/drivers/usb/class/cdc-acm.c index 44f69016238433..4a0c7806fc0b45 100644 --- a/drivers/usb/class/cdc-acm.c +++ b/drivers/usb/class/cdc-acm.c @@ -762,7 +762,6 @@ static void acm_port_destruct(struct tty_port *port) if (acm->minor != ACM_MINOR_INVALID) acm_release_minor(acm); usb_put_intf(acm->control); - usb_put_intf(acm->data); kfree(acm->country_codes); kfree(acm); } @@ -849,11 +848,6 @@ static ssize_t acm_tty_write(struct tty_struct *tty, const u8 *buf, dev_vdbg(&acm->data->dev, "%zu bytes from tty layer\n", count); spin_lock_irqsave(&acm->write_lock, flags); - if (acm->disconnected) { - spin_unlock_irqrestore(&acm->write_lock, flags); - return -ENODEV; - } - wbn = acm_wb_alloc(acm); if (wbn < 0) { spin_unlock_irqrestore(&acm->write_lock, flags); @@ -861,6 +855,12 @@ static ssize_t acm_tty_write(struct tty_struct *tty, const u8 *buf, } wb = &acm->wb[wbn]; + if (!acm->dev) { + wb->use = false; + spin_unlock_irqrestore(&acm->write_lock, flags); + return -ENODEV; + } + count = (count > acm->writesize) ? acm->writesize : count; dev_vdbg(&acm->data->dev, "writing %zu bytes\n", count); memcpy(wb->buf, buf, count); @@ -890,9 +890,6 @@ static ssize_t acm_tty_write(struct tty_struct *tty, const u8 *buf, static unsigned int acm_tty_write_room(struct tty_struct *tty) { struct acm *acm = tty->driver_data; - - if (acm->disconnected) - return 0; /* * Do not let the line discipline to know that we have a reserve, * or it might get too enthusiastic. @@ -1403,7 +1400,6 @@ static int acm_probe(struct usb_interface *intf, acm->data = data_interface; usb_get_intf(acm->control); /* undone in destruct() */ - usb_get_intf(acm->data); minor = acm_alloc_minor(acm); if (minor < 0) { @@ -1631,9 +1627,7 @@ static void acm_disconnect(struct usb_interface *intf) if (!acm) return; - spin_lock_irq(&acm->write_lock); acm->disconnected = true; - spin_unlock_irq(&acm->write_lock); /* * there is a circular dependency. acm_softint() can resubmit * the URBs in error handling so we need to block any From 46c53aa3b831135fdcb5893d0885b1bc43394c00 Mon Sep 17 00:00:00 2001 From: Aldo Ariel Panzardo Date: Tue, 15 Sep 2026 08:08:33 -0300 Subject: [PATCH 1210/2102] usb: gadget: ncm: validate the NDP chain before parsing The (d)wNextNdpIndex fields form a linked chain supplied entirely by the USB host. ncm_unwrap_ntb() follows this chain in a do-while loop without cycle detection, so a malicious host can force the gadget to repeatedly parse the same NDP and allocate datagram skbs until a GFP_ATOMIC allocation fails. This causes avoidable memory pressure and allows a malicious host to deny service to the gadget receive path. Example: a 64-byte NTB16 from the host with a single NDP whose wNextNdpIndex points back to its own offset: Offset 0: NTH16 dwSignature = "NCMH" wHeaderLength = 12 wBlockLength = 64 wNdpIndex = 12 <- first NDP at byte 12 Offset 12: NDP16 dwSignature = "NCM0" wLength = 16 wNextNdpIndex = 12 <- points to itself Offset 20: DPE16[0] wDatagramIndex = 32 wDatagramLength = 14 Offset 24: DPE16[1] wDatagramIndex = 0 <- terminator wDatagramLength = 0 Offset 32: 14-byte Ethernet frame (payload) The existing do-while loop reads this NDP, processes the datagram entry, reads wNextNdpIndex (12), and jumps back to the same NDP indefinitely. Fix this by prewalking the NDP chain using only bounded header reads before parsing any NDP. NDP offsets must be four-byte aligned, so following more than block_len / 4 valid offsets proves that the chain contains a cycle. This terminates cyclic chains without imposing an arbitrary limit on valid NTBs or allocating skbs before the chain is known to terminate. The prewalk is safe for both NDP16 and NDP32. Fixes: 370af734dfaf ("usb: gadget: NCM: RX function support multiple NDPs") Cc: stable@kernel.org Signed-off-by: Aldo Ariel Panzardo Link: https://patch.msgid.link/20260915110833.2721086-1-qwe.aldo@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_ncm.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/drivers/usb/gadget/function/f_ncm.c b/drivers/usb/gadget/function/f_ncm.c index 7e945668f01703..c919ebb0d09f62 100644 --- a/drivers/usb/gadget/function/f_ncm.c +++ b/drivers/usb/gadget/function/f_ncm.c @@ -1180,6 +1180,7 @@ static int ncm_unwrap_ntb(struct gether *port, unsigned dg_len, dg_len2; unsigned ndp_len; unsigned block_len; + unsigned int ndp_count, next_ndp_index; struct sk_buff *skb2; int ret = -EINVAL; unsigned ntb_max = le32_to_cpu(ntb_parameters.dwNtbOutMaxSize); @@ -1229,6 +1230,30 @@ static int ncm_unwrap_ntb(struct gether *port, } ndp_index = get_ncm(&tmp, opts->ndp_index); + next_ndp_index = ndp_index; + ndp_count = 0; + + /* Validate the NDP chain before allocating datagram skbs. */ + while (next_ndp_index) { + if (next_ndp_index % 4 || + next_ndp_index < opts->nth_size || + next_ndp_index > block_len - opts->ndp_size) { + INFO(port->func.config->cdev, "Bad index: %#X\n", + next_ndp_index); + goto err; + } + + /* More aligned offsets than fit in the NTB imply a cycle. */ + if (++ndp_count > block_len / 4) { + INFO(port->func.config->cdev, "NDP chain cycle\n"); + goto err; + } + + tmp = (__le16 *)(ntb_ptr + next_ndp_index); + tmp += 3; /* skip the signature and length */ + tmp += opts->reserved1; + next_ndp_index = get_ncm(&tmp, opts->next_ndp_index); + } /* Run through all the NDP's in the NTB */ do { From 3146702513069d070a8374e20ee0da3a256da2d0 Mon Sep 17 00:00:00 2001 From: Boyan Liu Date: Thu, 15 Oct 2026 10:45:08 +0800 Subject: [PATCH 1211/2102] usb: gadget: f_ncm: Fix use-after-free in ncm_wrap_ntb() The err: path of ncm_wrap_ntb() frees ncm->skb_tx_data and ncm->skb_tx_ndp but never clears the pointers. The rest of the file treats NULL as "no aggregation in progress", and the other release site, package_for_tx(), clears them after freeing. When the NTH skb allocation succeeds but the NDP skb allocation fails -- both GFP_ATOMIC, so this happens under memory pressure -- the err: path frees both skbs and leaves stale pointers. The next transmit passes the guard on the freed skb_tx_data, reads ->len from the freed skb, and package_for_tx() may then write the NTB header through the freed skb's ->data: BUG: KASAN: slab-use-after-free in ncm_wrap_ntb (drivers/usb/gadget/function/f_ncm.c:1044) Read of size 4 at addr ffff888108582930 by task kworker/1:2/1623 Call Trace: ncm_wrap_ntb (drivers/usb/gadget/function/f_ncm.c:1044) eth_start_xmit (drivers/usb/gadget/function/u_ether.c:543) __dev_queue_xmit (net/core/dev.c:4884) Freed by task 4999: napi_skb_cache_put (net/core/skbuff.c:1471) /* deferred dev_kfree_skb_any() from err: */ net_tx_action (net/core/dev.c:5854) The buggy address belongs to the object at ffff8881085828c0 which belongs to the cache skbuff_head_cache of size 240 Clear both pointers after freeing so the next transmit re-enters the allocation branch on a clean state instead of dereferencing freed skbs. Fixes: 6d3865f9d41f ("usb: gadget: NCM: Add transmit multi-frame.") Cc: stable@kernel.org Reported-by: co+02480a85e1a0d4f5@bugs.sh Signed-off-by: Boyan Liu Link: https://patch.msgid.link/20261015024508.3179-1-yymhvert@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_ncm.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/drivers/usb/gadget/function/f_ncm.c b/drivers/usb/gadget/function/f_ncm.c index c919ebb0d09f62..aa71f7381bca64 100644 --- a/drivers/usb/gadget/function/f_ncm.c +++ b/drivers/usb/gadget/function/f_ncm.c @@ -1132,10 +1132,14 @@ static struct sk_buff *ncm_wrap_ntb(struct gether *port, if (skb) dev_kfree_skb_any(skb); - if (ncm->skb_tx_data) + if (ncm->skb_tx_data) { dev_kfree_skb_any(ncm->skb_tx_data); - if (ncm->skb_tx_ndp) + ncm->skb_tx_data = NULL; + } + if (ncm->skb_tx_ndp) { dev_kfree_skb_any(ncm->skb_tx_ndp); + ncm->skb_tx_ndp = NULL; + } return NULL; } From 0f02f0a79b33c3e1ce210837b6fcf26819306d5a Mon Sep 17 00:00:00 2001 From: Xinsheng Zhu Date: Mon, 9 Nov 2026 01:11:10 -0500 Subject: [PATCH 1212/2102] usb: gadget: f_ncm: prevent double-free of OS descriptor table ncm_bind() allocates an OS descriptor table only when cdev->use_os_string is enabled. However, ncm_unbind() frees the table and resets f->os_desc_n without clearing f->os_desc_table, leaving a dangling pointer. When a ConfigFS gadget is unbound, the function object can be reused for a subsequent bind. The OS descriptor support can be toggled through the ConfigFS os_desc/use attribute, which determines cdev->use_os_string on the next bind. If this flag changes from true to false between binds, ncm_bind() skips the allocation and leaves f->os_desc_table pointing to the previously freed memory. A subsequent unbind may therefore free the stale pointer again, resulting in a double-free. Set f->os_desc_table to NULL after freeing it to prevent the stale pointer from being reused across bind/unbind cycles. Fixes: 793409292382 ("usb: gadget: f_ncm: Add OS descriptor support") Cc: stable Signed-off-by: Xinsheng Zhu Link: https://patch.msgid.link/20261109061110.80422-1-xinsheng.zhu.ny@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_ncm.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/usb/gadget/function/f_ncm.c b/drivers/usb/gadget/function/f_ncm.c index aa71f7381bca64..9c6a86e05185e2 100644 --- a/drivers/usb/gadget/function/f_ncm.c +++ b/drivers/usb/gadget/function/f_ncm.c @@ -1775,6 +1775,7 @@ static void ncm_unbind(struct usb_configuration *c, struct usb_function *f) hrtimer_cancel(&ncm->task_timer); kfree(f->os_desc_table); + f->os_desc_table = NULL; f->os_desc_n = 0; ncm_string_defs[0].id = 0; From 597d3babb58720a2fe231138f33808e3aae6597f Mon Sep 17 00:00:00 2001 From: Massimo Toscanelli Date: Fri, 23 Oct 2026 12:15:27 +0000 Subject: [PATCH 1213/2102] usb: gadget: f_ncm: do not notify from ncm_set_alt() ncm_set_alt() calls ncm_notify() for both altsettings of the data interface. So a notification is already queued at SET_CONFIGURATION, when altsetting 0 is selected, and it waits until the host reads the interrupt endpoint. The USB 2.0 LPM ECN (section 2.2.2) lets a device answer NYET to an LPM request when it has data pending for the host, and DWC3 does so. So when the host loads no class driver, like the USB-IF test tool, the device never enters L1 and the LPM L1 test fails. The CDC NCM spec (version 1.1, section 9.2) [1] asks for the notifications only when the host selects altsetting 1. There the call is not needed: gether_connect() already calls ncm_open() or ncm_close(), and both notify. The extra call only restarts the sequence while the first notification is in flight, so the host gets two connection notifications before the speed one. The old ether.c also notified only for altsetting 1, until commit da741b8c56d6 ("usb ethernet gadget: split CDC Ethernet function") moved the call out of that branch in f_ecm. f_ncm copied that pattern. Remove the call. Fixes: 9f6ce4240a2b ("usb: gadget: f_ncm.c added") Cc: stable Link: https://www.usb.org/sites/default/files/NCM11.pdf # [1] Signed-off-by: Massimo Toscanelli Reviewed-by: Aldo Ariel Panzardo Link: https://patch.msgid.link/20261023-ncm-ecm-lpm-v1-1-d01e81fbf460@leica-geosystems.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_ncm.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/drivers/usb/gadget/function/f_ncm.c b/drivers/usb/gadget/function/f_ncm.c index 9c6a86e05185e2..5b28b871b0f3b9 100644 --- a/drivers/usb/gadget/function/f_ncm.c +++ b/drivers/usb/gadget/function/f_ncm.c @@ -921,10 +921,6 @@ static int ncm_set_alt(struct usb_function *f, unsigned intf, unsigned alt) return PTR_ERR(net); ncm->netdev = net; } - - spin_lock(&ncm->lock); - ncm_notify(ncm); - spin_unlock(&ncm->lock); } else goto fail; From dd6b7ab9efa052ee67feb660c98e0c5e9545cfbc Mon Sep 17 00:00:00 2001 From: Massimo Toscanelli Date: Fri, 23 Oct 2026 12:15:28 +0000 Subject: [PATCH 1214/2102] usb: gadget: f_ecm: do not notify from ecm_set_alt() ecm_set_alt() calls ecm_notify() for both altsettings of the data interface. So a notification is already queued at SET_CONFIGURATION, when altsetting 0 is selected, and it waits until the host reads the interrupt endpoint. The USB 2.0 LPM ECN (section 2.2.2) lets a device answer NYET to an LPM request when it has data pending for the host, and DWC3 does so. So when the host loads no class driver, the device never enters L1. For altsetting 1 the call is not needed: gether_connect() already calls ecm_open() or ecm_close(), and both notify. The extra call only restarts the sequence while the first notification is in flight, so the host gets two connection notifications before the speed one. The removed comment calls this a minor disagreement with the ECM spec. Remove the call and the comment. Fixes: da741b8c56d6 ("usb ethernet gadget: split CDC Ethernet function") Cc: stable Signed-off-by: Massimo Toscanelli Reviewed-by: Aldo Ariel Panzardo Link: https://patch.msgid.link/20261023-ncm-ecm-lpm-v1-2-d01e81fbf460@leica-geosystems.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_ecm.c | 8 -------- 1 file changed, 8 deletions(-) diff --git a/drivers/usb/gadget/function/f_ecm.c b/drivers/usb/gadget/function/f_ecm.c index e495bac4efeb5a..c8c3a7d1c80426 100644 --- a/drivers/usb/gadget/function/f_ecm.c +++ b/drivers/usb/gadget/function/f_ecm.c @@ -581,14 +581,6 @@ static int ecm_set_alt(struct usb_function *f, unsigned intf, unsigned alt) if (IS_ERR(net)) return PTR_ERR(net); } - - /* NOTE this can be a minor disagreement with the ECM spec, - * which says speed notifications will "always" follow - * connection notifications. But we allow one connect to - * follow another (if the first is in flight), and instead - * just guarantee that a speed notification is always sent. - */ - ecm_notify(ecm); } else goto fail; From 3b6b2bb5170c0840fa0f68d6106aa79152b7ef56 Mon Sep 17 00:00:00 2001 From: Chaithanya Lagisetty Date: Tue, 15 Sep 2026 08:44:17 +0000 Subject: [PATCH 1215/2102] usb: gadget: f_loopback: fix descriptor leak on unbind loopback_bind() allocates descriptor copies through usb_assign_descriptors(), but f_loopback does not release them during the unbind path. On every bind/unbind cycle of the gadget (for example by repeatedly writing the UDC attribute through configfs) a new set of descriptors is allocated while the previous ones are leaked. syzbot reported this via kmemleak: BUG: memory leak unreferenced object 0xffff888016b8f180 (size 64): comm "repro", pid 5613 backtrace: __kmalloc_noprof+0x3bf/0x550 usb_copy_descriptors+0x6c/0x160 usb_assign_descriptors+0x48/0x180 loopback_bind+0xff/0x120 usb_add_function+0xca/0x270 configfs_composite_bind+0x667/0x9b0 gadget_bind_driver+0xed/0x390 Move descriptor cleanup to a new loopback_unbind() callback that frees them with usb_free_all_descriptors(), matching the lifecycle used by other gadget functions such as f_acm. With descriptors released during unbind, the usb_free_all_descriptors() call in lb_free_func() becomes redundant and can be removed. Tested with CONFIG_DEBUG_KMEMLEAK=y, CONFIG_USB_CONFIGFS_F_LB_SS=y and CONFIG_USBIP_VUDC=y by running the syzbot reproducer in QEMU with kmemleak=on. The patched and unpatched kernels were built from the same tree, config and compiler, so this patch is the only difference between them. Without it, five reproducer iterations produce three leak reports, every one of them through loopback_bind(). With it applied, 25 iterations produce none and kmemleak stays silent. Fixes: 10287baec761 ("usb: gadget: always update HS/SS descriptors and create a copy of them") Cc: stable Reported-by: syzbot+28cf08dec5895bd562e6@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=28cf08dec5895bd562e6 Tested-by: Chaithanya Lagisetty Assisted-by: Cursor:claude-opus-5 Signed-off-by: Chaithanya Lagisetty Link: https://patch.msgid.link/20260915084417.131614-1-nagachaithanya9911@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/function/f_loopback.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/usb/gadget/function/f_loopback.c b/drivers/usb/gadget/function/f_loopback.c index d2d07fb49e704b..40aaf2eb00f24d 100644 --- a/drivers/usb/gadget/function/f_loopback.c +++ b/drivers/usb/gadget/function/f_loopback.c @@ -216,6 +216,11 @@ static int loopback_bind(struct usb_configuration *c, struct usb_function *f) return 0; } +static void loopback_unbind(struct usb_configuration *c, struct usb_function *f) +{ + usb_free_all_descriptors(f); +} + static void lb_free_func(struct usb_function *f) { struct f_lb_opts *opts; @@ -226,7 +231,6 @@ static void lb_free_func(struct usb_function *f) opts->refcnt--; mutex_unlock(&opts->lock); - usb_free_all_descriptors(f); kfree(func_to_loop(f)); } @@ -442,6 +446,7 @@ static struct usb_function *loopback_alloc(struct usb_function_instance *fi) loop->function.name = "loopback"; loop->function.bind = loopback_bind; + loop->function.unbind = loopback_unbind; loop->function.set_alt = loopback_set_alt; loop->function.disable = loopback_disable; loop->function.strings = loopback_strings; From ac6c19392c7996ac8135dba6907c391a4be5beaf Mon Sep 17 00:00:00 2001 From: Srinivas Pandruvada Date: Mon, 9 Nov 2026 11:59:46 -0800 Subject: [PATCH 1216/2102] HID: sensor: custom: Fix state lifetime during removal Open misc device files can outlive platform-device removal. Since the devm-allocated state can be freed while a reader is queued on its wait queue, subsequent file operations may access freed memory. Allocate the state independently of devres and give every open file a reference to keep the FIFO and state alive after removal. On removal, mark the device as disconnected and wake readers; make reads return -ENODEV and polls report hangup and error. Free the FIFO and state when the final reference is released. Unregister the sensor hub callback before tearing down the interface so in-flight raw-event processing finishes before the sensor state can be freed. Fixes: 4a7de0519df5 ("HID: sensor: Custom and Generic sensor support") Reported-by: Semyon Maryasin Closes: https://lore.kernel.org/all/CAM2dg7ewfVJSP4rFyhkCB1Rmd1+X56sAg=eUdbPthG2xrLqwQQ@mail.gmail.com/ Tested-by: Semyon Maryasin Tested-by: Zhang Lixu Signed-off-by: Srinivas Pandruvada Reviewed-by: Jonathan Cameron Signed-off-by: Jiri Kosina --- drivers/hid/hid-sensor-custom.c | 82 ++++++++++++++++++++++----------- 1 file changed, 56 insertions(+), 26 deletions(-) diff --git a/drivers/hid/hid-sensor-custom.c b/drivers/hid/hid-sensor-custom.c index 8375697b459daa..c940630d76db55 100644 --- a/drivers/hid/hid-sensor-custom.c +++ b/drivers/hid/hid-sensor-custom.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -37,6 +38,8 @@ struct hid_sensor_custom_field { struct hid_sensor_custom { struct mutex mutex; + struct kref ref; + bool removed; struct platform_device *pdev; struct hid_sensor_hub_device *hsdev; struct hid_sensor_hub_callbacks callbacks; @@ -643,6 +646,15 @@ static void hid_sensor_custom_remove_attributes(struct hid_sensor_custom * kfree(sensor_inst->fields); } +static void hid_sensor_custom_free(struct kref *ref) +{ + struct hid_sensor_custom *sensor_inst = + container_of(ref, struct hid_sensor_custom, ref); + + kfifo_free(&sensor_inst->data_fifo); + kfree(sensor_inst); +} + static ssize_t hid_sensor_custom_read(struct file *file, char __user *buf, size_t count, loff_t *f_ps) { @@ -656,22 +668,27 @@ static ssize_t hid_sensor_custom_read(struct file *file, char __user *buf, if (count < sizeof(struct hid_sensor_sample)) return -EINVAL; - do { - if (kfifo_is_empty(&sensor_inst->data_fifo)) { - if (file->f_flags & O_NONBLOCK) - return -EAGAIN; + for (;;) { + if (READ_ONCE(sensor_inst->removed)) + return -ENODEV; - ret = wait_event_interruptible(sensor_inst->wait, - !kfifo_is_empty(&sensor_inst->data_fifo)); - if (ret) - return ret; - } ret = kfifo_to_user(&sensor_inst->data_fifo, buf, count, &copied); + if (ret || copied) + break; + + if (file->f_flags & O_NONBLOCK) + return -EAGAIN; + + ret = wait_event_interruptible(sensor_inst->wait, + READ_ONCE(sensor_inst->removed) || + !kfifo_is_empty(&sensor_inst->data_fifo)); if (ret) return ret; + } - } while (copied == 0); + if (ret) + return ret; return copied; } @@ -684,6 +701,7 @@ static int hid_sensor_custom_release(struct inode *inode, struct file *file) struct hid_sensor_custom, custom_dev); clear_bit(0, &sensor_inst->misc_opened); + kref_put(&sensor_inst->ref, hid_sensor_custom_free); return 0; } @@ -691,14 +709,25 @@ static int hid_sensor_custom_release(struct inode *inode, struct file *file) static int hid_sensor_custom_open(struct inode *inode, struct file *file) { struct hid_sensor_custom *sensor_inst; + int ret; sensor_inst = container_of(file->private_data, struct hid_sensor_custom, custom_dev); + if (READ_ONCE(sensor_inst->removed)) + return -ENODEV; + /* We essentially have single reader and writer */ if (test_and_set_bit(0, &sensor_inst->misc_opened)) return -EBUSY; - return stream_open(inode, file); + kref_get(&sensor_inst->ref); + ret = stream_open(inode, file); + if (ret) { + clear_bit(0, &sensor_inst->misc_opened); + kref_put(&sensor_inst->ref, hid_sensor_custom_free); + } + + return ret; } static __poll_t hid_sensor_custom_poll(struct file *file, @@ -712,6 +741,9 @@ static __poll_t hid_sensor_custom_poll(struct file *file, poll_wait(file, &sensor_inst->wait, wait); + if (READ_ONCE(sensor_inst->removed)) + return EPOLLHUP | EPOLLERR; + if (!kfifo_is_empty(&sensor_inst->data_fifo)) mask = EPOLLIN | EPOLLRDNORM; @@ -741,21 +773,15 @@ static int hid_sensor_custom_dev_if_add(struct hid_sensor_custom *sensor_inst) sensor_inst->custom_dev.minor = MISC_DYNAMIC_MINOR; sensor_inst->custom_dev.name = dev_name(&sensor_inst->pdev->dev); sensor_inst->custom_dev.fops = &hid_sensor_custom_fops; - ret = misc_register(&sensor_inst->custom_dev); - if (ret) { - kfifo_free(&sensor_inst->data_fifo); - return ret; - } - return 0; + return misc_register(&sensor_inst->custom_dev); } static void hid_sensor_custom_dev_if_remove(struct hid_sensor_custom *sensor_inst) { - wake_up(&sensor_inst->wait); + WRITE_ONCE(sensor_inst->removed, true); + wake_up_interruptible_all(&sensor_inst->wait); misc_deregister(&sensor_inst->custom_dev); - kfifo_free(&sensor_inst->data_fifo); - } /* @@ -978,8 +1004,7 @@ static int hid_sensor_custom_probe(struct platform_device *pdev) int ret; const struct hid_sensor_custom_match *match; - sensor_inst = devm_kzalloc(&pdev->dev, sizeof(*sensor_inst), - GFP_KERNEL); + sensor_inst = kzalloc(sizeof(*sensor_inst), GFP_KERNEL); if (!sensor_inst) return -ENOMEM; @@ -989,6 +1014,7 @@ static int hid_sensor_custom_probe(struct platform_device *pdev) sensor_inst->hsdev = hsdev; sensor_inst->pdev = pdev; mutex_init(&sensor_inst->mutex); + kref_init(&sensor_inst->ref); platform_set_drvdata(pdev, sensor_inst); ret = hid_sensor_custom_get_known(hsdev, &match); @@ -1000,7 +1026,7 @@ static int hid_sensor_custom_probe(struct platform_device *pdev) if (ret) { dev_err(&pdev->dev, "register_platform_device failed\n"); - return ret; + goto err_put; } return 0; @@ -1010,7 +1036,7 @@ static int hid_sensor_custom_probe(struct platform_device *pdev) &sensor_inst->callbacks); if (ret < 0) { dev_err(&pdev->dev, "callback reg failed\n"); - return ret; + goto err_put; } ret = hid_sensor_custom_add_attributes(sensor_inst); @@ -1035,6 +1061,8 @@ static int hid_sensor_custom_probe(struct platform_device *pdev) hid_sensor_custom_remove_attributes(sensor_inst); err_remove_callback: sensor_hub_remove_callback(hsdev, hsdev->usage); +err_put: + kref_put(&sensor_inst->ref, hid_sensor_custom_free); return ret; } @@ -1046,9 +1074,10 @@ static void hid_sensor_custom_remove(struct platform_device *pdev) if (sensor_inst->custom_pdev) { platform_device_unregister(sensor_inst->custom_pdev); - return; + goto out; } + sensor_hub_remove_callback(hsdev, hsdev->usage); hid_sensor_custom_dev_if_remove(sensor_inst); /* Remove enable_sensor first as it uses fields via power_state/report_state. */ sysfs_remove_group(&sensor_inst->pdev->dev.kobj, @@ -1061,7 +1090,8 @@ static void hid_sensor_custom_remove(struct platform_device *pdev) } mutex_unlock(&sensor_inst->mutex); hid_sensor_custom_remove_attributes(sensor_inst); - sensor_hub_remove_callback(hsdev, hsdev->usage); +out: + kref_put(&sensor_inst->ref, hid_sensor_custom_free); } static const struct platform_device_id hid_sensor_custom_ids[] = { From fecb7895fbb1b7891e81a033f0dd1f5f7876dc07 Mon Sep 17 00:00:00 2001 From: Srinivas Pandruvada Date: Mon, 9 Nov 2026 11:59:47 -0800 Subject: [PATCH 1217/2102] HID: sensor: custom: Serialize misc device reads The misc device permits only one open file, but threads sharing that file can still read concurrently. Serialize readers to preserve the single-reader assumption of the FIFO while keeping removal independent of a stalled user copy. Fixes: 4a7de0519df5 ("HID: sensor: Custom and Generic sensor support") Reported-by: Semyon Maryasin Closes: https://lore.kernel.org/all/CAM2dg7ewfVJSP4rFyhkCB1Rmd1+X56sAg=eUdbPthG2xrLqwQQ@mail.gmail.com/ Tested-by: Semyon Maryasin Tested-by: Zhang Lixu Signed-off-by: Srinivas Pandruvada Reviewed-by: Jonathan Cameron Signed-off-by: Jiri Kosina --- drivers/hid/hid-sensor-custom.c | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/drivers/hid/hid-sensor-custom.c b/drivers/hid/hid-sensor-custom.c index c940630d76db55..f9e604920ea76b 100644 --- a/drivers/hid/hid-sensor-custom.c +++ b/drivers/hid/hid-sensor-custom.c @@ -38,6 +38,7 @@ struct hid_sensor_custom_field { struct hid_sensor_custom { struct mutex mutex; + struct mutex read_mutex; struct kref ref; bool removed; struct platform_device *pdev; @@ -668,25 +669,39 @@ static ssize_t hid_sensor_custom_read(struct file *file, char __user *buf, if (count < sizeof(struct hid_sensor_sample)) return -EINVAL; + if (file->f_flags & O_NONBLOCK) { + if (!mutex_trylock(&sensor_inst->read_mutex)) + return -EAGAIN; + } else { + ret = mutex_lock_interruptible(&sensor_inst->read_mutex); + if (ret) + return ret; + } + for (;;) { - if (READ_ONCE(sensor_inst->removed)) - return -ENODEV; + if (READ_ONCE(sensor_inst->removed)) { + ret = -ENODEV; + break; + } ret = kfifo_to_user(&sensor_inst->data_fifo, buf, count, &copied); if (ret || copied) break; - if (file->f_flags & O_NONBLOCK) - return -EAGAIN; + if (file->f_flags & O_NONBLOCK) { + ret = -EAGAIN; + break; + } ret = wait_event_interruptible(sensor_inst->wait, READ_ONCE(sensor_inst->removed) || !kfifo_is_empty(&sensor_inst->data_fifo)); if (ret) - return ret; + break; } + mutex_unlock(&sensor_inst->read_mutex); if (ret) return ret; @@ -1014,6 +1029,7 @@ static int hid_sensor_custom_probe(struct platform_device *pdev) sensor_inst->hsdev = hsdev; sensor_inst->pdev = pdev; mutex_init(&sensor_inst->mutex); + mutex_init(&sensor_inst->read_mutex); kref_init(&sensor_inst->ref); platform_set_drvdata(pdev, sensor_inst); From c6ebe27e3ba09edf956139c741b38e8432be3f67 Mon Sep 17 00:00:00 2001 From: Srinivas Pandruvada Date: Mon, 9 Nov 2026 11:59:48 -0800 Subject: [PATCH 1218/2102] HID: sensor: custom: Register enable attribute after misc device Register the enable_sensor sysfs group only after misc-device setup succeeds. This prevents userspace from opening the sensor hub while probe can still fail, which would otherwise leave the hub open reference unbalanced on unwind. Fixes: 4a7de0519df5 ("HID: sensor: Custom and Generic sensor support") Reported-by: Semyon Maryasin Closes: https://lore.kernel.org/all/CAM2dg7ewfVJSP4rFyhkCB1Rmd1+X56sAg=eUdbPthG2xrLqwQQ@mail.gmail.com/ Tested-by: Semyon Maryasin Tested-by: Zhang Lixu Signed-off-by: Srinivas Pandruvada Reviewed-by: Jonathan Cameron Signed-off-by: Jiri Kosina --- drivers/hid/hid-sensor-custom.c | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/drivers/hid/hid-sensor-custom.c b/drivers/hid/hid-sensor-custom.c index f9e604920ea76b..4d7cb7994dd815 100644 --- a/drivers/hid/hid-sensor-custom.c +++ b/drivers/hid/hid-sensor-custom.c @@ -1059,20 +1059,19 @@ static int hid_sensor_custom_probe(struct platform_device *pdev) if (ret) goto err_remove_callback; - ret = sysfs_create_group(&sensor_inst->pdev->dev.kobj, - &enable_sensor_attr_group); + ret = hid_sensor_custom_dev_if_add(sensor_inst); if (ret) goto err_remove_attributes; - ret = hid_sensor_custom_dev_if_add(sensor_inst); + ret = sysfs_create_group(&sensor_inst->pdev->dev.kobj, + &enable_sensor_attr_group); if (ret) - goto err_remove_group; + goto err_remove_dev_if; return 0; -err_remove_group: - sysfs_remove_group(&sensor_inst->pdev->dev.kobj, - &enable_sensor_attr_group); +err_remove_dev_if: + hid_sensor_custom_dev_if_remove(sensor_inst); err_remove_attributes: hid_sensor_custom_remove_attributes(sensor_inst); err_remove_callback: From 41cb3076a221afba052ae1624ccf62e500706b20 Mon Sep 17 00:00:00 2001 From: Srinivas Pandruvada Date: Mon, 9 Nov 2026 11:59:49 -0800 Subject: [PATCH 1219/2102] HID: sensor-hub: Remove clients before stopping hardware Remove MFD clients before stopping the HID hardware so their close calls remain valid. Runtime-PM teardown may cancel a pending autosuspend without running the client suspend callback, leaving hub references after child removal. Clients share one HID open while ref_cnt is nonzero. After removing the children, drain any remaining references and call hid_hw_close() once if the count is nonzero. Then stop the HID hardware. This avoids both a leaked open and the underflow caused by an unconditional close. The pending-request walk runs before hid_hw_stop() disconnects HID-core children such as hidraw. Skip non-platform children and platform children without sensor-hub data before checking pending request state. Fixes: 1df3a401154a ("HID: Delay opening HID device") Reported-by: Semyon Maryasin Closes: https://lore.kernel.org/all/CAM2dg7ewfVJSP4rFyhkCB1Rmd1+X56sAg=eUdbPthG2xrLqwQQ@mail.gmail.com/ Tested-by: Semyon Maryasin Tested-by: Zhang Lixu Signed-off-by: Srinivas Pandruvada Reviewed-by: Jonathan Cameron Signed-off-by: Jiri Kosina --- drivers/hid/hid-sensor-hub.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/drivers/hid/hid-sensor-hub.c b/drivers/hid/hid-sensor-hub.c index 0c4884c5821fd5..e9d6eb3b38314e 100644 --- a/drivers/hid/hid-sensor-hub.c +++ b/drivers/hid/hid-sensor-hub.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include "hid-ids.h" @@ -806,7 +807,14 @@ static int sensor_hub_probe(struct hid_device *hdev, static int sensor_hub_finalize_pending_fn(struct device *dev, void *data) { - struct hid_sensor_hub_device *hsdev = dev->platform_data; + struct hid_sensor_hub_device *hsdev; + + if (!dev_is_platform(dev)) + return 0; + + hsdev = to_platform_device(dev)->dev.platform_data; + if (!hsdev) + return 0; if (hsdev->pending.status) complete(&hsdev->pending.ready); @@ -820,8 +828,6 @@ static void sensor_hub_remove(struct hid_device *hdev) unsigned long flags; hid_dbg(hdev, " hardware removed\n"); - hid_hw_close(hdev); - hid_hw_stop(hdev); spin_lock_irqsave(&data->lock, flags); device_for_each_child(&hdev->dev, NULL, @@ -829,6 +835,14 @@ static void sensor_hub_remove(struct hid_device *hdev) spin_unlock_irqrestore(&data->lock, flags); mfd_remove_devices(&hdev->dev); + /* Clients share one HID open; release it if references remain. */ + mutex_lock(&data->mutex); + if (data->ref_cnt) { + data->ref_cnt = 0; + hid_hw_close(hdev); + } + mutex_unlock(&data->mutex); + hid_hw_stop(hdev); mutex_destroy(&data->mutex); } From 896143ce9368435c185e7d5a4f42380aeab01778 Mon Sep 17 00:00:00 2001 From: Hans de Goede Date: Mon, 9 Nov 2026 22:43:49 +0100 Subject: [PATCH 1220/2102] HID: lenovo: suppress spurious F23 key events on ThinkPad T14s gen6/7 snapdragon The Lenovo ThinkPad T14s gen6/7 snapdragon version I2C-HID keyboard sends spurirous F23 key-events when the Fn key is pressed/released. Leading to e.g. garbage ESC-sequences in the terminal when doing FN key combos. A hwdb entry was added to map these to KEY_UNKNOWN [1], but this also maps the F23 part of the left-meta + left-shift + F23 combo send by the co-pilot key to KEY_UNKNOWN making that key unusable. Add a raw_event filter which removes any 0x72 codes from the 6 scancodes reported in the standard HID keyboard boot protocol report, but only when the report's modifier byte is not 0x0a to preserve the F23 press event when the co-pilot key is pressed. Link: https://github.com/systemd/systemd/pull/44733 [1] Signed-off-by: Hans de Goede Reviewed-by: Mark Pearson Signed-off-by: Jiri Kosina --- drivers/hid/hid-ids.h | 1 + drivers/hid/hid-lenovo.c | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/drivers/hid/hid-ids.h b/drivers/hid/hid-ids.h index 91319aa6516dae..13d2ad7ba430b9 100644 --- a/drivers/hid/hid-ids.h +++ b/drivers/hid/hid-ids.h @@ -470,6 +470,7 @@ #define USB_DEVICE_ID_EDIFIER_QR30 0xa101 /* EDIFIER Hal0 2.0 SE */ #define USB_VENDOR_ID_ELAN 0x04f3 +#define I2C_DEVICE_ID_ELAN_LENOVO_T14S_KEYBOARD 0x000d #define USB_DEVICE_ID_SB974D 0x0400 #define USB_DEVICE_ID_TOSHIBA_CLICK_L9W 0x0401 #define USB_DEVICE_ID_HP_X2 0x074d diff --git a/drivers/hid/hid-lenovo.c b/drivers/hid/hid-lenovo.c index 617bba6626592e..26422a9d1cfa61 100644 --- a/drivers/hid/hid-lenovo.c +++ b/drivers/hid/hid-lenovo.c @@ -812,6 +812,22 @@ static int lenovo_raw_event(struct hid_device *hdev, size >= 4 && report->id == 0x03)) return lenovo_raw_event_TP_X12_tab(hdev, get_unaligned_le32(data)); + /* + * Lenovo ThinkPad T14s gen6/7 snapdragon version filter out spurious + * F23 events when Fn key is pressed. F23 cannot be unmapped because of + * the copilot key sending left-meta + left-shift + F23. Filter report 8 + * (keyboard) scancode 0x72 (F23) when the modifier byte is not 0x0a. + */ + if (unlikely(hdev->product == I2C_DEVICE_ID_ELAN_LENOVO_T14S_KEYBOARD && + size == 9 && data[0] == 8 && data[1] != 0x0a)) { + for (int i = 3; i < 9; i++) + if (data[i] == 0x72) { + memmove(&data[i], &data[i + 1], 8 - i); + data[8] = 0; + break; + } + } + return 0; } @@ -1397,6 +1413,10 @@ static int lenovo_probe(struct hid_device *hdev, { int ret; + /* Make the T14s keyboard trackpoint a separate input-device */ + if (hdev->product == I2C_DEVICE_ID_ELAN_LENOVO_T14S_KEYBOARD) + hdev->quirks |= HID_QUIRK_INPUT_PER_APP; + ret = hid_parse(hdev); if (ret) { hid_err(hdev, "hid_parse failed\n"); @@ -1562,6 +1582,7 @@ static const struct hid_device_id lenovo_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_IBM, USB_DEVICE_ID_IBM_SCROLLPOINT_800DPI_OPTICAL_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_SCROLLPOINT_OPTICAL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_TP10UBKBD) }, + { HID_I2C_DEVICE(USB_VENDOR_ID_ELAN, I2C_DEVICE_ID_ELAN_LENOVO_T14S_KEYBOARD) }, /* * Note bind to the HID_GROUP_GENERIC group, so that we only bind to the keyboard * part, while letting hid-multitouch.c handle the touchpad and trackpoint. From 4ea5f646f5f0c30f05e0576268f0bb913b1f05e2 Mon Sep 17 00:00:00 2001 From: Aldo Ariel Panzardo Date: Fri, 6 Nov 2026 22:26:36 -0300 Subject: [PATCH 1221/2102] HID: wacom: validate battery range before scaling Battery events divide by the difference between the logical maximum and minimum without validating the range. A malformed HID descriptor with equal limits can therefore trigger a divide-by-zero exception. Move percentage conversion to a helper that rejects non-positive ranges and accounts for a nonzero logical minimum. Clamp the result to [0, 100] as an additional safeguard against out-of-range percentages. Fixes: 37d160193834 ("HID: wacom: generic: Scale battery capacity measurements to percentages") Cc: stable@vger.kernel.org Signed-off-by: Aldo Ariel Panzardo Reviewed-by: Jason Gerecke Signed-off-by: Jiri Kosina --- drivers/hid/wacom_wac.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/drivers/hid/wacom_wac.c b/drivers/hid/wacom_wac.c index 361738bb872533..36bab07a72dba5 100644 --- a/drivers/hid/wacom_wac.c +++ b/drivers/hid/wacom_wac.c @@ -1960,6 +1960,16 @@ static void wacom_wac_battery_usage_mapping(struct hid_device *hdev, return; } +static __s32 wacom_wac_battery_percentage(struct hid_field *field, __s32 value) +{ + __s32 range = field->logical_maximum - field->logical_minimum; + + if (range <= 0) + return 0; + + return clamp_val((value - field->logical_minimum) * 100 / range, 0, 100); +} + static void wacom_wac_battery_event(struct hid_device *hdev, struct hid_field *field, struct hid_usage *usage, __s32 value) { @@ -1973,7 +1983,7 @@ static void wacom_wac_battery_event(struct hid_device *hdev, struct hid_field *f wacom_wac->hid_data.bat_status = POWER_SUPPLY_STATUS_UNKNOWN; } else { - value = value * 100 / (field->logical_maximum - field->logical_minimum); + value = wacom_wac_battery_percentage(field, value); wacom_wac->hid_data.battery_capacity = value; wacom_wac->hid_data.bat_connected = 1; wacom_wac->hid_data.bat_status = WACOM_POWER_SUPPLY_STATUS_AUTO; @@ -1981,7 +1991,7 @@ static void wacom_wac_battery_event(struct hid_device *hdev, struct hid_field *f wacom_wac->features.quirks |= WACOM_QUIRK_BATTERY; break; case WACOM_HID_WD_BATTERY_LEVEL: - value = value * 100 / (field->logical_maximum - field->logical_minimum); + value = wacom_wac_battery_percentage(field, value); wacom_wac->hid_data.battery_capacity = value; wacom_wac->hid_data.bat_connected = 1; wacom_wac->hid_data.bat_status = WACOM_POWER_SUPPLY_STATUS_AUTO; From 07e84ad110427fccfb7b4dd71593bd1ffb3badfe Mon Sep 17 00:00:00 2001 From: Aldo Ariel Panzardo Date: Fri, 6 Nov 2026 09:04:05 -0300 Subject: [PATCH 1222/2102] HID: wacom: avoid divide exception in dropped-packet calculation The dropped-packet calculation uses a modulo against sequence_size (logical_maximum - logical_minimum + 1). When a HID descriptor declares a sequence field whose logical range spans all 32-bit values, sequence_size wraps to zero and the modulo triggers a divide exception. Replace the division-based calculation with a branch that computes the forward distance through the sequence range directly, as suggested by Jason Gerecke. This keeps the existing int types and avoids the divide-by-zero without any 64-bit arithmetic. Fixes: 359673ea3a20 ("HID: wacom: Support sequence numbers smaller than 16-bit") Cc: stable@vger.kernel.org Suggested-by: Jason Gerecke Signed-off-by: Aldo Ariel Panzardo Reviewed-by: Jason Gerecke Signed-off-by: Jiri Kosina --- drivers/hid/wacom_wac.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/drivers/hid/wacom_wac.c b/drivers/hid/wacom_wac.c index 36bab07a72dba5..5b3fbc5a8e1b16 100644 --- a/drivers/hid/wacom_wac.c +++ b/drivers/hid/wacom_wac.c @@ -2436,6 +2436,13 @@ static void wacom_wac_pen_usage_mapping(struct hid_device *hdev, } } +static int wacom_hid_wrapped_dist(int after, int before, int min, int max) +{ + if (after >= before) + return after - before; + return (max - before) + (after - min) + 1; +} + static void wacom_wac_pen_event(struct hid_device *hdev, struct hid_field *field, struct hid_usage *usage, __s32 value) { @@ -2561,8 +2568,11 @@ static void wacom_wac_pen_event(struct hid_device *hdev, struct hid_field *field case WACOM_HID_WD_SEQUENCENUMBER: if (wacom_wac->hid_data.sequence_number != value && wacom_wac->hid_data.sequence_number >= 0) { - int sequence_size = field->logical_maximum - field->logical_minimum + 1; - int drop_count = (value - wacom_wac->hid_data.sequence_number) % sequence_size; + int drop_count = wacom_hid_wrapped_dist( + value, + wacom_wac->hid_data.sequence_number, + field->logical_minimum, + field->logical_maximum); hid_warn(hdev, "Dropped %d packets", drop_count); } wacom_wac->hid_data.sequence_number = value + 1; From ebe5e010199517103271033b435fb5b0f8213c68 Mon Sep 17 00:00:00 2001 From: Waqar Gulzar Date: Thu, 8 Oct 2026 12:15:01 +0500 Subject: [PATCH 1223/2102] HID: i2c-hid-acpi: restore touchscreen IRQ routing on HP OmniBook Flip laptops On the HP OmniBook X Flip 16, OmniBook 7 Flip 16 and OmniBook X Flip 14 the ELAN2514 touchscreen interrupt is a GPIO pad (GPP_E_18) routed directly to the IO-APIC. The firmware's touchscreen power resource does PTPL._ON: \_SB.SGRA (TPI2, TPIP) // TPIP = T0IP = 0 PTPL._OFF: \_SB.SGRA (TPI2, TPIP ^ 1) while the device's _INI enables routing with SGRA (GPLI, T0IP ^ 1). So _ON clears PADCFG0.GPIROUTIOXAPIC and disconnects the pad from the IO-APIC. Linux evaluates _ON at probe and on every D3->D0 transition (Windows apparently does not while _STA already reports the resource on), after which the level-triggered IRQ never deasserts: - ~630 interrupts/s while idle, nearly every read returns 0xffff - frames shifted by a leading 0xff, "incomplete report (67/7167)" - stylus reports arrive at ~25 Hz instead of the native ~268 Hz - touch stalls and false stylus proximity Re-enable the routing through the firmware's own \_SB.SGRA helper from the power_up hook, which runs at probe and on resume before the HID reset. Tested with this patch on the OmniBook X Flip 16 (board 8DA1, BIOS F.20): idle interrupts drop from ~630/s to 0 after boot and after s2idle resume, and pen and touch behave as on Windows. The same faulty _ON, the same pad and the same ~630/s storm were confirmed by other owners on the OmniBook 7 Flip 16 (board 8DA0, BIOS F.08) and the OmniBook X Flip 14 (board 8D9F, BIOS F.08). On both, correcting the _ON value through an ACPI table override stops the storm (routing bit set, 0 interrupts/s idle, also after s2idle), which is the same correction this patch applies at runtime. Link: https://bugzilla.kernel.org/show_bug.cgi?id=220854 Link: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/2142384 Link: https://github.com/testyfishy/hp-omnibook-flip16-touchscreen-fix Link: https://github.com/iamwaqargulzar/hp-omnibook-x-flip-16-linux-touchscreen-pen-fix Cc: stable@vger.kernel.org Signed-off-by: Waqar Gulzar Signed-off-by: Jiri Kosina --- drivers/hid/i2c-hid/i2c-hid-acpi.c | 65 ++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/drivers/hid/i2c-hid/i2c-hid-acpi.c b/drivers/hid/i2c-hid/i2c-hid-acpi.c index 9371db200fc4da..b307d9a3d04555 100644 --- a/drivers/hid/i2c-hid/i2c-hid-acpi.c +++ b/drivers/hid/i2c-hid/i2c-hid-acpi.c @@ -21,6 +21,7 @@ #include #include +#include #include #include #include @@ -55,6 +56,67 @@ static void i2c_hid_acpi_restore_sequence(struct i2chid_ops *ops) i2c_hid_acpi_get_descriptor(ihid_acpi->adev); } +/* + * HP OmniBook X Flip 14 (board 8D9F), OmniBook 7 Flip 16 (8DA0) and + * OmniBook X Flip 16 (8DA1): the touchscreen power resource + * \_SB.PC00.I2C4.PTPL._ON writes the wrong value to the GPIROUTIOXAPIC bit + * of the touchscreen interrupt pad, disconnecting it from the IO-APIC. The + * level-triggered interrupt then never deasserts, the controller is read + * continuously (~630 reads/s while idle) and it cannot deliver pen reports + * at its native rate. Windows does not run _ON while the resource already + * reports on, so it is not affected. Linux runs _ON at probe and on every + * resume, so re-enable the routing with the firmware's own helper before + * the HID reset. + */ +static const struct dmi_system_id i2c_hid_acpi_irq_route_dmi[] = { + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "HP"), + DMI_EXACT_MATCH(DMI_BOARD_NAME, "8D9F"), + }, + }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "HP"), + DMI_EXACT_MATCH(DMI_BOARD_NAME, "8DA0"), + }, + }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "HP"), + DMI_EXACT_MATCH(DMI_BOARD_NAME, "8DA1"), + }, + }, + { } +}; + +static int i2c_hid_acpi_restore_irq_route(struct i2chid_ops *ops) +{ + struct i2c_hid_acpi *ihid_acpi = container_of(ops, struct i2c_hid_acpi, ops); + union acpi_object args[2]; + struct acpi_object_list arg_list = { ARRAY_SIZE(args), args }; + unsigned long long pad; + acpi_status status; + + status = acpi_evaluate_integer(NULL, "\\GPLI", NULL, &pad); + if (ACPI_FAILURE(status)) + return 0; + + args[0].type = ACPI_TYPE_INTEGER; + args[0].integer.value = pad; + args[1].type = ACPI_TYPE_INTEGER; + args[1].integer.value = 1; + + status = acpi_evaluate_object(NULL, "\\_SB.SGRA", &arg_list, NULL); + if (ACPI_FAILURE(status)) + acpi_handle_warn(acpi_device_handle(ihid_acpi->adev), + "failed to restore interrupt routing: %s\n", + acpi_format_exception(status)); + + /* Never fail probe or resume because of this workaround */ + return 0; +} + static void i2c_hid_acpi_shutdown_tail(struct i2chid_ops *ops) { struct i2c_hid_acpi *ihid_acpi = container_of(ops, struct i2c_hid_acpi, ops); @@ -85,6 +147,9 @@ static int i2c_hid_acpi_probe(struct i2c_client *client) ihid_acpi->adev = adev; ihid_acpi->ops.shutdown_tail = i2c_hid_acpi_shutdown_tail; ihid_acpi->ops.restore_sequence = i2c_hid_acpi_restore_sequence; + if (acpi_dev_hid_uid_match(ihid_acpi->adev, "ELAN2514", NULL) && + dmi_check_system(i2c_hid_acpi_irq_route_dmi)) + ihid_acpi->ops.power_up = i2c_hid_acpi_restore_irq_route; acpi_device_fix_up_power(adev); From 7e1b58bd6d36aa76f920da72ae114574b21d5283 Mon Sep 17 00:00:00 2001 From: Jinmo Yang Date: Mon, 28 Sep 2026 00:30:14 +0900 Subject: [PATCH 1224/2102] HID: wiimote: initialise rumble_worker once per device wdata->rumble_worker is a single work_struct in struct wiimote_data, but two different modules called INIT_WORK() on it: wiimod_rumble_probe() devtype module, once per device wiimod_pro_probe() extension module, once per extension hotplug These have independent lifetimes. The devtype module is loaded once by wiimote_modules_load() and stays until wiimote_destroy(), while the extension module is loaded and unloaded any number of times by wiimote_ext_load() / wiimote_ext_unload(). wiimote_ext_load() calls the extension probe with no lock and no cancel_work_sync(), and for the common EXT_NONE -> EXT_PRO_CONTROLLER transition the preceding wiimote_ext_unload() is a no-op because wiimod_ext_table[] maps both EXT_NONE and EXT_UNKNOWN to wiimod_dummy, which has no .remove. So nothing stops the force-feedback path, which is still live in the base module, from having queued the work already: /* wiimod_rumble_play() */ wdata->state.cache_rumble = value; schedule_work(&wdata->rumble_worker); INIT_WORK() on a queued work item is memory corruption. __INIT_WORK() does (_work)->data = (atomic_long_t) WORK_DATA_INIT(); INIT_LIST_HEAD(&(_work)->entry); which clears the pool reference and the PENDING bit, and re-points ->entry at itself while the item is still linked into the worker pool list, leaving its neighbours pointing at a node that has left the list. Note that CONFIG_DEBUG_OBJECTS_WORK hides the impact rather than just reporting it: work_fixup_init() calls cancel_work_sync() for the caller, so a debug kernel prints a warning and then repairs the state. That is the kernel stating what the driver should have done. Production kernels have no such repair. Initialise the work once in wiimote_create(), which is where the object that contains it is created and which already initialises wdata->queue.worker, wdata->init_worker and wdata->timer, and drop both module-level INIT_WORK() calls. wiimote_create() runs as the first statement of wiimote_hid_probe(), before hid_parse() and hid_hw_start(), so it strictly precedes the existence of any input device and therefore of any path that could queue the work. This does not affect the deadlock fix in commit f50f9aabf32d ("HID: wiimote: fix FF deadlock"). That fix is the offload itself - caching the value and deferring to a worker instead of taking state.lock inside the FF callback - and this patch leaves wiimod_rumble_play(), wiimod_rumble_worker() and state.cache_rumble untouched. Only the placement of the initialisation changes. The two halves come from different actors, and both are available on a stock Android phone without root. The extension hotplug half needs only /dev/uhid, which is group 3011 and held by the shell. The shell cannot write to an evdev node - SELinux grants it read access only - so the force-feedback half comes from an ordinary app calling InputDevice.getVibrator().vibrate(), which reaches EVIOCSFF through system_server; VIBRATE is a normal permission and is granted automatically. A paired Bluetooth HID device can supply the hotplug half instead of /dev/uhid. The ordering matters: the device has to be created without an extension so that the devtype resolves to a GEN10/GEN20 that includes WIIMOD_RUMBLE, because WIIMOTE_DEV_PRO_CONTROLLER does not, and the extension has to be plugged afterwards. Measured before the change: Pixel 11, stock Android 17 user build, SELinux enforcing, no KASAN and no DEBUG_OBJECTS at runtime, kernel 6.12.81: reboots with ro.boot.bootreason=kernel_panic one to two seconds after the two paths start overlapping. Unable to handle kernel NULL pointer dereference at virtual address 0000000000000008 CPU: 5 Comm: kworker/5:4 Workqueue: wiimod_rumble_worker (events) pc : process_scheduled_works+0xd4/0x810 Kernel panic - not syncing: Oops: Fatal exception The empty workqueue name in that line is itself the corruption: print_worker_info() reads wq->name with copy_from_kernel_nofault() and it failed, while another CPU in the same dump shows the normal form, "Workqueue: events wiimote_init_worker" - the task that called wiimod_pro_probe(). x86_64 with CONFIG_KASAN_GENERIC and CONFIG_DEBUG_OBJECTS_WORK both enabled, 15 s in: KASAN says nothing, because INIT_WORK() writes to a valid field of a live object, and DEBUG_OBJECTS_WORK reports ODEBUG: init active (active state 0) object type: work_struct hint: wiimod_rumble_worker+0x0/0x70 WARNING: lib/debugobjects.c:629 at debug_print_object Workqueue: events wiimote_init_worker __debug_object_init+0x1ff/0x3b0 __init_work+0x51/0x60 wiimod_pro_probe+0x28/0xba0 wiimote_init_worker.cold+0xb6a/0xe88 After the change the same reproducer drives 36774 extension hotplugs and 612156 force-feedback plays in 60 s on that x86_64 kernel with no ODEBUG, WARNING or KASAN output, and the rumble reports still arrive, so the force-feedback path is unaffected. Fixes: f50f9aabf32d ("HID: wiimote: fix FF deadlock") Cc: stable@vger.kernel.org Signed-off-by: Jinmo Yang Signed-off-by: Jiri Kosina --- drivers/hid/hid-picolcd.h | 2 ++ drivers/hid/hid-wiimote-core.c | 1 + drivers/hid/hid-wiimote-modules.c | 5 +---- drivers/hid/hid-wiimote.h | 1 + 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/drivers/hid/hid-picolcd.h b/drivers/hid/hid-picolcd.h index 57c9d0a6757c1b..846a8ceb95acc2 100644 --- a/drivers/hid/hid-picolcd.h +++ b/drivers/hid/hid-picolcd.h @@ -102,6 +102,8 @@ struct picolcd_data { /* Housekeeping stuff */ spinlock_t lock; struct mutex mutex; + /* Serialize updates to output reports and their HID requests. */ + struct mutex report_mutex; struct picolcd_pending *pending; int status; #define PICOLCD_BOOTLOADER 1 diff --git a/drivers/hid/hid-wiimote-core.c b/drivers/hid/hid-wiimote-core.c index 9168b85029183e..06759247fb37e0 100644 --- a/drivers/hid/hid-wiimote-core.c +++ b/drivers/hid/hid-wiimote-core.c @@ -1741,6 +1741,7 @@ static struct wiimote_data *wiimote_create(struct hid_device *hdev) wdata->player_id = 0; // min 1, u8 0 is unassigned id INIT_WORK(&wdata->init_worker, wiimote_init_worker); + INIT_WORK(&wdata->rumble_worker, wiimod_rumble_worker); timer_setup(&wdata->timer, wiimote_init_timeout, 0); return wdata; diff --git a/drivers/hid/hid-wiimote-modules.c b/drivers/hid/hid-wiimote-modules.c index 199589cbf2b856..16f3e6ca3b0368 100644 --- a/drivers/hid/hid-wiimote-modules.c +++ b/drivers/hid/hid-wiimote-modules.c @@ -118,7 +118,7 @@ static const struct wiimod_ops wiimod_keys = { */ /* used by wiimod_rumble and wiipro_rumble */ -static void wiimod_rumble_worker(struct work_struct *work) +void wiimod_rumble_worker(struct work_struct *work) { struct wiimote_data *wdata = container_of(work, struct wiimote_data, rumble_worker); @@ -156,8 +156,6 @@ static int wiimod_rumble_play(struct input_dev *dev, void *data, static int wiimod_rumble_probe(const struct wiimod_ops *ops, struct wiimote_data *wdata) { - INIT_WORK(&wdata->rumble_worker, wiimod_rumble_worker); - set_bit(FF_RUMBLE, wdata->input->ffbit); if (input_ff_create_memless(wdata->input, NULL, wiimod_rumble_play)) return -ENOMEM; @@ -1857,7 +1855,6 @@ static int wiimod_pro_probe(const struct wiimod_ops *ops, int ret, i; unsigned long flags; - INIT_WORK(&wdata->rumble_worker, wiimod_rumble_worker); wdata->state.calib_pro_sticks[0] = 0; wdata->state.calib_pro_sticks[1] = 0; wdata->state.calib_pro_sticks[2] = 0; diff --git a/drivers/hid/hid-wiimote.h b/drivers/hid/hid-wiimote.h index 8e5002f515e24f..9738da167a009a 100644 --- a/drivers/hid/hid-wiimote.h +++ b/drivers/hid/hid-wiimote.h @@ -263,6 +263,7 @@ enum wiiproto_reqs { #define dev_to_wii(pdev) hid_get_drvdata(to_hid_device(pdev)) void __wiimote_schedule(struct wiimote_data *wdata); +void wiimod_rumble_worker(struct work_struct *work); extern void wiiproto_req_drm(struct wiimote_data *wdata, __u8 drm); extern void wiiproto_req_rumble(struct wiimote_data *wdata, __u8 rumble); From 72cfde169c753307cc4ea5fdd4090d45029d37fb Mon Sep 17 00:00:00 2001 From: Lu Huang Date: Mon, 28 Sep 2026 16:54:33 +0800 Subject: [PATCH 1225/2102] HID: nintendo: fix lost update of player LED state The player LED subcommand programs all four LEDs with a single value, so joycon_player_led_brightness_set() must aggregate the current brightness of all four LEDs and send that snapshot atomically. Commit 928276075f16 ("HID: nintendo: cleanup LED code") moved the aggregation loop out of output_mutex: if an update callback is preempted after reading the four states and another update sends its own snapshot first, the preempted callback later sends its stale value and silently reverts the completed update, leaving the hardware LED state inconsistent with sysfs brightness. Move the aggregation loop back under output_mutex so reading the four LED states and sending the subcommand are serialized. Fixes: 928276075f16 ("HID: nintendo: cleanup LED code") Cc: stable@vger.kernel.org Signed-off-by: Lu Huang Signed-off-by: Jiri Kosina --- drivers/hid/hid-nintendo.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/hid/hid-nintendo.c b/drivers/hid/hid-nintendo.c index d235de6868a227..c2a35154cc6c58 100644 --- a/drivers/hid/hid-nintendo.c +++ b/drivers/hid/hid-nintendo.c @@ -2272,10 +2272,9 @@ static int joycon_player_led_brightness_set(struct led_classdev *led, return -ENODEV; } + mutex_lock(&ctlr->output_mutex); for (i = 0; i < JC_NUM_LEDS; i++) val |= ctlr->leds[i].brightness << i; - - mutex_lock(&ctlr->output_mutex); ret = joycon_set_player_leds(ctlr, 0, val); mutex_unlock(&ctlr->output_mutex); From 7c2f5e907f236844d147b09a4019f553488f7ffa Mon Sep 17 00:00:00 2001 From: Hans van Essen Date: Tue, 6 Oct 2026 12:39:22 +0200 Subject: [PATCH 1226/2102] HID: asus: Resume the device before sending feature reports asus_kbd_set_report() sends a SET_REPORT control request through hid_hw_raw_request(). usbhid does not take a runtime PM reference for raw requests, so the request fails while the keyboard is runtime suspended. On a ROG Zephyrus G16 (GU605CW, N-KEY 0b05:19b6) with power/control set to auto, every deferred backlight change from asus_work() is lost: asus 0003:0B05:19B6.0002: Asus failed to set keyboard backlight: -108 Wrap the request in hid_hw_power(), as hidraw does, so the device is resumed for the write and can autosuspend again afterwards. Assisted-by: LLM Signed-off-by: Hans van Essen Signed-off-by: Jiri Kosina --- drivers/hid/hid-asus.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/drivers/hid/hid-asus.c b/drivers/hid/hid-asus.c index f6aa1be09ad538..dc9f41cf6e82d2 100644 --- a/drivers/hid/hid-asus.c +++ b/drivers/hid/hid-asus.c @@ -584,16 +584,24 @@ static int asus_raw_event(struct hid_device *hdev, static int asus_kbd_set_report(struct hid_device *hdev, const u8 *buf, size_t buf_size) { + int ret; u8 *dmabuf __free(kfree) = kmemdup(buf, buf_size, GFP_KERNEL); if (!dmabuf) return -ENOMEM; + /* The device may be runtime suspended, e.g. for a deferred backlight change */ + ret = hid_hw_power(hdev, PM_HINT_FULLON); + if (ret < 0) + return ret; + /* * The report ID should be set from the incoming buffer due to LED and key * interfaces having different pages */ - return hid_hw_raw_request(hdev, buf[0], dmabuf, buf_size, HID_FEATURE_REPORT, - HID_REQ_SET_REPORT); + ret = hid_hw_raw_request(hdev, buf[0], dmabuf, buf_size, HID_FEATURE_REPORT, + HID_REQ_SET_REPORT); + hid_hw_power(hdev, PM_HINT_NORMAL); + return ret; } static int asus_kbd_init(struct hid_device *hdev, u8 report_id) From c3cc505d71cc1c680012127055a2af657f9ab41b Mon Sep 17 00:00:00 2001 From: Krish Gulati Date: Sat, 10 Oct 2026 15:21:02 +0530 Subject: [PATCH 1227/2102] HID: core: serialize report_descriptor_read() against probe and remove Since commit 54f32fd5dff9 ("HID: Make report_descriptor available for all devices"), the "report_descriptor" sysfs attribute is part of the device's attribute group, so it exists from device_add() until device_del(). It reads hdev->rdesc, but that buffer only lives from hid_open_report() until hid_close_report(), that is, for the duration of a driver binding. For a driver with a report_fixup() callback, rdesc is a private copy that hid_close_report() frees, so a read that races with the driver being unbound accesses freed memory. syzbot reports this as: BUG: KASAN: slab-use-after-free in report_descriptor_read+0xb5/0x100 Read of size 24 at addr ffff888078d61f00 by task fido_id/7281 ... Allocated by task 10: kmemdup_noprof+0x2b/0x70 hid_open_report+0x1fa/0xf00 lg_probe+0x29c/0x890 hid_device_probe+0x46a/0x870 ... Because hid_close_report() also clears rdesc and rsize, the same missing serialization can make the reader see a NULL rdesc with a non-zero rsize. Hold the device lock in report_descriptor_read(). The driver core already holds it across probe and remove, so a read can no longer overlap with them. Reported-by: syzbot+bc537ca7a0efe33988eb@syzkaller.appspotmail.com Tested-by: syzbot+bc537ca7a0efe33988eb@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=bc537ca7a0efe33988eb Fixes: 54f32fd5dff9 ("HID: Make report_descriptor available for all devices") Cc: stable@vger.kernel.org Signed-off-by: Krish Gulati Signed-off-by: Jiri Kosina --- drivers/hid/hid-core.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/hid/hid-core.c b/drivers/hid/hid-core.c index a71ddaa810a036..e741ae71f12577 100644 --- a/drivers/hid/hid-core.c +++ b/drivers/hid/hid-core.c @@ -2270,6 +2270,8 @@ report_descriptor_read(struct file *filp, struct kobject *kobj, struct device *dev = kobj_to_dev(kobj); struct hid_device *hdev = to_hid_device(dev); + guard(device)(dev); + if (off >= hdev->rsize) return 0; From 98d30aedb99d8486e1457b823f55c112e1776af4 Mon Sep 17 00:00:00 2001 From: Jozef Riha Date: Wed, 18 Nov 2026 15:32:17 +0100 Subject: [PATCH 1228/2102] HID: betop: add support for SPEEDLINK TORID The SPEEDLINK TORID wireless gamepad (11c0:9105) is a Betop based device. Its output report has the same 4 byte layout as the other devices handled by hid-betopff, with the motors in bytes 2 and 3. Without the device ID the gamepad is bound to hid-generic and has no force feedback. Add it to betop_devices[]. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Jozef Riha Signed-off-by: Jiri Kosina --- drivers/hid/hid-betopff.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/hid/hid-betopff.c b/drivers/hid/hid-betopff.c index f802046a688a72..28ab0acce6ad78 100644 --- a/drivers/hid/hid-betopff.c +++ b/drivers/hid/hid-betopff.c @@ -16,6 +16,9 @@ * * 0x20bc:0x5500 "BTP2185 V2 BFM mode Joystick" * - tested with BTP2171s. + * + * 0x11c0:0x9105 "SPEEDLINK TORID" + * - tested with Speedlink TORID wireless gamepad. * Copyright (c) 2014 Huang Bo */ @@ -137,6 +140,7 @@ static int betop_probe(struct hid_device *hdev, const struct hid_device_id *id) static const struct hid_device_id betop_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185BFM, 0x2208) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185PC, 0x5506) }, + { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185PC, 0x9105) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185V2PC, 0x1850) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185V2BFM, 0x5500) }, { } From de58991a7338e260d5850cc8cb3d05745244568b Mon Sep 17 00:00:00 2001 From: Sanjay Govind Date: Sun, 8 Nov 2026 13:10:58 +1300 Subject: [PATCH 1229/2102] HID: sony: fix sleeping in atomic context in RB3 Pro raw event handler Rock Band 3 Pro instruments only send navigation reports until they receive a magic SET_REPORT feature request. When such a report is seen, rb3_pro_instrument_raw_event() sends that request directly through rb3_pro_instrument_enable_full_report(), which does a GFP_KERNEL allocation and a synchronous hid_hw_raw_request(). The raw event handler is called from the URB completion handler in softirq context, and on USB hid_hw_raw_request() ends up in usb_control_msg(), which sleeps. Plugging in an RB3 Pro instrument therefore triggers: BUG: scheduling while atomic ... softirq: huh, entered softirq 0 HI ... preempt_count 101, exited with 0 This was reported on a Mustang guitar (12ba:2430). Move the request to process context by registering rb3_pro_instrument_enable_full_report() as the send_output_report callback of the existing state worker. The raw event handler now only schedules the work, keeping the 8 second rate limit. The state worker is already cancelled by sony_cleanup() on remove and on probe failure, and sony_schedule_work() is a no-op once cancellation has started, so no new teardown is needed. Fixes: 7245b0017d12 ("HID: sony: add support for more instruments") Cc: stable@vger.kernel.org Signed-off-by: Sanjay Govind Signed-off-by: Jiri Kosina --- drivers/hid/hid-sony.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/drivers/hid/hid-sony.c b/drivers/hid/hid-sony.c index 50f5ad6bbeb4c1..9ee175f9e58d2b 100644 --- a/drivers/hid/hid-sony.c +++ b/drivers/hid/hid-sony.c @@ -630,7 +630,7 @@ static int ghl_init_urb(struct sony_sc *sc, struct usb_device *usbdev, * Sending HID_REQ_SET_REPORT enables the full report. Without this * Rock Band 3 Pro instruments only report navigation events */ -static int rb3_pro_instrument_enable_full_report(struct sony_sc *sc) +static void rb3_pro_instrument_enable_full_report(struct sony_sc *sc) { struct hid_device *hdev = sc->hdev; static const u8 report[] = { 0x00, 0xE9, 0x00, 0x89, 0x1B, @@ -647,14 +647,14 @@ static int rb3_pro_instrument_enable_full_report(struct sony_sc *sc) buf = kmemdup(report, sizeof(report), GFP_KERNEL); if (!buf) - return -ENOMEM; + return; ret = hid_hw_raw_request(hdev, buf[0], buf, sizeof(report), HID_FEATURE_REPORT, HID_REQ_SET_REPORT); + if (ret < 0) + hid_dbg(hdev, "failed to enable full report: %d\n", ret); kfree(buf); - - return ret; } static int djh_turntable_mapping(struct hid_device *hdev, struct hid_input *hi, @@ -1098,10 +1098,10 @@ static int rb3_pro_instrument_raw_event(struct sony_sc *sc, u8 *rd, int size) if (size < 25 || rd[24] != 0x02) return 0; - /* Only attempt to enable full report every 8 seconds */ + /* Only attempt to enable full report every 8 seconds, from the worker */ if (time_after(jiffies, sc->rb3_pro_poke_jiffies)) { sc->rb3_pro_poke_jiffies = jiffies + secs_to_jiffies(8); - rb3_pro_instrument_enable_full_report(sc); + sony_schedule_work(sc); } return 0; @@ -2217,6 +2217,7 @@ static int sony_input_configured(struct hid_device *hdev, hdev->quirks |= HID_QUIRK_SKIP_OUTPUT_REPORT_ID; sony_init_raw_event_handler(sc, rb3_pro_instrument_raw_event); + sony_init_output_report(sc, rb3_pro_instrument_enable_full_report); } else if (sc->quirks & SIXAXIS_CONTROLLER_USB) { /* * The Sony Sixaxis does not handle HID Output Reports on the From fd2ae56889ee949348c878222be12f6448db793e Mon Sep 17 00:00:00 2001 From: Michael Schwarz Date: Sun, 8 Nov 2026 18:01:17 +0100 Subject: [PATCH 1230/2102] HID: logitech-dj: Add support for G915 receiver 0xc541 The Logitech G915 keyboard has a lightspeed receiver with a product id of 0xc541. It seems to behave like its smaller brother, the G910 TKL which has a 0xc545 receiver. Add a definition for this new receiver id and a mapping for the recvr_type_gaming_hidpp_ls_1_3 type, the receiver now reports battery status of the connected keyboard. Signed-off-by: Michael Schwarz Signed-off-by: Jiri Kosina --- drivers/hid/hid-ids.h | 1 + drivers/hid/hid-logitech-dj.c | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/drivers/hid/hid-ids.h b/drivers/hid/hid-ids.h index 13d2ad7ba430b9..522a6678e806ba 100644 --- a/drivers/hid/hid-ids.h +++ b/drivers/hid/hid-ids.h @@ -987,6 +987,7 @@ #define USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_3 0xc547 #define USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_4 0xc54d #define USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_5 0xc545 +#define USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_6 0xc541 #define USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_POWERPLAY 0xc53a #define USB_DEVICE_ID_LOGITECH_BOLT_RECEIVER 0xc548 #define USB_DEVICE_ID_SPACETRAVELLER 0xc623 diff --git a/drivers/hid/hid-logitech-dj.c b/drivers/hid/hid-logitech-dj.c index 6e8db01d27ec0e..230abff5fcd5ee 100644 --- a/drivers/hid/hid-logitech-dj.c +++ b/drivers/hid/hid-logitech-dj.c @@ -2114,6 +2114,10 @@ static const struct hid_device_id logi_dj_receivers[] = { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_5), .driver_data = recvr_type_gaming_hidpp_ls_1_3}, + { /* Logitech lightspeed receiver (0xc541) */ + HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, + USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_6), + .driver_data = recvr_type_gaming_hidpp_ls_1_3}, { /* Logitech 27 MHz HID++ 1.0 receiver (0xc513) */ HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_MX3000_RECEIVER), From f2f69bbddd34801cbf6af2e89235ca427f3811c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eren=20=C3=87akar?= Date: Fri, 13 Nov 2026 11:05:10 +0000 Subject: [PATCH 1231/2102] HID: letsketch: skip string descriptors the firmware does not implement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Starcom GC-422 is a rebranded LetSketch WP9620C with the same USB ID (6161:4d15), so it binds to this driver. Its firmware ("Vision_V201_180530") does not implement every string descriptor index that the raw mode handshake reads. For those indices usb_string() keeps returning an empty string or -EPIPE, letsketch_get_string() gives up after its retries, and the probe fails: letsketch ...: probe with driver letsketch failed with error -5 The tablet then does not work at all. The handshake only needs the reads to happen, not their contents. Once the retries are used up, report an index that still reads as empty or STALLs as missing with -ENOENT, and let the probe skip it. Other errors still fail the probe as before, and the retries stay in place, so firmware that only fails a read now and then behaves as it did. With this change the GC-422 completes the handshake, switches to raw mode and reports pen position, pressure and the five pad buttons. The change and this message were written with the help of an AI coding assistant (Claude Code); I reviewed them and tested the result on the hardware. Fixes: 33a5c2793451 ("HID: Add new Letsketch tablet driver") Signed-off-by: Eren Çakar Reviewed-by: Hans de Goede Signed-off-by: Jiri Kosina --- drivers/hid/hid-letsketch.c | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/drivers/hid/hid-letsketch.c b/drivers/hid/hid-letsketch.c index b52e93a91ae542..6a93245b7ac1ea 100644 --- a/drivers/hid/hid-letsketch.c +++ b/drivers/hid/hid-letsketch.c @@ -213,6 +213,12 @@ static int letsketch_raw_event(struct hid_device *hdev, * string descriptors. But the firmware is buggy and does not like it if * we do this too fast. Even if we go slow sometimes the usb_string() call * fails. Ignore errors and retry it a couple of times if necessary. + * + * Some firmware revisions (e.g. "Vision_V201_180530", sold as the Starcom + * GC-422) do not implement every string descriptor index the handshake + * reads. For those indices usb_string() keeps returning an empty string or + * -EPIPE (STALL). Report such an index as missing with -ENOENT once the + * retries are used up, so that the caller can skip it. */ static int letsketch_get_string(struct usb_device *udev, int index, char *buf, int size) { @@ -225,9 +231,14 @@ static int letsketch_get_string(struct usb_device *udev, int index, char *buf, i return 0; } + if (ret == 0 || ret == -EPIPE) { + dev_dbg(&udev->dev, "String descriptor %d not implemented\n", index); + return -ENOENT; + } + dev_err(&udev->dev, "Max retries (%d) exceeded reading string descriptor %d\n", LETSKETCH_GET_STRING_RETRIES, index); - return ret ? ret : -EIO; + return ret; } static int letsketch_probe(struct hid_device *hdev, const struct hid_device_id *id) @@ -256,6 +267,8 @@ static int letsketch_probe(struct hid_device *hdev, const struct hid_device_id * */ for (i = LETSKETCH_INFO_STR_IDX_BEGIN; i <= LETSKETCH_INFO_STR_IDX_END; i++) { ret = letsketch_get_string(udev, i, buf, sizeof(buf)); + if (ret == -ENOENT) + continue; if (ret) return ret; @@ -264,16 +277,16 @@ static int letsketch_probe(struct hid_device *hdev, const struct hid_device_id * for (i = 1; i <= 250; i++) { ret = letsketch_get_string(udev, i, buf, sizeof(buf)); - if (ret) + if (ret && ret != -ENOENT) return ret; } ret = letsketch_get_string(udev, 0x64, buf, sizeof(buf)); - if (ret) + if (ret && ret != -ENOENT) return ret; ret = letsketch_get_string(udev, LETSKETCH_INFO_STR_IDX_BEGIN, buf, sizeof(buf)); - if (ret) + if (ret && ret != -ENOENT) return ret; /* From 21eeb98663bd36ace9c646771484be3f049c9f02 Mon Sep 17 00:00:00 2001 From: Lukasz Leczkowski Date: Fri, 13 Nov 2026 20:00:32 +0100 Subject: [PATCH 1232/2102] HID: quirks: add ALWAYS_POLL for ASUS ProArt MD301 mouse In mouse firmware version 0.00.31 and receiver 0.00.20, the receiver of the ASUS ProArt MD301 mouse (0b05:1cd3) delays button events by up to ~500 ms. The receiver exposes five HID interfaces. Besides the keyboard and mouse interfaces, interface 4 (vendor usage page 0xffc1) carries a copy of every button and wheel event as a 64-byte vendor report. As this interface has no input handlers, usbhid does not poll its interrupt-IN endpoint unless userspace opens the hidraw node. The firmware appears to hold back the mouse report on interface 1 until the vendor report has been read or some timeout expires. Add HID_QUIRK_ALWAYS_POLL for the receiver so that all of its endpoints are polled continuously. The issue was analysed with the help of Claude Code (Claude Opus 5.5), which captured the raw HID reports, identified the unpolled vendor interface and drafted this patch. Tested on 7.3.0 with this patch applied; clicks are delivered immediately and double-clicks work again. Signed-off-by: Lukasz Leczkowski Signed-off-by: Jiri Kosina --- drivers/hid/hid-ids.h | 1 + drivers/hid/hid-quirks.c | 1 + 2 files changed, 2 insertions(+) diff --git a/drivers/hid/hid-ids.h b/drivers/hid/hid-ids.h index 522a6678e806ba..845180955cb0d0 100644 --- a/drivers/hid/hid-ids.h +++ b/drivers/hid/hid-ids.h @@ -236,6 +236,7 @@ #define USB_DEVICE_ID_ASUSTEK_FX503VD_KEYBOARD 0x1869 #define USB_DEVICE_ID_ASUSTEK_XGM_2022 0x1970 #define USB_DEVICE_ID_ASUSTEK_XGM_2023 0x1a9a +#define USB_DEVICE_ID_ASUSTEK_MD301_DONGLE 0x1cd3 #define USB_VENDOR_ID_ATEN 0x0557 #define USB_DEVICE_ID_ATEN_UC100KM 0x2004 diff --git a/drivers/hid/hid-quirks.c b/drivers/hid/hid-quirks.c index 793db001a62b7b..952e1aec1ab692 100644 --- a/drivers/hid/hid-quirks.c +++ b/drivers/hid/hid-quirks.c @@ -37,6 +37,7 @@ static const struct hid_device_id hid_quirks[] = { { HID_USB_DEVICE(USB_VENDOR_ID_ALPS, USB_DEVICE_ID_IBM_GAMEPAD), HID_QUIRK_BADPAD }, { HID_USB_DEVICE(USB_VENDOR_ID_AMI, USB_DEVICE_ID_AMI_VIRT_KEYBOARD_AND_MOUSE), HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_REVB_ANSI), HID_QUIRK_ALWAYS_POLL }, + { HID_USB_DEVICE(USB_VENDOR_ID_ASUSTEK, USB_DEVICE_ID_ASUSTEK_MD301_DONGLE), HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_ATEN, USB_DEVICE_ID_ATEN_2PORTKVM), HID_QUIRK_NOGET }, { HID_USB_DEVICE(USB_VENDOR_ID_ATEN, USB_DEVICE_ID_ATEN_4PORTKVMC), HID_QUIRK_NOGET }, { HID_USB_DEVICE(USB_VENDOR_ID_ATEN, USB_DEVICE_ID_ATEN_4PORTKVM), HID_QUIRK_NOGET }, From c77a6be2ec23afe969046cbee63fa5a4945b58c1 Mon Sep 17 00:00:00 2001 From: Jianjun Lang Date: Tue, 3 Nov 2026 15:32:10 +0800 Subject: [PATCH 1233/2102] HID: steelseries: Add MSI Raider A18 HX A7VHG to RGB DMI table The MSI Raider A18 HX A7VHG (board MS-182K) uses the same internal SteelSeries KLC (1038:1122) and ALC (1038:1161) RGB controllers as the A9WJG, with the same 524-byte feature report layout and the same ALC LED IDs (0x00-0x02 lightbar segments, 0x03 lid logo). Add it to the DMI allow-list so the keyboard backlight and lightbar LED class devices are registered on this model as well. Tested on MSI Raider A18 HX A7VHG (BIOS E182KAMS.10D). Both devices bind on interface 0 and create steelseries::kbd_backlight and steelseries::lightbar. Writing multi_intensity and brightness changes the keyboard, lightbar and logo colors and brightness as expected. Signed-off-by: Jianjun Lang Signed-off-by: Jiri Kosina --- drivers/hid/hid-steelseries.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/hid/hid-steelseries.c b/drivers/hid/hid-steelseries.c index 7292da0313e112..116d5a01e6194f 100644 --- a/drivers/hid/hid-steelseries.c +++ b/drivers/hid/hid-steelseries.c @@ -356,6 +356,13 @@ static const struct dmi_system_id steelseries_msi_rgb_dmi_table[] = { DMI_MATCH(DMI_BOARD_NAME, "MS-182L"), }, }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International Co., Ltd."), + DMI_MATCH(DMI_PRODUCT_NAME, "Raider A18 HX A7VHG"), + DMI_MATCH(DMI_BOARD_NAME, "MS-182K"), + }, + }, { } }; From bfa77b14ac965677d8d4f716b790d42206ddaef5 Mon Sep 17 00:00:00 2001 From: Ping Cheng Date: Tue, 3 Nov 2026 18:01:08 -0700 Subject: [PATCH 1234/2102] HID: wacom: Access shared touch input by rcu_dereference() Allow the __rcu-annotated wacom_wac->shared->touch_input to be accessed inside an RCU read-side critical section by using rcu_dereference(). Cc: stable@vger.kernel.org Reported-by: kernel test robot Closes: https://lore.kernel.org/oe-kbuild-all/202610180015.KsRqmoTE-lkp@intel.com/ Fixes: 9183319a5ba4 ("Input: wacom - Setup SW_MUTE_DEVICE according to the order of input registration") Suggested-by: Dmitry Torokhov Signed-off-by: Ping Cheng Reviewed-by: Dmitry Torokhov Signed-off-by: Jiri Kosina --- drivers/hid/wacom_wac.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/drivers/hid/wacom_wac.c b/drivers/hid/wacom_wac.c index 5b3fbc5a8e1b16..ab89a11d674039 100644 --- a/drivers/hid/wacom_wac.c +++ b/drivers/hid/wacom_wac.c @@ -4434,7 +4434,7 @@ int wacom_setup_pad_input_capabilities(struct input_dev *input_dev, break; case HID_GENERIC: - if (wacom_wac->shared) { + if (wacom_wac->shared && wacom_wac->has_mute_touch_switch) { /* * The setup of touch switch capability can only be done * here for those devices, such as Cintiq Pro 13 and 16, @@ -4445,11 +4445,12 @@ int wacom_setup_pad_input_capabilities(struct input_dev *input_dev, * stylus first or touch first. This path covers the touch * input first case. */ - if (wacom_wac->has_mute_touch_switch && - wacom_wac->shared->touch_input) { - input_set_capability(wacom_wac->shared->touch_input, - EV_SW, SW_MUTE_DEVICE); - } + struct input_dev *touch_input; + + guard(rcu)(); + touch_input = rcu_dereference(wacom_wac->shared->touch_input); + if (touch_input) + input_set_capability(touch_input, EV_SW, SW_MUTE_DEVICE); } break; From 914d46521de1bdd999fb4c6263172c13b2164218 Mon Sep 17 00:00:00 2001 From: Mathias Krause Date: Thu, 5 Nov 2026 18:01:16 +0100 Subject: [PATCH 1235/2102] HID: Intel-thc-hid: Fix REGMAP dependency intel-thc-{dev,dma}.c make use of the regmap API and related data structures, breaking the build if CONFIG_REGMAP isn't set. Fix that by forcibly enabling REGMAP when this driver gets build. Fixes: 1b2d05384c29 ("HID: intel-thc-hid: Add basic THC driver skeleton") Signed-off-by: Mathias Krause Reviewed-by: Even Xu Signed-off-by: Jiri Kosina --- drivers/hid/intel-thc-hid/Kconfig | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/hid/intel-thc-hid/Kconfig b/drivers/hid/intel-thc-hid/Kconfig index 9d74e53b8c62b3..57a1e51cb512ef 100644 --- a/drivers/hid/intel-thc-hid/Kconfig +++ b/drivers/hid/intel-thc-hid/Kconfig @@ -8,6 +8,7 @@ config INTEL_THC_HID tristate "Intel Touch Host Controller" depends on ACPI select SGL_ALLOC + select REGMAP help THC (Touch Host Controller) is the name of the IP block in PCH that interfaces with Touch Devices (ex: touchscreen, touchpad etc.). It From 6f8fb7acb3848dcb094ab22053b4194e12dc8aee Mon Sep 17 00:00:00 2001 From: Muhammed Sariyildiz Date: Thu, 5 Nov 2026 20:42:52 +0300 Subject: [PATCH 1236/2102] HID: multitouch: Preserve class quirks when inverting orientation When exactly one coordinate axis is inverted, mt_probe() replaces the device class quirks with MT_QUIRK_ORIENTATION_INVERT. This drops all quirks selected for the device class. Applications created later inherit the truncated quirk mask, which can break device-specific contact handling. Add the orientation quirk instead of replacing the existing mask. Signed-off-by: Muhammed Sariyildiz Signed-off-by: Jiri Kosina --- drivers/hid/hid-multitouch.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/hid/hid-multitouch.c b/drivers/hid/hid-multitouch.c index 4e19a0c4d2381d..94e83fce90dc28 100644 --- a/drivers/hid/hid-multitouch.c +++ b/drivers/hid/hid-multitouch.c @@ -2155,7 +2155,7 @@ static int mt_probe(struct hid_device *hdev, const struct hid_device_id *id) if (hdev->quirks & (HID_QUIRK_X_INVERT | HID_QUIRK_Y_INVERT) && !((hdev->quirks & HID_QUIRK_X_INVERT) && (hdev->quirks & HID_QUIRK_Y_INVERT))) - td->mtclass.quirks = MT_QUIRK_ORIENTATION_INVERT; + td->mtclass.quirks |= MT_QUIRK_ORIENTATION_INVERT; /* This allows the driver to correctly support devices * that emit events over several HID messages. From 92cbe1442b0980dcc96f2d1d71049a18b044cb51 Mon Sep 17 00:00:00 2001 From: David Cemin Date: Tue, 20 Oct 2026 15:09:19 -0700 Subject: [PATCH 1237/2102] HID: asus: map Consumer brightness usages on I2C keyboards Several ASUS laptops carry their keyboard on an I2C-HID device with ID 0B05:4B42, the same ID as the Zenbook A16 (UX3607OA), so they bind to hid-asus with I2C_KEYBOARD_QUIRKS since commit 206107536018 ("HID: asus: support the Zenbook A16 (UX3607OA) keyboard"). Unlike the A16, which reports its brightness hotkeys on the ASUS vendor page, these keyboards report them as the standard Consumer usages Display Brightness Decrement (0x70) and Display Brightness Increment (0x6f) on report 3. I2C_KEYBOARD_QUIRKS includes QUIRK_NO_CONSUMER_USAGES, whose input mapping ignores every Consumer usage except mute and volume, so the brightness keys never produce input events. The keys work when the keyboard happens to be bound to hid-generic, which maps those usages by default, and stop working as soon as hid-asus claims the device. Let the two display brightness usages through the filter so hid-input maps them to KEY_BRIGHTNESSUP and KEY_BRIGHTNESSDOWN. Keyboards that do not report them are unaffected. Tested on two ASUS laptop models with this keyboard: with the keyboard bound to hid-asus, the brightness keys now adjust the panel brightness. Signed-off-by: David Cemin Signed-off-by: Jiri Kosina --- drivers/hid/hid-asus.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/hid/hid-asus.c b/drivers/hid/hid-asus.c index dc9f41cf6e82d2..f8339740b9ba45 100644 --- a/drivers/hid/hid-asus.c +++ b/drivers/hid/hid-asus.c @@ -1371,6 +1371,8 @@ static int asus_input_mapping(struct hid_device *hdev, case 0xe2: /* Mute */ case 0xe9: /* Volume up */ case 0xea: /* Volume down */ + case 0x6f: /* Display brightness increment */ + case 0x70: /* Display brightness decrement */ return 0; default: /* Ignore dummy Consumer usages which make the From ffadbae818a2f49551afba733d9f977b773ce6be Mon Sep 17 00:00:00 2001 From: Nguyen Ngoc Thang Date: Thu, 15 Oct 2026 22:13:18 +0700 Subject: [PATCH 1238/2102] HID: saitek: don't dereference a NULL hidinput in saitek_event() hid_process_event() calls the driver's ->event() for every usage of a report, including fields that hidinput did not map to any input device, e.g. a constant input item. For those fields field->hidinput is NULL, and saitek_event() loads field->hidinput->input unconditionally: KASAN: null-ptr-deref in range [0x0000000000000018-0x000000000000001f] RIP: 0010:saitek_event+0x51/0x2b0 drivers/hid/hid-saitek.c:154 hid_process_event drivers/hid/hid-core.c:1572 hid_report_raw_event drivers/hid/hid-core.c:2109 hid_input_report drivers/hid/hid-core.c:2180 hid_irq_in drivers/hid/usbhid/hid-core.c A device that claims to be a Saitek MMO7 and uses such a descriptor triggers it with a single input report. Bail out early when the input side is not claimed or the field has no input device, as the other HID drivers implementing ->event() do. The claimed check also covers a failed hidinput_connect(), which frees the hid_input structures without clearing field->hidinput. Fixes: 37c492c8f6a9 ("HID: quirk for Saitek RAT7 and MMO7 mices' mode button") Reported-by: syzbot+eba2b3201bd25a97cddf@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=eba2b3201bd25a97cddf Cc: stable@vger.kernel.org Signed-off-by: Nguyen Ngoc Thang Signed-off-by: Jiri Kosina --- drivers/hid/hid-saitek.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/hid/hid-saitek.c b/drivers/hid/hid-saitek.c index 6fe7c087c594ea..7e1160a24230c5 100644 --- a/drivers/hid/hid-saitek.c +++ b/drivers/hid/hid-saitek.c @@ -151,7 +151,12 @@ static int saitek_event(struct hid_device *hdev, struct hid_field *field, struct hid_usage *usage, __s32 value) { struct saitek_sc *ssc = hid_get_drvdata(hdev); - struct input_dev *input = field->hidinput->input; + struct input_dev *input; + + if (!(hdev->claimed & HID_CLAIMED_INPUT) || !field->hidinput) + return 0; + + input = field->hidinput->input; if (usage->type == EV_KEY && value && (((ssc->quirks & SAITEK_RELEASE_MODE_RAT7) && From 994baf0611c267040f9332358fc07237c16cd778 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ignacio=20Mart=C3=ADn=20Arano?= Date: Thu, 22 Oct 2026 21:44:19 -0300 Subject: [PATCH 1239/2102] HID: apple: Add "F108Pro Dongle" to the list of non-apple keyboards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 2.4 GHz dongle of the AULA F108 Pro keyboard reports itself as "Apple, Inc. Aluminium Keyboard (ANSI)" (05ac:024f), so hid-apple binds to it and, with the default fnmode, maps F1-F12 to their media functions. The keyboard has no Fn key visible to the host (Fn is handled in firmware), so the function keys become unreachable. Add its product string to the list of non-Apple keyboards so that fnmode=3 resolves to fkeysfirst, like it already does for the SONiX keyboards sharing the same VID/PID. Signed-off-by: Ignacio Martín Arano Signed-off-by: Jiri Kosina --- drivers/hid/hid-apple.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/hid/hid-apple.c b/drivers/hid/hid-apple.c index 5b32fb8c77f3fc..82118d65430aa9 100644 --- a/drivers/hid/hid-apple.c +++ b/drivers/hid/hid-apple.c @@ -357,6 +357,7 @@ static const struct apple_key_translation swapped_fn_leftctrl_keys[] = { }; static const struct apple_non_apple_keyboard non_apple_keyboards[] = { + { "F108Pro Dongle" }, /* AULA F108 Pro 2.4G dongle */ { "SONiX KN85 Keyboard" }, { "SONiX USB DEVICE" }, { "SONiX AK870 PRO" }, From 107274055fd9726f8f077529ae8c0da09237ad3e Mon Sep 17 00:00:00 2001 From: HyeongJun An Date: Wed, 28 Oct 2026 15:55:12 +0800 Subject: [PATCH 1240/2102] HID: intel-thc-hid: intel-quickspi: validate GET REPORT response size quickspi_handle_input_data() copies GET_FEATURE and GET_INPUT_REPORT responses into qsdev->report_buf. The response length is derived from data supplied by the controller, but was not checked against the destination buffer size. Adjust qsdev->report_buf_size to store the data length of report buffer, reject responses that exceed it before copying. This prevents an oversized response from overflowing report_buf. The rejected response does not complete the GET REPORT request, so quickspi_get_report() follows its existing timeout path. Fixes: 9d8d51735a3a ("HID: intel-thc-hid: intel-quickspi: Add HIDSPI protocol implementation") Cc: stable@vger.kernel.org Assisted-by: Claude:claude-opus-5 Signed-off-by: HyeongJun An Signed-off-by: Even Xu Tested-by: Rui Zhang Signed-off-by: Jiri Kosina --- .../intel-thc-hid/intel-quickspi/pci-quickspi.c | 16 ++++++++-------- .../intel-thc-hid/intel-quickspi/quickspi-dev.h | 1 + .../intel-quickspi/quickspi-protocol.c | 12 ++++++++++-- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/drivers/hid/intel-thc-hid/intel-quickspi/pci-quickspi.c b/drivers/hid/intel-thc-hid/intel-quickspi/pci-quickspi.c index 53023e30cf8d47..d0aa66a8a4b496 100644 --- a/drivers/hid/intel-thc-hid/intel-quickspi/pci-quickspi.c +++ b/drivers/hid/intel-thc-hid/intel-quickspi/pci-quickspi.c @@ -562,17 +562,17 @@ static int quickspi_alloc_report_buf(struct quickspi_device *qsdev) max_report_len = max(le16_to_cpu(qsdev->dev_desc.max_output_len), le16_to_cpu(qsdev->dev_desc.max_input_len)); - /* - * write_cmd_to_txdma() writes the output report header ahead of the - * content in this buffer, so it has to hold both. - */ - qsdev->report_buf_size = HIDSPI_OUTPUT_REPORT_SIZE(max_report_len); - - qsdev->report_buf = devm_kzalloc(qsdev->dev, qsdev->report_buf_size, - GFP_KERNEL); + qsdev->report_buf = devm_kzalloc(qsdev->dev, + HIDSPI_OUTPUT_REPORT_SIZE(max_report_len), GFP_KERNEL); if (!qsdev->report_buf) return -ENOMEM; + /* + * Store the max data length of this report buffer, then compare it with output/input + * packet content when write or read into this report buffer to avoid buffer overflow. + */ + qsdev->report_buf_size = max_report_len; + return 0; } diff --git a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-dev.h b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-dev.h index fe51ff51d8c0e9..4362ac568bdaa9 100644 --- a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-dev.h +++ b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-dev.h @@ -115,6 +115,7 @@ struct acpi_device; * @input_buf: store a copy of latest input report data * @input_len: the data size of the input report buffer * @report_buf: store a copy of latest input/output report packet from set/get feature + * @report_buf_size: the data size of input/output buffer * @report_len: the length of input/output report packet * @reset_ack_wq: workqueue for waiting reset response from device * @reset_ack: indicate reset response received or not diff --git a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-protocol.c b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-protocol.c index 0df33c44fbffe5..f8b455fd393995 100644 --- a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-protocol.c +++ b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-protocol.c @@ -30,7 +30,7 @@ static int write_cmd_to_txdma(struct quickspi_device *qsdev, write_buf = (struct output_report *)qsdev->report_buf; - if (HIDSPI_OUTPUT_REPORT_SIZE(report_buf_len) > qsdev->report_buf_size) + if (report_buf_len > qsdev->report_buf_size) return -EINVAL; write_buf->output_hdr.report_type = report_type; @@ -161,6 +161,7 @@ void quickspi_handle_input_data(struct quickspi_device *qsdev, u32 buf_len) struct input_report_body *input_body; u8 *input_report; u32 input_len; + u32 report_len; int ret = 0; input_body = (struct input_report_body *)qsdev->input_buf; @@ -210,7 +211,14 @@ void quickspi_handle_input_data(struct quickspi_device *qsdev, u32 buf_len) case GET_FEATURE_RESPONSE: case GET_INPUT_REPORT_RESPONSE: - qsdev->report_len = sizeof(body_hdr->content_id) + input_len; + report_len = sizeof(body_hdr->content_id) + input_len; + if (input_len > qsdev->report_buf_size) { + dev_err_once(qsdev->dev, "Get report response too big: %u\n", + input_len); + return; + } + + qsdev->report_len = report_len; input_report = input_body->content - sizeof(body_hdr->content_id); memcpy(qsdev->report_buf, input_report, qsdev->report_len); From 7220fddb3fc17cef19351cc9d12b6c9bc37a3b50 Mon Sep 17 00:00:00 2001 From: Devarjya Purkayastha Date: Fri, 30 Oct 2026 23:01:08 +0530 Subject: [PATCH 1241/2102] HID: wacom: Prevent NULL dereference in wireless work wacom_wireless_work() assumes that the active USB configuration has three interfaces and unconditionally accesses interface[1] and interface[2]. A malformed configuration with fewer interfaces can therefore cause a NULL pointer dereference in the wireless workqueue. Return early unless the configuration has at least three interfaces. Reported-by: Indrath Signed-off-by: Devarjya Purkayastha Reviewed-by: Jason Gerecke Signed-off-by: Jiri Kosina --- drivers/hid/wacom_sys.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/hid/wacom_sys.c b/drivers/hid/wacom_sys.c index 628372ab818a28..dcf2811a5c4832 100644 --- a/drivers/hid/wacom_sys.c +++ b/drivers/hid/wacom_sys.c @@ -2619,7 +2619,7 @@ static void wacom_wireless_work(struct work_struct *work) wacom_destroy_battery(wacom); - if (!usbdev) + if (!usbdev || usbdev->config->desc.bNumInterfaces < 3) return; /* Stylus interface */ From 314f3a84a49480488e67fabbae70a2262ea2a33c Mon Sep 17 00:00:00 2001 From: Viktor Sharha Date: Wed, 28 Oct 2026 23:29:45 +0000 Subject: [PATCH 1242/2102] HID: quirks: add ALWAYS_POLL quirk for Keychron Link receiver The Keychron Link 2.4 GHz receiver (3434:d030) exposes a joystick on an interface of its own. Keychron's Hall-effect keyboards, such as the K4 HE, send a burst of joystick reports on that interface every time the user switches actuation profile, even when no profile uses the joystick. Desktop environments do not open joystick devices, so usbhid does not poll that interface and the reports are never read. The receiver then stops delivering keyboard input on its other interfaces until the host re-enumerates it or the keyboard is switched to wired mode and back. A key held during the switch also keeps auto-repeating, because its release never arrives. Holding the joystick device open, or booting with usbhid.quirks=0x3434:0xd030:0x00000400, avoids the problem. Windows is not affected, as it polls every HID interface. Link: https://github.com/Keychron/qmk_firmware/issues/532 Signed-off-by: Viktor Sharha Signed-off-by: Jiri Kosina --- drivers/hid/hid-ids.h | 3 +++ drivers/hid/hid-quirks.c | 2 ++ 2 files changed, 5 insertions(+) diff --git a/drivers/hid/hid-ids.h b/drivers/hid/hid-ids.h index 845180955cb0d0..85902527f3cdeb 100644 --- a/drivers/hid/hid-ids.h +++ b/drivers/hid/hid-ids.h @@ -804,6 +804,9 @@ #define USB_VENDOR_ID_KENSINGTON 0x047d #define USB_DEVICE_ID_KS_SLIMBLADE 0x2041 +#define USB_VENDOR_ID_KEYCHRON 0x3434 +#define USB_DEVICE_ID_KEYCHRON_LINK 0xd030 + #define USB_VENDOR_ID_KWORLD 0x1b80 #define USB_DEVICE_ID_KWORLD_RADIO_FM700 0xd700 diff --git a/drivers/hid/hid-quirks.c b/drivers/hid/hid-quirks.c index 952e1aec1ab692..dbc40bb9c3adf8 100644 --- a/drivers/hid/hid-quirks.c +++ b/drivers/hid/hid-quirks.c @@ -117,6 +117,8 @@ static const struct hid_device_id hid_quirks[] = { { HID_USB_DEVICE(USB_VENDOR_ID_INNOMEDIA, USB_DEVICE_ID_INNEX_GENESIS_ATARI), HID_QUIRK_MULTI_INPUT }, { HID_USB_DEVICE(USB_VENDOR_ID_JESS, USB_DEVICE_ID_AULA_MINI_60_HE_PRO), HID_QUIRK_ALWAYS_POLL }, + { HID_USB_DEVICE(USB_VENDOR_ID_KEYCHRON, USB_DEVICE_ID_KEYCHRON_LINK), + HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_PIXART_USB_OPTICAL_MOUSE_ID2), HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_EASYPEN_M406), HID_QUIRK_MULTI_INPUT }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_EASYPEN_M506), HID_QUIRK_MULTI_INPUT }, From 10bc1d627c297097cfdc099377f8a13efdfffd86 Mon Sep 17 00:00:00 2001 From: Sang-Hoon Choi Date: Tue, 22 Sep 2026 03:49:28 +0900 Subject: [PATCH 1243/2102] HID: nintendo: release the player ID when LED setup fails joycon_leds_create() allocates a player ID before allocating the LED names and registering the LEDs. If one of those later steps fails, nintendo_hid_probe() jumps to err_io_stop and skips the ID cleanup. The failed probe leaves the allocated ID in nintendo_player_id_allocator. Use err_ida for this failure, as the power supply and input setup error paths already do. If the ID allocation itself failed, player_id is U32_MAX and ida_free() leaves the allocator untouched. Fixes: 5307de63d71d ("HID: nintendo: use ida for LED player id") Reported-by: Changyul Lee Assisted-by: LLM Signed-off-by: Sang-Hoon Choi Signed-off-by: Jiri Kosina --- drivers/hid/hid-nintendo.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/hid/hid-nintendo.c b/drivers/hid/hid-nintendo.c index c2a35154cc6c58..86d41d67eef4b8 100644 --- a/drivers/hid/hid-nintendo.c +++ b/drivers/hid/hid-nintendo.c @@ -2791,7 +2791,7 @@ static int joycon_probe(struct hid_device *hdev, ret = joycon_leds_create(ctlr); if (ret) { hid_err(hdev, "Failed to create leds; ret=%d\n", ret); - goto err_io_stop; + goto err_ida; } /* Initialize the battery power supply */ From 37f9e28baa834d488095c7676c617dfa509c0bd0 Mon Sep 17 00:00:00 2001 From: Nguyen Minh Tien Date: Thu, 8 Oct 2026 22:54:02 +0700 Subject: [PATCH 1244/2102] usb: musb: Disable the D+ pullup during system suspend When musb_suspend() clears DEVCTL, the host sees a disconnect. But VBUS is still there, so the controller can start a new session on its own and, with SOFTCONN still set, pull D+ up again while its interrupts are masked. The host then fails to enumerate the gadget ("unable to enumerate USB device") and gives up, and nothing at resume makes it try again. On a T113-S3 board the gadget link never survived an s2idle cycle. Clear SOFTCONN once the context is saved; musb_restore_context() puts it back on resume. This is what the FIXME asked for, as USB can't wake us in time with the interrupts masked. Platforms that power the PHY off during suspend, like the AM335x, never showed the problem: D+ drops with the PHY. Fixes: 6fc6f4b87cb3 ("usb: musb: Disable interrupts on suspend, enable them on resume") Cc: stable@kernel.org Signed-off-by: Nguyen Minh Tien Link: https://patch.msgid.link/20261008155402.66266-1-tien.nguyenminh@embeddedlinux.blog Signed-off-by: Greg Kroah-Hartman --- drivers/usb/musb/musb_core.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/drivers/usb/musb/musb_core.c b/drivers/usb/musb/musb_core.c index 25115217e0af6e..eb29ae47697c29 100644 --- a/drivers/usb/musb/musb_core.c +++ b/drivers/usb/musb/musb_core.c @@ -2834,18 +2834,26 @@ static int musb_suspend(struct device *dev) spin_lock_irqsave(&musb->lock, flags); + musb_save_context(musb); + if (is_peripheral_active(musb)) { - /* FIXME force disconnect unless we know USB will wake - * the system up quickly enough to respond ... + /* + * We can't answer a host with the interrupts off, so disable + * the D+ pullup. musb_restore_context() puts back the state + * saved above. Where the PHY is powered off during suspend + * (AM335x, for one), D+ drops anyway; where it stays powered, + * as on sunxi, the host would see a device that can't answer. */ + u8 power = musb_readb(musb->mregs, MUSB_POWER); + + musb_writeb(musb->mregs, MUSB_POWER, + power & ~MUSB_POWER_SOFTCONN); } else if (is_host_active(musb)) { /* we know all the children are suspended; sometimes * they will even be wakeup-enabled. */ } - musb_save_context(musb); - spin_unlock_irqrestore(&musb->lock, flags); return 0; } From 81fbc49e54cd8a8d10677878cc98a76d44797ea8 Mon Sep 17 00:00:00 2001 From: Myeonghun Pak Date: Fri, 2 Oct 2026 23:49:08 -0400 Subject: [PATCH 1245/2102] usb: gadget: m66592-udc: Free the IRQ before unmapping registers m66592_remove() unmaps the controller registers before removing its shared IRQ handler. Another device on the same IRQ can invoke m66592_irq() in that interval, and the handler reads and writes registers even when the controller has no enabled interrupt pending. CONFIG_DEBUG_SHIRQ can also invoke the handler from free_irq() after the mapping has gone away. Shut down the sampling timer and mask the controller interrupt sources before unregistering the gadget. The timer can enable interrupts and invoke the gadget driver's disconnect callback, while gadget teardown clears the driver pointer and disables the controller's internal clocks. Then free the IRQ before unmapping the registers so the handler finishes while its MMIO mapping and private data are still valid. This issue was identified during our ongoing static-analysis research while reviewing kernel code. Fixes: 4cf2503c6801 ("USB: m66592-udc: peripheral controller driver for M66592") Cc: stable@kernel.org Assisted-by: LLM Co-developed-by: Ijae Kim Signed-off-by: Ijae Kim Signed-off-by: Myeonghun Pak Reviewed-by: Aldo Ariel Panzardo Link: https://patch.msgid.link/20261003034908.619696-1-mhun512@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/udc/m66592-udc.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/drivers/usb/gadget/udc/m66592-udc.c b/drivers/usb/gadget/udc/m66592-udc.c index d77c11c4eb38bb..773cd00fbf1d33 100644 --- a/drivers/usb/gadget/udc/m66592-udc.c +++ b/drivers/usb/gadget/udc/m66592-udc.c @@ -1515,12 +1515,16 @@ static const struct usb_gadget_ops m66592_gadget_ops = { static void m66592_remove(struct platform_device *pdev) { struct m66592 *m66592 = platform_get_drvdata(pdev); - - usb_del_gadget_udc(&m66592->gadget); + unsigned long flags; timer_shutdown_sync(&m66592->timer); - iounmap(m66592->reg); + spin_lock_irqsave(&m66592->lock, flags); + m66592_write(m66592, 0, M66592_INTENB0); + spin_unlock_irqrestore(&m66592->lock, flags); + + usb_del_gadget_udc(&m66592->gadget); free_irq(platform_get_irq(pdev, 0), m66592); + iounmap(m66592->reg); m66592_free_request(&m66592->ep[0].ep, m66592->ep0_req); if (m66592->pdata->on_chip) { clk_disable(m66592->clk); From c0710989d7ebedf4b0130b08ad7dd3f65d026fe8 Mon Sep 17 00:00:00 2001 From: Sasha Levin Date: Tue, 27 Oct 2026 15:19:14 -0400 Subject: [PATCH 1246/2102] KVM: x86: Don't save the GPA of a fault on the guest's page tables When a #NPF or EPT violation on a direct MMU leads to emulation, x86_emulate_instruction() saves the faulting GPA to avoid a table walk. However, if the fault occurred while the CPU was walking the guest's page tables (PFERR_GUEST_PAGE_MASK), the GPA is that of a guest paging structure, not of the access being emulated, and the access goes to the wrong address. KVM selftest set_memory_region_test runs into this on AMD. test_delete_memory_region() deletes the memslot holding the guest's page tables while the guest spins on a read of 0xc0000000 that userspace handles as MMIO. If the vCPU is at the read when the memslot goes away, the CPU takes a #NPF on the guest's root page table at 0x180000. DecodeAssist provides the instruction bytes, the read of 0xc0000000 has the same page offset as 0x180000, and the emulator turns it into an MMIO read of 0x180000: ==== Test Assertion Failure ==== set_memory_region_test.c:83: run->mmio.phys_addr == MEM_REGION_GPA ... Unexpected exit mmio address = 0x180000 If the vCPU is at the next instruction instead, the #NPF happens on the code fetch, DecodeAssist provides no bytes, KVM fails to fetch the instruction itself and injects a #PF, and the guest shuts down as the test expects. KernelCI sees the failure in about half of the runs on a DL345 Gen11 (EPYC). Tell the emulator when the fault occurred on the guest's page tables and don't use the GPA for the access then, so that the emulator does perform the guest page table walk and the correct gpa is reported for KVM_EXIT_MMIO. Fixes: 0f89b207b04a ("kvm: svm: Use the hardware provided GPA instead of page walk") Signed-off-by: Sasha Levin Link: https://patch.msgid.link/20261027191914.2341911-1-sashal@kernel.org [Paolo: extract SEV change to a separate commit] Signed-off-by: Paolo Bonzini --- arch/x86/kvm/mmu/mmu.c | 2 ++ arch/x86/kvm/x86.c | 10 ++++++++-- arch/x86/kvm/x86.h | 4 ++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/arch/x86/kvm/mmu/mmu.c b/arch/x86/kvm/mmu/mmu.c index f89e9f8a6cc2f8..b122061b1fabab 100644 --- a/arch/x86/kvm/mmu/mmu.c +++ b/arch/x86/kvm/mmu/mmu.c @@ -6729,6 +6729,8 @@ int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 err emulate: if (error_code & PFERR_WRITE_MASK) emulation_type |= EMULTYPE_PF_WRITE; + if (error_code & PFERR_GUEST_PAGE_MASK) + emulation_type |= EMULTYPE_PF_GUEST_PAGE; return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn, insn_len); diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 802dd6fed8d436..0549c0b4890136 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -6495,8 +6495,14 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, /* Save the faulting GPA (cr2) in the address field */ ctxt->exception.address = cr2_or_gpa; - /* With shadow page tables, cr2 contains a GVA or nGPA. */ - if (vcpu->arch.mmu->root_role.direct) { + /* + * Remember the GPA if available; with shadow page tables, + * cr2 contains a GVA or nGPA, and if the fault occurred while + * walking the guest's page tables, the GPA is that of a guest + * paging structure. + */ + if (vcpu->arch.mmu->root_role.direct && + !(emulation_type & EMULTYPE_PF_GUEST_PAGE)) { ctxt->gpa_access = ACC_READ_MASK; /* * Always allow writes for guests with protected page diff --git a/arch/x86/kvm/x86.h b/arch/x86/kvm/x86.h index 436e2fb1396c46..cc9e28f32d1b63 100644 --- a/arch/x86/kvm/x86.h +++ b/arch/x86/kvm/x86.h @@ -410,6 +410,9 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, * * EMULTYPE_PF_WRITE - Set with EMULTYPE_PF when hardware reports a write access. * + * EMULTYPE_PF_GUEST_PAGE - Set with EMULTYPE_PF when hardware reports that the + * fault occurred while walking the guest's page tables. + * * EMULTYPE_COMPLETE_USER_EXIT - Set when the emulator should update interruptibility * state and inject single-step #DBs after skipping * an instruction (after completing userspace I/O). @@ -449,6 +452,7 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, #define EMULTYPE_WRITE_PF_TO_SP (1 << 8) #define EMULTYPE_SKIP_SOFT_INT (1 << 9) #define EMULTYPE_PF_WRITE (1 << 10) +#define EMULTYPE_PF_GUEST_PAGE (1 << 11) #define EMULTYPE_SET_SOFT_INT_VECTOR(v) ((u32)((v) & 0xff) << 16) #define EMULTYPE_GET_SOFT_INT_VECTOR(e) (((e) >> 16) & 0xff) From a26bd9acee2f35f9d9d7e8772740c8c8329adecb Mon Sep 17 00:00:00 2001 From: Aldo Ariel Panzardo Date: Tue, 15 Sep 2026 01:09:47 -0300 Subject: [PATCH 1247/2102] usb: gadget: composite: pass the validated interface index composite_setup() validates the low byte of wIndex as an interface number, but passes the full 16-bit wIndex to the function's get_alt and set_alt callbacks. FunctionFS reverse-maps the low byte and then uses the original callback argument to index its fixed-size cur_alt array. Pass the decoded and validated interface number to the callbacks. This matches the callback contract and prevents an out-of-bounds cur_alt access when the high byte of wIndex is nonzero. Fixes: 2f550553e23c ("usb: gadget: f_fs: Add the missing get_alt callback") Reported-by: Chris Mason Link: https://lore.kernel.org/r/3984c9bd-2ac8-424e-9390-7170fdab3c03@meta.com Cc: stable@kernel.org Signed-off-by: Aldo Ariel Panzardo Link: https://patch.msgid.link/20260915040947.2426239-1-qwe.aldo@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/composite.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/usb/gadget/composite.c b/drivers/usb/gadget/composite.c index 1b2238147cfe38..de677685069a22 100644 --- a/drivers/usb/gadget/composite.c +++ b/drivers/usb/gadget/composite.c @@ -1930,7 +1930,7 @@ composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl) break; spin_lock(&cdev->lock); - value = f->set_alt(f, w_index, w_value); + value = f->set_alt(f, intf, w_value); if (value == USB_GADGET_DELAYED_STATUS) { DBG(cdev, "%s: interface %d (%s) requested delayed status\n", @@ -1950,7 +1950,7 @@ composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl) if (!f) break; /* lots of interfaces only need altsetting zero... */ - value = f->get_alt ? f->get_alt(f, w_index) : 0; + value = f->get_alt ? f->get_alt(f, intf) : 0; if (value < 0) break; *((u8 *)req->buf) = value; From 3424a1e60694124595926538bf04a4e127671538 Mon Sep 17 00:00:00 2001 From: Fabrice Gasnier Date: Wed, 4 Nov 2026 14:20:15 +0100 Subject: [PATCH 1248/2102] usb: dwc2: fix fifo reinit in dwc2_hsotg_core_init_disconnected Currently, the fifo gets re-init, with a running DMA, e.g. when using_desc_dma(): - dwc2_hsotg_init_fifo -> Flushes the FIFO, DMA may run in parallel - DCFG_DESCDMA_EN gets cleared (e.g. disables dma desc) - then DCFG_DESCDMA_EN gets set back again. So move the dwc2_hsotg_init_fifo() call after DCFG_DESCDMA_EN gets cleared e.g. DCFG write. Then the FIFO can be flushed safely, before DCFG_DESCDMA_EN is set back on. A BNA interrupt may happen on EP0, before this change. When it happens we can't recover to a working device. Fixes: a5c18f113150 ("usb: dwc2: gadget: Enable descriptor DMA mode") Cc: stable@kernel.org Acked-by: Thinh Nguyen Signed-off-by: Fabrice Gasnier Link: https://patch.msgid.link/20261104-dwc2-fifo-fixes-v2-v2-1-2bb13820f662@foss.st.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc2/gadget.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/usb/dwc2/gadget.c b/drivers/usb/dwc2/gadget.c index c72f02adff5955..8f413d6f5ae23b 100644 --- a/drivers/usb/dwc2/gadget.c +++ b/drivers/usb/dwc2/gadget.c @@ -3486,8 +3486,6 @@ void dwc2_hsotg_core_init_disconnected(struct dwc2_hsotg *hsotg, dwc2_phy_init(hsotg, true); - dwc2_hsotg_init_fifo(hsotg); - if (!is_usb_reset) { dwc2_set_bit(hsotg, DCTL, DCTL_SFTDISCON); if (hsotg->params.eusb2_disc) @@ -3515,6 +3513,8 @@ void dwc2_hsotg_core_init_disconnected(struct dwc2_hsotg *hsotg, dwc2_writel(hsotg, dcfg, DCFG); + dwc2_hsotg_init_fifo(hsotg); + /* Clear any pending OTG interrupts */ dwc2_writel(hsotg, 0xffffffff, GOTGINT); From 8f89357faa07f99e1b5a9e5a0a92357e29c3e6f1 Mon Sep 17 00:00:00 2001 From: Fabrice Gasnier Date: Wed, 4 Nov 2026 14:20:16 +0100 Subject: [PATCH 1249/2102] usb: dwc2: wa for isoc packet tx fifo flush at periodic frame boundary If an isochronous packet is still being transmitted, when the end of periodic frame interval elapses, using dma desc on dwc2 controller, the device wrongly flushes the pending packets from the tx fifo. This can lead to a huge packet is sent on the bus, leading to the host finally reset the bus, and re-enumerate it. Workaround it by tuning the periodic frame interval limit from 80% to 95%, on the affected cores (2.70a to 4.00a). It makes the issue very unlikely to occur. Fixes: 540ccba08599 ("usb: dwc2: gadget: Start and complete DDMA isoc transfers") Cc: stable@kernel.org Signed-off-by: Fabrice Gasnier Acked-by: Thinh Nguyen Link: https://patch.msgid.link/20261104-dwc2-fifo-fixes-v2-v2-2-2bb13820f662@foss.st.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc2/core.h | 1 + drivers/usb/dwc2/gadget.c | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/drivers/usb/dwc2/core.h b/drivers/usb/dwc2/core.h index 015a5fb7842d57..54c040da0cae12 100644 --- a/drivers/usb/dwc2/core.h +++ b/drivers/usb/dwc2/core.h @@ -1108,6 +1108,7 @@ struct dwc2_hsotg { /* DWC OTG HW Release versions */ #define DWC2_CORE_REV_4_30a 0x4f54430a +#define DWC2_CORE_REV_2_70a 0x4f54270a #define DWC2_CORE_REV_2_71a 0x4f54271a #define DWC2_CORE_REV_2_72a 0x4f54272a #define DWC2_CORE_REV_2_80a 0x4f54280a diff --git a/drivers/usb/dwc2/gadget.c b/drivers/usb/dwc2/gadget.c index 8f413d6f5ae23b..36936a04502acc 100644 --- a/drivers/usb/dwc2/gadget.c +++ b/drivers/usb/dwc2/gadget.c @@ -3511,6 +3511,21 @@ void dwc2_hsotg_core_init_disconnected(struct dwc2_hsotg *hsotg, if (hsotg->params.ipg_isoc_en) dcfg |= DCFG_IPG_ISOC_SUPPORDED; + /* + * WA for Device Flushes Ongoing ISOC IN Packet at End-of-Periodic-Frame Boundary. + * Once passed the end of periodic frame, and the controller is transmitting an + * ISOC IN packet, the device flushes the transmit FIFO. Tune periodic frame + * interval to 95% instead of 80% to avoid it. + */ + if (using_desc_dma(hsotg) && + ((hsotg->hw_params.snpsid >= DWC2_CORE_REV_2_70a && + hsotg->hw_params.snpsid <= DWC2_CORE_REV_4_00a) || + hsotg->hw_params.snpsid == DWC2_FS_IOT_REV_1_00a || + hsotg->hw_params.snpsid == DWC2_HS_IOT_REV_1_00a)) { + dcfg &= ~DCFG_PERFRINT_MASK; + dcfg |= DCFG_PERFRINT(DCFG_PERFRINT_LIMIT); + } + dwc2_writel(hsotg, dcfg, DCFG); dwc2_hsotg_init_fifo(hsotg); From c303c716cac30f9358ac68f754483914778e80de Mon Sep 17 00:00:00 2001 From: Fang Xieyan Date: Wed, 11 Nov 2026 11:02:06 +0800 Subject: [PATCH 1250/2102] usb: gadget: r8a66597: fix NULL dereference for unmapped endpoints The epaddr2ep[] table is initialized with EP0 at probe time and populated for other endpoints when the gadget driver successfully enables them. Entries for endpoint numbers that have never been enabled remain NULL. The table is indexed by endpoint number and the lookup mask is USB_ENDPOINT_NUMBER_MASK, so the access itself stays in bounds; what is missing is the check for the NULL entry. get_status(), clear_feature() and set_feature() index this table using the host-controlled wIndex and immediately dereference the result without checking it. A malicious host can send a standard endpoint-recipient GET_STATUS, CLEAR_FEATURE or SET_FEATURE request for an unmapped endpoint number, triggering a NULL pointer dereference and crashing the kernel. Check the looked-up endpoint before using it. If the entry is NULL, stall the control pipe (pipe_stall(r8a66597, 0)) and abort the request, matching the existing handling of unsupported recipients. Fixes: c41442474a26 ("usb: gadget: R8A66597 peripheral controller support.") Cc: stable@kernel.org Reviewed-by: Liu Chao Signed-off-by: Fang Xieyan Link: https://patch.msgid.link/20261111030206.64608-1-fangxy@xiaopeng.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/udc/r8a66597-udc.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/drivers/usb/gadget/udc/r8a66597-udc.c b/drivers/usb/gadget/udc/r8a66597-udc.c index bfccc6565e0a3a..f9afa9812bdcb8 100644 --- a/drivers/usb/gadget/udc/r8a66597-udc.c +++ b/drivers/usb/gadget/udc/r8a66597-udc.c @@ -1174,6 +1174,10 @@ __acquires(r8a66597->lock) break; case USB_RECIP_ENDPOINT: ep = r8a66597->epaddr2ep[w_index & USB_ENDPOINT_NUMBER_MASK]; + if (!ep) { + pipe_stall(r8a66597, 0); + return; /* exit */ + } pid = control_reg_get_pid(r8a66597, ep->pipenum); if (pid == PID_STALL) status = 1 << USB_ENDPOINT_HALT; @@ -1210,6 +1214,10 @@ static void clear_feature(struct r8a66597 *r8a66597, u16 w_index = le16_to_cpu(ctrl->wIndex); ep = r8a66597->epaddr2ep[w_index & USB_ENDPOINT_NUMBER_MASK]; + if (!ep) { + pipe_stall(r8a66597, 0); + break; + } if (!ep->wedge) { pipe_stop(r8a66597, ep->pipenum); control_reg_sqclr(r8a66597, ep->pipenum); @@ -1270,6 +1278,10 @@ static void set_feature(struct r8a66597 *r8a66597, struct usb_ctrlrequest *ctrl) u16 w_index = le16_to_cpu(ctrl->wIndex); ep = r8a66597->epaddr2ep[w_index & USB_ENDPOINT_NUMBER_MASK]; + if (!ep) { + pipe_stall(r8a66597, 0); + break; + } pipe_stall(r8a66597, ep->pipenum); control_end(r8a66597, 1); From 232ff0632f8ca3f212c3fa97521419a640f9c8f3 Mon Sep 17 00:00:00 2001 From: Fang Xieyan Date: Thu, 5 Nov 2026 11:49:46 +0800 Subject: [PATCH 1251/2102] usb: dwc2: gadget: fix off-by-one in ep_from_windex bounds check ep_from_windex() checks whether idx is greater than hsotg->num_of_eps. However, num_of_eps includes EP0, so valid endpoint indices are in the range [0, num_of_eps - 1]. When idx equals num_of_eps, index_to_ep() accesses the endpoint array beyond the configured range. This results in an out-of-bounds access when num_of_eps equals MAX_EPS_CHANNELS. Otherwise, the zero-initialized array entry is NULL and the request is rejected. Reject indices greater than or equal to num_of_eps. Fixes: c6f5c050e2a7 ("usb: dwc2: gadget: add bi-directional endpoint support") Cc: stable@kernel.org Reviewed-by: Guanglei Zhu Signed-off-by: Fang Xieyan Acked-by: Thinh Nguyen Link: https://patch.msgid.link/20261105034946.20566-1-fangxy@xiaopeng.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc2/gadget.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/usb/dwc2/gadget.c b/drivers/usb/dwc2/gadget.c index 36936a04502acc..adc3df0ca7dd2c 100644 --- a/drivers/usb/dwc2/gadget.c +++ b/drivers/usb/dwc2/gadget.c @@ -1582,7 +1582,7 @@ static struct dwc2_hsotg_ep *ep_from_windex(struct dwc2_hsotg *hsotg, if (windex >= 0x100) return NULL; - if (idx > hsotg->num_of_eps) + if (idx >= hsotg->num_of_eps) return NULL; return index_to_ep(hsotg, idx, dir); From b2fdb6d0bb146b84479262492cc94796b4d528a6 Mon Sep 17 00:00:00 2001 From: Marek Szyprowski Date: Thu, 1 Oct 2026 23:39:03 +0200 Subject: [PATCH 1252/2102] usb: dwc3: fix use of destroyed dwc->connect_mutex on gadget exit dwc3_gadget_exit() destroys dwc->connect_mutex before calling usb_del_gadget(), which unbinds the gadget driver and ends up in dwc3_gadget_pullup() taking that already destroyed mutex. With CONFIG_DEBUG_MUTEXES this triggers the following warning on reboot: DEBUG_LOCKS_WARN_ON(lock->magic != lock) WARNING: kernel/locking/mutex.c:625 at __mutex_lock+0x4bc/0xb88, CPU#1: systemd-shutdow/1 ... Call trace: __mutex_lock+0x4bc/0xb88 (P) mutex_lock_nested+0x24/0x30 dwc3_gadget_pullup+0x88/0x150 usb_gadget_disconnect_locked+0x44/0x1f0 gadget_unbind_driver+0x48/0x124 device_remove+0x4c/0x80 device_release_driver_internal+0x1e0/0x23c device_release_driver+0x18/0x24 bus_remove_device+0xe8/0x1a0 device_del+0x14c/0x414 usb_del_gadget+0x90/0xe8 dwc3_gadget_exit+0x40/0x9c dwc3_drd_exit+0xe4/0x14c dwc3_core_remove+0x140/0x17c dwc3_qcom_remove+0x38/0x120 platform_shutdown+0x24/0x34 device_shutdown+0x158/0x260 kernel_restart+0x44/0xa4 __do_sys_reboot+0x118/0x24c ... Fix this by initializing dwc->connect_mutex together with dwc->mutex in dwc3_core_probe(). Fixes: 1ff77cbefe5a ("usb: dwc3: gadget: fix IRQ storm on invalid event buffer count") Cc: stable Assisted-by: Claude Opus 5.5 Signed-off-by: Marek Szyprowski Acked-by: Thinh Nguyen Link: https://patch.msgid.link/20261001213905.3290308-1-m.szyprowski@samsung.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/core.c | 1 + drivers/usb/dwc3/gadget.c | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/usb/dwc3/core.c b/drivers/usb/dwc3/core.c index 372737f4750b10..f4aa6a01e50013 100644 --- a/drivers/usb/dwc3/core.c +++ b/drivers/usb/dwc3/core.c @@ -2373,6 +2373,7 @@ int dwc3_core_probe(const struct dwc3_probe_data *data) } mutex_init(&dwc->mutex); + mutex_init(&dwc->connect_mutex); pm_runtime_get_noresume(dev); pm_runtime_set_active(dev); diff --git a/drivers/usb/dwc3/gadget.c b/drivers/usb/dwc3/gadget.c index a76f669a796c2e..c7d82a2550f525 100644 --- a/drivers/usb/dwc3/gadget.c +++ b/drivers/usb/dwc3/gadget.c @@ -4929,7 +4929,6 @@ int dwc3_gadget_init(struct dwc3 *dwc) init_completion(&dwc->ep0_in_setup); INIT_WORK(&dwc->err_recovery_work, dwc3_err_recovery_work); - mutex_init(&dwc->connect_mutex); dwc->gadget = kzalloc_obj(struct usb_gadget); if (!dwc->gadget) { ret = -ENOMEM; @@ -5027,7 +5026,6 @@ void dwc3_gadget_exit(struct dwc3 *dwc) return; cancel_work_sync(&dwc->err_recovery_work); - mutex_destroy(&dwc->connect_mutex); dwc3_enable_susphy(dwc, true); usb_del_gadget(dwc->gadget); dwc3_gadget_free_endpoints(dwc); From fb5289b697c965581104bafdd875b969a1db3e79 Mon Sep 17 00:00:00 2001 From: Ding Feng Date: Thu, 19 Nov 2026 11:10:26 +0800 Subject: [PATCH 1253/2102] zonefs: ignore RLIMIT_FSIZE above LLONG_MAX in zonefs_write_check_limits() zonefs_write_check_limits() follows generic_write_check_limits() and has the same problem: it stores rlimit(RLIMIT_FSIZE), an unsigned long, in a loff_t, so a soft limit between 2^63 and RLIM_INFINITY is negative and every write fails with -EFBIG and raises SIGXFSZ. Keep the limit unsigned and apply it only when it is at most LLONG_MAX, as the generic helper now does. Fixes: ebfd68cd0c1e ("zonefs: Fix O_APPEND async write handling") Cc: stable@vger.kernel.org Assisted-by: Claude:claude-opus-5-5 Frama-C Signed-off-by: Ding Feng Signed-off-by: Damien Le Moal --- fs/zonefs/file.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/fs/zonefs/file.c b/fs/zonefs/file.c index 319d9502ba5654..c9293e35d690c0 100644 --- a/fs/zonefs/file.c +++ b/fs/zonefs/file.c @@ -399,15 +399,16 @@ static loff_t zonefs_write_check_limits(struct file *file, loff_t pos, { struct inode *inode = file_inode(file); struct zonefs_zone *z = zonefs_inode_zone(inode); - loff_t limit = rlimit(RLIMIT_FSIZE); + u64 limit = rlimit(RLIMIT_FSIZE); loff_t max_size = z->z_capacity; - if (limit != RLIM_INFINITY) { - if (pos >= limit) { + /* No file position reaches a limit above LLONG_MAX. */ + if (limit != RLIM_INFINITY && limit <= LLONG_MAX) { + if (pos >= (loff_t)limit) { send_sig(SIGXFSZ, current, 0); return -EFBIG; } - count = min(count, limit - pos); + count = min(count, (loff_t)limit - pos); } if (!(file->f_flags & O_LARGEFILE)) From 39fbb9ba8831ca5af2792af50d9d9a02dbe710a3 Mon Sep 17 00:00:00 2001 From: Alexey Charkov Date: Tue, 17 Nov 2026 16:48:07 +0400 Subject: [PATCH 1254/2102] usb: gadget: udc: Clear a pending connection when starting the UDC Since commit 62911bc82b03 ("usb: gadget: udc: skip pullup() if already connected"), usb_gadget_connect_locked() returns early when gadget->connected is set. A connection requested while the UDC is stopped sets that flag too, without enabling the pullup. A later gadget_bind_driver() or soft_connect "connect" then finds it set and never enables the pullup, so the host doesn't see the gadget until it is unbound and bound again. This happens whenever a UDC driver reports VBUS through usb_udc_vbus_handler() while no gadget driver is bound, e.g. when a Type-C port controller switches the controller to the device role at boot, seconds before userspace binds a configfs gadget. The pullup is never enabled while the UDC is stopped, so clear gadget->connected once it starts. The bind connects according to the VBUS state that the core tracks anyway, and a function that deactivates the gadget during bind still has the connection recorded for usb_gadget_activate(). Fixes: 62911bc82b03 ("usb: gadget: udc: skip pullup() if already connected") Cc: stable@kernel.org Acked-by: Alan Stern Signed-off-by: Alexey Charkov Link: https://patch.msgid.link/20261117-udc-connect-v3-1-9413b491d213@flipper.net Signed-off-by: Greg Kroah-Hartman --- drivers/usb/gadget/udc/core.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/drivers/usb/gadget/udc/core.c b/drivers/usb/gadget/udc/core.c index d5844384c36805..577bc15f61a15b 100644 --- a/drivers/usb/gadget/udc/core.c +++ b/drivers/usb/gadget/udc/core.c @@ -1236,8 +1236,16 @@ static inline int usb_gadget_udc_start_locked(struct usb_udc *udc) } ret = udc->gadget->ops->udc_start(udc->gadget, udc->driver); - if (!ret) + if (!ret) { udc->started = true; + /* + * The pullup is never enabled while the UDC is stopped, so any + * connection recorded meanwhile was only a request. Forget it, + * so that the next usb_gadget_connect_locked() enables the + * pullup rather than returning early. + */ + udc->gadget->connected = false; + } return ret; } From a3fee4e3cebe7094864b0c9d0a6176fc7941ff45 Mon Sep 17 00:00:00 2001 From: David Collin Date: Sat, 5 Sep 2026 12:44:47 -0400 Subject: [PATCH 1255/2102] usb: dwc3: host: fix dangling xhci pointer on init failure dwc3_host_init()'s error path frees xhci via platform_device_put() but never clears dwc->xhci, leaving a dangling pointer that dwc3_host_exit() dereferences unconditionally on removal/shutdown. Clear dwc->xhci on the error path and return early from dwc3_host_exit() if NULL. Fixes: d07e8819a03d ("usb: dwc3: add xHCI Host support") Cc: stable@kernel.org Signed-off-by: David Collin Acked-by: Thinh Nguyen Link: https://patch.msgid.link/20260905164448.209348-1-davidcollin899@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/host.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/usb/dwc3/host.c b/drivers/usb/dwc3/host.c index c5674161b2b08e..74117cbb2f42fc 100644 --- a/drivers/usb/dwc3/host.c +++ b/drivers/usb/dwc3/host.c @@ -219,12 +219,16 @@ int dwc3_host_init(struct dwc3 *dwc) return 0; err: platform_device_put(xhci); + dwc->xhci = NULL; return ret; } EXPORT_SYMBOL_GPL(dwc3_host_init); void dwc3_host_exit(struct dwc3 *dwc) { + if (!dwc->xhci) + return; + if (dwc->sys_wakeup) device_init_wakeup(&dwc->xhci->dev, false); From 81cd3d5170197e618526927d23619ae6ca22a2ae Mon Sep 17 00:00:00 2001 From: David Collin Date: Sat, 5 Sep 2026 12:44:48 -0400 Subject: [PATCH 1256/2102] usb: dwc3: host: fix props[] overflow when all quirks are enabled props[] is sized for exactly the number of properties dwc3_host_init() can populate, leaving no slot for the NULL terminator property_entries_dup() requires when usb3_lpm_capable, usb2_lpm_disable, and the <=3.00a PED quirk are all true. Size props[] for one more slot. Fixes: 8da7644493b4 ("usb: dwc3: Specify maximum number of XHCI interrupters") Cc: stable@kernel.org Signed-off-by: David Collin Acked-by: Thinh Nguyen Link: https://patch.msgid.link/20260905164448.209348-2-davidcollin899@gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/host.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/usb/dwc3/host.c b/drivers/usb/dwc3/host.c index 74117cbb2f42fc..cd1e5204ac3a9b 100644 --- a/drivers/usb/dwc3/host.c +++ b/drivers/usb/dwc3/host.c @@ -130,7 +130,7 @@ static int dwc3_host_get_irq(struct dwc3 *dwc) int dwc3_host_init(struct dwc3 *dwc) { - struct property_entry props[6]; + struct property_entry props[7]; struct platform_device *xhci; int ret, irq; int prop_idx = 0; From 09ee6ce0a9496b39cb8682101912e8f9291df61d Mon Sep 17 00:00:00 2001 From: Jaewon Jung Date: Thu, 5 Nov 2026 08:19:26 +0900 Subject: [PATCH 1257/2102] tracing: Keep copying markers when one instance is stopped When several instances enable copy_trace_marker, stopping one instance can prevent the remaining buffers from receiving markers. Continue copying text and raw markers even if one copy fails. Return the largest successful write length, or -ENODEV if no write succeeds. Link: https://patch.msgid.link/20261104232046.32519-1-jaewon8868@gmail.com Fixes: 7b382efd5e8a ("tracing: Allow the top level trace_marker to write into another instances") Signed-off-by: Jaewon Jung Signed-off-by: Steven Rostedt --- kernel/trace/trace.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c index 4ccdefb5c3efe5..527b16690acb9d 100644 --- a/kernel/trace/trace.c +++ b/kernel/trace/trace.c @@ -6345,9 +6345,10 @@ tracing_mark_write(struct file *filp, const char __user *ubuf, if (tr == &global_trace) { guard(rcu)(); list_for_each_entry_rcu(tr, &marker_copies, marker_list) { - written = write_marker_to_buffer(tr, buf, cnt, ip); - if (written < 0) - break; + ssize_t w = write_marker_to_buffer(tr, buf, cnt, ip); + + if (w >= 0 && w > written) + written = w; } } else { written = write_marker_to_buffer(tr, buf, cnt, ip); @@ -6424,9 +6425,10 @@ tracing_mark_raw_write(struct file *filp, const char __user *ubuf, if (tr == &global_trace) { guard(rcu)(); list_for_each_entry_rcu(tr, &marker_copies, marker_list) { - written = write_raw_marker_to_buffer(tr, buf, cnt); - if (written < 0) - break; + ssize_t w = write_raw_marker_to_buffer(tr, buf, cnt); + + if (w >= 0 && w > written) + written = w; } } else { written = write_raw_marker_to_buffer(tr, buf, cnt); From 9eb7e9068b26120b201e4b10237a5bbe5b95d855 Mon Sep 17 00:00:00 2001 From: Kyle Zeng Date: Tue, 6 Oct 2026 15:40:05 -0700 Subject: [PATCH 1258/2102] tracing: Restrict perf filters that read kernel strings A task-bound, counting-only syscall tracepoint can be opened without permission to read raw kernel tracepoint data. Setting exclude_kernel does not prevent its filter from running: perf_syscall_enter() submits the saved user-mode registers. Pointer-string filters use FILTER_PRED_FN_PCHAR by default, which reads through strncpy_from_kernel_nofault(). For sys_enter_openat, for example, the filename field comes directly from a syscall argument. An unprivileged caller can pass a kernel address, install a filter such as 'filename ~ "Linux version*"', and use the event count to test the contents of kernel memory, even with perf_event_paranoid=2. Check the compiled filter before installing it and require the same kernel and raw-tracepoint permissions as access to raw kernel tracepoint data for FILTER_PRED_FN_PCHAR. Inspect every predicate so that other events, operators, and boolean expressions cannot bypass the check. Return the permission error through the existing cleanup path before publishing the filter. Keep user-pointer (.ustring) and record-local predicates available under the existing policy. This leaves tracefs filtering and authorized kernel string filtering unchanged. Link: https://patch.msgid.link/20261006224005.49636-1-kylebot@openai.com Fixes: 5967bd5c4239 ("tracing: Let filter_assign_type() detect FILTER_PTR_STRING") Assisted-by: Codex:gpt-6-astra Signed-off-by: Kyle Zeng Reviewed-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- kernel/trace/trace_events_filter.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c index c10951bcfc5f14..cd0da148414ddd 100644 --- a/kernel/trace/trace_events_filter.c +++ b/kernel/trace/trace_events_filter.c @@ -2749,6 +2749,28 @@ static int ftrace_function_set_filter(struct perf_event *event, } #endif /* CONFIG_FUNCTION_TRACER */ +static int ftrace_profile_filter_perm(struct event_filter *filter) +{ + struct prog_entry *prog = rcu_dereference_protected(filter->prog, + lockdep_is_held(&event_mutex)); + int i, err; + + for (i = 0; prog[i].pred; i++) { + if (prog[i].pred->fn_num != FILTER_PRED_FN_PCHAR) + continue; + + /* + * Even a counting filter can reveal kernel string data. + * Require the same access as raw kernel tracepoints. + */ + err = perf_allow_kernel(); + if (err) + return err; + return perf_allow_tracepoint(); + } + return 0; +} + int ftrace_profile_set_filter(struct perf_event *event, int event_id, char *filter_str) { @@ -2770,6 +2792,10 @@ int ftrace_profile_set_filter(struct perf_event *event, int event_id, if (err) goto free_filter; + err = ftrace_profile_filter_perm(filter); + if (err) + goto free_filter; + if (ftrace_event_is_function(call)) err = ftrace_function_set_filter(event, filter); else From 97adb02064c6e3f378523b35563848cedbc23ec7 Mon Sep 17 00:00:00 2001 From: Kyle Zeng Date: Tue, 6 Oct 2026 15:56:42 -0700 Subject: [PATCH 1259/2102] tracing/filters: Treat zero-length dynamic strings as empty The regex callbacks use a length of zero for NUL-terminated strings of unknown size, such as the trailing buffer in a trace_marker record. However, filter_pred_strloc() and filter_pred_strrelloc() pass the length from a data locator directly to those callbacks. A zero-length locator has no data and need not point at a NUL byte. In particular, syscall entry events can contain an empty captured array or a failed user-string copy. Matching such a field with an equality, prefix, or substring filter can read beyond the record. The per-CPU perf trace buffer is reused, so an unprivileged counting syscall event can disclose bytes left by a previous kernel tracepoint even when raw sampling is denied and exclude_kernel prevents counting that tracepoint. Handle both locator formats through a common helper. For a zero-length field, pass an empty string and its actual size to the regex callback. This gives all matching modes the empty-string semantics without reading the locator's target. Keep nonzero fields and the legacy trace_marker unknown-length convention unchanged. Fixes: 10f20e9f9da9 ("tracing: Have zero size length in filter logic be full string") Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261006225642.58778-1-kylebot@openai.com Assisted-by: Codex:gpt-6-astra Signed-off-by: Kyle Zeng Reviewed-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- kernel/trace/trace_events_filter.c | 38 +++++++++++++++++++----------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c index cd0da148414ddd..62444db0f78bd7 100644 --- a/kernel/trace/trace_events_filter.c +++ b/kernel/trace/trace_events_filter.c @@ -891,6 +891,25 @@ static int filter_pred_pchar_user(struct filter_pred *pred, void *event) return filter_pchar(pred, str); } +static __always_inline int filter_dyn_string(struct filter_pred *pred, + char *str, int len) +{ + int cmp; + + /* + * The regex callbacks use zero for an unknown-length, NUL-terminated + * string. A zero-length data_loc or rel_loc field has no bytes at all. + * Match an empty string instead of reading past the end of the field. + */ + if (!len) { + str = ""; + len = 1; + } + + cmp = pred->regex->match(str, pred->regex, len); + return cmp ^ pred->not; +} + /* * Filter predicate for dynamic sized arrays of characters. * These are implemented through a list of strings at the end @@ -907,13 +926,8 @@ static int filter_pred_strloc(struct filter_pred *pred, void *event) int str_loc = str_item & 0xffff; int str_len = str_item >> 16; char *addr = (char *)(event + str_loc); - int cmp, match; - - cmp = pred->regex->match(addr, pred->regex, str_len); - match = cmp ^ pred->not; - - return match; + return filter_dyn_string(pred, addr, str_len); } /* @@ -930,13 +944,8 @@ static int filter_pred_strrelloc(struct filter_pred *pred, void *event) int str_loc = str_item & 0xffff; int str_len = str_item >> 16; char *addr = (char *)(&item[1]) + str_loc; - int cmp, match; - - cmp = pred->regex->match(addr, pred->regex, str_len); - match = cmp ^ pred->not; - - return match; + return filter_dyn_string(pred, addr, str_len); } /* Filter predicate for CPUs. */ @@ -1037,7 +1046,8 @@ static int filter_pred_within(struct filter_pred *pred, void *event) * * @str: the string to be searched * @r: the regex structure containing the pattern string - * @len: the length of the string to be searched (including '\0') + * @len: the length of the string to be searched (including '\0'), or zero + * for a NUL-terminated string of unknown length * * Note: * - @str might not be NULL-terminated if it's of type DYN_STRING @@ -1046,7 +1056,7 @@ static int filter_pred_within(struct filter_pred *pred, void *event) static int regex_match_full(char *str, struct regex *r, int len) { - /* len of zero means str is dynamic and ends with '\0' */ + /* Zero is reserved for a NUL-terminated string of unknown length. */ if (!len) return strcmp(str, r->pattern) == 0; From 3432b3d1f51770e57558944d8321121c66d5ada2 Mon Sep 17 00:00:00 2001 From: David Carlier Date: Thu, 22 Oct 2026 21:42:18 +0100 Subject: [PATCH 1260/2102] tracing: Define common event fields before enabling boot events event_trace_enable() parses trace_event= filters before event_trace_init_fields() has defined the common and generic fields, so a filter on common_pid or comm fails and the event stays off until event_trace_enable_again(). Link: https://patch.msgid.link/20261022204218.1222647-1-devnexen@gmail.com Fixes: 084100a1b579 ("tracing: Parse filter from boot event string") Signed-off-by: David Carlier Signed-off-by: Steven Rostedt --- kernel/trace/trace_events.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kernel/trace/trace_events.c b/kernel/trace/trace_events.c index 49d135bc2fbfcc..c9d31c9f3fcad5 100644 --- a/kernel/trace/trace_events.c +++ b/kernel/trace/trace_events.c @@ -5026,8 +5026,8 @@ void __init trace_event_init(void) { event_trace_memsetup(); init_ftrace_syscalls(); - event_trace_enable(); event_trace_init_fields(); + event_trace_enable(); } #ifdef CONFIG_EVENT_TRACE_STARTUP_TEST From 2b3bed9617bb71c9b1893d9f54ef8df59a239224 Mon Sep 17 00:00:00 2001 From: David Carlier Date: Thu, 22 Oct 2026 21:53:16 +0100 Subject: [PATCH 1261/2102] tracing: Drop the synthetic event ref when clearing hist triggers clear_event_triggers() frees a hist trigger on a synthetic event without dropping the se->ref taken by event_hist_trigger_parse(). Removing an instance with such a trigger leaves the synthetic event busy forever. Cc: stable@vger.kernel.org Fixes: 4b147936fa50 ("tracing: Add support for 'synthetic' events") Link: https://patch.msgid.link/20261022205405.1228742-1-devnexen@gmail.com Signed-off-by: David Carlier Signed-off-by: Steven Rostedt --- kernel/trace/trace.h | 2 ++ kernel/trace/trace_events_hist.c | 20 +++++++++++++------- kernel/trace/trace_events_trigger.c | 2 ++ 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/kernel/trace/trace.h b/kernel/trace/trace.h index 0635503a31dd75..6b695a7f42c874 100644 --- a/kernel/trace/trace.h +++ b/kernel/trace/trace.h @@ -1912,9 +1912,11 @@ extern const struct file_operations event_inject_fops; #ifdef CONFIG_HIST_TRIGGERS extern int register_trigger_hist_cmd(void); extern int register_trigger_hist_enable_disable_cmds(void); +extern void hist_put_synth_event(struct trace_event_file *file); #else static inline int register_trigger_hist_cmd(void) { return 0; } static inline int register_trigger_hist_enable_disable_cmds(void) { return 0; } +static inline void hist_put_synth_event(struct trace_event_file *file) { } #endif extern int register_trigger_cmds(void); diff --git a/kernel/trace/trace_events_hist.c b/kernel/trace/trace_events_hist.c index 1aae7d7c6dc54e..a87d626e40e885 100644 --- a/kernel/trace/trace_events_hist.c +++ b/kernel/trace/trace_events_hist.c @@ -6761,6 +6761,17 @@ static bool hist_trigger_check_refs(struct event_trigger_data *data, return false; } +void hist_put_synth_event(struct trace_event_file *file) +{ + struct synth_event *se; + + lockdep_assert_held(&event_mutex); + + se = find_synth_event_call(file->event_call); + if (se) + se->ref--; +} + static void hist_unregister_trigger(char *glob, struct event_trigger_data *data, struct trace_event_file *file) @@ -6816,7 +6827,6 @@ static void hist_unreg_all(struct trace_event_file *file) { struct event_trigger_data *test, *n; struct hist_trigger_data *hist_data; - struct synth_event *se; lockdep_assert_held(&event_mutex); @@ -6829,9 +6839,7 @@ static void hist_unreg_all(struct trace_event_file *file) list_del_rcu(&test->list); trace_event_trigger_enable_disable(file, 0); - se = find_synth_event_call(file->event_call); - if (se) - se->ref--; + hist_put_synth_event(file); update_cond_flag(file); if (hist_data->enable_timestamps) @@ -6946,9 +6954,7 @@ static int event_hist_trigger_parse(struct event_command *cmd_ops, } event_trigger_unregister(cmd_ops, file, glob+1, trigger_data); - se = find_synth_event_call(file->event_call); - if (se) - se->ref--; + hist_put_synth_event(file); ret = 0; goto out_free; } diff --git a/kernel/trace/trace_events_trigger.c b/kernel/trace/trace_events_trigger.c index 4d2fde996c0f6c..a2487ad7fef85a 100644 --- a/kernel/trace/trace_events_trigger.c +++ b/kernel/trace/trace_events_trigger.c @@ -643,6 +643,8 @@ clear_event_triggers(struct trace_array *tr) list_for_each_entry_safe(data, n, &file->triggers, list) { trace_event_trigger_enable_disable(file, 0); list_del_rcu(&data->list); + if (data->cmd_ops->trigger_type == ETT_EVENT_HIST) + hist_put_synth_event(file); if (data->cmd_ops->free) data->cmd_ops->free(data); } From cae7fb0d853eff05c70b08ef9e7ecb18867f8945 Mon Sep 17 00:00:00 2001 From: Jaewon Jung Date: Wed, 28 Oct 2026 16:44:54 +0900 Subject: [PATCH 1262/2102] tracing: Avoid undefined shifts for zero histogram map size Reject size=0 before calling roundup_pow_of_two(). include/linux/log2.h documents roundup_pow_of_two() as: - the result is undefined when n == 0 With CONFIG_UBSAN_SHIFT=y, a size=0 histogram trigger reports: UBSAN: shift-out-of-bounds in include/linux/log2.h shift exponent 64 is too large for 64-bit type 'long unsigned int' Tested on x86_64 QEMU: size=0 is rejected without UBSAN warnings, and the histogram modifier and parser tests pass. Fixes: 7ef224d1d0e3 ("tracing: Add 'hist' event trigger command") Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261028074610.2212374-1-jaewon8868@gmail.com Signed-off-by: Jaewon Jung Signed-off-by: Steven Rostedt --- kernel/trace/trace_events_hist.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/kernel/trace/trace_events_hist.c b/kernel/trace/trace_events_hist.c index a87d626e40e885..d4702ad4e0036a 100644 --- a/kernel/trace/trace_events_hist.c +++ b/kernel/trace/trace_events_hist.c @@ -1430,6 +1430,11 @@ static int parse_map_size(char *str) if (ret) goto out; + if (!size) { + ret = -EINVAL; + goto out; + } + map_bits = ilog2(roundup_pow_of_two(size)); if (map_bits < TRACING_MAP_BITS_MIN || map_bits > TRACING_MAP_BITS_MAX) From b82178ad9e282e20c3f3636bde5c52143ed5b933 Mon Sep 17 00:00:00 2001 From: "Masami Hiramatsu (Google)" Date: Thu, 29 Oct 2026 10:37:35 +0900 Subject: [PATCH 1263/2102] tracing/filters: Fix MATCH_END_ONLY regex matching for fixed-size strings regex_match_end() calculates string length as "len - 1", assuming @len is the string length including trailing '\0'. For dynamic strings (filter_pred_strloc) and pointer strings (filter_pchar), this assumption holds and allows O(1) constant-time suffix matching. However, for fixed-size string fields (FILTER_STATIC_STRING) and "comm" (FILTER_COMM), the callers pass the buffer capacity rather than the actual string length (field->size for filter_pred_string, and TASK_COMM_LEN for filter_pred_comm). Because these buffers hold null-terminated strings (e.g. prev_comm in sched_switch holding "bash" in a 16-byte buffer), regex_match_end() tests against the tail of the buffer capacity (typically trailing '\0' padding at offset 13) rather than the actual string end. Consequently, suffix matching like comm ~ "*sh" or prev_comm ~ "*sh" fails for all strings shorter than the buffer capacity. Furthermore, for trace events like ftrace/print (trace_marker), the "buf" field is defined with size 0, denoting an unbounded NUL-terminated string. regex_match_end() and regex_match_end_str() return 0 when len is 0, causing suffix matching to fail on ftrace/print events as well. To fix this without penalizing dynamic and pointer strings with an unnecessary scan on every event: - Introduce regex_match_end_str() using strnlen(str, len) for fixed-size buffers (FILTER_COMM and FILTER_STATIC_STRING with field->size > 0). - Introduce regex_match_end_dynstr() using strlen(str) for unbounded strings (FILTER_STATIC_STRING with field->size == 0). Assign these match callbacks in parse_pred() when MATCH_END_ONLY is requested. Cc: stable@vger.kernel.org Fixes: a3291c14ecf0 ("tracing/filters: Fix MATCH_END_ONLY filter matching") Fixes: 10f20e9f9da9 ("tracing: Have zero size length in filter logic be full string") Link: https://patch.msgid.link/179323785497.740114.7643531772387726730.stgit@devnote2 Signed-off-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- kernel/trace/trace_events_filter.c | 32 ++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c index 62444db0f78bd7..d2069ef554d65f 100644 --- a/kernel/trace/trace_events_filter.c +++ b/kernel/trace/trace_events_filter.c @@ -1092,6 +1092,30 @@ static int regex_match_end(char *str, struct regex *r, int len) return 0; } +static int regex_match_end_str(char *str, struct regex *r, int len) +{ + int slen; + + if (len < r->len) + return 0; + + slen = strnlen(str, len); + if (slen >= r->len && + memcmp(str + slen - r->len, r->pattern, r->len) == 0) + return 1; + return 0; +} + +static int regex_match_end_dynstr(char *str, struct regex *r, int len) +{ + int slen = strlen(str); + + if (slen >= r->len && + memcmp(str + slen - r->len, r->pattern, r->len) == 0) + return 1; + return 0; +} + static int regex_match_glob(char *str, struct regex *r, int len) { return glob_match_len(r->pattern, str, len) ? 1 : 0; @@ -2031,10 +2055,18 @@ static int parse_pred(const char *str, void *data, if (field->filter_type == FILTER_COMM) { pred->fn_num = FILTER_PRED_FN_COMM; + if (pred->regex->match == regex_match_end) + pred->regex->match = regex_match_end_str; } else if (field->filter_type == FILTER_STATIC_STRING) { pred->fn_num = FILTER_PRED_FN_STRING; pred->regex->field_len = field->size; + if (pred->regex->match == regex_match_end) { + if (!field->size) + pred->regex->match = regex_match_end_dynstr; + else + pred->regex->match = regex_match_end_str; + } } else if (field->filter_type == FILTER_DYN_STRING) { pred->fn_num = FILTER_PRED_FN_STRLOC; From 87e0a196153e983a4d95903e7422b7d766cd37cf Mon Sep 17 00:00:00 2001 From: "Masami Hiramatsu (Google)" Date: Thu, 29 Oct 2026 10:37:53 +0900 Subject: [PATCH 1264/2102] tracing/filters: Handle out-of-range CPU for OP_NE in cpumask comparison In filter_pred_##size##_cpumask(), if the event's scalar CPU value is out of range (cpu >= nr_cpu_ids), it unconditionally returns 0. However, if the predicate operation is OP_NE (e.g., field != CPUS{0,1}), an out-of-range CPU cannot match any valid CPU in the user-provided cpumask and the condition is satisfied. Returning 0 produces a false negative. Return "pred->op == OP_NE" instead of 0 when cpu >= nr_cpu_ids. Cc: stable@vger.kernel.org Fixes: 3cbec9d7b93d ("tracing/filters: Enable filtering a scalar field by a cpumask") Link: https://patch.msgid.link/179323787340.740114.14434420599496956193.stgit@devnote2 Signed-off-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- kernel/trace/trace_events_filter.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c index d2069ef554d65f..1b960cfdc69daa 100644 --- a/kernel/trace/trace_events_filter.c +++ b/kernel/trace/trace_events_filter.c @@ -758,7 +758,7 @@ static int filter_pred_##size##_cpumask(struct filter_pred *pred, void *event) \ unsigned int cpu = *addr; \ \ if (cpu >= nr_cpu_ids) \ - return 0; \ + return pred->op == OP_NE; \ \ return do_filter_scalar_cpumask(pred->op, cpu, pred->mask); \ } From 42647658bdd8434a90c1b63391081396f36820ba Mon Sep 17 00:00:00 2001 From: "Masami Hiramatsu (Google)" Date: Thu, 29 Oct 2026 10:38:11 +0900 Subject: [PATCH 1265/2102] tracing/filters: Check for missing operand after operator in parse_pred() In parse_pred(), after matching the operator and skipping whitespace, the filter string may terminate (str[i] == '\0') if the operand is missing (e.g. "ip ==" or "common_pid =="). For function events, the loop 'for (i++; str[i]; i++)' unconditionally increments 'i' past the NUL terminator, causing an out-of-bounds read. For other event types, allocating a predicate only to fail later during value parsing is wasteful. Check if 'str[i]' is NUL immediately after skipping whitespace after the operator, and report FILT_ERR_INVALID_FILTER. Cc: stable@vger.kernel.org Fixes: 80765597bc58 ("tracing: Rewrite filter logic to be simpler and faster") Link: https://patch.msgid.link/179323789181.740114.16161070743864669086.stgit@devnote2 Signed-off-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- kernel/trace/trace_events_filter.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c index 1b960cfdc69daa..32fcc6215d2424 100644 --- a/kernel/trace/trace_events_filter.c +++ b/kernel/trace/trace_events_filter.c @@ -1766,6 +1766,11 @@ static int parse_pred(const char *str, void *data, while (isspace(str[i])) i++; + if (!str[i]) { + parse_error(pe, FILT_ERR_INVALID_FILTER, pos + i); + goto err_free; + } + s = i; pred = kzalloc_obj(*pred); From 5d4eeee1697e63cc0010cf34910a72c0f4776e42 Mon Sep 17 00:00:00 2001 From: "Masami Hiramatsu (Google)" Date: Thu, 29 Oct 2026 11:30:11 +0900 Subject: [PATCH 1266/2102] tracing/filters: Fix false success return in process_system_preds() In process_system_preds(), "fail" was initialized to true to indicate whether any event in the subsystem successfully applied the filter. However, "fail = false;" was placed at the end of the event loop outside the error check, unconditionally clearing "fail" on every iteration even when process_preds() returned an error. As a result, if every event in the subsystem fails to match the filter (e.g., an invalid field), process_system_preds() returns 0 (success) instead of -EINVAL. Consequently, create_system_filter() considers the operation successful and silently resets the subsystem filter display to the default global filter message instead of reporting the parse error. Fix this by clearing "fail" only when at least one event filter succeeds. Consolidate the cleanup logic in fail and fail_mem by using ret initialized to -ENOMEM, setting ret to -EINVAL in fail, and falling through to fail_mem, freeing any replaced filters via delay_free_filter() if !list_empty(&filter_list->list). Cc: stable@vger.kernel.org Fixes: 80765597bc58 ("tracing: Rewrite filter logic to be simpler and faster") Link: https://patch.msgid.link/179324101176.752804.17624386967710135045.stgit@devnote2 Suggested-by: Steven Rostedt Signed-off-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- kernel/trace/trace_events_filter.c | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c index 32fcc6215d2424..a1c298210059ab 100644 --- a/kernel/trace/trace_events_filter.c +++ b/kernel/trace/trace_events_filter.c @@ -2352,6 +2352,7 @@ static int process_system_preds(struct trace_subsystem_dir *dir, struct event_filter *filter = NULL; struct filter_head *filter_list; bool fail = true; + int ret = -ENOMEM; int err; filter_list = kmalloc_obj(*filter_list); @@ -2378,9 +2379,10 @@ static int process_system_preds(struct trace_subsystem_dir *dir, filter_disable(file); parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0); append_filter_err(tr, pe, filter); - } else + } else { event_set_filtered_flag(file); - + fail = false; + } filter_item = kzalloc_obj(*filter_item); if (!filter_item) @@ -2394,8 +2396,6 @@ static int process_system_preds(struct trace_subsystem_dir *dir, filter_item->filter = event_filter(file); event_set_filter(file, filter); filter = NULL; - - fail = false; } if (fail) @@ -2410,19 +2410,18 @@ static int process_system_preds(struct trace_subsystem_dir *dir, return 0; fail: /* No call succeeded */ - free_filter_list(filter_list); parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0); - return -EINVAL; + ret = -EINVAL; fail_mem: __free_filter(filter); - /* If any call succeeded, we still need to sync */ - if (!fail) + /* If any filter was replaced, we still need to sync */ + if (!list_empty(&filter_list->list)) delay_free_filter(filter_list); else free_filter_list(filter_list); - return -ENOMEM; + return ret; } static int create_filter_start(char *filter_string, bool set_str, From a20691808762d48ae38191cf856878e4c901b553 Mon Sep 17 00:00:00 2001 From: "Baek Kyu, Kim" Date: Fri, 30 Oct 2026 02:31:27 +0900 Subject: [PATCH 1267/2102] tracing: Free tracer resources on instance creation failure Creating a tracefs instance can allocate private tracer nodes, copied flags and option arrays before trace_array_create_dir() returns. If a later allocation fails, trace_array_create_systems() frees the trace_array without releasing those private allocations. The failed instance is never registered, so normal removal cannot reclaim them. Free the tracer nodes and option arrays when trace_array_create_dir() fails, then continue through the existing trace_array cleanup. Share the option array cleanup with normal instance removal. Earlier failures still use out_free_tr because the tracer list is not yet initialized there. Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261029173127.387835-1-pocj8ur4in@gmail.com Fixes: 428add559b69 ("tracing: Have tracer option be instance specific") Signed-off-by: Baek Kyu, Kim Signed-off-by: Steven Rostedt --- kernel/trace/trace.c | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c index 527b16690acb9d..b11ec4d3cfb8ae 100644 --- a/kernel/trace/trace.c +++ b/kernel/trace/trace.c @@ -1456,6 +1456,13 @@ static void free_tracers(struct trace_array *tr) } } +static void free_tracer_options(struct trace_array *tr) +{ + for (int i = 0; i < tr->nr_topts; i++) + kfree(tr->topts[i].topts); + kfree(tr->topts); +} + /** * register_tracer - register a tracer with the ftrace system. * @type: the plugin for the tracer @@ -8763,7 +8770,7 @@ trace_array_create_systems(const char *name, const char *systems, if (trace_instance_dir) { ret = trace_array_create_dir(tr); if (ret) - goto out_free_tr; + goto out_free_tracers; } else __trace_early_add_events(tr); @@ -8773,6 +8780,9 @@ trace_array_create_systems(const char *name, const char *systems, return tr; + out_free_tracers: + free_tracers(tr); + free_tracer_options(tr); out_free_tr: ftrace_free_ftrace_ops(tr); free_trace_buffers(tr); @@ -8926,10 +8936,7 @@ static int __remove_instance(struct trace_array *tr) if (tr->flags & TRACE_ARRAY_FL_VMALLOC) vfree((void *)tr->range_addr_start); - for (i = 0; i < tr->nr_topts; i++) { - kfree(tr->topts[i].topts); - } - kfree(tr->topts); + free_tracer_options(tr); free_cpumask_var(tr->pipe_cpumask); free_cpumask_var(tr->tracing_cpumask); From 700e5c063fd765fd09c1007ec8a927bddd82798b Mon Sep 17 00:00:00 2001 From: Vineet Gupta Date: Wed, 21 Oct 2026 10:44:05 -0700 Subject: [PATCH 1268/2102] fgraph: Allocate shadow stacks inline with GFP_NOWAIT When ftrace graphing is turned on, all tasks in the system missing return stack page are assigned one. This is done in a simplistic multi-sweep loop of FTRACE_RETSTACK_ALLOC_SIZE (currently 32) tasks at a time as follows: start_graph_tracing() do { alloc_retstack_tasklist } while (-EAGAIN); alloc_retstack_tasklist() alloc x32 # GFP_KERNEL, may sleep rcu_read_lock() # preempt off for_each_process_thread walk N_total, no cond_resched t->ret_stack = new_page rcu_read_unlock() # preempt enable but no explicit yield Each successive iteration of loop invokes for_each_process_thread() which doesn't support cursor based resume and always restarts from the init_task. Thus each successive loop needs to skip the tasks assigned ret_stack in prior sweeps and thus take longer and longer to find the candidate 32 tasks. And while the loop end calls rcu unlock, and re-enables preemption briefly, there is no explicit yield. The total number of iterations turn out to be N_total * N_null / (2 * FTRACE_RETSTACK_ALLOC_SIZE) where N_total is the number of threads on the system and N_null the number of those whose ret_stack is still NULL. After boot with no fgraph user that is every thread. This is not a tracing-only path. Since commit 4346ba160409 ("fprobe: Rewrite fprobe on function-graph tracer") fprobe is built on fgraph, so an ordinary kprobe_multi BPF attach that flips ftrace_graph_active from 0 to 1 pays the whole cost inside one bpf() syscall. Commit 2c67dc457bc6 ("tracing: fprobe: optimization for entry only case") narrows that to return and session probes but does not remove it. A host running hundreds of thousands of threads, with the current batch size of 32, turns the ftrace_graph_active 0 -> 1 transition into a multi-second, and eventually multi-minute, operation which showed up as RCU stall and softlockup_panic on heavily loaded Meta Fleet machines with preemption disabled. rcu: INFO: rcu_sched self-detected stall on CPU rcu: 0-....: (20718 ticks this GP) (t=21000 jiffies g=913 q=8 ncpus=8) CPU: 0 UID: 0 PID: 160141 Comm: bpftrace ___slab_alloc+0x549/0xa20 kmem_cache_alloc_noprof+0x16c/0x340 register_ftrace_graph+0x3d7/0x6c0 register_fprobe_ips+0x2d5/0x310 bpf_kprobe_multi_link_attach+0x218/0x7e0 __sys_bpf+0x267a/0x27a0 Fix this by allocating inline with GFP_NOWAIT instead of pre-allocating a fixed batch. GFP_NOWAIT does not sleep, so it is legal inside the RCU read-side critical section. A single sweep now serves every task, so the walk becomes O(N) rather than O(N_total * N_null), and the retry loop is no longer the normal path. The pre-allocated array remains as the fallback when GFP_NOWAIT fails. The runs below never needed it, so it was exercised with failslab injection: at a 100% failure rate every task falls back and -EAGAIN retries ~1560 times for 50000 threads, with no stall or splat. smp_store_release() is a drop-in replacement for the smp_wmb() and plain store it replaces. Measured on a 60-core Sapphire Rapids machine running a PREEMPT_LAZY kernel (CONFIG_PREEMPT_DYNAMIC=y, mode lazy), timing the write that drives the ftrace_graph_active 0 -> 1 transition. Threads are spawned while fgraph is inactive so every one of them has ret_stack == NULL, and the loop was instrumented to count sweeps: threads before after sweeps time sweeps time 100000 3126 15.3 s 1 0.019 s 200000 6253 59.1 s 1 0.047 s 400000 12503 227.8 s 1 0.092 s The sweep count is 1 throughout. Time now scales linearly with the thread count at roughly 230 ns per task, which is the allocation and initialisation of one shadow stack. Fixes: f201ae2356c7 ("tracing/function-return-tracer: store return stack into task_struct and allocate it dynamically") Suggested-by: Peter Zijlstra Signed-off-by: Vineet Gupta Tested-by: Vineet Gupta Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261021174406.2891598-2-vineet.gupta@linux.dev Acked-by: Andrii Nakryiko Acked-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- kernel/trace/fgraph.c | 39 ++++++++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/kernel/trace/fgraph.c b/kernel/trace/fgraph.c index 6d87143b3ddb5f..59c217b066954e 100644 --- a/kernel/trace/fgraph.c +++ b/kernel/trace/fgraph.c @@ -1033,13 +1033,16 @@ void ftrace_stub_graph(struct ftrace_graph_ret *trace, struct fgraph_ops *gops, trace_func_graph_ret_t ftrace_graph_return = ftrace_stub_graph; trace_func_graph_ent_t ftrace_graph_entry = ftrace_graph_entry_stub; -/* Try to assign a return stack array on FTRACE_RETSTACK_ALLOC_SIZE tasks. */ +/* + * Loop thru all the tasks in the system and assign ret_stack. + * The @ret_stack_list is a small pre-allocated fallback, in case + * the GFP_NOWAIT allocations here fail. + */ static int alloc_retstack_tasklist(unsigned long **ret_stack_list) { - int i; - int ret = 0; int start = 0, end = FTRACE_RETSTACK_ALLOC_SIZE; struct task_struct *g, *t; + int i, ret = 0; if (WARN_ON_ONCE(!fgraph_stack_cachep)) return -ENOMEM; @@ -1056,20 +1059,26 @@ static int alloc_retstack_tasklist(unsigned long **ret_stack_list) rcu_read_lock(); for_each_process_thread(g, t) { - if (start == end) { - ret = -EAGAIN; - goto unlock; - } + unsigned long *rs; - if (t->ret_stack == NULL) { - atomic_set(&t->trace_overrun, 0); - ret_stack_init_task_vars(ret_stack_list[start]); - t->curr_ret_stack = 0; - t->curr_ret_depth = -1; - /* Make sure the tasks see the 0 first: */ - smp_wmb(); - t->ret_stack = ret_stack_list[start++]; + if (t->ret_stack) + continue; + + rs = kmem_cache_alloc(fgraph_stack_cachep, GFP_NOWAIT); + if (!rs) { + if (start == end) { + ret = -EAGAIN; + goto unlock; + } + rs = ret_stack_list[start++]; } + + atomic_set(&t->trace_overrun, 0); + ret_stack_init_task_vars(rs); + t->curr_ret_stack = 0; + t->curr_ret_depth = -1; + /* Make sure the tasks see the 0 first: */ + smp_store_release(&t->ret_stack, rs); } unlock: From 7ea88e9d57e9b0241302e8e2f90b470a40651ffc Mon Sep 17 00:00:00 2001 From: Vineet Gupta Date: Wed, 21 Oct 2026 10:44:06 -0700 Subject: [PATCH 1269/2102] fgraph: Use scoped_guard() for the task list walk alloc_retstack_tasklist() open-codes rcu_read_lock() and unwinds it through an unlock label. Use scoped_guard(rcu) instead and let the compiler emit the unlock on every exit path. The -EAGAIN case now jumps straight to the free label rather than to unlock; leaving the guard's scope releases the RCU read lock on the way, so the unlock label has no remaining users and is removed. No functional change: objdump of fgraph.o shows identical call targets and counts, including the three __rcu_read_unlock() sites the compiler emits for the exits from the read-side section. A PROVE_RCU + DEBUG_ATOMIC_SLEEP build with the -EAGAIN path forced several thousand times is clean. Link: https://patch.msgid.link/20261021174406.2891598-3-vineet.gupta@linux.dev Suggested-by: Peter Zijlstra Signed-off-by: Vineet Gupta Tested-by: Vineet Gupta Acked-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- kernel/trace/fgraph.c | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/kernel/trace/fgraph.c b/kernel/trace/fgraph.c index 59c217b066954e..8a6709959b6289 100644 --- a/kernel/trace/fgraph.c +++ b/kernel/trace/fgraph.c @@ -1057,32 +1057,31 @@ static int alloc_retstack_tasklist(unsigned long **ret_stack_list) } } - rcu_read_lock(); - for_each_process_thread(g, t) { - unsigned long *rs; + scoped_guard (rcu) { + for_each_process_thread(g, t) { + unsigned long *rs; - if (t->ret_stack) - continue; + if (t->ret_stack) + continue; - rs = kmem_cache_alloc(fgraph_stack_cachep, GFP_NOWAIT); - if (!rs) { - if (start == end) { - ret = -EAGAIN; - goto unlock; + rs = kmem_cache_alloc(fgraph_stack_cachep, GFP_NOWAIT); + if (!rs) { + if (start == end) { + ret = -EAGAIN; + goto free; + } + rs = ret_stack_list[start++]; } - rs = ret_stack_list[start++]; - } - atomic_set(&t->trace_overrun, 0); - ret_stack_init_task_vars(rs); - t->curr_ret_stack = 0; - t->curr_ret_depth = -1; - /* Make sure the tasks see the 0 first: */ - smp_store_release(&t->ret_stack, rs); + atomic_set(&t->trace_overrun, 0); + ret_stack_init_task_vars(rs); + t->curr_ret_stack = 0; + t->curr_ret_depth = -1; + /* Make sure the tasks see the 0 first: */ + smp_store_release(&t->ret_stack, rs); + } } -unlock: - rcu_read_unlock(); free: for (i = start; i < end; i++) kmem_cache_free(fgraph_stack_cachep, ret_stack_list[i]); From d03e7f74c47198807091924e9bb9c009e7fe0912 Mon Sep 17 00:00:00 2001 From: Steven Rostedt Date: Tue, 17 Nov 2026 20:01:08 -0500 Subject: [PATCH 1270/2102] fgraph: Read the task->ret_stack with a smp_load_acquire() The setting of task->ret_stack was switched from a smp_wmb() and the update to the variable with a smp_store_release(). Match the reading of the task->ret_stack with a smp_load_acquire() to replace the read and smp_rmb(). Also update graph_init_task() to use smp_store_release(). Link: https://lore.kernel.org/all/20261021174406.2891598-2-vineet.gupta@linux.dev/ Link: https://patch.msgid.link/20261117200108.35179ae8@gandalf.local.home Signed-off-by: Steven Rostedt --- kernel/trace/fgraph.c | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/kernel/trace/fgraph.c b/kernel/trace/fgraph.c index 8a6709959b6289..1d900445d23aa9 100644 --- a/kernel/trace/fgraph.c +++ b/kernel/trace/fgraph.c @@ -568,7 +568,11 @@ ftrace_push_return_trace(unsigned long ret, unsigned long func, if (unlikely(ftrace_graph_is_dead())) return -EBUSY; - if (!current->ret_stack) + /* + * We must make sure the ret_stack is tested before we read + * anything else (See alloc_retstack_tasklist()). + */ + if (!smp_load_acquire(¤t->ret_stack)) return -EBUSY; BUILD_BUG_ON(SHADOW_STACK_SIZE % sizeof(long)); @@ -576,12 +580,6 @@ ftrace_push_return_trace(unsigned long ret, unsigned long func, /* Set val to "reserved" with the delta to the new fgraph frame */ val = (FGRAPH_TYPE_RESERVED << FGRAPH_TYPE_SHIFT) | FGRAPH_FRAME_OFFSET; - /* - * We must make sure the ret_stack is tested before we read - * anything else. - */ - smp_rmb(); - /* * Check if there's room on the shadow stack to fit a fraph frame * and a bitmap word. @@ -1125,8 +1123,7 @@ graph_init_task(struct task_struct *t, unsigned long *ret_stack) t->curr_ret_stack = 0; t->curr_ret_depth = -1; /* make curr_ret_stack visible before we add the ret_stack */ - smp_wmb(); - t->ret_stack = ret_stack; + smp_store_release(&t->ret_stack, ret_stack); } /* From 5f855410554564ca05903979e6dab96e754d8773 Mon Sep 17 00:00:00 2001 From: Chaosheng Qu Date: Wed, 14 Oct 2026 16:10:34 +0800 Subject: [PATCH 1271/2102] tracing/osnoise: Don't start a kthread in timerlat user-space mode In timerlat user-space mode (NO_OSNOISE_WORKLOAD) the workload is a user task reading timerlat_fd, so there is no per-CPU kernel thread to run. start_kthread() only checks for that in the osnoise branch: if (timerlat_enabled()) { snprintf(comm, 24, "timerlat/%d", cpu); main = timerlat_main; } else { /* if no workload, just return */ if (!test_bit(OSN_WORKLOAD, &osnoise_options)) { ... return 0; } ... } start_per_cpu_kthreads() guards against this mode itself, but osnoise_hotplug_workfn() calls start_kthread() directly. Bringing a CPU online in user-space mode therefore starts a timerlat/N thread and sets its bit in kthread_cpumask while OSN_WORKLOAD is clear. stop_kthread() uses that bit to decide what the recorded task is: if (cpumask_test_and_clear_cpu(cpu, &kthread_cpumask) && !WARN_ON(!test_bit(OSN_WORKLOAD, &osnoise_options))) { kthread_stop(kthread); } else if (!WARN_ON(test_bit(OSN_WORKLOAD, &osnoise_options))) { kill_pid(kthread->thread_pid, SIGKILL, 1); put_task_struct(kthread); } The bit is set but OSN_WORKLOAD is not, so the first WARN_ON() fires and the && short-circuits into the user-task branch. A running kernel thread is SIGKILLed and its task_struct is put without ever being stopped, so it keeps executing until it is freed underneath itself. Any write to osnoise/options reaches this: osnoise_options_write() stops the per-CPU threads before applying the new value, so stop_kthread() still sees OSN_WORKLOAD clear. Re-writing the value that is already set triggers it just as well as changing it. echo NO_OSNOISE_WORKLOAD > osnoise/options echo timerlat > current_tracer echo 0 > /sys/devices/system/cpu/cpu1/online echo 1 > /sys/devices/system/cpu/cpu1/online echo NO_OSNOISE_WORKLOAD > osnoise/options The offline/online pair is required, otherwise no kthread is recorded and no bit is set. Running this on 7.3-rc7 with KASAN gives a WARNING in stop_kthread() followed by a slab-use-after-free in update_se(); leaving out the hotplug step produces neither. Keep the check in start_kthread(), where the related hotplug bug was fixed in 0bb0a5c12ecf, instead of adding another copy to the callback. Cc: stable@vger.kernel.org Fixes: e88ed227f639 ("tracing/timerlat: Add user-space interface") Link: https://patch.msgid.link/20261014081034.12702-1-chaosheng.qu.linux@gmail.com Signed-off-by: Chaosheng Qu Signed-off-by: Steven Rostedt --- kernel/trace/trace_osnoise.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/kernel/trace/trace_osnoise.c b/kernel/trace/trace_osnoise.c index 995da9e0b548af..fbba422867474b 100644 --- a/kernel/trace/trace_osnoise.c +++ b/kernel/trace/trace_osnoise.c @@ -2039,6 +2039,14 @@ static int start_kthread(unsigned int cpu) return 0; if (timerlat_enabled()) { + /* + * In timerlat user-space mode the workload is the user task + * reading timerlat_fd, so there is no kernel thread to start. + * One started here would set its kthread_cpumask bit, which + * stop_kthread() reads as "osnoise workload kthread". + */ + if (!test_bit(OSN_WORKLOAD, &osnoise_options)) + return 0; snprintf(comm, 24, "timerlat/%d", cpu); main = timerlat_main; } else { From 0fbdc293697a5d72dc985e533eef5155a1b264cc Mon Sep 17 00:00:00 2001 From: David Carlier Date: Sat, 31 Oct 2026 21:24:35 +0000 Subject: [PATCH 1272/2102] tracing/user_events: Don't free an event that a dynamic event still references An eprobe takes a reference on the call of the event it attaches to, and kprobe, uprobe, fprobe and synth events all refuse to go away while trace_event_dyn_busy() says such a reference exists. user_events never checks it, so a user event can be freed under an eprobe: echo 'u:test u32 a' >> dynamic_events echo 'e:ep user_events/test a=$a' >> dynamic_events echo '-:user_events/test u32 a' >> dynamic_events echo '-:eprobes/ep' >> dynamic_events The last write drops the reference on the freed call. If the last fd of a non-persistent event closes while such a reference is held, the delayed destroy now fails. Mark the event persistent then, so it can still be deleted once the reference is gone instead of being leaked. Return -EBUSY from destroy_user_event() in that case. Fixes: 7f5a08c79df3 ("user_events: Add minimal support for trace_event into ftrace") Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261031212453.16116-1-devnexen@gmail.com Signed-off-by: David Carlier Signed-off-by: Steven Rostedt --- kernel/trace/trace_events_user.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/kernel/trace/trace_events_user.c b/kernel/trace/trace_events_user.c index f658c3a77aa7a1..ea6a20a30cf52b 100644 --- a/kernel/trace/trace_events_user.c +++ b/kernel/trace/trace_events_user.c @@ -256,6 +256,11 @@ static void delayed_destroy_user_event(struct work_struct *work) * attempt to delete it later. */ pr_warn("user_events: Unable to delete event\n"); + /* + * Keep it as persistent so it can be still deleted + * since nobody own this event + */ + user->reg_flags |= USER_EVENT_REG_PERSIST; refcount_set(&user->refcnt, 1); } out: @@ -1506,6 +1511,10 @@ static int destroy_user_event(struct user_event *user) lockdep_assert_held(&event_mutex); + /* If there is a reference to a dynamic event */ + if (trace_event_dyn_busy(&user->call)) + return -EBUSY; + /* * Detach the fields before removing the call. Removing the event * frees the field list memory (trace_destroy_fields() is run on From 2b237dc23a3957a6b8413cf31b686a3e5d871367 Mon Sep 17 00:00:00 2001 From: Pengfei Li Date: Sat, 7 Nov 2026 19:07:22 +0800 Subject: [PATCH 1273/2102] tracing: Wait for marker writers when copy_trace_marker is cleared Clearing copy_trace_marker removes the instance from marker_copies without waiting for trace_marker writers still walking the list. If the option is set again right away, a writer on that entry can revisit instances and write the same marker twice. Assisted-by: LLM Link: https://patch.msgid.link/20261107110722.1241413-1-lipengfei28@xiaomi.com Fixes: 7b382efd5e8a ("tracing: Allow the top level trace_marker to write into another instances") Signed-off-by: Pengfei Li Reviewed-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- kernel/trace/trace.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c index b11ec4d3cfb8ae..bffba5e27086a3 100644 --- a/kernel/trace/trace.c +++ b/kernel/trace/trace.c @@ -4035,7 +4035,9 @@ int set_tracer_flag(struct trace_array *tr, u64 mask, int enabled) break; case TRACE_ITER(COPY_MARKER): - update_marker_trace(tr, enabled); + /* Writers of the top level trace_marker may still be on this instance */ + if (update_marker_trace(tr, enabled) && !enabled) + synchronize_rcu(); /* update_marker_trace updates the tr->trace_flags */ return 0; } From c62206dfe9c80490de8cc2d211fb28eea4958240 Mon Sep 17 00:00:00 2001 From: Kyle Zeng Date: Mon, 9 Nov 2026 21:44:11 -0800 Subject: [PATCH 1274/2102] tracing: Validate user addresses in faultable buffer copies trace_user_fault_read() uses __copy_from_user() when no custom copy function is supplied. That primitive assumes the source address has already been validated, but the helper only checks the destination buffer size. A caller that passes an unchecked kernel address can therefore cause mapped kernel memory to be copied into the tracing buffer. The original syscall-array tracing implementation exposed this path to syscall arguments before the syscall validated them. Use copy_from_user() for the default copy as documented. Non-user addresses then fail the copy and follow the existing NULL-return path. Successful user copies, buffer bounds, and preemption and migration retry rules are unchanged. Cc: stable@vger.kernel.org Fixes: 64cf7d058a005 ("tracing: Have trace_marker use per-cpu data to read user space") Link: https://patch.msgid.link/20261110054411.75788-1-kylebot@openai.com Signed-off-by: Kyle Zeng Signed-off-by: Steven Rostedt --- kernel/trace/trace.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c index bffba5e27086a3..70b3c11ac16656 100644 --- a/kernel/trace/trace.c +++ b/kernel/trace/trace.c @@ -6298,7 +6298,7 @@ char *trace_user_fault_read(struct trace_user_buf_info *tinfo, if (copy_func) { ret = copy_func(buffer, ptr, size, data); } else { - ret = __copy_from_user(buffer, ptr, size); + ret = copy_from_user(buffer, ptr, size); } preempt_disable_notrace(); From 65f42f1fa03829e0ab1473369461a7aabf525cb2 Mon Sep 17 00:00:00 2001 From: Breno Leitao Date: Thu, 12 Nov 2026 07:18:42 -0800 Subject: [PATCH 1275/2102] fgraph: Do not mark index 0 in every shadow stack frame We are seeing this warning on an arm64 host: WARNING: kernel/trace/fprobe.c:676 at fprobe_return+0x260/0x2c8, CPU#16: FuncSched/3281330 Call trace: fprobe_return+0x260/0x2c8 (P) ftrace_return_to_handler+0x2bc/0x5a8 return_to_handler+0x20/0x48 futex_wait+0xa4/0x218 do_futex+0xb4/0x1d0 __arm64_sys_futex+0x15c/0x278 The theory is that function_graph_enter_regs() sets BIT(0) in the bitmap of every frame, a leftover of an old tail-call check, while the return path calls the retfunc of every set bit. A reproducer on linux-next supports the theory. On a fresh boot, with no other fgraph user yet: cd /sys/kernel/tracing echo 'f:fpexit vfs_read%return' >> dynamic_events echo 1 > events/fprobes/fpexit/enable # fprobe_graph_ops: index 0 echo vfs_write > set_ftrace_filter echo function_graph > current_tracer # function_graph: index 1 echo x > /dev/null # WARN on vfs_write return Removing the bit was agreed in the review of the series that added it [0], but the line stayed. Drop it now. [0] https://lore.kernel.org/all/20240527093436.7060d358a64cc2ea3213b07b@kernel.org/ Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261112-fgraph-bit0-v1-1-695ad14f4b1e@debian.org Fixes: 7aa1eaef9f42 ("function_graph: Allow multiple users to attach to function graph") Signed-off-by: Breno Leitao Signed-off-by: Steven Rostedt --- kernel/trace/fgraph.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/kernel/trace/fgraph.c b/kernel/trace/fgraph.c index 1d900445d23aa9..d1f79a85ed2e97 100644 --- a/kernel/trace/fgraph.c +++ b/kernel/trace/fgraph.c @@ -698,11 +698,7 @@ int function_graph_enter_regs(unsigned long ret, unsigned long func, if (!bitmap) goto out_ret; - /* - * Since this function uses fgraph_idx = 0 as a tail-call checking - * flag, set that bit always. - */ - set_bitmap(current, offset, bitmap | BIT(0)); + set_bitmap(current, offset, bitmap); ftrace_test_recursion_unlock(bit); return 0; out_ret: From 2a6d7231c79ecb0e6a1d4e6549302e0c47175d22 Mon Sep 17 00:00:00 2001 From: Vincent Donnefort Date: Fri, 13 Nov 2026 15:27:10 +0000 Subject: [PATCH 1276/2102] ring-buffer: Skip remote reader page swap when on tail When the reader page is also the tail, swap should not be permitted or it would insert the tail behind the head, breaking the integrity of the ring buffer. While __rb_get_reader_page() does correctly prevent this situation, the simple_ring_buffer implementation misses it. Once the reader catches up with the tail, make simple_ring_buffer_swap_reader_page() return 0. The remote reader now can expect an unchanged reader. When it is the case, there's nothing more to read. Also, when the simple_ring_buffer writer moves the tail to a new page, it resets the new tail counters and more specifically page::commit. As moving the tail unblocks page swap, order the page reset before the tail_page update. This ensures the reader can't swap the reader page with the new tail and observe a stale commit value. Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261113152729.837429-2-vdonnefort@google.com Fixes: 2e67fabd8b77 ("ring-buffer: Introduce ring-buffer remotes") Fixes: 34e5b958bdad ("tracing: Introduce simple_ring_buffer") Signed-off-by: Vincent Donnefort Signed-off-by: Steven Rostedt --- kernel/trace/ring_buffer.c | 3 ++- kernel/trace/simple_ring_buffer.c | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c index ed267d62882650..15ccb65de35b06 100644 --- a/kernel/trace/ring_buffer.c +++ b/kernel/trace/ring_buffer.c @@ -5848,7 +5848,8 @@ __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer) new_reader = cpu_buffer->subbuf_ids[cpu_buffer->meta_page->reader.id]; - WARN_ON_ONCE(prev_reader == new_reader); + if (prev_reader == new_reader) + return NULL; prev_head = new_reader; /* New reader was also the previous head */ new_head = prev_head; diff --git a/kernel/trace/simple_ring_buffer.c b/kernel/trace/simple_ring_buffer.c index abfaf9bee12e1f..d5c84af0192520 100644 --- a/kernel/trace/simple_ring_buffer.c +++ b/kernel/trace/simple_ring_buffer.c @@ -139,6 +139,13 @@ int simple_ring_buffer_swap_reader_page(struct simple_rb_per_cpu *cpu_buffer) reader = cpu_buffer->reader_page; + /* + * The reader is already the tail page. See simple_rb_move_tail() for + * memory ordering. + */ + if (reader == smp_load_acquire(&cpu_buffer->tail_page)) + return 0; + do { /* Run after the writer to find the head */ ret = simple_rb_find_head(cpu_buffer); @@ -196,7 +203,13 @@ static struct simple_buffer_page *simple_rb_move_tail(struct simple_rb_per_cpu * } simple_bpage_reset(new_tail); - cpu_buffer->tail_page = new_tail; + + /* + * Setting a new tail may unblock the swap in + * simple_ring_buffer_swap_reader_page(). Ensure the reader observes the + * page::commit reset. + */ + smp_store_release(&cpu_buffer->tail_page, new_tail); simple_rb_meta_inc(cpu_buffer->meta->pages_touched, 1); From 27d44f1c58092c56cf38adf831ca4cfe05b4a03c Mon Sep 17 00:00:00 2001 From: Vincent Donnefort Date: Fri, 13 Nov 2026 15:27:11 +0000 Subject: [PATCH 1277/2102] ring-buffer: Check remote reader page commit before meta entries __rb_get_reader_page_from_remote() bails out when rb_num_of_entries() is zero before verifying if there is more data committed on the current reader_page (rb_page_size()), while simple_ring_buffer updates page::commit before meta::entries. As a consequence, a race between the writer and reader could lead to __rb_get_reader_page_from_remote() returning NULL, while more data is available for reading on the ring buffer. CPU0 (writer) CPU1 (reader) ------------- ------------- local_set(&page->commit, write); __rb_get_reader_page_from_remote() !rb_read_remote_meta_page() return NULL; simple_rb_meta_inc(meta->entries, 1); This is an issue for rb_advance_reader() which always expects rb_get_reader_page() to return a page. Fix this issue by swapping the checks in __rb_get_reader_page_from_remote(): first it verifies if there is more to read in the current reader page, then it verifies if there's anything at all in the ring buffer. Also, if the reader observes the meta::entries update before page::commit while the writer moves tail_page, it could swap reader_page out and drop unread events. Order page::commit before meta::entries on the writer and rb_read_remote_meta_page() before rb_page_size() on the reader size. Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261113152729.837429-3-vdonnefort@google.com Fixes: 2e67fabd8b77 ("ring-buffer: Introduce ring-buffer remotes") Fixes: 34e5b958bdad ("tracing: Introduce simple_ring_buffer") Signed-off-by: Vincent Donnefort Signed-off-by: Steven Rostedt --- kernel/trace/ring_buffer.c | 19 +++++++++++++------ kernel/trace/simple_ring_buffer.c | 6 ++++++ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c index 15ccb65de35b06..f728ee82cf54b2 100644 --- a/kernel/trace/ring_buffer.c +++ b/kernel/trace/ring_buffer.c @@ -5615,14 +5615,12 @@ unsigned long ring_buffer_overruns(struct trace_buffer *buffer) } EXPORT_SYMBOL_GPL(ring_buffer_overruns); -static bool rb_read_remote_meta_page(struct ring_buffer_per_cpu *cpu_buffer) +static void rb_read_remote_meta_page(struct ring_buffer_per_cpu *cpu_buffer) { local_set(&cpu_buffer->entries, READ_ONCE(cpu_buffer->meta_page->entries)); local_set(&cpu_buffer->overrun, READ_ONCE(cpu_buffer->meta_page->overrun)); local_set(&cpu_buffer->pages_touched, READ_ONCE(cpu_buffer->meta_page->pages_touched)); local_set(&cpu_buffer->pages_lost, READ_ONCE(cpu_buffer->meta_page->pages_lost)); - - return rb_num_of_entries(cpu_buffer); } static void rb_update_remote_head(struct ring_buffer_per_cpu *cpu_buffer) @@ -5825,8 +5823,13 @@ __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer) { struct buffer_page *new_reader, *prev_reader, *prev_head, *new_head, *last; - if (!rb_read_remote_meta_page(cpu_buffer)) - return NULL; + rb_read_remote_meta_page(cpu_buffer); + + /* + * Order meta::entries read before page::commit, most likely paired with + * simple_ring_buffer_commit(). + */ + smp_rmb(); /* More to read on the reader page */ if (cpu_buffer->reader_page->read < rb_page_size(cpu_buffer->reader_page)) { @@ -5835,6 +5838,9 @@ __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer) return cpu_buffer->reader_page; } + if (!rb_num_of_entries(cpu_buffer)) + return NULL; + prev_reader = cpu_buffer->subbuf_ids[cpu_buffer->meta_page->reader.id]; if (cpu_buffer->remote->swap_reader_page(cpu_buffer->cpu, @@ -6909,7 +6915,8 @@ int ring_buffer_poll_remote(struct trace_buffer *buffer, int cpu) cpu_buffer = buffer->buffers[cpu]; guard(raw_spinlock)(&cpu_buffer->reader_lock); - if (rb_read_remote_meta_page(cpu_buffer)) + rb_read_remote_meta_page(cpu_buffer); + if (rb_num_of_entries(cpu_buffer)) rb_wakeups(buffer, cpu_buffer); return 0; diff --git a/kernel/trace/simple_ring_buffer.c b/kernel/trace/simple_ring_buffer.c index d5c84af0192520..5f14ba152fba6b 100644 --- a/kernel/trace/simple_ring_buffer.c +++ b/kernel/trace/simple_ring_buffer.c @@ -309,6 +309,12 @@ void simple_ring_buffer_commit(struct simple_rb_per_cpu *cpu_buffer) { local_set(&cpu_buffer->tail_page->page->commit, cpu_buffer->tail_page->write); + + /* + * Order page::commit before meta::entries. Paired with + * __rb_get_reader_page_from_remote(). + */ + smp_wmb(); simple_rb_meta_inc(cpu_buffer->meta->entries, 1); /* From d1a4551c99aa6a29c1c4e6466dfebaa4449ad0ed Mon Sep 17 00:00:00 2001 From: Vincent Donnefort Date: Fri, 13 Nov 2026 15:27:12 +0000 Subject: [PATCH 1278/2102] ring-buffer: Order remote page commit with data and timestamp __rb_get_reader_page_from_remote() uses page::commit to check if more data is available for consumption. However, it needs to make sure that data and page::time_stamp are not stale. Enforce page::commit order with page::data and page::time_stamp, and defer updating read_stamp on page swap until rb_page_size() confirms committed data is present. Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261113152729.837429-4-vdonnefort@google.com Fixes: 2e67fabd8b77 ("ring-buffer: Introduce ring-buffer remotes") Fixes: 34e5b958bdad ("tracing: Introduce simple_ring_buffer") Signed-off-by: Vincent Donnefort Signed-off-by: Steven Rostedt --- kernel/trace/ring_buffer.c | 23 ++++++++++++++++------- kernel/trace/simple_ring_buffer.c | 5 +++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c index f728ee82cf54b2..158c7c75688bd8 100644 --- a/kernel/trace/ring_buffer.c +++ b/kernel/trace/ring_buffer.c @@ -5832,11 +5832,8 @@ __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer) smp_rmb(); /* More to read on the reader page */ - if (cpu_buffer->reader_page->read < rb_page_size(cpu_buffer->reader_page)) { - if (!cpu_buffer->reader_page->read) - cpu_buffer->read_stamp = cpu_buffer->reader_page->page->time_stamp; - return cpu_buffer->reader_page; - } + if (cpu_buffer->reader_page->read < rb_page_size(cpu_buffer->reader_page)) + goto out; if (!rb_num_of_entries(cpu_buffer)) return NULL; @@ -5883,10 +5880,22 @@ __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer) cpu_buffer->reader_page = new_reader; cpu_buffer->reader_page->read = 0; cpu_buffer->pages = &new_head->list; - cpu_buffer->read_stamp = new_reader->page->time_stamp; cpu_buffer->lost_events = cpu_buffer->meta_page->reader.lost_events; - return rb_page_size(cpu_buffer->reader_page) ? cpu_buffer->reader_page : NULL; + if (!rb_page_size(cpu_buffer->reader_page)) + return NULL; + +out: + /* + * Order page::commit read before page::data and page::time_stamp, most + * likely paired with simple_ring_buffer_commit(). + */ + smp_rmb(); + + if (!cpu_buffer->reader_page->read) + cpu_buffer->read_stamp = cpu_buffer->reader_page->page->time_stamp; + + return cpu_buffer->reader_page; } static struct buffer_page * diff --git a/kernel/trace/simple_ring_buffer.c b/kernel/trace/simple_ring_buffer.c index 5f14ba152fba6b..2dddaef638dc64 100644 --- a/kernel/trace/simple_ring_buffer.c +++ b/kernel/trace/simple_ring_buffer.c @@ -307,6 +307,11 @@ EXPORT_SYMBOL_GPL(simple_ring_buffer_reserve); */ void simple_ring_buffer_commit(struct simple_rb_per_cpu *cpu_buffer) { + /* + * Order page::data and page::time_stamp before page::commit. Paired + * with __rb_get_reader_page_from_remote(). + */ + smp_wmb(); local_set(&cpu_buffer->tail_page->page->commit, cpu_buffer->tail_page->write); From 1382c57e40b3885614dba4bd53b65b21aec2e874 Mon Sep 17 00:00:00 2001 From: Vincent Donnefort Date: Fri, 13 Nov 2026 15:27:13 +0000 Subject: [PATCH 1279/2102] ring-buffer: Increment pages_read on remote ring buffer page swap __rb_get_reader_page_from_remote() swaps in a new reader page without incrementing cpu_buffer->pages_read. While this isn't an issue now as trace remotes do not use buffer_percent, add this missing increment for consistency. Link: https://patch.msgid.link/20261113152729.837429-5-vdonnefort@google.com Signed-off-by: Vincent Donnefort Signed-off-by: Steven Rostedt --- kernel/trace/ring_buffer.c | 1 + 1 file changed, 1 insertion(+) diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c index 158c7c75688bd8..0a1c7f98159ea4 100644 --- a/kernel/trace/ring_buffer.c +++ b/kernel/trace/ring_buffer.c @@ -5881,6 +5881,7 @@ __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer) cpu_buffer->reader_page->read = 0; cpu_buffer->pages = &new_head->list; cpu_buffer->lost_events = cpu_buffer->meta_page->reader.lost_events; + local_inc(&cpu_buffer->pages_read); if (!rb_page_size(cpu_buffer->reader_page)) return NULL; From 210bc23d47088f4962df85a807b05c5c8fc99215 Mon Sep 17 00:00:00 2001 From: Wenwu Hou Date: Mon, 16 Nov 2026 11:21:56 +0800 Subject: [PATCH 1280/2102] tracing/hwlat: Do the latency calculations in nanoseconds tr->max_latency is expected to hold nanoseconds: tracing_max_lat_read() converts it with nsecs_to_usecs() to print the usecs documented in hwlat_detector.rst, and the other latency tracers store nanoseconds there too. Do all the latency calculations in nanoseconds instead, and only convert the durations to microseconds when recording the hwlat event. This also makes the backward-clock error paths reachable. Previously, time_to_us() passed the delta through unsigned div_u64(), so a negative delta became a positive value after division. These error paths jumped to out without clearing trace_hwlat_callback_enabled. Fix this as well. Link: https://patch.msgid.link/20261116032156.3138060-1-hwenwur@gmail.com Fixes: e7c15cd8a1133 ("tracing: Added hardware latency tracer") Fixes: 7b2c86250122d ("tracing: Add NMI tracing in hwlat detector") Suggested-by: Steven Rostedt Signed-off-by: Wenwu Hou Signed-off-by: Steven Rostedt --- kernel/trace/trace_hwlat.c | 41 +++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/kernel/trace/trace_hwlat.c b/kernel/trace/trace_hwlat.c index 3fe274b84f1c2e..5be9031f1ffe30 100644 --- a/kernel/trace/trace_hwlat.c +++ b/kernel/trace/trace_hwlat.c @@ -203,14 +203,12 @@ static int get_sample(void) time_type start, t1, t2, last_t2; s64 diff, outer_diff, total, last_total = 0; u64 sample = 0; - u64 sample_width = READ_ONCE(hwlat_data.sample_width); + u64 sample_width = READ_ONCE(hwlat_data.sample_width) * NSEC_PER_USEC; u64 thresh = tracing_thresh; u64 outer_sample = 0; - int ret = -1; + int ret = 0; unsigned int count = 0; - do_div(thresh, NSEC_PER_USEC); /* modifies interval value */ - kdata->nmi_total_ts = 0; kdata->nmi_count = 0; /* Make sure NMIs see this first */ @@ -229,28 +227,37 @@ static int get_sample(void) if (time_u64(last_t2)) { /* Check the delta from outer loop (t2 to next t1) */ - outer_diff = time_to_us(time_sub(t1, last_t2)); + outer_diff = time_sub(t1, last_t2); /* This shouldn't happen */ if (outer_diff < 0) { hwlat_err(BANNER "time running backwards\n"); - goto out; + ret = -1; + break; } if (outer_diff > outer_sample) outer_sample = outer_diff; } last_t2 = t2; - total = time_to_us(time_sub(t2, start)); /* sample width */ + total = time_sub(t2, start); /* sample width */ /* Check for possible overflows */ if (total < last_total) { hwlat_err("Time total overflowed\n"); + /* Keep ret == 0 to preserve any latencies already detected */ break; } last_total = total; /* This checks the inner loop (t1 to t2) */ - diff = time_to_us(time_sub(t2, t1)); /* current diff */ + diff = time_sub(t2, t1); /* current diff */ + + /* This shouldn't happen: time went backwards between t1 and t2 */ + if (diff < 0) { + hwlat_err(BANNER "time running backwards\n"); + ret = -1; + break; + } if (diff > thresh || outer_diff > thresh) { if (!count) @@ -258,12 +265,6 @@ static int get_sample(void) count++; } - /* This shouldn't happen */ - if (diff < 0) { - hwlat_err(BANNER "time running backwards\n"); - goto out; - } - if (diff > sample) sample = diff; /* only want highest value */ @@ -273,10 +274,11 @@ static int get_sample(void) trace_hwlat_callback_enabled = false; barrier(); /* Make sure nmi_total_ts is no longer updated */ - ret = 0; + if (ret) + return ret; /* If we exceed the threshold value, we have found a hardware latency */ - if (sample > thresh || outer_sample > thresh) { + if (count) { u64 latency; ret = 1; @@ -286,8 +288,8 @@ static int get_sample(void) do_div(kdata->nmi_total_ts, NSEC_PER_USEC); s.seqnum = atomic64_inc_return(&hwlat_data.count); - s.duration = sample; - s.outer_duration = outer_sample; + s.duration = time_to_us(sample); + s.outer_duration = time_to_us(outer_sample); s.nmi_total_ts = kdata->nmi_total_ts; s.nmi_count = kdata->nmi_count; s.count = count; @@ -301,8 +303,6 @@ static int get_sample(void) latency_fsnotify(tr); } } - -out: return ret; } @@ -835,7 +835,6 @@ static int hwlat_tracer_init(struct trace_array *tr) tr->max_latency = 0; save_tracing_thresh = tracing_thresh; - /* tracing_thresh is in nsecs, we speak in usecs */ if (!tracing_thresh) tracing_thresh = last_tracing_thresh; From 4d0d961873409168e77c6bbc1453fcf8ade37788 Mon Sep 17 00:00:00 2001 From: Brian Norris Date: Mon, 16 Nov 2026 18:27:10 -0800 Subject: [PATCH 1281/2102] tracing: Properly match strings that start with numbers As an optimization, set_ftrace_filter supports writing indices (numbers) instead of function names. This support was added to the generic glob (fake regex) function, which breaks the ability to filter string patterns that start with a number. For example, PCI device names tend to look like '0001:01:00.0', and a reasonable filter might be: echo 'name ~ "0001:*"' > /sys/kernel/tracing/events/rpm/rpm_resume/filter Move the MATCH_INDEX code out to the only place it actually was intended to work -- ftrace match_records(), with a 'func' and no 'mod'. As a side effect, this also fixes :mod: function filtering for modules whose names start with a digit. Link: https://patch.msgid.link/20261116182710.1.Ic0625a2bd2e6f8960c0f75e5d15f14f3c84d1d38@changeid Fixes: f79b3f338564 ("ftrace: Allow enabling of filters via index of available_filter_functions") Signed-off-by: Brian Norris Signed-off-by: Steven Rostedt --- kernel/trace/ftrace.c | 3 ++- kernel/trace/trace.h | 1 - kernel/trace/trace_events_filter.c | 5 ----- 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/kernel/trace/ftrace.c b/kernel/trace/ftrace.c index c7d74b33d36de1..6654da9d1bbf96 100644 --- a/kernel/trace/ftrace.c +++ b/kernel/trace/ftrace.c @@ -5029,7 +5029,8 @@ match_records(struct ftrace_hash *hash, char *func, int len, char *mod) if (unlikely(ftrace_disabled)) return 0; - if (func_g.type == MATCH_INDEX) + if (func_g.type == MATCH_FULL && !mod && + func_g.search && isdigit(func_g.search[0])) return add_rec_by_index(hash, &func_g, clear_filter); do_for_each_ftrace_rec(pg, rec) { diff --git a/kernel/trace/trace.h b/kernel/trace/trace.h index 6b695a7f42c874..1fec567e789ea2 100644 --- a/kernel/trace/trace.h +++ b/kernel/trace/trace.h @@ -1807,7 +1807,6 @@ enum regex_type { MATCH_MIDDLE_ONLY, MATCH_END_ONLY, MATCH_GLOB, - MATCH_INDEX, }; struct regex { diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c index a1c298210059ab..6704ef3d9520c6 100644 --- a/kernel/trace/trace_events_filter.c +++ b/kernel/trace/trace_events_filter.c @@ -1152,9 +1152,6 @@ enum regex_type filter_parse_regex(char *buff, int len, char **search, int *not) *search = buff; - if (isdigit(buff[0])) - return MATCH_INDEX; - for (i = 0; i < len; i++) { if (buff[i] == '*') { if (!i) { @@ -1192,8 +1189,6 @@ static void filter_build_regex(struct filter_pred *pred) } switch (type) { - /* MATCH_INDEX should not happen, but if it does, match full */ - case MATCH_INDEX: case MATCH_FULL: r->match = regex_match_full; break; From a152600010847fec3829c9302e6bab0e2b8d53b2 Mon Sep 17 00:00:00 2001 From: Brian Norris Date: Mon, 16 Nov 2026 18:27:11 -0800 Subject: [PATCH 1282/2102] tracing: Add tests for globbing number-based strings In "tracing: Properly match strings that start with numbers", we fixed bugs related to string fields that start with a number and also use globs instead of full matches. Add some additional startup test cases for this. For easy reproducible testing, I abused the kunit.py script to boot a minimal kernel with FTRACE_STARTUP_TEST enabled: ./tools/testing/kunit/kunit.py run --arch=x86_64 \ --kconfig_add=CONFIG_FTRACE=y \ --kconfig_add=CONFIG_FUNCTION_TRACER=y \ --kconfig_add=CONFIG_DYNAMIC_FTRACE=y \ --kconfig_add=CONFIG_FTRACE_STARTUP_TEST=y \ --kconfig_add=CONFIG_EVENT_TRACE_STARTUP_TEST=n \ --raw_output=all deadbeef Relevant line: Testing ftrace filter: OK Without "tracing: Properly match strings that start with numbers", the test fails with: Testing ftrace filter: Failed to match filter 'str ~ "0001:*"', expected 1 Link: https://patch.msgid.link/20261116182710.2.Ic117871c2b1e94c5a2176903a5c3316a10584e61@changeid Signed-off-by: Brian Norris Signed-off-by: Steven Rostedt --- kernel/trace/trace_events_filter.c | 74 ++++++++++++++++++++++++- kernel/trace/trace_events_filter_test.h | 12 ++-- 2 files changed, 80 insertions(+), 6 deletions(-) diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c index 6704ef3d9520c6..7018964c94fc88 100644 --- a/kernel/trace/trace_events_filter.c +++ b/kernel/trace/trace_events_filter.c @@ -2856,6 +2856,8 @@ int ftrace_profile_set_filter(struct perf_event *event, int event_id, #include #include +#include "trace_probe.h" + #define CREATE_TRACE_POINTS #include "trace_events_filter_test.h" @@ -2867,12 +2869,22 @@ int ftrace_profile_set_filter(struct perf_event *event, int event_id, .match = m, \ .not_visited = nvisit, \ } + +#define DATA_STR(m, s) \ +{ \ + .filter = FILTER, \ + .str = s, \ + .match = m, \ + .not_visited = "", \ +} + #define YES 1 #define NO 0 static struct test_filter_data_t { char *filter; struct trace_event_raw_ftrace_test_filter rec; + const char *str; int match; char *not_visited; } test_filter_data[] = { @@ -2924,9 +2936,46 @@ static struct test_filter_data_t { DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, "bdfh"), DATA_REC(YES, 0, 1, 0, 1, 0, 1, 0, 1, ""), DATA_REC(YES, 1, 0, 1, 0, 1, 0, 1, 0, "bdfh"), +#undef FILTER +#define FILTER "str ~ \"0001:*\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(YES, "0001:"), + DATA_STR(NO, "0002:01:00.0"), + DATA_STR(NO, "pci:0001:01:00.0"), + DATA_STR(NO, "0001"), +#undef FILTER +#define FILTER "str ~ \"!0001:*\"" + DATA_STR(NO, "0001:01:00.0"), + DATA_STR(YES, "0002:01:00.0"), +#undef FILTER +#define FILTER "str ~ \"0001:*:00.[0-9]\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(YES, "0001:ff:00.7"), + DATA_STR(NO, "0001:01:00.a"), + DATA_STR(NO, "0002:01:00.0"), +#undef FILTER +#define FILTER "str ~ \"0001:01:00.0\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(NO, "0001:01:00.1"), + DATA_STR(NO, "0001:01:00.00"), + DATA_STR(NO, "0001:01:00"), +#undef FILTER +#define FILTER "str == \"0001:01:00.0\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(NO, "0001:01:00.1"), +#undef FILTER +#define FILTER "str ~ \"*0001:*\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(YES, "pci:0001:01:00.0"), + DATA_STR(NO, "0002:01:00.0"), +#undef FILTER +#define FILTER "str ~ \"*:00.0\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(NO, "0001:01:00.1"), }; #undef DATA_REC +#undef DATA_STR #undef FILTER #undef YES #undef NO @@ -2977,8 +3026,29 @@ static __init int ftrace_test_event_filter(void) for (i = 0; i < DATA_CNT; i++) { struct event_filter *filter = NULL; struct test_filter_data_t *d = &test_filter_data[i]; + union { + struct trace_event_raw_ftrace_test_filter rec; + /* Add some spare, to append the string contents. */ + char buf[sizeof(struct trace_event_raw_ftrace_test_filter) + 32]; + } event = { .rec = d->rec }; int err; + if (d->str) { + struct ftrace_event_field *field; + u32 offset = offsetof(typeof(event.rec), __data); + u32 len = strlen(d->str) + 1; + u32 *str_item; + + field = trace_find_event_field(&event_ftrace_test_filter, "str"); + if (WARN_ON_ONCE(!field)) + break; + if (WARN_ON_ONCE(offset + len > sizeof(event.buf))) + break; + str_item = (u32 *)&event.buf[field->offset]; + *str_item = make_data_loc(len, offset); + memcpy(&event.buf[offset], d->str, len); + } + err = create_filter(NULL, &event_ftrace_test_filter, d->filter, false, &filter); if (err) { @@ -3000,7 +3070,7 @@ static __init int ftrace_test_event_filter(void) update_pred_fn(filter, d->not_visited); test_pred_visited = 0; - err = filter_match_preds(filter, &d->rec); + err = filter_match_preds(filter, &event.rec); preempt_enable(); mutex_unlock(&event_mutex); @@ -3027,7 +3097,7 @@ static __init int ftrace_test_event_filter(void) /* Need to call ftrace_test_filter to prevent a warning */ if (!trace_ftrace_test_filter_enabled()) - trace_ftrace_test_filter(1, 2, 3, 4, 5, 6, 7, 8); + trace_ftrace_test_filter(1, 2, 3, 4, 5, 6, 7, 8, ""); return 0; } diff --git a/kernel/trace/trace_events_filter_test.h b/kernel/trace/trace_events_filter_test.h index e651dfbd345e63..74a9dba91545d7 100644 --- a/kernel/trace/trace_events_filter_test.h +++ b/kernel/trace/trace_events_filter_test.h @@ -9,9 +9,10 @@ TRACE_EVENT(ftrace_test_filter, - TP_PROTO(int a, int b, int c, int d, int e, int f, int g, int h), + TP_PROTO(int a, int b, int c, int d, int e, int f, int g, int h, + const char *str), - TP_ARGS(a, b, c, d, e, f, g, h), + TP_ARGS(a, b, c, d, e, f, g, h, str), TP_STRUCT__entry( __field(int, a) @@ -22,6 +23,7 @@ TRACE_EVENT(ftrace_test_filter, __field(int, f) __field(int, g) __field(int, h) + __string(str, str) ), TP_fast_assign( @@ -33,11 +35,13 @@ TRACE_EVENT(ftrace_test_filter, __entry->f = f; __entry->g = g; __entry->h = h; + __assign_str(str); ), - TP_printk("a %d, b %d, c %d, d %d, e %d, f %d, g %d, h %d", + TP_printk("a %d, b %d, c %d, d %d, e %d, f %d, g %d, h %d, str %s", __entry->a, __entry->b, __entry->c, __entry->d, - __entry->e, __entry->f, __entry->g, __entry->h) + __entry->e, __entry->f, __entry->g, __entry->h, + __get_str(str)) ); #endif /* _TRACE_TEST_H || TRACE_HEADER_MULTI_READ */ From 2891516d90b4dc9d41aa55fde08882e40c7c0336 Mon Sep 17 00:00:00 2001 From: Vincent Donnefort Date: Tue, 17 Nov 2026 08:29:32 +0000 Subject: [PATCH 1283/2102] tracing: Take trace_access_lock() in tracing_buffers_ioctl() tracing_buffers_ioctl() calls ring_buffer_map_get_reader() without trace_access_lock, breaking concurrent readers. Take trace_access_lock() around ring_buffer_map_get_reader(), matching the other consuming readers. Cc: stable@vger.kernel.org Fixes: cf9f0f7c4c5b ("tracing: Allow user-space mapping of the ring-buffer") Reported-by: Kyuwon Cho Closes: https://lore.kernel.org/all/179485165154.2547186.6129837870360499372@gmail.com/ Link: https://patch.msgid.link/20261117082932.3441173-1-vdonnefort@google.com Signed-off-by: Vincent Donnefort Reviewed-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- kernel/trace/trace.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c index 70b3c11ac16656..65b9d67647e578 100644 --- a/kernel/trace/trace.c +++ b/kernel/trace/trace.c @@ -7415,8 +7415,12 @@ static long tracing_buffers_ioctl(struct file *file, unsigned int cmd, unsigned return err; } - return ring_buffer_map_get_reader(iter->array_buffer->buffer, - iter->cpu_file); + trace_access_lock(iter->cpu_file); + err = ring_buffer_map_get_reader(iter->array_buffer->buffer, + iter->cpu_file); + trace_access_unlock(iter->cpu_file); + + return err; } else if (cmd) { return -ENOTTY; } From 761a77e09577bc7e5fdaff1d11bbff3486a87bf9 Mon Sep 17 00:00:00 2001 From: Steven Rostedt Date: Wed, 18 Nov 2026 12:25:20 -0500 Subject: [PATCH 1284/2102] tracing: Do not allow user events to add a system name User events currently do not support the addition of a system name, but the parsing does not check to see if one is specified. A kprobe can add its own system name with the following command: ~# echo 'p:mysystem/kprobe_event schedule a=%ax' >> dynamic_events ~# ls events/mysystem enable filter kprobe_event But if one tries to do the same with user events: ~# echo 'u:user_events/test u32 a' >> dynamic_events ~# ls events/user_events ls: reading directory 'events/user_events/': Invalid argument enable filter It corrupts the file system as the event added had a '/' in the name. Until user events support specifying system names, just return -EINVAL to prevent the corrupted file system from happening: ~# echo 'u:user_events/test u32 a' >> dynamic_events -bash: echo: write error: Invalid argument Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261118122520.4a689710@gandalf.local.home Acked-by: Beau Belgrave Fixes: 7f5a08c79df35 ("user_events: Add minimal support for trace_event into ftrace") Signed-off-by: Steven Rostedt --- kernel/trace/trace_events_user.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/kernel/trace/trace_events_user.c b/kernel/trace/trace_events_user.c index ea6a20a30cf52b..e29e1c772aa7d6 100644 --- a/kernel/trace/trace_events_user.c +++ b/kernel/trace/trace_events_user.c @@ -1040,6 +1040,9 @@ static int user_event_parse_cmd(struct user_event_group *group, if (flags) *flags++ = '\0'; + if (strstr(name, "/") != NULL) + return -EINVAL; + return user_event_parse(group, name, args, flags, newuser, reg_flags); } From abf7185109d3986c1f945641d2fb20e44527f7c6 Mon Sep 17 00:00:00 2001 From: Amit Machhiwal Date: Thu, 19 Nov 2026 00:02:35 +0530 Subject: [PATCH 1285/2102] ring-buffer: Do not check si_mem_available() before deferred init completes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With CONFIG_DEFERRED_STRUCT_PAGE_INIT=y, only about one memory section per node is initialized early in boot (16 MiB on powerpc). The rest is initialized on demand by deferred_grow_zone() when an allocation would otherwise fail, or later by page_alloc_init_late(). Until then NR_FREE_PAGES can be close to zero, because early allocations (SLUB, vmalloc, ftrace records) use up the first section. si_mem_available() is derived from NR_FREE_PAGES, so it under-reports. __rb_allocate_pages() returns -ENOMEM when si_mem_available() is below the requested size. This check wrongly fails the buffers allocated for the boot CPU in early_trace_init() and for secondary CPUs in smp_init(), both of which run before page_alloc_init_late(). The resulting boot log shows: ERROR: Failed to allocate trace buffer ERROR: tracer: failed to allocate ring buffer! Skip the check until SYSTEM_FREEING_INITMEM on CONFIG_DEFERRED_STRUCT_PAGE_INIT kernels. The allocation itself still fails if memory really is short. This is the second half of the fix for the early boot crash reported on ppc64le KVM guests. Commit b3b974008388 ("tracing: Do not initialize tracefs work if tracing is disabled") stopped the NULL pointer dereference in __find_event_file() that followed the failed allocation. This patch fixes the allocation failure itself. Cc: stable@vger.kernel.org Fixes: 2a872fa4e9c8 ("ring-buffer: Check if memory is available before allocation") Link: https://patch.msgid.link/20261118183235.63310-1-amachhiw@linux.ibm.com Reported-by: Michal Suchánek Closes: https://lore.kernel.org/all/arYskzbiaNzBR9MD@kunlun.suse.cz/ Reviewed-by: Vincent Donnefort Signed-off-by: Amit Machhiwal Signed-off-by: Steven Rostedt --- kernel/trace/ring_buffer.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c index 0a1c7f98159ea4..a5a0adc934faa6 100644 --- a/kernel/trace/ring_buffer.c +++ b/kernel/trace/ring_buffer.c @@ -2468,8 +2468,17 @@ static int __rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer, * memory. It may not be accurate. But we don't care, we just want * to prevent doing any allocation when it is obvious that it is * not going to succeed. + * + * With CONFIG_DEFERRED_STRUCT_PAGE_INIT, si_mem_available() + * will reflect the actual available memory only after + * SYSTEM_FREEING_INITMEM. */ - i = si_mem_available(); + if (IS_ENABLED(CONFIG_DEFERRED_STRUCT_PAGE_INIT) && + unlikely(system_state < SYSTEM_FREEING_INITMEM)) + i = LONG_MAX; + else + i = si_mem_available(); + if (i < (nr_pages << subbuf_order)) return -ENOMEM; From 39bc1fdbce1e5f435f8d02d57a9415735690bb1f Mon Sep 17 00:00:00 2001 From: Steven Rostedt Date: Thu, 19 Nov 2026 12:43:19 -0500 Subject: [PATCH 1286/2102] tracing: Add notrace to event functions that hook to ftrace A few functions in trace_events.c are used to hook to the ftrace function hooks. Before CONFIG_FUNCTION_SELF_TRACING was added, these functions were not marked for tracing because the entire directory was set to "notrace". But now that certain files can be traced by ftrace when the CONFIG_FUNCTION_SELF_TRACING config is set, individual functions that use ftrace must be annotated with "notrace" otherwise they can trigger a triple fault when called. Annotate the trace_events.c functions that are attached to ftrace with "notrace. Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261119124319.3a8bfe50@gandalf.local.home Fixes: f93a7d0caccd6 ("ftrace: Allow tracing of some of the tracing code") Signed-off-by: Steven Rostedt --- kernel/trace/trace_events.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/kernel/trace/trace_events.c b/kernel/trace/trace_events.c index c9d31c9f3fcad5..7f89160aeff3af 100644 --- a/kernel/trace/trace_events.c +++ b/kernel/trace/trace_events.c @@ -4317,7 +4317,7 @@ static void update_event_probe(struct event_probe_data *data) set_bit(EVENT_FILE_FL_SOFT_DISABLED_BIT, &data->file->flags); } -static void +static void notrace event_enable_probe(unsigned long ip, unsigned long parent_ip, struct trace_array *tr, struct ftrace_probe_ops *ops, void *data) @@ -4334,7 +4334,7 @@ event_enable_probe(unsigned long ip, unsigned long parent_ip, update_event_probe(edata); } -static void +static void notrace event_enable_count_probe(unsigned long ip, unsigned long parent_ip, struct trace_array *tr, struct ftrace_probe_ops *ops, void *data) @@ -5205,7 +5205,7 @@ static DEFINE_PER_CPU(atomic_t, ftrace_test_event_disable); static struct trace_event_file event_trace_file __initdata; -static void __init +static void notrace __init function_test_events_call(unsigned long ip, unsigned long parent_ip, struct ftrace_ops *op, struct ftrace_regs *regs) { From 56ce4ed6316cae9536ea891d6686b92f1d930c00 Mon Sep 17 00:00:00 2001 From: David Carlier Date: Thu, 19 Nov 2026 08:01:39 +0000 Subject: [PATCH 1287/2102] tracing: Ignore .function on the function trace event For the function event, parse_pred() handles the .function suffix before the ftrace_event_is_function() case, so "ip.function == schedule" builds a predicate with no regex. Setting it through perf then dereferences the NULL pred->regex in ftrace_function_set_filter_pred(). The "ip" field of that event already takes a function name, so ignore the suffix there and let the function event case handle it. Cc: stable@vger.kernel.org Fixes: cfb58e278c6a ("tracing/filters: Dynamically allocate filter_pred.regex") Link: https://patch.msgid.link/20261119080139.131834-1-devnexen@gmail.com Suggested-by: Steven Rostedt Signed-off-by: David Carlier Signed-off-by: Steven Rostedt --- kernel/trace/trace_events_filter.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c index 7018964c94fc88..a9d77df3e19a9e 100644 --- a/kernel/trace/trace_events_filter.c +++ b/kernel/trace/trace_events_filter.c @@ -1737,7 +1737,9 @@ static int parse_pred(const char *str, void *data, /* See if the field is a kernel function name */ if ((len = str_has_prefix(str + i, ".function"))) { - function = true; + /* Ignore if event is already a function */ + if (!ftrace_event_is_function(call)) + function = true; i += len; } From 7233cadb56c5de9359f4005e2c26e9a1b52504dd Mon Sep 17 00:00:00 2001 From: Sakari Ailus Date: Mon, 3 Aug 2026 19:45:33 +0300 Subject: [PATCH 1288/2102] MAINTAINERS: Update usbio driver maintainers and reviewers Israel's e-mail address is no longer functional so remove him as a maintainer of the usbio driver. At the same time, add myself as a maintainer and Antti as a reviewer for the driver. Signed-off-by: Sakari Ailus Acked-by: Hans de Goede Link: https://patch.msgid.link/20260803164533.58833-1-sakari.ailus@linux.intel.com Signed-off-by: Greg Kroah-Hartman --- MAINTAINERS | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index d738990161bd0f..ec0d53e2a2f0f1 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -13844,9 +13844,9 @@ F: Documentation/admin-guide/pm/intel_uncore_frequency_scaling.rst F: drivers/platform/x86/intel/uncore-frequency/ INTEL USBIO USB I/O EXPANDER DRIVERS -M: Israel Cepeda M: Hans de Goede -R: Sakari Ailus +M: Sakari Ailus +R: Antti Laakso S: Maintained F: drivers/gpio/gpio-usbio.c F: drivers/i2c/busses/i2c-usbio.c From 9fb790aeb56b91c7c8a62dcc4bb64497b52f164c Mon Sep 17 00:00:00 2001 From: Myeonghun Pak Date: Thu, 24 Sep 2026 16:41:33 -0500 Subject: [PATCH 1289/2102] usb: dwc3-am62: shut down refclk on remove dwc3_ti_remove() relies on pm_runtime_put_sync() to invoke the runtime-suspend callback and disable the USB2 reference clock. The callback is not guaranteed to run: autosuspend may defer it, and a reference held by pm_runtime_forbid() keeps the usage count above zero. The following pm_runtime_disable() then cancels pending work while the clock remains enabled. Balance only the reference acquired by remove without requesting a suspend, then disable runtime PM to drain any operation in progress. Disable the clock explicitly when the stable runtime status shows that the device was not already suspended. This also handles CONFIG_PM=n, where the runtime-PM calls are stubs, without double-disabling the clock after a failed resume. This issue was identified during our ongoing static-analysis research while reviewing kernel code. Fixes: 6661befe4100 ("usb: dwc3-am62: fix module unload/reload behavior") Cc: stable@kernel.org Assisted-by: OpenAI:GPT-5.6 Co-developed-by: Ijae Kim Signed-off-by: Ijae Kim Signed-off-by: Myeonghun Pak Acked-by: Thinh Nguyen Link: https://patch.msgid.link/CAGEsz8EXYLRxnOFOD=FxKn6QFFFTGhqDpsvs3q_dZw5dna8fTg@mail.gmail.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/dwc3/dwc3-am62.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/usb/dwc3/dwc3-am62.c b/drivers/usb/dwc3/dwc3-am62.c index 88702868436472..80e3c74d8cfcdb 100644 --- a/drivers/usb/dwc3/dwc3-am62.c +++ b/drivers/usb/dwc3/dwc3-am62.c @@ -320,9 +320,11 @@ static void dwc3_ti_remove(struct platform_device *pdev) reg &= ~USBSS_MODE_VALID; dwc3_ti_writel(am62, USBSS_MODE_CONTROL, reg); - pm_runtime_put_sync(dev); + pm_runtime_put_noidle(dev); pm_runtime_disable(dev); pm_runtime_dont_use_autosuspend(dev); + if (!pm_runtime_status_suspended(dev)) + clk_disable_unprepare(am62->usb2_refclk); pm_runtime_set_suspended(dev); } From 8f51823de3c9184fd8b7a4430a030eb071f39dae Mon Sep 17 00:00:00 2001 From: Jiale Yao Date: Sat, 3 Oct 2026 16:11:52 +0800 Subject: [PATCH 1290/2102] usb: cdns3: report endpoint reset timeout cdns3_gadget_ep_disable() discards the endpoint reset poll result and then tests ret, which is still zero. A reset timeout is therefore neither reported nor returned to the caller. Store the poll result in ret so the existing diagnostic and return path expose the timeout. Fixes: 7733f6c32e36 ("usb: cdns3: Add Cadence USB3 DRD Driver") Signed-off-by: Jiale Yao Add: stable@kernel.org Acked-by: Peter Chen Link: https://patch.msgid.link/20261003081152.433499-1-yaojiale02@163.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/cdns3/cdns3-gadget.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/usb/cdns3/cdns3-gadget.c b/drivers/usb/cdns3/cdns3-gadget.c index 380c4fde8298e3..e2db946560c1a2 100644 --- a/drivers/usb/cdns3/cdns3-gadget.c +++ b/drivers/usb/cdns3/cdns3-gadget.c @@ -2530,9 +2530,9 @@ static int cdns3_gadget_ep_disable(struct usb_ep *ep) !(val & EP_STS_DBUSY), 1, 10); writel(EP_CMD_EPRST, &priv_dev->regs->ep_cmd); - readl_poll_timeout_atomic(&priv_dev->regs->ep_cmd, val, - !(val & (EP_CMD_CSTALL | EP_CMD_EPRST)), - 1, 1000); + ret = readl_poll_timeout_atomic(&priv_dev->regs->ep_cmd, val, + !(val & (EP_CMD_CSTALL | EP_CMD_EPRST)), + 1, 1000); if (unlikely(ret)) dev_err(priv_dev->dev, "Timeout: %s resetting failed.\n", priv_ep->name); From ce05cc49d8c4d41549f53c382a1588a43cb1c0be Mon Sep 17 00:00:00 2001 From: Xu Yang Date: Mon, 19 Oct 2026 16:49:44 +0800 Subject: [PATCH 1291/2102] usb: cdns3: imx: fix kernel panic on remove due to kfree of static platform_data When cdns_imx_remove() calls of_platform_depopulate(), the child platform device is destroyed. platform_device_release() then calls kfree(pdev->dev.platform_data), but cdns3-imx assigns a pointer to a static global variable as platform_data, so kfree() on it triggers a kernel panic. [ 56.809541] Call trace: [ 56.811982] kfree+0x44/0x398 (P) [ 56.815300] platform_device_release+0x24/0x4c [ 56.819747] device_release+0x3c/0xa0 [ 56.823413] kobject_put+0xa0/0x120 [ 56.826906] klist_children_put+0x18/0x28 [ 56.830920] klist_prev+0xb4/0x1c0 [ 56.834325] device_for_each_child_reverse+0x7c/0xc8 [ 56.839294] of_platform_depopulate+0x34/0x80 [ 56.843664] cdns_imx_remove+0x34/0xcc [cdns3_imx] Fix this by iterating over child devices and clearing platform_data to NULL before of_platform_depopulate() is called, preventing the invalid kfree(). Fixes: ff6d6e6c6778 ("usb: cdns3: imx: add glue layer runtime pm implementation") Cc: stable@kernel.org Signed-off-by: Xu Yang Reviewed-by: Frank Li Acked-by: Peter Chen Link: https://patch.msgid.link/20261019084944.2051097-1-xu.yang_2@oss.nxp.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/cdns3/cdns3-imx.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/usb/cdns3/cdns3-imx.c b/drivers/usb/cdns3/cdns3-imx.c index 710334c3431e74..5e92623296e502 100644 --- a/drivers/usb/cdns3/cdns3-imx.c +++ b/drivers/usb/cdns3/cdns3-imx.c @@ -218,12 +218,20 @@ static int cdns_imx_probe(struct platform_device *pdev) return ret; } +static int cdns_imx_reset_pdata(struct device *dev, void *data) +{ + if (device_is_compatible(dev, "cdns,usb3")) + dev->platform_data = NULL; + return 0; +} + static void cdns_imx_remove(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct cdns_imx *data = dev_get_drvdata(dev); pm_runtime_get_sync(dev); + device_for_each_child(dev, NULL, cdns_imx_reset_pdata); of_platform_depopulate(dev); clk_bulk_disable_unprepare(data->num_clks, data->clks); pm_runtime_disable(dev); From 75d6b9d82c35d35dad9fdd783975be1edd32fe2f Mon Sep 17 00:00:00 2001 From: Thomas de Gruijter Date: Fri, 20 Nov 2026 02:13:35 +0100 Subject: [PATCH 1292/2102] Bluetooth: MSFT: Record the filter state on Command Disallowed msft_le_set_advertisement_filter_enable_cb() treats status 0x0C (Command Disallowed) as success: a controller returns it when the advertisement filter is already in the requested state, and some controllers start with the filter enabled. Since commit 493ea69970e2 ("Bluetooth: Convert MSFT filter HCI cmd to hci_sync") the callback is passed the return value of __hci_cmd_sync_status() instead of the HCI status. That function reports Command Disallowed as -EBUSY, so the 0x0C branch is never taken and msft->filter_enabled keeps its old value whenever the filter was already in the requested state. msft_set_filter_enable() also always returns 0, hiding real errors from its callers. Pass the error code to the callback, treat -EBUSY as the filter already being in the requested state, and return real errors from msft_set_filter_enable(). Nothing reads msft->filter_enabled yet, but the next patch relies on it to decide when to change the filter state. The problem was found, with the help of an AI coding assistant (Claude Code with Claude Opus 5.5). Fixes: 493ea69970e2 ("Bluetooth: Convert MSFT filter HCI cmd to hci_sync") Signed-off-by: Thomas de Gruijter Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/msft.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/net/bluetooth/msft.c b/net/bluetooth/msft.c index 7a06c2b8974b7e..f372df9a98311f 100644 --- a/net/bluetooth/msft.c +++ b/net/bluetooth/msft.c @@ -1142,26 +1142,27 @@ __u64 msft_get_features(struct hci_dev *hdev) static void msft_le_set_advertisement_filter_enable_cb(struct hci_dev *hdev, void *user_data, - u8 status) + int err) { struct msft_cp_le_set_advertisement_filter_enable *cp = user_data; struct msft_data *msft = hdev->msft_data; - /* Error 0x0C would be returned if the filter enabled status is + /* Error 0x0C (Command Disallowed), which __hci_cmd_sync_status() + * reports as -EBUSY, would be returned if the filter enabled status is * already set to whatever we were trying to set. * Although the default state should be disabled, some controller set * the initial value to enabled. Because there is no way to know the * actual initial value before sending this command, here we also treat * error 0x0C as success. */ - if (status != 0x00 && status != 0x0C) + if (err && err != -EBUSY) return; hci_dev_lock(hdev); msft->filter_enabled = cp->enable; - if (status == 0x0C) + if (err == -EBUSY) bt_dev_warn(hdev, "MSFT filter_enable is already %s", cp->enable ? "on" : "off"); @@ -1212,7 +1213,7 @@ int msft_set_filter_enable(struct hci_dev *hdev, bool enable) msft_le_set_advertisement_filter_enable_cb(hdev, &cp, err); - return 0; + return err == -EBUSY ? 0 : err; } bool msft_curve_validity(struct hci_dev *hdev) From 4a8f9b7fb4f503f48e2ccfc67caa8b07d303f8a8 Mon Sep 17 00:00:00 2001 From: Thomas de Gruijter Date: Fri, 20 Nov 2026 02:13:36 +0100 Subject: [PATCH 1293/2102] Bluetooth: MSFT: Only enable the advertisement filter with monitors msft_do_open() unconditionally enables the MSFT LE advertisement filter on every power on, whether or not any advertisement monitor is registered. On MediaTek MT7922 (USB 0e8d:0616, firmware build 20260724) the controller then drops every LE advertisement: LE Set Extended Scan Enable succeeds, but no LE Extended Advertising Report is ever delivered, so LE discovery and passive scanning find nothing. BR/EDR inquiry is not affected. Sending LE Set Advertisement Filter Enable with Enable set to 0x00 restores reporting immediately. The Microsoft HCI extension specification defines the filter as disabled by default and does not specify what a controller reports while the filter is enabled without any monitor condition. Only enable the filter while at least one monitor is offloaded to the controller, and update it after a monitor is added or removed and after the monitors are re-registered on power on and resume. Like the monitors, the filter state does not survive a power off, so reset the tracked state in msft_do_close() instead of sending a redundant disable on power on. A command is only sent when the wanted state differs from msft->filter_enabled, so this depends on the previous patch keeping that state accurate when the controller reports the filter as already being in the requested state. Fixes: 394566bf1e37 ("Bluetooth: advmon offload MSFT handle filter enablement") Signed-off-by: Thomas de Gruijter Signed-off-by: Luiz Augusto von Dentz --- net/bluetooth/msft.c | 46 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/net/bluetooth/msft.c b/net/bluetooth/msft.c index f372df9a98311f..db7b40ab5fc164 100644 --- a/net/bluetooth/msft.c +++ b/net/bluetooth/msft.c @@ -468,6 +468,30 @@ static int msft_remove_monitor_sync(struct hci_dev *hdev, return err; } +/* Keep the advertisement filter enabled only while at least one monitor is + * offloaded to the controller. With the filter enabled and no monitors, some + * controllers (e.g. MediaTek MT7922) drop every advertisement, which breaks + * LE discovery and passive scanning entirely. + * + * This function requires the caller holds hci_req_sync_lock + */ +static void msft_update_filter_enable(struct hci_dev *hdev) +{ + struct msft_data *msft = hdev->msft_data; + bool enable, update; + + if (!msft) + return; + + hci_dev_lock(hdev); + enable = !list_empty(&msft->handle_map); + update = enable != msft->filter_enabled; + hci_dev_unlock(hdev); + + if (update) + msft_set_filter_enable(hdev, enable); +} + /* This function requires the caller holds hci_req_sync_lock */ int msft_suspend_sync(struct hci_dev *hdev) { @@ -493,6 +517,8 @@ int msft_suspend_sync(struct hci_dev *hdev) /* All monitors have been removed */ msft->suspending = false; + msft_update_filter_enable(hdev); + return 0; } @@ -633,6 +659,7 @@ int msft_resume_sync(struct hci_dev *hdev) hci_dev_unlock(hdev); reregister_monitor(hdev); + msft_update_filter_enable(hdev); return 0; } @@ -670,11 +697,11 @@ void msft_do_open(struct hci_dev *hdev) if (msft_monitor_supported(hdev)) { msft->resuming = true; - msft_set_filter_enable(hdev, true); /* Monitors get removed on power off, so we need to explicitly * tell the controller to re-monitor. */ reregister_monitor(hdev); + msft_update_filter_enable(hdev); } } @@ -706,6 +733,11 @@ void msft_do_close(struct hci_dev *hdev) kfree(handle_data); } + /* The advertisement filter is back to its default, disabled state + * after power off as well. + */ + msft->filter_enabled = false; + hci_dev_unlock(hdev); mutex_lock(&msft->filter_lock); @@ -1173,6 +1205,7 @@ static void msft_le_set_advertisement_filter_enable_cb(struct hci_dev *hdev, int msft_add_monitor_pattern(struct hci_dev *hdev, struct adv_monitor *monitor) { struct msft_data *msft = hdev->msft_data; + int err; if (!msft) return -EOPNOTSUPP; @@ -1180,13 +1213,17 @@ int msft_add_monitor_pattern(struct hci_dev *hdev, struct adv_monitor *monitor) if (msft->resuming || msft->suspending) return -EBUSY; - return msft_add_monitor_sync(hdev, monitor); + err = msft_add_monitor_sync(hdev, monitor); + msft_update_filter_enable(hdev); + + return err; } /* This function requires the caller holds hci_req_sync_lock */ int msft_remove_monitor(struct hci_dev *hdev, struct adv_monitor *monitor) { struct msft_data *msft = hdev->msft_data; + int err; if (!msft) return -EOPNOTSUPP; @@ -1194,7 +1231,10 @@ int msft_remove_monitor(struct hci_dev *hdev, struct adv_monitor *monitor) if (msft->resuming || msft->suspending) return -EBUSY; - return msft_remove_monitor_sync(hdev, monitor); + err = msft_remove_monitor_sync(hdev, monitor); + msft_update_filter_enable(hdev); + + return err; } int msft_set_filter_enable(struct hci_dev *hdev, bool enable) From b535edbf51782cc38acc2e7a6f5ff590ab865c27 Mon Sep 17 00:00:00 2001 From: Kiran K Date: Fri, 20 Nov 2026 15:12:48 +0530 Subject: [PATCH 1294/2102] Bluetooth: btintel_pcie: Set only MAC_INIT in btintel_pcie_mac_init() btintel_pcie_mac_init() is called prior to reading device memory via target access. To acquire MAC access, only the MAC_INIT and MAC_ACCESS_REQ bits in the function control register need to be programmed. Currently, btintel_pcie_mac_init() also modifies FUNC_ENA, FUNC_INIT, BUS_MASTER_DISCON, and SW_RESET, which are not relevant to MAC access (though doing so had no observed side effects). Leave those bits untouched and only set MAC_INIT if it is not already set. Fixes: b9465e6670a2 ("Bluetooth: btintel_pcie: Read hardware exception data") Assisted-by: Copilot:Gemini 4 Argon Reviewed-by: Paul Menzel Signed-off-by: Kiran K Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/btintel_pcie.c | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/drivers/bluetooth/btintel_pcie.c b/drivers/bluetooth/btintel_pcie.c index 91b1ee9d601028..70e4f02ce6bf9e 100644 --- a/drivers/bluetooth/btintel_pcie.c +++ b/drivers/bluetooth/btintel_pcie.c @@ -737,14 +737,11 @@ static void btintel_pcie_mac_init(struct btintel_pcie_data *data) { u32 reg; - /* Set MAC_INIT bit to start primary bootloader */ reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG); - reg &= ~(BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_INIT | - BTINTEL_PCIE_CSR_FUNC_CTRL_BUS_MASTER_DISCON | - BTINTEL_PCIE_CSR_FUNC_CTRL_SW_RESET); - reg |= (BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_ENA | - BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT); - btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg); + if (!(reg & BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT)) { + reg |= BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT; + btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg); + } } static int btintel_pcie_get_mac_access(struct btintel_pcie_data *data) From 4fe38719e6738feaa90486e36b0790dd5d960a96 Mon Sep 17 00:00:00 2001 From: Kiran K Date: Fri, 20 Nov 2026 15:12:49 +0530 Subject: [PATCH 1295/2102] Bluetooth: btintel_pcie: Fold MAC_INIT into btintel_pcie_get_mac_access() MAC_INIT and MAC_ACCESS_REQ are the function control register bits required to acquire MAC access for target reads. Currently, MAC_INIT is set separately by btintel_pcie_mac_init(), which is called right before btintel_pcie_read_device_mem() in btintel_parse_mbox_tlv(), btintel_pcie_read_hwexp() and btintel_pcie_dump_fwtrigger_event(). btintel_pcie_dump_traces() also reads device memory under MAC access, but it never called btintel_pcie_mac_init(), so MAC_INIT was missing on the coredump path. Fold the MAC_INIT handling into btintel_pcie_get_mac_access() so that every user of MAC access programs MAC_INIT. Set MAC_INIT and MAC_ACCESS_REQ with a single register write when either bit is not already set. Drop btintel_pcie_mac_init() along with its three call sites. This also fixes btintel_pcie_dump_traces(). Fixes: 07e6bddb54b4 ("Bluetooth: btintel_pcie: Add support for device coredump") Assisted-by: Copilot:Gemini 4 Argon Reviewed-by: Paul Menzel Signed-off-by: Kiran K Signed-off-by: Luiz Augusto von Dentz --- drivers/bluetooth/btintel_pcie.c | 28 ++++++---------------------- 1 file changed, 6 insertions(+), 22 deletions(-) diff --git a/drivers/bluetooth/btintel_pcie.c b/drivers/bluetooth/btintel_pcie.c index 70e4f02ce6bf9e..e58bd5156af387 100644 --- a/drivers/bluetooth/btintel_pcie.c +++ b/drivers/bluetooth/btintel_pcie.c @@ -733,28 +733,18 @@ static int btintel_pcie_reset_bt(struct btintel_pcie_data *data) return reg == 0 ? 0 : -ENODEV; } -static void btintel_pcie_mac_init(struct btintel_pcie_data *data) -{ - u32 reg; - - reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG); - if (!(reg & BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT)) { - reg |= BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT; - btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg); - } -} - static int btintel_pcie_get_mac_access(struct btintel_pcie_data *data) { - u32 reg; + u32 reg, val; int retry = 15; + const u32 req = BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT | + BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ; reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG); - if (!(reg & BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ)) { - reg |= BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ; - btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg); - } + val = reg | req; + if (val != reg) + btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, val); do { reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG); @@ -1657,8 +1647,6 @@ static int btintel_parse_mbox_tlv(struct btintel_pcie_data *data) if (!buffer) return -ENOMEM; - btintel_pcie_mac_init(data); - err = btintel_pcie_read_device_mem(data, buffer, tbl_addr, buffer_len); if (err) @@ -2323,8 +2311,6 @@ static void btintel_pcie_read_hwexp(struct btintel_pcie_data *data) if (!buf) goto exit_on_error; - btintel_pcie_mac_init(data); - err = btintel_pcie_read_device_mem(data, buf, addr, len); if (err) goto exit_on_error; @@ -2412,8 +2398,6 @@ static int btintel_pcie_dump_fwtrigger_event(struct btintel_pcie_data *data) if (!buf) return -ENOMEM; - btintel_pcie_mac_init(data); - err = btintel_pcie_read_device_mem(data, buf, data->debug_evt_addr, len); if (err) From 56e2cfb32881fb63f647420b90d716cb388bcaa1 Mon Sep 17 00:00:00 2001 From: Fabrice Gasnier Date: Fri, 21 Aug 2026 16:33:14 +0200 Subject: [PATCH 1296/2102] usb: misc: onboard-hub: add support for Microchip USB2422 Add support for the Microchip USB2422 USB2.0 Hub. It is similar to the USB2412. It provides two downstream ports. It is supplied by a single 3v3 power source, and provides a reset pin. So add the generic compatible, defined as "usbVID,PID", and reuse existing usb424_data. This hub can be found on stm32mp257f-dk board. Signed-off-by: Fabrice Gasnier Cc: stable Link: https://patch.msgid.link/20260821-usb-onboard-hub-2422-v1-v1-1-d1cee9685524@foss.st.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/misc/onboard_usb_dev.c | 1 + drivers/usb/misc/onboard_usb_dev.h | 1 + 2 files changed, 2 insertions(+) diff --git a/drivers/usb/misc/onboard_usb_dev.c b/drivers/usb/misc/onboard_usb_dev.c index 0606d405c16f11..b43d9d41dce452 100644 --- a/drivers/usb/misc/onboard_usb_dev.c +++ b/drivers/usb/misc/onboard_usb_dev.c @@ -667,6 +667,7 @@ static const struct usb_device_id onboard_dev_id_table[] = { { USB_DEVICE(VENDOR_ID_GENESYS, 0x0620) }, /* Genesys Logic GL3523 USB 3.1 HUB */ { USB_DEVICE(VENDOR_ID_GENESYS, 0x0625) }, /* Genesys Logic GL3590 USB 3.2 HUB */ { USB_DEVICE(VENDOR_ID_MICROCHIP, 0x2412) }, /* USB2412 USB 2.0 HUB */ + { USB_DEVICE(VENDOR_ID_MICROCHIP, 0x2422) }, /* USB2422 USB 2.0 HUB */ { USB_DEVICE(VENDOR_ID_MICROCHIP, 0x2514) }, /* USB2514B USB 2.0 HUB */ { USB_DEVICE(VENDOR_ID_MICROCHIP, 0x2517) }, /* USB2517 USB 2.0 HUB */ { USB_DEVICE(VENDOR_ID_MICROCHIP, 0x2744) }, /* USB5744 USB 2.0 HUB */ diff --git a/drivers/usb/misc/onboard_usb_dev.h b/drivers/usb/misc/onboard_usb_dev.h index 3523f8f8a1496d..e425a94e117598 100644 --- a/drivers/usb/misc/onboard_usb_dev.h +++ b/drivers/usb/misc/onboard_usb_dev.h @@ -137,6 +137,7 @@ static const struct onboard_dev_pdata xmos_xvf3500_data = { static const struct of_device_id onboard_dev_match[] = { { .compatible = "usb-a-connector", .data = &usb_a_conn_data, }, { .compatible = "usb424,2412", .data = µchip_usb424_data, }, + { .compatible = "usb424,2422", .data = µchip_usb424_data, }, { .compatible = "usb424,2514", .data = µchip_usb2514_data, }, { .compatible = "usb424,2517", .data = µchip_usb424_data, }, { .compatible = "usb424,2744", .data = µchip_usb5744_data, }, From b0baaf6cbb16bc773d0c76916aac17c44a6cd557 Mon Sep 17 00:00:00 2001 From: Heikki Krogerus Date: Fri, 11 Sep 2026 15:28:50 +0200 Subject: [PATCH 1297/2102] usb: typec: ucsi: acpi: Add DMI quirk for Dell XPS platforms On Dell XPS systems, the UCSI firmware incorrectly reports duplicate or extra DisplayPort and Thunderbolt alternate mode entries with conflicting and malformed VDOs when querying alternate mode details. This causes the kernel to retain an invalid VDO descriptor, breaking DisplayPort Alternate Mode functionality during hotplug events. Work around this issue by clearing the UCSI_CAP_ALT_MODE_DETAILS feature flag in a DMI quirk matching Dell XPS platforms so that the driver does not attempt to register alternate modes on these systems. Reported-by: Manuel Knitza Cc: stable Closes: https://lore.kernel.org/linux-usb/CAMRbua4xZfsQ0FXsrfq=SCbyZa1n=Aw5UrD3bEaU41d+J3KmXw@mail.gmail.com/ Signed-off-by: Heikki Krogerus Tested-by: Manuel Knitza Link: https://patch.msgid.link/20260911132850.1580669-1-heikki.krogerus@linux.intel.com Signed-off-by: Greg Kroah-Hartman --- drivers/usb/typec/ucsi/ucsi_acpi.c | 41 ++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/drivers/usb/typec/ucsi/ucsi_acpi.c b/drivers/usb/typec/ucsi/ucsi_acpi.c index aae358f23268c2..9c14f93a93408e 100644 --- a/drivers/usb/typec/ucsi/ucsi_acpi.c +++ b/drivers/usb/typec/ucsi/ucsi_acpi.c @@ -216,6 +216,39 @@ static const struct ucsi_operations ucsi_gram_ops = { .async_control = ucsi_acpi_async_control }; +static int ucsi_dell_sync_control(struct ucsi *ucsi, u64 command, u32 *cci, + void *val, size_t len, void *msg_out, + size_t msg_out_size) +{ + int ret; + + ret = ucsi_sync_control_common(ucsi, command, cci, val, len, + msg_out, msg_out_size); + if (ret < 0) + return ret; + + if (UCSI_COMMAND(command) == UCSI_GET_CAPABILITY && val) { + struct ucsi_capability *cap = val; + + if (cap->features & UCSI_CAP_ALT_MODE_DETAILS) { + dev_warn(ucsi->dev, + "Firmware bug: broken altmode details reporting, disabling\n"); + cap->features &= ~UCSI_CAP_ALT_MODE_DETAILS; + } + } + + return ret; +} + +static const struct ucsi_operations ucsi_dell_ops = { + .read_version = ucsi_acpi_read_version, + .read_cci = ucsi_acpi_read_cci, + .poll_cci = ucsi_acpi_poll_cci, + .read_message_in = ucsi_acpi_read_message_in, + .sync_control = ucsi_dell_sync_control, + .async_control = ucsi_acpi_async_control +}; + static const struct dmi_system_id ucsi_acpi_quirks[] = { { .matches = { @@ -239,6 +272,14 @@ static const struct dmi_system_id ucsi_acpi_quirks[] = { }, .driver_data = (void *)&ucsi_gram_ops, }, + { + .ident = "Dell XPS", + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), + DMI_MATCH(DMI_PRODUCT_NAME, "XPS"), + }, + .driver_data = (void *)&ucsi_dell_ops, + }, { } }; From bedefcbb8a0827e2758d6fc4a0601756eba7c248 Mon Sep 17 00:00:00 2001 From: Takashi Iwai Date: Thu, 19 Nov 2026 13:23:52 +0100 Subject: [PATCH 1298/2102] ALSA: pcm: Fix potential ABBA deadlock at snd_pcm_action_nonatomic() snd_pcm_action_nonatomic() is called for PCM PREPARE and other operations, and the function takes snd_pcm_buffer_access_lock() of the given substream (that takes runtime->buffer_mutex internally) at first, followed by the call of snd_pcm_action_group() that takes buffer_mutex of other substreams in the same link group again. Recently Sashiko suggested it may lead to an ABBA deadlock when two different substreams in the same PCM link call it concurrently: CPU0 CPU1 ---- ---- lock(&A->runtime->buffer_mutex) lock(&B->runtime->buffer_mutex) lock(&B->runtime->buffer_mutex) lock(&A->runtime->buffer_mutex) This patch tries to address the potential deadlock. Instead of taking the buffer_mutex of the target substream at first and processing the rest in the loop, take the whole buffer_mutex for each in the loop. This assures the order of the nested mutexes -- the linked list itself is kept intact by the read_rwsem() around snd_pcm_action_nonatomic(). Also, this changes the action in the snd_pcm_action_group() loop from the direct call of mutex_lock(buffer_mutex) to snd_pcm_buffer_access_lock(). This prevents the unexpected state transition or the buffer access during the action, too. Since the target substream is no longer locked before the loop, the lockdep subclass for buffer_mutex in the loop now starts from 0, so that a link group of N substreams uses the subclasses 0..N-1 as before. The subclass for the stream lock case still starts from 1, as the caller holds the target stream lock at subclass 0. Note that this change might have a slight side-effect, though: when some concurrent operations happen during the PREPARE or RESET, now it may return -EBUSY. But this can be seen rather as an expected behavior that was overlooked before the fix. Fixes: 3c3201f8c7bb ("ALSA: pcm: Fix races among concurrent prepare and hw_params/hw_free calls") Reported-by: sashiko-bot@kernel.org Closes: https://lore.kernel.org/sashiko-outbox-221145@kernel.org Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261119122356.2134523-2-tiwai@suse.de --- sound/core/pcm_native.c | 63 +++++++++++++++++++++++++++-------------- 1 file changed, 41 insertions(+), 22 deletions(-) diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c index 5d80b56449e2ea..d630bc290959b8 100644 --- a/sound/core/pcm_native.c +++ b/sound/core/pcm_native.c @@ -718,14 +718,20 @@ static int snd_pcm_hw_params_choose(struct snd_pcm_substream *pcm, /* acquire buffer_mutex; if it's in r/w operation, return -EBUSY, otherwise * block the further r/w operations */ -static int snd_pcm_buffer_access_lock(struct snd_pcm_runtime *runtime) +static int __snd_pcm_buffer_access_lock(struct snd_pcm_runtime *runtime, + int depth) { if (!atomic_dec_unless_positive(&runtime->buffer_accessing)) return -EBUSY; - mutex_lock(&runtime->buffer_mutex); + mutex_lock_nested(&runtime->buffer_mutex, depth); return 0; /* keep buffer_mutex, unlocked by below */ } +static int snd_pcm_buffer_access_lock(struct snd_pcm_runtime *runtime) +{ + return __snd_pcm_buffer_access_lock(runtime, 0); +} + /* release buffer_mutex and clear r/w access flag */ static void snd_pcm_buffer_access_unlock(struct snd_pcm_runtime *runtime) { @@ -1317,26 +1323,38 @@ struct action_ops { * this functions is core for handling of linked stream * Note: the stream state might be changed also on failure * Note2: call with calling stream lock + link lock + * + * Locking: + * When @stream_lock is false, it takes buffer-access lock for all substreams. + * OTOH, when @stream_lock is true, takes substream lock except for the + * target substream (that should have taken its lock before calling this). */ static int snd_pcm_action_group(const struct action_ops *ops, struct snd_pcm_substream *substream, snd_pcm_state_t state, bool stream_lock) { - struct snd_pcm_substream *s = NULL; - struct snd_pcm_substream *s1; - int res = 0, depth = 1; + struct snd_pcm_substream *s, *s1, *last; + int res = 0, depth; + /* the caller already holds the target stream lock at depth 0 */ + depth = stream_lock ? 1 : 0; + + last = NULL; snd_pcm_group_for_each_entry(s, substream) { - if (s != substream) { - if (!stream_lock) - mutex_lock_nested(&s->runtime->buffer_mutex, depth); - else if (s->pcm->nonatomic) + if (!stream_lock) { + res = __snd_pcm_buffer_access_lock(s->runtime, depth); + if (res < 0) + goto _unlock; + depth++; + } else if (s != substream) { + if (s->pcm->nonatomic) mutex_lock_nested(&s->self_group.mutex, depth); else spin_lock_nested(&s->self_group.lock, depth); depth++; } + last = s; res = ops->pre_action(s, state); if (res < 0) goto _unlock; @@ -1351,7 +1369,6 @@ static int snd_pcm_action_group(const struct action_ops *ops, ops->undo_action(s1, state); } } - s = NULL; /* unlock all */ goto _unlock; } } @@ -1359,17 +1376,19 @@ static int snd_pcm_action_group(const struct action_ops *ops, ops->post_action(s, state); } _unlock: + if (!last) + return res; /* unlock streams */ - snd_pcm_group_for_each_entry(s1, substream) { - if (s1 != substream) { - if (!stream_lock) - mutex_unlock(&s1->runtime->buffer_mutex); - else if (s1->pcm->nonatomic) - mutex_unlock(&s1->self_group.mutex); + snd_pcm_group_for_each_entry(s, substream) { + if (!stream_lock) { + snd_pcm_buffer_access_unlock(s->runtime); + } else if (s != substream) { + if (s->pcm->nonatomic) + mutex_unlock(&s->self_group.mutex); else - spin_unlock(&s1->self_group.lock); + spin_unlock(&s->self_group.lock); } - if (s1 == s) /* end */ + if (s == last) /* end */ break; } return res; @@ -1496,13 +1515,13 @@ static int snd_pcm_action_nonatomic(const struct action_ops *ops, /* Guarantee the group members won't change during non-atomic action */ guard(rwsem_read)(&snd_pcm_link_rwsem); + if (snd_pcm_stream_linked(substream)) + return snd_pcm_action_group(ops, substream, state, false); + res = snd_pcm_buffer_access_lock(substream->runtime); if (res < 0) return res; - if (snd_pcm_stream_linked(substream)) - res = snd_pcm_action_group(ops, substream, state, false); - else - res = snd_pcm_action_single(ops, substream, state); + res = snd_pcm_action_single(ops, substream, state); snd_pcm_buffer_access_unlock(substream->runtime); return res; } From 39d0b8bd61d986e5a710e45a822f85156f710dfa Mon Sep 17 00:00:00 2001 From: Takashi Iwai Date: Thu, 19 Nov 2026 13:23:53 +0100 Subject: [PATCH 1299/2102] ALSA: pcm: Simplify PCM buffer access gate with auto-cleanup helpers There are a few places to grant the PCM buffer access with the gate using runtime->buffer_accessing. They are paired like below in each place: if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) return -EBUSY; .... atomic_dec(&runtime->buffer_accessing); which is not really intuitive and error-prone, as being open-coded. This patch introduces helper macros to replace the code like the above with auto-cleanup. With the new helper, the above will become SND_PCM_BUFFER_ACQUIRE(runtime, lock); if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) return -EBUSY; .... and the counter-part (atomic_dec()) is dropped as it's automagically done by the auto-cleanup. Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261119122356.2134523-3-tiwai@suse.de --- sound/core/pcm_lib.c | 7 +++--- sound/core/pcm_local.h | 26 +++++++++++++++++++++++ sound/core/pcm_native.c | 47 ++++++++++++++++------------------------- 3 files changed, 47 insertions(+), 33 deletions(-) diff --git a/sound/core/pcm_lib.c b/sound/core/pcm_lib.c index bb16738bb59195..3b66677c037a6f 100644 --- a/sound/core/pcm_lib.c +++ b/sound/core/pcm_lib.c @@ -2377,10 +2377,9 @@ snd_pcm_sframes_t __snd_pcm_lib_xfer(struct snd_pcm_substream *substream, err = -EINVAL; goto _end_unlock; } - if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) { - err = -EBUSY; + err = snd_pcm_buffer_access_get(runtime); + if (err < 0) goto _end_unlock; - } snd_pcm_stream_unlock_irq(substream); if (!is_playback) snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_CPU); @@ -2389,7 +2388,7 @@ snd_pcm_sframes_t __snd_pcm_lib_xfer(struct snd_pcm_substream *substream, if (is_playback) snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_DEVICE); snd_pcm_stream_lock_irq(substream); - atomic_dec(&runtime->buffer_accessing); + snd_pcm_buffer_access_put(runtime); if (err < 0) goto _end_unlock; err = pcm_accessible_state(substream); diff --git a/sound/core/pcm_local.h b/sound/core/pcm_local.h index 4b134d435c24f3..7762c89e0f9ffd 100644 --- a/sound/core/pcm_local.h +++ b/sound/core/pcm_local.h @@ -86,4 +86,30 @@ static inline void snd_pcm_dma_buffer_sync(struct snd_pcm_substream *substream, #define is_oss_stream(substream) false #endif +/* + * helpers for restricting hw_params / hw_refine changes + */ +static inline int snd_pcm_buffer_access_get(struct snd_pcm_runtime *runtime) +{ + if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + return -EBUSY; + return 0; +} + +static inline void snd_pcm_buffer_access_put(struct snd_pcm_runtime *runtime) +{ + atomic_dec(&runtime->buffer_accessing); +} + +/* auto-cleanup macros */ +DEFINE_GUARD(snd_pcm_buffer_access, struct snd_pcm_runtime *, + snd_pcm_buffer_access_get(_T), snd_pcm_buffer_access_put(_T)); +DEFINE_GUARD_COND(snd_pcm_buffer_access, _try, + snd_pcm_buffer_access_get(_T), _RET == 0); + +#define SND_PCM_BUFFER_ACQUIRE(runtime, var) \ + ACQUIRE(snd_pcm_buffer_access_try, var)(runtime) +#define SND_PCM_BUFFER_ACQUIRE_ERR(var) \ + ACQUIRE_ERR(snd_pcm_buffer_access_try, &(var)) + #endif /* __SOUND_CORE_PCM_LOCAL_H */ diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c index d630bc290959b8..7e7465c2b6edfc 100644 --- a/sound/core/pcm_native.c +++ b/sound/core/pcm_native.c @@ -3147,7 +3147,8 @@ static snd_pcm_sframes_t snd_pcm_rewind(struct snd_pcm_substream *substream, return 0; /* Keep the DMA buffer alive through the sync below. */ - if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) return -EBUSY; scoped_guard(pcm_stream_lock_irq, substream) { ret = do_pcm_hwsync(substream); @@ -3157,7 +3158,6 @@ static snd_pcm_sframes_t snd_pcm_rewind(struct snd_pcm_substream *substream, } if (ret >= 0) snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_DEVICE); - atomic_dec(&runtime->buffer_accessing); return ret; } @@ -3171,7 +3171,8 @@ static snd_pcm_sframes_t snd_pcm_forward(struct snd_pcm_substream *substream, return 0; /* Keep the DMA buffer alive through the sync below. */ - if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) return -EBUSY; scoped_guard(pcm_stream_lock_irq, substream) { ret = do_pcm_hwsync(substream); @@ -3181,7 +3182,6 @@ static snd_pcm_sframes_t snd_pcm_forward(struct snd_pcm_substream *substream, } if (ret >= 0) snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_DEVICE); - atomic_dec(&runtime->buffer_accessing); return ret; } @@ -3192,7 +3192,8 @@ static int snd_pcm_delay(struct snd_pcm_substream *substream, int err; /* Keep the DMA buffer alive through the sync below. */ - if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) return -EBUSY; scoped_guard(pcm_stream_lock_irq, substream) { err = do_pcm_hwsync(substream); @@ -3200,7 +3201,6 @@ static int snd_pcm_delay(struct snd_pcm_substream *substream, *delay = snd_pcm_calc_delay(substream); } snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_CPU); - atomic_dec(&runtime->buffer_accessing); return err; } @@ -4104,32 +4104,23 @@ int snd_pcm_mmap_data(struct snd_pcm_substream *substream, struct file *file, } runtime = substream->runtime; /* don't race with buffer reallocation in hw_params/hw_free */ - if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) return -EBUSY; - if (runtime->state == SNDRV_PCM_STATE_OPEN) { - err = -EBADFD; - goto out; - } - if (!(runtime->info & SNDRV_PCM_INFO_MMAP)) { - err = -ENXIO; - goto out; - } + if (runtime->state == SNDRV_PCM_STATE_OPEN) + return -EBADFD; + if (!(runtime->info & SNDRV_PCM_INFO_MMAP)) + return -ENXIO; if (runtime->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED || - runtime->access == SNDRV_PCM_ACCESS_RW_NONINTERLEAVED) { - err = -EINVAL; - goto out; - } + runtime->access == SNDRV_PCM_ACCESS_RW_NONINTERLEAVED) + return -EINVAL; size = area->vm_end - area->vm_start; offset = area->vm_pgoff << PAGE_SHIFT; dma_bytes = PAGE_ALIGN(runtime->dma_bytes); - if ((size_t)size > dma_bytes) { - err = -EINVAL; - goto out; - } - if (offset > dma_bytes - size) { - err = -EINVAL; - goto out; - } + if ((size_t)size > dma_bytes) + return -EINVAL; + if (offset > dma_bytes - size) + return -EINVAL; area->vm_ops = &snd_pcm_vm_ops_data; area->vm_private_data = substream; @@ -4139,8 +4130,6 @@ int snd_pcm_mmap_data(struct snd_pcm_substream *substream, struct file *file, err = snd_pcm_lib_default_mmap(substream, area); if (!err) atomic_inc(&substream->mmap_count); -out: - atomic_dec(&runtime->buffer_accessing); return err; } EXPORT_SYMBOL(snd_pcm_mmap_data); From 943f1b0dff8afb8e88dae7cd011e3f0fa765675a Mon Sep 17 00:00:00 2001 From: Takashi Iwai Date: Thu, 19 Nov 2026 13:23:54 +0100 Subject: [PATCH 1300/2102] ALSA: pcm: Avoid hw_params/hw_refine changes during PCM buffer access While we've already protected the concurrent hw_params or hw_free changes during the PCM streaming in snd_pcm_lib_read*() and snd_pcm_lib_write*(), those entry points aren't covered by the buffer access gate yet, hence the associated PCM runtime instance may still change concurrently. This can lead to the inconsistency, e.g. in snd_pcm_xfern_frames_ioctl() or other places that refers to the runtime attribute like runtime->channel; since the concurrent hw_params may change the runtime->channel afterwards, this can result in OOB access for the array allocated for a different size with the former runtime->channels. For avoiding such races, let's take the buffer access gate at those ioctls and read/write ops from the beginning. Reported-by: on Sim Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261119122356.2134523-4-tiwai@suse.de --- sound/core/pcm_compat.c | 3 +++ sound/core/pcm_native.c | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/sound/core/pcm_compat.c b/sound/core/pcm_compat.c index c54cb07304ad49..c5931fdfe1f54d 100644 --- a/sound/core/pcm_compat.c +++ b/sound/core/pcm_compat.c @@ -338,6 +338,9 @@ static int snd_pcm_ioctl_xfern_compat(struct snd_pcm_substream *substream, return -ENOTTY; if (substream->stream != dir) return -EINVAL; + SND_PCM_BUFFER_ACQUIRE(substream->runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_OPEN) return -EBADFD; diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c index 7e7465c2b6edfc..897975e43a9bd6 100644 --- a/sound/core/pcm_native.c +++ b/sound/core/pcm_native.c @@ -3441,6 +3441,9 @@ static int snd_pcm_xfern_frames_ioctl(struct snd_pcm_substream *substream, void *bufs __free(kfree) = NULL; snd_pcm_sframes_t result; + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_OPEN) return -EBADFD; if (runtime->channels > 128) @@ -3680,6 +3683,9 @@ static ssize_t snd_pcm_read(struct file *file, char __user *buf, size_t count, if (PCM_RUNTIME_CHECK(substream)) return -ENXIO; runtime = substream->runtime; + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_state_open_or_disconnected(substream)) return -EBADFD; if (!frame_aligned(runtime, count)) @@ -3704,6 +3710,9 @@ static ssize_t snd_pcm_write(struct file *file, const char __user *buf, if (PCM_RUNTIME_CHECK(substream)) return -ENXIO; runtime = substream->runtime; + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_state_open_or_disconnected(substream)) return -EBADFD; if (!frame_aligned(runtime, count)) @@ -3730,6 +3739,9 @@ static ssize_t snd_pcm_readv(struct kiocb *iocb, struct iov_iter *to) if (PCM_RUNTIME_CHECK(substream)) return -ENXIO; runtime = substream->runtime; + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_state_open_or_disconnected(substream)) return -EBADFD; if (!user_backed_iter(to)) @@ -3769,6 +3781,9 @@ static ssize_t snd_pcm_writev(struct kiocb *iocb, struct iov_iter *from) if (PCM_RUNTIME_CHECK(substream)) return -ENXIO; runtime = substream->runtime; + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_state_open_or_disconnected(substream)) return -EBADFD; if (!user_backed_iter(from)) From 9d30450b6ac8cfc827be3d38f4f5ee86f68687ad Mon Sep 17 00:00:00 2001 From: "chris@kode54.net" Date: Fri, 20 Nov 2026 04:03:47 -0800 Subject: [PATCH 1301/2102] ALSA: usb-audio: Ignore trailing whitespace in quirk_flags Writing a flag name to the quirk_flags module parameter through sysfs with echo leaves a trailing newline on the string. The parser keeps it as part of the last flag name, so a valid flag is rejected: snd_usb_audio: unknown flag SKIP_IFACE_SETUP while parsing param quirk_flags Numeric flags are not affected because kstrtou64() accepts a trailing newline. Strip leading and trailing whitespace before parsing. Fixes: ffd586126a82 ("ALSA: usb-audio: improve module param quirk_flags") Assisted-by: AI Signed-off-by: Christopher Snowhill Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261120120356.10909-2-chris@kode54.net --- sound/usb/quirks.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/usb/quirks.c b/sound/usb/quirks.c index a4eb0d0cdf4ba4..24b67a85cec90a 100644 --- a/sound/usb/quirks.c +++ b/sound/usb/quirks.c @@ -3059,7 +3059,7 @@ void snd_usb_init_quirk_flags_parse_string(struct snd_usb_audio *chip, if (!val) return; - for (p = val; p && *p;) { + for (p = strim(val); p && *p;) { /* Each entry consists of VID:PID:flags */ field = strsep(&p, ":"); if (!field) From 4fc210ff1deaa67579b4f36c820a91c0a222e363 Mon Sep 17 00:00:00 2001 From: "chris@kode54.net" Date: Fri, 20 Nov 2026 04:03:48 -0800 Subject: [PATCH 1302/2102] ALSA: usb-audio: Add quirk flags for Logitech PRO X 2 LIGHTSPEED The receiver of the Logitech PRO X 2 LIGHTSPEED headset (046d:0af7) resets itself on ordinary requests such as SET_INTERFACE when it has been hotplugged and not yet gone through a reset of its own. When the probe-time interface setup runs shortly after configuration, the receiver can instead stop answering control requests altogether until its watchdog resets it about 77 seconds later, and the headset may not pair afterwards. Skip the probe-time interface setup, so that the first alt setting change happens at stream open. The receiver still resets once there, but re-enumerates within half a second and then works normally. Also set IFACE_DELAY: the delay after SET_INTERFACE lets the receiver drop off before the sample rate request is sent; otherwise that request is in flight when the device disappears and the disconnect waits for the control message timeout, delaying recovery by five seconds. Keep CTL_MSG_DELAY_1M from the Logitech vendor entry, which a device entry replaces. A receiver that is present at boot is not affected. Assisted-by: AI Signed-off-by: Christopher Snowhill Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261120120356.10909-3-chris@kode54.net --- sound/usb/quirks.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sound/usb/quirks.c b/sound/usb/quirks.c index 24b67a85cec90a..08ee7bc1c57b00 100644 --- a/sound/usb/quirks.c +++ b/sound/usb/quirks.c @@ -2552,6 +2552,9 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { DEVICE_FLG(0x046d, 0x0aba, /* Logitech PRO X Wireless */ QUIRK_FLAG_MIXER_GET_CUR_OK | QUIRK_FLAG_MIXER_PLAYBACK_MIN_MUTE), + DEVICE_FLG(0x046d, 0x0af7, /* Logitech PRO X 2 LIGHTSPEED */ + QUIRK_FLAG_CTL_MSG_DELAY_1M | QUIRK_FLAG_SKIP_IFACE_SETUP | + QUIRK_FLAG_IFACE_DELAY), DEVICE_FLG(0x0499, 0x1506, /* Yamaha THR5 */ QUIRK_FLAG_GENERIC_IMPLICIT_FB), DEVICE_FLG(0x0499, 0x1509, /* Steinberg UR22 */ From d1458f8c2282975f2bd7467cd3c3cf4c0c58c1ca Mon Sep 17 00:00:00 2001 From: Akhil Arul Date: Fri, 20 Nov 2026 18:27:29 +0530 Subject: [PATCH 1303/2102] ALSA: hda/tas2781-spi: Set tas_hda->dev in probe tas2781_hda_remove() is shared by the I2C and SPI drivers and uses tas_hda->dev for component_del() and for the runtime PM calls. The I2C probe sets that field, the SPI probe does not, so for SPI it stays NULL from the devm_kzalloc(). Unbinding the device through sysfs then warns in component_del() and crashes on the NULL device in pm_runtime_get_sync(): WARNING: drivers/base/component.c:839 at component_del+0x149/0x170 Call Trace: tas2781_hda_remove+0x16/0x60 [snd_hda_scodec_tas2781] device_release_driver_internal+0x19e/0x200 unbind_store+0xa4/0xb0 Oops: general protection fault, kernel NULL pointer dereference 0x1d1 RIP: 0010:__pm_runtime_resume+0x1a/0x90 tas2781_hda_remove+0x23/0x60 [snd_hda_scodec_tas2781] The same path runs from the driver remove callback and from the component_add() failure path in tas2781_hda_spi_probe(). Before the common library was introduced, the SPI driver had its own remove function that used tas_priv->dev. Set tas_hda->dev in tas2781_hda_spi_probe(), as the I2C driver does. Tested the probe/unbind path with KASAN and lockdep enabled: without this change, unbinding the device gives the warning and oops above; with it, unbind, bind and unbind again complete without any splat. Fixes: 28a09d9e42c5 ("ALSA: hda/tas2781: Create an independent lib to save the shared parts for both SPI and I2C driver") Reported-by: Carmel Okun Closes: https://lore.kernel.org/linux-sound/AS2PR02MB10038DB2CE8CAE659D35B9F1AC8792@AS2PR02MB10038.eurprd02.prod.outlook.com/ Cc: stable@vger.kernel.org Signed-off-by: Akhil Arul Link: https://patch.msgid.link/20261120125729.135171-1-akhilarul324@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/side-codecs/tas2781_hda_spi.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/hda/codecs/side-codecs/tas2781_hda_spi.c b/sound/hda/codecs/side-codecs/tas2781_hda_spi.c index 0951a950d585b7..0c68c5b3348c71 100644 --- a/sound/hda/codecs/side-codecs/tas2781_hda_spi.c +++ b/sound/hda/codecs/side-codecs/tas2781_hda_spi.c @@ -780,6 +780,7 @@ static int tas2781_hda_spi_probe(struct spi_device *spi) if (!hda_priv) return -ENOMEM; + tas_hda->dev = &spi->dev; tas_hda->hda_priv = hda_priv; spi->max_speed_hz = TAS2781_SPI_MAX_FREQ; From d7f2d9b6c7d0ff0af7d19d889810d35dfe07da90 Mon Sep 17 00:00:00 2001 From: Jingxuan Xie Date: Wed, 18 Nov 2026 13:54:43 +0000 Subject: [PATCH 1304/2102] af_packet: avoid waiting for TPACKET_V3 copies at retirement TPACKET_V3 retires a full or expired block while holding sk_receive_queue.lock. prb_retire_current_block() takes blk_fill_in_prog_lock for write to wait for in-flight skb_copy_bits() before publishing the block. On PREEMPT_RT a read lock can be held by a task that has been preempted or is running on another CPU. The packet path or the retirement timer then blocks on the write lock while holding sk_receive_queue.lock, and the receive path resumes only after the copy completes. This was observed as a receive stall of hundreds of milliseconds in a PREEMPT_RT deployment; manual inspection found the same unconditional write_lock() in both the full-block and the timer retirement paths. Try to take the write lock without blocking on PREEMPT_RT. If a copy is still in progress, leave the current block and its metadata untouched: - the retirement timer re-arms itself and retries after the configured interval; - packet allocation returns NULL, so tpacket_rcv() drops this capture record and accounts it in tp_drops, while the original packet remains in the network stack; - a later packet can retire the block once the copier has finished. Do not dispatch the next block while the current block is still open. The existing lock order and completion ordering are preserved, and no new state or worker is introduced. The trade-off is a higher capture drop rate while a copy is in progress; original traffic is unaffected. Non-PREEMPT_RT kernels keep the unconditional write_lock(): there read_lock() disables preemption, so the writer only waits for the copy to finish, not for a scheduled-out task to run again. The stall was reproduced on QEMU arm64 SMP PREEMPT_RT by delaying a copier after frame reservation: without this change the next sender blocks until the copier is released, with this change only that capture record is dropped. Fixes: 632ca50f2cbd ("af_packet: TPACKET_V3: replace busy-wait loop") Signed-off-by: Jingxuan Xie Reviewed-by: Willem de Bruijn Link: https://patch.msgid.link/20261118135443.24767-1-jingxuanxie@deeproute.ai Signed-off-by: Jakub Kicinski --- net/packet/af_packet.c | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/net/packet/af_packet.c b/net/packet/af_packet.c index 73222563fb7049..e0ebd0627509f7 100644 --- a/net/packet/af_packet.c +++ b/net/packet/af_packet.c @@ -200,7 +200,7 @@ static void packet_increment_head(struct packet_ring_buffer *buff); static int prb_curr_blk_in_use(struct tpacket_block_desc *); static void *prb_dispatch_next_block(struct tpacket_kbdq_core *, struct packet_sock *); -static void prb_retire_current_block(struct tpacket_kbdq_core *, +static bool prb_retire_current_block(struct tpacket_kbdq_core *, struct packet_sock *, unsigned int status); static int prb_queue_frozen(struct tpacket_kbdq_core *); static void prb_open_block(struct tpacket_kbdq_core *, @@ -677,6 +677,24 @@ static void init_prb_bdqc(struct packet_sock *po, prb_open_block(p1, pbd); } +/* + * Wait for an in-flight skb_copy_bits() before retiring the current block. + * On PREEMPT_RT the read lock can be held by a task that has been preempted + * or is running on another CPU, so do not block while holding + * sk_receive_queue.lock; return false and let the caller retry. + */ +static bool prb_wait_for_copy_bits(struct tpacket_kbdq_core *pkc) +{ + if (IS_ENABLED(CONFIG_PREEMPT_RT)) { + if (!write_trylock(&pkc->blk_fill_in_prog_lock)) + return false; + } else { + write_lock(&pkc->blk_fill_in_prog_lock); + } + write_unlock(&pkc->blk_fill_in_prog_lock); + return true; +} + /* * With a 1MB block-size, on a 1Gbps line, it will take * i) ~8 ms to fill a block + ii) memcpy etc. @@ -711,9 +729,9 @@ static enum hrtimer_restart prb_retire_rx_blk_timer_expired(struct hrtimer *t) * */ if (BLOCK_NUM_PKTS(pbd)) { - /* Waiting for skb_copy_bits to finish... */ - write_lock(&pkc->blk_fill_in_prog_lock); - write_unlock(&pkc->blk_fill_in_prog_lock); + /* Retry later if a packet copy is still in progress. */ + if (!prb_wait_for_copy_bits(pkc)) + goto refresh_timer; } if (!frozen) { @@ -738,6 +756,7 @@ static enum hrtimer_restart prb_retire_rx_blk_timer_expired(struct hrtimer *t) } } +refresh_timer: hrtimer_forward_now(&pkc->retire_blk_timer, pkc->interval_ktime); spin_unlock(&po->sk.sk_receive_queue.lock); return HRTIMER_RESTART; @@ -946,7 +965,7 @@ static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc, return (void *)pkc->nxt_offset; } -static void prb_retire_current_block(struct tpacket_kbdq_core *pkc, +static bool prb_retire_current_block(struct tpacket_kbdq_core *pkc, struct packet_sock *po, unsigned int status) { struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc); @@ -963,13 +982,13 @@ static void prb_retire_current_block(struct tpacket_kbdq_core *pkc, * the timer-handler already handled this case. */ if (!(status & TP_STATUS_BLK_TMO)) { - /* Waiting for skb_copy_bits to finish... */ - write_lock(&pkc->blk_fill_in_prog_lock); - write_unlock(&pkc->blk_fill_in_prog_lock); + /* Do not wait for copies while holding the queue lock. */ + if (!prb_wait_for_copy_bits(pkc)) + return false; } prb_close_block(pkc, pbd, po, status); - return; } + return true; } static int prb_curr_blk_in_use(struct tpacket_block_desc *pbd) @@ -1097,7 +1116,8 @@ static void *__packet_lookup_frame_in_block(struct packet_sock *po, } /* Ok, close the current block */ - prb_retire_current_block(pkc, po, 0); + if (!prb_retire_current_block(pkc, po, 0)) + return NULL; /* Now, try to dispatch the next block */ curr = (char *)prb_dispatch_next_block(pkc, po); From 18a7abf1a0b168ea6a50f08562de2f286d6f5a86 Mon Sep 17 00:00:00 2001 From: Jiayuan Chen Date: Sun, 15 Nov 2026 22:45:07 +0800 Subject: [PATCH 1305/2102] ipv6, calipso: fix data-race in calipso_cache_add() bucketsize check Issue found by sashiko when reviewing my data-races patch [1]. This is not a plain READ_ONCE() annotation like the rest of that series but a real fix, so it is sent separately. calipso_cache_add() reads calipso_cache_bucketsize twice: the "<= 0" guard on entry, then the "size < bucketsize" test after taking the bucket lock. A writer can flip it to 0 in between: CPU0 CPU1 calipso_cache_add() calipso_cache_bucketsize == 10 (> 0) proc_dointvec() calipso_cache_bucketsize = 0 spin_lock_bh(&bucket.lock) size(0) < calipso_cache_bucketsize(0) -> false -> else branch, but the bucket is empty On an empty bucket the else branch takes list.prev (the list head itself), list_del()s it and then list_add()s through the now poisoned head: Oops: general protection fault, probably for non-canonical address 0xdead000000000108 RIP: 0010:calipso_cache_add+0x2f0/0x380 Call Trace: calipso_cache_add+0x4c/0x70 netlbl_cache_add+0x4a/0xa0 selinux_netlbl_skbuff_getsid+0x1ac/0x280 selinux_skb_peerlbl_sid+0x7d/0x100 selinux_socket_sock_rcv_skb+0x2d3/0x460 security_sock_rcv_skb+0x86/0x150 sk_filter_trim_cap+0x56/0x730 sock_queue_rcv_skb_reason+0x1e/0x80 rawv6_rcv+0x679/0xb20 raw6_local_deliver+0x1f0/0x5b0 ip6_protocol_deliver_rcu+0x215/0x9a0 ip6_input_finish+0xb0/0x1b0 ip6_input+0xa8/0x250 ipv6_rcv+0x14b/0x1c0 __netif_receive_skb_one_core+0x8f/0xe0 __netif_receive_skb+0x23/0xb0 process_backlog+0x27a/0x950 __napi_poll.constprop.0+0x61/0x2c0 net_rx_action+0x372/0x800 handle_softirqs+0x109/0x570 __do_softirq+0x10/0x18 do_softirq.part.0+0x47/0xd0 __local_bh_enable_ip+0xf0/0x120 __dev_queue_xmit+0x578/0x23f0 neigh_resolve_output+0x278/0x3c0 ip6_finish_output2+0x4b1/0xcb0 ip6_finish_output+0x2b6/0x6b0 ip6_output+0x122/0x400 ip6_local_out+0x61/0xb0 ip6_send_skb+0xa0/0x260 ip6_push_pending_frames+0x2b/0x40 rawv6_sendmsg+0x1b7a/0x2750 inet_sendmsg+0xa1/0xb0 __sys_sendto+0x2fe/0x350 __x64_sys_sendto+0x7f/0xb0 do_syscall_64+0xe1/0x450 entry_SYSCALL_64_after_hwframe+0x76/0x7e Snapshot the sysctl into a local once and use it for both tests, like cipso_v4_cache_add() has since commit dd44f04b9214 ("cipso: Fix data-races around sysctl."). [1] https://lore.kernel.org/netdev/179428999963.994134.16904544500890053668@kernel.org/ Fixes: 4fee5242bf41 ("calipso: Add a label cache.") Signed-off-by: Jiayuan Chen Acked-by: Paul Moore Link: https://patch.msgid.link/20261115144508.71543-1-jiayuan.chen@linux.dev Signed-off-by: Jakub Kicinski --- net/ipv6/calipso.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/net/ipv6/calipso.c b/net/ipv6/calipso.c index 4cd0ae9313b322..d7838451db0958 100644 --- a/net/ipv6/calipso.c +++ b/net/ipv6/calipso.c @@ -263,13 +263,14 @@ static int calipso_cache_check(const unsigned char *key, static int calipso_cache_add(const unsigned char *calipso_ptr, const struct netlbl_lsm_secattr *secattr) { + int bkt_size = READ_ONCE(calipso_cache_bucketsize); int ret_val = -EPERM; u32 bkt; struct calipso_map_cache_entry *entry = NULL; struct calipso_map_cache_entry *old_entry = NULL; u32 calipso_ptr_len; - if (!calipso_cache_enabled || calipso_cache_bucketsize <= 0) + if (!calipso_cache_enabled || bkt_size <= 0) return 0; calipso_ptr_len = calipso_ptr[1]; @@ -289,7 +290,7 @@ static int calipso_cache_add(const unsigned char *calipso_ptr, bkt = entry->hash & (CALIPSO_CACHE_BUCKETS - 1); spin_lock_bh(&calipso_cache[bkt].lock); - if (calipso_cache[bkt].size < calipso_cache_bucketsize) { + if (calipso_cache[bkt].size < bkt_size) { list_add(&entry->list, &calipso_cache[bkt].list); calipso_cache[bkt].size += 1; } else { From fdb6fcabdbb8247f1647d54fb1b9dc3575d7fcc8 Mon Sep 17 00:00:00 2001 From: Imre Kaloz Date: Mon, 16 Nov 2026 00:08:12 +0100 Subject: [PATCH 1306/2102] net: marvell: prestera: disable port before changing its MAC mode prestera_pcs_config() writes a new mode, speed or inband setting to an enabled port. The firmware can then report link down until the port is disabled and enabled again. Disable the port before such a write. 2500BASE-X and SGMII share one MAC mode, so SGMII sets its own speed and the speed is compared as well. Exercising this needs a link partner, so no in-tree test covers it. Before this patch, the SFP+ ports (S-RJ01 module in sfp-52) on a Delta TN48M (98DX3265) with firmware 4.1.0 come up in 21 of 30 attempts. 30 out of 30 with the patch. Fixes: 52323ef75414 ("net: marvell: prestera: add phylink support") Signed-off-by: Imre Kaloz Reviewed-by: Elad Nachman Link: https://patch.msgid.link/20261115230812.29644-1-kaloz@kernel.org Signed-off-by: Jakub Kicinski --- .../ethernet/marvell/prestera/prestera_main.c | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/marvell/prestera/prestera_main.c b/drivers/net/ethernet/marvell/prestera/prestera_main.c index a82e7a80298513..3173145573600d 100644 --- a/drivers/net/ethernet/marvell/prestera/prestera_main.c +++ b/drivers/net/ethernet/marvell/prestera/prestera_main.c @@ -307,13 +307,14 @@ static int prestera_pcs_config(struct phylink_pcs *pcs, unsigned int neg_mode, bool permit_pause_to_mac) { struct prestera_port *port = prestera_pcs_to_port(pcs); - struct prestera_port_mac_config cfg_mac; + struct prestera_port_mac_config cfg_mac, old; int err; err = prestera_port_cfg_mac_read(port, &cfg_mac); if (err) return err; + old = cfg_mac; cfg_mac.admin = true; cfg_mac.fec = PRESTERA_PORT_FEC_OFF; cfg_mac.inband = neg_mode == PHYLINK_PCS_NEG_INBAND_ENABLED; @@ -329,6 +330,7 @@ static int prestera_pcs_config(struct phylink_pcs *pcs, unsigned int neg_mode, cfg_mac.mode = PRESTERA_MAC_MODE_SGMII; break; case PHY_INTERFACE_MODE_SGMII: + cfg_mac.speed = SPEED_1000; cfg_mac.mode = PRESTERA_MAC_MODE_SGMII; break; case PHY_INTERFACE_MODE_1000BASEX: @@ -339,6 +341,19 @@ static int prestera_pcs_config(struct phylink_pcs *pcs, unsigned int neg_mode, break; } + /* Firmware may not report link up after the mode, speed or inband + * setting of an enabled port changes until the port is disabled and + * re-enabled. + */ + if (old.admin && (old.mode != cfg_mac.mode || + old.speed != cfg_mac.speed || + old.inband != cfg_mac.inband)) { + old.admin = false; + err = prestera_port_cfg_mac_write(port, &old); + if (err) + return err; + } + err = prestera_port_cfg_mac_write(port, &cfg_mac); if (err) return err; From bfccb4e44e4725270ccef366078d7b6063920ff3 Mon Sep 17 00:00:00 2001 From: Gal Pressman Date: Wed, 18 Nov 2026 16:36:53 +0200 Subject: [PATCH 1307/2102] net/mlx5e: Release FIB event work flows before dropping RTNL The FIB event work, neigh update work and the neigh stats work all use flow->tmp_list to hold the encap flows they work on, while RTNL is what keeps them from using it at the same time. mlx5e_tc_fib_event_work() drops RTNL before it is done with its list. A neigh work can then take the same flows while the FIB work is still walking them, and the two overwrite each other's list. Release the flow list before dropping RTNL. The issue was hit once in our regression testing (OVS connection tracking with the VXLAN endpoint on a VF, KASAN build): BUG: KASAN: stack-out-of-bounds in mlx5e_flow_put+0x23/0x80 [mlx5_core] Write of size 4 at addr ffff8881226d7b20 by task kworker/u40:1/20171 Workqueue: mlx5e mlx5e_tc_fib_event_work [mlx5_core] Call Trace: mlx5e_flow_put+0x23/0x80 [mlx5_core] mlx5e_put_flow_list+0x82/0xe0 [mlx5_core] mlx5e_tc_fib_event_work+0x704/0x1fb0 [mlx5_core] process_one_work+0x8df/0x1660 The race was also reproduced with an msleep() inserted between rtnl_unlock() and mlx5e_put_flow_list() to widen the window, a VXLAN encap rule whose endpoint IP is on a VF, and route churn on the endpoint address. Fixes: 8914add2c9e5 ("net/mlx5e: Handle FIB events to update tunnel endpoint device") Signed-off-by: Gal Pressman Reviewed-by: Jianbo Liu Signed-off-by: Tariq Toukan Link: https://patch.msgid.link/20261118143653.1915247-1-tariqt@nvidia.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/mellanox/mlx5/core/en/tc_tun_encap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en/tc_tun_encap.c b/drivers/net/ethernet/mellanox/mlx5/core/en/tc_tun_encap.c index 5e40107efa266a..4f9f8beffbc8db 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en/tc_tun_encap.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en/tc_tun_encap.c @@ -1718,9 +1718,9 @@ static void mlx5e_tc_fib_event_work(struct work_struct *work) r->flags |= MLX5E_ROUTE_ENTRY_VALID; out: mutex_unlock(&esw->offloads.encap_tbl_lock); + mlx5e_put_flow_list(priv, &flow_list); rtnl_unlock(); - mlx5e_put_flow_list(priv, &flow_list); mlx5e_route_put(priv, event_data->r); dev_put(event_data->ul_dev); kfree(event_data); From 7a505bb0168a132c2a3ab4efff4c6d6474ca3aa1 Mon Sep 17 00:00:00 2001 From: Eric Dumazet Date: Tue, 17 Nov 2026 20:06:12 +0530 Subject: [PATCH 1308/2102] net: clear skb->mac_len in skb_unset_mac_header() skb_unset_mac_header() marks the mac header as unset but leaves skb->mac_len alone, so an skb can end up with no mac header and a non-zero mac_len. Code that uses mac_len to decide whether a mac header is present is then misled. end_dt_vrf_rcv() (SRv6 End.DT4/End.DT6) unsets the mac header of the decapsulated packet so that the VRF device can rebuild it. The VRF device only does so when a packet sniffer is attached, so without one the skb continues up the stack with mac_len == 14. In xfrm4_remove_tunnel_encap() and xfrm6_remove_tunnel_encap(), skb_mac_header_rebuild() is a no-op for such an skb, and the following if (skb->mac_len) eth_hdr(skb)->h_proto = skb->protocol; writes two bytes at skb->head + 0xffff + offsetof(struct ethhdr, h_proto): BUG: KASAN: slab-out-of-bounds in xfrm4_remove_tunnel_encap+0x17d/0x220 Write of size 2 at addr ffff88805f85800b by task syz-executor/10831 xfrm4_remove_tunnel_encap xfrm_input xfrm4_esp_rcv ip_protocol_deliver_rcu ip_local_deliver_finish seg6_local_input_core lwtunnel_input __netif_receive_skb netif_receive_skb tun_rx_batched tun_get_user __input_process_payload() in net/xfrm/xfrm_iptfs.c has the same three lines and reported as a use-after-free rather than an out-of-bounds. The address written is fixed relative to skb->head, so what it lands in is whatever the allocator placed sixteen pages past the skb: a live object gives slab-out-of-bounds, a freed one or a page back on the buddy free list gives use-after-free, and a different live object gives no report at all. Clearing mac_len at the source makes the guard false at all three sites. Clear mac_len in skb_unset_mac_header() so that all callers leave the skb in a consistent state, and remove the now redundant assignment in skb_carve_reset_headers(). The other callers are on egress paths (__bpf_redirect_neigh(), bpf_lwt_push_ip_encap()) or only reach the helper when the mac header was already unset (bpf_update_srh_state()), and do not read mac_len afterwards. vrf_prepare_mac_header(), the rebuild end_dt_vrf_rcv() unsets the header for, pushes ETH_HLEN and then calls skb_reset_mac_header() and skb_reset_mac_len(), so it recomputes mac_len itself and never reads the stale value. The issue was reported on the list by Piyus Kedia and Kapil Vaswani, who found it by fuzzing with AI assistance and reproduced the KASAN splat on v7.4-rc3. Their reproducer was not published. Fixes: 664d6f86868b ("seg6: add support for the SRv6 End.DT4 behavior") Reported-by: Piyus Kedia Reported-by: Kapil Vaswani Closes: https://lore.kernel.org/netdev/20261116174531.2540348-2-piyus@iiitd.ac.in/ Suggested-by: Kapil Vaswani Suggested-by: Piyus Kedia Tested-by: Piyus Kedia Signed-off-by: Eric Dumazet Signed-off-by: Piyus Kedia Link: https://patch.msgid.link/20261117143612.95112-1-piyus@iiitd.ac.in Signed-off-by: Jakub Kicinski --- include/linux/skbuff.h | 1 + net/core/skbuff.c | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/include/linux/skbuff.h b/include/linux/skbuff.h index adc61f5e3e850f..cf6a8e64b40313 100644 --- a/include/linux/skbuff.h +++ b/include/linux/skbuff.h @@ -3187,6 +3187,7 @@ static inline u32 skb_mac_header_len(const struct sk_buff *skb) static inline void skb_unset_mac_header(struct sk_buff *skb) { skb->mac_header = (typeof(skb->mac_header))~0U; + skb->mac_len = 0; } static inline void skb_reset_mac_header(struct sk_buff *skb) diff --git a/net/core/skbuff.c b/net/core/skbuff.c index 74e9a96bc5df08..33735e8ca69be8 100644 --- a/net/core/skbuff.c +++ b/net/core/skbuff.c @@ -6988,7 +6988,6 @@ static void skb_carve_reset_headers(struct sk_buff *skb) skb_unset_mac_header(skb); skb_unset_transport_header(skb); skb_reset_network_header(skb); - skb->mac_len = 0; /* Inner offsets have no "unset" marker, zero them so that * skb_inner_network_header_was_set() becomes false and no From c0ec15a586556c11583d8e336c3963c231c379c3 Mon Sep 17 00:00:00 2001 From: Yevgeny Kliteynik Date: Wed, 18 Nov 2026 19:32:26 +0200 Subject: [PATCH 1309/2102] net/mlx5: HWS, Handle NULL in vport destination action creation mlx5hws_action_create_dest_vport() can return NULL. If this happens, xa_insert() will insert a NULL entry into the xarray. The next mlx5hws_action_create_dest_vport() failure will try to insert NULL again, but xa_insert() will return -EBUSY, because we already have NULL entry. In such case the code will go into error flow of action creation, and eventually will cause NULL dereference at hws_action_destroy_hws(). The issue was discovered by code inspection. Fixes: 8e2e08a6d1e0 ("net/mlx5: fs, add support for dest vport HWS action") Signed-off-by: Yevgeny Kliteynik Signed-off-by: Alex Vesker Reviewed-by: Erez Shitrit Signed-off-by: Tariq Toukan Link: https://patch.msgid.link/20261118173227.1957670-2-tariqt@nvidia.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c index cbcbc2b62809d7..de22e7279a312d 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c @@ -441,6 +441,8 @@ mlx5_fs_get_dest_action_vport(struct mlx5_fs_hws_context *fs_ctx, dest = mlx5hws_action_create_dest_vport(ctx, vport_num, vhca_id_valid, dest_attr->vport.vhca_id, flags); + if (!dest) + return NULL; err = xa_insert(dests_xa, idx, dest, GFP_KERNEL); if (err) { From 0e56ff4441eea333bfbfeff86ef39038f6e8c378 Mon Sep 17 00:00:00 2001 From: Yevgeny Kliteynik Date: Wed, 18 Nov 2026 19:32:27 +0200 Subject: [PATCH 1310/2102] net/mlx5: DR, Fix out-of-bounds write when sync to HW fails mlx5dr_icm_free_chunk() moves a freed chunk to the "hot" chunks array by writing it to hot_chunks_arr and, once the accumulated hot memory crosses a threshold, triggers a sync to HW that flushes the array. The array is large enough to hold the chunks of a single accumulation cycle, and relies on the sync path to flush it. However, if sync to HW fails, hot chunks array is not cleared, and every subsequent mlx5dr_icm_free_chunk will write past the end of hot_chunks_arr, resulting in an out-of-bounds write and kernel heap corruption. A failed sync to HW also means it is no longer safe to recycle ICM: a chunk's memory may only be returned to the buddy allocator (and thus be reused) after a sync has confirmed that HW no longer references it. The issue was discovered by a fuzzer that repeatedly triggered sync failure, at which point the out-of-bounds write was reported by KASAN: KASAN log excerpt: BUG: slab-out-of-bounds in mlx5dr_icm_free_chunk+0x4cd at call 2 (hot_chunks_num=3 > cap=2). Fix this by putting the pool into an error state on the first failed sync to HW, reporting the failure once. The sync is not retried, and while the pool is in this state: - mlx5dr_icm_free_chunk() doesn't queue freed chunks; the segment is left reserved and is reclaimed when the pool is destroyed. - mlx5dr_icm_alloc_chunk() doesn't serve new chunks. Fixes: 4519fc45beeb ("net/mlx5: DR, Keep track of hot ICM chunks in an array instead of list") Signed-off-by: Yevgeny Kliteynik Reviewed-by: Alex Vesker Signed-off-by: Tariq Toukan Link: https://patch.msgid.link/20261118173227.1957670-3-tariqt@nvidia.com Signed-off-by: Jakub Kicinski --- .../mlx5/core/steering/sws/dr_icm_pool.c | 32 +++++++++++++++++-- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/steering/sws/dr_icm_pool.c b/drivers/net/ethernet/mellanox/mlx5/core/steering/sws/dr_icm_pool.c index 1b928b40686e5b..a906a72601c4fa 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/steering/sws/dr_icm_pool.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/steering/sws/dr_icm_pool.c @@ -33,6 +33,11 @@ struct mlx5dr_icm_pool { u64 hot_memory_size; /* hot memory size threshold for triggering sync */ u64 th; + /* Set when a sync to HW fails - no new chunks are served, freed + * chunks are no longer queued, and their ICM is not returned to + * the buddy allocator. + */ + bool error_state; }; struct mlx5dr_icm_dm { @@ -368,7 +373,15 @@ static int dr_icm_pool_sync_all_buddy_pools(struct mlx5dr_icm_pool *pool) err = mlx5dr_cmd_sync_steering(pool->dmn->mdev); if (err) { - mlx5dr_err(pool->dmn, "Failed to sync to HW (err: %d)\n", err); + /* The hot chunks could not be flushed. Put the pool in an + * error state so that no further chunks are queued (which + * would overflow hot_chunks_arr), and no new chunks are + * served. The sync is not retried. + */ + mlx5dr_err(pool->dmn, + "Failed to sync to HW (err: %d), disabling ICM pool\n", + err); + pool->error_state = true; return err; } @@ -443,6 +456,10 @@ mlx5dr_icm_alloc_chunk(struct mlx5dr_icm_pool *pool, return NULL; mutex_lock(&pool->mutex); + + if (pool->error_state) + goto out; + /* find mem, get back the relevant buddy pool and seg in that mem */ ret = dr_icm_handle_buddies_get_mem(pool, chunk_size, &buddy, &seg); if (ret) @@ -475,6 +492,14 @@ void mlx5dr_icm_free_chunk(struct mlx5dr_icm_chunk *chunk) /* move the chunk to the waiting chunks array, AKA "hot" memory */ mutex_lock(&pool->mutex); + /* If the pool is in an error state, the chunk must not be queued. + * ICM memory is not returned to the buddy allocator - it is + * reclaimed only when the pool is destroyed. + * Just free the chunk's bookkeeping struct. + */ + if (pool->error_state) + goto out; + pool->hot_memory_size += mlx5dr_icm_pool_get_chunk_byte_size(chunk); hot_chunk = &pool->hot_chunks_arr[pool->hot_chunks_num++]; @@ -482,12 +507,13 @@ void mlx5dr_icm_free_chunk(struct mlx5dr_icm_chunk *chunk) hot_chunk->seg = chunk->seg; hot_chunk->size = chunk->size; - kmem_cache_free(chunks_cache, chunk); - /* Check if we have chunks that are waiting for sync-ste */ if (dr_icm_pool_is_sync_required(pool)) dr_icm_pool_sync_all_buddy_pools(pool); +out: + kmem_cache_free(chunks_cache, chunk); + mutex_unlock(&pool->mutex); } From 7bc16d84facd37b44ff508d4970bac6636329eb9 Mon Sep 17 00:00:00 2001 From: Dimitri Daskalakis Date: Tue, 17 Nov 2026 13:54:12 -0800 Subject: [PATCH 1311/2102] eth: fbnic: wait on the correct queues in fbnic_queue_stop() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fbnic_queue_stop() waits for every queue of the NAPI vector to go idle before tearing it down, using sub0.q_idx as the queue index. We set q_idx on submission queues for Tx, and completion queues on Rx, so this waits on queue 0 for every Rx queue. For non-combined channels, stopping an Rx queue always stops/wakes Tx queue 0. Set the queue id on Tx completion rings so we don't have to distinguish between ring types to get the correct queue id, and don't stop/wake disabled rings. This bug was found by AI and verified on HW. Reproduced by binding a devmem dmabuf to one Rx queue (netdev bind-rx). Added a printk to fbnic_wait_queue_idle(), and traced Tx queue stop/wake with bpftrace. combined 79, bind rxq 1: before: netif_stop_subqueue(1) fbnic_wait_queue_idle(tx, 1) fbnic_wait_queue_idle(rx, 0) netif_wake_subqueue(1) after: netif_stop_subqueue(1) fbnic_wait_queue_idle(tx, 1) fbnic_wait_queue_idle(rx, 1) netif_wake_subqueue(1) rx 34 tx 34, bind rxq 5: before: netif_stop_subqueue(0) fbnic_wait_queue_idle(tx, 0) fbnic_wait_queue_idle(rx, 0) netif_wake_subqueue(0) after: fbnic_wait_queue_idle(tx, 39) fbnic_wait_queue_idle(rx, 5) ^ no more stop/wake of Tx queue 0 (tx 39 is the XDP Tx queue of rxq 5's vector, Rx queues always get an XDP Tx queue) Fixes: da43127a8edc ("eth: fbnic: support queue ops / zero-copy Rx") Signed-off-by: Dimitri Daskalakis Reviewed-by: Björn Töpel Link: https://patch.msgid.link/20261117215416.1901246-2-dimitri.daskalakis1@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/meta/fbnic/fbnic_txrx.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c index c75c5683b724e8..9f96ed7d0300f6 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c @@ -1772,7 +1772,7 @@ static int fbnic_alloc_napi_vector(struct fbnic_dev *fbd, struct fbnic_net *fbn, /* Configure Tx completion queue */ db = &uc_addr[FBNIC_QUEUE(txq_idx) + FBNIC_QUEUE_TCQ_HEAD]; - fbnic_ring_init(&qt->cmpl, db, 0, 0); + fbnic_ring_init(&qt->cmpl, db, txq_idx, 0); /* Update Tx queue index */ txt_count--; @@ -3094,8 +3094,11 @@ static void __fbnic_nv_restart(struct fbnic_net *fbn, fbnic_wr32(fbd, FBNIC_INTR_SET(nv->v_idx / 32), BIT(nv->v_idx % 32)); fbnic_wrfl(fbd); - for (i = 0; i < nv->txt_count; i++) + for (i = 0; i < nv->txt_count; i++) { + if (nv->qt[i].sub0.flags & FBNIC_RING_F_DISABLED) + continue; netif_wake_subqueue(fbn->netdev, nv->qt[i].sub0.q_idx); + } fbnic_dbg_nv_init(nv); } @@ -3136,13 +3139,16 @@ static int fbnic_queue_stop(struct net_device *dev, void *qmem, int idx) napi_disable_locked(&nv->napi); fbnic_nv_irq_disable(nv); - for (i = 0; i < nv->txt_count; i++) + for (i = 0; i < nv->txt_count; i++) { + if (nv->qt[i].sub0.flags & FBNIC_RING_F_DISABLED) + continue; netif_stop_subqueue(dev, nv->qt[i].sub0.q_idx); + } fbnic_nv_disable(fbn, nv); for (t = 0; t < nv->txt_count + nv->rxt_count; t++) { err = fbnic_wait_queue_idle(fbn, t >= nv->txt_count, - nv->qt[t].sub0.q_idx); + nv->qt[t].cmpl.q_idx); if (err) goto err_restart; } From 561175f45a23527d2853e2b745d40bf963e87dce Mon Sep 17 00:00:00 2001 From: Dimitri Daskalakis Date: Tue, 17 Nov 2026 13:54:13 -0800 Subject: [PATCH 1312/2102] eth: fbnic: skip disabled Tx rings when setting the queue NAPI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When Rx and Tx channels are not combined, each Rx vector gets a Tx triad whose sub0 is disabled with a q_idx of 0. fbnic_set_netif_napi() and fbnic_reset_netif_napi() don't skip it, so every Rx vector associates Tx queue 0 with its own NAPI, and the netlink queue info reports the wrong NAPI for Tx queue 0. This bug was found by AI and verified on HW. Reproduced with "ethtool -L eth0 combined 0 rx 34 tx 34", and reading the NAPI IDs with "ynl --family netdev --dump queue-get": before: tx 0 napi-id 580, tx 1 napi-id 514, rx 33 napi-id 580 ^^^ rx 33's NAPI, not vector 0's after: tx 0 napi-id 513, tx 1 napi-id 514, rx 33 napi-id 580 Fixes: cf4facfb132a ("eth: fbnic: Add support for XDP queues") Signed-off-by: Dimitri Daskalakis Reviewed-by: Björn Töpel Link: https://patch.msgid.link/20261117215416.1901246-3-dimitri.daskalakis1@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/meta/fbnic/fbnic_txrx.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c index 9f96ed7d0300f6..381831b7e1080d 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c @@ -2184,6 +2184,9 @@ static void fbnic_set_netif_napi(struct fbnic_napi_vector *nv) for (i = 0; i < nv->txt_count; i++) { struct fbnic_q_triad *qt = &nv->qt[i]; + if (qt->sub0.flags & FBNIC_RING_F_DISABLED) + continue; + netif_queue_set_napi(nv->napi.dev, qt->sub0.q_idx, NETDEV_QUEUE_TYPE_TX, &nv->napi); } @@ -2205,6 +2208,9 @@ static void fbnic_reset_netif_napi(struct fbnic_napi_vector *nv) for (i = 0; i < nv->txt_count; i++) { struct fbnic_q_triad *qt = &nv->qt[i]; + if (qt->sub0.flags & FBNIC_RING_F_DISABLED) + continue; + netif_queue_set_napi(nv->napi.dev, qt->sub0.q_idx, NETDEV_QUEUE_TYPE_TX, NULL); } From 729f807b58f6ed646b81cf7fd7939b2271daa33f Mon Sep 17 00:00:00 2001 From: Dimitri Daskalakis Date: Tue, 17 Nov 2026 13:54:14 -0800 Subject: [PATCH 1313/2102] eth: fbnic: skip freed Tx rings in fbnic_get_ts_stats() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fbnic_stop() frees the NAPI vectors, which clears fbn->tx[] while num_tx_queues is left unchanged. fbnic_get_ts_stats() walks fbn->tx[] without checking for NULL, so asking for timestamping statistics while the interface is down dereferences a NULL ring. This was found by AI and reproduced on HW. # ip link set dev eth0 down; ethtool -I -T eth0 BUG: kernel NULL pointer dereference, address: 0000000000000050 RIP: 0010:fbnic_get_ts_stats+0x38/0x60 Call Trace: tsinfo_prepare_data+0x82/0xb0 ethnl_default_doit+0x213/0x470 genl_family_rcv_msg_doit+0xdd/0x110 ... Fixes: 96f358f75d1a ("eth: fbnic: add ethtool timestamping statistics") Signed-off-by: Dimitri Daskalakis Reviewed-by: Björn Töpel Link: https://patch.msgid.link/20261117215416.1901246-4-dimitri.daskalakis1@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c b/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c index b300017b53d4a4..9714a89977fa7a 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c @@ -1740,6 +1740,9 @@ static void fbnic_get_ts_stats(struct net_device *netdev, ts_stats->lost = fbn->tx_stats.twq.ts_lost; for (i = 0; i < fbn->num_tx_queues; i++) { ring = fbn->tx[i]; + if (!ring) + continue; + do { start = u64_stats_fetch_begin(&ring->stats.syncp); ts_packets = ring->stats.twq.ts_packets; From a6c99fc2d6dce2db5c969bbcb0bfef16920b04d9 Mon Sep 17 00:00:00 2001 From: Dimitri Daskalakis Date: Tue, 17 Nov 2026 13:54:15 -0800 Subject: [PATCH 1314/2102] netdevsim: report fake timestamping stats drivers/net selftests can't skip on netdevsim. Implement get_ts_stats with fixed counters so the stats test can read timestamping statistics. Signed-off-by: Dimitri Daskalakis Link: https://patch.msgid.link/20261117215416.1901246-5-dimitri.daskalakis1@gmail.com Signed-off-by: Jakub Kicinski --- drivers/net/netdevsim/ethtool.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/drivers/net/netdevsim/ethtool.c b/drivers/net/netdevsim/ethtool.c index c3d2bc783d5571..e0c4c96209c433 100644 --- a/drivers/net/netdevsim/ethtool.c +++ b/drivers/net/netdevsim/ethtool.c @@ -205,6 +205,14 @@ static int nsim_get_ts_info(struct net_device *dev, return 0; } +static void nsim_get_ts_stats(struct net_device *dev, + struct ethtool_ts_stats *ts_stats) +{ + ts_stats->pkts = 3; + ts_stats->lost = 1; + ts_stats->err = 0; +} + static u32 nsim_get_rxfh_key_size(struct net_device *dev) { return NETDEV_RSS_KEY_LEN; @@ -275,6 +283,7 @@ static const struct ethtool_ops nsim_ethtool_ops = { .set_fecparam = nsim_set_fecparam, .get_fec_stats = nsim_get_fec_stats, .get_ts_info = nsim_get_ts_info, + .get_ts_stats = nsim_get_ts_stats, }; static void nsim_ethtool_ring_init(struct netdevsim *ns) From 43cb59e7a47b2b0721b542e33c6d8da0ef4b9f17 Mon Sep 17 00:00:00 2001 From: Dimitri Daskalakis Date: Tue, 17 Nov 2026 13:54:16 -0800 Subject: [PATCH 1315/2102] selftests: drv-net: stats: query timestamping stats while down Read timestamping statistics before and after ifdown, to catch drivers that crash while the interface is down. Counters must not go backwards across ifdown; the test does not send timestamped traffic, so a reset is only caught if the counters were already nonzero. Signed-off-by: Dimitri Daskalakis Link: https://patch.msgid.link/20261117215416.1901246-6-dimitri.daskalakis1@gmail.com Signed-off-by: Jakub Kicinski --- tools/testing/selftests/drivers/net/stats.py | 25 +++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/drivers/net/stats.py b/tools/testing/selftests/drivers/net/stats.py index b08e4d48b15ce4..e61db30b51817b 100755 --- a/tools/testing/selftests/drivers/net/stats.py +++ b/tools/testing/selftests/drivers/net/stats.py @@ -220,6 +220,28 @@ def check_down(cfg) -> None: netfam.qstats_get({"ifindex": cfg.ifindex, "scope": "queue"}, dump=True) +@ksft_disruptive +def check_down_ts_stats(cfg) -> None: + """Test timestamping stats are not impacted by ifdown""" + + req = {"header": {"dev-index": cfg.ifindex, "flags": {"stats"}}} + try: + stats = ethnl.tsinfo_get(req).get("stats") + except NlError as e: + if e.error == errno.EOPNOTSUPP: + raise KsftSkipEx("timestamping not supported by the device") from e + raise + if not stats: + raise KsftSkipEx("timestamping stats not supported by the device") + + ip(f"link set dev {cfg.dev['ifname']} down") + defer(ip, f"link set dev {cfg.dev['ifname']} up") + + stats2 = ethnl.tsinfo_get(req).get("stats", {}) + for k in stats: + ksft_ge(stats2[k], stats[k], comment=f"{k} went backwards on device down") + + def __run_inf_loop(body): body = body.strip() if body[-1] != ';': @@ -311,7 +333,8 @@ def main() -> None: with NetDrvEnv(__file__, queue_count=100) as cfg: ksft_run([check_pause, check_fec, check_fec_hist, pkt_byte_sum, - qstat_by_ifindex, check_down, procfs_hammer, + qstat_by_ifindex, check_down, check_down_ts_stats, + procfs_hammer, procfs_downup_hammer], args=(cfg, )) ksft_exit() From def1745a6a8bc44b39e8670c737c27fd38b3595c Mon Sep 17 00:00:00 2001 From: Xiangwu Lai Date: Thu, 19 Nov 2026 15:16:09 +0800 Subject: [PATCH 1316/2102] scsi: ufs-mediatek: Use devm_regulator_get() for the va09 regulator ufs_mtk_init_va09_pwr_ctrl() obtains the va09 regulator with regulator_get() but the reference is never released with regulator_put(), neither on driver unbind nor on probe failure. The other regulators handled by this driver (dvfsrc-vcore) are already obtained with devm_regulator_get_optional(). Use devm_regulator_get() so that the reference is released automatically when the UFS device is detached. This alone is not enough, though: ufs_mtk_init() powers the M-PHY on, which enables the va09 regulator, and nothing powers it off again on the way out. The variant operations have no .exit callback and ufshcd_pltfrm_remove() only resumes the device. The devm release would then hit WARN_ON(regulator->enable_count) in _regulator_put() and leak the enable reference. Balance the use count by adding an .exit callback which powers the M-PHY off, in the same spirit as the .exit callbacks of ufs-exynos and ufs-qcom. ufshcd_hba_exit() invokes it both on driver unbind and on ufshcd_init() failure after the variant init, so the enable count is always balanced by the time devm releases the regulator. It relies on the state tracking in ufs_mtk_mphy_power_on() and is a no-op if the M-PHY was never powered on. Fixes: cf137b3ea49a ("scsi: ufs-mediatek: Support VA09 regulator operations") Reviewed-by: Peter Wang Signed-off-by: Xiangwu Lai Link: https://patch.msgid.link/20261119071611.117-2-laixiangwu@cmss.chinamobile.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/host/ufs-mediatek.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/drivers/ufs/host/ufs-mediatek.c b/drivers/ufs/host/ufs-mediatek.c index 5b6bff2cf9a20b..ebbc017d04ab87 100644 --- a/drivers/ufs/host/ufs-mediatek.c +++ b/drivers/ufs/host/ufs-mediatek.c @@ -692,7 +692,7 @@ static void ufs_mtk_init_va09_pwr_ctrl(struct ufs_hba *hba) { struct ufs_mtk_host *host = ufshcd_get_variant(hba); - host->reg_va09 = regulator_get(hba->dev, "va09"); + host->reg_va09 = devm_regulator_get(hba->dev, "va09"); if (IS_ERR(host->reg_va09)) dev_info(hba->dev, "failed to get va09"); else @@ -1331,6 +1331,14 @@ static int ufs_mtk_init(struct ufs_hba *hba) return err; } +static void ufs_mtk_exit(struct ufs_hba *hba) +{ + struct ufs_mtk_host *host = ufshcd_get_variant(hba); + + if (host) + ufs_mtk_mphy_power_on(hba, false); +} + static int ufs_mtk_negotiate_pwr_mode(struct ufs_hba *hba, const struct ufs_pa_layer_attr *dev_max_params, struct ufs_pa_layer_attr *dev_req_params) @@ -2353,6 +2361,7 @@ static void ufs_mtk_config_scsi_dev(struct scsi_device *sdev) static const struct ufs_hba_variant_ops ufs_hba_mtk_vops = { .name = "mediatek.ufshci", .init = ufs_mtk_init, + .exit = ufs_mtk_exit, .get_ufs_hci_version = ufs_mtk_get_ufs_hci_version, .setup_clocks = ufs_mtk_setup_clocks, .hce_enable_notify = ufs_mtk_hce_enable_notify, From 71b5da0b45fb83b590f1ec3df5361c7754b0e113 Mon Sep 17 00:00:00 2001 From: Xiangwu Lai Date: Thu, 19 Nov 2026 15:16:10 +0800 Subject: [PATCH 1317/2102] scsi: ufs-mediatek: Restore the M-PHY power state when va09 disable fails In ufs_mtk_mphy_power_on(), the power-off path tears the M-PHY down in two steps before regulator_disable() is called: phy_power_off() puts the PHY PLL and its clocks down, and ufs_mtk_va09_pwr_ctrl() asks the firmware to drop the VA09 supply. If regulator_disable() then fails, the M-PHY stays physically off while host->mphy_powered_on is left set, so the next power-on attempt bails out through the !(on ^ host->mphy_powered_on) check and never powers the M-PHY back up, leaving the UFS host with an unpowered PHY (I/O timeouts, controller lockups). Simply forcing mphy_powered_on to false would trade this for two more problems. First, the regulator core drops the consumer enable count only after a successful disable, so the count stays at 1, the next power-on raises it to 2 and it never returns to zero: va09 is then never physically disabled and the devm-acquired regulator would hit WARN_ON(enable_count) again on release. Second, when the power-off fails during ufs_mtk_suspend(), the error recovery in __ufshcd_wl_suspend() runs ufshcd_host_reset_and_restore() without powering the M-PHY back on, which would run against an unpowered PHY. (Both points were raised by the Sashiko AI review of v2.) Since the va09 regulator stays enabled when its disable fails, restore the M-PHY power state instead: power the PHY back on through ufs_mtk_va09_pwr_ctrl() and phy_power_on() and leave mphy_powered_on set. The next power-off attempt then retries the full sequence and the enable count stays balanced. Found by code inspection while reviewing the va09 error paths of the driver; the failure has not been observed on real hardware. Suggested-by: Peter Wang Link: https://lore.kernel.org/r/sashiko-outbox-220026@kernel.org Fixes: cf137b3ea49a ("scsi: ufs-mediatek: Support VA09 regulator operations") Signed-off-by: Xiangwu Lai Reviewed-by: Peter Wang Link: https://patch.msgid.link/20261119071611.117-3-laixiangwu@cmss.chinamobile.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/ufs/host/ufs-mediatek.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/drivers/ufs/host/ufs-mediatek.c b/drivers/ufs/host/ufs-mediatek.c index ebbc017d04ab87..caf186966c9100 100644 --- a/drivers/ufs/host/ufs-mediatek.c +++ b/drivers/ufs/host/ufs-mediatek.c @@ -541,6 +541,16 @@ static int ufs_mtk_mphy_power_on(struct ufs_hba *hba, bool on) if (ufs_mtk_is_va09_supported(hba)) { ufs_mtk_va09_pwr_ctrl(res, 0); ret = regulator_disable(host->reg_va09); + if (ret) { + /* + * The va09 regulator stays enabled, so + * bring the M-PHY back up to keep the + * software state in sync with the + * hardware. + */ + ufs_mtk_va09_pwr_ctrl(res, 1); + phy_power_on(mphy); + } } } out: From d5b89d55a322b632e2b465b392a4c1d9d338db9c Mon Sep 17 00:00:00 2001 From: Igor Opaniuk Date: Sat, 14 Nov 2026 13:46:11 +0100 Subject: [PATCH 1318/2102] net: qrtr: ns: keep notifying local servers after a failed send ctrl_cmd_bye() and ctrl_cmd_del_client() forward the event to every local server, but stop at the first failed send. Each send goes to a different socket, so a single server with a full receive queue (-ENOSPC) hides the event from all servers after it. Log the failure and carry on. Likewise, keep notifying local lookups when the NEW_SERVER broadcast fails, which can only happen on -ENOMEM. Tested on the Arduino UNO Q (QRB2210). Fixes: 0c2204a4ad71 ("net: qrtr: Migrate nameservice to kernel from userspace") Signed-off-by: Igor Opaniuk Link: https://patch.msgid.link/20261114-upstream-qrtr-hello-gate-fix_b4-v2-1-2fb62c2853bb@oss.qualcomm.com Signed-off-by: Jakub Kicinski --- net/qrtr/ns.c | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/net/qrtr/ns.c b/net/qrtr/ns.c index bcb090ee79d494..8209573221a5f3 100644 --- a/net/qrtr/ns.c +++ b/net/qrtr/ns.c @@ -374,11 +374,11 @@ static int ctrl_cmd_bye(struct sockaddr_qrtr *from) msg.msg_name = (struct sockaddr *)&sq; msg.msg_namelen = sizeof(sq); + /* A server that cannot take it must not hide it from the rest */ ret = kernel_sendmsg(qrtr_ns.sock, &msg, &iv, 1, sizeof(pkt)); - if (ret < 0 && ret != -ENODEV) { - pr_err("failed to send bye cmd\n"); - goto delete_node; - } + if (ret < 0 && ret != -ENODEV) + pr_err_ratelimited("failed to send bye cmd to %u:%u: %d\n", + srv->node, srv->port, ret); } /* Ignore -ENODEV */ @@ -458,11 +458,11 @@ static int ctrl_cmd_del_client(struct sockaddr_qrtr *from, msg.msg_name = (struct sockaddr *)&sq; msg.msg_namelen = sizeof(sq); + /* A server that cannot take it must not hide it from the rest */ ret = kernel_sendmsg(qrtr_ns.sock, &msg, &iv, 1, sizeof(pkt)); - if (ret < 0 && ret != -ENODEV) { - pr_err("failed to send del client cmd\n"); - return ret; - } + if (ret < 0 && ret != -ENODEV) + pr_err_ratelimited("failed to send del client cmd to %u:%u: %d\n", + srv->node, srv->port, ret); } return 0; } @@ -487,11 +487,10 @@ static int ctrl_cmd_new_server(struct sockaddr_qrtr *from, return -EINVAL; if (srv->node == qrtr_ns.local_node) { + /* The lookups below still need to hear about the server */ ret = service_announce_new(&qrtr_ns.bcast_sq, srv); - if (ret < 0) { + if (ret < 0) pr_err("failed to announce new service\n"); - return ret; - } } /* Notify any potential lookups about the new server */ From efd68f17acca65f581b9f2fa9ba50c8643ab544d Mon Sep 17 00:00:00 2001 From: Weibin Liu Date: Thu, 29 Oct 2026 15:33:16 +0800 Subject: [PATCH 1319/2102] scsi: mpt3sas: Validate data_out size before SMP link-reset check _ctl_do_mpt_command() handles MPI2_FUNCTION_SMP_PASSTHROUGH by reading data[1] and data[10] of the data_out buffer to detect SMP link-reset requests. The non-IMMEDIATE path sets data = data_out after checking only for a NULL pointer, so a payload shorter than 11 bytes can read past the end of the buffer, and out-of-bounds bytes can unexpectedly set ioc_link_reset_in_progress and ignore_loginfos. However, a short SMP request is not invalid: SMP_REPORT_GENERAL, for example, can use an 8-byte payload. Rejecting every data_out smaller than 11 bytes would break valid requests. Instead, require enough data only when checking for a link reset, and keep sending the request normally otherwise. The IMMEDIATE path reads from the request frame rather than data_out, so data_out_sz does not apply to it. Fixes: f92363d12359 ("[SCSI] mpt3sas: add new driver supporting 12GB SAS") Cc: stable@vger.kernel.org # 3.8+ Reviewed-by: Guanglei Zhu Signed-off-by: Weibin Liu Link: https://patch.msgid.link/20261029073316.4188569-1-liuwb@xiaopeng.com Signed-off-by: Martin K. Petersen (Oracle) --- drivers/scsi/mpt3sas/mpt3sas_ctl.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/drivers/scsi/mpt3sas/mpt3sas_ctl.c b/drivers/scsi/mpt3sas/mpt3sas_ctl.c index 8bb947004885bf..b069dd384ed781 100644 --- a/drivers/scsi/mpt3sas/mpt3sas_ctl.c +++ b/drivers/scsi/mpt3sas/mpt3sas_ctl.c @@ -57,9 +57,13 @@ #include #include +#include + #include "mpt3sas_base.h" #include "mpt3sas_ctl.h" +/* PHY operation byte in an SMP PHY Control request */ +#define SMP_PHY_CONTROL_OP_OFFSET 10 static struct fasync_struct *async_queue; static DECLARE_WAIT_QUEUE_HEAD(ctl_poll_wait); @@ -959,13 +963,17 @@ _ctl_do_mpt_command(struct MPT3SAS_ADAPTER *ioc, struct mpt3_ioctl_command karg, Mpi2SmpPassthroughRequest_t *smp_request = (Mpi2SmpPassthroughRequest_t *)mpi_request; u8 *data; + bool immediate; if (!ioc->multipath_on_hba) { /* ioc determines which port to use */ smp_request->PhysicalPort = 0xFF; } - if (smp_request->PassthroughFlags & - MPI2_SMP_PT_REQ_PT_FLAGS_IMMEDIATE) + + immediate = smp_request->PassthroughFlags & + MPI2_SMP_PT_REQ_PT_FLAGS_IMMEDIATE; + + if (immediate) data = (u8 *)&smp_request->SGL; else { if (unlikely(data_out == NULL)) { @@ -978,7 +986,11 @@ _ctl_do_mpt_command(struct MPT3SAS_ADAPTER *ioc, struct mpt3_ioctl_command karg, data = data_out; } - if (data[1] == 0x91 && (data[10] == 1 || data[10] == 2)) { + if ((immediate || + data_out_sz >= SMP_PHY_CONTROL_OP_OFFSET + 1) && + data[1] == SMP_PHY_CONTROL && + (data[10] == PHY_FUNC_LINK_RESET || + data[10] == PHY_FUNC_HARD_RESET)) { ioc->ioc_link_reset_in_progress = 1; ioc->ignore_loginfos = 1; } From 0e3d5c0408262aef599df888e9bde88d0337c1dc Mon Sep 17 00:00:00 2001 From: Gautam Menghani Date: Fri, 6 Nov 2026 13:37:42 +0530 Subject: [PATCH 1320/2102] KVM: PPC: Book3S HV: Use u8 to store guest's interrupt priorities Interrupt priorities range from 0x00 - 0xFF. When represented as u32 by the host in kvm_rtas_set_xive(), the guest can pass in a higher priority number (eg: 0x1FF) which ends up breaking this check in kvmppc_xive_set_xive(): if (priority != MASKED) { mutex_lock(&xive->lock); rc = xive_check_provisioning(xive->kvm, xive_prio_from_guest(priority)); mutex_unlock(&xive->lock); } This results in an attempt to access invalid memory in the function xive_provision_queue(): struct xive_q *q = &xc->queues[prio]; // prio = 0xFF Fix this by converting the priority variable to u8. Fixes: 5af50993850a ("KVM: PPC: Book3S HV: Native usage of the XIVE interrupt controller") Tested-by: R Nageswara Sastry Reviewed-by: Shrikanth Hegde Signed-off-by: Gautam Menghani Signed-off-by: Madhavan Srinivasan --- arch/powerpc/include/asm/kvm_ppc.h | 4 ++-- arch/powerpc/kvm/book3s_rtas.c | 5 +++-- arch/powerpc/kvm/book3s_xive.c | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/arch/powerpc/include/asm/kvm_ppc.h b/arch/powerpc/include/asm/kvm_ppc.h index 169ea6a7fbad44..0b85c13baf2866 100644 --- a/arch/powerpc/include/asm/kvm_ppc.h +++ b/arch/powerpc/include/asm/kvm_ppc.h @@ -720,7 +720,7 @@ static inline int kvmppc_xive_xics_hcall(struct kvm_vcpu *vcpu, u32 req) * new "XIVE" interrupt controller. */ extern int kvmppc_xive_set_xive(struct kvm *kvm, u32 irq, u32 server, - u32 priority); + u8 priority); extern int kvmppc_xive_get_xive(struct kvm *kvm, u32 irq, u32 *server, u32 *priority); extern int kvmppc_xive_int_on(struct kvm *kvm, u32 irq); @@ -758,7 +758,7 @@ extern bool kvmppc_xive_native_supported(void); #else static inline int kvmppc_xive_set_xive(struct kvm *kvm, u32 irq, u32 server, - u32 priority) { return -1; } + u8 priority) { return -1; } static inline int kvmppc_xive_get_xive(struct kvm *kvm, u32 irq, u32 *server, u32 *priority) { return -1; } static inline int kvmppc_xive_int_on(struct kvm *kvm, u32 irq) { return -1; } diff --git a/arch/powerpc/kvm/book3s_rtas.c b/arch/powerpc/kvm/book3s_rtas.c index 0507715d0fdd02..125e06d9988410 100644 --- a/arch/powerpc/kvm/book3s_rtas.c +++ b/arch/powerpc/kvm/book3s_rtas.c @@ -18,7 +18,8 @@ #ifdef CONFIG_KVM_XICS static void kvm_rtas_set_xive(struct kvm_vcpu *vcpu, struct rtas_args *args) { - u32 irq, server, priority; + u32 irq, server; + u8 priority; int rc; if (be32_to_cpu(args->nargs) != 3 || be32_to_cpu(args->nret) != 1) { @@ -28,7 +29,7 @@ static void kvm_rtas_set_xive(struct kvm_vcpu *vcpu, struct rtas_args *args) irq = be32_to_cpu(args->args[0]); server = be32_to_cpu(args->args[1]); - priority = be32_to_cpu(args->args[2]); + priority = (u8) be32_to_cpu(args->args[2]); if (xics_on_xive()) rc = kvmppc_xive_set_xive(vcpu->kvm, irq, server, priority); diff --git a/arch/powerpc/kvm/book3s_xive.c b/arch/powerpc/kvm/book3s_xive.c index 9d2039ee37b2c9..00218a7dc68833 100644 --- a/arch/powerpc/kvm/book3s_xive.c +++ b/arch/powerpc/kvm/book3s_xive.c @@ -1267,7 +1267,7 @@ static int xive_target_interrupt(struct kvm *kvm, */ int kvmppc_xive_set_xive(struct kvm *kvm, u32 irq, u32 server, - u32 priority) + u8 priority) { struct kvmppc_xive *xive = kvm->arch.xive; struct kvmppc_xive_src_block *sb; From bd6d2f87c2239d10bf5f37ab52b3968565528417 Mon Sep 17 00:00:00 2001 From: Narayana Murty N Date: Fri, 6 Nov 2026 13:37:43 +0530 Subject: [PATCH 1321/2102] KVM: PPC: Fix TOCTOU kernel stack disclosure via kvm_run->mmio.len struct kvm_run is mmap'd and writable by host userspace at any time. kvmppc_complete_mmio_load() re-reads run->mmio.len from the shared page on the KVM_RUN completion path. A malicious userspace can: 1. Trigger a guest MMIO load; the kernel sets a valid run->mmio.len (1, 2, 4, or 8) and exits with mmio_needed=1. 2. Rewrite run->mmio.len to an invalid value (0, 3, 5, 6, or 7) before the next KVM_RUN ioctl. 3. On re-entry, kvm_arch_vcpu_ioctl_run() calls kvmppc_complete_mmio_load() unconditionally. 4. No switch case matches the tampered length, so 'gpr' remains uninitialised on the kernel stack. 5. The uninitialised value is written into a guest GPR and is subsequently readable by the attacker via KVM_GET_REGS or KVM_GET_ONE_REG, disclosing kernel stack contents (CWE-457/200). The same issue affects every site that advances paddr_accessed or passes the length to the VSX/VMX repeat-load/store helpers, since all of them re-read run->mmio.len from the shared mapping. Fix by introducing vcpu->arch.mmio_len, a kernel-private u8 field that is written once in __kvmppc_handle_load() and kvmppc_handle_store() alongside the other vcpu->arch.mmio_* fields and never touched by userspace. All consumption sites are updated to use vcpu->arch.mmio_len: - kvmppc_complete_mmio_load(): reads vcpu->arch.mmio_len; validates it is exactly one of {1,2,4,8} (EMULATE_FAIL otherwise); initialises gpr = 0 before the switch so no uninitialised value can escape even if future code changes introduce a new path. Return type changed from void to int (EMULATE_DONE / EMULATE_FAIL) so callers can propagate failures. - kvm_arch_vcpu_ioctl_run(): checks the return value and exits with KVM_EXIT_INTERNAL_ERROR / KVM_INTERNAL_ERROR_EMULATION on failure, matching the VSX/VMX error paths already in place. run->internal.ndata is initialised to 0 so the union field does not carry stale mmio data. Clear mmio_needed before completing an in-kernel MMIO load or a userspace MMIO load on KVM_RUN re-entry, so a completion failure cannot leave stale pending-MMIO state. - kvmppc_handle_vsx_load(), kvmppc_handle_vsx_store(), kvmppc_handle_vmx_load(), kvmppc_handle_vmx_store(): paddr_accessed increments use vcpu->arch.mmio_len. - kvmppc_emulate_mmio_vsx_loadstore() and kvmppc_emulate_mmio_vmx_loadstore() use vcpu->arch.mmio_len for the paddr_accessed increment and for the length passed to the load/store helpers. Fixes: bbf45ba57eae ("KVM: ppc: PowerPC 440 KVM implementation") Tested-by: R Nageswara Sastry Signed-off-by: Narayana Murty N Signed-off-by: Gautam Menghani Signed-off-by: Madhavan Srinivasan --- arch/powerpc/include/asm/kvm_host.h | 1 + arch/powerpc/kvm/powerpc.c | 65 ++++++++++++++++++----------- 2 files changed, 42 insertions(+), 24 deletions(-) diff --git a/arch/powerpc/include/asm/kvm_host.h b/arch/powerpc/include/asm/kvm_host.h index c068cc1dd51fc7..d447c847f7ef98 100644 --- a/arch/powerpc/include/asm/kvm_host.h +++ b/arch/powerpc/include/asm/kvm_host.h @@ -746,6 +746,7 @@ struct kvm_vcpu_arch { pgd_t *pgdir; u16 io_gpr; /* GPR used as IO source/target */ + u8 mmio_len; /* kernel-private copy of mmio.len, immune to TOCTOU */ u8 mmio_host_swabbed; u8 mmio_sign_extend; /* conversion between single and double precision */ diff --git a/arch/powerpc/kvm/powerpc.c b/arch/powerpc/kvm/powerpc.c index 9eb5a944abe81f..4da6659c5d9d4b 100644 --- a/arch/powerpc/kvm/powerpc.c +++ b/arch/powerpc/kvm/powerpc.c @@ -1157,23 +1157,29 @@ static inline u32 dp_to_sp(u64 fprd) #define dp_to_sp(x) (x) #endif /* CONFIG_PPC_FPU */ -static void kvmppc_complete_mmio_load(struct kvm_vcpu *vcpu) +static int kvmppc_complete_mmio_load(struct kvm_vcpu *vcpu) { struct kvm_run *run = vcpu->run; - u64 gpr; + u64 gpr = 0; + u8 len = vcpu->arch.mmio_len; /* use kernel-private copy, not run->mmio.len */ - if (run->mmio.len > sizeof(gpr)) - return; + /* Reject lengths that have no corresponding switch case below. */ + switch (len) { + case 1: case 2: case 4: case 8: + break; + default: + return EMULATE_FAIL; + } if (!vcpu->arch.mmio_host_swabbed) { - switch (run->mmio.len) { + switch (len) { case 8: gpr = *(u64 *)run->mmio.data; break; case 4: gpr = *(u32 *)run->mmio.data; break; case 2: gpr = *(u16 *)run->mmio.data; break; case 1: gpr = *(u8 *)run->mmio.data; break; } } else { - switch (run->mmio.len) { + switch (len) { case 8: gpr = swab64(*(u64 *)run->mmio.data); break; case 4: gpr = swab32(*(u32 *)run->mmio.data); break; case 2: gpr = swab16(*(u16 *)run->mmio.data); break; @@ -1182,11 +1188,11 @@ static void kvmppc_complete_mmio_load(struct kvm_vcpu *vcpu) } /* conversion between single and double precision */ - if ((vcpu->arch.mmio_sp64_extend) && (run->mmio.len == 4)) + if ((vcpu->arch.mmio_sp64_extend) && (len == 4)) gpr = sp_to_dp(gpr); if (vcpu->arch.mmio_sign_extend) { - switch (run->mmio.len) { + switch (len) { #ifdef CONFIG_PPC64 case 4: gpr = (s64)(s32)gpr; @@ -1265,6 +1271,7 @@ static void kvmppc_complete_mmio_load(struct kvm_vcpu *vcpu) default: BUG(); } + return EMULATE_DONE; } static int __kvmppc_handle_load(struct kvm_vcpu *vcpu, @@ -1290,6 +1297,7 @@ static int __kvmppc_handle_load(struct kvm_vcpu *vcpu, run->mmio.is_write = 0; vcpu->arch.io_gpr = rt; + vcpu->arch.mmio_len = bytes; /* kernel-private, immune to TOCTOU */ vcpu->arch.mmio_host_swabbed = host_swabbed; vcpu->mmio_needed = 1; vcpu->mmio_is_write = 0; @@ -1303,8 +1311,11 @@ static int __kvmppc_handle_load(struct kvm_vcpu *vcpu, srcu_read_unlock(&vcpu->kvm->srcu, idx); if (!ret) { - kvmppc_complete_mmio_load(vcpu); vcpu->mmio_needed = 0; + + if (kvmppc_complete_mmio_load(vcpu) != EMULATE_DONE) + return EMULATE_FAIL; + return EMULATE_DONE; } @@ -1345,7 +1356,7 @@ int kvmppc_handle_vsx_load(struct kvm_vcpu *vcpu, if (emulated != EMULATE_DONE) break; - vcpu->arch.paddr_accessed += vcpu->run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; vcpu->arch.mmio_vsx_copy_nums--; vcpu->arch.mmio_vsx_offset++; @@ -1375,6 +1386,7 @@ int kvmppc_handle_store(struct kvm_vcpu *vcpu, run->mmio.phys_addr = vcpu->arch.paddr_accessed; run->mmio.len = bytes; run->mmio.is_write = 1; + vcpu->arch.mmio_len = bytes; /* kernel-private, immune to TOCTOU */ vcpu->mmio_needed = 1; vcpu->mmio_is_write = 1; @@ -1491,7 +1503,7 @@ int kvmppc_handle_vsx_store(struct kvm_vcpu *vcpu, if (emulated != EMULATE_DONE) break; - vcpu->arch.paddr_accessed += vcpu->run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; vcpu->arch.mmio_vsx_copy_nums--; vcpu->arch.mmio_vsx_offset++; @@ -1506,14 +1518,14 @@ static int kvmppc_emulate_mmio_vsx_loadstore(struct kvm_vcpu *vcpu) enum emulation_result emulated = EMULATE_FAIL; int r; - vcpu->arch.paddr_accessed += run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; if (!vcpu->mmio_is_write) { emulated = kvmppc_handle_vsx_load(vcpu, vcpu->arch.io_gpr, - run->mmio.len, 1, vcpu->arch.mmio_sign_extend); + vcpu->arch.mmio_len, 1, vcpu->arch.mmio_sign_extend); } else { emulated = kvmppc_handle_vsx_store(vcpu, - vcpu->arch.io_gpr, run->mmio.len, 1); + vcpu->arch.io_gpr, vcpu->arch.mmio_len, 1); } switch (emulated) { @@ -1551,7 +1563,7 @@ int kvmppc_handle_vmx_load(struct kvm_vcpu *vcpu, if (emulated != EMULATE_DONE) break; - vcpu->arch.paddr_accessed += vcpu->run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; vcpu->arch.mmio_vmx_copy_nums--; vcpu->arch.mmio_vmx_offset++; } @@ -1671,7 +1683,7 @@ int kvmppc_handle_vmx_store(struct kvm_vcpu *vcpu, if (emulated != EMULATE_DONE) break; - vcpu->arch.paddr_accessed += vcpu->run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; vcpu->arch.mmio_vmx_copy_nums--; vcpu->arch.mmio_vmx_offset++; } @@ -1685,14 +1697,14 @@ static int kvmppc_emulate_mmio_vmx_loadstore(struct kvm_vcpu *vcpu) enum emulation_result emulated = EMULATE_FAIL; int r; - vcpu->arch.paddr_accessed += run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; if (!vcpu->mmio_is_write) { emulated = kvmppc_handle_vmx_load(vcpu, - vcpu->arch.io_gpr, run->mmio.len, 1); + vcpu->arch.io_gpr, vcpu->arch.mmio_len, 1); } else { emulated = kvmppc_handle_vmx_store(vcpu, - vcpu->arch.io_gpr, run->mmio.len, 1); + vcpu->arch.io_gpr, vcpu->arch.mmio_len, 1); } switch (emulated) { @@ -1820,8 +1832,16 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) if (vcpu->mmio_needed) { vcpu->mmio_needed = 0; - if (!vcpu->mmio_is_write) - kvmppc_complete_mmio_load(vcpu); + if (!vcpu->mmio_is_write) { + if (kvmppc_complete_mmio_load(vcpu) != EMULATE_DONE) { + run->exit_reason = KVM_EXIT_INTERNAL_ERROR; + run->internal.suberror = + KVM_INTERNAL_ERROR_EMULATION; + run->internal.ndata = 0; + r = 0; + goto out; + } + } #ifdef CONFIG_VSX if (vcpu->arch.mmio_vsx_copy_nums > 0) { vcpu->arch.mmio_vsx_copy_nums--; @@ -1880,10 +1900,7 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) kvm_sigset_deactivate(vcpu); -#ifdef CONFIG_ALTIVEC out: -#endif - /* * We're already returning to userspace, don't pass the * RESUME_HOST flags along. From f8b648c1ace89bb784febaf09cf2d59cc167f840 Mon Sep 17 00:00:00 2001 From: Baolin Liu Date: Fri, 20 Nov 2026 23:50:21 +0800 Subject: [PATCH 1322/2102] ntfs: limit MFT mirror comparisons to system records Windows 10 can leave $MFTMirr records from record 16 onwards stale on volumes with large clusters. Comparing them can falsely report corruption. Commit 749357bd48c1 ("ntfs: mount hibernated volumes read-only regardless of errors=") made these mismatches force a read-only mount even with errors=continue. Limit the record checks and comparison to the first 16 records within the mirror, following ntfs-3g. Keep reading the full mirror for runlist mapping and location checks, and leave mirror writeback unchanged. Fixes: 2beaa98b46c4 ("ntfs: restore $MFT mirror contents check") Cc: stable@vger.kernel.org Link: https://github.com/tuxera/ntfs-3g/commit/85e208176ffd16ce9a51a9f534b194f0ebbde6e3 Signed-off-by: Baolin Liu Reviewed-by: Hyunchul Lee Signed-off-by: Namjae Jeon --- fs/ntfs/super.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/fs/ntfs/super.c b/fs/ntfs/super.c index 891b5e0c384b19..f38f3543499539 100644 --- a/fs/ntfs/super.c +++ b/fs/ntfs/super.c @@ -1207,6 +1207,14 @@ static bool check_mft_mirror(struct ntfs_volume *vol) ++index; } + /* + * Windows 10 may leave mirror records beyond the system files + * stale. Read the full mirror to map its runlist, but only + * compare the system records, as ntfs-3g does. + */ + if (i >= FILE_first_user) + goto next_record; + /* Do not check the record if it is not in use. */ if (((struct mft_record *)kmft)->flags & MFT_RECORD_IN_USE) { /* Make sure the record is ok. */ @@ -1250,6 +1258,7 @@ static bool check_mft_mirror(struct ntfs_volume *vol) i); goto mm_unmap_out; } +next_record: kmft += vol->mft_record_size; kmirr += vol->mft_record_size; } while (++i < vol->mftmirr_size); From ae6985a0d20d1621feed98b89903944513a221e1 Mon Sep 17 00:00:00 2001 From: Namjae Jeon Date: Mon, 9 Nov 2026 21:10:16 +0900 Subject: [PATCH 1323/2102] ntfs: flush sibling attribute mappings during stream fsync Stream fsync skips sibling mappings, so an attribute converted to non-resident during a resize can lose its old contents after a crash. Flush sibling mappings through the shared fsync path. Skip self-parent FILE_NAME entries to avoid recursively locking the root directory's MFT record. Fixes: 48996054b706 ("ntfs: add named stream ioctls support") Signed-off-by: Namjae Jeon --- fs/ntfs/file.c | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/fs/ntfs/file.c b/fs/ntfs/file.c index 1861d0f07fef8a..5ab0e3437d671f 100644 --- a/fs/ntfs/file.c +++ b/fs/ntfs/file.c @@ -323,13 +323,6 @@ int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end, ret = __ntfs_write_inode(vi, 1); write_inode_now(vi, !datasync); - /* - * file_write_and_wait_range() already flushed this stream mapping. - * A stream fsync does not need to flush sibling attribute mappings. - */ - if (stream) - goto sync_volume; - ctx = ntfs_attr_get_search_ctx(ni, NULL); if (!ctx) return -ENOMEM; @@ -340,6 +333,9 @@ int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end, struct file_name_attr *fn = (struct file_name_attr *)((u8 *)ctx->attr + le16_to_cpu(ctx->attr->data.resident.value_offset)); + if (MREF_LE(fn->parent_directory) == ni->mft_no) + continue; + parent_vi = ntfs_iget(vi->i_sb, MREF_LE(fn->parent_directory)); if (IS_ERR(parent_vi)) continue; @@ -409,7 +405,6 @@ int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end, if (err && !ret) ret = err; -sync_volume: write_inode_now(vol->mftbmp_ino, 1); down_write(&vol->lcnbmp_lock); write_inode_now(vol->lcnbmp_ino, 1); From 136760737a7659518e5aaa17b2630246ad0b7f33 Mon Sep 17 00:00:00 2001 From: Yue Yang Date: Fri, 13 Nov 2026 11:26:15 +0800 Subject: [PATCH 1324/2102] ntfs: don't let a fatal signal interrupt metadata reads read_mapping_folio() returns -EINTR when the caller has a fatal signal pending while it waits for the read it submitted. ntfs reads its metadata through it and treats the failure as a volume error, so killing a task that waits on a metadata read turns the volume read-only with errors=remount-ro. A read that is part of an update also stops the update half way: killing an rm can leave clusters allocated in $Bitmap, an MFT record in use without a directory entry, or a directory index with entries that point to freed records. Killing a mount makes it fail with bogus $AttrDef and $UpCase errors, or leaves the volume mounted read-only with a bogus $MFTMirr or $BadClus error. Add ntfs_read_metadata_folio(), which waits for the read uninterruptibly, and use it for metadata reads. Named stream contents, compressed data and the read-only bitmap scans through ntfs_get_locked_folio(), whose callers do not report a volume error, keep using read_mapping_folio(). A named stream write that is interrupted that way no longer reports a volume error either. A killed task now waits for its metadata read to complete, as it does on filesystems that use the buffer cache. Closes: https://github.com/namjaejeon/linux-ntfs/issues/98 Fixes: 11ccc9107dc4 ("ntfs: update runlist handling and cluster allocator") Fixes: 115380f9a2f9 ("ntfs: update mft operations") Fixes: af0db57d4293 ("ntfs: update inode operations") Fixes: 495e90fa3348 ("ntfs: update attrib operations") Fixes: 0a8ac0c1fa0b ("ntfs: update directory operations") Fixes: 5218cd102aec ("ntfs: update misc operations") Fixes: 6251f0b0de7d ("ntfs: update super block operations") Fixes: 8506a8031ebf ("ntfs: validate and reserve bad clusters at mount") Cc: stable@vger.kernel.org Signed-off-by: Yue Yang Reviewed-by: Baolin Liu Signed-off-by: Namjae Jeon --- fs/ntfs/aops.c | 60 ++++++++++++++++++++++++++++++++++++++++++++++ fs/ntfs/attrib.c | 2 +- fs/ntfs/bdev-io.c | 2 +- fs/ntfs/bitmap.c | 7 +++--- fs/ntfs/dir.c | 4 ++-- fs/ntfs/inode.c | 21 +++++++++++++--- fs/ntfs/lcnalloc.c | 2 +- fs/ntfs/logfile.c | 4 ++-- fs/ntfs/mft.c | 20 ++++++++-------- fs/ntfs/ntfs.h | 4 ++++ fs/ntfs/super.c | 14 +++++------ 11 files changed, 109 insertions(+), 31 deletions(-) diff --git a/fs/ntfs/aops.c b/fs/ntfs/aops.c index cb3d5443ee1dd6..d0d1a8402bc4d9 100644 --- a/fs/ntfs/aops.c +++ b/fs/ntfs/aops.c @@ -7,6 +7,7 @@ * Copyright (c) 2025 LG Electronics Co., Ltd. */ +#include #include #include "attrib.h" @@ -304,6 +305,65 @@ static int ntfs_swap_activate(struct swap_info_struct *sis, ntfs_read_iomap_next); } +/** + * ntfs_read_metadata_folio - read a metadata folio, ignoring fatal signals + * @mapping: address space of the metadata inode or block device + * @index: page cache index to read + * + * Like read_mapping_folio(), but the wait for the read cannot be interrupted, + * so a fatal signal cannot fail a metadata read in the middle of an update. + * The caller must not hold the lock of the folio at @index. + * + * Return: the uptodate folio with a reference held, or an ERR_PTR(). + */ +struct folio *ntfs_read_metadata_folio(struct address_space *mapping, + pgoff_t index) +{ + struct folio *folio; + int err; + + folio = filemap_get_folio(mapping, index); + if (!IS_ERR(folio)) { + if (folio_test_uptodate(folio)) + goto out; + folio_put(folio); + } +repeat: + folio = __filemap_get_folio(mapping, index, FGP_LOCK | FGP_CREAT, + mapping_gfp_mask(mapping)); + if (IS_ERR(folio)) + return folio; + /* $MFT updates clear uptodate under the folio lock, so check it locked. */ + if (folio_test_uptodate(folio)) + goto unlock; + + /* ->read_folio() unlocks the folio when the read completes. */ + err = mapping->a_ops->read_folio(NULL, folio); + if (err) { + folio_put(folio); + if (err == AOP_TRUNCATED_PAGE) + goto repeat; + return ERR_PTR(err); + } + folio_lock(folio); + if (folio->mapping != mapping) { + /* Truncated while the read was in flight. */ + folio_unlock(folio); + folio_put(folio); + goto repeat; + } + if (!folio_test_uptodate(folio)) { + folio_unlock(folio); + folio_put(folio); + return ERR_PTR(-EIO); + } +unlock: + folio_unlock(folio); +out: + folio_mark_accessed(folio); + return folio; +} + const struct address_space_operations ntfs_aops = { .read_folio = ntfs_read_folio, .readahead = ntfs_readahead, diff --git a/fs/ntfs/attrib.c b/fs/ntfs/attrib.c index ce7c1b524180af..1a3ee7da240b5a 100644 --- a/fs/ntfs/attrib.c +++ b/fs/ntfs/attrib.c @@ -2323,7 +2323,7 @@ int ntfs_attr_set(struct ntfs_inode *ni, s64 ofs, s64 cnt, const u8 val) index = ofs >> PAGE_SHIFT; while (cnt) { - folio = read_mapping_folio(mapping, index, NULL); + folio = ntfs_read_metadata_folio(mapping, index); if (IS_ERR(folio)) { ret = PTR_ERR(folio); ntfs_error(VFS_I(ni)->i_sb, "Failed to read a page %lu for attr %#x: %ld", diff --git a/fs/ntfs/bdev-io.c b/fs/ntfs/bdev-io.c index 4f27eed3b0723b..afb1d1df37e09e 100644 --- a/fs/ntfs/bdev-io.c +++ b/fs/ntfs/bdev-io.c @@ -99,7 +99,7 @@ int ntfs_bdev_write(struct super_block *sb, void *buf, loff_t start, size_t size for (; idx < idx_end; idx++, from = 0) { u32 len; - folio = read_mapping_folio(sb->s_bdev->bd_mapping, idx, NULL); + folio = ntfs_read_metadata_folio(sb->s_bdev->bd_mapping, idx); if (IS_ERR(folio)) { ntfs_error(sb, "Unable to read %ld page", idx); return PTR_ERR(folio); diff --git a/fs/ntfs/bitmap.c b/fs/ntfs/bitmap.c index af86fb1c199ba5..0ad80255d6222e 100644 --- a/fs/ntfs/bitmap.c +++ b/fs/ntfs/bitmap.c @@ -36,8 +36,7 @@ int ntfs_bitmap_check_used(struct ntfs_volume *vol, s64 start, s64 count, return -EROFS; while (count) { - folio = read_mapping_folio(mapping, - start >> (PAGE_SHIFT + 3), NULL); + folio = ntfs_read_metadata_folio(mapping, start >> (PAGE_SHIFT + 3)); if (IS_ERR(folio)) return PTR_ERR(folio); @@ -203,7 +202,7 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit, /* Get the page containing the first bit (@start_bit). */ mapping = vi->i_mapping; - folio = read_mapping_folio(mapping, index, NULL); + folio = ntfs_read_metadata_folio(mapping, index); if (IS_ERR(folio)) { if (!is_rollback) ntfs_error(vi->i_sb, @@ -267,7 +266,7 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit, folio_unlock(folio); kunmap_local(kaddr); folio_put(folio); - folio = read_mapping_folio(mapping, ++index, NULL); + folio = ntfs_read_metadata_folio(mapping, ++index); if (IS_ERR(folio)) { ntfs_error(vi->i_sb, "Failed to map subsequent page (error %li), aborting.", diff --git a/fs/ntfs/dir.c b/fs/ntfs/dir.c index 9fb5bb3d351205..ce87799a28e8e4 100644 --- a/fs/ntfs/dir.c +++ b/fs/ntfs/dir.c @@ -327,8 +327,8 @@ u64 ntfs_lookup_inode_by_name(struct ntfs_inode *dir_ni, const __le16 *uname, * of PAGE_SIZE and map the page cache page, reading it from * disk if necessary. */ - folio = read_mapping_folio(ia_mapping, vcn << - dir_ni->itype.index.vcn_size_bits >> PAGE_SHIFT, NULL); + folio = ntfs_read_metadata_folio(ia_mapping, vcn << + dir_ni->itype.index.vcn_size_bits >> PAGE_SHIFT); if (IS_ERR(folio)) { ntfs_error(sb, "Failed to map directory index page, error %ld.", -PTR_ERR(folio)); diff --git a/fs/ntfs/inode.c b/fs/ntfs/inode.c index b799e6668a6939..20949ac16f34e4 100644 --- a/fs/ntfs/inode.c +++ b/fs/ntfs/inode.c @@ -3773,8 +3773,14 @@ s64 ntfs_inode_attr_pread(struct inode *vi, s64 pos, s64 count, u8 *buf) index = pos >> PAGE_SHIFT; do { - /* Update @index and get the next folio. */ - folio = read_mapping_folio(mapping, index, NULL); + /* + * Update @index and get the next folio. The contents of a named + * stream are user data, so a fatal signal may still stop that read. + */ + if (ntfs_inode_is_named_stream(ni)) + folio = read_mapping_folio(mapping, index, NULL); + else + folio = ntfs_read_metadata_folio(mapping, index); if (IS_ERR(folio)) { err = PTR_ERR(folio); break; @@ -3926,9 +3932,18 @@ static s64 __ntfs_inode_non_resident_attr_pwrite(struct inode *vi, break; } } else { - folio = read_mapping_folio(mapping, index, NULL); + /* + * Named stream contents are user data; keep that read + * killable, as in ntfs_inode_attr_pread(). + */ + if (ntfs_inode_is_named_stream(ni)) + folio = read_mapping_folio(mapping, index, NULL); + else + folio = ntfs_read_metadata_folio(mapping, index); if (IS_ERR(folio)) { ret = PTR_ERR(folio); + if (ret == -EINTR) + break; ntfs_error(vi->i_sb, "Failed to read a page %lu for attr %#x: %ld", index, ni->type, PTR_ERR(folio)); break; diff --git a/fs/ntfs/lcnalloc.c b/fs/ntfs/lcnalloc.c index 3ebcac4c286481..7e00016f42adee 100644 --- a/fs/ntfs/lcnalloc.c +++ b/fs/ntfs/lcnalloc.c @@ -340,7 +340,7 @@ struct runlist_element *ntfs_cluster_alloc(struct ntfs_volume *vol, const s64 st if (vol->lcn_empty_bits_per_page[index] == 0) goto next_bmp_pos; - folio = read_mapping_folio(mapping, index, NULL); + folio = ntfs_read_metadata_folio(mapping, index); if (IS_ERR(folio)) { err = PTR_ERR(folio); ntfs_error(vol->sb, "Failed to map page."); diff --git a/fs/ntfs/logfile.c b/fs/ntfs/logfile.c index 2f27ae7a3927f1..cdc951309d0ca8 100644 --- a/fs/ntfs/logfile.c +++ b/fs/ntfs/logfile.c @@ -367,7 +367,7 @@ static int ntfs_check_and_load_restart_page(struct inode *vi, to_read = le32_to_cpu(rp->system_page_size) - size; idx = (pos + size) >> PAGE_SHIFT; do { - folio = read_mapping_folio(vi->i_mapping, idx, NULL); + folio = ntfs_read_metadata_folio(vi->i_mapping, idx); if (IS_ERR(folio)) { ntfs_error(vi->i_sb, "Error mapping LogFile page (index %lu).", idx); @@ -514,7 +514,7 @@ bool ntfs_check_logfile(struct inode *log_vi, struct restart_page_header **rp) kunmap_local(kbase); folio_put(folio); } - folio = read_mapping_folio(mapping, idx, NULL); + folio = ntfs_read_metadata_folio(mapping, idx); if (IS_ERR(folio)) { ntfs_error(vol->sb, "Error mapping LogFile page (index %lu).", idx); diff --git a/fs/ntfs/mft.c b/fs/ntfs/mft.c index 60734500a40624..d2852fc68838c4 100644 --- a/fs/ntfs/mft.c +++ b/fs/ntfs/mft.c @@ -143,7 +143,7 @@ static inline struct mft_record *map_mft_record_folio(struct ntfs_inode *ni) } /* Read, map, and pin the folio. */ - folio = read_mapping_folio(mft_vi->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(mft_vi->i_mapping, index); if (!IS_ERR(folio)) { u8 *addr; @@ -549,8 +549,8 @@ static int ntfs_sync_mft_mirror_unit(struct ntfs_volume *vol, if (unit->folio_ofs + unit->len > folio_size(source)) return -EIO; - mirror = read_mapping_folio(vol->mftmirr_ino->i_mapping, - mirror_file_ofs >> PAGE_SHIFT, NULL); + mirror = ntfs_read_metadata_folio(vol->mftmirr_ino->i_mapping, + mirror_file_ofs >> PAGE_SHIFT); if (IS_ERR(mirror)) return PTR_ERR(mirror); @@ -1023,7 +1023,7 @@ static bool mft_reserved_is_free(struct ntfs_volume *vol, if (!m) return false; - folio = read_mapping_folio(vol->mft_ino->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(vol->mft_ino->i_mapping, index); if (IS_ERR(folio)) goto free_m; @@ -1199,8 +1199,8 @@ static s64 mft_bitmap_alloc_free_rec(struct ntfs_volume *vol, * for a zero bit. */ if (size) { - folio = read_mapping_folio(mftbmp_mapping, - ofs >> PAGE_SHIFT, NULL); + folio = ntfs_read_metadata_folio(mftbmp_mapping, + ofs >> PAGE_SHIFT); if (IS_ERR(folio)) { ntfs_error(vol->sb, "Failed to read mft bitmap, aborting."); return PTR_ERR(folio); @@ -1392,8 +1392,8 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(struct ntfs_volume *vol) * to us. */ ll = lcn >> 3; - folio = read_mapping_folio(vol->lcnbmp_ino->i_mapping, - ll >> PAGE_SHIFT, NULL); + folio = ntfs_read_metadata_folio(vol->lcnbmp_ino->i_mapping, + ll >> PAGE_SHIFT); if (IS_ERR(folio)) { up_write(&mftbmp_ni->runlist.lock); ntfs_error(vol->sb, "Failed to read from lcn bitmap."); @@ -2207,7 +2207,7 @@ static int ntfs_mft_record_format(const struct ntfs_volume *vol, const s64 mft_n } /* Read, map, and pin the folio containing the mft record. */ - folio = read_mapping_folio(mft_vi->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(mft_vi->i_mapping, index); if (IS_ERR(folio)) { ntfs_error(vol->sb, "Failed to map page containing mft record to format 0x%llx.", (long long)mft_no); @@ -2725,7 +2725,7 @@ int ntfs_mft_record_alloc(struct ntfs_volume *vol, const int mode, index = NTFS_MFT_NR_TO_PIDX(vol, bit); ofs = NTFS_MFT_NR_TO_POFS(vol, bit); /* Read, map, and pin the folio containing the mft record. */ - folio = read_mapping_folio(vol->mft_ino->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(vol->mft_ino->i_mapping, index); if (IS_ERR(folio)) { ntfs_error(vol->sb, "Failed to map page containing allocated mft record 0x%llx.", bit); diff --git a/fs/ntfs/ntfs.h b/fs/ntfs/ntfs.h index fac72d40f5832b..f33df986f5eea8 100644 --- a/fs/ntfs/ntfs.h +++ b/fs/ntfs/ntfs.h @@ -294,6 +294,10 @@ static inline int ntfs_ffs(int x) return r; } +/* From fs/ntfs/aops.c */ +struct folio *ntfs_read_metadata_folio(struct address_space *mapping, + pgoff_t index); + /* From fs/ntfs/bdev-io.c */ int ntfs_bdev_read(struct block_device *bdev, char *data, loff_t start, size_t size); int ntfs_bdev_write(struct super_block *sb, void *buf, loff_t start, size_t size); diff --git a/fs/ntfs/super.c b/fs/ntfs/super.c index f38f3543499539..103d2b1b630ba0 100644 --- a/fs/ntfs/super.c +++ b/fs/ntfs/super.c @@ -1187,8 +1187,8 @@ static bool check_mft_mirror(struct ntfs_volume *vol) folio_put(mft_folio); } /* Get the $MFT page. */ - mft_folio = read_mapping_folio(vol->mft_ino->i_mapping, - index, NULL); + mft_folio = ntfs_read_metadata_folio(vol->mft_ino->i_mapping, + index); if (IS_ERR(mft_folio)) { ntfs_error(sb, "Failed to read $MFT."); return false; @@ -1196,8 +1196,8 @@ static bool check_mft_mirror(struct ntfs_volume *vol) kmft_base = kmap_local_folio(mft_folio, 0); kmft = kmft_base; /* Get the $MFTMirr page. */ - mirr_folio = read_mapping_folio(vol->mftmirr_ino->i_mapping, - index, NULL); + mirr_folio = ntfs_read_metadata_folio(vol->mftmirr_ino->i_mapping, + index); if (IS_ERR(mirr_folio)) { ntfs_error(sb, "Failed to read $MFTMirr."); goto mft_unmap_out; @@ -1404,7 +1404,7 @@ static int check_windows_hibernation_status(struct ntfs_volume *vol) goto iput_out; } - folio = read_mapping_folio(vi->i_mapping, 0, NULL); + folio = ntfs_read_metadata_folio(vi->i_mapping, 0); if (IS_ERR(folio)) { ntfs_error(vol->sb, "Failed to read from hiberfil.sys."); ret = PTR_ERR(folio); @@ -1469,7 +1469,7 @@ static bool load_and_init_attrdef(struct ntfs_volume *vol) while (index < max_index) { /* Read the attrdef table and copy it into the linear buffer. */ read_partial_attrdef_page: - folio = read_mapping_folio(ino->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(ino->i_mapping, index); if (IS_ERR(folio)) goto free_iput_failed; addr = kmap_local_folio(folio, 0); @@ -1535,7 +1535,7 @@ static bool load_and_init_upcase(struct ntfs_volume *vol) while (index < max_index) { /* Read the upcase table and copy it into the linear buffer. */ read_partial_upcase_page: - folio = read_mapping_folio(ino->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(ino->i_mapping, index); if (IS_ERR(folio)) goto iput_upcase_failed; addr = kmap_local_folio(folio, 0); From ea04295b4f1f4c40b955e85f432ddde72f659ee3 Mon Sep 17 00:00:00 2001 From: Wahid Khan Date: Sat, 14 Nov 2026 13:04:51 +0530 Subject: [PATCH 1325/2102] ntfs: convert a named $DATA stream safely when making room in a record When an attribute has to grow and the mft record is full, ntfs_resident_attr_resize() walks the other resident attributes and converts them to non-resident ones. For $DATA it always opens the unnamed data inode of the base inode, even if the attribute found is a named stream: tvi = ntfs_iget(sb, base_ni->mft_no); ntfs_attr_make_non_resident(NTFS_I(tvi), value_len); value_len is the length of the stream, so it does not match the attribute that ntfs_attr_make_non_resident() looks up for the unnamed inode, and the WARN_ON() on entry fires: WARNING: fs/ntfs/attrib.c:2115 at ntfs_attr_make_non_resident ntfs_resident_attr_resize ntfs_attr_expand_locked ntfs_expand_for_write ntfs_file_write_iter vfs_write It does not need a damaged volume. A file with an alternate data stream whose record has no room left is enough. Open a named stream by name with ntfs_attr_iget(), as is done for the other attribute types in this loop, and keep ntfs_iget() for the unnamed one. The loop runs with the mft record lock held and takes no lock of the stream inode, so converting a stream from here needs more care than the plain lookup gives: - A reader of the stream holds the folio lock and then takes the mft record lock in ntfs_read_iomap_begin_resident(), the conversion takes them the other way round and waits for folio 0. Take the folio with FGP_NOWAIT in this loop and skip the attribute if it is busy. The loop only tries to free space. The same inversion exists for the conversion of the attribute being resized, which waited for folio 0 with the lock held and hangs against an mmap fault or splice reader. Use FGP_NOWAIT there too. The resize then fails with -EBUSY while such a reader is stuck on the lock, instead of hanging. Do not look for room in other attributes either: the reader keeps the folio until the lock is dropped, so the attribute can neither be converted nor written without waiting for it, and the loop would only convert other attributes for nothing. FGP_NOWAIT also fails when the folio can not be allocated, so on failure look the folio up: only one that is there means a busy folio, otherwise return -ENOMEM. - A stream that is in the inode cache can be open, being written, being removed or already unlinked. A write that passed its residency check before the conversion carries on with a non-resident attribute, and a stream in the middle of ntfs_stream_finish_remove() is converted under its feet. Convert only a stream that is not cached. - An attribute inode of a file that has no links left is evicted on the last iput() with its dirty folio, so what was converted is lost and an open file reads its extended attributes back as missing. Convert nothing, of any type, in a file that is being deleted or has no links left. - The unnamed data is converted through the file's own inode, whose i_rwsem only a resize of the unnamed data itself holds. When a stream or an extended attribute is being resized, a writer of the file can have passed its residency check and carry on with a non-resident attribute (iomap_iter warnings, recursive mrec_lock). When the unnamed data is the attribute being resized, its conversion was just tried by the caller. Do not convert the unnamed data from this loop. - Do not convert the attribute that is being resized either. Its conversion was just tried and failed, for instance on a busy folio, and a second try that succeeds leaves the resize to go on with the resident layout of a record that is now non-resident. - The lookup of a stream ignores case, so a stream whose name differs only in case from an earlier one resolves to that one and the length does not match again. Compare the names exactly. Fixes: 495e90fa3348 ("ntfs: update attrib operations") Cc: stable@vger.kernel.org # v7.1+ Signed-off-by: Wahid Khan Reviewed-by: Baolin Liu Signed-off-by: Namjae Jeon --- fs/ntfs/attrib.c | 109 +++++++++++++++++++++++++++++++++++++++++++---- fs/ntfs/inode.c | 19 +++++++++ fs/ntfs/inode.h | 2 + 3 files changed, 121 insertions(+), 9 deletions(-) diff --git a/fs/ntfs/attrib.c b/fs/ntfs/attrib.c index 1a3ee7da240b5a..9266a3ea3b0f38 100644 --- a/fs/ntfs/attrib.c +++ b/fs/ntfs/attrib.c @@ -1975,7 +1975,21 @@ int ntfs_resident_attr_value_resize(struct mft_record *m, struct attr_record *a, * inode i_size is that this is not necessarily uptodate. This happens when * ntfs_attr_make_non_resident() is called in the ->truncate call path(s). */ +static int __ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size, + bool nowait); + int ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size) +{ + return __ntfs_attr_make_non_resident(ni, data_size, false); +} + +/* + * With @nowait the folio lock is only tried: a caller that holds mrec_lock + * must not wait for a folio lock, the read path takes them the other way + * round. Fails with -EAGAIN if the folio is locked. + */ +static int __ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size, + bool nowait) { s64 new_size; struct inode *vi = VFS_I(ni); @@ -2056,10 +2070,23 @@ int ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size) * outside all ntfs locks, we need to get the folio now. */ folio = __filemap_get_folio(vi->i_mapping, 0, - FGP_CREAT | FGP_LOCK, + FGP_CREAT | FGP_LOCK | + (nowait ? FGP_NOWAIT : 0), mapping_gfp_mask(vi->i_mapping)); if (IS_ERR(folio)) { err = -ENOMEM; + if (nowait) { + /* + * FGP_NOWAIT also fails when it can not + * allocate the folio. Only a folio that is + * there and locked means a busy folio. + */ + folio = filemap_get_folio(vi->i_mapping, 0); + if (!IS_ERR(folio)) { + folio_put(folio); + err = -EAGAIN; + } + } goto err_out; } @@ -4895,8 +4922,23 @@ static int ntfs_resident_attr_resize(struct ntfs_inode *attr_ni, const s64 newsi /* There is not enough space in the mft record to perform the resize. */ /* Make the attribute non-resident if possible. */ - err = ntfs_attr_make_non_resident(attr_ni, - le32_to_cpu(ctx->attr->data.resident.value_length)); + err = __ntfs_attr_make_non_resident(attr_ni, + le32_to_cpu(ctx->attr->data.resident.value_length), true); + /* + * A reader holding folio 0 waits for mrec_lock, which we hold. Do not + * wait for it and do not look for room elsewhere either: the reader + * keeps the folio until we drop the lock, so the attribute can neither + * be converted nor written without waiting for it, and the loop below + * would only convert other attributes for nothing. + */ + if (err == -EAGAIN) { + /* + * Not -EAGAIN, it would reach user space and index.c uses it + * for its own retry. Not -ENOSPC, the record is not full. + */ + err = -EBUSY; + goto put_err_out; + } if (!err) { mark_mft_record_dirty(ctx->ntfs_ino); ntfs_attr_put_search_ctx(ctx); @@ -4913,12 +4955,14 @@ static int ntfs_resident_attr_resize(struct ntfs_inode *attr_ni, const s64 newsi while (!(err = ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx))) { struct inode *tvi; struct attr_record *a; + __le16 *name; u32 value_len; a = ctx->attr; if (a->non_resident || a->type == AT_ATTRIBUTE_LIST) continue; value_len = le32_to_cpu(a->data.resident.value_length); + name = (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)); if (ntfs_attr_can_be_non_resident(vol, a->type)) continue; @@ -4933,18 +4977,65 @@ static int ntfs_resident_attr_resize(struct ntfs_inode *attr_ni, const s64 newsi if (a->type == AT_DATA && !value_len) continue; - if (a->type == AT_DATA) - tvi = ntfs_iget(sb, base_ni->mft_no); - else - tvi = ntfs_attr_iget(VFS_I(base_ni), a->type, - (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)), + /* + * The attribute inode of an unlinked file is evicted on the + * last iput() together with its dirty folio. + */ + if (NInoBeingDeleted(base_ni) || !VFS_I(base_ni)->i_nlink) + continue; + + /* + * Not the attribute being resized. Its conversion was tried + * above and failed, for instance on a busy folio, and + * converting it here would leave the resize to go on with the + * resident layout of a non-resident record. + */ + if (a->type == attr_ni->type && + a->name_length == attr_ni->name_len && + (!a->name_length || + !memcmp(name, attr_ni->name, + a->name_length * sizeof(__le16)))) + continue; + + /* + * Not the unnamed data either. Only the resize of the unnamed + * data itself holds its i_rwsem, a writer of the file can be + * between its residency check and the mft record lock. + */ + if (a->type == AT_DATA && !a->name_length) + continue; + + /* + * A named $DATA stream is converted only if nobody has it open: + * an open one can be unlinked, being removed or in use. A WOF + * file reads its stream from the device, so the stream must + * stay resident. + */ + if (a->type == AT_DATA) { + if (NInoWofCompressed(base_ni)) + continue; + tvi = ntfs_attr_ilookup(VFS_I(base_ni), a->type, + name, a->name_length); + if (tvi) { + iput(tvi); + continue; + } + } + tvi = ntfs_attr_iget(VFS_I(base_ni), a->type, name, a->name_length); + /* the lookup ignores case for streams, ours does not */ + if (!IS_ERR(tvi) && a->type == AT_DATA && + memcmp(NTFS_I(tvi)->name, name, + a->name_length * sizeof(__le16))) { + iput(tvi); + continue; + } if (IS_ERR(tvi)) { ntfs_error(sb, "Couldn't open attribute"); continue; } - if (ntfs_attr_make_non_resident(NTFS_I(tvi), value_len)) { + if (__ntfs_attr_make_non_resident(NTFS_I(tvi), value_len, true)) { iput(tvi); continue; } diff --git a/fs/ntfs/inode.c b/fs/ntfs/inode.c index 20949ac16f34e4..6a9f488e277509 100644 --- a/fs/ntfs/inode.c +++ b/fs/ntfs/inode.c @@ -287,6 +287,25 @@ struct inode *ntfs_attr_iget(struct inode *base_vi, __le32 type, return vi; } +/* + * ntfs_attr_ilookup - find an attribute inode that is already in the cache + * + * Like ntfs_attr_iget() but never reads anything. Returns the inode with an + * increased reference count, or NULL if it is not cached. + */ +struct inode *ntfs_attr_ilookup(struct inode *base_vi, __le32 type, + __le16 *name, u32 name_len) +{ + struct ntfs_attr na = { + .mft_no = base_vi->i_ino, + .type = type, + .name = name, + .name_len = name_len, + }; + + return ilookup5(base_vi->i_sb, na.mft_no, ntfs_test_inode, &na); +} + /* * ntfs_index_iget - obtain a struct inode corresponding to an index * @base_vi: vfs base inode containing the index related attributes diff --git a/fs/ntfs/inode.h b/fs/ntfs/inode.h index a18cbcf1c6312e..7ea52c59c04b56 100644 --- a/fs/ntfs/inode.h +++ b/fs/ntfs/inode.h @@ -326,6 +326,8 @@ struct ntfs_attr { int ntfs_test_inode(struct inode *vi, void *data); int ntfs_test_inode_rcu(struct inode *vi, void *data); struct inode *ntfs_iget(struct super_block *sb, u64 mft_no); +struct inode *ntfs_attr_ilookup(struct inode *base_vi, __le32 type, + __le16 *name, u32 name_len); struct inode *ntfs_attr_iget(struct inode *base_vi, __le32 type, __le16 *name, u32 name_len); struct inode *ntfs_index_iget(struct inode *base_vi, __le16 *name, From 2f7928516314f37d7cb334675656b4412edc8be3 Mon Sep 17 00:00:00 2001 From: Tao Cui Date: Thu, 12 Nov 2026 22:49:34 +0800 Subject: [PATCH 1326/2102] sched/core: Pass ENQUEUE_RQ_SELECTED on initial enqueue select_task_rq() sets WF_RQ_SELECTED and ttwu_do_activate() maps it to ENQUEUE_RQ_SELECTED so enqueue_task_scx() knows whether ops.select_cpu() ran. wake_up_new_task() also calls select_task_rq() but activates the new task without the flag, so on the fork path ops.enqueue() never sees SCX_ENQ_CPU_SELECTED and SCX_EV_SELECT_CPU_FALLBACK never counts a fork-path fallback: a misbehaving select_cpu() leaves no trace in the counters, and schedulers testing SCX_ENQ_CPU_SELECTED run a redundant select_cpu_dfl() on tasks select_cpu() already placed. Set ENQUEUE_RQ_SELECTED on the initial enqueue when select_task_rq() was called, matching the wakeup path. Only sched_ext consumes the flag. Fixes: 9b671793c7d9 ("sched_ext, scx_qmap: Add and use SCX_ENQ_CPU_SELECTED") Cc: stable@vger.kernel.org # v6.12+ Signed-off-by: Tao Cui Signed-off-by: Tejun Heo --- kernel/sched/core.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/kernel/sched/core.c b/kernel/sched/core.c index 04b62c16fa8ca0..f7a452123ef552 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -5016,6 +5016,7 @@ void wake_up_new_task(struct task_struct *p) struct rq_flags rf; struct rq *rq; int wake_flags = WF_FORK; + int en_flags = ENQUEUE_NOCLOCK | ENQUEUE_INITIAL; raw_spin_lock_irqsave(&p->pi_lock, rf.flags); WRITE_ONCE(p->__state, TASK_RUNNING); @@ -5029,11 +5030,13 @@ void wake_up_new_task(struct task_struct *p) */ p->recent_used_cpu = task_cpu(p); __set_task_cpu(p, select_task_rq(p, task_cpu(p), &wake_flags)); + if (wake_flags & WF_RQ_SELECTED) + en_flags |= ENQUEUE_RQ_SELECTED; rq = __task_rq_lock(p, &rf); update_rq_clock(rq); post_init_entity_util_avg(p); - activate_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_INITIAL); + activate_task(rq, p, en_flags); trace_sched_wakeup_new(p); wakeup_preempt(rq, p, wake_flags); if (p->sched_class->task_woken) { From 7d49d6e0898680925ea410cbb9d1a6a0e6441462 Mon Sep 17 00:00:00 2001 From: Han Gao Date: Sat, 21 Nov 2026 18:38:07 +0800 Subject: [PATCH 1327/2102] riscv: efi: Map runtime MMIO with device attributes EFI_MEMORY_MAPPED_IO regions are mapped with PAGE_KERNEL, so device registers end up mapped as normal memory. On Milk-V Pioneer, GetTime() reads the clock controller registers and faults: Oops - load access fault [#1] Workqueue: efi_runtime efi_call_rts status: 0000000200000120 badaddr: 0000007030012000 cause: 0000000000000005 Use PAGE_KERNEL_IO for these regions. Fixes: b91540d52a08 ("RISC-V: Add EFI runtime services") Signed-off-by: Han Gao Signed-off-by: Ard Biesheuvel --- arch/riscv/kernel/efi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/riscv/kernel/efi.c b/arch/riscv/kernel/efi.c index 2d3cc57b453525..11e85d0ebc911a 100644 --- a/arch/riscv/kernel/efi.c +++ b/arch/riscv/kernel/efi.c @@ -22,7 +22,7 @@ static __init pgprot_t efimem_to_pgprot_map(efi_memory_desc_t *md) u32 type = md->type; if (type == EFI_MEMORY_MAPPED_IO) - return PAGE_KERNEL; + return PAGE_KERNEL_IO; /* R-- */ if ((attr & (EFI_MEMORY_XP | EFI_MEMORY_RO)) == From ae3398a7da224e1cb14a04ce8e9da66fc2948121 Mon Sep 17 00:00:00 2001 From: Richard Weinberger Date: Thu, 25 Jun 2026 11:06:27 +0200 Subject: [PATCH 1328/2102] x86/Kconfig: Enable ROX also when STRICT_KERNEL_RWX is present Running a kernel with CONFIG_MODULES=n causes the W+X page detection to trigger: x86/mm: Found insecure W+X mapping at address 0xffffffffc033a000 The W+X pages come from __its_alloc() with type being EXECMEM_MODULE_TEXT. Without ARCH_HAS_EXECMEM_ROX pgprot is PAGE_KERNEL instead of PAGE_KERNEL_ROX. Fixes: 47410d839fcda ("x86/Kconfig: only enable ROX cache in execmem when STRICT_MODULE_RWX is set") Suggested-by: Mike Rapoport (Microsoft) Signed-off-by: Richard Weinberger Signed-off-by: Borislav Petkov (AMD) Acked-by: Peter Zijlstra (Intel) Acked-by: Mike Rapoport (Microsoft) Tested-by: Vinny Horgan Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20260625090627.1501095-1-richard@nod.at --- arch/x86/Kconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig index 58dce0b66179b6..3159852fd6b3ec 100644 --- a/arch/x86/Kconfig +++ b/arch/x86/Kconfig @@ -84,7 +84,7 @@ config X86 select ARCH_HAS_DMA_OPS if GART_IOMMU || XEN select ARCH_HAS_EARLY_DEBUG if KGDB select ARCH_HAS_ELF_RANDOMIZE - select ARCH_HAS_EXECMEM_ROX if X86_64 && STRICT_MODULE_RWX + select ARCH_HAS_EXECMEM_ROX if X86_64 && (STRICT_MODULE_RWX || STRICT_KERNEL_RWX) select ARCH_HAS_FAST_MULTIPLIER select ARCH_HAS_FORTIFY_SOURCE select ARCH_HAS_GCOV_PROFILE_ALL From fa827805a62967723f5a962da1849c627f8ad509 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Tue, 17 Nov 2026 16:25:30 +0100 Subject: [PATCH 1329/2102] net: don't leak pidfds through a short SO_PEERPIDFD optlen sk_getsockopt_peerpidfd() caps the caller's optlen at sizeof(int) but never checks that it is at least that large. sk_getsockopt() only rejects a negative optlen. So with an optlen of 0 to 3 we still allocate a pidfd via pidfd_prepare(), copy zero to three bytes of the fd number to userspace, write the short optlen back and then fd_install() the pidfd anyway. getsockopt() reports success but the caller only got part of the fd number or none of it at all. It has no sane way to find out which fd it has to close and the pidfd stays in its file descriptor table until the process exits. Calling it in a loop fills up the table. scm_pidfd_recv() deals with the same problem for SCM_PIDFD. Since put_cmsg() doesn't fail on truncation it checks the size of the control buffer itself and sets MSG_CTRUNC before it allocates a pidfd. There's no point in handing out part of a file descriptor number. So fail with EINVAL if optlen is smaller than sizeof(int) before we prepare a pidfd. Since commit e10899b2a098 ("net: add SO_PEERPIDFD_THREAD to get a thread-specific pidfd") SO_PEERPIDFD and SO_PEERPIDFD_THREAD share the helper and the latter inherited the bug, so this fixes both. Fixes: 7b26952a91cf ("net: core: add getsockopt SO_PEERPIDFD") Cc: stable@vger.kernel.org Reported-by: Sashiko Closes: https://lore.kernel.org/all/sashiko-outbox-205984@kernel.org Signed-off-by: Christian Brauner (Amutable) Reviewed-by: Alexander Mikhalitsyn Reviewed-by: Kuniyuki Iwashima Link: https://patch.msgid.link/20261117-work-net-peerpidfd_short_optlen-v1-1-a93f56288501@kernel.org Signed-off-by: Jakub Kicinski --- net/core/sock.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/net/core/sock.c b/net/core/sock.c index ad414878dc5ba8..74a00a5e2d1165 100644 --- a/net/core/sock.c +++ b/net/core/sock.c @@ -1746,8 +1746,10 @@ static int sk_getsockopt_peerpidfd(struct sock *sk, enum pid_type type, struct pid *peer_pid; int pidfd; - if (len > sizeof(pidfd)) - len = sizeof(pidfd); + /* Userspace can't close a pidfd whose number it didn't get. */ + if (len < sizeof(pidfd)) + return -EINVAL; + len = sizeof(pidfd); spin_lock(&sk->sk_peer_lock); peer_pid = get_pid(sk->sk_peer_pid[type]); From c9b3eb7bfd7f2bb7c045761ff8e2007487b15c62 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Tue, 17 Nov 2026 16:25:31 +0100 Subject: [PATCH 1330/2102] selftests/net: check that a short SO_PEERPIDFD optlen fails Cover SO_PEERPIDFD and SO_PEERPIDFD_THREAD with an optlen of 0 to 3: - getsockopt() fails with EINVAL - optlen and the buffer stay untouched - no pidfd is installed in the file descriptor table Check that a full-sized buffer still gets a pidfd. Signed-off-by: Christian Brauner (Amutable) Reviewed-by: Alexander Mikhalitsyn Reviewed-by: Kuniyuki Iwashima Link: https://patch.msgid.link/20261117-work-net-peerpidfd_short_optlen-v1-2-a93f56288501@kernel.org Signed-off-by: Jakub Kicinski --- .../testing/selftests/net/af_unix/scm_pidfd.c | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/tools/testing/selftests/net/af_unix/scm_pidfd.c b/tools/testing/selftests/net/af_unix/scm_pidfd.c index cbe53fab44fc5a..c26f055a190327 100644 --- a/tools/testing/selftests/net/af_unix/scm_pidfd.c +++ b/tools/testing/selftests/net/af_unix/scm_pidfd.c @@ -1155,4 +1155,55 @@ TEST(so_peerpidfd_thread) close(server); } +/* The lowest free file descriptor, where the next pidfd would land. */ +static int lowest_free_fd(int fd) +{ + int nfd; + + nfd = dup(fd); + if (nfd >= 0) + close(nfd); + return nfd; +} + +/* A short optlen must fail without installing a pidfd. */ +TEST(so_peerpidfd_short_optlen) +{ + const int optnames[] = { SO_PEERPIDFD, SO_PEERPIDFD_THREAD }; + int sv[2], i, free_fd, pidfd; + socklen_t len, optlen; + + ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sv)); + + for (i = 0; i < ARRAY_SIZE(optnames); i++) { + for (len = 0; len < sizeof(pidfd); len++) { + free_fd = lowest_free_fd(sv[0]); + ASSERT_LE(0, free_fd); + + pidfd = -1; + optlen = len; + ASSERT_EQ(-1, getsockopt(sv[0], SOL_SOCKET, optnames[i], + &pidfd, &optlen)); + ASSERT_EQ(EINVAL, errno); + EXPECT_EQ(len, optlen); + EXPECT_EQ(-1, pidfd); + + /* No pidfd was installed behind our back. */ + ASSERT_EQ(free_fd, lowest_free_fd(sv[0])); + } + + /* A full-sized buffer still gets the pidfd. */ + free_fd = lowest_free_fd(sv[0]); + optlen = sizeof(pidfd); + ASSERT_EQ(0, getsockopt(sv[0], SOL_SOCKET, optnames[i], + &pidfd, &optlen)); + EXPECT_EQ(sizeof(pidfd), optlen); + EXPECT_EQ(free_fd, pidfd); + close(pidfd); + } + + close(sv[0]); + close(sv[1]); +} + TEST_HARNESS_MAIN From a6c2f5e46b9a1179981036070e03f799621e349f Mon Sep 17 00:00:00 2001 From: Krzysztof Kozlowski Date: Fri, 13 Nov 2026 19:52:16 +0100 Subject: [PATCH 1331/2102] riscv: dts: spacemit: k1: Correct missing space Correct minor style issue around white-space - missing space. Signed-off-by: Krzysztof Kozlowski Reviewed-by: Yixun Lan Reviewed-by: Troy Mitchell Link: https://patch.msgid.link/20261113185214.182695-4-krzysztof.kozlowski@oss.qualcomm.com Signed-off-by: Paul Walmsley --- arch/riscv/boot/dts/spacemit/k1.dtsi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/riscv/boot/dts/spacemit/k1.dtsi b/arch/riscv/boot/dts/spacemit/k1.dtsi index 542bfc0d19f55a..5d5f7f8a393d37 100644 --- a/arch/riscv/boot/dts/spacemit/k1.dtsi +++ b/arch/riscv/boot/dts/spacemit/k1.dtsi @@ -948,7 +948,7 @@ resets = <&syscon_apmu RESET_DMA>; interrupts = <72>; dma-channels = <16>; - #dma-cells= <1>; + #dma-cells = <1>; status = "disabled"; }; From 27fc871b963183d9371cc838c1a543033d91357f Mon Sep 17 00:00:00 2001 From: Vladimir Kondratiev Date: Wed, 11 Nov 2026 12:41:21 +0200 Subject: [PATCH 1332/2102] riscv: unaligned: fix __setup handlers Returning -EINVAL from a __setup() callback cause invalid unaligned_scalar_speed= and unaligned_vector_speed= values to be treated as handled. obsolete_checksetup() treats any non-zero return value from setup_func() as success, so an unrecognized argument is silently accepted instead of being reported as an unknown boot option. __setup() handlers return 0 on failure. Fixes: aecb09e091dc ("riscv: Add parameter for skipping access speed tests") Signed-off-by: Vladimir Kondratiev Reviewed-by: Jisheng Zhang Link: https://patch.msgid.link/20261111-fix-riscv-unaligned-v1-1-0722514fc1e4@mobileye.com Cc: stable@vger.kernel.org Signed-off-by: Paul Walmsley --- arch/riscv/kernel/unaligned_access_speed.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/arch/riscv/kernel/unaligned_access_speed.c b/arch/riscv/kernel/unaligned_access_speed.c index 67f1a03716597a..323ccfcfbbb726 100644 --- a/arch/riscv/kernel/unaligned_access_speed.c +++ b/arch/riscv/kernel/unaligned_access_speed.c @@ -322,7 +322,7 @@ static int __init set_unaligned_scalar_speed_param(char *str) else if (!strcmp(str, speed_str[RISCV_HWPROBE_MISALIGNED_SCALAR_UNSUPPORTED])) unaligned_scalar_speed_param = RISCV_HWPROBE_MISALIGNED_SCALAR_UNSUPPORTED; else - return -EINVAL; + return 0; return 1; } @@ -337,7 +337,7 @@ static int __init set_unaligned_vector_speed_param(char *str) else if (!strcmp(str, speed_str[RISCV_HWPROBE_MISALIGNED_VECTOR_UNSUPPORTED])) unaligned_vector_speed_param = RISCV_HWPROBE_MISALIGNED_VECTOR_UNSUPPORTED; else - return -EINVAL; + return 0; return 1; } From fc91dacd0c2b4f9ca7e0ce30016f5aee6256cba5 Mon Sep 17 00:00:00 2001 From: Marek Szyprowski Date: Wed, 4 Nov 2026 11:46:03 +0100 Subject: [PATCH 1333/2102] riscv: mm: reserve the DTB before scanning reserved memory early_init_fdt_scan_reserved_mem() allocates memory from memblock while it scans /reserved-memory: the reserved_mem array, and the regions that are placed dynamically by size. On RISC-V the DTB was only reserved after that scan, so memblock could hand out the memory the DTB occupies while the DTB was still being parsed. Reserve the DTB before the scan, so that memblock never allocates from it. Fixes: ef69d2559fe9 ("riscv: Move early dtb mapping into the fixmap region") Closes: https://lore.kernel.org/all/b71ac175-fba5-4f61-bbdb-0b98dec9ccee@samsung.com/ Signed-off-by: Marek Szyprowski Link: https://patch.msgid.link/20261104104604.3370384-1-m.szyprowski@samsung.com Cc: stable@vger.kernel.org Signed-off-by: Paul Walmsley --- arch/riscv/mm/init.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/arch/riscv/mm/init.c b/arch/riscv/mm/init.c index 070ee69eabb381..d73688402b5050 100644 --- a/arch/riscv/mm/init.c +++ b/arch/riscv/mm/init.c @@ -294,13 +294,6 @@ static void __init setup_bootmem(void) reserve_initrd_mem(); - /* - * No allocation should be done before reserving the memory as defined - * in the device tree, otherwise the allocation could end up in a - * reserved region. - */ - early_init_fdt_scan_reserved_mem(); - /* * If DTB is built in, no need to reserve its memblock. * Otherwise, do reserve it but avoid using @@ -309,6 +302,13 @@ static void __init setup_bootmem(void) */ if (!IS_ENABLED(CONFIG_BUILTIN_DTB)) memblock_reserve(dtb_early_pa, fdt_totalsize(dtb_early_va)); + + /* + * No allocation should be done before reserving the memory as defined + * in the device tree, otherwise the allocation could end up in a + * reserved region. + */ + early_init_fdt_scan_reserved_mem(); } #ifdef CONFIG_RELOCATABLE From 5924465bb4e986eae6809c899ddaf38d3897f55d Mon Sep 17 00:00:00 2001 From: Haishuang Yan Date: Mon, 16 Nov 2026 20:56:19 +0900 Subject: [PATCH 1334/2102] net: do not run out of frags in alloc_skb_with_frags() alloc_skb_with_frags() can need more than MAX_SKB_FRAGS frags for a data_len that passed its size check, and then fails with -ENOBUFS: - the tail is split into one frag per bit set in its page count; - after a failed high-order allocation, the order is lowered without checking that the frags left can hold the rest. tun hits this with large GSO packets from a vhost-net guest. Use one larger page for the tail when splitting it would not fit. Only lower the order if the rest still fits, else retry the same order with direct reclaim. If that retry fails too, the allocation still fails. Found while prototyping >64K TSO in a virtio-net guest. Tested with that guest, page allocation fault injection and the KUnit test in patch 2. Fixes: 09c2c90705bb ("net: allow alloc_skb_with_frags() to allocate bigger packets") Signed-off-by: Haishuang Yan Link: https://patch.msgid.link/20261116115620.18151-2-yanhaishuang@cmss.chinamobile.com Signed-off-by: Jakub Kicinski --- net/core/skbuff.c | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/net/core/skbuff.c b/net/core/skbuff.c index 33735e8ca69be8..85d5caa0888777 100644 --- a/net/core/skbuff.c +++ b/net/core/skbuff.c @@ -6944,17 +6944,40 @@ struct sk_buff *alloc_skb_with_frags(unsigned long header_len, while (data_len) { if (nr_frags == MAX_SKB_FRAGS) goto failure; - while (order && PAGE_ALIGN(data_len) < (PAGE_SIZE << order)) - order--; + if (order && PAGE_ALIGN(data_len) < (PAGE_SIZE << order)) { + unsigned long pages = DIV_ROUND_UP(data_len, PAGE_SIZE); + + /* If splitting the rest into smaller pages would need + * more frags than we have left, use one larger page. + */ + if (hweight_long(pages) > MAX_SKB_FRAGS - nr_frags) + order = order_base_2(pages); + else + order = ilog2(pages); + } if (order) { page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) | __GFP_COMP | __GFP_NOWARN, order); - if (!page) { - order--; - continue; + if (unlikely(!page)) { + unsigned int shift = PAGE_SHIFT + order - 1; + + /* Can smaller pages hold the rest? */ + if (((data_len - 1) >> shift) + 1 <= + MAX_SKB_FRAGS - nr_frags) { + order--; + continue; + } + /* No, retry this order with direct reclaim. */ + if (!gfpflags_allow_blocking(gfp_mask)) + goto failure; + page = alloc_pages(gfp_mask | __GFP_COMP | + __GFP_NOWARN | __GFP_NORETRY, + order); + if (!page) + goto failure; } } else { page = alloc_page(gfp_mask); From e8c39bfac24d488218b77c4535c257c3d549a720 Mon Sep 17 00:00:00 2001 From: Haishuang Yan Date: Mon, 16 Nov 2026 20:56:20 +0900 Subject: [PATCH 1335/2102] net: add a KUnit test for the alloc_skb_with_frags() tail split Allocate MAX_SKB_FRAGS - 2 full order-3 chunks plus a 7 page tail, which needs one frag too many if the tail is rounded down to 4 + 2 + 1 pages. If the allocation fails, skip the test unless MAX_SKB_FRAGS - 1 order-3 pages can be held at once, so that fragmented memory is not reported as a failure. Signed-off-by: Haishuang Yan Link: https://patch.msgid.link/20261116115620.18151-3-yanhaishuang@cmss.chinamobile.com Signed-off-by: Jakub Kicinski --- net/core/net_test.c | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/net/core/net_test.c b/net/core/net_test.c index c36333b362115f..47f5dc0fa5cf68 100644 --- a/net/core/net_test.c +++ b/net/core/net_test.c @@ -1723,7 +1723,58 @@ static void netmem_ref_test_tcp_devmem_recv(struct kunit *test) #endif #endif +/* Can @nr pages of @order be allocated and held at the same time? */ +static bool alloc_skb_with_frags_test_have_pages(unsigned int nr, + unsigned int order) +{ + struct page *pages[MAX_SKB_FRAGS]; + unsigned int i, n; + + for (n = 0; n < nr; n++) { + pages[n] = alloc_pages(GFP_KERNEL | __GFP_NOWARN | + __GFP_NORETRY, order); + if (!pages[n]) + break; + } + for (i = 0; i < n; i++) + __free_pages(pages[i], order); + + return n == nr; +} + +static void alloc_skb_with_frags_test_tail(struct kunit *test) +{ + /* MAX_SKB_FRAGS - 2 full chunks plus a 7 page tail: rounding the + * tail down to 4 + 2 + 1 pages would need one frag too many. + */ + unsigned long len = (MAX_SKB_FRAGS - 2) * + (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER) + + 7 * PAGE_SIZE; + unsigned long frags_len = 0; + struct sk_buff *skb; + int err, i; + + skb = alloc_skb_with_frags(0, len, PAGE_ALLOC_COSTLY_ORDER, &err, + GFP_KERNEL); + /* The full chunks can't fall back to smaller pages here, so the + * call needs up to MAX_SKB_FRAGS - 1 order-3 pages at once. Don't + * report a lack of them as a failure. + */ + if (!skb && !alloc_skb_with_frags_test_have_pages(MAX_SKB_FRAGS - 1, + PAGE_ALLOC_COSTLY_ORDER)) + kunit_skip(test, "not enough order-%d pages", + PAGE_ALLOC_COSTLY_ORDER); + KUNIT_ASSERT_NOT_NULL_MSG(test, skb, "err %d", err); + + for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) + frags_len += skb_frag_size(&skb_shinfo(skb)->frags[i]); + KUNIT_EXPECT_EQ(test, frags_len, len); + + kfree_skb(skb); +} + static struct kunit_case net_test_cases[] = { + KUNIT_CASE(alloc_skb_with_frags_test_tail), KUNIT_CASE_PARAM(gso_test_func, gso_test_gen_params), KUNIT_CASE_PARAM(ip_tunnel_flags_test_run, ip_tunnel_flags_test_gen_params), From 746dbdc5fa60f29bab06c08f2126f3ae7ee92506 Mon Sep 17 00:00:00 2001 From: Rishikesh Jethwani Date: Mon, 16 Nov 2026 12:01:08 -0700 Subject: [PATCH 1336/2102] kcm: reject TLS on attached TCP sockets Neither kcm_attach() nor tls_init() rejects the other, so KCM and kTLS RX can be stacked on the same TCP socket in either order. This breaks in several ways: - KCM calls read_sock() from its receive callback in atomic context. With kTLS RX this reaches tls_sw_read_sock(), which can sleep. - Before tls_sw_read_sock() existed, read_sock was tcp_read_sock(), so KCM consumed raw ciphertext from the receive queue that TLS parses. - Both install socket callbacks. kcm_unattach() restores the pre-KCM sk_data_ready over tls_data_ready, so TLS RX stops getting notified. The sleep in atomic context was reproduced on an unmodified kernel with CONFIG_DEBUG_ATOMIC_SLEEP. Reject sockets with a ULP in kcm_attach(), and make tls_init() fail while KCM is attached. A tcp_sock boolean, present when CONFIG_AF_KCM is enabled, tracks attachment. It is set and cleared under the transport socket lock. Also switch the transport check to sk_is_tcp(). The family and protocol checks alone also accept raw IPPROTO_TCP sockets, which have no tcp_sock. Validated with KASAN and lockdep: connected IPv4/IPv6 raw sockets, both attach orders, detach, and concurrent installation. Backports without commit 8cc3aef0cb198 ("tcp: Do not allow buggy transitions between ehash and lhash2.") must also prevent attached sockets from becoming listeners after disconnect. Fixes: c46234ebb4d1 ("tls: RX path for ktls") Cc: # needs 8cc3aef0cb198 or equivalent, see above Link: https://lore.kernel.org/netdev/3108e934-ec00-458b-8720-450554b35b55@linux.dev/ Signed-off-by: Rishikesh Jethwani Link: https://patch.msgid.link/20261116190111.3317976-1-rjethwani@purestorage.com Signed-off-by: Jakub Kicinski --- Documentation/networking/kcm.rst | 3 +++ include/linux/tcp.h | 3 +++ include/net/tcp.h | 9 +++++++++ net/kcm/kcmsock.c | 16 +++++++++++++--- net/tls/tls_main.c | 3 +++ 5 files changed, 31 insertions(+), 3 deletions(-) diff --git a/Documentation/networking/kcm.rst b/Documentation/networking/kcm.rst index 71f44d0beaa368..07778f29211c42 100644 --- a/Documentation/networking/kcm.rst +++ b/Documentation/networking/kcm.rst @@ -167,6 +167,9 @@ The kcm_attach structure contains: - fd: file descriptor for TCP socket being attached - bpf_prog_fd: file descriptor for compiled BPF program downloaded +The transport socket must be a TCP stream socket with no TCP ULP installed. +TLS cannot be enabled on a transport socket while it is attached to KCM. + Unattach transport sockets -------------------------- diff --git a/include/linux/tcp.h b/include/linux/tcp.h index e6b79cf4798f49..d4b07fbae2d5f1 100644 --- a/include/linux/tcp.h +++ b/include/linux/tcp.h @@ -516,6 +516,9 @@ struct tcp_sock { #if IS_ENABLED(CONFIG_MPTCP) bool is_mptcp; #endif +#if IS_ENABLED(CONFIG_AF_KCM) + bool kcm_attached; +#endif #if IS_ENABLED(CONFIG_SMC) bool syn_smc; /* SYN includes SMC */ bool (*smc_hs_congested)(const struct sock *sk); diff --git a/include/net/tcp.h b/include/net/tcp.h index 27de546dc802de..5a638727d42091 100644 --- a/include/net/tcp.h +++ b/include/net/tcp.h @@ -2892,6 +2892,15 @@ void tcp_cleanup_ulp(struct sock *sk); void tcp_update_ulp(struct sock *sk, struct proto *p, void (*write_space)(struct sock *sk)); +static inline bool tcp_kcm_attached(const struct sock *sk) +{ +#if IS_ENABLED(CONFIG_AF_KCM) + return tcp_sk(sk)->kcm_attached; +#else + return false; +#endif +} + #define MODULE_ALIAS_TCP_ULP(name) \ MODULE_INFO(alias, name); \ MODULE_INFO(alias, "tcp-ulp-" name) diff --git a/net/kcm/kcmsock.c b/net/kcm/kcmsock.c index a7f94d42036fb1..ca789812124e80 100644 --- a/net/kcm/kcmsock.c +++ b/net/kcm/kcmsock.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include @@ -1259,9 +1260,10 @@ static int kcm_attach(struct socket *sock, struct socket *csock, lock_sock(csk); - /* Only allow TCP sockets to be attached for now */ - if ((csk->sk_family != AF_INET && csk->sk_family != AF_INET6) || - csk->sk_protocol != IPPROTO_TCP) { + /* Only allow TCP sockets to be attached for now. A raw socket + * created with IPPROTO_TCP has that sk_protocol but no icsk. + */ + if (!sk_is_tcp(csk)) { err = -EOPNOTSUPP; goto out; } @@ -1272,6 +1274,12 @@ static int kcm_attach(struct socket *sock, struct socket *csock, goto out; } + /* KCM and ULPs cannot share the receive path and socket callbacks. */ + if (inet_csk_has_ulp(csk)) { + err = -EOPNOTSUPP; + goto out; + } + psock = kmem_cache_zalloc(kcm_psockp, GFP_KERNEL); if (!psock) { err = -ENOMEM; @@ -1305,6 +1313,7 @@ static int kcm_attach(struct socket *sock, struct socket *csock, psock->save_write_space = csk->sk_write_space; psock->save_state_change = csk->sk_state_change; csk->sk_user_data = psock; + tcp_sk(csk)->kcm_attached = true; WRITE_ONCE(csk->sk_data_ready, psock_data_ready); WRITE_ONCE(csk->sk_write_space, psock_write_space); csk->sk_state_change = psock_state_change; @@ -1386,6 +1395,7 @@ static void kcm_unattach(struct kcm_psock *psock) WRITE_ONCE(csk->sk_write_space, psock->save_write_space); csk->sk_state_change = psock->save_state_change; strp_stop(&psock->strp); + tcp_sk(csk)->kcm_attached = false; if (WARN_ON(psock->rx_kcm)) { write_unlock_bh(&csk->sk_callback_lock); diff --git a/net/tls/tls_main.c b/net/tls/tls_main.c index b8d5a843f76171..fa71c75c28611d 100644 --- a/net/tls/tls_main.c +++ b/net/tls/tls_main.c @@ -1067,6 +1067,9 @@ static int tls_init(struct sock *sk) if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; + if (tcp_kcm_attached(sk)) + return -EBUSY; + /* allocate tls context */ write_lock_bh(&sk->sk_callback_lock); ctx = tls_ctx_create(sk); From cbea6bdc930b2de974e77e6c3031f67796793625 Mon Sep 17 00:00:00 2001 From: Ruben Wauters Date: Tue, 17 Nov 2026 14:17:51 +0000 Subject: [PATCH 1337/2102] drm/gud: fix potential divide error due to optimisation Compilers can potentially optmise the read of gdrm->stats_actual_length to two separate reads. As flagged by sashiko, when the rect is flushed the stats_actual_length can reset to zero. If this was to occur between the two reads, the divide error can still be triggered (albeit rarely). Fix this by adding a READ_ONCE around the gdrm->stats_actual_length Fixes: 431c2dffd2b7 ("drm/gud: avoid divide error in gud_stats_debugfs") Cc: Reviewed-by: Thomas Zimmermann Link: https://patch.msgid.link/20261117141943.10540-1-ruben.wauters@linux.dev Signed-off-by: Ruben Wauters --- drivers/gpu/drm/gud/gud_drv.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/gud/gud_drv.c b/drivers/gpu/drm/gud/gud_drv.c index cec5d64e152bbe..4854b30ea5ba5d 100644 --- a/drivers/gpu/drm/gud/gud_drv.c +++ b/drivers/gpu/drm/gud/gud_drv.c @@ -329,7 +329,7 @@ static int gud_stats_debugfs(struct seq_file *m, void *data) seq_puts(m, "\n"); if (gdrm->compression) { - u64 actual_length = gdrm->stats_actual_length; + u64 actual_length = READ_ONCE(gdrm->stats_actual_length); u64 remainder; u64 ratio, ratio_frac; From ff73a2bb558f1279aa7d9c83285f93d2d644e558 Mon Sep 17 00:00:00 2001 From: Henry Martin Date: Wed, 18 Nov 2026 18:17:52 +0800 Subject: [PATCH 1338/2102] net: initialize sk_peer_lock in cloned sockets sock_copy() clones a struct sock with two memcpys that both include sk_peer_lock. sk_clone() re-initializes sk_lock, but nothing resets sk_peer_lock, so a clone created while the parent's sk_peer_lock is held inherits the lock in the locked state. The first getsockopt(SO_PEERCRED) on such a child spins forever in queued_spin_lock_slowpath(). spin_lock() disables preemption, so the task never schedules and its CPU stops reporting quiescent states; RCU grace periods then stop and callers of synchronize_rcu(), such as expand_files() from accept(), hang. Initialize sk_peer_lock explicitly for the clone. This issue was discovered by Tencent CodeBuddy Security. Fixes: 35306eb23814 ("af_unix: fix races in sk_peer_pid and sk_peer_cred accesses") Cc: stable@vger.kernel.org Signed-off-by: Henry Martin Reviewed-by: Eric Dumazet Reviewed-by: Kuniyuki Iwashima Link: https://patch.msgid.link/20261118101752.1989502-1-bsdhenrymartin@gmail.com Signed-off-by: Jakub Kicinski --- net/core/sock.c | 1 + 1 file changed, 1 insertion(+) diff --git a/net/core/sock.c b/net/core/sock.c index 74a00a5e2d1165..5675053625e6fe 100644 --- a/net/core/sock.c +++ b/net/core/sock.c @@ -2547,6 +2547,7 @@ struct sock *sk_clone(const struct sock *sk, const gfp_t priority, sk_node_init(&newsk->sk_node); sock_lock_init(newsk); + spin_lock_init(&newsk->sk_peer_lock); if (lock) bh_lock_sock(newsk); From 890f23ba87a7ca1aba97c8320770a686e3b689fb Mon Sep 17 00:00:00 2001 From: Uri Dar Date: Wed, 18 Nov 2026 18:51:55 +0200 Subject: [PATCH 1339/2102] net/mlx5: E-Switch, skip vport change work for disabled vports A vport change work can still be pending when its vport is disabled. For an SF, the vport is then freed in FW and the work's query fails with syndrome 0x29d722. A disabled vport has nothing to sync, so skip the work. Fixes: d970812b91d0 ("net/mlx5: E-switch, Add eswitch helpers for SF vport") Signed-off-by: Uri Dar Reviewed-by: Shay Drory Reviewed-by: Mark Bloch Signed-off-by: Tariq Toukan Link: https://patch.msgid.link/20261118165155.1946097-1-tariqt@nvidia.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/mellanox/mlx5/core/eswitch.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c b/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c index 76f808e06a88bf..174197f6988876 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c @@ -758,7 +758,8 @@ static void esw_vport_change_handler(struct work_struct *work) struct mlx5_eswitch *esw = vport->dev->priv.eswitch; mutex_lock(&esw->state_lock); - esw_vport_change_handle_locked(vport); + if (vport->enabled) + esw_vport_change_handle_locked(vport); mutex_unlock(&esw->state_lock); } From 9175e1d6d2f0d4f353682833f78188cb35b80e4d Mon Sep 17 00:00:00 2001 From: Michal Swiatkowski Date: Fri, 13 Nov 2026 15:12:18 -0800 Subject: [PATCH 1340/2102] ice: use global queue index in TC to-queue offload Previously index within PF was used, which caused rules to fail on any PF other than PF0. Switch to global queue index by adding first RX queue id from caps. Triggered during code development. Validated on HW by adding different set of to queue rules on various PFs Fixes: 143b86f346c7 ("ice: Enable RX queue selection using skbedit action") Reviewed-by: Aleksandr Loktionov Signed-off-by: Michal Swiatkowski Reviewed-by: Simon Horman Tested-by: Alexander Nowlin Signed-off-by: Tony Nguyen Link: https://patch.msgid.link/20261113231225.1864810-2-anthony.l.nguyen@intel.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/intel/ice/ice_tc_lib.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/intel/ice/ice_tc_lib.c b/drivers/net/ethernet/intel/ice/ice_tc_lib.c index d20357c0412731..6f49ecb4165b24 100644 --- a/drivers/net/ethernet/intel/ice/ice_tc_lib.c +++ b/drivers/net/ethernet/intel/ice/ice_tc_lib.c @@ -1202,7 +1202,8 @@ ice_add_tc_flower_adv_fltr(struct ice_vsi *vsi, break; case ICE_FWD_TO_Q: /* HW queue number in global space */ - rule_info.sw_act.fwd_id.q_id = tc_fltr->action.fwd.q.hw_queue; + rule_info.sw_act.fwd_id.q_id = tc_fltr->action.fwd.q.hw_queue + + hw->func_caps.common_cap.rxq_first_id; rule_info.sw_act.vsi_handle = dest_vsi->idx; rule_info.priority = ICE_SWITCH_FLTR_PRIO_QUEUE; rule_info.sw_act.src = hw->pf_id; From dc84cae413bdcebfe130803022b8e02abc2ffa83 Mon Sep 17 00:00:00 2001 From: Petr Oros Date: Fri, 13 Nov 2026 15:12:23 -0800 Subject: [PATCH 1341/2102] ice: allow reading the last byte of the NVM and Shadow RAM regions ice_devlink_nvm_read() rejects a read whose end lands exactly on the region size, so feeding back the size devlink itself reports fails: devlink region show pci/0000:04:00.0/nvm-flash pci/0000:04:00.0/nvm-flash: size 10485760 snapshot [] max 1 devlink region read pci/0000:04:00.0/nvm-flash address 0 length 10485760 Error: ice: Cannot read beyond the region size. shadow-ram behaves the same. The regions are created with those sizes, so a read ending on the size is the whole region and has to be allowed. ice_read_flat_nvm() uses > for its own Shadow RAM check, and so does ixgbe, which grew its region support from this code. Fixes: 3af4b40b0f2f ("ice: implement direct read for NVM and Shadow RAM regions") Signed-off-by: Petr Oros Reviewed-by: Przemek Kitszel Acked-by: Jacob Keller Tested-by: Alexander Nowlin Signed-off-by: Tony Nguyen Link: https://patch.msgid.link/20261113231225.1864810-7-anthony.l.nguyen@intel.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/intel/ice/devlink/devlink.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/ethernet/intel/ice/devlink/devlink.c b/drivers/net/ethernet/intel/ice/devlink/devlink.c index a87a3e0a900c32..9eafe7d5773263 100644 --- a/drivers/net/ethernet/intel/ice/devlink/devlink.c +++ b/drivers/net/ethernet/intel/ice/devlink/devlink.c @@ -1953,7 +1953,7 @@ static int ice_devlink_nvm_read(struct devlink *devlink, return -EOPNOTSUPP; } - if (offset + size >= nvm_size) { + if (offset + size > nvm_size) { NL_SET_ERR_MSG_MOD(extack, "Cannot read beyond the region size"); return -ERANGE; } From af6737b9066832a2017c281159950ba92385ce00 Mon Sep 17 00:00:00 2001 From: Daniel Wade Date: Sun, 15 Nov 2026 09:05:29 +1030 Subject: [PATCH 1342/2102] net: af_key: fix use-after-free in dump_sp() on policy migrate pfkey_xfrm_policy2msg_size() derives an exported policy's message length from xfrm_vec[].encap_family. dump_sp() derives it twice: once through pfkey_xfrm_policy2msg_prep(), which allocates the skb, and again in pfkey_xfrm_policy2msg(), which fills it in. dump_sp() holds net->xfrm.xfrm_policy_lock rather than pol->lock, so xfrm_policy_migrate() can rewrite encap_family between the two derivations. The second length is then up to 24 bytes per template larger than the first, and pfkey_xfrm_policy2msg() opens with memset(hdr, 0, size), clearing the difference into the skb's shared info. Four BEET templates put 80 bytes there, which reaches dataref: alloc_skb() had set it to 1, the memset makes it 0, and the skb_clone() in pfkey_broadcast_one() leaves two skbs sharing one head with a dataref of 1. Freeing the original releases a head the queued clone still points at, so recvmsg() copies freed memory to user space and consume_skb() frees it a second time. The CAP_NET_ADMIN that pfkey_create() and the xfrm netlink receive path check is namespace-relative, so an unprivileged user can reach this. SLUB's double-free check fires within a second of starting the reproducer; the oops kills a task, or panics the machine when the corruption lands in softirq context. Racing SADB_X_SPDDUMP against XFRM_MSG_MIGRATE as an ordinary user gave 4585 use-after-free reports and 765 double-frees in 300s on mainline with KASAN and 8 CPUs. The reads reach user space (addresses trimmed): BUG: KASAN: slab-use-after-free in _copy_to_iter+0x1d8/0x1430 Read of size 240 at addr ffff88810f98d140 by task pfkey_dataref_o/433 CPU: 3 UID: 65534 PID: 433 Comm: pfkey_dataref_o Not tainted 7.4.0-rc2 Call Trace: dump_stack_lvl+0x66/0xa0 print_report+0xd0/0x600 kasan_report+0xc6/0x100 kasan_check_range+0x105/0x1b0 _copy_to_iter+0x1d8/0x1430 __skb_datagram_iter+0xf8/0x820 skb_copy_datagram_iter+0x6c/0x1a0 pfkey_recvmsg+0x1ff/0x500 sock_recvmsg+0x15e/0x1a0 __sys_recvfrom+0x182/0x260 do_syscall_64+0x10b/0x5f0 entry_SYSCALL_64_after_hwframe+0x77/0x7f Allocated by task 433: kmalloc_reserve+0x108/0x2b0 __alloc_skb+0x123/0x5b0 dump_sp+0xdf/0x490 xfrm_policy_walk+0x1d9/0x6c0 pfkey_do_dump+0x61/0x420 pfkey_recvmsg+0x358/0x500 Take xp->lock for reading across both calls, so both derivations see the same encap_family. xfrm_policy_walk() already calls dump_sp() under spin_lock_bh(), so the plain reader suffices, as in xfrm_policy_timer(). The other callers of this pair are already serialized against migrate by net->xfrm.xfrm_cfg_mutex. Fixes: 80c9abaabf42 ("[XFRM]: Extension for dynamic update of endpoint address(es)") Cc: stable@vger.kernel.org Signed-off-by: Daniel Wade Link: https://patch.msgid.link/20261114223529.1791-1-danjwade95@gmail.com Signed-off-by: Jakub Kicinski --- net/key/af_key.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/net/key/af_key.c b/net/key/af_key.c index d215b33b7492c2..ab4aaca9147066 100644 --- a/net/key/af_key.c +++ b/net/key/af_key.c @@ -2712,11 +2712,18 @@ static int dump_sp(struct xfrm_policy *xp, int dir, int count, void *ptr) if (!pfkey_can_dump(&pfk->sk)) return -ENOBUFS; + /* Both halves derive the size from xfrm_vec[].encap_family, so + * hold xp->lock against a concurrent xfrm_policy_migrate(). + */ + read_lock(&xp->lock); out_skb = pfkey_xfrm_policy2msg_prep(xp); - if (IS_ERR(out_skb)) + if (IS_ERR(out_skb)) { + read_unlock(&xp->lock); return PTR_ERR(out_skb); + } err = pfkey_xfrm_policy2msg(out_skb, xp, dir); + read_unlock(&xp->lock); if (err < 0) { kfree_skb(out_skb); return err; From a89ca0d6e5c03f1b9fcd076fa0cef2c2505b6aab Mon Sep 17 00:00:00 2001 From: "Masami Hiramatsu (Google)" Date: Wed, 18 Nov 2026 08:47:30 +0900 Subject: [PATCH 1343/2102] bootconfig: Exclude alignment padding from bootconfig max size When attaching a bootconfig to an initrd image, apply_xbc() appends 0-3 null padding bytes to align the total image size to 4 bytes and includes those padding bytes in the footer size field. As documented in Documentation/admin-guide/bootconfig.rst, the maximum bootconfig size (XBC_DATA_MAX, 32767 bytes including the terminal null) is not supposed to include these padding null characters. However, both load_xbc_from_initrd() in tools/bootconfig and get_boot_config_from_initrd() / xbc_init() in the kernel check the raw footer size directly against XBC_DATA_MAX. As a result, a valid 32766-byte config (size = 32767 with the terminal null) gets a footer size of 32768..32770 when alignment padding is added, and is rejected with "bootconfig size is too big" depending on the initrd size. Define XBC_DATA_MAX_PADDED (XBC_DATA_MAX + BOOTCONFIG_ALIGN - 1) for the raw trailer size check, and add xbc_exclude_padding() to strip up to BOOTCONFIG_ALIGN - 1 trailing null padding bytes (keeping the terminal null byte) before checking the unpadded bootconfig size against XBC_DATA_MAX and passing it to xbc_init(). Keep using the raw footer size when truncating or trimming the initrd so that both the bootconfig and its alignment padding are removed. Also expand test-bootconfig.sh to verify applying, reading back, and deleting a maximum-size bootconfig across all 4 alignment paddings. Link: https://lore.kernel.org/all/179495925054.237695.2777053796977822521.stgit@devnote2/ Fixes: e1cef2d4c379 ("tools/bootconfig: Align the bootconfig applied initrd image size to 4") Cc: stable@vger.kernel.org Signed-off-by: Masami Hiramatsu (Google) Reviewed-by: Breno Leitao --- include/linux/bootconfig.h | 24 ++++++++++++++++++++++++ init/main.c | 23 +++++++++++++++-------- tools/bootconfig/main.c | 14 ++++++++++---- tools/bootconfig/test-bootconfig.sh | 17 +++++++++++++++-- 4 files changed, 64 insertions(+), 14 deletions(-) diff --git a/include/linux/bootconfig.h b/include/linux/bootconfig.h index 260a6f46042e12..f745068c07cdc0 100644 --- a/include/linux/bootconfig.h +++ b/include/linux/bootconfig.h @@ -63,6 +63,30 @@ struct xbc_node { #define XBC_VALUE (1 << 15) /* Maximum size of boot config is 32KB - 1 */ #define XBC_DATA_MAX (XBC_VALUE - 1) +/* Maximum size of padded boot config in initrd trailer */ +#define XBC_DATA_MAX_PADDED (XBC_DATA_MAX + BOOTCONFIG_ALIGN - 1) + +/** + * xbc_exclude_padding() - Exclude trailing null padding bytes from size + * @data: Bootconfig data (including padding). + * @size: The size of @data from the bootconfig footer. + * + * Exclude up to BOOTCONFIG_ALIGN - 1 trailing null padding bytes while + * keeping the terminal null byte of the bootconfig data, and return the + * unpadded bootconfig size. + */ +static inline __init uint32_t xbc_exclude_padding(const char *data, uint32_t size) +{ + int i; + + for (i = 0; i < BOOTCONFIG_ALIGN - 1; i++) { + if (size <= 1 || data[size - 1] != '\0' || data[size - 2] != '\0') + break; + size--; + } + + return size; +} #define XBC_NODE_MAX 8192 #define XBC_KEYLEN_MAX 256 diff --git a/init/main.c b/init/main.c index 7b0c8c34e6a911..9471ece3d7d5cd 100644 --- a/init/main.c +++ b/init/main.c @@ -268,7 +268,7 @@ early_param("loglevel", loglevel); #ifdef CONFIG_BLK_DEV_INITRD static void * __init get_boot_config_from_initrd(size_t *_size) { - u32 size, csum; + u32 size, raw_size, csum; char *data; u8 *hdr; int i; @@ -294,24 +294,31 @@ static void * __init get_boot_config_from_initrd(size_t *_size) if ((unsigned long)hdr < initrd_start) return NULL; - size = get_unaligned_le32(hdr); + raw_size = get_unaligned_le32(hdr); csum = get_unaligned_le32(hdr + 4); - if (size > XBC_DATA_MAX) { + if (raw_size > XBC_DATA_MAX_PADDED) { pr_err("bootconfig size %u is greater than max size %d\n", - size, XBC_DATA_MAX); + raw_size, XBC_DATA_MAX); return NULL; } - if (size > ((unsigned long)hdr - initrd_start)) { + if (raw_size > ((unsigned long)hdr - initrd_start)) { pr_err("bootconfig size %u is greater than initrd size %lu\n", - size, initrd_end - initrd_start); + raw_size, initrd_end - initrd_start); return NULL; } - data = ((void *)hdr) - size; + data = ((void *)hdr) - raw_size; + + size = xbc_exclude_padding(data, raw_size); + if (size > XBC_DATA_MAX) { + pr_err("bootconfig size %u is greater than max size %d\n", + size, XBC_DATA_MAX); + return NULL; + } - if (xbc_calc_checksum(data, size) != csum) { + if (xbc_calc_checksum(data, raw_size) != csum) { pr_err("bootconfig checksum failed\n"); return NULL; } diff --git a/tools/bootconfig/main.c b/tools/bootconfig/main.c index d3f840c5adce78..c32fb1e2140cf4 100644 --- a/tools/bootconfig/main.c +++ b/tools/bootconfig/main.c @@ -182,7 +182,7 @@ static int load_xbc_fd(int fd, char **buf, int size) { int ret; - if (size < 0 || size > XBC_DATA_MAX) + if (size < 0 || size > XBC_DATA_MAX_PADDED) return -EINVAL; *buf = malloc(size + 1); @@ -237,7 +237,7 @@ static int load_xbc_from_initrd(int fd, char **buf) { struct stat stat; int ret; - uint32_t size = 0, csum = 0, rcsum; + uint32_t size = 0, data_size, csum = 0, rcsum; char magic[BOOTCONFIG_MAGIC_LEN]; ret = fstat(fd, &stat); @@ -269,7 +269,7 @@ static int load_xbc_from_initrd(int fd, char **buf) csum = le32toh(csum); /* Wrong size error */ - if (size > XBC_DATA_MAX || + if (size > XBC_DATA_MAX_PADDED || size > stat.st_size - BOOTCONFIG_FOOTER_SIZE) { pr_err("bootconfig size is too big\n"); return -E2BIG; @@ -283,6 +283,12 @@ static int load_xbc_from_initrd(int fd, char **buf) if (ret < 0) return ret; + data_size = xbc_exclude_padding(*buf, size); + if (data_size > XBC_DATA_MAX) { + pr_err("bootconfig size is too big\n"); + return -E2BIG; + } + /* Wrong Checksum */ rcsum = xbc_calc_checksum(*buf, size); if (csum != rcsum) { @@ -290,7 +296,7 @@ static int load_xbc_from_initrd(int fd, char **buf) return -EINVAL; } - ret = init_xbc_with_error(*buf, size); + ret = init_xbc_with_error(*buf, data_size); return ret < 0 ? ret : size; } diff --git a/tools/bootconfig/test-bootconfig.sh b/tools/bootconfig/test-bootconfig.sh index f584f7637e12a5..e03301ad76c4d3 100755 --- a/tools/bootconfig/test-bootconfig.sh +++ b/tools/bootconfig/test-bootconfig.sh @@ -118,10 +118,23 @@ dd if=/dev/urandom bs=768 count=32 | base64 -w0 >> $TEMPCONF printf "\"\n" >> $TEMPCONF xfail $BOOTCONF -a $TEMPCONF $INITRD +dd if=$TEMPCONF of=$OUTFILE bs=1 count=32765 +cp $OUTFILE $TEMPCONF +printf "\"\n" >> $TEMPCONF # 32767 bytes + terminal ('\0') = 32768 (> max) +xfail $BOOTCONF -a $TEMPCONF $INITRD + dd if=$TEMPCONF of=$OUTFILE bs=1 count=32764 cp $OUTFILE $TEMPCONF -printf "\"\n" >> $TEMPCONF # add 2 bytes + terminal ('\"\n\0') -xpass $BOOTCONF -a $TEMPCONF $INITRD +printf "\"\n" >> $TEMPCONF # add 2 bytes + terminal ('\"\n\0') = 32767 +# Test max size across all 4 alignment paddings (0..3 bytes) +for sz in 4096 4097 4098 4099; do + dd if=/dev/zero of=$INITRD bs=1 count=$sz 2>/dev/null + xpass $BOOTCONF -a $TEMPCONF $INITRD + $BOOTCONF -l $INITRD > $OUTFILE + xpass cmp $TEMPCONF $OUTFILE + xpass $BOOTCONF -d $INITRD + xpass test $(wc -c < $INITRD) -eq $sz +done echo "Adding same-key values" cat > $TEMPCONF << EOF From 9ae84f30d74763bcee0dd8c2155c7dfeb135f5fa Mon Sep 17 00:00:00 2001 From: "Masami Hiramatsu (Google)" Date: Wed, 18 Nov 2026 08:47:40 +0900 Subject: [PATCH 1344/2102] bootconfig: Free the initrd memory used by bootconfig get_boot_config_from_initrd() removes the bootconfig from the initrd by decrementing initrd_end in place. However, the whole initrd including the bootconfig is reserved, e.g. reserve_initrd_mem() reserves [initrd_start, PAGE_ALIGN(original initrd_end)), and do_populate_rootfs() frees it with free_initrd_mem(initrd_start, initrd_end). Thus the full pages in [PAGE_ALIGN(new initrd_end), PAGE_ALIGN(original initrd_end)) are never freed. This leaks up to 8 pages for a 32KB bootconfig. Save the original initrd_end in initrd_mem_end when trimming the bootconfig, and restore initrd_end before freeing the initrd memory. The bootconfig data has already been copied by xbc_init() at that point. The trimmed initrd_end is kept when the initrd is retained, so that /sys/firmware/initrd does not expose the bootconfig. Link: https://lore.kernel.org/all/179495926058.237695.12800083196053168375.stgit@devnote2/ Fixes: de462e5f1071 ("bootconfig: Fix to remove bootconfig data from initrd while boot") Cc: stable@vger.kernel.org Signed-off-by: Masami Hiramatsu (Google) Reviewed-by: Breno Leitao --- include/linux/initrd.h | 2 ++ init/initramfs.c | 10 ++++++++++ init/main.c | 8 +++++++- 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/include/linux/initrd.h b/include/linux/initrd.h index 7e5d26c8136f19..3086a462da764b 100644 --- a/include/linux/initrd.h +++ b/include/linux/initrd.h @@ -17,6 +17,8 @@ extern unsigned long initrd_start, initrd_end; extern void free_initrd_mem(unsigned long, unsigned long); #ifdef CONFIG_BLK_DEV_INITRD +/* initrd_end before trailing data (e.g. bootconfig) was trimmed off */ +extern unsigned long initrd_mem_end; extern void __init reserve_initrd_mem(void); extern void wait_for_initramfs(void); #else diff --git a/init/initramfs.c b/init/initramfs.c index ebddde9c8f0d91..11030cc1f35df4 100644 --- a/init/initramfs.c +++ b/init/initramfs.c @@ -582,6 +582,7 @@ char * __init unpack_to_rootfs(char *buf, unsigned long len) } static int __initdata do_retain_initrd; +unsigned long initrd_mem_end __initdata; static int __init retain_initrd_param(char *str) { @@ -750,6 +751,15 @@ static void __init do_populate_rootfs(void *unused, async_cookie_t cookie) security_initramfs_populated(); } + /* + * The bootconfig loader trims the bootconfig off initrd_end. Restore + * it to free the memory used by the bootconfig too, unless the initrd + * is retained (which must not expose the bootconfig). + */ + if (!do_retain_initrd && initrd_start && initrd_end < initrd_mem_end) + initrd_end = initrd_mem_end; + initrd_mem_end = 0; + /* * If the initrd region is overlapped with crashkernel reserved region, * free only memory that is not part of crashkernel region. diff --git a/init/main.c b/init/main.c index 9471ece3d7d5cd..f1478034505130 100644 --- a/init/main.c +++ b/init/main.c @@ -323,7 +323,13 @@ static void * __init get_boot_config_from_initrd(size_t *_size) return NULL; } - /* Remove bootconfig from initramfs/initrd */ + /* + * Remove bootconfig from initramfs/initrd. Since the initrd memory + * (including the bootconfig) is freed with initrd_end, save the + * original end to free the whole region later. + */ + if (!initrd_mem_end) + initrd_mem_end = initrd_end; initrd_end = (unsigned long)data; if (_size) *_size = size; From 8e83fac77aa975cb0b2f2586d5072872a0147db6 Mon Sep 17 00:00:00 2001 From: "Masami Hiramatsu (Google)" Date: Sun, 22 Nov 2026 10:01:32 +0900 Subject: [PATCH 1345/2102] bootconfig: Fix xbc_verify_tree() to check subkeys of valued keys When a key node has both a value and subkeys, the value node is always inserted as the first child of the key node (xbc_add_head_sibling()), and subkeys follow as next siblings of that value node. However, xbc_verify_tree() uses xbc_node_get_child(n) and checks xbc_node_is_key(m) to descend into subkeys. When a key node has a value, xbc_node_get_child(n) returns the value node, so xbc_node_is_key(m) is false and xbc_verify_tree() completely skips verifying all subkeys under that key. This allows subkeys under a valued key to bypass both the XBC_DEPTH_MAX (16) and XBC_KEYLEN_MAX (256) checks during xbc_init(), causing runtime -ERANGE failures in xbc_node_compose_key_after(). Use xbc_node_get_subkey(n) so that subkeys of mixed value+subkey nodes are properly verified. Link: https://lore.kernel.org/all/179530929234.109991.150550090881188440.stgit@devnote2/ Fixes: e5efaeb8a8f5 ("bootconfig: Support mixing a value and subkeys under a key") Cc: stable@vger.kernel.org Signed-off-by: Masami Hiramatsu (Google) --- lib/bootconfig.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/bootconfig.c b/lib/bootconfig.c index 948c8c10e4b985..026d88a65c5c7a 100644 --- a/lib/bootconfig.c +++ b/lib/bootconfig.c @@ -1058,8 +1058,8 @@ static int __init xbc_verify_tree(void) return xbc_parse_error("Too long key length", xbc_node_get_data(n)); - m = xbc_node_get_child(n); - if (m && xbc_node_is_key(m)) { + m = xbc_node_get_subkey(n); + if (m) { n = m; depth++; if (depth > XBC_DEPTH_MAX) From 2913c7c94b786a7193faf67390a305895b8180ee Mon Sep 17 00:00:00 2001 From: "Masami Hiramatsu (Google)" Date: Sun, 22 Nov 2026 10:01:41 +0900 Subject: [PATCH 1346/2102] bootconfig: Fix xbc_node_compose_key_after() for value nodes Fix two issues in xbc_node_compose_key_after() when @node is a value node: 1. Since array values are chained via the child pointer in xbc_parse_array(), the 2nd and subsequent value nodes of an array have the preceding value node as their parent rather than the owning key node. Climbing only one parent (if (xbc_node_is_value(node))) caused preceding array value strings to be included in the composed key (e.g. "foo.bar.val1" instead of "foo.bar"). 2. Checking `if (!node || node == root)` before climbing to the owning key node allowed a value node belonging to the subtree @root key node itself (e.g. `foo = "val"` with `@root = xbc_find_node("foo")`) to pass the check, climb to @root, skip the key-collection loop (depth == 0), and return 0 without writing anything (not even a NUL terminator) to @buf. Climb parent pointers in a loop while the node is a value node, and perform the `if (!node || node == root)` check afterward. Link: https://lore.kernel.org/all/179530930140.109991.1418783350874051238.stgit@devnote2/ Fixes: ca24306d83a1 ("bootconfig: Change array value to use child node") Cc: stable@vger.kernel.org Signed-off-by: Masami Hiramatsu (Google) --- lib/bootconfig.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/bootconfig.c b/lib/bootconfig.c index 026d88a65c5c7a..280b7e73321b9b 100644 --- a/lib/bootconfig.c +++ b/lib/bootconfig.c @@ -421,12 +421,12 @@ int __init xbc_node_compose_key_after(struct xbc_node *root, uint16_t keys[XBC_DEPTH_MAX]; int depth = 0, ret = 0, total = 0; + while (node && xbc_node_is_value(node)) + node = xbc_node_get_parent(node); + if (!node || node == root) return -EINVAL; - if (xbc_node_is_value(node)) - node = xbc_node_get_parent(node); - while (node && node != root) { if (depth == XBC_DEPTH_MAX) return -ERANGE; From 919165d94fb4aeb2e41b6d0a60118750b1f75f26 Mon Sep 17 00:00:00 2001 From: "Masami Hiramatsu (Google)" Date: Sun, 22 Nov 2026 10:01:50 +0900 Subject: [PATCH 1347/2102] bootconfig: Avoid out-of-bounds pointer arithmetic in xbc_snprint_cmdline_filter() xbc_snprint_cmdline_filter() passes `buf ? buf + len : NULL` to snprintf(). While this avoids NULL pointer arithmetic when @buf is NULL, if @buf is non-NULL and the rendered output exceeds @size (len > size), evaluating `buf + len` forms a pointer past the end of the @buf allocation, which is undefined behavior in C even though rest(len, size) is 0. Pass `buf && len < size ? buf + len : NULL` so that snprintf() receives NULL whenever the remaining buffer capacity is 0. Link: https://lore.kernel.org/all/179530931041.109991.12049130742435464205.stgit@devnote2/ Fixes: dec4d8118c17 ("bootconfig: fix NULL-pointer arithmetic in xbc_snprint_cmdline()") Cc: stable@vger.kernel.org Signed-off-by: Masami Hiramatsu (Google) --- lib/bootconfig.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/bootconfig.c b/lib/bootconfig.c index 280b7e73321b9b..9ae9a215b1da3c 100644 --- a/lib/bootconfig.c +++ b/lib/bootconfig.c @@ -587,8 +587,8 @@ int __init xbc_snprint_cmdline_filter(char *buf, size_t size, struct xbc_node *r vnode = xbc_node_get_child(knode); if (!vnode) { - ret = snprintf(buf ? buf + len : NULL, rest(len, size), - "%s ", xbc_namebuf); + ret = snprintf(buf && len < size ? buf + len : NULL, + rest(len, size), "%s ", xbc_namebuf); if (ret < 0) return ret; len += ret; @@ -601,7 +601,8 @@ int __init xbc_snprint_cmdline_filter(char *buf, size_t size, struct xbc_node *r * whitespace. */ q = strpbrk(val, " \t\r\n") ? "\"" : ""; - ret = snprintf(buf ? buf + len : NULL, rest(len, size), + ret = snprintf(buf && len < size ? buf + len : NULL, + rest(len, size), "%s=%s%s%s ", xbc_namebuf, q, val, q); if (ret < 0) return ret; From ce26f15d878137e30c1dfc7c4fce9aac88a08c5c Mon Sep 17 00:00:00 2001 From: "Masami Hiramatsu (Google)" Date: Sun, 22 Nov 2026 10:01:59 +0900 Subject: [PATCH 1348/2102] tools/bootconfig: Add tests for unclosed brace position and mixed-kv limits Add regression test cases to test-bootconfig.sh for: 1. Unclosed brace error position reporting in xbc_verify_tree() (verifying both samples/bad-tree.bconf and a multi-block config). 2. XBC_DEPTH_MAX (16) and XBC_KEYLEN_MAX (256) enforcement on subkeys under a key node that also has a value (mixed value+subkey). Link: https://lore.kernel.org/all/179530931973.109991.15787416583892751589.stgit@devnote2/ Signed-off-by: Masami Hiramatsu (Google) --- tools/bootconfig/test-bootconfig.sh | 33 +++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tools/bootconfig/test-bootconfig.sh b/tools/bootconfig/test-bootconfig.sh index e03301ad76c4d3..a93a40d11d278f 100755 --- a/tools/bootconfig/test-bootconfig.sh +++ b/tools/bootconfig/test-bootconfig.sh @@ -233,6 +233,39 @@ xpass $BOOTCONF -a $TEMPCONF $INITRD $BOOTCONF $INITRD > $OUTFILE xpass grep -q "value" $OUTFILE +echo "Unclosed brace error position" +cat > $TEMPCONF << EOF +a { + b = 1 +} +c { + d = 2 +EOF +echo > $INITRD + +xfail $BOOTCONF -a $TEMPCONF $INITRD +$BOOTCONF -a $TEMPCONF $INITRD > $OUTFILE 2>&1 +xpass grep -q "Brace.is.not.closed.at.4:1" $OUTFILE +$BOOTCONF -a samples/bad-tree.bconf $INITRD > $OUTFILE 2>&1 +xpass grep -q "Brace.is.not.closed.at.2:1" $OUTFILE + +echo "Mixed value and subkey depth/length limits" +cat > $TEMPCONF << EOF +k1 = v1 +k1.k2.k3.k4.k5.k6.k7.k8.k9.k10.k11.k12.k13.k14.k15.k16.k17 = v2 +EOF +xfail $BOOTCONF -a $TEMPCONF $INITRD + +awk ' +BEGIN { + printf("root = v\nroot.") + for (i = 0; i < 255; i += 1) + printf("a") + printf(" = v2\n") +} +' > $TEMPCONF +xfail $BOOTCONF -a $TEMPCONF $INITRD + echo "=== expected failure cases ===" for i in samples/bad-* ; do xfail $BOOTCONF -a $i $INITRD From 463f7353676179a0535dcc2aa21516a4595b4601 Mon Sep 17 00:00:00 2001 From: Andrea Di Pietro Date: Sat, 21 Nov 2026 18:43:26 +0100 Subject: [PATCH 1349/2102] ALSA: hda/realtek: Enable mute LEDs for HP OmniBook 7 14-hg0xxx Use ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS for PCI SSID 103c:8f07 (HP OmniBook 7 Laptop 14-hg0xxx) so both mute and mic-mute LEDs work alongside the dual CS35L41 I2C amplifiers. Signed-off-by: Andrea Di Pietro Link: https://patch.msgid.link/20261121174326.16369-1-andreadipietro084@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index d38be4d500b213..c746aa3a5c115c 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -8145,7 +8145,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8ee4, "HP Bantie A6U", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_GPIO), SND_PCI_QUIRK(0x103c, 0x8ee5, "HP Bantie A6U", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_GPIO), SND_PCI_QUIRK(0x103c, 0x8ee7, "HP Abe A6U", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_GPIO), - SND_PCI_QUIRK(0x103c, 0x8f07, "HP Agusta G7KX", ALC287_FIXUP_CS35L41_I2C_2), + SND_PCI_QUIRK(0x103c, 0x8f07, "HP OmniBook 7 Laptop 14-hg0xxx", ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS), SND_PCI_QUIRK(0x103c, 0x8f0c, "HP ZBook X G2i 16W", ALC236_FIXUP_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8f0e, "HP ZBook X G2i 16W", ALC236_FIXUP_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8f2d, "HP Auster 14", ALC287_FIXUP_CS35L41_I2C_2), From 2c2f36d275fefdea7e1dfc251b4fee246298dedc Mon Sep 17 00:00:00 2001 From: Parmjot Singh Date: Sun, 22 Nov 2026 19:19:08 +1300 Subject: [PATCH 1350/2102] ALSA: hda/realtek: Enable mute LEDs on HP Envy x360 15-ew0xxx The HP ENVY x360 2-in-1 Laptop 15-ew0xxx (103c:8a2a) has speaker and mic mute LEDs that are left unconfigured by the existing two-amplifier quirk. On its ALC245 codec the speaker LED uses coefficient 0x0b bits 3:2 and the mic LED uses active-low GPIO 2. Select the existing combined CS35L41 I2C and x360 mute LED fixup for this board. On an equivalent Arch Linux 7.2.14 backport, both physical LEDs responded, both native ALSA LED triggers followed the onboard mixer switches, and both CS35L41 amps loaded their protection firmware. Codex helped trace the ALSA LED controls, prepare the change and write the commit message. The LEDs were verified on the laptop. Fixes: aa8e3ef4fe53 ("ALSA: hda/realtek: Add quirks for various HP ENVY models") Cc: stable@vger.kernel.org Signed-off-by: Parmjot Singh Link: https://patch.msgid.link/20261122061908.130239-1-parmjotsinghrobot@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index c746aa3a5c115c..bcbd7edac415aa 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -7912,7 +7912,8 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8a26, "HP Victus 16-d1xxx (MB 8A26)", ALC245_FIXUP_HP_MUTE_LED_COEFBIT), SND_PCI_QUIRK(0x103c, 0x8a28, "HP Envy 13", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8a29, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2), - SND_PCI_QUIRK(0x103c, 0x8a2a, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2), + SND_PCI_QUIRK(0x103c, 0x8a2a, "HP ENVY x360 2-in-1 Laptop 15-ew0xxx", + ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS), SND_PCI_QUIRK(0x103c, 0x8a2b, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8a2c, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8a2d, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2), From 0a5550dd94e61852941fb37142f4664ecddef312 Mon Sep 17 00:00:00 2001 From: Kai Vehmanen Date: Fri, 20 Nov 2026 17:09:36 +0200 Subject: [PATCH 1351/2102] ALSA: hda: intel: Release i915 power also when delayed probe fails Commit fbaccb1b19c7 ("ALSA: hda: intel: Don't free card in the probe work") stopped freeing the card from azx_probe_work() when the delayed probe fails, and only disconnects it, leaving the free to azx_remove(). This avoids the double free, but the resources that were released by the card free via azx_free() are now kept until the PCI device is unbound. In particular the display power reference stay held, blocking runtime suspend for i915/xe. Release the display power in the azx_probe_continue() work in all cases. This power reference is only taken for the purpose of the display codec probe. If the display codec probe was successful, it will have taken its own reference. In case of systems with the HDA controller on GPU side (hda->need_i915_power), functionality is same as before - we have to keep power. Fixes: fbaccb1b19c7 ("ALSA: hda: intel: Don't free card in the probe work") Reported-by: Michal Grzelak Link: https://gitlab.freedesktop.org/drm/i915/kernel/-/work_items/17751 Signed-off-by: Kai Vehmanen Link: https://patch.msgid.link/20261120150937.2187228-1-kai.vehmanen@linux.intel.com Signed-off-by: Takashi Iwai --- sound/hda/controllers/intel.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sound/hda/controllers/intel.c b/sound/hda/controllers/intel.c index 958b00f7e2e0d9..5db800f482cc0a 100644 --- a/sound/hda/controllers/intel.c +++ b/sound/hda/controllers/intel.c @@ -2452,6 +2452,9 @@ static int azx_probe_continue(struct azx *chip, bool free_on_error) } out_free: + if (!hda->need_i915_power) + display_power(chip, false); + if (err < 0) { if (hda->vga_switcheroo_registered) dev_warn(&pci->dev, "GPU sound probed, but not operational: please add a quirk to driver_denylist\n"); @@ -2462,8 +2465,6 @@ static int azx_probe_continue(struct azx *chip, bool free_on_error) return err; } - if (!hda->need_i915_power) - display_power(chip, false); complete_all(&hda->probe_wait); to_hda_bus(bus)->bus_probing = 0; hda->probe_retry = 0; From 51934668ca98f1b23c51ce4edea3c61018da342c Mon Sep 17 00:00:00 2001 From: Eduardo Mucelli Rezende Oliveira Date: Sun, 22 Nov 2026 01:34:58 +0100 Subject: [PATCH 1352/2102] tools/bootconfig: Use the registered global tracing parameter names The boot-time tracing guide lists four kernel.* keys that do not match the parameters registered by the tracing code. For example, ftrace2bconf.sh emits kernel.fgraph_max_depth, which bootconfig passes as fgraph_max_depth on the kernel command line. The function-graph tracer registers ftrace_graph_max_depth. Use the registered names in the guide and the exporter. Teach bconf2ftrace.sh to read those names, with the previous script keys as fallbacks so existing replay configurations still work. Link: https://lore.kernel.org/all/fecf6e33d4f7e2ddf031526e7a1abef27e28f754.1795307698.git.edumucelli@gmail.com/ Fixes: 47781947947a ("Documentation: tracing: Add boot-time tracing document") Fixes: 7e66ef0046cc ("tools/bootconfig: Add a script to generate ftrace shell-command from bootconfig") Fixes: 2b86062a34a8 ("tools/bootconfig: Add a script to generates bootconfig from ftrace") Signed-off-by: Eduardo Mucelli Rezende Oliveira Signed-off-by: Masami Hiramatsu (Google) --- Documentation/trace/boottime-trace.rst | 8 ++++---- tools/bootconfig/scripts/bconf2ftrace.sh | 21 ++++++++++++++++----- tools/bootconfig/scripts/ftrace2bconf.sh | 5 +++-- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/Documentation/trace/boottime-trace.rst b/Documentation/trace/boottime-trace.rst index 2c3c1fedb92cc9..68fd6152cd0fdf 100644 --- a/Documentation/trace/boottime-trace.rst +++ b/Documentation/trace/boottime-trace.rst @@ -36,20 +36,20 @@ these options are passed as a part of kernel legacy command line. kernel.tp_printk Output trace-event data on printk buffer too. -kernel.dump_on_oops [= MODE] +kernel.ftrace_dump_on_oops [= MODE] Dump ftrace on Oops. If MODE = 1 or omitted, dump trace buffer on all CPUs. If MODE = 2, dump a buffer on a CPU which kicks Oops. kernel.traceoff_on_warning Stop tracing if WARN_ON() occurs. -kernel.fgraph_max_depth = MAX_DEPTH +kernel.ftrace_graph_max_depth = MAX_DEPTH Set MAX_DEPTH to maximum depth of fgraph tracer. -kernel.fgraph_filters = FILTER[, FILTER2...] +kernel.ftrace_graph_filter = FILTER[, FILTER2...] Add fgraph tracing function filters. -kernel.fgraph_notraces = FILTER[, FILTER2...] +kernel.ftrace_graph_notrace = FILTER[, FILTER2...] Add fgraph non-tracing function filters. diff --git a/tools/bootconfig/scripts/bconf2ftrace.sh b/tools/bootconfig/scripts/bconf2ftrace.sh index 850c2073433e12..ba29f7411f62a7 100755 --- a/tools/bootconfig/scripts/bconf2ftrace.sh +++ b/tools/bootconfig/scripts/bconf2ftrace.sh @@ -275,15 +275,26 @@ setup_instance() { # [instance] } # ftrace global configs (kernel.*) -if xbc_has_key "kernel.dump_on_oops"; then - dump_mode=`xbc_get_val "kernel.dump_on_oops" 1` +# Prefer the kernel parameter names and accept the old script keys as fallbacks. +dump_key=kernel.ftrace_dump_on_oops +xbc_has_key "$dump_key" || dump_key=kernel.dump_on_oops +if xbc_has_key "$dump_key"; then + dump_mode=`xbc_get_val "$dump_key" 1` [ "$dump_mode" ] && dump_mode=`eval echo $dump_mode` || dump_mode=1 run_cmd "echo \"$dump_mode\" > /proc/sys/kernel/ftrace_dump_on_oops" fi -set_value_of kernel.fgraph_max_depth $TRACEFS/max_graph_depth -set_array_of kernel.fgraph_filters $TRACEFS/set_graph_function -set_array_of kernel.fgraph_notraces $TRACEFS/set_graph_notrace +graph_depth_key=kernel.ftrace_graph_max_depth +xbc_has_key "$graph_depth_key" || graph_depth_key=kernel.fgraph_max_depth +set_value_of "$graph_depth_key" $TRACEFS/max_graph_depth + +graph_filter_key=kernel.ftrace_graph_filter +xbc_has_key "$graph_filter_key" || graph_filter_key=kernel.fgraph_filters +set_array_of "$graph_filter_key" $TRACEFS/set_graph_function + +graph_notrace_key=kernel.ftrace_graph_notrace +xbc_has_key "$graph_notrace_key" || graph_notrace_key=kernel.fgraph_notraces +set_array_of "$graph_notrace_key" $TRACEFS/set_graph_notrace # Per-instance/per-event configs if ! xbc_has_branch "ftrace" ; then diff --git a/tools/bootconfig/scripts/ftrace2bconf.sh b/tools/bootconfig/scripts/ftrace2bconf.sh index 8eed445c295e34..f62372adbfd598 100755 --- a/tools/bootconfig/scripts/ftrace2bconf.sh +++ b/tools/bootconfig/scripts/ftrace2bconf.sh @@ -46,10 +46,11 @@ emit_kv() { # key =|+= value global_options() { val=`cat $TRACEFS/max_graph_depth` - [ $val != 0 ] && emit_kv kernel.fgraph_max_depth = $val + [ $val != 0 ] && emit_kv kernel.ftrace_graph_max_depth = $val if grep -qv "^#" $TRACEFS/set_graph_function $TRACEFS/set_graph_notrace ; then cat 1>&2 << EOF -# WARN: kernel.fgraph_filters and kernel.fgraph_notrace are not supported, since the wild card expression was expanded and lost from memory. +# WARN: Cannot export kernel.ftrace_graph_filter and kernel.ftrace_graph_notrace. +# Only the expanded function list is available. EOF fi } From 49276f7c85ba1c140b2605b816a2596d02b36ba4 Mon Sep 17 00:00:00 2001 From: Yifan Feng Date: Tue, 17 Nov 2026 16:32:05 -0800 Subject: [PATCH 1353/2102] tracing/fprobe: Do not let KASAN check the $stackN read ftrace_regs_get_kernel_stack_nth() reads the Nth entry of the kernel stack for the $stackN argument of fprobe and tracepoint probe events. That entry can be in the redzone of another stack frame, so with CONFIG_KASAN_STACK every hit of such an event is reported: # echo 'f:fp_read vfs_read $stack10' >> dynamic_events # echo 1 > events/fprobes/fp_read/enable BUG: KASAN: stack-out-of-bounds in process_fetch_insn+0xac9/0xcb0 Use READ_ONCE_NOCHECK(), as arm64 does in regs_get_kernel_stack_nth() for kprobe events. Link: https://lore.kernel.org/all/20261118003205.59804-1-evanfengff@gmail.com/ Fixes: 0566cefe73b9 ("tracing/fprobe: Enable fprobe events with CONFIG_DYNAMIC_FTRACE_WITH_ARGS") Signed-off-by: Yifan Feng Signed-off-by: Masami Hiramatsu (Google) --- include/linux/ftrace.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/linux/ftrace.h b/include/linux/ftrace.h index 1c2056a1a68b30..bdb6ee6bc3b9e5 100644 --- a/include/linux/ftrace.h +++ b/include/linux/ftrace.h @@ -270,7 +270,7 @@ ftrace_regs_get_kernel_stack_nth(struct ftrace_regs *fregs, unsigned int nth) stackp = (unsigned long *)ftrace_regs_get_stack_pointer(fregs); if (((unsigned long)(stackp + nth) & ~(THREAD_SIZE - 1)) == ((unsigned long)stackp & ~(THREAD_SIZE - 1))) - return *(stackp + nth); + return READ_ONCE_NOCHECK(*(stackp + nth)); return 0; } From b6a9fa34ce4187cb69d3c588a4bbffc31ce5db8f Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 22 Nov 2026 14:57:40 -0800 Subject: [PATCH 1354/2102] Linux 7.4-rc4 --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 17b7ac3afbc4a4..9d5bfe5e0b43cc 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ VERSION = 7 PATCHLEVEL = 4 SUBLEVEL = 0 -EXTRAVERSION = -rc3 +EXTRAVERSION = -rc4 NAME = Baby Opossum Posse # *DOCUMENTATION* From 0fa2474dd3d04f31d885c2da82fa5f85ef2bd76c Mon Sep 17 00:00:00 2001 From: Guenter Roeck Date: Sun, 22 Nov 2026 01:19:38 +0000 Subject: [PATCH 1355/2102] hwmon: (aquacomputer_d5next) Fix collection check for Aquaero devices Commit b7743c6dbe3a ("hwmon: (aquacomputer_d5next) Check maxcollection when probing AQUAERO devices") added a check rejecting devices with hdev->maxcollection < 2 before inspecting hdev->collection[1].type in aqc_probe(). Aquacomputer Aquaero 5 (0c70:f001) exposes three HID interfaces under the same product ID: "keyboard/mouse" (3 collections, with collection[1].type == 1), "System Control" (2 collections, with collection[1].type == 1), and "aquaero Device", which is the sensor interface the driver binds to and only presents a single vendor-defined top-level collection (maxcollection == 1). Prior to that commit, probing "aquaero Device" worked because the HID core allocates HID_DEFAULT_NUM_COLLECTIONS (16) zero-filled entries for hdev->collection, so hdev->collection[1].type read as 0. Rejecting hdev->maxcollection < 2 causes aqc_probe() to return -ENODEV for "aquaero Device" and prevents the hwmon device from registering. Guard the hdev->collection[1].type != 0 check with hdev->maxcollection > 1 instead of requiring at least two collections, keeping the array access bounds-safe while allowing single-collection Aquaero sensor interfaces to probe. This commit was prepared with assistance from Gemini based on the bug report and proposed fix. Fixes: b7743c6dbe3a ("hwmon: (aquacomputer_d5next) Check maxcollection when probing AQUAERO devices") Cc: stable@vger.kernel.org Reported-by: Nandor Lieszkovszky Link: https://lore.kernel.org/linux-hwmon/3b6ce200-ae89-4629-a05b-bcdc503871d3@gmail.com/ Suggested-by: Nandor Lieszkovszky Tested-by: Aleksa Savic # Aquaero 6 Reviewed-by: Aleksa Savic Signed-off-by: Guenter Roeck --- drivers/hwmon/aquacomputer_d5next.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/hwmon/aquacomputer_d5next.c b/drivers/hwmon/aquacomputer_d5next.c index f521a6142a1326..884b5cf80fde6e 100644 --- a/drivers/hwmon/aquacomputer_d5next.c +++ b/drivers/hwmon/aquacomputer_d5next.c @@ -1575,9 +1575,10 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id) * * The difference between "aquaero Device" and the other two is in the collections * they present. The two other devices have the type of the second element in - * their respective collections set to 1, while the real device has it set to 0. + * their respective collections set to 1, while the real device either presents + * a single collection or has the type of the second element set to 0. */ - if (hdev->maxcollection < 2 || hdev->collection[1].type != 0) { + if (hdev->maxcollection > 1 && hdev->collection[1].type != 0) { ret = -ENODEV; goto fail_and_close; } From dd8680d5dc1d49d98e2d031e5899d2d20177d737 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Fri, 20 Nov 2026 11:23:09 +0100 Subject: [PATCH 1356/2102] watchdog: intel_oc_wdt: Stop the watchdog during system sleep The driver has no system sleep callbacks, so a running watchdog keeps counting in suspend-to-idle. Suspend-to-idle stops the tick, so neither user space nor the watchdog core can ping it, and the watchdog resets the machine once the timeout expires. On a Dell XPS 13 9310 (Tiger Lake, BIOS 3.17.0, no ACPI S3) with systemd `RuntimeWatchdogSec=30s` on /dev/watchdog-oc, both `rtcwake -m freeze -s 900` and `rtcwake -m freeze -s 60` resulted in a reset about 30 s after entering suspend, without any message in the journal or in pstore. With the systemd runtime watchdog disabled, the system stayed in suspend-to-idle for 900 s and resumed normally. Stop the watchdog in the noirq suspend phase and restart it, with a reload, in the noirq resume phase, as iTCO_wdt does. Check the enable bit in hardware rather than watchdog_active(), so a watchdog started by the firmware, which only the watchdog core pings, is covered too. If the control register is locked, the watchdog cannot be stopped, so leave it alone. Also program the timeout again on resume, whether or not the watchdog was running: the platform firmware may reset the control register, and when resuming from hibernation, it holds the timeout the boot kernel set. intel_oc_wdt_start() only sets the enable bit, so a timeout set with WDIOC_SETTIMEOUT would otherwise be lost. Unlike iTCO_wdt, do this for all sleep states and not only for suspend-to-idle, as it is not documented whether the platform firmware stops the OC watchdog in ACPI S3 or S4. Hangs in the device suspend and resume callbacks outside the noirq phases are still caught. Tested on a Dell XPS 13 9310 (BIOS 3.17.0) with the module built for 7.4.0-rc1 and systemd RuntimeWatchdogSec=30s: - rtcwake -m freeze -s 120 resumes normally; the stock module reset the machine in 2 of 2 attempts. - TOV restore: with the watchdog armed, overwrite TOV with 0x3b (60 s) via outl, as the firmware might, then rtcwake -m freeze -s 60. v1: register 0x0080603b after resume (TOV 60 s kept). v2: 0x0080601d (TOV 30 s restored, EN set), watchdog still running 40 s later. Fixes: 535d1784d8a9 ("watchdog: Add driver for Intel OC WDT") Signed-off-by: Paul Menzel Link: https://patch.msgid.link/20261120102311.621074-1-pmenzel@molgen.mpg.de Signed-off-by: Guenter Roeck --- drivers/watchdog/intel_oc_wdt.c | 52 +++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/drivers/watchdog/intel_oc_wdt.c b/drivers/watchdog/intel_oc_wdt.c index 0b012aeb18e155..4400a2a8811c93 100644 --- a/drivers/watchdog/intel_oc_wdt.c +++ b/drivers/watchdog/intel_oc_wdt.c @@ -44,6 +44,7 @@ struct intel_oc_wdt { struct resource *ctrl_res; struct watchdog_info info; bool locked; + bool suspended; }; static int heartbeat; @@ -204,6 +205,7 @@ static int intel_oc_wdt_probe(struct platform_device *pdev) if (ret) return ret; + platform_set_drvdata(pdev, oc_wdt); watchdog_set_drvdata(wdd, oc_wdt); watchdog_set_nowayout(wdd, nowayout); watchdog_stop_on_reboot(wdd); @@ -212,6 +214,55 @@ static int intel_oc_wdt_probe(struct platform_device *pdev) return devm_watchdog_register_device(dev, wdd); } +/* + * Neither user space nor the watchdog core can ping the watchdog while the + * system sleeps, and in suspend-to-idle the counter keeps running, so stop the + * watchdog late in suspend and restart it early in resume. Check the hardware + * enable bit, as the watchdog may also have been started by the firmware. + */ +static int intel_oc_wdt_suspend_noirq(struct device *dev) +{ + struct intel_oc_wdt *oc_wdt = dev_get_drvdata(dev); + + oc_wdt->suspended = false; + + if (oc_wdt->locked || + !(inl(INTEL_OC_WDT_CTRL_REG(oc_wdt)) & INTEL_OC_WDT_EN)) + return 0; + + intel_oc_wdt_stop(&oc_wdt->wdd); + oc_wdt->suspended = true; + + return 0; +} + +static int intel_oc_wdt_resume_noirq(struct device *dev) +{ + struct intel_oc_wdt *oc_wdt = dev_get_drvdata(dev); + + if (oc_wdt->locked) + return 0; + + /* + * The timeout in hardware may have been reset by the platform firmware + * or, when resuming from hibernation, set by the boot kernel, and + * intel_oc_wdt_start() does not program it. + */ + intel_oc_wdt_set_timeout(&oc_wdt->wdd, oc_wdt->wdd.timeout); + + if (!oc_wdt->suspended) + return 0; + + intel_oc_wdt_start(&oc_wdt->wdd); + intel_oc_wdt_ping(&oc_wdt->wdd); + oc_wdt->suspended = false; + + return 0; +} + +static DEFINE_NOIRQ_DEV_PM_OPS(intel_oc_wdt_pm_ops, intel_oc_wdt_suspend_noirq, + intel_oc_wdt_resume_noirq); + static const struct acpi_device_id intel_oc_wdt_match[] = { { "INT3F0D" }, { "INTC1099" }, @@ -223,6 +274,7 @@ static struct platform_driver intel_oc_wdt_platform_driver = { .driver = { .name = DRV_NAME, .acpi_match_table = intel_oc_wdt_match, + .pm = pm_sleep_ptr(&intel_oc_wdt_pm_ops), }, .probe = intel_oc_wdt_probe, }; From 7ad760b1be330ae39e67fa0f405bb6518f82c861 Mon Sep 17 00:00:00 2001 From: Nhat Tran Date: Sat, 21 Nov 2026 12:29:50 +0700 Subject: [PATCH 1357/2102] watchdog: core: Don't report time left for a stopped watchdog watchdog_get_timeleft() calls the driver's ->get_timeleft() regardless of whether the watchdog is running. It is reachable through the sysfs timeleft attribute, which is world readable with CONFIG_WATCHDOG_SYSFS=y, and through WDIOC_GETTIMELEFT, also after the watchdog was stopped with WDIOS_DISABLECARD while the device is still open. Drivers may not be able to access the hardware while the watchdog is stopped. omap_wdt only holds a runtime PM reference while the watchdog is running, so on a BeagleBone Black (AM335x) reading the counter of a stopped watchdog triggers an external abort. Any unprivileged user can hit it through sysfs: $ cat /sys/class/watchdog/watchdog0/timeleft Unhandled fault: external abort on non-linefetch (0x1028) at 0xf9e35028 Internal error: : 1028 [#1] SMP ARM PC is at omap_wdt_get_timeleft+0x4/0x14 LR is at watchdog_get_timeleft+0x24/0x130 Call trace: omap_wdt_get_timeleft from watchdog_get_timeleft+0x24/0x130 watchdog_get_timeleft from timeleft_show+0x3c/0x80 timeleft_show from dev_attr_show+0x18/0x4c dev_attr_show from sysfs_kf_seq_show+0xa0/0x138 ... and the same happens with WDIOS_DISABLECARD followed by WDIOC_GETTIMELEFT on the open device, once the module has idled: Call trace: omap_wdt_get_timeleft from watchdog_get_timeleft+0x24/0x130 watchdog_get_timeleft from watchdog_ioctl+0x494/0x668 watchdog_ioctl from sys_ioctl+0x128/0xbcc sys_ioctl from ret_fast_syscall+0x0/0x54 If the ioctl comes before the module has idled, the read succeeds but reports 59 seconds left for a watchdog that is stopped. A stopped watchdog will not reboot the system, so report 0 time left when neither WDOG_ACTIVE nor WDOG_HW_RUNNING is set, without calling into the driver. This matches the software fallback for drivers without ->get_timeleft(), which already decays to 0 once the watchdog is no longer pinged. Tested on a BeagleBone Black: with the watchdog stopped, both the sysfs attribute and WDIOC_GETTIMELEFT after WDIOS_DISABLECARD return 0; with the watchdog started through /dev/watchdog0, timeleft counts down as before (59, then 56 three seconds later). Fixes: 452fafed839e ("watchdog: omap_wdt: implement get_timeleft") Cc: stable@vger.kernel.org Suggested-by: Guenter Roeck Signed-off-by: Nhat Tran Link: https://patch.msgid.link/20261121052950.287506-1-nhat.tranminhk2@gmail.com Signed-off-by: Guenter Roeck --- drivers/watchdog/watchdog_dev.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/watchdog/watchdog_dev.c b/drivers/watchdog/watchdog_dev.c index aad3f1f1b4ce8d..9b175730fa9898 100644 --- a/drivers/watchdog/watchdog_dev.c +++ b/drivers/watchdog/watchdog_dev.c @@ -445,6 +445,9 @@ static void watchdog_get_timeleft(struct watchdog_device *wdd, { *timeleft = 0; + if (!watchdog_active(wdd) && !watchdog_hw_running(wdd)) + return; + if (wdd->ops->get_timeleft) { *timeleft = wdd->ops->get_timeleft(wdd); } else { From 53047bfedfb81a190c90c9b6b1713e770adc03cf Mon Sep 17 00:00:00 2001 From: David Yang Date: Sun, 22 Nov 2026 04:45:25 +0800 Subject: [PATCH 1358/2102] watchdog: sp805: re-enable the clock in the restart handler wdt_restart() fail to reboot the system if the watchdog counter clock was previously disabled: If userspace cleanly stops the watchdog, the core calls wdt_disable() which disables wdt->clk. No reset comes. Re-enable the clock in it as in npcm_wdt. The watchdog .restart() callback runs in atomic context: get the clock with devm_clk_get_optional_prepared() at probe time and keep it prepared for the lifetime of the driver, so the restart handler only needs clk_enable(), which is safe in atomic context. Link: https://lore.kernel.org/r/20260911031916.A8E051F000FF@smtp.kernel.org Fixes: 6c5c0d48b686 ("watchdog: sp805: add restart handler") Cc: stable@vger.kernel.org Signed-off-by: David Yang Link: https://patch.msgid.link/20261121204528.2435533-1-mmyangfl@gmail.com Signed-off-by: Guenter Roeck --- drivers/watchdog/sp805_wdt.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/drivers/watchdog/sp805_wdt.c b/drivers/watchdog/sp805_wdt.c index a14ff7ac0db486..4e4febc5285357 100644 --- a/drivers/watchdog/sp805_wdt.c +++ b/drivers/watchdog/sp805_wdt.c @@ -138,6 +138,13 @@ wdt_restart(struct watchdog_device *wdd, unsigned long mode, void *cmd) { struct sp805_wdt *wdt = watchdog_get_drvdata(wdd); + /* + * For reset, we start the WDT clock and leave it running. + * The clock was prepared at probe time; only clk_enable() is + * safe in this atomic (restart notifier) context. + */ + clk_enable(wdt->clk); + writel_relaxed(UNLOCK, wdt->base + WDTLOCK); writel_relaxed(0, wdt->base + WDTCONTROL); writel_relaxed(0, wdt->base + WDTLOAD); @@ -156,7 +163,7 @@ static int wdt_config(struct watchdog_device *wdd, bool ping) if (!ping) { - ret = clk_prepare_enable(wdt->clk); + ret = clk_enable(wdt->clk); if (ret) { dev_err(&wdt->adev->dev, "clock enable fail"); return ret; @@ -208,7 +215,7 @@ static int wdt_disable(struct watchdog_device *wdd) readl_relaxed(wdt->base + WDTLOCK); spin_unlock(&wdt->lock); - clk_disable_unprepare(wdt->clk); + clk_disable(wdt->clk); return 0; } @@ -253,7 +260,11 @@ sp805_wdt_probe(struct amba_device *adev, const struct amba_id *id) */ device_property_read_u64(&adev->dev, "clock-frequency", &rate); - wdt->clk = devm_clk_get_optional(&adev->dev, NULL); + /* + * Keep the clock prepared for the lifetime of the driver: + * wdt_restart() runs in atomic context and may only call clk_enable(). + */ + wdt->clk = devm_clk_get_optional_prepared(&adev->dev, NULL); if (IS_ERR(wdt->clk)) return dev_err_probe(&adev->dev, PTR_ERR(wdt->clk), "Clock not found\n"); From 5ffdc8f8361387a1b11553e5c95cd589c67a51f2 Mon Sep 17 00:00:00 2001 From: Ian Forbes Date: Wed, 27 May 2026 15:20:18 -0500 Subject: [PATCH 1359/2102] ttm/pool: Don't leak LRU list on shutdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TTM pool was changed from a regular list to an lru list in the referenced fixes commit. list_lru_init allocates state and it needs to be freed unlike a simple list. Found using the igt@core_hotunplug and kmemleak. Fixes: 444e2a19d7fd ("ttm/pool: port to list_lru. (v2)") Signed-off-by: Ian Forbes Reviewed-by: Christian König Signed-off-by: Dave Airlie Link: https://patch.msgid.link/20260527202018.1223912-1-ian.forbes@broadcom.com --- drivers/gpu/drm/ttm/ttm_pool.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/gpu/drm/ttm/ttm_pool.c b/drivers/gpu/drm/ttm/ttm_pool.c index 1bf37023fed663..0076594b00683a 100644 --- a/drivers/gpu/drm/ttm/ttm_pool.c +++ b/drivers/gpu/drm/ttm/ttm_pool.c @@ -421,6 +421,7 @@ static void ttm_pool_type_fini(struct ttm_pool_type *pt) list_lru_walk(&pt->pages, pool_move_to_dispose_list, &dispose, LONG_MAX); ttm_pool_dispose_list(pt, &dispose); + list_lru_destroy(&pt->pages); } /* Return the pool_type to use for the given caching and order */ From 86d477c009ed7f3a24b420b7f4aa314fabe36be3 Mon Sep 17 00:00:00 2001 From: Atish Patra Date: Wed, 18 Nov 2026 19:19:17 -0800 Subject: [PATCH 1360/2102] x86/entry: Make SafeRET robust also against NMIs On NMI entry, the kernel copies three exception frames which are used in crazy ways in order to be able to handle nested NMIs. However, when that handler interrupts a SafeRET sequence of a #VC exception, it would copy the SafeRET-unfixed rSP and rIP into those frames. paranoid_entry() later will fix up the original frame but the IRET frame which is the one actually used to return from the NMI handler remains unfixed, leaving the two frames inconsistent. And because this is a #VC exception which gets to use __sev_es_ist_enter() to handle NMIs raised in the #VC exception entry code, that function will use the fixed up stack pointer from pt_regs. However, in doing so, it will overwrite the return address which the stale IRET frame still needs, leading up to the NMI returning to the old, now stale VC stack slot. Convert the SafeRET frame fixup code to asm and change it so that it can get a frame passed in and it can correct it before it gets worked on later. And because it is an asm macro, it doesn't need the LFENCE speculation stopper anymore. Fixes: 7e7f81cf6f5c ("x86/bugs: Make Safe-RET robust against interrupt injection") Signed-off-by: Atish Patra Co-developed-by: Thomas Gleixner Signed-off-by: Thomas Gleixner Signed-off-by: Borislav Petkov (AMD) Cc: --- arch/x86/entry/entry_64.S | 7 ++- arch/x86/include/asm/nospec-branch.h | 83 +++++++++++++++------------- arch/x86/kernel/cpu/bugs.c | 39 ------------- arch/x86/lib/retpoline.S | 6 +- 4 files changed, 54 insertions(+), 81 deletions(-) diff --git a/arch/x86/entry/entry_64.S b/arch/x86/entry/entry_64.S index 253f0a585927fe..7cfc617750c56b 100644 --- a/arch/x86/entry/entry_64.S +++ b/arch/x86/entry/entry_64.S @@ -937,7 +937,7 @@ SYM_CODE_START(paranoid_entry) IBRS_ENTER save_reg=%r15 UNTRAIN_RET_FROM_CALL - HANDLE_INTR_SAFERET 8(%rsp) + FIXUP_INTR_SAFERET %rsp RET SYM_CODE_END(paranoid_entry) @@ -1044,7 +1044,7 @@ SYM_CODE_START(error_entry) VALIDATE_UNRET_END - HANDLE_INTR_SAFERET 8(%rsp) + FIXUP_INTR_SAFERET %rsp cmpq $.Lgs_change, RIP+8(%rsp) jne .Lerror_entry_done_lfence @@ -1205,6 +1205,9 @@ SYM_CODE_START(asm_exc_nmi) jmp swapgs_restore_regs_and_return_to_usermode .Lnmi_from_kernel: + /* Repair the source frame before inspecting or copying it. */ + FIXUP_NMI_INTR_SAFERET %rsp + /* * Here's what our stack frame will look like: * +---------------------------------------------------------+ diff --git a/arch/x86/include/asm/nospec-branch.h b/arch/x86/include/asm/nospec-branch.h index 1abeb9af000ba1..64554434320d0c 100644 --- a/arch/x86/include/asm/nospec-branch.h +++ b/arch/x86/include/asm/nospec-branch.h @@ -185,42 +185,39 @@ * * The Safe-RET sequence is: * - * CALL - * LEA 8(%RSP), %RSP - * RET + * CALL L1 + * L1: LEA 8(%RSP), %RSP + * L2: RET * - * The two CMPs below check whether RIP points to after the CALL or after the - * LEA. + * The C equivalent of the ASM sequence below is: * - * The LFENCE below is to address this particular speculation case: + * if (ptr->RIP > L2) // After RET? + * goto done; + * if (ptr->RIP < L1) // Before LEA ? + * goto done; + * if (ptr->RIP == L1) // At LEA ? + * ptr->RSP += 8; // Emulate LEA + * tmp = *ptr->RSP; // Read original return IP + * ptr->RIP = tmp; // Overwrite interrupt return IP + * ptr->RSP += 8; // Emulate RET * - * 1. Userspace runs and poisons the BTB around the safe-RET routine - * - * 2. Userspace triggers some kind of exception - * - * 3. Kernel executes error_entry() and mis-speculates the branch into thinking - * it actually came from kernel space - * - * 4. The kernel then further mis-speculates that the exception occurred due - * to an interrupted safe-RET - * - * 5. The handle_interrupted_saferet() routine speculatively executes and - * speculatively does a safe-RET. But this is unsafe since it was never - * untrained. - * - * The LFENCE fixes this by ensuring step 5 is never reached speculatively. - * Note that this LFENCE only occurs if safe-RET was actually interrupted (so - * it's outside of the normal path). + * This ensures that this interrupt returns to the original return IP without + * resuming the interrupted safe-RET sequence. */ -#define __HANDLE_INTR_SAFERET(name, pt_regs) \ - cmpq $(name), RIP+pt_regs; \ - jb 1f; \ - cmpq $(name)+5, RIP+pt_regs; \ - ja 1f; \ - lfence; \ - leaq pt_regs, %rdi; \ - call handle_interrupted_saferet; \ - 1: +#define __FIXUP_INTR_SAFERET(name, ptr, rip_offs, rsp_offs) \ + cmpq $(name)+5, rip_offs(ptr); \ + ja 2f; \ + cmpq $(name), rip_offs(ptr); \ + jb 2f; \ + jne 1f; \ + addq $8, rsp_offs(ptr); \ + 1:; \ + movq rsp_offs(ptr), %rdx; \ + movq (%rdx), %rdx; \ + movq %rdx, rip_offs(ptr); \ + addq $8, rsp_offs(ptr); \ + 2: + #ifdef __ASSEMBLER__ @@ -305,7 +302,7 @@ .macro CALL_UNTRAIN_RET #if defined(CONFIG_MITIGATION_UNRET_ENTRY) || defined(CONFIG_MITIGATION_SRSO) ALTERNATIVE_2 "", "call entry_untrain_ret", X86_FEATURE_UNRET, \ - "call srso_alias_untrain_ret", X86_FEATURE_SRSO_ALIAS + "call srso_alias_untrain_ret", X86_FEATURE_SRSO_ALIAS #endif .endm @@ -339,12 +336,25 @@ #define UNTRAIN_RET_FROM_CALL \ __UNTRAIN_RET X86_FEATURE_ENTRY_IBPB, __stringify(RESET_CALL_DEPTH_FROM_CALL) -.macro HANDLE_INTR_SAFERET pt_regs +.macro FIXUP_INTR_SAFERET pt_regs #ifdef CONFIG_MITIGATION_SRSO ALTERNATIVE_2 "", \ - __stringify(__HANDLE_INTR_SAFERET(srso_safe_ret, \pt_regs)), X86_FEATURE_SRSO, \ - __stringify(__HANDLE_INTR_SAFERET(srso_alias_safe_ret, \pt_regs)), X86_FEATURE_SRSO_ALIAS + __stringify(__FIXUP_INTR_SAFERET(srso_safe_ret, \pt_regs, RIP+8, RSP+8)), X86_FEATURE_SRSO, \ + __stringify(__FIXUP_INTR_SAFERET(srso_alias_safe_ret, \pt_regs, RIP+8, RSP+8)), X86_FEATURE_SRSO_ALIAS +#endif +.endm +/* + * Note the offsets encoding below: + * + * The IRET frame at call site in asm_exc_nmi() starts at 8(%rsp) (NMI handler + * users %rdx as a temp var so it pushes it on the stack on entry). + */ +.macro FIXUP_NMI_INTR_SAFERET fptr +#ifdef CONFIG_MITIGATION_SRSO + ALTERNATIVE_2 "", \ + __stringify(__FIXUP_INTR_SAFERET(srso_safe_ret, \fptr, RIP-RIP+8, RSP-RIP+8)), X86_FEATURE_SRSO, \ + __stringify(__FIXUP_INTR_SAFERET(srso_alias_safe_ret, \fptr, RIP-RIP+8, RSP-RIP+8)), X86_FEATURE_SRSO_ALIAS #endif .endm @@ -681,7 +691,6 @@ static __always_inline void x86_idle_clear_cpu_buffers(void) void srso_safe_ret(void); void srso_alias_safe_ret(void); -void handle_interrupted_saferet(struct pt_regs *regs); #endif /* __ASSEMBLER__ */ diff --git a/arch/x86/kernel/cpu/bugs.c b/arch/x86/kernel/cpu/bugs.c index 4ced10c6ba0db9..8c2c8310f96f61 100644 --- a/arch/x86/kernel/cpu/bugs.c +++ b/arch/x86/kernel/cpu/bugs.c @@ -3787,42 +3787,3 @@ void __warn_thunk(void) { WARN_ONCE(1, "Unpatched return thunk in use. This should not happen!\n"); } - -#ifdef CONFIG_MITIGATION_SRSO -/* - * Called during exception/interrupt entry if interrupted during the - * safe-RET sequence. The safe-RET sequence consists of 3 instructions: - * - * CALL - * LEA 8(%RSP), %RSP - * RET - * - * An interrupt after the CALL or after the LEA could potentially lead - * to branch predictor poisoning and results in the sequence not being - * able to be safely resumed. - * - * Therefore, modify the regs state as if the remaining part of the - * safe-RET sequence executed so the interrupt returns back to the - * desired return target, instead of the to the safe-RET sequence. - */ -void noinstr handle_interrupted_saferet(struct pt_regs *regs) -{ - unsigned long rip = regs->ip; - - if (rip == (unsigned long) srso_safe_ret || - rip == (unsigned long) srso_alias_safe_ret) { - /* Modify stack pointer as if LEA executed: */ - regs->sp += 8; - } - - /* - * Adjust registers as if RET executed: - * - * 1. Read the return address off the stack and into rIP: - */ - regs->ip = *(unsigned long *)(regs->sp); - - /* 2. Pop rIP off the stack: */ - regs->sp += 8; -} -#endif /* CONFIG_MITIGATION_SRSO */ diff --git a/arch/x86/lib/retpoline.S b/arch/x86/lib/retpoline.S index f9ca1d8eabca0d..376119f0bba791 100644 --- a/arch/x86/lib/retpoline.S +++ b/arch/x86/lib/retpoline.S @@ -210,13 +210,13 @@ SYM_CODE_START_NOALIGN(srso_alias_safe_ret) /* * Tell objtool that those are not function pointers referenced by - * __HANDLE_INTR_SAFERET(). Below too. + * FIXUP_[NMI_]INTR_SAFERET(). Below too. */ ANNOTATE_NOENDBR /* * Safe-RET sequence. If you need to change it, adjust - * handle_interrupted_saferet() too. + * FIXUP_[NMI_]INTR_SAFERET() too. */ lea 8(%_ASM_SP), %_ASM_SP UNWIND_HINT_FUNC @@ -261,7 +261,7 @@ SYM_CODE_START_LOCAL_NOALIGN(srso_untrain_ret) SYM_INNER_LABEL(srso_safe_ret, SYM_L_GLOBAL) /* * Safe-RET sequence. If you need to change it, adjust - * handle_interrupted_saferet() too. + * FIXUP_[NMI_]INTR_SAFERET() too. */ lea 8(%_ASM_SP), %_ASM_SP ret From ff056011e9f7604683694c9c4a3daf102c785921 Mon Sep 17 00:00:00 2001 From: Chris Down Date: Sun, 8 Nov 2026 00:41:37 -0800 Subject: [PATCH 1361/2102] mm: memcontrol: don't lose track of exiting OOM victims When oom_evaluate_task() comes across a victim we've already killed, it backs off until the victim's mm has MMF_OOM_SKIP. This gives the victim a chance to free some memory before we kill anything else. However, since commit a72f73c4dd9b ("cgroup: Don't expose dead tasks in cgroup"), css_task_iter skips exiting tasks once signal->live reaches zero. That happens before exit_mm(), so a single-threaded victim can disappear from the memcg scan while it still has all its memory. This can kill another process when the first kill would have been enough to recover, and we've seen it happen in production. If the second victim is in a cgroup with memory.oom.group enabled, the extra kill can take down the whole workload. In tests I used a 64 MiB memcg with swap disabled. I started a process that faults in 44 MiB of anonymous memory, submits a 4 KiB direct AIO read to null_blk, and goes to sleep. I set null_blk to take 10 seconds to complete the read so the victim would have to wait for it in exit_aio(). Two seconds after starting the first process, I started a second one that tries to fault in 40 MiB. The 40 MiB allocation hits memory.max partway through and triggers an OOM kill. The OOM killer picks the first process, which has more resident memory. With the read still pending, the victim blocks in exit_aio() before it can tear down its address space. memory.events showed oom_kill 2 in three runs. In one of them the first process hadn't submitted the read yet when it was killed. The slow read just makes the window easier to hit. The cgroup iterator hides these tasks so that cgroup.procs doesn't show processes that waitpid() may already have reaped. That's fine for cgroup.procs, but the OOM scan needs to see a victim even after its last thread has started exiting. We already have CSS_TASK_ITER_WITH_DEAD for sched_ext, so use it for mem_cgroup_scan_tasks() as well. With this applied, OOM selection backs off while the first victim still has memory to free. The 40 MiB allocation completes and memory.events shows oom_kill 1 in three test runs. Link: https://patch.msgid.link/avA1wXhTMs9eY2NF@chrisdown.name Fixes: a72f73c4dd9b ("cgroup: Don't expose dead tasks in cgroup") Signed-off-by: Chris Down Signed-off-by: Andrew Morton Acked-by: Shakeel Butt Acked-by: Michal Hocko Reviewed-by: Johannes Weiner Tested-by: elenchist Link: https://lore.kernel.org/6B8E9261-3FF8-441B-8F47-7D35834A8D35@gmail.com Cc: Michal Hocko Cc: Roman Gushchin Cc: Muchun Song Cc: Tejun Heo Cc: Sebastian Andrzej Siewior Cc: Zhan Xusheng Cc: mm/memcontrol.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) --- mm/memcontrol.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 84f4a8fd4d16f1..cb7cfae9ce5a6c 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -1451,7 +1451,13 @@ void mem_cgroup_scan_tasks(struct mem_cgroup *memcg, struct css_task_iter it; struct task_struct *task; - css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it); + /* + * An OOM victim can start exiting well before its mm is + * torn down. Keep it visible so oom_evaluate_task() can + * back off while there's still memory to free. + */ + css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS | + CSS_TASK_ITER_WITH_DEAD, &it); while (!ret && (task = css_task_iter_next(&it))) { ret = fn(task, arg); /* Avoid potential softlockup warning */ From 76e1b20670b51a6cb31dc65877fc9a10f06366a2 Mon Sep 17 00:00:00 2001 From: Hungyu Lin Date: Wed, 4 Nov 2026 07:10:02 +0000 Subject: [PATCH 1362/2102] filemap: prefault writes starting beyond EOF Since prefaulting moved to the slow write path, a buffered write can reach ->write_begin() and ->write_end() before discovering that its source buffer is unreadable. Several filesystems can extend i_size in these callbacks even when no data was copied. For example, a one-byte pwrite() at offset 4096 into an empty file can fail with EFAULT but leave a 4096-byte file. Prefault the source before ->write_begin() when the write position is beyond EOF, and return EFAULT if no source bytes can be made readable. Overwrites and appends continue to skip this prefault. Keep the existing slow-path faulting for forward progress after a failed atomic copy. This also leaves intentional zero-length ->write_end() calls used by generic_cont_expand_simple() unchanged. As with the previous prefaulting behavior, a concurrent userspace unmap can still race with the later copy. Link: https://patch.msgid.link/20261104071002.49693-1-dennylin0707@gmail.com Fixes: 665575cff098 ("filemap: move prefaulting out of hot write path") Signed-off-by: Hungyu Lin Signed-off-by: Andrew Morton Suggested-by: Kiryl Shutsemau Link: https://lore.kernel.org/all/at-XtWBQg3jv3H8Z@thinkstation/ Reviewed-by: Jan Kara Reviewed-by: Kiryl Shutsemau (Meta) Cc: Matthew Wilcox (Oracle) Cc: Dave Hansen Cc: Pedro Falcato Cc: mm/filemap.c | 10 ++++++++++ 1 file changed, 10 insertions(+) --- mm/filemap.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/mm/filemap.c b/mm/filemap.c index a1b2ca5b933cb3..3bf31cc9d27091 100644 --- a/mm/filemap.c +++ b/mm/filemap.c @@ -4404,6 +4404,16 @@ ssize_t generic_perform_write(struct kiocb *iocb, struct iov_iter *i) break; } + /* + * Some filesystems can extend i_size even when nothing was copied. + * Prefault writes beyond EOF to catch unreadable source buffers. + */ + if (unlikely(pos > i_size_read(mapping->host)) && + fault_in_iov_iter_readable(i, bytes) == bytes) { + status = -EFAULT; + break; + } + status = a_ops->write_begin(iocb, mapping, pos, bytes, &folio, &fsdata); if (unlikely(status < 0)) From 2ec6ad932675db84a55d0bce7543e80c5ba8351c Mon Sep 17 00:00:00 2001 From: Alexandre Ghiti Date: Mon, 9 Nov 2026 15:18:32 -0800 Subject: [PATCH 1363/2102] mm, swap: only prefer nonfull clusters on synchronous devices Commit 9a42aed48421 ("mm, swap: prefer nonfull over free clusters") made the allocator fill nonfull clusters before taking free ones on swap devices without discard. Commit 3cedb745d354 ("mm: clarify the folio_free_swap() for do_swap_page()") frees the swap slot on an exclusive write fault. Such faults now leave holes in formerly full clusters, putting those clusters back on the nonfull list. Reclaim allocates slots one folio at a time, scattering a batch across the holes instead of producing mergeable writes. Later swapin can also require more read requests. On a mysql/sysbench workload in a 256 MiB memcg swapping to an NVMe partition, 7.3 compared with the previous version produced 59% more device read requests and 27% more write requests per transaction. Throughput was unchanged without iocost and fell 19% with iocost. Prefer free clusters first on nonsynchronous devices, preserving contiguous swap slots for merging I/O. Keep nonfull-first on synchronous devices such as zram: they do not merge I/O, and filling holes saves free clusters for large folios. Keep free-cluster preference on discard devices to spread writes. In the same workload, v2 reduced read requests per transaction by 14% and write requests by 48% against its base kernel. Throughput was unchanged without iocost and improved 33% with iocost. The RFC's batch-aware allocator also improved this workload, but this policy needs no batch information from reclaim. Reverting the slot-freeing change would keep swap space pinned under dirty pages; a proposed 50% swap-usage cutoff for free-cluster preference was arbitrary and would stop helping as swap filled. The 7.0 to 7.2 kernels retained the swap slot after a write fault as a side effect of 4b34f1d82c65 ("mm, swap: free the swap cache after folio is mapped"). The observed regression requires both 9a42aed48421 and 3cedb745d354; stable backports should target trees containing both. Link: https://lore.kernel.org/r/20261105155032.240457-1-alex@ghiti.fr Link: https://lore.kernel.org/r/20261105155032.240457-2-alex@ghiti.fr Link: https://lore.kernel.org/r/20261022145615.2184343-1-alex@ghiti.fr Link: https://lore.kernel.org/r/CAMgjq7BFbXEKEt9faj_rg5AStfLkpJ0j57EQOOJ+L3-w2xRvtg@mail.gmail.com Fixes: 9a42aed48421 ("mm, swap: prefer nonfull over free clusters") Signed-off-by: Alexandre Ghiti Signed-off-by: Andrew Morton Suggested-by: Kairui Song Acked-by: Kairui Song Reviewed-by: Nhat Pham Cc: mm/swapfile.c | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) --- mm/swapfile.c | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/mm/swapfile.c b/mm/swapfile.c index c2af13eb15b33d..4a0afc8f9a07b9 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -973,6 +973,17 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si, return true; } +/* + * Prefer a new cluster over a nonfull one if the device needs discard, to + * spread out the writes, or if it is not synchronous, to keep the slots + * of a swapout batch contiguous so that its writes can be merged. + */ +static bool swap_prefer_free_cluster(struct swap_info_struct *si) +{ + return (si->flags & SWP_PAGE_DISCARD) || + !(si->flags & SWP_SYNCHRONOUS_IO); +} + /* Try use a new cluster for current CPU and allocate from it. */ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci, @@ -1143,11 +1154,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, } new_cluster: - /* - * If the device need discard, prefer new cluster over nonfull - * to spread out the writes. - */ - if (si->flags & SWP_PAGE_DISCARD) { + if (swap_prefer_free_cluster(si)) { found = alloc_swap_scan_list(si, &si->free_clusters, folio, false); if (found) goto done; @@ -1159,7 +1166,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, goto done; } - if (!(si->flags & SWP_PAGE_DISCARD)) { + if (!swap_prefer_free_cluster(si)) { found = alloc_swap_scan_list(si, &si->free_clusters, folio, false); if (found) goto done; From dedc63739690f130e19d7ff10945cdd54a9dc30f Mon Sep 17 00:00:00 2001 From: Wang Guangke Date: Mon, 9 Nov 2026 16:48:14 -0800 Subject: [PATCH 1364/2102] mm/damon/stat: avoid overflow in estimated_memory_bandwidth calculation estimated_memory_bandwidth is calculated by access_bytes * USEC_PER_MSEC * MSEC_PER_SEC (= USEC_PER_SEC) / aggr_interval, and users read it via /sys/module/damon_stat/parameters/estimated_memory_bandwidth. On 32-bit systems, access_bytes * USEC_PER_SEC overflows unsigned long once access_bytes exceeds about 4294 (U32_MAX / USEC_PER_SEC), so users get a wrong value. Fix it by doing the calculation in 64-bit and splitting the division into quotient and remainder. The issue was reproduced on a 32-bit system (qemu-system-i386): the parameter estimated_memory_bandwidth reported 362 instead of the expected 1926150; with the fix, the value matches the expectation. Link: https://patch.msgid.link/20261110004816.100066-1-sj@kernel.org Fixes: fabdd1e911da ("mm/damon/stat: calculate and expose estimated memory bandwidth") Signed-off-by: Wang Guangke Signed-off-by: SJ Park Signed-off-by: Andrew Morton Reviewed-by: SJ Park Cc: mm/damon/stat.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) --- mm/damon/stat.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/mm/damon/stat.c b/mm/damon/stat.c index b05b68f73e10de..e44f5bf3645ccf 100644 --- a/mm/damon/stat.c +++ b/mm/damon/stat.c @@ -32,8 +32,8 @@ static bool enabled __read_mostly = IS_ENABLED( module_param_cb(enabled, &enabled_param_ops, NULL, 0600); MODULE_PARM_DESC(enabled, "Enable of disable DAMON_STAT"); -static unsigned long estimated_memory_bandwidth __read_mostly; -module_param(estimated_memory_bandwidth, ulong, 0400); +static u64 estimated_memory_bandwidth __read_mostly; +module_param(estimated_memory_bandwidth, ullong, 0400); MODULE_PARM_DESC(estimated_memory_bandwidth, "Estimated memory bandwidth usage in bytes per second"); @@ -55,15 +55,18 @@ static void damon_stat_set_estimated_memory_bandwidth(struct damon_ctx *c) { struct damon_target *t; struct damon_region *r; - unsigned long access_bytes = 0; + u64 access_bytes = 0; + u64 remainder, bytes_per_us; damon_for_each_target(t, c) { damon_for_each_region(r, t) - access_bytes += (r->ar.end - r->ar.start) * + access_bytes += (u64)(r->ar.end - r->ar.start) * r->nr_accesses; } - estimated_memory_bandwidth = access_bytes * USEC_PER_MSEC * - MSEC_PER_SEC / c->attrs.aggr_interval; + bytes_per_us = div64_u64_rem(access_bytes, + c->attrs.aggr_interval, &remainder); + estimated_memory_bandwidth = bytes_per_us * USEC_PER_SEC + + div64_u64(remainder * USEC_PER_SEC, c->attrs.aggr_interval); } static int damon_stat_idletime(const struct damon_region *r) From 19fbd11621c79fc22d212837c4dbd11fa369da21 Mon Sep 17 00:00:00 2001 From: "Lorenzo Stoakes (ARM)" Date: Tue, 10 Nov 2026 12:03:07 +0000 Subject: [PATCH 1365/2102] MAINTAINERS: remove myself from MM core reviewership MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Patch series "MAINTAINERS: remove my reviewerships, add CREDITS entry for THP". Given the current throughput in the kernel resulting from AI-generated series, I unfortunately lack the bandwidth to generally be able to offer review except in those areas I maintain. I have separated the patches into areas maintained by David, Andrew, and Alice + Danilo, so each can take the patches relevant to the subsystems, for convenience. Apologies for doing this, but given the current trends I'd like to do something to make my inbox a little more manageable :) Also add a CREDITS entry for THP, as, since Zi's rightful and well-earned appointment as co-maintainer there, I have no fear of needing to step in there, and so would like to record my time in that role. This patch (of 4): Given the current throughput in the kernel resulting from AI-generated series, I unfortunately lack the bandwidth to generally be able to offer review except in those areas I maintain. Therefore, remove myself as a reviewer. Link: https://lore.kernel.org/20261110-drop-reviewerships-v1-0-07c2f06e8dfa@kernel.org Link: https://patch.msgid.link/20261110-drop-reviewerships-v1-1-07c2f06e8dfa@kernel.org Signed-off-by: Lorenzo Stoakes (ARM) Signed-off-by: Andrew Morton Acked-by: Mike Rapoport (Microsoft) Acked-by: Zi Yan Acked-by: Lance Yang Acked-by: David Hildenbrand (Arm) Acked-by: Kiryl Shutsemau (Meta) Acked-by: Danilo Krummrich Acked-by: Barry Song Acked-by: SJ Park Acked-by: Baolin Wang Acked-by: Dev Jain Cc: Miguel Ojeda Cc: Alice Ryhl Cc: Boqun Feng Cc: Gary Guo Cc: Björn Roy Baron Cc: Benno Lossin Cc: Andreas Hindborg Cc: Trevor Gross Cc: Daniel Almeida Cc: Tamir Duberstein Cc: Alexandre Courbot Cc: Onur Özkan Cc: Liam R. Howlett Cc: Vlastimil Babka Cc: Suren Baghdasaryan Cc: Michal Hocko Cc: Johannes Weiner Cc: Qi Zheng Cc: Shakeel Butt Cc: Uladzislau Rezki (Sony) Cc: Nico Pache Cc: Ryan Roberts Cc: Usama Arif MAINTAINERS | 1 - 1 file changed, 1 deletion(-) --- MAINTAINERS | 1 - 1 file changed, 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index ca1c59e1fc5928..8914a92a3cd448 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -17504,7 +17504,6 @@ F: mm/balloon.c MEMORY MANAGEMENT - CORE M: David Hildenbrand -R: Lorenzo Stoakes R: Liam R. Howlett R: Vlastimil Babka R: Mike Rapoport From cedc74686fd63972f87de6017a5738e6b6709c13 Mon Sep 17 00:00:00 2001 From: "Lorenzo Stoakes (ARM)" Date: Tue, 10 Nov 2026 12:03:08 +0000 Subject: [PATCH 1366/2102] MAINTAINERS: remove myself from MM misc, reclaim reviewership MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Given the current throughput in the kernel resulting from AI-generated series, I unfortunately lack the bandwidth to generally be able to offer review except in those areas I maintain. Therefore, remove myself as a reviewer. Link: https://patch.msgid.link/20261110-drop-reviewerships-v1-2-07c2f06e8dfa@kernel.org Signed-off-by: Lorenzo Stoakes (ARM) Signed-off-by: Andrew Morton Acked-by: Mike Rapoport (Microsoft) Acked-by: Zi Yan Acked-by: Lance Yang Acked-by: David Hildenbrand (Arm) Acked-by: Kiryl Shutsemau (Meta) Acked-by: Danilo Krummrich Acked-by: Barry Song Acked-by: SJ Park Acked-by: Baolin Wang Acked-by: Dev Jain Cc: Miguel Ojeda Cc: Alice Ryhl Cc: Boqun Feng Cc: Gary Guo Cc: Björn Roy Baron Cc: Benno Lossin Cc: Andreas Hindborg Cc: Trevor Gross Cc: Daniel Almeida Cc: Tamir Duberstein Cc: Alexandre Courbot Cc: Onur Özkan Cc: Liam R. Howlett Cc: Vlastimil Babka Cc: Suren Baghdasaryan Cc: Michal Hocko Cc: Johannes Weiner Cc: Qi Zheng Cc: Shakeel Butt Cc: Uladzislau Rezki (Sony) Cc: Nico Pache Cc: Ryan Roberts Cc: Usama Arif MAINTAINERS | 2 -- 1 file changed, 2 deletions(-) --- MAINTAINERS | 2 -- 1 file changed, 2 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index 8914a92a3cd448..b20eb70cb6cbb7 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -17674,7 +17674,6 @@ F: mm/migrate_device.c MEMORY MANAGEMENT - MISC M: Andrew Morton M: David Hildenbrand -R: Lorenzo Stoakes R: Liam R. Howlett R: Vlastimil Babka R: Mike Rapoport @@ -17810,7 +17809,6 @@ R: David Hildenbrand R: Michal Hocko R: Qi Zheng R: Shakeel Butt -R: Lorenzo Stoakes L: linux-mm@kvack.org S: Maintained F: include/trace/events/vmscan.h From 6de077ea0a7df6bc78797376c309642472490f73 Mon Sep 17 00:00:00 2001 From: "Lorenzo Stoakes (ARM)" Date: Tue, 10 Nov 2026 12:03:09 +0000 Subject: [PATCH 1367/2102] MAINTAINERS: remove myself from MM rust reviewerships MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Given the current throughput in the kernel resulting from AI-generated series, I unfortunately lack the bandwidth to generally be able to offer review except in those areas I maintain. Therefore, remove myself as a reviewer. Link: https://patch.msgid.link/20261110-drop-reviewerships-v1-3-07c2f06e8dfa@kernel.org Signed-off-by: Lorenzo Stoakes (ARM) Signed-off-by: Andrew Morton Acked-by: Mike Rapoport (Microsoft) Acked-by: Zi Yan Acked-by: Lance Yang Acked-by: David Hildenbrand (Arm) Acked-by: Kiryl Shutsemau (Meta) Acked-by: Danilo Krummrich Acked-by: Barry Song Acked-by: SJ Park Acked-by: Baolin Wang Acked-by: Dev Jain Cc: Miguel Ojeda Cc: Alice Ryhl Cc: Boqun Feng Cc: Gary Guo Cc: Björn Roy Baron Cc: Benno Lossin Cc: Andreas Hindborg Cc: Trevor Gross Cc: Daniel Almeida Cc: Tamir Duberstein Cc: Alexandre Courbot Cc: Onur Özkan Cc: Liam R. Howlett Cc: Vlastimil Babka Cc: Suren Baghdasaryan Cc: Michal Hocko Cc: Johannes Weiner Cc: Qi Zheng Cc: Shakeel Butt Cc: Uladzislau Rezki (Sony) Cc: Nico Pache Cc: Ryan Roberts Cc: Usama Arif MAINTAINERS | 2 -- 1 file changed, 2 deletions(-) --- MAINTAINERS | 2 -- 1 file changed, 2 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index b20eb70cb6cbb7..792135be7a74bc 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -17957,7 +17957,6 @@ F: tools/testing/selftests/mm/uffd-*.[ch] MEMORY MANAGEMENT - RUST M: Alice Ryhl -R: Lorenzo Stoakes R: Liam R. Howlett L: linux-mm@kvack.org L: rust-for-linux@vger.kernel.org @@ -24658,7 +24657,6 @@ K: \b(?i:rust)\b RUST [ALLOC] M: Danilo Krummrich M: Alice Ryhl -R: Lorenzo Stoakes R: Vlastimil Babka R: Liam R. Howlett R: Uladzislau Rezki From 85bb3972069039f22610124d55cee26b88e9d8af Mon Sep 17 00:00:00 2001 From: "Lorenzo Stoakes (ARM)" Date: Tue, 10 Nov 2026 12:03:10 +0000 Subject: [PATCH 1368/2102] CREDITS: add entry for THP maintenance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Given my workload and current areas of focus, I think it's unlikely I will return to THP, so add a CREDITS entry to reflect my time as co-maintainer there. With Zi being appointed as an absolutely worthy successor as THP co-maintainer I am confident in its success, and this additionally makes me feel that it is unnecessary for me to return (for the best possible reasons!) Link: https://patch.msgid.link/20261110-drop-reviewerships-v1-4-07c2f06e8dfa@kernel.org Signed-off-by: Lorenzo Stoakes (ARM) Signed-off-by: Andrew Morton Acked-by: Mike Rapoport (Microsoft) Acked-by: Zi Yan Acked-by: Lance Yang Acked-by: David Hildenbrand (Arm) Acked-by: Kiryl Shutsemau (Meta) Acked-by: Danilo Krummrich Acked-by: Barry Song Acked-by: SJ Park Acked-by: Baolin Wang Acked-by: Dev Jain Cc: Miguel Ojeda Cc: Alice Ryhl Cc: Boqun Feng Cc: Gary Guo Cc: Björn Roy Baron Cc: Benno Lossin Cc: Andreas Hindborg Cc: Trevor Gross Cc: Daniel Almeida Cc: Tamir Duberstein Cc: Alexandre Courbot Cc: Onur Özkan Cc: Liam R. Howlett Cc: Vlastimil Babka Cc: Suren Baghdasaryan Cc: Michal Hocko Cc: Johannes Weiner Cc: Qi Zheng Cc: Shakeel Butt Cc: Uladzislau Rezki (Sony) Cc: Nico Pache Cc: Ryan Roberts Cc: Usama Arif CREDITS | 6 ++++++ 1 file changed, 6 insertions(+) --- CREDITS | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CREDITS b/CREDITS index c6c7b173b06445..226a71e45edc3c 100644 --- a/CREDITS +++ b/CREDITS @@ -3939,6 +3939,12 @@ D: mandocs and mandocs_install build targets S: (Email me and ask) S: Australia +N: Lorenzo Stoakes +E: ljs@kernel.org +W: https://ljs.io +D: THP co-maintainer +S: UK + N: Henrik Storner E: storner@image.dk W: http://www.image.dk/~storner/ From 4436e171b0a46e06c16b8eb7dcc9e7ff5436dcee Mon Sep 17 00:00:00 2001 From: Nhat Pham Date: Tue, 10 Nov 2026 07:14:05 -0800 Subject: [PATCH 1369/2102] mm: vmscan: allow writeout of swapcache folios without anon mappings Patch series "mm: fix swapcache writeout and cluster table races", v2. Reviews of vswap and v1 of this series found bugs in existing swap code. Allow swapcache writeout without anon mappings, publish cluster tables with the allocator locks held, and leave tableless clusters to the allocator. This patch (of 3): Unfaulted zswap readahead folios can be dirty and in swapcache without an anonymous mapping. pageout() rejects them before swap_writeout(), so reclaim cannot write them out while their swap entries remain referenced. Allow swapcache folios through the filesystem folio check. They already have swap entries and can use the existing swap writeout path. Anonymous folios outside swapcache have no mapping and already return PAGE_KEEP. Link: https://lore.kernel.org/20261110151407.789960-1-nphamcs@gmail.com Link: https://patch.msgid.link/20261110151407.789960-2-nphamcs@gmail.com Fixes: 84798514db50 ("mm: Remove swap_writepage() and shmem_writepage()") Signed-off-by: Nhat Pham Signed-off-by: Andrew Morton Reported-by: Sashiko Closes: https://lore.kernel.org/all/sashiko-outbox-181078@kernel.org/ Reviewed-by: Baolin Wang Cc: Johannes Weiner Cc: David Hildenbrand Cc: Michal Hocko Cc: Qi Zheng Cc: Shakeel Butt Cc: Lorenzo Stoakes Cc: Kairui Song Cc: Barry Song Cc: Axel Rasmussen Cc: Yuanchu Xie Cc: Wei Xu Cc: Baoquan He Cc: Matthew Wilcox (Oracle) Cc: Christian Brauner Cc: Christopher Li Cc: Kemeng Shi Cc: Youngjun Park Cc: Cc: mm/vmscan.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) --- mm/vmscan.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mm/vmscan.c b/mm/vmscan.c index 6a1af9b92349fb..877664642fa6b8 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -714,7 +714,8 @@ static pageout_t pageout(struct swap_io_ctx *ctx, struct address_space *mapping, */ if (folio_ref_count(folio) != 1 + folio_nr_pages(folio) || !mapping) return PAGE_KEEP; - if (!shmem_mapping(mapping) && !folio_test_anon(folio)) + /* Anonymous folios outside swapcache returned PAGE_KEEP above. */ + if (!shmem_mapping(mapping) && !folio_test_swapcache(folio)) return PAGE_ACTIVATE; if (!folio_clear_dirty_for_io(folio)) return PAGE_CLEAN; From afc0507d6e15cb21244f2b570dd57ced09375350 Mon Sep 17 00:00:00 2001 From: Nhat Pham Date: Tue, 10 Nov 2026 07:14:06 -0800 Subject: [PATCH 1370/2102] mm/swap: publish cluster tables after reacquiring allocator locks Under memory pressure, swap_cluster_populate() can publish a table while its locks are dropped for a sleeping allocation. A cached allocator can consume and free that table before the populating allocator resumes, leaving the resumed scan with a NULL table. CPU0 CPU1 alloc_swap_scan_list() isolate_lock_cluster() swap_cluster_populate() drop local/global/ci locks swap_cluster_alloc_table() rcu_assign_pointer(ci->table, table) folio_alloc_swap() swap_alloc_fast() alloc_swap_scan_cluster() __swap_cluster_alloc_entries() mem_cgroup_try_charge_swap() return -ENOMEM swap_cache_del_folio() __swap_cache_del_folio() __swap_cache_do_del_folio() __swap_cluster_free_entries() free_cluster() __free_cluster() swap_cluster_free_table() reacquire local/global/ci locks return ci alloc_swap_scan_cluster() cluster_scan_range() __swap_table_get() /* NULL table */ Keep the count table, cgroup table and zero bitmap private until swap_cluster_alloc_table() restores all allocator locks. Install them under the cluster lock and retain it through the scan. Initial bad-slot setup takes only the cluster lock because the device is unpublished. The allocator releases its locks before the sleeping allocation. A reclaimer that dropped ci->lock earlier can then resume and put the cluster back on the free list. Abandon installation if the list state changes or a table appears, freeing only private allocations. Restore locks on allocation failure too, so the caller can return a still-isolated cluster to its free list. Link: https://lore.kernel.org/20261110151407.789960-3-nphamcs@gmail.com Link: https://lore.kernel.org/all/sashiko-outbox-181086@kernel.org/ Fixes: cdd77f84d966 ("mm, swap: consolidate cluster allocation helpers") Signed-off-by: Nhat Pham Signed-off-by: Andrew Morton Reported-by: Sashiko Closes: https://lore.kernel.org/all/sashiko-outbox-181084@kernel.org/ Suggested-by: Kairui Song Acked-by: Kairui Song Cc: Johannes Weiner Cc: David Hildenbrand Cc: Michal Hocko Cc: Qi Zheng Cc: Shakeel Butt Cc: Lorenzo Stoakes Cc: Barry Song Cc: Axel Rasmussen Cc: Yuanchu Xie Cc: Wei Xu Cc: Baoquan He Cc: Baolin Wang Cc: Matthew Wilcox (Oracle) Cc: Christian Brauner Cc: Christopher Li Cc: Kemeng Shi Cc: Youngjun Park Cc: mm/swapfile.c | 106 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 74 insertions(+), 32 deletions(-) --- mm/swapfile.c | 106 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 74 insertions(+), 32 deletions(-) diff --git a/mm/swapfile.c b/mm/swapfile.c index 4a0afc8f9a07b9..2810d39a6ac0f9 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -449,15 +449,23 @@ static void swap_cluster_free_table(struct swap_cluster_info *ci) swap_cluster_free_count_table(table); } -static int swap_cluster_alloc_table(struct swap_cluster_info *ci, gfp_t gfp) +/* + * Return with ci locked. An unlocked allocator also needs si's outer locks; + * initial bad-slot setup passes NULL because the device is not published. + */ +static int swap_cluster_alloc_table(struct swap_info_struct *si, + struct swap_cluster_info *ci, + gfp_t gfp, bool locked) { struct swap_table *table = NULL; +#ifdef CONFIG_MEMCG + struct swap_memcg_table *memcg_table = NULL; +#endif +#if !SWAP_TABLE_HAS_ZEROFLAG + unsigned long *zero_bitmap = NULL; +#endif struct folio *folio; - - /* The cluster must be empty and not on any list during allocation. */ - VM_WARN_ON_ONCE(ci->flags || !cluster_is_empty(ci)); - if (rcu_access_pointer(ci->table)) - return 0; + int ret = -ENOMEM; if (SWP_TABLE_USE_PAGE) { folio = folio_alloc(gfp | __GFP_ZERO, 0); @@ -467,27 +475,49 @@ static int swap_cluster_alloc_table(struct swap_cluster_info *ci, gfp_t gfp) table = kmem_cache_zalloc(swap_table_cachep, gfp); } if (!table) - return -ENOMEM; + goto lock; #ifdef CONFIG_MEMCG if (!mem_cgroup_disabled()) { - VM_WARN_ON_ONCE(ci->memcg_table); - ci->memcg_table = kzalloc_obj(*ci->memcg_table, gfp); - if (!ci->memcg_table) { - swap_cluster_free_count_table(table); - return -ENOMEM; - } + memcg_table = kzalloc_obj(*ci->memcg_table, gfp); + if (!memcg_table) + goto lock; } #endif #if !SWAP_TABLE_HAS_ZEROFLAG - VM_WARN_ON_ONCE(ci->zero_bitmap); - ci->zero_bitmap = bitmap_zalloc(SWAPFILE_CLUSTER, gfp); - if (!ci->zero_bitmap) { - swap_cluster_free_table(ci); - swap_cluster_free_count_table(table); - return -ENOMEM; + zero_bitmap = bitmap_zalloc(SWAPFILE_CLUSTER, gfp); + if (!zero_bitmap) + goto lock; +#endif + ret = 0; + +lock: + if (!locked) { + if (si) { + local_lock(&percpu_swap_cluster.lock); + if (!(si->flags & SWP_SOLIDSTATE)) + spin_lock(&si->global_cluster_lock); + } + spin_lock(&ci->lock); } + lockdep_assert_held(&ci->lock); + + /* A stale reclaimer may have returned the cluster to the free list. */ + if (ci->flags != CLUSTER_FLAG_NONE || cluster_table_is_alloced(ci)) + ret = -EAGAIN; + if (ret) + goto free; + + /* The cluster must be empty and not on any list during allocation. */ + VM_WARN_ON_ONCE(!cluster_is_empty(ci)); +#ifdef CONFIG_MEMCG + VM_WARN_ON_ONCE(ci->memcg_table); + ci->memcg_table = memcg_table; +#endif +#if !SWAP_TABLE_HAS_ZEROFLAG + VM_WARN_ON_ONCE(ci->zero_bitmap); + ci->zero_bitmap = zero_bitmap; #endif /* @@ -496,6 +526,17 @@ static int swap_cluster_alloc_table(struct swap_cluster_info *ci, gfp_t gfp) */ rcu_assign_pointer(ci->table, table); return 0; + +free: +#ifdef CONFIG_MEMCG + kfree(memcg_table); +#endif +#if !SWAP_TABLE_HAS_ZEROFLAG + bitmap_free(zero_bitmap); +#endif + if (table) + swap_cluster_free_count_table(table); + return ret; } /* @@ -546,8 +587,8 @@ swap_cluster_populate(struct swap_info_struct *si, lockdep_assert_held(&si->global_cluster_lock); lockdep_assert_held(&ci->lock); - if (!swap_cluster_alloc_table(ci, __GFP_HIGH | __GFP_NOMEMALLOC | - __GFP_NOWARN)) + if (!swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC | + __GFP_NOWARN, true)) return ci; /* @@ -560,8 +601,8 @@ swap_cluster_populate(struct swap_info_struct *si, spin_unlock(&si->global_cluster_lock); local_unlock(&percpu_swap_cluster.lock); - ret = swap_cluster_alloc_table(ci, __GFP_HIGH | __GFP_NOMEMALLOC | - GFP_KERNEL); + ret = swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC | + GFP_KERNEL, false); /* * Back to atomic context. We might have migrated to a new CPU with a @@ -571,13 +612,9 @@ swap_cluster_populate(struct swap_info_struct *si, * could happen with ignoring the percpu cluster is fragmentation, * which is acceptable since this fallback and race is rare. */ - local_lock(&percpu_swap_cluster.lock); - if (!(si->flags & SWP_SOLIDSTATE)) - spin_lock(&si->global_cluster_lock); - spin_lock(&ci->lock); - if (ret) { - move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE); + if (ret != -EAGAIN) + move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE); spin_unlock(&ci->lock); return NULL; } @@ -825,9 +862,13 @@ static int swap_cluster_setup_bad_slot(struct swap_info_struct *si, ci = cluster_info + idx; /* Need to allocate swap table first for initial bad slot marking. */ - if (!ci->count && swap_cluster_alloc_table(ci, GFP_KERNEL)) - return -ENOMEM; - spin_lock(&ci->lock); + if (!ci->count) { + ret = swap_cluster_alloc_table(NULL, ci, GFP_KERNEL, false); + if (ret) + goto out; + } else { + spin_lock(&ci->lock); + } /* Check for duplicated bad swap slots. */ if (__swap_table_xchg(ci, ci_off, SWP_TB_BAD) != SWP_TB_NULL) { pr_warn("Duplicated bad slot offset %d\n", offset); @@ -835,6 +876,7 @@ static int swap_cluster_setup_bad_slot(struct swap_info_struct *si, } else { ci->count++; } +out: spin_unlock(&ci->lock); WARN_ON(ci->count > SWAPFILE_CLUSTER); From f6f10d976c8ad7c96c33eb90ef071e15f79010b6 Mon Sep 17 00:00:00 2001 From: Nhat Pham Date: Tue, 10 Nov 2026 07:14:07 -0800 Subject: [PATCH 1371/2102] mm/swap: skip relocation of tableless clusters A stale reclaimer can reach relocate_cluster() after another allocator re-isolates an emptied cluster and drops its locks to populate the table. The cluster has zero count, CLUSTER_FLAG_NONE and no table, so relocation can free it again and dereference NULL in the DEBUG_VM empty check. CPU0 CPU1 Reclaimer Allocator alloc_swap_scan_cluster() cluster_reclaim_range() spin_unlock(&ci->lock) __try_to_reclaim_swap() swap_cache_del_folio() __swap_cache_del_folio() __swap_cache_do_del_folio() __swap_cluster_free_entries() free_cluster() __free_cluster() swap_cluster_free_table() swap_cluster_unlock(ci) isolate_lock_cluster() swap_cluster_populate() drop ci and outer locks swap_cluster_alloc_table() spin_lock(&ci->lock) relocate_cluster() free_cluster() __free_cluster() swap_cluster_assert_empty() __swap_table_get() /* NULL table */ Leave tableless clusters to the allocator under ci->lock. This also stops a stale reclaimer from returning a cluster to the free list while table population is pending, avoiding the resulting FREE-to-NONE state cycle. The existing cluster lock serializes the table check and relocation with population. Link: https://patch.msgid.link/20261110151407.789960-4-nphamcs@gmail.com Fixes: 07adc4cf1ecd ("mm, swap: implement dynamic allocation of swap table") Signed-off-by: Nhat Pham Signed-off-by: Andrew Morton Reported-by: Sashiko Closes: https://lore.kernel.org/all/sashiko-outbox-203018@kernel.org/ Acked-by: Kairui Song Cc: Johannes Weiner Cc: David Hildenbrand Cc: Michal Hocko Cc: Qi Zheng Cc: Shakeel Butt Cc: Lorenzo Stoakes Cc: Barry Song Cc: Axel Rasmussen Cc: Yuanchu Xie Cc: Wei Xu Cc: Baoquan He Cc: Baolin Wang Cc: Matthew Wilcox (Oracle) Cc: Christian Brauner Cc: Christopher Li Cc: Kemeng Shi Cc: Youngjun Park Cc: Cc: mm/swapfile.c | 7 +++++++ 1 file changed, 7 insertions(+) --- mm/swapfile.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/mm/swapfile.c b/mm/swapfile.c index 2810d39a6ac0f9..4451f178ce396b 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -815,6 +815,13 @@ static void relocate_cluster(struct swap_info_struct *si, if (cluster_is_discard(ci)) return; + /* + * An allocator may still be preparing the table. + * Leave the cluster to it. + */ + if (!cluster_table_is_alloced(ci)) + return; + if (!ci->count) { if (ci->flags != CLUSTER_FLAG_FREE) free_cluster(si, ci); From 9436a736a148e3499cc1932b866d840803fbf764 Mon Sep 17 00:00:00 2001 From: Shakeel Butt Date: Tue, 10 Nov 2026 16:09:13 -0800 Subject: [PATCH 1372/2102] mm: mglru: splice all generations when reparenting a memcg Noah reported list_del corruption on single-node hosts running 7.2.11, which already has commit bf4ade7dbd76 ("memcg: keep folio's objcg same as its node"). The bad pointer is an MGLRU list head in a freed mem_cgroup_per_node: slab mem_cgroup_per_node start ff31bfa36a3c9e00 pointer offset 528 size 1920 list_del corruption. next->prev should be ffacf881ccc70e08, but was ff31bfa36a3ca010. (next=ff31bfa36a3ca010) When a memcg goes offline, __lru_gen_reparent_memcg() moves its MGLRU lists to the parent. It moves only the generations (gens) from min_seq to max_seq, and it puts each list at the same index in the parent. A folio's gen in folio->flags can be ahead of the list it is on. In the parent, the same index can stand for an older gen, so the folio's gen can end up older than its list. Once the parent's min_seq passes that gen, sort_folio() puts the folio on the list for max_seq + 1, where it stays until the next aging. If the parent goes offline before that aging, the folio is not moved to the grandparent. It stays on the parent's list after the parent is freed, and the next list_del() on it touches freed memory. This needs two cgroups on one branch to go offline one after the other, such as a container and then its pod. The parent always has MAX_NR_GENS gens at this point, so every index is valid in it. Move all MAX_NR_GENS lists, not only the gens from min_seq to max_seq. A reproducer that drives these steps through the lru_gen debugfs file gets a KASAN use-after-free on the freed mem_cgroup_per_node without this patch, and no report with it. Link: https://patch.msgid.link/20261111000913.22943-1-shakeel.butt@linux.dev Fixes: f304652609ea ("mm: vmscan: prepare for reparenting MGLRU folios") Signed-off-by: Shakeel Butt Signed-off-by: Andrew Morton Reported-by: Noah Feldt Closes: https://lore.kernel.org/all/20261110132853.71228-1-noah@feldt.systems/ Reviewed-by: Kairui Song Reviewed-by: Baolin Wang Tested-by: Noah Feldt Link: https://lore.kernel.org/20261115124954.7146-1-noah@feldt.systems Reviewed-by: Barry Song Cc: Johannes Weiner Cc: David Hildenbrand Cc: Qi Zheng Cc: Kairui Song Cc: mm/vmscan.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) --- mm/vmscan.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/mm/vmscan.c b/mm/vmscan.c index 877664642fa6b8..29fbb7a22cc697 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -4752,19 +4752,25 @@ void max_lru_gen_memcg(struct mem_cgroup *memcg, int nid) * The same generation has different meanings in the parent and child memcg, * so this compromise method will cause the LRU inversion problem. But as the * system runs, this problem will be fixed automatically. + * + * Move all MAX_NR_GENS lists, not only the gens from min_seq to max_seq. + * An earlier reparenting can leave a folio whose gen is older than the list + * it is on. Once min_seq passes that gen, sort_folio() puts the folio on the + * list for max_seq + 1, where it stays until the next aging. If that list + * were skipped, the folio would stay behind on a memcg that is about to be + * freed. The parent has MAX_NR_GENS gens here, so every index is valid in it. */ static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruvec *parent_lruvec, int zone, int type) { struct lru_gen_folio *child_lrugen, *parent_lrugen; enum lru_list lru = type * LRU_INACTIVE_FILE; - int i; + int gen; child_lrugen = &child_lruvec->lrugen; parent_lrugen = &parent_lruvec->lrugen; - for (i = 0; i < get_nr_gens(child_lruvec, type); i++) { - int gen = lru_gen_from_seq(child_lrugen->max_seq - i); + for (gen = 0; gen < MAX_NR_GENS; gen++) { long nr_pages = child_lrugen->nr_pages[gen][type][zone]; int child_lru_active = lru_gen_is_active(child_lruvec, gen) ? LRU_ACTIVE : 0; int parent_lru_active = lru_gen_is_active(parent_lruvec, gen) ? LRU_ACTIVE : 0; From 391f7207cb876b1f68368f2f7aed5abfb242a5ea Mon Sep 17 00:00:00 2001 From: Shakeel Butt Date: Wed, 11 Nov 2026 17:32:20 -0800 Subject: [PATCH 1373/2102] memcg: flush nr_charged_bytes when the obj stock trylock fails When interrupt code, such as an RCU callback in softirq, runs on top of a task that holds the obj stock lock, its trylock fails and the bytes go to objcg->nr_charged_bytes. Nothing empties that counter while every CPU using the objcg keeps it in its stock, so it can grow without limit. Users see memory.current and the "kernel" field of memory.stat keep growing while the cgroup's real usage does not. With memory.high or memory.max set, the cgroup is reclaimed, throttled or even OOM-killed for memory it does not use. The counter is 32-bit, so after 4 GiB it wraps, and those 4 GiB stay charged to the cgroup and its ancestors until reboot, even after the cgroup is removed. Fix it by uncharging the whole pages in nr_charged_bytes whenever the trylock fails. Link: https://patch.msgid.link/20261112013220.4064478-1-shakeel.butt@linux.dev Fixes: 200577f69f29 ("memcg: objcg stock trylock without irq disabling") Signed-off-by: Shakeel Butt Signed-off-by: Andrew Morton Reported-by: Chris Mason Acked-by: Muchun Song (ByteDance) Reviewed-by: Johannes Weiner Reviewed-by: Harry Yoo (Meta) Acked-by: Vlastimil Babka (SUSE) Cc: David Hildenbrand Cc: Michal Hocko Cc: Roman Gushchin Cc: mm/memcontrol.c | 2 ++ 1 file changed, 2 insertions(+) --- mm/memcontrol.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mm/memcontrol.c b/mm/memcontrol.c index cb7cfae9ce5a6c..afbb638e7e1cbb 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -3532,6 +3532,8 @@ static void __refill_obj_stock(struct obj_cgroup *objcg, int i, slot = -1, empty_slot = -1; if (!stock) { + nr_bytes += atomic_read(&objcg->nr_charged_bytes) + ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0; nr_pages = nr_bytes >> PAGE_SHIFT; nr_bytes = nr_bytes & (PAGE_SIZE - 1); atomic_add(nr_bytes, &objcg->nr_charged_bytes); From f6ed0f2a03045e4a059a9e6c14befa40c88e68fb Mon Sep 17 00:00:00 2001 From: Shakeel Butt Date: Wed, 11 Nov 2026 22:12:31 -0800 Subject: [PATCH 1374/2102] mm: list_lru: fix NULL deref when a folio moves to the root memcg folio_memcg_list_lru_alloc() makes sure that a folio's memcg has its own lists in a list_lru, such as the THP deferred split queue. It looks up the folio's memcg twice: a fast path under RCU checks if the lists exist, and a slow path takes a reference and allocates them. The fast path returns early for the root memcg, which uses the global lists. The slow path does not check for the root. The memcg can change between the two lookups: when a cgroup is removed, its folios are moved to the parent memcg. If the folio is moved up to the root in between, the slow path gets the root, and __memcg_list_lru_alloc() dereferences the root's parent, which is NULL. Users see a NULL pointer dereference oops while a THP is allocated, such as in a page fault, in khugepaged or at swap-in. tmpfs huge pages are affected too, and for them the oops can also happen in reclaim, for example in kswapd. The task that hits the oops is killed, or the machine panics if panic_on_oops is set. The race is narrow: the folio has to be moved up to the root right between the two lookups. For example, its cgroup is directly below the root and is removed, or has its memory controller disabled, at that moment. Fix it by checking memcg_list_lru_allocated() again in the slow path, like the fast path does. It returns true for the root, which needs no lists of its own. Link: https://patch.msgid.link/20261112061231.2469026-1-shakeel.butt@linux.dev Fixes: ae64f07a6a40 ("mm: list_lru: introduce folio_memcg_list_lru_alloc()") Signed-off-by: Shakeel Butt Signed-off-by: Andrew Morton Reported-by: Chris Mason Acked-by: Muchun Song (ByteDance) Reviewed-by: Johannes Weiner Reviewed-by: Harry Yoo (Meta) Cc: Dave Chinner Cc: David Hildenbrand Cc: Michal Hocko Cc: Roman Gushchin Cc: Qi Zheng Cc: mm/list_lru.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) --- mm/list_lru.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/mm/list_lru.c b/mm/list_lru.c index d1d256822ccc73..ca8de3793166b0 100644 --- a/mm/list_lru.c +++ b/mm/list_lru.c @@ -645,9 +645,16 @@ int folio_memcg_list_lru_alloc(struct folio *folio, struct list_lru *lru, if (likely(res)) return 0; - /* Allocation may block, pin the memcg */ + /* + * Allocation may block, so pin the memcg. If the folio's cgroup + * was removed after the check above, the folio has moved up to a + * parent memcg. That memcg may already have its lists, or may be + * the root, which uses the global lists and has no parent. So + * check again before allocating. + */ memcg = get_mem_cgroup_from_folio(folio); - res = __memcg_list_lru_alloc(memcg, lru, gfp); + if (!memcg_list_lru_allocated(memcg, lru)) + res = __memcg_list_lru_alloc(memcg, lru, gfp); mem_cgroup_put(memcg); return res; } From 642abe8448674a953675486596f68060bd6c7fb6 Mon Sep 17 00:00:00 2001 From: Shakeel Butt Date: Thu, 12 Nov 2026 14:12:48 -0800 Subject: [PATCH 1375/2102] mm: list_lru: don't use a new memcg's lists for an offline memcg A memcg's list_lru lists are found by its kmemcg_id, which is its private ID. Offlining a memcg moves its lists to the parent and frees the ID right away, with no RCU grace period. The next new memcg can get the same ID and allocate its own lists at that index. A caller that holds only the RCU read lock, such as __folio_unqueue_deferred_split(), can still hold the offline memcg. If it is preempted until the ID is reused, it then locks the new memcg's list and unlinks a folio that now sits on the parent's list, without holding the parent's lock. A concurrent change to the parent's list can then leave a pointer to a freed folio on it. Users see list corruption reports, crashes or silent memory corruption when memory cgroups are removed and created while THPs are freed, on kernels with preemptible RCU, which is the default on x86 and arm64. They can also see a warning from memcg_reparent_list_lru_one() when the new memcg is removed, because the wrong unlink made its count negative. Fix it by recording the owning memcg in each list_lru_memcg, and by treating the index as empty when its lists belong to another memcg. The lookup then moves up to the parent, whose list holds the folio. [akpm@linux-foundation.org: verify memcg owner before skipping allocation] Link: https://lore.kernel.org/20261112161502.18d9d72c0139b8f69bb88ff4@linux-foundation.org Link: https://patch.msgid.link/20261112221248.3512447-1-shakeel.butt@linux.dev Fixes: 28e98022b31e ("mm/list_lru: simplify reparenting and initial allocation") Signed-off-by: Shakeel Butt Signed-off-by: Andrew Morton Reported-by: Chris Mason Cc: Dave Chinner Cc: Johannes Weiner Cc: David Hildenbrand Cc: Michal Hocko Cc: Roman Gushchin Cc: Muchun Song Cc: Qi Zheng include/linux/list_lru.h | 2 ++ mm/list_lru.c | 30 ++++++++++++++++++++++-------- 2 files changed, 24 insertions(+), 8 deletions(-) --- include/linux/list_lru.h | 2 ++ mm/list_lru.c | 30 ++++++++++++++++++++++-------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/include/linux/list_lru.h b/include/linux/list_lru.h index a450fffe1550be..6ef5bc5396065a 100644 --- a/include/linux/list_lru.h +++ b/include/linux/list_lru.h @@ -38,6 +38,8 @@ struct list_lru_one { struct list_lru_memcg { struct rcu_head rcu; + /* owning memcg, only compared and never dereferenced */ + const void *memcg; /* array of per cgroup per node lists, indexed by node id */ struct list_lru_one node[]; }; diff --git a/mm/list_lru.c b/mm/list_lru.c index ca8de3793166b0..651983d0bf8bff 100644 --- a/mm/list_lru.c +++ b/mm/list_lru.c @@ -72,12 +72,15 @@ static int lru_shrinker_id(struct list_lru *lru) } static inline struct list_lru_one * -list_lru_from_memcg_idx(struct list_lru *lru, int nid, int idx) +list_lru_from_memcg(struct list_lru *lru, int nid, struct mem_cgroup *memcg) { + int idx = memcg_kmem_id(memcg); + if (list_lru_memcg_aware(lru) && idx >= 0) { struct list_lru_memcg *mlru = xa_load(&lru->xa, idx); - return mlru ? &mlru->node[nid] : NULL; + /* Lists at a reused index belong to another memcg. */ + return mlru && mlru->memcg == memcg ? &mlru->node[nid] : NULL; } return &lru->node[nid].lru; } @@ -91,7 +94,7 @@ lock_list_lru_of_memcg(struct list_lru *lru, int nid, rcu_read_lock(); again: - l = list_lru_from_memcg_idx(lru, nid, memcg_kmem_id(*memcg)); + l = list_lru_from_memcg(lru, nid, *memcg); if (likely(l)) { lock_list_lru(l, irq, irq_flags); if (likely(READ_ONCE(l->nr_items) != LONG_MIN)) { @@ -132,7 +135,7 @@ static inline bool list_lru_memcg_aware(struct list_lru *lru) } static inline struct list_lru_one * -list_lru_from_memcg_idx(struct list_lru *lru, int nid, int idx) +list_lru_from_memcg(struct list_lru *lru, int nid, struct mem_cgroup *memcg) { return &lru->node[nid].lru; } @@ -313,7 +316,7 @@ unsigned long list_lru_count_one(struct list_lru *lru, long count; rcu_read_lock(); - l = list_lru_from_memcg_idx(lru, nid, memcg_kmem_id(memcg)); + l = list_lru_from_memcg(lru, nid, memcg); count = l ? READ_ONCE(l->nr_items) : 0; rcu_read_unlock(); @@ -502,11 +505,10 @@ static void memcg_reparent_list_lru_one(struct list_lru *lru, int nid, struct list_lru_one *src, struct mem_cgroup *dst_memcg) { - int dst_idx = dst_memcg->kmemcg_id; struct list_lru_one *dst; spin_lock_irq(&src->lock); - dst = list_lru_from_memcg_idx(lru, nid, dst_idx); + dst = list_lru_from_memcg(lru, nid, dst_memcg); spin_lock_nested(&dst->lock, SINGLE_DEPTH_NESTING); list_splice_init(&src->list, &dst->list); @@ -566,9 +568,19 @@ void memcg_reparent_list_lrus(struct mem_cgroup *memcg, struct mem_cgroup *paren static inline bool memcg_list_lru_allocated(struct mem_cgroup *memcg, struct list_lru *lru) { + struct list_lru_memcg *mlru; + bool allocated; int idx = memcg->kmemcg_id; - return idx < 0 || xa_load(&lru->xa, idx); + if (idx < 0) + return true; + + rcu_read_lock(); + mlru = xa_load(&lru->xa, idx); + allocated = mlru && mlru->memcg == memcg; + rcu_read_unlock(); + + return allocated; } static int __memcg_list_lru_alloc(struct mem_cgroup *memcg, @@ -602,6 +614,8 @@ static int __memcg_list_lru_alloc(struct mem_cgroup *memcg, if (!mlru) return -ENOMEM; } + /* Set before the lists are published, and never changed after. */ + mlru->memcg = pos; xas_set(&xas, pos->kmemcg_id); do { xas_lock_irqsave(&xas, flags); From fe7e4ee305cf62f86e2545b7f657949399af8aeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20Ezequiel=20Rodriguez?= Date: Fri, 13 Nov 2026 16:38:12 -0300 Subject: [PATCH 1376/2102] mm: use PFN_PHYS() in phys_mem_access_prot() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit phys_mem_access_prot() stores "pfn << PAGE_SHIFT" in a phys_addr_t. The shift is evaluated as unsigned long, so on a 32-bit kernel with CONFIG_PHYS_ADDR_T_64BIT an address above 4 GiB is truncated before uncached_access() compares it with __pa(high_memory). mmap_mem_prepare() already shifts in phys_addr_t, so the mapping is accepted and then left cacheable. PFN_PHYS() casts before the shift. On a MIPS32 XPA Malta guest, mmap of /dev/mem at 0xf00000000 without O_DSYNC used the boot CCA. The same mapping with O_DSYNC was uncached. With PFN_PHYS() both are uncached. Link: https://patch.msgid.link/20261113193812.1239880-1-ivanrwcm25@gmail.com Fixes: 7e6735c3578e ("/dev/mem: use phys_addr_t for physical addresses") Signed-off-by: Iván Ezequiel Rodriguez Signed-off-by: Andrew Morton Reviewed-by: David Hildenbrand (Arm) Reviewed-by: Lorenzo Stoakes (ARM) Reviewed-by: Mike Rapoport (Microsoft) Cc: Liam R. Howlett Cc: Vlastimil Babka Cc: Suren Baghdasaryan Cc: Michal Hocko Cc: Jann Horn Cc: Pedro Falcato Cc: mm/char-mem.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) --- mm/char-mem.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mm/char-mem.c b/mm/char-mem.c index c5761ddedbd7df..53ce0034a4c13c 100644 --- a/mm/char-mem.c +++ b/mm/char-mem.c @@ -272,7 +272,7 @@ static pgprot_t phys_mem_access_prot(struct file *file, unsigned long pfn, unsigned long size, pgprot_t vma_prot) { #ifdef pgprot_noncached - phys_addr_t offset = pfn << PAGE_SHIFT; + phys_addr_t offset = PFN_PHYS(pfn); if (uncached_access(file, offset)) return pgprot_noncached(vma_prot); From 75ce6ae1ce0f77fb9e4de1938249c997a32dc57e Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Mon, 9 Nov 2026 19:31:53 +0100 Subject: [PATCH 1377/2102] MAINTAINERS: MEMORY MANAGEMENT - MGLRU (MULTI-GEN LRU) update Patch series "MAINTAINERS: MM updates (2)". Some more MAINTAINERS updates with a focus on MGLRU and reclaim this time. This patch (of 2): MGLRU is currently the only MM component without a dedicated component maintainer. Fortunately, Kairui and Barry have been actively contributing to MGLRU and have volunteered to take on more responsibility by officially taking care of it. Given that Kairui is already an established MM component maintainer in a related MM component (SWAP), add him as an MGLRU maintainer right away. For Barry, the idea is to transition him towards a component maintainer role over the coming months, starting by moving him to the top of the reviewer list. Link: https://lore.kernel.org/20261109-maintainers_mglru-v1-0-c25e6de60bcc@kernel.org Link: https://patch.msgid.link/20261109-maintainers_mglru-v1-1-c25e6de60bcc@kernel.org Signed-off-by: David Hildenbrand (Arm) Signed-off-by: Andrew Morton Reviewed-by: Lian Wang Reviewed-by: Ridong Chen Reviewed-by: Lance Yang Acked-by: Muchun Song Acked-by: Kairui Song Acked-by: Baolin Wang Acked-by: Lorenzo Stoakes (ARM) Acked-by: Qi Zheng Acked-by: SJ Park Acked-by: Barry Song Reviewed-by: Baoquan He Cc: Shakeel Butt Cc: Axel Rasmussen Cc: Yuanchu Xie Cc: Wei Xu Cc: Johannes Weiner Cc: Michal Hocko Cc: Kairui Song MAINTAINERS | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) --- MAINTAINERS | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index 792135be7a74bc..aae2543fa52aef 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -17633,10 +17633,10 @@ K: (?i:vmemmap) MEMORY MANAGEMENT - MGLRU (MULTI-GEN LRU) M: Andrew Morton -R: Kairui Song +M: Kairui Song +R: Barry Song R: Qi Zheng R: Shakeel Butt -R: Barry Song R: Axel Rasmussen R: Yuanchu Xie R: Wei Xu From ccc54eb67faaddd546304c90d106a39a6ca731e6 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Mon, 9 Nov 2026 19:31:54 +0100 Subject: [PATCH 1378/2102] MAINTAINERS: remove myself from MEMORY MANAGEMENT - RECLAIM I don't really get to look at most reclaim related stuff. For things that are actually relevant for me, I'm sure people will CC me. So remove myself from the MEMORY MANAGEMENT - RECLAIM section for now to have a bit less noise in my inbox. Link: https://patch.msgid.link/20261109-maintainers_mglru-v1-2-c25e6de60bcc@kernel.org Signed-off-by: David Hildenbrand (Arm) Signed-off-by: Andrew Morton Acked-by: SJ Park Acked-by: Lorenzo Stoakes (ARM) Acked-by: Muchun Song Acked-by: Baolin Wang Cc: Kairui Song Cc: Barry Song Cc: Qi Zheng Cc: Shakeel Butt Cc: Axel Rasmussen Cc: Yuanchu Xie Cc: Wei Xu Cc: Baoquan He Cc: Johannes Weiner Cc: Michal Hocko Cc: Lance Yang Cc: Ridong Chen Cc: Lian Wang MAINTAINERS | 1 - 1 file changed, 1 deletion(-) --- MAINTAINERS | 1 - 1 file changed, 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index aae2543fa52aef..a1695e9314adce 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -17805,7 +17805,6 @@ F: tools/mm/page_owner_sort.c MEMORY MANAGEMENT - RECLAIM M: Andrew Morton M: Johannes Weiner -R: David Hildenbrand R: Michal Hocko R: Qi Zheng R: Shakeel Butt From 6e6d8a0ab2f3d2a9a69f944ddcc73829f3506f8a Mon Sep 17 00:00:00 2001 From: Andrew Morton Date: Tue, 17 Nov 2026 11:05:44 -0800 Subject: [PATCH 1379/2102] MAINTAINERS: add page_ext.h to MEMORY MANAGEMENT - PAGE ALLOCATOR Signed-off-by: Andrew Morton Acked-by: Vlastimil Babka (SUSE) MAINTAINERS | 1 + 1 file changed, 1 insertion(+) --- MAINTAINERS | 1 + 1 file changed, 1 insertion(+) diff --git a/MAINTAINERS b/MAINTAINERS index a1695e9314adce..9d270eea168b6e 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -17779,6 +17779,7 @@ F: include/linux/compaction.h F: include/linux/gfp.h F: include/linux/page-isolation.h F: include/linux/pageblock-flags.h +F: include/linux/page_ext.h F: include/trace/events/compaction.h F: include/trace/events/page_isolation.h F: include/trace/events/page_ref.h From 50abb4245e1ecdd679aef504543bdbc055dc9247 Mon Sep 17 00:00:00 2001 From: Donggeun Yoo Date: Sat, 3 Oct 2026 19:30:29 +0900 Subject: [PATCH 1380/2102] userfaultfd: clear the inherited uffd bit in move_swap_pte() UFFDIO_MOVE on a swapped-out page installs the source PTE at the destination unchanged, so a uffd bit set on a write-protected or RWP-protected source lands in a destination VMA that was never registered for either. Nothing clears it there, and userspace sees: - /proc//pagemap reports the page as uffd-tracked (bit 57), both while it is swapped out and after it is faulted back in. - MADV_COLLAPSE fails with EINVAL on a range containing it, because the collapse scan bails on a swap entry with the uffd bit set. - With CONFIG_PAGE_TABLE_CHECK, faulting the page in warns. do_swap_page() carries the bit into the present PTE and, since the destination isn't WP-registered, also makes it writable: WARNING: mm/page_table_check.c:202 at __page_table_check_ptes_set+0x185/0x1e0 Call Trace: set_ptes+0x67/0xc0 do_swap_page+0x990/0xfe0 __handle_mm_fault+0x7d0/0xeb0 handle_mm_fault+0x9c/0x250 do_user_addr_fault+0x207/0x650 exc_page_fault+0x65/0x150 asm_exc_page_fault+0x26/0x30 Reaching it takes UFFDIO_MOVE out of a WP- or RWP-protected area into one that isn't, on a page that is swapped out at the time. It hasn't been seen in practice. A resident page doesn't carry the bit, because move_present_ptes() builds the destination PTE from dst_vma->vm_page_prot. Clear it on the moved swap entry as well, then re-arm it if the destination is RWP-registered. The WP case has been there since v6.8, where UFFDIO_MOVE was added. Link: https://lore.kernel.org/20261003103030.63380-1-donggeunyoo.kernel@gmail.com Link: https://lore.kernel.org/20261003103030.63380-2-donggeunyoo.kernel@gmail.com Fixes: adef440691ba ("userfaultfd: UFFDIO_MOVE uABI") Signed-off-by: Donggeun Yoo Signed-off-by: Andrew Morton Acked-by: David Hildenbrand (Arm) Acked-by: Mike Rapoport (Microsoft) Assisted-by: LLM Cc: Peter Xu Cc: Suren Baghdasaryan Cc: Andrea Arcangeli Cc: Lorenzo Stoakes Cc: Liam R. Howlett Cc: Vlastimil Babka Cc: Michal Hocko Cc: Shuah Khan Cc: Kiryl Shutsemau Cc: mm/userfaultfd.c | 1 + 1 file changed, 1 insertion(+) --- mm/userfaultfd.c | 1 + 1 file changed, 1 insertion(+) diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index 15ad69ec2fc016..65f7399e79b654 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -1403,6 +1403,7 @@ static int move_swap_pte(struct mm_struct *mm, struct vm_area_struct *dst_vma, orig_src_pte = ptep_get_and_clear(mm, src_addr, src_pte); if (pgtable_supports_soft_dirty()) orig_src_pte = pte_swp_mksoft_dirty(orig_src_pte); + orig_src_pte = pte_swp_clear_uffd(orig_src_pte); /* Re-arm RWP on the moved swap entry if dst_vma is RWP-registered. */ if (userfaultfd_rwp(dst_vma)) orig_src_pte = pte_swp_mkuffd(orig_src_pte); From 034008e9ce52245e0502484b9d5a9e14e80a704a Mon Sep 17 00:00:00 2001 From: "Lorenzo Stoakes (ARM)" Date: Wed, 18 Nov 2026 18:22:10 +0000 Subject: [PATCH 1381/2102] MAINTAINERS: consolidate the memory mapping entries into a VMA entry Memory mapping entries were kept in three different sections in order that those maintaining/reviewing each distinct part would be made responsible for/cc'd on only those parts. However this creates confusion as to what files belong to which component, so simplify things by consolidating them into one. Expand Suren's maintainership to the entire component, as he is a trusted and valued member of the VMA kernel team and very much deserving of the position. Additionally, drop Suren's core and misc reviewerships in order to focus upon VMA. As David is receiving pull requests directly, make him a reviewer, purely as an administrative change. Also specify the new tree location in preparation for the tree being established for next cycle, and remove the link to the not so regularly updated linux-mm website. Given that, from next cycle, the tree will sit outside of Andrew's current process, remove his entry, also purely as an administrative change. With that said, I'd like to take the opportunity to express gratitude for Andrew's huge contribution to mm, and for his being both generous and gracious throughout this period of change in the subsystem. Link: https://patch.msgid.link/20261118-maintainers-consolidate-vma-entry-v1-1-8019b0e9928f@kernel.org Signed-off-by: Suren Baghdasaryan Signed-off-by: Lorenzo Stoakes (ARM) Signed-off-by: Andrew Morton Co-developed-by: Suren Baghdasaryan Acked-by: Liam R. Howlett (Google) Acked-by: Shakeel Butt Acked-by: David Hildenbrand (Arm) Acked-by: Vlastimil Babka (SUSE) Acked-by: SJ Park Acked-by: Mike Rapoport (Microsoft) Cc: Pedro Falcato Cc: Jann Horn Cc: Michal Hocko MAINTAINERS | 51 ++++++++++++-------------------------------------- 1 file changed, 13 insertions(+), 38 deletions(-) --- MAINTAINERS | 51 +++++++++++++-------------------------------------- 1 file changed, 13 insertions(+), 38 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index 9d270eea168b6e..c6b05f8d363a61 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -17507,7 +17507,6 @@ M: David Hildenbrand R: Liam R. Howlett R: Vlastimil Babka R: Mike Rapoport -R: Suren Baghdasaryan R: Michal Hocko L: linux-mm@kvack.org S: Maintained @@ -17677,7 +17676,6 @@ M: David Hildenbrand R: Liam R. Howlett R: Vlastimil Babka R: Mike Rapoport -R: Suren Baghdasaryan R: Michal Hocko L: linux-mm@kvack.org S: Maintained @@ -17969,30 +17967,37 @@ F: rust/kernel/mm.rs F: rust/kernel/mm/ F: rust/kernel/page.rs -MEMORY MAPPING -M: Andrew Morton -M: Liam R. Howlett +MEMORY MANAGEMENT - VMA M: Lorenzo Stoakes +M: Liam R. Howlett +M: Suren Baghdasaryan R: Vlastimil Babka -R: Jann Horn +R: Shakeel Butt R: Pedro Falcato +R: David Hildenbrand +R: Jann Horn L: linux-mm@kvack.org S: Maintained -W: http://www.linux-mm.org -T: git git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm +T: git git://git.kernel.org/pub/scm/linux/kernel/git/mm/vma.git for-next F: Documentation/core-api/protection-keys.rst F: Documentation/filesystems/mmap_prepare.rst +F: Documentation/mm/process_addrs.rst F: Documentation/userspace-api/mseal.rst F: fs/proc/task_mmu.c F: fs/proc/task_nommu.c F: include/linux/mman.h +F: include/linux/mmap_lock.h F: include/linux/pkeys.h F: include/trace/events/mmap.h +F: include/trace/events/mmap_lock.h +F: include/uapi/asm-generic/mman-common.h F: include/uapi/linux/mman.h F: mm/char-mem.c +F: mm/madvise.c F: mm/mincore.c F: mm/mlock.c F: mm/mmap.c +F: mm/mmap_lock.c F: mm/mprotect.c F: mm/mremap.c F: mm/mseal.c @@ -18006,36 +18011,6 @@ F: mm/vma_internal.h F: tools/testing/selftests/mm/merge.c F: tools/testing/vma/ -MEMORY MAPPING - LOCKING -M: Andrew Morton -M: Suren Baghdasaryan -M: Liam R. Howlett -M: Lorenzo Stoakes -R: Vlastimil Babka -R: Shakeel Butt -L: linux-mm@kvack.org -S: Maintained -W: http://www.linux-mm.org -T: git git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm -F: Documentation/mm/process_addrs.rst -F: include/linux/mmap_lock.h -F: include/trace/events/mmap_lock.h -F: mm/mmap_lock.c - -MEMORY MAPPING - MADVISE (MEMORY ADVICE) -M: Andrew Morton -M: Liam R. Howlett -M: Lorenzo Stoakes -M: David Hildenbrand -R: Vlastimil Babka -R: Jann Horn -L: linux-mm@kvack.org -S: Maintained -W: http://www.linux-mm.org -T: git git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm -F: include/uapi/asm-generic/mman-common.h -F: mm/madvise.c - MEMORY TECHNOLOGY DEVICES (MTD) M: Miquel Raynal M: Richard Weinberger From 190936e7a5da594ffcc3bee75eabb586a3866443 Mon Sep 17 00:00:00 2001 From: Oleksandr Natalenko Date: Wed, 18 Nov 2026 12:26:10 +0100 Subject: [PATCH 1382/2102] mm/swapfile: really fix integer overflow in swap_show() and swapon() One of the enterprise customers uses 6 TiB of swap, and the values reported in /proc/swaps as well as in dmesg are still not correct. Cast si->pages to long explicitly so that the bitshift in K() doesn't truncate the value to 32 bits. Also do the same in swapon() for the same reason. Link: https://patch.msgid.link/20261118112610.122799-1-oleksandr@natalenko.name Fixes: 642929a2ded0 ("mm/swapfile: fix an integer overflow in swap_show()") Signed-off-by: Oleksandr Natalenko Signed-off-by: Andrew Morton Reviewed-by: Nhat Pham Reviewed-by: Youngjun Park Cc: Rafael Aquini Cc: Christopher Li Cc: Kairui Song Cc: Kemeng Shi Cc: Baoquan He Cc: Barry Song Cc: mm/swapfile.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) --- mm/swapfile.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mm/swapfile.c b/mm/swapfile.c index 4451f178ce396b..226230dda0aa65 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -3452,7 +3452,7 @@ static int swap_show(struct seq_file *swap, void *v) return 0; } - bytes = K(si->pages); + bytes = K((unsigned long)si->pages); inuse = K(swap_usage_in_pages(si)); file = si->swap_file; @@ -3968,8 +3968,8 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) /* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */ enable_swap_info(si); - pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s\n", - K(si->pages), name->name, si->prio, nr_extents, + pr_info("Adding %luk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s\n", + K((unsigned long)si->pages), name->name, si->prio, nr_extents, K((unsigned long long)span), (si->flags & SWP_SOLIDSTATE) ? "SS" : "", (si->flags & SWP_DISCARDABLE) ? "D" : "", From 49b51228a108b243dbe2ac41ae583ad3c7c5b848 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Mon, 16 Nov 2026 19:29:22 +0100 Subject: [PATCH 1383/2102] hugetlbfs: fix integer overflow in fallocate() hugetlbfs_fallocate() rounds the range end up by adding hpage_size - 1 to offset + len. vfs_fallocate()'s existing overflow check only makes sure that offset + len does not overflow. Once we overflow for valid endpoints near LLONG_MAX, we can get a negative temporary result that is then converted to a very large huge page index. A one-byte allocation ending at LLONG_MAX can therefore consume all available huge pages. Pages added beyond LLONG_MAX are skipped during inode eviction, leaking them and triggering the BUG_ON() in clear_inode(). To fix it, calculate the end index in a simpler way that cannot overflow. This also fixes the signed overflow reported by luojiajun in 2019. Backporting notes: without commit a08c7193e4f18 ("mm/filemap: remove hugetlb special casing in filemap.c"), remove_inode_hugepages() must include the final huge page during truncate and eviction. Link: https://lore.kernel.org/20261116-fixes_hugetlb-v2-0-4dd9e94ea9ac@kernel.org Link: https://patch.msgid.link/20261116-fixes_hugetlb-v2-1-4dd9e94ea9ac@kernel.org Fixes: 70c3547e36f5 ("hugetlbfs: add hugetlbfs_fallocate()") Signed-off-by: David Hildenbrand (Arm) Signed-off-by: Andrew Morton Reported-by: luojiajun Closes: https://lore.kernel.org/all/1554775226-67213-1-git-send-email-luojiajun3@huawei.com/ Reported-by: Josef Bacik Acked-by: Muchun Song Reviewed-by: Ackerley Tng Tested-by: Gregory Price (Meta) Link: https://lore.kernel.org/20261116-fixes_hugetlb-v2-1-4dd9e94ea9ac@kernel.org Reviewed-by: Gregory Price (Meta) Acked-by: Oscar Salvador Cc: Naoya Horiguchi Cc: Mel Gorman Cc: Andy Whitcroft Cc: Miaohe Lin Cc: Michal Hocko Cc: Rik van Riel Cc: Hugh Dickins Cc: Baolin Wang Cc: Vivek Kasireddy Cc: Dave Airlie Cc: Jason Gunthorpe Cc: Lorenzo Stoakes Cc: Liam R. Howlett Cc: Vlastimil Babka Cc: Mike Rapoport Cc: Suren Baghdasaryan Cc: Jonathan Corbet Cc: Shuah Khan Cc: Randy Dunlap Cc: Peter Xu Cc: Breno Leitao Cc: Will Deacon Cc: Aneesh Kumar K.V Cc: Nicholas Piggin Cc: Peter Zijlstra Cc: Heiko Carstens Cc: Vasily Gorbik Cc: Alexander Gordeev Cc: Christian Borntraeger Cc: Sven Schnelle Cc: Arnd Bergmann Cc: Gerd Hoffmann Cc: Chris Mason Cc: Daehyeon Ko <4ncienth@gmail.com> Cc: Oscar Salvador Cc: fs/hugetlbfs/inode.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) --- fs/hugetlbfs/inode.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/fs/hugetlbfs/inode.c b/fs/hugetlbfs/inode.c index 558007fa5e885b..d6ec140365e128 100644 --- a/fs/hugetlbfs/inode.c +++ b/fs/hugetlbfs/inode.c @@ -722,11 +722,13 @@ static long hugetlbfs_fallocate(struct file *file, int mode, loff_t offset, /* * Default preallocate case. - * For this range, start is rounded down and end is rounded up - * as well as being converted to page offsets. + * vfs_fallocate() guarantees that offset + len is positive and does + * not overflow. Avoid overflows when calculating the end huge page + * index: set it to one past the index of the huge page containing the + * last byte. */ start = offset >> hpage_shift; - end = (offset + len + hpage_size - 1) >> hpage_shift; + end = ((offset + len - 1) >> hpage_shift) + 1; inode_lock(inode); From 39e0ae8bf7291d0ab46b2323acb927dd132ce6ca Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Mon, 16 Nov 2026 19:29:27 +0100 Subject: [PATCH 1384/2102] mm/hugetlb: fix mremap() racing with page migration Migration of anon hugetlb folios walks the anon_vma, so the file's i_mmap_rwsem does not serialize it against move_hugetlb_page_tables(). There are various issues with that. Most importantly, move_huge_pte() releases both page table locks before the TLB is flushed. Migration can then find the destination entry and finish migration, reusing the old folio while the TLB still has entries cached. Hold the anon_vma write lock across the move and the final TLB flush. This also prevents concurrent rmap walks from missing entries moved during rollback. When we must allocate a destination page table, flush the TLB before dropping the anon_vma lock, then reacquire it after allocation. Dropping the lock only works around lockdep: hugetlb folios are not reclaimed or migrated by allocation compaction, but their anon_vmas share the lock class used by ordinary anonymous memory. Having a separate lock class for hugetlb's anon_vma (like already done for i_mmap_rwsem via hugetlbfs_i_mmap_rwsem_key) requires more thought. There is a concern that this can block page migration of anonymous folios quite a while ... which is not really different to what happens to page-cache folios today. If ever a problem, we can temporarily release the lock. So let's keep it simple for now. It is a shame that hugetlb has to implement everything core-mm implements in a different way that just screams for problems. Link: https://patch.msgid.link/20261116-fixes_hugetlb-v2-6-4dd9e94ea9ac@kernel.org Fixes: 550a7d60bd5e ("mm, hugepages: add mremap() support for hugepage backed vma") Signed-off-by: David Hildenbrand (Arm) Signed-off-by: Andrew Morton Reported-by: Chris Mason Acked-by: Muchun Song Tested-by: Gregory Price (Meta) Link: https://lore.kernel.org/179490494079.482102.4618915344813254218.b4-reply@b4 Reviewed-by: Gregory Price (Meta) Acked-by: Oscar Salvador (SUSE) Cc: Oscar Salvador Cc: Naoya Horiguchi Cc: Mel Gorman Cc: Andy Whitcroft Cc: Miaohe Lin Cc: Michal Hocko Cc: Rik van Riel Cc: Hugh Dickins Cc: Baolin Wang Cc: Vivek Kasireddy Cc: Dave Airlie Cc: Jason Gunthorpe Cc: Lorenzo Stoakes Cc: Liam R. Howlett Cc: Vlastimil Babka Cc: Mike Rapoport Cc: Suren Baghdasaryan Cc: Jonathan Corbet Cc: Shuah Khan Cc: Randy Dunlap Cc: Peter Xu Cc: Breno Leitao Cc: Will Deacon Cc: Aneesh Kumar K.V Cc: Nicholas Piggin Cc: Peter Zijlstra Cc: Heiko Carstens Cc: Vasily Gorbik Cc: Alexander Gordeev Cc: Christian Borntraeger Cc: Sven Schnelle Cc: Arnd Bergmann Cc: Gerd Hoffmann Cc: Josef Bacik Cc: Daehyeon Ko <4ncienth@gmail.com> Cc: luojiajun Cc: Ackerley Tng Cc: mm/hugetlb.c | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) --- mm/hugetlb.c | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/mm/hugetlb.c b/mm/hugetlb.c index ce9c8e57b8e5c0..bf1d0474034e0c 100644 --- a/mm/hugetlb.c +++ b/mm/hugetlb.c @@ -5204,6 +5204,7 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma, { struct hstate *h = hstate_vma(vma); struct address_space *mapping = vma->vm_file->f_mapping; + struct anon_vma *anon_vma = vma->anon_vma; unsigned long sz = huge_page_size(h); struct mm_struct *mm = vma->vm_mm; unsigned long old_end = old_addr + len; @@ -5227,6 +5228,8 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma, /* Prevent race with file truncation */ hugetlb_vma_lock_write(vma); i_mmap_lock_write(mapping); + if (anon_vma) + anon_vma_lock_write(anon_vma); for (; old_addr < old_end; old_addr += sz, new_addr += sz) { const unsigned long offset_to_last_entry = (old_addr | last_addr_mask) - old_addr; @@ -5266,7 +5269,20 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma, continue; } - dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz); + dst_pte = hugetlb_walk(new_vma, new_addr, sz); + if (!dst_pte) { + /* + * We can allocate memory under anon_vma lock with hugetlb, + * but lockdep does not know about that. So for now we simply + * flush the TLB and temporarily drop the lock. + */ + tlb_flush_mmu_tlbonly(&tlb); + if (anon_vma) + anon_vma_unlock_write(anon_vma); + dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz); + if (anon_vma) + anon_vma_lock_write(anon_vma); + } if (!dst_pte) break; @@ -5274,7 +5290,10 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma, tlb_remove_huge_tlb_entry(h, &tlb, src_pte, old_addr); } + /* Flush pending moves before allowing migration to walk the entries. */ tlb_flush_mmu_tlbonly(&tlb); + if (anon_vma) + anon_vma_unlock_write(anon_vma); huge_pmd_unshare_flush(&tlb, vma); mmu_notifier_invalidate_range_end(&range); From da48afefa78d358da74e7cef435e18c28451277a Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Mon, 16 Nov 2026 19:29:28 +0100 Subject: [PATCH 1385/2102] hugetlbfs: fix unmapping folios from private VMAs hugetlb_unmap_file_folio() assumes vm_private_data points to a struct hugetlb_vma_lock when hugetlb_vma_trylock_write() fails. Since hugetlb VMA locking was extended to private VMAs, this can also happen when vm_private_data contains a resv_map pointer; treating it as a hugetlb_vma_lock corrupts memory and can cause crashes or hangs. Only take the VMA lock when a shareable lock exists, as additional locking is only needed for PMD table sharing. The fault mutex and i_mmap_rwsem already provide the required protection for private VMAs. Fix generated by an LLM and sent by Josef Bacik in private. [david@kernel.org: simplify description and comment] Link: https://patch.msgid.link/20261116-fixes_hugetlb-v2-7-4dd9e94ea9ac@kernel.org Fixes: bf4916922c60 ("hugetlbfs: extend hugetlb_vma_lock to private VMAs") Signed-off-by: Josef Bacik Signed-off-by: David Hildenbrand (Arm) Signed-off-by: Andrew Morton Tested-by: Daehyeon Ko <4ncienth@gmail.com> Link: https://lore.kernel.org/20261116-fixes_hugetlb-v2-7-4dd9e94ea9ac@kernel.org Acked-by: Muchun Song Tested-by: Gregory Price (Meta) Link: https://lore.kernel.org/179490430300.482102.17633361840450824485.b4-reply@b4 Acked-by: Oscar Salvador (SUSE) Cc: Oscar Salvador Cc: Naoya Horiguchi Cc: Mel Gorman Cc: Andy Whitcroft Cc: Miaohe Lin Cc: Michal Hocko Cc: Rik van Riel Cc: Hugh Dickins Cc: Baolin Wang Cc: Vivek Kasireddy Cc: Dave Airlie Cc: Jason Gunthorpe Cc: Lorenzo Stoakes Cc: Liam R. Howlett Cc: Vlastimil Babka Cc: Mike Rapoport Cc: Suren Baghdasaryan Cc: Jonathan Corbet Cc: Shuah Khan Cc: Randy Dunlap Cc: Peter Xu Cc: Breno Leitao Cc: Will Deacon Cc: Aneesh Kumar K.V Cc: Nicholas Piggin Cc: Peter Zijlstra Cc: Heiko Carstens Cc: Vasily Gorbik Cc: Alexander Gordeev Cc: Christian Borntraeger Cc: Sven Schnelle Cc: Arnd Bergmann Cc: Gerd Hoffmann Cc: Chris Mason Cc: luojiajun Cc: Ackerley Tng Cc: fs/hugetlbfs/inode.c | 10 ++++++++++ 1 file changed, 10 insertions(+) --- fs/hugetlbfs/inode.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/fs/hugetlbfs/inode.c b/fs/hugetlbfs/inode.c index d6ec140365e128..f83c85caf8741b 100644 --- a/fs/hugetlbfs/inode.c +++ b/fs/hugetlbfs/inode.c @@ -401,6 +401,16 @@ static void hugetlb_unmap_file_folio(struct hstate *h, if (!hugetlb_vma_maps_pfn(vma, v_start, pfn)) continue; + /* + * We only need additional VMA locking here for PMD table + * sharing, which synchronizes on the shareable lock. + */ + if (!__vma_shareable_lock(vma)) { + unmap_hugepage_range(vma, v_start, v_end, NULL, + ZAP_FLAG_DROP_MARKER); + continue; + } + if (!hugetlb_vma_trylock_write(vma)) { vma_lock = vma->vm_private_data; /* From 448293c44d86abaff45d6f6919e6056ad97eaa31 Mon Sep 17 00:00:00 2001 From: Hui Zhu Date: Mon, 9 Nov 2026 10:16:11 +0800 Subject: [PATCH 1386/2102] mm/mglru: fix a no-op lru_gen_clear_refs() call in lru_lazyfree() lru_lazyfree() calls lru_gen_clear_refs() after lruvec_del_folio(), but lru_gen_del_folio() has already cleared LRU_GEN_MASK, so folio_lru_gen() returns -1 and lru_gen_clear_refs() exits at its "gen < 0" check without clearing the refs or PG_workingset. A MADV_FREE folio therefore keeps the state it had before madvise(2), even though madvise_free_pte_range() has already cleared the accessed and dirty bits of its PTEs. lru_gen_folio_seq() places it one generation younger, and PG_workingset puts it in the last tier, so sort_folio() promotes and protects it instead of evicting it and charges it to lrugen->protected[], which read_ctrl_pos() uses to balance anon against file reclaim. __folio_inc_gen() clears the refs but not PG_workingset, so this repeats every time the folio reaches the oldest generation. If the folio is redirtied first, ttu_anon_lazyfree_folio() keeps it and lru_gen_eviction() packs the stale state into the shadow entry, so a later refault is promoted to the youngest generation. Call lru_gen_clear_refs() while the folio is still on the generation list, as deactivate_file_folio() and folio_deactivate() already do. Its return value only says whether the folio is in the oldest generation, which lru_lazyfree() does not need because it re-adds the folio below. Keep folio_clear_referenced() unconditional: the classic LRU needs it, and it also covers the folios that lru_gen_clear_refs() skips. Link: https://patch.msgid.link/20261109021611.22247-1-hui.zhu@linux.dev Fixes: cc8ec7be78ff ("mm/mglru: optimize deactivation") Signed-off-by: Hui Zhu Signed-off-by: Andrew Morton Suggested-by: Barry Song Reviewed-by: Barry Song Reviewed-by: Liam R. Howlett (Google) Cc: David Hildenbrand Cc: Lorenzo Stoakes Cc: Vlastimil Babka Cc: Mike Rapoport Cc: Suren Baghdasaryan Cc: Michal Hocko Cc: Yu Zhao Cc: Kairui Song Cc: mm/folio.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) --- mm/folio.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/mm/folio.c b/mm/folio.c index 38046a40a9db52..7a3394e7c5dca0 100644 --- a/mm/folio.c +++ b/mm/folio.c @@ -623,12 +623,10 @@ static void lru_lazyfree(struct lruvec *lruvec, struct folio *folio) folio_test_swapcache(folio) || folio_test_unevictable(folio)) return; + lru_gen_clear_refs(folio); lruvec_del_folio(lruvec, folio); folio_clear_active(folio); - if (lru_gen_enabled()) - lru_gen_clear_refs(folio); - else - folio_clear_referenced(folio); + folio_clear_referenced(folio); /* * Lazyfree folios are clean anonymous folios. They have * the swapbacked flag cleared, to distinguish them from normal From b03f2f48069e9a62176e82f732c5645b5e0ced9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jouni=20H=C3=B6gander?= Date: Wed, 18 Nov 2026 13:02:20 +0200 Subject: [PATCH 1387/2102] drm/i915/psr: Adjust Xiaomi Book Pro 14 2026 psr2 disable quirk MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We want to apply psr2 disable quirk on Xiaomi Book Pro 14 2026 with differing device ID. Fixes: 5e79af5db00b ("drm/i915/psr: Disable PSR2 on Xiaomi Book Pro 14 2026 as a quirk") Closes: https://gitlab.freedesktop.org/drm/xe/kernel/-/work_items/9575 Cc: Jani Nikula Cc: Mika Kahola Cc: # v7.2+ Signed-off-by: Jouni Högander Reviewed-by: Mika Kahola Link: https://patch.msgid.link/20261118110220.77370-1-jouni.hogander@intel.com (cherry picked from commit 5bb277d94021fc6d19934a11d79333b996213fb1) Signed-off-by: Joonas Lahtinen --- drivers/gpu/drm/i915/display/intel_quirks.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/gpu/drm/i915/display/intel_quirks.c b/drivers/gpu/drm/i915/display/intel_quirks.c index 96eb9a40df9b95..e3303d5146e89c 100644 --- a/drivers/gpu/drm/i915/display/intel_quirks.c +++ b/drivers/gpu/drm/i915/display/intel_quirks.c @@ -270,6 +270,7 @@ static struct intel_quirk intel_quirks[] = { /* Xiaomi Book Pro 14 2026 */ { 0xb081, 0x1d72, 0x2424, quirk_disable_psr2 }, + { 0xb080, 0x1d72, 0x2424, quirk_disable_psr2 }, }; static const struct intel_dpcd_quirk intel_dpcd_quirks[] = { From e464a6356398a7050c13099eb5d684b9d2fbb318 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jouni=20H=C3=B6gander?= Date: Fri, 20 Nov 2026 13:24:46 +0200 Subject: [PATCH 1388/2102] drm/i915/alpm: Track the configured transcoder lifetime MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ALPM disable can access a stale transcoder when ALPM was not configured for the current modeset, causing unclaimed register accesses during pipe teardown. Record the transcoder only when programming ALPM and invalidate it after disable. Check it under the ALPM lock to avoid register accesses on repeated or unconfigured disables. Fixes: 504766382edb ("drm/i915/lobf: Disintegrate alpm_disable from psr_disable") Cc: Animesh Manna Cc: # v6.16+ Signed-off-by: Jouni Högander Reviewed-by: Jani Nikula Link: https://patch.msgid.link/20261120112446.1562267-1-jouni.hogander@intel.com (cherry picked from commit 47ae8ebe01676821fe0366188d576696609d26ee) Signed-off-by: Joonas Lahtinen --- drivers/gpu/drm/i915/display/intel_alpm.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/i915/display/intel_alpm.c b/drivers/gpu/drm/i915/display/intel_alpm.c index f54b29e193ee93..105006ca6be7f3 100644 --- a/drivers/gpu/drm/i915/display/intel_alpm.c +++ b/drivers/gpu/drm/i915/display/intel_alpm.c @@ -46,6 +46,7 @@ bool intel_alpm_is_alpm_aux_less(struct intel_dp *intel_dp, void intel_alpm_init(struct intel_dp *intel_dp) { mutex_init(&intel_dp->alpm.lock); + intel_dp->alpm.transcoder = INVALID_TRANSCODER; } static int get_silence_period_symbols(const struct intel_crtc_state *crtc_state) @@ -549,6 +550,7 @@ static void lnl_alpm_configure(struct intel_dp *intel_dp, alpm_ctl |= ALPM_CTL_ALPM_ENTRY_CHECK(crtc_state->alpm_state.check_entry_lines); intel_de_write(display, ALPM_CTL(display, cpu_transcoder), alpm_ctl); + intel_dp->alpm.transcoder = cpu_transcoder; mutex_unlock(&intel_dp->alpm.lock); } @@ -556,7 +558,6 @@ void intel_alpm_configure(struct intel_dp *intel_dp, const struct intel_crtc_state *crtc_state) { lnl_alpm_configure(intel_dp, crtc_state); - intel_dp->alpm.transcoder = crtc_state->cpu_transcoder; } void intel_alpm_port_configure(struct intel_dp *intel_dp, @@ -733,17 +734,23 @@ void intel_alpm_lobf_debugfs_add(struct intel_connector *connector) void intel_alpm_disable(struct intel_dp *intel_dp) { struct intel_display *display = to_intel_display(intel_dp); - enum transcoder cpu_transcoder = intel_dp->alpm.transcoder; + enum transcoder cpu_transcoder; if (DISPLAY_VER(display) < 20 || !intel_dp->alpm_dpcd) return; mutex_lock(&intel_dp->alpm.lock); + cpu_transcoder = intel_dp->alpm.transcoder; + if (cpu_transcoder == INVALID_TRANSCODER) + goto unlock; + intel_de_rmw(display, ALPM_CTL(display, cpu_transcoder), ALPM_CTL_ALPM_ENABLE | ALPM_CTL_LOBF_ENABLE, 0); + intel_dp->alpm.transcoder = INVALID_TRANSCODER; drm_dbg_kms(display->drm, "Disabling ALPM\n"); +unlock: mutex_unlock(&intel_dp->alpm.lock); } From 4ec9b9e4496a5546bc29c439328c27b82aa5da5f Mon Sep 17 00:00:00 2001 From: Alexandre Becholey Date: Thu, 19 Nov 2026 13:16:55 +0000 Subject: [PATCH 1389/2102] ALSA: caiaq: stop the iso packet parsers before a partial block The iso packet parsers in audio.c walk a packet in blocks of one sample per stream, but only compare the start of each block with the packet length. The block size follows from the channel counts the device reports, so it need not divide the packet length, and the last block of a packet runs past its end. A device reporting e.g. 62 channels can make the driver read and write up to 232 bytes past the capture and playback URB buffers in URB completion context. Make each parser round the packet length down to a multiple of its own block size, which depends only on n_streams and not on spec.data_alignment (the device can change that at any time), and zero the unused tail of a playback packet. The bug was found, and the reproducer and this fix were written, by AI agents (Claude Mythos and Claude Opus models). The analysis and the patch were reviewed by a human. Fixes: 523f1dce3743 ("[ALSA] Add Native Instrument usb audio device support") Cc: stable@vger.kernel.org Signed-off-by: Alexandre Becholey Link: https://patch.msgid.link/20261119131632.650637-1-alex@becholey.ch Signed-off-by: Takashi Iwai --- sound/usb/caiaq/audio.c | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/sound/usb/caiaq/audio.c b/sound/usb/caiaq/audio.c index bb6280aa353347..c7d47f0833da24 100644 --- a/sound/usb/caiaq/audio.c +++ b/sound/usb/caiaq/audio.c @@ -332,13 +332,14 @@ static void read_in_urb_mode0(struct snd_usb_caiaqdev *cdev, const struct usb_iso_packet_descriptor *iso) { unsigned char *usb_buf = urb->transfer_buffer + iso->offset; + unsigned int len = rounddown(iso->actual_length, cdev->n_streams); struct snd_pcm_substream *sub; int stream, i; if (all_substreams_zero(cdev->sub_capture)) return; - for (i = 0; i < iso->actual_length;) { + for (i = 0; i < len;) { for (stream = 0; stream < cdev->n_streams; stream++, i++) { sub = cdev->sub_capture[stream]; if (sub) { @@ -360,11 +361,13 @@ static void read_in_urb_mode2(struct snd_usb_caiaqdev *cdev, const struct usb_iso_packet_descriptor *iso) { unsigned char *usb_buf = urb->transfer_buffer + iso->offset; + unsigned int len = rounddown(iso->actual_length, + cdev->n_streams * BYTES_PER_SAMPLE_USB); unsigned char check_byte; struct snd_pcm_substream *sub; int stream, i; - for (i = 0; i < iso->actual_length;) { + for (i = 0; i < len;) { if (i % (cdev->n_streams * BYTES_PER_SAMPLE_USB) == 0) { for (stream = 0; stream < cdev->n_streams; @@ -407,6 +410,8 @@ static void read_in_urb_mode3(struct snd_usb_caiaqdev *cdev, const struct usb_iso_packet_descriptor *iso) { unsigned char *usb_buf = urb->transfer_buffer + iso->offset; + unsigned int len = rounddown(iso->actual_length, cdev->n_streams * + BYTES_PER_SAMPLE_USB * CHANNELS_PER_STREAM); struct device *dev = caiaqdev_to_dev(cdev); int stream, i; @@ -414,7 +419,7 @@ static void read_in_urb_mode3(struct snd_usb_caiaqdev *cdev, if (iso->actual_length % (BYTES_PER_SAMPLE_USB * CHANNELS_PER_STREAM)) return; - for (i = 0; i < iso->actual_length;) { + for (i = 0; i < len;) { for (stream = 0; stream < cdev->n_streams; stream++) { struct snd_pcm_substream *sub = cdev->sub_capture[stream]; char *audio_buf = NULL; @@ -495,10 +500,11 @@ static void fill_out_urb_mode_0(struct snd_usb_caiaqdev *cdev, const struct usb_iso_packet_descriptor *iso) { unsigned char *usb_buf = urb->transfer_buffer + iso->offset; + unsigned int len = rounddown(iso->length, cdev->n_streams); struct snd_pcm_substream *sub; int stream, i; - for (i = 0; i < iso->length;) { + for (i = 0; i < len;) { for (stream = 0; stream < cdev->n_streams; stream++, i++) { sub = cdev->sub_playback[stream]; if (sub) { @@ -516,12 +522,14 @@ static void fill_out_urb_mode_0(struct snd_usb_caiaqdev *cdev, } /* fill in the check bytes */ - if (cdev->spec.data_alignment == 2 && + if (cdev->spec.data_alignment == 2 && i < len && i % (cdev->n_streams * BYTES_PER_SAMPLE_USB) == (cdev->n_streams * CHANNELS_PER_STREAM)) for (stream = 0; stream < cdev->n_streams; stream++, i++) usb_buf[i] = MAKE_CHECKBYTE(cdev, stream, i); } + + memset(usb_buf + len, 0, iso->length - len); } static void fill_out_urb_mode_3(struct snd_usb_caiaqdev *cdev, @@ -529,9 +537,11 @@ static void fill_out_urb_mode_3(struct snd_usb_caiaqdev *cdev, const struct usb_iso_packet_descriptor *iso) { unsigned char *usb_buf = urb->transfer_buffer + iso->offset; + unsigned int len = rounddown(iso->length, cdev->n_streams * + BYTES_PER_SAMPLE_USB * CHANNELS_PER_STREAM); int stream, i; - for (i = 0; i < iso->length;) { + for (i = 0; i < len;) { for (stream = 0; stream < cdev->n_streams; stream++) { struct snd_pcm_substream *sub = cdev->sub_playback[stream]; char *audio_buf = NULL; @@ -565,6 +575,8 @@ static void fill_out_urb_mode_3(struct snd_usb_caiaqdev *cdev, } } } + + memset(usb_buf + len, 0, iso->length - len); } static inline void fill_out_urb(struct snd_usb_caiaqdev *cdev, From 95a4961c8b45e4c96b9368364764c8f5a715d6d5 Mon Sep 17 00:00:00 2001 From: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Date: Sun, 22 Nov 2026 18:40:39 +0800 Subject: [PATCH 1390/2102] ALSA: line6: Stop URBs synchronously via sync_stop callback line6_buffer_release() frees the stream buffer after line6_wait_clear_audio_urbs() gave up waiting for the URBs that are still active. The buffer is still referenced by those URBs, and the completion callback of such an URB resubmits it from submit_audio_out_urb() with line6pcm->out.buffer already set to NULL, which ends up in a NULL pointer dereference in the memset() in submit_audio_out_urb(). While the URBs remain queued, the host controller can also write the received isochronous data into the freed buffer. Such a write does not go through the KASAN checks, so it silently corrupts the freed slab object; the corruption was observed as a bogus KASAN quarantine entry that later led to a general protection fault in qlist_free_all(). The active_urbs bitmap cannot prove that the URBs are gone: line6_unlink_audio_urbs() is called outside the stream lock and only marks the URBs that are active at that moment, so an URB resubmitted by a completion callback right after the scan is never unlinked and keeps being resubmitted after the stream was stopped. Stop the URBs synchronously instead of polling for them: mark the URBs that are currently active under the stream lock, so that the completion callbacks cannot resubmit them, and kill them with usb_kill_urb(), which waits for the giveback. Expose this through the sync_stop PCM op, which ALSA core invokes before hw_free(), hw_params() and prepare() once the stream was stopped, so the buffer is guaranteed to be unused when it is released. The URBs are marked and killed only while no stream is running on that stream, and only those that are active at that moment, so neither a stream started concurrently nor another stream type still running (software monitoring, impulse or the capture helper) is stopped. Unlink marks left on already completed URBs are dropped afterwards, while those of still active URBs are kept, so that a later stream start can submit the URBs again. line6_pcm_acquire() and snd_line6_prepare() keep a synchronous stop for an idle stream as well: sync_stop() is invoked only when the substream itself was stopped, while the other stream types sharing the same stream never set that, and their unlinking URBs would make line6_stream_start() skip the submission. line6_pcm_disconnect() and line6_buffer_release() stop the URBs unconditionally, as the device may be gone already and the buffer is about to be freed. The helper skips the loop when the URBs were not created, as line6_pcm_disconnect() may run after a failed probe. Fixes: 63e20df1e5b2 ("ALSA: line6: Reorganize PCM stream handling") Cc: stable@vger.kernel.org Co-developed-by: Bin Yu Signed-off-by: Bin Yu Co-developed-by: Cheng Wen Signed-off-by: Cheng Wen Signed-off-by: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Link: https://patch.msgid.link/20261122104039.7160-1-25031212351@stu.xidian.edu.cn Signed-off-by: Takashi Iwai --- sound/usb/line6/capture.c | 1 + sound/usb/line6/pcm.c | 102 ++++++++++++++++++++++++++----------- sound/usb/line6/pcm.h | 1 + sound/usb/line6/playback.c | 1 + 4 files changed, 76 insertions(+), 29 deletions(-) diff --git a/sound/usb/line6/capture.c b/sound/usb/line6/capture.c index 626274e503c7aa..fa98c26cf77d14 100644 --- a/sound/usb/line6/capture.c +++ b/sound/usb/line6/capture.c @@ -284,6 +284,7 @@ const struct snd_pcm_ops snd_line6_capture_ops = { .hw_free = snd_line6_hw_free, .prepare = snd_line6_prepare, .trigger = snd_line6_trigger, + .sync_stop = snd_line6_sync_stop, .pointer = snd_line6_pointer, }; diff --git a/sound/usb/line6/pcm.c b/sound/usb/line6/pcm.c index d17baf7761c67d..34d68a9ce3285e 100644 --- a/sound/usb/line6/pcm.c +++ b/sound/usb/line6/pcm.c @@ -109,29 +109,51 @@ static void line6_unlink_audio_urbs(struct snd_line6_pcm *line6pcm, } /* - Wait until unlinking of all currently active URBs has been finished. -*/ -static void line6_wait_clear_audio_urbs(struct snd_line6_pcm *line6pcm, - struct line6_pcm_stream *pcms) + * Mark all currently active URBs for unlinking and kill them. + * + * The unlink bit is set under the stream lock, so the completion + * callbacks cannot resubmit these URBs any longer. usb_kill_urb() then + * waits for the giveback of every URB, hence the stream buffer is no + * longer referenced by the host controller. This function must be + * called from a sleepable context. + * + * When @idle_only is set, nothing is done if some stream is still running + * on @pcms, and only the URBs that are active at that moment are killed, + * so that a concurrently started stream is never stopped. + */ +static void line6_kill_audio_urbs(struct snd_line6_pcm *line6pcm, + struct line6_pcm_stream *pcms, bool idle_only) { - int timeout = HZ; + unsigned long active; int i; - int alive; - do { - alive = 0; - for (i = 0; i < line6pcm->line6->iso_buffers; i++) { - if (test_bit(i, &pcms->active_urbs)) - alive++; - } - if (!alive) - break; - set_current_state(TASK_UNINTERRUPTIBLE); - schedule_timeout(1); - } while (--timeout > 0); - if (alive) - dev_err(line6pcm->line6->ifcdev, - "timeout: still %d active urbs..\n", alive); + /* May be called when the URB creation failed during the probe */ + if (!pcms->urbs) + return; + + scoped_guard(spinlock_irqsave, &pcms->lock) { + if (idle_only && pcms->running) + return; + active = pcms->active_urbs; + for_each_set_bit(i, &active, line6pcm->line6->iso_buffers) + set_bit(i, &pcms->unlink_urbs); + } + + for_each_set_bit(i, &active, line6pcm->line6->iso_buffers) + if (pcms->urbs[i]) + usb_kill_urb(pcms->urbs[i]); + + /* + * Drop the unlink marks left on URBs that were completed and not + * resubmitted, so that a later stream start can submit the URBs + * again. An URB that is still active keeps its mark. + */ + scoped_guard(spinlock_irqsave, &pcms->lock) { + for_each_set_bit(i, &pcms->unlink_urbs, + line6pcm->line6->iso_buffers) + if (!test_bit(i, &pcms->active_urbs)) + clear_bit(i, &pcms->unlink_urbs); + } } static inline struct line6_pcm_stream * @@ -172,7 +194,7 @@ static void line6_buffer_release(struct snd_line6_pcm *line6pcm, { clear_bit(type, &pstr->opened); if (!pstr->opened) { - line6_wait_clear_audio_urbs(line6pcm, pstr); + line6_kill_audio_urbs(line6pcm, pstr, false); if (pstr == &line6pcm->in) { /* prev_fbuf points into the capture buffer we are about * to free; drop it while no capture URB is in flight. @@ -337,8 +359,7 @@ int line6_pcm_acquire(struct snd_line6_pcm *line6pcm, int type, bool start) ret = line6_buffer_acquire(line6pcm, pstr, dir, type); if (ret < 0) goto error; - if (!pstr->running) - line6_wait_clear_audio_urbs(line6pcm, pstr); + line6_kill_audio_urbs(line6pcm, pstr, true); } if (start) { for (dir = 0; dir < 2; dir++) { @@ -510,10 +531,8 @@ static int snd_line6_new_pcm(struct usb_line6 *line6, struct snd_pcm **pcm_ret) */ void line6_pcm_disconnect(struct snd_line6_pcm *line6pcm) { - line6_unlink_audio_urbs(line6pcm, &line6pcm->out); - line6_unlink_audio_urbs(line6pcm, &line6pcm->in); - line6_wait_clear_audio_urbs(line6pcm, &line6pcm->out); - line6_wait_clear_audio_urbs(line6pcm, &line6pcm->in); + line6_kill_audio_urbs(line6pcm, &line6pcm->out, false); + line6_kill_audio_urbs(line6pcm, &line6pcm->in, false); } /* @@ -592,6 +611,27 @@ int line6_init_pcm(struct usb_line6 *line6, } EXPORT_SYMBOL_GPL(line6_init_pcm); +/* common PCM sync_stop callback */ +int snd_line6_sync_stop(struct snd_pcm_substream *substream) +{ + struct snd_line6_pcm *line6pcm = snd_pcm_substream_chip(substream); + struct line6_pcm_stream *pstr = get_stream(line6pcm, substream->stream); + + guard(mutex)(&line6pcm->state_mutex); + line6_kill_audio_urbs(line6pcm, pstr, true); + /* + * A capture stream may use the playback stream as a helper, and + * snd_line6_trigger() stops it together with the capture stream. + * Stop the leftover playback URBs here as well, so that the helper + * stream can be restarted at the next trigger. + */ + if (substream->stream == SNDRV_PCM_STREAM_CAPTURE && + (line6pcm->line6->properties->capabilities & + LINE6_CAP_IN_NEEDS_OUT)) + line6_kill_audio_urbs(line6pcm, &line6pcm->out, true); + return 0; +} + /* prepare pcm callback */ int snd_line6_prepare(struct snd_pcm_substream *substream) { @@ -599,8 +639,12 @@ int snd_line6_prepare(struct snd_pcm_substream *substream) struct line6_pcm_stream *pstr = get_stream(line6pcm, substream->stream); guard(mutex)(&line6pcm->state_mutex); - if (!pstr->running) - line6_wait_clear_audio_urbs(line6pcm, pstr); + /* + * sync_stop() is called only after this substream itself was + * stopped; other stream types sharing the stream (monitor, impulse + * or the capture helper) may have left URBs unlinking. + */ + line6_kill_audio_urbs(line6pcm, pstr, true); if (!test_and_set_bit(LINE6_FLAG_PREPARED, &line6pcm->flags)) { line6pcm->out.count = 0; diff --git a/sound/usb/line6/pcm.h b/sound/usb/line6/pcm.h index a15913bf2a7aad..21e550948cd810 100644 --- a/sound/usb/line6/pcm.h +++ b/sound/usb/line6/pcm.h @@ -183,6 +183,7 @@ extern int line6_init_pcm(struct usb_line6 *line6, struct line6_pcm_properties *properties); extern int snd_line6_trigger(struct snd_pcm_substream *substream, int cmd); extern int snd_line6_prepare(struct snd_pcm_substream *substream); +extern int snd_line6_sync_stop(struct snd_pcm_substream *substream); extern int snd_line6_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params); extern int snd_line6_hw_free(struct snd_pcm_substream *substream); diff --git a/sound/usb/line6/playback.c b/sound/usb/line6/playback.c index e93a16f6958e37..10e273f4b77a47 100644 --- a/sound/usb/line6/playback.c +++ b/sound/usb/line6/playback.c @@ -414,6 +414,7 @@ const struct snd_pcm_ops snd_line6_playback_ops = { .hw_free = snd_line6_hw_free, .prepare = snd_line6_prepare, .trigger = snd_line6_trigger, + .sync_stop = snd_line6_sync_stop, .pointer = snd_line6_pointer, }; From eea981794753db5dc6bd005417d283fc00d81bd4 Mon Sep 17 00:00:00 2001 From: Suyuan Wang Date: Sun, 22 Nov 2026 10:08:16 +0000 Subject: [PATCH 1391/2102] ALSA: sis7019: Don't shift the voice IRQ status by 32 sis_voice_irq() walks the set bits of a PISR_A or PISR_B status word: bit = __ffs(status); status >>= bit + 1; When voice 31 or 63 interrupts, bit is 31 and status is shifted by 32, which is undefined for a u32. On x86 the shift count is masked to 0, so status does not change, the loop never ends, and voice keeps moving 32 entries forward on every pass, past the end of sis->voices[], with sis_update_voice() called on whatever is there. All of this runs in the hard IRQ handler. Voices are handed out from 0 up, so voice 31 is in use once enough playback streams are open. Walk the bits with for_each_set_bit() and index the voice by bit number instead. The voices are still updated in the same order. Found with a static analysis tool and checked by hand. Fixes: 175859bf1602 ("[ALSA] sis7019: support the SiS 7019 Audio Accelerator") Cc: stable@vger.kernel.org Co-developed-by: Kaixuan Li Signed-off-by: Kaixuan Li Signed-off-by: Suyuan Wang Link: https://patch.msgid.link/20261122-sis7019-voice-irq-v1-1-fa5d0cbecf62@gmail.com Signed-off-by: Takashi Iwai --- sound/pci/sis7019.c | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/sound/pci/sis7019.c b/sound/pci/sis7019.c index fe5bda5af6a5f5..f31e62068ee36c 100644 --- a/sound/pci/sis7019.c +++ b/sound/pci/sis7019.c @@ -278,15 +278,11 @@ static void sis_update_voice(struct voice *voice) static void sis_voice_irq(u32 status, struct voice *voice) { + unsigned long bits = status; int bit; - while (status) { - bit = __ffs(status); - status >>= bit + 1; - voice += bit; - sis_update_voice(voice); - voice++; - } + for_each_set_bit(bit, &bits, 32) + sis_update_voice(&voice[bit]); } static irqreturn_t sis_interrupt(int irq, void *dev) From 84ea739fa99f55d774817c885fc9deb69355d5c6 Mon Sep 17 00:00:00 2001 From: James Barnette Date: Mon, 23 Nov 2026 02:15:49 -0600 Subject: [PATCH 1392/2102] ALSA: usb-audio: Add generic implicit feedback quirk for Elgato XLR Dock The Elgato XLR Dock (0fd9:00a6) returns digital silence from its microphone when the playback stream is started before the capture stream. Starting capture first works. Enforcing the generic implicit feedback mode (quirk_flags=0fd9:00a6:0x20000) fixes it: with the flag set, capture returned valid data in both start orders, while without it every playback-first trial captured 0 nonzero samples. Add a quirk entry for the device. Suggested-by: Takashi Iwai Signed-off-by: James Barnette Link: https://patch.msgid.link/20261123081549.2237366-1-calmasacow@gmail.com Signed-off-by: Takashi Iwai --- sound/usb/quirks.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sound/usb/quirks.c b/sound/usb/quirks.c index 08ee7bc1c57b00..84436073953a7f 100644 --- a/sound/usb/quirks.c +++ b/sound/usb/quirks.c @@ -2684,6 +2684,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { QUIRK_FLAG_FIXED_RATE), DEVICE_FLG(0x0fd9, 0x0008, /* Hauppauge HVR-950Q */ QUIRK_FLAG_SHARE_MEDIA_DEVICE | QUIRK_FLAG_ALIGN_TRANSFER), + DEVICE_FLG(0x0fd9, 0x00a6, /* Elgato XLR Dock */ + QUIRK_FLAG_GENERIC_IMPLICIT_FB), DEVICE_FLG(0x1038, 0x1294, /* SteelSeries Arctis Pro Wireless */ QUIRK_FLAG_MIXER_PLAYBACK_MIN_MUTE), DEVICE_FLG(0x1101, 0x0003, /* Audioengine D1 */ From ca643603dd3408a5d110ada3765b79794b2a394d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?William=20Alberto=20Jimenez=20Mu=C3=B1oz?= Date: Sun, 22 Nov 2026 22:50:53 -0500 Subject: [PATCH 1393/2102] ALSA: hda/realtek: Add quirk for ASUS VivoBook X509UA MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The internal microphone on ASUS VivoBook X509UA (subsystem ID 0x1043:0x1961) records only silence without a quirk entry. Add ALC256_FIXUP_ASUS_MIC_NO_PRESENCE to fix the issue. Verified on the hardware by booting with snd_hda_intel.model=1043:1271, which selects the same fixup: the internal microphone then records normally. Link: https://bugzilla.kernel.org/show_bug.cgi?id=222320 Signed-off-by: William Alberto Jimenez Muñoz Link: https://patch.msgid.link/20261123035053.12487-1-alberto1192456@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index bcbd7edac415aa..887debabe9c6dc 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -8240,6 +8240,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1043, 0x18d3, "ASUS UM3504DA", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x1043, 0x18f1, "Asus FX505DT", ALC256_FIXUP_ASUS_HEADSET_MIC), SND_PCI_QUIRK(0x1043, 0x194e, "ASUS UX563FD", ALC294_FIXUP_ASUS_HPE), + SND_PCI_QUIRK(0x1043, 0x1961, "ASUS VivoBook X509UA", ALC256_FIXUP_ASUS_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1043, 0x1970, "ASUS UX550VE", ALC289_FIXUP_ASUS_GA401), SND_PCI_QUIRK(0x1043, 0x197e, "ASUS VivoBook X509DAP", ALC256_FIXUP_ASUS_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1043, 0x1982, "ASUS B1400CEPE", ALC256_FIXUP_ASUS_HPE), From e3abb03776197a9a4e2a92ac659b18bb10afa899 Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Mon, 23 Nov 2026 02:14:01 +0100 Subject: [PATCH 1394/2102] ALSA: usb-audio: Enable native DSD for Fosi Audio DS2 The Fosi Audio DS2 (USB ID 262a:0001, Savitech controller with a Cirrus Logic CS43131 DAC) exposes a UAC2 RAW_DATA playback altsetting (altset 4, bmFormats 0x80000000, 32-bit subslot), but ALSA reports it as SPECIAL without the DSD_RAW quirk, preventing native DSD playback. Add the device to the quirk flags table with QUIRK_FLAG_DSD_RAW, as already done for the ddHiFi TC44C (262a:9302) using the same vendor's controller. With the quirk enabled, altset 4 is exposed as DSD_U32_BE and stereo DSD64, DSD128 and DSD256 streams (88200, 176400 and 352800 frames/s) play through it. Tested using snd-usb-audio quirk_flags=262a:0001:DSD_RAW on Linux 7.3.5. Signed-off-by: Gianluca Boiano Link: https://patch.msgid.link/20261123011401.1545242-1-morf3089@gmail.com Signed-off-by: Takashi Iwai --- sound/usb/quirks.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sound/usb/quirks.c b/sound/usb/quirks.c index 84436073953a7f..03172f8e971662 100644 --- a/sound/usb/quirks.c +++ b/sound/usb/quirks.c @@ -2806,6 +2806,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { QUIRK_FLAG_SET_IFACE_FIRST), DEVICE_FLG(0x25aa, 0x600b, /* TAE1159 */ QUIRK_FLAG_FORCE_IFACE_RESET | QUIRK_FLAG_IFACE_DELAY), + DEVICE_FLG(0x262a, 0x0001, /* Fosi Audio DS2 */ + QUIRK_FLAG_DSD_RAW), DEVICE_FLG(0x262a, 0x9302, /* ddHiFi TC44C */ QUIRK_FLAG_DSD_RAW), DEVICE_FLG(0x2772, 0x0502, /* Musical Fidelity M6s DAC */ From 8b9746a2bdb80872cbd397db98c57a57392c98c5 Mon Sep 17 00:00:00 2001 From: Suyuan Wang Date: Mon, 23 Nov 2026 00:36:20 +0000 Subject: [PATCH 1395/2102] ALSA: emu10k1: Require CAP_SYS_ADMIN for SNDRV_EMU10K1_IOCTL_PCM_POKE snd_emu10k1_fx8010_ioctl() requires CAP_SYS_ADMIN for the commands that change the FX8010 DSP state: CODE_POKE, TRAM_SETUP, STOP, CONTINUE, ZERO_TRAM_COUNTER and SINGLE_STEP. PCM_POKE has no such check, although it changes the card's FX8010 PCM configuration. snd_emu10k1_ipcm_poke() stores the GPR and TRAM indices given by the caller without checking them, and the FX8010 PCM code in emupcm.c later uses them as register offsets: snd_emu10k1_ptr_write(emu, TANKMEMADDRREGBASE + 0x80 + pcm->etram[i], ...); snd_emu10k1_ptr_write(emu, emu->gpr_base + pcm->gpr_trigger, 0, 1); So a process that can open the hwdep device can change this card-wide configuration, including which registers the PCM code writes, while the other DSP configuration commands are limited to CAP_SYS_ADMIN. Require CAP_SYS_ADMIN for PCM_POKE too, like the other FX8010 configuration commands. Found with a static analysis tool and checked by hand. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Co-developed-by: Kaixuan Li Signed-off-by: Kaixuan Li Signed-off-by: Suyuan Wang Link: https://patch.msgid.link/20261123-emu10k1-pcm-poke-v1-1-097b8cb8daaf@gmail.com Signed-off-by: Takashi Iwai --- sound/pci/emu10k1/emufx.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sound/pci/emu10k1/emufx.c b/sound/pci/emu10k1/emufx.c index ddac6cecc8eb2c..df4661927041f0 100644 --- a/sound/pci/emu10k1/emufx.c +++ b/sound/pci/emu10k1/emufx.c @@ -2506,6 +2506,8 @@ static int snd_emu10k1_fx8010_ioctl(struct snd_hwdep * hw, struct file *file, un kfree(icode); return res; case SNDRV_EMU10K1_IOCTL_PCM_POKE: + if (!capable(CAP_SYS_ADMIN)) + return -EPERM; ipcm = memdup_user(argp, sizeof(*ipcm)); if (IS_ERR(ipcm)) return PTR_ERR(ipcm); From e30ec632e1f0e1fb92b3f0d727f5bc0c00ada6eb Mon Sep 17 00:00:00 2001 From: Abhiraj Dutta Date: Sun, 22 Nov 2026 17:02:47 -0500 Subject: [PATCH 1396/2102] ALSA: hda/realtek: Add quirk for HP Spectre x360 2-in-1 Laptop 16-f2xxx The HP Spectre x360 16-f2xxx (SSID 103c:891e) has the same speaker problem as the 14-eu0xxx and 16-aa0xxx: the BIOS marks the treble speaker pin 0x14 as unconnected, so only the bass speakers on 0x17 play. The mute and mic-mute LEDs don't work either. Use the existing EU0XXX pin fixup and chain ALC245_FIXUP_HP_X360_MUTE_LEDS. The mute LED is on COEF 0x0b bits 2-3 and the mic-mute LED on GPIO2 (active low), which is what that fixup already handles. Unlike the 16-aa0xxx, the bass speaker amp works without toggling GPIO0, so the EU0XXX variant is enough. Under SOF the PCI SSID on this machine reads as 103c:0000, so the entry is matched against the codec SSID. Tested on a 16-f2xxx: all four speakers play and both LEDs follow the mute state. Cc: stable@vger.kernel.org Signed-off-by: Abhiraj Dutta Link: https://patch.msgid.link/20261122-hp-spectre-16-f2-quirk-v1-1-2011ef8986fb@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 887debabe9c6dc..508bcfd3afea08 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -4524,6 +4524,7 @@ enum { ALC256_FIXUP_HEADPHONE_AMP_VOL, ALC245_FIXUP_HP_SPECTRE_X360_EU0XXX, ALC245_FIXUP_HP_SPECTRE_X360_16_AA0XXX, + ALC245_FIXUP_HP_SPECTRE_X360_16_F2XXX, ALC245_FIXUP_HP_ZBOOK_FIREFLY_G12A, ALC285_FIXUP_ASUS_GA403U, ALC285_FIXUP_ASUS_GA403U_HEADSET_MIC, @@ -7226,6 +7227,12 @@ static const struct hda_fixup alc269_fixups[] = { .type = HDA_FIXUP_FUNC, .v.func = alc245_fixup_hp_spectre_x360_16_aa0xxx, }, + [ALC245_FIXUP_HP_SPECTRE_X360_16_F2XXX] = { + .type = HDA_FIXUP_FUNC, + .v.func = alc245_fixup_hp_spectre_x360_eu0xxx, + .chained = true, + .chain_id = ALC245_FIXUP_HP_X360_MUTE_LEDS + }, [ALC245_FIXUP_HP_ZBOOK_FIREFLY_G12A] = { .type = HDA_FIXUP_FUNC, .v.func = alc245_fixup_hp_zbook_firefly_g12a, @@ -7869,6 +7876,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8902, "HP OMEN 16", ALC285_FIXUP_HP_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x890e, "HP 255 G8 Notebook PC", ALC236_FIXUP_HP_MUTE_LED_COEFBIT2), SND_PCI_QUIRK(0x103c, 0x8919, "HP Pavilion Aero Laptop 13-be0xxx", ALC287_FIXUP_HP_GPIO_LED), + SND_PCI_QUIRK(0x103c, 0x891e, "HP Spectre x360 2-in-1 Laptop 16-f2xxx", ALC245_FIXUP_HP_SPECTRE_X360_16_F2XXX), SND_PCI_QUIRK(0x103c, 0x896d, "HP ZBook Firefly 16 G9", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x896e, "HP EliteBook x360 830 G9", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8971, "HP EliteBook 830 G9", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), From 5e8802bf480da76634a8ac929c29af7b7acde615 Mon Sep 17 00:00:00 2001 From: Suyuan Wang Date: Sun, 22 Nov 2026 13:46:29 +0000 Subject: [PATCH 1397/2102] ALSA: firewire-lib: Abort the FCP transaction on a bus reset When fcp_bus_reset() marks a transaction as STATE_BUS_RESET, fcp_avc_transaction() sleeps and resends the command, but leaves the state as it is. The response to the resent command is then ignored, and the next wait returns at once, so the loop keeps resending the command without a retry limit until sending fails. The AV/C Digital Interface Command Set General Specification 4.2 says that a target which detects a bus reset discards any AV/C transaction in progress without returning a response. So instead of resending, end the transaction on a bus reset and return -EAGAIN, so that the caller can start the sequence again. ERROR_DELAY_MS and have no users left after this, so drop them. Found with a static analysis tool and checked by hand. Suggested-by: Takashi Sakamoto Fixes: 31ef9134eb52 ("ALSA: add LaCie FireWire Speakers/Griffin FireWave Surround driver") Cc: stable@vger.kernel.org Co-developed-by: Kaixuan Li Signed-off-by: Kaixuan Li Signed-off-by: Suyuan Wang Reviewed-by: Takashi Sakamoto Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261122-firewire-busreset-v2-1-e104d785c8a1@gmail.com --- sound/firewire/fcp.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/sound/firewire/fcp.c b/sound/firewire/fcp.c index e60bfd0ee4accc..b8e7e2c907912b 100644 --- a/sound/firewire/fcp.c +++ b/sound/firewire/fcp.c @@ -14,7 +14,6 @@ #include #include #include -#include #include "fcp.h" #include "lib.h" #include "amdtp-stream.h" @@ -22,7 +21,6 @@ #define CTS_AVC 0x00 #define ERROR_RETRIES 3 -#define ERROR_DELAY_MS 5 #define FCP_TIMEOUT_MS 125 int avc_general_set_sig_fmt(struct fw_unit *unit, unsigned int rate, @@ -272,7 +270,8 @@ int fcp_avc_transaction(struct fw_unit *unit, ret = t.response_size; break; } else if (t.state == STATE_BUS_RESET) { - msleep(ERROR_DELAY_MS); + ret = -EAGAIN; + break; } else if (++tries >= ERROR_RETRIES) { dev_err(&t.unit->device, "FCP command timed out\n"); ret = -EIO; From 890eff85e8a01012e1d3b6c54cba787416331381 Mon Sep 17 00:00:00 2001 From: Suyuan Wang Date: Sun, 22 Nov 2026 13:46:30 +0000 Subject: [PATCH 1398/2102] ALSA: fireworks: Abort the transaction on a bus reset When snd_efw_transaction_bus_reset() marks a transaction as STATE_BUS_RESET, snd_efw_transaction_run() sleeps and resends the command, but leaves the state as it is. The response to the resent command is then ignored, and the next wait returns at once, so the loop keeps resending the command without a retry limit until sending fails. Fireworks devices also accept AV/C commands, and the AV/C general specification says that a bus reset discards any transaction in progress. Do the same as for FCP: end the transaction on a bus reset and return -EAGAIN. ERROR_DELAY_MS has no users left, so drop it. Found with a static analysis tool and checked by hand. Suggested-by: Takashi Sakamoto Fixes: bde8a8f23bbe ("ALSA: fireworks: Add transaction and some commands") Cc: stable@vger.kernel.org Co-developed-by: Kaixuan Li Signed-off-by: Kaixuan Li Signed-off-by: Suyuan Wang Reviewed-by: Takashi Sakamoto Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261122-firewire-busreset-v2-2-e104d785c8a1@gmail.com --- sound/firewire/fireworks/fireworks_transaction.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sound/firewire/fireworks/fireworks_transaction.c b/sound/firewire/fireworks/fireworks_transaction.c index 5c859773fe0626..bb9ab8ed52b564 100644 --- a/sound/firewire/fireworks/fireworks_transaction.c +++ b/sound/firewire/fireworks/fireworks_transaction.c @@ -34,7 +34,6 @@ #define MEMORY_SPACE_EFW_RESPONSE 0xecc080000000ULL #define ERROR_RETRIES 3 -#define ERROR_DELAY_MS 5 #define EFC_TIMEOUT_MS 125 static DEFINE_SPINLOCK(instances_lock); @@ -99,7 +98,8 @@ int snd_efw_transaction_run(struct fw_unit *unit, ret = t.size; break; } else if (t.state == STATE_BUS_RESET) { - msleep(ERROR_DELAY_MS); + ret = -EAGAIN; + break; } else if (++tries >= ERROR_RETRIES) { dev_err(&t.unit->device, "EFW transaction timed out\n"); ret = -EIO; From 896ec6bbe7dd2f29aff1a12eb318a6828be1edd8 Mon Sep 17 00:00:00 2001 From: Oleg Antonyan Date: Sun, 22 Nov 2026 14:18:37 +0100 Subject: [PATCH 1399/2102] ALSA: hda/realtek: Fix headset mic on ASUS Zenbook S 13 UX5304MA The ASUS Zenbook S 13 UX5304MA (1043:1c33) uses an ALC294 codec with CS35L41 amplifiers over SPI. Its BIOS leaves pin 0x19 unconfigured, so the headset mic on the combo jack does not work. Use ALC294_FIXUP_ASUS_SPI_HEADSET_MIC like the UX3405MA and UX3402VA. It configures the headset mic pin and chains to ALC245_FIXUP_CS35L41_SPI_2 to keep the speakers working. Tested on a UX5304MA: headset mic, internal mic and speakers work. Fixes: 61cbc08fdb04 ("ALSA: hda/realtek: Add quirks for ASUS 2024 Zenbooks") Cc: stable@vger.kernel.org Signed-off-by: Oleg Antonyan Link: https://patch.msgid.link/20261122-ux5304ma-headset-mic-v1-1-80589ae749a8@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 508bcfd3afea08..dfdcf8b98c9eb4 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -8266,7 +8266,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1043, 0x1bbd, "ASUS Z550MA", ALC255_FIXUP_ASUS_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1043, 0x1c03, "ASUS UM3406HA", ALC294_FIXUP_ASUS_I2C_HEADSET_MIC), SND_PCI_QUIRK(0x1043, 0x1c23, "Asus X55U", ALC269_FIXUP_LIMIT_INT_MIC_BOOST), - SND_PCI_QUIRK(0x1043, 0x1c33, "ASUS UX5304MA", ALC245_FIXUP_CS35L41_SPI_2), + SND_PCI_QUIRK(0x1043, 0x1c33, "ASUS UX5304MA", ALC294_FIXUP_ASUS_SPI_HEADSET_MIC), SND_PCI_QUIRK(0x1043, 0x1c43, "ASUS UX8406MA", ALC245_FIXUP_CS35L41_SPI_2), SND_PCI_QUIRK(0x1043, 0x1c62, "ASUS GU603", ALC289_FIXUP_ASUS_GA401), SND_PCI_QUIRK(0x1043, 0x1c63, "ASUS GU605M", ALC285_FIXUP_ASUS_GU605_SPI_SPEAKER2_TO_DAC1), From 9ec96c4d21beb0603af01995330e5c8fa3f45a33 Mon Sep 17 00:00:00 2001 From: HyeongJun An Date: Sun, 22 Nov 2026 19:36:10 +0900 Subject: [PATCH 1400/2102] ALSA: seq: ump: Don't drop MIDI 2.0 RPN and NRPN for MIDI 1.0 clients The cvt_ump_midi2_to_midi1() converts MIDI 2.0 channel voice messages for a UMP MIDI 1.0 client. It has no case for the RPN and NRPN messages, so they fall into the default case and are dropped. A pitch bend range or a tuning set by a MIDI 2.0 client never reaches a MIDI 1.0 client. The core converter, cvt_ump_midi2_to_legacy(), turns the same messages into CC 101 and 100 (99 and 98 for NRPN) followed by CC 6 and 38. The program change case here already sends the bank select CCs ahead of the program in the same way. To fix this, deliver the four CCs that cvt_ump_midi2_to_legacy() produces. Fixes: e9e02819a98a ("ALSA: seq: Automatic conversion of UMP events") Cc: stable@vger.kernel.org Signed-off-by: HyeongJun An Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261122103611.3264343-2-sammiee5311@gmail.com --- sound/core/seq/seq_ump_convert.c | 36 ++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/sound/core/seq/seq_ump_convert.c b/sound/core/seq/seq_ump_convert.c index b42a7ffbf31eaa..e76fdb54df175a 100644 --- a/sound/core/seq/seq_ump_convert.c +++ b/sound/core/seq/seq_ump_convert.c @@ -432,6 +432,38 @@ static int cvt_ump_midi1_to_midi2(struct snd_seq_client *dest, atomic, hop); } +/* send a MIDI 2.0 RPN/NRPN as the four MIDI 1.0 CCs that select and set it */ +static int cvt_ump_midi2_rpn_to_midi1(struct snd_seq_client *dest, + struct snd_seq_client_port *dest_port, + struct snd_seq_ump_event *ev_cvt, + const union snd_ump_midi2_msg *midi2, + int atomic, int hop) +{ + union snd_ump_midi1_msg *midi1 = (union snd_ump_midi1_msg *)ev_cvt->ump; + bool rpn = midi2->rpn.status == UMP_MSG_STATUS_RPN; + u16 v = downscale_32_to_14bit(midi2->rpn.data); + const unsigned char cc[4][2] = { + { rpn ? UMP_CC_RPN_MSB : UMP_CC_NRPN_MSB, midi2->rpn.bank }, + { rpn ? UMP_CC_RPN_LSB : UMP_CC_NRPN_LSB, midi2->rpn.index }, + { UMP_CC_DATA, v >> 7 }, + { UMP_CC_DATA_LSB, v & 0x7f }, + }; + int i, err = 0; + + midi1->cc.status = UMP_MSG_STATUS_CC; + for (i = 0; i < ARRAY_SIZE(cc); i++) { + midi1->cc.index = cc[i][0]; + midi1->cc.data = cc[i][1]; + err = __snd_seq_deliver_single_event(dest, dest_port, + (struct snd_seq_event *)ev_cvt, + atomic, hop); + if (err < 0) + return err; + } + + return err; +} + /* convert UMP packet from MIDI 2.0 to MIDI 1.0 and deliver it */ static int cvt_ump_midi2_to_midi1(struct snd_seq_client *dest, struct snd_seq_client_port *dest_port, @@ -499,6 +531,10 @@ static int cvt_ump_midi2_to_midi1(struct snd_seq_client *dest, midi1->pb.data_msb = v >> 7; midi1->pb.data_lsb = v & 0x7f; break; + case UMP_MSG_STATUS_RPN: + case UMP_MSG_STATUS_NRPN: + return cvt_ump_midi2_rpn_to_midi1(dest, dest_port, &ev_cvt, + midi2, atomic, hop); default: return 0; } From 11ef0d515100259c7979f5b4c61b6ea97c6cdc27 Mon Sep 17 00:00:00 2001 From: HyeongJun An Date: Sun, 22 Nov 2026 19:36:11 +0900 Subject: [PATCH 1401/2102] selftests/alsa: Test the sequencer UMP MIDI 2.0 RPN conversion Check that an RPN and an NRPN from a UMP MIDI 2.0 client reach a UMP MIDI 1.0 client as the four CCs that select and set them. The NRPN data has low bits set, so CC 38 is checked as well. Signed-off-by: HyeongJun An Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261122103611.3264343-3-sammiee5311@gmail.com --- tools/testing/selftests/alsa/seq-ump-test.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tools/testing/selftests/alsa/seq-ump-test.c b/tools/testing/selftests/alsa/seq-ump-test.c index 55bb7ea5b02f9f..7030d061dfae89 100644 --- a/tools/testing/selftests/alsa/seq-ump-test.c +++ b/tools/testing/selftests/alsa/seq-ump-test.c @@ -620,4 +620,24 @@ TEST_F(seq_pair, ump_midi2_to_midi1_note) { 0x20913c01, 0 }, { 0x20813c00, 0 }); } +TEST_F(seq_pair, ump_midi2_to_midi1_rpn) +{ + int skip = 0; + int err; + + err = open_pair(&self->dst, SNDRV_SEQ_CLIENT_UMP_MIDI_1_0, + &self->src, SNDRV_SEQ_CLIENT_UMP_MIDI_2_0, &skip); + if (skip) + SKIP(return, "UMP sequencer client unavailable: %s", + strerror(-err)); + ASSERT_EQ(0, err); + + SEND_UMP(0x40210001, 0x80000000); + SEND_UMP(0x40310203, 0x12345678); + EXPECT_MT_PACKETS(2, { 0x20b16500, 0 }, { 0x20b16401, 0 }, + { 0x20b10640, 0 }, { 0x20b12600, 0 }, + { 0x20b16302, 0 }, { 0x20b16203, 0 }, + { 0x20b10609, 0 }, { 0x20b1260d, 0 }); +} + TEST_HARNESS_MAIN From 35fbc5a85891b2550425c7365ee3e011b505760b Mon Sep 17 00:00:00 2001 From: Peter Zijlstra Date: Wed, 18 Nov 2026 14:14:46 +0100 Subject: [PATCH 1402/2102] perf/core: Cancel hrtimer on perf_pmu_unregister() Since perf_pmu_register() initializes the hrtimer, make sure perf_pmu_unregister() cancels the timer before freeing the memory it lives in. Fixes: 9e6302056f80 ("perf: Use hrtimers for event multiplexing") Reported-by: Hanxiang Xu Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Cc: --- kernel/events/core.c | 1 + 1 file changed, 1 insertion(+) diff --git a/kernel/events/core.c b/kernel/events/core.c index e870f12c3ad812..f424b72239b83d 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -12968,6 +12968,7 @@ static void perf_pmu_free(struct pmu *pmu) struct perf_cpu_pmu_context *cpc; cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu); + hrtimer_cancel(&cpc->hrtimer); if (!cpc) continue; if (cpc->epc.embedded) { From dd1e556d9a5aef3e731fbe31ae43d9b4eaf05c1b Mon Sep 17 00:00:00 2001 From: Peter Zijlstra Date: Wed, 18 Nov 2026 14:15:11 +0100 Subject: [PATCH 1403/2102] perf/core: Fix perf_pmu_register() sysfs race Only expose the sysfs files after fully initializing the data they expose. Reported-by: Hanxiang Xu Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Cc: --- kernel/events/core.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/kernel/events/core.c b/kernel/events/core.c index f424b72239b83d..a2e4b078f7e4f2 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -13012,12 +13012,6 @@ int perf_pmu_register(struct pmu *_pmu, const char *name, int type) pmu->type = pmu_type.id; atomic_set(&pmu->exclusive_cnt, 0); - if (pmu_bus_running && !pmu->dev) { - int ret = pmu_dev_alloc(pmu); - if (ret) - return ret; - } - pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context *); if (!pmu->cpu_pmu_context) return -ENOMEM; @@ -13036,6 +13030,12 @@ int perf_pmu_register(struct pmu *_pmu, const char *name, int type) __perf_mux_hrtimer_init(cpc, cpu); } + if (pmu_bus_running && !pmu->dev) { + int ret = pmu_dev_alloc(pmu); + if (ret) + return ret; + } + if (!pmu->start_txn) { if (pmu->pmu_enable) { /* From 4aa81df6bb45e9cf693c86849fe90d4e3dd85bbc Mon Sep 17 00:00:00 2001 From: Phat Dinh Date: Tue, 3 Nov 2026 15:56:41 +0700 Subject: [PATCH 1404/2102] perf/core: Fix UAF from remove_on_exec with perf_event_open() perf_event_open() installs the event into the target context and then drops the target's exec_update_lock before linking event->owner_entry into current->perf_event_list. This leaves a window in which the target can exec() while the event is live in its context but not yet on the owner's list. If the event has attr.remove_on_exec set, perf_event_remove_on_exec() detaches it in that window through perf_remove_from_owner(), which does list_del_init(&event->owner_entry) on the not-yet-linked entry and clears event->owner. perf_event_open() then continues and adds the now ownerless event to current->perf_event_list: CPU 0: perf_event_open() CPU 1: target task exec() ------------------------ ------------------------- perf_install_in_context(event) event->owner = current up_read(exec_update_lock) down_write(exec_update_lock) perf_event_remove_on_exec() perf_remove_from_owner(event) list_del_init(&event->owner_entry) event->owner = NULL up_write(exec_update_lock) list_add_tail(&event->owner_entry, ¤t->perf_event_list) When the event fd is closed, perf_release() sees event->owner == NULL, skips unlinking owner_entry and frees the event, leaving a dangling entry on the opener's perf_event_list. The next walk of that list, e.g. perf_event_exit_task() or PR_TASK_PERF_EVENTS_{EN,DIS}ABLE, is a use-after-free. Fix this by linking the event into current->perf_event_list before releasing exec_update_lock, so exec() cannot observe the event until it is fully published. Lock order is exec_update_lock -> perf_event_mutex, the same as perf_event_exit_task() called from exec, so no new dependency is introduced. Fixes: 2e498d0a74e5 ("perf: Add support for event removal on exec") Signed-off-by: Phat Dinh Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261103085641.3686424-1-phatdt1116@gmail.com --- kernel/events/core.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/kernel/events/core.c b/kernel/events/core.c index a2e4b078f7e4f2..51c251c482945a 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -14420,15 +14420,22 @@ SYSCALL_DEFINE5(perf_event_open, mutex_unlock(&ctx->mutex); + /* + * Publish the event on the owner's list before dropping + * exec_update_lock. Otherwise a concurrent exec() can run + * perf_event_remove_on_exec() and clear event->owner before + * owner_entry is linked, leaving an ownerless event on + * current->perf_event_list that perf_release() won't unlink. + */ + mutex_lock(¤t->perf_event_mutex); + list_add_tail(&event->owner_entry, ¤t->perf_event_list); + mutex_unlock(¤t->perf_event_mutex); + if (task) { up_read(&task->signal->exec_update_lock); put_task_struct(task); } - mutex_lock(¤t->perf_event_mutex); - list_add_tail(&event->owner_entry, ¤t->perf_event_list); - mutex_unlock(¤t->perf_event_mutex); - /* * File reference in group guarantees that group_leader has been * kept alive until we place the new event on the sibling_list. From b57e800b6e70a0957642ab2bf1db3e176ac229b5 Mon Sep 17 00:00:00 2001 From: Usama Arif Date: Thu, 19 Nov 2026 13:10:44 -0800 Subject: [PATCH 1405/2102] perf/core: Fix perf_sample_data reuse across software events do_perf_sw_event() passes one on-stack struct perf_sample_data to every matching event. perf_prepare_sample() fills in the fields an event samples, marks them in data->sample_flags and skips fields that are already marked, and those marks survive from one event to the next. So a sampling event later in the list emits the sample ID, timestamp, pid/tid and callchain prepared for an earlier one. Its record size is computed from the earlier event's dynamic fields as well and can come out smaller than what is written, in which case the kernel writes past its ring-buffer reservation over the records that follow. Two "perf record -e page-faults,context-switches -c 1 -a" sessions running at the same time hit this: the one started first gets the other's sample IDs and fails with "Bad address". Commit: 1d1bfe30dad5 ("perf/core: Fix perf_sample_data not properly initialized for different swevents in perf_tp_event()") fixed the same problem for tracepoints. Do the same here: initialize the struct for each matching event. While at it, drop the unused 'data' argument of perf_swevent_match(). Fixes: bb447c27a467 ("perf/core: Set data->sample_flags in perf_prepare_sample()") Signed-off-by: Usama Arif Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261119211235.99805-2-usama.arif@linux.dev --- kernel/events/core.c | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/kernel/events/core.c b/kernel/events/core.c index 51c251c482945a..42bd8adfe55cd9 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -11142,7 +11142,6 @@ int perf_exclude_event(struct perf_event *event, struct pt_regs *regs) static int perf_swevent_match(struct perf_event *event, enum perf_type_id type, u32 event_id, - struct perf_sample_data *data, struct pt_regs *regs) { if (event->attr.type != type) @@ -11207,11 +11206,10 @@ find_swevent_head(struct swevent_htable *swhash, struct perf_event *event) } static void do_perf_sw_event(enum perf_type_id type, u32 event_id, - u64 nr, - struct perf_sample_data *data, - struct pt_regs *regs) + u64 nr, struct pt_regs *regs, u64 addr) { struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); + struct perf_sample_data data; struct perf_event *event; struct hlist_head *head; @@ -11221,8 +11219,10 @@ static void do_perf_sw_event(enum perf_type_id type, u32 event_id, goto end; hlist_for_each_entry_rcu(event, head, hlist_entry) { - if (perf_swevent_match(event, type, event_id, data, regs)) - perf_swevent_event(event, nr, data, regs); + if (perf_swevent_match(event, type, event_id, regs)) { + perf_sample_data_init(&data, addr, 0); + perf_swevent_event(event, nr, &data, regs); + } } end: rcu_read_unlock(); @@ -11243,13 +11243,10 @@ void perf_swevent_put_recursion_context(int rctx) void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) { - struct perf_sample_data data; - if (WARN_ON_ONCE(!regs)) return; - perf_sample_data_init(&data, addr, 0); - do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs); + do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, regs, addr); } void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) From c9ef606bc68a7bbbaa5fc9cef968a5226c12a283 Mon Sep 17 00:00:00 2001 From: Usama Arif Date: Thu, 19 Nov 2026 13:10:45 -0800 Subject: [PATCH 1406/2102] perf/core: Don't let BPF programs read an uninitialized sample address A BPF program attached to a perf event gets a struct bpf_perf_event_data, and reading its addr field turns into a load from the perf_sample_data the sample is being assembled in. The verifier allows that load no matter which fields the event samples. perf_sample_data_init() used to store the address unconditionally, so the program read 0 when there was none. To touch fewer cachelines, it now stores the address only when it is non-zero, and perf_prepare_sample() fills it in only when the event samples it (PERF_SAMPLE_ADDR, PHYS_ADDR or DATA_PAGE_SIZE). For all other events, including context switches, cpu-clock and hardware counters like cycles, the program reads whatever was left in that stack slot, often a kernel pointer. Kernels built with CONFIG_INIT_STACK_ALL_ZERO, the default when the compiler supports it, mostly hide this by clearing the struct on function entry. With INIT_STACK_ALL_PATTERN the program reads the fill pattern instead. Clear the address before running the program if nobody filled it in, the same way the SIGTRAP path already checks PERF_SAMPLE_ADDR before using it. Events without a BPF program are not affected. Fixes: 7b0846301531 ("perf: Use sample_flags for addr") Signed-off-by: Usama Arif Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261119211235.99805-3-usama.arif@linux.dev --- kernel/events/core.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/kernel/events/core.c b/kernel/events/core.c index 42bd8adfe55cd9..ee51134510578f 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -10819,6 +10819,9 @@ static int bpf_overflow_handler(struct perf_event *event, prog = READ_ONCE(event->prog); if (prog) { perf_prepare_sample(data, event, regs); + /* bpf_perf_event_data::addr is readable without PERF_SAMPLE_ADDR */ + if (!(data->sample_flags & PERF_SAMPLE_ADDR)) + data->addr = 0; ret = bpf_prog_run(prog, &ctx); } rcu_read_unlock(); From d2583cb031135d3e2f6eeec9049fc2066fd3655c Mon Sep 17 00:00:00 2001 From: Fernand Sieber Date: Thu, 12 Nov 2026 18:15:44 +0200 Subject: [PATCH 1407/2102] sched/deadline: Clear stale rq->dl_server when core-sched replaces a pick With core scheduling and the fair server, the forced-idle accounting warns from an idle core: WARNING: kernel/sched/core_sched.c:263 at __sched_core_account_forceidle+0x1d6/0x1f0, CPU#0: swapper/0/0 The core is in forced idle with no sibling running a task. The reason is a stale rq->dl_server causing the idle task to incorrectly be considered as carried by the deadline server. The idle task then wins over a runnable sibling task and the whole core is idle despite having runnable tasks. The timeline below describes the issue: Setup. CPU0 and CPU1 are SMT siblings. - CPU1 runs R, a SCHED_FIFO task with cookie X. - CPU0 has C, a CFS task with no cookie, which has been starved. So CPU0's fair server is due to step in. t0, CPU0 picks for the core. - pick_task(rq0) goes through the deadline class, which picks the fair server, which picks C. As a side effect it sets rq0->dl_server = &rq0->fair_server. - pick_task(rq1) picks R. t1, ranking. C->dl_server is only set once C is switched in, so C ranks as CFS. R (RT) beats C (CFS), so the core cookie becomes X. t2, matching. CPU0's pick C has cookie 0, not X, so it is replaced. There is no cookie-X task on CPU0, so the replacement is idle, and CPU0 is forced idle. - The code sets rq0->core_pick = idle and rq0->core_dl_server = NULL. - The bug: it leaves rq0->dl_server pointing at CPU0's fair server, even though idle didn't come through any server. t3, CPU0 switches. CPU0 is the selecting CPU, so next = idle, and put_prev_set_next_task() hands the stale rq0->dl_server to it. Now idle->dl_server is CPU0's fair server. t4, C leaves. Load balancing moves C to another core, so CPU0 has nothing runnable. The stale link stays on idle. t5, the next core-wide selection (when CPU1 reschedules, say on a wakeup). - CPU0's pick is idle, and the ranking sees idle->dl_server set, so it ranks idle as a deadline task. - idle now beats R, and the core cookie becomes idle's cookie, 0. - CPU1's R has cookie X, not 0, so CPU1 is forced idle. t6, result. The whole core is idle. R is runnable but can't run, and nothing runs on either CPU. That's the WARN in __sched_core_account_forceidle(): forced idle with no sibling running a task. It lasts until CPU0 goes through a full schedule that resets its server link. With this patch, step t2 also does rq0->dl_server = NULL. At t3 idle gets no server, and at t5 it ranks as plain idle, so R wins and keeps running on CPU1. Fixes: bd9bbc96e835 ("sched: Rework dl_server") Signed-off-by: Fernand Sieber Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Cc: Link: https://patch.msgid.link/20261112161548.78189-2-sieberf@amazon.com --- kernel/sched/core.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/kernel/sched/core.c b/kernel/sched/core.c index 515b9d0353ce9e..42b99be948706d 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -6453,10 +6453,15 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) p = sched_core_find(rq_i, cookie); if (!p) p = idle_sched_class.pick_task(rq_i, rf); + + /* + * Neither a core tree pick nor idle comes through a + * DL server; drop the one the replaced pick left. + */ + rq_i->core_dl_server = rq_i->dl_server = NULL; } rq_i->core_pick = p; - rq_i->core_dl_server = NULL; if (p == rq_i->idle) { if (rq_i->nr_running) { From f4626e1c3c14306453e89bfc7799bd295f38b402 Mon Sep 17 00:00:00 2001 From: Fernand Sieber Date: Thu, 12 Nov 2026 18:15:47 +0200 Subject: [PATCH 1408/2102] sched/deadline: Don't charge core-sched forced idle to the DL servers A deferred DL server is charged the idle time of its rq, on the premise that the time was available to the server's class and went unused. Core scheduling breaks that premise: a CPU is forced idle when a SMT sibling runs a task with an incompatible cookie, so that time was available to no class at all. update_curr_dl_se() then runs the server's runtime out while it is throttled and calls replenish_dl_new_period(), pushing the activation a full period out. dl_defer_idle does not help, as idle_rq() is false on a forced-idle CPU: nr_running is not 0. Every period of forced idle pushes the activation again, the zero-laxity timer never fires, and the class the server reserves for gets nothing. Reproduction on 2 cores x 2 threads with the default fair server (50 ms / 1 s): a SCHED_FIFO spinner with a core-sched cookie on CPU0 and an uncookied CFS spinner on CPU1 force-idle CPU1, and the CFS task gets under 0.1% of a CPU instead of the reserved 5%. The ext server starves sched_ext tasks the same way, and there a plain CFS spinner on the sibling is enough. Don't charge forced idle. A server still only loses runtime to real execution or real idle, and one whose class has nothing to run still stops through dl_defer_idle once the rq is idle for real; with core scheduling off nothing changes. Getting the reserved bandwidth back also needs the server's pick to win the core-wide selection, which the preceding sched/core patches fix. Fixes: a110a81c52a9 ("sched/deadline: Deferrable dl server") Signed-off-by: Fernand Sieber Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Cc: Link: https://patch.msgid.link/20261112161548.78189-5-sieberf@amazon.com --- kernel/sched/idle.c | 7 +++++++ kernel/sched/sched.h | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/kernel/sched/idle.c b/kernel/sched/idle.c index e0c10a5dbda2bd..717d566b0809ce 100644 --- a/kernel/sched/idle.c +++ b/kernel/sched/idle.c @@ -573,6 +573,13 @@ static void update_curr_idle(struct rq *rq) se->exec_start = now; + /* + * Forced idle was not time available to any class on this rq, so + * don't let the deferred servers consume their runtime on it. + */ + if (forced_idle_rq(rq)) + return; + dl_server_update_idle(&rq->fair_server, delta_exec); #ifdef CONFIG_SCHED_CLASS_EXT dl_server_update_idle(&rq->ext_server, delta_exec); diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index a4e6696e3a516c..804c70317637d2 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -1521,6 +1521,16 @@ static inline bool sched_core_disabled(void) return !static_branch_unlikely(&__sched_core_enabled); } +/* + * True while core scheduling keeps @rq idle because a SMT sibling runs a task + * with an incompatible cookie, even though @rq has runnable tasks of its own. + */ +static inline bool forced_idle_rq(struct rq *rq) +{ + return sched_core_enabled(rq) && rq->core->core_forceidle_count && + rq->nr_running; +} + /* * Be careful with this function; not for general use. The return value isn't * stable unless you actually hold a relevant rq->__lock. @@ -1655,6 +1665,11 @@ static inline bool sched_core_disabled(void) return true; } +static inline bool forced_idle_rq(struct rq *rq) +{ + return false; +} + static inline raw_spinlock_t *rq_lockp(struct rq *rq) { return &rq->__lock; From 6d6fca38f51f414b75201d07b9ad4003f714551e Mon Sep 17 00:00:00 2001 From: Fernand Sieber Date: Thu, 12 Nov 2026 18:15:48 +0200 Subject: [PATCH 1409/2102] selftests/sched: Add a core-sched forced-idle DL server test Nothing in selftests notices a deferred DL server that is charged for core-sched forced idle and so never activates: the fair server keeps its reservation in debugfs while the CFS tasks it reserves for get a few hundredths of a percent of a CPU. Add cs_dl_server_test. It pins a SCHED_FIFO 50 spinner with its own core cookie to one SMT sibling and an uncookied CFS spinner to the other, so the second sibling is forced idle whenever the FIFO task runs, then checks the CFS task's share of that CPU over five seconds against the fair server's reservation under /sys/kernel/debug/sched/. The floor is half the reservation, 2.5% by default, since every slice the server gets costs a forced-idle hand-over. It skips without SMT, without core scheduling, or without the debugfs reservation. At 2 cores x 2 threads the share measures 4.0-5.2% once both this idle charge and the core-wide DL server pick are fixed, and 0.0% with either missing, so it passes only with both. Signed-off-by: Fernand Sieber Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Link: https://patch.msgid.link/20261112161548.78189-6-sieberf@amazon.com --- tools/testing/selftests/sched/.gitignore | 1 + tools/testing/selftests/sched/Makefile | 4 +- tools/testing/selftests/sched/config | 4 +- .../selftests/sched/cs_dl_server_test.c | 402 ++++++++++++++++++ 4 files changed, 408 insertions(+), 3 deletions(-) create mode 100644 tools/testing/selftests/sched/cs_dl_server_test.c diff --git a/tools/testing/selftests/sched/.gitignore b/tools/testing/selftests/sched/.gitignore index 6996d4654d9241..4e3a0254e0abc5 100644 --- a/tools/testing/selftests/sched/.gitignore +++ b/tools/testing/selftests/sched/.gitignore @@ -1 +1,2 @@ cs_prctl_test +cs_dl_server_test diff --git a/tools/testing/selftests/sched/Makefile b/tools/testing/selftests/sched/Makefile index 099ee9213557ad..fa50d1385bd68d 100644 --- a/tools/testing/selftests/sched/Makefile +++ b/tools/testing/selftests/sched/Makefile @@ -8,7 +8,7 @@ CFLAGS += -O2 -Wall -g -I./ $(KHDR_INCLUDES) -Wl,-rpath=./ \ $(CLANG_FLAGS) LDLIBS += -lpthread -TEST_GEN_FILES := cs_prctl_test -TEST_PROGS := cs_prctl_test +TEST_GEN_FILES := cs_prctl_test cs_dl_server_test +TEST_PROGS := cs_prctl_test cs_dl_server_test include ../lib.mk diff --git a/tools/testing/selftests/sched/config b/tools/testing/selftests/sched/config index 1bb8bf6d7fd4c8..57b2439f75eedd 100644 --- a/tools/testing/selftests/sched/config +++ b/tools/testing/selftests/sched/config @@ -1 +1,3 @@ -# empty +CONFIG_SCHED_CORE=y +CONFIG_SCHED_SMT=y +CONFIG_DEBUG_FS=y diff --git a/tools/testing/selftests/sched/cs_dl_server_test.c b/tools/testing/selftests/sched/cs_dl_server_test.c new file mode 100644 index 00000000000000..38aa005080f1f2 --- /dev/null +++ b/tools/testing/selftests/sched/cs_dl_server_test.c @@ -0,0 +1,402 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Verify that core-scheduling forced idle does not starve the fair deadline + * server. + * + * A CPU is forced idle when it has runnable tasks of its own but its SMT + * sibling runs a task with an incompatible core-sched cookie. If that time is + * charged to the rq's deferred DL servers, the fair server's runtime drains + * while it is throttled, its activation is pushed out every period, and the + * CFS tasks it reserves bandwidth for get next to nothing. + * + * The test pins a cookied SCHED_FIFO spinner to one SMT sibling and an + * uncookied CFS spinner to the other, so the second sibling is forced idle + * whenever the FIFO task runs, and checks that the CFS task still gets a + * sensible fraction of the fair server's reservation. + * + * Copyright (c) 2026 Amazon.com, Inc. or its affiliates. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../kselftest.h" + +#ifndef PR_SCHED_CORE +#define PR_SCHED_CORE 62 +#define PR_SCHED_CORE_GET 0 +#define PR_SCHED_CORE_CREATE 1 /* create unique core_sched cookie */ +#define PR_SCHED_CORE_SHARE_TO 2 /* push core_sched cookie to pid */ +#define PR_SCHED_CORE_SHARE_FROM 3 /* pull core_sched cookie to pid */ +#define PR_SCHED_CORE_MAX 4 +#endif + +enum pid_type {PIDTYPE_PID = 0, PIDTYPE_TGID, PIDTYPE_PGID}; + +#define SIBLINGS_LIST "/sys/devices/system/cpu/cpu0/topology/thread_siblings_list" +#define FAIR_SERVER "/sys/kernel/debug/sched/fair_server" + +#define RUN_TIME 5 /* measurement window, in seconds */ +#define FIFO_PRIO 50 + +/* + * The reservation is only approached, not reached: every slice the fair server + * gets costs the sibling a forced-idle hand-over, and the core-wide pick runs + * at tick granularity. Ask for half of it, which is far above the few hundredths + * of a percent a starved server leaves. + */ +#define MIN_SHARE_OF_RESERVATION 0.5 + +/* Status a spinner child reports to the parent over its readiness pipe. */ +#define CHILD_READY 'R' +#define CHILD_EPERM 'P' +#define CHILD_ERROR 'E' + +/* Tell the parent how setup went; it decides whether to run or to skip. */ +static void signal_status(int fd, char status) +{ + if (write(fd, &status, 1) != 1) { + ksft_perror("write to readiness pipe"); + exit(1); + } + if (status != CHILD_READY) + exit(1); +} + +/* + * Burn CPU until killed. A constant controlling expression keeps the compiler + * from removing the loop, so no volatile is needed to hold it in place. + */ +static void spin_forever(void) +{ + while (1) + ; +} + +static int set_affinity(int cpu) +{ + cpu_set_t mask; + + CPU_ZERO(&mask); + CPU_SET(cpu, &mask); + + return sched_setaffinity(0, sizeof(mask), &mask); +} + +/* + * Read the first two distinct CPU ids out of a cpu list such as "0-1", "0,4" + * or "0,4-5". Returns 0 on success, -1 if the list holds fewer than two ids. + */ +static int parse_sibling_pair(const char *list, int *sib0, int *sib1) +{ + int found = 0, sib[2] = { -1, -1 }; + const char *p = list; + + while (*p && found < 2) { + int first, last, n = 0; + + if (sscanf(p, "%d-%d%n", &first, &last, &n) != 2) { + if (sscanf(p, "%d%n", &first, &n) != 1) + return -1; + last = first; + } + for (; first <= last && found < 2; first++) + sib[found++] = first; + p += n; + if (*p != ',') + break; + p++; + } + + if (found < 2) + return -1; + + *sib0 = sib[0]; + *sib1 = sib[1]; + + return 0; +} + +static int read_sibling_pair(int *sib0, int *sib1) +{ + char list[256]; + FILE *f; + char *s; + + f = fopen(SIBLINGS_LIST, "r"); + if (!f) + return -1; + s = fgets(list, sizeof(list), f); + fclose(f); + if (!s) + return -1; + + return parse_sibling_pair(list, sib0, sib1); +} + +static int read_u64_file(const char *path, unsigned long long *val) +{ + FILE *f; + int ret; + + f = fopen(path, "r"); + if (!f) + return -1; + ret = fscanf(f, "%llu", val); + fclose(f); + + return ret == 1 ? 0 : -1; +} + +/* Read the fair server reservation of @cpu, in nanoseconds. */ +static int read_fair_server(int cpu, unsigned long long *runtime, + unsigned long long *period) +{ + char path[PATH_MAX]; + + snprintf(path, sizeof(path), FAIR_SERVER "/cpu%d/runtime", cpu); + if (read_u64_file(path, runtime)) + return -1; + + snprintf(path, sizeof(path), FAIR_SERVER "/cpu%d/period", cpu); + if (read_u64_file(path, period)) + return -1; + + return 0; +} + +/* CPU time consumed by @pid so far, in seconds, from /proc//stat. */ +static double process_runtime(pid_t pid) +{ + char path[PATH_MAX]; + unsigned long utime, stime; + FILE *f; + int fields; + + snprintf(path, sizeof(path), "/proc/%d/stat", pid); + f = fopen(path, "r"); + if (!f) + return -1; + + /* Skip the first 13 fields and read the 14th and 15th. */ + fields = fscanf(f, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu", + &utime, &stime); + fclose(f); + if (fields != 2) + return -1; + + return (double)(utime + stime) / sysconf(_SC_CLK_TCK); +} + +static double monotonic_now(void) +{ + struct timespec ts; + + if (clock_gettime(CLOCK_MONOTONIC, &ts)) + return -1; + + return ts.tv_sec + ts.tv_nsec / 1000000000.0; +} + +/* + * Diagnostic only: how long the FIFO task's CPU was forced idle. Needs + * CONFIG_SCHEDSTATS and schedstats enabled, so it must not gate the result. + */ +static void print_forced_idle(pid_t pid) +{ + char path[PATH_MAX], line[256]; + FILE *f; + + snprintf(path, sizeof(path), "/proc/%d/sched", pid); + f = fopen(path, "r"); + if (!f) + return; + + while (fgets(line, sizeof(line), f)) { + if (strstr(line, "core_forceidle_sum")) { + line[strcspn(line, "\n")] = '\0'; + ksft_print_msg("FIFO task %s\n", line); + break; + } + } + fclose(f); +} + +/* Cookied SCHED_FIFO spinner. Only this task gets a cookie. */ +static void fifo_child(int cpu, int ready_fd) +{ + struct sched_param param = { .sched_priority = FIFO_PRIO }; + + if (set_affinity(cpu)) { + ksft_perror("FIFO child sched_setaffinity"); + signal_status(ready_fd, CHILD_ERROR); + } + if (prctl(PR_SCHED_CORE, PR_SCHED_CORE_CREATE, 0, PIDTYPE_PID, 0)) { + ksft_perror("FIFO child PR_SCHED_CORE_CREATE"); + signal_status(ready_fd, CHILD_ERROR); + } + if (sched_setscheduler(0, SCHED_FIFO, ¶m)) { + if (errno == EPERM) + signal_status(ready_fd, CHILD_EPERM); + ksft_perror("FIFO child sched_setscheduler"); + signal_status(ready_fd, CHILD_ERROR); + } + signal_status(ready_fd, CHILD_READY); + spin_forever(); +} + +/* Uncookied CFS spinner on the FIFO task's SMT sibling. */ +static void cfs_child(int cpu, int ready_fd) +{ + if (set_affinity(cpu)) { + ksft_perror("CFS child sched_setaffinity"); + signal_status(ready_fd, CHILD_ERROR); + } + signal_status(ready_fd, CHILD_READY); + spin_forever(); +} + +static char wait_ready(int fd) +{ + char status; + + if (read(fd, &status, 1) != 1) { + ksft_perror("read from readiness pipe"); + return CHILD_ERROR; + } + + return status; +} + +static void kill_child(pid_t *pid) +{ + if (*pid <= 0) + return; + kill(*pid, SIGKILL); + waitpid(*pid, NULL, 0); + *pid = -1; +} + +int main(void) +{ + double fifo_runtime, cfs_start, cfs_end, t_start, t_end, share, want; + unsigned long long runtime, period; + pid_t fifo_pid = -1, cfs_pid = -1; + int fifo_ready[2], cfs_ready[2]; + unsigned long long cookie; + int sib0, sib1; + char status; + + ksft_print_header(); + ksft_set_plan(1); + + if (read_sibling_pair(&sib0, &sib1)) { + ksft_test_result_skip("CPU0 has no SMT sibling\n"); + ksft_finished(); + } + ksft_print_msg("SMT siblings: CPU%d (FIFO) and CPU%d (CFS)\n", sib0, sib1); + + if (prctl(PR_SCHED_CORE, PR_SCHED_CORE_GET, 0, PIDTYPE_PID, + (unsigned long)&cookie)) { + ksft_test_result_skip("core scheduling unavailable: %s\n", + strerror(errno)); + ksft_finished(); + } + + if (read_fair_server(sib1, &runtime, &period)) { + ksft_test_result_skip("cannot read " FAIR_SERVER "/cpu%d, debugfs not mounted?\n", + sib1); + ksft_finished(); + } + if (!runtime || !period) { + ksft_test_result_skip("fair server on CPU%d is disabled (%llu/%llu)\n", + sib1, runtime, period); + ksft_finished(); + } + ksft_print_msg("CPU%d fair server reservation: %llu/%llu ns = %.3f%%\n", + sib1, runtime, period, 100.0 * runtime / period); + + if (pipe(fifo_ready) || pipe(cfs_ready)) + ksft_exit_fail_perror("pipe"); + + fifo_pid = fork(); + if (!fifo_pid) { + close(fifo_ready[0]); + close(cfs_ready[0]); + close(cfs_ready[1]); + fifo_child(sib0, fifo_ready[1]); + } else if (fifo_pid < 0) { + ksft_exit_fail_perror("fork FIFO child"); + } + close(fifo_ready[1]); + + status = wait_ready(fifo_ready[0]); + close(fifo_ready[0]); + if (status != CHILD_READY) { + kill_child(&fifo_pid); + close(cfs_ready[0]); + close(cfs_ready[1]); + if (status == CHILD_EPERM) { + ksft_test_result_skip("need privileges for SCHED_FIFO\n"); + ksft_finished(); + } + ksft_exit_fail_msg("FIFO child setup failed\n"); + } + + cfs_pid = fork(); + if (!cfs_pid) { + close(cfs_ready[0]); + cfs_child(sib1, cfs_ready[1]); + } else if (cfs_pid < 0) { + kill_child(&fifo_pid); + ksft_exit_fail_perror("fork CFS child"); + } + close(cfs_ready[1]); + + status = wait_ready(cfs_ready[0]); + close(cfs_ready[0]); + if (status != CHILD_READY) { + kill_child(&cfs_pid); + kill_child(&fifo_pid); + ksft_exit_fail_msg("CFS child setup failed\n"); + } + + cfs_start = process_runtime(cfs_pid); + t_start = monotonic_now(); + sleep(RUN_TIME); + t_end = monotonic_now(); + cfs_end = process_runtime(cfs_pid); + fifo_runtime = process_runtime(fifo_pid); + + print_forced_idle(fifo_pid); + kill_child(&cfs_pid); + kill_child(&fifo_pid); + + if (cfs_start < 0 || cfs_end < 0 || fifo_runtime < 0) + ksft_exit_fail_msg("cannot read /proc//stat\n"); + if (t_start < 0 || t_end <= t_start) + ksft_exit_fail_msg("cannot read CLOCK_MONOTONIC\n"); + + share = (cfs_end - cfs_start) / (t_end - t_start); + want = MIN_SHARE_OF_RESERVATION * runtime / period; + + ksft_print_msg("FIFO task ran %.3fs, CFS task ran %.3fs over %.3fs\n", + fifo_runtime, cfs_end - cfs_start, t_end - t_start); + ksft_print_msg("CFS share of CPU%d: %.3f%%, need %.3f%%\n", + sib1, share * 100, want * 100); + + ksft_test_result(share >= want, + "CFS task gets the fair server reservation while forced idle\n"); + + ksft_finished(); +} From b704f052aa943903be7140fa8bd805b1de9d5afb Mon Sep 17 00:00:00 2001 From: Ibrahim Elshahed Date: Fri, 20 Nov 2026 10:58:20 +0000 Subject: [PATCH 1410/2102] sched/core: Clear a stale rq->core_pick after dequeue A core-wide selection leaves the task chosen for each sibling in that sibling's rq->core_pick until pick_next_task() on the sibling consumes it. If the task is dequeued before the sibling consumes it, for example migrated away, the pointer stays until the sibling's next pick_next_task() overwrites it. Until then __sched_core_account_forceidle() keeps charging forced idle time to a task that no longer runs there and, with schedstats enabled, to its cgroup, even after the task has exited. Clear rq->core_pick and rq->core_dl_server in sched_core_dequeue() once the pending pick is dequeued, and don't wait for pick_next_task() to overwrite them. Fixes: 4feee7d12603 ("sched/core: Forced idle accounting") Co-developed-by: Roman Kagan Signed-off-by: Roman Kagan Signed-off-by: Ibrahim Elshahed Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261120105822.7770-2-lshahed@amazon.de --- kernel/sched/core.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/kernel/sched/core.c b/kernel/sched/core.c index 42b99be948706d..4b1d36c917c087 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -328,6 +328,15 @@ void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) RB_CLEAR_NODE(&p->core_node); } + /* + * @p left this rq, so it can no longer be the pick a sibling made. + * This also avoids forced idle accounting charging it once it is gone. + */ + if (rq->core_pick == p) { + rq->core_pick = NULL; + rq->core_dl_server = NULL; + } + /* * Migrating the last task off the cpu, with the cpu in forced idle * state. Reschedule to create an accounting edge for forced idle, From 029c90c449bfe0e200cdeb24c5b1a775764c0006 Mon Sep 17 00:00:00 2001 From: Ibrahim Elshahed Date: Fri, 20 Nov 2026 10:58:21 +0000 Subject: [PATCH 1411/2102] sched/core: Don't take the idle fast path while the core is forced idle Since v6.12, with commit 3dcac251b066 ("sched/core: Introduce SM_IDLE and an idle re-entry fast-path in __schedule()"), an idle CPU with an empty runqueue skips pick_next_task() when it is rescheduled. Under core scheduling that pick also ends or re-examines the core's forced idle. A core-wide selection chooses a task for an idle sibling and reschedules it. If the chosen task is migrated away before the sibling schedules and it was the sibling's only task, the sibling goes back to idle through the fast path. When that selection also forced the other sibling idle, because its runnable tasks did not match the chosen task's cookie, the core stays forced idle with nothing running on it, and two things go wrong: - Without the previous patch, the idle sibling's rq->core_pick keeps pointing at the migrated task, and with schedstats enabled the forced idle accounting keeps writing through it, even after the task and its cgroup are freed: BUG: unable to handle page fault for address: ffff8d6b205f7018 #PF: supervisor write access in kernel mode #PF: error_code(0x0002) - not-present page RIP: 0010:__cgroup_account_cputime_field+0x3c/0x70 Call Trace: __sched_core_account_forceidle+0xd8/0x140 __schedule+0x1390/0x18d0 schedule_idle+0x1a/0x30 cpu_startup_entry+0x29/0x30 start_secondary+0x11e/0x140 - The forced-idle sibling keeps waiting with runnable tasks until some unrelated event reschedules the core. Likewise, when the forced-idle CPU itself loses its last task, the reschedule that sched_core_dequeue() sends to end the forced idle also ends in the fast path. Take the SM_IDLE fast path only when the core is not forced idle. A pending rq->core_pick needs no check of its own: the previous patch clears it when the picked task is dequeued, so a CPU with an empty runqueue has none. Fixes: 3dcac251b066 ("sched/core: Introduce SM_IDLE and an idle re-entry fast-path in __schedule()") Co-developed-by: Roman Kagan Signed-off-by: Roman Kagan Signed-off-by: Ibrahim Elshahed Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261120105822.7770-3-lshahed@amazon.de --- kernel/sched/core.c | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/kernel/sched/core.c b/kernel/sched/core.c index 4b1d36c917c087..b2f6b998aa1bc1 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -347,6 +347,15 @@ void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) resched_curr(rq); } +/* + * An idle CPU with an empty runqueue must still call pick_next_task() while + * the core is forced idle. Only that pick ends or re-examines the forced idle. + */ +static inline bool sched_core_idle_needs_pick(struct rq *rq) +{ + return sched_core_enabled(rq) && rq->core->core_forceidle_count; +} + static int sched_task_is_throttled(struct task_struct *p, int cpu) { if (p->sched_class->task_is_throttled) @@ -550,6 +559,7 @@ void sched_core_put(void) static inline void sched_core_enqueue(struct rq *rq, struct task_struct *p) { } static inline void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) { } +static inline bool sched_core_idle_needs_pick(struct rq *rq) { return false; } #endif /* !CONFIG_SCHED_CORE */ @@ -7290,8 +7300,13 @@ static void __sched notrace __schedule(int sched_mode) */ prev_state = READ_ONCE(prev->__state); if (sched_mode == SM_IDLE) { - /* SCX must consult the BPF scheduler to tell if rq is empty */ - if (!rq->nr_running && !scx_enabled()) { + /* + * SCX must consult the BPF scheduler to tell if rq is empty, + * and core scheduling may need pick_next_task() to end forced + * idle. + */ + if (!rq->nr_running && !scx_enabled() && + !sched_core_idle_needs_pick(rq)) { next = prev; rq->next_class = &idle_sched_class; goto picked; From f4eb2ace3efdd8b6e3b0946bbd316166edb1a51e Mon Sep 17 00:00:00 2001 From: Fushuai Wang Date: Fri, 20 Nov 2026 13:16:25 +0800 Subject: [PATCH 1412/2102] sched/core: Fix a TOCTOU bug in sched_non_preferred_cpu_push_stop() sched_push_current_non_preferred_cpu() is called in IRQ context. It checks is_migration_disabled() before queuing the stopper. migrate_disable() sets p->migration_disabled in preempt_disable() section. An IRQ can hit after preempt_disable() but before p->migration_disabled=1. After the IRQ returns, the task cannot be preempted by stopper because preemption is disabled, so it finishes setting p->migration_disabled=1 before the stopper runs. It may be like: task context: IRQ context: migrate_disable() preempt_disable() is_migration_disabled() migration_disabled = 1 preempt_enable() So recheck is_migration_disabled() in sched_non_preferred_cpu_push_stop() before calling __migrate_task(). The stack may be like: WARNING: kernel/sched/core.c:3432 at set_task_cpu+0x1b8/0xdf0, CPU#21: migration/21/152 CPU: 21 UID: 0 PID: 152 Comm: migration/21 Tainted: G W O 7.4.0-rc1 #3 PREEMPT(lazy) Stopper: sched_non_preferred_cpu_push_stop+0x0/0xb10 <- sched_push_current_non_preferred_cpu+0x6a6/0x9a0 RIP: 0010:set_task_cpu+0x1b8/0xdf0 Call Trace: ? set_task_cpu+0x5/0xdf0 move_queued_task+0xfc/0x650 ? is_cpu_allowed+0x341/0x820 ? __this_cpu_preempt_check+0x13/0x20 sched_non_preferred_cpu_push_stop+0x7b7/0xb10 ? __this_cpu_preempt_check+0x13/0x20 ? __pfx_sched_non_preferred_cpu_push_stop+0x10/0x10 ? __pfx_sched_non_preferred_cpu_push_stop+0x10/0x10 ? sched_non_preferred_cpu_push_stop+0x5/0xb10 ? __pfx_sched_non_preferred_cpu_push_stop+0x10/0x10 cpu_stopper_thread+0x205/0x410 ? smpboot_thread_fn+0x307/0xa60 ? __pfx_cpu_stopper_thread+0x10/0x10 smpboot_thread_fn+0x352/0xa60 ? __pfx_smpboot_thread_fn+0x10/0x10 kthread+0x3a6/0x4d0 ? __pfx_kthread+0x10/0x10 ret_from_fork+0x68e/0xb40 ? __pfx_ret_from_fork+0x10/0x10 ? __kasan_check_read+0x11/0x20 ? __switch_to+0x592/0x1210 ? __pfx_kthread+0x10/0x10 ret_from_fork_asm+0x1a/0x30 Fixes: 74699f56ebcf ("sched/core: Push current task from non preferred CPU") Suggested-by: Peter Zijlstra Signed-off-by: Fushuai Wang Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Reviewed-by: Shrikanth Hegde Link: https://patch.msgid.link/20261120051625.50133-1-fushuai.wang@linux.dev --- kernel/sched/core.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/kernel/sched/core.c b/kernel/sched/core.c index b2f6b998aa1bc1..c9890ed35df7c8 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -11354,7 +11354,8 @@ static int sched_non_preferred_cpu_push_stop(void *arg) rq->npc_push_work_pending = false; update_rq_clock(rq); - if (task_rq(p) == rq && task_on_rq_queued(p)) { + if (task_rq(p) == rq && task_on_rq_queued(p) && + !is_migration_disabled(p)) { struct rq *dest_rq = __migrate_task(rq, &rf, p, cpu); if (rq != dest_rq) @@ -11395,6 +11396,11 @@ void sched_push_current_non_preferred_cpu(struct rq *rq) if (rq->npc_push_work_pending) return; + /* + * Racy: is_migration_disabled() isn't stable in IRQ + * context and can race with migrate_disable(). The stopper + * should recheck it. + */ if (is_migration_disabled(push_task)) return; From af1a4ab4bf3bcb969ad5ee9e7fca1d23703adf32 Mon Sep 17 00:00:00 2001 From: Bart Van Assche Date: Wed, 18 Nov 2026 15:09:57 -0800 Subject: [PATCH 1413/2102] bit_spinlock: Fix the __bitlock() macro definition Surround the 'bitnum' argument and the entire __bitlock() macro expansion with parentheses because 'bitnum' could be an expression that includes an operator with a lower precedence than the addition operator (e.g. the exclusive-or operator) and to prevent operator precedence issues in callers. Fixes: eb7d96a13bf4 ("bit_spinlock: Support Clang's context analysis") Signed-off-by: Bart Van Assche Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Acked-by: Marco Elver Link: https://patch.msgid.link/38cdec9322fa710f84c018e0b318894c6234c411.1795043161.git.bvanassche@acm.org --- include/linux/bit_spinlock.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/linux/bit_spinlock.h b/include/linux/bit_spinlock.h index 7869a6e59b6a6c..c31d4f4d09ee46 100644 --- a/include/linux/bit_spinlock.h +++ b/include/linux/bit_spinlock.h @@ -17,7 +17,7 @@ * static analysis can use. */ context_lock_struct(__context_bitlock) { }; -#define __bitlock(bitnum, addr) (struct __context_bitlock *)(bitnum + (addr)) +#define __bitlock(bitnum, addr) ((struct __context_bitlock *)((bitnum) + (addr))) /* * bit-based spin_lock() From da198fa75403535626b91cfddff7c2189b5f894f Mon Sep 17 00:00:00 2001 From: Bart Van Assche Date: Wed, 18 Nov 2026 15:09:58 -0800 Subject: [PATCH 1414/2102] cleanup: Disable context analysis for __free() helpers The __free_##_name() helper functions defined by DEFINE_FREE() call the free expression that has been passed to DEFINE_FREE(). If that expression releases a lock, e.g. because it is a call to an unlock function, the Clang thread-safety analyzer complains because it cannot know that the variable that is passed to the helper function holds a lock. This is needed by: - __drm_for_each_bridge_in_chain_cleanup (include/drm/drm_bridge.h), used by drm_for_each_bridge_in_chain_scoped() and drm_for_each_bridge_in_chain_from_scoped(). - netdev_unlock (net/core/dev.h), used by for_each_netdev_lock_scoped(). - netdev_unlock_ops_compat (net/core/dev.h), used by for_each_netdev_lock_ops_compat_scoped(). Disable context analysis for the __free() helper functions via __context_unsafe(). Signed-off-by: Bart Van Assche Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Acked-by: Marco Elver Link: https://patch.msgid.link/d87cfee3aa630885cbdb95f0f918e86a1263c2ec.1795043161.git.bvanassche@acm.org --- include/linux/cleanup.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/include/linux/cleanup.h b/include/linux/cleanup.h index 1fb8058b897d4a..1e09aead4b080e 100644 --- a/include/linux/cleanup.h +++ b/include/linux/cleanup.h @@ -207,8 +207,10 @@ * Without the NULL test it turns into a mess and the compiler can't help us. */ -#define DEFINE_FREE(_name, _type, _free) \ - static __always_inline void __free_##_name(void *p) { _type _T = *(_type *)p; _free; } +#define DEFINE_FREE(_name, _type, _free) \ + static __always_inline void __free_##_name(void *p) \ + __context_unsafe(/* _free may release a lock */) \ + { _type _T = *(_type *)p; _free; } #define __free(_name) __cleanup(__free_##_name) From e2652119b5944e7732ff856ba8057afaa28f5ac8 Mon Sep 17 00:00:00 2001 From: Bart Van Assche Date: Wed, 18 Nov 2026 15:09:59 -0800 Subject: [PATCH 1415/2102] srcu: Make the srcu_dereference_check() reader lock check conditional Users of srcu_dereference_check() must either hold an SRCU reader lock or satisfy the lockdep condition 'c', e.g. by holding the update-side lock. However, srcu_dereference_check() calls __srcu_read_lock_must_hold(), which tells the Clang context analyzer that the SRCU reader lock must be held. That requirement is too strict for update-side callers. Hence, only call __srcu_read_lock_must_hold() from srcu_dereference_check() if 'c' is the compile-time constant 0, i.e. if there is no update-side protection. Keep the fake RCU acquire and release around __rcu_dereference_check() and also keep the runtime lockdep check in srcu_dereference_check(). Use const_true() instead of __builtin_constant_p() to test whether 'c' is the constant 0. const_true() is based on __is_constexpr(), a sizeof() trick that the compiler front end always evaluates, so the Clang context analysis sees an integer constant expression. If 'c' is a plain variable, function argument or structure member, Clang may leave __builtin_constant_p(c) for the optimizer to decide. The context analysis then considers the __srcu_read_lock_must_hold() call reachable and reports a false positive. Additionally, const_true() never evaluates a non-constant 'c' at runtime, so the runtime behavior does not change. srcu_dereference() passes 0 as 'c' and hence gets the compile-time check automatically. srcu_dereference_notrace() does not accept a lockdep condition and hence may only be used by SRCU readers. Since it passes 1 as 'c', call __srcu_read_lock_must_hold() explicitly from srcu_dereference_notrace() such that the Clang context analysis keeps verifying at compile time that its callers hold the SRCU reader lock. Fixes: f0b7ce22d718 ("srcu: Support Clang's context analysis") Suggested-by: Paul E. McKenney Signed-off-by: Bart Van Assche Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Reviewed-by: Paul E. McKenney Link: https://patch.msgid.link/459250d4f2a6aa38ebab3fb51f6d4a63815bb4a1.1795043161.git.bvanassche@acm.org --- include/linux/srcu.h | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/include/linux/srcu.h b/include/linux/srcu.h index d4dcaeb83e2b63..380b5964fcb499 100644 --- a/include/linux/srcu.h +++ b/include/linux/srcu.h @@ -280,6 +280,10 @@ static inline int srcu_read_lock_held(const struct srcu_struct *ssp) * with __guarded_by(ssp) as it would complicate annotations for writers, we * choose the following strategy: srcu_dereference_check() calls this helper * that checks that the passed ssp is held, and then fake-acquires 'RCU'. + * srcu_dereference_check() only calls this helper if @c is the compile-time + * constant 0 because otherwise its callers may satisfy the condition @c + * instead of holding ssp, e.g. on the update side. srcu_dereference_notrace() + * passes 1 as @c and hence calls this helper explicitly. */ static inline void __srcu_read_lock_must_hold(const struct srcu_struct *ssp) __must_hold_shared(ssp) { } @@ -297,7 +301,8 @@ static inline void __srcu_read_lock_must_hold(const struct srcu_struct *ssp) __m */ #define srcu_dereference_check(p, ssp, c) \ ({ \ - __srcu_read_lock_must_hold(ssp); \ + if (const_true(!(c))) \ + __srcu_read_lock_must_hold(ssp); \ __acquire_shared_ctx_lock(RCU); \ __auto_type __v = __rcu_dereference_check((p), __UNIQUE_ID(rcu), \ (c) || srcu_read_lock_held(ssp), __rcu); \ @@ -323,7 +328,11 @@ static inline void __srcu_read_lock_must_hold(const struct srcu_struct *ssp) __m * @ssp: pointer to the srcu_struct, which is used to check that we * really are in an SRCU read-side critical section. */ -#define srcu_dereference_notrace(p, ssp) srcu_dereference_check((p), (ssp), 1) +#define srcu_dereference_notrace(p, ssp) \ +({ \ + __srcu_read_lock_must_hold(ssp); \ + srcu_dereference_check((p), (ssp), 1); \ +}) /** * srcu_read_lock - register a new reader for an SRCU-protected structure. From b9fd2f07df77076f83a58fe7a5640cbcbc5a61ff Mon Sep 17 00:00:00 2001 From: Takashi Iwai Date: Mon, 23 Nov 2026 10:34:26 +0100 Subject: [PATCH 1416/2102] Revert "ALSA: hda/realtek: Fix silent speaker on Higole F9B" This reverts commit 2a8ee6897302ca12ff39e8eb180503956797c60c. We've received a regression report due to this commit, and it turned out that the PCI SSID for this quirk entry is too generic (10ec:111e) that may match with several different models. Usually a workaround would be to apply the quirk for a more unique ID such as codec SSID, but in this case, unfortunately, the codec SSID is also 10ec:111e, so BIOS is in a premature state. For addressing the regression, revert the change for now. Fixes: 2a8ee6897302 ("ALSA: hda/realtek: Fix silent speaker on Higole F9B") Reported-by: Cristian-Marian Fotache Closes: https://lore.kernel.org/CACGjpbf73XdwrG34ffjmYU3ZYuStPpFNXf9w+AGYcTmLyHCN_w@mail.gmail.com Link: https://patch.msgid.link/20261123093436.48511-1-tiwai@suse.de Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 1 - 1 file changed, 1 deletion(-) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index dfdcf8b98c9eb4..87a47f238e4c14 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -8363,7 +8363,6 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x10cf, 0x1757, "Lifebook E752", ALC269_FIXUP_LIFEBOOK_HP_PIN), SND_PCI_QUIRK(0x10cf, 0x1845, "Lifebook U904", ALC269_FIXUP_LIFEBOOK_EXTMIC), SND_PCI_QUIRK(0x10ec, 0x10f2, "Intel Reference board", ALC700_FIXUP_INTEL_REFERENCE), - SND_PCI_QUIRK(0x10ec, 0x111e, "Higole F9B", ALC290_FIXUP_MONO_SPEAKERS), SND_PCI_QUIRK(0x10ec, 0x118c, "Medion EE4254 MD62100", ALC256_FIXUP_MEDION_HEADSET_NO_PRESENCE), SND_PCI_QUIRK(0x10ec, 0x119e, "Positivo SU C1400", ALC269_FIXUP_ASPIRE_HEADSET_MIC), SND_PCI_QUIRK(0x10ec, 0x11bc, "VAIO VJFE-IL", ALC269_FIXUP_LIMIT_INT_MIC_BOOST), From 3896ae4adf5ffc11ffd0f7f42c3923e8dc195e75 Mon Sep 17 00:00:00 2001 From: Antonio Quartulli Date: Sat, 14 Nov 2026 00:28:41 +0100 Subject: [PATCH 1417/2102] tun: complete the zerocopy buffer of packets consumed by XDP When vhost-net passes a zerocopy buffer that tun_get_user() does not use, because the packet spans too many pages, the packet is copied and the buffer completed. If the copy goes through build_skb() and native XDP consumes the packet (DROP, TX or REDIRECT), tun_get_user() returns without completing it: vhost-net never gets the descriptor back, and closing the vhost-net device then blocks forever. Complete it in that case too, as copied. Reproducer: vhost-net with experimental_zcopytx=1 on a tap device with a native XDP_DROP program; send one 806-byte packet as 40 descriptors, each in its own page. The descriptor is never returned and close() of the vhost-net fd does not return. With the patch it is returned. Tested in an x86-64 VM with the reproducer and the tun kselftest. Found by the Sashiko AI review bot, as a pre-existing issue while reviewing an unrelated tun patch, and confirmed with the reproducer. Link: https://sashiko.dev/#/bug/linux-f9997fb6-303f-41d6-93e2-60c392b1856f Fixes: 761876c857cb ("tap: XDP support") Signed-off-by: Antonio Quartulli Link: https://patch.msgid.link/20261113232843.2338734-1-antonio@mandelbit.com Signed-off-by: Paolo Abeni --- drivers/net/tun.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/drivers/net/tun.c b/drivers/net/tun.c index d4870bdc156f4c..d726c4523fe649 100644 --- a/drivers/net/tun.c +++ b/drivers/net/tun.c @@ -1871,8 +1871,15 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, err = PTR_ERR_OR_ZERO(skb); if (err) goto drop; - if (!skb) + if (!skb) { + /* consumed by XDP, after copying */ + if (msg_control) { + struct ubuf_info *uarg = msg_control; + + uarg->ops->complete(NULL, uarg, false); + } return total_len; + } } else { if (!zerocopy) { copylen = len; From b633d6547dd0ebf07e2798ca7a754625489e21bc Mon Sep 17 00:00:00 2001 From: Zhu Jun Date: Thu, 19 Nov 2026 15:59:12 +0800 Subject: [PATCH 1418/2102] ASoC: max98520: Handle reset and register restore errors on resume max98520_resume() ignores errors from both the software reset and the register cache sync. A failed I2C transfer can therefore leave the amplifier incorrectly configured while resume reports success. Restore the register cache only after the reset write succeeds. On either error, restore cache-only mode and return the error. Fixes: f88ee76b8645 ("ASoC: max98520: add max98520 audio amplifier driver") Signed-off-by: Zhu Jun Link: https://patch.msgid.link/20261119075912.50227-1-zhujun2@cmss.chinamobile.com Signed-off-by: Mark Brown --- sound/soc/codecs/max98520.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/sound/soc/codecs/max98520.c b/sound/soc/codecs/max98520.c index 56e559db88de9d..a1996568dda446 100644 --- a/sound/soc/codecs/max98520.c +++ b/sound/soc/codecs/max98520.c @@ -643,11 +643,16 @@ static int max98520_suspend(struct device *dev) static int max98520_resume(struct device *dev) { struct max98520_priv *max98520 = dev_get_drvdata(dev); + int ret; regcache_cache_only(max98520->regmap, false); - regmap_write(max98520->regmap, MAX98520_R2000_SW_RESET, 1); - regcache_sync(max98520->regmap); - return 0; + ret = regmap_write(max98520->regmap, MAX98520_R2000_SW_RESET, 1); + if (!ret) + ret = regcache_sync(max98520->regmap); + if (ret) + regcache_cache_only(max98520->regmap, true); + + return ret; } static const struct dev_pm_ops max98520_pm = { From 354e4d6f907ad7a60377bf817c700a674f063044 Mon Sep 17 00:00:00 2001 From: Dean Sellers Date: Wed, 18 Nov 2026 18:03:21 +1100 Subject: [PATCH 1419/2102] gpio: pca953x: restore output registers before direction on resume pca953x_regcache_sync() restores the direction registers before the output registers. If the chip lost power across suspend, it comes back with every line an input and its output registers at their power-on value, which is all-high on most of these parts. Restoring direction first turns the configured lines back into outputs while the output registers still hold that value. Every line programmed low is then driven high for the duration of the direction write and the output write that follows. Where those lines drive a load, there is potential for a spurious output. Restore output first, while the lines are still inputs, and direction second. This matches device_pca95xx_init(), which already writes output before direction when bringing the chip up at probe. Fixes: b76574300504 ("gpio: pca953x: Restore registers after suspend/resume cycle") Cc: stable@vger.kernel.org Signed-off-by: Dean Sellers Link: https://patch.msgid.link/20261118070321.2557621-1-dean@sellers.id.au Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-pca953x.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/drivers/gpio/gpio-pca953x.c b/drivers/gpio/gpio-pca953x.c index b662bcf7b9be8b..c90371eaa10c08 100644 --- a/drivers/gpio/gpio-pca953x.c +++ b/drivers/gpio/gpio-pca953x.c @@ -1337,20 +1337,23 @@ static int pca953x_regcache_sync(struct pca953x_chip *chip) u8 regaddr; /* - * The ordering between direction and output is important, - * sync these registers first and only then sync the rest. + * The ordering between output and direction is important: restore + * the output levels while the lines are still inputs, and only then + * turn them into outputs. Restoring direction first would drive + * every output at the power-on output value until the output + * registers are written. Sync these first, then the rest. */ - regaddr = chip->recalc_addr(chip, chip->regs->direction, 0); + regaddr = chip->recalc_addr(chip, chip->regs->output, 0); ret = regcache_sync_region(chip->regmap, regaddr, regaddr + NBANK(chip) - 1); if (ret) { - dev_err(dev, "Failed to sync GPIO dir registers: %d\n", ret); + dev_err(dev, "Failed to sync GPIO out registers: %d\n", ret); return ret; } - regaddr = chip->recalc_addr(chip, chip->regs->output, 0); + regaddr = chip->recalc_addr(chip, chip->regs->direction, 0); ret = regcache_sync_region(chip->regmap, regaddr, regaddr + NBANK(chip) - 1); if (ret) { - dev_err(dev, "Failed to sync GPIO out registers: %d\n", ret); + dev_err(dev, "Failed to sync GPIO dir registers: %d\n", ret); return ret; } From 0b3f1876d6db7fad0391ce714b315269b0dd5758 Mon Sep 17 00:00:00 2001 From: Zhu Jun Date: Fri, 20 Nov 2026 14:18:27 +0800 Subject: [PATCH 1420/2102] tools: gpio-hammer: Accept the maximum number of line offsets The offset count is incremented for every -o option, but the final check rejects the maximum itself and reports one extra offset. Only reject counts above the maximum and report the actual count. Fixes: d1ee7e1f5c91 ("tools: gpio-hammer: Avoid potential overflow in main") Signed-off-by: Zhu Jun Link: https://patch.msgid.link/20261120061827.98066-1-zhujun2@cmss.chinamobile.com Signed-off-by: Bartosz Golaszewski --- tools/gpio/gpio-hammer.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/gpio/gpio-hammer.c b/tools/gpio/gpio-hammer.c index 1a21e5460242e6..df6f71e48c59cb 100644 --- a/tools/gpio/gpio-hammer.c +++ b/tools/gpio/gpio-hammer.c @@ -159,10 +159,10 @@ int main(int argc, char **argv) } } - if (i >= GPIOHANDLES_MAX) { + if (i > GPIOHANDLES_MAX) { fprintf(stderr, "Only %d occurrences of '-o' are allowed, %d were found\n", - GPIOHANDLES_MAX, i + 1); + GPIOHANDLES_MAX, i); return -1; } From 04573b260599414672d39439929c47cad38aec7c Mon Sep 17 00:00:00 2001 From: Zhu Jun Date: Thu, 19 Nov 2026 15:59:06 +0800 Subject: [PATCH 1421/2102] ASoC: es9356: Handle register cache sync failures on resume The SoundWire resume callback reports success even if regcache_sync() fails, leaving the codec with a partially restored register state. Restore cache-only mode on a sync error and return the error to the PM core. Fixes: 5d9cb740cd38 ("ASoC: es9356-sdca: Add ES9356 SDCA driver") Signed-off-by: Zhu Jun Link: https://patch.msgid.link/20261119075906.50214-1-zhujun2@cmss.chinamobile.com Signed-off-by: Mark Brown --- sound/soc/codecs/es9356.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/sound/soc/codecs/es9356.c b/sound/soc/codecs/es9356.c index 74c8978b534790..cc69336dff79ea 100644 --- a/sound/soc/codecs/es9356.c +++ b/sound/soc/codecs/es9356.c @@ -1204,8 +1204,11 @@ static int es9356_sdca_dev_resume(struct device *dev) } regcache_cache_only(es9356->regmap, false); - regcache_sync(es9356->regmap); - return 0; + ret = regcache_sync(es9356->regmap); + if (ret) + regcache_cache_only(es9356->regmap, true); + + return ret; } static const struct dev_pm_ops es9356_sdca_pm = { From e5aa71cbb40d896d4ed2ccfe09137ea6134545b8 Mon Sep 17 00:00:00 2001 From: Devin Wittmayer Date: Thu, 19 Nov 2026 12:10:38 -0700 Subject: [PATCH 1422/2102] drm/panic: Bring back the kmsg screen fixes lost in a merge Commit b537d87d2632 ("drm/panic: Fix the loop that causes kmsg to not display correctly") and commit 1ba640563843 ("drm/panic: Fix kmsg screen hang on a long log line") changed the old panic file. By the time they reached drm-fixes, that code had moved into the helper library, and the merge left the helper as it was. So the panic screen that prints the kernel log hangs again on a long log line, and the machine never reboots. The helper's KUnit suite hangs the same way. Make both changes in the helper. Fixes: 5c3d323984fd ("drm/panic: Move panic display code into helper library") Reported-by: desobei Closes: https://lore.kernel.org/all/PH7PR19MB6658FDBDD012399C6E8D330FAF792@PH7PR19MB6658.namprd19.prod.outlook.com/ Tested-by: desobei Cc: luyuantao Signed-off-by: Devin Wittmayer Reviewed-by: Jocelyn Falempe Link: https://patch.msgid.link/20261119191038.146963-1-lucid_duck@justthetip.ca Signed-off-by: Jocelyn Falempe --- drivers/gpu/drm/drm_panic_helper.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/drm_panic_helper.c b/drivers/gpu/drm/drm_panic_helper.c index 8913c3d22e8d31..385a07ed314bc2 100644 --- a/drivers/gpu/drm/drm_panic_helper.c +++ b/drivers/gpu/drm/drm_panic_helper.c @@ -513,7 +513,8 @@ VISIBLE_IF_KUNIT int drm_panic_helper_draw_screen_kmsg(struct drm_scanout_buffer const struct font_desc *font = get_default_font(sb->width, sb->height, NULL, NULL); struct drm_rect r_screen = DRM_RECT_INIT(0, 0, sb->width, sb->height); struct kmsg_dump_iter iter; - char kmsg_buf[512]; + /* the size printk formats one record into, too big for the stack */ + static char kmsg_buf[2048]; size_t kmsg_len; struct drm_panic_line line; int yoffset; @@ -530,10 +531,15 @@ VISIBLE_IF_KUNIT int drm_panic_helper_draw_screen_kmsg(struct drm_scanout_buffer drm_panic_helper_fill(sb, &r_screen, bg_color); kmsg_dump_rewind(&iter); - while (kmsg_dump_get_buffer(&iter, false, kmsg_buf, sizeof(kmsg_buf), &kmsg_len)) { + while (yoffset >= 0 && kmsg_dump_get_buffer(&iter, false, kmsg_buf, + sizeof(kmsg_buf), &kmsg_len)) { char *start; char *end; + /* a record that does not fit comes back empty, every time */ + if (!kmsg_len) + break; + /* ignore terminating NUL and newline */ start = kmsg_buf + kmsg_len - 2; end = kmsg_buf + kmsg_len - 1; From d5612641c0dac28b7b4fdb4c782208d93742c75c Mon Sep 17 00:00:00 2001 From: Zhu Jun Date: Thu, 19 Nov 2026 15:58:40 +0800 Subject: [PATCH 1423/2102] ASoC: qcom: lpass: Propagate IRQ lookup errors The LPASS platform driver converts all four named IRQ lookup errors to -ENODEV. When an interrupt provider is not ready, platform_get_irq_byname() can return -EPROBE_DEFER. Replacing that error prevents the device core from retrying probe. Return the original error from each lookup. Fixes: c5c8635a0471 ("ASoC: qcom: Add LPASS platform driver") Fixes: 7cb37b7bd0d3 ("ASoC: qcom: Add support for lpass hdmi driver") Fixes: 7d7209557b67 ("ASoC: qcom: Add support for codec dma driver") Signed-off-by: Zhu Jun Link: https://patch.msgid.link/20261119075841.50185-1-zhujun2@cmss.chinamobile.com Signed-off-by: Mark Brown --- sound/soc/qcom/lpass-platform.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sound/soc/qcom/lpass-platform.c b/sound/soc/qcom/lpass-platform.c index dad4becf7579e0..7f4963d129e5cd 100644 --- a/sound/soc/qcom/lpass-platform.c +++ b/sound/soc/qcom/lpass-platform.c @@ -1281,7 +1281,7 @@ int asoc_qcom_lpass_platform_register(struct platform_device *pdev) drvdata->lpaif_irq = platform_get_irq_byname(pdev, "lpass-irq-lpaif"); if (drvdata->lpaif_irq < 0) - return -ENODEV; + return drvdata->lpaif_irq; /* ensure audio hardware is disabled */ ret = regmap_write(drvdata->lpaif_map, @@ -1322,7 +1322,7 @@ int asoc_qcom_lpass_platform_register(struct platform_device *pdev) } drvdata->rxtxif_irq = platform_get_irq_byname(pdev, "lpass-irq-rxtxif"); if (drvdata->rxtxif_irq < 0) - return -ENODEV; + return drvdata->rxtxif_irq; ret = devm_request_irq(&pdev->dev, drvdata->rxtxif_irq, lpass_platform_rxtxif_irq, 0, "lpass-irq-rxtxif", drvdata); @@ -1341,7 +1341,7 @@ int asoc_qcom_lpass_platform_register(struct platform_device *pdev) drvdata->vaif_irq = platform_get_irq_byname(pdev, "lpass-irq-vaif"); if (drvdata->vaif_irq < 0) - return -ENODEV; + return drvdata->vaif_irq; ret = devm_request_irq(&pdev->dev, drvdata->vaif_irq, lpass_platform_vaif_irq, 0, "lpass-irq-vaif", drvdata); @@ -1362,7 +1362,7 @@ int asoc_qcom_lpass_platform_register(struct platform_device *pdev) if (drvdata->hdmi_port_enable) { drvdata->hdmiif_irq = platform_get_irq_byname(pdev, "lpass-irq-hdmi"); if (drvdata->hdmiif_irq < 0) - return -ENODEV; + return drvdata->hdmiif_irq; ret = devm_request_irq(&pdev->dev, drvdata->hdmiif_irq, lpass_platform_hdmiif_irq, 0, "lpass-irq-hdmi", drvdata); From 7b0c5f0c757cb61e28dc4128633877aaa8f6f9bd Mon Sep 17 00:00:00 2001 From: Zhao Li Date: Wed, 18 Nov 2026 10:57:08 +0800 Subject: [PATCH 1424/2102] net/mlx5e: TC, fix a NULL pointer write in the peer flow error path The peer flow add path hands the duplicated flow over to the origin flow before it looks up the peer entry for the peer vhca_id. When that entry is missing, the function returns -ENODEV, and the caller then deletes the duplicated flow with list_del() on its peer node, a list head that was never initialised and never linked. list_del() on such a node writes through the NULL page. Look the peer entry up before the duplicated flow is created and handed over, so that a missing entry is reported without leaving a duplicated flow behind. The entry cannot change in between: the peer loop in mlx5e_add_fdb_flow() holds the devcom component's read lock, and peer_flows entries are only stored and erased by the pair and unpair events, under its write lock. Found by code review and not reproduced; compile-tested only. AI assistance was used. Fixes: 9d608a40c2d4 ("net/mlx5e: TC, track peer flows in a vhca_id xarray") Signed-off-by: Zhao Li Reviewed-by: Daniel Machon Reviewed-by: Shay Drory Acked-by: Mark Bloch Link: https://patch.msgid.link/20261118025708.86215-1-enderaoelyther@gmail.com Signed-off-by: Paolo Abeni --- drivers/net/ethernet/mellanox/mlx5/core/en_tc.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c b/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c index 1d35c97aea0bc3..011741553f5b94 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c @@ -4631,6 +4631,10 @@ static int mlx5e_tc_add_fdb_peer_flow(struct flow_cls_offload *f, else in_mdev = priv->mdev; + dup_peer_flows = xa_load(&esw->offloads.peer_flows, peer_vhca_id); + if (!dup_peer_flows) + return -ENODEV; + flow_flags |= BIT(MLX5E_TC_FLOW_FLAG_PEER); parse_attr = flow->attr->parse_attr; peer_flow = __mlx5e_add_fdb_flow(peer_priv, f, flow_flags, @@ -4644,9 +4648,6 @@ static int mlx5e_tc_add_fdb_peer_flow(struct flow_cls_offload *f, peer_flow->peer_orig = flow; list_add_tail(&peer_flow->peer_flows, &flow->peer_flows); flow_flag_set(flow, DUP); - dup_peer_flows = xa_load(&esw->offloads.peer_flows, peer_vhca_id); - if (!dup_peer_flows) - return -ENODEV; mutex_lock(&esw->offloads.peer_mutex); list_add_tail(&peer_flow->peer, dup_peer_flows); mutex_unlock(&esw->offloads.peer_mutex); From 8fb5a9464bac6e687c9ca3d164dbe7ec5e9b80bc Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 23 Nov 2026 13:15:01 +0100 Subject: [PATCH 1425/2102] efi: Avoid weak references to arch-specific objects There are two cases where generic EFI code in the kernel proper uses weak references to refer to data objects that an architecture might not define at all. Unlike weak definitions, which guarantee that a definition will ultimately exist, and where the weak attribute only decides which one takes precedence, weak references are permitted to remain unsatisfied. Given that PC relative symbol references in relocatable code cannot reliably produce NULL, this forces the compiler to use a GOT slot when the access is from code. For data references (i.e., statically initialized global pointer variables), it forces the use of a 24 byte RELA entry rather than a single RELR bit for similar reasons. Given that in both cases, only a single architecture does define the symbols, and this is unlikely to change going forward, just replace the weak references with Kconfig #ifdefs. Signed-off-by: Ard Biesheuvel --- drivers/firmware/efi/efi-init.c | 5 +++-- drivers/firmware/efi/efi.c | 8 +++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/drivers/firmware/efi/efi-init.c b/drivers/firmware/efi/efi-init.c index 9f09b0d2daa0b9..58acb5d25adfa6 100644 --- a/drivers/firmware/efi/efi-init.c +++ b/drivers/firmware/efi/efi-init.c @@ -54,7 +54,7 @@ static phys_addr_t __init efi_to_phys(unsigned long addr) return addr; } -extern __weak const efi_config_table_type_t efi_arch_tables[]; +extern const efi_config_table_type_t efi_arch_tables[]; /* * x86 defines its own instance of sysfb_primary_display and uses @@ -123,7 +123,8 @@ static int __init uefi_init(u64 efi_system_table) goto out; } retval = efi_config_parse_tables(config_tables, systab->nr_tables, - efi_arch_tables); + IS_ENABLED(CONFIG_ARM) ? efi_arch_tables + : NULL); early_memunmap(config_tables, table_size); out: diff --git a/drivers/firmware/efi/efi.c b/drivers/firmware/efi/efi.c index 9bc22de0d67ee0..9d73aa5ebf9267 100644 --- a/drivers/firmware/efi/efi.c +++ b/drivers/firmware/efi/efi.c @@ -157,18 +157,20 @@ static ssize_t fw_platform_size_show(struct kobject *kobj, return sysfs_emit(buf, "%d\n", efi_enabled(EFI_64BIT) ? 64 : 32); } -extern __weak const struct kobj_attribute efi_attr_fw_vendor; -extern __weak const struct kobj_attribute efi_attr_runtime; -extern __weak const struct kobj_attribute efi_attr_config_table; +extern const struct kobj_attribute efi_attr_fw_vendor; +extern const struct kobj_attribute efi_attr_runtime; +extern const struct kobj_attribute efi_attr_config_table; static const struct kobj_attribute efi_attr_fw_platform_size = __KOBJ_ATTR_RO(fw_platform_size); static const struct attribute *const efi_subsys_attrs[] = { &efi_attr_systab.attr, &efi_attr_fw_platform_size.attr, +#ifdef CONFIG_X86 &efi_attr_fw_vendor.attr, &efi_attr_runtime.attr, &efi_attr_config_table.attr, +#endif NULL, }; From 809117fc28453aafa7164ad45ea853f900974d08 Mon Sep 17 00:00:00 2001 From: Zhu Jun Date: Fri, 20 Nov 2026 14:20:53 +0800 Subject: [PATCH 1426/2102] tools: gpio: Preserve device listing errors in lsgpio When no chip is selected, lsgpio breaks out of the directory scan on a list_device() failure, then unconditionally resets ret to zero. A chip that cannot be opened or queried is therefore reported as success. Initialize ret to zero before scanning instead, so an empty scan still succeeds and errors from list_device() reach the caller. Fixes: 6d591c46bce0 ("tools/gpio: create GPIO tools") Signed-off-by: Zhu Jun Link: https://patch.msgid.link/20261120062053.98356-1-zhujun2@cmss.chinamobile.com Signed-off-by: Bartosz Golaszewski --- tools/gpio/lsgpio.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tools/gpio/lsgpio.c b/tools/gpio/lsgpio.c index 52a0be45410c97..de2eccc1347964 100644 --- a/tools/gpio/lsgpio.c +++ b/tools/gpio/lsgpio.c @@ -205,7 +205,7 @@ int main(int argc, char **argv) goto error_out; } - ret = -ENOENT; + ret = 0; while (ent = readdir(dp), ent) { if (check_prefix(ent->d_name, "gpiochip")) { ret = list_device(ent->d_name); @@ -214,7 +214,6 @@ int main(int argc, char **argv) } } - ret = 0; if (closedir(dp) == -1) { perror("scanning devices: Failed to close directory"); ret = -errno; From 1eaf27d99938dd30ea7855174b65e37a2503a349 Mon Sep 17 00:00:00 2001 From: Zhu Jun Date: Fri, 20 Nov 2026 14:21:07 +0800 Subject: [PATCH 1427/2102] tools: gpio: Return success after monitoring requested events After reading the requested number of events, monitor_device() returns the positive byte count left in ret by read(). main() passes this value through as the exit status, so a successful invocation with -c reports failure. Clear ret when the event limit is reached, keeping read failures on their existing error paths. Fixes: 97f69747d8b1 ("tools/gpio: add the gpio-event-mon tool") Signed-off-by: Zhu Jun Link: https://patch.msgid.link/20261120062107.98391-1-zhujun2@cmss.chinamobile.com Signed-off-by: Bartosz Golaszewski --- tools/gpio/gpio-event-mon.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/gpio/gpio-event-mon.c b/tools/gpio/gpio-event-mon.c index b70813b0bf8efa..af223e254bc980 100644 --- a/tools/gpio/gpio-event-mon.c +++ b/tools/gpio/gpio-event-mon.c @@ -124,8 +124,10 @@ int monitor_device(const char *device_name, fprintf(stdout, "\n"); i++; - if (i == loops) + if (i == loops) { + ret = 0; break; + } } exit_line_close: From a6ac1eb673fe0a1856a0d3c4281fc65364529dad Mon Sep 17 00:00:00 2001 From: Zhu Jun Date: Thu, 19 Nov 2026 15:57:16 +0800 Subject: [PATCH 1428/2102] ASoC: ak4535: Fix AUX input DAPM routes The AUX input PGA is named "AUX In", but the route from the AUX pin and the Aux Capture Switch route refer to "Aux In". DAPM matches widget names case sensitively, so it cannot add either route. Use the existing widget name in both routes to connect the AUX input to the capture mixer and complete the path to the bypass mixer. Fixes: 796d2ca84859 ("ALSA: ASoC: Add AK4535 driver") Signed-off-by: Zhu Jun Link: https://patch.msgid.link/20261119075716.50110-1-zhujun2@cmss.chinamobile.com Signed-off-by: Mark Brown --- sound/soc/codecs/ak4535.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sound/soc/codecs/ak4535.c b/sound/soc/codecs/ak4535.c index 66ca753e765174..ce877d99569069 100644 --- a/sound/soc/codecs/ak4535.c +++ b/sound/soc/codecs/ak4535.c @@ -237,12 +237,12 @@ static const struct snd_soc_dapm_route ak4535_audio_map[] = { {"Mono 2 Enable", "Switch", "Stereo Mixer"}, /* Aux In */ - {"Aux In", NULL, "AUX"}, + {"AUX In", NULL, "AUX"}, /* ADC */ {"ADC", NULL, "Input Mixer"}, {"Input Mixer", "Mic Capture Switch", "Mic"}, - {"Input Mixer", "Aux Capture Switch", "Aux In"}, + {"Input Mixer", "Aux Capture Switch", "AUX In"}, }; static int ak4535_set_dai_sysclk(struct snd_soc_dai *codec_dai, From 602af7b1c19309330a36ffe787336cb95e040ab1 Mon Sep 17 00:00:00 2001 From: Anastasia Eskova Date: Mon, 23 Nov 2026 11:23:23 +0100 Subject: [PATCH 1429/2102] s390/cert_store: Allocate keyring with link restriction The keyring is linked into the user session keyring on allocation, but keyring_restrict() is only called after all certificates were added. Until then a possessor of the keyring can link arbitrary keys into it. If keyring_restrict() fails, the error is only logged and the keyring stays writable. Allocate the keyring with a restriction which rejects all links, create the certificate keys with KEY_ALLOC_BYPASS_RESTRICTION and drop the late keyring_restrict() call. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Anastasia Eskova Reviewed-by: Jarkko Sakkinen Signed-off-by: Heiko Carstens --- arch/s390/kernel/cert_store.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index e3cc9389a50a46..6f5c63cd907ff3 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -409,6 +409,7 @@ static void cleanup_cs_keys(void) static struct key *create_cs_keyring(void) { + struct key_restriction *restriction; struct key *cs_keyring, *us_keyring; /* Cleanup previous cs_keyring and all associated keys if any. */ @@ -416,13 +417,21 @@ static struct key *create_cs_keyring(void) us_keyring = get_user_session_keyring(); if (IS_ERR(us_keyring)) return NULL; + restriction = kzalloc_obj(*restriction); + if (!restriction) { + key_put(us_keyring); + return NULL; + } + /* Reject all links, the kernel bypasses the restriction. */ + restriction->check = restrict_link_reject; cs_keyring = keyring_alloc(CERT_STORE_KEYRING_NAME, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(), (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_SET_KEEP, - NULL, us_keyring); + restriction, us_keyring); key_put(us_keyring); if (IS_ERR(cs_keyring)) { + kfree(restriction); pr_dbf_msg("Can't allocate cert_store keyring"); return NULL; } @@ -485,7 +494,7 @@ static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce, desc, (u8 *)vce + vce->vce_hdr.vc_offset, vce->vce_hdr.vc_length, (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ, - KEY_ALLOC_NOT_IN_QUOTA); + KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_BYPASS_RESTRICTION); rc = PTR_ERR_OR_ZERO(newkey); if (rc) { @@ -653,14 +662,6 @@ static int add_certificates_to_keyring(struct vcssb *vcssb, struct key *keyring) pr_info("Added %d of %d keys to cert_store keyring", added, count); - /* - * Do not allow to link more keys to certificate store keyring after all - * the VCEs were processed. - */ - rc = keyring_restrict(make_key_ref(keyring, true), NULL, NULL); - if (rc) - pr_dbf_msg("Failed to set restriction to cert_store keyring (%d)", rc); - return 0; } From 23a04cb4f2bdbfc87fc4e1c15450e7f8cfc9842a Mon Sep 17 00:00:00 2001 From: Anastasia Eskova Date: Mon, 23 Nov 2026 11:23:24 +0100 Subject: [PATCH 1430/2102] s390/cert_store: Only allow the kernel to create cert_store_key keys Keys of type cert_store_key can be created by any user with add_key() in any keyring, as the key type has no vet_description() callback. The type is registered whenever CONFIG_CERT_STORE is enabled, even if the machine has no DIAG 320 support. cert_store_key_describe() expects a description in the format created by get_key_description(), i.e. a 64 byte key name followed by the VCE index and the certificate store token. If a key with a shorter description is created, seq_puts() may read beyond the end of the description allocation. Reading /proc/keys may then disclose adjacent kernel heap memory to the user space. Also, a consumer which trusts keys by type can be fooled by keys that were not created from the certificate store. Add a vet_description() callback which only accepts the task currently executing refresh_store(), which creates all valid keys of this type. Fixes: 8cf57d7217c3 ("s390: add support for user-defined certificates") Signed-off-by: Anastasia Eskova Reviewed-by: Jarkko Sakkinen Signed-off-by: Heiko Carstens --- arch/s390/kernel/cert_store.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index 6f5c63cd907ff3..6e518ff3832280 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -46,6 +46,9 @@ static debug_info_t *cert_store_dbf; static debug_info_t *cert_store_hexdump; +/* Task currently running refresh_store(). Written under cs_refresh_lock. */ +static struct task_struct *cs_refresh_task; + #define pr_dbf_msg(fmt, ...) \ debug_sprintf_event(cert_store_dbf, 3, fmt "\n", ## __VA_ARGS__) @@ -148,12 +151,24 @@ static void cert_store_key_describe(const struct key *key, struct seq_file *m) seq_printf(m, ": %u", key->datalen); } +/* + * Only the kernel may create keys of this type. Accept the task which runs + * refresh_store(), as it cannot execute userspace during the refresh. + */ +static int cert_store_key_vet_description(const char *description) +{ + if (READ_ONCE(cs_refresh_task) != current) + return -EPERM; + return 0; +} + /* * Certificate store key type takes over properties of * user key but cannot be updated. */ static struct key_type key_type_cert_store_key = { .name = CERT_STORE_KEY_TYPE_NAME, + .vet_description = cert_store_key_vet_description, .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, @@ -768,6 +783,7 @@ static ssize_t refresh_store(struct kobject *kobj, struct kobj_attribute *attr, if (rc) return rc; + WRITE_ONCE(cs_refresh_task, current); for (retries = 0; retries < DIAG_MAX_RETRIES; retries++) { /* Request certificates from certificate store. */ rc = fill_cs_keyring(); @@ -776,6 +792,7 @@ static ssize_t refresh_store(struct kobject *kobj, struct kobj_attribute *attr, if (rc != -EAGAIN) break; } + WRITE_ONCE(cs_refresh_task, NULL); cs_status_val = rc; mutex_unlock(&cs_refresh_lock); From d4dc896fa2bdfd7d1a78911598a0fa3e3c831d92 Mon Sep 17 00:00:00 2001 From: Randy Dunlap Date: Sun, 22 Nov 2026 16:45:01 -0800 Subject: [PATCH 1431/2102] chardev: GPIO common access methods: repair non-kernel-doc comment Change a "/**" non-kernel-doc comment to a plain C comment "/*" to avoid 21 warnings like these: Warning: ./include/linux/nsc_gpio.h:2 Cannot find identifier on line: nsc_gpio.c Warning: ./include/linux/nsc_gpio.h:4 Cannot find identifier on line: National Semiconductor GPIO common access methods. Warning: ./include/linux/nsc_gpio.h:6 Cannot find identifier on line: struct nsc_gpio_ops abstracts the low-level access Fixes: fe3a168a2ce1 ("[PATCH] chardev: GPIO for SCx200 & PC-8736x: add gpio-ops vtable") Signed-off-by: Randy Dunlap Acked-by: Jim Cromie Acked-by: Linus Walleij Link: https://patch.msgid.link/20261123004501.1771603-1-rdunlap@infradead.org Signed-off-by: Bartosz Golaszewski --- include/linux/nsc_gpio.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/linux/nsc_gpio.h b/include/linux/nsc_gpio.h index d7a04a6e3783a1..342ce97975e8a8 100644 --- a/include/linux/nsc_gpio.h +++ b/include/linux/nsc_gpio.h @@ -1,5 +1,5 @@ /* SPDX-License-Identifier: GPL-2.0 */ -/** +/* nsc_gpio.c National Semiconductor GPIO common access methods. From 18dd7729be0693cd9a8df3f9b19d59f6bfb8079b Mon Sep 17 00:00:00 2001 From: Anupama Kunkulagunta Date: Thu, 19 Nov 2026 12:25:10 +0000 Subject: [PATCH 1432/2102] ASoC: dt-bindings: tegra: Add Tegra268 ADMAIF support Add the Tegra268 ADMAIF compatible. Tegra268 ADMAIF supports five RX and five TX channels. Signed-off-by: Anupama Kunkulagunta Signed-off-by: Sheetal Reviewed-by: Krzysztof Kozlowski Reviewed-by: Jon Hunter Link: https://patch.msgid.link/20261119122511.1324643-2-sheetal@nvidia.com Signed-off-by: Mark Brown --- .../sound/nvidia,tegra210-admaif.yaml | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Documentation/devicetree/bindings/sound/nvidia,tegra210-admaif.yaml b/Documentation/devicetree/bindings/sound/nvidia,tegra210-admaif.yaml index 2ce4049f94acc7..054bacf6023495 100644 --- a/Documentation/devicetree/bindings/sound/nvidia,tegra210-admaif.yaml +++ b/Documentation/devicetree/bindings/sound/nvidia,tegra210-admaif.yaml @@ -27,6 +27,7 @@ properties: - nvidia,tegra210-admaif - nvidia,tegra186-admaif - nvidia,tegra264-admaif + - nvidia,tegra268-admaif - items: - enum: - nvidia,tegra234-admaif @@ -134,6 +135,27 @@ allOf: minItems: 1 maxItems: 64 + - if: + properties: + compatible: + contains: + const: nvidia,tegra268-admaif + then: + properties: + dmas: + description: + DMA channel specifiers, equally divided for Tx and Rx. + minItems: 1 + maxItems: 10 + dma-names: + items: + pattern: "^[rt]x[1-5]$" + description: + Should be "rx1", "rx2" ... "rx5" for DMA Rx channel + Should be "tx1", "tx2" ... "tx5" for DMA Tx channel + minItems: 1 + maxItems: 10 + required: - compatible - reg From e30058ddec9949cda0b6975f1500ed1af6003901 Mon Sep 17 00:00:00 2001 From: Anupama Kunkulagunta Date: Thu, 19 Nov 2026 12:25:11 +0000 Subject: [PATCH 1433/2102] ASoC: tegra: ADMAIF: Add Tegra268 support Tegra268 reuses the Tegra264 ADMAIF register layout but provides only five RX and five TX interfaces. Add the compatible and SoC data for this configuration. Add register defaults and five-entry DAI and control tables. Retain the Tegra264 32-channel per-stream limit and use Tegra268 FIFO defaults. Signed-off-by: Anupama Kunkulagunta Signed-off-by: Sheetal Link: https://patch.msgid.link/20261119122511.1324643-3-sheetal@nvidia.com Signed-off-by: Mark Brown --- sound/soc/tegra/tegra210_admaif.c | 66 +++++++++++++++++++++++++++++++ sound/soc/tegra/tegra210_admaif.h | 18 +++++++++ 2 files changed, 84 insertions(+) diff --git a/sound/soc/tegra/tegra210_admaif.c b/sound/soc/tegra/tegra210_admaif.c index 73be3a67db859f..31c0f893eb20d5 100644 --- a/sound/soc/tegra/tegra210_admaif.c +++ b/sound/soc/tegra/tegra210_admaif.c @@ -184,6 +184,20 @@ static const struct reg_default tegra264_admaif_reg_defaults[] = { {(TEGRA_ADMAIF_GLOBAL_CG_0 + TEGRA264_ADMAIF_GLOBAL_BASE), 0x00000003} }; +static const struct reg_default tegra268_admaif_reg_defaults[] = { + ADMAIF_RX_REG_DEFAULTS(1, TEGRA268), + ADMAIF_RX_REG_DEFAULTS(2, TEGRA268), + ADMAIF_RX_REG_DEFAULTS(3, TEGRA268), + ADMAIF_RX_REG_DEFAULTS(4, TEGRA268), + ADMAIF_RX_REG_DEFAULTS(5, TEGRA268), + ADMAIF_TX_REG_DEFAULTS(1, TEGRA268), + ADMAIF_TX_REG_DEFAULTS(2, TEGRA268), + ADMAIF_TX_REG_DEFAULTS(3, TEGRA268), + ADMAIF_TX_REG_DEFAULTS(4, TEGRA268), + ADMAIF_TX_REG_DEFAULTS(5, TEGRA268), + {(TEGRA_ADMAIF_GLOBAL_CG_0 + TEGRA268_ADMAIF_GLOBAL_BASE), 0x00000003} +}; + static bool tegra_admaif_wr_reg(struct device *dev, unsigned int reg) { struct tegra_admaif *admaif = dev_get_drvdata(dev); @@ -342,6 +356,20 @@ static const struct regmap_config tegra264_admaif_regmap_config = { .cache_type = REGCACHE_FLAT, }; +static const struct regmap_config tegra268_admaif_regmap_config = { + .reg_bits = 32, + .reg_stride = 4, + .val_bits = 32, + .max_register = TEGRA264_ADMAIF_LAST_REG, + .writeable_reg = tegra_admaif_wr_reg, + .readable_reg = tegra_admaif_rd_reg, + .volatile_reg = tegra_admaif_volatile_reg, + .reg_defaults = tegra268_admaif_reg_defaults, + .num_reg_defaults = TEGRA268_ADMAIF_CHANNEL_COUNT * 6 + 1, + .reg_default_cb = regmap_default_zero_cb, + .cache_type = REGCACHE_FLAT, +}; + static int tegra_admaif_runtime_suspend(struct device *dev) { struct tegra_admaif *admaif = dev_get_drvdata(dev); @@ -796,6 +824,14 @@ static struct snd_soc_dai_driver tegra264_admaif_cmpnt_dais[] = { DAI("ADMAIF32", TEGRA264_ADMAIF_MAX_CHANNEL), }; +static struct snd_soc_dai_driver tegra268_admaif_cmpnt_dais[] = { + DAI("ADMAIF1", TEGRA268_ADMAIF_MAX_CHANNEL), + DAI("ADMAIF2", TEGRA268_ADMAIF_MAX_CHANNEL), + DAI("ADMAIF3", TEGRA268_ADMAIF_MAX_CHANNEL), + DAI("ADMAIF4", TEGRA268_ADMAIF_MAX_CHANNEL), + DAI("ADMAIF5", TEGRA268_ADMAIF_MAX_CHANNEL), +}; + static const char * const tegra_admaif_stereo_conv_text[] = { "CH0", "CH1", "AVG", }; @@ -908,6 +944,14 @@ static struct snd_kcontrol_new tegra264_admaif_controls[] = { TEGRA_ADMAIF_CIF_CTRL(32), }; +static struct snd_kcontrol_new tegra268_admaif_controls[] = { + TEGRA_ADMAIF_CIF_CTRL(1), + TEGRA_ADMAIF_CIF_CTRL(2), + TEGRA_ADMAIF_CIF_CTRL(3), + TEGRA_ADMAIF_CIF_CTRL(4), + TEGRA_ADMAIF_CIF_CTRL(5), +}; + static const struct snd_soc_component_driver tegra210_admaif_cmpnt = { .controls = tegra210_admaif_controls, .num_controls = ARRAY_SIZE(tegra210_admaif_controls), @@ -938,6 +982,16 @@ static const struct snd_soc_component_driver tegra264_admaif_cmpnt = { .pointer = tegra_pcm_pointer, }; +static const struct snd_soc_component_driver tegra268_admaif_cmpnt = { + .controls = tegra268_admaif_controls, + .num_controls = ARRAY_SIZE(tegra268_admaif_controls), + .pcm_new = tegra_pcm_new, + .open = tegra_pcm_open, + .close = tegra_pcm_close, + .hw_params = tegra_pcm_hw_params, + .pointer = tegra_pcm_pointer, +}; + static const struct tegra_admaif_soc_data soc_data_tegra210 = { .num_ch = TEGRA210_ADMAIF_CHANNEL_COUNT, .max_stream_ch = TEGRA210_ADMAIF_MAX_CHANNEL, @@ -971,10 +1025,22 @@ static const struct tegra_admaif_soc_data soc_data_tegra264 = { .rx_base = TEGRA264_ADMAIF_RX_BASE, }; +static const struct tegra_admaif_soc_data soc_data_tegra268 = { + .num_ch = TEGRA268_ADMAIF_CHANNEL_COUNT, + .max_stream_ch = TEGRA268_ADMAIF_MAX_CHANNEL, + .cmpnt = &tegra268_admaif_cmpnt, + .dais = tegra268_admaif_cmpnt_dais, + .regmap_conf = &tegra268_admaif_regmap_config, + .global_base = TEGRA268_ADMAIF_GLOBAL_BASE, + .tx_base = TEGRA268_ADMAIF_TX_BASE, + .rx_base = TEGRA268_ADMAIF_RX_BASE, +}; + static const struct of_device_id tegra_admaif_of_match[] = { { .compatible = "nvidia,tegra210-admaif", .data = &soc_data_tegra210 }, { .compatible = "nvidia,tegra186-admaif", .data = &soc_data_tegra186 }, { .compatible = "nvidia,tegra264-admaif", .data = &soc_data_tegra264 }, + { .compatible = "nvidia,tegra268-admaif", .data = &soc_data_tegra268 }, {}, }; MODULE_DEVICE_TABLE(of, tegra_admaif_of_match); diff --git a/sound/soc/tegra/tegra210_admaif.h b/sound/soc/tegra/tegra210_admaif.h index fd9877aa95d386..4290f7a049fb2b 100644 --- a/sound/soc/tegra/tegra210_admaif.h +++ b/sound/soc/tegra/tegra210_admaif.h @@ -31,6 +31,12 @@ #define TEGRA264_ADMAIF_TX_BASE 0x1000 #define TEGRA264_ADMAIF_GLOBAL_BASE 0x2000 #define TEGRA264_ADMAIF_MAX_CHANNEL 32 +/* Tegra268 specific */ +#define TEGRA268_ADMAIF_CHANNEL_COUNT 5 +#define TEGRA268_ADMAIF_RX_BASE TEGRA264_ADMAIF_RX_BASE +#define TEGRA268_ADMAIF_TX_BASE TEGRA264_ADMAIF_TX_BASE +#define TEGRA268_ADMAIF_GLOBAL_BASE TEGRA264_ADMAIF_GLOBAL_BASE +#define TEGRA268_ADMAIF_MAX_CHANNEL TEGRA264_ADMAIF_MAX_CHANNEL /* Global registers */ #define TEGRA_ADMAIF_GLOBAL_ENABLE 0x0 #define TEGRA_ADMAIF_GLOBAL_CG_0 0x8 @@ -204,6 +210,18 @@ #define TEGRA264_ADMAIF_TX30_FIFO_CTRL_REG_DEFAULT 0x01800257 #define TEGRA264_ADMAIF_TX31_FIFO_CTRL_REG_DEFAULT 0x0180025a #define TEGRA264_ADMAIF_TX32_FIFO_CTRL_REG_DEFAULT 0x0180025d +/* Default values - Tegra268 */ +#define TEGRA268_ADMAIF_CIF_REG_DEFAULT 0x00003f00 +#define TEGRA268_ADMAIF_RX1_FIFO_CTRL_REG_DEFAULT 0x00000500 +#define TEGRA268_ADMAIF_RX2_FIFO_CTRL_REG_DEFAULT 0x00000507 +#define TEGRA268_ADMAIF_RX3_FIFO_CTRL_REG_DEFAULT 0x0000050e +#define TEGRA268_ADMAIF_RX4_FIFO_CTRL_REG_DEFAULT 0x00000514 +#define TEGRA268_ADMAIF_RX5_FIFO_CTRL_REG_DEFAULT 0x0000051a +#define TEGRA268_ADMAIF_TX1_FIFO_CTRL_REG_DEFAULT 0x03000500 +#define TEGRA268_ADMAIF_TX2_FIFO_CTRL_REG_DEFAULT 0x03000507 +#define TEGRA268_ADMAIF_TX3_FIFO_CTRL_REG_DEFAULT 0x0300050e +#define TEGRA268_ADMAIF_TX4_FIFO_CTRL_REG_DEFAULT 0x03000514 +#define TEGRA268_ADMAIF_TX5_FIFO_CTRL_REG_DEFAULT 0x0300051a enum { DATA_8BIT, From 0151278a98ca578ea714b7d67ecf2790b32a3cc4 Mon Sep 17 00:00:00 2001 From: Zhu Jun Date: Thu, 19 Nov 2026 15:58:32 +0800 Subject: [PATCH 1434/2102] ASoC: imx-audmix: Balance SAI node references with devres Each successful parse of a SAI phandle in imx_audmix_probe() takes a node reference. The card uses these nodes in the DAI links and codec configuration, but neither probe failure nor device removal releases the references. Register a devres action for each reference as soon as it is acquired. The card registration is managed by the same device, so the actions release the nodes after the card has been unregistered. Fixes: b86ef5367761 ("ASoC: fsl: Add Audio Mixer machine driver") Signed-off-by: Zhu Jun Link: https://patch.msgid.link/20261119075832.50172-1-zhujun2@cmss.chinamobile.com Signed-off-by: Mark Brown --- sound/soc/fsl/imx-audmix.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/sound/soc/fsl/imx-audmix.c b/sound/soc/fsl/imx-audmix.c index 2372cd26ee4716..8d7faa1b9cc310 100644 --- a/sound/soc/fsl/imx-audmix.c +++ b/sound/soc/fsl/imx-audmix.c @@ -10,6 +10,7 @@ * https://www.gnu.org/copyleft/gpl.html */ +#include #include #include #include @@ -123,6 +124,11 @@ static const char *name[][3] = { {"SAI-Playback", "SAI-Playback", "AUDMIX-Capture-0"}, }; +static void imx_audmix_put_node(void *data) +{ + of_node_put(data); +} + static int imx_audmix_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; @@ -206,6 +212,11 @@ static int imx_audmix_probe(struct platform_device *pdev) return ret; } + ret = devm_add_action_or_reset(&pdev->dev, imx_audmix_put_node, + args.np); + if (ret) + return ret; + cpu_pdev = of_find_device_by_node(args.np); if (!cpu_pdev) { dev_err(&pdev->dev, "failed to find SAI platform device\n"); From a233b32f1a124a0b878071aa75f3f85a6f1bccde Mon Sep 17 00:00:00 2001 From: SeungJong Ha Date: Wed, 18 Nov 2026 15:27:44 +0900 Subject: [PATCH 1435/2102] net: release netpoll dev_lock when NETDEV_PRE_UP vetoes an open When netpoll is attached to a device, __dev_open() takes npinfo->dev_lock through netpoll_poll_disable() before calling the NETDEV_PRE_UP notifiers, but returns without releasing it when a notifier vetoes the open. The next attempt to open the device then sleeps in down() with RTNL held, and every other RTNL user blocks behind it. For example, with netconsole on a wireless interface, cfg80211 vetoes the open while the wiphy is rfkill-blocked. Release the lock on that path, as the ndo_open() error path does. Found by an AI coding assistant reviewing __dev_open(). Reproduced in QEMU on an unmodified net tree with mac80211_hwsim built in and netconsole bound to wlan0: ip link set wlan0 down echo 1 > /sys/class/ieee80211/phy0/rfkill0/soft ip link set wlan0 up # fails: RF-kill echo 0 > /sys/class/ieee80211/phy0/rfkill0/soft ip link set wlan0 up # hangs in D state: down __dev_open __dev_change_flags netif_change_flags do_setlink With this patch the last command succeeds. Selftests were not run. Fixes: ca99ca14c95a ("netpoll: protect napi_poll and poll_controller during dev_[open|close]") Cc: stable@vger.kernel.org Signed-off-by: SeungJong Ha Link: https://patch.msgid.link/20261118-netpoll-preup-veto-v1-1-7d3fdf101d3a@gmail.com Signed-off-by: Paolo Abeni --- net/core/dev.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/net/core/dev.c b/net/core/dev.c index 6140fd9d11cd0e..cd0796a1dbfdf8 100644 --- a/net/core/dev.c +++ b/net/core/dev.c @@ -1748,8 +1748,10 @@ static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack) ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack); ret = notifier_to_errno(ret); - if (ret) + if (ret) { + netpoll_poll_enable(dev); return ret; + } set_bit(__LINK_STATE_START, &dev->state); From e7d2f93a4426ea6b33dbca1ce585a9876e3a7344 Mon Sep 17 00:00:00 2001 From: Guangshuo Li Date: Tue, 10 Nov 2026 22:32:25 +0800 Subject: [PATCH 1436/2102] phy: rockchip: inno-hdmi: Fix potential stale clock provider The clock provider remains registered if PHY provider registration fails. Device-managed cleanup then frees the clock hardware and PHY private data still referenced by the provider. Use a device-managed clock provider so both probe failure and removal unregister it before the clock hardware is released. This issue was found by our static analysis tool under development. Fixes: 53706a116863 ("phy: add Rockchip Innosilicon hdmi phy") Cc: stable@vger.kernel.org Signed-off-by: Guangshuo Li Reviewed-by: Heiko Stuebner Link: https://patch.msgid.link/20261110-9f141e6bc8-phy-rockchip@mail.sdu.edu.cn Signed-off-by: Vinod Koul --- drivers/phy/rockchip/phy-rockchip-inno-hdmi.c | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/drivers/phy/rockchip/phy-rockchip-inno-hdmi.c b/drivers/phy/rockchip/phy-rockchip-inno-hdmi.c index d2c2b17df5f340..09608f204798ea 100644 --- a/drivers/phy/rockchip/phy-rockchip-inno-hdmi.c +++ b/drivers/phy/rockchip/phy-rockchip-inno-hdmi.c @@ -1068,7 +1068,7 @@ static int inno_hdmi_phy_clk_register(struct inno_hdmi_phy *inno) return ret; } - ret = of_clk_add_provider(np, of_clk_src_simple_get, inno->phyclk); + ret = devm_of_clk_add_hw_provider(dev, of_clk_hw_simple_get, &inno->hw); if (ret) { dev_err(dev, "failed to register clock provider: %d\n", ret); return ret; @@ -1454,11 +1454,6 @@ static int inno_hdmi_phy_probe(struct platform_device *pdev) return PTR_ERR_OR_ZERO(phy_provider); } -static void inno_hdmi_phy_remove(struct platform_device *pdev) -{ - of_clk_del_provider(pdev->dev.of_node); -} - static const struct of_device_id inno_hdmi_phy_of_match[] = { { .compatible = "rockchip,rk3228-hdmi-phy", @@ -1472,7 +1467,6 @@ MODULE_DEVICE_TABLE(of, inno_hdmi_phy_of_match); static struct platform_driver inno_hdmi_phy_driver = { .probe = inno_hdmi_phy_probe, - .remove = inno_hdmi_phy_remove, .driver = { .name = "inno-hdmi-phy", .of_match_table = inno_hdmi_phy_of_match, From dd206ec7ed36be3883d08def9eca8faab7a38ee5 Mon Sep 17 00:00:00 2001 From: Blake Alexander Date: Thu, 19 Nov 2026 11:50:00 +0100 Subject: [PATCH 1437/2102] net: dsa: mv88e6xxx: do not override PHYIDs on external MDIO Some variants of the Marvell 88E6xxx family (such as MV88E6390) support an external MDIO bus (in addition to the internal MDIO bus for configuring internal PHYs). A typical use-case for the external bus is to configure PHYs that are external to the switch. On switches that do not assign a PHYID for internal PHYs (i.e. the value is 0), the mv88e6xxx_mdio_read() function traps read calls to the PHYID registers and sets the PHYID equal to the family ID of the switch. The mv88e6xxx_mdio_read() function is reused for both internal and mdio bus operations. The PHYID overwrite trap does not check whether the MDIO bus is internal or external and wrongly modifies the PHYID of devices on the external bus when their PHYID2 register reports a value of 0. When a C22 device reports a PHYID of 0, get_phy_device() will reprobe the device as C45 and if successful create a C45 device. Overriding the PHYID in this case will prevent a C45 device (such as Aquantia AQR115) from being reprobed and their driver will fail to bind. This was observed on a development board during the bring-up phase. The board included an MV88E6393X with external AQR115 PHYs. The MDIO bus of the PHYs was connected to the external MDIO bus of the Marvell switch. Prior to applying this patch, the aquantia driver failed to detect the AQR115 and instead detected a generic C22 device (as a PHYID of 0x00000393 does not match a known PHY). After applying this fix, the external AQR115s were detected correctly and their respective driver bound to them successfully. Do not modify the returned PHYID in mv88e6xxx_mdio_read() when reading from a device on the external MDIO bus. Fixes: da9f33018e2c ("net: dsa: mv88e6xxx: Workaround missing PHY ID on mv88e6390") Cc: stable@vger.kernel.org Signed-off-by: Blake Alexander Reviewed-by: Andrew Lunn Link: https://patch.msgid.link/20261119-mv88e6xxx-fix-v1-1-2db604f3516f@airbus.com Signed-off-by: Paolo Abeni --- drivers/net/dsa/mv88e6xxx/chip.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/dsa/mv88e6xxx/chip.c b/drivers/net/dsa/mv88e6xxx/chip.c index 425fd2d22c289e..abef896b7670ff 100644 --- a/drivers/net/dsa/mv88e6xxx/chip.c +++ b/drivers/net/dsa/mv88e6xxx/chip.c @@ -3779,7 +3779,7 @@ static int mv88e6xxx_mdio_read(struct mii_bus *bus, int phy, int reg) mv88e6xxx_reg_unlock(chip); /* Some internal PHYs don't have a model number. */ - if (reg == MII_PHYSID2 && !(val & 0x3f0) && + if (!mdio_bus->external && reg == MII_PHYSID2 && !(val & 0x3f0) && chip->info->family < ARRAY_SIZE(family_prod_id_table)) { prod_id = family_prod_id_table[chip->info->family]; if (prod_id) From bda3c8381653343f1b94d26853f531f30b3ddfc9 Mon Sep 17 00:00:00 2001 From: Ankit Garg Date: Wed, 18 Nov 2026 13:20:45 -0800 Subject: [PATCH 1438/2102] gve: fix checksum state and gso_segs of HW-GRO packets With HW-GRO enabled, gve_rx_complete_rsc() turns a coalesced packet into a GSO skb by setting gso_size, gso_segs and gso_type, but leaves it CHECKSUM_UNNECESSARY with th->check as the device wrote it. Unlike tcp4_gro_complete() and tcp6_gro_complete() for a SW-GRO packet, it does not seed th->check with the TCP pseudo-header checksum or set CHECKSUM_PARTIAL. The GRO stack completes a HW-GRO skb itself only if it holds the skb for merging (since commit 5eddb24901ee ("gro: add support of (hw)gro packets to gro stack")). Otherwise the skb is delivered as is, e.g. with rx-gro off or for a packet that is flushed immediately (e.g. with PSH set). If such an skb is forwarded out of a TSO-capable device, netif_needs_gso() accepts it as CHECKSUM_UNNECESSARY and the device segments it with a bogus checksum seed, so every segment is dropped by the receiver. This blackholes forwarded TCP traffic on VMs acting as routers or NAT gateways and was observed on VMs in real use. Fix it in a manner consistent with other drivers with HW-GRO: set the network and transport headers and, for packets whose checksum the device verified, seed th->check with the pseudo-header checksum and call tcp_gro_complete(), passing gso_segs through NAPI_GRO_CB(skb)->count. skb->data points at the Ethernet header on the napi_gro_frags() path and at the IP header on the header-split and copybreak paths, so account for that when setting the network header. Since the header layout now matters, tell IPv4 from IPv6 by the EtherType, as qede and bnx2x do, rather than by the packet type. The device only coalesces TCP directly over IPv4 or IPv6, without VLAN tags, IPv6 extension headers or encapsulation, so the IP header always follows the Ethernet header and the TCP header always follows the IP header. The IP and TCP header lengths are read from the packet, so check that the headers are in the linear part before using them, and drop the packet otherwise. Also compute gso_segs from the TCP payload length. It was computed from skb->data_len, which is 0 for a packet that rx_copybreak copied whole into the linear part, leaving such packets with gso_segs 0 and a non-zero gso_size. Such small packets usually carry a single segment, so deliver a packet with at most one segment of payload as a non-GSO skb. Fixes: e637c244b954 ("gve: Advertise NETIF_F_GRO_HW instead of NETIF_F_LRO") Cc: stable@vger.kernel.org Reviewed-by: Jordan Rhee Reviewed-by: Praveen Kaligineedi Signed-off-by: Ankit Garg Signed-off-by: Joshua Washington Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261118212045.3575303-1-joshwash@google.com Signed-off-by: Paolo Abeni --- drivers/net/ethernet/google/gve/gve_rx_dqo.c | 84 ++++++++++++++++---- 1 file changed, 68 insertions(+), 16 deletions(-) diff --git a/drivers/net/ethernet/google/gve/gve_rx_dqo.c b/drivers/net/ethernet/google/gve/gve_rx_dqo.c index 82ed5e48b00abd..b4dbfb1ba39b01 100644 --- a/drivers/net/ethernet/google/gve/gve_rx_dqo.c +++ b/drivers/net/ethernet/google/gve/gve_rx_dqo.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -1000,13 +1001,34 @@ static int gve_rx_dqo(struct napi_struct *napi, struct gve_rx_ring *rx, return -ENOMEM; } +/* Prepare a HW-GRO packet the way tcp4/6_gro_complete() prepare a SW-GRO + * packet, so that it can be resegmented by GSO or TSO if it is forwarded: + * seed th->check with the TCP pseudo-header checksum and set CHECKSUM_PARTIAL. + */ +static void gve_rx_fixup_gro_checksum(struct sk_buff *skb) +{ + int len = skb->len - skb_transport_offset(skb); + struct tcphdr *th = tcp_hdr(skb); + + if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) + th->check = ~tcp_v4_check(len, ip_hdr(skb)->saddr, + ip_hdr(skb)->daddr, 0); + else + th->check = ~tcp_v6_check(len, &ipv6_hdr(skb)->saddr, + &ipv6_hdr(skb)->daddr, 0); + + NAPI_GRO_CB(skb)->count = skb_shinfo(skb)->gso_segs; + tcp_gro_complete(skb); +} + static int gve_rx_complete_rsc(struct sk_buff *skb, const struct gve_rx_compl_desc_dqo *desc, struct gve_ptype ptype) { struct skb_shared_info *shinfo = skb_shinfo(skb); - int rsc_segments, rsc_seg_len, hdr_len; + int rsc_seg_len, hdr_len, nhoff, thoff, gso_type, payload; skb_frag_t *frag; + __be16 proto; void *va; /* HW-GRO only coalesces TCP. */ @@ -1017,20 +1039,11 @@ static int gve_rx_complete_rsc(struct sk_buff *skb, if (!rsc_seg_len) return 0; - switch (ptype.l3_type) { - case GVE_L3_TYPE_IPV4: - shinfo->gso_type = SKB_GSO_TCPV4; - break; - case GVE_L3_TYPE_IPV6: - shinfo->gso_type = SKB_GSO_TCPV6; - break; - default: - return -EINVAL; - } - if (skb_headlen(skb)) { - /* With header-split, payload is in the non-linear part */ - rsc_segments = DIV_ROUND_UP(skb->data_len, rsc_seg_len); + /* With header-split or copybreak, eth_type_trans() has already + * pulled the Ethernet header. + */ + nhoff = 0; } else { /* HW-GRO packets are guaranteed to have complete TCP/IP * headers in frag[0] when header-split is not enabled. @@ -1039,7 +1052,6 @@ static int gve_rx_complete_rsc(struct sk_buff *skb, va = skb_frag_address(frag); hdr_len = eth_get_headlen(skb->dev, va, skb_frag_size(frag)); - rsc_segments = DIV_ROUND_UP(skb->len - hdr_len, rsc_seg_len); skb_copy_to_linear_data(skb, va, hdr_len); skb_frag_size_sub(frag, hdr_len); /* Verify we didn't empty the fragment completely as that could @@ -1049,10 +1061,50 @@ static int gve_rx_complete_rsc(struct sk_buff *skb, skb_frag_off_add(frag, hdr_len); skb->data_len -= hdr_len; skb->tail += hdr_len; + /* napi_gro_frags() pulls the Ethernet header later. */ + nhoff = ETH_HLEN; + } + + /* The header lengths come from the packet, so make sure the headers are + * in the linear part before reading them and writing th->check. + */ + if (unlikely(skb_headlen(skb) < nhoff + sizeof(struct iphdr))) + return -EINVAL; + + skb_set_network_header(skb, nhoff); + proto = nhoff ? ((struct ethhdr *)skb->data)->h_proto : skb->protocol; + switch (proto) { + case htons(ETH_P_IP): + gso_type = SKB_GSO_TCPV4; + thoff = nhoff + ip_hdrlen(skb); + break; + case htons(ETH_P_IPV6): + gso_type = SKB_GSO_TCPV6; + thoff = nhoff + sizeof(struct ipv6hdr); + break; + default: + return -EINVAL; } + if (unlikely(skb_headlen(skb) < thoff + sizeof(struct tcphdr))) + return -EINVAL; + skb_set_transport_header(skb, thoff); + if (unlikely(skb->len < thoff + tcp_hdrlen(skb))) + return -EINVAL; + + /* With at most one segment of payload, this is not a GSO packet. */ + payload = skb->len - thoff - tcp_hdrlen(skb); + if (payload <= rsc_seg_len) + return 0; + + shinfo->gso_type = gso_type; shinfo->gso_size = rsc_seg_len; - shinfo->gso_segs = rsc_segments; + shinfo->gso_segs = DIV_ROUND_UP(payload, rsc_seg_len); + + if (!IS_ENABLED(CONFIG_INET) || + unlikely(skb->ip_summed != CHECKSUM_UNNECESSARY)) + return 0; + gve_rx_fixup_gro_checksum(skb); return 0; } From 5677cf0e039b3cabf79d5aa10facbdb54aea93c6 Mon Sep 17 00:00:00 2001 From: Eric Dumazet Date: Wed, 18 Nov 2026 13:54:43 +0100 Subject: [PATCH 1439/2102] tun: flush uc and mc addresses in TUNSETLINK TUNSETLINK changes dev->type and dev->addr_len, but leaves dev->uc and dev->mc untouched. Entries added with the old addr_len stay in lists and rb-trees that are now searched and dumped with the new addr_len. When addr_len grows (eg ARPHRD_NONE -> ARPHRD_IP6GRE), dumps like /proc/net/dev_mcast and RTM_GETMULTICAST expose bytes of netdev_hw_addr that were never initialized. bonding and team already call dev_uc_flush() and dev_mc_flush() between NETDEV_PRE_TYPE_CHANGE and the type change. Do the same in tun, but only when addr_len changes: if it does not, existing entries are still valid and there is no reason to drop them. Fixes: cca8ea3b05c9 ("net: tun: set tun->dev->addr_len during TUNSETLINK processing") Link: https://lore.kernel.org/netdev/20261116024056.1274402-1-bsdhenrymartin@gmail.com/ Signed-off-by: Eric Dumazet Reviewed-by: Willem de Bruijn Link: https://patch.msgid.link/20261118125443.1137177-1-edumazet@kernel.org Signed-off-by: Paolo Abeni --- drivers/net/tun.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/drivers/net/tun.c b/drivers/net/tun.c index d726c4523fe649..5178c11ba5b137 100644 --- a/drivers/net/tun.c +++ b/drivers/net/tun.c @@ -3386,6 +3386,8 @@ static long __tun_chr_ioctl(struct file *file, unsigned int cmd, (unsigned short)arg == ARPHRD_MCTP) { ret = -EINVAL; } else { + unsigned char addr_len = tun_get_addr_len(arg); + ret = call_netdevice_notifiers(NETDEV_PRE_TYPE_CHANGE, tun->dev); ret = notifier_to_errno(ret); @@ -3394,8 +3396,13 @@ static long __tun_chr_ioctl(struct file *file, unsigned int cmd, "Refused to change device type\n"); break; } + /* Addresses were added with the old dev->addr_len. */ + if (addr_len != tun->dev->addr_len) { + dev_uc_flush(tun->dev); + dev_mc_flush(tun->dev); + } tun->dev->type = (int) arg; - tun->dev->addr_len = tun_get_addr_len(tun->dev->type); + tun->dev->addr_len = addr_len; netif_info(tun, drv, tun->dev, "linktype set to %d\n", tun->dev->type); call_netdevice_notifiers(NETDEV_POST_TYPE_CHANGE, From 398ee8a011d9187e83fc24738b3391e508da91da Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Wed, 21 Oct 2026 20:34:59 +0100 Subject: [PATCH 1440/2102] btrfs: send: fix missing hole punching during incremental send When using the no-holes feature (enabled by default since btrfs-progs v5.15) and doing an incremental send, we can miss issuing a hole punching command when the following conditions happen: 1) A hole is punched in a tail section of a file extent item that happens to be the last item in a leaf (for example the extent covers the file range [1M, 3M) and a hole is punched in the range [2M, 3M)). Between the end of this file extent item's range and the i_size, there are other file extent items; 2) The next leaf was not modified in the send snapshot, remaining shared with the parent snapshot. In this scenario we are unable to detect a hole was punched and never issue a hole punch command because with no-holes there we don't have an explicit file extent item to mark a hole. Fix this by teaching maybe_send_hole() to detect such case. A test case for fstests will follow soon. Reported-by: Tristan Elvers Link: https://lore.kernel.org/linux-btrfs/CAFoLKK+aErV4p6ZJPnVeH5SHQ5++0f=8ZgxPWe-E-CkeKBs8PA@mail.gmail.com/ Fixes: 16e7549f045d ("Btrfs: incompatible format change to remove hole extents") Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Signed-off-by: David Sterba --- fs/btrfs/send.c | 69 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 65 insertions(+), 4 deletions(-) diff --git a/fs/btrfs/send.c b/fs/btrfs/send.c index c523bf950c898f..1b903e75cec0ab 100644 --- a/fs/btrfs/send.c +++ b/fs/btrfs/send.c @@ -6371,6 +6371,9 @@ static int range_is_hole_in_parent(struct send_ctx *sctx, static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path, struct btrfs_key *key) { + BTRFS_PATH_AUTO_FREE(next_path); + const u64 cur_extent_end = btrfs_file_extent_end(path); + u64 next_offset; int ret = 0; if (sctx->cur_ino != key->objectid || !need_send_hole(sctx)) @@ -6397,14 +6400,72 @@ static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path, ret = range_is_hole_in_parent(sctx, sctx->cur_inode_last_extent, key->offset); + if (ret == 0) + ret = send_hole(sctx, key->offset); + else if (ret == 1) + ret = 0; + if (ret < 0) return ret; - else if (ret == 0) - ret = send_hole(sctx, key->offset); + } + sctx->cur_inode_last_extent = cur_extent_end; + + /* + * If we are the last file extent item in a leaf, we may have had a tail + * section that got a hole punched or the extent replaced with a smaller + * one, and if there is no change in the next leaf, we must find out if + * we have such a hole and punch it. + */ + if (!btrfs_fs_incompat(sctx->send_root->fs_info, NO_HOLES) || + (sctx->cur_inode_size <= cur_extent_end) || + (path->slots[0] != btrfs_header_nritems(path->nodes[0]) - 1)) + return 0; + + next_path = alloc_path_for_send(); + if (!next_path) + return -ENOMEM; + + ret = btrfs_search_slot(NULL, sctx->send_root, key, next_path, 0, 0); + if (ret < 0) + return ret; + if (WARN_ON(ret != 0)) + return -EUCLEAN; + + ret = btrfs_next_leaf(sctx->send_root, next_path); + if (ret < 0) { + return ret; + } else if (ret > 0) { + /* + * No next leaf, must punch hole to i_size and set the path back + * to where it was before. + */ + next_offset = sctx->cur_inode_size; + } else { + struct btrfs_key next_key; + + btrfs_item_key_to_cpu(next_path->nodes[0], &next_key, + next_path->slots[0]); + if (next_key.objectid != key->objectid || + next_key.type != BTRFS_EXTENT_DATA_KEY) + next_offset = sctx->cur_inode_size; else - ret = 0; + next_offset = next_key.offset; } - sctx->cur_inode_last_extent = btrfs_file_extent_end(path); + + if (next_offset == cur_extent_end) + return 0; + + btrfs_free_path(next_path); + next_path = NULL; + + ret = range_is_hole_in_parent(sctx, sctx->cur_inode_last_extent, next_offset); + if (ret == 0) + ret = send_hole(sctx, next_offset); + else if (ret == 1) + ret = 0; + + sctx->cur_inode_last_extent = next_offset; + return ret; } From 7260adf3a1225a9476f65b50162f0a37fd0831ae Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Mon, 16 Nov 2026 16:06:58 +0100 Subject: [PATCH 1441/2102] mm/mmu_gather: delay rmap removal on UP as well Commit 5df397dec7c4 ("mm: delay page_remove_rmap() until after the TLB has been flushed") introduced delayed rmap removal of dirty pages until after the TLB flush, so writeback cannot clean a page that is still writable through a stale TLB entry. It skips this on UP, because on UP there are no remote TLBs (single CPU) and because the PTL prevents preemption. The PTL prevents preemption while removing the rmap, but the local TLB flush is usually only performed after dropping the PTL. Consequently, after dropping the PTL we could reschedule to another thread of the same mm, which does not flush the TLB. A kworker could then run into the original race with writeback: it cleans the folio, but the other thread can still modify it through the stale TLB entries, and these writes get lost. Fix it by simply not special-casing UP. Now, only architectures that select MMU_GATHER_NO_GATHER (s390) will skip delay_rmap handling. Fixes: 5df397dec7c4 ("mm: delay page_remove_rmap() until after the TLB has been flushed") Cc: stable@vger.kernel.org Reported-by: Lorenzo Stoakes (ARM) Closes: https://lore.kernel.org/r/avrxOt_GyXLXNqtR@gremlin Reviewed-by: Lorenzo Stoakes (ARM) Acked-by: Zi Yan Acked-by: Kiryl Shutsemau (Meta) Link: https://patch.msgid.link/20261116-dirty_file_pmd-v2-1-571883053174@kernel.org Signed-off-by: David Hildenbrand (Arm) --- include/asm-generic/tlb.h | 6 +----- mm/mmu_gather.c | 2 -- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/include/asm-generic/tlb.h b/include/asm-generic/tlb.h index 4bba02fd5d543f..cb087315b4e728 100644 --- a/include/asm-generic/tlb.h +++ b/include/asm-generic/tlb.h @@ -249,23 +249,19 @@ extern bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page, in bool __tlb_remove_folio_pages(struct mmu_gather *tlb, struct page *page, unsigned int nr_pages, bool delay_rmap); -#ifdef CONFIG_SMP /* * This both sets 'delayed_rmap', and returns true. It would be an inline * function, except we define it before the 'struct mmu_gather'. */ #define tlb_delay_rmap(tlb) (((tlb)->delayed_rmap = 1), true) extern void tlb_flush_rmaps(struct mmu_gather *tlb, struct vm_area_struct *vma); -#endif #endif /* * We have a no-op version of the rmap removal that doesn't * delay anything. That is used on S390, which flushes remote - * TLBs synchronously, and on UP, which doesn't have any - * remote TLBs to flush and is not preemptible due to this - * all happening under the page table lock. + * TLBs synchronously. */ #ifndef tlb_delay_rmap #define tlb_delay_rmap(tlb) (false) diff --git a/mm/mmu_gather.c b/mm/mmu_gather.c index e98397ac577c4e..c022aeb7c84d03 100644 --- a/mm/mmu_gather.c +++ b/mm/mmu_gather.c @@ -49,7 +49,6 @@ static bool tlb_next_batch(struct mmu_gather *tlb) return true; } -#ifdef CONFIG_SMP static void tlb_flush_rmap_batch(struct mmu_gather_batch *batch, struct vm_area_struct *vma) { struct encoded_page **pages = batch->encoded_pages; @@ -91,7 +90,6 @@ void tlb_flush_rmaps(struct mmu_gather *tlb, struct vm_area_struct *vma) tlb_flush_rmap_batch(tlb->active, vma); tlb->delayed_rmap = 0; } -#endif /* * We might end up freeing a lot of pages. Reschedule on a regular From c818150bf00b0b42ff02bffc6a2c36d4f0ff7a52 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Mon, 16 Nov 2026 16:06:59 +0100 Subject: [PATCH 1442/2102] mm/huge_memory: flush dirty file PMDs before removing rmap Unmapping a file PMD can lose concurrent stores when it races with writeback. zap_huge_pmd() removes rmap and drops the PMD lock before the gather flushes the TLB. Writeback can then clean the folio while another thread can still write through a stale writable TLB entry. Those stores do not fault and dirty the folio again. Filesystem DAX has the same problem with its dirty tags. Commit 5df397dec7c4 ("mm: delay page_remove_rmap() until after the TLB has been flushed") fixed the same race for PTEs by adding delayed rmap removal to the mmu_gather infrastructure. The PMD path still removes rmap before flushing. Flush the TLB under the PMD lock before removing rmap for dirty file PMDs. Skip the early flush at address-space teardown, when no users remain, and for mappings without writeback, including shmem and device DAX. Use tlb_can_delay_rmap() to share the PTE path's architecture checks. On s390, clearing the entry already handles TLB synchronization, and __tlb_remove_page_size() immediately drops the mapping reference, so rmap must be removed first. Make the predicate side-effect-free and set the gather's delayed_rmap flag when an entry is actually queued for delayed rmap removal. Queue the folio before the early flush, while the gather still has a valid range. Keep batching references and drain a full batch only after dropping the PMD lock. The early flush resets the gather's TLB state, so draining the batch does not flush that range again. Although writing to files through mmap is generally discouraged, unmapping such mappings may become slower: each dirty file PMD now requires a TLB flush under the PMD lock. Future work should properly extend the delayed-rmap machinery to PMDs and hold the PMD spinlock across multiple entries, so their TLB invalidations and rmap removals can be batched. Fixes: 4b4bb46d00b3 ("dax: clear dirty entry tags on cache flush") Cc: stable@vger.kernel.org Reported-by: Kiryl Shutsemau Closes: https://lore.kernel.org/linux-mm/aoWw_iKEDLjKL2jr@thinkstation/ Reported-by: Chris Mason Link: https://git.kernel.org/linus/5df397dec7c4c08c23bd14f162f1228836faa4ce Suggested-by: Lance Yang Suggested-by: Usama Arif Reviewed-by: Lance Yang Reviewed-by: Baolin Wang Reviewed-by: Lorenzo Stoakes (ARM) Reviewed-by: Kiryl Shutsemau (Meta) Fixes: 2d6692e642e7 ("drm/i915: Start writeback from the shrinker") Signed-off-by: Kiryl Shutsemau (Meta) Reviewed-by: Zi Yan Link: https://patch.msgid.link/20261116-dirty_file_pmd-v2-2-571883053174@kernel.org Signed-off-by: David Hildenbrand (Arm) --- include/asm-generic/tlb.h | 10 +++------- mm/huge_memory.c | 39 +++++++++++++++++++++++++++++++-------- mm/memory.c | 2 +- mm/mmu_gather.c | 2 ++ 4 files changed, 37 insertions(+), 16 deletions(-) diff --git a/include/asm-generic/tlb.h b/include/asm-generic/tlb.h index cb087315b4e728..b318e3e9e66a8d 100644 --- a/include/asm-generic/tlb.h +++ b/include/asm-generic/tlb.h @@ -249,11 +249,7 @@ extern bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page, in bool __tlb_remove_folio_pages(struct mmu_gather *tlb, struct page *page, unsigned int nr_pages, bool delay_rmap); -/* - * This both sets 'delayed_rmap', and returns true. It would be an inline - * function, except we define it before the 'struct mmu_gather'. - */ -#define tlb_delay_rmap(tlb) (((tlb)->delayed_rmap = 1), true) +#define tlb_can_delay_rmap() (true) extern void tlb_flush_rmaps(struct mmu_gather *tlb, struct vm_area_struct *vma); #endif @@ -263,8 +259,8 @@ extern void tlb_flush_rmaps(struct mmu_gather *tlb, struct vm_area_struct *vma); * delay anything. That is used on S390, which flushes remote * TLBs synchronously. */ -#ifndef tlb_delay_rmap -#define tlb_delay_rmap(tlb) (false) +#ifndef tlb_can_delay_rmap +#define tlb_can_delay_rmap() (false) static inline void tlb_flush_rmaps(struct mmu_gather *tlb, struct vm_area_struct *vma) { } #endif diff --git a/mm/huge_memory.c b/mm/huge_memory.c index 75e8641bf9ff9f..4f70612ccb703c 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -2508,10 +2508,12 @@ static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd) mm_dec_nr_ptes(mm); } -static void zap_huge_pmd_folio(struct mm_struct *mm, struct vm_area_struct *vma, - pmd_t pmdval, struct folio *folio, bool is_present) +static void zap_huge_pmd_folio(struct mmu_gather *tlb, struct vm_area_struct *vma, + pmd_t pmdval, struct folio *folio, bool is_present, bool *force_flush) { const bool is_device_private = pmd_is_device_private_entry(pmdval); + struct mm_struct *mm = tlb->mm; + bool delay_rmap = false; if (folio_test_anon(folio)) { add_mm_counter(mm, MM_ANONPAGES, -HPAGE_PMD_NR); @@ -2519,23 +2521,42 @@ static void zap_huge_pmd_folio(struct mm_struct *mm, struct vm_area_struct *vma, add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR); - if (is_present && pmd_dirty(pmdval)) + if (is_present && pmd_dirty(pmdval)) { folio_mark_dirty(folio); + /* + * Remove rmap after the TLB flush if stale TLB entries + * could still be used to write to a mapping that + * supports writeback. + */ + if (!tlb->fullmm && vma->vm_file && + mapping_can_writeback(vma->vm_file->f_mapping)) + delay_rmap = tlb_can_delay_rmap(); + } if (is_present && pmd_young(pmdval) && likely(vma_has_recency(vma))) folio_mark_accessed(folio); } + if (!is_present && !is_device_private) + return; + /* * Present and device private folios are rmappable. Remove the * rmap after transferring young+dirty to the folio. */ - if (is_present || is_device_private) + if (!delay_rmap) folio_remove_rmap_pmd(folio, &folio->page, vma); - /* Device private folios are pinned. */ + /* Device private folios are pinned and don't need a TLB flush. */ if (is_device_private) folio_put(folio); + else if (__tlb_remove_page_size(tlb, &folio->page, HPAGE_PMD_SIZE)) + *force_flush = true; + + if (delay_rmap) { + tlb_flush_mmu_tlbonly(tlb); + folio_remove_rmap_pmd(folio, &folio->page, vma); + } } static struct folio *normal_or_softleaf_folio_pmd(struct vm_area_struct *vma, @@ -2573,6 +2594,7 @@ bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, struct mm_struct *mm = tlb->mm; struct folio *folio = NULL; bool is_present = false; + bool force_flush = false; bool has_deposit; spinlock_t *ptl; pmd_t orig_pmd; @@ -2597,13 +2619,14 @@ bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, folio = normal_or_softleaf_folio_pmd(vma, addr, orig_pmd, is_present); has_deposit = vma_has_deposited_pgtable(vma); if (folio) - zap_huge_pmd_folio(mm, vma, orig_pmd, folio, is_present); + zap_huge_pmd_folio(tlb, vma, orig_pmd, folio, is_present, + &force_flush); if (has_deposit) zap_deposited_table(mm, pmd); spin_unlock(ptl); - if (is_present && folio) - tlb_remove_page_size(tlb, &folio->page, HPAGE_PMD_SIZE); + if (force_flush) + tlb_flush_mmu(tlb); return true; } diff --git a/mm/memory.c b/mm/memory.c index 7f019afc35ca07..cd954afb146f47 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -1757,7 +1757,7 @@ static __always_inline void zap_present_folio_ptes(struct mmu_gather *tlb, ptent = get_and_clear_full_ptes(mm, addr, pte, nr, tlb->fullmm); if (pte_dirty(ptent)) { folio_mark_dirty(folio); - if (tlb_delay_rmap(tlb)) { + if (tlb_can_delay_rmap()) { delay_rmap = true; *force_flush = true; } diff --git a/mm/mmu_gather.c b/mm/mmu_gather.c index c022aeb7c84d03..fc547be33a919b 100644 --- a/mm/mmu_gather.c +++ b/mm/mmu_gather.c @@ -169,6 +169,8 @@ static bool __tlb_remove_folio_pages_size(struct mmu_gather *tlb, struct mmu_gather_batch *batch; VM_BUG_ON(!tlb->end); + if (delay_rmap) + tlb->delayed_rmap = 1; #ifdef CONFIG_MMU_GATHER_PAGE_SIZE VM_WARN_ON(tlb->page_size != page_size); From e81dfb6df941a84ec004b1eff0a5492ca919d537 Mon Sep 17 00:00:00 2001 From: Daniel Wade Date: Tue, 17 Nov 2026 20:36:22 +1030 Subject: [PATCH 1443/2102] mm/memory: mark unshare copies dirty to fix MADV_FREE data loss wp_page_copy() only calls pte_mkdirty() for write faults, so the copy it makes for FAULT_FLAG_UNSHARE comes out clean. Nothing marks the folio dirty either and there is no swap entry. Unshare faults come from R/O GUP pins, like process_vm_readv() on a page shared with a child. If the process forks after the pin is gone, MADV_FREE in one of them marks the folio lazyfree and reclaim frees it. The other process then reads zeroes. Mark the copy's PTE dirty. pte_mkdirty() also sets soft-dirty on x86, so take soft-dirty from the old PTE in both directions. Side effect: smaps and numa_maps count an unshare copy as Private_Dirty or Shared_Dirty rather than _Clean. Fixes: c89357e27f20 ("mm: support GUP-triggered unsharing of anonymous pages") Suggested-by: David Hildenbrand (Arm) Cc: stable@vger.kernel.org Signed-off-by: Daniel Wade Reviewed-by: David Hildenbrand (Arm) Link: https://patch.msgid.link/20261117100622.807-1-danjwade95@gmail.com Signed-off-by: David Hildenbrand (Arm) --- mm/memory.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/mm/memory.c b/mm/memory.c index cd954afb146f47..aa6e5932319747 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -4149,8 +4149,11 @@ static vm_fault_t wp_page_copy(struct vm_fault *vmf) entry = folio_mk_pte(new_folio, vma->vm_page_prot); entry = pte_sw_mkyoung(entry); if (unlikely(unshare)) { + entry = pte_mkdirty(entry); if (pte_soft_dirty(vmf->orig_pte)) entry = pte_mksoft_dirty(entry); + else + entry = pte_clear_soft_dirty(entry); if (pte_uffd(vmf->orig_pte)) { entry = pte_mkuffd(entry); if (userfaultfd_rwp(vma)) From 7b317adeb7f39c294607fff54e9b8813534ee669 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Tue, 17 Nov 2026 10:28:18 +0100 Subject: [PATCH 1444/2102] mm/khugepaged: mark ptes dirty and soft-dirty on mTHP collapse An mTHP collapse can lose soft-dirty PTE bits if pages were written and the VMA was then made read-only, and not setting the PTE dirty in VMAs without VM_WRITE can interact with a later MADV_FREE on a COW-shared page such that all processes lose the data even though a single process MADV_FREE'ed it. Collapse does not preserve the soft-dirty bits of the old PTEs, so the new entries must be marked soft-dirty. map_anon_folio_pte_nopf() relies on pte_mkdirty() to do that, but only calls it if the VMA has VM_WRITE. Further, after CoW-sharing such collapsed folios later, all PTEs will be clean and the folios will be clean. One process doing a MADV_FREE can mark the folios as lazyfree and result in all processes sharing it losing the data once memory reclaim zaps it. In map_anon_folio_pte_nopf(), call pte_mkdirty() unconditionally, just like map_anon_folio_pmd_nopf() already does with pmd_mkdirty(). Consequently, we always mark these PTEs dirty (including soft-dirty) but only set them writable if the VMA has VM_WRITE. This essentially reverts Hugh's commit 1ac0cb5d0e22 ("mm: fix anonymous dirtying") that back then touched do_anonymous_page() to avoid forcing clean anonymous pages through swap instead of discarding them. This no longer applies as shrink_folio_list() allocates swap for ordinary anonymous folios and unconditionally marks them dirty before unmapping, regardless of PTE dirty state. Keeping their PTEs clean does not make them discardable. This now also marks fresh anonymous PTEs dirty and soft-dirty in read-only VMAs when page faults allocate real pages. This has low urgency. Fixes: e22f2fe72c74 ("mm/khugepaged: generalize collapse_huge_page for mTHP collapse") Cc: stable@vger.kernel.org Reported-by: Chris Mason Reported-by: Daniel Wade Closes: https://lore.kernel.org/all/20261117075246.61336-1-danjwade95@gmail.com/ Reviewed-by: Daniel Wade Reviewed-by: Lorenzo Stoakes (ARM) Reviewed-by: Kiryl Shutsemau (Meta) Reviewed-by: Nico Pache Link: https://patch.msgid.link/20261117-khugepaged_mthp_dirty-v1-1-024e4a12c2fa@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/memory.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/mm/memory.c b/mm/memory.c index aa6e5932319747..c966b3fe48b164 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -5525,8 +5525,7 @@ void map_anon_folio_pte_nopf(struct folio *folio, pte_t *pte, entry = pte_sw_mkyoung(entry); - if (vma->vm_flags & VM_WRITE) - entry = pte_mkwrite(pte_mkdirty(entry), vma); + entry = maybe_mkwrite(pte_mkdirty(entry), vma); if (uffd_wp) entry = pte_mkuffd(entry); From dab101c9414da2c0efed8b8db07ba79d88fe2fbe Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Thu, 19 Nov 2026 09:04:58 +0100 Subject: [PATCH 1445/2102] fork: clear p->mm when copy_process() fails When copy_process() fails after copy_mm(), the error path drops the mm reference but leaves p->mm set. Perf and BPF can still reach the task, and take a reference on the already freed mm through get_task_mm() or bpf_find_vma(), resulting in a use-after-free: copy_process() PERF_EVENT_IOC_SET_FILTER ============== ========================= perf_event_init_task(p) copy_mm(p) a later step fails mmput(p->mm) /* frees the mm */ perf_event_addr_filters_apply() get_task_mm(p) /* use-after-free */ Similarly, a BPF program on the task_free LSM hook can call bpf_find_vma(p) before the task is freed. Fix it by clearing p->mm under task_lock() before dropping the reference, just like exit_mm() does. Further, if copy_process() fails before copy_mm(), p->mm is still the parent's mm pointer copied by dup_task_struct(), without having taken a reference. While nobody can access it concurrently, there is the chance that it might get accessed later when a BPF program is attached to free_task(). With CONFIG_MEMCG the task is freed after an RCU grace period, so the parent might already be gone and p->mm in the child points at something that was already freed. So let's just clear p->mm before freeing the task. No lock is required as there cannot be concurrent access (and we might not even have the lock initialized yet). This has medium urgency. Fixes: 375637bc5249 ("perf/core: Introduce address range filtering") Fixes: 7c7e3d31e785 ("bpf: Introduce helper bpf_find_vma") Reported-by: Sashiko Closes: https://lore.kernel.org/sashiko-outbox-180866@kernel.org/ Cc: stable@vger.kernel.org Signed-off-by: Chris Mason [ david: simplify description and comments ] Acked-by: Michal Hocko Reviewed-by: Lorenzo Stoakes (ARM) Reviewed-by: Bradley Morgan Link: https://patch.msgid.link/20261119-mm_failed_fork-v1-1-b3019f43d197@kernel.org Acked-by: Peter Zijlstra (Intel) Signed-off-by: David Hildenbrand (Arm) --- kernel/fork.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/kernel/fork.c b/kernel/fork.c index 5efceb8d58a78b..77d6c8fc38c669 100644 --- a/kernel/fork.c +++ b/kernel/fork.c @@ -2628,8 +2628,14 @@ __latent_entropy struct task_struct *copy_process( bad_fork_cleanup_mm: sched_cache_fork_cleanup(p); if (p->mm) { - mm_clear_owner(p->mm, p); - mmput(p->mm); + struct mm_struct *mm = p->mm; + + /* Perf events and BPF programs can still reach p. */ + task_lock(p); + p->mm = NULL; + task_unlock(p); + mm_clear_owner(mm, p); + mmput(mm); } bad_fork_cleanup_signal: if (!(clone_flags & CLONE_THREAD)) @@ -2663,6 +2669,11 @@ __latent_entropy struct task_struct *copy_process( exit_cred_namespaces(p); exit_creds(p); bad_fork_free: + /* + * If set, p->mm points at the parent's mm without a reference. Nobody + * can access it concurrently anymore, but prevent later access. + */ + p->mm = NULL; WRITE_ONCE(p->__state, TASK_DEAD); exit_task_stack_account(p); put_task_stack(p); From e983389736f21f3818dc060a986582f13454442e Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Fri, 13 Nov 2026 21:45:22 +0000 Subject: [PATCH 1446/2102] mm/migrate_device: allocate THP deferred split heads A THP that device migration maps into an empty PMD can end up on the wrong deferred split list when it is later queued for a deferred split. This occurs if the memcg has no heads yet (resulting in a warning if CONFIG_DEBUG_VM is set), where deferred_split_folio() will then queue the folio on the parent's list. Once a later THP fault in the same memcg allocates the heads, __folio_unqueue_deferred_split() and the split path resolve folio_memcg() to the memcg's own, now existing, list and take its lock. They then list_del_init() a folio that is linked on the parent's list, racing with anything holding the parent's lock, and both lists' nr_items counts go wrong. Resolve the issue by calling folio_memcg_alloc_deferred() after the charge in migrate_vma_insert_huge_pmd_page() and falling back like a failed charge if that fails, as __do_huge_pmd_anonymous_page() does. This was originally discovered by code inspection. Fixes: fafaeceb89a5 ("mm: switch deferred split shrinker to list_lru") Cc: stable@vger.kernel.org Signed-off-by: Josef Bacik [ ljs: tweak commit message, remove unnecessary comment ] Tested-by: Gregory Price (Meta) Acked-by: Balbir Singh Tested-by: Andrew Morton Signed-off-by: Lorenzo Stoakes (ARM) Reviewed-by: Chris Down Tested-by: Chris Down Acked-by: David Hildenbrand (Arm) Link: https://patch.msgid.link/20261113-mason-migrate-et-al-fixes-v2-4-50a2ed382b61@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/migrate_device.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/mm/migrate_device.c b/mm/migrate_device.c index 9e19fadfa65c67..9e5dab8e1b77f7 100644 --- a/mm/migrate_device.c +++ b/mm/migrate_device.c @@ -833,6 +833,13 @@ static int migrate_vma_insert_huge_pmd_page(struct migrate_vma *migrate, goto abort; } + if (folio_memcg_alloc_deferred(folio)) { + count_vm_event(THP_FAULT_FALLBACK); + count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_FALLBACK); + ret = -ENOMEM; + goto abort; + } + __folio_mark_uptodate(folio); pgtable = pte_alloc_one(vma->vm_mm); From 4fc9c04065870100c0a068b7868a282fc1a3bb66 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Fri, 13 Nov 2026 21:45:23 +0000 Subject: [PATCH 1447/2102] mm/migrate_device: don't collect a range twice migrate_vma_collect_pmd() drops the page table lock to split a large folio which it finds in the middle of a page table, and then starts over at the "again" label. The entries for [start, addr) are in migrate->src[] and migrate->dst[] by then. While the page table lock is dropped the page table can go away, in which case the restarted walk invokes migrate_vma_collect_huge_pmd(). However this is passed start rather than addr, so [start, addr) is collected a second time. This can result in migrate->npages exceeding the number of pages the caller asked for, and therefore in writes past the end of the migrate->src[] and migrate->dst[] arrays. Fix this by only handing over what has not yet been collected, page-by-page, and flush the TLB for those entries which have been previously replaced, similar to the other returns in the function. Fixes: 022a12deda53 ("mm/migrate_device: handle partially mapped folios during collection") Cc: stable@vger.kernel.org Signed-off-by: Josef Bacik [ ljs: cleanup commit message ] Tested-by: Gregory Price (Meta) Reviewed-by: Gregory Price (Meta) Signed-off-by: Lorenzo Stoakes (ARM) Reviewed-by: Chris Down Acked-by: Balbir Singh Acked-by: David Hildenbrand (Arm) Link: https://patch.msgid.link/20261113-mason-migrate-et-al-fixes-v2-5-50a2ed382b61@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/migrate_device.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/mm/migrate_device.c b/mm/migrate_device.c index 9e5dab8e1b77f7..28ed706109da11 100644 --- a/mm/migrate_device.c +++ b/mm/migrate_device.c @@ -257,13 +257,17 @@ static int migrate_vma_collect_pmd(pmd_t *pmdp, pte_t *ptep; again: + /* [start, addr) is collected if we get here after splitting a folio */ if (pmd_trans_huge(*pmdp) || !pmd_present(*pmdp)) { - int ret = migrate_vma_collect_huge_pmd(pmdp, start, end, walk, fault_folio); + int ret = migrate_vma_collect_huge_pmd(pmdp, addr, end, walk, fault_folio); if (ret == -EAGAIN) goto again; - if (ret == 0) + if (ret == 0) { + if (unmapped) + flush_tlb_range(walk->vma, start, end); return 0; + } } ptep = pte_offset_map_lock(mm, pmdp, start, &ptl); From 20365e376b05d942bd9196e5a4b0486470b04b55 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Fri, 13 Nov 2026 21:45:24 +0000 Subject: [PATCH 1448/2102] mm/migrate_device: don't let go of the fault page When migrate_vma_split_folio() has split the folio of the fault page, the lock and the reference which the fault handler has taken are at the former head page. It then moves them to the folio which now holds the fault page, by taking a reference on and locking that folio, then unlocking and putting the former head. split_folio() has unlocked the new folio and has dropped its own reference on it, so until folio_get() nothing but the page table entry holds it. Only the mmap lock is held for read, which does not prevent another thread from zapping the entry with MADV_DONTNEED. If this happens the folio is freed which results in folio_get() taking a reference on a free device page, which the driver can hand out again at any time. In addition, folio_lock() can sleep here with the lock of the head page held. Utilise split_huge_page() which will leave the lock and reference at the fault page correctly. Fixes: 022a12deda53 ("mm/migrate_device: handle partially mapped folios during collection") Cc: stable@vger.kernel.org Signed-off-by: Josef Bacik [ ljs: tweaked commit message ] Tested-by: Gregory Price (Meta) Signed-off-by: Lorenzo Stoakes (ARM) Reviewed-by: Balbir Singh Reviewed-by: Chris Down Tested-by: Chris Down Acked-by: David Hildenbrand (Arm) Link: https://patch.msgid.link/20261113-mason-migrate-et-al-fixes-v2-6-50a2ed382b61@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/migrate_device.c | 39 ++++++++++----------------------------- 1 file changed, 10 insertions(+), 29 deletions(-) diff --git a/mm/migrate_device.c b/mm/migrate_device.c index 28ed706109da11..ae795fdf36f43d 100644 --- a/mm/migrate_device.c +++ b/mm/migrate_device.c @@ -87,39 +87,20 @@ static int migrate_vma_split_folio(struct folio *folio, { int ret; struct folio *fault_folio = fault_page ? page_folio(fault_page) : NULL; - struct folio *new_fault_folio = NULL; - - if (folio != fault_folio) - folio_lock(folio); - - ret = split_folio(folio); - if (ret) { - if (folio != fault_folio) { - folio_unlock(folio); - folio_put(folio); - } - return ret; - } - - new_fault_folio = fault_page ? page_folio(fault_page) : NULL; /* - * Ensure the lock is held on the correct - * folio after the split + * The lock and the reference of the fault handler stay with the + * folio which holds the fault page after the split. */ - if (!new_fault_folio) { - folio_unlock(folio); - folio_put(folio); - } else if (folio != new_fault_folio) { - if (new_fault_folio != fault_folio) { - folio_get(new_fault_folio); - folio_lock(new_fault_folio); - } - folio_unlock(folio); - folio_put(folio); - } + if (folio == fault_folio) + return split_huge_page(fault_page); - return 0; + folio_lock(folio); + ret = split_folio(folio); + folio_unlock(folio); + folio_put(folio); + + return ret; } /** migrate_vma_collect_huge_pmd - collect THP pages without splitting the From 9804b9e0e796da9ca99d1a7d62ec40e97b132a50 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Fri, 13 Nov 2026 21:45:25 +0000 Subject: [PATCH 1449/2102] mm/migrate_device: look up fault folio after a split migrate_vma_collect_pmd() looks up the folio of migrate->fault_page once, when it is entered, at which point the folio is locked. The fault folio is assumed not to change after this, however if migrate_vma_split_folio() splits a PTE-mapped large folio which contains the fault page, the fault page ends up in a different folio. Resolve the issue by looking up fault_folio again after each restart of the walk. Fixes: 022a12deda53 ("mm/migrate_device: handle partially mapped folios during collection") Cc: stable@vger.kernel.org Signed-off-by: Josef Bacik [ ljs: pared down commit message ] Tested-by: Gregory Price (Meta) Signed-off-by: Lorenzo Stoakes (ARM) Reviewed-by: Balbir Singh Reviewed-by: Chris Down Tested-by: Chris Down Acked-by: David Hildenbrand (Arm) Link: https://patch.msgid.link/20261113-mason-migrate-et-al-fixes-v2-7-50a2ed382b61@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/migrate_device.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/mm/migrate_device.c b/mm/migrate_device.c index ae795fdf36f43d..45e571dbfb4c36 100644 --- a/mm/migrate_device.c +++ b/mm/migrate_device.c @@ -233,11 +233,14 @@ static int migrate_vma_collect_pmd(pmd_t *pmdp, struct mm_struct *mm = vma->vm_mm; unsigned long addr = start, unmapped = 0; spinlock_t *ptl; - struct folio *fault_folio = migrate->fault_page ? - page_folio(migrate->fault_page) : NULL; + struct folio *fault_folio; pte_t *ptep; again: + /* The fault page is in another folio once its folio has been split */ + fault_folio = migrate->fault_page ? + page_folio(migrate->fault_page) : NULL; + /* [start, addr) is collected if we get here after splitting a folio */ if (pmd_trans_huge(*pmdp) || !pmd_present(*pmdp)) { int ret = migrate_vma_collect_huge_pmd(pmdp, addr, end, walk, fault_folio); From 0f41c57aae7fb679e77e8a36f22acc34bc097fe8 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Fri, 13 Nov 2026 21:45:26 +0000 Subject: [PATCH 1450/2102] mm/migrate_device: fix ksmd oops on a migrated KSM page After a KSM page is migrated to device private memory, ksmd can oops, and KSM then stops until reboot. A process that maps the page can also loop in page faults when it next accesses the page. The problem arises because KSM doesn't know not to try to look at device private memory that does not exist in the direct map. In addition, ksmd skips all device pages when it scans, so it drops its rmap of a KSM page which was migrated to device private or device coherent memory. Disallow migrating a KSM page to either by explicitly testing for this in __migrate_device_pages(). Fixes: a5430dda8a3a ("mm/migrate: support un-addressable ZONE_DEVICE page in migration") Cc: stable@vger.kernel.org Signed-off-by: Chris Mason [ ljs: tweak commit message, comment, also refuse device coherent ] Tested-by: Gregory Price (Meta) Acked-by: Balbir Singh Reviewed-by: Alistair Popple Signed-off-by: Lorenzo Stoakes (ARM) Reviewed-by: Chris Down Tested-by: Chris Down Acked-by: David Hildenbrand (Arm) Link: https://patch.msgid.link/20261113-mason-migrate-et-al-fixes-v2-8-50a2ed382b61@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/migrate_device.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/mm/migrate_device.c b/mm/migrate_device.c index 45e571dbfb4c36..141d60d27e90ee 100644 --- a/mm/migrate_device.c +++ b/mm/migrate_device.c @@ -1207,6 +1207,11 @@ static void __migrate_device_pages(unsigned long *src_pfns, if (folio_is_device_private(newfolio) || folio_is_device_coherent(newfolio)) { + /* KSM does not scan or track device pages. */ + if (folio_test_ksm(folio)) { + src_pfns[i] &= ~MIGRATE_PFN_MIGRATE; + goto next; + } if (mapping) { /* * For now only support anonymous memory migrating to From 11990871862e699dd41f16a77cd5bcefe33883db Mon Sep 17 00:00:00 2001 From: "Lorenzo Stoakes (ARM)" Date: Fri, 13 Nov 2026 21:45:27 +0000 Subject: [PATCH 1451/2102] mm/migrate_device: fix use-after-free of the anon rmap A munmap() of anonymous memory can result in a use-after-free of the anonymous rmap if a concurrent device memory migration occurs and the migration runs without the mmap_lock held. This can occur for a long-term pin of device-coherent memory, or a driver evicting its device memory by PFN. Consider: eviction munmap() ======== ======== migrate_device_range() migrate_device_unmap() try_to_migrate() zap the migration entry unlink_anon_vmas() last VMA: free the anon_vma migrate_device_finalize() remove_migration_ptes() /* locks and walks the freed anon_vma */ If munmap() runs before try_to_migrate() instead, the folio is no longer mapped and gets no migration entry. The walk still runs, and follows the stale folio->mapping to the freed anon_vma. Resolve this by pinning the anon rmap of each folio which possesses one in migrate_device_range(), migrate_device_pfns() and migrate_device_coherent_folio() before its PTEs are replaced, and unpinning it once the walk is done. A folio which is no longer mapped cannot be pinned and has no migration entries to remove, so skip it rather than migrating it. Reported-by: Chris Mason Fixes: e778406b40db ("mm/migrate_device.c: add migrate_device_range()") Cc: stable@vger.kernel.org Reviewed-by: Zi Yan Tested-by: Gregory Price (Meta) Signed-off-by: Lorenzo Stoakes (ARM) Reviewed-by: Chris Down Tested-by: Chris Down Acked-by: David Hildenbrand (Arm) Reviewed-by: Alistair Popple Link: https://patch.msgid.link/20261113-mason-migrate-et-al-fixes-v2-9-50a2ed382b61@kernel.org Signed-off-by: David Hildenbrand (Arm) --- include/linux/migrate.h | 1 + mm/migrate_device.c | 39 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/include/linux/migrate.h b/include/linux/migrate.h index 78424b3824c294..c6cce7925b9bc8 100644 --- a/include/linux/migrate.h +++ b/include/linux/migrate.h @@ -136,6 +136,7 @@ static inline int migrate_misplaced_folio(struct folio *folio, int node) #define MIGRATE_PFN_MIGRATE (1UL << 1) #define MIGRATE_PFN_WRITE (1UL << 3) #define MIGRATE_PFN_COMPOUND (1UL << 4) +#define MIGRATE_PFN_ANON_RMAP (1UL << 5) /* mm internal */ #define MIGRATE_PFN_SHIFT 6 static inline struct page *migrate_pfn_to_page(unsigned long mpfn) diff --git a/mm/migrate_device.c b/mm/migrate_device.c index 141d60d27e90ee..b4660eeb975a7d 100644 --- a/mm/migrate_device.c +++ b/mm/migrate_device.c @@ -552,6 +552,27 @@ static bool migrate_vma_check_page(struct page *page, struct page *fault_page) return true; } +/* + * Pin the anonymous rmap if present to allow migration entries to be safely + * removed. Returns true if the pin succeeded or no pin is required, and false + * if the folio is no longer mapped. + */ +static bool pin_anon_rmap(struct folio *folio, unsigned long *src_pfn) +{ + if (!folio_test_anon(folio) || folio_test_ksm(folio)) + return true; + if (!folio_get_anon_vma(folio)) /* Pin the anon rmap. */ + return false; + *src_pfn |= MIGRATE_PFN_ANON_RMAP; + return true; +} + +static void unpin_anon_rmap(struct folio *folio, unsigned long src_pfn) +{ + if (src_pfn & MIGRATE_PFN_ANON_RMAP) + put_anon_vma(folio_anon_vma(folio)); /* Unpin the anon rmap. */ +} + /* * Unmaps pages for migration. Returns number of source pfns marked as * migrating. @@ -633,6 +654,7 @@ static unsigned long migrate_device_unmap(unsigned long *src_pfns, folio = page_folio(page); remove_migration_ptes(folio, folio, 0); + unpin_anon_rmap(folio, src_pfns[i]); src_pfns[i] = 0; if (fault_folio != folio) @@ -1331,6 +1353,7 @@ static void __migrate_device_finalize(unsigned long *src_pfns, if (!folio_is_zone_device(dst)) folio_add_lru(dst); remove_migration_ptes(src, dst, 0); + unpin_anon_rmap(src, src_pfns[i]); if (fault_folio != src) folio_unlock(src); folio_put(src); @@ -1380,6 +1403,7 @@ EXPORT_SYMBOL(migrate_vma_finalize); static unsigned long migrate_device_pfn_lock(unsigned long pfn) { + unsigned long src_pfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE; struct folio *folio; folio = folio_get_nontail_page(pfn_to_page(pfn)); @@ -1391,7 +1415,13 @@ static unsigned long migrate_device_pfn_lock(unsigned long pfn) return 0; } - return migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE; + if (!pin_anon_rmap(folio, &src_pfn)) { + folio_unlock(folio); + folio_put(folio); + return 0; + } + + return src_pfn; } /** @@ -1427,6 +1457,7 @@ int migrate_device_range(unsigned long *src_pfns, unsigned long start, nr = folio_nr_pages(folio); if (nr > npages - i) { if (src_pfns[i] & MIGRATE_PFN_MIGRATE) { + unpin_anon_rmap(folio, src_pfns[i]); folio_unlock(folio); folio_put(folio); } @@ -1470,6 +1501,7 @@ int migrate_device_pfns(unsigned long *src_pfns, unsigned long npages) nr = folio_nr_pages(folio); if (nr > npages - i) { if (src_pfns[i] & MIGRATE_PFN_MIGRATE) { + unpin_anon_rmap(folio, src_pfns[i]); folio_unlock(folio); folio_put(folio); } @@ -1505,6 +1537,11 @@ int migrate_device_coherent_folio(struct folio *folio) folio_lock(folio); src_pfn = migrate_pfn(folio_pfn(folio)) | MIGRATE_PFN_MIGRATE; + if (!pin_anon_rmap(folio, &src_pfn)) { + folio_unlock(folio); + folio_put(folio); + return -EBUSY; + } /* * We don't have a VMA and don't need to walk the page tables to find From a643a82e27eeb681cff6f8c1270eb565579d6157 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Wed, 18 Nov 2026 10:20:36 +0100 Subject: [PATCH 1452/2102] mm: flush stale TLB entries before installing a CoW'ed folio MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Zapping PTEs in zap_pte_range() defers the TLB flush until after dropping the PTL for clean page-cache folios. A concurrent write fault in a MAP_PRIVATE mapping can then CoW the page-cache folio and install a new anon folio without a prior TLB flush: CPU0 CPU1 LOAD(ADDR) -> #PF installs R/O PTE -> A fuse_open() -> invalidate_inode_pages2() -> zap_pte_range() clears R/O PTE // delayed flush // Other CPUs (incl CPU0) still cache ADDR -> A STORE(ADDR) -> #PF do_cow_fault() copies A to B, installs R/W PTE -> B // no TLB flush: PTE was none CPUs with stale TLB entries will still read from the old folio while writes go to the new folio, until the TLB is flushed. We really must process pending TLB flushes if we are not faulting the same folio back in. Fix it by flushing the TLB before installing an anon (CoW'ed) folio in set_pte_range() if a TLB flush is pending. Zapping itself stays as fast as before. Other faults are not affected: unmap_mapping_*() users only remove folios from the page-cache after their own TLB flush, so until then, a refault maps the same folio again. The exception is a concurrent invalidation that removes the already-unmapped folio from the page-cache before the zapper flushed the TLB; that is an unlikely corner case that we'll not handle for now. Note that we don't care about MADV_DONTNEED followed by a new read fault, as MADV_DONTNEED only guarantees its semantics once the operation completed. CoW faults will flush the TLB either way. For example, imagine that MADV_DONTNEED zaps a page-cache folio and doesn't flush the TLB (but still holds a reference). If the page-cache replaces the folio, a new read fault might map the new folio without flushing the TLB. That's okay, as MADV_DONTNEED did not complete yet. Same applies to MADV_DONTNEED of CoW'ed folios when re-faulting the page-cache folio. Memory reclaim, which removes folios from the page-cache before performing its own batched TLB flush, will be handled separately. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Reported-by: Cenk Yılmaz Debugged-by: Cenk Yılmaz Cc: stable@vger.kernel.org Tested-by: Cenk Yılmaz Reviewed-by: Jose A. Perez de Azpillaga Reviewed-by: Zi Yan Link: https://patch.msgid.link/20261118-file_folio_flush-v1-1-e9e739ed14e0@kernel.org Reviewed-by: Vlastimil Babka (SUSE) Signed-off-by: David Hildenbrand (Arm) --- mm/memory.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mm/memory.c b/mm/memory.c index c966b3fe48b164..05d350efc84bb0 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -5854,6 +5854,12 @@ void set_pte_range(struct vm_fault *vmf, struct folio *folio, /* copy-on-write page */ if (write && !(vma->vm_flags & VM_SHARED)) { VM_BUG_ON_FOLIO(nr != 1, folio); + /* + * Concurrent zapping might have dropped the PTL but not flushed + * the TLB yet. Flush before installing a new folio. + */ + if (mm_tlb_flush_pending(vma->vm_mm)) + flush_tlb_page(vma, addr); folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE); folio_add_lru_vma(folio, vma); } else { From ca13678be3c2a07a903210d92c1ad8f4a9bf1c66 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Wed, 18 Nov 2026 10:20:37 +0100 Subject: [PATCH 1453/2102] mm/vmscan: flush deferred writable TLB entries before unlocking the folio try_to_unmap() with TTU_BATCH_FLUSH transfers the PTE dirty bit to the folio and defers the TLB flush. Reclaim must flush the TLB before unlocking the folio, otherwise stale writable TLB entries might be left behind temporarily: writeback started by other mechanisms (e.g., fsync) will not find any mappings in folio_mkclean(), so it will neither write-protect nor flush anything. A write through a stale TLB entry after the folio was cleaned gets lost once the folio is reclaimed. However, reclaim currently does not flush the TLB if the now-dirty folio does not get written back (e.g., gets activated or kept instead). Fix it by flushing right after try_to_unmap() if the folio is dirty, which makes the existing flush before pageout() unnecessary. For dirty page-cache folios that reclaim activates, we will now flush the TLB immediately after unmapping them instead of batching the flush, which is the right thing to do. Performance-wise, it shouldn't really matter much, because folios with dirty PTEs are usually young and reclaim won't even try to unmap them. Fixes: d950c9477d51 ("mm: defer flush of writable TLB entries") Cc: stable@vger.kernel.org Reviewed-by: Jose A. Perez de Azpillaga Reviewed-by: Johannes Weiner Acked-by: Zi Yan Link: https://patch.msgid.link/20261118-file_folio_flush-v1-2-e9e739ed14e0@kernel.org Acked-by: Vlastimil Babka (SUSE) Signed-off-by: David Hildenbrand (Arm) --- mm/vmscan.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/mm/vmscan.c b/mm/vmscan.c index 6a1af9b92349fb..053f8e437bdd81 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -1455,6 +1455,12 @@ static unsigned int shrink_folio_list(struct list_head *folio_list, flags |= TTU_SYNC; try_to_unmap(folio, flags); + /* + * Flush deferred writable TLB entries before we could + * drop the folio lock and others could start writeback. + */ + if (folio_test_dirty(folio)) + try_to_unmap_flush_dirty(); if (folio_mapped(folio)) { stat->nr_unmap_fail += nr_pages; if (!was_swapbacked && @@ -1496,12 +1502,6 @@ static unsigned int shrink_folio_list(struct list_head *folio_list, if (!sc->may_writepage) goto keep_locked; - /* - * Folio is dirty. Flush the TLB if a writable entry - * potentially exists to avoid CPU writes after I/O - * starts and then write it out here. - */ - try_to_unmap_flush_dirty(); switch (pageout(&ctx, mapping, folio, folio_list)) { case PAGE_KEEP: goto keep_locked; From 18d1998802d770b29ec112175e0608f6c4bb0bdb Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 19 Nov 2026 17:04:34 +0100 Subject: [PATCH 1454/2102] mm/madvise: fix MADV_FREE handling for PMD-mapped THPs After MADV_FREE cleared the dirty flag of an anonymous folio, reclaim will later free the folio without writing it back if no mappings are dirty. If our folio is still in the swap cache, the swap entries then point at swap slots that were never written, exposing stale content of the swap device. Bad. madvise_free_pte_range() therefore frees the swap slots first, and skips the folio if that is impossible. madvise_free_huge_pmd() does not, and a PMD-mapped THP can be in the swap cache if try_to_unmap() failed during reclaim, for example due to a racing mlock(). Further, madvise_free_huge_pmd() checks whether the THP is mapped by other processes before taking the folio lock. Another process that still has swap entries for the THP can concurrently map it from the swap cache, and we might end up clearing the dirty flag of a shared folio. Fix it by factoring out the folio handling of madvise_free_pte_range() into madvise_free_try_prepare_folio(), and using it for PMD-mapped THPs as well. Hopefully this prevents further bugs. For PMD-mapped THPs, this change implies: 1. We free the swap slots of a THP in the swap cache, and skip the THP if that is impossible. 2. We check the mapcount under the folio lock. 3. We no longer lock and check THPs that are neither dirty nor in the swap cache, just like for PTE-mapped folios. For PTE-mapped folios, this means: 4. We check the mapcount once before taking the folio lock, to not lock folios that are mapped by other processes. Only compile madvise_free_huge_pmd() with CONFIG_ADVISE_SYSCALLS to keep !CONFIG_ADVISE_SYSCALLS builds working. Chris and Sashiko reported the missing swap cache handling for PMD-mapped THPs, the other issue was found by code inspection. This has medium urgency. Fixes: bd4c82c22c36 ("mm, THP, swap: delay splitting THP after swapped out") Cc: stable@vger.kernel.org Reported-by: Chris Mason Reported-by: Sashiko Closes: https://lore.kernel.org/sashiko-outbox-202086@kernel.org/ Acked-by: Michal Hocko Acked-by: Usama Arif Link: https://patch.msgid.link/20261119-madv_free_thp-v1-1-a312919e1ee5@kernel.org Reviewed-by: Baolin Wang Signed-off-by: David Hildenbrand (Arm) --- mm/huge_memory.c | 19 +++++--------- mm/internal.h | 1 + mm/madvise.c | 65 +++++++++++++++++++++++++----------------------- 3 files changed, 41 insertions(+), 44 deletions(-) diff --git a/mm/huge_memory.c b/mm/huge_memory.c index 4f70612ccb703c..a6da3d9bb9a152 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -2421,6 +2421,7 @@ vm_fault_t do_huge_pmd_numa_page(struct vm_fault *vmf) return 0; } +#ifdef CONFIG_ADVISE_SYSCALLS /* * Return true if we do MADV_FREE successfully on entire pmd page. * Otherwise, return false. @@ -2455,21 +2456,13 @@ bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, if (folio_is_zone_device(folio)) goto out; - /* - * If other processes are mapping this folio, we couldn't discard - * the folio unless they all do MADV_FREE so let's skip the folio. - */ - if (folio_maybe_mapped_shared(folio)) - goto out; - - if (!folio_trylock(folio)) - goto out; - /* * If user want to discard part-pages of THP, split it so MADV_FREE * will deactivate only them. */ if (next - addr != HPAGE_PMD_SIZE) { + if (folio_maybe_mapped_shared(folio) || !folio_trylock(folio)) + goto out; folio_get(folio); spin_unlock(ptl); split_folio(folio); @@ -2478,9 +2471,8 @@ bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, goto out_unlocked; } - if (folio_test_dirty(folio)) - folio_clear_dirty(folio); - folio_unlock(folio); + if (!madvise_free_try_prepare_folio(folio, 1)) + goto out; if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) { pmdp_invalidate(vma, addr, pmd); @@ -2498,6 +2490,7 @@ bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, out_unlocked: return ret; } +#endif /* CONFIG_ADVISE_SYSCALLS */ static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd) { diff --git a/mm/internal.h b/mm/internal.h index 85cf7becf8588a..96cb55d7816b13 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -61,6 +61,7 @@ void lru_add_drain_cpu(int cpu); void lru_add_drain_cpu_zone(struct zone *zone); void folio_deactivate(struct folio *folio); void folio_mark_lazyfree(struct folio *folio); +bool madvise_free_try_prepare_folio(struct folio *folio, int nr_mappings); /* mm/vmscan.c */ unsigned long zone_reclaimable_pages(struct zone *zone); diff --git a/mm/madvise.c b/mm/madvise.c index 0214efd2a014f9..ebb4ce7daf6cb1 100644 --- a/mm/madvise.c +++ b/mm/madvise.c @@ -661,6 +661,38 @@ static long madvise_pageout(struct madvise_behavior *madv_behavior) return 0; } +bool madvise_free_try_prepare_folio(struct folio *folio, int nr_mappings) +{ + if (!folio_test_swapcache(folio) && !folio_test_dirty(folio)) + return true; + + if (folio_mapcount(folio) != nr_mappings || !folio_trylock(folio)) + return false; + + /* + * KSM folios can gain new mappings at any time, so we must + * not clear their dirty flag. + */ + if (folio_test_ksm(folio)) + goto unlock; + + /* + * Check under the folio lock that the folio is exclusive: we own all + * mappings, and there are no references from swap entries. + */ + if (folio_mapcount(folio) != nr_mappings) + goto unlock; + if (folio_test_swapcache(folio) && !folio_free_swap(folio)) + goto unlock; + + folio_clear_dirty(folio); + folio_unlock(folio); + return true; +unlock: + folio_unlock(folio); + return false; +} + static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) @@ -753,37 +785,8 @@ static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr, } } - if (folio_test_swapcache(folio) || folio_test_dirty(folio)) { - if (!folio_trylock(folio)) - continue; - /* - * KSM folios can gain new mappings at any time, so we must - * not clear their dirty flag. - */ - if (folio_test_ksm(folio)) { - folio_unlock(folio); - continue; - } - - /* - * If we have a large folio at this point, we know it is - * fully mapped so if its mapcount is the same as its - * number of pages, it must be exclusive. - */ - if (folio_mapcount(folio) != folio_nr_pages(folio)) { - folio_unlock(folio); - continue; - } - - if (folio_test_swapcache(folio) && - !folio_free_swap(folio)) { - folio_unlock(folio); - continue; - } - - folio_clear_dirty(folio); - folio_unlock(folio); - } + if (!madvise_free_try_prepare_folio(folio, folio_nr_pages(folio))) + continue; if (pte_young(ptent) || pte_dirty(ptent)) { clear_young_dirty_ptes(vma, addr, pte, nr, cydp_flags); From 3e168cc2672ff9c794d0059edb5cd52cf3e8dd83 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Fri, 20 Nov 2026 14:50:58 -0500 Subject: [PATCH 1455/2102] mm/shmem: don't use the memcg of an uncharged folio The shrinker for unused huge tmpfs folios can dereference a NULL memcg if it races with the migration of the folio at the end of a file. folio_memcg_list_lru_alloc() assumes that folio_memcg() is never NULL. But it is NULL until the folio is charged, and a migration target can be in the page cache before charging. shmem_unused_huge_shrink() looks the folio up without the folio lock, so we can race with migration: __migrate_folio() shmem_unused_huge_shrink() ================= ========================== __folio_migrate_mapping() xas_store(newfolio) filemap_get_entry() returns newfolio folio_trylock() fails shmem_unused_huge_requeue() folio_memcg_list_lru_alloc() folio_memcg() is NULL memcg->kmemcg_id folio_migrate_flags() mem_cgroup_migrate() commit_charge(newfolio) Fix it by keeping the original objcg around while the inode is isolated. Fixes: 743e7d025d2f ("mm: shmem: make unused huge shrinker memcg aware") Suggested-by: Qi Zheng Signed-off-by: Chris Mason Reviewed-by: Qi Zheng Tested-by: Gregory Price (Meta) Reviewed-by: Gregory Price (Meta) Link: https://patch.msgid.link/20261120195057.50031-2-mason@kernel.org Reviewed-by: Baolin Wang Signed-off-by: David Hildenbrand (Arm) --- mm/shmem.c | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/mm/shmem.c b/mm/shmem.c index e351cd425d6917..c7a9c4c375ba19 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -758,6 +758,13 @@ shmem_unused_huge_alloc_lru(struct shmem_sb_info *sbinfo, struct folio *folio, { int ret; + /* + * A migration target is in the page cache before it is charged. Once + * charged, its objcg can't change while we hold a folio reference. + */ + if (!mem_cgroup_disabled() && !folio_memcg_charged(folio)) + return ERR_PTR(-EAGAIN); + ret = folio_memcg_list_lru_alloc(folio, &sbinfo->shrinklist, gfp); if (ret) return ERR_PTR(ret); @@ -887,12 +894,11 @@ static enum lru_status shmem_unused_huge_isolate(struct list_head *item, return LRU_REMOVED; } + /* keep shrinklist_objcg, requeue may need it */ list_lru_isolate(lru, item); - objcg = shmem_get_and_clear_objcg(info); set_shmem_unused_huge_isolated(info); list_add_tail(&info->shrinklist, &scan->list); spin_unlock(&info->lock); - obj_cgroup_put(objcg); return LRU_REMOVED; } @@ -928,10 +934,26 @@ static bool is_shmem_unused_huge_match(struct folio *folio, static void shmem_unused_huge_drop(struct inode *inode) { struct shmem_inode_info *info = SHMEM_I(inode); + struct obj_cgroup *objcg; spin_lock(&info->lock); list_del_init(&info->shrinklist); + objcg = shmem_get_and_clear_objcg(info); spin_unlock(&info->lock); + + obj_cgroup_put(objcg); +} + +static void shmem_unused_huge_requeue_locked(struct shmem_inode_info *info, + struct shmem_sb_info *sbinfo, + int nid) +{ + lockdep_assert_held(&info->lock); + + list_del_init(&info->shrinklist); + shmem_unused_huge_lru_add(sbinfo, &info->shrinklist, nid, + info->shrinklist_objcg); + info->shrinklist_nid = nid; } static void shmem_unused_huge_requeue(struct inode *inode, struct folio *folio) @@ -943,17 +965,18 @@ static void shmem_unused_huge_requeue(struct inode *inode, struct folio *folio) objcg = shmem_unused_huge_alloc_lru(sbinfo, folio, GFP_NOWAIT); if (IS_ERR(objcg)) { - shmem_unused_huge_drop(inode); + spin_lock(&info->lock); + shmem_unused_huge_requeue_locked(info, sbinfo, nid); + spin_unlock(&info->lock); return; } spin_lock(&info->lock); - /* Requeue the inode to shrinklist */ - list_del_init(&info->shrinklist); - shmem_unused_huge_lru_add(sbinfo, &info->shrinklist, nid, objcg); - info->shrinklist_objcg = objcg; - info->shrinklist_nid = nid; + swap(info->shrinklist_objcg, objcg); + shmem_unused_huge_requeue_locked(info, sbinfo, nid); spin_unlock(&info->lock); + + obj_cgroup_put(objcg); } static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo, From aaa55c8ff9147b1ce1ba50267aa9f080d469a963 Mon Sep 17 00:00:00 2001 From: Louis Thiery Date: Thu, 19 Nov 2026 23:29:35 +0000 Subject: [PATCH 1456/2102] io_uring/net: don't charge the folio offset to truesize for managed frags Registered buffers backed by huge pages are coalesced into one bvec per folio, so bv_offset is relative to the folio, not to a 4K page. io_sg_from_iter() adds PAGE_ALIGN(bv_len + bv_offset) to the skb truesize, which charges the socket for the whole run-up inside the folio. A 64K send from 1.5MB into a 2MB THP folio adds about 1.6MB of truesize, and sk_wmem_queued fills long before any real memory is used. The visible effect is a socket that looks full: with a 2MB send buffer only 4 of 128 queued 64K sends complete before the sender blocks, versus 30 of 128 with the same buffer registered as 4K pages, and most pipelined send_zc requests come back short. Only the in-page part of the offset matters for how much memory a fragment ties up, so use offset_in_page(). This matches what zerocopy_fill_skb_from_iter() charges for the same data. Fixes: 57bebf807e2a ("io_uring/rsrc: optimise registered huge pages") Cc: stable@vger.kernel.org Signed-off-by: Louis Thiery Reviewed-by: Pavel Begunkov Reported-by: Brian Martin Closes: https://lore.kernel.org/io-uring/CAC+fX10wVVSqGnfCg+aazorsCxB34sUDV-XJiBPd6R3Kuqc-7Q@mail.gmail.com/ Tested-by: Brian Martin Link: https://patch.msgid.link/20261119232935.1708458-1-thiery.louis@gmail.com Signed-off-by: Jens Axboe --- io_uring/net.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/io_uring/net.c b/io_uring/net.c index 533afd335627a9..8afad1b2ddc010 100644 --- a/io_uring/net.c +++ b/io_uring/net.c @@ -1501,7 +1501,12 @@ static int io_sg_from_iter(struct sk_buff *skb, struct bio_vec v = mp_bvec_iter_bvec(from->bvec, bi); copied += v.bv_len; - truesize += PAGE_ALIGN(v.bv_len + v.bv_offset); + /* + * bv_offset is relative to the folio for coalesced huge page + * registrations, so only the in-page part of it matters for + * how much memory this fragment ties up. + */ + truesize += PAGE_ALIGN(v.bv_len + offset_in_page(v.bv_offset)); __skb_fill_page_desc_noacc(shinfo, frag++, v.bv_page, v.bv_offset, v.bv_len); bvec_iter_advance_single(from->bvec, &bi, v.bv_len); From 204a4125a7e3c3e414448a1dd76d161ba4bf8797 Mon Sep 17 00:00:00 2001 From: Thomas Zimmermann Date: Fri, 20 Nov 2026 16:57:58 +0100 Subject: [PATCH 1457/2102] drm/ast: Add an option to disable Write-Combine WC-mapped video memory presumably has PCI I/O bursts that interfere with real-time tasks. Seen on AST2600 hardware. Add an Kconfig option to ast for vmapping the video memory uncached if CONFIG_RT=y. If set, video-memory access is slower, but avoids I/O bursts on the PCI us. Mirrors a similar change to mgag200 in commit b593ea940623 ("drm/mgag200: Add an option to disable Write-Combine"). Signed-off-by: Thomas Zimmermann Fixes: f2fa5a99ca81 ("drm/ast: Convert ast to SHMEM") Cc: # v6.2+ Reviewed-by: Jocelyn Falempe Link: https://patch.msgid.link/20261120155821.119377-1-tzimmermann@suse.de --- drivers/gpu/drm/ast/Kconfig | 9 +++++++++ drivers/gpu/drm/ast/ast_mm.c | 13 +++++++++++++ 2 files changed, 22 insertions(+) diff --git a/drivers/gpu/drm/ast/Kconfig b/drivers/gpu/drm/ast/Kconfig index 242fbccdf84432..f2c99e99b5b44d 100644 --- a/drivers/gpu/drm/ast/Kconfig +++ b/drivers/gpu/drm/ast/Kconfig @@ -14,3 +14,12 @@ config DRM_AST is bound to the driver. These GPUs are commonly found in server chipsets. +config DRM_AST_DISABLE_WRITECOMBINE + bool "Disable Write Combine mapping of VRAM" + depends on DRM_AST && (PREEMPT_RT || COMPILE_TEST) + help + The VRAM of AST GPUs is mapped with Write-Combine to improve + performances. This can interfere with real-time tasks; even if they + are running on other CPU cores than the graphics output. + Enable this option only if you run real-time tasks on a server with + Aspeed graphics. diff --git a/drivers/gpu/drm/ast/ast_mm.c b/drivers/gpu/drm/ast/ast_mm.c index 0bc14031946491..cc882d2c172d04 100644 --- a/drivers/gpu/drm/ast/ast_mm.c +++ b/drivers/gpu/drm/ast/ast_mm.c @@ -74,6 +74,18 @@ int ast_mm_init(struct ast_device *ast) { struct drm_device *dev = &ast->base; struct pci_dev *pdev = to_pci_dev(dev->dev); +#if defined(CONFIG_DRM_AST_DISABLE_WRITECOMBINE) + resource_size_t base; + u32 vram_size; + + base = pci_resource_start(pdev, 0); + + vram_size = ast_get_vram_size(ast); + + ast->vram = devm_ioremap(dev->dev, base, vram_size); + if (!ast->vram) + return -ENOMEM; +#else resource_size_t base, size; u32 vram_size; @@ -89,6 +101,7 @@ int ast_mm_init(struct ast_device *ast) ast->vram = devm_ioremap_wc(dev->dev, base, vram_size); if (!ast->vram) return -ENOMEM; +#endif ast->vram_base = base; ast->vram_size = vram_size; From beed53bd3cb5f0b0a0aad453aa6f0b49060ff2dc Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Thu, 12 Nov 2026 17:10:25 +0000 Subject: [PATCH 1458/2102] btrfs: send: fix invalid access to inline extents in clone_range() We can't access the disk_bytenr and offset fields of a file extent item that represents an inline extent, since the extent's data starts at the offset of the disk_bytenr field and the offset field is after that, so both fields point either to inline data or beyond the file extent item in case the data is too small. Fix this by not reading the disk_bytenr and offset fields if we are dealing with an inline extent. Link: https://sashiko.dev/#/bug/linux-b662b951-0491-465b-a262-f01a108d8146 Fixes: 040ee6120cb6 ("Btrfs: send, improve clone range") Fixes: d906d49fc5f4 ("Btrfs: send, fix file corruption due to incorrect cloning operations") Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Reviewed-by: David Sterba Signed-off-by: David Sterba --- fs/btrfs/send.c | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/fs/btrfs/send.c b/fs/btrfs/send.c index 1b903e75cec0ab..3cc7749f04522a 100644 --- a/fs/btrfs/send.c +++ b/fs/btrfs/send.c @@ -5842,7 +5842,7 @@ static int clone_range(struct send_ctx *sctx, struct btrfs_path *dst_path, u8 type; u64 ext_len; u64 clone_len; - u64 clone_data_offset; + u64 clone_data_offset = 0; bool crossed_src_i_size = false; if (slot >= btrfs_header_nritems(leaf)) { @@ -5906,23 +5906,26 @@ static int clone_range(struct send_ctx *sctx, struct btrfs_path *dst_path, crossed_src_i_size = true; } - clone_data_offset = btrfs_file_extent_offset(leaf, ei); - if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte) { - clone_root->offset = key.offset; - if (clone_data_offset < data_offset && - clone_data_offset + ext_len > data_offset) { - u64 extent_offset; - - extent_offset = data_offset - clone_data_offset; - ext_len -= extent_offset; - clone_data_offset += extent_offset; - clone_root->offset += extent_offset; + if (type != BTRFS_FILE_EXTENT_INLINE) { + clone_data_offset = btrfs_file_extent_offset(leaf, ei); + if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte) { + clone_root->offset = key.offset; + if (clone_data_offset < data_offset && + clone_data_offset + ext_len > data_offset) { + u64 extent_offset; + + extent_offset = data_offset - clone_data_offset; + ext_len -= extent_offset; + clone_data_offset += extent_offset; + clone_root->offset += extent_offset; + } } } clone_len = min_t(u64, ext_len, len); - if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte && + if (type != BTRFS_FILE_EXTENT_INLINE && + btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte && clone_data_offset == data_offset) { const u64 src_end = clone_root->offset + clone_len; const u64 sectorsize = SZ_64K; From 38c94b99f8743a5b9aab864a12ecf9a06d36aeb4 Mon Sep 17 00:00:00 2001 From: Binbin Deng <18983559317@163.com> Date: Wed, 14 Oct 2026 10:37:33 +0800 Subject: [PATCH 1459/2102] btrfs: wait for a grace period before freeing a new device KASAN reports a slab-use-after-free in btrfs_statfs() walking fs_devices->devices. btrfs_init_new_device() publishes the new device with list_add_rcu() and can fail afterwards, for example with -ENOSPC in init_first_rw_device() when a user with CAP_SYS_ADMIN adds a device that is too small to a seeding filesystem mounted read-only. The error path removes the entry with list_del_rcu() and frees the object in btrfs_free_device() without waiting for a grace period, while btrfs_calc_avail_data_space() and btrfs_ioctl_fs_info() keep reading the device list under rcu_read_lock(). BUG: KASAN: slab-use-after-free in btrfs_statfs+0x11af/0x14a0 Read of size 8 at addr ffff8880096be858 by task poc/252 Call Trace: dump_stack_lvl+0x53/0x70 print_report+0xd0/0x630 ? __pfx__raw_spin_lock_irqsave+0x10/0x10 ? filename_lookup+0x1a9/0x540 ? btrfs_statfs+0x11af/0x14a0 kasan_report+0xce/0x100 ? btrfs_statfs+0x11af/0x14a0 btrfs_statfs+0x11af/0x14a0 statfs_by_dentry+0x117/0x1e0 user_statfs+0xac/0x130 ? __pfx_user_statfs+0x10/0x10 __do_sys_statfs+0x80/0xe0 ? __pfx___do_sys_statfs+0x10/0x10 do_syscall_64+0xf9/0x540 entry_SYSCALL_64_after_hwframe+0x77/0x7f Allocated by task 256: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 __kasan_kmalloc+0x8f/0xa0 __kmalloc_cache_noprof+0x158/0x370 btrfs_alloc_device+0xad/0x3e0 btrfs_init_new_device+0x3e8/0x36e0 btrfs_ioctl+0x150d/0x6c20 __x64_sys_ioctl+0x134/0x1c0 do_syscall_64+0xf9/0x540 entry_SYSCALL_64_after_hwframe+0x77/0x7f Freed by task 256: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 kasan_save_free_info+0x3b/0x60 __kasan_slab_free+0x43/0x70 kfree+0x121/0x380 btrfs_init_new_device+0x4a0/0x36e0 btrfs_ioctl+0x150d/0x6c20 __x64_sys_ioctl+0x134/0x1c0 do_syscall_64+0xf9/0x540 entry_SYSCALL_64_after_hwframe+0x77/0x7f Fix by waiting for an RCU grace period after the device is removed from the list and before it is freed.Place the synchronize_rcu() after dropping the mutexes and before the `error_trans` label. Fixes: 1f78160ce1b1 ("Btrfs: using rcu lock in the reader side of devices list") Reviewed-by: Daniel Vacek Signed-off-by: Binbin Deng <18983559317@163.com> Signed-off-by: David Sterba --- fs/btrfs/volumes.c | 1 + 1 file changed, 1 insertion(+) diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c index f1305f68b1f8ab..a049fd250746eb 100644 --- a/fs/btrfs/volumes.c +++ b/fs/btrfs/volumes.c @@ -3206,6 +3206,7 @@ int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path btrfs_update_per_profile_avail(fs_info); mutex_unlock(&fs_info->chunk_mutex); mutex_unlock(&fs_info->fs_devices->device_list_mutex); + synchronize_rcu(); error_trans: if (trans) btrfs_end_transaction(trans); From 6b456f4640f5319f1f3223cba5faddb5970ae809 Mon Sep 17 00:00:00 2001 From: Daniel Vacek Date: Fri, 30 Oct 2026 15:28:03 +0100 Subject: [PATCH 1460/2102] btrfs: fix a livelock in wait_for_commit() on PREEMPT_RT Peter reported [1] that running multiple RR tasks doing sync() on fully preemptible kernel may starve other/normal sync() tasks due to fs_info::trans_lock turned into rt_mutex. This is caused by RR tasks contending over the mutex with priority over other tasks, which in turn lack progress and they are no longer able to remove TRANS_STATE_COMPLETED transactions from the fs_info::trans_list. The offenders start looping in wait_for_commit() expecting the completed transactions to get off the trans_list but since they're bouncing the trans_lock the tasks with other/normal priority which are about to delist such transactions never get a chance to do so due to lower priority. A simple reproducer can be found in the mentioned email thread [1]. The situation can be resolved by boosting the priority of the starved tasks or dropping priority of the offenders. Thought this fix prevents the situation from happening in the first place. We simply delist the transactions before changing them to completed state. That breaks the loop condition. [1] https://lore.kernel.org/linux-btrfs/SJ0PR17MB4288C46458DCE2C015839D0FBB9E2@SJ0PR17MB4288.namprd17.prod.outlook.com/ Reported-by: Naulls, Peter Fixes: 5fd76bf31ccfe ("btrfs: fix relocation crash due to premature return from btrfs_commit_transaction()") CC: stable@vger.kernel.org # 5.15+ Tested-by: Naulls, Peter Reviewed-by: Qu Wenruo Signed-off-by: Daniel Vacek Signed-off-by: David Sterba --- fs/btrfs/disk-io.c | 18 +++++++----------- fs/btrfs/transaction.c | 15 +++++---------- 2 files changed, 12 insertions(+), 21 deletions(-) diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c index 4356e0b3368cc3..86788234d18602 100644 --- a/fs/btrfs/disk-io.c +++ b/fs/btrfs/disk-io.c @@ -4367,10 +4367,6 @@ static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info) trans->transid, dirty_bytes); btrfs_cleanup_one_transaction(trans); - if (trans == fs_info->running_transaction) - fs_info->running_transaction = NULL; - list_del_init(&trans->list); - btrfs_put_transaction(trans); } ASSERT(!found); @@ -5043,7 +5039,13 @@ void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans) EXTENT_DIRTY); btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents); - cur_trans->state =TRANS_STATE_COMPLETED; + spin_lock(&fs_info->trans_lock); + if (cur_trans == fs_info->running_transaction) + fs_info->running_transaction = NULL; + list_del_init(&cur_trans->list); + spin_unlock(&fs_info->trans_lock); + + cur_trans->state = TRANS_STATE_COMPLETED; wake_up(&cur_trans->commit_wait); } @@ -5079,12 +5081,6 @@ static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info) } btrfs_cleanup_one_transaction(t); - spin_lock(&fs_info->trans_lock); - if (t == fs_info->running_transaction) - fs_info->running_transaction = NULL; - list_del_init(&t->list); - spin_unlock(&fs_info->trans_lock); - btrfs_put_transaction(t); spin_lock(&fs_info->trans_lock); } diff --git a/fs/btrfs/transaction.c b/fs/btrfs/transaction.c index 8df7b47b09e08f..684382b514037a 100644 --- a/fs/btrfs/transaction.c +++ b/fs/btrfs/transaction.c @@ -2154,12 +2154,7 @@ static void cleanup_transaction(struct btrfs_trans_handle *trans, int err) spin_unlock(&fs_info->trans_lock); - btrfs_cleanup_one_transaction(trans->transaction); - - spin_lock(&fs_info->trans_lock); - if (cur_trans == fs_info->running_transaction) - fs_info->running_transaction = NULL; - spin_unlock(&fs_info->trans_lock); + btrfs_cleanup_one_transaction(cur_trans); if (trans->type & TRANS_SB_INTWRITER_MASK) sb_end_intwrite(fs_info->sb); @@ -2677,6 +2672,10 @@ int btrfs_commit_transaction(struct btrfs_trans_handle *trans) btrfs_clear_space_info_full(fs_info); btrfs_set_last_trans_committed(fs_info, cur_trans->transid); + + spin_lock(&fs_info->trans_lock); + list_del_init(&cur_trans->list); + spin_unlock(&fs_info->trans_lock); /* * We needn't acquire the lock here because there is no other task * which can change it. @@ -2686,10 +2685,6 @@ int btrfs_commit_transaction(struct btrfs_trans_handle *trans) wake_up(&cur_trans->commit_wait); btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED); - spin_lock(&fs_info->trans_lock); - list_del_init(&cur_trans->list); - spin_unlock(&fs_info->trans_lock); - btrfs_put_transaction(cur_trans); btrfs_put_transaction(cur_trans); From 5588a3dd3c651824507ff57522718ea53360d1df Mon Sep 17 00:00:00 2001 From: Qu Wenruo Date: Mon, 2 Nov 2026 19:58:38 +1030 Subject: [PATCH 1461/2102] btrfs: reject subvolume ids that do not fit into unsigned long fs_roots_radix is indexed by unsigned long, so on 32-bit systems the subvolume id is silently truncated to 32 bits, e.g: Subvolume 257 (0x101) and subvolume 4294967553 (0x100000101) will have the same index (0x101) on 32-bit systems. Although this should be very rare, as btrfs can reuse deleted subvolume ids, and there are other limits like anon_dev preventing us from so many subvolumes. But it's still better to address such problems, since 32 bit systems are still widely supported by the kernel. Address such rare problem by: - Add btrfs_check_subvolid() to btrfs_insert_fs_root() So that all subvolumes inserted into the fs radix tree are ensured to be no larger than ULONG_MAX. If there is a high subvolume id, it will show an error message. - Do not search the radix tree if subvolid is is too larger It's possible to pass reloc tree into btrfs_lookup_fs_root() through backref walk. And it can be very common during qgroup operations. So we don't want to flood the dmesg with error messages. Just silently reject such search silently, and searching tree reloc tree inside btrfs_lookup_fs_root() will return nothing anyway. Reviewed-by: Filipe Manana Signed-off-by: Qu Wenruo Reviewed-by: David Sterba Signed-off-by: David Sterba --- fs/btrfs/disk-io.c | 13 +++++++++++++ fs/btrfs/disk-io.h | 18 ++++++++++++++++++ fs/btrfs/ioctl.c | 6 ++++-- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c index 86788234d18602..c8abc203d24273 100644 --- a/fs/btrfs/disk-io.c +++ b/fs/btrfs/disk-io.c @@ -1129,6 +1129,15 @@ static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info, { struct btrfs_root *root; +#if BITS_PER_LONG == 32 + /* + * Roots with ids above ULONG_MAX are never inserted into the radix + * tree, and a truncated index may hit an unrelated root. + */ + if (root_id > ULONG_MAX) + return NULL; +#endif + spin_lock(&fs_info->fs_roots_radix_lock); root = radix_tree_lookup(&fs_info->fs_roots_radix, (unsigned long)root_id); @@ -1181,6 +1190,10 @@ int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info, { int ret; + ret = btrfs_check_subvolid(fs_info, btrfs_root_id(root)); + if (ret) + return ret; + ret = radix_tree_preload(GFP_NOFS); if (ret) return ret; diff --git a/fs/btrfs/disk-io.h b/fs/btrfs/disk-io.h index 290508894f7ceb..e4e9f50a2c29eb 100644 --- a/fs/btrfs/disk-io.h +++ b/fs/btrfs/disk-io.h @@ -106,6 +106,24 @@ static inline struct btrfs_root *btrfs_grab_root(struct btrfs_root *root) return NULL; } +/* + * fs_roots_radix is indexed by unsigned long, so on 32-bit systems a subvolume + * id above ULONG_MAX is truncated, and can conflict with other subvolumes. + * Such subvolumes are not supported. + */ +static inline int btrfs_check_subvolid(const struct btrfs_fs_info *fs_info, u64 subvolid) +{ +#if BITS_PER_LONG == 32 + if (unlikely(subvolid > ULONG_MAX)) { + btrfs_err_rl(fs_info, + "subvolume id %llu is too large for 32-bit systems, max supported id is %lu", + subvolid, ULONG_MAX); + return -EOVERFLOW; + } +#endif + return 0; +} + void btrfs_put_root(struct btrfs_root *root); void btrfs_mark_buffer_dirty(struct btrfs_trans_handle *trans, struct extent_buffer *buf); diff --git a/fs/btrfs/ioctl.c b/fs/btrfs/ioctl.c index 000276bb49ad6d..ed8bf8f7da1463 100644 --- a/fs/btrfs/ioctl.c +++ b/fs/btrfs/ioctl.c @@ -5051,6 +5051,7 @@ static int btrfs_ioctl_subvol_sync(struct btrfs_fs_info *fs_info, void __user *a struct btrfs_ioctl_subvol_wait args = { 0 }; signed long sched_ret; int refs; + int ret; u64 root_flags; bool wait_for_deletion = false; bool found = false; @@ -5121,8 +5122,9 @@ static int btrfs_ioctl_subvol_sync(struct btrfs_fs_info *fs_info, void __user *a } /* 32bit limitation: fs_roots_radix key is not wide enough. */ - if (sizeof(unsigned long) != sizeof(u64) && args.subvolid > U32_MAX) - return -EOVERFLOW; + ret = btrfs_check_subvolid(fs_info, args.subvolid); + if (ret < 0) + return ret; while (1) { /* Wait for the specific one. */ From 356217202a30e58b02c49c1027874a13e011c822 Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Mon, 2 Nov 2026 18:55:35 +0000 Subject: [PATCH 1462/2102] btrfs: don't propagate nodatacow mount option on files with inherited compression If we set the compression property on a directory and the filesystem was mounted with the nodatacow option, then when creating a file under that directory we get both the compression and nodatacow attributes set on the file. These are incompatible attributes as compression requires COW. This has a couple unexpected behaviours: 1) If later a user sets another attribute on the file, like immutability or append writing mode for example, the chattr command will fail with -EINVAL since we in the setattr callback (btrfs_fileattr_set()) we do some validation, through a call to check_fsflags(), that rejects having both the nodatacow and compression flags set. I.e, doing a simple: $ chattr +i file /usr/bin/chattr: Invalid argument while setting flags on file 2) The file ends up not being compressed, which is unexpected since the compression attribute set on a directory/file should have precedence over the global nodatacow mount option. Example reproducer: $ cat test.sh #!/bin/bash DEV=/dev/sdi MNT=/mnt/sdi mkfs.btrfs -f $DEV mount -o nodatacow $DEV $MNT # Create a directory with the compression attribute, so that all files # created under it inherit the compression attribute. mkdir $MNT/dir chattr +c $MNT/dir # Now create a file with some data inside the directory. xfs_io -f -c "pwrite 0 128K" $MNT/dir/foo # Now try to make the file immutable, it should work. chattr +i $MNT/dir/foo umount $MNT # Check the file has a compressed extent. It should have since # despite the fs being mounted with nodatacow, the directory has # the compression flag set and so that should take priority and # it's what makes sense. btrfs inspect-internal dump-tree -t 5 $DEV | grep -A 5 'EXTENT_DATA 0' Running it: $ ./test.sh (...) chattr: Invalid argument while setting flags on /mnt/sdi/dir/foo item 11 key (258 EXTENT_DATA 0) itemoff 15529 itemsize 53 generation 9 type 1 (regular) extent data disk byte 13631488 nr 131072 extent data offset 0 nr 131072 ram 131072 extent compression 0 (none) extent encryption 0 Fix this by updating btrfs_create_new_inode() to not apply the mount options nodatacow and nodatasum on a file that has inherited compression from its parent directory. A test case will follow soon for fstests. Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Reviewed-by: David Sterba Signed-off-by: David Sterba --- fs/btrfs/inode.c | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c index 343b6402bb3528..f602c550b5e647 100644 --- a/fs/btrfs/inode.c +++ b/fs/btrfs/inode.c @@ -6691,11 +6691,20 @@ int btrfs_create_new_inode(struct btrfs_trans_handle *trans, btrfs_set_inode_mapping_order(BTRFS_I(inode)); if (S_ISREG(inode->i_mode)) { - if (btrfs_test_opt(fs_info, NODATASUM)) - BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM; - if (btrfs_test_opt(fs_info, NODATACOW)) - BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW | - BTRFS_INODE_NODATASUM; + /* + * If we inherited compression from the parent directory, it + * takes precedence to nodatacow/nodatasum and we don't set + * compression along with nodatacow/nodatasun, otherwise if a + * user attempts to change some other attribute (say chattr +i), + * it will fail at -EINVAL. + */ + if (!(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) { + if (btrfs_test_opt(fs_info, NODATASUM)) + BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM; + if (btrfs_test_opt(fs_info, NODATACOW)) + BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW | + BTRFS_INODE_NODATASUM; + } btrfs_update_inode_mapping_flags(BTRFS_I(inode)); } From aec8248642ce734dcc2991c069e8edfcf90770c8 Mon Sep 17 00:00:00 2001 From: Qu Wenruo Date: Thu, 5 Nov 2026 14:51:16 +1030 Subject: [PATCH 1463/2102] btrfs: skip fast sync for inodes with encoded writes [BUG REPORT] Sashiko reported a bug that encoded writes can have its file extents recorded before their data reach disks. [CAUSE] An encoded write returns to the caller as soon as its bio is submitted, and its folios are not in the inode's page cache: btrfs_ioctl_encoded_write() \- btrfs_do_encoded_write() |- btrfs_alloc_ordered_extent() \- btrfs_submit_compressed_write() <- returns before the bio ends A fast fsync only waits for writeback of the folios in the page cache, so it has nothing to wait for on such an ordered extent: btrfs_sync_file() |- btrfs_get_ordered_extents_for_logging() |- filemap_fdatawait_range() <- no folio under writeback \- btrfs_log_dentry_safe() \- ... \- log_extent_csums() \- log_csums() <- csum_list may be in flight This has two problems: - fsync can return before the data of the encoded write is on disk, while the log tree describing it is already persisted. - With async data checksum generation, the sums are attached to ordered->csum_list by btrfs_csum_one_bio() before the checksums are calculated. log_extent_csums() can then log zeroed or partially calculated checksums. For buffered writes this is not a problem, as writeback of a folio ends after the bio endio, which in turn runs after the checksums are generated. [FIX] Fix it by requiring full sync for the inode which went through encoded writes. Encoded writes are mostly utilized by btrfs-receive, so it's never on the hot path. And received subvolumes are set read-only, so normally no one should even call fsync() on those inodes. Thus the cost of full fsync on encoded writes should be very acceptable. Link: https://sashiko.dev/#/patchset/8eb322321cac98013cc46dfe8d89fa58c1ad3dee.1793766229.git.wqu%40suse.com Reviewed-by: Filipe Manana Signed-off-by: Qu Wenruo Signed-off-by: David Sterba --- fs/btrfs/inode.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c index f602c550b5e647..a4acb457fc8e22 100644 --- a/fs/btrfs/inode.c +++ b/fs/btrfs/inode.c @@ -10147,6 +10147,16 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from, ret = PTR_ERR(ordered); goto out_free_reserved; } + /* + * A fast fsync can't deal with encoded writes because it neither + * dirties folios nor it waits for ordered extent completion (or finish + * its IO only) before unlocking the inode. + * The consequence is that it results in a race that can make the fast + * fsync log file extent items with the incorrect csum items, + * as the data may not reach disks, or the csum is not properly + * generated yet. + */ + btrfs_set_inode_full_sync(inode); btrfs_dec_block_group_reservations(fs_info, ins.objectid); if (start + encoded->len > inode->vfs_inode.i_size) From 035a0a1562efe1dfa3a8488f1b66992c6b0c06aa Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Mon, 16 Nov 2026 16:24:04 +0700 Subject: [PATCH 1464/2102] ASoC: atmel: mchp-i2s-mcc: Use devm_clk_get_optional() for gclk The current code is unnecessarily verbose for handling an optional clock. Use devm_clk_get_optional() to simplify it. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261116092407.514998-2-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-i2s-mcc.c | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/sound/soc/atmel/mchp-i2s-mcc.c b/sound/soc/atmel/mchp-i2s-mcc.c index cb0f3e55b05d69..9d8043a857824a 100644 --- a/sound/soc/atmel/mchp-i2s-mcc.c +++ b/sound/soc/atmel/mchp-i2s-mcc.c @@ -1073,14 +1073,10 @@ static int mchp_i2s_mcc_probe(struct platform_device *pdev) } /* Get the optional generated clock */ - dev->gclk = devm_clk_get(&pdev->dev, "gclk"); - if (IS_ERR(dev->gclk)) { - if (PTR_ERR(dev->gclk) == -EPROBE_DEFER) - return -EPROBE_DEFER; - dev_warn(&pdev->dev, - "generated clock not found: %d\n", err); - dev->gclk = NULL; - } + dev->gclk = devm_clk_get_optional(&pdev->dev, "gclk"); + if (IS_ERR(dev->gclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->gclk), + "failed to get the generated clock\n"); dev->soc = of_device_get_match_data(&pdev->dev); err = mchp_i2s_mcc_soc_data_parse(pdev, dev); From 0cce417afa5262aeaab2d1365503a4a7aa351d0b Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Mon, 16 Nov 2026 16:24:05 +0700 Subject: [PATCH 1465/2102] ASoC: atmel: mchp-i2s-mcc: Use devm_clk_get_enabled() for pclk The peripheral clock is enabled once during probe and disabled during remove. Use devm_clk_get_enabled() to automate clock management and remove the unnecessary remove callback. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261116092407.514998-3-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-i2s-mcc.c | 28 ++++------------------------ 1 file changed, 4 insertions(+), 24 deletions(-) diff --git a/sound/soc/atmel/mchp-i2s-mcc.c b/sound/soc/atmel/mchp-i2s-mcc.c index 9d8043a857824a..fe42a8c2cad3a2 100644 --- a/sound/soc/atmel/mchp-i2s-mcc.c +++ b/sound/soc/atmel/mchp-i2s-mcc.c @@ -1064,13 +1064,10 @@ static int mchp_i2s_mcc_probe(struct platform_device *pdev) if (err) return err; - dev->pclk = devm_clk_get(&pdev->dev, "pclk"); - if (IS_ERR(dev->pclk)) { - err = PTR_ERR(dev->pclk); - dev_err(&pdev->dev, - "failed to get the peripheral clock: %d\n", err); - return err; - } + dev->pclk = devm_clk_get_enabled(&pdev->dev, "pclk"); + if (IS_ERR(dev->pclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->pclk), + "failed to get/enable the peripheral clock\n"); /* Get the optional generated clock */ dev->gclk = devm_clk_get_optional(&pdev->dev, "gclk"); @@ -1087,19 +1084,11 @@ static int mchp_i2s_mcc_probe(struct platform_device *pdev) dev->regmap = regmap; platform_set_drvdata(pdev, dev); - err = clk_prepare_enable(dev->pclk); - if (err) { - dev_err(&pdev->dev, - "failed to enable the peripheral clock: %d\n", err); - return err; - } - err = devm_snd_soc_register_component(&pdev->dev, &mchp_i2s_mcc_component, &mchp_i2s_mcc_dai, 1); if (err) { dev_err(&pdev->dev, "failed to register DAI: %d\n", err); - clk_disable_unprepare(dev->pclk); return err; } @@ -1109,7 +1098,6 @@ static int mchp_i2s_mcc_probe(struct platform_device *pdev) err = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (err) { dev_err(&pdev->dev, "failed to register PCM: %d\n", err); - clk_disable_unprepare(dev->pclk); return err; } @@ -1121,20 +1109,12 @@ static int mchp_i2s_mcc_probe(struct platform_device *pdev) return 0; } -static void mchp_i2s_mcc_remove(struct platform_device *pdev) -{ - struct mchp_i2s_mcc_dev *dev = platform_get_drvdata(pdev); - - clk_disable_unprepare(dev->pclk); -} - static struct platform_driver mchp_i2s_mcc_driver = { .driver = { .name = "mchp_i2s_mcc", .of_match_table = mchp_i2s_mcc_dt_ids, }, .probe = mchp_i2s_mcc_probe, - .remove = mchp_i2s_mcc_remove, }; module_platform_driver(mchp_i2s_mcc_driver); From 3376223461b3a323342114cd7e1969fc0cc0faae Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Mon, 16 Nov 2026 16:24:06 +0700 Subject: [PATCH 1466/2102] ASoC: atmel: mchp-i2s-mcc: Request IRQ after enabling pclk Request the IRQ after enabling the peripheral clock to ensure the clock is available when the interrupt handler accesses hardware registers. This also ensures proper resource cleanup ordering, with the IRQ being released before the clock is disabled. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261116092407.514998-4-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-i2s-mcc.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sound/soc/atmel/mchp-i2s-mcc.c b/sound/soc/atmel/mchp-i2s-mcc.c index fe42a8c2cad3a2..6a54d3d67e862c 100644 --- a/sound/soc/atmel/mchp-i2s-mcc.c +++ b/sound/soc/atmel/mchp-i2s-mcc.c @@ -1059,11 +1059,6 @@ static int mchp_i2s_mcc_probe(struct platform_device *pdev) if (irq < 0) return irq; - err = devm_request_irq(&pdev->dev, irq, mchp_i2s_mcc_interrupt, 0, - dev_name(&pdev->dev), dev); - if (err) - return err; - dev->pclk = devm_clk_get_enabled(&pdev->dev, "pclk"); if (IS_ERR(dev->pclk)) return dev_err_probe(&pdev->dev, PTR_ERR(dev->pclk), @@ -1084,6 +1079,11 @@ static int mchp_i2s_mcc_probe(struct platform_device *pdev) dev->regmap = regmap; platform_set_drvdata(pdev, dev); + err = devm_request_irq(&pdev->dev, irq, mchp_i2s_mcc_interrupt, 0, + dev_name(&pdev->dev), dev); + if (err) + return err; + err = devm_snd_soc_register_component(&pdev->dev, &mchp_i2s_mcc_component, &mchp_i2s_mcc_dai, 1); From 3b112e8542862db4a92978385e0b9d3fb8064e7a Mon Sep 17 00:00:00 2001 From: Qu Wenruo Date: Thu, 5 Nov 2026 11:38:00 +1030 Subject: [PATCH 1467/2102] btrfs: fix a race between reflink and compressed writes [BUG] There is a bug report with a reproducer that can lead to transaction abort. The reproducer requires either large folios or page size larger than block size and compression: BTRFS info (device dm-2): use zstd compression, level 3 ------------[ cut here ]------------ WARNING: fs/btrfs/extent_map.c:443 at btrfs_unpin_extent_cache+0x12a/0x1a0 [btrfs], CPU#0: kworker/u41:1/1073 CPU: 0 UID: 0 PID: 1073 Comm: kworker/u41:1 Tainted: G W E 7.3.0-rc7-custom+ #111 PREEMPT(full) 181cfbec4e757bdd6c595e90a917484279074a92 Workqueue: btrfs-endio-write btrfs_work_helper [btrfs] RIP: 0010:btrfs_unpin_extent_cache+0x12a/0x1a0 [btrfs] Call Trace: btrfs_finish_one_ordered+0x8f9/0xce0 [btrfs 78b39de6ff5f8aabf4d2477512804f86456deeca] btrfs_work_helper+0xc5/0x3a0 [btrfs 78b39de6ff5f8aabf4d2477512804f86456deeca] process_scheduled_works+0x20b/0x480 worker_thread+0x1f7/0x2f0 kthread+0x101/0x130 ret_from_fork+0xd9/0x250 ret_from_fork_asm+0x11/0x20 ---[ end trace 0000000000000000 ]--- BTRFS warning (device dm-2): found extent map for inode 257 (root 5) with unexpected start offset 8192 when unpinning extent range [4096, 12288), generation 12 ------------[ cut here ]------------ WARNING: fs/btrfs/inode.c:3321 at btrfs_finish_one_ordered+0xc4b/0xce0 [btrfs], CPU#0: kworker/u41:1/1073 CPU: 0 UID: 0 PID: 1073 Comm: kworker/u41:1 Tainted: G W E 7.3.0-rc7-custom+ #111 PREEMPT(full) 181cfbec4e757bdd6c595e90a917484279074a92 Workqueue: btrfs-endio-write btrfs_work_helper [btrfs] RIP: 0010:btrfs_finish_one_ordered+0xc4b/0xce0 [btrfs] Call Trace: btrfs_work_helper+0xc5/0x3a0 [btrfs 78b39de6ff5f8aabf4d2477512804f86456deeca] process_scheduled_works+0x20b/0x480 worker_thread+0x1f7/0x2f0 kthread+0x101/0x130 ret_from_fork+0xd9/0x250 ret_from_fork_asm+0x11/0x20 ---[ end trace 0000000000000000 ]--- BTRFS error (device dm-2 state A): Transaction 12 aborted (-EUCLEAN) BTRFS: error (device dm-2 state A) in btrfs_finish_one_ordered:3321: errno=-117 Filesystem corrupted [CAUSE] There is a race between compressed write and regular write inside the same folio, that can lead to incorrect PAGECACHE_TAG_DIRTY tag to be cleared too early. In this example, we have a large folio containing 8 pages (4K page size, 4K block size), with the following layout: 0 8K 16K 24K 32K |//////////| |///| Where [4K, 12K) is dirty, and [20K, 24K) is also dirty. Writeback | Compression worker ----------------------------------+------------------------------------ writepage_delalloc() | |- run_delalloc_compressed() | | | Queueing [4K, 12K) for | | | compression. | | \- btrfs_queue_work() | | | compress_file_range() | | |- extent_range_clear_dirty_for_io() | | \- btrfs_folio_clamp_clear_dirty() | | Now range [4K, 12K) is no longer | | dirty, but also without an OE. \- run_delalloc_cow() | | For the [20K, 24K) | \- submit_one_sector() | |- btrfs_folio_clear_dirty()| | Since [20K, 24K) is the | | last dirty block, the | | folio is no longer dirty | | | |- btrfs_folio_set_writeback() Since the folio is no | longer dirty, the | PAGECACHE_TAG_DIRTY tag | is also cleared. | The above race will lead to a 32K folio that contains [4K, 12K) range that is still under compression (and should still be counted dirty), but without an OE. Then later in the reflink: Reflink | Compression worker ----------------------------------+------------------------------------ btrfs_clone_files() | | Which is to replace [4K, 8K) | | | |- btrfs_wait_ordered_range() | | |- btrfs_fdatawrite_range() | | | Nothing to do, since no | | | DIRTY tag for the folio | | | | | |- filemap_fdatawait_range() | | | The [20K, 24K) finished, | | | So no WRITEBACK tag | | | | | \- lookup OE | | No OE is created for range | | [4K, 12K) | | | | | submit_compressed_extents | | \- submit_one_async_extent | | \- btrfs_alloc_ordered_extent() | | OE for [4K, 12K) created, but | | it's too late. \- btrfs_clone() | Replace file extents for range | [4K, 8K), which will conflict | with the new compressed range | [4K, 12K) | | end_bbio_data_write([4k, 12K)) | \- btrfs_finish_ordered() | | | finish_ordered_fn() | \- btrfs_finish_one_ordered() | \- btrfs_unpin_extent_cache() | em start 8K != 4K return -EUCLEAN, transaction aborted [FIX] Do not clear the folio dirty early during compress_file_range(). The premature clearing is done through extent_range_clear_dirty_for_io(), so remove the folio dirty clearing completely from it. And since what's left is only checking the folio write protection, rename the function to extent_range_check_write_protected() instead, and slightly clean it up, so it doesn't need to return an int. Finally since the range is still dirty now, all run_delalloc_cow() callers pass @pages_dirty = true, we can remove that parameter along other involved functions. Fixes: 1d2fbb7f1f9e ("btrfs: allow compression even if the range is not page aligned") Reported-by: Breno Leitao Link: https://lore.kernel.org/linux-btrfs/ause7k_HjzUWT3D-@gmail.com/ Reviewed-by: Filipe Manana Tested-by: Breno Leitao Signed-off-by: Qu Wenruo Signed-off-by: David Sterba --- fs/btrfs/extent_io.c | 5 ++--- fs/btrfs/extent_io.h | 3 +-- fs/btrfs/inode.c | 44 ++++++++++++++------------------------------ 3 files changed, 17 insertions(+), 35 deletions(-) diff --git a/fs/btrfs/extent_io.c b/fs/btrfs/extent_io.c index 5ff630630490e3..b2739838c6462d 100644 --- a/fs/btrfs/extent_io.c +++ b/fs/btrfs/extent_io.c @@ -2879,8 +2879,7 @@ static int extent_write_cache_pages(struct address_space *mapping, * locked. */ void extent_write_locked_range(struct inode *inode, const struct folio *locked_folio, - u64 start, u64 end, struct writeback_control *wbc, - bool pages_dirty) + u64 start, u64 end, struct writeback_control *wbc) { bool found_error = false; int ret = 0; @@ -2923,7 +2922,7 @@ void extent_write_locked_range(struct inode *inode, const struct folio *locked_f cur_len = cur_end + 1 - cur; ASSERT(folio_test_locked(folio)); - if (pages_dirty && folio != locked_folio) + if (folio != locked_folio) ASSERT(folio_test_dirty(folio)); /* diff --git a/fs/btrfs/extent_io.h b/fs/btrfs/extent_io.h index d8dd2ae9ff9a8a..c55b37cb24b709 100644 --- a/fs/btrfs/extent_io.h +++ b/fs/btrfs/extent_io.h @@ -280,8 +280,7 @@ void btrfs_check_folio_write_protected(struct folio *folio); static inline void btrfs_check_folio_write_protected(struct folio *folio) { } #endif void extent_write_locked_range(struct inode *inode, const struct folio *locked_folio, - u64 start, u64 end, struct writeback_control *wbc, - bool pages_dirty); + u64 start, u64 end, struct writeback_control *wbc); int btrfs_writepages(struct address_space *mapping, struct writeback_control *wbc); int btree_writepages(struct address_space *mapping, struct writeback_control *wbc); void btrfs_btree_wait_writeback_range(struct btrfs_fs_info *fs_info, u64 start, u64 end); diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c index a4acb457fc8e22..c0200683f81e5c 100644 --- a/fs/btrfs/inode.c +++ b/fs/btrfs/inode.c @@ -120,8 +120,7 @@ static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback); static noinline int run_delalloc_cow(struct btrfs_inode *inode, struct folio *locked_folio, u64 start, - u64 end, struct writeback_control *wbc, - bool pages_dirty); + u64 end, struct writeback_control *wbc); static int data_reloc_print_warning_inode(u64 inum, u64 offset, u64 num_bytes, u64 root, void *warn_ctx) @@ -776,33 +775,29 @@ static inline void inode_should_defrag(struct btrfs_inode *inode, btrfs_add_inode_defrag(inode, small_write); } -static int extent_range_clear_dirty_for_io(struct btrfs_inode *inode, u64 start, u64 end) +static void extent_range_check_write_protected(struct btrfs_inode *inode, u64 start, u64 end) { pgoff_t index = start >> PAGE_SHIFT; const pgoff_t end_index = end >> PAGE_SHIFT; struct folio *folio; - int ret = 0; + + if (!IS_ENABLED(CONFIG_BTRFS_DEBUG)) + return; while (index <= end_index) { folio = filemap_get_folio(inode->vfs_inode.i_mapping, index); + /* Compression should have all involved folios still locked. */ if (IS_ERR(folio)) { - if (!ret) - ret = PTR_ERR(folio); + DEBUG_WARN( +"missing a folio inside the compression range, index %lu start %llu end %llu", + index, start, end); index++; continue; } - /* - * We are about to compress the folio, so it must not be mmap - * writeable or we could corrupt the data as we attempt to - * compress it. - */ btrfs_check_folio_write_protected(folio); - btrfs_folio_clamp_clear_dirty(inode->root->fs_info, folio, start, - end + 1 - start); index = folio_next_index(folio); folio_put(folio); } - return ret; } static struct folio *compressed_bio_last_folio(struct compressed_bio *cb) @@ -889,16 +884,7 @@ static void compress_file_range(struct btrfs_work *work) inode_should_defrag(inode, start, end, end - start + 1, SZ_16K); - ret = extent_range_clear_dirty_for_io(inode, start, end); - - /* - * All the folios should have been locked thus no failure. - * - * And even if some folios are missing, btrfs_compress_bio() - * would handle them correctly, so here just do an ASSERT() check for - * early logic errors. - */ - ASSERT(ret == 0); + extent_range_check_write_protected(inode, start, end); /* * We need to save i_size before now because it could change in between @@ -1014,8 +1000,7 @@ static void submit_uncompressed_range(struct btrfs_inode *inode, }; wbc_attach_fdatawrite_inode(&wbc, &inode->vfs_inode); - ret = run_delalloc_cow(inode, locked_folio, start, end, - &wbc, false); + ret = run_delalloc_cow(inode, locked_folio, start, end, &wbc); wbc_detach_inode(&wbc); if (ret < 0) { if (locked_folio) @@ -1660,8 +1645,7 @@ static bool run_delalloc_compressed(struct btrfs_inode *inode, */ static noinline int run_delalloc_cow(struct btrfs_inode *inode, struct folio *locked_folio, u64 start, - u64 end, struct writeback_control *wbc, - bool pages_dirty) + u64 end, struct writeback_control *wbc) { u64 done_offset = end; int ret; @@ -1672,7 +1656,7 @@ static noinline int run_delalloc_cow(struct btrfs_inode *inode, if (ret) return ret; extent_write_locked_range(&inode->vfs_inode, locked_folio, - start, done_offset, wbc, pages_dirty); + start, done_offset, wbc); start = done_offset + 1; } @@ -2454,7 +2438,7 @@ int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct folio *locked_fol return 1; if (zoned) - return run_delalloc_cow(inode, locked_folio, start, end, wbc, true); + return run_delalloc_cow(inode, locked_folio, start, end, wbc); else return cow_file_range(inode, locked_folio, start, end, NULL, 0); } From e35cdd54ef7779e97e8057d30ebb432974df60f9 Mon Sep 17 00:00:00 2001 From: Mikolaj Kucharski Date: Sun, 22 Nov 2026 21:38:46 +0000 Subject: [PATCH 1468/2102] ASoC: amd: yc: Add DMI quirk for Xiaomi REDMI Book 14 2025 (AMD) The internal digital microphones on the Xiaomi REDMI Book 14 2025 (AMD), board TM2422, are not detected because the BIOS exposes neither the _WOV method nor the AcpDmicConnected property. The ACP6x PCI driver creates the acp_yc_mach platform device, but acp6x_probe() returns -ENODEV, so no capture card is registered. Add a DMI quirk entry for this board, in the same way as for the related TM2423 board. DMI information: sys_vendor: XIAOMI product_name: REDMI Book 14 2025(AMD) board_vendor: XIAOMI board_name: TM2422 bios_version: RMARB4B1P0606 The ACP is PCI 1022:15e2 rev 0x60, subsystem 1d72:2422. Diagnosis and patch were prepared with the help of an AI coding assistant (Claude Code); the change was reviewed and tested by the submitter. Signed-off-by: Mikolaj Kucharski Link: https://patch.msgid.link/awNg5lUNAYmZ2tOx@gdkpeagp.my.home.arpa Signed-off-by: Mark Brown --- sound/soc/amd/yc/acp6x-mach.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/sound/soc/amd/yc/acp6x-mach.c b/sound/soc/amd/yc/acp6x-mach.c index f636b5ba5b0720..766d493ba9cb2c 100644 --- a/sound/soc/amd/yc/acp6x-mach.c +++ b/sound/soc/amd/yc/acp6x-mach.c @@ -955,6 +955,13 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { DMI_MATCH(DMI_BOARD_NAME, "TM2423"), } }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "XIAOMI"), + DMI_MATCH(DMI_BOARD_NAME, "TM2422"), + } + }, { .driver_data = &acp6x_card, .matches = { From 6b3f779dcac4ea16e232019b68650395ad55f5a2 Mon Sep 17 00:00:00 2001 From: Stefan Ghetu Date: Mon, 16 Nov 2026 11:37:47 +0200 Subject: [PATCH 1469/2102] ASoC: fsl_asrc_m2m: fix out-of-bounds write when draining the output FIFO asrc_read_last_fifo() checks the FIFO fill level, a number of frames, against a length in bytes, and ignores the frames already drained by previous iterations of its retry loop. With an output length close to the 512 KiB buffer size, which userspace controls through the task input size and formats, the drain writes past the end of the output buffer: 312 bytes for 10 channels of S24_LE with 8 frames left in the FIFO. Check the space needed by all drained frames in bytes. Fixes: 24a01710f627 ("ASoC: fsl_asrc_m2m: Add memory to memory function") Signed-off-by: Stefan Ghetu Reviewed-by: Shengjiu Wang Link: https://patch.msgid.link/20261116093751.138455-2-stefan.ghetu@nxp.com Signed-off-by: Mark Brown --- sound/soc/fsl/fsl_asrc_m2m.c | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/sound/soc/fsl/fsl_asrc_m2m.c b/sound/soc/fsl/fsl_asrc_m2m.c index 21e5cafaf8235f..5e9dc5b956fa54 100644 --- a/sound/soc/fsl/fsl_asrc_m2m.c +++ b/sound/soc/fsl/fsl_asrc_m2m.c @@ -53,21 +53,27 @@ static void asrc_read_last_fifo(struct fsl_asrc_pair *pair, void *dma_vaddr, u32 { struct fsl_asrc *asrc = pair->asrc; enum asrc_pair_index index = pair->index; - u32 i, reg, size, t_size = 0, width; + u32 i, reg, size, t_size = 0, width, sample_bytes, frame_bytes; u32 *reg32 = NULL; u16 *reg16 = NULL; u8 *reg24 = NULL; width = snd_pcm_format_physical_width(pair->sample_format[OUT]); - if (width == 32) + if (width == 32) { reg32 = dma_vaddr + *length; - else if (width == 16) + sample_bytes = 4; + } else if (width == 16) { reg16 = dma_vaddr + *length; - else + sample_bytes = 2; + } else { reg24 = dma_vaddr + *length; + sample_bytes = 3; + } + + frame_bytes = pair->channels * sample_bytes; retry: size = asrc->get_output_fifo_size(pair); - if (size + *length > ASRC_M2M_BUFFER_SIZE) + if (*length + (t_size + size) * frame_bytes > ASRC_M2M_BUFFER_SIZE) goto end; for (i = 0; i < size * pair->channels; i++) { @@ -89,12 +95,7 @@ static void asrc_read_last_fifo(struct fsl_asrc_pair *pair, void *dma_vaddr, u32 goto retry; end: /* Update payload length */ - if (reg32) - *length += t_size * pair->channels * 4; - else if (reg16) - *length += t_size * pair->channels * 2; - else - *length += t_size * pair->channels * 3; + *length += t_size * frame_bytes; } /* config dma channel */ From fbeac9352de6584bd5eb7c23d2f224339772c992 Mon Sep 17 00:00:00 2001 From: Stefan Ghetu Date: Mon, 16 Nov 2026 11:37:48 +0200 Subject: [PATCH 1470/2102] ASoC: fsl_asrc: fix pair ownership on repeated or failed hw_params hw_params() can be called again without hw_free() in between, and hw_free() is also called after a failed hw_params(). fsl_asrc_request_pair() always takes a new pair, so a second hw_params() leaves the stream in two asrc->pair[] entries. Only one is released, and after close the other points to freed memory, which is dereferenced by fsl_asrc_isr() and fsl_asrc_m2m_suspend(). After a failed hw_params(), fsl_asrc_release_pair() releases a stale index that may belong to another running stream. Keep the owned pair and only update its channels when it is requested again, and ignore a pair the stream does not own on release. Fixes: 3117bb3109dc ("ASoC: fsl_asrc: Add ASRC ASoC CPU DAI and platform drivers") Signed-off-by: Stefan Ghetu Reviewed-by: Shengjiu Wang Link: https://patch.msgid.link/20261116093751.138455-3-stefan.ghetu@nxp.com Signed-off-by: Mark Brown --- sound/soc/fsl/fsl_asrc.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/sound/soc/fsl/fsl_asrc.c b/sound/soc/fsl/fsl_asrc.c index be33ad3e00ae33..ea79bdae9cf536 100644 --- a/sound/soc/fsl/fsl_asrc.c +++ b/sound/soc/fsl/fsl_asrc.c @@ -216,6 +216,8 @@ static void fsl_asrc_sel_proc(int inrate, int outrate, * It assigns pair by the order of A->C->B because allocation of pair B, * within range [ANCA, ANCA+ANCB-1], depends on the channels of pair A * while pair A and pair C are comparatively independent. + * + * If @pair already owns a pair, it is kept and only its channels are updated. */ static int fsl_asrc_request_pair(int channels, struct fsl_asrc_pair *pair) { @@ -226,6 +228,19 @@ static int fsl_asrc_request_pair(int channels, struct fsl_asrc_pair *pair) guard(spinlock_irqsave)(&asrc->lock); + if (asrc->pair[pair->index] == pair) { + if (asrc->channel_avail + pair->channels < channels) { + dev_err(dev, "can't afford required channels: %d\n", channels); + return -EINVAL; + } + + asrc->channel_avail += pair->channels; + asrc->channel_avail -= channels; + pair->channels = channels; + + return 0; + } + for (i = ASRC_PAIR_A; i < ASRC_PAIR_MAX_NUM; i++) { if (asrc->pair[i] != NULL) continue; @@ -257,12 +272,19 @@ static int fsl_asrc_request_pair(int channels, struct fsl_asrc_pair *pair) * @pair: pair to release * * It clears the resource from asrc and releases the occupied channels. + * Nothing is done if @pair does not own a pair. */ static void fsl_asrc_release_pair(struct fsl_asrc_pair *pair) { struct fsl_asrc *asrc = pair->asrc; enum asrc_pair_index index = pair->index; + /* Only the owner clears its entry, so it cannot change after this check */ + scoped_guard(spinlock_irqsave, &asrc->lock) { + if (asrc->pair[index] != pair) + return; + } + /* Make sure the pair is disabled */ regmap_update_bits(asrc->regmap, REG_ASRCTR, ASRCTR_ASRCEi_MASK(index), 0); From 0d02516a94b47637acaad8e7a83c3a810402e70a Mon Sep 17 00:00:00 2001 From: Stefan Ghetu Date: Mon, 16 Nov 2026 11:37:49 +0200 Subject: [PATCH 1471/2102] ASoC: fsl_asrc_dma: release DMA channels on repeated hw_params fsl_asrc_dma_hw_params() requests new DMA channels on every call and overwrites the previous ones, which are leaked when hw_params() is called again without hw_free(). Its Back-End error path also releases a channel without clearing the pointer, so the following hw_free() releases it a second time. Release the channels of a previous call first, and clear the pointer in the error path. Fixes: 3117bb3109dc ("ASoC: fsl_asrc: Add ASRC ASoC CPU DAI and platform drivers") Fixes: 36124fb19f1a ("ASoC: fsl_asrc_dma: Fix dma_chan leak when config DMA channel failed") Signed-off-by: Stefan Ghetu Reviewed-by: Shengjiu Wang Link: https://patch.msgid.link/20261116093751.138455-4-stefan.ghetu@nxp.com Signed-off-by: Mark Brown --- sound/soc/fsl/fsl_asrc_dma.c | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/sound/soc/fsl/fsl_asrc_dma.c b/sound/soc/fsl/fsl_asrc_dma.c index b417de6abebe4a..5ba4bdeff01915 100644 --- a/sound/soc/fsl/fsl_asrc_dma.c +++ b/sound/soc/fsl/fsl_asrc_dma.c @@ -124,6 +124,19 @@ static int fsl_asrc_dma_trigger(struct snd_soc_component *component, return 0; } +static void fsl_asrc_dma_release_chans(struct fsl_asrc_pair *pair, u8 dir) +{ + if (pair->dma_chan[!dir]) + dma_release_channel(pair->dma_chan[!dir]); + + /* release dev_to_dev chan if we aren't reusing the Back-End one */ + if (pair->dma_chan[dir] && pair->req_dma_chan) + dma_release_channel(pair->dma_chan[dir]); + + pair->dma_chan[!dir] = NULL; + pair->dma_chan[dir] = NULL; +} + static int fsl_asrc_dma_hw_params(struct snd_soc_component *component, struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) @@ -190,6 +203,9 @@ static int fsl_asrc_dma_hw_params(struct snd_soc_component *component, dma_params_fe->addr = asrc->paddr + asrc->get_fifo_addr(!dir, index); dma_params_fe->maxburst = dma_params_be->maxburst; + /* hw_params() may be called again without hw_free() in between */ + fsl_asrc_dma_release_chans(pair, dir); + tmp_chan = asrc->get_dma_channel(pair, !dir); if (IS_ERR(tmp_chan)) { dev_err(dev, "failed to request DMA channel\n"); @@ -342,6 +358,7 @@ static int fsl_asrc_dma_hw_params(struct snd_soc_component *component, dev_err(dev, "failed to config DMA channel for Back-End\n"); if (pair->req_dma_chan) dma_release_channel(pair->dma_chan[dir]); + pair->dma_chan[dir] = NULL; return ret; } @@ -356,15 +373,7 @@ static int fsl_asrc_dma_hw_free(struct snd_soc_component *component, struct fsl_asrc_pair *pair = runtime->private_data; u8 dir = tx ? OUT : IN; - if (pair->dma_chan[!dir]) - dma_release_channel(pair->dma_chan[!dir]); - - /* release dev_to_dev chan if we aren't reusing the Back-End one */ - if (pair->dma_chan[dir] && pair->req_dma_chan) - dma_release_channel(pair->dma_chan[dir]); - - pair->dma_chan[!dir] = NULL; - pair->dma_chan[dir] = NULL; + fsl_asrc_dma_release_chans(pair, dir); return 0; } From f50dfefe6d4dd8cf5e826353de21228b9f073e68 Mon Sep 17 00:00:00 2001 From: Stefan Ghetu Date: Mon, 16 Nov 2026 11:37:50 +0200 Subject: [PATCH 1472/2102] ASoC: fsl_easrc: fix context ownership on repeated hw_params hw_params() can be called again without hw_free() in between. fsl_easrc_hw_params() then requests a second context while the stream still owns the first one, which is never released. After close, that easrc->pair[] entry points to freed memory and is dereferenced by fsl_easrc_runtime_resume() on the next open. The EASRC slots depend on the number of channels, so release the owned context before requesting a new one, and make fsl_easrc_release_context() ignore a context it does not own. Fixes: 955ac624058f ("ASoC: fsl_easrc: Add EASRC ASoC CPU DAI drivers") Signed-off-by: Stefan Ghetu Reviewed-by: Shengjiu Wang Link: https://patch.msgid.link/20261116093751.138455-5-stefan.ghetu@nxp.com Signed-off-by: Mark Brown --- sound/soc/fsl/fsl_easrc.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/sound/soc/fsl/fsl_easrc.c b/sound/soc/fsl/fsl_easrc.c index 5c5002537951ee..b7a429170794fe 100644 --- a/sound/soc/fsl/fsl_easrc.c +++ b/sound/soc/fsl/fsl_easrc.c @@ -1347,6 +1347,10 @@ static void fsl_easrc_release_context(struct fsl_asrc_pair *ctx) guard(spinlock_irqsave)(&easrc->lock); + /* Nothing to release if the context is not owned by @ctx */ + if (easrc->pair[ctx->index] != ctx) + return; + fsl_easrc_release_slot(easrc, ctx->index); easrc->channel_avail += ctx->channels; @@ -1500,6 +1504,12 @@ static int fsl_easrc_hw_params(struct snd_pcm_substream *substream, snd_pcm_format_t format = params_format(params); int ret; + /* hw_params() may be called again without hw_free() in between */ + if (ctx_priv->ctx_streams & BIT(substream->stream)) { + ctx_priv->ctx_streams &= ~BIT(substream->stream); + fsl_easrc_release_context(ctx); + } + ret = fsl_easrc_request_context(channels, ctx); if (ret) { dev_err(dev, "failed to request context\n"); From f0277994dbd09cc45d600c2f86cbfde9c17c6fcf Mon Sep 17 00:00:00 2001 From: Stefan Ghetu Date: Mon, 16 Nov 2026 11:37:51 +0200 Subject: [PATCH 1473/2102] ASoC: fsl_asrc_m2m: allow only one task at a time per stream All tasks of a stream share one pair and one set of DMA channels, and get_caps() advertises a single fragment, but the compress core allows up to 64 tasks. A second task requests the pair again and overwrites the DMA channels. Freeing both tasks then releases the same channels twice and leaves a stale asrc->pair[] entry after close. Return -EBUSY from task_create() while a task exists, and clear the DMA channel pointers once they are released. Fixes: 24a01710f627 ("ASoC: fsl_asrc_m2m: Add memory to memory function") Signed-off-by: Stefan Ghetu Reviewed-by: Shengjiu Wang Link: https://patch.msgid.link/20261116093751.138455-6-stefan.ghetu@nxp.com Signed-off-by: Mark Brown --- sound/soc/fsl/fsl_asrc_m2m.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/sound/soc/fsl/fsl_asrc_m2m.c b/sound/soc/fsl/fsl_asrc_m2m.c index 5e9dc5b956fa54..0537a8aff515e0 100644 --- a/sound/soc/fsl/fsl_asrc_m2m.c +++ b/sound/soc/fsl/fsl_asrc_m2m.c @@ -470,6 +470,10 @@ static int fsl_asrc_m2m_comp_task_create(struct snd_compr_stream *stream, struct dma_chan *tmp_chan; int ret; + /* All tasks share the pair and DMA channels: one task at a time */ + if (pair->dma_chan[IN]) + return -EBUSY; + exp_info_in.ops = &fsl_asrc_m2m_dma_buf_ops; exp_info_in.size = ASRC_M2M_BUFFER_SIZE; exp_info_in.flags = O_RDWR; @@ -526,6 +530,7 @@ static int fsl_asrc_m2m_comp_task_create(struct snd_compr_stream *stream, err_dma_channel_out: dma_release_channel(pair->dma_chan[IN]); + pair->dma_chan[IN] = NULL; err_dma_channel_in: if (asrc->m2m_unprepare) asrc->m2m_unprepare(pair); @@ -570,6 +575,8 @@ static int fsl_asrc_m2m_comp_task_free(struct snd_compr_stream *stream, dma_release_channel(pair->dma_chan[IN]); if (pair->dma_chan[OUT]) dma_release_channel(pair->dma_chan[OUT]); + pair->dma_chan[IN] = NULL; + pair->dma_chan[OUT] = NULL; return 0; } From a636989f93b4f70df0e44dd3025ba13c05266053 Mon Sep 17 00:00:00 2001 From: Hugo Sales Date: Sat, 14 Nov 2026 11:51:52 +0000 Subject: [PATCH 1474/2102] cpufreq: intel_pstate: Refresh cpuinfo.max_freq when a CPU goes online A write to no_turbo or a change in the HWP capabilities updates policy->cpuinfo.max_freq through intel_pstate_update_max_freq(), which gets the policy with cpufreq_cpu_get(). That returns NULL for an offline CPU, so its policy keeps the old value. When the CPU comes back, the core reuses the policy and calls ->online(), and intel_pstate_cpu_online() doesn't recompute cpuinfo.max_freq either. Before commit 4adcf2e5829f ("cpufreq: intel_pstate: Add ->offline and ->online callbacks"), ->init() ran on every online and set it Turning turbo on while a CPU is offline leaves that CPU at the non-turbo maximum once it's back, while the other CPUs report the turbo frequency. In the reverse order the CPU keeps the turbo maximum with turbo off Set cpuinfo.max_freq at the end of intel_pstate_cpu_online(), after HWP is enabled again, the same way __intel_pstate_update_max_freq() does. cpufreq_online() applies the policy limits after that. Hold the CPU hotplug lock in store_no_turbo(), so a CPU can't come online between the no_turbo store and the update of the online CPUs Fixes: 4adcf2e5829f ("cpufreq: intel_pstate: Add ->offline and ->online callbacks") Reported-by: Ximing Zhang Closes: https://lore.kernel.org/all/20261108071225.54656-1-xzhangjr@gmail.com/ Signed-off-by: Hugo Sales Tested-by: Ximing Zhang [ rjw: Renamed the new function ] Link: https://patch.msgid.link/20261114-intel-pstate-online-max-freq-v1-1-1bbdae2b4986@hsal.es Signed-off-by: Rafael J. Wysocki --- drivers/cpufreq/intel_pstate.c | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/drivers/cpufreq/intel_pstate.c b/drivers/cpufreq/intel_pstate.c index c78dcd681511cc..d3650a6e37b548 100644 --- a/drivers/cpufreq/intel_pstate.c +++ b/drivers/cpufreq/intel_pstate.c @@ -1426,16 +1426,24 @@ static void intel_pstate_update_policies(void) cpufreq_update_policy(cpu); } -static void __intel_pstate_update_max_freq(struct cpufreq_policy *policy, - struct cpudata *cpudata) +static void __intel_pstate_update_cpuinfo_max_freq(struct cpufreq_policy *policy, + struct cpudata *cpudata) { - guard(cpufreq_policy_write)(policy); + lockdep_assert_held_write(&policy->rwsem); if (hwp_active) intel_pstate_get_hwp_cap(cpudata); policy->cpuinfo.max_freq = READ_ONCE(global.no_turbo) ? cpudata->pstate.max_freq : cpudata->pstate.turbo_freq; +} + +static void __intel_pstate_update_max_freq(struct cpufreq_policy *policy, + struct cpudata *cpudata) +{ + guard(cpufreq_policy_write)(policy); + + __intel_pstate_update_cpuinfo_max_freq(policy, cpudata); refresh_frequency_limits(policy); } @@ -1569,6 +1577,12 @@ static ssize_t store_no_turbo(struct kobject *a, struct kobj_attribute *b, return -EINVAL; guard(mutex)(&intel_pstate_driver_lock); + /* + * intel_pstate_update_max_freq() skips offline CPUs, and a CPU coming + * online reads global.no_turbo in intel_pstate_cpu_online(). Keep CPUs + * from coming online until every online CPU has the new limit + */ + guard(cpus_read_lock)(); if (!intel_pstate_driver) return -EAGAIN; @@ -3019,6 +3033,14 @@ static int intel_pstate_cpu_online(struct cpufreq_policy *policy) hybrid_update_capacity(cpu); } + /* + * intel_pstate_update_max_freq() skips offline CPUs, so the turbo + * setting or the HWP capabilities may have changed since this CPU + * went offline. Read the HWP capabilities only once HWP is enabled + * again + */ + __intel_pstate_update_cpuinfo_max_freq(policy, cpu); + return 0; } From 52424a7805a05286743a5e9cb2dfe6548480b4af Mon Sep 17 00:00:00 2001 From: Yu Zhang Date: Fri, 13 Nov 2026 14:55:02 +1000 Subject: [PATCH 1475/2102] thermal: sysfs: take the zone lock in the tzp attribute handlers The thermal zone parameter (tz->tzp) sysfs attributes - sustainable_power, k_po, k_pu, k_i, k_d, integral_cutoff, slope and offset - dereference tz->tzp without holding the zone lock: if (!tz->tzp) return -EIO; ... tz->tzp->name = value; For a zone registered without thermal zone parameters (tzp == NULL at registration - the thermal testing zones, ACPI thermal and every driver using thermal_zone_device_register_with_trips(..., NULL, ...)), power_allocator_bind() allocates tz->tzp and power_allocator_unbind() frees it and sets it back to NULL, both under the zone lock: tz->tzp = kzalloc(sizeof(*tz->tzp), GFP_KERNEL); ... params->allocated_tzp = true; /* unbind */ if (params->allocated_tzp) { kfree(tz->tzp); tz->tzp = NULL; } bind/unbind run from policy_store() -> thermal_zone_device_set_policy() under the zone lock when the governor is switched to or away from power_allocator. The tzp attribute handlers take no lock, so a read or write of one of these files racing a governor switch dereferences a freed tz->tzp or a NULL pointer. The read side (0644) is reachable by an unprivileged user. KASAN, one test thermal zone, one loop switching the policy between power_allocator and step_wise and one loop writing k_pu, panics in seconds: BUG: KASAN: slab-use-after-free in k_pu_store+0xd7/0x130 Write of size 4 at addr ffff8880064e5c94 by task init k_pu_store+0xd7/0x130 dev_attr_store+0x46/0x70 sysfs_kf_write+0xed/0x110 kernfs_fop_write_iter+0x29f/0x380 vfs_write+0x5df/0x950 ksys_write+0xfd/0x1e0 Allocated by task: power_allocator_bind+0x51a/0x600 thermal_set_governor+0x86/0x170 thermal_zone_device_set_policy+0x58/0xb0 Freed by task: power_allocator_unbind+0xad/0xd0 thermal_set_governor+0x57/0x170 thermal_zone_device_set_policy+0x58/0xb0 Take the zone lock in the tzp attribute handlers, as mode_show() and weight_store() already do ("Don't race with governors using the 'weight' value"). The governor already reads these fields under the zone lock, so this also serialises the PID constant updates against a running power_allocator. Fixes: f5cbb182586e ("thermal: power_allocator: don't require tzp to be present for the thermal zone") Cc: stable@vger.kernel.org Signed-off-by: Yu Zhang Link: https://patch.msgid.link/20261113045502.68053-1-yuz08559@gmail.com Signed-off-by: Rafael J. Wysocki --- drivers/thermal/thermal_sysfs.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/thermal/thermal_sysfs.c b/drivers/thermal/thermal_sysfs.c index 47daba943a7644..0c2313c794272d 100644 --- a/drivers/thermal/thermal_sysfs.c +++ b/drivers/thermal/thermal_sysfs.c @@ -258,6 +258,8 @@ sustainable_power_show(struct device *dev, struct device_attribute *devattr, { struct thermal_zone_device *tz = to_thermal_zone(dev); + guard(thermal_zone)(tz); + if (tz->tzp) return sysfs_emit(buf, "%u\n", tz->tzp->sustainable_power); else @@ -271,6 +273,8 @@ sustainable_power_store(struct device *dev, struct device_attribute *devattr, struct thermal_zone_device *tz = to_thermal_zone(dev); u32 sustainable_power; + guard(thermal_zone)(tz); + if (!tz->tzp) return -EIO; @@ -289,6 +293,8 @@ sustainable_power_store(struct device *dev, struct device_attribute *devattr, { \ struct thermal_zone_device *tz = to_thermal_zone(dev); \ \ + guard(thermal_zone)(tz); \ + \ if (!tz->tzp) \ return -EIO; \ \ @@ -302,6 +308,8 @@ sustainable_power_store(struct device *dev, struct device_attribute *devattr, struct thermal_zone_device *tz = to_thermal_zone(dev); \ s32 value; \ \ + guard(thermal_zone)(tz); \ + \ if (!tz->tzp) \ return -EIO; \ \ From ed1e119c27819d710400308753d8a933bb5b5f0e Mon Sep 17 00:00:00 2001 From: Zhu Jun Date: Thu, 19 Nov 2026 15:58:59 +0800 Subject: [PATCH 1476/2102] ASoC: sti: uniperif: Propagate the IRQ lookup error The uniperipheral driver converts any error from platform_get_irq() to -ENXIO. This also masks -EPROBE_DEFER when an interrupt provider is not ready, preventing the device core from retrying probe. Return the error from platform_get_irq() directly. Fixes: f3bd847eb0a7 ("ASoC: sti: Add uniperipheral dai driver") Signed-off-by: Zhu Jun Link: https://patch.msgid.link/20261119075859.50201-1-zhujun2@cmss.chinamobile.com Signed-off-by: Mark Brown --- sound/soc/sti/sti_uniperif.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/sti/sti_uniperif.c b/sound/soc/sti/sti_uniperif.c index 3fbd9fee94acab..d30d5b3efad6c4 100644 --- a/sound/soc/sti/sti_uniperif.c +++ b/sound/soc/sti/sti_uniperif.c @@ -425,7 +425,7 @@ static int sti_uniperiph_cpu_dai_of(struct device_node *node, uni->irq = platform_get_irq(priv->pdev, 0); if (uni->irq < 0) - return -ENXIO; + return uni->irq; uni->type = dev_data->type; From 9383a7fdcb27142d97e65fc76f28475018980b35 Mon Sep 17 00:00:00 2001 From: Cheng Yongkang Date: Mon, 26 Oct 2026 03:51:09 -0700 Subject: [PATCH 1477/2102] btrfs: remove devid kobject when deleting a missing device btrfs_rm_device() removes the sysfs device entry only when device->bdev_file is non-NULL. A missing device (created by add_missing_dev() for an absent disk) has bdev_file == NULL, but btrfs_sysfs_add_device() still registers its devid kobject under /sys/fs/btrfs//devinfo/. When such a device is deleted, btrfs_free_device() frees the btrfs_device while the devid kobject remains registered. The kobject is embedded in the freed btrfs_device and its show functions use container_of() to reach it, so reading any devinfo attribute is a use-after-free: BUG: KASAN: slab-use-after-free in sysfs_kf_seq_show+0x157/0x490 Read of size 8 at addr ffff88801d8172a8 by task poc/9385 ... Freed by task 9385: kfree btrfs_rm_device+0x11ee/0x17b0 btrfs_ioctl_rm_dev+0x265/0x400 Allocated by task 9390: btrfs_alloc_device+0x7e/0x400 device_list_add btrfs_scan_one_device btrfs_control_ioctl The freed object is kmalloc-1k and the faulting access is 680 bytes inside it (offsetof(struct btrfs_device, devid_kobj) = 640 plus offsetof(struct kobject, ktype) = 40), confirming the embedded devid_kobj. btrfs_sysfs_remove_device() already skips the block-device link when device->bdev is NULL and only touches the devid kobject when it is initialized. Call it for missing devices too. Fixes: 668e48af7a94 ("btrfs: sysfs, add devid/dev_state kobject and device attributes") Reviewed-by: Qu Wenruo Assisted-by: LLM Signed-off-by: Cheng Yongkang Reviewed-by: David Sterba Signed-off-by: David Sterba --- fs/btrfs/volumes.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c index a049fd250746eb..d297acfcf2fa6a 100644 --- a/fs/btrfs/volumes.c +++ b/fs/btrfs/volumes.c @@ -2475,11 +2475,11 @@ int btrfs_rm_device(struct btrfs_fs_info *fs_info, btrfs_assign_next_active_device(device, NULL); - if (device->bdev_file) { + if (device->bdev_file) cur_devices->open_devices--; - /* remove sysfs entry */ - btrfs_sysfs_remove_device(device); - } + + /* Remove sysfs entry, including for a missing device. */ + btrfs_sysfs_remove_device(device); num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1; btrfs_set_super_num_devices(fs_info->super_copy, num_devices); From 016bbc403305b3d5d61e5a1b543bd69dc7c813c3 Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Fri, 6 Nov 2026 17:42:42 +0000 Subject: [PATCH 1478/2102] btrfs: drop the link count of a subvolume inode when deleting the subvolume When we delete a subvolume we don't drop the link count of the subvolume's inode. This is harmless in general, however if someone is holding an open file descriptor on the inode while and after the subvolume is deleted, the subvolume will still be listed by btrfs-progs. Example reproducer: $ cat test.sh #!/bin/bash DEV=/dev/sdi MNT=/mnt/sdi mkfs.btrfs -f $DEV mount $DEV $MNT btrfs subvolume create $MNT/sv echo "*** Setting up inotify ***" inotifywait -m $MNT/sv & sleep 1 echo "*** Setup done ***" echo "*** Deleting subvolume ***" btrfs subvolume delete $MNT/sv echo "*** Subvolume deleted ***" echo "*** Sleeping and syncing ***" sleep 30 btrfs filesystem sync $MNT echo "*** Listing subvolumes ***" btrfs subvolume list -d $MNT echo "*** Killing inotify and syncing ***" kill %1 sleep 5 btrfs filesystem sync $MNT echo "*** Listing subvolumes again ***" btrfs subvolume list -d $MNT echo "*** Done ***" umount $MNT When running this, the first subvolume listing still shows the deleted subvolume and inotify does not report the subvolume as deleted: $ ./test.sh (...) Create subvolume '/mnt/sdi/sv' *** Setting up inotify *** Setting up watches. Watches established. *** Setup done *** *** Deleting subvolume *** Delete subvolume 256 (no-commit): '/mnt/sdi/sv' /mnt/sdi/sv/ OPEN,ISDIR /mnt/sdi/sv/ CLOSE_NOWRITE,CLOSE,ISDIR *** Subvolume deleted *** *** Sleeping and syncing *** *** Listing subvolumes *** ID 256 gen 9 top level 0 path DELETED *** Killing inotify and syncing *** *** Listing subvolumes again *** *** Done *** Fix this by dropping the subvolume's inode link count when we delete a subvolume. After this, running the reproducer gives us: $ ./test.sh (...) Create subvolume '/mnt/sdi/sv' *** Setting up inotify *** Setting up watches. Watches established. *** Setup done *** *** Deleting subvolume *** Delete subvolume 256 (no-commit): '/mnt/sdi/sv' /mnt/sdi/sv/ OPEN,ISDIR /mnt/sdi/sv/ CLOSE_NOWRITE,CLOSE,ISDIR /mnt/sdi/sv/ DELETE_SELF *** Subvolume deleted *** *** Sleeping and syncing *** *** Listing subvolumes *** *** Killing inotify and syncing *** *** Listing subvolumes again *** *** Done *** The subvolume is no longer listed after deleting it while inotifywait is running and inotifywait reports the deletion. Reported-by: Alex Link: https://lore.kernel.org/linux-btrfs/18e431317f832f21-26f56778@a-workstation/ Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Reviewed-by: David Sterba Signed-off-by: David Sterba --- fs/btrfs/inode.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c index c0200683f81e5c..48c41f6390b24d 100644 --- a/fs/btrfs/inode.c +++ b/fs/btrfs/inode.c @@ -4871,6 +4871,7 @@ int btrfs_delete_subvolume(struct btrfs_inode *dir, struct dentry *dentry) out_up_write: up_write(&fs_info->subvol_sem); if (!ret) { + drop_nlink(inode); d_invalidate(dentry); btrfs_prune_dentries(dest); ASSERT(dest->send_in_progress == 0); @@ -5630,6 +5631,14 @@ void btrfs_evict_inode(struct inode *inode) if (is_bad_inode(inode)) goto out; + /* + * For a deleted subvolume we drop the link count to 0 and we don't need + * to truncate items in its btree (which is dropped all at once). + */ + if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID && + btrfs_root_refs(&root->root_item) == 0) + goto out; + if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) goto out; From ad4bb983915d8588dc9dd3aeb60cf58aff574e3b Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Tue, 10 Nov 2026 19:14:34 +0000 Subject: [PATCH 1479/2102] btrfs: fix race between concurrent sync direct IO writes If we have a direct IO write within i_size, we lock the inode's VFS lock in shared mode, which allows for concurrent direct IO writes within different ranges of the file, which is an important optimization for many applications such as databases. However if we have a sync direct IO write within i_size, it locks the inode in shared mode and then enters fsync through the call to the iomap_dio_complete() function from iomap using the shared lock. This means that if we have another concurrent direct IO write that locks the inode in shared mode and the fsync is in fast mode (the inode flag BTRFS_INODE_NEEDS_FULL_SYNC is not set), the fsync does not wait for the ordered extent created by the concurrent direct IO write to complete before logging its extent map. The fsync code relies on direct IO writes to create ordered extents and wait for their IO to finish while holding the inode's lock, while the fsync should hold the inode lock in exclusive mode. This means that this race can end up persisting a log tree with file extent items that point to extents that were not yet written when the log is synced. Fix this by always taking the inode lock in exclusive mode if we have a sync write. This issue was identified by Sashiko in the link below, which identifies two different races between direct IO writes and fsync. The race fixed here is the second case identified by Sashiko in the link below. The first race is already being fixed in a separate patch from Josef. Link: https://sashiko.dev/#/bug/linux-ee047626-2fa7-46d5-b543-861136993fc7 Fixes: 939b656bc8ab ("btrfs: fix corruption after buffer fault in during direct IO append write") Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Signed-off-by: David Sterba --- fs/btrfs/direct-io.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c index ed3914257d3959..e7c3647c0f739e 100644 --- a/fs/btrfs/direct-io.c +++ b/fs/btrfs/direct-io.c @@ -896,9 +896,13 @@ ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from) * If the write DIO is within EOF, use a shared lock and also only if * security bits will likely not be dropped by file_remove_privs() called * from btrfs_write_check(). Either will need to be rechecked after the - * lock was acquired. + * lock was acquired. Also if this is a sync write we will need to fsync + * and therefore we must lock in exclusive mode, otherwise we would race + * with other concurrent DIO writes and the fsync would not wait for + * their ordered extent to finish IO before logging the new extent maps. */ - if (iocb->ki_pos + iov_iter_count(from) <= i_size_read(inode) && IS_NOSEC(inode)) + if (iocb->ki_pos + iov_iter_count(from) <= i_size_read(inode) && + IS_NOSEC(inode) && !iocb_is_dsync(iocb)) ilock_flags |= BTRFS_ILOCK_SHARED; relock: @@ -920,6 +924,13 @@ ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from) goto relock; } + /* Sync writes must use exclusive locking, see the comment above. */ + if ((ilock_flags & BTRFS_ILOCK_SHARED) && iocb_is_dsync(iocb)) { + btrfs_inode_unlock(BTRFS_I(inode), ilock_flags); + ilock_flags &= ~BTRFS_ILOCK_SHARED; + goto relock; + } + ret = generic_write_checks(iocb, from); if (ret <= 0) { btrfs_inode_unlock(BTRFS_I(inode), ilock_flags); From 2d8b3d9b210a388129e41757372d70c66ae20a5b Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Tue, 10 Nov 2026 22:21:19 +0000 Subject: [PATCH 1480/2102] btrfs: zstd: fix UAF due to race between putting workspace and reclaim When we put a workspace with a level matching the requested level, we add it back to the lru list of the workspace manager and set the timer to run the reclaim function (zstd_reclaim_timer_fn()). If that workspace than gets used by some other task, obtained with zstd_find_workspace(), for some compression level lower than the workspace's level, we set the workspace's req_level field to the requested level (done in zstd_find_workspace()) and leave it in the lru list without updating the last_used field of the workspace. Once the last_used field ages past the ZSTD_BTRFS_RECLAIM_JIFFIES value, when zstd_put_workspace() is called it skips the lru update branch because the workspace's req_level does not match its level, and then it sets its req_level to 0 before releasing the workspace manager's lock - and after that and before zstd_put_workspace() does: if (workspace->level == clip_level(ZSTD_BTRFS_MAX_LEVEL)) cond_wake_up(&zwsm->wait); the reclaim function, zstd_reclaim_timer_fn(), can run, see the workspace in the lru list and see that it has a req_level of 0 and an expired last_used time, and therefore call zstd_free_workspace() to free the workspace, right before the task that is putting the workspace executes the code above to read its level. Fix this by reading the workspace's level before unlocking the workspace manager in zstd_put_workspace(). Link: https://sashiko.dev/#/bug/linux-92b08485-a86c-4bb5-9138-fa80c84389f0 Fixes: 3f93aef535c8 ("btrfs: add zstd compression level support") Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Reviewed-by: David Sterba Signed-off-by: David Sterba --- fs/btrfs/zstd.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/fs/btrfs/zstd.c b/fs/btrfs/zstd.c index 9b7c7f43527f7f..588d7af2953fc0 100644 --- a/fs/btrfs/zstd.c +++ b/fs/btrfs/zstd.c @@ -340,6 +340,7 @@ void zstd_put_workspace(struct btrfs_fs_info *fs_info, struct list_head *ws) { struct zstd_workspace_manager *zwsm = fs_info->compr_wsm[BTRFS_COMPRESS_ZSTD]; struct workspace *workspace = list_to_workspace(ws); + bool wakeup; ASSERT(zwsm); spin_lock_bh(&zwsm->lock); @@ -363,9 +364,14 @@ void zstd_put_workspace(struct btrfs_fs_info *fs_info, struct list_head *ws) list_add(&workspace->list, &zwsm->idle_ws[workspace->level]); workspace->req_level = 0; + /* + * Check if we should wakeup before releasing the lock because after + * that the reclaim function can run and free the workspace. + */ + wakeup = (workspace->level == clip_level(ZSTD_BTRFS_MAX_LEVEL)); spin_unlock_bh(&zwsm->lock); - if (workspace->level == clip_level(ZSTD_BTRFS_MAX_LEVEL)) + if (wakeup) cond_wake_up(&zwsm->wait); } From 0dbdb81da6fb510c0ea24c6e19d65f24e9e8a21e Mon Sep 17 00:00:00 2001 From: Joseph Qi Date: Wed, 11 Nov 2026 20:41:52 +0800 Subject: [PATCH 1481/2102] btrfs: don't wait for ordered extents in nowait buffered writes lock_and_cleanup_extent() honours @nowait when taking the extent lock, but then waits for an overlapping ordered extent regardless of it: btrfs_start_ordered_extent() wait_event(entry->wait, BTRFS_ORDERED_COMPLETE) BTRFS_ORDERED_COMPLETE is only set by btrfs_remove_ordered_extent(), which runs from the ordered extent completion work, so this sleeps uninterruptibly until that work gets to run, and it starts a transaction. A pwritev2(RWF_NOWAIT) buffered write must not block like that. This used to be limited to writes starting below i_size, because the ordered extent lookup was guarded by a start_pos < i_size test. Commit ec78575dde99 ("btrfs: always wait for ordered extents to avoid OE races") dropped that guard so that appends also wait for the ordered extent left behind by a short direct write whose i_size was reverted, which made the wait, and the blocking with it, unconditional. btrfs_write_check() rejects a NOWAIT write with -EAGAIN unless the inode has BTRFS_INODE_NODATACOW or BTRFS_INODE_PREALLOC, so the inode has to have one of those: a chattr +C file, a preallocated file, or a nodatacow mount. Those are the usual setups for database files and VM images, which is also where NOWAIT writes get used. Given such an inode, an append write does reach the wait. With i_size S and a direct write of L bytes of which only W get submitted: task A: O_DIRECT append, short write task B: pwritev2(RWF_NOWAIT) append ------------------------------------ ----------------------------------- btrfs_split_ordered_extent() gives the submitted part [S, S+W) its own OE, so dio_data->ordered is left covering [S+W, S+L) btrfs_dio_iomap_end(): i_size_write(max(S, S+W)) <- i_size reverted btrfs_mark_ordered_extent_truncated() btrfs_finish_ordered_extent() btrfs_queue_ordered_fn() -> endio_write_workers <- the OE is still in the tree iomap_dio_complete() btrfs_inode_unlock() btrfs_buffered_write() at S+W btrfs_inode_lock(BTRFS_ILOCK_TRY) <- succeeds, A dropped it btrfs_write_check() <- passes copy_one_range() lock_and_cleanup_extent() btrfs_try_lock_extent() <- succeeds btrfs_lookup_ordered_range() <- finds A's [S+W, S+L) btrfs_start_ordered_extent() wait_event() <- blocks here endio_write_workers eventually runs finish_ordered_fn() btrfs_finish_ordered_io() btrfs_remove_ordered_extent() <- sets BTRFS_ORDERED_COMPLETE, B finally wakes up -EAGAIN propagates back through copy_one_range() to userspace Because i_size was reverted to S+W, start_pos equals i_size, which is exactly the case the dropped start_pos < i_size guard used to skip. Return -EAGAIN without starting the ordered extent instead. copy_one_range() passes that straight back and btrfs_buffered_write() returns it to userspace when nothing was written yet, so a nowait caller retries from a blocking context without IOCB_NOWAIT and takes the waiting branch then. btrfs_try_lock_ordered_range(), which btrfs_check_nocow_lock() uses for the same purpose, already behaves this way. Fixes: ec78575dde99 ("btrfs: always wait for ordered extents to avoid OE races") CC: stable@vger.kernel.org Reviewed-by: Filipe Manana Signed-off-by: Joseph Qi Signed-off-by: Filipe Manana Signed-off-by: David Sterba --- fs/btrfs/file.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c index f978c6524aa03f..e84e9e129169e6 100644 --- a/fs/btrfs/file.c +++ b/fs/btrfs/file.c @@ -916,7 +916,14 @@ lock_and_cleanup_extent(struct btrfs_inode *inode, struct folio *folio, cached_state); folio_unlock(folio); folio_put(folio); - btrfs_start_ordered_extent(ordered); + /* + * Waiting for the ordered extent blocks uninterruptibly, which + * a nowait caller must not do. Leave it alone and let the + * caller retry where blocking is acceptable, like + * btrfs_try_lock_ordered_range() does. + */ + if (!nowait) + btrfs_start_ordered_extent(ordered); btrfs_put_ordered_extent(ordered); return -EAGAIN; } From 94973b2c0914743da136fe3dd05a06e00af0ec37 Mon Sep 17 00:00:00 2001 From: Boris Burkov Date: Wed, 11 Nov 2026 16:08:55 -0800 Subject: [PATCH 1482/2102] btrfs: fix block group ref leak when scrub races with unused bg deletion btrfs_delete_unused_bgs() takes a block group off fs_info->unused_bgs with list_del_init() and, when discard is on, later moves it onto the transaction's deleted_bgs list and takes a reference for that list membership. Meanwhile, it is possible for scrub to add it back to the unused block groups list: CLEANER SCRUB btrfs_delete_unused_bgs() list_del_init(&bg->bg_list) scrub_enumerate_chunks() btrfs_mark_bg_unused(bg) if (list_empty(&bg->bg_list)) btrfs_get_block_group(bg) list_add_tail(unused_bgs) list_move(&bg->bg_list, deleted_bgs) btrfs_get_block_group(bg) Other users of list_move() for bg->bg_list (like btrfs_mark_bg_unused itself) ensure that the list was empty under the bg spin lock to decide whether it merits a fresh reference for being linked to the list, and we need to apply that pattern here as well. Note that this is not abstracted to a helper function because some of the callers have additional logic deciding whether to link it or not and I think a twice used, twice unused helper would be more confusing than it would be helpful. Reported-by: Sashiko Link: https://sashiko.dev/#/bug/linux-821034ac-556f-4d72-af2c-d04468879af8 Reviewed-by: Qu Wenruo Signed-off-by: Boris Burkov Reviewed-by: David Sterba Signed-off-by: David Sterba --- fs/btrfs/block-group.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c index 822d550e77da16..ba920582874a6b 100644 --- a/fs/btrfs/block-group.c +++ b/fs/btrfs/block-group.c @@ -1860,12 +1860,15 @@ void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info) /* * A concurrent scrub might have added us to the list * fs_info->unused_bgs, so use a list_move operation - * to add the block group to the deleted_bgs list. + * to add the block group to the deleted_bgs list. In + * that case the list reference moves along with it, + * so only take a new one if we were not on any list. */ + if (list_empty(&block_group->bg_list)) + btrfs_get_block_group(block_group); list_move(&block_group->bg_list, &trans->transaction->deleted_bgs); spin_unlock(&fs_info->unused_bgs_lock); - btrfs_get_block_group(block_group); } end_trans: /* From 3092b9e481fedc413bf7acda9edc04b0bd8cb28a Mon Sep 17 00:00:00 2001 From: Arnav Kapoor Date: Wed, 18 Nov 2026 16:01:27 +0530 Subject: [PATCH 1483/2102] ASoC: SOF: control: reject out-of-range enum values snd_sof_enum_put() passes the item indexes from user space to the IPC enum_put() op unchecked, and the IPC3 and IPC4 ops store them as they are and send them to the DSP. With the IPC4 sof-hda-generic-2ch.tplg on a Tiger Lake laptop, "Dmic0 Capture TDFB angle set enum" has 13 items but accepts 13 and 0xffffffff, and reads them back. The ALSA mixer-test selftest reports this as a write_invalid failure. Reject indexes past the last item, as snd_soc_put_enum_double() does. Fixes: c3078f539704 ("ASoC: SOF: Add Sound Open Firmware KControl support") Signed-off-by: Arnav Kapoor Link: https://patch.msgid.link/20261118103129.113970-1-kapoorarnav43@gmail.com Signed-off-by: Mark Brown --- sound/soc/sof/control.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sound/soc/sof/control.c b/sound/soc/sof/control.c index 74d997a4f6203c..625a17624f4155 100644 --- a/sound/soc/sof/control.c +++ b/sound/soc/sof/control.c @@ -120,6 +120,11 @@ int snd_sof_enum_put(struct snd_kcontrol *kcontrol, struct snd_soc_component *scomp = scontrol->scomp; struct snd_sof_dev *sdev = snd_soc_component_get_drvdata(scomp); const struct sof_ipc_tplg_ops *tplg_ops = sof_ipc_get_ops(sdev, tplg); + unsigned int i; + + for (i = 0; i < scontrol->num_channels; i++) + if (ucontrol->value.enumerated.item[i] >= se->items) + return -EINVAL; if (tplg_ops && tplg_ops->control && tplg_ops->control->enum_put) return tplg_ops->control->enum_put(scontrol, ucontrol); From fd573263740371f76cad610cbcc70629b27f6c0c Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Thu, 12 Nov 2026 17:24:57 +0000 Subject: [PATCH 1484/2102] btrfs: fiemap: deal with inline extent in fiemap_find_last_extent_offset() In the while loop that finds the first file extent item, counting from the end of the file, that is not a hole, we are accessing the disk_bytenr field of each file extent item, which is wrong in case we have an item that represents an inline extent. In that case the inline data starts at the disk_bytenr offset and therefore we are reading user data or in case the inline data is less than 8 bytes, we are accessing another region of the leaf or even beyond the leaf boundaries in case it's the last item. This should be a very rare case, as it implies having an inline extent followed by a hole file extent item (the no-holes feature is not used). Fixes: ac3c0d36a2a2 ("btrfs: make fiemap more efficient and accurate reporting extent sharedness") Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Signed-off-by: David Sterba --- fs/btrfs/fiemap.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/fs/btrfs/fiemap.c b/fs/btrfs/fiemap.c index 817171028413c1..285398eb36dc14 100644 --- a/fs/btrfs/fiemap.c +++ b/fs/btrfs/fiemap.c @@ -621,6 +621,8 @@ static int fiemap_find_last_extent_offset(struct btrfs_inode *inode, leaf = path->nodes[0]; ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); + if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) + break; disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei); } From eb11039d8a3cab58c658ff4b8b14aa4b00961e46 Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Thu, 12 Nov 2026 19:56:22 +0000 Subject: [PATCH 1485/2102] btrfs: fix off-by-one max tree level bound when replaying log trees In walk_up_log_tree() we are bounding the loop iteration to 7 levels instead of 8. This is a bug since the maximum number of levels for a tree is 8 and they go from 0 (leaf level) to 7, so the loop condition should be: i < BTRFS_MAX_LEVEL (which 8) and not i < BTRFS_MAX_LEVEL - 1 (7) This means that in case if we ever get a log tree with 8 levels, which theoretically should be impossible specially because they are very short lived, we would miss replaying large parts of the log tree. Link: https://sashiko.dev/#/bug/linux-8d5b7229-3920-47fa-ad36-3a7ddd02f0e7 Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Reviewed-by: David Sterba Signed-off-by: David Sterba --- fs/btrfs/tree-log.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/btrfs/tree-log.c b/fs/btrfs/tree-log.c index 1d9dfb63fc5a4f..62d94d1a0a1a3b 100644 --- a/fs/btrfs/tree-log.c +++ b/fs/btrfs/tree-log.c @@ -3064,7 +3064,7 @@ static noinline int walk_up_log_tree(struct btrfs_path *path, int *level, int slot; int ret; - for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) { + for (i = *level; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) { slot = path->slots[i]; if (slot + 1 < btrfs_header_nritems(path->nodes[i])) { path->slots[i]++; From ee020b5f0eb81a86533a16dcaafcee2b97a0f74d Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Thu, 12 Nov 2026 20:25:30 +0000 Subject: [PATCH 1486/2102] btrfs: fix double release of space when cloning compressed inline extent In copy_inline_to_page(), if we fail to decompress the inline extent, we jump to the out_unlock label and release the reserved data and metadata space with a call to btrfs_delalloc_release_space(). However we leave the range in the inode's io_tree marked as delalloc, which was set by btrfs_reset_extent_delalloc(), and that means when someone later clears the delalloc range, using EXTENT_DO_ACCOUNTING (like btrfs_reset_extent_delalloc() does), it will release again the space. This does not happen for uncompressed inline extents, because after the call to btrfs_reset_extent_delalloc() we can't get any other errors. Link: https://sashiko.dev/#/bug/linux-52478dd4-bd10-48de-baba-a527b38b64aa Fixes: 05a5a7621ce6 ("Btrfs: implement full reflink support for inline extents") Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Signed-off-by: David Sterba --- fs/btrfs/reflink.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/fs/btrfs/reflink.c b/fs/btrfs/reflink.c index b5d2c094941df6..7d7e304c69243b 100644 --- a/fs/btrfs/reflink.c +++ b/fs/btrfs/reflink.c @@ -120,8 +120,21 @@ static int copy_inline_to_page(struct btrfs_inode *inode, ret = btrfs_decompress(comp_type, data_start, folio, offset_in_folio(folio, file_offset), inline_size, datal); - if (ret) + if (ret) { + /* + * btrfs_reset_extent_delalloc() set the range as + * delalloc, so clear it, otherwise we will free the + * reserved data and metadata space twice, once below by + * btrfs_delalloc_release_space() and once again when + * someone else clears the delalloc range with + * EXTENT_DO_ACCOUNTING (like + * btrfs_reset_extent_delalloc() does). + */ + btrfs_clear_extent_bit(&inode->io_tree, file_offset, + range_end, EXTENT_DELALLOC | + EXTENT_DELALLOC_NEW, NULL); goto out_unlock; + } flush_dcache_folio(folio); } From 6cd72166183bfc290fd853470232020c4b807aa2 Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Fri, 13 Nov 2026 17:10:54 +0000 Subject: [PATCH 1487/2102] btrfs: abort transaction on failure to update inode after hole punching If we fail to update the inode we simply release the transaction and don't abort the transaction. This means the transaction can get committed and we will not persist important updates to the inode item such as nbytes (which gets reduced after punching holes) and the timestamps. Fix this by adding the missing abort. Link: https://sashiko.dev/#/bug/linux-d8b4cb7a-8dfe-454f-9b19-a67af28b81bd Fixes: 2aaa66558172 ("Btrfs: add hole punching") Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Signed-off-by: David Sterba --- fs/btrfs/file.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c index e84e9e129169e6..cf033c08ec181b 100644 --- a/fs/btrfs/file.c +++ b/fs/btrfs/file.c @@ -2754,7 +2754,10 @@ static int btrfs_punch_hole(struct file *file, loff_t offset, loff_t len) inode_inc_iversion(inode); inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode)); ret = btrfs_update_inode(trans, BTRFS_I(inode)); - updated_inode = true; + if (ret) + btrfs_abort_transaction(trans, ret); + else + updated_inode = true; btrfs_end_transaction(trans); btrfs_btree_balance_dirty(fs_info); out: @@ -2780,6 +2783,8 @@ static int btrfs_punch_hole(struct file *file, loff_t offset, loff_t len) int ret2; ret = btrfs_update_inode(trans, BTRFS_I(inode)); + if (ret) + btrfs_abort_transaction(trans, ret); ret2 = btrfs_end_transaction(trans); if (!ret) ret = ret2; From 85c98fd512bb3e2f326f1a1cac30f2fb0af30c6a Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Fri, 13 Nov 2026 17:36:57 +0000 Subject: [PATCH 1488/2102] btrfs: fix blocking allocation for nowait encoded reads of inline extents If we are doing a nowait encoded read of an inline extent, we are doing a GFP_NOFS allocation for the temporary buffer, which can block. We are also returning -ENOMEM on failure, which is wrong for a nowait context. Fix this by using GFP_NOWAIT when we are in a nowait context and by returning -EAGAIN instead of -ENOMEM if the allocation fails. Fixes: 973a432637ed ("btrfs: don't sleep in btrfs_encoded_read() if IOCB_NOWAIT is set") Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Reviewed-by: David Sterba Signed-off-by: David Sterba --- fs/btrfs/inode.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c index 48c41f6390b24d..2983c420eacba7 100644 --- a/fs/btrfs/inode.c +++ b/fs/btrfs/inode.c @@ -9573,9 +9573,9 @@ static ssize_t btrfs_encoded_read_inline( ptr += iocb->ki_pos - extent_start; } - tmp = kmalloc(count, GFP_NOFS); + tmp = kmalloc(count, nowait ? GFP_NOWAIT : GFP_NOFS); if (!tmp) - return -ENOMEM; + return nowait ? -EAGAIN : -ENOMEM; read_extent_buffer(leaf, tmp, ptr, count); btrfs_release_path(path); From 42de7db475fe895d97934b73a06527a2e4912d93 Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Fri, 13 Nov 2026 21:52:42 +0000 Subject: [PATCH 1489/2102] btrfs: fix incorrect task accounting on error during io_uring read We are passing 'ret' to add_rchar() under the 'out' label, which is meant to take a byte count for accounting, however if we got an error we pass it to add_rchar() too, which is just wrong. Fix thing by passing 'ret' only when it's not an error. Fixes: 34310c442e17 ("btrfs: add io_uring command for encoded reads (ENCODED_READ ioctl)") Link: https://sashiko.dev/#/bug/linux-beb0369e-eb47-41d3-86c1-e79cdc2de157 Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Reviewed-by: David Sterba Signed-off-by: David Sterba --- fs/btrfs/ioctl.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fs/btrfs/ioctl.c b/fs/btrfs/ioctl.c index ed8bf8f7da1463..0334dfacb4cce8 100644 --- a/fs/btrfs/ioctl.c +++ b/fs/btrfs/ioctl.c @@ -4661,7 +4661,8 @@ static void btrfs_uring_read_finished(struct io_tw_req tw_req, io_tw_token_t tw) btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED); io_uring_cmd_done(cmd, ret, IO_URING_CMD_TASK_WORK_ISSUE_FLAGS); - add_rchar(current, ret); + if (ret > 0) + add_rchar(current, ret); for (index = 0; index < priv->nr_pages; index++) __free_page(priv->pages[index]); From 3100f46985fd14148e79a0e79912180934ef7231 Mon Sep 17 00:00:00 2001 From: Filipe Manana Date: Mon, 16 Nov 2026 11:24:38 +0000 Subject: [PATCH 1490/2102] btrfs: fix delayed inode count leak after failure to delete inode ref When updating a delayed inode, if we have an inode ref to delete (the flag BTRFS_DELAYED_NODE_DEL_IREF is set) and we fail the deletion of the inode ref item (if it's in another leaf), we abort the transaction and then never release the delayed count for the inode ref deletion (by calling btrfs_release_delayed_iref()), resulting in a permanent leak of the delayed inode. Fix this by jumping to the 'out' label instead and removing the now no longer necessary 'err_out' label. Fixes: 67de11769bd5 ("Btrfs: introduce the delayed inode ref deletion for the single link inode") Link: https://sashiko.dev/#/bug/linux-3520c6eb-7928-477d-b369-9caff2b98d10 Reviewed-by: Qu Wenruo Signed-off-by: Filipe Manana Reviewed-by: David Sterba Signed-off-by: David Sterba --- fs/btrfs/delayed-inode.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/fs/btrfs/delayed-inode.c b/fs/btrfs/delayed-inode.c index 333ce8b5248999..295329d67b219f 100644 --- a/fs/btrfs/delayed-inode.c +++ b/fs/btrfs/delayed-inode.c @@ -1053,7 +1053,7 @@ static int __btrfs_update_delayed_inode(struct btrfs_trans_handle *trans, ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (unlikely(ret < 0)) { btrfs_abort_transaction(trans, ret); - goto err_out; + goto out; } ASSERT(ret > 0); ASSERT(path->slots[0] > 0); @@ -1081,7 +1081,6 @@ static int __btrfs_update_delayed_inode(struct btrfs_trans_handle *trans, out: btrfs_release_delayed_iref(node); btrfs_release_path(path); -err_out: btrfs_delayed_inode_release_metadata(fs_info, node, (ret < 0)); btrfs_release_delayed_inode(node); return ret; From 9af3cacff4adcfb8c4dbc003d6fe7166420088e4 Mon Sep 17 00:00:00 2001 From: Haowen Tu Date: Wed, 18 Nov 2026 10:11:34 +0800 Subject: [PATCH 1491/2102] ASoC: da7213: Disable runtime PM on component registration failure The probe function enables runtime PM before registering the ASoC component. If component registration fails, it returns the error without disabling runtime PM. The remove callback is not called for a failed probe, so runtime PM remains enabled while devres releases the regmap and powers off the supplies. Disable runtime PM on component registration failure before returning the error and allowing the managed resources to be released. Fixes: b2a378816d0f ("ASoC: da7213: Add regulator support") Signed-off-by: Haowen Tu Link: https://patch.msgid.link/0D45FEC273BAD5EF+20261118021134.3827729-1-tuhaowen@uniontech.com Signed-off-by: Mark Brown --- sound/soc/codecs/da7213.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/soc/codecs/da7213.c b/sound/soc/codecs/da7213.c index b08e8ab6b42186..53ed58ca9ab292 100644 --- a/sound/soc/codecs/da7213.c +++ b/sound/soc/codecs/da7213.c @@ -2242,6 +2242,7 @@ static int da7213_i2c_probe(struct i2c_client *i2c) if (ret < 0) { dev_err(&i2c->dev, "Failed to register da7213 component: %d\n", ret); + pm_runtime_disable(&i2c->dev); } return ret; } From 94531f24f5b434eb022902b4e8ce7e12274923dd Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Mon, 16 Nov 2026 11:26:32 +0700 Subject: [PATCH 1492/2102] ASoC: atmel-classd: Simplify probe error handling Use dev_err_probe() for clock acquisition and regmap initialization to suppress probe deferral logs and simplify error handling. Also remove the unnecessary cleanup label, as all resources are managed by devm. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261116042633.497423-2-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/atmel-classd.c | 37 ++++++++++++---------------------- 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/sound/soc/atmel/atmel-classd.c b/sound/soc/atmel/atmel-classd.c index 746e6bbbf4237b..59490e9effab26 100644 --- a/sound/soc/atmel/atmel-classd.c +++ b/sound/soc/atmel/atmel-classd.c @@ -547,18 +547,14 @@ static int atmel_classd_probe(struct platform_device *pdev) return dd->irq; dd->pclk = devm_clk_get(dev, "pclk"); - if (IS_ERR(dd->pclk)) { - ret = PTR_ERR(dd->pclk); - dev_err(dev, "failed to get peripheral clock: %d\n", ret); - return ret; - } + if (IS_ERR(dd->pclk)) + return dev_err_probe(dev, PTR_ERR(dd->pclk), + "failed to get peripheral clock\n"); dd->gclk = devm_clk_get(dev, "gclk"); - if (IS_ERR(dd->gclk)) { - ret = PTR_ERR(dd->gclk); - dev_err(dev, "failed to get GCK clock: %d\n", ret); - return ret; - } + if (IS_ERR(dd->gclk)) + return dev_err_probe(dev, PTR_ERR(dd->gclk), + "failed to get GCK clock\n"); io_base = devm_platform_get_and_ioremap_resource(pdev, 0, &res); if (IS_ERR(io_base)) @@ -569,11 +565,9 @@ static int atmel_classd_probe(struct platform_device *pdev) dd->regmap = devm_regmap_init_mmio(dev, io_base, &atmel_classd_regmap_config); - if (IS_ERR(dd->regmap)) { - ret = PTR_ERR(dd->regmap); - dev_err(dev, "failed to init register map: %d\n", ret); - return ret; - } + if (IS_ERR(dd->regmap)) + return dev_err_probe(dev, PTR_ERR(dd->regmap), + "failed to init register map\n"); ret = devm_snd_soc_register_component(dev, &atmel_classd_cpu_dai_component, @@ -593,29 +587,24 @@ static int atmel_classd_probe(struct platform_device *pdev) /* register sound card */ card = devm_kzalloc_obj(dev, *card); - if (!card) { - ret = -ENOMEM; - goto unregister_codec; - } + if (!card) + return -ENOMEM; snd_soc_card_set_drvdata(card, dd); ret = atmel_classd_asoc_card_init(dev, card); if (ret) { dev_err(dev, "failed to init sound card\n"); - goto unregister_codec; + return ret; } ret = devm_snd_soc_register_card(dev, card); if (ret) { dev_err(dev, "failed to register sound card: %d\n", ret); - goto unregister_codec; + return ret; } return 0; - -unregister_codec: - return ret; } static struct platform_driver atmel_classd_driver = { From 76f1c241d10c8ea284891d40949d6c87b664e45e Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Mon, 16 Nov 2026 11:26:33 +0700 Subject: [PATCH 1493/2102] ASoC: atmel-classd: Enable pclk during probe The peripheral clock is enabled in the startup callback but never disabled, causing its enable reference count to increase on each startup and preventing the clock from being gated. Use devm_clk_get_enabled() to enable pclk once during probe and automatically disable it on device removal. Signed-off-by: bui duc phuc Fixes: 1dfdbe73ccf9 ("ASoC: atmel-classd: remove codec component") Link: https://patch.msgid.link/20261116042633.497423-3-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/atmel-classd.c | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/sound/soc/atmel/atmel-classd.c b/sound/soc/atmel/atmel-classd.c index 59490e9effab26..4216a28d337144 100644 --- a/sound/soc/atmel/atmel-classd.c +++ b/sound/soc/atmel/atmel-classd.c @@ -122,19 +122,10 @@ static int atmel_classd_cpu_dai_startup(struct snd_pcm_substream *substream, { struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct atmel_classd *dd = snd_soc_card_get_drvdata(rtd->card); - int err; regmap_write(dd->regmap, CLASSD_THR, 0x0); - err = clk_prepare_enable(dd->pclk); - if (err) - return err; - err = clk_prepare_enable(dd->gclk); - if (err) { - clk_disable_unprepare(dd->pclk); - return err; - } - return 0; + return clk_prepare_enable(dd->gclk); } /* platform */ @@ -546,10 +537,10 @@ static int atmel_classd_probe(struct platform_device *pdev) if (dd->irq < 0) return dd->irq; - dd->pclk = devm_clk_get(dev, "pclk"); + dd->pclk = devm_clk_get_enabled(dev, "pclk"); if (IS_ERR(dd->pclk)) return dev_err_probe(dev, PTR_ERR(dd->pclk), - "failed to get peripheral clock\n"); + "failed to get/enable peripheral clock\n"); dd->gclk = devm_clk_get(dev, "gclk"); if (IS_ERR(dd->gclk)) From 5bb070e3f968b58901b5899b6a8970042ecf2882 Mon Sep 17 00:00:00 2001 From: Somesh Dey Date: Wed, 18 Nov 2026 18:26:07 +0530 Subject: [PATCH 1494/2102] spi: geni-qcom: Fix sub-byte transfer packing and length calculation On iq-9075-evk, short four-bit SPI loopback transfers can time out immediately after boot. The failure is reproduced with spidev_test: ./spidev_test -D /dev/spidev0.0 -s 2500000 -b 4 -l -I 10 -v The test reports "can't send spi message: Connection timed out", with the following kernel messages: [ 732.730335] spidev spi0.0: SPI transfer timed out [ 732.735216] geni_spi 880000.spi: Can't set CS when prev xfer running [ 732.742882] spi_master spi0: failed to transfer one message from queue [ 732.749619] spi_master spi0: noqueue transfer failed At BPW 4, the driver requests eight protocol words per 32-bit FIFO entry. The GENI helper needs one packing vector per sub-byte word but only supports four vectors, so it returns without programming the packing registers. This leaves the transfer dependent on the previous packing configuration. The driver also assumes that a buffer byte contains two four-bit words. Linux SPI buffers store each sub-byte word in a separate byte, so the programmed transfer length can exceed the available data. Use byte-sized packing slots for sub-byte transfers and derive word counts from spi_bpw_to_bytes(). Share the packing count across hardware configuration, FIFO accounting and DMA selection. Account for storage padding in the last received word, and drain leftover FIFO entries without relying on a cached word width. Fixes: 561de45f72bd ("spi: spi-geni-qcom: Add SPI driver support for GENI based QUP") Cc: stable@vger.kernel.org Signed-off-by: Somesh Dey Link: https://patch.msgid.link/20261118-spi-bpw-fix-v1-1-e475586ca8e8@oss.qualcomm.com Signed-off-by: Mark Brown --- drivers/spi/spi-geni-qcom.c | 81 ++++++++++++++++--------------------- 1 file changed, 34 insertions(+), 47 deletions(-) diff --git a/drivers/spi/spi-geni-qcom.c b/drivers/spi/spi-geni-qcom.c index 91e75e213f929e..bde3d434e4ca20 100644 --- a/drivers/spi/spi-geni-qcom.c +++ b/drivers/spi/spi-geni-qcom.c @@ -14,7 +14,6 @@ #include #include #include -#include #include #include #include @@ -306,22 +305,26 @@ static bool spi_geni_is_abort_still_pending(struct spi_geni_master *mas) return false; } +static unsigned int geni_spi_words_per_fifo(struct spi_geni_master *mas, + unsigned int bits_per_word) +{ + /* Each sub-byte SPI word occupies a separate byte in memory. */ + unsigned int packing_bits = max_t(unsigned int, bits_per_word, BITS_PER_BYTE); + + if (mas->fifo_width_bits % packing_bits) + return 1; + + return mas->fifo_width_bits / packing_bits; +} + static void spi_setup_word_len(struct spi_geni_master *mas, u16 mode, unsigned int bits_per_word) { - unsigned int pack_words; + unsigned int pack_words = geni_spi_words_per_fifo(mas, bits_per_word); bool msb_first = (mode & SPI_LSB_FIRST) ? false : true; struct geni_se *se = &mas->se; u32 word_len; - /* - * If bits_per_word isn't a byte aligned value, set the packing to be - * 1 SPI word per FIFO word. - */ - if (!(mas->fifo_width_bits % bits_per_word)) - pack_words = mas->fifo_width_bits / bits_per_word; - else - pack_words = 1; geni_se_config_packing(&mas->se, bits_per_word, pack_words, msb_first, true, true); word_len = (bits_per_word - MIN_WORD_LEN) & WORD_LEN_MSK; @@ -451,13 +454,7 @@ static int setup_gsi_xfer(struct spi_transfer *xfer, struct spi_geni_master *mas peripheral.rx_len = 0; } else if (xfer->rx_buf) { peripheral.cmd = SPI_RX; - if (!(mas->cur_bits_per_word % MIN_WORD_LEN)) { - peripheral.rx_len = ((xfer->len << 3) / mas->cur_bits_per_word); - } else { - int bytes_per_word = (mas->cur_bits_per_word / BITS_PER_BYTE) + 1; - - peripheral.rx_len = (xfer->len / bytes_per_word); - } + peripheral.rx_len = xfer->len / spi_bpw_to_bytes(xfer->bits_per_word); } peripheral.loopback_en = !!(spi_slv->mode & SPI_LOOP); @@ -523,15 +520,7 @@ static int setup_gsi_xfer(struct spi_transfer *xfer, struct spi_geni_master *mas static u32 get_xfer_len_in_words(struct spi_transfer *xfer, struct spi_geni_master *mas) { - u32 len; - - if (!(xfer->bits_per_word % MIN_WORD_LEN)) - len = xfer->len * BITS_PER_BYTE / xfer->bits_per_word; - else - len = xfer->len / (xfer->bits_per_word / BITS_PER_BYTE + 1); - len &= TRANS_LEN_MSK; - - return len; + return (xfer->len / spi_bpw_to_bytes(xfer->bits_per_word)) & TRANS_LEN_MSK; } static bool geni_can_dma(struct spi_controller *ctlr, @@ -548,7 +537,7 @@ static bool geni_can_dma(struct spi_controller *ctlr, return true; len = get_xfer_len_in_words(xfer, mas); - fifo_size = mas->tx_fifo_depth * mas->fifo_width_bits / xfer->bits_per_word; + fifo_size = mas->tx_fifo_depth * geni_spi_words_per_fifo(mas, xfer->bits_per_word); if (len > fifo_size) return true; @@ -725,16 +714,8 @@ static int spi_geni_init(struct spi_geni_master *mas) static unsigned int geni_byte_per_fifo_word(struct spi_geni_master *mas) { - /* - * Calculate how many bytes we'll put in each FIFO word. If the - * transfer words don't pack cleanly into a FIFO word we'll just put - * one transfer word in each FIFO word. If they do pack we'll pack 'em. - */ - if (mas->fifo_width_bits % mas->cur_bits_per_word) - return roundup_pow_of_two(DIV_ROUND_UP(mas->cur_bits_per_word, - BITS_PER_BYTE)); - - return mas->fifo_width_bits / BITS_PER_BYTE; + return geni_spi_words_per_fifo(mas, mas->cur_bits_per_word) * + spi_bpw_to_bytes(mas->cur_bits_per_word); } static bool geni_spi_handle_tx(struct spi_geni_master *mas) @@ -742,7 +723,7 @@ static bool geni_spi_handle_tx(struct spi_geni_master *mas) struct geni_se *se = &mas->se; unsigned int max_bytes; const u8 *tx_buf; - unsigned int bytes_per_fifo_word = geni_byte_per_fifo_word(mas); + unsigned int bytes_per_fifo_word; unsigned int i = 0; /* Stop the watermark IRQ if nothing to send */ @@ -751,6 +732,7 @@ static bool geni_spi_handle_tx(struct spi_geni_master *mas) return false; } + bytes_per_fifo_word = geni_byte_per_fifo_word(mas); max_bytes = (mas->tx_fifo_depth - mas->tx_wm) * bytes_per_fifo_word; if (mas->tx_rem_bytes < max_bytes) max_bytes = mas->tx_rem_bytes; @@ -782,25 +764,30 @@ static void geni_spi_handle_rx(struct spi_geni_master *mas) unsigned int rx_bytes; unsigned int rx_last_byte_valid; u8 *rx_buf; - unsigned int bytes_per_fifo_word = geni_byte_per_fifo_word(mas); + unsigned int bytes_per_fifo_word; unsigned int i = 0; rx_fifo_status = readl(se->base + SE_GENI_RX_FIFO_STATUS); + + /* Clear out the FIFO and bail if nowhere to put it. */ + if (!mas->cur_xfer || !mas->cur_xfer->rx_buf) { + for (i = 0; i < (rx_fifo_status & RX_FIFO_WC_MSK); i++) + readl(se->base + SE_GENI_RX_FIFOn); + return; + } + + bytes_per_fifo_word = geni_byte_per_fifo_word(mas); rx_bytes = (rx_fifo_status & RX_FIFO_WC_MSK) * bytes_per_fifo_word; if (rx_fifo_status & RX_LAST) { rx_last_byte_valid = rx_fifo_status & RX_LAST_BYTE_VALID_MSK; rx_last_byte_valid >>= RX_LAST_BYTE_VALID_SHFT; - if (rx_last_byte_valid && rx_last_byte_valid < 4) + /* Include the padding in the last in-memory SPI word. */ + rx_last_byte_valid = round_up(rx_last_byte_valid, + spi_bpw_to_bytes(mas->cur_bits_per_word)); + if (rx_last_byte_valid && rx_last_byte_valid < bytes_per_fifo_word) rx_bytes -= bytes_per_fifo_word - rx_last_byte_valid; } - /* Clear out the FIFO and bail if nowhere to put it */ - if (!mas->cur_xfer) { - for (i = 0; i < DIV_ROUND_UP(rx_bytes, bytes_per_fifo_word); i++) - readl(se->base + SE_GENI_RX_FIFOn); - return; - } - if (mas->rx_rem_bytes < rx_bytes) rx_bytes = mas->rx_rem_bytes; From 4e04e396207027060055119ed45925bc89843a12 Mon Sep 17 00:00:00 2001 From: Yichong Chen Date: Mon, 14 Sep 2026 16:25:16 +0800 Subject: [PATCH 1495/2102] ext4: fix the logical block counter overflow in indirect migration update_tind_extent_range() advances lb->curr_block, an ext4_lblk_t, by max_entries * max_entries for every empty triple-indirect slot. One triple-indirect block spans max_entries^3 logical blocks, which exceeds 2^32 as soon as the block size is 8K or larger (16384^3 = 2^42 with 64K blocks), so the counter wraps while that block is walked. A wrapped counter makes the migration store a block number that is 2^32 blocks away from the one the pointer block describes. Two ranges can then end up with the same ee_block, which trips BUG_ON(newext->ee_block == nearex->ee_block) in ext4_ext_insert_extent(), and without that collision the data is still moved to the wrong logical block while the migration reports success. Keep the counter in 64 bit so that it cannot wrap, and refuse the migration with -EOPNOTSUPP once a data block would land on EXT_MAX_BLOCKS or beyond: an extent may not cover that block, because ext4_valid_extent() rejects a wrapping ee_block + ee_len, and only a corrupt block map has data there. Fixes: c14c6fd5c56a ("ext4: Add EXT4_IOC_MIGRATE ioctl") Signed-off-by: Yichong Chen Reviewed-by: Jan Kara Link: https://patch.msgid.link/20260914082516.3442815-1-chenyichong@uniontech.com Cc: stable@kernel.org Signed-off-by: Theodore Ts'o --- fs/ext4/migrate.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/fs/ext4/migrate.c b/fs/ext4/migrate.c index e2ae57cdc71862..3822bc8729b899 100644 --- a/fs/ext4/migrate.c +++ b/fs/ext4/migrate.c @@ -14,7 +14,7 @@ * represented by a single extent */ struct migrate_struct { - ext4_lblk_t first_block, last_block, curr_block; + u64 first_block, last_block, curr_block; ext4_fsblk_t first_pblock, last_pblock; }; @@ -65,6 +65,10 @@ static int update_extent_range(handle_t *handle, struct inode *inode, ext4_fsblk_t pblock, struct migrate_struct *lb) { int retval; + + if (lb->curr_block >= EXT_MAX_BLOCKS) + return -EOPNOTSUPP; + /* * See if we can add on to the existing range (if it exists) */ From 263f338d312a7a57ce50591142e743e5782c628f Mon Sep 17 00:00:00 2001 From: shuo chen <1289151713@qq.com> Date: Tue, 15 Sep 2026 00:41:44 +0800 Subject: [PATCH 1496/2102] ext4: fix WARNING in ext4_journalled_invalidate_folio Call the ext4_wait_for_tail_page_commit() helper before ext4_truncate_failed_write() from ext4_journalled_write_end(), which avoids invalidating the folio while it is being committed. Closes: https://lore.kernel.org/linux-ext4/CA+0ovCgxFN3TLpdS_O_Z48sARuQ-WR-JLDCqQWEmd9ELtkzddA@mail.gmail.com/T/ Suggested-by: Jan Kara Reported-by: Farhad Alemi Signed-off-by: shuo chen <1289151713@qq.com> Reviewed-by: Jan Kara Link: https://patch.msgid.link/tencent_87F5A404ED65B0B1349C60E830C485716705@qq.com Signed-off-by: Theodore Ts'o Signed-off-by: Theodore Ts'o Cc: stable@kernel.org Signed-off-by: Theodore Ts'o --- fs/ext4/inode.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index f3c3e6d03f5247..6cfd22874b1f7a 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -57,6 +57,7 @@ static void ext4_journalled_zero_new_buffers(handle_t *handle, struct inode *inode, struct folio *folio, unsigned from, unsigned to); +static void ext4_wait_for_tail_page_commit(struct inode *inode); static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw, struct ext4_inode_info *ei) @@ -1723,6 +1724,7 @@ static int ext4_journalled_write_end(const struct kiocb *iocb, if (!ret) ret = ret2; if (pos + len > inode->i_size && !verity) { + ext4_wait_for_tail_page_commit(inode); ext4_truncate_failed_write(inode); /* * If truncate failed early the inode might still be From b28443aa879b2b5aefe8fb5b3f9b65c31233f5d7 Mon Sep 17 00:00:00 2001 From: lty <781735889@qq.com> Date: Tue, 15 Sep 2026 09:57:46 +0800 Subject: [PATCH 1497/2102] ext4: propagate errors from fast commit i_blocks replay ext4_ext_replay_set_iblocks() breaks out of its mapping loop when ext4_map_blocks() fails, but then continues with a partial block count and unconditionally returns success. The fast commit replay caller also ignores the helper return value. Stop the count immediately on mapping errors, leave i_blocks unchanged, and propagate the failure to abort inode replay. Fixes: 8016e29f4362 ("ext4: fast commit recovery path") Signed-off-by: lty <781735889@qq.com> Reviewed-by: Jan Kara Link: https://patch.msgid.link/tencent_ECF4DA918377A7A0D8863B860B0F3025C106@qq.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/extents.c | 26 ++++++++++++++++---------- fs/ext4/fast_commit.c | 7 +++++-- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index 3fa93db7e7ee3d..0bb135f8b661e6 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -6322,7 +6322,7 @@ int ext4_ext_replay_set_iblocks(struct inode *inode) map.m_len = end - cur; ret = ext4_map_blocks(NULL, inode, &map, 0); if (ret < 0) - break; + goto cleanup; if (ret > 0) numblks += ret; cur = cur + map.m_len; @@ -6338,15 +6338,19 @@ int ext4_ext_replay_set_iblocks(struct inode *inode) cur = 0; ret = skip_hole(inode, &cur); if (ret < 0) - goto out; + goto cleanup; path = ext4_find_extent(inode, cur, path, 0); - if (IS_ERR(path)) - goto out; + if (IS_ERR(path)) { + ret = PTR_ERR(path); + goto cleanup; + } numblks += path->p_depth; while (cur < end) { path = ext4_find_extent(inode, cur, path, 0); - if (IS_ERR(path)) - break; + if (IS_ERR(path)) { + ret = PTR_ERR(path); + goto cleanup; + } ex = path[path->p_depth].p_ext; if (!ex) goto cleanup; @@ -6355,11 +6359,13 @@ int ext4_ext_replay_set_iblocks(struct inode *inode) ext4_ext_get_actual_len(ex)); ret = skip_hole(inode, &cur); if (ret < 0) - break; + goto cleanup; path2 = ext4_find_extent(inode, cur, path2, 0); - if (IS_ERR(path2)) - break; + if (IS_ERR(path2)) { + ret = PTR_ERR(path2); + goto cleanup; + } for (i = 0; i <= max(path->p_depth, path2->p_depth); i++) { cmp1 = cmp2 = 0; @@ -6380,7 +6386,7 @@ int ext4_ext_replay_set_iblocks(struct inode *inode) cleanup: ext4_free_ext_path(path); ext4_free_ext_path(path2); - return 0; + return ret; } int ext4_ext_clear_bb(struct inode *inode) diff --git a/fs/ext4/fast_commit.c b/fs/ext4/fast_commit.c index 0cac890cf37029..8110b01e36c11c 100644 --- a/fs/ext4/fast_commit.c +++ b/fs/ext4/fast_commit.c @@ -2002,8 +2002,11 @@ static int ext4_fc_replay_inode(struct super_block *sb, * crashing. This should be fixed but until then, we calculate * the number of blocks the inode. */ - if (!ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA)) - ext4_ext_replay_set_iblocks(inode); + if (!ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA)) { + ret = ext4_ext_replay_set_iblocks(inode); + if (ret) + goto out_brelse; + } inode->i_generation = le32_to_cpu(ext4_raw_inode(&iloc)->i_generation); ext4_reset_inode_seed(inode); From 4a5cc4d1a7f0b22fef7e42e6fbedd4c41ff7ac77 Mon Sep 17 00:00:00 2001 From: lty <781735889@qq.com> Date: Tue, 15 Sep 2026 09:58:28 +0800 Subject: [PATCH 1498/2102] ext4: propagate errors from fast commit block cleanup ext4_ext_clear_bb() stops scanning when ext4_map_blocks() fails, but it returns success to its caller. It also ignores failures from extent lookup and replay-region allocation. ext4_fc_replay_inode() ignores the helper result and continues replay with stale block bitmap accounting. Propagate all cleanup errors from ext4_ext_clear_bb() and abort inode replay when cleanup fails. Fixes: 8016e29f4362 ("ext4: fast commit recovery path") Cc: stable@vger.kernel.org Testing: QEMU fast-commit replay with an injected -EIO at the ext4_ext_clear_bb() mapping call. The unpatched kernel completed recovery and e2fsck reported a free-block count mismatch; the patched kernel aborted recovery with EIO. Also built the ext4 target objects with the expanded error paths. Signed-off-by: lty <781735889@qq.com> Link: https://patch.msgid.link/tencent_FBD69AA6034FE7AF98BC3B90CB1EF012C106@qq.com Signed-off-by: Theodore Ts'o --- fs/ext4/extents.c | 31 ++++++++++++++++++------------- fs/ext4/fast_commit.c | 5 ++++- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index 0bb135f8b661e6..855d328fc7b9fe 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -6416,29 +6416,34 @@ int ext4_ext_clear_bb(struct inode *inode) map.m_len = end - cur; ret = ext4_map_blocks(NULL, inode, &map, 0); if (ret < 0) - break; + goto out; if (ret > 0) { path = ext4_find_extent(inode, map.m_lblk, path, 0); - if (!IS_ERR(path)) { - for (j = 0; j < path->p_depth; j++) { - ext4_mb_mark_bb(inode->i_sb, - path[j].p_block, 1, false); - ext4_fc_record_regions(inode->i_sb, inode->i_ino, - 0, path[j].p_block, 1, 1); - } - } else { - path = NULL; + if (IS_ERR(path)) { + ret = PTR_ERR(path); + goto out; + } + for (j = 0; j < path->p_depth; j++) { + ext4_mb_mark_bb(inode->i_sb, + path[j].p_block, 1, false); + ret = ext4_fc_record_regions(inode->i_sb, + inode->i_ino, 0, + path[j].p_block, 1, 1); + if (ret) + goto out; } ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, false); - ext4_fc_record_regions(inode->i_sb, inode->i_ino, - map.m_lblk, map.m_pblk, map.m_len, 1); + ret = ext4_fc_record_regions(inode->i_sb, inode->i_ino, + map.m_lblk, map.m_pblk, map.m_len, 1); + if (ret) + goto out; } cur = cur + map.m_len; } out: ext4_free_ext_path(path); - return 0; + return ret < 0 ? ret : 0; } #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) diff --git a/fs/ext4/fast_commit.c b/fs/ext4/fast_commit.c index 8110b01e36c11c..8c24e882aee85d 100644 --- a/fs/ext4/fast_commit.c +++ b/fs/ext4/fast_commit.c @@ -1941,8 +1941,11 @@ static int ext4_fc_replay_inode(struct super_block *sb, inode = ext4_iget(sb, ino, EXT4_IGET_NORMAL); if (!IS_ERR(inode)) { - ext4_ext_clear_bb(inode); + ret = ext4_ext_clear_bb(inode); iput(inode); + inode = NULL; + if (ret) + goto out; } inode = NULL; From 2c1c8c412bb801c12cd6931ff626e64c45ec9c15 Mon Sep 17 00:00:00 2001 From: lty <781735889@qq.com> Date: Tue, 15 Sep 2026 18:29:22 +0800 Subject: [PATCH 1499/2102] ext4: propagate errors from fast commit bitmap rebuild ext4_fc_set_bitmaps_and_counters() rebuilds block bitmaps for modified inodes during fast-commit replay. When ext4_map_blocks() fails, the helper stops scanning but previously returned success. Errors from ext4_find_extent() were also discarded, so replay continued after an incomplete bitmap rebuild. Return errors from the helper and propagate them through both replay call sites so journal recovery aborts when bitmap reconstruction fails. Testing: With CONFIG_EXT4_DEBUG, QEMU fast-commit replay was run using a temporary fault injection that forced -EIO in the bitmap rebuild mapping call. The unmodified kernel reported recovery complete and mounted the filesystem; the patched kernel reported journal recovery failure and mount returned EIO. Built fs/ext4/fast_commit.o and a complete x86 bzImage. Fixes: 8016e29f4362 ("ext4: fast commit recovery path") Cc: stable@vger.kernel.org Signed-off-by: lty <781735889@qq.com> Link: https://patch.msgid.link/tencent_B320F7091730E06C02BAB57D87B0CE363107@qq.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/fast_commit.c | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/fs/ext4/fast_commit.c b/fs/ext4/fast_commit.c index 8c24e882aee85d..1fbc86519d19fd 100644 --- a/fs/ext4/fast_commit.c +++ b/fs/ext4/fast_commit.c @@ -2320,13 +2320,13 @@ ext4_fc_replay_del_range(struct super_block *sb, u8 *val) return ret; } -static void ext4_fc_set_bitmaps_and_counters(struct super_block *sb) +static int ext4_fc_set_bitmaps_and_counters(struct super_block *sb) { struct ext4_fc_replay_state *state; struct inode *inode; struct ext4_ext_path *path = NULL; struct ext4_map_blocks map; - int i, ret, j; + int i, ret = 0, j; ext4_lblk_t cur, end; state = &EXT4_SB(sb)->s_fc_replay_state; @@ -2354,13 +2354,14 @@ static void ext4_fc_set_bitmaps_and_counters(struct super_block *sb) if (ret > 0) { path = ext4_find_extent(inode, map.m_lblk, path, 0); - if (!IS_ERR(path)) { - for (j = 0; j < path->p_depth; j++) - ext4_mb_mark_bb(inode->i_sb, - path[j].p_block, 1, true); - } else { + if (IS_ERR(path)) { + ret = PTR_ERR(path); path = NULL; + break; } + for (j = 0; j < path->p_depth; j++) + ext4_mb_mark_bb(inode->i_sb, + path[j].p_block, 1, true); cur += ret; ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, true); @@ -2369,9 +2370,14 @@ static void ext4_fc_set_bitmaps_and_counters(struct super_block *sb) } } iput(inode); + if (ret < 0) + goto out; } + ret = 0; +out: ext4_free_ext_path(path); + return ret; } /* @@ -2595,8 +2601,7 @@ static int ext4_fc_replay(journal_t *journal, struct buffer_head *bh, } if (!sbi->s_fc_replay_state.fc_replay_num_tags) { ext4_debug("Replay stops\n"); - ext4_fc_set_bitmaps_and_counters(sb); - return 0; + return ext4_fc_set_bitmaps_and_counters(sb); } #ifdef CONFIG_EXT4_DEBUG @@ -2615,8 +2620,7 @@ static int ext4_fc_replay(journal_t *journal, struct buffer_head *bh, val = cur + EXT4_FC_TAG_BASE_LEN; if (state->fc_replay_num_tags == 0) { - ret = JBD2_FC_REPLAY_STOP; - ext4_fc_set_bitmaps_and_counters(sb); + ret = ext4_fc_set_bitmaps_and_counters(sb); break; } From 180354ab292fae2d0448df3ea61ba9ebf1e9f3bc Mon Sep 17 00:00:00 2001 From: Matthias Goergens Date: Wed, 16 Sep 2026 15:10:46 +0800 Subject: [PATCH 1500/2102] ext4: drop extra ea_inode ref in cached-block reuse path ext4_xattr_block_set() takes a reference on the ea_inode via ext4_xattr_inode_lookup_create() before it builds the new xattr block. The new-block path drops that reference once ext4_xattr_inode_inc_ref_all() has counted every entry in the block. When a separately built block is discarded in favour of an identical cached block, the cached block already counts its entries and the lookup reference is left unbalanced. Each affected reuse leaks one on-disk reference, and the ea_inode and its data blocks stay allocated after the last xattr referring to them is gone. Setting the same xattr on two files is enough when the value needs an EA inode and the entry does not fit in the inode body: the second set reuses the first file's block and leaves the ea_inode at refcount 2, and removing the xattr from both files leaves it at 1. Drop the reference when the entry was not written into the old block in place. new_bh != bs->bh is not the right test: the in-place path can reach 'inserted' and match a different cached block, and there the reference belongs to the old block and ext4_xattr_release_block() drops it, so dropping it here too would under-count. Conversely, new_bh == bs->bh with a cloned s->base (re-setting an unchanged external value on a shared block) leaks the reference as well, so the check follows both branches. If the decrement fails the filesystem is already broken: report the error and return it without rolling back, putting and clearing ea_inode first so that cleanup does not retry the decrement. The reused block keeps its incremented refcount and its block quota charge; e2fsck corrects the refcount. Found by the Sashiko AI review bot while reviewing commit 54b6bd40898d ("ext4: stop retrying saturated xattr cache entries"): https://sashiko.dev/#/patchset/20260802065941.1726052-1-matthias.goergens@gmail.com?part=1 Fixes: 0a46ef234756 ("ext4: do not create EA inode under buffer lock") Cc: stable@vger.kernel.org Signed-off-by: Matthias Goergens Reviewed-by: Jan Kara Link: https://patch.msgid.link/20260916071046.2182813-1-matthias.goergens@gmail.com Signed-off-by: Theodore Ts'o --- fs/ext4/xattr.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/fs/ext4/xattr.c b/fs/ext4/xattr.c index 5c310747b96500..d9e60b5952d2dc 100644 --- a/fs/ext4/xattr.c +++ b/fs/ext4/xattr.c @@ -2113,6 +2113,24 @@ ext4_xattr_block_set(handle_t *handle, struct inode *inode, mb_cache_entry_touch(ea_block_cache, ce); mb_cache_entry_put(ea_block_cache, ce); ce = NULL; + if (ea_inode && !(bs->bh && s->base == bs->bh->b_data)) { + /* + * The cached block already owns its EA inode + * references. For an in-place update the lookup + * reference belongs to the old block and is + * dropped when that block is released. + */ + error = ext4_xattr_inode_dec_ref(handle, + ea_inode); + if (error) { + EXT4_ERROR_INODE(inode, + "dec ref error=%d", + error); + ext4_put_ea_inode(ea_inode); + ea_inode = NULL; + goto cleanup; + } + } } else if (bs->bh && s->base == bs->bh->b_data) { /* We were modifying this block in-place. */ ea_bdebug(bs->bh, "keeping this block"); From addc6c34e5aec1ee279d820b3468718adda38040 Mon Sep 17 00:00:00 2001 From: Manuel Ebner Date: Wed, 16 Sep 2026 12:42:52 +0200 Subject: [PATCH 1501/2102] ext4, doc: remove unnecessary bracket Fix sentence structure to improve readability Signed-off-by: Manuel Ebner Reviewed-by: Jan Kara CC: Randy Dunlap Acked-by: Randy Dunlap Link: https://patch.msgid.link/20260916104251.296148-3-manuelebnerli@mailbox.org Signed-off-by: Theodore Ts'o --- Documentation/filesystems/ext4/directory.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/filesystems/ext4/directory.rst b/Documentation/filesystems/ext4/directory.rst index 9b003a4d453fe7..6d8021309ca45b 100644 --- a/Documentation/filesystems/ext4/directory.rst +++ b/Documentation/filesystems/ext4/directory.rst @@ -429,7 +429,7 @@ block (precisely the length of one dx_entry) are used to store a ``count`` entries in the dx_root/dx_node structures are adjusted as necessary to fit the dx_tail into the block. If there is no space for the dx_tail, the user is notified to run e2fsck -D to rebuild the -directory index (which will ensure that there's space for the checksum. +directory index, which will ensure that there's space for the checksum. The dx_tail structure is 8 bytes long and looks like this: .. list-table:: From 489b444770b16cfdde86e10c05766da976a57928 Mon Sep 17 00:00:00 2001 From: lty <781735889@qq.com> Date: Thu, 17 Sep 2026 11:28:33 +0800 Subject: [PATCH 1502/2102] ext4: propagate errors from fast commit create replay During fast-commit replay, ext4_fc_replay_create() can fail while looking up the parent directory, initializing a new directory, or dirtying the replayed inode. The parent lookup error jumps to the cleanup path while ret is still zero. Errors from ext4_init_new_dir() are explicitly converted to zero, and the return value from ext4_mark_inode_dirty() is ignored. Consequently, replay can report success and mount the filesystem even though the directory creation was not completely replayed. A failed parent lookup, for example, leaves an unconnected directory inode. Propagate these errors so journal recovery aborts rather than completing with inconsistent metadata. Tested with QEMU fast-commit directory replay and injected failures in the parent lookup, directory initialization, and inode dirtying paths. Before the change, recovery completed and e2fsck reported an unconnected directory inode or inconsistent inode metadata. With the change, JBD2 reports recovery failure and the mount fails in all three cases. Fixes: 8016e29f4362 ("ext4: fast commit recovery path") Cc: stable@vger.kernel.org Signed-off-by: lty <781735889@qq.com> Reviewed-by: Jan Kara Link: https://patch.msgid.link/tencent_46A95D4281B70962D6EC1D523A85C448DC09@qq.com Signed-off-by: Theodore Ts'o --- fs/ext4/fast_commit.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fs/ext4/fast_commit.c b/fs/ext4/fast_commit.c index 1fbc86519d19fd..6deaa61e3e7f1d 100644 --- a/fs/ext4/fast_commit.c +++ b/fs/ext4/fast_commit.c @@ -2068,12 +2068,12 @@ static int ext4_fc_replay_create(struct super_block *sb, dir = ext4_iget(sb, darg.parent_ino, EXT4_IGET_NORMAL); if (IS_ERR(dir)) { ext4_debug("Dir %d not found.", darg.ino); + ret = PTR_ERR(dir); goto out; } ret = ext4_init_new_dir(NULL, dir, inode); iput(dir); if (ret) { - ret = 0; goto out; } } @@ -2081,7 +2081,7 @@ static int ext4_fc_replay_create(struct super_block *sb, if (ret) goto out; set_nlink(inode, 1); - ext4_mark_inode_dirty(NULL, inode); + ret = ext4_mark_inode_dirty(NULL, inode); out: iput(inode); return ret; From 3b9f870a75492c1704448cd27ec13781948033ed Mon Sep 17 00:00:00 2001 From: Deepanshu Kartikey Date: Fri, 18 Sep 2026 06:35:58 +0530 Subject: [PATCH 1503/2102] ext4: add bounds check for e_value_offs in ext4_read_inline_data ext4_read_inline_data() reads the location of an inline data xattr value directly from entry->e_value_offs without validating it against the actual bounds of the inode's xattr area. A corrupted filesystem image can set e_value_offs to an out-of-range value, causing the subsequent memcpy() to read from an address far outside the inode buffer, including memory that has already been freed and reused for something else. This mirrors the check already performed in ext4_xattr_ibody_get(), which is missing here. Add a bounds check on the computed source pointer against the end of the inode's xattr area before the memcpy, and reject the read with -EFSCORRUPTED if it would go out of bounds. Fixes: 67cf5b09a46f ("ext4: add the basic function for inline data support") Reported-by: syzbot+085a394c92518a04fd09@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=085a394c92518a04fd09 Tested-by: syzbot+085a394c92518a04fd09@syzkaller.appspotmail.com Signed-off-by: Deepanshu Kartikey Reviewed-by: Jan Kara Link: https://patch.msgid.link/20260918010558.8210-1-kartikey406@gmail.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/inline.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/fs/ext4/inline.c b/fs/ext4/inline.c index 9f6a4d13b9abc6..ee5425183024b1 100644 --- a/fs/ext4/inline.c +++ b/fs/ext4/inline.c @@ -187,6 +187,8 @@ static int ext4_read_inline_data(struct inode *inode, void *buffer, struct ext4_xattr_ibody_header *header; int cp_len = 0; struct ext4_inode *raw_inode; + void *end, *p; + u16 offset; if (!len) return 0; @@ -205,13 +207,21 @@ static int ext4_read_inline_data(struct inode *inode, void *buffer, goto out; header = IHDR(inode, raw_inode); + end = ITAIL(inode, raw_inode); entry = (struct ext4_xattr_entry *)((void *)raw_inode + EXT4_I(inode)->i_inline_off); len = min_t(unsigned int, len, (unsigned int)le32_to_cpu(entry->e_value_size)); - memcpy(buffer, - (void *)IFIRST(header) + le16_to_cpu(entry->e_value_offs), len); + offset = le16_to_cpu(entry->e_value_offs); + p = (void *)IFIRST(header) + offset; + + if (unlikely(p + len > end)) { + EXT4_ERROR_INODE(inode, "corrupt inline xattr entry"); + return -EFSCORRUPTED; + } + + memcpy(buffer, p, len); cp_len += len; out: From 337c173f966c1fbb1aad6dfdf4243323e3b7e304 Mon Sep 17 00:00:00 2001 From: Yichong Chen Date: Fri, 18 Sep 2026 18:12:40 +0800 Subject: [PATCH 1504/2102] ext4: don't free the tmp_inode tree after a partial migration swap ext4_ext_migrate() cleans up the temporary inode when ext4_ext_swap_inode_data() fails: retval = ext4_ext_swap_inode_data(handle, inode, tmp_inode); if (retval) free_ext_block(handle, tmp_inode); ext4_ext_swap_inode_data() switches the inode to extents and copies the tree root into it before it frees the old indirect block map, so it can return an error after the swap has already happened. The copied root points at index blocks that tmp_inode allocated, and free_ext_block() walks that same tree and frees them, leaving the migrated inode with a tree node that the block bitmap considers free. Only free the tmp_inode tree when the inode has not been switched to extents, which is exactly the case where the swap did not happen. Fixes: c14c6fd5c56a ("ext4: Add EXT4_IOC_MIGRATE ioctl") Signed-off-by: Yichong Chen Reviewed-by: Jan Kara Link: https://patch.msgid.link/20260918101240.3721805-1-chenyichong@uniontech.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/migrate.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/ext4/migrate.c b/fs/ext4/migrate.c index 3822bc8729b899..ac314210b630de 100644 --- a/fs/ext4/migrate.c +++ b/fs/ext4/migrate.c @@ -562,7 +562,7 @@ int ext4_ext_migrate(struct inode *inode) free_ext_block(handle, tmp_inode); else { retval = ext4_ext_swap_inode_data(handle, inode, tmp_inode); - if (retval) + if (retval && !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) /* * if we fail to swap inode data free the extent * details of the tmp inode From e290c77088e6f829f7d1d88c915f2a2fb22241e6 Mon Sep 17 00:00:00 2001 From: Zhao Gongyi Date: Fri, 18 Sep 2026 18:12:49 +0800 Subject: [PATCH 1505/2102] ext4: fix OOB memmove in ext4_xattr_set_entry A corrupted filesystem can leave an inode marked as having inline data while the system.data xattr is missing. ext4_destroy_inline_data_nolock() then asks ext4_xattr_set_entry() to remove an entry even though ext4_xattr_ibody_find() left the search state at the insertion position. In the syzkaller reproducer, the old xattr value offset is smaller than min_offs. ext4_xattr_set_entry() then computes val - first_val for memmove(), the length wraps to a huge size_t, and memmove() can run out of the xattr buffer. This results in an out-of-bounds memmove and a kernel page fault. A crafted corrupted ext4 image can trigger this while inline data is being converted out of the inode. Treat the inconsistent inline/xattr state as filesystem corruption before updating the xattr entry. The issue was found by syzkaller and reproduced with the generated C reproducer. The crash signature is: BUG: unable to handle page fault for address: ffff8880074cf000 RIP: 0010:memmove+0x28/0x1b0 Call Trace: ext4_xattr_set_entry+0xe2f/0x1e90 fs/ext4/xattr.c:1761 ext4_xattr_ibody_set+0x3d6/0x5d0 fs/ext4/xattr.c:2268 ext4_destroy_inline_data_nolock+0x288/0x5b0 fs/ext4/inline.c:467 ext4_convert_inline_data_nolock+0x178/0xe80 fs/ext4/inline.c:1222 ext4_convert_inline_data+0x52a/0x610 fs/ext4/inline.c:2083 ext4_fallocate+0x1a0/0x3ba0 fs/ext4/extents.c:4752 Reject the missing system.data xattr before destroying inline data, and validate the old value offset before ext4_xattr_set_entry() reaches the memmove(). The crash was reproduced on unpatched 7.3.0-rc3 and 6.6.122 kernels. With this fix applied to both versions, the same syzkaller C reproducer ran for 120 seconds without triggering KASAN, Oops, a memmove fault, or panic. Fixes: 67cf5b09a46f ("ext4: add the basic function for inline data support") Cc: stable@vger.kernel.org # v3.8+ Signed-off-by: Zhao Gongyi Link: https://patch.msgid.link/20260918101249.43643-1-zhaogongyi@bytedance.com Signed-off-by: Theodore Ts'o --- fs/ext4/inline.c | 6 ++++++ fs/ext4/xattr.c | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/fs/ext4/inline.c b/fs/ext4/inline.c index ee5425183024b1..be76ffc1f98aaf 100644 --- a/fs/ext4/inline.c +++ b/fs/ext4/inline.c @@ -471,6 +471,12 @@ static int ext4_destroy_inline_data_nolock(handle_t *handle, error = ext4_xattr_ibody_find(inode, &i, &is); if (error) goto out; + if (is.s.not_found) { + EXT4_ERROR_INODE(inode, + "corrupted inline data without system.data xattr"); + error = -EFSCORRUPTED; + goto out; + } BUFFER_TRACE(is.iloc.bh, "get_write_access"); error = ext4_journal_get_write_access(handle, inode->i_sb, is.iloc.bh, diff --git a/fs/ext4/xattr.c b/fs/ext4/xattr.c index d9e60b5952d2dc..7be5d49e550c6f 100644 --- a/fs/ext4/xattr.c +++ b/fs/ext4/xattr.c @@ -1712,6 +1712,18 @@ static int ext4_xattr_set_entry(struct ext4_xattr_info *i, } } + if (!s->not_found && here->e_value_size && !here->e_value_inum) { + size_t offs = le16_to_cpu(here->e_value_offs); + + if (offs < min_offs) { + EXT4_ERROR_INODE(inode, + "corrupted xattr: value offset %zu < min_offs %zu", + offs, min_offs); + ret = -EFSCORRUPTED; + goto out; + } + } + /* * Getting access to old and new ea inodes is subject to failures. * Finish that work before doing any modifications to the xattr data. From eb63eca72747d85cc0ac3e7d8044bba77080a3f1 Mon Sep 17 00:00:00 2001 From: Kaixuan Li Date: Sat, 19 Sep 2026 19:39:40 +0800 Subject: [PATCH 1506/2102] ext4: stop verify_reserved_gdb() one entry short of the block verify_reserved_gdb() walks the backup group list, reading one __le32 from the reserved GDT block per iteration, and bounds the walk after the read: if (le32_to_cpu(*p++) != grp * EXT4_BLOCKS_PER_GROUP(sb) + blk){ ... return -EINVAL; } if (++gdbackups > EXT4_ADDR_PER_BLOCK(sb)) return -EFBIG; The block holds exactly EXT4_ADDR_PER_BLOCK(sb) entries, so when gdbackups reaches that value the test is false, the loop runs once more, and *p++ reads one entry past the block before -EFBIG is returned. The same value is also the largest gdbackups the function can return, and reserve_backup_gdb() then uses it as an index into a block of exactly that many entries: data = (__le32 *)primary[i]->b_data; data[gdbackups] = cpu_to_le32(blk + primary[i]->b_blocknr); which writes one entry past. Comparing with >= stops the walk before the read and caps the return value one lower, which closes both. The walk enumerates the groups ext4_list_backups() produces -- the powers of 3, 5 and 7 below the group being added -- so EXT4_ADDR_PER_BLOCK of them, 256 at a 1K block size and 1024 at 4K, cannot occur within a 32-bit group number. The entry the old bound went on to read was therefore never a real backup. Signed-off-by: Kaixuan Li Reviewed-by: Jan Kara Link: https://patch.msgid.link/20260919113940.1823559-1-kaixuanli0131@gmail.com Signed-off-by: Theodore Ts'o --- fs/ext4/resize.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/ext4/resize.c b/fs/ext4/resize.c index 041ab212c3a6c3..8e61f1e22c51c3 100644 --- a/fs/ext4/resize.c +++ b/fs/ext4/resize.c @@ -795,7 +795,7 @@ static int verify_reserved_gdb(struct super_block *sb, blk); return -EINVAL; } - if (++gdbackups > EXT4_ADDR_PER_BLOCK(sb)) + if (++gdbackups >= EXT4_ADDR_PER_BLOCK(sb)) return -EFBIG; } From f0a38eb3ebf925386ded88e642bd2c5b3d06534b Mon Sep 17 00:00:00 2001 From: Ojaswin Mujoo Date: Thu, 24 Sep 2026 13:09:28 +0530 Subject: [PATCH 1507/2102] ext4: Fix sparse warning in extents kunit test when EXT4_KUNIT_TESTS=m When kunit tests are compiled as modules, the extents kunit test emits a sparse warning: >> fs/ext4/extents-test.c:59:3: sparse: sparse: symbol 'k_ctx' was not declared. Should it be static? Fix this by declaring it as static. Fixes: cb1e0c1d1fad ("ext4: kunit tests for extent splitting and conversion") Reported-by: kernel test robot Closes: https://lore.kernel.org/oe-kbuild-all/202609221900.Pgwrcp41-lkp@intel.com/ Reviewed-by: Baokun Li Reviewed-by: Zhang Yi Reviewed-by: Jan Kara Signed-off-by: Ojaswin Mujoo Link: https://patch.msgid.link/20260924073929.2594339-1-ojaswin@linux.ibm.com Signed-off-by: Theodore Ts'o --- fs/ext4/extents-test.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/ext4/extents-test.c b/fs/ext4/extents-test.c index 2e997f228330f5..0f897d9ff4feea 100644 --- a/fs/ext4/extents-test.c +++ b/fs/ext4/extents-test.c @@ -48,7 +48,7 @@ #define EXT_DATA_LBLK 10 #define EXT_DATA_LEN 3 -struct kunit_ctx { +static struct kunit_ctx { /* * Ext4 inode which has only 1 unwrit extent */ From 40e53dad45a92e932156de23a69c991f3e2512c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20G=C3=B6ttsche?= Date: Mon, 28 Sep 2026 22:21:59 +0200 Subject: [PATCH 1508/2102] jbd2: set JBD2_LOADED under j_state_lock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit j_flags is protected by j_state_lock, with only quick racy checks done without it. jbd2_journal_load() however sets JBD2_LOADED with a plain read-modify-write after journal_reset() has already started kjournald2, which tests and may update j_flags under the lock. KCSAN reports this while mounting the root file system: BUG: KCSAN: data-race in jbd2_journal_load / kjournald2 write to 0xffff9c6b012c6000 of 8 bytes by task 1 on cpu 3: jbd2_journal_load+0x279/0x3c0 ext4_fill_super+0x34dc/0x5740 get_tree_bdev_flags+0x21d/0x340 ... read to 0xffff9c6b012c6000 of 8 bytes by task 77 on cpu 0: kjournald2+0xc8/0x3e0 kthread+0x1bd/0x200 ... value changed: 0x00000000000000a8 -> 0x00000000000000b8 A concurrent update of another flag, e.g. JBD2_ABORT, could be lost. Take j_state_lock when setting JBD2_LOADED, like the other writers of j_flags do. Fixes: 470decc613ab ("[PATCH] jbd2: initial copy of files from jbd") Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Christian Göttsche Reviewed-by: Jan Kara Link: https://patch.msgid.link/20260928202159.2463182-1-cgoettsche@seltendoof.de Signed-off-by: Theodore Ts'o --- fs/jbd2/journal.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/fs/jbd2/journal.c b/fs/jbd2/journal.c index 3a4f3f613ead8a..a1c4772c7200da 100644 --- a/fs/jbd2/journal.c +++ b/fs/jbd2/journal.c @@ -2096,7 +2096,10 @@ int jbd2_journal_load(journal_t *journal) return err; } + /* kjournald2 is already running, see journal_reset(). */ + write_lock(&journal->j_state_lock); journal->j_flags |= JBD2_LOADED; + write_unlock(&journal->j_state_lock); return 0; } From 8d90b9ab0875a6a838125e4980c8c6ab4a021c0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Jean?= Date: Wed, 30 Sep 2026 13:45:17 +0000 Subject: [PATCH 1509/2102] ext4: save converted extent before merging MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In ext4_split_convert_extents(), merging can release the leaf holding the extent pointed to by ex. The later extent status cache update can then dereference freed memory, causing a use-after-free. KASAN reports: BUG: KASAN: use-after-free in ext4_split_convert_extents.constprop.0+0xb98/0xc80 Read of size 2 at addr ff11000002547034 by task fixture/65 Save the converted extent before merging and use the copy for the cache update. This also avoids using the old extent slot after a merge with the left neighbour. Fixes: 716b9c23b862 ("ext4: refactor split and convert extents") Cc: stable@kernel.org Assisted-by: LLM Signed-off-by: Jérémy Jean Reviewed-by: Ojaswin Mujoo Link: https://patch.msgid.link/20260930134516.397754-2-Jeremy.Jean@oss.cyber.gouv.fr Signed-off-by: Theodore Ts'o --- fs/ext4/extents.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index 855d328fc7b9fe..a584d1bbd84609 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -3830,6 +3830,7 @@ static struct ext4_ext_path *ext4_split_convert_extents(handle_t *handle, ext4_lblk_t eof_block; ext4_lblk_t ee_block; struct ext4_extent *ex; + struct ext4_extent converted_ex; unsigned int ee_len; int split_flag = 0, depth, err = 0; bool did_zeroout = false; @@ -3887,6 +3888,9 @@ static struct ext4_ext_path *ext4_split_convert_extents(handle_t *handle, else if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) ext4_ext_mark_unwritten(ex); + /* Merging can move ex or release the leaf containing it. */ + converted_ex = *ex; + if (!(flags & EXT4_GET_BLOCKS_SPLIT_NOMERGE)) /* * note: ext4_ext_correct_indexes() isn't needed here because @@ -3897,6 +3901,7 @@ static struct ext4_ext_path *ext4_split_convert_extents(handle_t *handle, err = ext4_ext_dirty(handle, inode, path + depth); if (err) goto err; + ex = &converted_ex; } /* Lets update the extent status tree after conversion */ From 0bc15784860ec2c61ec7abd1ccba6e931ba830b6 Mon Sep 17 00:00:00 2001 From: Qiliang Yuan Date: Thu, 1 Oct 2026 15:43:43 +0800 Subject: [PATCH 1510/2102] jbd2: fix shrinker scan budget accounting in jbd2_journal_shrink_scan() do_shrink_slab() reads count_objects() once per invocation to derive a one-shot scan budget, then calls scan_objects() repeatedly until that budget is exhausted or scan_objects() returns SHRINK_STOP. include/linux/shrinker.h documents that scan_objects() "should track its actual progress" in sc->nr_scanned, so do_shrink_slab() can tell when there is nothing left to examine and stop early. jbd2_journal_shrink_scan() never updates sc->nr_scanned, so it defaults to the full sc->nr_to_scan on every call. do_shrink_slab() therefore always believes a full batch was examined, regardless of what jbd2_journal_shrink_checkpoint_list() actually did, and keeps calling scan_objects() until the budget derived from the (possibly stale) percpu checkpoint count is drained, even after the checkpoint list has already been fully drained. jbd2_journal_shrink_checkpoint_list() already tracks examined buffers accurately: it decrements its nr_to_scan in/out parameter for every journal_head walked, whether or not it gets freed. Derive sc->nr_scanned from the difference, and return SHRINK_STOP once it comes back zero, since that only happens when the checkpoint list had nothing left to walk. Key this off sc->nr_scanned rather than nr_shrunk: a batch can find every buffer in its transactions busy and free none, while later transactions may still hold buffers whose writeback has completed; sc->nr_scanned reflects that real work either way. Tested by creating 20000 small files, running sync, and letting checkpointing settle for a few seconds (with systemd-journald and cron stopped, since their own writes to the same filesystem keep re-populating the checkpoint list and mask the effect being measured), then triggering "echo 2 > /proc/sys/vm/drop_caches" while tracing jbd2_shrink_scan_enter/exit: total scan_objects() calls with calls nr_scanned == 0 before this patch 22 10 (45%) after this patch 8 1 (12%) Fixes: 4ba3fcdde7e3 ("jbd2,ext4: add a shrinker to release checkpointed buffers") Cc: stable@vger.kernel.org Signed-off-by: Qiliang Yuan Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261001-fix-jbd2-shrink-scan-nr-scanned-v5-1-5348b51efce2@gmail.com Signed-off-by: Theodore Ts'o --- fs/jbd2/journal.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/fs/jbd2/journal.c b/fs/jbd2/journal.c index a1c4772c7200da..4ae325a1a657e7 100644 --- a/fs/jbd2/journal.c +++ b/fs/jbd2/journal.c @@ -1268,10 +1268,22 @@ static unsigned long jbd2_journal_shrink_scan(struct shrinker *shrink, trace_jbd2_shrink_scan_enter(journal, sc->nr_to_scan, count); nr_shrunk = jbd2_journal_shrink_checkpoint_list(journal, &nr_to_scan); + sc->nr_scanned = sc->nr_to_scan - nr_to_scan; count = percpu_counter_read_positive(&journal->j_checkpoint_jh_count); trace_jbd2_shrink_scan_exit(journal, nr_to_scan, nr_shrunk, count); + /* + * Key SHRINK_STOP off sc->nr_scanned (buffers actually examined), + * not nr_shrunk (buffers actually freed): a batch can find every + * buffer in its transactions busy and free none, while later + * transactions may still hold buffers whose writeback has + * completed. sc->nr_scanned only comes back 0 when the checkpoint + * list had nothing left to walk. + */ + if (sc->nr_scanned == 0) + return SHRINK_STOP; + return nr_shrunk; } From 020035ee8fea4b7ee0cac6197c4bc801c793d889 Mon Sep 17 00:00:00 2001 From: Qiliang Yuan Date: Thu, 1 Oct 2026 15:43:56 +0800 Subject: [PATCH 1511/2102] ext4: fix shrinker scan budget accounting in ext4_es_scan() do_shrink_slab() reads count_objects() once per invocation to derive a one-shot scan budget, then calls scan_objects() repeatedly until that budget is exhausted or scan_objects() returns SHRINK_STOP. include/linux/shrinker.h documents that scan_objects() "should track its actual progress" in sc->nr_scanned, so do_shrink_slab() can tell when there is nothing left to examine and stop early. ext4_es_scan() never updates sc->nr_scanned, so it defaults to the full sc->nr_to_scan on every call. do_shrink_slab() therefore always believes a full batch was examined, regardless of what __es_shrink() actually did, and keeps calling scan_objects() until the budget derived from the (possibly stale) percpu extent_status count is drained, even after sbi->s_es_list has nothing left to examine. Make __es_shrink() report the number of extent_status objects it actually examined through a new nr_scanned output parameter, derived from the existing per-extent nr_to_scan counter that es_reclaim_extents() already decrements as it walks the tree. Have ext4_es_scan() copy this into sc->nr_scanned, and return SHRINK_STOP once it comes back zero. Key this off nr_scanned rather than nr_shrunk: a batch that finds every extent still referenced correctly ages them without freeing any, and that is real progress nr_shrunk would miss. nr_scanned can come back zero for more than a genuinely empty list: es_stats_shk_cnt is a stale percpu count, an inode can be momentarily skipped (precached, lock contended), or durably have nothing shrinkable (i_es_shk_nr == 0) without es_reclaim_extents() ever touching nr_to_scan. Treat all of these alike: not stopping doesn't help the transient cases either, since do_shrink_slab()'s budget only decrements by nr_scanned, so retrying forever at nr_scanned == 0 never terminates. Tested by fallocate(2)-ing 10000 4K files (to populate the shrinker with reclaimable unwritten extents without also exercising the extent_status "referenced" second-chance path, which needs a separate two-pass accounting of its own) and triggering "echo 2 > /proc/sys/vm/drop_caches", while tracing the ext4_es_shrink* tracepoints: total scan_objects() calls with calls nr_shrunk == 0 before this patch 429 189 (44%) after this patch 239 1 (0.4%) Fixes: 1ab6c4997e04 ("fs: convert fs shrinkers to new scan/count API") Cc: stable@vger.kernel.org Signed-off-by: Qiliang Yuan Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261001-fix-ext4-es-scan-nr-scanned-v4-1-b13703714ce2@gmail.com Signed-off-by: Theodore Ts'o --- fs/ext4/extents_status.c | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/fs/ext4/extents_status.c b/fs/ext4/extents_status.c index 018b6146b9d815..a48e62e61e69c2 100644 --- a/fs/ext4/extents_status.c +++ b/fs/ext4/extents_status.c @@ -184,7 +184,7 @@ static int __es_remove_extent(struct inode *inode, ext4_lblk_t lblk, struct extent_status *prealloc); static int es_reclaim_extents(struct ext4_inode_info *ei, int *nr_to_scan); static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, - struct ext4_inode_info *locked_ei); + struct ext4_inode_info *locked_ei, int *nr_scanned); static int __revise_pending(struct inode *inode, ext4_lblk_t lblk, ext4_lblk_t len, struct pending_reservation **prealloc); @@ -1670,7 +1670,7 @@ void ext4_es_remove_extent(struct inode *inode, ext4_lblk_t lblk, } static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, - struct ext4_inode_info *locked_ei) + struct ext4_inode_info *locked_ei, int *nr_scanned) { struct ext4_inode_info *ei; struct ext4_es_stats *es_stats; @@ -1679,6 +1679,7 @@ static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, int nr_to_walk; int nr_shrunk = 0; int retried = 0, nr_skipped = 0; + int orig_nr_to_scan = nr_to_scan; es_stats = &sbi->s_es_stats; start_time = ktime_get(); @@ -1738,6 +1739,8 @@ static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, nr_shrunk = es_reclaim_extents(locked_ei, &nr_to_scan); out: + *nr_scanned = orig_nr_to_scan - nr_to_scan; + scan_time = ktime_to_ns(ktime_sub(ktime_get(), start_time)); if (likely(es_stats->es_stats_scan_time)) es_stats->es_stats_scan_time = (scan_time + @@ -1774,15 +1777,36 @@ static unsigned long ext4_es_scan(struct shrinker *shrink, { struct ext4_sb_info *sbi = shrink->private_data; int nr_to_scan = sc->nr_to_scan; - int ret, nr_shrunk; + int ret, nr_shrunk, nr_scanned; ret = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt); trace_ext4_es_shrink_scan_enter(sbi->s_sb, nr_to_scan, ret); - nr_shrunk = __es_shrink(sbi, nr_to_scan, NULL); + nr_shrunk = __es_shrink(sbi, nr_to_scan, NULL, &nr_scanned); + sc->nr_scanned = nr_scanned; ret = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt); trace_ext4_es_shrink_scan_exit(sbi->s_sb, nr_shrunk, ret); + + /* + * Key SHRINK_STOP off nr_scanned (extents actually examined), not + * nr_shrunk (extents actually freed): a batch that finds every + * extent still referenced correctly ages them without freeing + * any, and that is real progress nr_shrunk would miss. + * + * nr_scanned can come back 0 for more than a genuinely empty + * sbi->s_es_list: es_stats_shk_cnt is a stale percpu count, an + * inode can be momentarily skipped (precached, lock contended), + * or durably have nothing shrinkable (i_es_shk_nr == 0) without + * es_reclaim_extents() ever touching nr_to_scan. Treat all of + * these alike: not stopping doesn't help the transient cases + * either, since do_shrink_slab()'s budget only decrements by + * nr_scanned, so retrying forever at nr_scanned == 0 never + * terminates. + */ + if (nr_scanned == 0) + return SHRINK_STOP; + return nr_shrunk; } From b06e975bf451a3a90cec05693f0836f38cd398c8 Mon Sep 17 00:00:00 2001 From: Qiliang Yuan Date: Thu, 1 Oct 2026 15:43:57 +0800 Subject: [PATCH 1512/2102] ext4: remove unused locked_ei parameter from __es_shrink() __es_shrink()'s locked_ei parameter exists to let a caller pass in an inode it already holds i_es_lock on, so the shrinker walk can skip that inode instead of deadlocking on write_trylock(), and fall back to reclaiming from it directly if nothing else could be freed. Its only caller, ext4_es_scan(), always passes NULL. Drop the parameter along with the two code paths that exist solely to support it: the ei == locked_ei skip check, and the trailing es_reclaim_extents(locked_ei, ...) fallback, neither of which can ever run while locked_ei is always NULL. Signed-off-by: Qiliang Yuan Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261001-fix-ext4-es-scan-nr-scanned-v4-2-b13703714ce2@gmail.com Signed-off-by: Theodore Ts'o --- fs/ext4/extents_status.c | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/fs/ext4/extents_status.c b/fs/ext4/extents_status.c index a48e62e61e69c2..c250b7d356f506 100644 --- a/fs/ext4/extents_status.c +++ b/fs/ext4/extents_status.c @@ -184,7 +184,7 @@ static int __es_remove_extent(struct inode *inode, ext4_lblk_t lblk, struct extent_status *prealloc); static int es_reclaim_extents(struct ext4_inode_info *ei, int *nr_to_scan); static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, - struct ext4_inode_info *locked_ei, int *nr_scanned); + int *nr_scanned); static int __revise_pending(struct inode *inode, ext4_lblk_t lblk, ext4_lblk_t len, struct pending_reservation **prealloc); @@ -1670,7 +1670,7 @@ void ext4_es_remove_extent(struct inode *inode, ext4_lblk_t lblk, } static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, - struct ext4_inode_info *locked_ei, int *nr_scanned) + int *nr_scanned) { struct ext4_inode_info *ei; struct ext4_es_stats *es_stats; @@ -1707,7 +1707,7 @@ static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, continue; } - if (ei == locked_ei || !write_trylock(&ei->i_es_lock)) { + if (!write_trylock(&ei->i_es_lock)) { nr_skipped++; continue; } @@ -1735,9 +1735,6 @@ static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, goto retry; } - if (locked_ei && nr_shrunk == 0) - nr_shrunk = es_reclaim_extents(locked_ei, &nr_to_scan); - out: *nr_scanned = orig_nr_to_scan - nr_to_scan; @@ -1782,7 +1779,7 @@ static unsigned long ext4_es_scan(struct shrinker *shrink, ret = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt); trace_ext4_es_shrink_scan_enter(sbi->s_sb, nr_to_scan, ret); - nr_shrunk = __es_shrink(sbi, nr_to_scan, NULL, &nr_scanned); + nr_shrunk = __es_shrink(sbi, nr_to_scan, &nr_scanned); sc->nr_scanned = nr_scanned; ret = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt); From daa099ec5ce3fa863886588fbc8a9af1e351e368 Mon Sep 17 00:00:00 2001 From: Jan Kara Date: Fri, 2 Oct 2026 13:50:41 +0200 Subject: [PATCH 1513/2102] ext4: Fix maximum orphan file size check Mikulas reported that e2fsprogs 1.47.4 with 1k fs blocksize by default creates orphan file of the size the kernel rejects. This is because that version of e2fsprogs creates 2MB file by default regardless of the block size and with 1k blocks that's more than the limit of 512 fs blocks. Fix the check to make kernel accept any file upto those 2MB regardless of the number of blocks. Fixes: 7c11c56eb32e ("ext4: align max orphan file size with e2fsprogs limit") CC: stable@vger.kernel.org Reported-by: Mikulas Patocka Link: https://lore.kernel.org/all/e65cdbfe-3ff9-4638-fbd3-4d8f8880966f@redhat.com Signed-off-by: Jan Kara Tested-by: Mikulas Patocka Reviewed-by: Mikulas Patocka Reviewed-by: Baokun Li Reviewed-by: Zhang Yi Link: https://patch.msgid.link/20261002115040.2783654-2-jack@suse.cz Signed-off-by: Theodore Ts'o --- fs/ext4/orphan.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/fs/ext4/orphan.c b/fs/ext4/orphan.c index b4675aa7ea965f..7394d04e0fd930 100644 --- a/fs/ext4/orphan.c +++ b/fs/ext4/orphan.c @@ -576,6 +576,7 @@ int ext4_init_orphan_info(struct super_block *sb) int inodes_per_ob = ext4_inodes_per_orphan_block(sb); struct ext4_orphan_block_tail *ot; ino_t orphan_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_orphan_file_inum); + loff_t max_size; if (!ext4_has_feature_orphan_file(sb)) return 0; @@ -589,8 +590,13 @@ int ext4_init_orphan_info(struct super_block *sb) * This is just an artificial limit to prevent corrupted fs from * consuming absurd amounts of memory when pinning blocks of orphan * file in memory. + * + * e2fsprogs 1.47.4 produces 2MB orphan files by default regardless + * of the number of blocks so that's where the second limit comes from. */ - if (inode->i_size > (EXT4_MAX_ORPHAN_FILE_BLOCKS << inode->i_blkbits)) { + max_size = max(EXT4_MAX_ORPHAN_FILE_BLOCKS << inode->i_blkbits, + 2 << 20); + if (inode->i_size > max_size) { ext4_msg(sb, KERN_ERR, "orphan file too big: %llu", (unsigned long long)inode->i_size); ret = -EFSCORRUPTED; From 474b6405c0f6a29ab3ae749647c2bc06970bff53 Mon Sep 17 00:00:00 2001 From: Hengyu Liang Date: Tue, 6 Oct 2026 07:15:46 -0400 Subject: [PATCH 1514/2102] ext4: do not accept rec_len 0 for block sizes below 64k Commit afa6d5a16bf2 ("ext4: remove PAGE_SIZE checks for rec_len conversion") made ext4_rec_len_from_disk() read a rec_len of 0 as "this entry covers the whole block" for every block size. However, this special value only exists for block sizes of 64k and more. With smaller blocks, a rec_len of 0 means that the directory block is corrupted. As of now, a directory block that has been overwritten with zeroes is treated as an empty block. The kernel no longer reports the corruption and can store new entries in that block, while e2fsck still reports the block as corrupted. The issue can be reproduced on a file system without metadata_csum: mke2fs -q -t ext4 -b 1024 -O ^metadata_csum,^dir_index img 8M mount -o loop img /mnt mkdir /mnt/d for i in $(seq 100); do touch /mnt/d/file_with_a_long_name_$i; done umount /mnt dd if=/dev/zero of=img bs=1024 count=1 conv=notrunc \ seek=$(debugfs -R "bmap d 1" img) mount -o loop img /mnt touch /mnt/d/new Before commit afa6d5a16bf2 ("ext4: remove PAGE_SIZE checks for rec_len conversion"), the last command fails with "Structure needs cleaning". After that commit, it succeeds. This patch makes ext4_rec_len_from_disk() return the on-disk value unchanged when the block size is below 64k, as e2fsprogs does. Fixes: afa6d5a16bf2 ("ext4: remove PAGE_SIZE checks for rec_len conversion") Cc: stable@vger.kernel.org Signed-off-by: Hengyu Liang Reviewed-by: Jan Kara Reviewed-by: Baokun Li Link: https://patch.msgid.link/20261006111546.3252481-1-hengyul@cs.unc.edu Signed-off-by: Theodore Ts'o --- fs/ext4/ext4.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index 8386e85d29644c..578238b7b41cdf 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -2628,6 +2628,13 @@ ext4_rec_len_from_disk(__le16 dlen, unsigned blocksize) { unsigned len = le16_to_cpu(dlen); + /* + * Only blocks of 64k and more need the special encoding of rec_len. + * For smaller blocks 0 and EXT4_MAX_REC_LEN are not valid lengths + * and must not be taken for an entry that spans the whole block. + */ + if (blocksize < 65536) + return len; if (len == EXT4_MAX_REC_LEN || len == 0) return blocksize; return (len & 65532) | ((len & 3) << 16); From 543341eba8f4f2c6de0aa7b74b3c50dd2c5825b4 Mon Sep 17 00:00:00 2001 From: Daejun Park Date: Wed, 7 Oct 2026 09:41:09 +0900 Subject: [PATCH 1515/2102] jbd2: don't start a fast commit while the journal is marked empty jbd2_journal_flush() checkpoints everything, and jbd2_mark_journal_empty() then writes the journal superblock with s_start == 0 and the fast commit feature cleared. It sets JBD2_FLUSHED so that the next commit writes the log tail and the feature back, but only jbd2_journal_commit_transaction() looks at that flag. A fast commit started before the next full commit writes its blocks while the superblock on disk still says the log is empty: jbd2_journal_recover() returns at once and the fast commit is never replayed. On ext4 with -O fast_commit this happens after ext4_freeze(), and after a remount to read-only, which flushes the journal in ext4_mark_recovery_complete(), once the file system is read-write again. EXT4_IOC_CHECKPOINT and online resize flush it as well. An fsync that a fast commit handles after one of them is lost if the system crashes before the next full commit, which can be up to the commit interval later: mount -o commit=60 (-O fast_commit file system) echo first > a; sync fsfreeze -f; fsfreeze -u # or: remount ro, then rw write b; fsync b # one fast commit, s_start still 0 crash (kill the VM), mount b is missing Refuse to start a fast commit while JBD2_FLUSHED is set, as is already done before the first full commit. ext4 then falls back to a full commit, which writes the log tail, and the fast commits after it are recovered again. fc_info counts the refused fast commit as ineligible, as it does for the existing check. Fixes: ff780b91efe9 ("jbd2: add fast commit machinery") Cc: stable@vger.kernel.org Signed-off-by: Daejun Park Reviewed-by: Jan Kara Reviewed-by: Zhang Yi Link: https://patch.msgid.link/20261007-jbd2-fc-after-flush-v1-1-548bd91cd959@samsung.com Signed-off-by: Theodore Ts'o --- fs/jbd2/journal.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/fs/jbd2/journal.c b/fs/jbd2/journal.c index 4ae325a1a657e7..eb8e944f1f9e67 100644 --- a/fs/jbd2/journal.c +++ b/fs/jbd2/journal.c @@ -700,7 +700,8 @@ int jbd2_log_wait_commit(journal_t *journal, tid_t tid) * it to complete. Returns 0 if a new fast commit was started. Returns -EALREADY * if a fast commit is not needed, either because there's an already a commit * going on or this tid has already been committed. Returns -EINVAL if no jbd2 - * commit has yet been performed. + * commit has yet been performed, or none since the journal was last marked + * empty. */ int jbd2_fc_begin_commit(journal_t *journal, tid_t tid) { @@ -719,6 +720,16 @@ int jbd2_fc_begin_commit(journal_t *journal, tid_t tid) return -EALREADY; } + /* + * The log was emptied and the superblock on disk says so, which makes + * recovery skip the fast commit area as well. Only a full commit + * records the log tail again. + */ + if (journal->j_flags & JBD2_FLUSHED) { + write_unlock(&journal->j_state_lock); + return -EINVAL; + } + if (journal->j_flags & JBD2_FULL_COMMIT_ONGOING || (journal->j_flags & JBD2_FAST_COMMIT_ONGOING)) { DEFINE_WAIT(wait); From 44d3b834bef881c7ee9d5454661d54e6a562c53e Mon Sep 17 00:00:00 2001 From: Daejun Park Date: Wed, 7 Oct 2026 09:41:31 +0900 Subject: [PATCH 1516/2102] ext4: skip holes when shrinking the extent tree in fast commit replay ext4_ext_replay_shrink_inode() walks the extents of an inode from block 0 up to the given end and tries to merge each one with its neighbours. When the walk is in a hole that follows an extent, ext4_find_extent() returns that extent, and the walk moves on by a single block. Replay calls it up to i_size after every ADD_RANGE and DEL_RANGE tag, so the time recovery takes is proportional to the number of tags times the number of hole blocks below i_size. After a crash, mount can be busy for minutes. Replaying a single ADD_RANGE tag, for one block written and fsynced in a sparse file with a 1 TiB i_size, kept mount busy for 157 seconds. Replaying four fast commits of a sparse file with 512 written regions (2048 ADD_RANGE tags, and 2044 DEL_RANGE tags for the gaps between them) took 44 seconds when the file was 64 MiB and 177 seconds when it was 256 MiB. With this change the 1 TiB case takes less than 0.1 seconds, and the other two 3 seconds each. When the walk is in such a hole, continue at the next extent, as returned by ext4_ext_next_allocated_block(), or stop if there is none. For each block skipped this way, the old walk found the same extent again and retried the same merges, so the resulting tree is the same. Fixes: 8016e29f4362 ("ext4: fast commit recovery path") Cc: stable@vger.kernel.org Signed-off-by: Daejun Park Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261007-ext4-fc-replay-shrink-v1-1-0e45fc03030d@samsung.com Signed-off-by: Theodore Ts'o --- fs/ext4/extents.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index a584d1bbd84609..453c4492805ca2 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -6271,8 +6271,10 @@ void ext4_ext_replay_shrink_inode(struct inode *inode, ext4_lblk_t end) } old_cur = cur; cur = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex); + /* ex ends before old_cur, which is in a hole: skip the hole */ if (cur <= old_cur) - cur = old_cur + 1; + cur = max(old_cur + 1, + ext4_ext_next_allocated_block(path)); ext4_ext_try_to_merge(NULL, inode, path, ex); down_write(&EXT4_I(inode)->i_data_sem); ext4_ext_dirty(NULL, inode, &path[path->p_depth]); From ff06f373c1d796f2c4f196c8bee9cd7ea5ee3c96 Mon Sep 17 00:00:00 2001 From: Hsiu-Hsien Lee Date: Wed, 7 Oct 2026 12:08:29 +0800 Subject: [PATCH 1517/2102] ext4: don't fail journal recovery on an incomplete fast commit If the system crashes while the first fast commit after a full commit is being written, the fast commit area can hold the head of that fast commit without a valid tail. ext4_fc_replay_scan() treats this as an error as long as no valid tail has been seen: an invalid tag length or an unknown tag returns -ECANCELED, a tail with a wrong tid or checksum returns -EFSBADCRC. jbd2_journal_recover() then fails, the file system can be mounted neither read-write nor read-only, and the regular journal transactions committed before the fast commit are not replayed either: JBD2: journal recovery failed EXT4-fs (sdb): error loading journal The tail is written last and fsync() does not return before it has completed, so an incomplete fast commit was never reported as durable. Handle it like jbd2 handles a transaction without a valid commit block: stop the scan and replay what is valid. This is already what happens when an earlier fast commit in the area has a valid tail. Reproducer, with the power cut emulated by copying the device while it is mounted: mkfs.ext4 -O fast_commit /dev/sdb mount /dev/sdb /mnt; mkdir /mnt/d create 20 files in /mnt/d; sync write a fragmented file and modify the 20 files, fsync one file (one fast commit spanning several blocks) copy /dev/sdb while still mounted, then zero the block holding the fast commit tail in the copy mount the copy Without this patch the mount fails as above. With it, the mount succeeds, the state after sync is recovered and e2fsck finds no errors. The same holds when a full commit precedes the torn fast commit, in which case the full commit is now replayed as well. Fixes: 8016e29f4362 ("ext4: fast commit recovery path") Signed-off-by: Hsiu-Hsien Lee Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261007040829.2074386-1-swinds24@gmail.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/fast_commit.c | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/fs/ext4/fast_commit.c b/fs/ext4/fast_commit.c index 6deaa61e3e7f1d..c634f7ae743839 100644 --- a/fs/ext4/fast_commit.c +++ b/fs/ext4/fast_commit.c @@ -2455,6 +2455,12 @@ static bool ext4_fc_value_len_isvalid(struct ext4_sb_info *sbi, * It returns a negative error to indicate that there was an error. At the end * of a successful scan phase, sbi->s_fc_replay_state.fc_replay_num_tags is set * to indicate the number of tags that need to replayed during the replay phase. + * + * An invalid tag or a tail that does not match ends the scan without an error. + * This is what a fast commit that was only partially written before a crash + * looks like. Its tail is written last and fsync() does not return before + * the tail is on disk, so such a fast commit was never reported as durable and + * is simply dropped, like jbd2 drops a transaction without a commit block. */ static int ext4_fc_replay_scan(journal_t *journal, struct buffer_head *bh, int off, @@ -2501,8 +2507,9 @@ static int ext4_fc_replay_scan(journal_t *journal, val = cur + EXT4_FC_TAG_BASE_LEN; if (tl.fc_len > end - val || !ext4_fc_value_len_isvalid(sbi, tl.fc_tag, tl.fc_len)) { - ret = state->fc_replay_num_tags ? - JBD2_FC_REPLAY_STOP : -ECANCELED; + ext4_debug("Scan phase, invalid tag length, blk %lld\n", + bh->b_blocknr); + ret = JBD2_FC_REPLAY_STOP; goto out_err; } ext4_debug("Scan phase, tag:%s, blk %lld\n", @@ -2542,8 +2549,9 @@ static int ext4_fc_replay_scan(journal_t *journal, state->fc_regions_valid = state->fc_regions_used; } else { - ret = state->fc_replay_num_tags ? - JBD2_FC_REPLAY_STOP : -EFSBADCRC; + ext4_debug("Scan phase, invalid tail, blk %lld\n", + bh->b_blocknr); + ret = JBD2_FC_REPLAY_STOP; } state->fc_crc = 0; break; @@ -2563,8 +2571,9 @@ static int ext4_fc_replay_scan(journal_t *journal, EXT4_FC_TAG_BASE_LEN + tl.fc_len); break; default: - ret = state->fc_replay_num_tags ? - JBD2_FC_REPLAY_STOP : -ECANCELED; + ext4_debug("Scan phase, unknown tag %d, blk %lld\n", + tl.fc_tag, bh->b_blocknr); + ret = JBD2_FC_REPLAY_STOP; } if (ret < 0 || ret == JBD2_FC_REPLAY_STOP) break; From 79906e00636e7e7831489e9c6a53dad1ec7a3399 Mon Sep 17 00:00:00 2001 From: Daejun Park Date: Thu, 8 Oct 2026 10:25:36 +0900 Subject: [PATCH 1518/2102] ext4: don't cache unzeroed blocks as written after a failed zeroout ext4_ext_convert_to_initialized() may zero out the blocks before and after the range being written and convert them to written together with it, instead of splitting them off the unwritten extent. If ext4_ext_zeroout() fails for one side, it falls back to splitting the extent, so the blocks on that side stay unwritten in the extent tree. But zero_ex1 or zero_ex2 keeps its length, and ext4_zeroout_es() still inserts those blocks into the extent status tree as written. Until that entry goes away, a read of those blocks returns whatever was on the disk before the extent was allocated. A write to them is mapped from the cache and goes in place without converting the extent, so its data would read back as zeroes once the entry is dropped. To reproduce on 4 KiB blocks with -o nodelalloc: fallocate 32 KiB, map the last seven blocks of that extent to dm-error, write the first block, restore the mapping and read the second block. It returns the old disk contents instead of zeroes. Clear the length of an extent that could not be zeroed out, so that ext4_zeroout_es() skips it, as the comment at the out label intends. Fixes: 308c57ccf431 ("ext4: if zeroout fails fall back to splitting the extent node") Cc: stable@vger.kernel.org Reviewed-by: Jan Kara Signed-off-by: Daejun Park Reviewed-by: Ojaswin Mujoo Link: https://patch.msgid.link/20261008-ext4-fc-zeroout-v2-1-55cab1e24fa3@samsung.com Signed-off-by: Theodore Ts'o --- fs/ext4/extents.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index 453c4492805ca2..c8fb68bbbf7426 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -3755,8 +3755,10 @@ ext4_ext_convert_to_initialized(handle_t *handle, struct inode *inode, ext4_ext_pblock(ex) + split_map.m_lblk + split_map.m_len - ee_block); err = ext4_ext_zeroout(inode, &zero_ex1); - if (err) + if (err) { + zero_ex1.ee_len = 0; goto fallback; + } split_map.m_len = *allocated; } if (split_map.m_lblk - ee_block + split_map.m_len < @@ -3769,8 +3771,10 @@ ext4_ext_convert_to_initialized(handle_t *handle, struct inode *inode, ext4_ext_store_pblock(&zero_ex2, ext4_ext_pblock(ex)); err = ext4_ext_zeroout(inode, &zero_ex2); - if (err) + if (err) { + zero_ex2.ee_len = 0; goto fallback; + } } split_map.m_len += split_map.m_lblk - ee_block; From cd169c27f0ab7fb274c2ebedf23b0e56d66e4fa0 Mon Sep 17 00:00:00 2001 From: Daejun Park Date: Thu, 8 Oct 2026 10:25:37 +0900 Subject: [PATCH 1519/2102] ext4: track zeroed out blocks of unwritten extents for fast commit When ext4_ext_convert_to_initialized() converts part of an unwritten extent, it may zero out the blocks before and after that range (a side only if it fits together with the range in s_extent_max_zeroout_kb, 32 KiB by default, and the extent ends within i_disksize or the write) and convert them to written together with it, instead of splitting them off. ext4_split_extent() zeroes out the rest of the extent and converts all of it when a split fails with -ENOSPC, -EDQUOT or -ENOMEM. In both cases ext4_map_blocks() reports only the mapped range to fast commit, so the other converted blocks are not tracked. A later write to one of those blocks overwrites a written block in place. That changes no mapping and is not tracked either, so the next fsync is a fast commit that logs the inode but no range for the block. After a crash, replay starts from the last full commit, where the block is still part of an unwritten extent, and the fsynced data reads back as zeroes. Fast commit tracks one [min, max] range per inode, so this shows only when no other block beyond the zeroed ones was tracked in the same commit, which makes it easy to miss. The first conversion runs when writes allocate through ext4_map_blocks() with EXT4_GET_BLOCKS_CREATE, for example with -o nodelalloc, -o dioread_lock or DAX. On a 4 KiB block file system made with -O fast_commit and mounted with -o nodelalloc,commit=60: fallocate -l 32k f; sync # blocks 0-7 unwritten write block 0; fsync f # zeroes out 1-7, tracks only 0 write block 2; fsync f # in place, nothing tracked crash (kill the VM), mount # fast commit replay block 2 reads back as zeroes Track the range in ext4_issue_zeroout(), where the zeroes are written, once the zeroout has succeeded. It takes the handle for that, and so does ext4_ext_zeroout(). The EXT4_GET_BLOCKS_CONVERT_UNWRITTEN zeroout in ext4_split_extent_zeroout() and the EXT4_GET_BLOCKS_ZERO one in ext4_map_create_blocks() zero out the mapped range, which ext4_map_blocks() tracks anyway. ext4_alloc_file_blocks() zeroes out without a handle and passes NULL: ext4_convert_unwritten_extents() right after it tracks the blocks it converts through ext4_map_blocks(), and blocks that were already written keep their mapping. The callers with a handle hold i_data_sem, as fast commit tracking already does when ext4_ext_dirty() changes an extent kept in the inode (through ext4_mark_inode_dirty()). Fixes: aa75f4d3daae ("ext4: main fast-commit commit path") Cc: stable@vger.kernel.org Suggested-by: Jan Kara Signed-off-by: Daejun Park Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261008-ext4-fc-zeroout-v2-2-55cab1e24fa3@samsung.com Signed-off-by: Theodore Ts'o --- fs/ext4/ext4.h | 5 +++-- fs/ext4/ext4_extents.h | 3 ++- fs/ext4/extents-test.c | 8 +++++--- fs/ext4/extents.c | 31 ++++++++++++++++++++----------- fs/ext4/inode.c | 25 +++++++++++++++++-------- 5 files changed, 47 insertions(+), 25 deletions(-) diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index 578238b7b41cdf..fd15ecd3805ecb 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -3253,8 +3253,9 @@ extern int ext4_get_projid(struct inode *inode, kprojid_t *projid); extern void ext4_da_release_space(struct inode *inode, int to_free); extern void ext4_da_update_reserve_space(struct inode *inode, int used, int quota_claim); -extern int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, - ext4_fsblk_t pblk, ext4_lblk_t len); +extern int ext4_issue_zeroout(handle_t *handle, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + ext4_lblk_t len); static inline bool is_special_ino(struct super_block *sb, unsigned long ino) { diff --git a/fs/ext4/ext4_extents.h b/fs/ext4/ext4_extents.h index ebaf7cc42430fa..f4218ff0842d5d 100644 --- a/fs/ext4/ext4_extents.h +++ b/fs/ext4/ext4_extents.h @@ -267,7 +267,8 @@ static inline void ext4_idx_store_pblock(struct ext4_extent_idx *ix, extern int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle, struct inode *inode, struct ext4_ext_path *path); -extern int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex); +extern int ext4_ext_zeroout(handle_t *handle, struct inode *inode, + struct ext4_extent *ex); #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) extern int ext4_ext_space_root_idx_test(struct inode *inode, int check); extern struct ext4_ext_path *ext4_split_convert_extents_test( diff --git a/fs/ext4/extents-test.c b/fs/ext4/extents-test.c index 0f897d9ff4feea..1abeb614b8bad5 100644 --- a/fs/ext4/extents-test.c +++ b/fs/ext4/extents-test.c @@ -176,7 +176,8 @@ ext4_ext_insert_extent_stub(handle_t *handle, struct inode *inode, /* * We will zeroout the equivalent range in the data area */ -static int ext4_ext_zeroout_stub(struct inode *inode, struct ext4_extent *ex) +static int ext4_ext_zeroout_stub(handle_t *handle, struct inode *inode, + struct ext4_extent *ex) { ext4_lblk_t ee_block, off_blk; loff_t ee_len; @@ -199,8 +200,9 @@ static int ext4_ext_zeroout_stub(struct inode *inode, struct ext4_extent *ex) return 0; } -static int ext4_issue_zeroout_stub(struct inode *inode, ext4_lblk_t lblk, - ext4_fsblk_t pblk, ext4_lblk_t len) +static int ext4_issue_zeroout_stub(handle_t *handle, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + ext4_lblk_t len) { ext4_lblk_t off_blk; loff_t off_bytes; diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index c8fb68bbbf7426..d8c1e2d12add5f 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -3167,17 +3167,18 @@ static void ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex) } /* FIXME!! we need to try to merge to left or right after zero-out */ -int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex) +int ext4_ext_zeroout(handle_t *handle, struct inode *inode, + struct ext4_extent *ex) { ext4_fsblk_t ee_pblock; unsigned int ee_len; - KUNIT_STATIC_STUB_REDIRECT(ext4_ext_zeroout, inode, ex); + KUNIT_STATIC_STUB_REDIRECT(ext4_ext_zeroout, handle, inode, ex); ee_len = ext4_ext_get_actual_len(ex); ee_pblock = ext4_ext_pblock(ex); - return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock, - ee_len); + return ext4_issue_zeroout(handle, inode, le32_to_cpu(ex->ee_block), + ee_pblock, ee_len); } /* @@ -3347,7 +3348,8 @@ static int ext4_split_extent_zeroout(handle_t *handle, struct inode *inode, lblk = ee_block; len = map->m_lblk - ee_block; pblk = ext4_ext_pblock(ex); - err = ext4_issue_zeroout(inode, lblk, pblk, len); + err = ext4_issue_zeroout(handle, inode, lblk, pblk, + len); if (err) /* ZEROOUT failed, just return original error */ return err; @@ -3358,7 +3360,8 @@ static int ext4_split_extent_zeroout(handle_t *handle, struct inode *inode, lblk = map_end; len = ex_end - map_end; pblk = ext4_ext_pblock(ex) + (map_end - ee_block); - err = ext4_issue_zeroout(inode, lblk, pblk, len); + err = ext4_issue_zeroout(handle, inode, lblk, pblk, + len); if (err) /* ZEROOUT failed, just return original error */ return err; @@ -3377,7 +3380,7 @@ static int ext4_split_extent_zeroout(handle_t *handle, struct inode *inode, lblk = map->m_lblk; len = map->m_len; pblk = ext4_ext_pblock(ex) + (map->m_lblk - ee_block); - err = ext4_issue_zeroout(inode, lblk, pblk, len); + err = ext4_issue_zeroout(handle, inode, lblk, pblk, len); if (err) /* ZEROOUT failed, just return original error */ return err; @@ -3754,7 +3757,7 @@ ext4_ext_convert_to_initialized(handle_t *handle, struct inode *inode, ext4_ext_store_pblock(&zero_ex1, ext4_ext_pblock(ex) + split_map.m_lblk + split_map.m_len - ee_block); - err = ext4_ext_zeroout(inode, &zero_ex1); + err = ext4_ext_zeroout(handle, inode, &zero_ex1); if (err) { zero_ex1.ee_len = 0; goto fallback; @@ -3770,7 +3773,7 @@ ext4_ext_convert_to_initialized(handle_t *handle, struct inode *inode, ee_block); ext4_ext_store_pblock(&zero_ex2, ext4_ext_pblock(ex)); - err = ext4_ext_zeroout(inode, &zero_ex2); + err = ext4_ext_zeroout(handle, inode, &zero_ex2); if (err) { zero_ex2.ee_len = 0; goto fallback; @@ -4698,8 +4701,14 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, WARN_ON_ONCE(map.m_lblk + map.m_len > EXT4_B_TO_LBLK(inode, new_size ?: old_size)); - ret = ext4_issue_zeroout(inode, map.m_lblk, map.m_pblk, - map.m_len); + /* + * Zeroed out without a handle, see the comment + * on EXT4_GET_BLOCKS_ZERO above. The conversion + * below tracks the blocks it converts for fast + * commit, and written blocks keep their mapping. + */ + ret = ext4_issue_zeroout(NULL, inode, map.m_lblk, + map.m_pblk, map.m_len); if (unlikely(ret)) break; diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 6cfd22874b1f7a..95c18d6431b650 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -476,23 +476,32 @@ static int __check_block_validity(struct inode *inode, const char *func, return 0; } -int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk, - ext4_lblk_t len) +/* + * The zeroes written here are file data. With a @handle the range is tracked + * for fast commit, because some callers zero out blocks outside the range that + * ext4_map_blocks() tracks and convert them to written. A caller without a + * handle must make sure that the conversion tracks the range. + */ +int ext4_issue_zeroout(handle_t *handle, struct inode *inode, ext4_lblk_t lblk, + ext4_fsblk_t pblk, ext4_lblk_t len) { int ret; - KUNIT_STATIC_STUB_REDIRECT(ext4_issue_zeroout, inode, lblk, pblk, len); + KUNIT_STATIC_STUB_REDIRECT(ext4_issue_zeroout, handle, inode, lblk, pblk, + len); if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode)) - return fscrypt_zeroout_range(inode, + ret = fscrypt_zeroout_range(inode, (loff_t)lblk << inode->i_blkbits, pblk << (inode->i_blkbits - SECTOR_SHIFT), (u64)len << inode->i_blkbits); - - ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS); + else + ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS); if (ret > 0) ret = 0; + if (!ret && handle) + ext4_fc_track_range(handle, inode, lblk, lblk + len - 1); return ret; } @@ -727,8 +736,8 @@ int ext4_map_create_blocks(handle_t *handle, struct inode *inode, */ if (flags & EXT4_GET_BLOCKS_ZERO && map->m_flags & EXT4_MAP_MAPPED && map->m_flags & EXT4_MAP_NEW) { - err = ext4_issue_zeroout(inode, map->m_lblk, map->m_pblk, - map->m_len); + err = ext4_issue_zeroout(handle, inode, map->m_lblk, + map->m_pblk, map->m_len); if (err) return err; } From 79c818505d4a7bee51fb9a5c935e2fc9889c01c5 Mon Sep 17 00:00:00 2001 From: guolingxing Date: Fri, 9 Oct 2026 06:28:46 +0000 Subject: [PATCH 1520/2102] ext4: fix buffer_head leak in ext4_ind_map_blocks() error path When ext4_ind_map_blocks() is called with EXT4_GET_BLOCKS_CREATE on a non-extent mapped inode of a filesystem with the bigalloc feature enabled, it fails with -EFSCORRUPTED via 'goto out'. However, at this point ext4_get_branch() has already acquired buffer_head references for the chain of indirect blocks, which are stored in the stack variable 'chain'. Since 'goto out' skips the cleanup loop that releases these references, they are leaked permanently (each failed allocation can leak up to 3 buffer_heads, and repeated allocation attempts keep pinning the corresponding pages in memory). Jump to 'cleanup' instead, so that the chain of buffer_heads is properly released before the error is returned. Signed-off-by: guolingxing Reviewed-by: Zhang Yi Link: https://patch.msgid.link/20261009062846.327298-1-guolingxing@tju.edu.cn Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/indirect.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/ext4/indirect.c b/fs/ext4/indirect.c index a495080df71092..15c978f37a5c66 100644 --- a/fs/ext4/indirect.c +++ b/fs/ext4/indirect.c @@ -620,7 +620,7 @@ int ext4_ind_map_blocks(handle_t *handle, struct inode *inode, EXT4_ERROR_INODE(inode, "Can't allocate blocks for " "non-extent mapped inodes with bigalloc"); err = -EFSCORRUPTED; - goto out; + goto cleanup; } /* Set up for the direct block allocation */ From a7fd013d368a4ae6480edcd12aa6827269011f9e Mon Sep 17 00:00:00 2001 From: Tal Zussman Date: Mon, 12 Oct 2026 13:17:40 -0400 Subject: [PATCH 1521/2102] ext4: reject atomic writes on inodes that can't do direct I/O ext4_dio_write_iter() falls back to buffered I/O when the inode can't do direct I/O at all, i.e. journaled data, inline data or verity. That fallback runs before any atomic write handling, and ext4_buffered_write_iter() doesn't look at IOCB_ATOMIC, so an atomic write to such an inode is silently done as a plain buffered write with no torn-write protection. ext4_inode_can_atomic_write() makes it worse for journaled data by advertising atomic writes for those inodes: statx() reports atomic write limits and the file gets FMODE_CAN_ATOMIC_WRITE, so the write passes the VFS checks and reaches the fallback. This is reachable with data=journal, or with chattr +j on a nodelalloc mount. Inline data inodes don't have the extents flag and verity files can't be opened for writing, so those are refused before ext4 sees the write, but the fallback would still accept them. Reject IOCB_ATOMIC in ext4_buffered_write_iter(), next to the existing IOCB_NOWAIT rejection, so neither fallback into it can complete an atomic write non-atomically. Also require ext4_dio_alignment() to be nonzero in ext4_inode_can_atomic_write(), so statx() stops advertising atomic writes for these inodes and VFS refuses RWF_ATOMIC early. The runtime check is still needed, as the journal data flag can be changed on an open file. Fixes: b7987a7d69a4 ("ext4: Support setting FMODE_CAN_ATOMIC_WRITE") Reported-by: Sashiko Link: https://sashiko.dev/#/patchset/20260909-ext4-atomic-no-fallback-v1-1-5a6b9539c002%40columbia.edu Signed-off-by: Tal Zussman Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261012-ext4-atomic-no-fallback-v2-1-c4b30c60e500@columbia.edu Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/ext4.h | 8 +++++++- fs/ext4/file.c | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index fd15ecd3805ecb..743dc02e429495 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -4137,12 +4137,18 @@ static inline int ext4_buffer_uptodate(struct buffer_head *bh) return buffer_uptodate(bh); } +/* + * Atomic writes are only supported through direct I/O, so an inode that + * can't do direct I/O at all (journaled data, inline data, verity) can't do + * atomic writes either. + */ static inline bool ext4_inode_can_atomic_write(struct inode *inode) { return S_ISREG(inode->i_mode) && ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) && - EXT4_SB(inode->i_sb)->s_awu_min > 0; + EXT4_SB(inode->i_sb)->s_awu_min > 0 && + ext4_dio_alignment(inode) != 0; } extern int ext4_block_write_begin(handle_t *handle, struct folio *folio, diff --git a/fs/ext4/file.c b/fs/ext4/file.c index 50d3c92709c8b8..cb56d01ddd6870 100644 --- a/fs/ext4/file.c +++ b/fs/ext4/file.c @@ -354,6 +354,14 @@ static ssize_t ext4_buffered_write_iter(struct kiocb *iocb, if (iocb->ki_flags & IOCB_NOWAIT) return -EOPNOTSUPP; + /* + * Buffered I/O provides no torn-write protection. The direct I/O path + * falls back here for inodes that can't do direct I/O at all, so an + * atomic write must be rejected rather than silently done non-atomically. + */ + if (iocb->ki_flags & IOCB_ATOMIC) + return -EOPNOTSUPP; + inode_lock(inode); /* From 18133865a11b834338372d0156d01856bd3ad5db Mon Sep 17 00:00:00 2001 From: Tal Zussman Date: Mon, 12 Oct 2026 13:17:41 -0400 Subject: [PATCH 1522/2102] ext4: never fall back to buffered I/O for atomic direct writes ext4_dio_write_iter() finishes a short direct write through the page cache. ext4_buffered_write_iter() now rejects IOCB_ATOMIC, so a short atomic write would warn and then fail with -EOPNOTSUPP, as if atomic writes were unsupported on the inode. This came out of a block device fix [1], where an IOCB_ATOMIC direct write could complete short when only part of the buffer could be pinned, with the rest going through the buffered fallback. Christoph Hellwig noted that ext4 has the same fallback and only warns in it [2], and John Garry agreed it should reject the write instead [3]. In contrast to the block device, nothing reaches the branch on ext4 today: iomap requires the mapping to cover the whole atomic write, a buffer that can't be pinned in full fails in iomap before the bio is submitted, and a failed page cache invalidation returns -EAGAIN rather than reaching the buffered fallback. A short atomic write is therefore a bug, and neither a short count nor -EOPNOTSUPP is a valid result for one. Fail the write with -EIO before the fallback, keeping the WARN() so any future bug is visible. Link: https://lore.kernel.org/linux-block/20260828-blkdev-fixes-v2-0-32f3f40cebed@columbia.edu/ [1] Link: https://lore.kernel.org/linux-block/20260907071217.GD934@lst.de/ [2] Link: https://lore.kernel.org/linux-block/a7752d1e-8ec1-44d1-a266-c287c315e8ab@oracle.com/ [3] Signed-off-by: Tal Zussman Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261012-ext4-atomic-no-fallback-v2-2-c4b30c60e500@columbia.edu Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/file.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/fs/ext4/file.c b/fs/ext4/file.c index cb56d01ddd6870..124000e8dd8258 100644 --- a/fs/ext4/file.c +++ b/fs/ext4/file.c @@ -697,11 +697,12 @@ static ssize_t ext4_dio_write_iter(struct kiocb *iocb, struct iov_iter *from) loff_t endbyte; /* - * There is no support for atomic writes on buffered-io yet, - * we should never fallback to buffered-io for DIO atomic - * writes. + * Buffered I/O provides no torn-write protection, so never + * finish an atomic write through the page cache. iomap must + * not return a short atomic write, so treat one as a bug. */ - WARN_ON_ONCE(iocb->ki_flags & IOCB_ATOMIC); + if (WARN_ON_ONCE(iocb->ki_flags & IOCB_ATOMIC)) + return -EIO; offset = iocb->ki_pos; err = ext4_buffered_write_iter(iocb, from); From d4e9b9bb1e3848b139174c4fb268c3f19e707982 Mon Sep 17 00:00:00 2001 From: Tal Zussman Date: Mon, 12 Oct 2026 13:17:42 -0400 Subject: [PATCH 1523/2102] ext4: don't advertise atomic writes for DAX inodes ext4_file_write_iter() hands DAX inodes to ext4_dax_write_iter() before any of the atomic write handling, and the DAX path neither checks IOCB_ATOMIC nor provides torn-write protection. ext4_inode_can_atomic_write() doesn't exclude DAX inodes, so on a device that supported both DAX and atomic writes, statx() would advertise atomic writes for such an inode and the VFS would let an RWF_ATOMIC write through to a plain DAX write. No DAX-capable block device advertises atomic write limits today, so this isn't reachable. When XFS gained its corresponding check, Ritesh Harjani suggested excluding DAX inodes in ext4 anyway [1], so that what is advertised matches what the write path can do. XFS does the same in xfs_inode_can_hw_atomic_write() and xfs_inode_can_sw_atomic_write(). Link: https://lore.kernel.org/linux-ext4/87a54e4cdn.fsf@gmail.com/ [1] Signed-off-by: Tal Zussman Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261012-ext4-atomic-no-fallback-v2-3-c4b30c60e500@columbia.edu Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/ext4.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index 743dc02e429495..5bff68363cf6d8 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -4140,12 +4140,13 @@ static inline int ext4_buffer_uptodate(struct buffer_head *bh) /* * Atomic writes are only supported through direct I/O, so an inode that * can't do direct I/O at all (journaled data, inline data, verity) can't do - * atomic writes either. + * atomic writes either. DAX inodes bypass the direct I/O path entirely. */ static inline bool ext4_inode_can_atomic_write(struct inode *inode) { return S_ISREG(inode->i_mode) && + !IS_DAX(inode) && ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) && EXT4_SB(inode->i_sb)->s_awu_min > 0 && ext4_dio_alignment(inode) != 0; From 7d7c9c83c8227c113aa4f1bae9a8d43b8ea6c839 Mon Sep 17 00:00:00 2001 From: Tal Zussman Date: Mon, 12 Oct 2026 14:04:37 -0400 Subject: [PATCH 1524/2102] ext4: complete dropbehind writeback in task context ext4_end_bio() ends writeback directly from bio completion, which usually runs in interrupt context, unless the io_end has unwritten extents to convert and is completed from ext4's workqueue. folio_end_dropbehind() only invalidates the folios of an RWF_DONTCACHE write when it runs in task context, and silently skips them otherwise. So on ext4, dontcache writes that overwrite blocks that are already written, or that allocate blocks without unwritten extents, leave their folios in the page cache. Dropping them was best effort so far, as there was no way to get task context from bio completion. Use the task-context bio completion infrastructure instead: set BIO_COMPLETE_IN_TASK on bios that carry dropbehind folios in io_submit_add_bh(), so that bio_endio() runs their completion from a worker. ext4's iomap buffered I/O path already gets this from iomap, so only the buffer_head based writeback is affected. Skip the flag when the io_end already has unwritten extents, as ext4 then defers the completion itself. A later extent can still make the io_end unwritten after an earlier bio was built. That bio's completion is then deferred twice, which is not optimal, but harmless. This changes behavior only for bios that carry dropbehind folios: their completion now runs from a worker instead of in interrupt context. On the unpatched kernel a dontcache overwrite of already-written blocks, or a dontcache write into a new file on a dioread_lock mount, leaves every folio in the page cache (16384/16384 for a 64M file). With the patch, none remain in the page cache. A dontcache write into a new file with unwritten extents already drops its folios on both kernels, as expected, and a plain write keeps them. Signed-off-by: Tal Zussman Reviewed-by: Jan Kara Fixes: ae21c0c0ac56 ("ext4: support uncached buffered I/O") Reviewed-by: Baokun Li Reviewed-by: Zhang Yi Link: https://patch.msgid.link/20261012-ext4-dontcache-complete-in-task-v1-1-6ac801557041@columbia.edu Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/page-io.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/fs/ext4/page-io.c b/fs/ext4/page-io.c index 734d856a6d4784..e556598ce9e14c 100644 --- a/fs/ext4/page-io.c +++ b/fs/ext4/page-io.c @@ -458,6 +458,16 @@ static void io_submit_add_bh(struct ext4_io_submit *io, io_submit_init_bio(io, inode, folio, bh); if (!bio_add_folio(io->io_bio, folio, bh->b_size, bh_offset(bh))) goto submit_and_retry; + + /* + * Dropbehind folios can only be invalidated in task context. An + * io_end with unwritten extents is completed from ext4's workqueue + * anyway, so only ask the block layer to defer the others. + */ + if (folio_test_dropbehind(folio) && + !(io->io_end->flag & EXT4_IO_END_UNWRITTEN)) + bio_set_flag(io->io_bio, BIO_COMPLETE_IN_TASK); + wbc_account_cgroup_owner(io->io_wbc, folio, bh->b_size); io->io_next_block++; } From 40b2a37f9a7e2264e7f62949ea5b27020a0eacb3 Mon Sep 17 00:00:00 2001 From: guolingxing Date: Tue, 13 Oct 2026 01:40:26 +0000 Subject: [PATCH 1525/2102] jbd2: check return value of blkdev_issue_flush() when checkpointing jbd2_cleanup_journal_tail() calls blkdev_issue_flush() on the file system device to make sure all checkpointed data are on permanent storage before it updates the log tail in the superblock. However the return value of blkdev_issue_flush() is ignored so if the flush fails, we still advance the log tail. After a crash the journal recovery will consider the checkpointed transactions as committed and skip the replay while their data may have never reached the disk, which may lead to a filesystem corruption. Abort the journal when the flush fails, similar to how we abort when detecting writeback errors of the file system device. Fixes: 79feb521a447 ("jbd2: issue cache flush after checkpointing even with internal journal") Cc: stable@vger.kernel.org Reviewed-by: Jan Kara Signed-off-by: guolingxing Link: https://patch.msgid.link/20261013014028.1152277-2-guolingxing@tju.edu.cn Signed-off-by: Theodore Ts'o --- fs/jbd2/checkpoint.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/fs/jbd2/checkpoint.c b/fs/jbd2/checkpoint.c index 5132737120108c..9bbce4c8cadb68 100644 --- a/fs/jbd2/checkpoint.c +++ b/fs/jbd2/checkpoint.c @@ -346,8 +346,14 @@ int jbd2_cleanup_journal_tail(journal_t *journal) * need this to guarantee correctness. Fortunately * jbd2_cleanup_journal_tail() doesn't get called all that often. */ - if (journal->j_flags & JBD2_BARRIER) - blkdev_issue_flush(journal->j_fs_dev); + if (journal->j_flags & JBD2_BARRIER) { + int err = blkdev_issue_flush(journal->j_fs_dev); + + if (err) { + jbd2_journal_abort(journal, err); + return err; + } + } return __jbd2_update_log_tail(journal, first_tid, blocknr); } From b8e62a68c59fc6171c51e919beff5dff6e473f4e Mon Sep 17 00:00:00 2001 From: guolingxing Date: Tue, 13 Oct 2026 01:40:27 +0000 Subject: [PATCH 1526/2102] jbd2: check return value of blkdev_issue_flush() when committing For journals on a separate device, jbd2_commit_transaction() must flush the file system device before submitting the commit record, otherwise the transaction may get committed while the ordered data are still in the device cache. However the return value of blkdev_issue_flush() is ignored so if the flush fails, the commit record is still submitted and fsync() reports success although the ordered data may have never reached the disk. After a crash the journal recovery will consider such transactions committed and data written by fsync() may be lost. Abort the journal when the flush fails. The commit record is then not submitted anymore since journal_submit_commit_record() checks for an aborted journal. Fixes: cc3e1bea5d87 ("ext4, jbd2: Add barriers for file systems with exernal journals") Cc: stable@vger.kernel.org Signed-off-by: guolingxing Link: https://patch.msgid.link/20261013014028.1152277-3-guolingxing@tju.edu.cn Signed-off-by: Theodore Ts'o --- fs/jbd2/commit.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/fs/jbd2/commit.c b/fs/jbd2/commit.c index ebf6ba58ff4d0c..2a0ccc484331e8 100644 --- a/fs/jbd2/commit.c +++ b/fs/jbd2/commit.c @@ -800,8 +800,12 @@ void jbd2_journal_commit_transaction(journal_t *journal) */ if ((commit_transaction->t_need_data_flush || update_tail) && (journal->j_fs_dev != journal->j_dev) && - (journal->j_flags & JBD2_BARRIER)) - blkdev_issue_flush(journal->j_fs_dev); + (journal->j_flags & JBD2_BARRIER)) { + err = blkdev_issue_flush(journal->j_fs_dev); + + if (err) + jbd2_journal_abort(journal, err); + } /* Done it all: now write the commit record asynchronously. */ if (jbd2_has_feature_async_commit(journal)) { From 9e3cb03d39332370474222437660efb2ede3be6b Mon Sep 17 00:00:00 2001 From: guolingxing Date: Tue, 13 Oct 2026 01:40:28 +0000 Subject: [PATCH 1527/2102] jbd2: check return value of blkdev_issue_flush() for async commits When asynchronous commits are enabled, jbd2_commit_transaction() calls blkdev_issue_flush() on the journal device to make the commit record permanent. However the return value is ignored so if the flush fails, the transaction is considered committed although the commit record may have never reached the disk. Abort the journal when the flush fails, as we already do when waiting for the commit record fails. Fixes: f73bee49855f ("jbd2: Modify ASYNC_COMMIT code to not rely on queue draining on barrier") Cc: stable@vger.kernel.org Signed-off-by: guolingxing Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261013014028.1152277-4-guolingxing@tju.edu.cn Signed-off-by: Theodore Ts'o --- fs/jbd2/commit.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/fs/jbd2/commit.c b/fs/jbd2/commit.c index 2a0ccc484331e8..00a5a6b369ed52 100644 --- a/fs/jbd2/commit.c +++ b/fs/jbd2/commit.c @@ -912,7 +912,10 @@ void jbd2_journal_commit_transaction(journal_t *journal) stats.run.rs_blocks_logged++; if (jbd2_has_feature_async_commit(journal) && journal->j_flags & JBD2_BARRIER) { - blkdev_issue_flush(journal->j_dev); + int flush_err = blkdev_issue_flush(journal->j_dev); + + if (!err) + err = flush_err; } if (err) From 8a72b083d8bcdb37bff6d42da679df528b16b452 Mon Sep 17 00:00:00 2001 From: guolingxing Date: Tue, 13 Oct 2026 08:23:30 +0000 Subject: [PATCH 1528/2102] ext4: check return value of blkdev_issue_flush() when initializing inode tables When lazily zeroing an inode table, ext4_init_inode_table() issues a cache flush to make sure the zeroed blocks have reached the disk before setting the EXT4_BG_INODE_ZEROED flag, but the return value is ignored. If the cache flush fails, the inode table is still marked as initialized, and a subsequent crash can leave the table containing stale data from the previous use of the disk, which may then be exposed to user space through newly allocated inodes. Check the return value of blkdev_issue_flush() and leave EXT4_BG_INODE_ZEROED unset if the cache flush fails, so that the inode table zeroing is retried on the next mount. Since a cache flush failure now aborts the lazy inode table initialization, also pass the barrier mount option down to ext4_init_inode_table(), consistent with the other cache flushes in ext4 and jbd2 which are issued only when the barrier option is enabled. This keeps file systems mounted with nobarrier working on devices with failing cache flushes. Fixes: a107e5a3a473a ("Merge branch 'next' into upstream-merge") Cc: stable@vger.kernel.org Signed-off-by: guolingxing Link: https://patch.msgid.link/20261013082331.2089623-2-guolingxing@tju.edu.cn Signed-off-by: Theodore Ts'o --- fs/ext4/ialloc.c | 7 +++++-- fs/ext4/super.c | 3 ++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c index 527f1f703c3e08..17868dcb4dcca1 100644 --- a/fs/ext4/ialloc.c +++ b/fs/ext4/ialloc.c @@ -1611,8 +1611,11 @@ int ext4_init_inode_table(struct super_block *sb, ext4_group_t group, ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS); if (ret < 0) goto err_out; - if (barrier) - blkdev_issue_flush(sb->s_bdev); + if (barrier) { + ret = blkdev_issue_flush(sb->s_bdev); + if (ret) + goto err_out; + } skip_zeroout: ext4_lock_group(sb, group); diff --git a/fs/ext4/super.c b/fs/ext4/super.c index f0c46d50d15a19..3de309a2bdaf71 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -3835,7 +3835,8 @@ static int ext4_run_li_request(struct ext4_li_request *elr) if (!ret) { start_time = ktime_get_ns(); ret = ext4_init_inode_table(sb, group, - elr->lr_timeout ? 0 : 1); + !elr->lr_timeout && + test_opt(sb, BARRIER)); trace_ext4_lazy_itable_init(sb, group); if (elr->lr_timeout == 0) { elr->lr_timeout = nsecs_to_jiffies((ktime_get_ns() - start_time) * From 6025f9d156cfb6cd67186dbb14ce1e277f73cc66 Mon Sep 17 00:00:00 2001 From: guolingxing Date: Tue, 13 Oct 2026 08:23:31 +0000 Subject: [PATCH 1529/2102] ext4: check return value of blkdev_issue_flush() when starting a fast commit When the file system device differs from the journal device, a cache flush is issued on the file system device before fast commit blocks are written, but the return value is ignored. If the cache flush fails, the fast commit blocks are written and the fast commit completes anyway, even though the updates covered by the preceding transactions may not be on stable storage yet, so the fast commit may provide guarantees it cannot keep. Check the return value of blkdev_issue_flush() and abort the fast commit if the cache flush fails. ext4_fc_commit() will then fall back to a full journal commit, so the caller still gets the expected durability guarantees. Since a cache flush failure now aborts the fast commit, also issue the flush only when the journal barrier option is enabled, consistent with the file system device flush issued during a full journal commit and with the fast commit tail block flush. This keeps file systems mounted with nobarrier working on devices with failing cache flushes. Fixes: da0c5d2695265 ("ext4: issue fsdev cache flush before starting fast commit") Cc: stable@vger.kernel.org Signed-off-by: guolingxing Link: https://patch.msgid.link/20261013082331.2089623-3-guolingxing@tju.edu.cn Signed-off-by: Theodore Ts'o --- fs/ext4/fast_commit.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/fs/ext4/fast_commit.c b/fs/ext4/fast_commit.c index c634f7ae743839..5688b487acb41c 100644 --- a/fs/ext4/fast_commit.c +++ b/fs/ext4/fast_commit.c @@ -1425,8 +1425,12 @@ static int ext4_fc_perform_commit(journal_t *journal, tid_t commit_tid) * Step 5: If file system device is different from journal device, * issue a cache flush before we start writing fast commit blocks. */ - if (journal->j_fs_dev != journal->j_dev) - blkdev_issue_flush(journal->j_fs_dev); + if (journal->j_fs_dev != journal->j_dev && + journal->j_flags & JBD2_BARRIER) { + ret = blkdev_issue_flush(journal->j_fs_dev); + if (ret) + return ret; + } blk_start_plug(&plug); alloc_ctx = ext4_fc_lock(sb); From 06954d44c6d0e8f3c1b0d7961ae217795b734c37 Mon Sep 17 00:00:00 2001 From: Daejun Park Date: Tue, 13 Oct 2026 16:28:52 +0900 Subject: [PATCH 1530/2102] ext4: spread files of sibling directories over a flex group On a flex_bg file system, find_group_other() puts a new file in the first group of the parent's flex group that has a free inode. Orlov usually keeps a directory below the top level in its parent's flex group and packs directory inodes at its start, so the files of sibling directories come from the same group and get consecutive inode numbers. The flex_bg path was added by commit a4912123b688 ("ext4: New inode/block allocation algorithms for flex_bg filesystems"). The non-flex_bg path instead adds the parent's inode number to the starting group once the parent's own group has no free inode or block, so that the files of different directories which share a group land in different groups. When several tasks create files in sibling directories at the same time, their new inodes share inode table blocks. __ext4_get_inode_loc() skips reading an inode table block only when no other inode in that block is in use in the inode bitmap. The bit of another task's new inode defeats that check, so the block is read from disk under the buffer lock while the other creators wait for the lock. When the other inodes in use in the block are new as well, as on a freshly made file system, the read is wasted, because ext4_do_update_inode() clears the on-disk copy of a new inode before filling it in. With 16 tasks each creating 60000 empty files in its own directory under a common parent on NVMe, the creators read inode table blocks from disk 50000 times, nine in ten of their context switches were in lock_buffer() in __ext4_get_inode_loc(), and the throughput was 290k files/s. Pick the group inside the flex group by the parent's inode number first. When that group is full, keep using the group last picked for the directory, and after that prefer a group with no inode in use, which no other directory uses yet. Do the same inside the flex group last used and inside the one Orlov picks when those are full. The inode tables of a flex group are normally contiguous, so the inodes stay in the same region of the disk (32MiB for 16 groups with the mke2fs defaults), and the files of a directory mostly share inode table blocks with each other rather than with other directories. The data block goal from ext4_inode_to_goal_block() does not move for flex_bg sizes of 4 and more: it starts regular files at the second group of the flex group regardless of the inode's group. An external xattr block starts at the inode's own group, and the mballoc stream goal slot is picked by inode number. In the test above, the creators read inode table blocks 260 to 530 times and the throughput is 780k files/s. When find_group_other() fails in the last flex group and the number of groups is a multiple of the flex size, it leaves *group, and so i_last_alloc_group, equal to the number of groups: parent_group + flex_size was reset to 0 only when it was larger, and find_group_orlov() does not read the value. Nothing used that value as a group before. The retry now passes it to find_group_in_flex() as the first group of a flex group, so reset it when it is equal too, and retry only with a group below the number of groups. Update the description in Documentation/filesystems/ext4/allocators.rst. Signed-off-by: Daejun Park Link: https://patch.msgid.link/20261013-ialloc-flex-spread-v1-1-9ea1d86961aa@samsung.com Signed-off-by: Theodore Ts'o --- Documentation/filesystems/ext4/allocators.rst | 6 +- fs/ext4/ialloc.c | 91 +++++++++++++++---- 2 files changed, 80 insertions(+), 17 deletions(-) diff --git a/Documentation/filesystems/ext4/allocators.rst b/Documentation/filesystems/ext4/allocators.rst index 7aa85152ace3d0..70a3930ca5480d 100644 --- a/Documentation/filesystems/ext4/allocators.rst +++ b/Documentation/filesystems/ext4/allocators.rst @@ -38,7 +38,11 @@ file's data blocks to begin I/O operations. The fourth trick is that all the inodes in a directory are placed in the same block group as the directory, when feasible. The working assumption here is that all the files in a directory might be related, therefore it -is useful to try to keep them all together. +is useful to try to keep them all together. With flex_bg, the files of a +directory are kept in the directory's flex group instead, in a block +group chosen by the directory's inode number, so that the files of +different directories in the same flex group are less likely to share +inode table blocks. The fifth trick is that the disk volume is cut up into 128MB block groups; these mini-containers are used as outlined above to try to diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c index 17868dcb4dcca1..92e2243b98cf87 100644 --- a/fs/ext4/ialloc.c +++ b/fs/ext4/ialloc.c @@ -569,11 +569,70 @@ static int find_group_orlov(struct super_block *sb, struct inode *parent, return -1; } +static bool ext4_group_has_free_inode(struct super_block *sb, ext4_group_t g) +{ + struct ext4_group_desc *desc = ext4_get_group_desc(sb, g, NULL); + + return desc && ext4_free_inodes_count(sb, desc); +} + +/* + * Pick a group with a free inode in the flex group that starts at @first. + * First try the group chosen by the parent's inode number, so that the + * files of different directories in a flex group are less likely to share + * an inode bitmap and inode table blocks. Once that group is full, keep + * using @last, the group last picked for this directory, if it is in this + * flex group, then prefer a group with no inode in use, which no other + * directory uses yet, then take any group with a free inode. Return -1 if + * no group in the flex group has a free inode. + */ +static int find_group_in_flex(struct super_block *sb, struct inode *parent, + ext4_group_t first, ext4_group_t last, + int flex_size, ext4_group_t *group) +{ + ext4_group_t ngroups = ext4_get_groups_count(sb); + ext4_group_t n = min_t(ext4_group_t, flex_size, ngroups - first); + ext4_group_t start = (unsigned int)parent->i_ino % n; + ext4_group_t i, g, avail = ngroups; + + if (ext4_group_has_free_inode(sb, first + start)) { + *group = first + start; + return 0; + } + if (last >= first && last < first + n && + ext4_group_has_free_inode(sb, last)) { + *group = last; + return 0; + } + for (i = 1; i < n; i++) { + struct ext4_group_desc *desc; + unsigned int nr_free; + + if (++start == n) + start = 0; + g = first + start; + desc = ext4_get_group_desc(sb, g, NULL); + if (!desc) + continue; + nr_free = ext4_free_inodes_count(sb, desc); + if (nr_free == EXT4_INODES_PER_GROUP(sb)) { + *group = g; + return 0; + } + if (nr_free && avail == ngroups) + avail = g; + } + if (avail == ngroups) + return -1; + *group = avail; + return 0; +} + static int find_group_other(struct super_block *sb, struct inode *parent, ext4_group_t *group, umode_t mode) { ext4_group_t parent_group = EXT4_I(parent)->i_block_group; - ext4_group_t i, last, ngroups = ext4_get_groups_count(sb); + ext4_group_t i, ngroups = ext4_get_groups_count(sb); struct ext4_group_desc *desc; int flex_size = ext4_flex_bg_size(EXT4_SB(sb)); @@ -585,34 +644,34 @@ static int find_group_other(struct super_block *sb, struct inode *parent, * group for future allocations. */ if (flex_size > 1) { + ext4_group_t last_alloc = EXT4_I(parent)->i_last_alloc_group; int retry = 0; try_again: parent_group &= ~(flex_size-1); - last = parent_group + flex_size; - if (last > ngroups) - last = ngroups; - for (i = parent_group; i < last; i++) { - desc = ext4_get_group_desc(sb, i, NULL); - if (desc && ext4_free_inodes_count(sb, desc)) { - *group = i; - return 0; - } - } - if (!retry && EXT4_I(parent)->i_last_alloc_group != ~0) { + if (!find_group_in_flex(sb, parent, parent_group, last_alloc, + flex_size, group)) + return 0; + if (!retry && last_alloc < ngroups) { retry = 1; - parent_group = EXT4_I(parent)->i_last_alloc_group; + parent_group = last_alloc; goto try_again; } /* * If this didn't work, use the Orlov search algorithm * to find a new flex group; we pass in the mode to - * avoid the topdir algorithms. + * avoid the topdir algorithms. Then pick the group inside + * the flex group Orlov chose the same way as above. */ *group = parent_group + flex_size; - if (*group > ngroups) + if (*group >= ngroups) *group = 0; - return find_group_orlov(sb, parent, group, mode, NULL); + if (find_group_orlov(sb, parent, group, mode, NULL)) + return -1; + /* Keep Orlov's group if its flex group has no free inode now */ + find_group_in_flex(sb, parent, *group & ~(flex_size - 1), + last_alloc, flex_size, group); + return 0; } /* From ed2c4b549a7191938f14fc0b5cef8d0c821dd75c Mon Sep 17 00:00:00 2001 From: Stephen Kitt Date: Wed, 14 Oct 2026 18:29:20 +0200 Subject: [PATCH 1531/2102] docs: ext4 filesystems can be converted to 64-bit Since commit fe12931 ("resize2fs: convert fs to and from 64bit mode") in e2fsprogs, which shipped in version 1.43, resize2fs can convert filesystems from 32-bit to 64-bit and back, so the mention in the checksum documentation that this is impossible is obsolete. This fixes that. Signed-off-by: Stephen Kitt Reviewed-by: Daniel Pereira Link: https://patch.msgid.link/20261014162921.450235-1-steve@sk2.org Signed-off-by: Theodore Ts'o --- Documentation/filesystems/ext4/checksums.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Documentation/filesystems/ext4/checksums.rst b/Documentation/filesystems/ext4/checksums.rst index e232749daf5f30..51a2150a1bf8dd 100644 --- a/Documentation/filesystems/ext4/checksums.rst +++ b/Documentation/filesystems/ext4/checksums.rst @@ -10,9 +10,9 @@ of October 2012 the only supported algorithm is crc32c. Some data structures did not have space to fit a full 32-bit checksum, so only the lower 16 bits are stored. Enabling the 64bit feature increases the data structure size so that full 32-bit checksums can be stored for many data -structures. However, existing 32-bit filesystems cannot be extended to -enable 64bit mode, at least not without the experimental resize2fs -patches to do so. +structures. ``resize2fs`` in ``e2fsprogs`` 1.43 or later can be used to +convert filesystems from 32-bit to 64-bit and back (using the ``-b`` +and ``-s`` options). Existing filesystems can have checksumming added by running ``tune2fs -O metadata_csum`` against the underlying device. If tune2fs From 2cfcd9fa8734c1c526de8a17bda00db0a454e276 Mon Sep 17 00:00:00 2001 From: Karl Mehltretter Date: Fri, 16 Oct 2026 12:37:26 +0200 Subject: [PATCH 1532/2102] ext4: return an error when a journal block is not mapped If the internal journal inode contains a hole, ext4_map_blocks() returns 0. ext4_journal_bmap() logs "journal bmap failed" and aborts the journal, but also returns 0 and leaves *block unchanged. jbd2_journal_bmap() takes that as success and uses the unchanged logical journal block number as a physical filesystem block number. Journal I/O can then overwrite filesystem blocks outside the journal despite the abort. Return -EFSCORRUPTED for a hole, matching the error passed to jbd2_journal_abort(). Keep propagating negative mapping errors. Fixes: 62913ae96de7 ("ext4, jbd2: add an optimized bmap for the journal inode") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Karl Mehltretter Reviewed-by: Jan Kara Reviewed-by: Zhang Yi Link: https://patch.msgid.link/20261016103726.98553-1-kmehltretter@gmail.com Signed-off-by: Theodore Ts'o --- fs/ext4/super.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/fs/ext4/super.c b/fs/ext4/super.c index 3de309a2bdaf71..81c7e8812d3d16 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -6017,7 +6017,9 @@ static int ext4_journal_bmap(journal_t *journal, sector_t *block) ext4_msg(journal->j_inode->i_sb, KERN_CRIT, "journal bmap failed: block %llu ret %d\n", *block, ret); - jbd2_journal_abort(journal, ret ? ret : -EFSCORRUPTED); + if (!ret) + ret = -EFSCORRUPTED; + jbd2_journal_abort(journal, ret); return ret; } *block = map.m_pblk; From 8eb922c5c4672aa872d1459d74ce5d6fa8846031 Mon Sep 17 00:00:00 2001 From: guolingxing Date: Fri, 16 Oct 2026 11:03:11 +0000 Subject: [PATCH 1533/2102] ext4: record writeback error when discarding pages on failed delalloc When mpage_map_and_submit_extent() gives up on a failed block mapping, it sets give_up_on_write so that mpage_release_unused_pages() discards the remaining dirty folios. However, the error is not recorded in the mapping's writeback error state. If this happens during background writeback, a later fsync() may report success even though the dirty data was discarded and never written. Returning the error from ext4_writepages() is not sufficient to notify a later fsync(). In addition, ext4_do_writepages() may clear -ENOSPC when committing the journal and retrying, even after the affected dirty folios have been discarded. Call mapping_set_error() when deciding to give up on the write, before the dirty folios are invalidated, so that fsync() can report the writeback failure through the mapping's error state. The give_up_on_write flag also persists across writeback loop iterations. After a fatal -ENOSPC failure sets it, ext4_do_writepages() may commit the journal and retry without clearing the flag. If a subsequent iteration encounters a transient error and leaves dirty folios pending, mpage_release_unused_pages() invalidates them instead of preserving them for retry. Initialize give_up_on_write inside the loop so that only a fatal failure in the current iteration causes the remaining dirty folios to be discarded. Fixes: c4a0c46ec92c ("ext4: invalidate pages if delalloc block allocation fails.") Fixes: cb530541182b ("ext4: fix up error handling for mpage_map_and_submit_extent()") Cc: stable@vger.kernel.org Signed-off-by: guolingxing Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261016110311.71391-1-guolingxing@tju.edu.cn Signed-off-by: Theodore Ts'o --- fs/ext4/inode.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 95c18d6431b650..6408e159224dd7 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -2648,6 +2648,12 @@ static int mpage_map_and_submit_extent(handle_t *handle, ext4_print_free_blocks(inode); invalidate_dirty_pages: *give_up_on_write = true; + /* + * Record the error so that a subsequent fsync() + * / errseq check can observe the data loss that + * discarding these dirty pages implies. + */ + mapping_set_error(inode->i_mapping, err); return err; } progress = 1; @@ -2917,7 +2923,6 @@ static int ext4_do_writepages(struct mpage_da_data *mpd) int needed_blocks, rsv_blocks = 0, ret = 0; struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb); struct blk_plug plug; - bool give_up_on_write = false; trace_ext4_writepages(inode, wbc); @@ -3042,6 +3047,8 @@ static int ext4_do_writepages(struct mpage_da_data *mpd) goto unplug; while (!mpd->scanned_until_end && wbc->nr_to_write > 0) { + bool give_up_on_write = false; + /* For each extent of pages we use new io_end */ mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL); if (!mpd->io_submit.io_end) { From 0a10fca0f1545af1f9b55323b8d6958c12c7a7a6 Mon Sep 17 00:00:00 2001 From: guolingxing Date: Fri, 16 Oct 2026 14:25:24 +0000 Subject: [PATCH 1534/2102] ext4: fix folio reference leak in mpage_submit_partial_folio() mpage_submit_partial_folio() obtains a folio reference with filemap_get_folio(). If the subsequent position check fails, it returns -EINVAL without dropping that reference. Call folio_put() before returning from this error path. Leave the folio locked so that the caller can invalidate and unlock it through mpage_release_unused_pages(). Fixes: ded2d726a304 ("ext4: fix stale data if it bail out of the extents mapping loop") Cc: stable@vger.kernel.org Signed-off-by: guolingxing Reviewed-by: Zhang Yi Link: https://patch.msgid.link/20261016142524.655789-1-guolingxing@tju.edu.cn Signed-off-by: Theodore Ts'o --- fs/ext4/inode.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 6408e159224dd7..8bfb5c821163a7 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -2555,8 +2555,14 @@ static int mpage_submit_partial_folio(struct mpage_da_data *mpd) */ pos = ((loff_t)mpd->map.m_lblk) << inode->i_blkbits; if (WARN_ON_ONCE((folio_pos(folio) == pos) || - !folio_contains(folio, pos >> PAGE_SHIFT))) + !folio_contains(folio, pos >> PAGE_SHIFT))) { + /* + * Leave the folio locked so that the caller can invalidate + * and unlock it through mpage_release_unused_pages(). + */ + folio_put(folio); return -EINVAL; + } mpage_submit_folio(mpd, folio); /* From 46b2ccfab37b4040fa27da9d0b0cf068e5875db5 Mon Sep 17 00:00:00 2001 From: Kaixuan Li Date: Mon, 19 Oct 2026 21:16:55 +0800 Subject: [PATCH 1535/2102] ext4: don't read past the UAPI struct in GROUP_ADD EXT4_IOC_GROUP_ADD casts the user pointer to struct ext4_new_group_input, its UAPI type, but sizes the copy by struct ext4_new_group_data, the internal type: struct ext4_new_group_data input; if (copy_from_user(&input, (struct ext4_new_group_input __user *)arg, sizeof(input))) The UAPI struct is 40 bytes, the internal one 48. A caller that follows the UAPI and allocates 40 bytes gets 8 bytes read past its object, and the ioctl returns EFAULT when those bytes are unmapped. The two structs have differed in size for as long as I can see back -- v6.12.9, v7.2.4 and current master all have 40 against 48 -- so the copy has been over-reading the UAPI object throughout. The first 40 bytes of the two structs have the same layout, with the UAPI 'unused' in the slot of mdata_blocks, so copying that much fills every field the UAPI defines. free_clusters_count, the one field past it, is overwritten by verify_group_input(), and mdata_blocks is read only on the ext4_resize_fs() path, which builds its own group_data array. Copy the UAPI size into a zero-initialised struct. Reproducible on v6.12.9 and v7.2.4 by placing a 40-byte struct at the end of a mapped page whose successor is unmapped: the ioctl returns EFAULT. Signed-off-by: Kaixuan Li Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261019131655.2583227-1-kaixuanli0131@gmail.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/ioctl.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/fs/ext4/ioctl.c b/fs/ext4/ioctl.c index e8e579498c9902..792360dc00d115 100644 --- a/fs/ext4/ioctl.c +++ b/fs/ext4/ioctl.c @@ -1675,10 +1675,10 @@ static long __ext4_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) } case EXT4_IOC_GROUP_ADD: { - struct ext4_new_group_data input; + struct ext4_new_group_input __user *uinput = (void __user *)arg; + struct ext4_new_group_data input = {}; - if (copy_from_user(&input, (struct ext4_new_group_input __user *)arg, - sizeof(input))) + if (copy_from_user(&input, uinput, sizeof(*uinput))) return -EFAULT; return ext4_ioctl_group_add(filp, &input); From 356c926061758e4a578f3d42069eca65f13d1e80 Mon Sep 17 00:00:00 2001 From: Jiaming Zhang Date: Wed, 21 Oct 2026 16:56:35 +0800 Subject: [PATCH 1536/2102] ext4: clear in-inode xattr space before adding the first xattr An inode can hold extended attributes in the space that follows its extra fields, whose size is given by i_extra_isize. When ext4 loads an inode, ext4_iget_extra_inode() validates that space only if it starts with the xattr magic, and only then sets EXT4_STATE_XATTR. Without the magic, the space is treated as empty and is not checked. ext4_xattr_ibody_set() passes the space to ext4_xattr_set_entry() whether or not EXT4_STATE_XATTR is set. ext4_xattr_set_entry() walks the entries there to find min_offs, the lowest value offset. That offset decides whether the new value fits and where the value is copied: free = min_offs - ((void *)last - s->base) - sizeof(__u32); ... void *val = s->base + min_offs - new_size; A crafted image can leave non-zero bytes in that space without the magic where ext4 looks for it, for example by shrinking i_extra_isize. Those bytes are parsed as entries, and an entry that claims an in-inode value at offset 0 sets min_offs to 0. Because free is a size_t, the subtraction then wraps around to a huge value, and the free space check passes although the value does not fit. The value is copied new_size bytes before the start of the space, over the inode's own fields and, for a large value, the memory in front of the inode. On a kernel without KASAN, the copy corrupts memory: it overwrites the inode's own fields and, for a large value, also the memory in front of the inode. The bytes and their length are decided by the setxattr() caller. Nothing is freed and reused here, so the use-after-free in the report only reflects where the write happened to land. Triggering this issue requires mounting a crafted image, which needs CAP_SYS_ADMIN or automounting of removable media; after that, any setxattr() on the file reaches this path. The issue was found by fuzzing and has not been seen in production; a reproducer is available in the linked report. When EXT4_STATE_XATTR is not set, zero the first 32 bits of the space in ext4_xattr_ibody_set() before calling ext4_xattr_set_entry(). These are the bits IS_LAST_ENTRY() reads, so the space is treated as empty and the walk stops before reading any stale entry. Fixes: ac27a0ec112a ("[PATCH] ext4: initial copy of files from ext3") Closes: https://lore.kernel.org/lkml/CANypQFZzxTAH=4QRRDoqH6VAw1daAq88NDWiQKoM7QTOnP40sg@mail.gmail.com/ Cc: stable@vger.kernel.org Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Jiaming Zhang Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261021085635.3633692-1-r772577952@gmail.com Signed-off-by: Theodore Ts'o --- fs/ext4/xattr.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/fs/ext4/xattr.c b/fs/ext4/xattr.c index 7be5d49e550c6f..062786fa364641 100644 --- a/fs/ext4/xattr.c +++ b/fs/ext4/xattr.c @@ -2304,6 +2304,14 @@ int ext4_xattr_ibody_set(handle_t *handle, struct inode *inode, if (IS_ERR(ea_inode)) return PTR_ERR(ea_inode); } + + /* + * Make sure xattr space is properly initialized so that + * IS_LAST_ENTRY() returns true for its first entry + */ + if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR)) + *(__u32 *)s->first = 0; + error = ext4_xattr_set_entry(i, s, handle, inode, ea_inode, false /* is_block */); if (error) { From bfb8f5ce8815bb99770e355a916348df98181f18 Mon Sep 17 00:00:00 2001 From: Yichong Chen Date: Thu, 22 Oct 2026 15:02:35 +0800 Subject: [PATCH 1537/2102] ext4: drop tmp inode ownership before migration cleanup After the extent tree is transferred to the original inode, ext4_journal_ensure_credits() can fail before tmp_inode is cleared. The subsequent iput(tmp_inode) may then free the transferred tree. Move the existing resets of tmp_inode's size, block count and checksum seed before ext4_journal_ensure_credits(). This leaves the temporary inode ready for eviction even if obtaining journal credits fails. Keep ext4_ext_tree_init(), which marks the inode dirty, after the credits check. Fixes: a413036791d0 ("ext4: Provide function to handle transaction restarts") Signed-off-by: Yichong Chen Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261022070235.17849-1-chenyichong@uniontech.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/migrate.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/fs/ext4/migrate.c b/fs/ext4/migrate.c index ac314210b630de..f8ec43a202d0ad 100644 --- a/fs/ext4/migrate.c +++ b/fs/ext4/migrate.c @@ -570,13 +570,6 @@ int ext4_ext_migrate(struct inode *inode) free_ext_block(handle, tmp_inode); } - /* We mark the tmp_inode dirty via ext4_ext_tree_init. */ - err = ext4_journal_ensure_credits(handle, 1, 0); - if (err < 0) { - if (!retval) - retval = err; - goto out_stop; - } /* * Mark the tmp_inode as of size zero */ @@ -593,6 +586,13 @@ int ext4_ext_migrate(struct inode *inode) tmp_inode->i_blocks = 0; EXT4_I(tmp_inode)->i_csum_seed = tmp_csum_seed; + /* We mark the tmp_inode dirty via ext4_ext_tree_init. */ + err = ext4_journal_ensure_credits(handle, 1, 0); + if (err < 0) { + if (!retval) + retval = err; + goto out_stop; + } /* Reset the extent details */ ext4_ext_tree_init(handle, tmp_inode); out_stop: From f0872c44eda1f936b766bf87a384286986ef1b7c Mon Sep 17 00:00:00 2001 From: Baokun Li Date: Thu, 22 Oct 2026 20:26:25 +0800 Subject: [PATCH 1538/2102] ext4: skip eof zeroing when the zero range covers the eof block ext4_zero_range() drops the page cache of the range before allocating, to avoid exposing stale cached data. However, the dropped page can be read back by the eof zeroing: fallocate(fd, FALLOC_FL_ZERO_RANGE, 0, 4096) ext4_zero_range() ext4_truncate_page_cache_block_range(0, 4096) truncate_pagecache_range(0, 4095) truncate_inode_pages_range() delete_from_page_cache_batch() # drops the page ext4_alloc_file_blocks(..., 4096) ext4_block_zero_eof(512, LLONG_MAX) # not block aligned ext4_load_tail_bh() __filemap_get_folio(FGP_WRITEBEGIN | FGP_ACCESSED) # FGP_CREAT reads the dropped page back # zeroes [512,1024), marks the buffer dirty ext4_map_blocks(...) # converts the extent to unwritten ext4_update_inode_size(4096) The bytes below the old EOF keep the stale disk content. The page is left dirty, so read() returns old data while O_DIRECT reads zeroes, and a write into the same block is not converted and is lost until the page is dropped: page [0, 4096), 1k block size, file ends at 512 0 512 1024 4096 |--- data ----|-- tail ---|---- zero range ----------| | old data | | | For example: $ xfs_io -f -c "pwrite -S 1 0 512" f $ sync $ fallocate -z -o 0 -l 4096 f $ xfs_io -c "pread -v 0 16" f # old data, not zeroes FALLOC_FL_WRITE_ZEROES hits the same path. ext4_issue_zeroout() zeroes the block on disk without updating the page cache, and the block stays written. Therefore, writeback of the dirty page overwrites the zeroes with old data. Since the whole eof block is converted to unwritten or zeroed out, zeroing it here is redundant. Therefore, skip the zeroing when this allocation covers the eof block entirely. Fixes: c4602a1d09ec ("ext4: move zero partial block range functions out of active handle") Fixes: f4265b8d32c4 ("ext4: add FALLOC_FL_WRITE_ZEROES support") Cc: stable@vger.kernel.org Signed-off-by: Baokun Li Reviewed-by: Zhang Yi Link: https://patch.msgid.link/20261022122625.1744363-1-libaokun@linux.alibaba.com Signed-off-by: Theodore Ts'o --- fs/ext4/extents.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index d8c1e2d12add5f..0c0bdd9b8826b1 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -4651,8 +4651,15 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, credits = ext4_chunk_trans_blocks(inode, len_lblk); depth = ext_depth(inode); - /* Zero to the end of the block containing i_size */ - if (new_size > old_size) { + /* + * Zero to the end of the block containing i_size. + * Loading the eof block back before it is converted to unwritten + * or zeroed out may leave the page cache inconsistent with the + * disk, and zeroing it is redundant, so skip it. + */ + if (new_size > old_size && + !(in_range(old_size >> blkbits, map.m_lblk, map.m_len) && + (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN || alloc_zero))) { ret = ext4_block_zero_eof(inode, old_size, LLONG_MAX); if (ret) return ret; From 43fd15ef7deb3fb6dbf749112c80046e3c1926fc Mon Sep 17 00:00:00 2001 From: Ojaswin Mujoo Date: Fri, 23 Oct 2026 15:53:45 +0530 Subject: [PATCH 1539/2102] ext4: return -EINVAL on hole in ext4_convert_unwritten_extents_atomic() We should ideally never encounter a hole during the endio conversion as that indicates something is wrong with our extent handling. Still if we do find a hole at atomic write endio, ext4_map_blocks() returns 0 which would be returned back to callers by ext4_convert_unwritten_extents_atomic(). This can be wrongly interpreted as a success. Fix this by bailing out with -EINVAL instead. Signed-off-by: Ojaswin Mujoo Reviewed-by: Jan Kara Reviewed-by: Zhang Yi Link: https://patch.msgid.link/20261023-ext4-atomic-endio-fix-b4-v1-1-f91feb0b9613@linux.ibm.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/extents.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index 0c0bdd9b8826b1..155331ee3f7a44 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -5132,6 +5132,14 @@ int ext4_convert_unwritten_extents_atomic(handle_t *handle, struct inode *inode, map.m_lblk += ret; map.m_len = (max_blocks -= ret); ret = ext4_map_blocks(handle, inode, &map, flags); + if (ret == 0) { + ext4_msg(inode->i_sb, KERN_ERR, + "inode #%llu: block %u: len %u: " + "hole found while converting extents for atomic write", + inode->i_ino, map.m_lblk, map.m_len); + ret = -EINVAL; + break; + } if (ret != max_blocks) ext4_msg(inode->i_sb, KERN_INFO, "inode #%llu: block %u: len %u: " From f62b22b69aefa031ab65b46794a64e448edaa9ae Mon Sep 17 00:00:00 2001 From: Lukas Czerner Date: Sat, 24 Oct 2026 12:44:07 +0200 Subject: [PATCH 1540/2102] ext4: free fast commit replay state on failed mounts ext4_fc_replay_cleanup() is only ever called on the success path of __ext4_fill_super(). Fast commit replay runs from jbd2_journal_load(), so a mount that fails after that point leaks the fc_regions and fc_modified_inodes allocated during replay. Call ext4_fc_replay_cleanup() from the failed_mount3a error path, which every failure after jbd2_journal_load() goes through. Do it after draining deferred EA inode iputs, so evictions still run with EXT4_FC_REPLAY set. On paths where no replay happened both are NULL so this would be a no-op. Failures after the success path ext4_fc_replay_cleanup() call fall through failed_mount3a as well, so set both pointers to NULL after freeing them to avoid a double free. Fixes: 8016e29f4362 ("ext4: fast commit recovery path") Signed-off-by: Lukas Czerner Link: https://patch.msgid.link/20261024104407.1037354-1-lukas@czerner.cz Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/fast_commit.c | 2 ++ fs/ext4/super.c | 1 + 2 files changed, 3 insertions(+) diff --git a/fs/ext4/fast_commit.c b/fs/ext4/fast_commit.c index 5688b487acb41c..5f12449b97ec9e 100644 --- a/fs/ext4/fast_commit.c +++ b/fs/ext4/fast_commit.c @@ -2413,7 +2413,9 @@ void ext4_fc_replay_cleanup(struct super_block *sb) sbi->s_mount_state &= ~EXT4_FC_REPLAY; kfree(sbi->s_fc_replay_state.fc_regions); + sbi->s_fc_replay_state.fc_regions = NULL; kfree(sbi->s_fc_replay_state.fc_modified_inodes); + sbi->s_fc_replay_state.fc_modified_inodes = NULL; } static bool ext4_fc_value_len_isvalid(struct ext4_sb_info *sbi, diff --git a/fs/ext4/super.c b/fs/ext4/super.c index 81c7e8812d3d16..359f9d4ed44791 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -5854,6 +5854,7 @@ failed_mount8: __maybe_unused failed_mount3a: /* Drain deferred EA inode iputs from journal replay */ flush_delayed_work(&sbi->s_ea_inode_work); + ext4_fc_replay_cleanup(sb); ext4_es_unregister_shrinker(sbi); ext4_es_destroy_stats(sbi); failed_mount3: From e057b8082759e9dfed7a77ee1cadcd37810681c1 Mon Sep 17 00:00:00 2001 From: dardaoe Date: Sun, 25 Oct 2026 13:16:21 +0000 Subject: [PATCH 1541/2102] Documentation: ext4: fix group descriptor and superblock placement in meta_bg description MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Meta Block Groups section is imprecise in two places:  - Without meta_bg, it says all group descriptor copies are kept in    the first block group. In fact the primary table lives in group 0    and a backup of the whole table follows every superblock backup.  - With meta_bg, it says the superblock and a group descriptor block    are placed at the start of the first, second and last groups of    each meta-block group. Only the descriptor block is; superblock    backups still follow the sparse_super placement rules    (ext4_bg_has_super()), independent of meta_bg. Fix the wording and describe the interaction. Assisted-by: LLM Signed-off-by: dardaoe Link: https://patch.msgid.link/cJaripqlNO272O1fNRgrozKg2ocrVAPYS9w-1c-x1ltKdOsoNw9hWVKawqm7CoIhYb1pOwrTf6xxju_RKzajEmy8T1be_FuyQKKQ-GPGvB0=@proton.me Signed-off-by: Theodore Ts'o --- Documentation/filesystems/ext4/blockgroup.rst | 43 ++++++++++++------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/Documentation/filesystems/ext4/blockgroup.rst b/Documentation/filesystems/ext4/blockgroup.rst index 7cbf0b2b778eab..d33d1c426bda1b 100644 --- a/Documentation/filesystems/ext4/blockgroup.rst +++ b/Documentation/filesystems/ext4/blockgroup.rst @@ -83,11 +83,13 @@ flex_bg is given by 2 ^ ``sb.s_log_groups_per_flex``. Meta Block Groups ~~~~~~~~~~~~~~~~~ -Without the option META_BG, for safety concerns, all block group -descriptors copies are kept in the first block group. Given the default -128MiB(2^27 bytes) block group size and 64-byte group descriptors, ext4 -can have at most 2^27/64 = 2^21 block groups. This limits the entire -filesystem size to 2^21 * 2^27 = 2^48bytes or 256TiB. +Without the option META_BG, the group descriptors for all block groups +are stored together in a single table that follows the superblock in +the first block group, with a backup copy of the whole table following +each superblock backup. Given the default 128MiB(2^27 bytes) block +group size and 64-byte group descriptors, ext4 can have at most +2^27/64 = 2^21 block groups. This limits the entire filesystem size to +2^21 * 2^27 = 2^48bytes or 256TiB. The solution to this problem is to use the metablock group feature (META_BG), which is already in ext3 for all 2.6 releases. With the @@ -104,17 +106,26 @@ to the hard limit 2^32, allowing support for a 512PiB filesystem. The change in the filesystem format replaces the current scheme where the superblock is followed by a variable-length set of block group -descriptors. Instead, the superblock and a single block group descriptor -block is placed at the beginning of the first, second, and last block -groups in a meta-block group. A meta-block group is a collection of -block groups which can be described by a single block group descriptor -block. Since the size of the block group descriptor structure is 64 -bytes, a meta-block group contains 16 block groups for filesystems with -a 1KB block size, and 64 block groups for filesystems with a 4KB -blocksize. Filesystems can either be created using this new block group -descriptor layout, or existing filesystems can be resized on-line, and -the field s_first_meta_bg in the superblock will indicate the first -block group using this new layout. +descriptors. Instead, a single block group descriptor block is placed +at the beginning of the first, second, and last block groups in a +meta-block group (immediately after the superblock, if that group has +one), regardless of the sparse_super feature. A meta-block group is a +collection of block groups which can be described by a single block +group descriptor block. Since the size of the block group descriptor +structure is 64 bytes, a meta-block group contains 16 block groups for +filesystems with a 1KB block size, and 64 block groups for filesystems +with a 4KB blocksize. Filesystems can either be created using this new +block group descriptor layout, or existing filesystems can be resized +on-line, and the field s_first_meta_bg in the superblock will indicate +the first block group using this new layout. + +Superblock backups continue to follow the ordinary sparse_super +placement rule (block group 0, 1, or a power of 3, 5, or 7) +independently of meta-block group boundaries; without sparse_super, +every block group carries one. As a result, a block group at one of the +three meta-block-group positions above will carry a superblock backup +only if its group number also satisfies that rule; otherwise it holds +only the group descriptor block. Please see an important note about ``BLOCK_UNINIT`` in the section about block and inode bitmaps. From 6bda1a98b7ce2f88a0e206756999f608f8437722 Mon Sep 17 00:00:00 2001 From: Lukas Czerner Date: Sun, 25 Oct 2026 21:18:02 +0100 Subject: [PATCH 1542/2102] ext4: fix failed migrate freeing extent tree blocks In case ext4_ext_swap_inode_data() fails it will clean up a failed migration by freeing the extent tree in the tmp_inode. However, in case we already copied the temporary inode's extent tree root into the original inode, the process has been functionally finished. The error case clean up calls free_ext_block() which will free those extent tree blocks while the original inode already points at them and the filesystem ends up with multiply claimed blocks. Fix it by resetting the temporary inode's root to an empty tree right after copying i_data to the original inode, so free_ext_block() won't free the original inode extent tree blocks. Move temporary inode's i_blocks as well so eviction won't try to truncate metadata blocks the tmp_inode no longer owns. Signed-off-by: Lukas Czerner Link: https://patch.msgid.link/20261025201803.3043712-2-lukas@czerner.cz Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/ext4.h | 1 + fs/ext4/extents.c | 11 ++++++++++- fs/ext4/migrate.c | 13 ++++++++++++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index 5bff68363cf6d8..aa0f23052ca2a9 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -3967,6 +3967,7 @@ struct ext4_extent; */ #define EXT_MAX_BLOCKS 0xffffffff +extern void ext4_ext_init_root(struct inode *inode); extern void ext4_ext_tree_init(handle_t *handle, struct inode *inode); extern int ext4_ext_index_trans_blocks(struct inode *inode, int extents); extern int ext4_ext_map_blocks(handle_t *handle, struct inode *inode, diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index 155331ee3f7a44..c0618ce3719911 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -869,7 +869,11 @@ ext4_ext_binsearch(struct inode *inode, } -void ext4_ext_tree_init(handle_t *handle, struct inode *inode) +/* + * Initialize the extent tree of inode. This only changes the in-memory + * inode, the caller has to mark the inode dirty. + */ +void ext4_ext_init_root(struct inode *inode) { struct ext4_extent_header *eh; @@ -879,6 +883,11 @@ void ext4_ext_tree_init(handle_t *handle, struct inode *inode) eh->eh_magic = EXT4_EXT_MAGIC; eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0)); eh->eh_generation = 0; +} + +void ext4_ext_tree_init(handle_t *handle, struct inode *inode) +{ + ext4_ext_init_root(inode); ext4_mark_inode_dirty(handle, inode); } diff --git a/fs/ext4/migrate.c b/fs/ext4/migrate.c index f8ec43a202d0ad..cdef31eaa490ca 100644 --- a/fs/ext4/migrate.c +++ b/fs/ext4/migrate.c @@ -326,6 +326,12 @@ static int ext4_ext_swap_inode_data(handle_t *handle, struct inode *inode, */ ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); memcpy(ei->i_data, tmp_ei->i_data, sizeof(ei->i_data)); + /* + * The extent tree belongs to the inode now. Make tmp_inode's extent + * tree empty, so that cleaning up tmp_inode can't free the tree + * blocks, if we fail to finish the migration. + */ + ext4_ext_init_root(tmp_inode); /* * Update i_blocks with the new blocks that got @@ -335,10 +341,13 @@ static int ext4_ext_swap_inode_data(handle_t *handle, struct inode *inode, * While converting to extents we need not * update the original inode i_blocks for extent blocks * via quota APIs. The quota update happened via tmp_inode already. + * Clear tmp_inode i_blocks to avoid truncating original data blocks + * in case we fail to finish the migration. */ spin_lock(&inode->i_lock); inode->i_blocks += tmp_inode->i_blocks; spin_unlock(&inode->i_lock); + tmp_inode->i_blocks = 0; up_write(&EXT4_I(inode)->i_data_sem); /* @@ -565,7 +574,9 @@ int ext4_ext_migrate(struct inode *inode) if (retval && !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) /* * if we fail to swap inode data free the extent - * details of the tmp inode + * details of the tmp inode. If the tree was already + * moved to the original inode, the tmp_inode has an + * empty tree and there is nothing to free. */ free_ext_block(handle, tmp_inode); } From 58b186b5bbd295b0a3001ef4d40af1ea84501e5c Mon Sep 17 00:00:00 2001 From: Hamza Mahfooz Date: Mon, 26 Oct 2026 12:48:53 -0400 Subject: [PATCH 1543/2102] ext4: validate inode block references during fast commit replay __ext4_iget() currently skips ext4_ext_check_inode() and ext4_ind_check_inode() when EXT4_FC_REPLAY is set in s_mount_state. As a result, an extent-mapped inode loaded from disk during fast commit replay never has its in-inode extent header or root extent entries validated before replay paths such as ext4_fc_replay_inode() and ext4_fc_replay_add_range() walk or modify i_data[]. A crafted filesystem image with a fast commit journal and an inode whose eh_max / eh_entries exceed the four-extent capacity of i_data[] triggers slab-out-of-bounds reads in ext4_cache_extents() and slab-out-of-bounds writes in ext4_ext_insert_extent() into adjacent fields of struct ext4_inode_info and beyond the ext4_inode_cache slab allocation. ext4_ext_check_inode() and ext4_ind_check_inode() only validate the in-inode extent header and check block numbers against static superblock bounds via ext4_inode_block_valid(), not block allocation bitmaps. So, drop the EXT4_FC_REPLAY exemption in __ext4_iget() so inodes read during fast commit replay are validated. Cc: stable@vger.kernel.org Reported-by: Simon Brakhane Fixes: 8016e29f4362 ("ext4: fast commit recovery path") Signed-off-by: Hamza Mahfooz Link: https://patch.msgid.link/20261026164853.3125835-1-hamzamahfooz@linux.microsoft.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/inode.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 8bfb5c821163a7..f42bbf987c81cf 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -6508,10 +6508,9 @@ struct inode *__ext4_iget(struct super_block *sb, unsigned long ino, goto bad_inode; } else if (!ext4_has_inline_data(inode)) { /* validate the block references in the inode */ - if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) && - (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || - (S_ISLNK(inode->i_mode) && - !ext4_inode_is_fast_symlink(inode)))) { + if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || + (S_ISLNK(inode->i_mode) && + !ext4_inode_is_fast_symlink(inode))) { if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) ret = ext4_ext_check_inode(inode); else From cdecc68d94a7f35284e36ea80bc7a09bd7cb42b8 Mon Sep 17 00:00:00 2001 From: Hungyu Lin Date: Tue, 27 Oct 2026 03:58:57 +0000 Subject: [PATCH 1544/2102] ext4: preserve force-fsck requests across unmount EXT4_TUNE_FL_FORCE_FSCK sets EXT4_ERROR_FS in the on-disk superblock but leaves s_mount_state unchanged. On a normal read-write unmount, ext4_put_super() restores s_state from s_mount_state, clearing the requested flag. As a result, a successful EXT4_IOC_SET_TUNE_SB_PARAM call can be lost before e2fsck runs: after unmount it treats the filesystem as clean and skips the requested check. Set EXT4_ERROR_FS in s_mount_state as well, matching the state handling in ext4_clear_journal_err(), so later superblock updates retain the request. Fixes: 04a91570ac67 ("ext4: implemet new ioctls to set and get superblock parameters") Cc: stable@vger.kernel.org Signed-off-by: Hungyu Lin Link: https://patch.msgid.link/20261027035857.72265-1-dennylin0707@gmail.com Signed-off-by: Theodore Ts'o --- fs/ext4/ioctl.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/fs/ext4/ioctl.c b/fs/ext4/ioctl.c index 792360dc00d115..368005d318d957 100644 --- a/fs/ext4/ioctl.c +++ b/fs/ext4/ioctl.c @@ -1384,8 +1384,10 @@ static void ext4_sb_setparams(struct ext4_sb_info *sbi, EXT4_FEATURE_INCOMPAT_CSUM_SEED) es->s_checksum_seed = cpu_to_le32(sbi->s_csum_seed); } - if (params->set_flags & EXT4_TUNE_FL_FORCE_FSCK) + if (params->set_flags & EXT4_TUNE_FL_FORCE_FSCK) { + sbi->s_mount_state |= EXT4_ERROR_FS; es->s_state |= cpu_to_le16(EXT4_ERROR_FS); + } } static int ext4_ioctl_set_tune_sb(struct file *filp, From 1ea9e6b3bd3136288fb8717c6899ff43e4d99524 Mon Sep 17 00:00:00 2001 From: Zhang Yi Date: Fri, 30 Oct 2026 10:13:35 +0800 Subject: [PATCH 1545/2102] ext4: return 0 instead of stale ret in ext4_iomap_writepages() smatch reports a "missing error code" warning: fs/ext4/inode.c:4518 ext4_iomap_writepages() warn: missing error code? 'ret' The 'ret' variable has already been consumed by the ext4_emergency_state() check at the beginning of the function, so its value is always zero at this point. Returning it is equivalent to returning 0, but it is misleading because it looks like an error code is being propagated. This branch handles the race with ext4_change_inode_journal_flag(), which flushes the dirty data and drops the page cache before switching the inode to the buffer_head path, so there is genuinely nothing to write back here. Return 0 explicitly to make the intent clear. Fixes: bdcbb0f19e92 ("ext4: partially enable iomap for the buffered I/O path of regular files") Reported-by: kernel test robot Reported-by: Dan Carpenter Closes: https://lore.kernel.org/r/202610160314.PLMEXaOJ-lkp@intel.com/ Signed-off-by: Zhang Yi Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261030021338.1768292-2-yi.zhang@huaweicloud.com Signed-off-by: Theodore Ts'o --- fs/ext4/inode.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index f42bbf987c81cf..f3b933c63df971 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -4539,7 +4539,7 @@ static int ext4_iomap_writepages(struct address_space *mapping, */ if (!ext4_inode_buffered_iomap(inode)) { ext4_writepages_up_read(sb, alloc_ctx); - return ret; + return 0; } trace_ext4_writepages(inode, wbc); From d5fd7d0564d800d42302c6750b74b78f655fe81d Mon Sep 17 00:00:00 2001 From: Zhang Yi Date: Fri, 30 Oct 2026 10:13:36 +0800 Subject: [PATCH 1546/2102] ext4: fix extent status cache clearing when truncating inline data ext4_inline_data_truncate() clears the whole extent status tree of the inode when it truncates the inline data, with ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); It does that when the inode still carries inline data while the EXT4_STATE_MAY_INLINE_DATA state bit is already cleared. This is the case once an inline-to-extent conversion has been initiated, which is triggered by a delalloc buffered write larger than the inline space in ext4_da_convert_inline_data_to_extent(). The clear is meant to drop stale extent status entries of such an inode to prevent stale extents and stale reserved space after the conversion, but the range is too wide. It also drops the entries of the blocks below the new end of file, that is the blocks that stay in the file. When writeback of these blocks starts later, the lookup of such a block misses the extent status tree, falls back to the extent tree and caches a hole entry for it. Those blocks then have dirty, mapped and delayed buffers together with a hole extent status entry. This is an unexpected inconsistency. This problem has been hidden so far because we allocate blocks and new extents for them during writeback. But once '244392197bb9 ("ext4: skip block allocation for holes in the data submission path")' is merged during the iomap conversion, the writeback behavior will be normalized, and it will no longer allocate blocks for holes, thus exposing this problem. Therefore, restrict the range to the blocks that are actually truncated away, and pass EXT_MAX_BLOCKS minus lblk as the length. Reported-by: syzbot ci Closes: https://lore.kernel.org/linux-ext4/6ac92a4c.70ed5d86.2ac85.0072.GAE@google.com/ Fixes: 0add491df4e5 ("ext4: remove extent cache entries when truncating inline data") Signed-off-by: Zhang Yi Reviewed-by: Jan Kara Reported-by: syzbot+97fbc97fdd4e4fa2ed3a@syzkaller.appspotmail.com Tested-by: syzbot+97fbc97fdd4e4fa2ed3a@syzkaller.appspotmail.com Link: https://lore.kernel.org/linux-ext4/20261009103033.2920530-9-yi.zhang@huaweicloud.com/ Link: https://lore.kernel.org/linux-ext4/6ac92a4c.70ed5d86.2ac85.0072.GAE@google.com/ Link: https://patch.msgid.link/20261030021338.1768292-3-yi.zhang@huaweicloud.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/inline.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/fs/ext4/inline.c b/fs/ext4/inline.c index be76ffc1f98aaf..2e14ee9b4241b0 100644 --- a/fs/ext4/inline.c +++ b/fs/ext4/inline.c @@ -1921,8 +1921,12 @@ int ext4_inline_data_truncate(struct inode *inode, int *has_inline) * the extent status cache must be cleared to avoid leaving * behind stale delayed allocated extent entries */ - if (!ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) - ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + if (!ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) { + ext4_lblk_t lblk = EXT4_B_TO_LBLK(inode, i_size); + + ext4_es_remove_extent(inode, lblk, + EXT_MAX_BLOCKS - lblk); + } /* Clear the content in the xattr space. */ if (inline_size > EXT4_MIN_INLINE_DATA_SIZE) { From 390d69dd5c82e402882d690754a72a3e898b701b Mon Sep 17 00:00:00 2001 From: Zhang Yi Date: Fri, 30 Oct 2026 10:13:37 +0800 Subject: [PATCH 1547/2102] ext4: add inode to orphan list before extent conversion ext4_alloc_file_blocks() zeroes the blocks it has just allocated and converts their unwritten extents in a handle started with ext4_chunk_trans_blocks(), which reserves credits for a single extent. The range is allocated with ext4_map_blocks() first and converted afterwards, and only the unwritten extent conversion which runs on I/O completion can modify the extent tree of that range in between, since this path holds i_rwsem. If such a conversion converts part of the range first, it splits the extent, and converting the whole range then needs more credits than the handle has reserved. Before commit 10660a0ca7ed ("ext4: rework handle credit accounting for unwritten extent conversion"), this race condition led to insufficient credits, which made the conversion fail with -ENOSPC in the middle of the range. After it, ext4_convert_unwritten_extents() can extend or restart the transaction. Restarting commits everything modified so far, so the extents converted by the first iterations reach the disk before this function adds the inode to the orphan list. A crash in between leaves written extents beyond i_disksize on disk with the inode not on the orphan list, which fsck complains about. Add the inode to the orphan list before the conversion instead and keep it there until i_disksize has caught up. A restart then commits the orphan entry together with the extents converted so far, and the entry is only removed by the transaction which raises i_disksize and i_size. Fixes: 10660a0ca7ed ("ext4: rework handle credit accounting for unwritten extent conversion") Fixes: f7237a775c8f ("ext4: protect WRITE_ZEROES written extents with orphan list") Signed-off-by: Zhang Yi Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261030021338.1768292-4-yi.zhang@huaweicloud.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/extents.c | 47 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index c0618ce3719911..db49be6e4eb093 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -4735,6 +4735,23 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, break; } + /* + * Add the inode to the orphan list before the + * conversion, as it may restart the transaction and + * commit the extents converted so far. Written + * extents must stay covered by the orphan list until + * i_disksize catches up. + */ + if (new_size) { + ret2 = ext4_orphan_add(handle, inode); + orphan = true; + if (unlikely(ret2)) { + ret = ret2; + ext4_journal_stop(handle); + break; + } + } + ret = ext4_convert_unwritten_extents(handle, inode, (loff_t)map.m_lblk << blkbits, (loff_t)map.m_len << blkbits, @@ -4742,23 +4759,21 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, if (ret) map.m_len = converted; - /* - * If blocks beyond i_disksize are converted, add - * the inode to the orphan list and advance the epos. - */ - if (new_size && converted) { - ret2 = ext4_orphan_add(handle, inode); - ret = ret ? ret : ret2; - orphan = true; - } - ret3 = ext4_journal_stop(handle); ret = ret ? ret : ret3; } + /* + * The conversion may have failed without converting + * anything. Only move epos over the blocks that were + * actually converted, so that a failure updates + * i_disksize just far enough to cover them. + */ + if (map.m_len) + epos = EXT4_LBLK_TO_B(inode, map.m_lblk + map.m_len); + map.m_lblk += map.m_len; map.m_len = len_lblk = len_lblk - map.m_len; - epos = EXT4_LBLK_TO_B(inode, map.m_lblk); if (ret) break; } @@ -4766,12 +4781,13 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry; - if (!epos || !new_size) + if (!new_size || (!epos && !orphan)) return ret; /* - * Allocate blocks, update the file size to match the size of the - * already successfully allocated blocks. + * Update the file size to match the size of the already + * successfully allocated blocks, and release the orphan entry + * if we added one. */ if (epos > new_size) epos = new_size; @@ -4789,7 +4805,8 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, goto out; } - ext4_update_inode_size(inode, epos); + if (epos) + ext4_update_inode_size(inode, epos); if (orphan && inode->i_nlink) ext4_orphan_del(handle, inode); From d0877f8eb3c08218cb9f6165f565d90e956fb9ea Mon Sep 17 00:00:00 2001 From: Zhang Yi Date: Fri, 30 Oct 2026 10:13:38 +0800 Subject: [PATCH 1548/2102] ext4: initialize map->m_pblk in ext4_da_map_blocks() ext4_da_map_blocks() returns a delalloc mapping through @map without touching map->m_pblk at all. Callers that only set up m_lblk and m_len of their local struct ext4_map_blocks and leave the rest to the mapping helper, like ext4_iomap_map_blocks() does, end up with whatever happened to be on their stack, so the trace_ext4_iomap_buffered_write_begin() tracepoint prints an uninitialized pblk for a delalloc mapping. This has been harmless so far, ext4_da_get_block_prep() and ext4_set_iomap() both ignore m_pblk for a delalloc mapping, only the new tracepoint dumps it. Initialize m_pblk along with m_flags at the beginning of ext4_da_map_blocks(), so that a delalloc mapping is always reported with pblk 0, the same way ext4_map_blocks() reports it. Fixes: 008f019ab559 ("ext4: add block mapping tracepoints for iomap buffered I/O path") Signed-off-by: Zhang Yi Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261030021338.1768292-5-yi.zhang@huaweicloud.com Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/inode.c | 1 + 1 file changed, 1 insertion(+) diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index f3b933c63df971..298de8cd224f3d 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -2052,6 +2052,7 @@ static int ext4_da_map_blocks(struct inode *inode, struct ext4_map_blocks *map) #endif map->m_flags = 0; + map->m_pblk = 0; ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len, (unsigned long) map->m_lblk); From bbae5e26222e901ca412927ef8b4662e6586171a Mon Sep 17 00:00:00 2001 From: Hengyu Liang Date: Thu, 29 Oct 2026 22:57:30 -0400 Subject: [PATCH 1549/2102] ext4: do not report inline conversion allocation failures as fs errors When truncate grows an inline-data file beyond its inline capacity, ext4_setattr() first calls ext4_convert_inline_data(). If the conversion fails, it jumps to err_out and passes the error to ext4_std_error(). Allocating the first block can fail with -ENOSPC or -EDQUOT on a healthy filesystem. Reporting these as filesystem errors records an error in the superblock and, with errors=remount-ro, aborts the journal and rejects subsequent writes with -EROFS. For example, create a filesystem with inline_data,quota and mount it with usrquota,errors=remount-ro. Create a small inline file owned by a user with a 1 MiB block quota, then let that user fill the quota in a second file. Growing the inline file with ftruncate() returns EDQUOT, after which even root can no longer create a file. Return conversion errors directly, as other callers of ext4_convert_inline_data() do. The conversion helper handles its own cleanup, and lower layers report metadata and journal errors. Fixes: ed9356a30e59 ("ext4: convert inline data to extents when truncate exceeds inline size") Cc: stable@vger.kernel.org Signed-off-by: Hengyu Liang Link: https://patch.msgid.link/20261030025730.3965245-1-hengyul@cs.unc.edu Signed-off-by: Theodore Ts'o Cc: stable@kernel.org --- fs/ext4/inode.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 298de8cd224f3d..5946f5d99da625 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -7157,7 +7157,7 @@ int ext4_setattr(const struct mnt_idmap *idmap, struct dentry *dentry, attr->ia_size > EXT4_I(inode)->i_inline_size) { error = ext4_convert_inline_data(inode); if (error) - goto err_out; + return error; } if (shrink) { From e5db68ec43e9afc56ca3141ed16c70f0c6a48b0f Mon Sep 17 00:00:00 2001 From: Hengyu Liang Date: Fri, 30 Oct 2026 00:05:20 -0400 Subject: [PATCH 1550/2102] ext4: do not advance i_size on a buffered write that copied nothing Commit 665575cff098 ("filemap: move prefaulting out of hot write path") made generic_perform_write() call ->write_begin() and ->write_end() before it finds out that the source buffer cannot be read. In that case ->write_end() is called with copied == 0. However, ext4_write_end(), ext4_journalled_write_end() and ext4_da_do_write_end() set i_size to pos + copied without checking copied. As of now, a buffered write() past EOF that fails with EFAULT grows the file to the write offset, and the new size can reach the disk. The issue can be reproduced on an ext4 mount with: char *p = mmap(NULL, 4096, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); int fd = open("/mnt/ext4/file", O_CREAT | O_TRUNC | O_RDWR, 0600); pwrite(fd, p, 4096, 1024 * 1024); /* fails with EFAULT */ fstat(fd, &st); Before that commit, the result is st_size = 0. After it, the result is st_size = 1048576. This patch will leave i_size alone when nothing was copied, as ext4_write_inline_data_end() already does. Unlike ext4_write_end(), the delalloc path does not trim after a short write, so the folio and the delayed blocks that ->write_begin() set up beyond i_size are left behind, and the blocks stay reserved until the inode is evicted. When the write ends beyond i_size, drop them as well. Fixes: 665575cff098 ("filemap: move prefaulting out of hot write path") Cc: stable@vger.kernel.org Signed-off-by: Hengyu Liang Reviewed-by: Zhang Yi Link: https://patch.msgid.link/20261030040520.4138904-1-hengyul@cs.unc.edu Signed-off-by: Theodore Ts'o --- fs/ext4/inode.c | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 5946f5d99da625..b9a0d085e75d0c 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -1588,15 +1588,18 @@ static int ext4_write_end(const struct kiocb *iocb, * it's important to update i_size while still holding folio lock: * page writeout could otherwise come in and zero beyond i_size. * + * If nothing was copied (e.g. the source buffer was unreadable), do + * not move i_size up to pos. + * * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree * blocks are being written past EOF, so skip the i_size update. */ - if (!verity) + if (copied && !verity) i_size_changed = ext4_update_inode_size(inode, pos + copied); folio_unlock(folio); folio_put(folio); - if (old_size < pos && !verity) + if (copied && old_size < pos && !verity) pagecache_isize_extended(inode, old_size, pos); /* @@ -1707,13 +1710,13 @@ static int ext4_journalled_write_end(const struct kiocb *iocb, if (!partial) folio_mark_uptodate(folio); } - if (!verity) + if (copied && !verity) size_changed = ext4_update_inode_size(inode, pos + copied); EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid; folio_unlock(folio); folio_put(folio); - if (old_size < pos && !verity) + if (copied && old_size < pos && !verity) pagecache_isize_extended(inode, old_size, pos); if (size_changed) { @@ -3374,6 +3377,24 @@ static int ext4_da_should_update_i_disksize(struct folio *folio, return 1; } +/* + * Delalloc counterpart of ext4_truncate_failed_write(): ->write_begin() only + * reserved delayed blocks, so drop the page cache and the delayed extents + * beyond i_size and leave the blocks that are allocated there alone. + */ +static void ext4_da_truncate_failed_write(struct inode *inode) +{ + struct address_space *mapping = inode->i_mapping; + ext4_lblk_t lblk = EXT4_B_TO_LBLK(inode, inode->i_size); + + filemap_invalidate_lock(mapping); + truncate_inode_pages(mapping, inode->i_size); + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, lblk, EXT_MAX_BLOCKS - lblk); + up_write(&EXT4_I(inode)->i_data_sem); + filemap_invalidate_unlock(mapping); +} + static int ext4_da_do_write_end(struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct folio *folio) @@ -3411,12 +3432,12 @@ static int ext4_da_do_write_end(struct address_space *mapping, * checked, we need to update i_disksize here as certain * ext4_writepages() paths not allocating blocks and update i_disksize. */ - if (new_i_size > inode->i_size) { + if (copied && new_i_size > inode->i_size) { unsigned long end; i_size_write(inode, new_i_size); end = offset_in_folio(folio, new_i_size - 1); - if (copied && ext4_da_should_update_i_disksize(folio, end)) { + if (ext4_da_should_update_i_disksize(folio, end)) { ext4_update_i_disksize(inode, new_i_size); disksize_changed = true; } @@ -3425,9 +3446,13 @@ static int ext4_da_do_write_end(struct address_space *mapping, folio_unlock(folio); folio_put(folio); - if (pos > old_size) + if (copied && pos > old_size) pagecache_isize_extended(inode, old_size, pos); + /* Drop what ->write_begin() prepared beyond the resulting i_size. */ + if (pos + len > inode->i_size) + ext4_da_truncate_failed_write(inode); + if (!disksize_changed) return copied; From 7b42853f32d97febf8e71e6a07b805b61f7a108c Mon Sep 17 00:00:00 2001 From: guolingxing Date: Sun, 1 Nov 2026 10:21:45 +0000 Subject: [PATCH 1551/2102] ext4: report unwritten extent conversion failures as writeback errors When a data writeback bio completes successfully but the subsequent unwritten extent conversion fails, ext4_end_io_end() does not record the error in the inode's mapping writeback error state. Bio failures are already recorded by ext4_end_bio(), but conversion failures are not. When the conversion is processed asynchronously, its return value is not propagated to userspace, so fsync() may return success despite the failed conversion. Record conversion errors with mapping_set_error() before ext4_release_io_end() ends folio writeback and wakes waiters. This allows fsync() to observe the failure. Cc: stable@vger.kernel.org Signed-off-by: guolingxing Reviewed-by: Jan Kara Reviewed-by: Zhang Yi Reviewed-by: Ojaswin Mujoo Link: https://patch.msgid.link/20261101102145.647496-1-guolingxing@tju.edu.cn Signed-off-by: Theodore Ts'o --- fs/ext4/page-io.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/fs/ext4/page-io.c b/fs/ext4/page-io.c index e556598ce9e14c..791e61228f418d 100644 --- a/fs/ext4/page-io.c +++ b/fs/ext4/page-io.c @@ -192,6 +192,8 @@ static int ext4_end_io_end(ext4_io_end_t *io_end) jbd2_journal_abort(EXT4_SB(sb)->s_journal, ret); } else { ret = ext4_convert_unwritten_io_end_vec(handle, io_end); + if (ret < 0) + mapping_set_error(inode->i_mapping, ret); } if (ret < 0 && !ext4_emergency_state(sb) && io_end->flag & EXT4_IO_END_UNWRITTEN) { From 308c3c2ead9b32e959e8b08f6375b19aabad116f Mon Sep 17 00:00:00 2001 From: Amit Patole Date: Thu, 5 Nov 2026 09:00:36 -0500 Subject: [PATCH 1552/2102] jbd2: document the h_invalid handle flag Commit 61e2a90a910c ("ext4: enable scoped NOFS when starting a handle in nojournal mode") added the h_invalid bit to struct jbd2_journal_handle but did not add it to the kernel-doc comment above the structure, so kernel-doc now warns: include/linux/jbd2.h:523 struct member 'h_invalid' not described in 'jbd2_journal_handle' Describe the new flag. It is set by ext4_get_nojournal() on a handle that is not attached to any journal and is tested by ext4_handle_valid(). The warning was found by running scripts/kernel-doc over the headers pulled into the htmldocs build. An AI coding assistant (Claude Opus 5.5) was used to locate the warning and draft this change; it was verified with scripts/kernel-doc (no warnings left) and checkpatch. Fixes: 61e2a90a910c ("ext4: enable scoped NOFS when starting a handle in nojournal mode") Signed-off-by: Amit Patole Reviewed-by: Jan Kara Link: https://patch.msgid.link/20261105-kdoc-jbd2-h_invalid-v1-1-4bc224f7d0a2@gmail.com Signed-off-by: Theodore Ts'o --- include/linux/jbd2.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/linux/jbd2.h b/include/linux/jbd2.h index e3886963ba0040..69f12366a09a84 100644 --- a/include/linux/jbd2.h +++ b/include/linux/jbd2.h @@ -482,6 +482,7 @@ struct jbd2_revoke_table_s; * @h_sync: Flag for sync-on-close. * @h_reserved: Flag for handle for reserved credits. * @h_aborted: Flag indicating fatal error on handle. + * @h_invalid: Flag for a handle not attached to a journal (ext4 nojournal mode). * @h_type: For handle statistics. * @h_line_no: For handle statistics. * @h_start_jiffies: Handle Start time. From 5cb6d612274ecb907a8482c8b670a353b05630df Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Thu, 5 Nov 2026 03:17:44 +0000 Subject: [PATCH 1553/2102] ext4: add KUinit tests for fs/ext4/extents_status.c These tests were created with the help of Gemini Pro and verified by a human. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 3 +- fs/ext4/extents.c | 6 - fs/ext4/extents_status-test.c | 1646 +++++++++++++++++++++++++++++++++ fs/ext4/extents_status.c | 20 + fs/ext4/inode.c | 10 + 5 files changed, 1678 insertions(+), 7 deletions(-) create mode 100644 fs/ext4/extents_status-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 3f9fc0eb8ecadb..74b485dbb229b7 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -15,7 +15,8 @@ ext4-y := balloc.o bitmap.o block_validity.o dir.o ext4_jbd2.o extents.o \ ext4-$(CONFIG_EXT4_FS_POSIX_ACL) += acl.o ext4-$(CONFIG_EXT4_FS_SECURITY) += xattr_security.o ext4-test-objs += inode-test.o mballoc-test.o \ - extents-test.o hash-test.o + extents-test.o hash-test.o \ + extents_status-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index db49be6e4eb093..aa65aca4a1ead6 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -6526,13 +6526,7 @@ EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_split_convert_extents_test); EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_ext_dirty); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_zeroout); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_register_shrinker); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_unregister_shrinker); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_destroy_stats); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_create_blocks); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_init_tree); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_lookup_extent); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_insert_extent); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_insert_extent); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_extent); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_issue_zeroout); diff --git a/fs/ext4/extents_status-test.c b/fs/ext4/extents_status-test.c new file mode 100644 index 00000000000000..825d12513e4af2 --- /dev/null +++ b/fs/ext4/extents_status-test.c @@ -0,0 +1,1646 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 extents status tree and bigalloc pending reservations. + */ + +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_extents.h" + +#define ES_MAX_EXPECTED_EXTENTS 8 + +struct es_test_ctx { + struct super_block *sb; + struct ext4_sb_info *sbi; + struct ext4_inode_info *ei; + + /* + * Saved shrinker callbacks so the registered shrinker can be + * replaced with no-op stubs to prevent asynchronous background + * reclaim (kswapd / direct reclaim) from touching mock extents. + */ + unsigned long (*shrinker_count)(struct shrinker *shrink, + struct shrink_control *sc); + unsigned long (*shrinker_scan)(struct shrinker *shrink, + struct shrink_control *sc); + + /* Tracking for stubbed delalloc reservation callbacks */ + int da_update_calls; + int last_da_used; + int total_da_used; + int last_da_quota_claim; + + int da_release_calls; + int last_da_released; + int total_da_released; +}; + +struct expected_es { + ext4_lblk_t lblk; + ext4_lblk_t len; + ext4_fsblk_t pblk; + unsigned int type; +}; + +static void reset_da_stub_stats(struct es_test_ctx *ctx) +{ + ctx->da_update_calls = 0; + ctx->last_da_used = 0; + ctx->total_da_used = 0; + ctx->last_da_quota_claim = 0; + + ctx->da_release_calls = 0; + ctx->last_da_released = 0; + ctx->total_da_released = 0; +} + +static void ext4_da_update_reserve_space_stub(struct inode *inode, + int used, int quota_claim) +{ + struct kunit *test = kunit_get_current_test(); + struct es_test_ctx *ctx; + + if (!test || !test->priv) + return; + + ctx = test->priv; + ctx->da_update_calls++; + ctx->last_da_used = used; + ctx->total_da_used += used; + ctx->last_da_quota_claim = quota_claim; +} + +static void ext4_da_release_space_stub(struct inode *inode, int to_free) +{ + struct kunit *test = kunit_get_current_test(); + struct es_test_ctx *ctx; + + if (!to_free || !test || !test->priv) + return; + + ctx = test->priv; + ctx->da_release_calls++; + ctx->last_da_released = to_free; + ctx->total_da_released += to_free; +} + +static struct ext4_ext_path * +ext4_find_extent_stub(struct inode *inode, ext4_lblk_t block, + struct ext4_ext_path *path, int flags) +{ + return ERR_PTR(-EOPNOTSUPP); +} + +static unsigned long es_dummy_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long es_dummy_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +static unsigned long es_shrinker_count(struct es_test_ctx *ctx, + struct shrink_control *sc) +{ + return ctx->shrinker_count(ctx->sbi->s_es_shrinker, sc); +} + +static unsigned long es_shrinker_scan(struct es_test_ctx *ctx, + struct shrink_control *sc) +{ + return ctx->shrinker_scan(ctx->sbi->s_es_shrinker, sc); +} + +static void es_insert_extent(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len, ext4_fsblk_t pblk, + unsigned int status, bool delalloc_reserve_used) +{ + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_insert_extent(inode, lblk, len, pblk, status, + delalloc_reserve_used); + up_write(&EXT4_I(inode)->i_data_sem); +} + +static void es_insert_delayed_extent(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len, bool lclu_allocated, + bool end_allocated) +{ + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_insert_delayed_extent(inode, lblk, len, lclu_allocated, + end_allocated); + up_write(&EXT4_I(inode)->i_data_sem); +} + +static void es_cache_extent(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len, ext4_fsblk_t pblk, + unsigned int status) +{ + down_read(&EXT4_I(inode)->i_data_sem); + ext4_es_cache_extent(inode, lblk, len, pblk, status); + up_read(&EXT4_I(inode)->i_data_sem); +} + +static void es_remove_extent(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len) +{ + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, lblk, len); + up_write(&EXT4_I(inode)->i_data_sem); +} + +static int es_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static int es_set_anon(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static struct file_system_type es_fs_type = { + .name = "extents_status test", + .init_fs_context = es_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void es_init_mock_inode(struct ext4_inode_info *ei, + struct super_block *sb, unsigned long ino) +{ + struct inode *inode = &ei->vfs_inode; + + memset(ei, 0, sizeof(*ei)); + inode->i_sb = sb; + inode->i_ino = ino; + inode->i_blkbits = sb->s_blocksize_bits; + + ext4_es_init_tree(&ei->i_es_tree); + ext4_init_pending_tree(&ei->i_pending_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + init_rwsem(&ei->i_data_sem); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); +} + +static void es_cleanup_inode(struct inode *inode) +{ + struct ext4_inode_info *ei = EXT4_I(inode); + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct rb_node *node; + + sbi->s_mount_state &= ~EXT4_FC_REPLAY; + es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + + while ((node = rb_first(&ei->i_pending_tree.root)) != NULL) { + struct pending_reservation *pr; + + pr = rb_entry(node, struct pending_reservation, rb_node); + ext4_remove_pending(inode, EXT4_C2B(sbi, pr->lclu)); + } +} + +KUNIT_DEFINE_ACTION_WRAPPER(es_cleanup_inode_action, es_cleanup_inode, + struct inode *); +static void es_cleanup_shrinker(struct ext4_sb_info *sbi) +{ + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); +} + +KUNIT_DEFINE_ACTION_WRAPPER(es_unregister_shrinker_action, + es_cleanup_shrinker, + struct ext4_sb_info *); +KUNIT_DEFINE_ACTION_WRAPPER(es_deactivate_super_action, deactivate_super, + struct super_block *); + +static struct inode *es_alloc_test_inode(struct kunit *test, + struct super_block *sb, + unsigned long ino) +{ + struct ext4_inode_info *ei; + int ret; + + ei = kunit_kzalloc(test, sizeof(*ei), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ei); + es_init_mock_inode(ei, sb, ino); + + ret = kunit_add_action_or_reset(test, es_cleanup_inode_action, + &ei->vfs_inode); + KUNIT_ASSERT_EQ(test, ret, 0); + + return &ei->vfs_inode; +} + +static void es_set_cluster_bits(struct super_block *sb, + unsigned int cluster_bits) +{ + struct ext4_sb_info *sbi = EXT4_SB(sb); + + sbi->s_cluster_bits = cluster_bits; + sbi->s_cluster_ratio = 1U << cluster_bits; +} + +/* + * All test resources and deferred cleanup actions are registered with KUnit's + * resource stack (test->resources), which unwinds in strict LIFO order after + * each test case completes (or aborts). + * + * The registration order below (and in helpers like es_alloc_test_inode()) + * MUST be preserved when modifying these tests so that teardown happens in the + * reverse order: + * 1. kunit_kzalloc() of ctx, sbi, and ctx->ei (freed last) + * 2. es_deactivate_super_action(sb) (superblock deactivated after shrinker + * and all inodes are torn down) + * 3. es_unregister_shrinker_action(sbi) (shrinker and s_es_stats per-CPU + * counters destroyed after all inode extent trees are emptied) + * 4. kunit_activate_static_stub() for ext4_da_update_reserve_space, + * ext4_da_release_space, and ext4_find_extent (stubs must remain active + * while es_cleanup_inode() removes delayed extents via + * ext4_es_remove_extent()) + * 5. es_cleanup_inode_action() for ctx->ei and any additional test inodes + * allocated via es_alloc_test_inode() (run first during teardown; inside + * es_alloc_test_inode(), kunit_kzalloc() must precede + * kunit_add_action_or_reset() so the inode is cleaned up before freed) + */ +static int es_kunit_init(struct kunit *test) +{ + struct es_test_ctx *ctx; + struct ext4_sb_info *sbi; + struct super_block *sb; + struct fs_context *fc; + int err; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + if (!ctx) + return -ENOMEM; + + sbi = kunit_kzalloc(test, sizeof(*sbi), GFP_KERNEL); + if (!sbi) + return -ENOMEM; + + ctx->ei = kunit_kzalloc(test, sizeof(*ctx->ei), GFP_KERNEL); + if (!ctx->ei) + return -ENOMEM; + + fc = fs_context_for_mount(&es_fs_type, 0); + if (IS_ERR(fc)) + return PTR_ERR(fc); + + sb = sget_fc(fc, NULL, es_set_anon); + put_fs_context(fc); + if (IS_ERR(sb)) + return PTR_ERR(sb); + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_blocksize = 4096; + sb->s_blocksize_bits = 12; + strscpy(sb->s_id, "es_kunit", sizeof(sb->s_id)); + + es_set_cluster_bits(sb, 0); + set_opt(sb, DELALLOC); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + up_write(&sb->s_umount); + + err = kunit_add_action_or_reset(test, es_deactivate_super_action, sb); + if (err) + return err; + + err = ext4_es_register_shrinker(sbi); + if (err) + return err; + + /* + * Detach the real callbacks from the globally registered shrinker + * before any extents are inserted so background kswapd / direct + * reclaim cannot asynchronously evict mock extents during a test. + */ + ctx->shrinker_count = sbi->s_es_shrinker->count_objects; + ctx->shrinker_scan = sbi->s_es_shrinker->scan_objects; + WRITE_ONCE(sbi->s_es_shrinker->count_objects, es_dummy_shrinker_count); + WRITE_ONCE(sbi->s_es_shrinker->scan_objects, es_dummy_shrinker_scan); + + err = kunit_add_action_or_reset(test, es_unregister_shrinker_action, + sbi); + if (err) + return err; + + ctx->sb = sb; + ctx->sbi = sbi; + test->priv = ctx; + + kunit_activate_static_stub(test, ext4_da_update_reserve_space, + ext4_da_update_reserve_space_stub); + kunit_activate_static_stub(test, ext4_da_release_space, + ext4_da_release_space_stub); + kunit_activate_static_stub(test, ext4_find_extent, + ext4_find_extent_stub); + + es_init_mock_inode(ctx->ei, sb, 12); + err = kunit_add_action_or_reset(test, es_cleanup_inode_action, + &ctx->ei->vfs_inode); + if (err) + return err; + + return 0; +} + +static void assert_es_tree(struct kunit *test, struct inode *inode, + const struct expected_es *exp, unsigned int nr_exp) +{ + struct ext4_inode_info *ei = EXT4_I(inode); + struct extent_status found[ES_MAX_EXPECTED_EXTENTS]; + struct rb_node *node; + unsigned int nr_found = 0; + unsigned int all_nr; + unsigned int i; + ext4_lblk_t prev_end = 0; + + KUNIT_ASSERT_LE(test, nr_exp, (unsigned int)ARRAY_SIZE(found)); + + /* + * Snapshot the tree under i_es_lock and release the lock before + * running any KUnit assertions or expectations. KUNIT_ASSERT_* + * aborts the test kthread on failure (which would leak i_es_lock + * and deadlock es_cleanup_inode()), and KUNIT_EXPECT_* allocates + * failure logs with GFP_KERNEL. + */ + read_lock(&ei->i_es_lock); + for (node = rb_first(&ei->i_es_tree.root); node; node = rb_next(node)) { + struct extent_status *es = + rb_entry(node, struct extent_status, rb_node); + + if (nr_found < ARRAY_SIZE(found)) + found[nr_found] = *es; + nr_found++; + } + all_nr = ei->i_es_all_nr; + read_unlock(&ei->i_es_lock); + + for (i = 0; i < nr_found; i++) { + struct extent_status *es = &found[min(i, + (unsigned int)ARRAY_SIZE(found) - 1)]; + + KUNIT_ASSERT_LT_MSG(test, i, nr_exp, + "unexpected extra extent [%u/%u) type 0x%x", + es->es_lblk, es->es_len, ext4_es_type(es)); + + if (i > 0) + KUNIT_EXPECT_GT_MSG(test, es->es_lblk, prev_end, + "extent %u not strictly ordered", + i); + + KUNIT_EXPECT_EQ_MSG(test, es->es_lblk, exp[i].lblk, + "extent %u lblk mismatch", i); + KUNIT_EXPECT_EQ_MSG(test, es->es_len, exp[i].len, + "extent %u len mismatch", i); + KUNIT_EXPECT_EQ_MSG(test, ext4_es_type(es), exp[i].type, + "extent %u type mismatch", i); + + if (exp[i].type & (EXTENT_STATUS_WRITTEN | + EXTENT_STATUS_UNWRITTEN)) + KUNIT_EXPECT_EQ_MSG(test, ext4_es_pblock(es), + exp[i].pblk, + "extent %u pblk mismatch", i); + + prev_end = es->es_lblk + es->es_len - 1; + } + + KUNIT_EXPECT_EQ(test, nr_found, nr_exp); + KUNIT_EXPECT_EQ(test, all_nr, nr_exp); +} + +/* + * Group 1: Bitfield Encoding & Inline Helpers + */ +static void test_es_bitfield_written_and_unwritten_encoding(struct kunit *test) +{ + struct extent_status es = {}; + const ext4_fsblk_t sample_pblk = 0x123456789abcULL; + + ext4_es_store_pblock_status(&es, sample_pblk, EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), sample_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_show_pblock(&es), sample_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_type(&es), EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_EQ(test, ext4_es_status(&es), EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_TRUE(test, ext4_es_is_written(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_unwritten(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_delayed(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_hole(&es)); + KUNIT_EXPECT_TRUE(test, ext4_es_is_mapped(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_referenced(&es)); + + ext4_es_store_pblock_status(&es, sample_pblk, EXTENT_STATUS_UNWRITTEN); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), sample_pblk); + KUNIT_EXPECT_TRUE(test, ext4_es_is_unwritten(&es)); + KUNIT_EXPECT_TRUE(test, ext4_es_is_mapped(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_written(&es)); +} + +static void test_es_bitfield_delayed_and_hole_encoding(struct kunit *test) +{ + struct extent_status es = {}; + /* 59-bit physical block field (64 - 5 status bits) all ones */ + const ext4_fsblk_t max_59bit_pblk = 0x07ffffffffffffffULL; + + ext4_es_store_pblock_status(&es, ~0ULL, EXTENT_STATUS_DELAYED); + KUNIT_EXPECT_TRUE(test, ext4_es_is_delayed(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_mapped(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), max_59bit_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_show_pblock(&es), 0ULL); + + ext4_es_store_pblock_status(&es, 0ULL, EXTENT_STATUS_HOLE); + KUNIT_EXPECT_TRUE(test, ext4_es_is_hole(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_mapped(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 0ULL); +} + +static void +test_es_bitfield_referenced_and_pblock_update_preserve_state(struct kunit *test) +{ + struct extent_status es = {}; + const ext4_fsblk_t initial_pblk = 0x123456789abcULL; + const ext4_fsblk_t updated_pblk = 0x07ffffffffffffffULL; + + ext4_es_store_pblock_status(&es, initial_pblk, EXTENT_STATUS_WRITTEN); + + /* Setting referenced bit preserves pblk and type */ + ext4_es_set_referenced(&es); + KUNIT_EXPECT_TRUE(test, ext4_es_is_referenced(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_type(&es), EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), initial_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_status(&es), + EXTENT_STATUS_WRITTEN | EXTENT_STATUS_REFERENCED); + + /* Updating pblock preserves status and referenced bit */ + ext4_es_store_pblock(&es, updated_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), updated_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_type(&es), EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_TRUE(test, ext4_es_is_referenced(&es)); + + /* Clearing referenced bit preserves updated pblk and type */ + ext4_es_clear_referenced(&es); + KUNIT_EXPECT_FALSE(test, ext4_es_is_referenced(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), updated_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_type(&es), EXTENT_STATUS_WRITTEN); +} + +/* + * Group 2: Insertion, Lookup, Sequence Numbers, and Merging + */ +static void test_es_lookup_empty_tree_returns_miss(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct extent_status es; + ext4_lblk_t next_lblk = 0xdead; + s64 misses_before; + int ret; + + misses_before = percpu_counter_sum_positive( + &ctx->sbi->s_es_stats.es_stats_cache_misses); + ret = ext4_es_lookup_extent(inode, 10, &next_lblk, &es, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum_positive( + &ctx->sbi->s_es_stats.es_stats_cache_misses), + misses_before + 1); +} + +static void test_es_insert_zero_len_is_noop(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + es_insert_extent(inode, 10, 0, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_delayed_extent(inode, 20, 0, false, false); + es_cache_extent(inode, 30, 0, 300, EXTENT_STATUS_WRITTEN); + + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_all_nr, 0U); + KUNIT_EXPECT_TRUE(test, RB_EMPTY_ROOT(&ctx->ei->i_es_tree.root)); +} + +static void +test_es_lookup_hits_cache_and_rbtree_with_next_lblk(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct extent_status es; + ext4_lblk_t next_lblk = 0xdead; + u64 seq_after_first, seq_after_second, lookup_seq = 0; + s64 hits_before; + int ret; + + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + seq_after_first = ctx->ei->i_es_seq; + es_insert_extent(inode, 20, 5, 200, EXTENT_STATUS_UNWRITTEN, false); + seq_after_second = ctx->ei->i_es_seq; + KUNIT_EXPECT_GT(test, seq_after_second, seq_after_first); + + /* + * Right after inserting [20, 5), tree->cache_es points to [20, 5). + * Looking up lblk 22 hits cache_es and sets next_lblk to 0 because + * [20, 5) is the last extent in the tree. + */ + hits_before = percpu_counter_sum_positive( + &ctx->sbi->s_es_stats.es_stats_cache_hits); + + ret = ext4_es_lookup_extent(inode, 22, &next_lblk, &es, &lookup_seq); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, es.es_lblk, 20U); + KUNIT_EXPECT_EQ(test, es.es_len, 5U); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 200ULL); + KUNIT_EXPECT_TRUE(test, ext4_es_is_unwritten(&es)); + KUNIT_EXPECT_EQ(test, next_lblk, 0U); + KUNIT_EXPECT_EQ(test, lookup_seq, seq_after_second); + + /* Lookup start, middle, and end of first extent [10, 5) via rb-tree */ + ret = ext4_es_lookup_extent(inode, 10, &next_lblk, &es, NULL); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, es.es_lblk, 10U); + KUNIT_EXPECT_EQ(test, next_lblk, 20U); + + ret = ext4_es_lookup_extent(inode, 12, &next_lblk, &es, NULL); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, es.es_lblk, 10U); + KUNIT_EXPECT_EQ(test, next_lblk, 20U); + + ret = ext4_es_lookup_extent(inode, 14, &next_lblk, &es, NULL); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, es.es_lblk, 10U); + KUNIT_EXPECT_EQ(test, next_lblk, 20U); + + KUNIT_EXPECT_EQ(test, percpu_counter_sum_positive( + &ctx->sbi->s_es_stats.es_stats_cache_hits), + hits_before + 4); + + /* Lookup in gap [15..19] returns 0 */ + ret = ext4_es_lookup_extent(inode, 15, &next_lblk, &es, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); +} + +static void test_es_fc_replay_bypasses_tree_operations(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct extent_status es; + static const struct expected_es expected[] = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }; + + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + + ctx->sbi->s_mount_state |= EXT4_FC_REPLAY; + KUNIT_EXPECT_EQ(test, + ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), 0); + ext4_es_find_extent_range(inode, ext4_es_is_written, 0, 20, &es); + KUNIT_EXPECT_EQ(test, es.es_len, 0U); + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_range(inode, ext4_es_is_written, + 0, 20)); + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_clu(inode, ext4_es_is_written, 10)); + + es_insert_extent(inode, 30, 5, 300, EXTENT_STATUS_WRITTEN, false); + es_cache_extent(inode, 40, 5, 400, EXTENT_STATUS_WRITTEN); + es_insert_delayed_extent(inode, 50, 5, false, false); + es_remove_extent(inode, 10, 5); + ctx->sbi->s_mount_state &= ~EXT4_FC_REPLAY; + + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +struct es_merge_test_param { + const char *desc; + unsigned int nr_inserts; + struct expected_es inserts[3]; + unsigned int nr_expected; + struct expected_es expected[3]; +}; + +static const struct es_merge_test_param es_merge_params[] = { + { + .desc = "left merge contiguous written extents", + .nr_inserts = 2, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_WRITTEN }, + }, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 10, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "right merge contiguous written extents", + .nr_inserts = 2, + .inserts = { + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 10, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "three-way bridge merge via try_to_merge_right", + .nr_inserts = 3, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 20, .len = 5, .pblk = 110, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_WRITTEN }, + }, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 15, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "three-way bridge merge via try_to_merge_left", + .nr_inserts = 3, + .inserts = { + { .lblk = 20, .len = 5, .pblk = 110, + .type = EXTENT_STATUS_UNWRITTEN }, + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_UNWRITTEN }, + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_UNWRITTEN }, + }, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 15, .pblk = 100, + .type = EXTENT_STATUS_UNWRITTEN }, + }, + }, + { + .desc = "adjacent hole extents merge", + .nr_inserts = 2, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 0, + .type = EXTENT_STATUS_HOLE }, + { .lblk = 15, .len = 5, .pblk = 0, + .type = EXTENT_STATUS_HOLE }, + }, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 10, .pblk = 0, + .type = EXTENT_STATUS_HOLE }, + }, + }, + { + .desc = "discontiguous physical blocks do not merge", + .nr_inserts = 2, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 200, + .type = EXTENT_STATUS_WRITTEN }, + }, + .nr_expected = 2, + .expected = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 200, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "different status types with contiguous pblk do not merge", + .nr_inserts = 2, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_UNWRITTEN }, + }, + .nr_expected = 2, + .expected = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_UNWRITTEN }, + }, + }, + { + .desc = "logically separated extents with 1-block gap do not merge", + .nr_inserts = 2, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 16, .len = 5, .pblk = 106, + .type = EXTENT_STATUS_WRITTEN }, + }, + .nr_expected = 2, + .expected = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 16, .len = 5, .pblk = 106, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, +}; + +static void es_merge_get_desc(const struct es_merge_test_param *param, + char *desc) +{ + strscpy(desc, param->desc, KUNIT_PARAM_DESC_SIZE); +} +KUNIT_ARRAY_PARAM(es_merge, es_merge_params, es_merge_get_desc); + +static void test_es_merge_cases(struct kunit *test) +{ + const struct es_merge_test_param *param = test->param_value; + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + unsigned int i; + + for (i = 0; i < param->nr_inserts; i++) { + const struct expected_es *ins = ¶m->inserts[i]; + + es_insert_extent(inode, ins->lblk, ins->len, + ins->pblk, ins->type, false); + } + + assert_es_tree(test, inode, param->expected, param->nr_expected); +} + +static void test_es_insert_adjacent_delayed_extents_merges(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 10, .len = 10, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + + es_insert_delayed_extent(inode, 10, 5, false, false); + es_insert_delayed_extent(inode, 15, 5, false, false); + + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +static void test_es_merge_preserves_referenced(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct extent_status es; + struct rb_node *node; + bool is_ref = false; + + /* + * Insert [10, 5) and [20, 5), mark [20, 5) referenced via lookup, + * then bridge [15, 5) so [20, 5) is merged into [10, 10) via + * ext4_es_try_to_merge_right(). + */ + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 20, 5, 110, EXTENT_STATUS_WRITTEN, false); + KUNIT_ASSERT_EQ(test, + ext4_es_lookup_extent(inode, 20, NULL, &es, NULL), 1); + + es_insert_extent(inode, 15, 5, 105, EXTENT_STATUS_WRITTEN, false); + KUNIT_ASSERT_EQ(test, ctx->ei->i_es_all_nr, 1U); + + read_lock(&ctx->ei->i_es_lock); + node = rb_first(&ctx->ei->i_es_tree.root); + if (node) + is_ref = ext4_es_is_referenced(rb_entry(node, + struct extent_status, + rb_node)); + read_unlock(&ctx->ei->i_es_lock); + + KUNIT_ASSERT_NOT_NULL(test, node); + KUNIT_EXPECT_TRUE(test, is_ref); +} + +static void +test_es_merge_at_max_blocks_boundary_succeeds(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 0, .len = EXT_MAX_BLOCKS, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }; + + es_insert_extent(inode, 0, 0x80000000U, 100, + EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 0x80000000U, 0x7fffffffU, + 100ULL + 0x80000000ULL, + EXTENT_STATUS_WRITTEN, false); + + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +/* + * Group 3: Removal, Trimming, Splitting, and Overwrites + */ +struct es_remove_test_param { + const char *desc; + ext4_lblk_t rem_lblk; + ext4_lblk_t rem_len; + unsigned int nr_expected; + struct expected_es expected[2]; +}; + +static const struct es_remove_test_param es_remove_params[] = { + { + .desc = "remove range before extent", + .rem_lblk = 0, + .rem_len = 5, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 10, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "remove range after extent", + .rem_lblk = 20, + .rem_len = 5, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 10, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "remove exact extent range", + .rem_lblk = 10, + .rem_len = 10, + .nr_expected = 0, + }, + { + .desc = "remove superset of extent range", + .rem_lblk = 5, + .rem_len = 20, + .nr_expected = 0, + }, + { + .desc = "prefix trim of extent", + .rem_lblk = 10, + .rem_len = 4, + .nr_expected = 1, + .expected = { + { .lblk = 14, .len = 6, .pblk = 104, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "suffix trim of extent", + .rem_lblk = 16, + .rem_len = 4, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 6, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "middle split of extent into two", + .rem_lblk = 13, + .rem_len = 4, + .nr_expected = 2, + .expected = { + { .lblk = 10, .len = 3, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 17, .len = 3, .pblk = 107, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, +}; + +static void es_remove_get_desc(const struct es_remove_test_param *param, + char *desc) +{ + strscpy(desc, param->desc, KUNIT_PARAM_DESC_SIZE); +} +KUNIT_ARRAY_PARAM(es_remove, es_remove_params, es_remove_get_desc); + +static void test_es_remove_geometries(struct kunit *test) +{ + const struct es_remove_test_param *param = test->param_value; + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + es_insert_extent(inode, 10, 10, 100, EXTENT_STATUS_WRITTEN, false); + es_remove_extent(inode, param->rem_lblk, param->rem_len); + + assert_es_tree(test, inode, param->expected, param->nr_expected); +} + +static void +test_es_remove_multi_extent_span_trims_and_deletes(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 10, .len = 2, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 43, .len = 2, .pblk = 403, + .type = EXTENT_STATUS_UNWRITTEN }, + }; + + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 20, 5, 200, EXTENT_STATUS_HOLE, false); + es_insert_extent(inode, 30, 5, 300, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 40, 5, 400, EXTENT_STATUS_UNWRITTEN, false); + + /* + * Remove [12, 31) covering lblks 12..42 inclusive: + * - trims suffix of [10, 5) -> [10, 2) + * - completely removes [20, 5) and [30, 5) + * - trims prefix of [40, 5) -> [43, 2) + */ + es_remove_extent(inode, 12, 31); + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +static void test_es_insert_overwrite_split_and_remerge(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es split_exp[] = { + { .lblk = 10, .len = 3, .pblk = 100, + .type = EXTENT_STATUS_UNWRITTEN }, + { .lblk = 13, .len = 4, .pblk = 103, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 17, .len = 3, .pblk = 107, + .type = EXTENT_STATUS_UNWRITTEN }, + }; + static const struct expected_es merged_exp[] = { + { .lblk = 10, .len = 10, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }; + + es_insert_extent(inode, 10, 10, 100, EXTENT_STATUS_UNWRITTEN, false); + es_insert_extent(inode, 13, 4, 103, EXTENT_STATUS_WRITTEN, false); + assert_es_tree(test, inode, split_exp, ARRAY_SIZE(split_exp)); + + /* Convert the remaining prefix and suffix to WRITTEN; all 3 merge */ + es_insert_extent(inode, 10, 3, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 17, 3, 107, EXTENT_STATUS_WRITTEN, false); + assert_es_tree(test, inode, merged_exp, ARRAY_SIZE(merged_exp)); +} + +/* + * Group 4: On-Disk Caching & Conflict Detection (ext4_es_cache_extent) + */ +static void +test_es_cache_extent_inserts_and_coalesces_same_status(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es initial_exp[] = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }; + static const struct expected_es coalesced_exp[] = { + { .lblk = 8, .len = 10, .pblk = 98, + .type = EXTENT_STATUS_WRITTEN }, + }; + int warnings_before; + + warnings_before = atomic_read(&ctx->sbi->s_warning_count); + + /* Cache into empty tree */ + es_cache_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN); + assert_es_tree(test, inode, initial_exp, ARRAY_SIZE(initial_exp)); + + /* Caching sub-range with identical status is a no-op */ + es_cache_extent(inode, 11, 2, 101, EXTENT_STATUS_WRITTEN); + assert_es_tree(test, inode, initial_exp, ARRAY_SIZE(initial_exp)); + + /* Caching larger covering range with same status coalesces */ + es_cache_extent(inode, 8, 10, 98, EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->sbi->s_warning_count), + warnings_before); + assert_es_tree(test, inode, coalesced_exp, ARRAY_SIZE(coalesced_exp)); +} + +static void +test_es_cache_extent_conflict_covered_range_warns(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 8, .len = 10, .pblk = 98, + .type = EXTENT_STATUS_WRITTEN }, + }; + int warnings_before; + + es_cache_extent(inode, 8, 10, 98, EXTENT_STATUS_WRITTEN); + warnings_before = atomic_read(&ctx->sbi->s_warning_count); + + /* Sub-range [10, 4) covered by [8, 10) with conflicting status */ + es_cache_extent(inode, 10, 4, 500, EXTENT_STATUS_UNWRITTEN); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->sbi->s_warning_count), + warnings_before + 1); + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +static void +test_es_cache_extent_conflict_partial_overlap_warns(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }; + int warnings_before; + + es_cache_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN); + warnings_before = atomic_read(&ctx->sbi->s_warning_count); + + /* + * Range [8, 10) is not covered by [10, 5), so ext4_es_cache_extent() + * enters __es_remove_extent() which detects the status conflict and + * returns -EINVAL without modifying [10, 5). + */ + es_cache_extent(inode, 8, 10, 500, EXTENT_STATUS_UNWRITTEN); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->sbi->s_warning_count), + warnings_before + 1); + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +static void +test_es_cache_extent_hole_over_delayed_does_not_warn(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 30, .len = 5, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + int warnings_before; + + es_insert_delayed_extent(inode, 30, 5, false, false); + warnings_before = atomic_read(&ctx->sbi->s_warning_count); + + es_cache_extent(inode, 30, 5, 0, EXTENT_STATUS_HOLE); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->sbi->s_warning_count), + warnings_before); + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +/* + * Group 5: Range Search & Cluster Scanning + */ +static void +test_es_find_extent_range_skips_nonmatching_and_finds_next(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct extent_status es; + + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_delayed_extent(inode, 20, 5, false, false); + es_insert_extent(inode, 30, 5, 300, EXTENT_STATUS_UNWRITTEN, false); + + /* + * Prime cache_es to [10, 5) WRITTEN, then search [10, 25] for DELAYED: + * cache_es is hit at lblk 10, fails matching_fn(ext4_es_is_delayed), + * and walks rb_next to find [20, 5) DELAYED. + */ + KUNIT_ASSERT_EQ(test, + ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), 1); + ext4_es_find_extent_range(inode, ext4_es_is_delayed, 10, 25, &es); + KUNIT_EXPECT_EQ(test, es.es_lblk, 20U); + KUNIT_EXPECT_EQ(test, es.es_len, 5U); + KUNIT_EXPECT_TRUE(test, ext4_es_is_delayed(&es)); + + /* Search [10, 18] for DELAYED when starting inside [10, 5) returns 0 */ + KUNIT_ASSERT_EQ(test, + ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), 1); + ext4_es_find_extent_range(inode, ext4_es_is_delayed, 10, 18, &es); + KUNIT_EXPECT_EQ(test, es.es_len, 0U); + + /* + * Search [16, 18] in gap before [20, 5): __es_tree_search(16) returns + * the next extent [20, 5) following the range. + */ + ext4_es_find_extent_range(inode, ext4_es_is_delayed, 16, 18, &es); + KUNIT_EXPECT_EQ(test, es.es_lblk, 20U); + KUNIT_EXPECT_EQ(test, es.es_len, 5U); +} + +static void +test_es_scan_range_matches_only_overlapping_extents(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + es_insert_delayed_extent(inode, 20, 5, false, false); + es_insert_extent(inode, 30, 5, 300, EXTENT_STATUS_UNWRITTEN, false); + + /* Gap [16, 18] before [20, 5) does not overlap */ + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_range(inode, ext4_es_is_delayed, + 16, 18)); + + /* Ranges overlapping [20, 5) or [30, 5) return true */ + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_range(inode, ext4_es_is_delayed, + 16, 20)); + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_range(inode, ext4_es_is_delayed, + 22, 23)); + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_range(inode, ext4_es_is_mapped, + 34, 40)); + + /* Range [35, 40] after [30, 5) does not overlap */ + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_range(inode, ext4_es_is_mapped, + 35, 40)); +} + +static void test_es_scan_clu_matches_extent_in_same_cluster(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Configure cluster size = 16 blocks (cluster_bits = 4) */ + es_set_cluster_bits(ctx->sb, 4); + + /* Insert delayed block at the very end of cluster 0 (lblk 15) */ + es_insert_delayed_extent(inode, 15, 1, false, false); + + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_clu(inode, ext4_es_is_delayed, 0)); + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_clu(inode, ext4_es_is_delayed, 8)); + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_clu(inode, ext4_es_is_delayed, 15)); + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_clu(inode, ext4_es_is_delayed, 16)); + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_clu(inode, ext4_es_is_mapped, 0)); +} + +/* + * Group 6: Delayed Allocation & Bigalloc Pending Reservations + */ +static void +test_es_delalloc_remove_and_overwrite_account_reserved_blocks(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es after_rem_exp[] = { + { .lblk = 10, .len = 2, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + { .lblk = 15, .len = 5, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + static const struct expected_es after_ins_exp[] = { + { .lblk = 10, .len = 6, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 16, .len = 4, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + + /* Delayed extents are must-keep: i_es_shk_nr remains 0 */ + es_insert_delayed_extent(inode, 10, 10, false, false); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_all_nr, 1U); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 0U); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei->i_es_list)); + + /* Removing 3 delayed blocks [12, 3) releases 3 reserved blocks */ + reset_da_stub_stats(ctx); + es_remove_extent(inode, 12, 3); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_released, 3); + assert_es_tree(test, inode, after_rem_exp, ARRAY_SIZE(after_rem_exp)); + + /* + * Inserting WRITTEN [10, 6) overwrites [10, 2) delayed, [12, 3) gap, + * and [15, 1) delayed -> claims 3 delayed blocks of reservation. + */ + reset_da_stub_stats(ctx); + es_insert_extent(inode, 10, 6, 100, EXTENT_STATUS_WRITTEN, true); + KUNIT_EXPECT_EQ(test, ctx->da_update_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_used, 3); + KUNIT_EXPECT_EQ(test, ctx->last_da_quota_claim, 1); + assert_es_tree(test, inode, after_ins_exp, ARRAY_SIZE(after_ins_exp)); +} + +static void +test_es_bigalloc_insert_delayed_creates_and_removes_pending(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks: clu 0=[0..15], clu 1=[16..31], clu 2=[32..47] */ + es_set_cluster_bits(ctx->sb, 4); + + /* Single cluster with lclu_allocated = true */ + es_insert_delayed_extent(inode, 2, 4, true, false); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 0)); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 15)); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 16)); + + /* Multi-cluster [20, 20) spanning clusters 1 and 2, both allocated */ + es_insert_delayed_extent(inode, 20, 20, true, true); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 16)); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 32)); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 48)); + + /* Duplicate pending insertion on cluster 0 is idempotent */ + es_insert_delayed_extent(inode, 8, 2, true, false); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 0)); + + /* Explicit removal of pending reservation */ + ext4_remove_pending(inode, 16); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 16)); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 32)); +} + +static void +test_es_bigalloc_revise_pending_single_cluster_halves(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks */ + es_set_cluster_bits(ctx->sb, 4); + + /* Insert delayed extent [0, 32) covering clusters 0 and 1 */ + es_insert_delayed_extent(inode, 0, 32, false, false); + + /* + * 1. Allocate first half of cluster 0: [0, 8) -> WRITTEN. + * Delayed blocks [8, 8) remain after [0, 8) in cluster 0 (l_del=true): + * __revise_pending inserts pending on cluster 0 and claims 1 cluster. + */ + reset_da_stub_stats(ctx); + es_insert_extent(inode, 0, 8, 100, EXTENT_STATUS_WRITTEN, true); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 0)); + KUNIT_EXPECT_EQ(test, ctx->da_update_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_used, 1); + + /* + * 2. Allocate second half of cluster 0: [8, 8) -> WRITTEN. + * No delayed blocks remain in cluster 0; pending reservation on + * cluster 0 is removed and 0 additional clusters are claimed. + */ + reset_da_stub_stats(ctx); + es_insert_extent(inode, 8, 8, 108, EXTENT_STATUS_WRITTEN, true); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 0)); + KUNIT_EXPECT_EQ(test, ctx->da_update_calls, 0); + + /* + * 3. Allocate second half of cluster 1 first: [24, 8) -> WRITTEN while + * [16, 8) remains delayed before it in cluster 1 (f_del=true branch in + * __revise_pending): inserts pending on cluster 1 and claims 1 cluster. + */ + reset_da_stub_stats(ctx); + es_insert_extent(inode, 24, 8, 224, EXTENT_STATUS_WRITTEN, true); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 16)); + KUNIT_EXPECT_EQ(test, ctx->da_update_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_used, 1); +} + +static void +test_es_bigalloc_revise_pending_multi_cluster_span(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks */ + es_set_cluster_bits(ctx->sb, 4); + + /* + * Insert delayed [16, 32) across cluster 1 [16..31] and cluster 2 + * [32..47], then allocate [20, 24) (lblks 20..43), leaving delayed + * [16, 4) in cluster 1 and delayed [44, 4) in cluster 2. Both clusters + * get pending reservations and 2 clusters are claimed. + */ + es_insert_delayed_extent(inode, 16, 32, false, false); + reset_da_stub_stats(ctx); + es_insert_extent(inode, 20, 24, 220, EXTENT_STATUS_WRITTEN, true); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 16)); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 32)); + KUNIT_EXPECT_EQ(test, ctx->da_update_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_used, 2); +} + +static void +test_es_bigalloc_remove_partial_cluster_holds_rsvd_until_empty(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks */ + es_set_cluster_bits(ctx->sb, 4); + + es_insert_delayed_extent(inode, 0, 16, false, false); + reset_da_stub_stats(ctx); + + es_remove_extent(inode, 0, 4); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 0); + + es_remove_extent(inode, 12, 4); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 0); + + es_remove_extent(inode, 4, 8); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_released, 1); +} + +static void +test_es_bigalloc_remove_fragmented_cluster_releases_once(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks */ + es_set_cluster_bits(ctx->sb, 4); + + /* + * Two fragmented delayed extents within cluster 0 ([2, 3) and [10, 3)) + * share a single cluster reservation and must release 1 cluster, not 2. + */ + es_insert_delayed_extent(inode, 2, 3, false, false); + es_insert_delayed_extent(inode, 10, 3, false, false); + reset_da_stub_stats(ctx); + + es_remove_extent(inode, 0, 16); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_released, 1); +} + +static void +test_es_bigalloc_remove_pending_cluster_cancels_pending_only(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks */ + es_set_cluster_bits(ctx->sb, 4); + + /* + * Removing a delayed extent in a cluster with a pending reservation + * cancels the pending reservation and releases 0 clusters (because the + * cluster reservation was already claimed when allocated). + */ + es_insert_delayed_extent(inode, 16, 8, true, false); + KUNIT_ASSERT_TRUE(test, ext4_is_pending(inode, 16)); + reset_da_stub_stats(ctx); + + es_remove_extent(inode, 16, 8); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 0); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 16)); +} + +/* + * Group 7: Shrinker, Referenced Aging, and Cache Clearing + */ +static void +test_es_clear_inode_es_retains_only_delayed_extents(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es only_delayed_exp[] = { + { .lblk = 40, .len = 5, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 20, 5, 200, EXTENT_STATUS_UNWRITTEN, false); + es_insert_extent(inode, 30, 5, 0, EXTENT_STATUS_HOLE, false); + es_insert_delayed_extent(inode, 40, 5, false, false); + ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED); + + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_all_nr, 4U); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 3U); + + ext4_clear_inode_es(inode); + + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, + EXT4_STATE_EXT_PRECACHED)); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 0U); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei->i_es_list)); + assert_es_tree(test, inode, only_delayed_exp, + ARRAY_SIZE(only_delayed_exp)); +} + +static void +test_es_shrinker_ages_referenced_and_keeps_delayed(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct percpu_counter *shk_cnt = &ctx->sbi->s_es_stats.es_stats_shk_cnt; + struct shrink_control sc = { .nr_to_scan = 0 }; + struct extent_status es; + unsigned long count, shrunk; + static const struct expected_es after_first_scan[] = { + { .lblk = 10, .len = 2, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 30, .len = 2, .pblk = 300, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 50, .len = 2, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + static const struct expected_es after_second_scan[] = { + { .lblk = 50, .len = 2, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + + /* Insert 4 reclaimable WRITTEN extents and 1 non-reclaimable DELAYED */ + es_insert_extent(inode, 10, 2, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 20, 2, 200, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 30, 2, 300, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 40, 2, 400, EXTENT_STATUS_WRITTEN, false); + es_insert_delayed_extent(inode, 50, 2, false, false); + + /* Mark [10, 2) and [30, 2) as EXTENT_STATUS_REFERENCED via lookup */ + KUNIT_ASSERT_EQ(test, + ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), 1); + KUNIT_ASSERT_EQ(test, + ext4_es_lookup_extent(inode, 30, NULL, &es, NULL), 1); + + /* + * Fold per-CPU counter deltas into the central count so count_objects + * (which uses percpu_counter_read_positive) sees all 4 extents on SMP. + */ + percpu_counter_set(shk_cnt, percpu_counter_sum_positive(shk_cnt)); + count = es_shrinker_count(ctx, &sc); + KUNIT_EXPECT_EQ(test, count, 4UL); + + /* + * First scan (nr_to_scan = 5): + * - [20, 2) and [40, 2) are unreferenced and reclaimed (shrunk = 2) + * - [10, 2) and [30, 2) have REFERENCED cleared and survive + * - [50, 2) is DELAYED (must_keep) and survives + */ + sc.nr_to_scan = 5; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 2UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 2U); + assert_es_tree(test, inode, after_first_scan, + ARRAY_SIZE(after_first_scan)); + + /* + * Second scan (nr_to_scan = 5): + * - [10, 2) and [30, 2) are now unreferenced and reclaimed (shrunk = 2) + * - Only [50, 2) DELAYED remains; inode is removed from s_es_list + */ + sc.nr_to_scan = 5; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 2UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 0U); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei->i_es_list)); + assert_es_tree(test, inode, after_second_scan, + ARRAY_SIZE(after_second_scan)); +} + +static void +test_es_shrinker_cursor_advances_and_wraps_around(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct shrink_control sc = {}; + unsigned long shrunk; + + es_insert_extent(inode, 10, 2, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 20, 2, 200, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 30, 2, 300, EXTENT_STATUS_WRITTEN, false); + + sc.nr_to_scan = 1; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 1UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shrink_lblk, 20U); + + /* Re-insert [10, 2) behind the shrink cursor; next scan wraps to it */ + es_insert_extent(inode, 10, 2, 100, EXTENT_STATUS_WRITTEN, false); + sc.nr_to_scan = 3; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 3UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_all_nr, 0U); +} + +static void +test_es_shrinker_skips_precached_inode_until_last_resort(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode1 = &ctx->ei->vfs_inode; + struct inode *inode2; + struct shrink_control sc = {}; + unsigned long shrunk; + + inode2 = es_alloc_test_inode(test, ctx->sb, 13); + + es_insert_extent(inode1, 10, 2, 100, EXTENT_STATUS_WRITTEN, false); + ext4_set_inode_state(inode1, EXT4_STATE_EXT_PRECACHED); + es_insert_extent(inode2, 10, 2, 200, EXTENT_STATUS_WRITTEN, false); + + /* First scan skips precached inode1 and reclaims from inode2 */ + sc.nr_to_scan = 1; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 1UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 1U); + KUNIT_EXPECT_EQ(test, EXT4_I(inode2)->i_es_shk_nr, 0U); + + /* + * Now only precached inode1 remains on s_es_list; shrinker retries + * and reclaims from inode1 as a last resort. + */ + sc.nr_to_scan = 1; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 1UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 0U); +} + +static void test_es_seq_shrinker_info_show_formats_stats(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct seq_file seq = {}; + char *buf; + + es_insert_extent(inode, 10, 2, 100, EXTENT_STATUS_WRITTEN, false); + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + seq.buf = buf; + seq.size = PAGE_SIZE; + seq.private = ctx->sb; + + KUNIT_EXPECT_EQ(test, + ext4_seq_es_shrinker_info_show(&seq, SEQ_START_TOKEN), + 0); + KUNIT_EXPECT_GT(test, seq.count, 0UL); + KUNIT_EXPECT_NOT_NULL(test, strstr(buf, "reclaimable objects")); +} + +static struct kunit_case extents_status_test_cases[] = { + KUNIT_CASE(test_es_bitfield_written_and_unwritten_encoding), + KUNIT_CASE(test_es_bitfield_delayed_and_hole_encoding), + KUNIT_CASE(test_es_bitfield_referenced_and_pblock_update_preserve_state), + KUNIT_CASE(test_es_lookup_empty_tree_returns_miss), + KUNIT_CASE(test_es_insert_zero_len_is_noop), + KUNIT_CASE(test_es_lookup_hits_cache_and_rbtree_with_next_lblk), + KUNIT_CASE(test_es_fc_replay_bypasses_tree_operations), + KUNIT_CASE_PARAM(test_es_merge_cases, es_merge_gen_params), + KUNIT_CASE(test_es_insert_adjacent_delayed_extents_merges), + KUNIT_CASE(test_es_merge_preserves_referenced), + KUNIT_CASE(test_es_merge_at_max_blocks_boundary_succeeds), + KUNIT_CASE_PARAM(test_es_remove_geometries, es_remove_gen_params), + KUNIT_CASE(test_es_remove_multi_extent_span_trims_and_deletes), + KUNIT_CASE(test_es_insert_overwrite_split_and_remerge), + KUNIT_CASE(test_es_cache_extent_inserts_and_coalesces_same_status), + KUNIT_CASE(test_es_cache_extent_conflict_covered_range_warns), + KUNIT_CASE(test_es_cache_extent_conflict_partial_overlap_warns), + KUNIT_CASE(test_es_cache_extent_hole_over_delayed_does_not_warn), + KUNIT_CASE(test_es_find_extent_range_skips_nonmatching_and_finds_next), + KUNIT_CASE(test_es_scan_range_matches_only_overlapping_extents), + KUNIT_CASE(test_es_scan_clu_matches_extent_in_same_cluster), + KUNIT_CASE(test_es_delalloc_remove_and_overwrite_account_reserved_blocks), + KUNIT_CASE(test_es_bigalloc_insert_delayed_creates_and_removes_pending), + KUNIT_CASE(test_es_bigalloc_revise_pending_single_cluster_halves), + KUNIT_CASE(test_es_bigalloc_revise_pending_multi_cluster_span), + KUNIT_CASE(test_es_bigalloc_remove_partial_cluster_holds_rsvd_until_empty), + KUNIT_CASE(test_es_bigalloc_remove_fragmented_cluster_releases_once), + KUNIT_CASE(test_es_bigalloc_remove_pending_cluster_cancels_pending_only), + KUNIT_CASE(test_es_clear_inode_es_retains_only_delayed_extents), + KUNIT_CASE(test_es_shrinker_ages_referenced_and_keeps_delayed), + KUNIT_CASE(test_es_shrinker_cursor_advances_and_wraps_around), + KUNIT_CASE(test_es_shrinker_skips_precached_inode_until_last_resort), + KUNIT_CASE(test_es_seq_shrinker_info_show_formats_stats), + {} +}; + +static struct kunit_suite extents_status_test_suite = { + .name = "ext4_extents_status_test", + .init = es_kunit_init, + .test_cases = extents_status_test_cases, +}; + +kunit_test_suites(&extents_status_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 extents status tree and pending reservations"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/extents_status.c b/fs/ext4/extents_status.c index c250b7d356f506..c86bf438b48c3d 100644 --- a/fs/ext4/extents_status.c +++ b/fs/ext4/extents_status.c @@ -2416,3 +2416,23 @@ static int __revise_pending(struct inode *inode, ext4_lblk_t lblk, out: return (ret < 0) ? ret : pendings; } + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_init_tree); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_insert_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_cache_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_remove_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_find_extent_range); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_lookup_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_scan_range); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_scan_clu); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_register_shrinker); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_unregister_shrinker); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_destroy_stats); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_seq_es_shrinker_info_show); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_pending_tree); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_remove_pending); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_is_pending); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_insert_delayed_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_clear_inode_es); +#endif diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index b9a0d085e75d0c..43a183978692ed 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -418,6 +418,9 @@ void ext4_da_update_reserve_space(struct inode *inode, struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); struct ext4_inode_info *ei = EXT4_I(inode); + KUNIT_STATIC_STUB_REDIRECT(ext4_da_update_reserve_space, + inode, used, quota_claim); + spin_lock(&ei->i_block_reservation_lock); trace_ext4_da_update_reserve_space(inode, used, quota_claim); if (unlikely(used > ei->i_reserved_data_blocks)) { @@ -1786,6 +1789,8 @@ void ext4_da_release_space(struct inode *inode, int to_free) struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); struct ext4_inode_info *ei = EXT4_I(inode); + KUNIT_STATIC_STUB_REDIRECT(ext4_da_release_space, inode, to_free); + if (!to_free) return; /* Nothing to release, exit */ @@ -7994,3 +7999,8 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf) sb_end_pagefault(inode->i_sb); return ret; } + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_update_reserve_space); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_release_space); +#endif From 975e805e9af9e7522cb2d118fdda41257181c614 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Thu, 5 Nov 2026 03:18:08 +0000 Subject: [PATCH 1554/2102] ext4: add KUnit tests for fs/ext4/extents.c Expand the ext4_extents_test KUnit test suite in fs/ext4/extents-test.c to cover the core extent tree operations in fs/ext4/extents.c: - 48-bit physical block encoding/decoding (ext4_ext_pblock, ext4_ext_store_pblock, ext4_idx_pblock, ext4_idx_store_pblock) and unwritten extent length encoding (ext4_ext_mark_unwritten, ext4_ext_is_unwritten, ext4_ext_get_actual_len, ext4_ext_mark_initialized). - Extent tree initialization (ext4_ext_tree_init) and header/entry validation (ext4_ext_check_inode, __ext4_ext_check) across 13 parameterized corruption cases (magic, depth, max, entries, empty non-root index, zero-length extent, logical block wrap-around, out-of-bounds physical blocks, overlapping/unsorted extents and indexes, and parent/leaf logical block mismatch). - Metadata checksum calculation and verification on external extent blocks when EXT4_FEATURE_RO_COMPAT_METADATA_CSUM is enabled. - Root and multi-level (depth >= 1) extent tree lookup and navigation (ext4_find_extent, ext4_ext_search_left, ext4_ext_search_right, ext4_ext_next_allocated_block, ext4_ext_next_leaf_block) and extent status precaching (ext4_ext_precache) using in-memory simulated metadata buffer_heads via an ext4_ext_getblk() KUnit static stub. - Extent merge rules (ext4_can_extents_be_merged) and insertion (ext4_ext_insert_extent), including forward/backward/three-way merging, nomerge flag handling, tree depth growth (ext4_ext_grow_indepth), leaf and intermediate index node splitting (ext4_ext_split via test_insert_extent_leaf_split and test_insert_extent_index_split), and tree collapse back into the root inode (ext4_ext_try_to_merge_up). - Extent space removal and truncation (ext4_ext_remove_space, ext4_ext_truncate) across tail truncates, partial trims, middle hole punches, multi-level index removal (ext4_ext_rm_idx), and bigalloc partial-cluster nofree and pending cluster rereservation (ext4_rereserve_cluster). - Block mapping and allocation (ext4_ext_map_blocks), including hole lookup, delayed-extent hole adjustment, QUERY_LAST_IN_LEAF, block allocation, overlap clamping, ENOSPC handling, unwritten-to-written conversion with neighbor merging, and bigalloc implied cluster allocation (ext4_map_cluster_from_extent). - Extent shifting (ext4_ext_shift_extents) for FALLOC_FL_COLLAPSE_RANGE and FALLOC_FL_INSERT_RANGE, extent swapping (ext4_swap_extents, also exporting ext4_double_{down,up}_write_data_sem for lockdep-clean two-inode locking in test_swap_extents), cluster mapping queries (ext4_clu_mapped), JBD2 transaction credit calculations (ext4_ext_calc_credits_for_single_extent, ext4_ext_index_trans_blocks), and fast-commit replay helpers (ext4_ext_replay_update_ex, ext4_ext_replay_shrink_inode, ext4_ext_replay_set_iblocks). - Fix ext4_ext_path memory leaks in the existing test_split_convert() helpers and isolate the mock extent status shrinker from background reclaim. Signed-off-by: Theodore Ts'o --- fs/ext4/ext4_extents.h | 21 + fs/ext4/ext4_jbd2.c | 8 + fs/ext4/extents-test.c | 2089 ++++++++++++++++++++++++++++++++++++++-- fs/ext4/extents.c | 83 +- fs/ext4/inode.c | 5 + fs/ext4/mballoc.c | 7 + fs/ext4/move_extent.c | 5 + fs/ext4/super.c | 1 + 8 files changed, 2147 insertions(+), 72 deletions(-) diff --git a/fs/ext4/ext4_extents.h b/fs/ext4/ext4_extents.h index f4218ff0842d5d..f819ae995a103c 100644 --- a/fs/ext4/ext4_extents.h +++ b/fs/ext4/ext4_extents.h @@ -269,6 +269,8 @@ extern int __ext4_ext_dirty(const char *where, unsigned int line, struct ext4_ext_path *path); extern int ext4_ext_zeroout(handle_t *handle, struct inode *inode, struct ext4_extent *ex); +extern struct buffer_head *ext4_ext_getblk(struct inode *inode, + ext4_fsblk_t pblk, gfp_t gfp_flags); #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) extern int ext4_ext_space_root_idx_test(struct inode *inode, int check); extern struct ext4_ext_path *ext4_split_convert_extents_test( @@ -276,6 +278,25 @@ extern struct ext4_ext_path *ext4_split_convert_extents_test( struct ext4_map_blocks *map, struct ext4_ext_path *path, int flags, unsigned int *allocated); +extern int ext4_ext_check_test(struct inode *inode, + struct ext4_extent_header *eh, int depth, + ext4_fsblk_t pblk, ext4_lblk_t lblk); +extern void ext4_extent_block_csum_set_test(struct inode *inode, + struct ext4_extent_header *eh); +extern int ext4_can_extents_be_merged_test(struct inode *inode, + struct ext4_extent *ex1, + struct ext4_extent *ex2); +extern int ext4_ext_search_left_test(struct inode *inode, + struct ext4_ext_path *path, + ext4_lblk_t *logical, ext4_fsblk_t *phys); +extern int ext4_ext_search_right_test(struct inode *inode, + struct ext4_ext_path *path, + ext4_lblk_t *logical, ext4_fsblk_t *phys, + struct ext4_extent *ret_ex, int flags); +extern ext4_lblk_t ext4_ext_next_leaf_block_test(struct ext4_ext_path *path); +extern int ext4_ext_shift_extents_test(struct inode *inode, handle_t *handle, + ext4_lblk_t start, ext4_lblk_t shift, + enum SHIFT_DIRECTION direction); #endif #endif /* _EXT4_EXTENTS */ diff --git a/fs/ext4/ext4_jbd2.c b/fs/ext4/ext4_jbd2.c index cf1032a8c89a25..7d4f36baf25064 100644 --- a/fs/ext4/ext4_jbd2.c +++ b/fs/ext4/ext4_jbd2.c @@ -4,6 +4,7 @@ */ #include "ext4_jbd2.h" +#include #include @@ -383,6 +384,9 @@ int __ext4_handle_dirty_metadata(const char *where, unsigned int line, { int err = 0; + KUNIT_STATIC_STUB_REDIRECT(__ext4_handle_dirty_metadata, where, line, + handle, inode, bh); + might_sleep(); set_buffer_meta(bh); @@ -435,3 +439,7 @@ int __ext4_handle_dirty_metadata(const char *where, unsigned int line, } return err; } + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_handle_dirty_metadata); +#endif diff --git a/fs/ext4/extents-test.c b/fs/ext4/extents-test.c index 1abeb614b8bad5..cb1ef31490d02e 100644 --- a/fs/ext4/extents-test.c +++ b/fs/ext4/extents-test.c @@ -3,60 +3,75 @@ * Written by Ojaswin Mujoo (IBM) * * These Kunit tests are designed to test the functionality of - * extent split and conversion in ext4. - * - * Currently, ext4 can split extents in 2 ways: - * 1. By splitting the extents in the extent tree and optionally converting them - * to written or unwritten based on flags passed. - * 2. In case 1 encounters an error, ext4 instead zerooes out the unwritten - * areas of the extent and marks the complete extent written. - * - * The primary function that handles this is ext4_split_convert_extents(). - * - * We test both of the methods of split. The behavior we try to enforce is: - * 1. When passing EXT4_GET_BLOCKS_CONVERT flag to ext4_split_convert_extents(), - * the split extent should be converted to initialized. - * 2. When passing EXT4_GET_BLOCKS_CONVERT_UNWRITTEN flag to - * ext4_split_convert_extents(), the split extent should be converted to - * uninitialized. - * 3. In case we use the zeroout method, then we should correctly write zeroes - * to the unwritten areas of the extent and we should not corrupt/leak any - * data. - * - * Enforcing 1 and 2 is straight forward, we just setup a minimal inode with - * extent tree, call ext4_split_convert_extents() and check the final state of - * the extent tree. - * - * For zeroout testing, we maintain a separate buffer which represents the disk - * data corresponding to the extents. We then override ext4's zeroout functions - * to instead write zeroes to our buffer. Then, we override - * ext4_ext_insert_extent() to return -ENOSPC, which triggers the zeroout. - * Finally, we check the state of the extent tree and zeroout buffer to confirm - * everything went well. + * fs/ext4/extents.c, including extent tree initialization and validation, + * binary search and multi-level navigation, extent insertion, merging, + * splitting, tree depth growth and collapse, space removal and bigalloc + * partial cluster handling, block mapping, unwritten-to-written conversion, + * zeroout fallback, extent shifting, extent swapping, cluster mapping, + * transaction credit calculation, and fast-commit replay helpers. */ #include #include +#include +#include #include #include #include #include "ext4.h" #include "ext4_extents.h" +#include "ext4_jbd2.h" #define EXT_DATA_PBLK 100 #define EXT_DATA_LBLK 10 #define EXT_DATA_LEN 3 +#define EXT_MAX_META_BLOCKS 16 +#define EXT_META_BASE_PBLK 500 +#define EXT_ALLOC_BASE_PBLK 1000 +#define EXT_TOTAL_BLOCKS 0x100000ULL + +struct kunit_meta_block { + ext4_fsblk_t pblk; + struct buffer_head bh; + char data[4096]; + bool in_use; +}; + static struct kunit_ctx { /* - * Ext4 inode which has only 1 unwrit extent + * Ext4 inode initialized with 1 extent by default */ struct ext4_inode_info *k_ei; + /* + * Optional secondary inode (used for swap_extents tests) + */ + struct ext4_inode_info *k_ei2; /* * Represents the underlying data area (used for zeroout testing) */ char *k_data; + /* + * In-memory pool of external extent tree blocks (leaf/index blocks) + */ + struct kunit_meta_block *meta_blocks; + /* + * Mock block allocator and free tracking + */ + ext4_fsblk_t next_alloc_pblk; + unsigned int alloc_calls; + ext4_fsblk_t last_alloc_pblk; + unsigned int last_alloc_len; + int fail_alloc_err; + + unsigned int free_calls; + ext4_fsblk_t last_free_pblk; + unsigned long last_free_count; + int last_free_flags; + unsigned long total_freed_blocks; + + bool fail_getblk; } k_ctx; /* @@ -126,6 +141,31 @@ struct kunit_ext_test_param { struct kunit_ext_data_state exp_data_state[3]; }; +static unsigned long ext_dummy_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long ext_dummy_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +static const struct super_operations ext_dummy_sops = {}; + +#ifdef CONFIG_QUOTA +static qsize_t *ext_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations ext_dummy_qops = { + .get_reserved_space = ext_get_reserved_space, +}; +#endif + static int ext_init_fs_context(struct fs_context *fc) { return 0; @@ -142,34 +182,205 @@ static struct file_system_type ext_fs_type = { .kill_sb = kill_anon_super, }; +static void ext_init_mock_inode(struct ext4_inode_info *ei, + struct super_block *sb, unsigned long ino) +{ + struct inode *inode = &ei->vfs_inode; + + memset(ei, 0, sizeof(*ei)); + inode->i_sb = sb; + inode->i_ino = ino; + inode->i_mode = S_IFREG | 0644; + inode->i_blkbits = sb->s_blocksize_bits; + inode->i_flags |= S_NOQUOTA; + inode->i_mapping = &inode->i_data; + + spin_lock_init(&inode->i_lock); + i_size_ordered_init(inode); + init_rwsem(&inode->i_rwsem); + init_rwsem(&inode->i_data.invalidate_lock); + inode_state_set_raw(inode, I_DIRTY_SYNC | I_DIRTY_DATASYNC); + + ext4_es_init_tree(&ei->i_es_tree); + ext4_init_pending_tree(&ei->i_pending_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + init_rwsem(&ei->i_data_sem); + spin_lock_init(&ei->i_block_reservation_lock); + rwlock_init(&ei->i_prealloc_lock); + ei->i_prealloc_node = RB_ROOT; + ei->i_csum_seed = 0x12345678; + + ei->i_disksize = (EXT_DATA_LBLK + EXT_DATA_LEN + 10) + << sb->s_blocksize_bits; + inode->i_size = ei->i_disksize; + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); +} + +static void ext_cleanup_inode(struct inode *inode) +{ + struct ext4_inode_info *ei = EXT4_I(inode); + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct rb_node *node; + + down_write(&ei->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + up_write(&ei->i_data_sem); + + while ((node = rb_first(&ei->i_pending_tree.root)) != NULL) { + struct pending_reservation *pr; + + pr = rb_entry(node, struct pending_reservation, rb_node); + ext4_remove_pending(inode, EXT4_C2B(sbi, pr->lclu)); + } +} + static void extents_kunit_exit(struct kunit *test) { + struct block_device *bdev; struct ext4_sb_info *sbi; + struct super_block *sb; if (!k_ctx.k_ei) return; - sbi = k_ctx.k_ei->vfs_inode.i_sb->s_fs_info; + sb = k_ctx.k_ei->vfs_inode.i_sb; + sbi = sb->s_fs_info; + bdev = sb->s_bdev; + + if (k_ctx.k_ei2) { + ext_cleanup_inode(&k_ctx.k_ei2->vfs_inode); + kfree(k_ctx.k_ei2); + } + ext_cleanup_inode(&k_ctx.k_ei->vfs_inode); + + percpu_counter_destroy(&sbi->s_freeclusters_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); ext4_es_unregister_shrinker(sbi); ext4_es_destroy_stats(sbi); - deactivate_super(sbi->s_sb); + deactivate_super(sb); + + kfree(k_ctx.meta_blocks); + kfree(sbi->s_es); + kfree(bdev->bd_mapping); + kfree(bdev); kfree(sbi); kfree(k_ctx.k_ei); kfree(k_ctx.k_data); + memset(&k_ctx, 0, sizeof(k_ctx)); } static int __ext4_ext_dirty_stub(const char *where, unsigned int line, handle_t *handle, struct inode *inode, struct ext4_ext_path *path) +{ + if (path && path->p_bh) { + ext4_extent_block_csum_set_test(inode, + ext_block_hdr(path->p_bh)); + set_buffer_verified(path->p_bh); + } + return 0; +} + +static int __ext4_handle_dirty_metadata_stub(const char *where, + unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + if (bh) + set_buffer_uptodate(bh); + return 0; +} + +static int __ext4_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) { return 0; } +static struct buffer_head *ext4_ext_getblk_stub(struct inode *inode, + ext4_fsblk_t pblk, + gfp_t gfp_flags) +{ + struct kunit_meta_block *slot = NULL; + int i; + + if (k_ctx.fail_getblk || !k_ctx.meta_blocks) + return NULL; + + for (i = 0; i < EXT_MAX_META_BLOCKS; i++) { + if (k_ctx.meta_blocks[i].in_use && + k_ctx.meta_blocks[i].pblk == pblk) { + slot = &k_ctx.meta_blocks[i]; + break; + } + } + + if (!slot) { + for (i = 0; i < EXT_MAX_META_BLOCKS; i++) { + if (!k_ctx.meta_blocks[i].in_use) { + slot = &k_ctx.meta_blocks[i]; + break; + } + } + if (!slot) + return NULL; + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->pblk = pblk; + slot->bh.b_data = slot->data; + slot->bh.b_size = inode->i_sb->s_blocksize; + slot->bh.b_blocknr = pblk; + slot->bh.b_bdev = inode->i_sb->s_bdev; + atomic_set(&slot->bh.b_count, 1); + set_buffer_uptodate(&slot->bh); + set_buffer_mapped(&slot->bh); + } + + get_bh(&slot->bh); + return &slot->bh; +} + +static ext4_fsblk_t ext4_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, + int *errp) +{ + struct ext4_sb_info *sbi = EXT4_SB(ar->inode->i_sb); + ext4_fsblk_t pblk; + + k_ctx.alloc_calls++; + if (k_ctx.fail_alloc_err) { + *errp = k_ctx.fail_alloc_err; + return 0; + } + + pblk = k_ctx.next_alloc_pblk; + k_ctx.next_alloc_pblk += EXT4_C2B(sbi, ar->len); + k_ctx.last_alloc_pblk = pblk; + k_ctx.last_alloc_len = ar->len; + *errp = 0; + return pblk; +} + +static void ext4_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ + k_ctx.free_calls++; + k_ctx.last_free_pblk = block; + k_ctx.last_free_count = count; + k_ctx.last_free_flags = flags; + k_ctx.total_freed_blocks += count; +} + static struct ext4_ext_path * ext4_ext_insert_extent_stub(handle_t *handle, struct inode *inode, struct ext4_ext_path *path, struct ext4_extent *newext, int gb_flags) { + ext4_free_ext_path(path); return ERR_PTR(-ENOSPC); } @@ -230,10 +441,11 @@ static int extents_kunit_init(struct kunit *test) struct super_block *sb; struct fs_context *fc; struct ext4_sb_info *sbi = NULL; - struct kunit_ext_test_param *param = - (struct kunit_ext_test_param *)(test->param_value); int err; + memset(&k_ctx, 0, sizeof(k_ctx)); + k_ctx.next_alloc_pblk = EXT_ALLOC_BASE_PBLK; + sbi = kzalloc_obj(struct ext4_sb_info); if (sbi == NULL) return -ENOMEM; @@ -252,16 +464,76 @@ static int extents_kunit_init(struct kunit *test) sbi->s_sb = sb; sb->s_fs_info = sbi; - + sb->s_op = &ext_dummy_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &ext_dummy_qops; +#endif sb->s_blocksize = 4096; sb->s_blocksize_bits = 12; + sb->s_maxbytes = MAX_LFS_FILESIZE; + strscpy(sb->s_id, "extents_kunit", sizeof(sb->s_id)); - if (!param || !param->disable_zeroout) - sbi->s_extent_max_zeroout_kb = 32; + sb->s_bdev = kzalloc_obj(struct block_device); + if (!sb->s_bdev) { + err = -ENOMEM; + goto out_deactivate; + } + bdev_set_flag(sb->s_bdev, BD_READ_ONLY); + sb->s_bdev->bd_mapping = kzalloc_obj(struct address_space); + if (!sb->s_bdev->bd_mapping) { + err = -ENOMEM; + goto out_bdev; + } + + sbi->s_es = kzalloc_obj(struct ext4_super_block); + if (!sbi->s_es) { + err = -ENOMEM; + goto out_bdev_mapping; + } + sbi->s_es->s_first_data_block = cpu_to_le32(1); + sbi->s_es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ext4_blocks_count_set(sbi->s_es, EXT_TOTAL_BLOCKS); + set_opt(sb, ERRORS_CONT); + sbi->s_blocks_per_group = 32768; + sbi->s_clusters_per_group = 32768; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_desc_per_block = 64; + sbi->s_groups_count = 32; + sbi->s_extent_max_zeroout_kb = 32; + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + + err = percpu_counter_init(&sbi->s_freeclusters_counter, 100000, + GFP_KERNEL); + if (err) + goto out_es; + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, + GFP_KERNEL); + if (err) + goto out_freeclusters; err = ext4_es_register_shrinker(sbi); if (err) - goto out_deactivate; + goto out_dirtyclusters; + + /* + * Isolate the mock shrinker from asynchronous background reclaim. + */ + sbi->s_es_shrinker->count_objects = ext_dummy_shrinker_count; + sbi->s_es_shrinker->scan_objects = ext_dummy_shrinker_scan; + + k_ctx.meta_blocks = kcalloc(EXT_MAX_META_BLOCKS, + sizeof(struct kunit_meta_block), + GFP_KERNEL); + if (!k_ctx.meta_blocks) { + err = -ENOMEM; + goto out; + } /* setup the mock inode */ k_ctx.k_ei = kzalloc_obj(struct ext4_inode_info); @@ -271,19 +543,7 @@ static int extents_kunit_init(struct kunit *test) } ei = k_ctx.k_ei; inode = &ei->vfs_inode; - - ext4_es_init_tree(&ei->i_es_tree); - rwlock_init(&ei->i_es_lock); - INIT_LIST_HEAD(&ei->i_es_list); - ei->i_es_all_nr = 0; - ei->i_es_shk_nr = 0; - ei->i_es_shrink_lblk = 0; - - ei->i_disksize = (EXT_DATA_LBLK + EXT_DATA_LEN + 10) - << sb->s_blocksize_bits; - ei->i_flags = 0; - ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); - inode->i_sb = sb; + ext_init_mock_inode(ei, sb, 12); k_ctx.k_data = kzalloc(EXT_DATA_LEN * 4096, GFP_KERNEL); if (k_ctx.k_data == NULL) { @@ -296,9 +556,6 @@ static int extents_kunit_init(struct kunit *test) */ memset(k_ctx.k_data, 'X', EXT_DATA_LEN * 4096); - /* create a tree with depth 0 */ - eh = (struct ext4_extent_header *)k_ctx.k_ei->i_data; - /* Fill extent header */ eh = ext_inode_hdr(&k_ctx.k_ei->vfs_inode); eh->eh_depth = 0; @@ -310,25 +567,34 @@ static int extents_kunit_init(struct kunit *test) /* * add 1 extent in leaf node covering: - * - lblks: [EXT_DATA_LBLK, EXT_DATA_LBLK * + EXT_DATA_LEN) + * - lblks: [EXT_DATA_LBLK, EXT_DATA_LBLK + EXT_DATA_LEN) * - pblks: [EXT_DATA_PBLK, EXT_DATA_PBLK + EXT_DATA_LEN) */ EXT_FIRST_EXTENT(eh)->ee_block = cpu_to_le32(EXT_DATA_LBLK); EXT_FIRST_EXTENT(eh)->ee_len = cpu_to_le16(EXT_DATA_LEN); ext4_ext_store_pblock(EXT_FIRST_EXTENT(eh), EXT_DATA_PBLK); - if (!param || param->is_unwrit_at_start) - ext4_ext_mark_unwritten(EXT_FIRST_EXTENT(eh)); + ext4_ext_mark_unwritten(EXT_FIRST_EXTENT(eh)); + down_write(&ei->i_data_sem); ext4_es_insert_extent(inode, EXT_DATA_LBLK, EXT_DATA_LEN, EXT_DATA_PBLK, - ext4_ext_is_unwritten(EXT_FIRST_EXTENT(eh)) ? - EXTENT_STATUS_UNWRITTEN : - EXTENT_STATUS_WRITTEN, - 0); + EXTENT_STATUS_UNWRITTEN, 0); + up_write(&ei->i_data_sem); /* Add stubs */ kunit_activate_static_stub(test, __ext4_ext_dirty, __ext4_ext_dirty_stub); - kunit_activate_static_stub(test, ext4_ext_zeroout, ext4_ext_zeroout_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + __ext4_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + __ext4_mark_inode_dirty_stub); + kunit_activate_static_stub(test, ext4_ext_getblk, + ext4_ext_getblk_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + ext4_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + ext4_free_blocks_stub); + kunit_activate_static_stub(test, ext4_ext_zeroout, + ext4_ext_zeroout_stub); kunit_activate_static_stub(test, ext4_issue_zeroout, ext4_issue_zeroout_stub); up_write(&sb->s_umount); @@ -336,14 +602,24 @@ static int extents_kunit_init(struct kunit *test) return 0; out: - kfree(k_ctx.k_ei); - k_ctx.k_ei = NULL; - kfree(k_ctx.k_data); k_ctx.k_data = NULL; - + kfree(k_ctx.k_ei); + k_ctx.k_ei = NULL; + kfree(k_ctx.meta_blocks); + k_ctx.meta_blocks = NULL; ext4_es_unregister_shrinker(sbi); ext4_es_destroy_stats(sbi); +out_dirtyclusters: + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); +out_freeclusters: + percpu_counter_destroy(&sbi->s_freeclusters_counter); +out_es: + kfree(sbi->s_es); +out_bdev_mapping: + kfree(sb->s_bdev->bd_mapping); +out_bdev: + kfree(sb->s_bdev); out_deactivate: deactivate_locked_super(sb); kfree(sbi); @@ -396,12 +672,24 @@ static void test_split_convert(struct kunit *test) { struct ext4_ext_path *path; struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); struct ext4_extent *ex; struct ext4_map_blocks map; const struct kunit_ext_test_param *param = (const struct kunit_ext_test_param *)(test->param_value); int blkbits = inode->i_sb->s_blocksize_bits; + if (param->disable_zeroout) + EXT4_SB(inode->i_sb)->s_extent_max_zeroout_kb = 0; + + if (!param->is_unwrit_at_start) { + ext4_ext_mark_initialized(EXT_FIRST_EXTENT(eh)); + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_insert_extent(inode, EXT_DATA_LBLK, EXT_DATA_LEN, + EXT_DATA_PBLK, EXTENT_STATUS_WRITTEN, 0); + up_write(&EXT4_I(inode)->i_data_sem); + } + if (param->is_zeroout_test) /* * Force zeroout by making ext4_ext_insert_extent return ENOSPC @@ -410,6 +698,7 @@ static void test_split_convert(struct kunit *test) ext4_ext_insert_extent_stub); path = ext4_find_extent(inode, EXT_DATA_LBLK, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); ex = path->p_ext; KUNIT_EXPECT_EQ(test, EXT_DATA_LBLK, le32_to_cpu(ex->ee_block)); KUNIT_EXPECT_EQ(test, EXT_DATA_LEN, ext4_ext_get_actual_len(ex)); @@ -427,15 +716,21 @@ static void test_split_convert(struct kunit *test) case TEST_SPLIT_CONVERT: path = ext4_split_convert_extents_test(NULL, inode, &map, path, param->split_flags, NULL); + if (!IS_ERR(path)) + ext4_free_ext_path(path); break; case TEST_CREATE_BLOCKS: + ext4_free_ext_path(path); ext4_map_create_blocks_helper(test, inode, &map, param->split_flags); break; default: + ext4_free_ext_path(path); KUNIT_FAIL(test, "param->type %d not support.", param->type); + return; } path = ext4_find_extent(inode, EXT_DATA_LBLK, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); ex = path->p_ext; for (int i = 0; i < param->nr_exp_ext; i++) { @@ -498,6 +793,8 @@ static void test_split_convert(struct kunit *test) ex = ex + 1; } + ext4_free_ext_path(path); + if (!param->is_zeroout_test) return; @@ -516,8 +813,1637 @@ static void test_split_convert(struct kunit *test) "# corruption in byte range [%lld, %lld)", off, len); } +} + +/* + * Helper to reset an inode's extent tree and extent status cache to empty. + */ +static void ext_reset_tree(struct inode *inode) +{ + struct ext4_inode_info *ei = EXT4_I(inode); + + down_write(&ei->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + memset(ei->i_data, 0, sizeof(ei->i_data)); + ext4_ext_tree_init(NULL, inode); + up_write(&ei->i_data_sem); +} + +/* + * Helper to insert an extent into @inode's extent tree under i_data_sem. + */ +static int ext_insert_one(struct inode *inode, ext4_lblk_t lblk, + unsigned short len, ext4_fsblk_t pblk, + bool unwritten, int gb_flags) +{ + struct ext4_ext_path *path; + struct ext4_extent newex = {}; + + newex.ee_block = cpu_to_le32(lblk); + newex.ee_len = cpu_to_le16(len); + ext4_ext_store_pblock(&newex, pblk); + if (unwritten) + ext4_ext_mark_unwritten(&newex); + + down_write(&EXT4_I(inode)->i_data_sem); + path = ext4_find_extent(inode, lblk, NULL, EXT4_EX_NOCACHE); + if (IS_ERR(path)) { + up_write(&EXT4_I(inode)->i_data_sem); + return PTR_ERR(path); + } + path = ext4_ext_insert_extent(NULL, inode, path, &newex, + gb_flags | EXT4_EX_NOCACHE); + up_write(&EXT4_I(inode)->i_data_sem); + if (IS_ERR(path)) + return PTR_ERR(path); + + ext4_free_ext_path(path); + return 0; +} + +/* + * Verify 48-bit physical block number store and load helpers for both + * leaf extents (ext4_extent) and index entries (ext4_extent_idx). + */ +static void test_ext_pblock_48bit(struct kunit *test) +{ + struct ext4_extent ex = {}; + struct ext4_extent_idx idx = {}; + const ext4_fsblk_t pblk_48 = 0x123456789abcULL; + const ext4_fsblk_t pblk_max = 0xffffffffffffULL; + + ext4_ext_store_pblock(&ex, 0); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex), 0ULL); + + ext4_ext_store_pblock(&ex, 0xffffffffULL); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex), 0xffffffffULL); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ex.ee_start_hi), 0); + + ext4_ext_store_pblock(&ex, pblk_48); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex.ee_start_lo), 0x56789abcU); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ex.ee_start_hi), 0x1234U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex), pblk_48); + + ext4_ext_store_pblock(&ex, pblk_max); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex), pblk_max); + + ext4_idx_store_pblock(&idx, pblk_48); + KUNIT_EXPECT_EQ(test, le32_to_cpu(idx.ei_leaf_lo), 0x56789abcU); + KUNIT_EXPECT_EQ(test, le16_to_cpu(idx.ei_leaf_hi), 0x1234U); + KUNIT_EXPECT_EQ(test, ext4_idx_pblock(&idx), pblk_48); + + ext4_idx_store_pblock(&idx, pblk_max); + KUNIT_EXPECT_EQ(test, ext4_idx_pblock(&idx), pblk_max); +} + +/* + * Verify extent length encoding and unwritten bit manipulation at boundaries: + * - EXT_INIT_MAX_LEN (32768 = 0x8000) is the maximum initialized extent length + * and must NOT be treated as unwritten. + * - EXT_UNWRITTEN_MAX_LEN (32767 = 0x7fff) is the maximum unwritten extent + * length (stored on disk as 0xffff). + */ +static void test_ext_unwritten_len_encoding(struct kunit *test) +{ + struct ext4_extent ex = {}; + + ex.ee_len = cpu_to_le16(1); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 0); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), 1); + + ext4_ext_mark_unwritten(&ex); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 1); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), 1); + + ext4_ext_mark_initialized(&ex); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 0); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), 1); + + ex.ee_len = cpu_to_le16(EXT_UNWRITTEN_MAX_LEN); + ext4_ext_mark_unwritten(&ex); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 1); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), + EXT_UNWRITTEN_MAX_LEN); + + ext4_ext_mark_initialized(&ex); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 0); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), + EXT_UNWRITTEN_MAX_LEN); + + ex.ee_len = cpu_to_le16(EXT_INIT_MAX_LEN); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 0); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), EXT_INIT_MAX_LEN); +} + +/* + * Verify ext4_ext_tree_init() initializes the in-inode extent header and + * ext4_ext_check_inode() accepts valid empty and populated root headers. + */ +static void test_ext_tree_init_and_check_inode(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + + memset(k_ctx.k_ei->i_data, 0xff, sizeof(k_ctx.k_ei->i_data)); + ext4_ext_tree_init(NULL, inode); + + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_magic), + le16_to_cpu(EXT4_EXT_MAGIC)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_depth), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_max), 4); + KUNIT_EXPECT_EQ(test, le32_to_cpu(eh->eh_generation), 0U); + KUNIT_EXPECT_EQ(test, ext4_ext_check_inode(inode), 0); + + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 5, 100, false, 0), 0); + KUNIT_EXPECT_EQ(test, ext4_ext_check_inode(inode), 0); +} + +enum ext_check_corrupt_type { + CORRUPT_BAD_MAGIC, + CORRUPT_BAD_DEPTH, + CORRUPT_ZERO_MAX, + CORRUPT_EXCESS_MAX, + CORRUPT_ENTRIES_GT_MAX, + CORRUPT_EMPTY_NONROOT_INDEX, + CORRUPT_ZERO_LEN_EXTENT, + CORRUPT_LBLK_OVERFLOW, + CORRUPT_PBLK_TOO_LOW, + CORRUPT_PBLK_TOO_HIGH, + CORRUPT_UNSORTED_EXTENTS, + CORRUPT_UNSORTED_INDEXES, + CORRUPT_NONROOT_LBLK_MISMATCH, +}; + +struct ext_check_corrupt_param { + const char *desc; + enum ext_check_corrupt_type type; +}; + +static const struct ext_check_corrupt_param ext_check_corrupt_params[] = { + { "invalid eh_magic", CORRUPT_BAD_MAGIC }, + { "mismatched eh_depth", CORRUPT_BAD_DEPTH }, + { "eh_max == 0", CORRUPT_ZERO_MAX }, + { "eh_max exceeds root capacity", CORRUPT_EXCESS_MAX }, + { "eh_entries exceeds eh_max", CORRUPT_ENTRIES_GT_MAX }, + { "empty index block at depth > 0", CORRUPT_EMPTY_NONROOT_INDEX }, + { "extent with ee_len == 0", CORRUPT_ZERO_LEN_EXTENT }, + { "extent logical block 32-bit wrap-around", CORRUPT_LBLK_OVERFLOW }, + { "extent physical block <= first_data_block", CORRUPT_PBLK_TOO_LOW }, + { "extent physical block past blocks_count", CORRUPT_PBLK_TOO_HIGH }, + { "overlapping/unsorted leaf extents", CORRUPT_UNSORTED_EXTENTS }, + { "unsorted index entries", CORRUPT_UNSORTED_INDEXES }, + { "non-root leaf first ee_block != parent ei_block", + CORRUPT_NONROOT_LBLK_MISMATCH }, +}; + +static void ext_check_corrupt_get_desc(struct kunit *test, const void *p, + char *desc) +{ + const struct ext_check_corrupt_param *param = p; + + strscpy(desc, param->desc, KUNIT_PARAM_DESC_SIZE); +} + +static int ext_check_corrupt_param_init(struct kunit *test) +{ + kunit_register_params_array(test, ext_check_corrupt_params, + ARRAY_SIZE(ext_check_corrupt_params), + ext_check_corrupt_get_desc); + return 0; +} + +/* + * Verify __ext4_ext_check() detects and rejects all classes of corrupt + * extent headers, leaf extents, and index entries with -EFSCORRUPTED. + */ +static void test_ext_check_corruptions(struct kunit *test) +{ + const struct ext_check_corrupt_param *param = test->param_value; + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + struct ext4_extent_idx *ix; + struct { + struct ext4_extent_header eh; + struct ext4_extent ex; + } nonroot_leaf; + int depth = 0; + ext4_fsblk_t pblk = 0; + ext4_lblk_t lblk = 0; + int err; + + ext_reset_tree(inode); + eh->eh_entries = cpu_to_le16(1); + ex = EXT_FIRST_EXTENT(eh); + ex->ee_block = cpu_to_le32(10); + ex->ee_len = cpu_to_le16(4); + ext4_ext_store_pblock(ex, 100); + + switch (param->type) { + case CORRUPT_BAD_MAGIC: + eh->eh_magic = cpu_to_le16(0xdead); + break; + case CORRUPT_BAD_DEPTH: + eh->eh_depth = cpu_to_le16(1); + depth = 0; + break; + case CORRUPT_ZERO_MAX: + eh->eh_max = 0; + break; + case CORRUPT_EXCESS_MAX: + eh->eh_max = cpu_to_le16(10); + break; + case CORRUPT_ENTRIES_GT_MAX: + eh->eh_entries = cpu_to_le16(5); + break; + case CORRUPT_EMPTY_NONROOT_INDEX: + eh->eh_depth = cpu_to_le16(1); + eh->eh_entries = 0; + depth = 1; + break; + case CORRUPT_ZERO_LEN_EXTENT: + ex->ee_len = 0; + break; + case CORRUPT_LBLK_OVERFLOW: + ex->ee_block = cpu_to_le32(0xfffffff0U); + ex->ee_len = cpu_to_le16(32); + break; + case CORRUPT_PBLK_TOO_LOW: + ext4_ext_store_pblock(ex, 1); + break; + case CORRUPT_PBLK_TOO_HIGH: + ext4_ext_store_pblock(ex, EXT_TOTAL_BLOCKS); + break; + case CORRUPT_UNSORTED_EXTENTS: + eh->eh_entries = cpu_to_le16(2); + ex[1].ee_block = cpu_to_le32(12); + ex[1].ee_len = cpu_to_le16(4); + ext4_ext_store_pblock(&ex[1], 200); + break; + case CORRUPT_UNSORTED_INDEXES: + eh->eh_depth = cpu_to_le16(1); + eh->eh_entries = cpu_to_le16(2); + depth = 1; + ix = EXT_FIRST_INDEX(eh); + ix[0].ei_block = cpu_to_le32(20); + ext4_idx_store_pblock(&ix[0], 500); + ix[1].ei_block = cpu_to_le32(10); + ext4_idx_store_pblock(&ix[1], 501); + break; + case CORRUPT_NONROOT_LBLK_MISMATCH: + eh->eh_depth = cpu_to_le16(1); + memset(&nonroot_leaf, 0, sizeof(nonroot_leaf)); + nonroot_leaf.eh.eh_magic = EXT4_EXT_MAGIC; + nonroot_leaf.eh.eh_depth = 0; + nonroot_leaf.eh.eh_entries = cpu_to_le16(1); + nonroot_leaf.eh.eh_max = cpu_to_le16(340); + nonroot_leaf.ex.ee_block = cpu_to_le32(10); + nonroot_leaf.ex.ee_len = cpu_to_le16(4); + ext4_ext_store_pblock(&nonroot_leaf.ex, 100); + eh = &nonroot_leaf.eh; + depth = 0; + pblk = 500; + lblk = 20; + break; + } + + /* Suppress __ext4_error_inode() log spam during expected failure */ + set_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + err = ext4_ext_check_test(inode, eh, depth, pblk, lblk); + clear_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); +} + +/* + * Verify metadata checksum calculation and verification on external extent + * tree blocks when EXT4_FEATURE_RO_COMPAT_METADATA_CSUM is enabled. + */ +static void test_ext_block_csum_verify(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct buffer_head *bh; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + struct ext4_extent_tail *et; + int max_entries; + int err; + + ext_reset_tree(inode); + ext_inode_hdr(inode)->eh_depth = cpu_to_le16(1); + ext4_set_feature_metadata_csum(inode->i_sb); + bh = ext4_ext_getblk_stub(inode, EXT_META_BASE_PBLK, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bh); + + max_entries = (inode->i_sb->s_blocksize - + sizeof(struct ext4_extent_header) - + sizeof(struct ext4_extent_tail)) / + sizeof(struct ext4_extent); + + eh = ext_block_hdr(bh); + eh->eh_magic = EXT4_EXT_MAGIC; + eh->eh_depth = 0; + eh->eh_entries = cpu_to_le16(1); + eh->eh_max = cpu_to_le16(max_entries); + + ex = EXT_FIRST_EXTENT(eh); + ex->ee_block = cpu_to_le32(10); + ex->ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(ex, 100); + + ext4_extent_block_csum_set_test(inode, eh); + err = ext4_ext_check_test(inode, eh, 0, EXT_META_BASE_PBLK, 10); + KUNIT_EXPECT_EQ(test, err, 0); + + /* Flip a bit in the tail checksum and verify -EFSBADCRC */ + et = find_ext4_extent_tail(eh); + et->et_checksum ^= cpu_to_le32(0x1); + + set_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + err = ext4_ext_check_test(inode, eh, 0, EXT_META_BASE_PBLK, 10); + clear_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + + KUNIT_EXPECT_EQ(test, err, -EFSBADCRC); + brelse(bh); +} + +/* + * Verify ext4_find_extent() binary search on an empty tree and a multi-extent + * root leaf, as well as extent status caching vs EXT4_EX_NOCACHE. + */ +static void test_find_extent_root_binsearch(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_ext_path *path; + struct extent_status es; + + ext_reset_tree(inode); + + /* Empty tree returns NULL p_ext */ + path = ext4_find_extent(inode, 10, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_PTR_EQ(test, path[0].p_ext, NULL); + ext4_free_ext_path(path); + + /* Populate 3 separated extents: [10, 15), [20, 25), [30, 35) */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 5, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 20, 5, 200, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 30, 5, 300, false, 0), 0); + + /* Lookup before first extent (lblk 5) -> points to first extent */ + path = ext4_find_extent(inode, 5, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_ASSERT_NOT_NULL(test, path[0].p_ext); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[0].p_ext->ee_block), 10U); + ext4_free_ext_path(path); + + /* Lookup inside first extent (lblk 12) */ + path = ext4_find_extent(inode, 12, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[0].p_ext->ee_block), 10U); + ext4_free_ext_path(path); + + /* Lookup in hole between 1st and 2nd extent (lblk 17) -> 1st extent */ + path = ext4_find_extent(inode, 17, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[0].p_ext->ee_block), 10U); + ext4_free_ext_path(path); + + /* Lookup exact start of 2nd extent (lblk 20) */ + path = ext4_find_extent(inode, 20, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[0].p_ext->ee_block), 20U); + ext4_free_ext_path(path); + + /* Lookup past last extent (lblk 50) -> 3rd extent */ + path = ext4_find_extent(inode, 50, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[0].p_ext->ee_block), 30U); + ext4_free_ext_path(path); + + /* EXT4_EX_NOCACHE left i_es_tree empty */ + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), + 0); + + /* Lookup without EXT4_EX_NOCACHE populates extents and holes in es */ + down_read(&EXT4_I(inode)->i_data_sem); + path = ext4_find_extent(inode, 20, NULL, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + ext4_free_ext_path(path); + + /* + * Verify inter-extent hole [15, 20) and extents are cached in es + * (ext4_cache_extents only caches holes where prev != 0). + */ + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 5, NULL, &es, NULL), + 0); + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 17, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_hole(&es)); + KUNIT_EXPECT_EQ(test, es.es_lblk, 15U); + KUNIT_EXPECT_EQ(test, es.es_len, 5U); + + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 22, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_written(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 200ULL); +} + +/* + * Helper to construct a depth-1 tree with two external leaf blocks: + * Leaf 0 (pblk 500): [10, 15) -> 1000 (written), [20, 25) -> 1100 (written) + * Leaf 1 (pblk 501): [40, 45) -> 2000 (unwritten), [50, 55) -> 2100 (written) + */ +static void setup_depth1_two_leaf_tree(struct kunit *test, struct inode *inode) +{ + struct ext4_extent_header *root_eh = ext_inode_hdr(inode); + struct ext4_extent_idx *idx; + struct buffer_head *bh0, *bh1; + struct ext4_extent_header *eh0, *eh1; + struct ext4_extent *ex; + int max_leaf = (inode->i_sb->s_blocksize - + sizeof(struct ext4_extent_header)) / + sizeof(struct ext4_extent); + + ext_reset_tree(inode); + + root_eh->eh_depth = cpu_to_le16(1); + root_eh->eh_entries = cpu_to_le16(2); + root_eh->eh_max = cpu_to_le16(ext4_ext_space_root_idx_test(inode, 0)); + + idx = EXT_FIRST_INDEX(root_eh); + idx[0].ei_block = cpu_to_le32(10); + ext4_idx_store_pblock(&idx[0], EXT_META_BASE_PBLK); + idx[1].ei_block = cpu_to_le32(40); + ext4_idx_store_pblock(&idx[1], EXT_META_BASE_PBLK + 1); + + bh0 = ext4_ext_getblk_stub(inode, EXT_META_BASE_PBLK, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bh0); + eh0 = ext_block_hdr(bh0); + eh0->eh_magic = EXT4_EXT_MAGIC; + eh0->eh_depth = 0; + eh0->eh_entries = cpu_to_le16(2); + eh0->eh_max = cpu_to_le16(max_leaf); + ex = EXT_FIRST_EXTENT(eh0); + ex[0].ee_block = cpu_to_le32(10); + ex[0].ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex[0], 1000); + ex[1].ee_block = cpu_to_le32(20); + ex[1].ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex[1], 1100); + brelse(bh0); + + bh1 = ext4_ext_getblk_stub(inode, EXT_META_BASE_PBLK + 1, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bh1); + eh1 = ext_block_hdr(bh1); + eh1->eh_magic = EXT4_EXT_MAGIC; + eh1->eh_depth = 0; + eh1->eh_entries = cpu_to_le16(2); + eh1->eh_max = cpu_to_le16(max_leaf); + ex = EXT_FIRST_EXTENT(eh1); + ex[0].ee_block = cpu_to_le32(40); + ex[0].ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex[0], 2000); + ext4_ext_mark_unwritten(&ex[0]); + ex[1].ee_block = cpu_to_le32(50); + ex[1].ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex[1], 2100); + brelse(bh1); +} + +/* + * Verify multi-level (depth 1) extent lookup and tree navigation helpers: + * ext4_ext_next_allocated_block(), ext4_ext_next_leaf_block(), + * ext4_ext_search_left(), and ext4_ext_search_right() across leaf boundaries. + */ +static void test_find_extent_multilevel_and_navigation(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_ext_path *path; + struct ext4_extent ret_ex; + ext4_lblk_t logical; + ext4_fsblk_t phys; + int ret; + + setup_depth1_two_leaf_tree(test, inode); + + /* Lookup first extent [10, 15) in leaf 0 */ + path = ext4_find_extent(inode, 10, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, path->p_depth, 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_next_allocated_block(path), 20U); + KUNIT_EXPECT_EQ(test, ext4_ext_next_leaf_block_test(path), 40U); + ext4_free_ext_path(path); + + /* + * Lookup lblk 30 (in hole between leaf 0 and leaf 1): + * path[1].p_ext points to [20, 25) (last extent in leaf 0). + */ + path = ext4_find_extent(inode, 30, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 20U); + KUNIT_EXPECT_EQ(test, ext4_ext_next_allocated_block(path), 40U); + + /* Search left from lblk 30 finds last block of [20, 25) -> 24 @ 1104 */ + logical = 30; + ret = ext4_ext_search_left_test(inode, path, &logical, &phys); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, logical, 24U); + KUNIT_EXPECT_EQ(test, phys, 1104ULL); + + /* Search right from lblk 30 crosses into leaf 1 -> [40, 45) @ 2000 */ + logical = 30; + ret = ext4_ext_search_right_test(inode, path, &logical, &phys, &ret_ex, + EXT4_EX_NOCACHE); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, logical, 40U); + KUNIT_EXPECT_EQ(test, phys, 2000ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ret_ex.ee_block), 40U); + ext4_free_ext_path(path); + + /* Lookup last extent [50, 55) in leaf 1 */ + path = ext4_find_extent(inode, 52, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 50U); + KUNIT_EXPECT_EQ(test, ext4_ext_next_allocated_block(path), + EXT_MAX_BLOCKS); + KUNIT_EXPECT_EQ(test, ext4_ext_next_leaf_block_test(path), + EXT_MAX_BLOCKS); + ext4_free_ext_path(path); +} + +/* + * Verify ext4_ext_precache() walks all leaf blocks of a multi-level extent + * tree, caches all extents and holes into the extent status tree, and sets + * EXT4_STATE_EXT_PRECACHED. + */ +static void test_ext_precache(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct extent_status es; + int err; + + setup_depth1_two_leaf_tree(test, inode); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, + EXT4_STATE_EXT_PRECACHED)); + + err = ext4_ext_precache(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(inode, + EXT4_STATE_EXT_PRECACHED)); + + /* Verify cached inter-extent hole [15, 20) and extents from both leaves */ + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 17, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_hole(&es)); + KUNIT_EXPECT_EQ(test, es.es_lblk, 15U); + KUNIT_EXPECT_EQ(test, es.es_len, 5U); + + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_written(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 1000ULL); + + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 40, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_unwritten(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 2000ULL); + + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 50, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_written(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 2100ULL); +} + +/* + * Verify ext4_can_extents_be_merged() rules for written/unwritten state, + * logical and physical contiguity, and maximum length limits. + */ +static void test_can_extents_be_merged(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent ex1 = {}, ex2 = {}; + + /* Contiguous written extents [10, 15) @ 100 and [15, 20) @ 105 */ + ex1.ee_block = cpu_to_le32(10); + ex1.ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex1, 100); + ex2.ee_block = cpu_to_le32(15); + ex2.ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex2, 105); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 1); + + /* Mismatched written vs unwritten cannot merge */ + ext4_ext_mark_unwritten(&ex2); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 0); + + /* Both unwritten and contiguous can merge */ + ext4_ext_mark_unwritten(&ex1); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 1); + + /* Non-contiguous physical blocks cannot merge */ + ext4_ext_mark_initialized(&ex1); + ext4_ext_mark_initialized(&ex2); + ext4_ext_store_pblock(&ex2, 200); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 0); + + /* Non-contiguous logical blocks cannot merge */ + ext4_ext_store_pblock(&ex2, 105); + ex2.ee_block = cpu_to_le32(16); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 0); + + /* Written max length boundary (EXT_INIT_MAX_LEN = 32768) */ + ex1.ee_block = cpu_to_le32(0); + ex1.ee_len = cpu_to_le16(32760); + ext4_ext_store_pblock(&ex1, 100); + ex2.ee_block = cpu_to_le32(32760); + ex2.ee_len = cpu_to_le16(8); + ext4_ext_store_pblock(&ex2, 100 + 32760); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 1); + ex2.ee_len = cpu_to_le16(9); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 0); + + /* Unwritten max length boundary (EXT_UNWRITTEN_MAX_LEN = 32767) */ + ex1.ee_len = cpu_to_le16(32760); + ext4_ext_mark_unwritten(&ex1); + ex2.ee_len = cpu_to_le16(7); + ext4_ext_mark_unwritten(&ex2); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 1); + ex2.ee_len = cpu_to_le16(8); + ext4_ext_mark_unwritten(&ex2); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 0); +} + +/* + * Verify ext4_ext_insert_extent() appending, prepending, 3-way bridge merging, + * and EXT4_GET_BLOCKS_SPLIT_NOMERGE suppression. + */ +static void test_insert_extent_merge_and_nomerge(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + + ext_reset_tree(inode); + + /* Insert [10, 15) @ 100 and [20, 25) @ 110 */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 5, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 20, 5, 110, false, 0), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); + + /* Append [15, 18) @ 105 -> merges with [10, 15) into [10, 18) */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 15, 3, 105, false, 0), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 8); + + /* Insert [18, 20) @ 108 -> bridges [10, 18) and [20, 25) into [10, 25) */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 18, 2, 108, false, 0), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 15); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[0]), 100ULL); + + /* Insert contiguous [25, 30) @ 115 with SPLIT_NOMERGE -> stays separate */ + KUNIT_ASSERT_EQ(test, + ext_insert_one(inode, 25, 5, 115, false, + EXT4_GET_BLOCKS_SPLIT_NOMERGE), + 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); +} + +/* + * Verify tree growth (depth 0 -> 1 via ext4_ext_grow_indepth), parent index + * update when inserting a new lowest lblk (ext4_ext_correct_indexes), and + * tree collapse back into the inode root (depth 1 -> 0 via + * ext4_ext_try_to_merge_up) when merging reduces leaf entries to <= 4. + */ +static void test_insert_extent_grow_and_merge_up(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + + ext_reset_tree(inode); + + /* + * Insert 4 non-contiguous extents that fill the root leaf (eh_max = 4): + * [10, 12) @ 100, [14, 16) @ 104, [18, 20) @ 108, [22, 24) @ 112. + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 2, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 14, 2, 104, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 18, 2, 108, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 22, 2, 112, false, 0), 0); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 4); + + /* + * Insert 5th extent [26, 28) @ 116: triggers ext4_ext_grow_indepth(), + * moving the leaf to a newly allocated external block and increasing + * tree depth to 1. + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 26, 2, 116, false, 0), 0); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)->ei_block), 10U); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 1U); + + /* + * Prepend [8, 10) @ 98 to [10, 12) @ 100: modifies first extent in the + * leaf and triggers ext4_ext_correct_indexes(), updating root ei_block + * from 10 to 8. + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 8, 2, 98, false, 0), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)->ei_block), 8U); + + /* + * Bridge two gaps ([12, 14) @ 102 and [16, 18) @ 106): leaf entries + * shrink from 5 -> 4 -> 3. Once <= 4 (max_root), ext4_ext_try_to_merge_up() + * copies the extents back into the inode root and frees the leaf block! + */ + k_ctx.free_calls = 0; + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 12, 2, 102, false, 0), 0); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 4); + KUNIT_EXPECT_EQ(test, k_ctx.free_calls, 1U); + + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 16, 2, 106, false, 0), 0); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 8U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 12); +} + +/* + * Verify ext4_ext_split() at depth 1 both when splitting a full leaf in the + * middle (moving tail extents to a newly allocated leaf block) and when + * appending past the end of a full leaf (m == 0). + */ +static void test_insert_extent_leaf_split(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_ext_path *path; + int i; + + ext_reset_tree(inode); + + /* + * Insert 340 non-contiguous extents [i * 4, i * 4 + 2) @ 2000 + i * 4 + * to grow from depth 0 to depth 1 and completely fill the external + * 4096-byte leaf block (eh_max = 340). + */ + for (i = 0; i < 340; i++) { + KUNIT_ASSERT_EQ_MSG(test, + ext_insert_one(inode, i * 4, 2, + 2000 + i * 4, false, 0), + 0, "i=%d", i); + } + KUNIT_EXPECT_EQ(test, ext_depth(inode), 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + + /* + * Insert [402, 403) @ 9000 in the middle of the full leaf between + * [400, 402) and [404, 406): triggers ext4_ext_split() with m = 239, + * moving [404..1358) into a newly allocated second leaf block. + */ + k_ctx.alloc_calls = 0; + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 402, 1, 9000, false, 0), 0); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 1U); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)[0].ei_block), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)[1].ei_block), + 404U); + KUNIT_EXPECT_EQ(test, ext4_ext_check_inode(inode), 0); + + path = ext4_find_extent(inode, 402, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(path[1].p_hdr->eh_entries), 102); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 402U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[1].p_ext), 9000ULL); + ext4_free_ext_path(path); + + path = ext4_find_extent(inode, 404, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(path[1].p_hdr->eh_entries), 239); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 404U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[1].p_ext), 2404ULL); + ext4_free_ext_path(path); + + /* + * Fill the second leaf to capacity (239 + 101 = 340 entries), then + * append [1764, 1766) @ 3764 past its end to exercise ext4_ext_split() + * with m == 0 (adding a new leaf without moving existing entries). + */ + for (i = 340; i < 441; i++) { + KUNIT_ASSERT_EQ_MSG(test, + ext_insert_one(inode, i * 4, 2, + 2000 + i * 4, false, 0), + 0, "i=%d", i); + } + k_ctx.alloc_calls = 0; + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 1764, 2, 3764, false, 0), + 0); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 1U); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)[2].ei_block), + 1764U); + + path = ext4_find_extent(inode, 1764, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(path[1].p_hdr->eh_entries), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 1764U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[1].p_ext), 3764ULL); + ext4_free_ext_path(path); +} + +/* + * Verify multi-level tree growth from depth 1 -> 2 followed by leaf split + * (ext4_ext_create_new_leaf repeat loop), and intermediate index block + * splitting in ext4_ext_split() when both leaf and depth-1 index are full. + */ +static void test_insert_extent_index_split(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent_idx *idx; + struct ext4_ext_path *path; + struct buffer_head *bh; + int i; + + ext_reset_tree(inode); + + /* + * Build a full depth-1 root index (eh_entries = eh_max = 4) pointing + * to 4 full leaf blocks (eh_entries = eh_max = 2). + */ + eh->eh_depth = cpu_to_le16(1); + eh->eh_entries = cpu_to_le16(4); + eh->eh_max = cpu_to_le16(ext4_ext_space_root_idx_test(inode, 0)); + idx = EXT_FIRST_INDEX(eh); + + for (i = 0; i < 4; i++) { + struct ext4_extent_header *leaf_eh; + struct ext4_extent *ex; + ext4_lblk_t lblk = 10 + i * 10; + + idx[i].ei_block = cpu_to_le32(lblk); + ext4_idx_store_pblock(&idx[i], EXT_META_BASE_PBLK + i); + + bh = ext4_ext_getblk_stub(inode, EXT_META_BASE_PBLK + i, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bh); + leaf_eh = ext_block_hdr(bh); + leaf_eh->eh_magic = EXT4_EXT_MAGIC; + leaf_eh->eh_depth = 0; + leaf_eh->eh_entries = cpu_to_le16(2); + leaf_eh->eh_max = cpu_to_le16(2); + ex = EXT_FIRST_EXTENT(leaf_eh); + ex[0].ee_block = cpu_to_le32(lblk); + ex[0].ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(&ex[0], 2000 + i * 10); + ex[1].ee_block = cpu_to_le32(lblk + 4); + ex[1].ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(&ex[1], 2004 + i * 10); + brelse(bh); + } + + /* + * Inserting [48, 50) @ 2038 finds both leaf 3 and the root index full: + * ext4_ext_grow_indepth() grows depth 1 -> 2, and the repeat loop in + * ext4_ext_create_new_leaf() calls ext4_ext_split() at depth 1. + */ + k_ctx.alloc_calls = 0; + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 48, 2, 2038, false, 0), 0); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 2U); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 2); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + + /* + * Clamp the depth-1 index block's eh_max to its current 5 entries so + * inserting [12, 13) @ 9000 into full leaf 0 splits both leaf 0 and + * the intermediate depth-1 index block (depth = 2, at = 0, k = 1). + */ + bh = ext4_ext_getblk_stub(inode, ext4_idx_pblock(EXT_FIRST_INDEX(eh)), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_ASSERT_EQ(test, le16_to_cpu(ext_block_hdr(bh)->eh_entries), 5); + ext_block_hdr(bh)->eh_max = cpu_to_le16(5); + brelse(bh); + + k_ctx.alloc_calls = 0; + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 12, 1, 9000, false, 0), 0); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 2U); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 2); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)[0].ei_block), + 10U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)[1].ei_block), + 14U); + KUNIT_EXPECT_EQ(test, ext4_ext_check_inode(inode), 0); + + path = ext4_find_extent(inode, 12, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, path->p_depth, 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[2].p_ext->ee_block), 12U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[2].p_ext), 9000ULL); + ext4_free_ext_path(path); + + path = ext4_find_extent(inode, 14, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, path->p_depth, 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[2].p_ext->ee_block), 14U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[2].p_ext), 2004ULL); + ext4_free_ext_path(path); + + path = ext4_find_extent(inode, 48, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, path->p_depth, 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[2].p_ext->ee_block), 48U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[2].p_ext), 2038ULL); + ext4_free_ext_path(path); +} + +/* + * Verify ext4_ext_remove_space() for middle-of-extent hole punching, full + * extent removal with left-scooting, and ext4_ext_truncate() tail removal. + */ +static void test_remove_space_tail_and_hole_punch(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + int err; + + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 10, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 30, 10, 200, false, 0), 0); + + /* + * Punch hole [12, 17] inside [10, 20): splits [10, 20) into [10, 12) + * and [18, 20), leaving 3 extents total. + */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_remove_space(inode, 12, 17); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 18U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[1]), 2); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[1]), 108ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[2].ee_block), 30U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[2]), 10); + + /* + * Punch out the entire middle extent [18, 19]: scoots [30, 40) into + * slot 1 and reduces eh_entries to 2. + */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_remove_space(inode, 18, 19); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 30U); + + /* + * Truncate file to 11 blocks (i_size = 11 * 4096): removes [30, 40) + * and trims [10, 12) down to [10, 11). + */ + inode->i_size = 11ULL << inode->i_sb->s_blocksize_bits; + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_truncate(NULL, inode); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 1); +} + +/* + * Verify ext4_ext_remove_space() on a depth-1 tree removes all leaf extents, + * removes empty index entries via ext4_ext_rm_idx(), frees the leaf metadata + * blocks, and resets the root header to eh_depth == 0. + */ +static void test_remove_space_multilevel_collapse(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + int err; + + setup_depth1_two_leaf_tree(test, inode); + k_ctx.free_calls = 0; + k_ctx.total_freed_blocks = 0; + + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_remove_space(inode, 0, EXT_MAX_BLOCKS - 1); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_max), 4); + /* 4 data extents (5 blocks each = 20) + 2 leaf metadata blocks = 22 */ + KUNIT_EXPECT_EQ(test, k_ctx.total_freed_blocks, 22UL); +} + +/* + * Verify bigalloc partial cluster handling in ext4_ext_remove_space(): + * 1. When a cluster is shared with a remaining extent (state == nofree), + * the physical cluster is not freed. + * 2. When the entire unaligned extent is removed and has a pending reservation + * in i_pending_tree, the cluster is freed with RERESERVE_CLUSTER and + * ext4_rereserve_cluster() re-increments i_reserved_data_blocks and removes + * the pending reservation. + */ +static void test_remove_space_bigalloc_partial_cluster(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct ext4_inode_info *ei = EXT4_I(inode); + int err; + + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + + /* + * Case 1: [0, 2) @ 100 and [2, 4) @ 102 share physical cluster 25 + * (blocks 100..103). Punching [0, 1] must NOT free cluster 25. + */ + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, + ext_insert_one(inode, 0, 2, 100, false, + EXT4_GET_BLOCKS_SPLIT_NOMERGE), + 0); + KUNIT_ASSERT_EQ(test, + ext_insert_one(inode, 2, 2, 102, false, + EXT4_GET_BLOCKS_SPLIT_NOMERGE), + 0); + + k_ctx.free_calls = 0; + k_ctx.total_freed_blocks = 0; + down_write(&ei->i_data_sem); + err = ext4_ext_remove_space(inode, 0, 1); + up_write(&ei->i_data_sem); + KUNIT_ASSERT_EQ(test, err, 0); + /* + * ext4_remove_blocks() is called with NOFREE_FIRST_CLUSTER | + * NOFREE_LAST_CLUSTER, and partial cluster 25 is marked nofree. + */ + KUNIT_EXPECT_EQ(test, k_ctx.free_calls, 1U); + KUNIT_EXPECT_TRUE(test, + (k_ctx.last_free_flags & + EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) != 0); + + /* + * Case 2: Single unaligned extent [1, 3) @ 101 in cluster 0 (pclu 25) + * with a pending reservation on cluster 0. Truncating from 1 frees + * cluster 25 with RERESERVE_CLUSTER and calls ext4_rereserve_cluster(). + */ + ext_reset_tree(inode); + set_opt(inode->i_sb, DELALLOC); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 1, 2, 101, true, 0), 0); + + down_write(&ei->i_data_sem); + /* Insert delayed extent at lblk 0 in already-allocated cluster 0 */ + ext4_es_insert_delayed_extent(inode, 0, 1, true, false); + up_write(&ei->i_data_sem); + KUNIT_ASSERT_TRUE(test, ext4_is_pending(inode, 0)); + + ei->i_reserved_data_blocks = 0; + k_ctx.free_calls = 0; + down_write(&ei->i_data_sem); + err = ext4_ext_remove_space(inode, 1, EXT_MAX_BLOCKS - 1); + up_write(&ei->i_data_sem); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, k_ctx.last_free_pblk, 100ULL); + KUNIT_EXPECT_EQ(test, k_ctx.last_free_count, 4UL); + KUNIT_EXPECT_TRUE(test, + (k_ctx.last_free_flags & + EXT4_FREE_BLOCKS_RERESERVE_CLUSTER) != 0); + KUNIT_EXPECT_EQ(test, ei->i_reserved_data_blocks, 1U); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 0)); +} + +/* + * Verify ext4_ext_map_blocks() hole lookup, delayed-extent hole truncation + * (ext4_ext_determine_insert_hole), and EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF. + */ +static void test_map_blocks_lookup_hole_and_query_last_in_leaf(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_map_blocks map = {}; + int ret; + + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 5, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 20, 5, 200, false, 0), 0); + + /* Hole lookup at [2, 22) returns 0 and trims m_len to [2, 10) (len 8) */ + map.m_lblk = 2; + map.m_len = 20; + map.m_flags = 0; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_pblk, 0ULL); + KUNIT_EXPECT_EQ(test, map.m_len, 8U); + + /* + * Insert a delayed extent at [5, 7) in the es tree: hole lookup at + * [2, 22) must stop at the delayed extent -> [2, 5) (len 3). + */ + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + ext4_es_insert_delayed_extent(inode, 5, 2, false, false); + up_write(&EXT4_I(inode)->i_data_sem); + + map.m_lblk = 2; + map.m_len = 20; + map.m_flags = 0; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_EX_NOCACHE); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_len, 3U); + + /* QUERY_LAST_IN_LEAF on first extent [10, 15) -> flag NOT set */ + map.m_lblk = 10; + map.m_len = 5; + map.m_flags = 0; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, + EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_FALSE(test, + (map.m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF) != 0); + + /* QUERY_LAST_IN_LEAF on last extent [20, 25) -> flag IS set */ + map.m_lblk = 20; + map.m_len = 5; + map.m_flags = 0; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, + EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_TRUE(test, + (map.m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF) != 0); +} + +/* + * Verify ext4_ext_map_blocks() block allocation with overlap clamping + * (ext4_ext_check_overlap) and freeing of newly allocated blocks when + * ext4_ext_insert_extent() fails with -ENOSPC. + */ +static void test_map_blocks_alloc_overlap_and_enospc(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_map_blocks map = {}; + int ret; + + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 15, 5, 200, false, 0), 0); + + /* + * Request allocation for [10, 20) (len 10): ext4_ext_check_overlap() + * clamps the allocation to [10, 15) (len 5) to avoid overlapping [15, 20). + */ + k_ctx.alloc_calls = 0; + map.m_lblk = 10; + map.m_len = 10; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_EQ(test, map.m_len, 5U); + KUNIT_EXPECT_EQ(test, map.m_pblk, EXT_ALLOC_BASE_PBLK); + KUNIT_EXPECT_TRUE(test, + (map.m_flags & (EXT4_MAP_NEW | EXT4_MAP_MAPPED)) == + (EXT4_MAP_NEW | EXT4_MAP_MAPPED)); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 1U); + KUNIT_EXPECT_EQ(test, k_ctx.last_alloc_len, 5U); + + /* + * Force ext4_ext_insert_extent() to return -ENOSPC and verify that + * ext4_ext_map_blocks() frees the newly allocated blocks. + */ + kunit_activate_static_stub(test, ext4_ext_insert_extent, + ext4_ext_insert_extent_stub); + k_ctx.free_calls = 0; + map.m_lblk = 30; + map.m_len = 4; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, + EXT4_GET_BLOCKS_CREATE | + EXT4_GET_BLOCKS_DELALLOC_RESERVE); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_EQ(test, k_ctx.free_calls, 1U); + KUNIT_EXPECT_EQ(test, k_ctx.last_free_pblk, k_ctx.last_alloc_pblk); + KUNIT_EXPECT_EQ(test, k_ctx.last_free_count, 4UL); + KUNIT_EXPECT_EQ(test, k_ctx.last_free_flags, + EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); +} + +/* + * Verify ext4_ext_convert_to_initialized() fastpath block transfers to + * abutting left (ex - 1) and right (ex + 1) initialized neighbors without + * splitting into new extent entries. + */ +static void test_convert_to_initialized_abut_neighbors(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + struct ext4_map_blocks map = {}; + int ret; + + EXT4_SB(inode->i_sb)->s_extent_max_zeroout_kb = 0; + ext_reset_tree(inode); + + /* + * Setup: [10, 12) @ 100 (written), [12, 16) @ 102 (unwritten), + * [16, 18) @ 106 (written). + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 2, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 12, 4, 102, true, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 16, 2, 106, false, 0), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + /* + * Convert head of unwritten extent [12, 14): transfers 2 blocks to + * left neighbor [10, 12) -> [10, 14) written, [14, 16) unwritten. + */ + map.m_lblk = 12; + map.m_len = 2; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 4); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex[0]), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 14U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[1]), 2); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex[1]), 1); + + /* + * Convert tail of unwritten extent [15, 16): transfers 1 block to + * right neighbor [16, 18) -> [14, 15) unwritten, [15, 18) written. + * Drop stale unwritten extent status entries cached during the first + * ext4_ext_map_blocks() call (normally updated by ext4_map_blocks()). + */ + map.m_lblk = 15; + map.m_len = 1; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 14U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[1]), 1); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex[1]), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[2].ee_block), 15U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[2]), 3); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[2]), 105ULL); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex[2]), 0); +} + +/* + * Verify bigalloc get_implied_cluster_alloc() in ext4_ext_map_blocks() when + * an existing extent to the left or right already maps the same logical + * cluster, avoiding a duplicate physical cluster allocation. + */ +static void test_map_blocks_bigalloc_implied_cluster(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct ext4_map_blocks map = {}; + int ret; + + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + + /* + * Case 1: Left extent [8, 9) @ 100 in logical cluster 2 (lblks 8..11). + * Allocating [10, 12) reuses physical cluster 25 (pblks 102..103) + * without calling ext4_mb_new_blocks(). + */ + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 8, 1, 100, false, 0), 0); + + k_ctx.alloc_calls = 0; + map.m_lblk = 10; + map.m_len = 2; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, map.m_pblk, 102ULL); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 0U); + + /* + * Case 2: Right extent [10, 12) @ 102 in logical cluster 2 (lblks 8..11). + * Allocating [8, 10) searches right, finds [10, 12), and reuses + * physical cluster 25 (pblks 100..101) without calling ext4_mb_new_blocks(). + */ + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 2, 102, false, 0), 0); + + k_ctx.alloc_calls = 0; + map.m_lblk = 8; + map.m_len = 2; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, map.m_pblk, 100ULL); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 0U); +} + +/* + * Verify ext4_ext_shift_extents() for SHIFT_LEFT (collapse range) with + * neighbor merging, SHIFT_RIGHT (insert range), and -EINVAL boundary checks. + */ +static void test_ext_shift_extents(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + int err; + + ext_reset_tree(inode); + /* [10, 15) @ 100 and [20, 25) @ 105 (physically contiguous!) */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 5, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 20, 5, 105, false, 0), 0); + + /* Shifting [20, 25) left by 6 overlaps [10, 15) -> -EINVAL */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_shift_extents_test(inode, NULL, 20, 6, SHIFT_LEFT); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, err, -EINVAL); + + /* Shifting [20, 25) left by 5 merges with [10, 15) into [10, 20) @ 100 */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_shift_extents_test(inode, NULL, 20, 5, SHIFT_LEFT); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 10); + + /* Shifting [10, 20) right by 4 moves it to [14, 24) @ 100 */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_shift_extents_test(inode, NULL, 10, 4, SHIFT_RIGHT); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 14U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 10); + + /* Shifting right past EXT_MAX_BLOCKS -> -EINVAL */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_shift_extents_test(inode, NULL, 14, EXT_MAX_BLOCKS, + SHIFT_RIGHT); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, err, -EINVAL); +} + +/* + * Verify ext4_swap_extents() splits unaligned boundaries on both inodes, + * swaps physical block mappings for the requested subrange, and marks + * the donor inode's swapped extent unwritten when requested. + */ +static void test_swap_extents(struct kunit *test) +{ + struct inode *inode1 = &k_ctx.k_ei->vfs_inode; + struct inode *inode2; + struct ext4_extent_header *eh1, *eh2; + struct ext4_extent *ex1, *ex2; + int replaced, err = 0; + + k_ctx.k_ei2 = kzalloc_obj(struct ext4_inode_info); + KUNIT_ASSERT_NOT_NULL(test, k_ctx.k_ei2); + ext_init_mock_inode(k_ctx.k_ei2, inode1->i_sb, 13); + inode2 = &k_ctx.k_ei2->vfs_inode; + + ext_reset_tree(inode1); + ext_reset_tree(inode2); + + /* inode1: [10, 20) @ 100; inode2: [10, 20) @ 200 */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode1, 10, 10, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode2, 10, 10, 200, false, 0), 0); + + lock_two_nondirectories(inode1, inode2); + ext4_double_down_write_data_sem(inode1, inode2); + + replaced = ext4_swap_extents(NULL, inode1, inode2, 12, 12, 5, 1, &err); + + ext4_double_up_write_data_sem(inode1, inode2); + unlock_two_nondirectories(inode1, inode2); + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, replaced, 5); + + eh1 = ext_inode_hdr(inode1); + eh2 = ext_inode_hdr(inode2); + KUNIT_ASSERT_EQ(test, le16_to_cpu(eh1->eh_entries), 3); + KUNIT_ASSERT_EQ(test, le16_to_cpu(eh2->eh_entries), 3); + + ex1 = EXT_FIRST_EXTENT(eh1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex1[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex1[0]), 100ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex1[1].ee_block), 12U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex1[1]), 5); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex1[1]), 202ULL); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex1[1]), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex1[2].ee_block), 17U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex1[2]), 107ULL); + + ex2 = EXT_FIRST_EXTENT(eh2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex2[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex2[0]), 200ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex2[1].ee_block), 12U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex2[1]), 5); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex2[1]), 102ULL); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex2[1]), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex2[2].ee_block), 17U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex2[2]), 207ULL); +} + +/* + * Verify ext4_clu_mapped() across inline-data inodes, empty trees, clusters + * mapped at the start or end of a cluster, and unmapped clusters. + */ +static void test_clu_mapped(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + + ext_reset_tree(inode); + /* Empty tree -> unmapped */ + KUNIT_EXPECT_EQ(test, ext4_clu_mapped(inode, 0), 0); + + /* + * Insert [0, 2) @ 100 (in lclu 0 = lblks 0..3) and + * [6, 8) @ 106 (in lclu 1 = lblks 4..7). + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 2, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 6, 2, 106, false, 0), 0); + + /* Inline-data state returns 0 immediately */ + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + KUNIT_EXPECT_EQ(test, ext4_clu_mapped(inode, 0), 0); + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + + /* lclu 0 (lblk 0) is mapped directly by [0, 2) */ + KUNIT_EXPECT_EQ(test, ext4_clu_mapped(inode, 0), 1); + /* lclu 1 (lblk 4) is mapped by next allocated extent [6, 8) */ + KUNIT_EXPECT_EQ(test, ext4_clu_mapped(inode, 1), 1); + /* lclu 2 (lblk 8..11) is unmapped */ + KUNIT_EXPECT_EQ(test, ext4_clu_mapped(inode, 2), 0); +} + +/* + * Verify ext4_ext_index_trans_blocks() and + * ext4_ext_calc_credits_for_single_extent() credit calculations. + */ +static void test_ext_credits_calculation(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_ext_path *path; + int credits_with_space, credits_full; + + /* 1 extent vs multiple extents */ + KUNIT_EXPECT_EQ(test, ext4_ext_index_trans_blocks(inode, 1), + EXT4_MAX_EXTENT_DEPTH * 2 + 1); + KUNIT_EXPECT_EQ(test, ext4_ext_index_trans_blocks(inode, 2), + EXT4_MAX_EXTENT_DEPTH * 3 + 2); + + /* Inline data inode needs only 1 index block credit */ + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + EXT4_I(inode)->i_inline_off = 1; + KUNIT_EXPECT_EQ(test, ext4_ext_index_trans_blocks(inode, 2), 1); + EXT4_I(inode)->i_inline_off = 0; + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 2, 100, false, 0), 0); + + path = ext4_find_extent(inode, 10, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + /* Leaf has free space (eh_entries = 1 < eh_max = 4) */ + credits_with_space = + ext4_ext_calc_credits_for_single_extent(inode, 1, path); + + /* Mark leaf full (eh_entries == eh_max) */ + eh->eh_entries = eh->eh_max; + credits_full = ext4_ext_calc_credits_for_single_extent(inode, 1, path); + eh->eh_entries = cpu_to_le16(1); + ext4_free_ext_path(path); + + KUNIT_EXPECT_LT(test, credits_with_space, credits_full); + KUNIT_EXPECT_EQ(test, credits_full, + ext4_ext_calc_credits_for_single_extent(inode, 1, NULL)); +} + +/* + * Verify fast-commit replay extent helpers: + * - ext4_ext_replay_update_ex() splits and updates extent state/pblk + * - ext4_ext_replay_shrink_inode() merges adjacent compatible extents + * - ext4_ext_replay_set_iblocks() counts data and extent tree blocks and + * updates inode->i_blocks. + */ +static void test_ext_fast_commit_replay(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + unsigned short saved_mount_state; + int err; - return; + ext_reset_tree(inode); + saved_mount_state = sbi->s_mount_state; + sbi->s_mount_state |= EXT4_FC_REPLAY; + + /* Start with unwritten extent [10, 20) @ 100 */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 10, 100, true, 0), 0); + + /* Replay update converting middle [12, 16) to written @ 102 */ + err = ext4_ext_replay_update_ex(inode, 12, 4, 0, 102); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + /* Replay update converting [10, 12) @ 100 and [16, 20) @ 106 to written */ + KUNIT_ASSERT_EQ(test, ext4_ext_replay_update_ex(inode, 10, 2, 0, 100), + 0); + KUNIT_ASSERT_EQ(test, ext4_ext_replay_update_ex(inode, 16, 4, 0, 106), + 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + /* Shrink inode merges the 3 contiguous written extents into [10, 20) */ + ext4_ext_replay_shrink_inode(inode, 25); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 10); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex[0]), 0); + + /* Recalculate i_blocks for the 10-block extent (10 * 8 = 80 sectors) */ + inode->i_size = 30ULL << inode->i_sb->s_blocksize_bits; + inode->i_blocks = 0; + err = ext4_ext_replay_set_iblocks(inode); + sbi->s_mount_state = saved_mount_state; + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, inode->i_blocks, + 10ULL << (inode->i_sb->s_blocksize_bits - 9)); } static const struct kunit_ext_test_param test_split_convert_params[] = { @@ -1053,6 +2979,33 @@ static struct kunit_case extents_test_cases[] = { test_convert_initialized_param_init, NULL), KUNIT_CASE_PARAM_WITH_INIT(test_split_convert, kunit_array_gen_params, test_handle_unwritten_init, NULL), + KUNIT_CASE(test_ext_pblock_48bit), + KUNIT_CASE(test_ext_unwritten_len_encoding), + KUNIT_CASE(test_ext_tree_init_and_check_inode), + KUNIT_CASE_PARAM_WITH_INIT(test_ext_check_corruptions, + kunit_array_gen_params, + ext_check_corrupt_param_init, NULL), + KUNIT_CASE(test_ext_block_csum_verify), + KUNIT_CASE(test_find_extent_root_binsearch), + KUNIT_CASE(test_find_extent_multilevel_and_navigation), + KUNIT_CASE(test_ext_precache), + KUNIT_CASE(test_can_extents_be_merged), + KUNIT_CASE(test_insert_extent_merge_and_nomerge), + KUNIT_CASE(test_insert_extent_grow_and_merge_up), + KUNIT_CASE(test_insert_extent_leaf_split), + KUNIT_CASE(test_insert_extent_index_split), + KUNIT_CASE(test_remove_space_tail_and_hole_punch), + KUNIT_CASE(test_remove_space_multilevel_collapse), + KUNIT_CASE(test_remove_space_bigalloc_partial_cluster), + KUNIT_CASE(test_map_blocks_lookup_hole_and_query_last_in_leaf), + KUNIT_CASE(test_map_blocks_alloc_overlap_and_enospc), + KUNIT_CASE(test_convert_to_initialized_abut_neighbors), + KUNIT_CASE(test_map_blocks_bigalloc_implied_cluster), + KUNIT_CASE(test_ext_shift_extents), + KUNIT_CASE(test_swap_extents), + KUNIT_CASE(test_clu_mapped), + KUNIT_CASE(test_ext_credits_calculation), + KUNIT_CASE(test_ext_fast_commit_replay), {} }; diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index aa65aca4a1ead6..0a442844b954e5 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -547,6 +547,13 @@ static void ext4_cache_extents(struct inode *inode, } } +struct buffer_head *ext4_ext_getblk(struct inode *inode, ext4_fsblk_t pblk, + gfp_t gfp_flags) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_ext_getblk, inode, pblk, gfp_flags); + return sb_getblk_gfp(inode->i_sb, pblk, gfp_flags); +} + static struct buffer_head * __read_extent_tree_block(const char *function, unsigned int line, struct inode *inode, struct ext4_extent_idx *idx, @@ -561,7 +568,7 @@ __read_extent_tree_block(const char *function, unsigned int line, gfp_flags |= __GFP_NOFAIL; pblk = ext4_idx_pblock(idx); - bh = sb_getblk_gfp(inode->i_sb, pblk, gfp_flags); + bh = ext4_ext_getblk(inode, pblk, gfp_flags); if (unlikely(!bh)) return ERR_PTR(-ENOMEM); @@ -1133,7 +1140,7 @@ static int ext4_ext_split(handle_t *handle, struct inode *inode, err = -EFSCORRUPTED; goto cleanup; } - bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS); + bh = ext4_ext_getblk(inode, newblock, __GFP_MOVABLE | GFP_NOFS); if (unlikely(!bh)) { err = -ENOMEM; goto cleanup; @@ -1212,7 +1219,7 @@ static int ext4_ext_split(handle_t *handle, struct inode *inode, while (k--) { oldblock = newblock; newblock = ablocks[--a]; - bh = sb_getblk(inode->i_sb, newblock); + bh = ext4_ext_getblk(inode, newblock, __GFP_MOVABLE | GFP_NOFS); if (unlikely(!bh)) { err = -ENOMEM; goto cleanup; @@ -1341,7 +1348,7 @@ static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode, if (newblock == 0) return err; - bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS); + bh = ext4_ext_getblk(inode, newblock, __GFP_MOVABLE | GFP_NOFS); if (unlikely(!bh)) return -ENOMEM; lock_buffer(bh); @@ -6524,11 +6531,79 @@ struct ext4_ext_path *ext4_split_convert_extents_test(handle_t *handle, } EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_split_convert_extents_test); +int ext4_ext_check_test(struct inode *inode, struct ext4_extent_header *eh, + int depth, ext4_fsblk_t pblk, ext4_lblk_t lblk) +{ + return __ext4_ext_check(__func__, __LINE__, inode, eh, depth, pblk, + lblk); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_check_test); + +void ext4_extent_block_csum_set_test(struct inode *inode, + struct ext4_extent_header *eh) +{ + ext4_extent_block_csum_set(inode, eh); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_extent_block_csum_set_test); + +int ext4_can_extents_be_merged_test(struct inode *inode, + struct ext4_extent *ex1, + struct ext4_extent *ex2) +{ + return ext4_can_extents_be_merged(inode, ex1, ex2); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_can_extents_be_merged_test); + +int ext4_ext_search_left_test(struct inode *inode, struct ext4_ext_path *path, + ext4_lblk_t *logical, ext4_fsblk_t *phys) +{ + return ext4_ext_search_left(inode, path, logical, phys); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_search_left_test); + +int ext4_ext_search_right_test(struct inode *inode, struct ext4_ext_path *path, + ext4_lblk_t *logical, ext4_fsblk_t *phys, + struct ext4_extent *ret_ex, int flags) +{ + return ext4_ext_search_right(inode, path, logical, phys, ret_ex, flags); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_search_right_test); + +ext4_lblk_t ext4_ext_next_leaf_block_test(struct ext4_ext_path *path) +{ + return ext4_ext_next_leaf_block(path); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_next_leaf_block_test); + +int ext4_ext_shift_extents_test(struct inode *inode, handle_t *handle, + ext4_lblk_t start, ext4_lblk_t shift, + enum SHIFT_DIRECTION direction) +{ + return ext4_ext_shift_extents(inode, handle, start, shift, direction); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_shift_extents_test); + EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_ext_dirty); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_getblk); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_zeroout); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_create_blocks); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_insert_extent); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_extent); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_issue_zeroout); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_query_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_ext_path); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_tree_init); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_check_inode); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_precache); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_next_allocated_block); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_calc_credits_for_single_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_index_trans_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_remove_space); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_truncate); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_map_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_swap_extents); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_clu_mapped); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_replay_update_ex); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_replay_shrink_inode); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_replay_set_iblocks); #endif diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 43a183978692ed..c9400d50528138 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -7696,6 +7696,9 @@ int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode, struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); int err; + KUNIT_STATIC_STUB_REDIRECT(__ext4_mark_inode_dirty, handle, inode, + func, line); + might_sleep(); trace_ext4_mark_inode_dirty(inode, _RET_IP_); err = ext4_reserve_inode_write(handle, inode, &iloc); @@ -8003,4 +8006,6 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf) #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_update_reserve_space); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_release_space); +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_mark_inode_dirty); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_blocks); #endif diff --git a/fs/ext4/mballoc.c b/fs/ext4/mballoc.c index cf728da45ad741..a0f3058da90c41 100644 --- a/fs/ext4/mballoc.c +++ b/fs/ext4/mballoc.c @@ -6239,6 +6239,8 @@ ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle, int retries = 0; u64 seq; + KUNIT_STATIC_STUB_REDIRECT(ext4_mb_new_blocks, handle, ar, errp); + might_sleep(); sb = ar->inode->i_sb; sbi = EXT4_SB(sb); @@ -6697,6 +6699,9 @@ void ext4_free_blocks(handle_t *handle, struct inode *inode, unsigned int overflow; struct ext4_sb_info *sbi; + KUNIT_STATIC_STUB_REDIRECT(ext4_free_blocks, handle, inode, bh, block, + count, flags); + sbi = EXT4_SB(sb); if (bh) { @@ -7281,4 +7286,6 @@ EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_block_bitmap_nowait); EXPORT_SYMBOL_FOR_EXT4_TEST(mb_set_bits); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_init_inode); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_mark_context); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_new_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_blocks); #endif diff --git a/fs/ext4/move_extent.c b/fs/ext4/move_extent.c index 948ef3f44df5eb..e5450e83da8064 100644 --- a/fs/ext4/move_extent.c +++ b/fs/ext4/move_extent.c @@ -667,3 +667,8 @@ int ext4_move_extents(struct file *o_filp, struct file *d_filp, __u64 orig_blk, unlock_two_nondirectories(orig_inode, donor_inode); return ret; } + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_double_down_write_data_sem); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_double_up_write_data_sem); +#endif diff --git a/fs/ext4/super.c b/fs/ext4/super.c index 359f9d4ed44791..9f0951673fa3c3 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -1170,6 +1170,7 @@ void ext4_update_dynamic_rev(struct super_block *sb) * can leave it up to e2fsck to clean up any inconsistencies there. */ } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_dynamic_rev); static inline struct inode *orphan_list_entry(struct list_head *l) { From 5df08dcafa99c2655a54dc4742d538e3d03b9203 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Thu, 5 Nov 2026 03:18:41 +0000 Subject: [PATCH 1555/2102] ext4: add KUnit tests for fs/ext4/xattr.c Add the ext4_xattr_test KUnit test suite in fs/ext4/xattr-test.c to exercise the core extended attribute operations in fs/ext4/xattr.c without requiring a mounted block device: - Entry/value sizing macros (EXT4_XATTR_LEN, EXT4_XATTR_SIZE, EXT4_XATTR_MIN_LARGE_EA_SIZE), EXT4_INODE_HAS_XATTR_SPACE boundary checks, and xattr_sem locking helpers (ext4_write_lock_xattr, ext4_write_trylock_xattr, ext4_write_unlock_xattr) preserving EXT4_STATE_NO_EXPAND. - In-inode xattr validation (xattr_check_inode / __xattr_check_inode) across 11 parameterized valid and corrupted on-disk layouts (bad magic, truncated headers, out-of-bounds names, unterminated entry lists, non-zero offset on EA inode entries, and overlapping or out-of-bounds value ranges). - In-inode (ibody) get/set operations (ext4_xattr_get, ext4_xattr_ibody_get, ext4_xattr_set_handle, ext4_xattr_set), XATTR_CREATE and XATTR_REPLACE flag enforcement, EXT4_STATE_NEW raw inode initialization, superblock EXT4_FEATURE_COMPAT_EXT_ATTR update, and the identical-value fastpath (ext4_xattr_value_same). - In-inode value replacement (same padded size vs. shifted offsets), zero-length values, entry removal, and EXT4_I(inode)->i_inline_off adjustment when system.data is present. - External xattr block allocation, entry sorting by (e_name_index, e_name_len, e_name), migration from ibody to external block, EXT4_XATTR_BLOCK_RESERVE enforcement when ea_inode is enabled, and external block header and metadata CRC32C checksum verification. - External xattr block mb_cache deduplication across inodes, copy-on-write cloning when modifying a shared block, and EXT4_XATTR_REFCOUNT_MAX reuse bit transitions. - Attribute listing (ext4_listxattr) across ibody and external block entries, and user/hurd/trusted xattr handler prefix and mount-option filtering. - Large xattr inode (EXT4_FEATURE_INCOMPAT_EA_INODE) multi-block write/read, 64-bit refcount and hash encoding, mb_cache deduplication, reference decrement to zero, and ext4_evict_ea_inode() cache cleanup. - EA inode hash verification (including legacy signed-char name hash fallback), ext4_xattr_inode_iget() corruption checks, and Lustre-style EA inode compatibility. - Inode quota usage calculation (ext4_get_inode_usage), journal credit estimation (__ext4_xattr_set_credits, ext4_xattr_set_credits), extra isize expansion (ext4_expand_extra_isize_ea) for in-place shifts and external block eviction, inode xattr deletion (ext4_xattr_delete_inode), and error-injection rollback paths. Export the tested xattr entry points with EXPORT_SYMBOL_FOR_EXT4_TEST and add KUNIT_STATIC_STUB_REDIRECT hooks for ext4_xattr_getblk, ext4_sb_bread, ext4_map_blocks, ext4_getblk, ext4_get_inode_loc, ext4_mark_iloc_dirty, __ext4_iget, and __ext4_new_inode. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 2 + fs/ext4/ialloc.c | 9 + fs/ext4/inline.c | 4 + fs/ext4/inode.c | 17 +- fs/ext4/super.c | 11 +- fs/ext4/xattr-test.c | 1810 +++++++++++++++++++++++++++++++++++++++ fs/ext4/xattr.c | 30 +- fs/ext4/xattr.h | 2 + fs/ext4/xattr_hurd.c | 4 + fs/ext4/xattr_trusted.c | 4 + fs/ext4/xattr_user.c | 4 + 12 files changed, 1895 insertions(+), 4 deletions(-) create mode 100644 fs/ext4/xattr-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 74b485dbb229b7..13040b97d2ffc0 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -16,7 +16,7 @@ ext4-$(CONFIG_EXT4_FS_POSIX_ACL) += acl.o ext4-$(CONFIG_EXT4_FS_SECURITY) += xattr_security.o ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ - extents_status-test.o + extents_status-test.o xattr-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index aa0f23052ca2a9..30d6f7b99f07b3 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -4160,6 +4160,8 @@ extern int ext4_block_write_begin(handle_t *handle, struct folio *folio, #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) #define EXPORT_SYMBOL_FOR_EXT4_TEST(sym) \ EXPORT_SYMBOL_FOR_MODULES(sym, "ext4-test") +#else +#define EXPORT_SYMBOL_FOR_EXT4_TEST(sym) #endif #endif /* __KERNEL__ */ diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c index 92e2243b98cf87..8b9833ea38027e 100644 --- a/fs/ext4/ialloc.c +++ b/fs/ext4/ialloc.c @@ -23,6 +23,7 @@ #include #include #include +#include #include @@ -1012,6 +1013,10 @@ struct inode *__ext4_new_inode(const struct mnt_idmap *idmap, struct ext4_group_info *grp = NULL; bool encrypt = false; + KUNIT_STATIC_STUB_REDIRECT(__ext4_new_inode, idmap, handle, dir, mode, + qstr, goal, owner, i_flags, handle_type, + line_no, nblocks); + /* Cannot create files in a deleted directory */ if (!dir || !dir->i_nlink) return ERR_PTR(-EPERM); @@ -1693,3 +1698,7 @@ int ext4_init_inode_table(struct super_block *sb, ext4_group_t group, out: return ret; } + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_new_inode); +#endif diff --git a/fs/ext4/inline.c b/fs/ext4/inline.c index 2e14ee9b4241b0..1f7aa2223d1cf2 100644 --- a/fs/ext4/inline.c +++ b/fs/ext4/inline.c @@ -2036,3 +2036,7 @@ int ext4_convert_inline_data(struct inode *inode) brelse(iloc.bh); return error; } + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_inline_data_nolock); +#endif diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index c9400d50528138..5fa293c9581ea1 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -796,6 +796,8 @@ int ext4_map_blocks(handle_t *handle, struct inode *inode, memcpy(&orig_map, map, sizeof(*map)); #endif + KUNIT_STATIC_STUB_REDIRECT(ext4_map_blocks, handle, inode, map, flags); + map->m_flags = 0; ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n", flags, map->m_len, (unsigned long) map->m_lblk); @@ -996,6 +998,7 @@ int ext4_map_blocks(handle_t *handle, struct inode *inode, return ret ? ret : retval; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_blocks); /* * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages @@ -1121,6 +1124,9 @@ struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode, bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT; int err; + KUNIT_STATIC_STUB_REDIRECT(ext4_getblk, handle, inode, block, + map_flags); + ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) || handle != NULL || create == 0); ASSERT(create == 0 || !nowait); @@ -1183,6 +1189,7 @@ struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode, brelse(bh); return ERR_PTR(err); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_getblk); struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode, ext4_lblk_t block, int map_flags) @@ -5922,6 +5929,8 @@ int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc) ext4_fsblk_t err_blk = 0; int ret; + KUNIT_STATIC_STUB_REDIRECT(ext4_get_inode_loc, inode, iloc); + ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc, &err_blk); @@ -5931,6 +5940,7 @@ int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc) return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_inode_loc); /* * ext4_get_inode_loc_noio() is a best-effort variant of ext4_get_inode_loc(). @@ -6288,6 +6298,8 @@ struct inode *__ext4_iget(struct super_block *sb, unsigned long ino, gid_t i_gid; projid_t i_projid; + KUNIT_STATIC_STUB_REDIRECT(__ext4_iget, sb, ino, flags, function, line); + if ((!(flags & EXT4_IGET_SPECIAL) && is_special_ino(sb, ino)) || (ino < EXT4_ROOT_INO) || (ino > le32_to_cpu(es->s_inodes_count))) { @@ -6663,6 +6675,7 @@ struct inode *__ext4_iget(struct super_block *sb, unsigned long ino, iget_failed(inode); return ERR_PTR(ret); } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_iget); static void __ext4_update_other_inode_time(struct super_block *sb, unsigned long orig_ino, @@ -7455,6 +7468,8 @@ int ext4_mark_iloc_dirty(handle_t *handle, struct super_block *sb = inode->i_sb; int err = 0; + KUNIT_STATIC_STUB_REDIRECT(ext4_mark_iloc_dirty, handle, inode, iloc); + err = ext4_emergency_state(sb); if (unlikely(err)) { put_bh(iloc->bh); @@ -7488,6 +7503,7 @@ int ext4_mark_iloc_dirty(handle_t *handle, } return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mark_iloc_dirty); /* * On success, We end up with an outstanding reference count against @@ -8007,5 +8023,4 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf) EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_update_reserve_space); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_release_space); EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_mark_inode_dirty); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_blocks); #endif diff --git a/fs/ext4/super.c b/fs/ext4/super.c index 9f0951673fa3c3..4542a1b8ca0fff 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -49,6 +49,7 @@ #include #include #include +#include #include "ext4.h" #include "ext4_extents.h" /* Needed for trace points definition */ @@ -262,7 +263,11 @@ static struct buffer_head *__ext4_sb_bread_gfp(struct super_block *sb, struct buffer_head *ext4_sb_bread(struct super_block *sb, sector_t block, blk_opf_t op_flags) { - gfp_t gfp = mapping_gfp_constraint(sb->s_bdev->bd_mapping, + gfp_t gfp; + + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_bread, sb, block, op_flags); + + gfp = mapping_gfp_constraint(sb->s_bdev->bd_mapping, ~__GFP_FS) | __GFP_MOVABLE; return __ext4_sb_bread_gfp(sb, block, op_flags, gfp); @@ -7701,3 +7706,7 @@ MODULE_DESCRIPTION("Fourth Extended Filesystem"); MODULE_LICENSE("GPL"); module_init(ext4_init_fs) module_exit(ext4_exit_fs) + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_bread); +#endif diff --git a/fs/ext4/xattr-test.c b/fs/ext4/xattr-test.c new file mode 100644 index 00000000000000..30ee5c337284f8 --- /dev/null +++ b/fs/ext4/xattr-test.c @@ -0,0 +1,1810 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 extended attributes (fs/ext4/xattr.c). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" + +#define TEST_BLK_SIZE 1024 +#define TEST_BLK_BITS 10 +#define TEST_INODE_SIZE 256 +#define TEST_EXTRA_ISIZE (sizeof(struct ext4_inode) - \ + EXT4_GOOD_OLD_INODE_SIZE) +#define TEST_FIRST_PBLK 100 +#define TEST_MAX_BLOCKS 16 +#define TEST_MAX_EA_INODES 8 +#define TEST_PRIMARY_INO 12 +#define TEST_SECONDARY_INO 13 +#define TEST_FIRST_EA_INO 20 +#define TEST_CSUM_SEED 0x87654321U + +struct mock_block { + bool in_use; + struct buffer_head bh; + char data[TEST_BLK_SIZE] __aligned(8); +}; + +struct mock_inode_slot { + bool allocated; + struct ext4_inode_info ei; + struct buffer_head iloc_bh; + char raw_buf[TEST_INODE_SIZE] __aligned(8); + ext4_fsblk_t lblk_to_pblk[8]; +}; + +struct xattr_test_ctx { + struct super_block sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct block_device bdev; + struct address_space bd_mapping; + struct buffer_head sb_bh; + struct dentry root_dentry; + + struct mock_inode_slot primary; + struct mock_inode_slot secondary; + struct mock_inode_slot ea_inodes[TEST_MAX_EA_INODES]; + struct mock_block blocks[TEST_MAX_BLOCKS]; + + int fail_get_inode_loc; + int fail_mark_iloc_dirty; + int fail_dirty_metadata; + int fail_alloc_block; + int fail_sb_bread; + int fail_getblk; + int fail_iget; + int fail_new_inode; + bool fail_xattr_getblk; + + unsigned int alloc_block_calls; + unsigned int free_block_calls; + ext4_fsblk_t last_freed_block; + unsigned int mark_iloc_dirty_calls; + unsigned int mark_inode_dirty_calls; + unsigned int dirty_metadata_calls; +}; + +static const struct super_operations xattr_test_sops = {}; + +#ifdef CONFIG_QUOTA +static qsize_t *xattr_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations xattr_test_qops = { + .get_reserved_space = xattr_test_get_reserved_space, +}; +#endif + +static void init_mock_inode_slot(struct xattr_test_ctx *ctx, + struct mock_inode_slot *slot, + unsigned long ino) +{ + struct inode *inode = &slot->ei.vfs_inode; + struct ext4_inode *raw_inode; + + memset(slot, 0, sizeof(*slot)); + slot->allocated = true; + + inode->i_sb = &ctx->sb; + inode->i_ino = ino; + inode->i_mode = S_IFREG | 0644; + inode->i_blkbits = TEST_BLK_BITS; + inode->i_mapping = &inode->i_data; + set_nlink(inode, 1); + atomic_set(&inode->i_count, 1); + + spin_lock_init(&inode->i_lock); + i_size_ordered_init(inode); + init_rwsem(&inode->i_rwsem); + INIT_LIST_HEAD(&inode->i_io_list); + INIT_LIST_HEAD(&inode->i_wb_list); + INIT_LIST_HEAD(&inode->i_lru); + INIT_HLIST_NODE(&inode->i_hash); + /* + * Pre-set all I_DIRTY flags so mark_inode_dirty() from quota helpers + * sees the flags already set and returns without touching global bdi + * writeback lists. + */ + inode_state_set_raw(inode, I_DIRTY); + + init_rwsem(&slot->ei.xattr_sem); + init_rwsem(&slot->ei.i_data_sem); + spin_lock_init(&slot->ei.i_raw_lock); + spin_lock_init(&slot->ei.i_block_reservation_lock); + INIT_LIST_HEAD(&slot->ei.i_orphan); + slot->ei.i_extra_isize = TEST_EXTRA_ISIZE; + slot->ei.i_csum_seed = TEST_CSUM_SEED ^ (u32)ino; + + slot->iloc_bh.b_data = slot->raw_buf; + slot->iloc_bh.b_size = TEST_INODE_SIZE; + slot->iloc_bh.b_blocknr = 10 + ino; + slot->iloc_bh.b_bdev = &ctx->bdev; + atomic_set(&slot->iloc_bh.b_count, 1); + set_buffer_uptodate(&slot->iloc_bh); + set_buffer_mapped(&slot->iloc_bh); + + raw_inode = (struct ext4_inode *)slot->raw_buf; + raw_inode->i_extra_isize = cpu_to_le16(slot->ei.i_extra_isize); +} + +static struct mock_block *alloc_mock_block(struct xattr_test_ctx *ctx) +{ + int i; + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + struct mock_block *blk = &ctx->blocks[i]; + + if (!blk->in_use) { + memset(blk, 0, sizeof(*blk)); + blk->in_use = true; + blk->bh.b_data = blk->data; + blk->bh.b_size = TEST_BLK_SIZE; + blk->bh.b_blocknr = TEST_FIRST_PBLK + i; + blk->bh.b_bdev = &ctx->bdev; + atomic_set(&blk->bh.b_count, 1); + set_buffer_uptodate(&blk->bh); + set_buffer_mapped(&blk->bh); + return blk; + } + } + return NULL; +} + +static struct mock_block *find_mock_block(struct xattr_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + int i; + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + if (ctx->blocks[i].in_use && + ctx->blocks[i].bh.b_blocknr == blocknr) + return &ctx->blocks[i]; + } + return NULL; +} + +static int ext4_get_inode_loc_stub(struct inode *inode, struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + + if (ctx->fail_get_inode_loc) + return ctx->fail_get_inode_loc; + + slot = container_of(EXT4_I(inode), struct mock_inode_slot, ei); + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int ext4_mark_iloc_dirty_stub(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + + brelse(iloc->bh); + ctx->mark_iloc_dirty_calls++; + if (ctx->fail_mark_iloc_dirty) + return ctx->fail_mark_iloc_dirty; + return 0; +} + +static int __ext4_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + + ctx->mark_inode_dirty_calls++; + return 0; +} + +static int __ext4_handle_dirty_metadata_stub(const char *where, + unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + + if (ctx->fail_dirty_metadata) + return ctx->fail_dirty_metadata; + if (bh) + set_buffer_uptodate(bh); + ctx->dirty_metadata_calls++; + return 0; +} + +static ext4_fsblk_t ext4_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, + int *errp) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_block *blk; + + if (ctx->fail_alloc_block) { + *errp = ctx->fail_alloc_block; + return 0; + } + + blk = alloc_mock_block(ctx); + if (!blk) { + *errp = -ENOSPC; + return 0; + } + + ctx->alloc_block_calls++; + *errp = 0; + return blk->bh.b_blocknr; +} + +static void ext4_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_block *blk; + + if (bh) { + if (!block) + block = bh->b_blocknr; + if (flags & EXT4_FREE_BLOCKS_FORGET) + brelse(bh); + } + if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE)) + dquot_free_block(inode, + EXT4_C2B(EXT4_SB(inode->i_sb), count)); + + blk = find_mock_block(ctx, block); + if (blk) + blk->in_use = false; + + ctx->free_block_calls++; + ctx->last_freed_block = block; +} + +static struct buffer_head *ext4_xattr_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_block *blk; + + if (ctx->fail_xattr_getblk) + return NULL; + + blk = find_mock_block(ctx, block); + if (!blk) + return NULL; + + get_bh(&blk->bh); + return &blk->bh; +} + +static struct buffer_head *ext4_sb_bread_stub(struct super_block *sb, + sector_t block, + blk_opf_t op_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_block *blk; + + if (ctx->fail_sb_bread) + return ERR_PTR(ctx->fail_sb_bread); + + blk = find_mock_block(ctx, block); + if (!blk) + return ERR_PTR(-EIO); + + get_bh(&blk->bh); + return &blk->bh; +} + +static int ext4_map_blocks_stub(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + struct mock_block *blk; + + slot = container_of(EXT4_I(inode), struct mock_inode_slot, ei); + if (map->m_lblk >= ARRAY_SIZE(slot->lblk_to_pblk)) + return -EFSCORRUPTED; + + if (!slot->lblk_to_pblk[map->m_lblk]) { + if (!(flags & EXT4_GET_BLOCKS_CREATE)) + return 0; + if (ctx->fail_alloc_block) + return ctx->fail_alloc_block; + blk = alloc_mock_block(ctx); + if (!blk) + return -ENOSPC; + slot->lblk_to_pblk[map->m_lblk] = blk->bh.b_blocknr; + inode->i_blocks += TEST_BLK_SIZE >> 9; + map->m_flags = EXT4_MAP_NEW | EXT4_MAP_MAPPED; + } else { + map->m_flags = EXT4_MAP_MAPPED; + } + + map->m_pblk = slot->lblk_to_pblk[map->m_lblk]; + map->m_len = 1; + return 1; +} + +static struct buffer_head *ext4_getblk_stub(handle_t *handle, + struct inode *inode, + ext4_lblk_t block, int map_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + struct mock_block *blk; + + if (ctx->fail_getblk) + return ERR_PTR(ctx->fail_getblk); + + slot = container_of(EXT4_I(inode), struct mock_inode_slot, ei); + if (block >= ARRAY_SIZE(slot->lblk_to_pblk)) + return ERR_PTR(-EFSCORRUPTED); + if (!slot->lblk_to_pblk[block]) { + if (!(map_flags & EXT4_GET_BLOCKS_CREATE)) + return NULL; + blk = alloc_mock_block(ctx); + if (!blk) + return ERR_PTR(-ENOSPC); + slot->lblk_to_pblk[block] = blk->bh.b_blocknr; + inode->i_blocks += TEST_BLK_SIZE >> 9; + } else { + blk = find_mock_block(ctx, slot->lblk_to_pblk[block]); + if (!blk) + return ERR_PTR(-EIO); + } + + get_bh(&blk->bh); + return &blk->bh; +} + +static struct inode *__ext4_new_inode_stub(const struct mnt_idmap *idmap, + handle_t *handle, + struct inode *dir, umode_t mode, + const struct qstr *qstr, + __u32 goal, uid_t *owner, + __u32 i_flags, int handle_type, + unsigned int line_no, int nblocks) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + int i; + + if (ctx->fail_new_inode) + return ERR_PTR(ctx->fail_new_inode); + + for (i = 0; i < TEST_MAX_EA_INODES; i++) { + struct mock_inode_slot *slot = &ctx->ea_inodes[i]; + struct inode *inode = &slot->ei.vfs_inode; + + if (!slot->allocated) { + init_mock_inode_slot(ctx, slot, TEST_FIRST_EA_INO + i); + inode->i_mode = mode; + slot->ei.i_flags = i_flags; + if (owner) { + i_uid_write(inode, owner[0]); + i_gid_write(inode, owner[1]); + } + /* + * Set I_NEW for unlock_new_inode() and give the mock + * inode an extra baseline reference (i_count = 2) so + * ext4_put_ea_inode()'s iput_if_not_last() decrements + * i_count to 1 and returns without entering VFS + * eviction. + */ + inode_state_set_raw(inode, I_DIRTY | I_NEW); + atomic_set(&inode->i_count, 2); + return inode; + } + } + return ERR_PTR(-ENOSPC); +} + +static struct inode *__ext4_iget_stub(struct super_block *sb, + unsigned long ino, + ext4_iget_flags flags, + const char *function, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + int i; + + if (ctx->fail_iget) + return ERR_PTR(ctx->fail_iget); + + for (i = 0; i < TEST_MAX_EA_INODES; i++) { + struct mock_inode_slot *slot = &ctx->ea_inodes[i]; + struct inode *inode = &slot->ei.vfs_inode; + + if (slot->allocated && inode->i_ino == ino) { + if ((flags & EXT4_IGET_EA_INODE) && + !(slot->ei.i_flags & EXT4_EA_INODE_FL)) + return ERR_PTR(-EFSCORRUPTED); + atomic_inc(&inode->i_count); + return inode; + } + } + return ERR_PTR(-ENOENT); +} + +static int xattr_test_init(struct kunit *test) +{ + struct xattr_test_ctx *ctx; + struct super_block *sb; + struct ext4_sb_info *sbi; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + sb = &ctx->sb; + sbi = &ctx->sbi; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &xattr_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &xattr_test_qops; +#endif + sb->s_blocksize = TEST_BLK_SIZE; + sb->s_blocksize_bits = TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_xattr_kunit", sizeof(sb->s_id)); + init_rwsem(&sb->s_umount); + + ctx->bdev.bd_mapping = &ctx->bd_mapping; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + sbi->s_es = &ctx->es; + ctx->es.s_first_data_block = cpu_to_le32(1); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_inodes_count = cpu_to_le32(1024); + ctx->es.s_first_ino = cpu_to_le32(11); + ctx->es.s_inode_size = cpu_to_le16(TEST_INODE_SIZE); + ext4_blocks_count_set(&ctx->es, 65536); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + sbi->s_inode_size = TEST_INODE_SIZE; + sbi->s_first_ino = 11; + sbi->s_want_extra_isize = TEST_EXTRA_ISIZE; + ctx->es.s_min_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); + sbi->s_blocks_per_group = 8192; + sbi->s_clusters_per_group = 8192; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = 8; + sbi->s_csum_seed = TEST_CSUM_SEED; + + set_opt(sb, ERRORS_CONT); + set_opt(sb, XATTR_USER); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + + /* + * Use burst = 0 so expected corruption-test error/warning messages + * are suppressed without setting EXT4_FLAGS_SHUTDOWN. + */ + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + init_mock_inode_slot(ctx, &ctx->primary, TEST_PRIMARY_INO); + init_mock_inode_slot(ctx, &ctx->secondary, TEST_SECONDARY_INO); + + ctx->root_dentry.d_sb = sb; + ctx->root_dentry.d_inode = &ctx->primary.ei.vfs_inode; + sb->s_root = &ctx->root_dentry; + + kunit_activate_static_stub(test, ext4_get_inode_loc, + ext4_get_inode_loc_stub); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + ext4_mark_iloc_dirty_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + __ext4_mark_inode_dirty_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + __ext4_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + ext4_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + ext4_free_blocks_stub); + kunit_activate_static_stub(test, ext4_xattr_getblk, + ext4_xattr_getblk_stub); + kunit_activate_static_stub(test, ext4_sb_bread, + ext4_sb_bread_stub); + kunit_activate_static_stub(test, ext4_map_blocks, + ext4_map_blocks_stub); + kunit_activate_static_stub(test, ext4_getblk, + ext4_getblk_stub); + kunit_activate_static_stub(test, __ext4_new_inode, + __ext4_new_inode_stub); + kunit_activate_static_stub(test, __ext4_iget, + __ext4_iget_stub); + + return 0; +} + +static void xattr_test_exit(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + + if (!ctx) + return; + + ext4_xattr_destroy_cache(ctx->sbi.s_ea_block_cache); + ctx->sbi.s_ea_block_cache = NULL; + ext4_xattr_destroy_cache(ctx->sbi.s_ea_inode_cache); + ctx->sbi.s_ea_inode_cache = NULL; +} + +/* + * Test 1: Sizing macros, EXT4_INODE_HAS_XATTR_SPACE, and xattr_sem locking + * helpers. + */ +static void test_xattr_macros_and_locking(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + int save_outer = -1, save_inner = -1; + int locked; + + /* EXT4_XATTR_LEN rounds (sizeof(entry) + name_len) to 4-byte boundary */ + KUNIT_EXPECT_EQ(test, EXT4_XATTR_LEN(0), 16U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_LEN(1), 20U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_LEN(4), 20U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_LEN(5), 24U); + + /* EXT4_XATTR_SIZE rounds value size up to 4-byte boundary */ + KUNIT_EXPECT_EQ(test, EXT4_XATTR_SIZE(0), 0U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_SIZE(1), 4U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_SIZE(4), 4U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_SIZE(5), 8U); + + /* + * EXT4_XATTR_MIN_LARGE_EA_SIZE(b) is + * b - EXT4_XATTR_LEN(3) - sizeof(struct ext4_xattr_header) - 4. + */ + KUNIT_EXPECT_EQ(test, EXT4_XATTR_MIN_LARGE_EA_SIZE(1024), 968); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_MIN_LARGE_EA_SIZE(4096), 4040); + + /* + * EXT4_INODE_HAS_XATTR_SPACE requires at least + * sizeof(ibody_header) + EXT4_XATTR_PAD = 8 bytes of space after + * EXT4_GOOD_OLD_INODE_SIZE + i_extra_isize. + */ + KUNIT_EXPECT_TRUE(test, EXT4_INODE_HAS_XATTR_SPACE(inode)); + + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + KUNIT_EXPECT_FALSE(test, EXT4_INODE_HAS_XATTR_SPACE(inode)); + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + + /* Exact boundary: 256 - 128 - 8 = 120 bytes of i_extra_isize fits */ + EXT4_I(inode)->i_extra_isize = 120; + KUNIT_EXPECT_TRUE(test, EXT4_INODE_HAS_XATTR_SPACE(inode)); + + /* 124 bytes leaves only 4 bytes (< 8 bytes required) */ + EXT4_I(inode)->i_extra_isize = 124; + KUNIT_EXPECT_FALSE(test, EXT4_INODE_HAS_XATTR_SPACE(inode)); + EXT4_I(inode)->i_extra_isize = TEST_EXTRA_ISIZE; + + /* Locking helpers and EXT4_STATE_NO_EXPAND state preservation */ + KUNIT_EXPECT_EQ(test, + ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND), 0); + + ext4_write_lock_xattr(inode, &save_outer); + locked = ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND); + ext4_write_unlock_xattr(inode, &save_outer); + + KUNIT_EXPECT_EQ(test, save_outer, 0); + KUNIT_EXPECT_NE(test, locked, 0); + KUNIT_EXPECT_EQ(test, + ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND), 0); + + /* When EXT4_STATE_NO_EXPAND is already set, unlock must preserve it */ + ext4_set_inode_state(inode, EXT4_STATE_NO_EXPAND); + locked = ext4_write_trylock_xattr(inode, &save_inner); + if (locked) + ext4_write_unlock_xattr(inode, &save_inner); + + KUNIT_EXPECT_EQ(test, locked, 1); + KUNIT_EXPECT_NE(test, save_inner, 0); + KUNIT_EXPECT_NE(test, + ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND), 0); + ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND); +} + +/* + * Test 2: Parameterized xattr_check_inode() validation across valid and + * corrupted in-inode xattr layouts. + */ +enum xattr_check_case_id { + CHECK_VALID_EMPTY, + CHECK_VALID_TWO_ENTRIES, + CHECK_BAD_MAGIC, + CHECK_END_BEFORE_FIRST, + CHECK_ENTRY_HDR_OVERFLOW, + CHECK_ENTRY_NAME_OVERFLOW, + CHECK_UNTERMINATED_LIST, + CHECK_EA_INODE_WITHOUT_FEATURE, + CHECK_VALUE_SIZE_GT_TOTAL, + CHECK_VALUE_OFFS_OVERLAPS_ENTRY, + CHECK_VALUE_END_EXCEEDS_TOTAL, +}; + +struct xattr_check_param { + const char *desc; + enum xattr_check_case_id id; + int expected_err; +}; + +static const struct xattr_check_param xattr_check_params[] = { + { "valid_empty_ibody", CHECK_VALID_EMPTY, 0 }, + { "valid_two_entries", CHECK_VALID_TWO_ENTRIES, 0 }, + { "bad_magic", CHECK_BAD_MAGIC, -EFSCORRUPTED }, + { "end_before_first_entry", CHECK_END_BEFORE_FIRST, -EFSCORRUPTED }, + { "entry_header_overflows_end", CHECK_ENTRY_HDR_OVERFLOW, -EFSCORRUPTED }, + { "entry_name_overflows_end", CHECK_ENTRY_NAME_OVERFLOW, -EFSCORRUPTED }, + { "unterminated_entry_list", CHECK_UNTERMINATED_LIST, -EFSCORRUPTED }, + { "ea_inode_without_feature", CHECK_EA_INODE_WITHOUT_FEATURE, -EFSCORRUPTED }, + { "value_size_gt_total_size", CHECK_VALUE_SIZE_GT_TOTAL, -EFSCORRUPTED }, + { "value_offset_overlaps_entries", CHECK_VALUE_OFFS_OVERLAPS_ENTRY, -EFSCORRUPTED }, + { "value_end_exceeds_total_size", CHECK_VALUE_END_EXCEEDS_TOTAL, -EFSCORRUPTED }, +}; + +static void xattr_check_param_get_desc(const struct xattr_check_param *p, + char *desc) +{ + strscpy(desc, p->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(xattr_check, xattr_check_params, xattr_check_param_get_desc); + +static void test_xattr_check_inode(struct kunit *test) +{ + const struct xattr_check_param *p = test->param_value; + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct ext4_inode *raw_inode = (struct ext4_inode *)ctx->primary.raw_buf; + struct ext4_xattr_ibody_header *hdr = IHDR(inode, raw_inode); + struct ext4_xattr_entry *e1, *e2; + void *end = ITAIL(inode, raw_inode); + size_t total_size = (char *)end - (char *)IFIRST(hdr); + int ret; + + memset(hdr, 0, (char *)end - (char *)hdr); + hdr->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC); + e1 = IFIRST(hdr); + + switch (p->id) { + case CHECK_VALID_EMPTY: + break; + case CHECK_VALID_TWO_ENTRIES: + e1->e_name_len = 1; + e1->e_name_index = EXT4_XATTR_INDEX_USER; + e1->e_name[0] = 'a'; + e1->e_value_size = cpu_to_le32(4); + e1->e_value_offs = cpu_to_le16(total_size - 4); + + e2 = EXT4_XATTR_NEXT(e1); + e2->e_name_len = 1; + e2->e_name_index = EXT4_XATTR_INDEX_USER; + e2->e_name[0] = 'b'; + e2->e_value_size = cpu_to_le32(4); + e2->e_value_offs = cpu_to_le16(total_size - 8); + break; + case CHECK_BAD_MAGIC: + hdr->h_magic = cpu_to_le32(0xdeadbeef); + break; + case CHECK_END_BEFORE_FIRST: + end = (char *)IFIRST(hdr) + 2; + break; + case CHECK_ENTRY_HDR_OVERFLOW: + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + end = (char *)IFIRST(hdr) + EXT4_XATTR_LEN(1) + 8; + e2 = EXT4_XATTR_NEXT(e1); + e2->e_name_len = 1; + break; + case CHECK_ENTRY_NAME_OVERFLOW: + e1->e_name_len = 100; + break; + case CHECK_UNTERMINATED_LIST: + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + end = (char *)IFIRST(hdr) + EXT4_XATTR_LEN(1); + break; + case CHECK_EA_INODE_WITHOUT_FEATURE: + ext4_clear_feature_ea_inode(&ctx->sb); + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + e1->e_value_inum = cpu_to_le32(20); + e1->e_value_size = cpu_to_le32(4); + break; + case CHECK_VALUE_SIZE_GT_TOTAL: + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + e1->e_value_size = cpu_to_le32(total_size + 4); + e1->e_value_offs = cpu_to_le16(total_size - 4); + break; + case CHECK_VALUE_OFFS_OVERLAPS_ENTRY: + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + e1->e_value_size = cpu_to_le32(4); + /* Offset points inside e1 + 4-byte terminator */ + e1->e_value_offs = cpu_to_le16(EXT4_XATTR_LEN(1)); + break; + case CHECK_VALUE_END_EXCEEDS_TOTAL: + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + e1->e_value_size = cpu_to_le32(8); + e1->e_value_offs = cpu_to_le16(total_size - 4); + break; + } + + ret = xattr_check_inode(inode, hdr, end); + KUNIT_EXPECT_EQ_MSG(test, ret, p->expected_err, "case: %s", p->desc); +} + +/* + * Test 3: In-inode (ibody) get/set, flags validation, EXT4_STATE_NEW handling, + * superblock feature update, and identical-value fastpath. + */ +static void test_xattr_ibody_basic_and_flags(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct ext4_inode *raw_inode = (struct ext4_inode *)ctx->primary.raw_buf; + char long_name[260]; + char buf[32]; + unsigned int prev_dirty; + int ret; + + /* Fresh inode without EXT4_STATE_XATTR returns -ENODATA */ + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "missing", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, -ENODATA); + + /* Parameter validation: NULL name -> -EINVAL, >255 name -> -ERANGE */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + NULL, "v", 1, 0); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + memset(long_name, 'x', sizeof(long_name) - 1); + long_name[sizeof(long_name) - 1] = '\0'; + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + long_name, "v", 1, 0); + KUNIT_EXPECT_EQ(test, ret, -ERANGE); + + /* Forced shutdown check on get and set */ + set_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "k", + buf, sizeof(buf)), + -EIO); + KUNIT_EXPECT_EQ(test, + ext4_xattr_set_handle(NULL, inode, + EXT4_XATTR_INDEX_USER, "k", + "v", 1, 0), + -EIO); + clear_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + + /* XATTR_REPLACE on non-existent attribute returns -ENODATA */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "no_such", "val", 3, XATTR_REPLACE); + KUNIT_EXPECT_EQ(test, ret, -ENODATA); + + /* Deleting non-existent attribute without XATTR_REPLACE succeeds (0) */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "no_such", NULL, 0, 0); + KUNIT_EXPECT_EQ(test, ret, 0); + + /* + * Verify EXT4_STATE_NEW causes ext4_xattr_set_handle() to zero the raw + * inode and clear EXT4_STATE_NEW. + */ + memset(raw_inode, 0x5a, TEST_INODE_SIZE); + ext4_set_inode_state(inode, EXT4_STATE_NEW); + KUNIT_EXPECT_FALSE(test, + ext4_has_feature_xattr(&ctx->sb)); + + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "key1", "hello", 5, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, + ext4_test_inode_state(inode, EXT4_STATE_NEW), 0); + KUNIT_EXPECT_NE(test, + ext4_test_inode_state(inode, EXT4_STATE_XATTR), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(IHDR(inode, raw_inode)->h_magic), + (u32)EXT4_XATTR_MAGIC); + /* Setting first xattr enables EXT4_FEATURE_COMPAT_EXT_ATTR on sb */ + KUNIT_EXPECT_TRUE(test, ext4_has_feature_xattr(&ctx->sb)); + + /* XATTR_CREATE on existing attribute returns -EEXIST */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "key1", "other", 5, XATTR_CREATE); + KUNIT_EXPECT_EQ(test, ret, -EEXIST); + + /* Query length (NULL buffer), too small buffer (-ERANGE), and read */ + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "key1", NULL, 0); + KUNIT_EXPECT_EQ(test, ret, 5); + + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "key1", buf, 4); + KUNIT_EXPECT_EQ(test, ret, -ERANGE); + + memset(buf, 0, sizeof(buf)); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "key1", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_MEMEQ(test, buf, "hello", 5); + + /* Direct ext4_xattr_ibody_get() check */ + memset(buf, 0, sizeof(buf)); + ret = ext4_xattr_ibody_get(inode, EXT4_XATTR_INDEX_USER, "key1", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_MEMEQ(test, buf, "hello", 5); + + /* + * Setting the exact same value triggers the ext4_xattr_value_same() + * fastpath and skips dirtying the inode location. + */ + prev_dirty = ctx->mark_iloc_dirty_calls; + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "key1", "hello", 5, XATTR_REPLACE); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->mark_iloc_dirty_calls, prev_dirty); +} + +/* + * Test 4: In-inode (ibody) replacement (same padded size vs different size), + * zero-length values, entry removal, and i_inline_off adjustment. + */ +static void test_xattr_ibody_replace_and_remove(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct ext4_inode *raw_inode = (struct ext4_inode *)ctx->primary.raw_buf; + struct ext4_xattr_ibody_header *hdr = IHDR(inode, raw_inode); + struct ext4_xattr_entry *e; + char buf[32]; + u16 offs_before, offs_after; + int ret; + + /* Create two entries in ibody: "a" (7 bytes -> 8 padded) and "b" (4 bytes) */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "a", "1234567", 7, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "b", "wxyz", 4, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + e = IFIRST(hdr); + offs_before = le16_to_cpu(e->e_value_offs); + + /* + * Replace "a" with a 5-byte value (still 8 bytes padded): hits the + * in-place overwrite fastpath without shifting offsets, and zeroes + * the last 3 padding bytes. + */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "a", "ABCDE", 5, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + + offs_after = le16_to_cpu(e->e_value_offs); + KUNIT_EXPECT_EQ(test, offs_after, offs_before); + KUNIT_EXPECT_MEMEQ(test, (char *)IFIRST(hdr) + offs_after, + "ABCDE\0\0\0", 8); + + /* + * Replace "a" with a 12-byte value (different padded size): shifts + * "b"'s value and updates offsets while preserving "b"'s content. + */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "a", "0123456789ab", 12, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "a", + buf, sizeof(buf)), + 12); + KUNIT_EXPECT_MEMEQ(test, buf, "0123456789ab", 12); + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "b", + buf, sizeof(buf)), + 4); + KUNIT_EXPECT_MEMEQ(test, buf, "wxyz", 4); + + /* Replace "a" with a zero-length value ("", size = 0) */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "a", "", 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "a", + buf, sizeof(buf)), + 0); + + /* + * Add system.data (inline data entry) and verify removing an earlier + * entry ("a") shifts system.data's entry header left and updates + * EXT4_I(inode)->i_inline_off. + */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_SYSTEM, + "data", "inlinedata", 10, + XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_find_inline_data_nolock(inode); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + offs_before = EXT4_I(inode)->i_inline_off; + KUNIT_EXPECT_GT(test, offs_before, (u16)0); + + /* Remove "a": system.data entry header moves left by EXT4_XATTR_LEN(1) */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "a", NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_inline_off, + (u16)(offs_before - EXT4_XATTR_LEN(1))); + + /* Remove "b" and "system.data": emptying ibody clears h_magic and state */ + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "b", NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_NE(test, + ext4_test_inode_state(inode, EXT4_STATE_XATTR), 0); + + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_SYSTEM, + "data", NULL, 0, + XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(hdr->h_magic), 0U); + KUNIT_EXPECT_EQ(test, + ext4_test_inode_state(inode, EXT4_STATE_XATTR), 0); +} + +/* + * Test 5: External xattr block allocation, entry sorting, migration between + * ibody and external block, EXT4_XATTR_BLOCK_RESERVE enforcement, and external + * block header/CRC32C checksum validation. + */ +static void test_xattr_external_block_and_check(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct mock_block *blk; + struct ext4_xattr_header *bhdr; + struct ext4_xattr_entry *e1, *e2, *e3; + char val100[100]; + char *val796; + char buf[128]; + int ret; + + ext4_set_feature_metadata_csum(&ctx->sb); + memset(val100, 'V', sizeof(val100)); + + /* + * Start with a small attribute in ibody ("migr", 4 bytes), then grow + * it to 100 bytes (> 88-byte ibody space) so it migrates from ibody + * to a newly allocated external block. + */ + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "migr", + "tiny", 4, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "migr", + val100, sizeof(val100), XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_NE(test, EXT4_I(inode)->i_file_acl, 0ULL); + KUNIT_EXPECT_EQ(test, + ext4_test_inode_state(inode, EXT4_STATE_XATTR), 0); + + /* + * Add two more entries into the external block (by temporarily setting + * s_inode_size = 128 so ibody is bypassed) and verify external block + * entries are kept sorted by (e_name_index, e_name_len, e_name). + */ + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "z", + "1", 1, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "a", + "2", 1, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + + blk = find_mock_block(ctx, EXT4_I(inode)->i_file_acl); + KUNIT_ASSERT_NOT_NULL(test, blk); + bhdr = BHDR(&blk->bh); + e1 = BFIRST(&blk->bh); + e2 = EXT4_XATTR_NEXT(e1); + e3 = EXT4_XATTR_NEXT(e2); + + /* Length 1 ("a", "z") precede length 4 ("migr") */ + KUNIT_EXPECT_EQ(test, e1->e_name_len, 1); + KUNIT_EXPECT_EQ(test, e1->e_name[0], 'a'); + KUNIT_EXPECT_EQ(test, e2->e_name_len, 1); + KUNIT_EXPECT_EQ(test, e2->e_name[0], 'z'); + KUNIT_EXPECT_EQ(test, e3->e_name_len, 4); + KUNIT_EXPECT_MEMEQ(test, e3->e_name, "migr", 4); + + /* + * Verify external block validation and buffer_verified caching: + * 1) Reading sets buffer_verified. + * 2) Corrupting h_checksum while buffer_verified is set still succeeds + * because ext4_xattr_check_block() trusts buffer_verified. + * 3) Clearing buffer_verified exposes the bad checksum (-EFSBADCRC). + * 4) Corrupting h_blocks or h_magic returns -EFSCORRUPTED. + */ + clear_buffer_verified(&blk->bh); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "migr", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, 100); + KUNIT_EXPECT_NE(test, buffer_verified(&blk->bh), 0); + + bhdr->h_checksum ^= cpu_to_le32(1); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "a", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, 1); + + clear_buffer_verified(&blk->bh); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "a", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, -EFSBADCRC); + bhdr->h_checksum ^= cpu_to_le32(1); + + bhdr->h_blocks = cpu_to_le32(2); + clear_buffer_verified(&blk->bh); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "a", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + bhdr->h_blocks = cpu_to_le32(1); + + /* + * Verify EXT4_XATTR_BLOCK_RESERVE (128 bytes on 1024B block) when + * EXT4_FEATURE_INCOMPAT_EA_INODE is enabled: + * With "migr" (100B), "a" (4B), and "z" (4B) in the block, min_offs is + * 1024 - 108 = 916 and free space is 820 bytes. Adding "r1" with a + * 796-byte value (816B total <= 820B free) leaves min_offs - new_size + * = 916 - 796 = 120 < 128 (EXT4_XATTR_BLOCK_RESERVE), so with ea_inode + * enabled and EA inode creation disabled it fails with -ENOSPC, + * whereas with ea_inode disabled it fits inline in the block. + */ + val796 = kunit_kmalloc(test, 796, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, val796); + memset(val796, 'R', 796); + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + ext4_set_feature_ea_inode(&ctx->sb); + ctx->fail_new_inode = -ENOSPC; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "r1", + val796, 796, XATTR_CREATE); + ctx->fail_new_inode = 0; + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + + ext4_clear_feature_ea_inode(&ctx->sb); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "r1", + val796, 796, XATTR_CREATE); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_ASSERT_EQ(test, + ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "r1", + NULL, 0, XATTR_REPLACE), + 0); + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "a", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "z", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * Removing the last entry ("migr") from the external block frees the + * external xattr block and clears i_file_acl to 0. + */ + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "migr", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); +} + +/* + * Test 6: External xattr block mb_cache deduplication, copy-on-write cloning + * when modifying a shared block, and EXT4_XATTR_REFCOUNT_MAX handling. + */ +static void test_xattr_block_dedup_and_cow(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode1 = &ctx->primary.ei.vfs_inode; + struct inode *inode2 = &ctx->secondary.ei.vfs_inode; + struct mock_block *blk; + struct mb_cache_entry *ce; + char val100[100]; + ext4_fsblk_t shared_blk; + u32 hash; + int ret; + + ctx->sbi.s_ea_block_cache = ext4_xattr_create_cache(); + KUNIT_ASSERT_NOT_NULL(test, ctx->sbi.s_ea_block_cache); + + memset(val100, 'D', sizeof(val100)); + ret = ext4_xattr_set(inode1, EXT4_XATTR_INDEX_USER, "shared", + val100, sizeof(val100), XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + shared_blk = EXT4_I(inode1)->i_file_acl; + KUNIT_ASSERT_NE(test, shared_blk, 0ULL); + + /* Setting identical xattr on inode2 reuses shared_blk from mb_cache */ + ret = ext4_xattr_set(inode2, EXT4_XATTR_INDEX_USER, "shared", + val100, sizeof(val100), XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode2)->i_file_acl, shared_blk); + + blk = find_mock_block(ctx, shared_blk); + KUNIT_ASSERT_NOT_NULL(test, blk); + KUNIT_EXPECT_EQ(test, le32_to_cpu(BHDR(&blk->bh)->h_refcount), 2U); + + /* + * Modifying the xattr on inode2 triggers copy-on-write: inode2 gets a + * new block and shared_blk's refcount drops back to 1. + */ + val100[0] = 'M'; + ret = ext4_xattr_set(inode2, EXT4_XATTR_INDEX_USER, "shared", + val100, sizeof(val100), XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_NE(test, EXT4_I(inode2)->i_file_acl, shared_blk); + KUNIT_EXPECT_EQ(test, le32_to_cpu(BHDR(&blk->bh)->h_refcount), 1U); + + /* + * Test EXT4_XATTR_REFCOUNT_MAX (1024) limit: + * Bump shared_blk's h_refcount to EXT4_XATTR_REFCOUNT_MAX (1024), + * then set the same xattr on inode2. Cache lookup must see + * ref >= EXT4_XATTR_REFCOUNT_MAX, clear MBE_REUSABLE_B, and allocate + * a separate block instead of exceeding 1024. + */ + val100[0] = 'D'; + BHDR(&blk->bh)->h_refcount = cpu_to_le32(EXT4_XATTR_REFCOUNT_MAX); + hash = le32_to_cpu(BHDR(&blk->bh)->h_hash); + + ret = ext4_xattr_set(inode2, EXT4_XATTR_INDEX_USER, "shared", + val100, sizeof(val100), XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_NE(test, EXT4_I(inode2)->i_file_acl, shared_blk); + + ce = mb_cache_entry_get(ctx->sbi.s_ea_block_cache, hash, shared_blk); + KUNIT_ASSERT_NOT_NULL(test, ce); + KUNIT_EXPECT_FALSE(test, test_bit(MBE_REUSABLE_B, &ce->e_flags)); + mb_cache_entry_put(ctx->sbi.s_ea_block_cache, ce); + + /* + * Removing the attribute on inode1 releases one reference on + * shared_blk (1024 -> 1023 = EXT4_XATTR_REFCOUNT_MAX - 1), which + * re-enables MBE_REUSABLE_B on the mb_cache entry. + */ + ret = ext4_xattr_set(inode1, EXT4_XATTR_INDEX_USER, "shared", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(BHDR(&blk->bh)->h_refcount), + EXT4_XATTR_REFCOUNT_MAX - 1); + + ce = mb_cache_entry_get(ctx->sbi.s_ea_block_cache, hash, shared_blk); + KUNIT_ASSERT_NOT_NULL(test, ce); + KUNIT_EXPECT_TRUE(test, test_bit(MBE_REUSABLE_B, &ce->e_flags)); + mb_cache_entry_put(ctx->sbi.s_ea_block_cache, ce); +} + +/* + * Test 7: ext4_listxattr() across ibody and external block, and user/hurd/ + * trusted handler prefix and mount-option filtering. + */ +static void test_xattr_list_and_handlers(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct dentry *dentry = &ctx->root_dentry; + char val100[100]; + char list_buf[128]; + char val_buf[16]; + ssize_t list_len; + int ret; + + /* Handler get/set/list via user, hurd, and trusted handlers */ + ret = ext4_xattr_user_handler.set(&ext4_xattr_user_handler, + &nop_mnt_idmap, dentry, inode, + "ukey", "uval", 4, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_user_handler.get(&ext4_xattr_user_handler, + dentry, inode, "ukey", + val_buf, sizeof(val_buf)); + KUNIT_EXPECT_EQ(test, ret, 4); + + ret = ext4_xattr_hurd_handler.set(&ext4_xattr_hurd_handler, + &nop_mnt_idmap, dentry, inode, + "hkey", "hval", 4, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_hurd_handler.get(&ext4_xattr_hurd_handler, + dentry, inode, "hkey", + val_buf, sizeof(val_buf)); + KUNIT_EXPECT_EQ(test, ret, 4); + + /* Add a large attribute in external block via trusted handler */ + memset(val100, 'T', sizeof(val100)); + ret = ext4_xattr_trusted_handler.set(&ext4_xattr_trusted_handler, + &nop_mnt_idmap, dentry, inode, + "tkey", val100, sizeof(val100), + XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * With XATTR_USER set: "user.ukey\0" (10) + "gnu.hkey\0" (9) + + * (if CAP_SYS_ADMIN) "trusted.tkey\0" (13). + */ + list_len = ext4_listxattr(dentry, NULL, 0); + KUNIT_EXPECT_GE(test, list_len, (ssize_t)19); + + /* Buffer too small by 1 byte returns -ERANGE */ + KUNIT_EXPECT_EQ(test, + ext4_listxattr(dentry, list_buf, list_len - 1), + (ssize_t)-ERANGE); + + memset(list_buf, 0, sizeof(list_buf)); + KUNIT_EXPECT_EQ(test, + ext4_listxattr(dentry, list_buf, sizeof(list_buf)), + list_len); + KUNIT_EXPECT_MEMEQ(test, list_buf, "user.ukey\0gnu.hkey\0", 19); + + /* + * Clearing XATTR_USER mount option disables user and hurd handlers + * (-EOPNOTSUPP on get/set and filtered out of ext4_listxattr). + */ + clear_opt(&ctx->sb, XATTR_USER); + KUNIT_EXPECT_FALSE(test, ext4_xattr_user_handler.list(dentry)); + KUNIT_EXPECT_FALSE(test, ext4_xattr_hurd_handler.list(dentry)); + KUNIT_EXPECT_EQ(test, + ext4_xattr_user_handler.get(&ext4_xattr_user_handler, + dentry, inode, "ukey", + val_buf, sizeof(val_buf)), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_xattr_user_handler.set(&ext4_xattr_user_handler, + &nop_mnt_idmap, dentry, + inode, "ukey", "x", 1, 0), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_xattr_hurd_handler.get(&ext4_xattr_hurd_handler, + dentry, inode, "hkey", + val_buf, sizeof(val_buf)), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_xattr_hurd_handler.set(&ext4_xattr_hurd_handler, + &nop_mnt_idmap, dentry, + inode, "hkey", "x", 1, 0), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, ext4_listxattr(dentry, NULL, 0), + capable(CAP_SYS_ADMIN) ? (ssize_t)13 : (ssize_t)0); + set_opt(&ctx->sb, XATTR_USER); +} + +/* + * Test 8: Large xattr inodes (ea_inode feature) multi-block write/read, + * 64-bit refcount & hash encoding, mb_cache deduplication across inodes, + * reference decrement to 0, and ext4_evict_ea_inode(). + */ +static void test_xattr_ea_inode_lifecycle_and_dedup(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode1 = &ctx->primary.ei.vfs_inode; + struct inode *inode2 = &ctx->secondary.ei.vfs_inode; + struct inode *ea_inode; + struct ext4_inode *raw1 = (struct ext4_inode *)ctx->primary.raw_buf; + struct ext4_xattr_entry *e1; + char *large_val, *read_buf; + const size_t large_len = 1500; /* Spans 2 1024-byte blocks */ + unsigned int ea_ino; + u64 refcount; + int i, ret; + + ext4_set_feature_ea_inode(&ctx->sb); + ctx->sbi.s_ea_inode_cache = ext4_xattr_create_cache(); + KUNIT_ASSERT_NOT_NULL(test, ctx->sbi.s_ea_inode_cache); + ext4_init_ea_inode_work(&ctx->sbi); + + large_val = kunit_kmalloc(test, large_len, GFP_KERNEL); + read_buf = kunit_kzalloc(test, large_len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, large_val); + KUNIT_ASSERT_NOT_NULL(test, read_buf); + for (i = 0; i < large_len; i++) + large_val[i] = (char)('A' + (i % 26)); + + /* Create 1500-byte xattr on inode1: stored in a new EA inode */ + ret = ext4_xattr_set(inode1, EXT4_XATTR_INDEX_USER, "big", + large_val, large_len, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + e1 = IFIRST(IHDR(inode1, raw1)); + ea_ino = le32_to_cpu(e1->e_value_inum); + KUNIT_ASSERT_EQ(test, ea_ino, (unsigned int)TEST_FIRST_EA_INO); + KUNIT_EXPECT_EQ(test, le16_to_cpu(e1->e_value_offs), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(e1->e_value_size), + (u32)large_len); + + ea_inode = &ctx->ea_inodes[0].ei.vfs_inode; + refcount = ((u64)inode_get_ctime_sec(ea_inode) << 32) | + (u32)inode_peek_iversion_raw(ea_inode); + KUNIT_EXPECT_EQ(test, refcount, 1ULL); + KUNIT_EXPECT_EQ(test, ea_inode->i_nlink, 1U); + + /* Read back multi-block EA inode value via ext4_xattr_get() */ + ret = ext4_xattr_get(inode1, EXT4_XATTR_INDEX_USER, "big", + read_buf, large_len); + KUNIT_ASSERT_EQ(test, ret, (int)large_len); + KUNIT_EXPECT_MEMEQ(test, read_buf, large_val, large_len); + + /* + * Setting the identical 1500-byte value on inode2 deduplicates via + * s_ea_inode_cache and increments ea_inode's refcount to 2. + */ + ret = ext4_xattr_set(inode2, EXT4_XATTR_INDEX_USER, "big2", + large_val, large_len, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + refcount = ((u64)inode_get_ctime_sec(ea_inode) << 32) | + (u32)inode_peek_iversion_raw(ea_inode); + KUNIT_EXPECT_EQ(test, refcount, 2ULL); + + /* Removing from inode1 drops refcount to 1; i_nlink remains 1 */ + ret = ext4_xattr_set(inode1, EXT4_XATTR_INDEX_USER, "big", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + refcount = ((u64)inode_get_ctime_sec(ea_inode) << 32) | + (u32)inode_peek_iversion_raw(ea_inode); + KUNIT_EXPECT_EQ(test, refcount, 1ULL); + KUNIT_EXPECT_EQ(test, ea_inode->i_nlink, 1U); + + /* + * Removing from inode2 drops refcount to 0 and clears i_nlink to 0. + * Also verify ext4_evict_ea_inode() removes it from s_ea_inode_cache. + */ + ret = ext4_xattr_set(inode2, EXT4_XATTR_INDEX_USER, "big2", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + refcount = ((u64)inode_get_ctime_sec(ea_inode) << 32) | + (u32)inode_peek_iversion_raw(ea_inode); + KUNIT_EXPECT_EQ(test, refcount, 0ULL); + KUNIT_EXPECT_EQ(test, ea_inode->i_nlink, 0U); + + ext4_evict_ea_inode(ea_inode); +} + +/* + * Test 9: EA inode hash verification (including legacy signed-char name hash + * fallback), ext4_xattr_inode_iget() corruption checks, and Lustre-style + * EA inode compatibility. + */ +static void test_xattr_ea_inode_validation_and_compat(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct inode *ea_inode; + struct ext4_inode *raw = (struct ext4_inode *)ctx->primary.raw_buf; + struct ext4_xattr_entry *e; + static const char signed_name[] = "\x80\xfe"; + const size_t val_len = 1000; + char *val, *buf; + u32 val_hash, signed_e_hash = 0; + __le32 orig_e_hash; + int i, ret; + + ext4_set_feature_ea_inode(&ctx->sb); + val = kunit_kmalloc(test, val_len, GFP_KERNEL); + buf = kunit_kzalloc(test, val_len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, val); + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(val, 'S', val_len); + + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, signed_name, + val, val_len, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + e = IFIRST(IHDR(inode, raw)); + ea_inode = &ctx->ea_inodes[0].ei.vfs_inode; + orig_e_hash = e->e_hash; + + /* + * Compute the legacy signed-char entry hash for "\x80\xfe" and verify + * ext4_xattr_inode_verify_hashes() accepts it as a valid fallback. + */ + val_hash = (u32)inode_get_atime_sec(ea_inode); + for (i = 0; i < (int)strlen(signed_name); i++) { + signed_e_hash = (signed_e_hash << 5) ^ + (signed_e_hash >> 27) ^ + (signed char)signed_name[i]; + } + signed_e_hash = (signed_e_hash << 16) ^ + (signed_e_hash >> 16) ^ val_hash; + e->e_hash = cpu_to_le32(signed_e_hash); + + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, (int)val_len); + + /* Truly corrupted entry hash is rejected with -EFSCORRUPTED */ + e->e_hash = cpu_to_le32(signed_e_hash ^ 0x12345678U); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + e->e_hash = orig_e_hash; + + /* Corrupted value hash stored in ea_inode->i_atime is rejected */ + inode_set_atime(ea_inode, val_hash ^ 1, 0); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + inode_set_atime(ea_inode, val_hash, 0); + + /* Size mismatch between ea_inode->i_size and entry->e_value_size */ + i_size_write(ea_inode, val_len - 1); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + i_size_write(ea_inode, val_len); + + /* Invalid i_nlink (0 or 2) on active EA inode returns -EFSCORRUPTED */ + set_nlink(ea_inode, 2); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + set_nlink(ea_inode, 1); + + /* Self-referencing e_value_inum == parent->i_ino returns -EFSCORRUPTED */ + e->e_value_inum = cpu_to_le32(inode->i_ino); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + e->e_value_inum = cpu_to_le32(ea_inode->i_ino); + + /* + * Lustre-style old EA inode compatibility: when e_hash != ea_inode + * hash, but parent ino (stored in i_mtime) and generation (stored in + * i_generation) match parent, ext4_xattr_inode_iget() sets + * EXT4_STATE_LUSTRE_EA_INODE and forces ref_count = 1. + */ + e->e_hash = 0; + inode->i_generation = 42; + ea_inode->i_generation = 42; + inode_set_mtime(ea_inode, inode->i_ino, 0); + inode_set_ctime(ea_inode, 0, 0); + inode_set_iversion_raw(ea_inode, 0); + /* Even with initial ref_count = 0, Lustre compat sets ref = 1 */ + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, (int)val_len); + KUNIT_EXPECT_NE(test, + ext4_test_inode_state(ea_inode, + EXT4_STATE_LUSTRE_EA_INODE), + 0); +} + +/* + * Test 10: ext4_get_inode_usage(), credit calculation, handle credit check, + * ext4_expand_extra_isize_ea(), and ext4_xattr_delete_inode(). + */ +static void test_xattr_credits_usage_expand_and_delete(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct ext4_inode *raw = (struct ext4_inode *)ctx->primary.raw_buf; + journal_t *fake_journal; + handle_t fake_handle = { + .h_reserved = 1, + .h_total_credits = 1, + }; + const size_t large_len = 1000; + char *large_val; + char val28[28]; + char buf[64]; + qsize_t usage = 0; + int credits_create, credits_replace, credits_out = -1; + int ret; + + fake_journal = kunit_kzalloc(test, sizeof(*fake_journal), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, fake_journal); + fake_journal->j_revoke_records_per_block = 64; + fake_handle.h_journal = fake_journal; + + large_val = kunit_kmalloc(test, large_len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, large_val); + memset(large_val, 'L', large_len); + + /* + * 1. Credit calculation and insufficient handle credits check + */ + credits_create = __ext4_xattr_set_credits(&ctx->sb, inode, NULL, + 100, true); + KUNIT_EXPECT_GT(test, credits_create, 0); + + ext4_set_feature_ea_inode(&ctx->sb); + credits_create = __ext4_xattr_set_credits(&ctx->sb, inode, NULL, + 1500, true); + credits_replace = __ext4_xattr_set_credits(&ctx->sb, inode, NULL, + 1500, false); + KUNIT_EXPECT_GT(test, credits_replace, credits_create); + + /* Without a journal (s_journal == NULL), credits_out is 0 */ + ret = ext4_xattr_set_credits(inode, 1500, true, &credits_out); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, credits_out, 0); + + /* With s_journal set, ext4_xattr_set_credits() returns credits_create */ + ctx->sbi.s_journal = fake_journal; + ret = ext4_xattr_set_credits(inode, 1500, true, &credits_out); + ctx->sbi.s_journal = NULL; + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, credits_out, credits_create); + + /* Handle with only 1 buffer credit (< credits) fails with -ENOSPC */ + ret = ext4_xattr_set_handle(&fake_handle, inode, EXT4_XATTR_INDEX_USER, + "k", "v", 1, XATTR_CREATE); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + + /* + * 2. ext4_expand_extra_isize_ea(): + * Put "keep" (4B -> 24B total) and "evict" (28B -> 52B total) in + * ibody (88B usable, leaving 12B free). + * First expand i_extra_isize from 32 -> 40 (8 bytes <= 12B free): + * shifts ibody entries in-place without allocating an external block. + * Then expand i_extra_isize from 40 -> 72 (32 bytes > 4B free): + * "keep" (24 + 4 = 28 < 32) is too small alone, so "evict" (52 + 4 >= 32) + * is moved to an external xattr block while "keep" stays in ibody! + */ + ext4_clear_feature_ea_inode(&ctx->sb); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "keep", + "1234", 4, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + memset(val28, 'E', sizeof(val28)); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "evict", + val28, sizeof(val28), XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* In-place ibody shift (32 -> 40) */ + ret = ext4_expand_extra_isize_ea(inode, 40, raw, NULL); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_extra_isize, (u16)40); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* Eviction of "evict" to external block (40 -> 72) */ + ret = ext4_expand_extra_isize_ea(inode, 72, raw, NULL); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_extra_isize, (u16)72); + KUNIT_EXPECT_NE(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* Both "keep" (in ibody) and "evict" (in external block) remain readable */ + KUNIT_EXPECT_EQ(test, + ext4_xattr_ibody_get(inode, EXT4_XATTR_INDEX_USER, + "keep", buf, sizeof(buf)), + 4); + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, + "evict", buf, sizeof(buf)), + 28); + + /* + * 3. ext4_get_inode_usage() and ext4_xattr_delete_inode(): + * Add a 1000-byte EA inode attribute ("large_ea") and check that + * ext4_get_inode_usage() accounts for 1 (parent inode) + 1 (EA inode) + * = 2 inodes, and ext4_xattr_delete_inode() frees the external block + * and drops the EA inode reference to 0. + */ + ext4_set_feature_ea_inode(&ctx->sb); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "large_ea", + large_val, large_len, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + down_read(&EXT4_I(inode)->xattr_sem); + ret = ext4_get_inode_usage(inode, &usage); + up_read(&EXT4_I(inode)->xattr_sem); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, usage, (qsize_t)2); + + ret = ext4_xattr_delete_inode(NULL, inode, 0); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + KUNIT_EXPECT_EQ(test, ctx->ea_inodes[0].ei.vfs_inode.i_nlink, 0U); +} + +/* + * Test 11: Error injection and rollback paths across inode location lookup, + * external block allocation/getblk/bread/dirty_metadata, and EA inode + * creation/write/lookup. + */ +static void test_xattr_error_injection(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + const size_t large_len = 1000; + char *large_val; + char val100[100]; + char buf[128]; + unsigned int prev_free; + int ret; + + large_val = kunit_kmalloc(test, large_len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, large_val); + memset(large_val, 'F', large_len); + memset(val100, 'B', sizeof(val100)); + + /* 1. ext4_get_inode_loc() failure on set and get */ + ctx->fail_get_inode_loc = -EIO; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "k", + "v", 1, XATTR_CREATE); + KUNIT_EXPECT_EQ(test, ret, -EIO); + + ext4_set_inode_state(inode, EXT4_STATE_XATTR); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "k", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, -EIO); + ext4_clear_inode_state(inode, EXT4_STATE_XATTR); + ctx->fail_get_inode_loc = 0; + + /* 2. ext4_mark_iloc_dirty() failure on set */ + ctx->fail_mark_iloc_dirty = -EIO; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "k", + "v", 1, XATTR_CREATE); + ctx->fail_mark_iloc_dirty = 0; + KUNIT_EXPECT_EQ(test, ret, -EIO); + /* Clean up the entry written to raw_buf before mark_iloc_dirty */ + KUNIT_ASSERT_EQ(test, + ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "k", + NULL, 0, XATTR_REPLACE), + 0); + + /* 3. External block allocation failure (-ENOSPC) */ + ctx->fail_alloc_block = -ENOSPC; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "blk", + val100, sizeof(val100), XATTR_CREATE); + ctx->fail_alloc_block = 0; + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* + * 4. ext4_xattr_getblk() failure (-ENOMEM) after block allocation must + * free the newly allocated block via ext4_free_blocks(). + */ + prev_free = ctx->free_block_calls; + ctx->fail_xattr_getblk = true; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "blk", + val100, sizeof(val100), XATTR_CREATE); + ctx->fail_xattr_getblk = false; + KUNIT_EXPECT_EQ(test, ret, -ENOMEM); + KUNIT_EXPECT_EQ(test, ctx->free_block_calls, prev_free + 1); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* 5. ext4_handle_dirty_metadata() failure when creating external block */ + ctx->fail_dirty_metadata = -EIO; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "blk", + val100, sizeof(val100), XATTR_CREATE); + ctx->fail_dirty_metadata = 0; + KUNIT_EXPECT_EQ(test, ret, -EIO); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* Successfully create external block, then test ext4_sb_bread() failure */ + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "blk", + val100, sizeof(val100), XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->fail_sb_bread = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "blk", + buf, sizeof(buf)), + -EIO); + KUNIT_EXPECT_EQ(test, + ext4_listxattr(&ctx->root_dentry, buf, sizeof(buf)), + (ssize_t)-EIO); + KUNIT_EXPECT_EQ(test, ext4_xattr_delete_inode(NULL, inode, 0), -EIO); + ctx->fail_sb_bread = 0; + + /* + * 6. EA inode block allocation failure in ext4_xattr_inode_write() + * must clean up the newly created EA inode (dropping its i_nlink to 0). + */ + ext4_set_feature_ea_inode(&ctx->sb); + ctx->fail_alloc_block = -ENOSPC; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "big_err", + large_val, large_len, XATTR_CREATE); + ctx->fail_alloc_block = 0; + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_TRUE(test, ctx->ea_inodes[0].allocated); + KUNIT_EXPECT_EQ(test, ctx->ea_inodes[0].ei.vfs_inode.i_nlink, 0U); + + /* 7. Successfully create EA inode, then test __ext4_iget() and ext4_getblk() failure */ + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "big_ok", + large_val, large_len, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->fail_iget = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "big_ok", + large_val, large_len), + -EIO); + ctx->fail_iget = 0; + + ctx->fail_getblk = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "big_ok", + large_val, large_len), + -EIO); + ctx->fail_getblk = 0; +} + +static struct kunit_case xattr_test_cases[] = { + KUNIT_CASE(test_xattr_macros_and_locking), + KUNIT_CASE_PARAM(test_xattr_check_inode, xattr_check_gen_params), + KUNIT_CASE(test_xattr_ibody_basic_and_flags), + KUNIT_CASE(test_xattr_ibody_replace_and_remove), + KUNIT_CASE(test_xattr_external_block_and_check), + KUNIT_CASE(test_xattr_block_dedup_and_cow), + KUNIT_CASE(test_xattr_list_and_handlers), + KUNIT_CASE(test_xattr_ea_inode_lifecycle_and_dedup), + KUNIT_CASE(test_xattr_ea_inode_validation_and_compat), + KUNIT_CASE(test_xattr_credits_usage_expand_and_delete), + KUNIT_CASE(test_xattr_error_injection), + {} +}; + +static struct kunit_suite xattr_test_suite = { + .name = "ext4_xattr_test", + .init = xattr_test_init, + .exit = xattr_test_exit, + .test_cases = xattr_test_cases, +}; + +kunit_test_suites(&xattr_test_suite); + +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/xattr.c b/fs/ext4/xattr.c index 062786fa364641..277731c424a091 100644 --- a/fs/ext4/xattr.c +++ b/fs/ext4/xattr.c @@ -57,6 +57,7 @@ #include #include #include +#include #include "ext4_jbd2.h" #include "ext4.h" #include "xattr.h" @@ -107,6 +108,7 @@ const struct xattr_handler * const ext4_xattr_handlers[] = { &ext4_xattr_hurd_handler, NULL }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_handlers); #define EA_BLOCK_CACHE(inode) (((struct ext4_sb_info *) \ inode->i_sb->s_fs_info)->s_ea_block_cache) @@ -169,6 +171,14 @@ static void ext4_xattr_block_csum_set(struct inode *inode, bh->b_blocknr, BHDR(bh)); } +struct buffer_head *ext4_xattr_getblk(struct super_block *sb, + ext4_fsblk_t block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_xattr_getblk, sb, block); + return sb_getblk(sb, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_getblk); + static inline const char *ext4_xattr_prefix(int name_index, struct dentry *dentry) { @@ -315,6 +325,7 @@ __xattr_check_inode(struct inode *inode, struct ext4_xattr_ibody_header *header, return check_xattrs(inode, NULL, IFIRST(header), end, IFIRST(header), function, line); } +EXPORT_SYMBOL_FOR_EXT4_TEST(__xattr_check_inode); static int xattr_find_entry(struct inode *inode, struct ext4_xattr_entry **pentry, @@ -493,6 +504,7 @@ void ext4_evict_ea_inode(struct inode *inode) mb_cache_entry_put(EA_INODE_CACHE(inode), oe); } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_evict_ea_inode); static int ext4_xattr_inode_verify_hashes(struct inode *ea_inode, @@ -693,6 +705,7 @@ ext4_xattr_ibody_get(struct inode *inode, int name_index, const char *name, brelse(iloc.bh); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_ibody_get); /* * ext4_xattr_get() @@ -725,6 +738,7 @@ ext4_xattr_get(struct inode *inode, int name_index, const char *name, up_read(&EXT4_I(inode)->xattr_sem); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_get); static int ext4_xattr_list_entries(struct dentry *dentry, struct ext4_xattr_entry *entry, @@ -841,6 +855,7 @@ ext4_listxattr(struct dentry *dentry, char *buffer, size_t buffer_size) up_read(&EXT4_I(d_inode(dentry))->xattr_sem); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_listxattr); /* * If the EXT4_FEATURE_COMPAT_EXT_ATTR feature of this file system is @@ -912,6 +927,7 @@ int ext4_get_inode_usage(struct inode *inode, qsize_t *usage) brelse(bh); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_inode_usage); static inline size_t round_up_cluster(struct inode *inode, size_t length) { @@ -1029,6 +1045,7 @@ int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode, } return credits; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_xattr_set_credits); static int ext4_xattr_inode_update_ref(handle_t *handle, struct inode *ea_inode, int ref_change) @@ -2166,7 +2183,7 @@ ext4_xattr_block_set(handle_t *handle, struct inode *inode, ea_idebug(inode, "creating block %llu", (unsigned long long)block); - new_bh = sb_getblk(sb, block); + new_bh = ext4_xattr_getblk(sb, block); if (unlikely(!new_bh)) { error = -ENOMEM; getblk_failed: @@ -2282,6 +2299,7 @@ int ext4_xattr_ibody_find(struct inode *inode, struct ext4_xattr_info *i, } return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_ibody_find); int ext4_xattr_ibody_set(handle_t *handle, struct inode *inode, struct ext4_xattr_info *i, @@ -2340,6 +2358,7 @@ int ext4_xattr_ibody_set(handle_t *handle, struct inode *inode, ext4_put_ea_inode(ea_inode); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_ibody_set); static int ext4_xattr_value_same(struct ext4_xattr_search *s, struct ext4_xattr_info *i) @@ -2537,6 +2556,7 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index, ext4_write_unlock_xattr(inode, &no_expand); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_set_handle); int ext4_xattr_set_credits(struct inode *inode, size_t value_len, bool is_create, int *credits) @@ -2564,6 +2584,7 @@ int ext4_xattr_set_credits(struct inode *inode, size_t value_len, up_read(&EXT4_I(inode)->xattr_sem); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_set_credits); /* * ext4_xattr_set() @@ -2612,6 +2633,7 @@ ext4_xattr_set(struct inode *inode, int name_index, const char *name, return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_set); /* * Shift the EA entries in the inode to create space for the increased @@ -2903,6 +2925,7 @@ int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize, } return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_expand_extra_isize_ea); /* * ext4_xattr_delete_inode() @@ -3011,6 +3034,7 @@ int ext4_xattr_delete_inode(handle_t *handle, struct inode *inode, brelse(bh); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_delete_inode); /* * Worker function for deferred EA inode iput. Processes all inodes queued @@ -3064,12 +3088,14 @@ void ext4_put_ea_inode(struct inode *inode) */ schedule_delayed_work(&EXT4_SB(inode->i_sb)->s_ea_inode_work, 1); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_put_ea_inode); void ext4_init_ea_inode_work(struct ext4_sb_info *sbi) { init_llist_head(&sbi->s_ea_inode_to_free); INIT_DELAYED_WORK(&sbi->s_ea_inode_work, ext4_ea_inode_work); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_ea_inode_work); /* * ext4_xattr_block_cache_insert() @@ -3267,10 +3293,12 @@ ext4_xattr_create_cache(void) { return mb_cache_create(HASH_BUCKET_BITS); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_create_cache); void ext4_xattr_destroy_cache(struct mb_cache *cache) { if (cache) mb_cache_destroy(cache); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_destroy_cache); diff --git a/fs/ext4/xattr.h b/fs/ext4/xattr.h index 821dc6a50e51e7..1a72e68cea0c78 100644 --- a/fs/ext4/xattr.h +++ b/fs/ext4/xattr.h @@ -229,3 +229,5 @@ static inline void ext4_xattr_inode_set_class(struct inode *ea_inode) { } #endif extern int ext4_get_inode_usage(struct inode *inode, qsize_t *usage); +extern struct buffer_head *ext4_xattr_getblk(struct super_block *sb, + ext4_fsblk_t block); diff --git a/fs/ext4/xattr_hurd.c b/fs/ext4/xattr_hurd.c index a3ecbff72b1015..9cd42f6546b5a1 100644 --- a/fs/ext4/xattr_hurd.c +++ b/fs/ext4/xattr_hurd.c @@ -50,3 +50,7 @@ const struct xattr_handler ext4_xattr_hurd_handler = { .get = ext4_xattr_hurd_get, .set = ext4_xattr_hurd_set, }; + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_hurd_handler); +#endif diff --git a/fs/ext4/xattr_trusted.c b/fs/ext4/xattr_trusted.c index 458e1982ef83a3..d5d033ba75949e 100644 --- a/fs/ext4/xattr_trusted.c +++ b/fs/ext4/xattr_trusted.c @@ -45,3 +45,7 @@ const struct xattr_handler ext4_xattr_trusted_handler = { .get = ext4_xattr_trusted_get, .set = ext4_xattr_trusted_set, }; + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_trusted_handler); +#endif diff --git a/fs/ext4/xattr_user.c b/fs/ext4/xattr_user.c index ad35215f66104c..26087e98677be6 100644 --- a/fs/ext4/xattr_user.c +++ b/fs/ext4/xattr_user.c @@ -48,3 +48,7 @@ const struct xattr_handler ext4_xattr_user_handler = { .get = ext4_xattr_user_get, .set = ext4_xattr_user_set, }; + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_user_handler); +#endif From b82144c319f92784f3ac2ee8c989cf8e265c64c8 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Thu, 5 Nov 2026 03:19:14 +0000 Subject: [PATCH 1556/2102] ext4: add KUnit tests for fs/ext4/namei.c Add the ext4_namei_test KUnit test suite in fs/ext4/namei-test.c and shared internal HTree definitions in fs/ext4/namei.h to exercise directory lookup, HTree indexing, and namespace operations in fs/ext4/namei.c without requiring a mounted block device: - Directory leaf tail initialization (ext4_initialize_dirent_tail), metadata CRC32C checksum calculation and verification (ext4_dirblock_csum_verify, ext4_handle_dirty_dirblock), and corrupted tail/checksum detection. - HTree root and interior node limit calculations (dx_root_limit, dx_node_limit), entry accessors (dx_get_block, dx_set_block, dx_get_hash, dx_set_hash, dx_get_count, dx_get_limit, dx_set_count, dx_set_limit), and index block checksum verification (ext4_dx_csum_set, ext4_dx_csum_verify). - Directory block reading (__ext4_read_dirblock) across 10 parameterized cases covering valid leaf and index blocks, unmapped holes (EITHER vs. block 0 vs. DIRENT_HTREE), reads past i_size, ext4_bread -EIO propagation, leaf block found when expecting INDEX, and corrupted leaf/index checksums (-EFSBADCRC). - New directory initialization (ext4_init_new_dir, ext4_init_dirblock with and without inline directory conversion data) and directory block appending (ext4_append), including s_max_dir_size_kb limit enforcement (-ENOSPC) and pre-allocated logical block detection (-EFSCORRUPTED). - Directory entry destination search (ext4_find_dest_de), insertion (ext4_insert_dentry), linear search (ext4_search_dir), and deletion (ext4_delete_entry, ext4_generic_delete_entry) for both first-entry inode zeroing and predecessor rec_len merging. - Directory emptiness checks (ext4_empty_dir) across fresh, populated, deleted, multi-block with unmapped holes, and corrupted '.'/'..' directories. - HTree leaf splitting and index helpers (dx_make_map, dx_sort_map exercising both combsort and bubble-sort phases, dx_move_dirents, dx_pack_dirents, and dx_insert_block). - HTree root validation (ext4_check_dx_root), multi-level index probing (dx_probe), and continuation block traversal (ext4_htree_next_block) across 14 parameterized valid and corrupted on-disk layouts (invalid '.'/'..' entries, bad hash_version, SipHash without hash-in-dirent, non-zero unused_flags, excessive indirect_levels, limit mismatch, zero entry count, and tree cycle detection). - End-to-end HTree conversion (make_indexed_dir), leaf splitting (do_split / ext4_dx_add_entry), indexed lookup (ext4_dx_find_entry), and readdir red-black tree population (ext4_htree_fill_tree). - HTree index level growth (splitting a full dx_root into a 2-level tree and splitting a full interior dx_node), max HTree level -ENOSPC enforcement, and corrupted dx_root fallback in __ext4_find_entry and __ext4_add_entry. - Inline directory lifecycle through namei.c entry points (ext4_init_new_dir, ext4_empty_dir, ext4_add_entry, ext4_find_entry, ext4_delete_entry, and ext4_htree_fill_tree). - Directory link count helpers (ext4_inc_count, ext4_dec_count including EXT4_LINK_MAX wrap to 1), VFS lookup (ext4_lookup) and parent resolution (ext4_get_parent) error paths (-ENAMETOOLONG, self-linked directory entry, invalid inode number, and -ESTALE to -EFSCORRUPTED translation). - Hard link creation (__ext4_link, ext4_link including 0-nlink tmpfile orphan removal, EXT4_INODE_PROJINHERIT -EXDEV, and EXT4_LINK_MAX -EMLINK), unlinking (__ext4_unlink, ext4_unlink including orphan addition and EXT4_FC_REPLAY inode mismatch handling), and directory removal (ext4_rmdir). - Same-directory rename, overwrite rename, cross-directory subdirectory rename, RENAME_EXCHANGE (ext4_cross_rename), project quota inheritance -EXDEV checks, 0-nlink target -EFSCORRUPTED check, slow symlink block initialization (ext4_init_symlink_block), and case-folded (EXT4_INODE_CASEFOLD) directory lookup and strict UTF-8 validation. Export the tested functions with EXPORT_SYMBOL_FOR_EXT4_TEST and add KUNIT_STATIC_STUB_REDIRECT hooks for ext4_orphan_add and ext4_orphan_del. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 3 +- fs/ext4/crypto.c | 4 + fs/ext4/dir.c | 4 + fs/ext4/namei-test.c | 2337 ++++++++++++++++++++++++++++++++++++++++++ fs/ext4/namei.c | 338 +++--- fs/ext4/namei.h | 213 ++++ fs/ext4/orphan.c | 7 + 7 files changed, 2741 insertions(+), 165 deletions(-) create mode 100644 fs/ext4/namei-test.c create mode 100644 fs/ext4/namei.h diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 13040b97d2ffc0..8fe7b512ebb426 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -16,7 +16,8 @@ ext4-$(CONFIG_EXT4_FS_POSIX_ACL) += acl.o ext4-$(CONFIG_EXT4_FS_SECURITY) += xattr_security.o ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ - extents_status-test.o xattr-test.o + extents_status-test.o xattr-test.o \ + namei-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/crypto.c b/fs/ext4/crypto.c index 318b2eaea74127..002ba8837d33af 100644 --- a/fs/ext4/crypto.c +++ b/fs/ext4/crypto.c @@ -37,6 +37,7 @@ int ext4_fname_setup_filename(struct inode *dir, const struct qstr *iname, return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fname_setup_filename); int ext4_fname_prepare_lookup(struct inode *dir, struct dentry *dentry, struct ext4_filename *fname) @@ -55,6 +56,7 @@ int ext4_fname_prepare_lookup(struct inode *dir, struct dentry *dentry, ext4_fname_free_filename(fname); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fname_prepare_lookup); void ext4_fname_free_filename(struct ext4_filename *fname) { @@ -69,6 +71,7 @@ void ext4_fname_free_filename(struct ext4_filename *fname) ext4_fname_free_ci_filename(fname); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fname_free_filename); static bool uuid_is_zero(__u8 u[16]) { @@ -255,3 +258,4 @@ const struct fscrypt_operations ext4_cryptops = { .empty_dir = ext4_empty_dir, .has_stable_inodes = ext4_has_stable_inodes, }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_cryptops); diff --git a/fs/ext4/dir.c b/fs/ext4/dir.c index e921e12acbd749..f9b6aaabcd1772 100644 --- a/fs/ext4/dir.c +++ b/fs/ext4/dir.c @@ -126,6 +126,7 @@ int __ext4_check_dir_entry(const char *function, unsigned int line, return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_check_dir_entry); static int ext4_readdir(struct file *file, struct dir_context *ctx) { @@ -475,6 +476,7 @@ void ext4_htree_free_dir_info(struct dir_private_info *p) free_rb_tree_fname(&p->root); kfree(p); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_htree_free_dir_info); /* * Given a directory entry, enter it into the fname rb tree. @@ -535,6 +537,7 @@ int ext4_htree_store_dirent(struct file *dir_file, __u32 hash, rb_insert_color(&new_fn->rb_hash, &info->root); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_htree_store_dirent); @@ -683,6 +686,7 @@ int ext4_check_all_de(struct inode *dir, struct buffer_head *bh, void *buf, return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_all_de); static int ext4_dir_open(struct inode *inode, struct file *file) { diff --git a/fs/ext4/namei-test.c b/fs/ext4/namei-test.c new file mode 100644 index 00000000000000..6dde9e5cc3327e --- /dev/null +++ b/fs/ext4/namei-test.c @@ -0,0 +1,2337 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 directory lookup, HTree indexing, and namespace + * operations (fs/ext4/namei.c). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" +#include "namei.h" + +#define TEST_BLK_SIZE 1024 +#define TEST_BLK_BITS 10 +#define TEST_INODE_SIZE 256 +#define TEST_EXTRA_ISIZE (sizeof(struct ext4_inode) - \ + EXT4_GOOD_OLD_INODE_SIZE) +#define TEST_FIRST_PBLK 100 +#define TEST_MAX_BLOCKS 64 +#define TEST_MAX_LBLOCKS 16 +#define TEST_MAX_INODES 8 + +#define TEST_ROOT_INO EXT4_ROOT_INO +#define TEST_DIR_INO 12 +#define TEST_DIR2_INO 13 +#define TEST_SUBDIR_INO 14 +#define TEST_FILE1_INO 15 +#define TEST_FILE2_INO 16 +#define TEST_FILE3_INO 17 +#define TEST_CSUM_SEED 0x12345678U + +struct mock_block { + bool in_use; + struct buffer_head bh; + char data[TEST_BLK_SIZE] __aligned(8); +}; + +struct mock_inode_slot { + bool allocated; + struct ext4_inode_info ei; + struct buffer_head iloc_bh; + char raw_buf[TEST_INODE_SIZE] __aligned(8); + ext4_fsblk_t lblk_to_pblk[TEST_MAX_LBLOCKS]; +}; + +struct namei_test_ctx { + struct super_block sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct block_device bdev; + struct address_space bd_mapping; + struct buffer_head sb_bh; + + struct mock_inode_slot inodes[TEST_MAX_INODES]; + struct mock_block blocks[TEST_MAX_BLOCKS]; + + int fail_map_blocks; + int force_map_blocks_ret; + int fail_getblk; + int fail_get_inode_loc; + int fail_mark_iloc_dirty; + int fail_dirty_metadata; + int fail_iget; + + unsigned long last_iget_ino; + unsigned int orphan_add_calls; + unsigned long last_orphan_add_ino; + unsigned int orphan_del_calls; + unsigned long last_orphan_del_ino; + unsigned int dirty_metadata_calls; + unsigned int mark_inode_dirty_calls; +}; + +static const struct super_operations namei_test_sops = {}; + +#ifdef CONFIG_QUOTA +static qsize_t *namei_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations namei_test_qops = { + .get_reserved_space = namei_test_get_reserved_space, +}; +#endif + +static void init_mock_inode_slot(struct namei_test_ctx *ctx, + struct mock_inode_slot *slot, + unsigned long ino, umode_t mode) +{ + struct inode *inode = &slot->ei.vfs_inode; + struct ext4_inode *raw_inode; + + memset(slot, 0, sizeof(*slot)); + slot->allocated = true; + + inode->i_sb = &ctx->sb; + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = TEST_BLK_BITS; + inode->i_mapping = &inode->i_data; + set_nlink(inode, S_ISDIR(mode) ? 2 : 1); + atomic_set(&inode->i_count, 1); + + spin_lock_init(&inode->i_lock); + init_rwsem(&inode->i_rwsem); + INIT_LIST_HEAD(&inode->i_io_list); + INIT_LIST_HEAD(&inode->i_wb_list); + INIT_LIST_HEAD(&inode->i_lru); + INIT_HLIST_NODE(&inode->i_hash); + /* + * Pre-set all I_DIRTY flags so mark_inode_dirty() is a fastpath + * no-op that does not touch superblock/bdi writeback lists. + */ + inode_state_set_raw(inode, I_DIRTY); + + init_rwsem(&slot->ei.xattr_sem); + init_rwsem(&slot->ei.i_data_sem); + INIT_LIST_HEAD(&slot->ei.i_orphan); + INIT_LIST_HEAD(&slot->ei.i_fc_list); + spin_lock_init(&slot->ei.i_fc_lock); + spin_lock_init(&slot->ei.i_raw_lock); + + slot->ei.i_extra_isize = TEST_EXTRA_ISIZE; + slot->ei.i_csum_seed = TEST_CSUM_SEED ^ (u32)ino; + slot->ei.i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + + slot->iloc_bh.b_data = slot->raw_buf; + slot->iloc_bh.b_size = TEST_INODE_SIZE; + slot->iloc_bh.b_blocknr = 10 + ino; + atomic_set(&slot->iloc_bh.b_count, 1); + set_buffer_uptodate(&slot->iloc_bh); + + raw_inode = (struct ext4_inode *)slot->raw_buf; + raw_inode->i_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); +} + +static struct mock_inode_slot *find_inode_slot_by_ino(struct namei_test_ctx *ctx, + unsigned long ino) +{ + int i; + + for (i = 0; i < TEST_MAX_INODES; i++) { + if (ctx->inodes[i].allocated && + ctx->inodes[i].ei.vfs_inode.i_ino == ino) + return &ctx->inodes[i]; + } + return NULL; +} + +static struct mock_inode_slot *find_inode_slot(struct namei_test_ctx *ctx, + struct inode *inode) +{ + return find_inode_slot_by_ino(ctx, inode->i_ino); +} + +static struct inode *get_mock_inode(struct namei_test_ctx *ctx, + unsigned long ino) +{ + struct mock_inode_slot *slot = find_inode_slot_by_ino(ctx, ino); + + return slot ? &slot->ei.vfs_inode : NULL; +} + +static struct mock_block *get_mock_block(struct namei_test_ctx *ctx, + ext4_fsblk_t pblk) +{ + unsigned long idx; + + if (pblk < TEST_FIRST_PBLK) + return NULL; + idx = pblk - TEST_FIRST_PBLK; + if (idx >= TEST_MAX_BLOCKS) + return NULL; + return &ctx->blocks[idx]; +} + +static ext4_fsblk_t alloc_mock_pblk(struct namei_test_ctx *ctx) +{ + int i; + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + if (!ctx->blocks[i].in_use) { + ctx->blocks[i].in_use = true; + memset(ctx->blocks[i].data, 0, TEST_BLK_SIZE); + set_buffer_uptodate(&ctx->blocks[i].bh); + clear_buffer_verified(&ctx->blocks[i].bh); + return TEST_FIRST_PBLK + i; + } + } + return 0; +} + +static struct buffer_head *map_and_get_dir_bh(struct namei_test_ctx *ctx, + struct inode *inode, + ext4_lblk_t lblk) +{ + struct mock_inode_slot *slot = find_inode_slot(ctx, inode); + struct mock_block *blk; + ext4_fsblk_t pblk; + + if (!slot || lblk >= TEST_MAX_LBLOCKS) + return NULL; + pblk = slot->lblk_to_pblk[lblk]; + if (!pblk) { + pblk = alloc_mock_pblk(ctx); + if (!pblk) + return NULL; + slot->lblk_to_pblk[lblk] = pblk; + } + blk = get_mock_block(ctx, pblk); + return blk ? &blk->bh : NULL; +} + +static void init_mock_dentry(struct dentry *dentry, struct dentry *parent, + const char *name, struct inode *inode, + struct super_block *sb) +{ + memset(dentry, 0, sizeof(*dentry)); + spin_lock_init(&dentry->d_lock); + seqcount_spinlock_init(&dentry->d_seq, &dentry->d_lock); + INIT_HLIST_NODE(&dentry->d_sib); + INIT_HLIST_HEAD(&dentry->d_children); + INIT_HLIST_BL_NODE(&dentry->d_hash); + dentry->d_parent = parent ? parent : dentry; + dentry->d_sb = sb; + dentry->__d_name.name = (const unsigned char *)name; + dentry->__d_name.len = strlen(name); + if (inode) { + dentry->d_inode = inode; + dentry->d_flags = S_ISDIR(inode->i_mode) ? + DCACHE_DIRECTORY_TYPE : DCACHE_REGULAR_TYPE; + } else { + dentry->d_flags = DCACHE_MISS_TYPE; + } +} + +/* --- KUnit Static Stubs --- */ + +static int ext4_map_blocks_stub(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + ext4_fsblk_t pblk; + + if (ctx->fail_map_blocks) + return ctx->fail_map_blocks; + if (ctx->force_map_blocks_ret) + return ctx->force_map_blocks_ret; + + slot = find_inode_slot(ctx, inode); + if (!slot || map->m_lblk >= TEST_MAX_LBLOCKS) + return -EFSCORRUPTED; + + pblk = slot->lblk_to_pblk[map->m_lblk]; + if (pblk) { + map->m_pblk = pblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED; + return 1; + } + + if (!(flags & EXT4_GET_BLOCKS_CREATE)) { + map->m_pblk = 0; + map->m_flags = 0; + return 0; + } + + pblk = alloc_mock_pblk(ctx); + if (!pblk) + return -ENOSPC; + + slot->lblk_to_pblk[map->m_lblk] = pblk; + map->m_pblk = pblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED | EXT4_MAP_NEW; + return 1; +} + +static struct buffer_head *ext4_getblk_stub(handle_t *handle, + struct inode *inode, + ext4_lblk_t block, int map_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + struct mock_block *blk; + ext4_fsblk_t pblk; + + if (ctx->fail_getblk) + return ERR_PTR(ctx->fail_getblk); + + slot = find_inode_slot(ctx, inode); + if (!slot || block >= TEST_MAX_LBLOCKS) + return ERR_PTR(-EFSCORRUPTED); + + pblk = slot->lblk_to_pblk[block]; + if (!pblk) { + if (!(map_flags & EXT4_GET_BLOCKS_CREATE)) + return NULL; + pblk = alloc_mock_pblk(ctx); + if (!pblk) + return ERR_PTR(-ENOSPC); + slot->lblk_to_pblk[block] = pblk; + } + + blk = get_mock_block(ctx, pblk); + if (!blk) + return ERR_PTR(-EFSCORRUPTED); + + get_bh(&blk->bh); + return &blk->bh; +} + +static int ext4_get_inode_loc_stub(struct inode *inode, struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + + if (ctx->fail_get_inode_loc) + return ctx->fail_get_inode_loc; + + slot = find_inode_slot(ctx, inode); + if (!slot) + return -ENOENT; + + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int ext4_mark_iloc_dirty_stub(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + brelse(iloc->bh); + iloc->bh = NULL; + if (ctx->fail_mark_iloc_dirty) + return ctx->fail_mark_iloc_dirty; + return 0; +} + +static int ext4_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + ctx->mark_inode_dirty_calls++; + if (ctx->fail_mark_iloc_dirty) + return ctx->fail_mark_iloc_dirty; + return 0; +} + +static int ext4_handle_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + ctx->dirty_metadata_calls++; + if (ctx->fail_dirty_metadata) + return ctx->fail_dirty_metadata; + return 0; +} + +static struct inode *ext4_iget_stub(struct super_block *sb, unsigned long ino, + ext4_iget_flags flags, + const char *function, unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + ctx->last_iget_ino = ino; + if (ctx->fail_iget) + return ERR_PTR(ctx->fail_iget); + return ERR_PTR(-ENOENT); +} + +static int ext4_orphan_add_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + ctx->orphan_add_calls++; + ctx->last_orphan_add_ino = inode->i_ino; + if (list_empty(&EXT4_I(inode)->i_orphan)) + list_add(&EXT4_I(inode)->i_orphan, &ctx->sbi.s_orphan); + return 0; +} + +static int ext4_orphan_del_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + ctx->orphan_del_calls++; + ctx->last_orphan_del_ino = inode->i_ino; + list_del_init(&EXT4_I(inode)->i_orphan); + return 0; +} + +static int namei_test_init(struct kunit *test) +{ + struct namei_test_ctx *ctx; + int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); + test->priv = ctx; + + ctx->sb.s_blocksize = TEST_BLK_SIZE; + ctx->sb.s_blocksize_bits = TEST_BLK_BITS; + ctx->sb.s_magic = EXT4_SUPER_MAGIC; + ctx->sb.s_maxbytes = MAX_LFS_FILESIZE; + ctx->sb.s_time_gran = 1; + ctx->sb.s_op = &namei_test_sops; + ctx->sb.s_fs_info = &ctx->sbi; + ctx->sb.s_bdev = &ctx->bdev; +#ifdef CONFIG_FS_ENCRYPTION + ctx->sb.s_cop = &ext4_cryptops; +#endif +#ifdef CONFIG_QUOTA + ctx->sb.dq_op = &namei_test_qops; +#endif + ctx->bdev.bd_mapping = &ctx->bd_mapping; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + init_rwsem(&ctx->sb.s_umount); + strscpy(ctx->sb.s_id, "ext4_namei_kunit", sizeof(ctx->sb.s_id)); + + ctx->sbi.s_sb = &ctx->sb; + ctx->sbi.s_es = &ctx->es; + ctx->sbi.s_sbh = &ctx->sb_bh; + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + ctx->sbi.s_first_ino = EXT4_GOOD_OLD_FIRST_INO; + ctx->sbi.s_want_extra_isize = TEST_EXTRA_ISIZE; + ctx->sbi.s_def_hash_version = DX_HASH_HALF_MD4; + ctx->sbi.s_hash_unsigned = 3; + ctx->sbi.s_hash_seed[0] = 0x11223344U; + ctx->sbi.s_hash_seed[1] = 0x55667788U; + ctx->sbi.s_hash_seed[2] = 0x99aabbccU; + ctx->sbi.s_hash_seed[3] = 0xddeeff00U; + ctx->sbi.s_csum_seed = TEST_CSUM_SEED; + set_opt(&ctx->sb, ERRORS_CONT); + spin_lock_init(&ctx->sbi.s_bdev_wb_lock); + spin_lock_init(&ctx->sbi.s_error_lock); + spin_lock_init(&ctx->sbi.s_md_lock); + mutex_init(&ctx->sbi.s_orphan_lock); + INIT_LIST_HEAD(&ctx->sbi.s_orphan); + ratelimit_state_init(&ctx->sbi.s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + ctx->es.s_inodes_count = cpu_to_le32(1024); + ctx->es.s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); + ctx->es.s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_FILETYPE); + ctx->es.s_feature_compat = cpu_to_le32(EXT4_FEATURE_COMPAT_DIR_INDEX); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = TEST_BLK_SIZE; + ctx->sb_bh.b_blocknr = 1; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + struct buffer_head *bh = &ctx->blocks[i].bh; + + bh->b_data = ctx->blocks[i].data; + bh->b_size = TEST_BLK_SIZE; + bh->b_blocknr = TEST_FIRST_PBLK + i; + atomic_set(&bh->b_count, 1); + set_buffer_uptodate(bh); + } + + init_mock_inode_slot(ctx, &ctx->inodes[0], TEST_ROOT_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[1], TEST_DIR_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[2], TEST_DIR2_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[3], TEST_SUBDIR_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[4], TEST_FILE1_INO, + S_IFREG | 0644); + init_mock_inode_slot(ctx, &ctx->inodes[5], TEST_FILE2_INO, + S_IFREG | 0644); + init_mock_inode_slot(ctx, &ctx->inodes[6], TEST_FILE3_INO, + S_IFLNK | 0777); + + kunit_activate_static_stub(test, ext4_map_blocks, ext4_map_blocks_stub); + kunit_activate_static_stub(test, ext4_getblk, ext4_getblk_stub); + kunit_activate_static_stub(test, ext4_get_inode_loc, + ext4_get_inode_loc_stub); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + ext4_mark_iloc_dirty_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + ext4_mark_inode_dirty_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + ext4_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_iget, ext4_iget_stub); + kunit_activate_static_stub(test, ext4_orphan_add, ext4_orphan_add_stub); + kunit_activate_static_stub(test, ext4_orphan_del, ext4_orphan_del_stub); + + return 0; +} + +static void namei_test_exit(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + + if (!ctx) + return; +#if IS_ENABLED(CONFIG_UNICODE) + utf8_unload(ctx->sb.s_encoding); + ctx->sb.s_encoding = NULL; +#endif +} + +/* + * Test 1: Directory leaf tail initialization, checksum computation, and + * verification (ext4_initialize_dirent_tail, ext4_dirblock_csum_verify, + * ext4_handle_dirty_dirblock). + */ +static void test_namei_dirent_tail_and_csum(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct buffer_head *bh; + struct ext4_dir_entry_tail *t; + int err; + + bh = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + + /* Without METADATA_CSUM, verification always succeeds */ + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); + + /* Enable METADATA_CSUM */ + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + /* Uninitialized tail fails verification */ + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 0); + + /* Initialize directory block and tail, then compute csum */ + err = ext4_init_dirblock(NULL, dir, bh, TEST_ROOT_INO, NULL, 0); + KUNIT_ASSERT_EQ(test, err, 0); + + t = EXT4_DIRENT_TAIL(bh->b_data, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(t->det_reserved_zero1), 0U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(t->det_rec_len), + sizeof(struct ext4_dir_entry_tail)); + KUNIT_EXPECT_EQ(test, t->det_reserved_zero2, 0); + KUNIT_EXPECT_EQ(test, t->det_reserved_ft, EXT4_FT_DIR_CSUM); + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); + + /* Flip a bit in the directory data -> checksum mismatch */ + bh->b_data[0] ^= 0x01; + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 0); + bh->b_data[0] ^= 0x01; + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); + + /* Corrupt tail reserved_ft -> get_dirent_tail() rejects it */ + t->det_reserved_ft = EXT4_FT_REG_FILE; + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 0); + ext4_initialize_dirent_tail(bh, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh), 0); + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); +} + +/* + * Test 2: HTree dx_entry accessors, dx_root_limit / dx_node_limit, and + * dx_root / dx_node metadata checksum verification (ext4_dx_csum_set_test, + * ext4_dx_csum_verify_test). + */ +static void test_namei_dx_helpers_and_csum(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct buffer_head *root_bh, *node_bh; + struct dx_root *root; + struct dx_node *node; + struct dx_entry *entries; + + root_bh = map_and_get_dir_bh(ctx, dir, 0); + node_bh = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, root_bh); + KUNIT_ASSERT_NOT_NULL(test, node_bh); + + /* Check limits without METADATA_CSUM (1024B block) */ + /* Root: (1024 - 12 - 12 - 8) / 8 = 124 */ + KUNIT_EXPECT_EQ(test, + dx_root_limit(dir, sizeof(struct dx_root_info)), 124U); + /* Node: (1024 - 8) / 8 = 127 */ + KUNIT_EXPECT_EQ(test, dx_node_limit(dir), 127U); + + /* Enable METADATA_CSUM -> 1 fewer entry for 8-byte dx_tail */ + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + KUNIT_EXPECT_EQ(test, + dx_root_limit(dir, sizeof(struct dx_root_info)), 123U); + KUNIT_EXPECT_EQ(test, dx_node_limit(dir), 126U); + + /* Set up a valid dx_root in root_bh */ + root = (struct dx_root *)root_bh->b_data; + root->dot.inode = cpu_to_le32(dir->i_ino); + root->dot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot.name_len = 1; + root->dot.file_type = EXT4_FT_DIR; + strscpy(root->dot_name, ".", sizeof(root->dot_name)); + + root->dotdot.inode = cpu_to_le32(TEST_ROOT_INO); + root->dotdot.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE - 12, + TEST_BLK_SIZE); + root->dotdot.name_len = 2; + root->dotdot.file_type = EXT4_FT_DIR; + strscpy(root->dotdot_name, "..", sizeof(root->dotdot_name)); + + root->info.info_length = sizeof(struct dx_root_info); + root->info.hash_version = DX_HASH_HALF_MD4; + entries = root->entries; + dx_set_limit(entries, dx_root_limit(dir, sizeof(struct dx_root_info))); + dx_set_count(entries, 2); + dx_set_block(entries + 0, 0xf0000001U); /* high 4 bits masked */ + dx_set_hash(entries + 1, 0x80001234U); + dx_set_block(entries + 1, 2); + + KUNIT_EXPECT_EQ(test, dx_get_limit(entries), 123U); + KUNIT_EXPECT_EQ(test, dx_get_count(entries), 2U); + KUNIT_EXPECT_EQ(test, dx_get_block(entries + 0), 1U); + KUNIT_EXPECT_EQ(test, dx_get_hash(entries + 1), 0x80001234U); + KUNIT_EXPECT_EQ(test, dx_get_block(entries + 1), 2U); + + ext4_dx_csum_set_test(dir, (struct ext4_dir_entry *)root_bh->b_data); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)root_bh->b_data), 1); + + /* Corrupt hash -> csum verify fails */ + dx_set_hash(entries + 1, 0x80001235U); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)root_bh->b_data), 0); + dx_set_hash(entries + 1, 0x80001234U); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)root_bh->b_data), 1); + + /* Overflow limit -> no space for csum fails */ + dx_set_limit(entries, 200); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)root_bh->b_data), 0); + + /* Set up a valid dx_node in node_bh */ + node = (struct dx_node *)node_bh->b_data; + node->fake.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE, TEST_BLK_SIZE); + dx_set_limit(node->entries, dx_node_limit(dir)); + dx_set_count(node->entries, 2); + dx_set_block(node->entries + 0, 3); + dx_set_hash(node->entries + 1, 0x40000000U); + dx_set_block(node->entries + 1, 4); + + ext4_dx_csum_set_test(dir, (struct ext4_dir_entry *)node_bh->b_data); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)node_bh->b_data), 1); + + /* Corrupt fake.rec_len -> get_dx_countlimit returns NULL */ + node->fake.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)node_bh->b_data), 0); +} + +/* + * Test 3: Parameterized tests for __ext4_read_dirblock (ext4_read_dirblock_test). + */ +enum read_dirblock_case_id { + RDB_VALID_LEAF, + RDB_VALID_INDEX, + RDB_HOLE_ALLOWED_EITHER, + RDB_PAST_ISIZE, + RDB_BREAD_EIO, + RDB_HOLE_AT_BLOCK0, + RDB_HOLE_FOR_HTREE_LEAF, + RDB_LEAF_INSTEAD_OF_INDEX, + RDB_BAD_LEAF_CSUM, + RDB_BAD_INDEX_CSUM, +}; + +struct read_dirblock_param { + const char *desc; + enum read_dirblock_case_id id; + ext4_lblk_t block; + enum dirblock_type type; + int expected_err; + bool expect_null; +}; + +static const struct read_dirblock_param read_dirblock_params[] = { + { + .desc = "valid leaf block with metadata_csum", + .id = RDB_VALID_LEAF, + .block = 0, + .type = DIRENT, + .expected_err = 0, + }, + { + .desc = "valid dx_root index block with metadata_csum", + .id = RDB_VALID_INDEX, + .block = 0, + .type = INDEX, + .expected_err = 0, + }, + { + .desc = "hole at block > 0 with EITHER returns NULL", + .id = RDB_HOLE_ALLOWED_EITHER, + .block = 1, + .type = EITHER, + .expected_err = 0, + .expect_null = true, + }, + { + .desc = "reading block past i_size returns -EFSCORRUPTED", + .id = RDB_PAST_ISIZE, + .block = 2, + .type = EITHER, + .expected_err = -EFSCORRUPTED, + }, + { + .desc = "ext4_bread -EIO error propagates", + .id = RDB_BREAD_EIO, + .block = 0, + .type = DIRENT, + .expected_err = -EIO, + }, + { + .desc = "hole at block 0 returns -EFSCORRUPTED", + .id = RDB_HOLE_AT_BLOCK0, + .block = 0, + .type = EITHER, + .expected_err = -EFSCORRUPTED, + }, + { + .desc = "hole for DIRENT_HTREE returns -EFSCORRUPTED", + .id = RDB_HOLE_FOR_HTREE_LEAF, + .block = 1, + .type = DIRENT_HTREE, + .expected_err = -EFSCORRUPTED, + }, + { + .desc = "leaf block found when expecting INDEX returns -EFSCORRUPTED", + .id = RDB_LEAF_INSTEAD_OF_INDEX, + .block = 1, + .type = INDEX, + .expected_err = -EFSCORRUPTED, + }, + { + .desc = "corrupted leaf checksum returns -EFSBADCRC", + .id = RDB_BAD_LEAF_CSUM, + .block = 0, + .type = DIRENT, + .expected_err = -EFSBADCRC, + }, + { + .desc = "corrupted index checksum returns -EFSBADCRC", + .id = RDB_BAD_INDEX_CSUM, + .block = 0, + .type = INDEX, + .expected_err = -EFSBADCRC, + }, +}; + +static void read_dirblock_get_desc(const struct read_dirblock_param *p, + char *desc) +{ + strscpy(desc, p->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(read_dirblock, read_dirblock_params, read_dirblock_get_desc); + +static void test_namei_read_dirblock(struct kunit *test) +{ + const struct read_dirblock_param *p = test->param_value; + struct namei_test_ctx *ctx = test->priv; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct buffer_head *bh, *res; + struct dx_root *root; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + dir->i_size = 2 * TEST_BLK_SIZE; + + switch (p->id) { + case RDB_VALID_LEAF: + bh = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_ASSERT_EQ(test, + ext4_init_dirblock(NULL, dir, bh, TEST_ROOT_INO, + NULL, 0), 0); + clear_buffer_verified(bh); + break; + case RDB_VALID_INDEX: + case RDB_BAD_INDEX_CSUM: + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + bh = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + root = (struct dx_root *)bh->b_data; + root->dot.inode = cpu_to_le32(dir->i_ino); + root->dot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot.name_len = 1; + strscpy(root->dot_name, ".", sizeof(root->dot_name)); + root->dotdot.inode = cpu_to_le32(TEST_ROOT_INO); + root->dotdot.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE - 12, + TEST_BLK_SIZE); + root->dotdot.name_len = 2; + strscpy(root->dotdot_name, "..", sizeof(root->dotdot_name)); + root->info.info_length = sizeof(struct dx_root_info); + root->info.hash_version = DX_HASH_HALF_MD4; + dx_set_limit(root->entries, + dx_root_limit(dir, sizeof(struct dx_root_info))); + dx_set_count(root->entries, 1); + dx_set_block(root->entries, 1); + ext4_dx_csum_set_test(dir, (struct ext4_dir_entry *)bh->b_data); + if (p->id == RDB_BAD_INDEX_CSUM) + dx_set_block(root->entries, 99); + clear_buffer_verified(bh); + break; + case RDB_HOLE_ALLOWED_EITHER: + case RDB_PAST_ISIZE: + case RDB_HOLE_AT_BLOCK0: + case RDB_HOLE_FOR_HTREE_LEAF: + break; + case RDB_BREAD_EIO: + ctx->fail_getblk = -EIO; + break; + case RDB_LEAF_INSTEAD_OF_INDEX: + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + bh = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_ASSERT_EQ(test, + ext4_init_dirblock(NULL, dir, bh, TEST_ROOT_INO, + NULL, 0), 0); + clear_buffer_verified(bh); + break; + case RDB_BAD_LEAF_CSUM: + bh = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_ASSERT_EQ(test, + ext4_init_dirblock(NULL, dir, bh, TEST_ROOT_INO, + NULL, 0), 0); + bh->b_data[0] ^= 0xff; + clear_buffer_verified(bh); + break; + } + + res = ext4_read_dirblock_test(dir, p->block, p->type); + if (p->expected_err) { + KUNIT_EXPECT_TRUE(test, IS_ERR(res)); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), p->expected_err); + } else if (p->expect_null) { + KUNIT_EXPECT_NULL(test, res); + } else { + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(res)); + KUNIT_EXPECT_TRUE(test, buffer_verified(res)); + brelse(res); + } +} + +/* + * Test 4: Directory initialization and block appending (ext4_init_new_dir, + * ext4_append_test, s_max_dir_size_kb limit, already-allocated block check, + * and ext4_init_dirblock with inline_buf conversion data). + */ +static void test_namei_append_and_init_dir(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct buffer_head *bh; + struct ext4_dir_entry_2 *de; + char inline_entries[64]; + ext4_lblk_t lblk = 0; + int err; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + err = ext4_init_new_dir(NULL, root_dir, dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 2U); + KUNIT_EXPECT_EQ(test, dir->i_size, (loff_t)TEST_BLK_SIZE); + + /* Append a second block (lblk 1) */ + bh = ext4_append_test(NULL, dir, &lblk); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_EXPECT_EQ(test, lblk, 1U); + KUNIT_EXPECT_EQ(test, dir->i_size, (loff_t)(2 * TEST_BLK_SIZE)); + brelse(bh); + + /* Enforce s_max_dir_size_kb limit -> -ENOSPC */ + ctx->sbi.s_max_dir_size_kb = 2; + bh = ext4_append_test(NULL, dir, &lblk); + KUNIT_EXPECT_TRUE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -ENOSPC); + ctx->sbi.s_max_dir_size_kb = 0; + + /* Pre-allocated logical block at append target -> -EFSCORRUPTED */ + ctx->force_map_blocks_ret = 1; + bh = ext4_append_test(NULL, dir, &lblk); + KUNIT_EXPECT_TRUE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + ctx->force_map_blocks_ret = 0; + + /* Test ext4_init_dirblock with non-NULL inline_buf */ + memset(inline_entries, 0, sizeof(inline_entries)); + de = (struct ext4_dir_entry_2 *)inline_entries; + de->inode = cpu_to_le32(TEST_FILE1_INO); + de->name_len = 3; + de->file_type = EXT4_FT_REG_FILE; + memcpy(de->name, "foo", 3); + de->rec_len = ext4_rec_len_to_disk(sizeof(inline_entries), + TEST_BLK_SIZE); + + bh = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, bh); + err = ext4_init_dirblock(NULL, dir, bh, TEST_ROOT_INO, + inline_entries, sizeof(inline_entries)); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); + + /* Verify '.', '..', and 'foo' in the initialized block */ + de = (struct ext4_dir_entry_2 *)bh->b_data; + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), dir->i_ino); + de = ext4_next_entry(de, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_ROOT_INO); + de = ext4_next_entry(de, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + KUNIT_EXPECT_EQ(test, de->name_len, 3); + KUNIT_EXPECT_MEMEQ(test, de->name, "foo", 3); + KUNIT_EXPECT_EQ(test, ext4_rec_len_from_disk(de->rec_len, TEST_BLK_SIZE), + TEST_BLK_SIZE - 24 - + (int)sizeof(struct ext4_dir_entry_tail)); +} + +/* + * Test 5: Directory entry destination search, insertion, linear lookup, and + * deletion (ext4_find_dest_de, ext4_insert_dentry, ext4_search_dir, + * ext4_delete_entry_test, ext4_generic_delete_entry). + */ +static void test_namei_search_insert_delete_dentry(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct buffer_head *bh; + struct ext4_dir_entry_2 *de = NULL, *res_de = NULL; + struct ext4_filename fname1, fname2; + struct qstr q1 = QSTR_INIT("alpha.txt", 9); + struct qstr q2 = QSTR_INIT("beta.txt", 8); + int csum_size = sizeof(struct ext4_dir_entry_tail); + int buf_size = TEST_BLK_SIZE - csum_size; + int err; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + bh = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + + KUNIT_ASSERT_EQ(test, ext4_fname_setup_filename(dir, &q1, 0, &fname1), 0); + KUNIT_ASSERT_EQ(test, ext4_fname_setup_filename(dir, &q2, 0, &fname2), 0); + + /* Find space and insert alpha.txt */ + err = ext4_find_dest_de(dir, bh, bh->b_data, buf_size, &fname1, &de); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_NOT_NULL(test, de); + ext4_insert_dentry(dir, file1, de, TEST_BLK_SIZE, &fname1); + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh), 0); + + /* Duplicate insert of alpha.txt must return -EEXIST */ + err = ext4_find_dest_de(dir, bh, bh->b_data, buf_size, &fname1, &de); + KUNIT_EXPECT_EQ(test, err, -EEXIST); + + /* Insert beta.txt */ + err = ext4_find_dest_de(dir, bh, bh->b_data, buf_size, &fname2, &de); + KUNIT_ASSERT_EQ(test, err, 0); + ext4_insert_dentry(dir, file2, de, TEST_BLK_SIZE, &fname2); + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh), 0); + + /* Search for both entries via ext4_search_dir */ + err = ext4_search_dir(bh, bh->b_data, buf_size, dir, &fname1, 0, + &res_de); + KUNIT_ASSERT_EQ(test, err, 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(res_de->inode), TEST_FILE1_INO); + KUNIT_EXPECT_EQ(test, res_de->file_type, EXT4_FT_REG_FILE); + + /* Delete alpha.txt via ext4_delete_entry_test (merges into '..') */ + err = ext4_delete_entry_test(NULL, dir, res_de, bh); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); + + /* alpha.txt is gone, beta.txt is still present */ + KUNIT_EXPECT_EQ(test, + ext4_search_dir(bh, bh->b_data, buf_size, dir, &fname1, 0, + &res_de), 0); + KUNIT_EXPECT_EQ(test, + ext4_search_dir(bh, bh->b_data, buf_size, dir, &fname2, 0, + &res_de), 1); + + /* + * Test deleting the very first entry in a buffer (pde == NULL), + * which zeroes de->inode while preserving rec_len. + */ + de = (struct ext4_dir_entry_2 *)bh->b_data; + err = ext4_generic_delete_entry(dir, de, bh, bh->b_data, + TEST_BLK_SIZE, csum_size); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), 0U); + KUNIT_EXPECT_EQ(test, ext4_rec_len_from_disk(de->rec_len, TEST_BLK_SIZE), + 12); + + /* Deleting a pointer not in the buffer returns -ENOENT */ + err = ext4_generic_delete_entry(dir, + (struct ext4_dir_entry_2 *)(bh->b_data + 500), + bh, bh->b_data, TEST_BLK_SIZE, csum_size); + KUNIT_EXPECT_EQ(test, err, -ENOENT); + + ext4_fname_free_filename(&fname1); + ext4_fname_free_filename(&fname2); +} + +/* + * Test 6: Directory emptiness validation (ext4_empty_dir) across fresh, + * non-empty, deleted, corrupt, and multi-block directories. + */ +static void test_namei_empty_dir(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry parent_dentry, file_dentry; + struct buffer_head *bh, *bh1; + struct ext4_dir_entry_2 *de = NULL; + ext4_lblk_t lblk; + + init_mock_dentry(&parent_dentry, NULL, "dir", dir, &ctx->sb); + init_mock_dentry(&file_dentry, &parent_dentry, "item", file1, &ctx->sb); + + /* Freshly initialized directory is empty */ + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + KUNIT_EXPECT_TRUE(test, ext4_empty_dir(dir)); + + /* Truncated i_size < 24 bytes is rejected as non-empty (corrupt) */ + dir->i_size = 12; + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); + dir->i_size = TEST_BLK_SIZE; + + /* Add an entry -> not empty */ + KUNIT_ASSERT_EQ(test, ext4_add_entry_test(NULL, &file_dentry, file1), 0); + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); + + /* Delete the entry -> empty again */ + bh = ext4_find_entry_test(dir, &file_dentry.d_name, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_ASSERT_EQ(test, ext4_delete_entry_test(NULL, dir, de, bh), 0); + brelse(bh); + KUNIT_EXPECT_TRUE(test, ext4_empty_dir(dir)); + + /* Multi-block directory with a hole at block 1 and an empty block 2 */ + dir->i_size = 2 * TEST_BLK_SIZE; /* block 1 is unmapped (hole) */ + bh1 = ext4_append_test(NULL, dir, &lblk); /* appends block 2 */ + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh1)); + KUNIT_EXPECT_EQ(test, lblk, 2U); + de = (struct ext4_dir_entry_2 *)bh1->b_data; + de->inode = 0; + de->rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE, TEST_BLK_SIZE); + KUNIT_EXPECT_TRUE(test, ext4_empty_dir(dir)); + + /* Active entry in block 2 makes directory non-empty */ + de->inode = cpu_to_le32(TEST_FILE1_INO); + de->name_len = 1; + de->name[0] = 'x'; + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); + de->inode = 0; + brelse(bh1); + + /* Corrupt '..' name in block 0 -> returns false */ + bh = map_and_get_dir_bh(ctx, dir, 0); + de = ext4_next_entry((struct ext4_dir_entry_2 *)bh->b_data, + TEST_BLK_SIZE); + de->name[1] = 'x'; + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); + de->name[1] = '.'; + + /* Corrupt '.' inode number in block 0 -> returns false */ + de = (struct ext4_dir_entry_2 *)bh->b_data; + de->inode = cpu_to_le32(999); + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); +} + +/* + * Test 7: HTree leaf splitting helpers: dx_make_map_test, dx_sort_map_test + * (exercising both combsort and bubble sort phases), dx_move_dirents_test, + * dx_pack_dirents_test, and dx_insert_block_test. + */ +static void test_namei_dx_map_pack_and_move(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct buffer_head *bh, *bh2; + struct dx_hash_info hinfo = {}; + struct dx_map_entry *map; + struct ext4_dir_entry_2 *de, *last_de; + struct dx_frame frame; + struct dx_entry entries[8]; + int i, count; + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + bh = map_and_get_dir_bh(ctx, dir, 0); + bh2 = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_ASSERT_NOT_NULL(test, bh2); + + /* Insert 16 entries into block 0 so count >= 18 (triggers combsort) */ + for (i = 0; i < 16; i++) { + char name[16]; + struct qstr q; + struct ext4_filename fname; + + snprintf(name, sizeof(name), "entry_%02d", i); + q.name = (const unsigned char *)name; + q.len = strlen(name); + KUNIT_ASSERT_EQ(test, + ext4_fname_setup_filename(dir, &q, 0, &fname), 0); + KUNIT_ASSERT_EQ(test, + ext4_find_dest_de(dir, bh, bh->b_data, TEST_BLK_SIZE, + &fname, &de), 0); + ext4_insert_dentry(dir, file1, de, TEST_BLK_SIZE, &fname); + ext4_fname_free_filename(&fname); + } + + hinfo.hash_version = DX_HASH_HALF_MD4 + ctx->sbi.s_hash_unsigned; + hinfo.seed = ctx->sbi.s_hash_seed; + + map = (struct dx_map_entry *)(bh2->b_data + TEST_BLK_SIZE); + count = dx_make_map_test(dir, bh, &hinfo, map); + /* 2 ('.' and '..') + 16 = 18 entries */ + KUNIT_ASSERT_EQ(test, count, 18); + + map -= count; + dx_sort_map_test(map, count); + for (i = 1; i < count; i++) + KUNIT_EXPECT_LE(test, map[i - 1].hash, map[i].hash); + + /* Move the second half (9 entries) to bh2 and pack the first half */ + last_de = dx_move_dirents_test(dir, bh->b_data, bh2->b_data, + map + 9, 9, TEST_BLK_SIZE); + KUNIT_ASSERT_NOT_NULL(test, last_de); + last_de->rec_len = ext4_rec_len_to_disk( + bh2->b_data + TEST_BLK_SIZE - (char *)last_de, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, + ext4_check_all_de(dir, bh2, bh2->b_data, TEST_BLK_SIZE), 0); + + last_de = dx_pack_dirents_test(dir, bh->b_data, TEST_BLK_SIZE); + KUNIT_ASSERT_NOT_NULL(test, last_de); + last_de->rec_len = ext4_rec_len_to_disk( + bh->b_data + TEST_BLK_SIZE - (char *)last_de, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, + ext4_check_all_de(dir, bh, bh->b_data, TEST_BLK_SIZE), 0); + + /* Test dx_insert_block_test shifting entries in a dx_frame */ + memset(entries, 0, sizeof(entries)); + dx_set_limit(entries, 8); + dx_set_count(entries, 2); + dx_set_block(entries + 0, 1); + dx_set_hash(entries + 1, 0x80000000U); + dx_set_block(entries + 1, 2); + + frame.entries = entries; + frame.at = entries + 0; + dx_insert_block_test(&frame, 0x40000000U, 3); + KUNIT_EXPECT_EQ(test, dx_get_count(entries), 3U); + KUNIT_EXPECT_EQ(test, dx_get_hash(entries + 1), 0x40000000U); + KUNIT_EXPECT_EQ(test, dx_get_block(entries + 1), 3U); + KUNIT_EXPECT_EQ(test, dx_get_hash(entries + 2), 0x80000000U); + KUNIT_EXPECT_EQ(test, dx_get_block(entries + 2), 2U); +} + +/* + * Test 8: Parameterized tests for ext4_check_dx_root_test, dx_probe_test, and + * ext4_htree_next_block_test across valid 1-level / 2-level trees and 10 + * on-disk corruption cases. + */ +enum dx_probe_case_id { + DXP_VALID_1LEVEL, + DXP_VALID_2LEVEL_AND_NEXT, + DXP_DOT_BAD_NAMELEN, + DXP_DOT_BAD_NAME, + DXP_DOT_BAD_RECLEN, + DXP_DOTDOT_BAD_NAMELEN, + DXP_DOTDOT_BAD_NAME, + DXP_BAD_HASH_VERSION, + DXP_SIPHASH_WITHOUT_IN_DIRENT, + DXP_UNUSED_FLAGS_SET, + DXP_INDIRECT_LEVEL_TOO_DEEP, + DXP_BAD_ROOT_LIMIT, + DXP_ZERO_COUNT, + DXP_TREE_CYCLE, +}; + +struct dx_probe_param { + const char *desc; + enum dx_probe_case_id id; + bool check_dx_root_only; + bool expect_ok; +}; + +static const struct dx_probe_param dx_probe_params[] = { + { + .desc = "valid 1-level dx_root binary search probe", + .id = DXP_VALID_1LEVEL, + .expect_ok = true, + }, + { + .desc = "valid 2-level htree probe and ext4_htree_next_block", + .id = DXP_VALID_2LEVEL_AND_NEXT, + .expect_ok = true, + }, + { + .desc = "ext4_check_dx_root rejects dot name_len != 1", + .id = DXP_DOT_BAD_NAMELEN, + .check_dx_root_only = true, + .expect_ok = false, + }, + { + .desc = "ext4_check_dx_root rejects dot name != '.'", + .id = DXP_DOT_BAD_NAME, + .check_dx_root_only = true, + .expect_ok = false, + }, + { + .desc = "ext4_check_dx_root rejects dot rec_len >= blocksize", + .id = DXP_DOT_BAD_RECLEN, + .check_dx_root_only = true, + .expect_ok = false, + }, + { + .desc = "ext4_check_dx_root rejects dotdot name_len != 2", + .id = DXP_DOTDOT_BAD_NAMELEN, + .check_dx_root_only = true, + .expect_ok = false, + }, + { + .desc = "ext4_check_dx_root rejects dotdot name != '..'", + .id = DXP_DOTDOT_BAD_NAME, + .check_dx_root_only = true, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects unrecognized hash_version", + .id = DXP_BAD_HASH_VERSION, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects DX_HASH_SIPHASH when not hash_in_dirent", + .id = DXP_SIPHASH_WITHOUT_IN_DIRENT, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects non-zero unused_flags & 1", + .id = DXP_UNUSED_FLAGS_SET, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects indirect_levels >= ext4_dir_htree_level", + .id = DXP_INDIRECT_LEVEL_TOO_DEEP, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects root limit mismatch", + .id = DXP_BAD_ROOT_LIMIT, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects count == 0", + .id = DXP_ZERO_COUNT, + .expect_ok = false, + }, + { + .desc = "dx_probe detects tree cycle pointing back to block 0", + .id = DXP_TREE_CYCLE, + .expect_ok = false, + }, +}; + +static void dx_probe_get_desc(const struct dx_probe_param *p, char *desc) +{ + strscpy(desc, p->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dx_probe, dx_probe_params, dx_probe_get_desc); + +static void setup_valid_dx_root(struct inode *dir, struct buffer_head *bh) +{ + struct dx_root *root = (struct dx_root *)bh->b_data; + + memset(root, 0, TEST_BLK_SIZE); + root->dot.inode = cpu_to_le32(dir->i_ino); + root->dot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot.name_len = 1; + root->dot.file_type = EXT4_FT_DIR; + strscpy(root->dot_name, ".", sizeof(root->dot_name)); + + root->dotdot.inode = cpu_to_le32(TEST_ROOT_INO); + root->dotdot.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE - 12, + TEST_BLK_SIZE); + root->dotdot.name_len = 2; + root->dotdot.file_type = EXT4_FT_DIR; + strscpy(root->dotdot_name, "..", sizeof(root->dotdot_name)); + + root->info.info_length = sizeof(struct dx_root_info); + root->info.hash_version = DX_HASH_HALF_MD4; + dx_set_limit(root->entries, + dx_root_limit(dir, sizeof(struct dx_root_info))); + dx_set_count(root->entries, 2); + dx_set_block(root->entries + 0, 1); + dx_set_hash(root->entries + 1, 0x80000000U); + dx_set_block(root->entries + 1, 2); +} + +static void test_namei_check_dx_root_and_probe(struct kunit *test) +{ + const struct dx_probe_param *p = test->param_value; + struct namei_test_ctx *ctx = test->priv; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct buffer_head *bh0, *bh1; + struct dx_root *root; + struct dx_node *node; + struct dx_frame frames[EXT4_HTREE_LEVEL], *frame; + struct dx_hash_info hinfo = {}; + __u32 start_hash = 0; + + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + dir->i_size = 4 * TEST_BLK_SIZE; + bh0 = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh0); + setup_valid_dx_root(dir, bh0); + root = (struct dx_root *)bh0->b_data; + + switch (p->id) { + case DXP_VALID_1LEVEL: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + KUNIT_EXPECT_TRUE(test, ext4_check_dx_root_test(dir, root)); + root->dotdot.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE - 12, + TEST_BLK_SIZE); + break; + case DXP_VALID_2LEVEL_AND_NEXT: + root->info.indirect_levels = 1; + bh1 = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, bh1); + node = (struct dx_node *)bh1->b_data; + node->fake.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE, + TEST_BLK_SIZE); + dx_set_limit(node->entries, dx_node_limit(dir)); + dx_set_count(node->entries, 2); + dx_set_block(node->entries + 0, 2); + /* Continuation hash (low bit 1) matching 0x40000000 */ + dx_set_hash(node->entries + 1, 0x40000001U); + dx_set_block(node->entries + 1, 3); + break; + case DXP_DOT_BAD_NAMELEN: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot.name_len = 2; + break; + case DXP_DOT_BAD_NAME: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot_name[0] = 'x'; + break; + case DXP_DOT_BAD_RECLEN: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE, + TEST_BLK_SIZE); + break; + case DXP_DOTDOT_BAD_NAMELEN: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dotdot.name_len = 1; + break; + case DXP_DOTDOT_BAD_NAME: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dotdot_name[1] = 'x'; + break; + case DXP_BAD_HASH_VERSION: + root->info.hash_version = 99; + break; + case DXP_SIPHASH_WITHOUT_IN_DIRENT: + root->info.hash_version = DX_HASH_SIPHASH; + break; + case DXP_UNUSED_FLAGS_SET: + root->info.unused_flags = 1; + break; + case DXP_INDIRECT_LEVEL_TOO_DEEP: + root->info.indirect_levels = EXT4_HTREE_LEVEL_COMPAT; + break; + case DXP_BAD_ROOT_LIMIT: + dx_set_limit(root->entries, 50); + break; + case DXP_ZERO_COUNT: + dx_set_count(root->entries, 0); + break; + case DXP_TREE_CYCLE: + dx_set_block(root->entries + 0, 0); + break; + } + + if (p->check_dx_root_only) { + KUNIT_EXPECT_EQ(test, ext4_check_dx_root_test(dir, root), + p->expect_ok); + return; + } + + hinfo.hash = 0x40000000U; + frame = dx_probe_test(NULL, dir, &hinfo, frames); + if (!p->expect_ok) { + KUNIT_EXPECT_TRUE(test, IS_ERR(frame)); + KUNIT_EXPECT_EQ(test, PTR_ERR(frame), ERR_BAD_DX_DIR); + return; + } + + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(frame)); + if (p->id == DXP_VALID_1LEVEL) { + KUNIT_EXPECT_PTR_EQ(test, frame, &frames[0]); + KUNIT_EXPECT_EQ(test, dx_get_block(frame->at), 1U); + } else if (p->id == DXP_VALID_2LEVEL_AND_NEXT) { + KUNIT_EXPECT_PTR_EQ(test, frame, &frames[1]); + KUNIT_EXPECT_EQ(test, dx_get_block(frame->at), 2U); + + /* Advance to next leaf block matching continuation hash */ + KUNIT_EXPECT_EQ(test, + ext4_htree_next_block_test(dir, 0x40000000U, frame, + frames, &start_hash), 1); + KUNIT_EXPECT_EQ(test, start_hash, 0x40000001U); + KUNIT_EXPECT_EQ(test, dx_get_block(frame->at), 3U); + + /* Non-matching even hash stops traversal */ + KUNIT_EXPECT_EQ(test, + ext4_htree_next_block_test(dir, 0x40000000U, frame, + frames, NULL), 0); + } + dx_release_test(frames); +} + +/* + * Test 9: End-to-end HTree directory conversion (make_indexed_dir), multiple + * leaf splits (ext4_dx_add_entry / do_split), indexed lookup + * (ext4_dx_find_entry), and rb-tree population (ext4_htree_fill_tree). + */ +static void test_namei_add_find_and_htree_split(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry *dentries; + struct dentry *parent_dentry, *child_dentry; + struct dir_private_info *dir_info; + struct file *dir_file; + __u32 curr_hash = 0, next_hash = 0; + int i, err, total_loaded = 0; + + dentries = kunit_kcalloc(test, 2, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + parent_dentry = &dentries[0]; + child_dentry = &dentries[1]; + dir_file = kunit_kzalloc(test, sizeof(*dir_file), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dir_file); + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + init_mock_dentry(parent_dentry, NULL, "dir", dir, &ctx->sb); + + /* + * Insert 60 entries into a 1024-byte block directory. + * Each entry takes 20 bytes (name_len = 10 -> rec_len = 20), so ~48 + * entries fit in block 0 before make_indexed_dir converts it into an + * HTree and subsequent insertions split leaves via ext4_dx_add_entry. + */ + for (i = 0; i < 60; i++) { + char name[16]; + + snprintf(name, sizeof(name), "file_%05d", i); + init_mock_dentry(child_dentry, parent_dentry, name, file1, + &ctx->sb); + err = ext4_add_entry_test(NULL, child_dentry, file1); + KUNIT_ASSERT_EQ_MSG(test, err, 0, "failed at entry %d", i); + } + + /* Verify the directory was converted to an HTree index */ + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(dir, EXT4_INODE_INDEX)); + KUNIT_EXPECT_GE(test, dir->i_size, (loff_t)(3 * TEST_BLK_SIZE)); + + /* Adding a duplicate entry must return -EEXIST */ + init_mock_dentry(child_dentry, parent_dentry, "file_00025", file1, + &ctx->sb); + KUNIT_EXPECT_EQ(test, + ext4_add_entry_test(NULL, child_dentry, file1), + -EEXIST); + + /* Look up all 60 entries via ext4_find_entry_test (ext4_dx_find_entry) */ + for (i = 0; i < 60; i++) { + char name[16]; + struct qstr q; + struct ext4_dir_entry_2 *de = NULL; + struct buffer_head *bh; + + snprintf(name, sizeof(name), "file_%05d", i); + q.name = (const unsigned char *)name; + q.len = strlen(name); + bh = ext4_find_entry_test(dir, &q, &de, NULL); + KUNIT_ASSERT_FALSE_MSG(test, IS_ERR_OR_NULL(bh), + "missing entry %s", name); + KUNIT_ASSERT_NOT_NULL(test, de); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + brelse(bh); + } + + /* Populate readdir rb-tree via ext4_htree_fill_tree */ + dir_file->f_inode = dir; + while (1) { + int cnt; + + dir_info = kzalloc_obj(*dir_info); + KUNIT_ASSERT_NOT_NULL(test, dir_info); + dir_file->private_data = dir_info; + cnt = ext4_htree_fill_tree(dir_file, curr_hash, 0, &next_hash); + KUNIT_ASSERT_GE(test, cnt, 0); + total_loaded += cnt; + ext4_htree_free_dir_info(dir_info); + if (next_hash == ~0U) + break; + curr_hash = next_hash; + } + /* 60 files + '.' + '..' = 62 total entries */ + KUNIT_EXPECT_EQ(test, total_loaded, 62); +} + +/* + * Test 10: HTree index level growth (splitting full dx_root into a 2-level + * tree with indirect_levels == 1), max htree level -ENOSPC enforcement, and + * corrupted dx_root fallback in __ext4_find_entry and __ext4_add_entry. + */ +static void test_namei_dx_index_level_growth_and_fallback(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry parent_dentry, child_dentry; + struct buffer_head *bh0, *bh1, *found_bh; + struct dx_root *root; + struct ext4_dir_entry_2 *de = NULL; + unsigned int root_limit; + int i, err; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + init_mock_dentry(&parent_dentry, NULL, "dir", dir, &ctx->sb); + + /* Set up a 1-level HTree where root->entries is completely full */ + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + dir->i_size = 2 * TEST_BLK_SIZE; + bh0 = map_and_get_dir_bh(ctx, dir, 0); + bh1 = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, bh0); + KUNIT_ASSERT_NOT_NULL(test, bh1); + + setup_valid_dx_root(dir, bh0); + root = (struct dx_root *)bh0->b_data; + root_limit = dx_root_limit(dir, sizeof(struct dx_root_info)); + dx_set_limit(root->entries, root_limit); + dx_set_count(root->entries, root_limit); + /* Point every index entry at leaf block 1 in ascending hash order */ + for (i = 0; i < root_limit; i++) { + if (i > 0) + dx_set_hash(root->entries + i, (u32)i * 0x02000000U); + dx_set_block(root->entries + i, 1); + } + ext4_dx_csum_set_test(dir, (struct ext4_dir_entry *)bh0->b_data); + + /* Fill leaf block 1 completely so adding one more entry splits it */ + KUNIT_ASSERT_EQ(test, + ext4_init_dirblock(NULL, dir, bh1, TEST_ROOT_INO, NULL, 0), 0); + for (i = 0; i < 60; i++) { + char name[16]; + struct qstr q; + struct ext4_filename fname; + + snprintf(name, sizeof(name), "leaf_%05d", i); + q.name = (const unsigned char *)name; + q.len = strlen(name); + KUNIT_ASSERT_EQ(test, + ext4_fname_setup_filename(dir, &q, 0, &fname), 0); + err = ext4_find_dest_de(dir, bh1, bh1->b_data, + TEST_BLK_SIZE - + sizeof(struct ext4_dir_entry_tail), + &fname, &de); + if (err == 0) + ext4_insert_dentry(dir, file1, de, TEST_BLK_SIZE, + &fname); + ext4_fname_free_filename(&fname); + if (err == -ENOSPC) + break; + } + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh1), 0); + + /* + * Adding "trigger_split_entry" finds leaf block 1 full and root index + * full (count == limit), triggering the add_level branch in + * ext4_dx_add_entry (indirect_levels: 0 -> 1). + */ + init_mock_dentry(&child_dentry, &parent_dentry, "trigger_split_entry", + file1, &ctx->sb); + err = ext4_add_entry_test(NULL, &child_dentry, file1); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, root->info.indirect_levels, 1); + KUNIT_EXPECT_EQ(test, dx_get_count(root->entries), 1U); + + /* Verify the newly inserted entry can be found in the 2-level tree */ + found_bh = ext4_find_entry_test(dir, &child_dentry.d_name, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(found_bh)); + brelse(found_bh); + + /* + * Test interior dx_node split (!add_level in ext4_dx_add_entry) and + * max htree level (-ENOSPC when levels == ext4_dir_htree_level(sb)): + * Block 2 is the new interior dx_node created by the root split above. + * Point all node_limit entries in block 2 to leaf block 1 and refill + * leaf block 1 so the next insertion splits the interior dx_node. + */ + { + struct buffer_head *bh2 = map_and_get_dir_bh(ctx, dir, 2); + struct dx_node *node; + unsigned int node_limit = dx_node_limit(dir); + + KUNIT_ASSERT_NOT_NULL(test, bh2); + node = (struct dx_node *)bh2->b_data; + dx_set_limit(node->entries, node_limit); + dx_set_count(node->entries, node_limit); + for (i = 0; i < node_limit; i++) { + if (i > 0) + dx_set_hash(node->entries + i, + (u32)i * 0x01000000U); + dx_set_block(node->entries + i, 1); + } + ext4_dx_csum_set_test(dir, + (struct ext4_dir_entry *)bh2->b_data); + + /* Refill leaf block 1 to capacity */ + for (i = 60; i < 120; i++) { + char name[16]; + struct qstr q; + struct ext4_filename fname; + + snprintf(name, sizeof(name), "leaf_%05d", i); + q.name = (const unsigned char *)name; + q.len = strlen(name); + KUNIT_ASSERT_EQ(test, + ext4_fname_setup_filename(dir, &q, 0, &fname), + 0); + err = ext4_find_dest_de(dir, bh1, bh1->b_data, + TEST_BLK_SIZE - + sizeof(struct ext4_dir_entry_tail), + &fname, &de); + if (err == 0) + ext4_insert_dentry(dir, file1, de, + TEST_BLK_SIZE, &fname); + ext4_fname_free_filename(&fname); + if (err == -ENOSPC) + break; + } + KUNIT_ASSERT_EQ(test, + ext4_handle_dirty_dirblock(NULL, dir, bh1), 0); + + /* + * First test max htree level check: if both root (level 0) and + * interior node (level 1) are full when LARGEDIR is disabled + * (max level 2), ext4_dx_add_entry returns -ENOSPC. + */ + dx_set_count(root->entries, root_limit); + for (i = 0; i < root_limit; i++) { + if (i > 0) + dx_set_hash(root->entries + i, + (u32)i * 0x02000000U); + dx_set_block(root->entries + i, 2); + } + ext4_dx_csum_set_test(dir, + (struct ext4_dir_entry *)bh0->b_data); + init_mock_dentry(&child_dentry, &parent_dentry, + "max_level_enospc", file1, &ctx->sb); + KUNIT_EXPECT_EQ(test, + ext4_add_entry_test(NULL, &child_dentry, file1), + -ENOSPC); + + /* + * Restore root count to 1 and insert again: now root has room + * while interior node at block 2 is full, exercising the + * !add_level interior node split in ext4_dx_add_entry. + */ + dx_set_count(root->entries, 1); + dx_set_block(root->entries + 0, 2); + ext4_dx_csum_set_test(dir, + (struct ext4_dir_entry *)bh0->b_data); + init_mock_dentry(&child_dentry, &parent_dentry, + "interior_node_split", file1, &ctx->sb); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, &child_dentry, file1), + 0); + KUNIT_EXPECT_EQ(test, root->info.indirect_levels, 1); + KUNIT_EXPECT_EQ(test, dx_get_count(root->entries), 2U); + } + + /* + * Now test corrupted dx_root handling: + * 1) With METADATA_CSUM enabled, __ext4_add_entry refuses to clear + * EXT4_INODE_INDEX and returns -EFSCORRUPTED. + */ + root->info.hash_version = 99; + ext4_dx_csum_set_test(dir, (struct ext4_dir_entry *)bh0->b_data); + init_mock_dentry(&child_dentry, &parent_dentry, "after_corrupt", + file1, &ctx->sb); + KUNIT_EXPECT_EQ(test, + ext4_add_entry_test(NULL, &child_dentry, file1), + -EFSCORRUPTED); + + /* + * 2) __ext4_find_entry falls back to linear block scan on + * ERR_BAD_DX_DIR and still finds "leaf_00000" in block 1! + */ + init_mock_dentry(&child_dentry, &parent_dentry, "leaf_00000", + file1, &ctx->sb); + found_bh = ext4_find_entry_test(dir, &child_dentry.d_name, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(found_bh)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + brelse(found_bh); + + /* + * 3) Without METADATA_CSUM, __ext4_add_entry clears EXT4_INODE_INDEX + * on ERR_BAD_DX_DIR and falls back to linear append. + */ + ctx->es.s_feature_ro_compat &= + ~cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + init_mock_dentry(&child_dentry, &parent_dentry, "fallback_new_entry", + file1, &ctx->sb); + KUNIT_EXPECT_EQ(test, + ext4_add_entry_test(NULL, &child_dentry, file1), 0); + KUNIT_EXPECT_FALSE(test, ext4_test_inode_flag(dir, EXT4_INODE_INDEX)); +} + +/* + * Test 11: Inline directory lifecycle through namei.c entry points + * (ext4_init_new_dir, ext4_empty_dir, ext4_add_entry_test, + * ext4_find_entry_test, ext4_delete_entry_test, ext4_htree_fill_tree). + */ +static void test_namei_inline_dir_lifecycle(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry parent_dentry, child_dentry; + struct buffer_head *bh; + struct ext4_dir_entry_2 *de = NULL; + struct dir_private_info *dir_info; + struct file dir_file = {}; + __u32 next_hash = 0; + int inlined = 0; + + ctx->es.s_feature_incompat |= + cpu_to_le32(EXT4_FEATURE_INCOMPAT_INLINE_DATA); + ext4_set_inode_state(dir, EXT4_STATE_MAY_INLINE_DATA); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(dir)); + KUNIT_EXPECT_TRUE(test, ext4_empty_dir(dir)); + + init_mock_dentry(&parent_dentry, NULL, "idir", dir, &ctx->sb); + init_mock_dentry(&child_dentry, &parent_dentry, "tiny", file1, + &ctx->sb); + + /* Add an entry into the inline directory */ + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, &child_dentry, file1), 0); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(dir)); + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); + + /* Find the inline entry */ + bh = ext4_find_entry_test(dir, &child_dentry.d_name, &de, &inlined); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_EXPECT_EQ(test, inlined, 1); + KUNIT_ASSERT_NOT_NULL(test, de); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + brelse(bh); + + /* Load inline directory into rb-tree via ext4_htree_fill_tree */ + dir_info = kzalloc_obj(*dir_info); + KUNIT_ASSERT_NOT_NULL(test, dir_info); + dir_file.f_inode = dir; + dir_file.private_data = dir_info; + KUNIT_EXPECT_EQ(test, + ext4_htree_fill_tree(&dir_file, 0, 0, &next_hash), 3); + KUNIT_EXPECT_EQ(test, next_hash, ~0U); + ext4_htree_free_dir_info(dir_info); + + /* Delete the inline entry -> directory becomes empty again */ + bh = ext4_find_entry_test(dir, &child_dentry.d_name, &de, &inlined); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_ASSERT_EQ(test, ext4_delete_entry_test(NULL, dir, de, bh), 0); + brelse(bh); + KUNIT_EXPECT_TRUE(test, ext4_empty_dir(dir)); +} + +/* + * Test 12: Directory link count helpers (ext4_inc_count_test, + * ext4_dec_count_test) and VFS lookup / parent resolution (ext4_lookup, + * ext4_get_parent). + */ +static void test_namei_nlink_and_lookup_parent(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry *dentries; + struct dentry *parent_dentry, *lookup_dentry, *res_dentry; + struct buffer_head *bh; + struct ext4_dir_entry_2 *de = NULL; + char *long_name; + + dentries = kunit_kcalloc(test, 2, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + parent_dentry = &dentries[0]; + lookup_dentry = &dentries[1]; + long_name = kunit_kzalloc(test, EXT4_NAME_LEN + 2, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, long_name); + + /* Test ext4_inc_count_test and ext4_dec_count_test on indexed dir */ + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + set_nlink(dir, 2); + ext4_inc_count_test(dir); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 3U); + ext4_dec_count_test(dir); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 2U); + + /* Overflow past EXT4_LINK_MAX wraps nlink to 1 and keeps it at 1 */ + set_nlink(dir, EXT4_LINK_MAX); + ext4_inc_count_test(dir); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 1U); + ext4_inc_count_test(dir); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 1U); + ext4_dec_count_test(dir); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 1U); + ext4_clear_inode_flag(dir, EXT4_INODE_INDEX); + + /* Initialize directory for lookup and get_parent tests */ + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + init_mock_dentry(parent_dentry, NULL, "dir", dir, &ctx->sb); + + /* 1) Name longer than EXT4_NAME_LEN -> -ENAMETOOLONG */ + memset(long_name, 'a', EXT4_NAME_LEN + 1); + long_name[EXT4_NAME_LEN + 1] = '\0'; + init_mock_dentry(lookup_dentry, parent_dentry, long_name, NULL, + &ctx->sb); + res_dentry = ext4_dir_inode_operations.lookup(dir, lookup_dentry, 0); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-ENAMETOOLONG)); + + /* 2) Negative lookup returns NULL without calling ext4_iget */ + ctx->last_iget_ino = 0; + init_mock_dentry(lookup_dentry, parent_dentry, "nonexistent", NULL, + &ctx->sb); + res_dentry = ext4_dir_inode_operations.lookup(dir, lookup_dentry, 0); + /* + * ext4_lookup() hashes negative dentries via d_splice_alias(); unhash + * it and wait for RCU readers before reusing or freeing memory. + */ + d_drop(lookup_dentry); + synchronize_rcu(); + KUNIT_EXPECT_NULL(test, res_dentry); + KUNIT_EXPECT_EQ(test, ctx->last_iget_ino, 0UL); + + /* 3) Positive lookup invokes ext4_iget with target inode number */ + init_mock_dentry(lookup_dentry, parent_dentry, "target", file1, + &ctx->sb); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, lookup_dentry, file1), 0); + ctx->fail_iget = -ESTALE; + /* -ESTALE from ext4_iget is translated to -EFSCORRUPTED */ + res_dentry = ext4_dir_inode_operations.lookup(dir, lookup_dentry, 0); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-EFSCORRUPTED)); + KUNIT_EXPECT_EQ(test, ctx->last_iget_ino, TEST_FILE1_INO); + + /* 4) Self-linked directory entry (de->inode == dir->i_ino) -> -EFSCORRUPTED */ + bh = ext4_find_entry_test(dir, &lookup_dentry->d_name, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + de->inode = cpu_to_le32(dir->i_ino); + brelse(bh); + res_dentry = ext4_dir_inode_operations.lookup(dir, lookup_dentry, 0); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-EFSCORRUPTED)); + + /* 5) Invalid inode number (e.g. reserved ino 5) -> -EFSCORRUPTED */ + de->inode = cpu_to_le32(5); + res_dentry = ext4_dir_inode_operations.lookup(dir, lookup_dentry, 0); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-EFSCORRUPTED)); + + /* 6) ext4_get_parent looks up ".." and calls ext4_iget(TEST_ROOT_INO) */ + ctx->fail_iget = -EUCLEAN; + ctx->last_iget_ino = 0; + res_dentry = ext4_get_parent(parent_dentry); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-EUCLEAN)); + KUNIT_EXPECT_EQ(test, ctx->last_iget_ino, (unsigned long)TEST_ROOT_INO); + + /* Corrupt '..' inode to invalid ino 5 -> ext4_get_parent returns -EFSCORRUPTED */ + bh = map_and_get_dir_bh(ctx, dir, 0); + de = ext4_next_entry((struct ext4_dir_entry_2 *)bh->b_data, + TEST_BLK_SIZE); + de->inode = cpu_to_le32(5); + res_dentry = ext4_get_parent(parent_dentry); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-EFSCORRUPTED)); +} + +/* + * Test 13: Hard link, unlink, and rmdir operations (__ext4_link, + * ext4_dir_inode_operations.link, __ext4_unlink, + * ext4_dir_inode_operations.unlink, ext4_dir_inode_operations.rmdir). + */ +static void test_namei_link_unlink_and_rmdir(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *subdir = get_mock_inode(ctx, TEST_SUBDIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry *dentries; + struct dentry *dir_dentry, *f1_dentry, *f1_link_dentry, *sub_dentry; + int err; + + dentries = kunit_kcalloc(test, 4, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + dir_dentry = &dentries[0]; + f1_dentry = &dentries[1]; + f1_link_dentry = &dentries[2]; + sub_dentry = &dentries[3]; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, dir, subdir), 0); + ext4_inc_count_test(dir); + + init_mock_dentry(dir_dentry, NULL, "dir", dir, &ctx->sb); + init_mock_dentry(f1_dentry, dir_dentry, "orig", file1, &ctx->sb); + init_mock_dentry(f1_link_dentry, dir_dentry, "hardlink", file1, + &ctx->sb); + init_mock_dentry(sub_dentry, dir_dentry, "subdir", subdir, &ctx->sb); + + /* Link a 0-nlink tmpfile -> nlink becomes 1 and ext4_orphan_del runs */ + set_nlink(file1, 0); + inode_state_set_raw(file1, I_DIRTY | I_LINKABLE); + ctx->orphan_del_calls = 0; + err = __ext4_link(dir, file1, &f1_dentry->d_name, f1_dentry); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, file1->i_nlink, 1U); + KUNIT_EXPECT_EQ(test, ctx->orphan_del_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_orphan_del_ino, TEST_FILE1_INO); + + /* Create a second hard link via __ext4_link */ + err = __ext4_link(dir, file1, &f1_link_dentry->d_name, f1_link_dentry); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, file1->i_nlink, 2U); + + /* Cross-project link with EXT4_INODE_PROJINHERIT returns -EXDEV */ + ext4_set_inode_flag(dir, EXT4_INODE_PROJINHERIT); + EXT4_I(file1)->i_projid = make_kprojid(&init_user_ns, 42); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.link(f1_dentry, dir, + f1_link_dentry), -EXDEV); + EXT4_I(file1)->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + + /* Max link count check returns -EMLINK */ + set_nlink(file1, EXT4_LINK_MAX); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.link(f1_dentry, dir, + f1_link_dentry), -EMLINK); + set_nlink(file1, 2); + + /* Unlink first link -> nlink drops to 1, not orphaned yet */ + ctx->orphan_add_calls = 0; + err = ext4_dir_inode_operations.unlink(dir, f1_dentry); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, file1->i_nlink, 1U); + KUNIT_EXPECT_EQ(test, ctx->orphan_add_calls, 0U); + + /* Unlink last link -> nlink drops to 0 and inode is added to orphans */ + err = ext4_dir_inode_operations.unlink(dir, f1_link_dentry); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, file1->i_nlink, 0U); + KUNIT_EXPECT_EQ(test, ctx->orphan_add_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_orphan_add_ino, TEST_FILE1_INO); + + /* Unlinking missing entry returns -ENOENT */ + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.unlink(dir, f1_link_dentry), + -ENOENT); + + /* + * Test __ext4_unlink when directory entry points to a different inode: + * normally rejected with -ENOENT, but permitted during EXT4_FC_REPLAY. + */ + { + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + + set_nlink(file1, 1); + set_nlink(file2, 1); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, f1_dentry, file1), 0); + KUNIT_EXPECT_EQ(test, + __ext4_unlink(dir, &f1_dentry->d_name, file2, + f1_dentry), -ENOENT); + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + KUNIT_EXPECT_EQ(test, + __ext4_unlink(dir, &f1_dentry->d_name, file2, + f1_dentry), 0); + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + } + + /* Add subdir to dir and test rmdir */ + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, sub_dentry, subdir), 0); + + /* Non-empty subdir cannot be removed (-ENOTEMPTY) */ + init_mock_dentry(f1_dentry, sub_dentry, "inside", file1, &ctx->sb); + set_nlink(file1, 1); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, f1_dentry, file1), 0); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.rmdir(dir, sub_dentry), -ENOTEMPTY); + + /* Unlink file inside subdir, then rmdir subdir succeeds */ + KUNIT_ASSERT_EQ(test, + ext4_dir_inode_operations.unlink(subdir, f1_dentry), 0); + KUNIT_ASSERT_EQ(test, + ext4_dir_inode_operations.rmdir(dir, sub_dentry), 0); + KUNIT_EXPECT_EQ(test, subdir->i_nlink, 0U); + KUNIT_EXPECT_EQ(test, subdir->i_size, 0LL); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 2U); + KUNIT_EXPECT_EQ(test, ctx->last_orphan_add_ino, TEST_SUBDIR_INO); +} + +/* + * Test 14: Rename, overwrite rename, cross-directory subdirectory rename, + * RENAME_EXCHANGE (ext4_cross_rename), and slow symlink block initialization + * (ext4_init_symlink_block_test). + */ +static void test_namei_rename_and_exchange(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir1 = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *dir2 = get_mock_inode(ctx, TEST_DIR2_INO); + struct inode *subdir = get_mock_inode(ctx, TEST_SUBDIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct inode *symlink_inode = get_mock_inode(ctx, TEST_FILE3_INO); + struct dentry *dentries; + struct dentry *d1_dentry, *d2_dentry; + struct dentry *old_dentry, *new_dentry, *sub_dentry; + struct buffer_head *bh; + struct ext4_dir_entry_2 *de = NULL; + const char *sym_target = "/very/long/symlink/target/path/for/ext4/test"; + struct fscrypt_str disk_link = { + .name = (unsigned char *)sym_target, + .len = strlen(sym_target) + 1, + }; + int err; + + dentries = kunit_kcalloc(test, 5, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + d1_dentry = &dentries[0]; + d2_dentry = &dentries[1]; + old_dentry = &dentries[2]; + new_dentry = &dentries[3]; + sub_dentry = &dentries[4]; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir1), 0); + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir2), 0); + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, dir1, subdir), 0); + set_nlink(dir1, 3); /* '.', '..', and subdir */ + set_nlink(dir2, 2); + + init_mock_dentry(d1_dentry, NULL, "dir1", dir1, &ctx->sb); + init_mock_dentry(d2_dentry, NULL, "dir2", dir2, &ctx->sb); + + /* Invalid rename flags are rejected with -EINVAL */ + init_mock_dentry(old_dentry, d1_dentry, "f1", file1, &ctx->sb); + init_mock_dentry(new_dentry, d1_dentry, "f1_new", NULL, &ctx->sb); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir1, new_dentry, ~0U), -EINVAL); + + /* Add f1 and f2 in dir1, and subdir in dir1 */ + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, old_dentry, file1), 0); + init_mock_dentry(sub_dentry, d1_dentry, "sub", subdir, &ctx->sb); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, sub_dentry, subdir), 0); + + /* 1) Same-directory rename: f1 -> f1_renamed */ + err = ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir1, new_dentry, + 0); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_NULL(test, + ext4_find_entry_test(dir1, &old_dentry->d_name, &de, NULL)); + bh = ext4_find_entry_test(dir1, &new_dentry->d_name, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + brelse(bh); + + /* 2) Overwrite rename: f1_renamed overwrites existing f2 in dir1 */ + init_mock_dentry(old_dentry, d1_dentry, "f1_new", file1, &ctx->sb); + init_mock_dentry(new_dentry, d1_dentry, "f2", file2, &ctx->sb); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, new_dentry, file2), 0); + ctx->orphan_add_calls = 0; + err = ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir1, new_dentry, + 0); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, file2->i_nlink, 0U); + KUNIT_EXPECT_EQ(test, ctx->orphan_add_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_orphan_add_ino, TEST_FILE2_INO); + + /* 3) Cross-directory subdir move: dir1/sub -> dir2/sub_moved */ + init_mock_dentry(new_dentry, d2_dentry, "sub_moved", NULL, &ctx->sb); + err = ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + sub_dentry, dir2, new_dentry, + 0); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, dir1->i_nlink, 2U); + KUNIT_EXPECT_EQ(test, dir2->i_nlink, 3U); + + /* Verify subdir's '..' now points to dir2 */ + bh = map_and_get_dir_bh(ctx, subdir, 0); + de = ext4_next_entry((struct ext4_dir_entry_2 *)bh->b_data, + TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_DIR2_INO); + + /* + * 4) RENAME_EXCHANGE (ext4_cross_rename): exchange regular file + * dir1/f2 with directory dir2/sub_moved across parents! + */ + init_mock_dentry(old_dentry, d1_dentry, "f2", file1, &ctx->sb); + init_mock_dentry(new_dentry, d2_dentry, "sub_moved", subdir, + &ctx->sb); + + /* Cross-project RENAME_EXCHANGE and normal rename return -EXDEV */ + ext4_set_inode_flag(dir2, EXT4_INODE_PROJINHERIT); + EXT4_I(dir2)->i_projid = make_kprojid(&init_user_ns, 77); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir2, new_dentry, RENAME_EXCHANGE), + -EXDEV); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir2, new_dentry, 0), + -EXDEV); + ext4_clear_inode_flag(dir2, EXT4_INODE_PROJINHERIT); + EXT4_I(dir2)->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + + err = ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir2, new_dentry, + RENAME_EXCHANGE); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, dir1->i_nlink, 3U); + KUNIT_EXPECT_EQ(test, dir2->i_nlink, 2U); + de = ext4_next_entry((struct ext4_dir_entry_2 *)bh->b_data, + TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_DIR_INO); + + /* + * Overwriting a target inode whose i_nlink == 0 returns -EFSCORRUPTED + * (in dir2, "sub_moved" now points to file1 after the exchange). + */ + init_mock_dentry(old_dentry, d1_dentry, "f2", subdir, &ctx->sb); + init_mock_dentry(new_dentry, d2_dentry, "sub_moved", file1, &ctx->sb); + set_nlink(file1, 0); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir2, + new_dentry, dir2, new_dentry, 0), + -EFSCORRUPTED); + set_nlink(file1, 1); + + /* 5) Test ext4_init_symlink_block_test */ + err = ext4_init_symlink_block_test(NULL, symlink_inode, &disk_link); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, symlink_inode->i_size, + (loff_t)strlen(sym_target)); + bh = map_and_get_dir_bh(ctx, symlink_inode, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_EXPECT_STREQ(test, bh->b_data, sym_target); +} + +#if IS_ENABLED(CONFIG_UNICODE) +/* + * Test 15: Case-insensitive (EXT4_INODE_CASEFOLD) filename setup, directory + * lookup, and strict UTF-8 validation. + */ +static void test_namei_casefold_lookup_and_strict(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct unicode_map *um; + struct dentry parent_dentry, add_dentry; + struct qstr upper_q = QSTR_INIT(" readme.md ", 11); + struct qstr bad_utf8 = QSTR_INIT("\xff\xfe", 2); + struct buffer_head *bh; + struct ext4_dir_entry_2 *de = NULL; + + um = utf8_load(UNICODE_AGE(12, 1, 0)); + if (IS_ERR(um)) + kunit_skip(test, "utf8data module not available"); + + ctx->sb.s_encoding = um; + ctx->es.s_feature_incompat |= + cpu_to_le32(EXT4_FEATURE_INCOMPAT_CASEFOLD); + ext4_set_inode_flag(dir, EXT4_INODE_CASEFOLD); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + init_mock_dentry(&parent_dentry, NULL, "cfdir", dir, &ctx->sb); + init_mock_dentry(&add_dentry, &parent_dentry, " ReadMe.MD ", file1, + &ctx->sb); + + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, &add_dentry, file1), 0); + + /* Case-insensitive lookup with different case finds the entry */ + bh = ext4_find_entry_test(dir, &upper_q, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_ASSERT_NOT_NULL(test, de); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + brelse(bh); + + /* Enable SB_ENC_STRICT_MODE_FL -> invalid UTF-8 sequence is rejected */ + ctx->sb.s_encoding_flags |= SB_ENC_STRICT_MODE_FL; + add_dentry.__d_name = bad_utf8; + KUNIT_EXPECT_EQ(test, + ext4_add_entry_test(NULL, &add_dentry, file1), + -EINVAL); +} +#endif /* CONFIG_UNICODE */ + +static struct kunit_case namei_test_cases[] = { + KUNIT_CASE(test_namei_dirent_tail_and_csum), + KUNIT_CASE(test_namei_dx_helpers_and_csum), + KUNIT_CASE_PARAM(test_namei_read_dirblock, read_dirblock_gen_params), + KUNIT_CASE(test_namei_append_and_init_dir), + KUNIT_CASE(test_namei_search_insert_delete_dentry), + KUNIT_CASE(test_namei_empty_dir), + KUNIT_CASE(test_namei_dx_map_pack_and_move), + KUNIT_CASE_PARAM(test_namei_check_dx_root_and_probe, + dx_probe_gen_params), + KUNIT_CASE(test_namei_add_find_and_htree_split), + KUNIT_CASE(test_namei_dx_index_level_growth_and_fallback), + KUNIT_CASE(test_namei_inline_dir_lifecycle), + KUNIT_CASE(test_namei_nlink_and_lookup_parent), + KUNIT_CASE(test_namei_link_unlink_and_rmdir), + KUNIT_CASE(test_namei_rename_and_exchange), +#if IS_ENABLED(CONFIG_UNICODE) + KUNIT_CASE(test_namei_casefold_lookup_and_strict), +#endif + {} +}; + +static struct kunit_suite namei_test_suite = { + .name = "ext4_namei_test", + .init = namei_test_init, + .exit = namei_test_exit, + .test_cases = namei_test_cases, +}; + +kunit_test_suites(&namei_test_suite); + +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/namei.c b/fs/ext4/namei.c index 354fc2d22df1aa..ed590010b04631 100644 --- a/fs/ext4/namei.c +++ b/fs/ext4/namei.c @@ -41,6 +41,7 @@ #include "xattr.h" #include "acl.h" +#include "namei.h" #include /* @@ -104,26 +105,12 @@ static struct buffer_head *ext4_append(handle_t *handle, static int ext4_dx_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent); -/* - * Hints to ext4_read_dirblock regarding whether we expect a directory - * block being read to be an index block, or a block containing - * directory entries (and if the latter, whether it was found via a - * logical block in an htree index block). This is used to control - * what sort of sanity checkinig ext4_read_dirblock() will do on the - * directory block read from the storage device. EITHER will means - * the caller doesn't know what kind of directory block will be read, - * so no specific verification will be done. - */ -typedef enum { - EITHER, INDEX, DIRENT, DIRENT_HTREE -} dirblock_type_t; - #define ext4_read_dirblock(inode, block, type) \ __ext4_read_dirblock((inode), (block), (type), __func__, __LINE__) static struct buffer_head *__ext4_read_dirblock(struct inode *inode, ext4_lblk_t block, - dirblock_type_t type, + enum dirblock_type type, const char *func, unsigned int line) { @@ -218,79 +205,6 @@ static struct buffer_head *__ext4_read_dirblock(struct inode *inode, #define dxtrace(command) #endif -struct fake_dirent -{ - __le32 inode; - __le16 rec_len; - u8 name_len; - u8 file_type; -}; - -struct dx_countlimit -{ - __le16 limit; - __le16 count; -}; - -struct dx_entry -{ - __le32 hash; - __le32 block; -}; - -/* - * dx_root_info is laid out so that if it should somehow get overlaid by a - * dirent the two low bits of the hash version will be zero. Therefore, the - * hash version mod 4 should never be 0. Sincerely, the paranoia department. - */ - -struct dx_root -{ - struct fake_dirent dot; - char dot_name[4]; - struct fake_dirent dotdot; - char dotdot_name[4]; - struct dx_root_info - { - __le32 reserved_zero; - u8 hash_version; - u8 info_length; /* 8 */ - u8 indirect_levels; - u8 unused_flags; - } - info; - struct dx_entry entries[]; -}; - -struct dx_node -{ - struct fake_dirent fake; - struct dx_entry entries[]; -}; - - -struct dx_frame -{ - struct buffer_head *bh; - struct dx_entry *entries; - struct dx_entry *at; -}; - -struct dx_map_entry -{ - u32 hash; - u16 offs; - u16 size; -}; - -/* - * This goes at the end of each htree block. - */ -struct dx_tail { - u32 dt_reserved; - __le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */ -}; - static struct buffer_head * ext4_dx_find_entry(struct inode *dir, struct ext4_filename *fname, struct ext4_dir_entry_2 **res_dir); @@ -308,6 +222,7 @@ void ext4_initialize_dirent_tail(struct buffer_head *bh, sizeof(struct ext4_dir_entry_tail), blocksize); t->det_reserved_ft = EXT4_FT_DIR_CSUM; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_initialize_dirent_tail); /* Walk through a dirent block to find a checksum "dirent" at the tail */ static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode, @@ -382,6 +297,7 @@ int ext4_dirblock_csum_verify(struct inode *inode, struct buffer_head *bh) return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dirblock_csum_verify); static void ext4_dirblock_csum_set(struct inode *inode, struct buffer_head *bh) @@ -408,6 +324,7 @@ int ext4_handle_dirty_dirblock(handle_t *handle, ext4_dirblock_csum_set(inode, bh); return ext4_handle_dirty_metadata(handle, inode, bh); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_handle_dirty_dirblock); static struct dx_countlimit *get_dx_countlimit(struct inode *inode, struct ext4_dir_entry *dirent, @@ -519,82 +436,6 @@ static inline int ext4_handle_dirty_dx_node(handle_t *handle, return ext4_handle_dirty_metadata(handle, inode, bh); } -/* - * p is at least 6 bytes before the end of page - */ -static inline struct ext4_dir_entry_2 * -ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize) -{ - return (struct ext4_dir_entry_2 *)((char *)p + - ext4_rec_len_from_disk(p->rec_len, blocksize)); -} - -/* - * Future: use high four bits of block for coalesce-on-delete flags - * Mask them off for now. - */ - -static inline ext4_lblk_t dx_get_block(struct dx_entry *entry) -{ - return le32_to_cpu(entry->block) & 0x0fffffff; -} - -static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value) -{ - entry->block = cpu_to_le32(value); -} - -static inline unsigned dx_get_hash(struct dx_entry *entry) -{ - return le32_to_cpu(entry->hash); -} - -static inline void dx_set_hash(struct dx_entry *entry, unsigned value) -{ - entry->hash = cpu_to_le32(value); -} - -static inline unsigned dx_get_count(struct dx_entry *entries) -{ - return le16_to_cpu(((struct dx_countlimit *) entries)->count); -} - -static inline unsigned dx_get_limit(struct dx_entry *entries) -{ - return le16_to_cpu(((struct dx_countlimit *) entries)->limit); -} - -static inline void dx_set_count(struct dx_entry *entries, unsigned value) -{ - ((struct dx_countlimit *) entries)->count = cpu_to_le16(value); -} - -static inline void dx_set_limit(struct dx_entry *entries, unsigned value) -{ - ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value); -} - -static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize) -{ - unsigned int entry_space = dir->i_sb->s_blocksize - - ext4_dir_rec_len(1, NULL) - - ext4_dir_rec_len(2, NULL) - infosize; - - if (ext4_has_feature_metadata_csum(dir->i_sb)) - entry_space -= sizeof(struct dx_tail); - return entry_space / sizeof(struct dx_entry); -} - -static inline unsigned dx_node_limit(struct inode *dir) -{ - unsigned int entry_space = dir->i_sb->s_blocksize - - ext4_dir_rec_len(0, dir); - - if (ext4_has_feature_metadata_csum(dir->i_sb)) - entry_space -= sizeof(struct dx_tail); - return entry_space / sizeof(struct dx_entry); -} - /* * Debug */ @@ -1258,6 +1099,7 @@ int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash, dx_release(frames); return (err); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_htree_fill_tree); static inline int search_dirblock(struct buffer_head *bh, struct inode *dir, @@ -1395,6 +1237,7 @@ int ext4_fname_setup_ci_filename(struct inode *dir, const struct qstr *iname, else return ext4fs_dirhash(dir, iname->name, iname->len, hinfo); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fname_setup_ci_filename); #endif /* @@ -1488,6 +1331,7 @@ int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size, } return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_search_dir); static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block, struct ext4_dir_entry *de) @@ -1837,6 +1681,7 @@ struct dentry *ext4_get_parent(struct dentry *child) return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL)); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_parent); /* * Move count entries from end of map between two memory locations. @@ -2066,6 +1911,7 @@ int ext4_find_dest_de(struct inode *dir, struct buffer_head *bh, *dest_de = de; return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_dest_de); void ext4_insert_dentry(struct inode *dir, struct inode *inode, @@ -2098,6 +1944,7 @@ void ext4_insert_dentry(struct inode *dir, cpu_to_le32(hinfo->minor_hash); } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_insert_dentry); /* * Add a new entry into a directory (leaf) block. If de is non-NULL, @@ -2705,6 +2552,7 @@ int ext4_generic_delete_entry(struct inode *dir, } return -ENOENT; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_generic_delete_entry); static int ext4_delete_entry(handle_t *handle, struct inode *dir, @@ -2967,6 +2815,7 @@ int ext4_init_dirblock(handle_t *handle, struct inode *inode, set_buffer_verified(bh); return ext4_handle_dirty_dirblock(handle, inode, bh); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_dirblock); int ext4_init_new_dir(handle_t *handle, struct inode *dir, struct inode *inode) @@ -2993,6 +2842,7 @@ int ext4_init_new_dir(handle_t *handle, struct inode *dir, brelse(dir_block); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_new_dir); static struct dentry *ext4_mkdir(const struct mnt_idmap *idmap, struct inode *dir, struct dentry *dentry, umode_t mode) @@ -3134,6 +2984,7 @@ bool ext4_empty_dir(struct inode *inode) brelse(bh); return true; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_empty_dir); static int ext4_rmdir(struct inode *dir, struct dentry *dentry) { @@ -3298,6 +3149,7 @@ int __ext4_unlink(struct inode *dir, const struct qstr *d_name, brelse(bh); return retval; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_unlink); static int ext4_unlink(struct inode *dir, struct dentry *dentry) { @@ -3491,6 +3343,7 @@ int __ext4_link(struct inode *dir, struct inode *inode, goto retry; return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_link); static int ext4_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry) @@ -4242,6 +4095,7 @@ const struct inode_operations ext4_dir_inode_operations = { .fileattr_get = ext4_fileattr_get, .fileattr_set = ext4_fileattr_set, }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dir_inode_operations); const struct inode_operations ext4_special_inode_operations = { .setattr = ext4_setattr, @@ -4250,3 +4104,159 @@ const struct inode_operations ext4_special_inode_operations = { .get_inode_acl = ext4_get_acl, .set_acl = ext4_set_acl, }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_special_inode_operations); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +struct buffer_head *ext4_append_test(handle_t *handle, struct inode *inode, + ext4_lblk_t *block) +{ + return ext4_append(handle, inode, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_append_test); + +struct buffer_head *ext4_read_dirblock_test(struct inode *inode, + ext4_lblk_t block, + enum dirblock_type type) +{ + return ext4_read_dirblock(inode, block, type); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_dirblock_test); + +void ext4_dx_csum_set_test(struct inode *inode, struct ext4_dir_entry *dirent) +{ + ext4_dx_csum_set(inode, dirent); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dx_csum_set_test); + +int ext4_dx_csum_verify_test(struct inode *inode, + struct ext4_dir_entry *dirent) +{ + return ext4_dx_csum_verify(inode, dirent); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dx_csum_verify_test); + +struct dx_frame *dx_probe_test(struct ext4_filename *fname, struct inode *dir, + struct dx_hash_info *hinfo, + struct dx_frame *frame_in) +{ + return dx_probe(fname, dir, hinfo, frame_in); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_probe_test); + +void dx_release_test(struct dx_frame *frames) +{ + dx_release(frames); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_release_test); + +int ext4_htree_next_block_test(struct inode *dir, __u32 hash, + struct dx_frame *frame, + struct dx_frame *frames, __u32 *start_hash) +{ + return ext4_htree_next_block(dir, hash, frame, frames, start_hash); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_htree_next_block_test); + +int dx_make_map_test(struct inode *dir, struct buffer_head *bh, + struct dx_hash_info *hinfo, + struct dx_map_entry *map_tail) +{ + return dx_make_map(dir, bh, hinfo, map_tail); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_make_map_test); + +void dx_sort_map_test(struct dx_map_entry *map, unsigned int count) +{ + dx_sort_map(map, count); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_sort_map_test); + +void dx_insert_block_test(struct dx_frame *frame, u32 hash, ext4_lblk_t block) +{ + dx_insert_block(frame, hash, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_insert_block_test); + +struct ext4_dir_entry_2 *dx_move_dirents_test(struct inode *dir, char *from, + char *to, + struct dx_map_entry *map, + int count, + unsigned int blocksize) +{ + return dx_move_dirents(dir, from, to, map, count, blocksize); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_move_dirents_test); + +struct ext4_dir_entry_2 *dx_pack_dirents_test(struct inode *dir, char *base, + unsigned int blocksize) +{ + return dx_pack_dirents(dir, base, blocksize); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_pack_dirents_test); + +struct ext4_dir_entry_2 *do_split_test(handle_t *handle, struct inode *dir, + struct buffer_head **bh, + struct dx_frame *frame, + struct dx_hash_info *hinfo) +{ + return do_split(handle, dir, bh, frame, hinfo); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(do_split_test); + +bool ext4_check_dx_root_test(struct inode *dir, struct dx_root *root) +{ + return ext4_check_dx_root(dir, root); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_dx_root_test); + +struct buffer_head *ext4_find_entry_test(struct inode *dir, + const struct qstr *d_name, + struct ext4_dir_entry_2 **res_dir, + int *inlined) +{ + return ext4_find_entry(dir, d_name, res_dir, inlined); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_entry_test); + +struct buffer_head *ext4_lookup_entry_test(struct inode *dir, + struct dentry *dentry, + struct ext4_dir_entry_2 **res_dir) +{ + return ext4_lookup_entry(dir, dentry, res_dir); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_lookup_entry_test); + +int ext4_add_entry_test(handle_t *handle, struct dentry *dentry, + struct inode *inode) +{ + return ext4_add_entry(handle, dentry, inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_add_entry_test); + +int ext4_delete_entry_test(handle_t *handle, struct inode *dir, + struct ext4_dir_entry_2 *de_del, + struct buffer_head *bh) +{ + return ext4_delete_entry(handle, dir, de_del, bh); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_delete_entry_test); + +void ext4_inc_count_test(struct inode *inode) +{ + ext4_inc_count(inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inc_count_test); + +void ext4_dec_count_test(struct inode *inode) +{ + ext4_dec_count(inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dec_count_test); + +int ext4_init_symlink_block_test(handle_t *handle, struct inode *inode, + struct fscrypt_str *disk_link) +{ + return ext4_init_symlink_block(handle, inode, disk_link); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_symlink_block_test); +#endif diff --git a/fs/ext4/namei.h b/fs/ext4/namei.h new file mode 100644 index 00000000000000..2539ed588966ba --- /dev/null +++ b/fs/ext4/namei.h @@ -0,0 +1,213 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * Internal definitions and helpers for fs/ext4/namei.c + */ + +#ifndef _EXT4_NAMEI_H +#define _EXT4_NAMEI_H + +#include "ext4.h" + +/* + * Hints to ext4_read_dirblock regarding whether we expect a directory + * block being read to be an index block, or a block containing + * directory entries (and if the latter, whether it was found via a + * logical block in an htree index block). This is used to control + * what sort of sanity checkinig ext4_read_dirblock() will do on the + * directory block read from the storage device. EITHER will means + * the caller doesn't know what kind of directory block will be read, + * so no specific verification will be done. + */ +enum dirblock_type { + EITHER, INDEX, DIRENT, DIRENT_HTREE +}; + +struct fake_dirent { + __le32 inode; + __le16 rec_len; + u8 name_len; + u8 file_type; +}; + +struct dx_countlimit { + __le16 limit; + __le16 count; +}; + +struct dx_entry { + __le32 hash; + __le32 block; +}; + +/* + * dx_root_info is laid out so that if it should somehow get overlaid by a + * dirent the two low bits of the hash version will be zero. Therefore, the + * hash version mod 4 should never be 0. Sincerely, the paranoia department. + */ +struct dx_root { + struct fake_dirent dot; + char dot_name[4]; + struct fake_dirent dotdot; + char dotdot_name[4]; + struct dx_root_info { + __le32 reserved_zero; + u8 hash_version; + u8 info_length; /* 8 */ + u8 indirect_levels; + u8 unused_flags; + } info; + struct dx_entry entries[]; +}; + +struct dx_node { + struct fake_dirent fake; + struct dx_entry entries[]; +}; + +struct dx_frame { + struct buffer_head *bh; + struct dx_entry *entries; + struct dx_entry *at; +}; + +struct dx_map_entry { + u32 hash; + u16 offs; + u16 size; +}; + +/* + * This goes at the end of each htree block. + */ +struct dx_tail { + u32 dt_reserved; + __le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */ +}; + +/* + * p is at least 6 bytes before the end of page + */ +static inline struct ext4_dir_entry_2 * +ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize) +{ + return (struct ext4_dir_entry_2 *)((char *)p + + ext4_rec_len_from_disk(p->rec_len, blocksize)); +} + +/* + * Future: use high four bits of block for coalesce-on-delete flags + * Mask them off for now. + */ +static inline ext4_lblk_t dx_get_block(struct dx_entry *entry) +{ + return le32_to_cpu(entry->block) & 0x0fffffff; +} + +static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value) +{ + entry->block = cpu_to_le32(value); +} + +static inline unsigned int dx_get_hash(struct dx_entry *entry) +{ + return le32_to_cpu(entry->hash); +} + +static inline void dx_set_hash(struct dx_entry *entry, unsigned int value) +{ + entry->hash = cpu_to_le32(value); +} + +static inline unsigned int dx_get_count(struct dx_entry *entries) +{ + return le16_to_cpu(((struct dx_countlimit *)entries)->count); +} + +static inline unsigned int dx_get_limit(struct dx_entry *entries) +{ + return le16_to_cpu(((struct dx_countlimit *)entries)->limit); +} + +static inline void dx_set_count(struct dx_entry *entries, unsigned int value) +{ + ((struct dx_countlimit *)entries)->count = cpu_to_le16(value); +} + +static inline void dx_set_limit(struct dx_entry *entries, unsigned int value) +{ + ((struct dx_countlimit *)entries)->limit = cpu_to_le16(value); +} + +static inline unsigned int dx_root_limit(struct inode *dir, unsigned int infosize) +{ + unsigned int entry_space = dir->i_sb->s_blocksize - + ext4_dir_rec_len(1, NULL) - + ext4_dir_rec_len(2, NULL) - infosize; + + if (ext4_has_feature_metadata_csum(dir->i_sb)) + entry_space -= sizeof(struct dx_tail); + return entry_space / sizeof(struct dx_entry); +} + +static inline unsigned int dx_node_limit(struct inode *dir) +{ + unsigned int entry_space = dir->i_sb->s_blocksize - + ext4_dir_rec_len(0, dir); + + if (ext4_has_feature_metadata_csum(dir->i_sb)) + entry_space -= sizeof(struct dx_tail); + return entry_space / sizeof(struct dx_entry); +} + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +struct buffer_head *ext4_append_test(handle_t *handle, struct inode *inode, + ext4_lblk_t *block); +struct buffer_head *ext4_read_dirblock_test(struct inode *inode, + ext4_lblk_t block, + enum dirblock_type type); +void ext4_dx_csum_set_test(struct inode *inode, struct ext4_dir_entry *dirent); +int ext4_dx_csum_verify_test(struct inode *inode, + struct ext4_dir_entry *dirent); +struct dx_frame *dx_probe_test(struct ext4_filename *fname, struct inode *dir, + struct dx_hash_info *hinfo, + struct dx_frame *frame_in); +void dx_release_test(struct dx_frame *frames); +int ext4_htree_next_block_test(struct inode *dir, __u32 hash, + struct dx_frame *frame, + struct dx_frame *frames, __u32 *start_hash); +int dx_make_map_test(struct inode *dir, struct buffer_head *bh, + struct dx_hash_info *hinfo, + struct dx_map_entry *map_tail); +void dx_sort_map_test(struct dx_map_entry *map, unsigned int count); +void dx_insert_block_test(struct dx_frame *frame, u32 hash, ext4_lblk_t block); +struct ext4_dir_entry_2 *dx_move_dirents_test(struct inode *dir, char *from, + char *to, + struct dx_map_entry *map, + int count, + unsigned int blocksize); +struct ext4_dir_entry_2 *dx_pack_dirents_test(struct inode *dir, char *base, + unsigned int blocksize); +struct ext4_dir_entry_2 *do_split_test(handle_t *handle, struct inode *dir, + struct buffer_head **bh, + struct dx_frame *frame, + struct dx_hash_info *hinfo); +bool ext4_check_dx_root_test(struct inode *dir, struct dx_root *root); +struct buffer_head *ext4_find_entry_test(struct inode *dir, + const struct qstr *d_name, + struct ext4_dir_entry_2 **res_dir, + int *inlined); +struct buffer_head *ext4_lookup_entry_test(struct inode *dir, + struct dentry *dentry, + struct ext4_dir_entry_2 **res_dir); +int ext4_add_entry_test(handle_t *handle, struct dentry *dentry, + struct inode *inode); +int ext4_delete_entry_test(handle_t *handle, struct inode *dir, + struct ext4_dir_entry_2 *de_del, + struct buffer_head *bh); +void ext4_inc_count_test(struct inode *inode); +void ext4_dec_count_test(struct inode *inode); +int ext4_init_symlink_block_test(handle_t *handle, struct inode *inode, + struct fscrypt_str *disk_link); +#endif /* CONFIG_EXT4_KUNIT_TESTS */ + +#endif /* _EXT4_NAMEI_H */ diff --git a/fs/ext4/orphan.c b/fs/ext4/orphan.c index 7394d04e0fd930..e04e90039fef2a 100644 --- a/fs/ext4/orphan.c +++ b/fs/ext4/orphan.c @@ -5,6 +5,7 @@ #include #include #include +#include #include "ext4.h" #include "ext4_jbd2.h" @@ -107,6 +108,8 @@ int ext4_orphan_add(handle_t *handle, struct inode *inode) int err = 0, rc; bool dirty = false; + KUNIT_STATIC_STUB_REDIRECT(ext4_orphan_add, handle, inode); + if (!sbi->s_journal || is_bad_inode(inode)) return 0; @@ -187,6 +190,7 @@ int ext4_orphan_add(handle_t *handle, struct inode *inode) ext4_std_error(sb, err); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_add); static int ext4_orphan_file_del(handle_t *handle, struct inode *inode) { @@ -232,6 +236,8 @@ int ext4_orphan_del(handle_t *handle, struct inode *inode) struct ext4_iloc iloc; int err = 0; + KUNIT_STATIC_STUB_REDIRECT(ext4_orphan_del, handle, inode); + if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS)) return 0; @@ -308,6 +314,7 @@ int ext4_orphan_del(handle_t *handle, struct inode *inode) brelse(iloc.bh); goto out_err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_del); #ifdef CONFIG_QUOTA static int ext4_quota_on_mount(struct super_block *sb, int type) From ef1e48eba57ac242b259a5d232c74ae26d55cd25 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Thu, 5 Nov 2026 03:19:31 +0000 Subject: [PATCH 1557/2102] ext4: expand KUnit tests for fs/ext4/mballoc.c Expand the ext4_mballoc_test KUnit test suite in fs/ext4/mballoc-test.c from 7 subtests (21 test cases) to 32 subtests (96 parameterized test cases across 1K, 4K, and 64K block sizes) to comprehensively exercise the multi-block allocator in fs/ext4/mballoc.c: - Low-level bitmap helpers (mb_set_bit, mb_clear_bit, mb_test_bit, mb_find_next_zero_bit, mb_find_next_bit, mb_clear_bits, mb_set_bits, and mb_test_and_clear_bits across clean, partially clear, and fully clear ranges). - Buddy bitmap lookup and extent discovery (mb_find_buddy, mb_find_order_for_block, mb_find_extent for free, used, and merged power-of-two ranges, and mb_regenerate_buddy). - Corrupted block bitmap detection in ext4_mb_generate_buddy (setting EXT4_GROUP_INFO_BBITMAP_CORRUPT when bitmap free count mismatches grp->bb_free) and double-free / EXT4_STATE_FC_REPLAY handling in mb_free_blocks. - Group fragment size order calculation (mb_avg_fragment_size_order), per-order XArray insertion/migration/removal (mb_update_avg_fragment_size and mb_set_largest_free_order), and largest free order tracking. - Group eligibility filtering (ext4_mb_good_group_nolock and ext4_mb_good_group) across CR_POWER2_ALIGNED, CR_GOAL_LEN_FAST, CR_BEST_AVAIL_LEN, CR_GOAL_LEN_SLOW, and CR_ANY_FREE, including BBITMAP_CORRUPT, 0 free blocks, uninitialized bitmaps, and flex_bg metadata allocation rules. - Goal-based allocation (ext4_mb_find_by_goal) covering power-of-two buddies, non-power-of-two extents, EXT4_MB_HINT_MERGE tail merging, stripe-aligned requests, and occupied goals. - Buddy and bitmap group scanning (ext4_mb_simple_scan_group, ext4_mb_scan_aligned, ext4_mb_complex_scan_group, ext4_mb_measure_extent, and ext4_mb_try_best_found) including s_mb_max_to_scan limits and EXT4_MB_HINT_FIRST. - Regular allocator orchestration (ext4_mb_regular_allocator) for EXT4_MB_HINT_GOAL_ONLY, stream allocation (EXT4_MB_STREAM_ALLOC) with s_mb_last_groups updates, and MB_OPTIMIZE_SCAN with CR_BEST_AVAIL_LEN goal length trimming. - Block bitmap prefetching (ext4_mb_prefetch and ext4_mb_prefetch_fini) and allocation context initialization and request normalization (ext4_mb_initialize_context and ext4_mb_normalize_request across metadata/no-normalize, small/large/huge files, stripe alignment, and existing preallocation overlap avoidance). - Inode and locality group preallocation lifecycles (ext4_mb_pa_alloc, ext4_mb_pa_put_free, ext4_mb_new_preallocation, ext4_mb_use_preallocated, ext4_mb_generate_from_pa, ext4_mb_discard_group_preallocations, ext4_discard_preallocations, ext4_mb_discard_preallocations, and locality group list trimming past PREALLOC_TB_SIZE). - Top-level allocation and deallocation entry points (ext4_mb_new_blocks including PA satisfaction and ENOSPC retry after discarding group PAs, ext4_mb_mark_context, ext4_mb_mark_bb, ext4_free_blocks with EXT4_FREE_BLOCKS_NO_QUOT_UPDATE / VALIDATED / METADATA and cross-group extents, mb_free_metadata merging and splitting with ext4_process_freed_data, ext4_group_add_blocks, ext4_trim_fs with a static stub for ext4_issue_discard, and ext4_mballoc_query_range). Export the tested functions with EXPORT_SYMBOL_FOR_EXT4_TEST and add a KUNIT_STATIC_STUB_REDIRECT hook to ext4_issue_discard. Signed-off-by: Theodore Ts'o --- fs/ext4/mballoc-test.c | 1927 +++++++++++++++++++++++++++++++++++++++- fs/ext4/mballoc.c | 168 +++- fs/ext4/mballoc.h | 40 + fs/ext4/super.c | 2 + 4 files changed, 2120 insertions(+), 17 deletions(-) diff --git a/fs/ext4/mballoc-test.c b/fs/ext4/mballoc-test.c index d31780075c21e5..6f70bff5c83a75 100644 --- a/fs/ext4/mballoc-test.c +++ b/fs/ext4/mballoc-test.c @@ -5,8 +5,10 @@ #include #include +#include #include #include +#include #include "ext4.h" #include "mballoc.h" @@ -79,6 +81,7 @@ static int mbt_mb_init(struct super_block *sb) sb->s_bdev = kzalloc_obj(*sb->s_bdev); if (sb->s_bdev == NULL) return -ENOMEM; + bdev_set_flag(sb->s_bdev, BD_READ_ONLY); sb->s_bdev->bd_queue = kzalloc_obj(struct request_queue); if (sb->s_bdev->bd_queue == NULL) { @@ -162,10 +165,15 @@ static struct super_block *mbt_ext4_alloc_super_block(void) goto out_deactivate; bgl_lock_init(sbi->s_blockgroup_lock); + spin_lock_init(&sbi->s_error_lock); + ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10); sbi->s_es = &fsb->es; sbi->s_sb = sb; sb->s_fs_info = sbi; + set_opt(sb, ERRORS_CONT); up_write(&sb->s_umount); return sb; @@ -341,15 +349,75 @@ ext4_mb_mark_context_stub(handle_t *handle, struct super_block *sb, bool state, { struct mbt_grp_ctx *grp_ctx = MBT_GRP_CTX(sb, group); struct buffer_head *bitmap_bh = &grp_ctx->bitmap_bh; + struct ext4_group_desc *gdp = &grp_ctx->desc; + ext4_grpblk_t i, already = 0, changed = len; + __u32 free; - if (state) + for (i = 0; i < len; i++) { + if (mb_test_bit_test(blkoff + i, bitmap_bh->b_data) == state) + already++; + } + if (flags & 0x0001 /* EXT4_MB_BITMAP_MARKED_CHECK */) + changed = len - already; + + free = ext4_free_group_clusters(sb, gdp); + if (state) { mb_set_bits(bitmap_bh->b_data, blkoff, len); - else + if (free >= changed) + ext4_free_group_clusters_set(sb, gdp, free - changed); + } else { mb_clear_bits_test(bitmap_bh->b_data, blkoff, len); + ext4_free_group_clusters_set(sb, gdp, free + changed); + } + + if (ret_changed) + *ret_changed = changed; return 0; } +static int +ext4_issue_discard_stub(struct super_block *sb, ext4_group_t block_group, + ext4_grpblk_t cluster, int count) +{ + return 0; +} + +static struct inode *mbt_alloc_test_inode(struct kunit *test, + struct super_block *sb, + umode_t mode) +{ + struct ext4_inode_info *ei; + struct inode *inode; + + ei = kunit_kzalloc(test, sizeof(*ei), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ei); + + INIT_LIST_HEAD(&ei->i_orphan); + init_rwsem(&ei->xattr_sem); + init_rwsem(&ei->i_data_sem); + ei->i_prealloc_node = RB_ROOT; + atomic_set(&ei->i_prealloc_active, 0); + rwlock_init(&ei->i_prealloc_lock); + spin_lock_init(&ei->i_block_reservation_lock); + spin_lock_init(&ei->i_raw_lock); + + inode = &ei->vfs_inode; + inode_init_once(inode); + spin_lock_init(&inode->i_lock); + init_rwsem(&inode->i_rwsem); + init_rwsem(&inode->i_data.invalidate_lock); + ext4_fc_init_inode(inode); + inode->i_sb = sb; + inode->i_ino = 12; + inode->i_mode = mode; + inode->i_flags |= S_NOQUOTA; + atomic_set(&inode->i_writecount, 1); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + + return inode; +} + #define TEST_GOAL_GROUP 1 static int mbt_kunit_init(struct kunit *test) { @@ -382,6 +450,9 @@ static int mbt_kunit_init(struct kunit *test) kunit_activate_static_stub(test, ext4_mb_mark_context, ext4_mb_mark_context_stub); + kunit_activate_static_stub(test, + ext4_issue_discard, + ext4_issue_discard_stub); /* stub function will be called in mbt_mb_init->ext4_mb_init */ if (mbt_mb_init(sb) != 0) { @@ -402,7 +473,10 @@ static void mbt_kunit_exit(struct kunit *test) if (!sb) return; + if (sb->s_blocksize <= PAGE_SIZE) + ext4_mb_discard_preallocations_test(sb, 0); mbt_mb_release(sb); + rcu_barrier(); mbt_ctx_release(sb); mbt_ext4_free_super_block(sb); } @@ -417,11 +491,7 @@ static void test_new_blocks_simple(struct kunit *test) ext4_fsblk_t found; struct ext4_sb_info *sbi = EXT4_SB(sb); - inode = kunit_kzalloc(test, sizeof(*inode), GFP_KERNEL); - if (!inode) - return; - - inode->i_sb = sb; + inode = mbt_alloc_test_inode(test, sb, S_IFREG); ar.inode = inode; /* get block at goal */ @@ -527,10 +597,7 @@ test_free_blocks_simple_range(struct kunit *test, ext4_group_t goal_group, struct inode *inode; ext4_fsblk_t block; - inode = kunit_kzalloc(test, sizeof(*inode), GFP_KERNEL); - if (!inode) - return; - inode->i_sb = sb; + inode = mbt_alloc_test_inode(test, sb, S_IFREG); if (len == 0) return; @@ -601,10 +668,7 @@ static void test_mark_diskspace_used(struct kunit *test) mbt_generate_test_ranges(sb, ranges, TEST_RANGE_COUNT); - inode = kunit_kzalloc(test, sizeof(*inode), GFP_KERNEL); - if (!inode) - return; - inode->i_sb = sb; + inode = mbt_alloc_test_inode(test, sb, S_IFREG); ac.ac_status = AC_STATUS_FOUND; ac.ac_sb = sb; @@ -949,6 +1013,1814 @@ static void test_mb_mark_used_cost(struct kunit *test) ext4_mb_unload_buddy_test(&e4b); } +static void test_mb_bit_ops(struct kunit *test) +{ + u8 *buf; + void *unaligned; + int bit, i; + + buf = kunit_kzalloc(test, 128, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf); + + /* + * Use an unaligned pointer (offset by 3 bytes) to exercise + * mb_correct_addr_and_bit() on 64-bit/32-bit architectures. + */ + unaligned = buf + 3; + + mb_set_bit_test(0, unaligned); + mb_set_bit_test(7, unaligned); + mb_set_bit_test(64, unaligned); + KUNIT_EXPECT_NE(test, mb_test_bit_test(0, unaligned), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(1, unaligned), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(7, unaligned), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(64, unaligned), 0); + + mb_clear_bit_test(7, unaligned); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(7, unaligned), 0); + + bit = mb_find_next_bit_test(unaligned, 128, 1); + KUNIT_EXPECT_EQ(test, bit, 64); + + /* Clamping when no set bit exists before max */ + bit = mb_find_next_bit_test(unaligned, 60, 1); + KUNIT_EXPECT_EQ(test, bit, 60); + + /* Zero-length mb_set_bits / mb_clear_bits should be a no-op */ + memset(buf, 0, 128); + mb_set_bits(buf, 10, 0); + KUNIT_EXPECT_EQ(test, mb_find_next_bit_test(buf, 256, 0), 256); + + /* Multi-word range spanning head bits, 32-bit words, and tail */ + mb_set_bits(buf, 5, 75); + KUNIT_EXPECT_EQ(test, mb_find_next_bit_test(buf, 256, 0), 5); + KUNIT_EXPECT_EQ(test, mb_find_next_zero_bit_test(buf, 256, 5), 80); + /* Clamping when no zero bit exists before max */ + KUNIT_EXPECT_EQ(test, mb_find_next_zero_bit_test(buf, 50, 5), 50); + + /* Clear a sub-range across 32-bit boundaries */ + mb_clear_bits_test(buf, 13, 50); + for (i = 0; i < 100; i++) { + int expected = (i >= 5 && i < 13) || (i >= 63 && i < 80); + + KUNIT_EXPECT_EQ(test, !!mb_test_bit_test(i, buf), expected); + } +} + +static void test_mb_test_and_clear_bits(struct kunit *test) +{ + u8 *buf; + void *bm; + int ret, i; + + buf = kunit_kzalloc(test, 128, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf); + bm = buf; + + /* Case 1: All bits in range [5, 85) are set -> returns -1 and clears all */ + memset(buf, 0xff, 128); + ret = mb_test_and_clear_bits_test(bm, 5, 80); + KUNIT_EXPECT_EQ(test, ret, -1); + KUNIT_EXPECT_NE(test, mb_test_bit_test(4, bm), 0); + for (i = 5; i < 85; i++) + KUNIT_EXPECT_EQ(test, mb_test_bit_test(i, bm), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(85, bm), 0); + + /* Case 2: Zero bit in the unaligned head (bit 7) */ + memset(buf, 0xff, 128); + mb_clear_bit_test(7, bm); + ret = mb_test_and_clear_bits_test(bm, 5, 80); + KUNIT_EXPECT_EQ(test, ret, 7); + for (i = 5; i < 85; i++) + KUNIT_EXPECT_EQ(test, mb_test_bit_test(i, bm), 0); + + /* Case 3: Zero bit inside the 32-bit word fast-path region (bit 45) */ + memset(buf, 0xff, 128); + mb_clear_bit_test(45, bm); + ret = mb_test_and_clear_bits_test(bm, 5, 80); + KUNIT_EXPECT_EQ(test, ret, 45); + for (i = 5; i < 85; i++) + KUNIT_EXPECT_EQ(test, mb_test_bit_test(i, bm), 0); +} + +static void test_mb_find_buddy_and_order(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_free_extent ex; + void *bb; + int max = 0, ret; + int ord0, ord1, ord2, ord3; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* Order 0 returns bitmap and bit count */ + bb = mb_find_buddy_test(&e4b, 0, &max); + KUNIT_EXPECT_PTR_EQ(test, bb, e4b.bd_bitmap); + KUNIT_EXPECT_EQ(test, max, (int)(sb->s_blocksize << 3)); + + /* Valid higher order returns buddy offset */ + bb = mb_find_buddy_test(&e4b, 1, &max); + KUNIT_EXPECT_PTR_EQ(test, bb, e4b.bd_buddy + sbi->s_mb_offsets[1]); + KUNIT_EXPECT_EQ(test, max, sbi->s_mb_maxs[1]); + + /* Out-of-bounds order (> bd_blkbits + 1) returns NULL and max = 0 */ + bb = mb_find_buddy_test(&e4b, MB_NUM_ORDERS(sb), &max); + KUNIT_EXPECT_NULL(test, bb); + KUNIT_EXPECT_EQ(test, max, 0); + + /* + * Mark cluster 0 used in group 1: this splits the group so that: + * - cluster 1 is free at order 0 + * - clusters [2, 4) are free at order 1 + * - clusters [4, 8) are free at order 2 + * - clusters [8, 16) are free at order 3 + */ + ex.fe_group = TEST_GOAL_GROUP; + ex.fe_start = 0; + ex.fe_len = 1; + ext4_lock_group(sb, TEST_GOAL_GROUP); + mb_mark_used_test(&e4b, &ex); + ord0 = mb_find_order_for_block_test(&e4b, 1); + ord1 = mb_find_order_for_block_test(&e4b, 2); + ord2 = mb_find_order_for_block_test(&e4b, 4); + ord3 = mb_find_order_for_block_test(&e4b, 8); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_EQ(test, ord0, 0); + KUNIT_EXPECT_EQ(test, ord1, 1); + KUNIT_EXPECT_EQ(test, ord2, 2); + KUNIT_EXPECT_EQ(test, ord3, 3); + + ext4_mb_unload_buddy_test(&e4b); +} + +static void test_mb_find_extent(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_buddy e4b; + struct ext4_free_extent ex, found_used, found_small, found_coalesced, found_unaligned; + int ret, len_used, len_small, len_coalesced, len_unaligned; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * Leave only [10, 26) (16 clusters) free: + * [10, 12) order 1 (2) + [12, 16) order 2 (4) + + * [16, 24) order 3 (8) + [24, 26) order 1 (2). + */ + ext4_lock_group(sb, TEST_GOAL_GROUP); + ex.fe_group = TEST_GOAL_GROUP; + ex.fe_start = 0; + ex.fe_len = 10; + mb_mark_used_test(&e4b, &ex); + + ex.fe_start = 26; + ex.fe_len = EXT4_CLUSTERS_PER_GROUP(sb) - 26; + mb_mark_used_test(&e4b, &ex); + + len_used = mb_find_extent_test(&e4b, 5, 8, &found_used); + len_small = mb_find_extent_test(&e4b, 10, 1, &found_small); + len_coalesced = mb_find_extent_test(&e4b, 10, 20, &found_coalesced); + len_unaligned = mb_find_extent_test(&e4b, 11, 20, &found_unaligned); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + /* Used block returns 0 */ + KUNIT_EXPECT_EQ(test, len_used, 0); + KUNIT_EXPECT_EQ(test, found_used.fe_len, 0); + + /* Needed = 1 at block 10 returns the order-1 buddy [10, 12) */ + KUNIT_EXPECT_EQ(test, len_small, 2); + KUNIT_EXPECT_EQ(test, found_small.fe_start, 10); + KUNIT_EXPECT_EQ(test, found_small.fe_len, 2); + + /* Needed = 20 at block 10 coalesces across orders 1, 2, 3, 1 -> 16 clusters */ + KUNIT_EXPECT_EQ(test, len_coalesced, 16); + KUNIT_EXPECT_EQ(test, found_coalesced.fe_start, 10); + KUNIT_EXPECT_EQ(test, found_coalesced.fe_len, 16); + + /* Unaligned start at block 11 coalesces [11, 26) -> 15 clusters */ + KUNIT_EXPECT_EQ(test, len_unaligned, 15); + KUNIT_EXPECT_EQ(test, found_unaligned.fe_start, 11); + KUNIT_EXPECT_EQ(test, found_unaligned.fe_len, 15); + + ext4_mb_unload_buddy_test(&e4b); +} + +static void test_mb_generate_buddy_corrupt(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_group_info *grp; + void *bitmap, *buddy; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + bool is_corrupt; + ext4_grpblk_t corrected_free; + int i; + + bitmap = kunit_kzalloc(test, sb->s_blocksize, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bitmap); + buddy = kunit_kzalloc(test, sb->s_blocksize, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buddy); + + grp = ext4_get_group_info(sb, TEST_GOAL_GROUP); + KUNIT_ASSERT_NOT_NULL(test, grp); + + /* Mark 10 clusters used in bitmap, so actual free is max - 10 */ + mb_set_bits(bitmap, max, sb->s_blocksize * 8 - max); + mb_set_bits(bitmap, 0, 10); + + ext4_lock_group(sb, TEST_GOAL_GROUP); + for (i = 0; i < MB_NUM_ORDERS(sb); i++) + grp->bb_counters[i] = 0; + /* Intentionally set wrong bb_free = max (mismatch with max - 10) */ + grp->bb_free = max; + memset(buddy, 0xff, sb->s_blocksize); + ext4_mb_generate_buddy_test(sb, buddy, bitmap, TEST_GOAL_GROUP, grp); + is_corrupt = EXT4_MB_GRP_BBITMAP_CORRUPT(grp); + corrected_free = grp->bb_free; + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_TRUE(test, is_corrupt); + KUNIT_EXPECT_EQ(test, corrected_free, max - 10); +} + +static void test_mb_free_blocks_double_free_and_fc_replay(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_free_extent ex; + bool corrupt_normal, corrupt_fc; + ext4_grpblk_t free_after_fc; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + /* Part 1: Normal mode double-free marks group bitmap corrupt */ + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + ext4_lock_group(sb, TEST_GOAL_GROUP); + /* Clusters [10, 14) are already free; freeing them again is a double free */ + mb_free_blocks_test(NULL, &e4b, 10, 4); + corrupt_normal = EXT4_MB_GRP_BBITMAP_CORRUPT(e4b.bd_info); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + ext4_mb_unload_buddy_test(&e4b); + + KUNIT_EXPECT_TRUE(test, corrupt_normal); + + /* + * Part 2: In EXT4_FC_REPLAY mode, freeing an already-freed range + * triggers mb_regenerate_buddy() instead of marking the group corrupt. + */ + ret = ext4_mb_load_buddy_test(sb, 2, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + ext4_lock_group(sb, 2); + ex.fe_group = 2; + ex.fe_start = 10; + ex.fe_len = 10; + mb_mark_used_test(&e4b, &ex); + /* Free sub-range [12, 16) first so [12, 16) is already free */ + mb_free_blocks_test(NULL, &e4b, 12, 4); + + /* Re-freeing [12, 16) in EXT4_FC_REPLAY mode regenerates buddy cleanly */ + sbi->s_mount_state |= EXT4_FC_REPLAY; + mb_free_blocks_test(NULL, &e4b, 12, 4); + sbi->s_mount_state &= ~EXT4_FC_REPLAY; + + corrupt_fc = EXT4_MB_GRP_BBITMAP_CORRUPT(e4b.bd_info); + free_after_fc = e4b.bd_info->bb_free; + ext4_unlock_group(sb, 2); + ext4_mb_unload_buddy_test(&e4b); + + KUNIT_EXPECT_FALSE(test, corrupt_fc); + KUNIT_EXPECT_EQ(test, free_after_fc, EXT4_CLUSTERS_PER_GROUP(sb) - 6); +} + +static void test_mb_xarray_orders_and_frag_size(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_group_info *grp; + int ord_1, ord_4, ord_7, ord_8; + int old_lfo, new_lfo, new_afso; + void *xa_lfo_entry, *xa_afso_entry, *xa_old_entry; + int i; + + set_opt2(sb, MB_OPTIMIZE_SCAN); + + /* mb_avg_fragment_size_order computes clamp(fls(len) - 2, 0, MB_NUM_ORDERS - 1) */ + ord_1 = mb_avg_fragment_size_order_test(sb, 1); + ord_4 = mb_avg_fragment_size_order_test(sb, 4); + ord_7 = mb_avg_fragment_size_order_test(sb, 7); + ord_8 = mb_avg_fragment_size_order_test(sb, 8); + KUNIT_EXPECT_EQ(test, ord_1, 0); + KUNIT_EXPECT_EQ(test, ord_4, 1); + KUNIT_EXPECT_EQ(test, ord_7, 1); + KUNIT_EXPECT_EQ(test, ord_8, 2); + + grp = ext4_get_group_info(sb, TEST_GOAL_GROUP); + KUNIT_ASSERT_NOT_NULL(test, grp); + + ext4_lock_group(sb, TEST_GOAL_GROUP); + old_lfo = grp->bb_largest_free_order; + for (i = 0; i < MB_NUM_ORDERS(sb); i++) + grp->bb_counters[i] = 0; + grp->bb_counters[3] = 2; + grp->bb_free = 16; + grp->bb_fragments = 2; + + mb_set_largest_free_order_test(sb, grp); + mb_update_avg_fragment_size_test(sb, grp); + + new_lfo = grp->bb_largest_free_order; + new_afso = grp->bb_avg_fragment_size_order; + xa_lfo_entry = xa_load(&sbi->s_mb_largest_free_orders[3], TEST_GOAL_GROUP); + xa_afso_entry = xa_load(&sbi->s_mb_avg_fragment_size[2], TEST_GOAL_GROUP); + + /* Now mark group completely full and verify XArray entries are erased */ + grp->bb_counters[3] = 0; + grp->bb_free = 0; + grp->bb_fragments = 0; + mb_set_largest_free_order_test(sb, grp); + mb_update_avg_fragment_size_test(sb, grp); + xa_old_entry = xa_load(&sbi->s_mb_largest_free_orders[3], TEST_GOAL_GROUP); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_EQ(test, old_lfo, -1); + KUNIT_EXPECT_EQ(test, new_lfo, 3); + KUNIT_EXPECT_EQ(test, new_afso, 2); + KUNIT_EXPECT_PTR_EQ(test, xa_lfo_entry, grp); + KUNIT_EXPECT_PTR_EQ(test, xa_afso_entry, grp); + KUNIT_EXPECT_NULL(test, xa_old_entry); +} + +static void test_mb_good_group(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_allocation_context ac = {}; + struct ext4_group_info *grp1, *grp2; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + /* Initialize group 1 buddy cache so bb_fragments and orders are populated */ + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + + grp1 = ext4_get_group_info(sb, TEST_GOAL_GROUP); + KUNIT_ASSERT_NOT_NULL(test, grp1); + + ac.ac_sb = sb; + ac.ac_2order = 3; + ac.ac_g_ex.fe_len = 8; + ac.ac_flags = EXT4_MB_HINT_DATA; + + /* Group 1 has all clusters free in 1 fragment -> eligible at all CRs */ + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_POWER2_ALIGNED)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_GOAL_LEN_FAST)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_BEST_AVAIL_LEN)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_GOAL_LEN_SLOW)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_ANY_FREE)); + + /* + * Simulate high fragmentation: free = 16, fragments = 8 (avg = 2 < 8), + * largest_free_order = 1 (< ac_2order = 3). + * CR_POWER2_ALIGNED, CR_GOAL_LEN_FAST, CR_BEST_AVAIL_LEN must reject, + * while CR_GOAL_LEN_SLOW (free 16 >= 8) and CR_ANY_FREE accept. + */ + ext4_lock_group(sb, TEST_GOAL_GROUP); + grp1->bb_free = 16; + grp1->bb_fragments = 8; + grp1->bb_largest_free_order = 1; + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_FALSE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_POWER2_ALIGNED)); + KUNIT_EXPECT_FALSE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_GOAL_LEN_FAST)); + KUNIT_EXPECT_FALSE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_BEST_AVAIL_LEN)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_GOAL_LEN_SLOW)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_ANY_FREE)); + + /* When free = 4 < fe_len = 8, CR_GOAL_LEN_SLOW rejects, CR_ANY_FREE accepts */ + ext4_lock_group(sb, TEST_GOAL_GROUP); + grp1->bb_free = 4; + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_FALSE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_GOAL_LEN_SLOW)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_ANY_FREE)); + + /* Flex_bg first group avoidance at CR_POWER2_ALIGNED for data */ + ret = ext4_mb_load_buddy_test(sb, 0, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + sbi->s_log_groups_per_flex = 2; /* flex_size = 4 >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME */ + KUNIT_EXPECT_FALSE(test, ext4_mb_good_group_test(&ac, 0, CR_POWER2_ALIGNED)); + sbi->s_log_groups_per_flex = 0; + + /* + * Test ext4_mb_good_group_nolock on an uninitialized group on a + * separate buddy-cache folio: + * At inexpensive CR_POWER2_ALIGNED, it skips initializing the group + * and returns 0. At expensive CR_GOAL_LEN_SLOW (with STRICT_CHECK), + * it initializes the group and returns 1. + */ + { + ext4_group_t uninit_grp = max_t(ext4_group_t, 2, + DIV_ROUND_UP(PAGE_SIZE / sb->s_blocksize, 2)); + + if (uninit_grp < ext4_get_groups_count(sb)) { + grp2 = ext4_get_group_info(sb, uninit_grp); + KUNIT_ASSERT_NOT_NULL(test, grp2); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp2)); + + ac.ac_criteria = CR_POWER2_ALIGNED; + ret = ext4_mb_good_group_nolock_test(&ac, uninit_grp, + CR_POWER2_ALIGNED); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp2)); + + ac.ac_flags |= EXT4_MB_STRICT_CHECK; + ac.ac_criteria = CR_GOAL_LEN_SLOW; + ret = ext4_mb_good_group_nolock_test(&ac, uninit_grp, + CR_GOAL_LEN_SLOW); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_NEED_INIT(grp2)); + } + } +} + +static void test_mb_find_by_goal(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_allocation_context ac = {}; + struct inode *inode; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* Mark [24, 32) used in group 1 so [20, 24) has only 4 free clusters */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 24, 8); + ext4_get_group_info(sb, TEST_GOAL_GROUP)->bb_free -= 8; + + /* 1. Exact goal hit at [10, 14) */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_TRY_GOAL; + ac.ac_g_ex.fe_group = TEST_GOAL_GROUP; + ac.ac_g_ex.fe_start = 10; + ac.ac_g_ex.fe_len = 4; + ac.ac_o_ex = ac.ac_g_ex; + + ret = ext4_mb_find_by_goal_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_group, TEST_GOAL_GROUP); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 10); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 4); + + /* 2. Partial goal at [20, 28) without HINT_MERGE fails to match */ + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_TRY_GOAL; + ac.ac_g_ex.fe_group = TEST_GOAL_GROUP; + ac.ac_g_ex.fe_start = 20; + ac.ac_g_ex.fe_len = 8; + ac.ac_o_ex = ac.ac_g_ex; + + ret = ext4_mb_find_by_goal_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_CONTINUE); + + /* 3. Partial goal at [20, 28) WITH EXT4_MB_HINT_MERGE allocates [20, 24) */ + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_TRY_GOAL | EXT4_MB_HINT_MERGE; + ac.ac_g_ex.fe_group = TEST_GOAL_GROUP; + ac.ac_g_ex.fe_start = 20; + ac.ac_g_ex.fe_len = 8; + ac.ac_o_ex = ac.ac_g_ex; + + ret = ext4_mb_find_by_goal_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 20); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 4); + + /* + * 4. Stripe-aligned check: s_stripe = 8 clusters; unaligned start 36 + * rejected, aligned 40 accepted. + */ + sbi->s_stripe = EXT4_C2B(sbi, 8); + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_TRY_GOAL; + ac.ac_g_ex.fe_group = TEST_GOAL_GROUP; + ac.ac_g_ex.fe_start = 36; + ac.ac_g_ex.fe_len = 8; + ac.ac_o_ex = ac.ac_g_ex; + + ret = ext4_mb_find_by_goal_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_CONTINUE); + + ac.ac_g_ex.fe_start = 40; + ac.ac_o_ex = ac.ac_g_ex; + ret = ext4_mb_find_by_goal_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 40); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 8); + sbi->s_stripe = 0; +} + +static void test_mb_simple_and_aligned_scan(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_allocation_context ac = {}; + struct inode *inode; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* + * Mark cluster 0 used in group 1 so: + * - order 3 buddy [8, 16) is the first order-3 buddy + * - first 16-cluster stripe [0, 16) is not completely free, so + * stripe-aligned scan must skip to cluster 16. + */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 0, 1); + ext4_get_group_info(sb, TEST_GOAL_GROUP)->bb_free--; + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* 1. ext4_mb_simple_scan_group with ac_2order = 3 (8 clusters) */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_criteria = CR_POWER2_ALIGNED; + ac.ac_2order = 3; + ac.ac_g_ex.fe_len = 8; + ac.ac_o_ex.fe_len = 8; + + ext4_lock_group(sb, TEST_GOAL_GROUP); + ext4_mb_simple_scan_group_test(&ac, &e4b); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + ext4_mb_release_context_test(&ac); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_group, TEST_GOAL_GROUP); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 8); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 8); + + /* 2. ext4_mb_scan_aligned with stripe = 16 clusters */ + sbi->s_stripe = EXT4_C2B(sbi, 16); + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_criteria = CR_GOAL_LEN_FAST; + ac.ac_g_ex.fe_len = 16; + ac.ac_o_ex.fe_len = 16; + + ext4_lock_group(sb, TEST_GOAL_GROUP); + ext4_mb_scan_aligned_test(&ac, &e4b); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + ext4_mb_release_context_test(&ac); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_group, TEST_GOAL_GROUP); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 16); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 16); + + sbi->s_stripe = 0; + ext4_mb_unload_buddy_test(&e4b); +} + +static void test_mb_complex_scan_and_measure(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_allocation_context ac = {}; + struct inode *inode; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* + * Create 3 power-of-2 aligned free extents in TEST_GOAL_GROUP: + * - [0, 4) len 4 (order 2 buddy) + * - [16, 32) len 16 (order 4 buddy) + * - [40, 48) len 8 (order 3 buddy) + * Mark everything else used (total free = 28 clusters). + */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 4, 12); + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 32, 8); + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 48, max - 48); + ext4_get_group_info(sb, TEST_GOAL_GROUP)->bb_free = 28; + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * Case 1: Goal len = 5 at CR_GOAL_LEN_SLOW. + * Scans [0, 4) (len 4 < 5), [16, 32) (order 4 buddy -> len 16 > 5), + * and [40, 48) (order 3 buddy -> len 8 > 5, smaller than 16 so preferred!), + * then allocates 5 clusters from [40, 48) at finish_group. + */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_criteria = CR_GOAL_LEN_SLOW; + ac.ac_g_ex.fe_len = 5; + ac.ac_o_ex.fe_len = 5; + + ext4_lock_group(sb, TEST_GOAL_GROUP); + ext4_mb_complex_scan_group_test(&ac, &e4b); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + ext4_mb_release_context_test(&ac); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 40); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 5); + + /* + * Case 2: Goal len = 32 (larger than any free extent) with s_mb_max_to_scan = 1. + * Scanning [0, 4) and [16, 32) increments ac_found to 2 > s_mb_max_to_scan, + * triggering AC_STATUS_BREAK with best smaller extent [16, 32) (len 16) + * recorded in ac_b_ex. Calling ext4_mb_try_best_found() then claims [16, 32). + */ + sbi->s_mb_max_to_scan = 1; + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_criteria = CR_ANY_FREE; + ac.ac_g_ex.fe_len = 32; + ac.ac_o_ex.fe_len = 32; + + ext4_lock_group(sb, TEST_GOAL_GROUP); + ext4_mb_complex_scan_group_test(&ac, &e4b); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_BREAK); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 16); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 16); + + ext4_mb_try_best_found_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 16); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 16); + + /* + * Case 3: EXT4_MB_HINT_FIRST immediately takes the first free extent [0, 4). + */ + sbi->s_mb_max_to_scan = 200; + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_criteria = CR_ANY_FREE; + ac.ac_flags = EXT4_MB_HINT_FIRST; + ac.ac_g_ex.fe_len = 4; + ac.ac_o_ex.fe_len = 4; + + ext4_lock_group(sb, TEST_GOAL_GROUP); + ext4_mb_complex_scan_group_test(&ac, &e4b); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + ext4_mb_release_context_test(&ac); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 0); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 4); + + ext4_mb_unload_buddy_test(&e4b); +} + +static void test_mb_regular_allocator(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_allocation_context ac = {}; + struct inode *inode; + int ret, hash; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* + * 1. EXT4_MB_HINT_GOAL_ONLY when goal block (group 0, cluster 0) is already + * marked used: must stop immediately without scanning other blocks. + */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_GOAL_ONLY; + ac.ac_g_ex.fe_group = 0; + ac.ac_g_ex.fe_start = 0; + ac.ac_g_ex.fe_len = 1; + ac.ac_o_ex = ac.ac_g_ex; + + ret = ext4_mb_regular_allocator_test(&ac); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_CONTINUE); + + /* + * 2. Stream allocation (EXT4_MB_STREAM_ALLOC) with group 0 full: + * allocates in group 1 and updates s_mb_last_groups[hash] to 1. + */ + mbt_ctx_mark_used(sb, 0, 0, EXT4_CLUSTERS_PER_GROUP(sb)); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 0)->desc, 0); + ext4_get_group_info(sb, 0)->bb_free = 0; + + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_STREAM_ALLOC | EXT4_MB_HINT_DATA; + ac.ac_g_ex.fe_len = 8; + ac.ac_orig_goal_len = 8; + ac.ac_o_ex.fe_len = 8; + + ret = ext4_mb_regular_allocator_test(&ac); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_group, 1); + + hash = (unsigned int)inode->i_ino % sbi->s_mb_nr_global_goals; + KUNIT_EXPECT_EQ(test, READ_ONCE(sbi->s_mb_last_groups[hash]), 1); + + /* + * 3. MB_OPTIMIZE_SCAN with CR_BEST_AVAIL_LEN goal length trimming: + * Make group 2 the only group with free blocks, fragmented into two + * 8-cluster chunks [0, 8) and [16, 24) so largest_free_order = 3 + * and avg_fragment_size = 8. + * Note: group 2 may have already been prefetched during step 2, so + * mark its blocks used via mb_mark_used_test on the loaded buddy. + */ + set_opt2(sb, MB_OPTIMIZE_SCAN); + mbt_ctx_mark_used(sb, 1, 0, EXT4_CLUSTERS_PER_GROUP(sb)); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 1)->desc, 0); + ext4_get_group_info(sb, 1)->bb_free = 0; + ext4_get_group_info(sb, 1)->bb_fragments = 0; + mb_set_largest_free_order_test(sb, ext4_get_group_info(sb, 1)); + mb_update_avg_fragment_size_test(sb, ext4_get_group_info(sb, 1)); + + mbt_ctx_mark_used(sb, 3, 0, EXT4_CLUSTERS_PER_GROUP(sb)); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 3)->desc, 0); + ext4_get_group_info(sb, 3)->bb_free = 0; + ext4_get_group_info(sb, 3)->bb_fragments = 0; + mb_set_largest_free_order_test(sb, ext4_get_group_info(sb, 3)); + mb_update_avg_fragment_size_test(sb, ext4_get_group_info(sb, 3)); + + { + struct ext4_buddy e4b; + struct ext4_free_extent ex; + + ret = ext4_mb_load_buddy_test(sb, 2, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_lock_group(sb, 2); + ex.fe_group = 2; + ex.fe_start = 8; + ex.fe_len = 8; + mb_mark_used_test(&e4b, &ex); + ex.fe_start = 24; + ex.fe_len = EXT4_CLUSTERS_PER_GROUP(sb) - 24; + mb_mark_used_test(&e4b, &ex); + ext4_unlock_group(sb, 2); + ext4_mb_unload_buddy_test(&e4b); + } + + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_DATA; + ac.ac_g_ex.fe_group = 0; + ac.ac_g_ex.fe_len = 16; + ac.ac_orig_goal_len = 16; + ac.ac_o_ex.fe_len = 4; + + ret = ext4_mb_pa_alloc_test(&ac); + KUNIT_ASSERT_EQ(test, ret, 0); + + ret = ext4_mb_regular_allocator_test(&ac); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_criteria, CR_BEST_AVAIL_LEN); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_group, 2); + KUNIT_EXPECT_EQ(test, ac.ac_f_ex.fe_len, 8); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 4); + ext4_discard_preallocations(inode); +} + +static void test_mb_prefetch(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_group_info *grp0, *grp1, *grp2; + ext4_group_t next_grp, uninit_grp; + int ios = 0; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + uninit_grp = max_t(ext4_group_t, 2, + DIV_ROUND_UP(PAGE_SIZE / sb->s_blocksize, 2)); + + grp0 = ext4_get_group_info(sb, 0); + grp1 = ext4_get_group_info(sb, 1); + grp2 = ext4_get_group_info(sb, 2); + KUNIT_ASSERT_NOT_NULL(test, grp0); + KUNIT_ASSERT_NOT_NULL(test, grp1); + KUNIT_ASSERT_NOT_NULL(test, grp2); + + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp0)); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp1)); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp2)); + + next_grp = ext4_mb_prefetch(sb, 0, 2, &ios); + KUNIT_EXPECT_EQ(test, next_grp, 2); + /* First prefetch of uninitialized buffers increments ios count */ + KUNIT_EXPECT_EQ(test, ios, 2); + + /* Repeated prefetch on the same groups does not re-read bitmaps */ + ios = 0; + ext4_mb_prefetch(sb, 0, 2, &ios); + KUNIT_EXPECT_EQ(test, ios, 0); + + /* ext4_mb_prefetch_fini initializes the prefetched groups [0, 2) */ + ext4_mb_prefetch_fini(sb, next_grp, 2); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_NEED_INIT(grp0)); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_NEED_INIT(grp1)); + if (uninit_grp < ext4_get_groups_count(sb)) { + grp2 = ext4_get_group_info(sb, uninit_grp); + KUNIT_ASSERT_NOT_NULL(test, grp2); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp2)); + } +} + +static void test_mb_initialize_context(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_allocation_context ac = {}; + struct ext4_allocation_request ar = {}; + struct inode *inode; + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* 1. Small open file (<= s_mb_stream_request) uses locality group alloc */ + i_size_write(inode, sb->s_blocksize); + ar.inode = inode; + ar.logical = 0; + ar.len = 1; + ar.goal = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + ar.flags = EXT4_MB_HINT_DATA; + + ext4_mb_initialize_context_test(&ac, &ar); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_NE(test, ac.ac_flags & EXT4_MB_HINT_GROUP_ALLOC, 0); + KUNIT_EXPECT_NOT_NULL(test, ac.ac_lg); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_group, TEST_GOAL_GROUP); + + /* 2. Large open file (> s_mb_stream_request) uses stream alloc */ + memset(&ac, 0, sizeof(ac)); + i_size_write(inode, (loff_t)(sbi->s_mb_stream_request + 64) << sb->s_blocksize_bits); + ext4_mb_initialize_context_test(&ac, &ar); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_NE(test, ac.ac_flags & EXT4_MB_STREAM_ALLOC, 0); + KUNIT_EXPECT_NULL(test, ac.ac_lg); + + /* + * 3. Closed file (i_writecount == 0) with size == isize and + * size > s_mb_stream_request sets EXT4_MB_HINT_NOPREALLOC. + */ + memset(&ac, 0, sizeof(ac)); + atomic_set(&inode->i_writecount, 0); + ar.logical = EXT4_LBLK_CMASK(sbi, sbi->s_mb_stream_request + EXT4_C2B(sbi, 2)); + ar.len = 1; + i_size_write(inode, (loff_t)(ar.logical + EXT4_C2B(sbi, 1)) << sb->s_blocksize_bits); + /* Also test out-of-range ar.goal fallback to group 0 */ + ar.goal = ext4_blocks_count(sbi->s_es) + 100; + ext4_mb_initialize_context_test(&ac, &ar); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_NE(test, ac.ac_flags & EXT4_MB_HINT_NOPREALLOC, 0); + KUNIT_EXPECT_EQ(test, ac.ac_o_ex.fe_group, 0); + KUNIT_EXPECT_EQ(test, ac.ac_o_ex.fe_start, 0); +} + +static void test_mb_normalize_request(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_allocation_context ac = {}; + struct ext4_allocation_request ar = {}; + struct inode *inode; + struct ext4_inode_info *ei; + struct ext4_prealloc_space left_pa = {}, right_pa = {}; + int bsbits = sb->s_blocksize_bits; + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + ei = EXT4_I(inode); + + /* 1. Metadata request (no EXT4_MB_HINT_DATA) is not normalized */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_o_ex.fe_logical = 0; + ac.ac_o_ex.fe_len = 1; + ac.ac_g_ex = ac.ac_o_ex; + ext4_mb_normalize_request_test(&ac, &ar); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_len, 1); + + /* 2. Locality group request normalizes fe_len to s_mb_group_prealloc */ + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags = EXT4_MB_HINT_DATA | EXT4_MB_HINT_GROUP_ALLOC; + ac.ac_lg = raw_cpu_ptr(sbi->s_locality_groups); + ac.ac_o_ex.fe_len = 1; + ac.ac_g_ex = ac.ac_o_ex; + ext4_mb_normalize_request_test(&ac, &ar); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_len, sbi->s_mb_group_prealloc); + + /* 3. Small file (<= 16KB) normalizes up to max(SZ_16K, cluster_size) */ + if ((SZ_16K >> bsbits) >= sbi->s_cluster_ratio) { + memset(&ac, 0, sizeof(ac)); + i_size_write(inode, 4096); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags = EXT4_MB_HINT_DATA; + ac.ac_o_ex.fe_logical = 0; + ac.ac_o_ex.fe_len = 1; + ac.ac_g_ex = ac.ac_o_ex; + ext4_mb_normalize_request_test(&ac, &ar); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_len, + EXT4_NUM_B2C(sbi, SZ_16K >> bsbits)); + } + + /* 4. 200KB file normalizes up to next power of two (256KB) */ + if ((SZ_256K >> bsbits) >= sbi->s_cluster_ratio) { + memset(&ac, 0, sizeof(ac)); + i_size_write(inode, 200 * 1024); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags = EXT4_MB_HINT_DATA; + ac.ac_o_ex.fe_logical = 0; + ac.ac_o_ex.fe_len = 1; + ac.ac_g_ex = ac.ac_o_ex; + ext4_mb_normalize_request_test(&ac, &ar); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_len, + EXT4_NUM_B2C(sbi, SZ_256K >> bsbits)); + } + + /* + * 5. Trimming against left/right allocated neighbors (ar.pleft / ar.pright) + * and against existing inode preallocations (ext4_mb_pa_adjust_overlap). + */ + if (((loff_t)EXT4_C2B(sbi, 16) << bsbits) <= SZ_1M) { + memset(&ac, 0, sizeof(ac)); + memset(&ar, 0, sizeof(ar)); + i_size_write(inode, (loff_t)EXT4_C2B(sbi, 16) << bsbits); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags = EXT4_MB_HINT_DATA; + ac.ac_o_ex.fe_logical = EXT4_C2B(sbi, 4); + ac.ac_o_ex.fe_len = 1; + ac.ac_g_ex = ac.ac_o_ex; + + /* Left neighbor ends at cluster 2 (logical block EXT4_C2B(sbi, 2) - 1) */ + ar.lleft = EXT4_C2B(sbi, 2) - 1; + ar.pleft = ext4_group_first_block_no(sb, TEST_GOAL_GROUP) + ar.lleft; + /* Right neighbor starts at cluster 10 */ + ar.lright = EXT4_C2B(sbi, 10); + ar.pright = ext4_group_first_block_no(sb, TEST_GOAL_GROUP) + ar.lright; + + /* + * Also insert a left PA covering clusters [2, 3) and a right PA covering + * clusters [8, 10) into ei->i_prealloc_node so ext4_mb_pa_adjust_overlap + * trims the range further to clusters [3, 8) (5 clusters). + */ + spin_lock_init(&left_pa.pa_lock); + left_pa.pa_lstart = EXT4_C2B(sbi, 2); + left_pa.pa_len = 1; + left_pa.pa_free = 1; + left_pa.pa_deleted = 0; + + spin_lock_init(&right_pa.pa_lock); + right_pa.pa_lstart = EXT4_C2B(sbi, 8); + right_pa.pa_len = 2; + right_pa.pa_free = 2; + right_pa.pa_deleted = 0; + + rb_link_node(&left_pa.pa_node.inode_node, NULL, + &ei->i_prealloc_node.rb_node); + rb_insert_color(&left_pa.pa_node.inode_node, &ei->i_prealloc_node); + rb_link_node(&right_pa.pa_node.inode_node, + &left_pa.pa_node.inode_node, + &left_pa.pa_node.inode_node.rb_right); + rb_insert_color(&right_pa.pa_node.inode_node, &ei->i_prealloc_node); + + ext4_mb_normalize_request_test(&ac, &ar); + ei->i_prealloc_node = RB_ROOT; + + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_logical, EXT4_C2B(sbi, 3)); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_len, 5); + } +} + +static void test_mb_inode_pa_lifecycle(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct inode *inode; + struct ext4_inode_info *ei; + struct ext4_allocation_request ar = {}; + struct ext4_group_info *grp; + ext4_group_t pa_grp; + ext4_grpblk_t pa_off, free_before; + ext4_fsblk_t blk1, blk2; + void *pa_bitmap; + int err = 0; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + ei = EXT4_I(inode); + /* Large file size (> s_mb_stream_request) so inode PA is used */ + i_size_write(inode, (loff_t)(sbi->s_mb_stream_request + 64) << sb->s_blocksize_bits); + + ar.inode = inode; + ar.logical = 0; + ar.len = 1; + ar.goal = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + ar.flags = EXT4_MB_HINT_DATA; + + blk1 = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_NE(test, blk1, 0ULL); + KUNIT_EXPECT_EQ(test, ar.len, 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ei->i_prealloc_active), 1); + KUNIT_EXPECT_FALSE(test, RB_EMPTY_ROOT(&ei->i_prealloc_node)); + + ext4_get_group_no_and_offset(sb, blk1, &pa_grp, &pa_off); + grp = ext4_get_group_info(sb, pa_grp); + free_before = ext4_free_group_clusters(sb, &MBT_GRP_CTX(sb, pa_grp)->desc) + 1; + + /* Verify ext4_mb_generate_from_pa marks the PA's clusters in a bitmap */ + pa_bitmap = kunit_kzalloc(test, sb->s_blocksize, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pa_bitmap); + ext4_lock_group(sb, pa_grp); + ext4_mb_generate_from_pa_test(sb, pa_bitmap, pa_grp); + ext4_unlock_group(sb, pa_grp); + KUNIT_EXPECT_NE(test, mb_test_bit_test(pa_off, pa_bitmap), 0); + + /* Second sequential allocation is served directly from the inode PA */ + ar.logical = EXT4_C2B(sbi, 1); + ar.len = 1; + ar.goal = blk1 + EXT4_C2B(sbi, 1); + blk2 = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, blk2, blk1 + EXT4_C2B(sbi, 1)); + + /* Discard inode preallocations and verify cleanup */ + ext4_discard_preallocations(inode); + KUNIT_EXPECT_EQ(test, atomic_read(&ei->i_prealloc_active), 0); + KUNIT_EXPECT_TRUE(test, RB_EMPTY_ROOT(&ei->i_prealloc_node)); + /* Only the 2 allocated clusters should remain used in the group */ + KUNIT_EXPECT_EQ(test, grp->bb_free, free_before - 2); +} + +struct mbt_saved_affinity { + cpumask_var_t mask; +}; + +static void mbt_restore_cpu_affinity(void *data) +{ + struct mbt_saved_affinity *saved = data; + + set_cpus_allowed_ptr(current, saved->mask); + free_cpumask_var(saved->mask); + kfree(saved); +} + +static void mbt_pin_current_cpu(struct kunit *test) +{ + struct mbt_saved_affinity *saved; + int err; + + saved = kzalloc_obj(*saved); + KUNIT_ASSERT_NOT_NULL(test, saved); + if (!alloc_cpumask_var(&saved->mask, GFP_KERNEL)) { + kfree(saved); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc cpumask"); + } + cpumask_copy(saved->mask, current->cpus_ptr); + + err = set_cpus_allowed_ptr(current, + cpumask_of(raw_smp_processor_id())); + if (err) { + free_cpumask_var(saved->mask); + kfree(saved); + KUNIT_ASSERT_EQ(test, err, 0); + } + + err = kunit_add_action_or_reset(test, mbt_restore_cpu_affinity, saved); + KUNIT_ASSERT_EQ(test, err, 0); +} + +static void test_mb_group_pa_lifecycle(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct inode *inode1, *inode2; + struct ext4_allocation_request ar = {}; + struct ext4_group_info *grp; + ext4_fsblk_t blk1, blk2; + int err = 0, discarded; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + /* Pin to one CPU so both allocations hit the same locality group PA */ + mbt_pin_current_cpu(test); + + inode1 = mbt_alloc_test_inode(test, sb, S_IFREG); + inode2 = mbt_alloc_test_inode(test, sb, S_IFREG); + inode2->i_ino = 13; + + /* Small files (<= s_mb_stream_request) use locality group PA (MB_GROUP_PA) */ + i_size_write(inode1, sb->s_blocksize); + i_size_write(inode2, sb->s_blocksize); + + ar.inode = inode1; + ar.logical = 0; + ar.len = 1; + ar.goal = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + ar.flags = EXT4_MB_HINT_DATA; + + blk1 = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, blk1, ext4_group_first_block_no(sb, TEST_GOAL_GROUP)); + + /* Second small file allocation reuses the locality group PA */ + ar.inode = inode2; + ar.logical = 0; + ar.len = 1; + ar.goal = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + blk2 = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, blk2, blk1 + EXT4_C2B(sbi, 1)); + + /* Discard all group preallocations and verify free count is restored */ + discarded = ext4_mb_discard_preallocations_test(sb, 0); + rcu_barrier(); + KUNIT_EXPECT_EQ(test, discarded, (int)sbi->s_mb_group_prealloc - 2); + + grp = ext4_get_group_info(sb, TEST_GOAL_GROUP); + KUNIT_EXPECT_EQ(test, grp->bb_free, EXT4_CLUSTERS_PER_GROUP(sb) - 2); +} + +static void test_mb_lg_list_trim(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_locality_group *lg; + struct inode *inode; + struct ext4_buddy e4b; + struct ext4_prealloc_space *pa; + int i, ret, count = 0; + int order = fls(15) - 1; /* pa_free = 15 -> order 3 */ + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + sbi->s_mb_group_prealloc = 16; + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * Create 9 locality-group PAs in bucket order 3 (each of length 16 with + * 1 cluster used -> pa_free = 15). When the 9th PA is added via + * ext4_mb_release_context -> ext4_mb_add_n_trim, lg_prealloc_count > 8 + * triggers ext4_mb_discard_lg_preallocations() to trim the list to 5! + * Capture one locality group pointer up front so CPU migration across + * iterations cannot split PAs across different per-CPU locality groups. + */ + lg = raw_cpu_ptr(sbi->s_locality_groups); + for (i = 0; i < 9; i++) { + struct ext4_allocation_context ac = {}; + struct ext4_free_extent ex = { + .fe_group = TEST_GOAL_GROUP, + .fe_start = i * 32, + .fe_len = 16, + }; + + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags = EXT4_MB_HINT_DATA | EXT4_MB_HINT_GROUP_ALLOC; + ac.ac_lg = lg; + mutex_lock(&ac.ac_lg->lg_mutex); + + ret = ext4_mb_pa_alloc_test(&ac); + if (ret) { + mutex_unlock(&ac.ac_lg->lg_mutex); + ext4_mb_unload_buddy_test(&e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + } + + ext4_lock_group(sb, TEST_GOAL_GROUP); + mb_mark_used_test(&e4b, &ex); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + ac.ac_status = AC_STATUS_FOUND; + ac.ac_o_ex.fe_len = 1; + ac.ac_b_ex = ex; + ac.ac_f_ex = ex; + ext4_mb_new_preallocation_test(&ac); + /* Release context updates pa_free to 15 and runs ext4_mb_add_n_trim */ + ext4_mb_release_context_test(&ac); + } + + ext4_mb_unload_buddy_test(&e4b); + + spin_lock(&lg->lg_prealloc_lock); + list_for_each_entry(pa, &lg->lg_prealloc_list[order], pa_node.lg_list) + count++; + spin_unlock(&lg->lg_prealloc_lock); + + KUNIT_EXPECT_EQ(test, count, 5); +} + +static void test_mb_new_blocks_and_enospc_retry(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct inode *inode1, *inode2; + struct ext4_allocation_request ar = {}; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + ext4_fsblk_t blk; + int err = 0; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode1 = mbt_alloc_test_inode(test, sb, S_IFREG); + inode2 = mbt_alloc_test_inode(test, sb, S_IFREG); + inode2->i_ino = 14; + i_size_write(inode1, sb->s_blocksize); + + /* + * Leave only 16 free clusters in group 1 and mark groups 0, 2, 3 full. + * Set s_mb_group_prealloc = 16 so allocating 1 cluster for inode1 + * preallocates the remaining 15 clusters into a group PA (leaving + * 0 free clusters in buddy for all groups). + */ + mbt_ctx_mark_used(sb, 0, 0, max); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 0)->desc, 0); + ext4_get_group_info(sb, 0)->bb_free = 0; + + mbt_ctx_mark_used(sb, 1, 16, max - 16); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 1)->desc, 16); + ext4_get_group_info(sb, 1)->bb_free = 16; + + mbt_ctx_mark_used(sb, 2, 0, max); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 2)->desc, 0); + ext4_get_group_info(sb, 2)->bb_free = 0; + + mbt_ctx_mark_used(sb, 3, 0, max); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 3)->desc, 0); + ext4_get_group_info(sb, 3)->bb_free = 0; + + percpu_counter_set(&sbi->s_freeclusters_counter, 16); + sbi->s_mb_group_prealloc = 16; + + ar.inode = inode1; + ar.logical = 0; + ar.len = 1; + ar.goal = ext4_group_first_block_no(sb, 1); + ar.flags = EXT4_MB_HINT_DATA; + + blk = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ext4_get_group_info(sb, 1)->bb_free, 0); + + /* + * Now request 4 metadata clusters (no EXT4_MB_HINT_DATA so it cannot + * use the PA directly). First allocator pass finds 0 free clusters, + * then ext4_mb_discard_preallocations_should_retry() discards the PA + * (recovering 15 clusters) and retries, succeeding! + */ + memset(&ar, 0, sizeof(ar)); + ar.inode = inode2; + ar.len = 4; + ar.goal = ext4_group_first_block_no(sb, 1); + ar.flags = 0; + + blk = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_NE(test, blk, 0ULL); + KUNIT_EXPECT_EQ(test, ar.len, 4); + + /* + * The 4-cluster power-of-2 allocation claimed [4, 8), leaving two + * fragments [1, 4) (3 clusters) and [8, 16) (8 clusters). + * Requesting 11 clusters allocates the largest fragment (8 clusters), + * then requesting 3 clusters allocates [1, 4), and the next request + * returns -ENOSPC. + */ + ar.len = 11; + blk = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ar.len, 8); + + ar.len = 3; + blk = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ar.len, 3); + + ar.len = 1; + blk = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_EXPECT_EQ(test, err, -ENOSPC); + KUNIT_EXPECT_EQ(test, blk, 0ULL); +} + +static int +ext4_handle_dirty_metadata_Updated_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + return 0; +} + +static void test_mb_mark_context_and_mark_bb(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_group_desc *gdp1, *gdp2; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + ext4_grpblk_t changed = 0; + ext4_fsblk_t boundary_blk; + __u32 free_before; + int ret; + + /* Test the real ext4_mb_mark_context implementation */ + kunit_deactivate_static_stub(test, ext4_mb_mark_context); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + ext4_handle_dirty_metadata_Updated_stub); + + gdp1 = ext4_get_group_desc(sb, 1, NULL); + gdp2 = ext4_get_group_desc(sb, 2, NULL); + KUNIT_ASSERT_NOT_NULL(test, gdp1); + KUNIT_ASSERT_NOT_NULL(test, gdp2); + free_before = ext4_free_group_clusters(sb, gdp1); + + /* 1. Mark [10, 20) used with EXT4_MB_BITMAP_MARKED_CHECK (0x1) */ + ret = ext4_mb_mark_context(NULL, sb, true, 1, 10, 10, 0x0001, &changed); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, changed, 10); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, gdp1), free_before - 10); + + /* 2. Mark overlapping [15, 25) used -> only 5 new clusters changed */ + ret = ext4_mb_mark_context(NULL, sb, true, 1, 15, 10, 0x0001, &changed); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, changed, 5); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, gdp1), free_before - 15); + + /* 3. Clear [10, 25) -> 15 clusters freed */ + ret = ext4_mb_mark_context(NULL, sb, false, 1, 10, 15, 0x0001, &changed); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, changed, 15); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, gdp1), free_before); + + /* + * 4. Test ext4_mb_mark_bb across the boundary between group 1 and group 2: + * 2 clusters at the end of group 1 + 3 clusters at the start of group 2. + */ + kunit_activate_static_stub(test, ext4_mb_mark_context, + ext4_mb_mark_context_stub); + boundary_blk = ext4_group_first_block_no(sb, 2) - EXT4_C2B(sbi, 2); + ext4_mb_mark_bb(sb, boundary_blk, EXT4_C2B(sbi, 5), true); + + KUNIT_EXPECT_NE(test, mb_test_bit_test(max - 2, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(max - 1, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(0, mbt_ctx_bitmap(sb, 2)), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(2, mbt_ctx_bitmap(sb, 2)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(3, mbt_ctx_bitmap(sb, 2)), 0); + + ext4_mb_mark_bb(sb, boundary_blk, EXT4_C2B(sbi, 5), false); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(max - 2, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(0, mbt_ctx_bitmap(sb, 2)), 0); +} + +static void test_ext4_free_blocks_flags_and_cross_group(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct inode *inode; + struct ext4_buddy e4b; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + ext4_fsblk_t grp1_first = ext4_group_first_block_no(sb, 1); + ext4_fsblk_t grp2_first = ext4_group_first_block_no(sb, 2); + s64 free_before; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* Mark clusters [10, 20) and [max - 2, max) in group 1, and [0, 3) in group 2 used */ + mbt_ctx_mark_used(sb, 1, 10, 10); + mbt_ctx_mark_used(sb, 1, max - 2, 2); + mbt_ctx_mark_used(sb, 2, 0, 3); + ext4_get_group_info(sb, 1)->bb_free -= 12; + ext4_get_group_info(sb, 2)->bb_free -= 3; + + ret = ext4_mb_load_buddy_test(sb, 1, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + ret = ext4_mb_load_buddy_test(sb, 2, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + + /* + * 1. EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER | EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER: + * Freeing from cluster 10 + 2 blocks through cluster 12 + 3 blocks + * skips partial clusters 10 and 12 and frees only full cluster 11! + */ + ext4_free_blocks(NULL, inode, NULL, + grp1_first + EXT4_C2B(sbi, 10) + 2, + EXT4_C2B(sbi, 2) - 2 + 3, + EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER | + EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER | + EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + + KUNIT_EXPECT_NE(test, mb_test_bit_test(10, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(11, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(12, mbt_ctx_bitmap(sb, 1)), 0); + + /* + * 2. EXT4_FREE_BLOCKS_RERESERVE_CLUSTER: frees cluster 12 in bitmap & buddy + * without incrementing s_freeclusters_counter. + */ + free_before = percpu_counter_sum(&sbi->s_freeclusters_counter); + ext4_free_blocks(NULL, inode, NULL, + grp1_first + EXT4_C2B(sbi, 12), + EXT4_C2B(sbi, 1), + EXT4_FREE_BLOCKS_RERESERVE_CLUSTER | + EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(12, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_freeclusters_counter), + free_before); + + /* + * 3. Cross-group boundary free: 2 clusters at end of group 1 + 3 clusters + * at start of group 2. + */ + ext4_free_blocks(NULL, inode, NULL, + grp2_first - EXT4_C2B(sbi, 2), + EXT4_C2B(sbi, 5), + EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(max - 2, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(max - 1, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(0, mbt_ctx_bitmap(sb, 2)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(2, mbt_ctx_bitmap(sb, 2)), 0); +} + +static void test_mb_free_metadata_and_process_freed_data(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct inode *inode; + struct ext4_buddy e4b; + struct ext4_group_info *grp; + struct ext4_free_data *entry; + transaction_t trans = { .t_tid = 42 }; + handle_t handle = { .h_transaction = &trans }; + ext4_fsblk_t grp1_first = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + ext4_grpblk_t merged_start = 0, merged_count = 0; + int node_count = 0, ret; + struct rb_node *n; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* Mark clusters [20, 28) used in group 1 and load buddy */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 20, 8); + grp = ext4_get_group_info(sb, TEST_GOAL_GROUP); + grp->bb_free -= 8; + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + + /* + * Free [20, 22), then [25, 28), then the middle [22, 25) as metadata + * with a valid journal handle (tid = 42). + * This exercises rbtree insertion and both prev and next extent merging! + */ + ext4_free_blocks(&handle, inode, NULL, + grp1_first + EXT4_C2B(sbi, 20), EXT4_C2B(sbi, 2), + EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + ext4_free_blocks(&handle, inode, NULL, + grp1_first + EXT4_C2B(sbi, 25), EXT4_C2B(sbi, 3), + EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + ext4_free_blocks(&handle, inode, NULL, + grp1_first + EXT4_C2B(sbi, 22), EXT4_C2B(sbi, 3), + EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + + KUNIT_EXPECT_EQ(test, atomic_read(&sbi->s_mb_free_pending), 8); + /* Blocks are not yet freed in buddy until transaction commit */ + KUNIT_EXPECT_EQ(test, grp->bb_free, EXT4_CLUSTERS_PER_GROUP(sb) - 8); + + ext4_lock_group(sb, TEST_GOAL_GROUP); + for (n = rb_first(&grp->bb_free_root); n; n = rb_next(n)) { + entry = rb_entry(n, struct ext4_free_data, efd_node); + merged_start = entry->efd_start_cluster; + merged_count = entry->efd_count; + node_count++; + } + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + /* All 3 freed extents for tid 42 must have merged into a single node [20, 28) */ + KUNIT_EXPECT_EQ(test, node_count, 1); + KUNIT_EXPECT_EQ(test, merged_start, 20); + KUNIT_EXPECT_EQ(test, merged_count, 8); + + /* Commit tid 42 -> ext4_process_freed_data releases [20, 28) into buddy */ + ext4_process_freed_data(sb, 42); + KUNIT_EXPECT_EQ(test, atomic_read(&sbi->s_mb_free_pending), 0); + KUNIT_EXPECT_TRUE(test, RB_EMPTY_ROOT(&grp->bb_free_root)); + KUNIT_EXPECT_EQ(test, grp->bb_free, EXT4_CLUSTERS_PER_GROUP(sb)); +} + +static void test_ext4_group_add_blocks(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_group_info *grp; + ext4_fsblk_t grp1_first = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + s64 free_before; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + /* Mark [50, 60) used in group 1 and initialize buddy */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 50, 10); + grp = ext4_get_group_info(sb, TEST_GOAL_GROUP); + grp->bb_free -= 10; + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + + free_before = percpu_counter_sum(&sbi->s_freeclusters_counter); + ret = ext4_group_add_blocks(NULL, sb, + grp1_first + EXT4_C2B(sbi, 50), + EXT4_C2B(sbi, 10)); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp->bb_free, EXT4_CLUSTERS_PER_GROUP(sb)); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_freeclusters_counter), + free_before + 10); + + /* Cross-group boundary addition must fail with -EINVAL */ + ret = ext4_group_add_blocks(NULL, sb, + grp1_first + EXT4_C2B(sbi, EXT4_CLUSTERS_PER_GROUP(sb) - 2), + EXT4_C2B(sbi, 5)); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + /* System zone block (block 0) must fail with -EINVAL */ + ret = ext4_group_add_blocks(NULL, sb, 0, EXT4_C2B(sbi, 1)); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); +} + +static int mbt_discard_calls; +static int mbt_discard_clusters; + +static int +ext4_issue_discard_count_stub(struct super_block *sb, ext4_group_t block_group, + ext4_grpblk_t cluster, int count) +{ + mbt_discard_calls++; + mbt_discard_clusters += count; + return 0; +} + +static void test_ext4_trim_fs(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct fstrim_range range = {}; + struct ext4_group_info *grp1; + struct inode *inode; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + kunit_activate_static_stub(test, ext4_issue_discard, + ext4_issue_discard_count_stub); + + /* + * Mark groups 0, 2, 3 completely used. + * In group 1, leave only [10, 14) (4 clusters) and [30, 50) (20 clusters) free. + */ + mbt_ctx_mark_used(sb, 0, 0, max); + ext4_get_group_info(sb, 0)->bb_free = 0; + mbt_ctx_mark_used(sb, 2, 0, max); + ext4_get_group_info(sb, 2)->bb_free = 0; + mbt_ctx_mark_used(sb, 3, 0, max); + ext4_get_group_info(sb, 3)->bb_free = 0; + + mbt_ctx_mark_used(sb, 1, 0, 10); + mbt_ctx_mark_used(sb, 1, 14, 16); + mbt_ctx_mark_used(sb, 1, 50, max - 50); + grp1 = ext4_get_group_info(sb, 1); + grp1->bb_free = 24; + + /* Invalid range checks */ + range.start = 0; + range.len = sb->s_blocksize - 1; + range.minlen = 0; + KUNIT_EXPECT_EQ(test, ext4_trim_fs(sb, &range), -EINVAL); + + /* Trim with minlen = 10 clusters: skips [10, 14) and trims only [30, 50) (20 clusters) */ + mbt_discard_calls = 0; + mbt_discard_clusters = 0; + range.start = 0; + range.len = (u64)ext4_blocks_count(sbi->s_es) << sb->s_blocksize_bits; + range.minlen = (u64)EXT4_C2B(sbi, 10) << sb->s_blocksize_bits; + + ret = ext4_trim_fs(sb, &range); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, mbt_discard_calls, 1); + KUNIT_EXPECT_EQ(test, mbt_discard_clusters, 20); + KUNIT_EXPECT_EQ(test, range.len, + (u64)EXT4_C2B(sbi, 20) << sb->s_blocksize_bits); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_WAS_TRIMMED(grp1)); + + /* Second trim with same minlen is skipped because WAS_TRIMMED is set */ + range.len = (u64)ext4_blocks_count(sbi->s_es) << sb->s_blocksize_bits; + ret = ext4_trim_fs(sb, &range); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, mbt_discard_calls, 1); + KUNIT_EXPECT_EQ(test, range.len, 0ULL); + + /* Freeing a block clears WAS_TRIMMED, allowing subsequent trim */ + ext4_free_blocks(NULL, inode, NULL, + ext4_group_first_block_no(sb, 1) + EXT4_C2B(sbi, 50), + EXT4_C2B(sbi, 1), EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_WAS_TRIMMED(grp1)); +} + +struct mbt_query_ctx { + int meta_calls; + ext4_grpblk_t meta_start; + ext4_grpblk_t meta_len; + int free_calls; + ext4_grpblk_t free_starts[4]; + ext4_grpblk_t free_lens[4]; + int stop_after; +}; + +static int mbt_query_meta_cb(struct super_block *sb, ext4_group_t agno, + ext4_grpblk_t start, ext4_grpblk_t len, void *priv) +{ + struct mbt_query_ctx *q = priv; + + q->meta_calls++; + q->meta_start = start; + q->meta_len = len; + return 0; +} + +static int mbt_query_free_cb(struct super_block *sb, ext4_group_t agno, + ext4_grpblk_t start, ext4_grpblk_t len, void *priv) +{ + struct mbt_query_ctx *q = priv; + + if (q->free_calls < 4) { + q->free_starts[q->free_calls] = start; + q->free_lens[q->free_calls] = len; + } + q->free_calls++; + if (q->stop_after && q->free_calls >= q->stop_after) + return -ECANCELED; + return 0; +} + +static void test_ext4_mballoc_query_range(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct mbt_query_ctx q = {}; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + /* + * In group 1: + * [0, 10) used (before bb_first_free = 10 -> reported to meta_formatter) + * [10, 15) free (len 5) + * [15, 25) used + * [25, 32) free (len 7) + * [32, max) used + */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 0, 10); + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 15, 10); + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 32, max - 32); + ext4_get_group_info(sb, TEST_GOAL_GROUP)->bb_free = 12; + + ret = ext4_mballoc_query_range(sb, TEST_GOAL_GROUP, 0, 100, + mbt_query_meta_cb, mbt_query_free_cb, &q); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, q.meta_calls, 1); + KUNIT_EXPECT_EQ(test, q.meta_start, 0); + KUNIT_EXPECT_EQ(test, q.meta_len, 10); + KUNIT_EXPECT_EQ(test, q.free_calls, 2); + KUNIT_EXPECT_EQ(test, q.free_starts[0], 10); + KUNIT_EXPECT_EQ(test, q.free_lens[0], 5); + KUNIT_EXPECT_EQ(test, q.free_starts[1], 25); + KUNIT_EXPECT_EQ(test, q.free_lens[1], 7); + + /* Early abort from formatter callback propagates error code */ + memset(&q, 0, sizeof(q)); + q.stop_after = 1; + ret = ext4_mballoc_query_range(sb, TEST_GOAL_GROUP, 0, 100, + NULL, mbt_query_free_cb, &q); + KUNIT_EXPECT_EQ(test, ret, -ECANCELED); + KUNIT_EXPECT_EQ(test, q.free_calls, 1); +} + static const struct mbt_ext4_block_layout mbt_test_layouts[] = { { .blocksize_bits = 10, @@ -991,6 +2863,31 @@ static struct kunit_case mbt_test_cases[] = { KUNIT_CASE_PARAM(test_mb_mark_used, mbt_layouts_gen_params), KUNIT_CASE_PARAM(test_mb_free_blocks, mbt_layouts_gen_params), KUNIT_CASE_PARAM(test_mark_diskspace_used, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_bit_ops, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_test_and_clear_bits, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_find_buddy_and_order, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_find_extent, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_generate_buddy_corrupt, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_free_blocks_double_free_and_fc_replay, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_xarray_orders_and_frag_size, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_good_group, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_find_by_goal, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_simple_and_aligned_scan, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_complex_scan_and_measure, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_regular_allocator, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_prefetch, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_initialize_context, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_normalize_request, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_inode_pa_lifecycle, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_group_pa_lifecycle, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_lg_list_trim, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_new_blocks_and_enospc_retry, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_mark_context_and_mark_bb, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_ext4_free_blocks_flags_and_cross_group, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_free_metadata_and_process_freed_data, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_ext4_group_add_blocks, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_ext4_trim_fs, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_ext4_mballoc_query_range, mbt_layouts_gen_params), KUNIT_CASE_PARAM_ATTR(test_mb_mark_used_cost, mbt_layouts_gen_params, { .speed = KUNIT_SPEED_SLOW }), {} diff --git a/fs/ext4/mballoc.c b/fs/ext4/mballoc.c index a0f3058da90c41..2ecf5aa77e68db 100644 --- a/fs/ext4/mballoc.c +++ b/fs/ext4/mballoc.c @@ -3957,11 +3957,14 @@ void ext4_mb_release(struct super_block *sb) kfree(sbi->s_mb_last_groups); } -static inline int ext4_issue_discard(struct super_block *sb, +int ext4_issue_discard(struct super_block *sb, ext4_group_t block_group, ext4_grpblk_t cluster, int count) { ext4_fsblk_t discard_block; + KUNIT_STATIC_STUB_REDIRECT(ext4_issue_discard, sb, block_group, + cluster, count); + discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) + ext4_group_first_block_no(sb, block_group)); count = EXT4_C2B(EXT4_SB(sb), count); @@ -7275,12 +7278,164 @@ void ext4_free_blocks_simple_test(struct inode *inode, ext4_fsblk_t block, } EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_blocks_simple_test); +void mb_set_bit_test(int bit, void *addr) +{ + mb_set_bit(bit, addr); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_set_bit_test); + +int mb_test_and_clear_bits_test(void *bm, int cur, int len) +{ + return mb_test_and_clear_bits(bm, cur, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_test_and_clear_bits_test); + +void *mb_find_buddy_test(struct ext4_buddy *e4b, int order, int *max) +{ + return mb_find_buddy(e4b, order, max); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_find_buddy_test); + +int mb_find_order_for_block_test(struct ext4_buddy *e4b, int block) +{ + return mb_find_order_for_block(e4b, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_find_order_for_block_test); + +int mb_find_extent_test(struct ext4_buddy *e4b, int block, int needed, + struct ext4_free_extent *ex) +{ + return mb_find_extent(e4b, block, needed, ex); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_find_extent_test); + +int mb_avg_fragment_size_order_test(struct super_block *sb, ext4_grpblk_t len) +{ + return mb_avg_fragment_size_order(sb, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_avg_fragment_size_order_test); + +void mb_update_avg_fragment_size_test(struct super_block *sb, + struct ext4_group_info *grp) +{ + mb_update_avg_fragment_size(sb, grp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_update_avg_fragment_size_test); + +void mb_set_largest_free_order_test(struct super_block *sb, + struct ext4_group_info *grp) +{ + mb_set_largest_free_order(sb, grp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_set_largest_free_order_test); + +bool ext4_mb_good_group_test(struct ext4_allocation_context *ac, + ext4_group_t group, enum criteria cr) +{ + return ext4_mb_good_group(ac, group, cr); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_good_group_test); + +int ext4_mb_good_group_nolock_test(struct ext4_allocation_context *ac, + ext4_group_t group, enum criteria cr) +{ + return ext4_mb_good_group_nolock(ac, group, cr); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_good_group_nolock_test); + +int ext4_mb_find_by_goal_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b) +{ + return ext4_mb_find_by_goal(ac, e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_find_by_goal_test); + +void ext4_mb_simple_scan_group_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b) +{ + ext4_mb_simple_scan_group(ac, e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_simple_scan_group_test); + +void ext4_mb_scan_aligned_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b) +{ + ext4_mb_scan_aligned(ac, e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_scan_aligned_test); + +void ext4_mb_complex_scan_group_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b) +{ + ext4_mb_complex_scan_group(ac, e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_complex_scan_group_test); + +void ext4_mb_try_best_found_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b) +{ + ext4_mb_try_best_found(ac, e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_try_best_found_test); + +int ext4_mb_regular_allocator_test(struct ext4_allocation_context *ac) +{ + return ext4_mb_regular_allocator(ac); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_regular_allocator_test); + +void ext4_mb_initialize_context_test(struct ext4_allocation_context *ac, + struct ext4_allocation_request *ar) +{ + ext4_mb_initialize_context(ac, ar); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_initialize_context_test); + +void ext4_mb_normalize_request_test(struct ext4_allocation_context *ac, + struct ext4_allocation_request *ar) +{ + ext4_mb_normalize_request(ac, ar); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_normalize_request_test); + +void ext4_mb_new_preallocation_test(struct ext4_allocation_context *ac) +{ + ext4_mb_new_preallocation(ac); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_new_preallocation_test); + +void ext4_mb_release_context_test(struct ext4_allocation_context *ac) +{ + ext4_mb_release_context(ac); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_release_context_test); + +int ext4_mb_pa_alloc_test(struct ext4_allocation_context *ac) +{ + return ext4_mb_pa_alloc(ac); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_pa_alloc_test); + +void ext4_mb_generate_from_pa_test(struct super_block *sb, void *bitmap, + ext4_group_t group) +{ + ext4_mb_generate_from_pa(sb, bitmap, group); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_generate_from_pa_test); + +int ext4_mb_discard_preallocations_test(struct super_block *sb, int needed) +{ + return ext4_mb_discard_preallocations(sb, needed); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_discard_preallocations_test); + EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_wait_block_bitmap); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_init); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_group_desc); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_count_free_clusters); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_group_info); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_group_clusters_set); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_group_no_and_offset); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_group_number); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_release); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_block_bitmap_nowait); EXPORT_SYMBOL_FOR_EXT4_TEST(mb_set_bits); @@ -7288,4 +7443,13 @@ EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_init_inode); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_mark_context); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_new_blocks); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_prefetch); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_prefetch_fini); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_discard_preallocations); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_mark_bb); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_process_freed_data); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_group_add_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_trim_fs); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mballoc_query_range); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_issue_discard); #endif diff --git a/fs/ext4/mballoc.h b/fs/ext4/mballoc.h index 571d9bd9381070..f332a23d66f866 100644 --- a/fs/ext4/mballoc.h +++ b/fs/ext4/mballoc.h @@ -275,6 +275,8 @@ extern int ext4_mb_mark_context(handle_t *handle, ext4_group_t group, ext4_grpblk_t blkoff, ext4_grpblk_t len, int flags, ext4_grpblk_t *ret_changed); +extern int ext4_issue_discard(struct super_block *sb, + ext4_group_t block_group, ext4_grpblk_t cluster, int count); #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) extern void mb_clear_bits_test(void *bm, int cur, int len); extern ext4_fsblk_t @@ -283,7 +285,45 @@ ext4_mb_new_blocks_simple_test(struct ext4_allocation_request *ar, extern int mb_find_next_zero_bit_test(void *addr, int max, int start); extern int mb_find_next_bit_test(void *addr, int max, int start); extern void mb_clear_bit_test(int bit, void *addr); +extern void mb_set_bit_test(int bit, void *addr); extern int mb_test_bit_test(int bit, void *addr); +extern int mb_test_and_clear_bits_test(void *bm, int cur, int len); +extern void *mb_find_buddy_test(struct ext4_buddy *e4b, int order, int *max); +extern int mb_find_order_for_block_test(struct ext4_buddy *e4b, int block); +extern int mb_find_extent_test(struct ext4_buddy *e4b, int block, int needed, + struct ext4_free_extent *ex); +extern int mb_avg_fragment_size_order_test(struct super_block *sb, + ext4_grpblk_t len); +extern void mb_update_avg_fragment_size_test(struct super_block *sb, + struct ext4_group_info *grp); +extern void mb_set_largest_free_order_test(struct super_block *sb, + struct ext4_group_info *grp); +extern bool ext4_mb_good_group_test(struct ext4_allocation_context *ac, + ext4_group_t group, enum criteria cr); +extern int ext4_mb_good_group_nolock_test(struct ext4_allocation_context *ac, + ext4_group_t group, enum criteria cr); +extern int ext4_mb_find_by_goal_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b); +extern void ext4_mb_simple_scan_group_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b); +extern void ext4_mb_scan_aligned_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b); +extern void ext4_mb_complex_scan_group_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b); +extern void ext4_mb_try_best_found_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b); +extern int ext4_mb_regular_allocator_test(struct ext4_allocation_context *ac); +extern void ext4_mb_initialize_context_test(struct ext4_allocation_context *ac, + struct ext4_allocation_request *ar); +extern void ext4_mb_normalize_request_test(struct ext4_allocation_context *ac, + struct ext4_allocation_request *ar); +extern void ext4_mb_new_preallocation_test(struct ext4_allocation_context *ac); +extern void ext4_mb_release_context_test(struct ext4_allocation_context *ac); +extern int ext4_mb_pa_alloc_test(struct ext4_allocation_context *ac); +extern void ext4_mb_generate_from_pa_test(struct super_block *sb, void *bitmap, + ext4_group_t group); +extern int ext4_mb_discard_preallocations_test(struct super_block *sb, + int needed); extern int ext4_mb_mark_diskspace_used_test(struct ext4_allocation_context *ac, handle_t *handle); diff --git a/fs/ext4/super.c b/fs/ext4/super.c index 4542a1b8ca0fff..517ab0de184138 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -372,6 +372,7 @@ __u32 ext4_free_group_clusters(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_group_clusters); __u32 ext4_free_inodes_count(struct super_block *sb, struct ext4_group_desc *bg) @@ -428,6 +429,7 @@ void ext4_free_group_clusters_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_group_clusters_set); void ext4_free_inodes_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) From 0a72862ce7c5a7dfe565cf348ccc76bed8005d54 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Thu, 5 Nov 2026 03:19:54 +0000 Subject: [PATCH 1558/2102] ext4: add KUnit tests for fs/ext4/inline.c Add the ext4_inline_test KUnit test suite in fs/ext4/inline-test.c to comprehensively exercise inline data operations for regular files, symlinks, and directories in fs/ext4/inline.c without requiring a mounted block device: - Inline capacity and discovery (ext4_get_max_inline_size and ext4_find_inline_data_nolock) across fresh inodes, inodes with zero extra_isize or 128-byte inode size, inodes with coexisting user xattrs in ibody, 0-byte and non-empty system.data xattrs, and corrupted xattr entries (e_name_len overflow and non-zero e_value_inum). - Inline file creation, expansion, overwrite, and destruction (ext4_try_to_write_inline_data, ext4_write_inline_data_end, and ext4_destroy_inline_data) spanning i_block (< 60 bytes) and the ibody system.data xattr (>= 60 bytes), short writes with failed-write truncation, non-uptodate folios, emergency shutdown (EXT4_FLAGS_SHUTDOWN), concurrent inline flag clearing, and corrupted inline xattr state detection. - Inline page reading, symlinks, and iomap mapping (ext4_readpage_inline on index 0 and index > 0, i_inline_size > PAGE_SIZE corruption detection, ext4_read_inline_link for short and long symlinks, and ext4_inline_data_iomap). - Inline file truncation (ext4_inline_data_truncate) across size extensions, shrinking within system.data xattr, shrinking into i_block with tail zeroing, truncating to zero, and clearing the extent status tree when EXT4_STATE_MAY_INLINE_DATA is unset. - Inline-to-extent conversion for regular files (ext4_convert_inline_data, ext4_convert_inline_data_to_extent, and ext4_da_convert_inline_data_to_extent via ext4_generic_write_inline_data), including DIOREAD_NOLOCK, DELALLOC, and journaled data modes, plus error rollback via ext4_restore_inline_data when block allocation, buffer lookup, or metadata dirtying fails. - Inline directory operations (ext4_update_final_de, ext4_try_create_inline_dir, ext4_get_first_inline_block, ext4_try_add_inline_entry across i_block and system.data xattr, duplicate -EEXIST handling, ext4_find_inline_entry, ext4_read_inline_dir with cookie/iversion revalidation, ext4_inlinedir_to_tree, ext4_delete_inline_entry, empty_inline_dir, conversion of full inline directories to extent-mapped directory blocks with rollback on allocation failure, and corrupted dirent detection). Export the tested functions with EXPORT_SYMBOL_FOR_EXT4_TEST and add KUNIT_STATIC_STUB_REDIRECT hooks for ext4_inline_getblk, ext4_da_get_block_prep, and ext4_inode_journal_mode. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 2 + fs/ext4/ext4_jbd2.c | 5 + fs/ext4/inline-test.c | 1852 +++++++++++++++++++++++++++++++++++++++++ fs/ext4/inline.c | 30 +- fs/ext4/inode.c | 4 + 6 files changed, 1893 insertions(+), 2 deletions(-) create mode 100644 fs/ext4/inline-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 8fe7b512ebb426..5a90bf5b28e3b0 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -17,7 +17,7 @@ ext4-$(CONFIG_EXT4_FS_SECURITY) += xattr_security.o ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ extents_status-test.o xattr-test.o \ - namei-test.o + namei-test.o inline-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index 30d6f7b99f07b3..ae5edd8e8d4d64 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -3831,6 +3831,8 @@ extern const struct file_operations ext4_file_operations; extern loff_t ext4_llseek(struct file *file, loff_t offset, int origin); /* inline.c */ +extern struct buffer_head *ext4_inline_getblk(struct super_block *sb, + ext4_fsblk_t block); extern int ext4_get_max_inline_size(struct inode *inode); extern int ext4_find_inline_data_nolock(struct inode *inode); extern int ext4_destroy_inline_data(handle_t *handle, struct inode *inode); diff --git a/fs/ext4/ext4_jbd2.c b/fs/ext4/ext4_jbd2.c index 7d4f36baf25064..b6d84057009c51 100644 --- a/fs/ext4/ext4_jbd2.c +++ b/fs/ext4/ext4_jbd2.c @@ -10,6 +10,8 @@ int ext4_inode_journal_mode(struct inode *inode) { + KUNIT_STATIC_STUB_REDIRECT(ext4_inode_journal_mode, inode); + if (EXT4_JOURNAL(inode) == NULL) return EXT4_INODE_WRITEBACK_DATA_MODE; /* writeback */ /* We do not support data journalling with delayed allocation */ @@ -127,6 +129,7 @@ handle_t *__ext4_journal_start_sb(struct inode *inode, return jbd2__journal_start(journal, blocks, rsv_blocks, revoke_creds, GFP_NOFS, type, line); } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_journal_start_sb); int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle) { @@ -154,6 +157,7 @@ int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle) __ext4_std_error(sb, where, line, err); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_journal_stop); handle_t *__ext4_journal_start_reserved(handle_t *handle, unsigned int line, int type) @@ -441,5 +445,6 @@ int __ext4_handle_dirty_metadata(const char *where, unsigned int line, } #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_journal_mode); EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_handle_dirty_metadata); #endif diff --git a/fs/ext4/inline-test.c b/fs/ext4/inline-test.c new file mode 100644 index 00000000000000..efc068c1f823db --- /dev/null +++ b/fs/ext4/inline-test.c @@ -0,0 +1,1852 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 inline data operations (fs/ext4/inline.c) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" +#include "truncate.h" +#include "namei.h" + +#define TEST_INODE_SIZE 256 +#define TEST_EXTRA_ISIZE 32 +#define TEST_BLOCK_SIZE 1024 +#define TEST_BLOCK_BITS 10 +#define EXT4_MIN_INLINE_DATA_SIZE ((sizeof(__le32) * EXT4_N_BLOCKS)) +#define EXT4_INLINE_DOTDOT_SIZE 4 +/* + * For a 256-byte inode with 32-byte i_extra_isize: + * EXT4_GOOD_OLD_INODE_SIZE (128) + 32 = 160 bytes fixed fields + * Remaining ibody space = 96 bytes + * 4-byte xattr magic + 20-byte system.data entry + 4-byte gap = 28 bytes + * Available xattr value space = 68 bytes + * Plus 60 bytes in i_block (EXT4_MIN_INLINE_DATA_SIZE) = 128 bytes max inline size. + */ +#define TEST_MAX_INLINE_SIZE 128 + +#define TEST_INO 12 +#define TEST_PARENT_INO 2 +#define TEST_PBLK 100 + +struct inline_test_ctx { + struct super_block sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct block_device bdev; + struct address_space bd_mapping; + struct buffer_head sb_bh; + struct ext4_inode_info ei; + struct buffer_head iloc_bh; + u8 raw_inode_buf[TEST_BLOCK_SIZE]; + struct buffer_head data_bh; + u8 data_block_buf[PAGE_SIZE]; + int get_inode_loc_err; + int map_blocks_ret; + ext4_fsblk_t map_pblk; + unsigned int map_flags; + bool getblk_fail; + int dirty_metadata_err; + int dirty_metadata_fail_on_call; + int dirty_metadata_calls; + int da_get_block_prep_err; + int journal_mode; +}; + +static struct inline_test_ctx *t_ctx; + +static const struct super_operations inline_test_sops = {}; + +static bool test_release_folio(struct folio *folio, gfp_t wait) +{ + return try_to_free_buffers(folio); +} + +static const struct address_space_operations test_inline_aops = { + .dirty_folio = noop_dirty_folio, + .invalidate_folio = block_invalidate_folio, + .release_folio = test_release_folio, +}; + +/* --- Static Stubs --- */ + +static int stub_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc) +{ + if (t_ctx->get_inode_loc_err) + return t_ctx->get_inode_loc_err; + + memset(iloc, 0, sizeof(*iloc)); + atomic_inc(&t_ctx->iloc_bh.b_count); + iloc->bh = &t_ctx->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int stub_handle_dirty_metadata(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + t_ctx->dirty_metadata_calls++; + if (t_ctx->dirty_metadata_fail_on_call > 0 && + t_ctx->dirty_metadata_calls == t_ctx->dirty_metadata_fail_on_call) + return t_ctx->dirty_metadata_err; + if (t_ctx->dirty_metadata_fail_on_call == 0 && + t_ctx->dirty_metadata_err) + return t_ctx->dirty_metadata_err; + set_buffer_dirty(bh); + return 0; +} + +static int stub_mark_iloc_dirty(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + brelse(iloc->bh); + return 0; +} + +static int stub_mark_inode_dirty(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + return 0; +} + +static int stub_map_blocks(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + if (t_ctx->map_blocks_ret < 0) + return t_ctx->map_blocks_ret; + + map->m_pblk = t_ctx->map_pblk; + map->m_flags = t_ctx->map_flags; + if (t_ctx->map_blocks_ret > 0) + map->m_len = t_ctx->map_blocks_ret; + return t_ctx->map_blocks_ret; +} + +static struct buffer_head *stub_inline_getblk(struct super_block *sb, + ext4_fsblk_t block) +{ + if (t_ctx->getblk_fail) + return NULL; + + atomic_inc(&t_ctx->data_bh.b_count); + t_ctx->data_bh.b_blocknr = block; + return &t_ctx->data_bh; +} + +static int stub_da_get_block_prep(struct inode *inode, sector_t iblock, + struct buffer_head *bh, int create) +{ + if (t_ctx->da_get_block_prep_err) + return t_ctx->da_get_block_prep_err; + + set_buffer_new(bh); + set_buffer_delay(bh); + bh->b_blocknr = 0; + bh->b_size = inode->i_sb->s_blocksize; + return 0; +} + +static int stub_inode_journal_mode(struct inode *inode) +{ + return t_ctx->journal_mode; +} + +/* --- Helpers --- */ + +static void *raw_inline_i_block(struct inline_test_ctx *ctx) +{ + struct ext4_inode *raw_inode = (struct ext4_inode *)ctx->raw_inode_buf; + + return (void *)raw_inode->i_block; +} + +static void *raw_inline_xattr_pos(struct inline_test_ctx *ctx) +{ + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_inode *raw_inode = (struct ext4_inode *)ctx->raw_inode_buf; + struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode); + struct ext4_xattr_entry *entry; + + entry = (struct ext4_xattr_entry *)((void *)raw_inode + + ctx->ei.i_inline_off); + return (void *)IFIRST(header) + le16_to_cpu(entry->e_value_offs); +} + +static void reset_inode_state(struct inline_test_ctx *ctx, umode_t mode) +{ + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_inode *raw_inode; + + if (!list_empty(&ctx->ei.i_orphan)) + list_del_init(&ctx->ei.i_orphan); + + truncate_inode_pages(&inode->i_data, 0); + + memset(ctx->raw_inode_buf, 0, sizeof(ctx->raw_inode_buf)); + memset(ctx->data_block_buf, 0, sizeof(ctx->data_block_buf)); + memset(ctx->ei.i_data, 0, sizeof(ctx->ei.i_data)); + + raw_inode = (struct ext4_inode *)ctx->raw_inode_buf; + raw_inode->i_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); + + ctx->ei.i_extra_isize = TEST_EXTRA_ISIZE; + ctx->ei.i_inline_off = 0; + ctx->ei.i_inline_size = 0; + ctx->ei.i_flags = 0; + ext4_clear_state_flags(&ctx->ei); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_disksize = 0; + + inode->i_mode = mode; + inode->i_size = 0; + inode->i_blocks = 0; + inode_set_iversion(inode, 1); + inode_state_set_raw(inode, I_DIRTY); +} + +static int create_inline_file(struct inode *inode, const void *data, size_t len) +{ + struct folio *folio = NULL; + void *kaddr; + int ret; + + inode_lock(inode); + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, len, + &folio); + if (ret != 1) { + inode_unlock(inode); + return ret < 0 ? ret : -ENOSPC; + } + + if (data && len) { + kaddr = kmap_local_folio(folio, 0); + memcpy(kaddr, data, len); + kunmap_local(kaddr); + } + + ret = ext4_write_inline_data_end(inode, 0, len, len, folio); + inode_unlock(inode); + if (ret < 0) + return ret; + + i_size_write(inode, len); + EXT4_I(inode)->i_disksize = len; + return 0; +} + +static int inline_test_init(struct kunit *test) +{ + struct inline_test_ctx *ctx; + struct inode *inode; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); + t_ctx = ctx; + test->priv = ctx; + + /* Superblock and ext4_sb_info setup */ + ctx->sb.s_blocksize = TEST_BLOCK_SIZE; + ctx->sb.s_blocksize_bits = TEST_BLOCK_BITS; + ctx->sb.s_maxbytes = MAX_LFS_FILESIZE; + ctx->sb.s_time_gran = 1; + ctx->sb.s_bdi = &noop_backing_dev_info; + ctx->sb.s_fs_info = &ctx->sbi; + ctx->sb.s_op = &inline_test_sops; + snprintf(ctx->sb.s_id, sizeof(ctx->sb.s_id), "ext4-inline-test"); + init_rwsem(&ctx->sb.s_umount); + + ctx->bdev.bd_mapping = &ctx->bd_mapping; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + ctx->sb.s_bdev = &ctx->bdev; + + ctx->es.s_feature_incompat = + cpu_to_le32(EXT4_FEATURE_INCOMPAT_INLINE_DATA | + EXT4_FEATURE_INCOMPAT_EXTENTS | + EXT4_FEATURE_INCOMPAT_FILETYPE); + ctx->es.s_first_data_block = cpu_to_le32(1); + ctx->es.s_inodes_count = cpu_to_le32(1024); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_inode_size = cpu_to_le16(TEST_INODE_SIZE); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + ctx->sbi.s_sbh = &ctx->sb_bh; + + ctx->sbi.s_sb = &ctx->sb; + ctx->sbi.s_es = &ctx->es; + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + ctx->sbi.s_want_extra_isize = TEST_EXTRA_ISIZE; + ctx->sbi.s_cluster_bits = 0; + ctx->sbi.s_cluster_ratio = 1; + INIT_LIST_HEAD(&ctx->sbi.s_orphan); + mutex_init(&ctx->sbi.s_orphan_lock); + set_opt(&ctx->sb, ERRORS_CONT); + spin_lock_init(&ctx->sbi.s_bdev_wb_lock); + spin_lock_init(&ctx->sbi.s_error_lock); + spin_lock_init(&ctx->sbi.s_md_lock); + ratelimit_state_init(&ctx->sbi.s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + /* Mock buffer_head for raw inode (iloc.bh) */ + ctx->iloc_bh.b_data = (char *)ctx->raw_inode_buf; + ctx->iloc_bh.b_size = TEST_BLOCK_SIZE; + ctx->iloc_bh.b_blocknr = 10; + ctx->iloc_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->iloc_bh.b_count, 1); + set_buffer_uptodate(&ctx->iloc_bh); + set_buffer_mapped(&ctx->iloc_bh); + + /* Mock buffer_head for allocated data block (data_bh) */ + ctx->data_bh.b_data = (char *)ctx->data_block_buf; + ctx->data_bh.b_size = TEST_BLOCK_SIZE; + ctx->data_bh.b_blocknr = TEST_PBLK; + ctx->data_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->data_bh.b_count, 1); + set_buffer_uptodate(&ctx->data_bh); + set_buffer_mapped(&ctx->data_bh); + + /* Default stub behavior */ + ctx->map_blocks_ret = 1; + ctx->map_pblk = TEST_PBLK; + ctx->map_flags = EXT4_MAP_MAPPED; + ctx->journal_mode = EXT4_INODE_WRITEBACK_DATA_MODE; + + /* Initialize mock ext4_inode_info and embedded vfs_inode */ + inode = &ctx->ei.vfs_inode; + inode->i_sb = &ctx->sb; + inode->i_ino = TEST_INO; + inode->i_blkbits = TEST_BLOCK_BITS; + set_nlink(inode, 1); + atomic_set(&inode->i_count, 1); + spin_lock_init(&inode->i_lock); + i_size_ordered_init(inode); + init_rwsem(&inode->i_rwsem); + INIT_LIST_HEAD(&inode->i_io_list); + INIT_LIST_HEAD(&inode->i_wb_list); + INIT_LIST_HEAD(&inode->i_lru); + INIT_HLIST_NODE(&inode->i_hash); + inode_state_set_raw(inode, I_DIRTY); + + address_space_init_once(&inode->i_data); + inode->i_data.host = inode; + inode->i_data.a_ops = &test_inline_aops; + mapping_set_gfp_mask(&inode->i_data, GFP_HIGHUSER_MOVABLE); + init_rwsem(&inode->i_data.invalidate_lock); + inode->i_mapping = &inode->i_data; + + init_rwsem(&ctx->ei.xattr_sem); + init_rwsem(&ctx->ei.i_data_sem); + spin_lock_init(&ctx->ei.i_raw_lock); + spin_lock_init(&ctx->ei.i_block_reservation_lock); + INIT_LIST_HEAD(&ctx->ei.i_orphan); + ctx->ei.i_prealloc_node = RB_ROOT; + rwlock_init(&ctx->ei.i_prealloc_lock); + ext4_es_init_tree(&ctx->ei.i_es_tree); + rwlock_init(&ctx->ei.i_es_lock); + INIT_LIST_HEAD(&ctx->ei.i_es_list); + ctx->ei.i_es_all_nr = 0; + ctx->ei.i_es_shk_nr = 0; + + reset_inode_state(ctx, S_IFREG | 0644); + + /* Activate static stubs */ + kunit_activate_static_stub(test, ext4_get_inode_loc, + stub_get_inode_loc); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + stub_handle_dirty_metadata); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + stub_mark_iloc_dirty); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + stub_mark_inode_dirty); + kunit_activate_static_stub(test, ext4_map_blocks, + stub_map_blocks); + kunit_activate_static_stub(test, ext4_inline_getblk, + stub_inline_getblk); + kunit_activate_static_stub(test, ext4_da_get_block_prep, + stub_da_get_block_prep); + kunit_activate_static_stub(test, ext4_inode_journal_mode, + stub_inode_journal_mode); + + return 0; +} + +static void inline_test_exit(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + + if (current->journal_info) + ext4_journal_stop(ext4_journal_current_handle()); + + if (ctx) { + if (!list_empty(&ctx->ei.i_orphan)) + list_del_init(&ctx->ei.i_orphan); + truncate_inode_pages(&ctx->ei.vfs_inode.i_data, 0); + } + t_ctx = NULL; +} + +/* ========================================================================= + * 1. Capacity and Lookup Tests (ext4_get_max_inline_size / + * ext4_find_inline_data_nolock) + * ========================================================================= + */ + +static void test_max_inline_size_variants(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + int ret; + + /* 1. Fresh 256-byte inode with 32-byte extra_isize -> 128 bytes */ + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), + TEST_MAX_INLINE_SIZE); + + /* 2. Inode with i_extra_isize == 0 -> 0 */ + ctx->ei.i_extra_isize = 0; + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), 0); + ctx->ei.i_extra_isize = TEST_EXTRA_ISIZE; + + /* 3. Old 128-byte inode size (no xattr space) -> 0 */ + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), 0); + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + + /* 4. ext4_get_inode_loc error -> 0 */ + ctx->get_inode_loc_err = -EIO; + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), 0); + ctx->get_inode_loc_err = 0; + + /* 5. With a user xattr in ibody reducing free space */ + { + struct ext4_xattr_ibody_find is = { + .s = { .not_found = -ENODATA, }, + }; + struct ext4_xattr_info i = { + .name_index = EXT4_XATTR_INDEX_USER, + .name = "foo", + .value = "12345678", + .value_len = 8, + }; + + ret = ext4_get_inode_loc(inode, &is.iloc); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_ibody_find(inode, &i, &is); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_ibody_set(NULL, inode, &i, &is); + KUNIT_ASSERT_EQ(test, ret, 0); + brelse(is.iloc.bh); + } + /* + * "foo" entry takes EXT4_XATTR_LEN(3) = 20 bytes + EXT4_XATTR_SIZE(8) = 8 + * Total 28 bytes consumed in ibody -> max inline size drops from 128 to 100. + */ + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), + TEST_MAX_INLINE_SIZE - 28); + + /* 6. When inline data already exists in system.data, its space counts as usable */ + reset_inode_state(ctx, S_IFREG | 0644); + { + char buf[80]; + + memset(buf, 'A', sizeof(buf)); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + } + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), + TEST_MAX_INLINE_SIZE); + + /* + * 7. When ibody free space is smaller than EXT4_XATTR_LEN(strlen("data")) + * (20 bytes), get_max_inline_xattr_value_size returns 0 -> max is 0. + */ + reset_inode_state(ctx, S_IFREG | 0644); + { + struct ext4_xattr_ibody_find is = { + .s = { .not_found = -ENODATA, }, + }; + char val[60]; + struct ext4_xattr_info i = { + .name_index = EXT4_XATTR_INDEX_USER, + .name = "bigattr", + .value = val, + .value_len = sizeof(val), + }; + + memset(val, 'x', sizeof(val)); + ret = ext4_get_inode_loc(inode, &is.iloc); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_ibody_find(inode, &i, &is); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_ibody_set(NULL, inode, &i, &is); + KUNIT_ASSERT_EQ(test, ret, 0); + brelse(is.iloc.bh); + } + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), 0); + + /* + * 8. Corrupted xattr entry in ibody (e_name_len overflows end of inode) + * -> get_max_inline_xattr_value_size returns 0 -> total max is 0. + */ + { + struct ext4_inode *raw_inode = + (struct ext4_inode *)ctx->raw_inode_buf; + struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode); + struct ext4_xattr_entry *entry = IFIRST(header); + + entry->e_name_len = 250; + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), 0); + } +} + +static void test_find_inline_data_nolock(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_iloc iloc = { 0 }; + char buf[90]; + int ret; + + /* 1. i_extra_isize == 0 -> returns 0 immediately without setting inline state */ + ctx->ei.i_extra_isize = 0; + ret = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + brelse(iloc.bh); + ctx->ei.i_extra_isize = TEST_EXTRA_ISIZE; + + /* 2. ext4_get_inode_loc error -> propagates error */ + ctx->get_inode_loc_err = -EIO; + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, -EIO); + ctx->get_inode_loc_err = 0; + + /* 3. Inode without EXT4_STATE_XATTR -> returns 0, inline_size == 0 */ + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 0); + + /* 4. Inode with EXT4_STATE_XATTR set, but no system.data xattr -> 0 */ + ext4_set_inode_state(inode, EXT4_STATE_XATTR); + { + struct ext4_inode *raw_inode = + (struct ext4_inode *)ctx->raw_inode_buf; + struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode); + + header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC); + } + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 0); + + /* 5. Inode with 30-byte inline file (0-byte system.data xattr) */ + reset_inode_state(ctx, S_IFREG | 0644); + memset(buf, 'B', sizeof(buf)); + ret = create_inline_file(inode, buf, 30); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->ei.i_inline_off = 0; + ctx->ei.i_inline_size = 0; + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_NE(test, ctx->ei.i_inline_off, 0); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + + /* 6. Inode with 90-byte inline file (30-byte system.data xattr) */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, 90); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->ei.i_inline_off = 0; + ctx->ei.i_inline_size = 0; + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 90); + KUNIT_EXPECT_GT(test, ctx->ei.i_inline_off, + EXT4_GOOD_OLD_INODE_SIZE + TEST_EXTRA_ISIZE); + + /* 7. Corrupted system.data entry with non-zero e_value_inum -> -EFSCORRUPTED */ + { + struct ext4_inode *raw_inode = + (struct ext4_inode *)ctx->raw_inode_buf; + struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode); + struct ext4_xattr_entry *entry = IFIRST(header); + + entry->e_value_inum = cpu_to_le32(99); + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + } +} + +/* ========================================================================= + * 2. Inline File Write & Destroy Lifecycle Tests + * ========================================================================= + */ + +static void test_write_and_destroy_inline_data(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_iloc iloc = { 0 }; + struct folio *folio = NULL; + handle_t *handle; + char pattern[100]; + char verify_buf[100]; + void *kaddr; + int i, ret; + + for (i = 0; i < sizeof(pattern); i++) + pattern[i] = (char)('A' + (i % 26)); + + /* + * Step 1: Write 20 bytes into a brand-new inode (fits in i_block). + */ + inode_lock(inode); + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 20, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, folio); + KUNIT_EXPECT_TRUE(test, folio_test_locked(folio)); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, + (u16)EXT4_MIN_INLINE_DATA_SIZE); + + kaddr = kmap_local_folio(folio, 0); + memcpy(kaddr, pattern, 20); + kunmap_local(kaddr); + + ret = ext4_write_inline_data_end(inode, 0, 20, 20, folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 20); + KUNIT_EXPECT_NULL(test, current->journal_info); + i_size_write(inode, 20); + ctx->ei.i_disksize = 20; + + /* Verify i_block contents */ + KUNIT_EXPECT_MEMEQ(test, raw_inline_i_block(ctx), pattern, 20); + + /* + * Step 2: Expand from 20 bytes to 90 bytes (crosses 60-byte boundary + * into ibody system.data xattr via ext4_update_inline_data). + */ + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 20, 70, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, folio); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 90); + + /* Verify existing first 20 bytes were loaded into the folio by prepare_inline_data */ + kaddr = kmap_local_folio(folio, 0); + KUNIT_EXPECT_MEMEQ(test, kaddr, pattern, 20); + memcpy((char *)kaddr + 20, pattern + 20, 70); + kunmap_local(kaddr); + + ret = ext4_write_inline_data_end(inode, 20, 70, 70, folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 70); + i_size_write(inode, 90); + ctx->ei.i_disksize = 90; + + /* + * Step 3: Overwrite 15 bytes purely within the xattr region + * (pos = 65, len = 15 -> pos >= EXT4_MIN_INLINE_DATA_SIZE). + */ + memset(pattern + 65, 'Z', 15); + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 65, 15, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + kaddr = kmap_local_folio(folio, 0); + memcpy((char *)kaddr + 65, pattern + 65, 15); + kunmap_local(kaddr); + ret = ext4_write_inline_data_end(inode, 65, 15, 15, folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 15); + + /* Verify both i_block (first 60B) and ibody xattr (remaining 30B) */ + memcpy(verify_buf, raw_inline_i_block(ctx), EXT4_MIN_INLINE_DATA_SIZE); + memcpy(verify_buf + EXT4_MIN_INLINE_DATA_SIZE, + raw_inline_xattr_pos(ctx), 30); + KUNIT_EXPECT_MEMEQ(test, verify_buf, pattern, 90); + + /* + * Step 4: Destroy inline data on a regular file -> clears inline state + * and initializes extent tree (EXT4_INODE_EXTENTS). + */ + handle = ext4_journal_start(inode, EXT4_HT_INODE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_destroy_inline_data(handle, inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_off, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 0); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + brelse(iloc.bh); + + /* Calling destroy again when inline_off == 0 is a no-op returning 0 */ + ret = ext4_destroy_inline_data(handle, inode); + KUNIT_EXPECT_EQ(test, ret, 0); + ext4_journal_stop(handle); + + /* + * Step 5: Initial creation directly > 60 bytes (75 bytes) on a non-extent + * mode inode (e.g. S_IFIFO) -> destroy does NOT set EXT4_INODE_EXTENTS. + */ + reset_inode_state(ctx, S_IFIFO | 0644); + ret = create_inline_file(inode, pattern, 75); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 75); + + handle = ext4_journal_start(inode, EXT4_HT_INODE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_destroy_inline_data(handle, inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + ext4_journal_stop(handle); +} + +static void test_write_inline_short_copy_and_edge_cases(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + struct folio *folio = NULL; + char buf[80]; + void *kaddr; + int ret; + + memset(buf, 'M', sizeof(buf)); + ret = create_inline_file(inode, buf, 20); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * 1. Short write (copied < len) when expanding from 20B to 80B: + * prepare_inline_data expands xattr to 80B, but only 10 bytes are + * copied (pos=20, len=60, copied=10 -> pos+copied=30 > i_size=20). + * ext4_write_inline_data_end adds to orphan, updates i_disksize to 30, + * and calls ext4_truncate_failed_write -> shrinks inline data back to + * 60B (i_block only). + */ + inode_lock(inode); + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 20, 60, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 80); + + kaddr = kmap_local_folio(folio, 0); + memcpy((char *)kaddr + 20, "0123456789", 10); + kunmap_local(kaddr); + + ret = ext4_write_inline_data_end(inode, 20, 60, 10, folio); + KUNIT_EXPECT_EQ(test, ret, 10); + KUNIT_EXPECT_EQ(test, i_size_read(inode), 30); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, + (u16)EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei.i_orphan)); + inode_unlock(inode); + + /* + * 2. Short write (copied < len) when folio is NOT uptodate -> + * copied is forced to 0. + */ + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 30, 10, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + folio_clear_uptodate(folio); + ret = ext4_write_inline_data_end(inode, 30, 10, 5, folio); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, i_size_read(inode), 30); + inode_unlock(inode); + + /* + * 3. Emergency shutdown flag (EXT4_FLAGS_SHUTDOWN): + * 3a. Set before ext4_try_to_write_inline_data -> ext4_journal_start + * fails with -EIO. + * 3b. Set after ext4_try_to_write_inline_data -> ext4_write_inline_data + * returns early without modifying inline data. + */ + set_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 10, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, -EIO); + clear_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 10, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + kaddr = kmap_local_folio(folio, 0); + memcpy(kaddr, "XXXXXXXXXX", 10); + kunmap_local(kaddr); + set_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + ret = ext4_write_inline_data_end(inode, 0, 10, 10, folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 10); + /* i_block should still have 'M's because shutdown skipped ext4_write_inline_data */ + KUNIT_EXPECT_MEMEQ(test, raw_inline_i_block(ctx), buf, 10); + clear_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + + /* + * 4. Race condition where EXT4_INODE_INLINE_DATA is cleared before + * ext4_write_inline_data_end runs -> skips inline copy and returns 0. + */ + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 10, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ret = ext4_write_inline_data_end(inode, 0, 10, 10, folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + + /* + * 5. Corruption detection in ext4_create_inline_data when system.data + * already exists on an inode with i_inline_off == 0 (e.g. corrupted + * e_value_inum so ext4_find_inline_data_nolock leaves i_inline_off == 0). + */ + { + struct ext4_inode *raw_inode = + (struct ext4_inode *)ctx->raw_inode_buf; + struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode); + struct ext4_xattr_entry *entry = IFIRST(header); + + entry->e_value_inum = cpu_to_le32(1); + ctx->ei.i_inline_off = 0; + ctx->ei.i_inline_size = 0; + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, + 10, &folio); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + } + + /* + * 6. Corruption detection in ext4_update_inline_data when inline state + * claims inline data exists, but system.data xattr was wiped. + */ + reset_inode_state(ctx, S_IFREG | 0644); + ctx->ei.i_inline_off = 164; + ctx->ei.i_inline_size = EXT4_MIN_INLINE_DATA_SIZE; + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 80, + &folio); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); +} + +/* ========================================================================= + * 3. Reading Inline Data, Symlinks, and iomap Tests + * ========================================================================= + */ + +static void test_readpage_inline_link_and_iomap(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + struct folio *folio; + struct iomap iomap = { 0 }; + char content[85]; + const char *short_link = "/usr/bin/python3"; + char long_link[85]; + char *target; + void *kaddr; + int i, ret; + + for (i = 0; i < sizeof(content); i++) + content[i] = (char)('0' + (i % 10)); + + /* 1. ext4_readpage_inline and ext4_inline_data_iomap on non-inline inode -> -EAGAIN */ + folio = __filemap_get_folio(&inode->i_data, 0, + FGP_LOCK | FGP_ACCESSED | FGP_CREAT, + GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + ret = ext4_readpage_inline(inode, folio); + KUNIT_EXPECT_EQ(test, ret, -EAGAIN); + folio_unlock(folio); + folio_put(folio); + + ret = ext4_inline_data_iomap(inode, &iomap); + KUNIT_EXPECT_EQ(test, ret, -EAGAIN); + + /* 2. Create 85-byte inline file and test ext4_readpage_inline on index 0 */ + truncate_inode_pages(&inode->i_data, 0); + ret = create_inline_file(inode, content, sizeof(content)); + KUNIT_ASSERT_EQ(test, ret, 0); + truncate_inode_pages(&inode->i_data, 0); + + folio = __filemap_get_folio(&inode->i_data, 0, + FGP_LOCK | FGP_ACCESSED | FGP_CREAT, + GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + ret = ext4_readpage_inline(inode, folio); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_TRUE(test, folio_test_uptodate(folio)); + KUNIT_EXPECT_FALSE(test, folio_test_locked(folio)); + + kaddr = kmap_local_folio(folio, 0); + KUNIT_EXPECT_MEMEQ(test, kaddr, content, sizeof(content)); + /* Verify zero-padding past inline_size */ + KUNIT_EXPECT_EQ(test, ((char *)kaddr)[sizeof(content)], 0); + KUNIT_EXPECT_EQ(test, ((char *)kaddr)[PAGE_SIZE - 1], 0); + kunmap_local(kaddr); + folio_put(folio); + + /* 3. ext4_readpage_inline on folio->index > 0 zeros the folio and marks uptodate */ + folio = __filemap_get_folio(&inode->i_data, 1, + FGP_LOCK | FGP_ACCESSED | FGP_CREAT, + GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + kaddr = kmap_local_folio(folio, 0); + memset(kaddr, 0xff, PAGE_SIZE); + kunmap_local(kaddr); + + ret = ext4_readpage_inline(inode, folio); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_TRUE(test, folio_test_uptodate(folio)); + kaddr = kmap_local_folio(folio, 0); + KUNIT_EXPECT_EQ(test, ((unsigned char *)kaddr)[0], 0); + kunmap_local(kaddr); + folio_put(folio); + + /* 4. ext4_readpage_inline when ext4_get_inode_loc fails -> propagates error */ + truncate_inode_pages(&inode->i_data, 0); + ctx->get_inode_loc_err = -EIO; + folio = __filemap_get_folio(&inode->i_data, 0, + FGP_LOCK | FGP_ACCESSED | FGP_CREAT, + GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + ret = ext4_readpage_inline(inode, folio); + KUNIT_EXPECT_EQ(test, ret, -EIO); + folio_put(folio); + ctx->get_inode_loc_err = 0; + + /* + * 5. ext4_readpage_inline when i_inline_size > PAGE_SIZE -> -EFSCORRUPTED. + * i_inline_size is a u16, so it can only exceed PAGE_SIZE when + * PAGE_SIZE < U16_MAX (e.g. 4KB, 8KB, 16KB, or 32KB base pages). + */ + if (PAGE_SIZE < U16_MAX) { + truncate_inode_pages(&inode->i_data, 0); + ctx->ei.i_inline_size = U16_MAX; + i_size_write(inode, U16_MAX); + folio = __filemap_get_folio(&inode->i_data, 0, + FGP_LOCK | FGP_ACCESSED | FGP_CREAT, + GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + ret = ext4_readpage_inline(inode, folio); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + folio_put(folio); + ctx->ei.i_inline_size = sizeof(content); + i_size_write(inode, sizeof(content)); + } + + /* 6. ext4_inline_data_iomap populates IOMAP_INLINE with inline address/len */ + memset(&iomap, 0, sizeof(iomap)); + ret = ext4_inline_data_iomap(inode, &iomap); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_INLINE); + KUNIT_EXPECT_EQ(test, iomap.offset, 0ULL); + KUNIT_EXPECT_EQ(test, iomap.length, (u64)sizeof(content)); + KUNIT_EXPECT_EQ(test, iomap.addr, + ((u64)ctx->iloc_bh.b_blocknr << TEST_BLOCK_BITS) + + offsetof(struct ext4_inode, i_block)); + + /* 7. ext4_inline_data_iomap error when ext4_get_inode_loc fails */ + ctx->get_inode_loc_err = -EIO; + ret = ext4_inline_data_iomap(inode, &iomap); + KUNIT_EXPECT_EQ(test, ret, -EIO); + ctx->get_inode_loc_err = 0; + + /* 8. ext4_read_inline_link: short symlink (in i_block) and long symlink (in xattr) */ + reset_inode_state(ctx, S_IFLNK | 0777); + ret = create_inline_file(inode, short_link, strlen(short_link)); + KUNIT_ASSERT_EQ(test, ret, 0); + + target = ext4_read_inline_link(inode); + KUNIT_ASSERT_FALSE(test, IS_ERR(target)); + KUNIT_EXPECT_STREQ(test, target, short_link); + kfree(target); + + reset_inode_state(ctx, S_IFLNK | 0777); + memset(long_link, 'a', sizeof(long_link) - 1); + long_link[sizeof(long_link) - 1] = '\0'; + ret = create_inline_file(inode, long_link, strlen(long_link)); + KUNIT_ASSERT_EQ(test, ret, 0); + + target = ext4_read_inline_link(inode); + KUNIT_ASSERT_FALSE(test, IS_ERR(target)); + KUNIT_EXPECT_STREQ(test, target, long_link); + kfree(target); + + /* ext4_read_inline_link error when ext4_get_inode_loc fails */ + ctx->get_inode_loc_err = -EIO; + target = ext4_read_inline_link(inode); + KUNIT_EXPECT_TRUE(test, IS_ERR(target)); + KUNIT_EXPECT_EQ(test, PTR_ERR(target), -EIO); + ctx->get_inode_loc_err = 0; +} + +/* ========================================================================= + * 4. Inline Truncation Tests (ext4_inline_data_truncate) + * ========================================================================= + */ + +static void test_inline_data_truncate(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + int has_inline = 1; + char buf[100]; + int i, ret; + + for (i = 0; i < sizeof(buf); i++) + buf[i] = (char)('a' + (i % 26)); + + /* 1. Non-inline inode -> sets *has_inline = 0 and returns */ + inode_lock(inode); + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, has_inline, 0); + + /* 2. Create a 100-byte inline file (60B in i_block + 40B in xattr) */ + ret = create_inline_file(inode, buf, 100); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 100); + + /* 3. Truncate extending i_size (100 -> 120): no-op on inline size */ + inode_lock(inode); + i_size_write(inode, 120); + has_inline = 1; + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, has_inline, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 100); + + /* 4. Shrink within xattr space (100 -> 75 bytes) */ + inode_lock(inode); + i_size_write(inode, 75); + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, has_inline, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 75); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 75); + KUNIT_EXPECT_MEMEQ(test, raw_inline_xattr_pos(ctx), + buf + EXT4_MIN_INLINE_DATA_SIZE, 15); + + /* 5. Shrink from xattr space into i_block (75 -> 25 bytes): zeros i_block[25..59] */ + inode_lock(inode); + i_size_write(inode, 25); + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, + (u16)EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 25); + KUNIT_EXPECT_MEMEQ(test, raw_inline_i_block(ctx), buf, 25); + for (i = 25; i < EXT4_MIN_INLINE_DATA_SIZE; i++) + KUNIT_EXPECT_EQ(test, ((char *)raw_inline_i_block(ctx))[i], 0); + + /* 6. Shrink to 0 bytes: zeros all of i_block */ + inode_lock(inode); + i_size_write(inode, 0); + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 0); + for (i = 0; i < EXT4_MIN_INLINE_DATA_SIZE; i++) + KUNIT_EXPECT_EQ(test, ((char *)raw_inline_i_block(ctx))[i], 0); + + /* + * 7. When !EXT4_STATE_MAY_INLINE_DATA (being converted), + * ext4_inline_data_truncate clears the extent status tree. + */ + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + inode_lock(inode); + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei.i_orphan)); +} + +/* ========================================================================= + * 5. Inline-to-Extent Conversion Tests for Regular Files + * ========================================================================= + */ + +static void test_convert_inline_data_and_rollback(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + char buf[80]; + int i, ret; + + for (i = 0; i < sizeof(buf); i++) + buf[i] = (char)('A' + (i % 26)); + + /* 1. Non-inline inode -> clears MAY_INLINE_DATA and returns 0 immediately */ + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + + /* + * 2. Inline inode without EXT4_STATE_MAY_INLINE_DATA -> calls + * filemap_flush() and finishes converting inline data if still inline. + */ + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_MEMEQ(test, ctx->data_block_buf, buf, sizeof(buf)); + + /* + * 3. Error rollback when ext4_map_blocks fails (-ENOSPC): + * ext4_restore_inline_data restores the original 80 bytes of inline data. + */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->map_blocks_ret = -ENOSPC; + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, sizeof(buf)); + KUNIT_EXPECT_MEMEQ(test, raw_inline_i_block(ctx), buf, + EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_MEMEQ(test, raw_inline_xattr_pos(ctx), + buf + EXT4_MIN_INLINE_DATA_SIZE, + sizeof(buf) - EXT4_MIN_INLINE_DATA_SIZE); + ctx->map_blocks_ret = 1; + + /* + * 4. Error rollback when ext4_map_blocks returns unmapped block -> -EIO + */ + ctx->map_flags = 0; + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, -EIO); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + ctx->map_flags = EXT4_MAP_MAPPED; + + /* + * 5. Error rollback when ext4_inline_getblk returns NULL -> -ENOMEM + */ + ctx->getblk_fail = true; + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, -ENOMEM); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + ctx->getblk_fail = false; + + /* + * 6. Error rollback when ext4_handle_dirty_metadata fails on data_bh + */ + ctx->dirty_metadata_err = -EIO; + ctx->dirty_metadata_fail_on_call = 1; + ctx->dirty_metadata_calls = 0; + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, -EIO); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + ctx->dirty_metadata_err = 0; + ctx->dirty_metadata_fail_on_call = 0; + + /* + * 7. Successful conversion via ext4_convert_inline_data(): + * copies 80 bytes into data_bh, destroys inline data, initializes + * extent tree. + */ + memset(ctx->data_block_buf, 0, sizeof(ctx->data_block_buf)); + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_MEMEQ(test, ctx->data_block_buf, buf, sizeof(buf)); +} + +static void test_write_triggers_inline_to_extent_conversion(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + struct folio *folio = NULL; + char buf[50]; + int ret; + + memset(buf, 'K', sizeof(buf)); + + /* + * 1. Standard write (ext4_try_to_write_inline_data) exceeding + * TEST_MAX_INLINE_SIZE (pos=0, len=200) converts inline data via + * ext4_convert_inline_data_to_extent -> returns 0 so caller proceeds + * with normal block write. + */ + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + + inode_lock(inode); + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 200, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + + /* + * 2. Conversion with DIOREAD_NOLOCK + DELALLOC in writeback mode + * (exercises ext4_should_dioread_nolock -> ext4_get_block_unwritten), + * and separately with JOURNAL_DATA mode (exercises + * ext4_should_journal_data -> do_journal_get_write_access). + */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + + set_opt(&ctx->sb, DIOREAD_NOLOCK); + set_opt(&ctx->sb, DELALLOC); + ctx->journal_mode = EXT4_INODE_WRITEBACK_DATA_MODE; + + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 200, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + + clear_opt(&ctx->sb, DIOREAD_NOLOCK); + clear_opt(&ctx->sb, DELALLOC); + + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->journal_mode = EXT4_INODE_JOURNAL_DATA_MODE; + + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 200, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + + ctx->journal_mode = EXT4_INODE_WRITEBACK_DATA_MODE; + + /* + * 3. Error paths in ext4_convert_inline_data_to_extent when + * ext4_get_block fails during ext4_block_write_begin (-EIO and -ENOSPC): + * cleans up orphan and propagates error. + */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->map_blocks_ret = -EIO; + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 200, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, -EIO); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei.i_orphan)); + ctx->map_blocks_ret = 1; + + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->map_blocks_ret = -ENOSPC; + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 200, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei.i_orphan)); + ctx->map_blocks_ret = 1; + + /* + * 4. Delayed allocation conversion (da = true in + * ext4_generic_write_inline_data): + * 4a. Fresh inode without inline data yet -> clears MAY_INLINE_DATA + * and returns 0. + */ + reset_inode_state(ctx, S_IFREG | 0644); + folio = NULL; + ret = ext4_generic_write_inline_data(&inode->i_data, inode, 0, 200, + &folio, true); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)); + + /* + * 4b. Existing inline data -> ext4_da_convert_inline_data_to_extent + * loads inline bytes into folio, marks buffer delayed, and clears + * EXT4_STATE_MAY_INLINE_DATA while keeping inline data until + * writepages. + */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + truncate_inode_pages(&inode->i_data, 0); + + folio = NULL; + ret = ext4_generic_write_inline_data(&inode->i_data, inode, 0, 200, + &folio, true); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)); + + /* + * 4c. Error in ext4_da_get_block_prep during DA conversion -> + * propagates error and unlocks folio. + */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + truncate_inode_pages(&inode->i_data, 0); + + ctx->da_get_block_prep_err = -ENOSPC; + inode_lock(inode); + folio = NULL; + ret = ext4_generic_write_inline_data(&inode->i_data, inode, 0, 200, + &folio, true); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + ctx->da_get_block_prep_err = 0; +} + +/* ========================================================================= + * 6. Inline Directory Operations Tests + * ========================================================================= + */ + +struct test_dir_ctx { + struct dir_context ctx; + int count; + char names[16][32]; + u64 inos[16]; + int max_emit; + struct inode *mutate_inode_on_second; +}; + +static bool test_filldir_actor(struct dir_context *dctx, const char *name, + int namelen, loff_t offset, u64 ino, + unsigned int d_type) +{ + struct test_dir_ctx *tctx = + container_of(dctx, struct test_dir_ctx, ctx); + + if (tctx->max_emit > 0 && tctx->count >= tctx->max_emit) + return false; + + if (tctx->count < 16) { + int copy_len = min(namelen, 31); + + memcpy(tctx->names[tctx->count], name, copy_len); + tctx->names[tctx->count][copy_len] = '\0'; + tctx->inos[tctx->count] = ino; + } + tctx->count++; + + if (tctx->mutate_inode_on_second && tctx->count == 2) { + inode_inc_iversion(tctx->mutate_inode_on_second); + tctx->mutate_inode_on_second = NULL; + } + return true; +} + +struct inline_dir_test_env { + struct inode parent; + struct inode child; + struct qstr qname; + struct ext4_filename fname; + struct dir_private_info info; + struct file filp; + struct test_dir_ctx dctx; + struct ext4_dir_entry_2 bogus_de; +}; + +static struct inline_dir_test_env * +alloc_dir_test_env(struct kunit *test, struct inline_test_ctx *ctx) +{ + struct inline_dir_test_env *env; + + env = kunit_kzalloc(test, sizeof(*env), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, env); + env->parent.i_sb = &ctx->sb; + env->parent.i_ino = TEST_PARENT_INO; + env->parent.i_mode = S_IFDIR | 0755; + return env; +} + +static void init_mock_fname_and_child(struct inline_dir_test_env *env, + struct super_block *sb, + const char *name, ino_t ino, + umode_t mode) +{ + memset(&env->fname, 0, sizeof(env->fname)); + memset(&env->qname, 0, sizeof(env->qname)); + memset(&env->child, 0, sizeof(env->child)); + + env->child.i_sb = sb; + env->child.i_ino = ino; + env->child.i_mode = mode; + + env->qname.name = (const unsigned char *)name; + env->qname.len = strlen(name); + env->fname.usr_fname = &env->qname; + env->fname.disk_name.name = (unsigned char *)name; + env->fname.disk_name.len = strlen(name); +} + +static void test_update_final_de(struct kunit *test) +{ + u8 buf[64]; + struct ext4_dir_entry_2 *de1, *de2; + + memset(buf, 0, sizeof(buf)); + + /* 1. old_size == 0 -> sets de1->rec_len to new_size (32) */ + de1 = (struct ext4_dir_entry_2 *)buf; + ext4_update_final_de(buf, 0, 32); + KUNIT_EXPECT_EQ(test, le16_to_cpu(de1->rec_len), 32); + + /* 2. Two entries in 32 bytes (12 + 20), expand to 56 bytes -> last entry becomes 44 */ + de1->rec_len = cpu_to_le16(12); + de2 = (struct ext4_dir_entry_2 *)(buf + 12); + de2->rec_len = cpu_to_le16(20); + ext4_update_final_de(buf, 32, 56); + KUNIT_EXPECT_EQ(test, le16_to_cpu(de1->rec_len), 12); + KUNIT_EXPECT_EQ(test, le16_to_cpu(de2->rec_len), 44); +} + +static void test_inline_dir_lifecycle_and_operations(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->ei.vfs_inode; + struct inline_dir_test_env *env; + struct ext4_dir_entry_2 *de = NULL; + struct buffer_head *bh = NULL; + handle_t *handle; + int has_inline_data = 1; + int ret; + + env = alloc_dir_test_env(test, ctx); + reset_inode_state(ctx, S_IFDIR | 0755); + + /* + * 1. Create inline directory via ext4_try_create_inline_dir. + */ + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_create_inline_dir(handle, &env->parent, dir); + ext4_journal_stop(handle); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(dir)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, + (u16)EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_EQ(test, i_size_read(dir), + (loff_t)EXT4_MIN_INLINE_DATA_SIZE); + + /* Newly created inline dir is empty */ + KUNIT_EXPECT_TRUE(test, empty_inline_dir(dir, &has_inline_data)); + KUNIT_EXPECT_EQ(test, has_inline_data, 1); + + /* + * 2. Verify ext4_get_first_inline_block returns the inline buffer + * starting at parent_de (whose inode field holds the parent ino). + */ + bh = ext4_get_first_inline_block(dir, &de, &ret); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_PARENT_INO); + brelse(bh); + + /* + * 3. Add first entry "file1" (fits in i_block alongside parent ino). + * Return value 1 means added inline without block conversion. + */ + init_mock_fname_and_child(env, &ctx->sb, "file1", 101, S_IFREG | 0644); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, + (u16)EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_FALSE(test, empty_inline_dir(dir, &has_inline_data)); + + /* + * 4. Adding duplicate "file1" returns -EEXIST. + */ + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, -EEXIST); + + /* + * 5. Add more entries ("file2_longer_name", "file3_longer_name", + * "file4_in_xattr") to overflow i_block (56B) and trigger expansion + * into ibody system.data xattr via ext4_update_inline_dir (132B). + */ + init_mock_fname_and_child(env, &ctx->sb, "file2_longer_name", 102, + S_IFREG | 0644); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 1); + + init_mock_fname_and_child(env, &ctx->sb, "file3_longer_name", 103, + S_IFDIR | 0755); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, TEST_MAX_INLINE_SIZE); + + init_mock_fname_and_child(env, &ctx->sb, "file4_in_xattr", 104, + S_IFREG | 0644); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 1); + + /* + * 6. Lookup entries in both i_block ("file1") and xattr ("file4_in_xattr"), + * and verify missing entry returns NULL. + */ + init_mock_fname_and_child(env, &ctx->sb, "file1", 0, 0); + bh = ext4_find_inline_entry(dir, &env->fname, &de, &has_inline_data); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, has_inline_data, 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), 101U); + brelse(bh); + + init_mock_fname_and_child(env, &ctx->sb, "file4_in_xattr", 0, 0); + bh = ext4_find_inline_entry(dir, &env->fname, &de, &has_inline_data); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), 104U); + brelse(bh); + + init_mock_fname_and_child(env, &ctx->sb, "nonexistent", 0, 0); + bh = ext4_find_inline_entry(dir, &env->fname, &de, &has_inline_data); + KUNIT_EXPECT_NULL(test, bh); + KUNIT_EXPECT_EQ(test, has_inline_data, 1); + + /* + * 7. Test ext4_read_inline_dir (full iteration, partial iteration, + * and iversion change re-validation). + */ + env->filp.f_inode = dir; + env->filp.private_data = &env->info; + env->dctx.ctx.actor = test_filldir_actor; + env->dctx.ctx.pos = 0; + + ret = ext4_read_inline_dir(&env->filp, &env->dctx.ctx, + &has_inline_data); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, has_inline_data, 1); + /* + * Expect ".", "..", "file1", "file2_longer_name", + * "file3_longer_name", "file4_in_xattr" + */ + KUNIT_EXPECT_EQ(test, env->dctx.count, 6); + KUNIT_EXPECT_STREQ(test, env->dctx.names[0], "."); + KUNIT_EXPECT_STREQ(test, env->dctx.names[1], ".."); + KUNIT_EXPECT_STREQ(test, env->dctx.names[2], "file1"); + KUNIT_EXPECT_STREQ(test, env->dctx.names[5], "file4_in_xattr"); + /* + * extra_size = (dotdot_size - EXT4_INLINE_DOTDOT_SIZE) + + * TEST_MAX_INLINE_SIZE = (24 - 4) + 128 = 148 + */ + KUNIT_EXPECT_EQ(test, env->dctx.ctx.pos, + (loff_t)(TEST_MAX_INLINE_SIZE + 20)); + + /* Calling again at EOF (pos == inline_size) emits nothing */ + env->dctx.count = 0; + ret = ext4_read_inline_dir(&env->filp, &env->dctx.ctx, + &has_inline_data); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, env->dctx.count, 0); + + /* + * Mutating inode iversion during iteration and re-entering at nonzero + * ctx.pos triggers offset revalidation in ext4_read_inline_dir(). + */ + memset(&env->dctx, 0, sizeof(env->dctx)); + env->dctx.ctx.actor = test_filldir_actor; + env->dctx.ctx.pos = 0; + env->dctx.max_emit = 3; + env->dctx.mutate_inode_on_second = dir; + ret = ext4_read_inline_dir(&env->filp, &env->dctx.ctx, + &has_inline_data); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, env->dctx.count, 3); + KUNIT_EXPECT_GT(test, env->dctx.ctx.pos, (loff_t)0); + + env->dctx.max_emit = 0; + ret = ext4_read_inline_dir(&env->filp, &env->dctx.ctx, + &has_inline_data); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, env->dctx.count, 6); + + /* + * 8. Test ext4_inlinedir_to_tree (htree rbtree population). + */ + { + struct dir_private_info *info; + struct dx_hash_info hinfo = { + .hash_version = DX_HASH_HALF_MD4, + }; + + memset(&env->filp, 0, sizeof(env->filp)); + env->filp.f_inode = dir; + info = kzalloc_obj(*info, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, info); + env->filp.private_data = info; + ret = ext4_inlinedir_to_tree(&env->filp, dir, 0, &hinfo, + 0, 0, &has_inline_data); + KUNIT_EXPECT_GT(test, ret, 0); + KUNIT_EXPECT_EQ(test, has_inline_data, 1); + + /* With start_hash = 0xffffffffU, entries with smaller hash are skipped */ + ext4_htree_free_dir_info(info); + info = kzalloc_obj(*info, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, info); + env->filp.private_data = info; + ret = ext4_inlinedir_to_tree(&env->filp, dir, 0, &hinfo, + 0xffffffffU, 0xffffffffU, + &has_inline_data); + KUNIT_EXPECT_GE(test, ret, 0); + ext4_htree_free_dir_info(info); + } + + /* + * 9. Delete entries in both i_block and xattr regions and verify + * empty_inline_dir behavior when only xattr has an entry vs completely empty. + */ + { + static const char * const del_names[] = { + "file1", + "file2_longer_name", + "file3_longer_name", + }; + int i; + + for (i = 0; i < ARRAY_SIZE(del_names); i++) { + init_mock_fname_and_child(env, &ctx->sb, del_names[i], + 0, 0); + bh = ext4_find_inline_entry(dir, &env->fname, &de, + &has_inline_data); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_delete_inline_entry(handle, dir, de, bh, + &has_inline_data); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 0); + brelse(bh); + } + } + + /* i_block now has no live entries, but "file4_in_xattr" is still in xattr */ + KUNIT_EXPECT_FALSE(test, empty_inline_dir(dir, &has_inline_data)); + + /* Delete "file4_in_xattr" -> directory becomes completely empty */ + init_mock_fname_and_child(env, &ctx->sb, "file4_in_xattr", 0, 0); + bh = ext4_find_inline_entry(dir, &env->fname, &de, &has_inline_data); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + + /* Deleting an address outside inline buffers returns -ENOENT */ + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_delete_inline_entry(handle, dir, &env->bogus_de, bh, + &has_inline_data); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, -ENOENT); + + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_delete_inline_entry(handle, dir, de, bh, &has_inline_data); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 0); + brelse(bh); + + KUNIT_EXPECT_TRUE(test, empty_inline_dir(dir, &has_inline_data)); +} + +static void test_inline_dir_conversion_and_corruptions(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->ei.vfs_inode; + struct inline_dir_test_env *env; + struct ext4_dir_entry_2 *de; + handle_t *handle; + int has_inline_data = 1; + int i, ret; + + env = alloc_dir_test_env(test, ctx); + reset_inode_state(ctx, S_IFDIR | 0755); + + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_create_inline_dir(handle, &env->parent, dir); + ext4_journal_stop(handle); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* Fill the inline directory up to its 128-byte limit */ + for (i = 0; i < 4; i++) { + char name[24]; + + snprintf(name, sizeof(name), "entry_long_name_%d", i); + init_mock_fname_and_child(env, &ctx->sb, name, 200 + i, + S_IFREG | 0644); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, + &env->child); + ext4_journal_stop(handle); + KUNIT_ASSERT_EQ(test, ret, 1); + } + + /* + * 1. When full, adding another entry triggers ext4_convert_inline_data_nolock. + * Test rollback first when ext4_map_blocks fails (-ENOSPC). + */ + init_mock_fname_and_child(env, &ctx->sb, "overflow_entry_name", 250, + S_IFREG | 0644); + ctx->map_blocks_ret = -ENOSPC; + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(dir)); + ctx->map_blocks_ret = 1; + + /* + * 2. Successful conversion of full inline directory to a normal + * 1024-byte directory block -> ext4_try_add_inline_entry returns 0 + * and data_block_buf starts with "." and ".." followed by copied entries. + */ + memset(ctx->data_block_buf, 0, sizeof(ctx->data_block_buf)); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(dir)); + KUNIT_EXPECT_EQ(test, i_size_read(dir), (loff_t)TEST_BLOCK_SIZE); + + /* Verify "." and ".." headers in converted block */ + de = (struct ext4_dir_entry_2 *)ctx->data_block_buf; + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_INO); + KUNIT_EXPECT_EQ(test, de->name_len, 1); + KUNIT_EXPECT_EQ(test, de->name[0], '.'); + de = ext4_next_entry(de, TEST_BLOCK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_PARENT_INO); + KUNIT_EXPECT_EQ(test, de->name_len, 2); + KUNIT_EXPECT_MEMEQ(test, de->name, "..", 2); + + /* + * 3. Non-inline directory behavior on inline dir functions: + * sets *has_inline_data = 0 and returns early. + */ + has_inline_data = 1; + KUNIT_EXPECT_TRUE(test, empty_inline_dir(dir, &has_inline_data)); + KUNIT_EXPECT_EQ(test, has_inline_data, 0); + + /* + * 4. Corrupted inline directory checks: + * 4a. Parent ino ("..") == 0 -> empty_inline_dir returns false. + * 4b. Zero rec_len dirent -> empty_inline_dir returns false and + * ext4_convert_inline_data aborts via ext4_check_all_de. + */ + reset_inode_state(ctx, S_IFDIR | 0755); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_create_inline_dir(handle, &env->parent, dir); + ext4_journal_stop(handle); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* Corrupt parent ino to 0 */ + *(__le32 *)raw_inline_i_block(ctx) = cpu_to_le32(0); + KUNIT_EXPECT_FALSE(test, empty_inline_dir(dir, &has_inline_data)); + *(__le32 *)raw_inline_i_block(ctx) = cpu_to_le32(TEST_PARENT_INO); + + /* Corrupt first dirent rec_len to 0 */ + de = (struct ext4_dir_entry_2 *)((char *)raw_inline_i_block(ctx) + + EXT4_INLINE_DOTDOT_SIZE); + de->rec_len = cpu_to_le16(0); + KUNIT_EXPECT_FALSE(test, empty_inline_dir(dir, &has_inline_data)); + + /* ext4_convert_inline_data on corrupted inline dir fails in ext4_check_all_de */ + ret = ext4_convert_inline_data(dir); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(dir)); +} + +static struct kunit_case ext4_inline_test_cases[] = { + KUNIT_CASE(test_max_inline_size_variants), + KUNIT_CASE(test_find_inline_data_nolock), + KUNIT_CASE(test_write_and_destroy_inline_data), + KUNIT_CASE(test_write_inline_short_copy_and_edge_cases), + KUNIT_CASE(test_readpage_inline_link_and_iomap), + KUNIT_CASE(test_inline_data_truncate), + KUNIT_CASE(test_convert_inline_data_and_rollback), + KUNIT_CASE(test_write_triggers_inline_to_extent_conversion), + KUNIT_CASE(test_update_final_de), + KUNIT_CASE(test_inline_dir_lifecycle_and_operations), + KUNIT_CASE(test_inline_dir_conversion_and_corruptions), + {} +}; + +static struct kunit_suite ext4_inline_test_suite = { + .name = "ext4_inline_test", + .init = inline_test_init, + .exit = inline_test_exit, + .test_cases = ext4_inline_test_cases, +}; + +kunit_test_suites(&ext4_inline_test_suite); + +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/inline.c b/fs/ext4/inline.c index 1f7aa2223d1cf2..acdc65ce47960a 100644 --- a/fs/ext4/inline.c +++ b/fs/ext4/inline.c @@ -9,6 +9,7 @@ #include #include #include +#include #include "ext4_jbd2.h" #include "ext4.h" @@ -1112,6 +1113,13 @@ static void ext4_restore_inline_data(handle_t *handle, struct inode *inode, ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); } +struct buffer_head *ext4_inline_getblk(struct super_block *sb, + ext4_fsblk_t block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_inline_getblk, sb, block); + return sb_getblk(sb, block); +} + static int ext4_convert_inline_data_nolock(handle_t *handle, struct inode *inode, struct ext4_iloc *iloc) @@ -1160,7 +1168,7 @@ static int ext4_convert_inline_data_nolock(handle_t *handle, goto out_restore; } - data_bh = sb_getblk(inode->i_sb, map.m_pblk); + data_bh = ext4_inline_getblk(inode->i_sb, map.m_pblk); if (!data_bh) { error = -ENOMEM; goto out_restore; @@ -2038,5 +2046,25 @@ int ext4_convert_inline_data(struct inode *inode) } #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inline_getblk); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_max_inline_size); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_inline_data_nolock); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_readpage_inline); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_generic_write_inline_data); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_try_to_write_inline_data); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_write_inline_data_end); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_final_de); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_try_add_inline_entry); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inlinedir_to_tree); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_inline_dir); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_inline_link); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_first_inline_block); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_try_create_inline_dir); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_inline_entry); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_delete_inline_entry); +EXPORT_SYMBOL_FOR_EXT4_TEST(empty_inline_dir); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_destroy_inline_data); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inline_data_iomap); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inline_data_truncate); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_convert_inline_data); #endif diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 5fa293c9581ea1..9fe324cda5e669 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -2171,6 +2171,9 @@ int ext4_da_get_block_prep(struct inode *inode, sector_t iblock, sector_t invalid_block = ~((sector_t) 0xffff); int ret = 0; + KUNIT_STATIC_STUB_REDIRECT(ext4_da_get_block_prep, inode, iblock, bh, + create); + BUG_ON(create == 0); BUG_ON(bh->b_size != inode->i_sb->s_blocksize); @@ -8020,6 +8023,7 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf) } #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_get_block_prep); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_update_reserve_space); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_release_space); EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_mark_inode_dirty); From 97211e479963e7ad808bd3e1f8e08969037c8adc Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Thu, 5 Nov 2026 03:20:12 +0000 Subject: [PATCH 1559/2102] ext4: add KUnit tests for fs/ext4/fast_commit.c Add the ext4_fast_commit_test KUnit test suite in fs/ext4/fast_commit-test.c to comprehensively exercise fast commit tracking, snapshotting, TLV serialization, commit execution, and journal replay in fs/ext4/fast_commit.c without requiring a mounted block device: - Fast commit initialization and eligibility helpers (ext4_fc_init, ext4_fc_init_inode, ext4_fc_disabled, ext4_fc_eligible, ext4_fc_set_snap_err, and ext4_fc_snap_stats_update_max). - Ineligibility tracking (ext4_fc_mark_ineligible) with active handles, NULL handles with or without a running transaction, monotonic s_fc_ineligible_tid updates, and per-reason statistics counters. - Inode and logical range tracking (ext4_fc_track_inode and ext4_fc_track_range), covering directory skips, data-journalling and inline-data ineligibility, special inodes (< EXT4_FIRST_INO), same-TID bounding-interval range merging, cross-TID resets, EXT4_STATE_FC_COMMITTING to EXT4_STATE_FC_REQUEUE transitions, and FC_Q_MAIN vs. FC_Q_STAGING queue routing. - Dentry update tracking (ext4_fc_track_create, ext4_fc_track_link, and ext4_fc_track_unlink) and inode deletion cleanup (ext4_fc_del), including root dentry parent handling, EXT4_FC_TAG_CREAT removal, and concurrent wait-bit wakeups across EXT4_STATE_FC_FLUSHING_DATA and EXT4_STATE_FC_COMMITTING. - Fast commit buffer space reservation and TLV serialization (ext4_fc_reserve_space, ext4_fc_add_tlv, and ext4_fc_write_tail), including oversize rejection, block boundary EXT4_FC_TAG_PAD insertion and buffer submission, and EXT4_FC_TAG_TAIL padding and CRC32C calculation. - Inode and extent-status range snapshotting (ext4_fc_snapshot_inode, ext4_fc_count_snapshot_inodes, ext4_fc_alloc_snapshot_inodes, ext4_fc_snapshot_inodes, ext4_fc_write_inode, and ext4_fc_write_inode_data), including ext4_get_inode_loc_noio fallback, ES miss/delayed/unsupported status errors, inode and range capacity caps (-E2BIG), extent splitting past EXT_INIT_MAX_LEN (32768), and create-only dentry inode snapshotting. - Fast and full commit cleanup (ext4_fc_cleanup), EWMA commit time stats (ext4_fc_update_stats), and procfs stats output (ext4_fc_info_show). - Top-level commit execution and fallbacks (ext4_fc_commit) across already-committed TIDs, disabled fast commits, jbd2_fc_begin_commit failures, ineligible filesystems, data flush -EIO errors, snapshot -EAGAIN fallbacks, jbd2_fc_wait_bufs -EIO errors, and consecutive fast commits with external journal device cache flushes. - Recovery region exclusion and scan validation (ext4_fc_record_regions, ext4_fc_replay_check_excluded, ext4_fc_record_modified_inode, ext4_fc_value_len_isvalid, tag2str, and PASS_SCAN validation of missing HEAD, unexpected offset, unsupported features, wrong TID, bad tail CRC, and partial multi-commit logs). - Recovery replay of EXT4_FC_TAG_INODE (extent and inline-data inodes), EXT4_FC_TAG_CREAT (regular files and subdirectories), EXT4_FC_TAG_LINK (-EEXIST idempotency), and EXT4_FC_TAG_UNLINK (missing entries and rename-overwrite inode mismatches). - Recovery replay of EXT4_FC_TAG_ADD_RANGE and EXT4_FC_TAG_DEL_RANGE, error handling, and an end-to-end ext4_fc_commit() -> PASS_SCAN -> PASS_REPLAY round-trip. Export the tested fast commit entry points with EXPORT_SYMBOL_FOR_EXT4_TEST and add KUNIT_STATIC_STUB_REDIRECT hooks for ext4_fc_get_buf, ext4_fc_submit_bh, ext4_fc_issue_flush, ext4_get_inode_loc_noio, ext4_get_fc_inode_loc, ext4_mark_inode_used, ext4_mb_mark_bb, and ext4_es_lookup_extent. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 3 +- fs/ext4/ext4.h | 35 + fs/ext4/extents_status.c | 3 + fs/ext4/fast_commit-test.c | 2702 ++++++++++++++++++++++++++++++++++++ fs/ext4/fast_commit.c | 180 ++- fs/ext4/ialloc.c | 3 + fs/ext4/inode.c | 6 + fs/ext4/mballoc.c | 3 +- 8 files changed, 2928 insertions(+), 7 deletions(-) create mode 100644 fs/ext4/fast_commit-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 5a90bf5b28e3b0..7bd91839c3ce0c 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -17,7 +17,8 @@ ext4-$(CONFIG_EXT4_FS_SECURITY) += xattr_security.o ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ extents_status-test.o xattr-test.o \ - namei-test.o inline-test.o + namei-test.o inline-test.o \ + fast_commit-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index ae5edd8e8d4d64..ae773eb08895e7 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -3094,6 +3094,9 @@ extern int ext4_init_inode_table(struct super_block *sb, void ext4_end_bitmap_read(struct bio *bio); /* fast_commit.c */ +int ext4_fc_get_buf(journal_t *journal, struct buffer_head **bh); +void ext4_fc_submit_bh(struct super_block *sb, bool is_tail); +int ext4_fc_issue_flush(struct block_device *bdev); int ext4_fc_info_show(struct seq_file *seq, void *v); void ext4_fc_init(struct super_block *sb, journal_t *journal); void ext4_fc_init_inode(struct inode *inode); @@ -3120,6 +3123,38 @@ void ext4_fc_destroy_dentry_cache(void); int ext4_fc_record_regions(struct super_block *sb, int ino, ext4_lblk_t lblk, ext4_fsblk_t pblk, int len, int replay); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +void ext4_fc_set_snap_err_test(int *snap_err, int err); +bool ext4_fc_disabled_test(struct super_block *sb); +bool ext4_fc_eligible_test(struct super_block *sb); +void ext4_fc_snap_stats_update_max_test(atomic64_t *stat, u64 value); +void ext4_fc_wake_inode_state_test(struct inode *inode, int bit); +u8 *ext4_fc_reserve_space_test(struct super_block *sb, int len, u32 *crc); +int ext4_fc_write_tail_test(struct super_block *sb, u32 crc); +bool ext4_fc_add_tlv_test(struct super_block *sb, u16 tag, u16 len, u8 *val, + u32 *crc); +int ext4_fc_write_inode_test(struct inode *inode, u32 *crc); +int ext4_fc_write_inode_data_test(struct inode *inode, u32 *crc); +void ext4_fc_free_inode_snap_test(struct inode *inode); +int ext4_fc_snapshot_inode_test(struct inode *inode, + unsigned int nr_ranges_total, + unsigned int *nr_rangesp, int *snap_err); +unsigned int ext4_fc_count_snapshot_inodes_test(struct super_block *sb); +int ext4_fc_alloc_snapshot_inodes_test(struct super_block *sb, + struct inode ***inodesp, + unsigned int *nr_inodesp); +int ext4_fc_snapshot_inodes_test(journal_t *journal, struct inode **inodes, + unsigned int inodes_size, + unsigned int *nr_inodesp, + unsigned int *nr_rangesp, int *snap_err); +void ext4_fc_update_stats_test(struct super_block *sb, int status, + u64 commit_time, int nblks, tid_t commit_tid); +void ext4_fc_cleanup_test(journal_t *journal, int full, tid_t tid); +int ext4_fc_record_modified_inode_test(struct super_block *sb, int ino); +bool ext4_fc_value_len_isvalid_test(struct ext4_sb_info *sbi, int tag, int len); +int ext4_fc_replay_test(journal_t *journal, struct buffer_head *bh, + enum passtype pass, int off, tid_t expected_tid); +#endif /* mballoc.c */ extern const struct seq_operations ext4_mb_seq_groups_ops; diff --git a/fs/ext4/extents_status.c b/fs/ext4/extents_status.c index c86bf438b48c3d..b7fb8502f9d460 100644 --- a/fs/ext4/extents_status.c +++ b/fs/ext4/extents_status.c @@ -1099,6 +1099,9 @@ int ext4_es_lookup_extent(struct inode *inode, ext4_lblk_t lblk, struct rb_node *node; int found = 0; + KUNIT_STATIC_STUB_REDIRECT(ext4_es_lookup_extent, inode, lblk, + next_lblk, es, pseq); + if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) return 0; diff --git a/fs/ext4/fast_commit-test.c b/fs/ext4/fast_commit-test.c new file mode 100644 index 00000000000000..be416cb3653ee9 --- /dev/null +++ b/fs/ext4/fast_commit-test.c @@ -0,0 +1,2702 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 fast commit operations (fs/ext4/fast_commit.c) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "ext4_extents.h" +#include "extents_status.h" +#include "fast_commit.h" +#include "namei.h" + +#define TEST_BLK_SIZE 1024 +#define TEST_BLK_BITS 10 +#define TEST_INODE_SIZE 256 +#define TEST_EXTRA_ISIZE 32 +#define TEST_FIRST_PBLK 100 +#define TEST_MAX_BLOCKS 32 +#define TEST_MAX_LBLOCKS 16 +#define TEST_MAX_INODES 8 +#define TEST_MAX_FC_BUFS 16 +#define TEST_MAX_BB_MARKS 32 + +#define TEST_ROOT_INO EXT4_ROOT_INO +#define TEST_DIR_INO 12 +#define TEST_FILE1_INO 13 +#define TEST_FILE2_INO 14 +#define TEST_SUBDIR_INO 15 +#define TEST_CSUM_SEED 0x12345678U + +struct fc_mock_block { + bool in_use; + struct buffer_head bh; + char data[TEST_BLK_SIZE] __aligned(8); +}; + +struct fc_mock_inode_slot { + bool allocated; + struct ext4_inode_info ei; + struct jbd2_inode jinode; + struct buffer_head iloc_bh; + char raw_buf[TEST_BLK_SIZE] __aligned(8); + ext4_fsblk_t lblk_to_pblk[TEST_MAX_LBLOCKS]; +}; + +struct fc_bb_mark { + ext4_fsblk_t block; + int len; + bool state; +}; + +struct fc_test_ctx { + struct super_block *sb; + struct ext4_sb_info *sbi; + struct ext4_super_block es; + struct block_device bdev; + struct block_device ext_jdev; + struct address_space bd_mapping; + struct buffer_head sb_bh; + + journal_t journal; + transaction_t running_txn; + handle_t handle; + struct buffer_head *fc_wbuf[TEST_MAX_FC_BUFS]; + struct buffer_head fc_bhs[TEST_MAX_FC_BUFS]; + char fc_buf_data[TEST_MAX_FC_BUFS][TEST_BLK_SIZE] __aligned(8); + + struct fc_mock_inode_slot inodes[TEST_MAX_INODES]; + struct fc_mock_block blocks[TEST_MAX_BLOCKS]; + + /* Shrinker callbacks saved during init */ + unsigned long (*shrinker_count)(struct shrinker *shrink, + struct shrink_control *sc); + unsigned long (*shrinker_scan)(struct shrinker *shrink, + struct shrink_control *sc); + bool es_shrinker_inited; + + /* Fault injection and call tracking */ + int journal_mode; + int fail_get_inode_loc; + int fail_get_inode_loc_noio; + int fail_get_fc_inode_loc; + int fail_dirty_metadata; + int fail_dirty_metadata_on_call; + int dirty_metadata_calls; + bool fail_sync_dirty_buffer; + int fail_mark_inode_used; + int fail_iget; + int fail_iget_on_call; + unsigned long fail_iget_ino; + int iget_calls; + int fail_map_blocks; + int force_map_blocks_ret; + ext4_fsblk_t force_map_pblk; + unsigned int force_map_flags; + int fail_find_extent; + int fail_insert_extent; + int fail_fc_get_buf; + int fail_fc_get_buf_on_call; + int fc_get_buf_calls; + bool fail_fc_wait_bufs; + int submit_inode_data_err; + + unsigned int fc_submit_bh_calls; + unsigned int fc_submit_tail_calls; + unsigned int fc_flush_calls; + struct block_device *last_flushed_bdev; + unsigned int mark_inode_used_calls; + int last_marked_ino; + + struct fc_bb_mark bb_marks[TEST_MAX_BB_MARKS]; + unsigned int nr_bb_marks; + + /* Custom ES lookup stub override */ + bool use_custom_es_lookup; + struct extent_status custom_es; + int custom_es_ret; +}; + +static const struct super_operations fc_test_sops = {}; + +#ifdef CONFIG_QUOTA +static qsize_t *fc_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations fc_test_qops = { + .get_reserved_space = fc_test_get_reserved_space, +}; +#endif + +static unsigned long fc_dummy_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long fc_dummy_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +static int fc_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static int fc_set_anon(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static struct file_system_type fc_fs_type = { + .name = "fast_commit_test", + .init_fs_context = fc_init_fs_context, + .kill_sb = kill_anon_super, +}; + +/* --- Mock Inode, Block, and Dentry Helpers --- */ + +static struct fc_mock_inode_slot *find_slot_by_ino(struct fc_test_ctx *ctx, + unsigned long ino) +{ + int i; + + for (i = 0; i < TEST_MAX_INODES; i++) { + if (ctx->inodes[i].allocated && + ctx->inodes[i].ei.vfs_inode.i_ino == ino) + return &ctx->inodes[i]; + } + return NULL; +} + +static struct fc_mock_inode_slot *find_slot(struct fc_test_ctx *ctx, + struct inode *inode) +{ + return find_slot_by_ino(ctx, inode->i_ino); +} + +static struct inode *get_mock_inode(struct fc_test_ctx *ctx, unsigned long ino) +{ + struct fc_mock_inode_slot *slot = find_slot_by_ino(ctx, ino); + + return slot ? &slot->ei.vfs_inode : NULL; +} + +static struct fc_mock_block *get_mock_block(struct fc_test_ctx *ctx, + ext4_fsblk_t pblk) +{ + unsigned long idx; + + if (pblk < TEST_FIRST_PBLK) + return NULL; + idx = pblk - TEST_FIRST_PBLK; + if (idx >= TEST_MAX_BLOCKS) + return NULL; + return &ctx->blocks[idx]; +} + +static ext4_fsblk_t alloc_mock_pblk(struct fc_test_ctx *ctx) +{ + int i; + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + if (!ctx->blocks[i].in_use) { + ctx->blocks[i].in_use = true; + memset(ctx->blocks[i].data, 0, TEST_BLK_SIZE); + set_buffer_uptodate(&ctx->blocks[i].bh); + clear_buffer_verified(&ctx->blocks[i].bh); + return TEST_FIRST_PBLK + i; + } + } + return 0; +} + +static void init_mock_inode_slot(struct fc_test_ctx *ctx, + struct fc_mock_inode_slot *slot, + unsigned long ino, umode_t mode) +{ + struct inode *inode = &slot->ei.vfs_inode; + struct ext4_inode *raw_inode; + + memset(slot, 0, sizeof(*slot)); + slot->allocated = true; + + inode->i_sb = ctx->sb; + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = TEST_BLK_BITS; + inode->i_flags |= S_NOQUOTA; + inode->i_mapping = &inode->i_data; + set_nlink(inode, S_ISDIR(mode) ? 2 : 1); + atomic_set(&inode->i_count, 1); + + spin_lock_init(&inode->i_lock); + i_size_ordered_init(inode); + init_rwsem(&inode->i_rwsem); + init_rwsem(&inode->i_data.invalidate_lock); + INIT_LIST_HEAD(&inode->i_io_list); + INIT_LIST_HEAD(&inode->i_wb_list); + INIT_LIST_HEAD(&inode->i_lru); + INIT_HLIST_NODE(&inode->i_hash); + inode_state_set_raw(inode, I_DIRTY); + + init_rwsem(&slot->ei.xattr_sem); + init_rwsem(&slot->ei.i_data_sem); + INIT_LIST_HEAD(&slot->ei.i_orphan); + spin_lock_init(&slot->ei.i_fc_lock); + spin_lock_init(&slot->ei.i_raw_lock); + spin_lock_init(&slot->ei.i_block_reservation_lock); + ext4_es_init_tree(&slot->ei.i_es_tree); + ext4_init_pending_tree(&slot->ei.i_pending_tree); + rwlock_init(&slot->ei.i_es_lock); + INIT_LIST_HEAD(&slot->ei.i_es_list); + ext4_fc_init_inode(inode); + + slot->ei.i_extra_isize = TEST_EXTRA_ISIZE; + slot->ei.i_csum_seed = TEST_CSUM_SEED ^ (u32)ino; + slot->ei.i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + + jbd2_journal_init_jbd_inode(&slot->jinode, inode); + slot->ei.jinode = &slot->jinode; + + slot->iloc_bh.b_data = slot->raw_buf; + slot->iloc_bh.b_size = TEST_BLK_SIZE; + slot->iloc_bh.b_blocknr = 10 + ino; + slot->iloc_bh.b_bdev = &ctx->bdev; + atomic_set(&slot->iloc_bh.b_count, 1); + set_buffer_uptodate(&slot->iloc_bh); + set_buffer_mapped(&slot->iloc_bh); + + raw_inode = (struct ext4_inode *)slot->raw_buf; + raw_inode->i_mode = cpu_to_le16(mode); + raw_inode->i_links_count = cpu_to_le16(inode->i_nlink); + raw_inode->i_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); + if (S_ISREG(mode)) { + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_ext_tree_init(NULL, inode); + raw_inode->i_flags = cpu_to_le32(EXT4_EXTENTS_FL); + memcpy(raw_inode->i_block, slot->ei.i_data, + sizeof(raw_inode->i_block)); + } +} + +static void init_mock_dentry(struct dentry *dentry, struct dentry *parent, + const char *name, struct inode *inode, + struct super_block *sb) +{ + memset(dentry, 0, sizeof(*dentry)); + spin_lock_init(&dentry->d_lock); + seqcount_spinlock_init(&dentry->d_seq, &dentry->d_lock); + INIT_HLIST_NODE(&dentry->d_sib); + INIT_HLIST_HEAD(&dentry->d_children); + INIT_HLIST_BL_NODE(&dentry->d_hash); + dentry->d_parent = parent ? parent : dentry; + dentry->d_sb = sb; + strscpy((char *)dentry->d_shortname.string, name, + sizeof(dentry->d_shortname.string)); + dentry->__d_name.name = dentry->d_shortname.string; + dentry->__d_name.len = strlen(name); + if (inode) { + dentry->d_inode = inode; + dentry->d_flags = S_ISDIR(inode->i_mode) ? + DCACHE_DIRECTORY_TYPE : DCACHE_REGULAR_TYPE; + } else { + dentry->d_flags = DCACHE_MISS_TYPE; + } +} + +static void sync_inode_to_raw(struct fc_mock_inode_slot *slot) +{ + struct inode *inode = &slot->ei.vfs_inode; + struct ext4_inode *raw = (struct ext4_inode *)slot->raw_buf; + + raw->i_mode = cpu_to_le16(inode->i_mode); + raw->i_links_count = cpu_to_le16(inode->i_nlink); + raw->i_size_lo = cpu_to_le32(lower_32_bits(inode->i_size)); + raw->i_size_high = cpu_to_le32(upper_32_bits(inode->i_size)); + raw->i_flags = cpu_to_le32(slot->ei.i_flags); + raw->i_generation = cpu_to_le32(inode->i_generation); + raw->i_extra_isize = cpu_to_le16(slot->ei.i_extra_isize); + memcpy(raw->i_block, slot->ei.i_data, sizeof(raw->i_block)); +} + +/* --- KUnit Static Stubs --- */ + +static int stub_inode_journal_mode(struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + + return ctx->journal_mode; +} + +static void stub_da_update_reserve_space(struct inode *inode, int used, + int quota_claim) +{ +} + +static void stub_da_release_space(struct inode *inode, int to_free) +{ +} + +static int stub_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + + if (ctx->fail_get_inode_loc) + return ctx->fail_get_inode_loc; + + slot = find_slot(ctx, inode); + if (!slot) + return -ENOENT; + + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int stub_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + + if (ctx->fail_get_inode_loc_noio) + return ctx->fail_get_inode_loc_noio; + + slot = find_slot(ctx, inode); + if (!slot) + return -EAGAIN; + + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int stub_get_fc_inode_loc(struct super_block *sb, unsigned long ino, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + + if (ctx->fail_get_fc_inode_loc) + return ctx->fail_get_fc_inode_loc; + + slot = find_slot_by_ino(ctx, ino); + if (!slot) + return -ENOENT; + + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int stub_handle_dirty_metadata(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + + ctx->dirty_metadata_calls++; + if (ctx->fail_dirty_metadata_on_call > 0 && + ctx->dirty_metadata_calls == ctx->fail_dirty_metadata_on_call) + return ctx->fail_dirty_metadata; + if (ctx->fail_dirty_metadata_on_call == 0 && ctx->fail_dirty_metadata) + return ctx->fail_dirty_metadata; + + if (ctx->fail_sync_dirty_buffer) { + /* + * __sync_dirty_buffer() checks test_clear_buffer_dirty(bh) + * and returns -EIO without submitting a bio if !buffer_mapped. + */ + set_buffer_dirty(bh); + clear_buffer_mapped(bh); + } else { + clear_buffer_dirty(bh); + set_buffer_mapped(bh); + } + return 0; +} + +static int stub_mark_iloc_dirty(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot = find_slot(ctx, inode); + + if (slot) + sync_inode_to_raw(slot); + brelse(iloc->bh); + return 0; +} + +static int stub_mark_inode_dirty(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot = find_slot(ctx, inode); + + if (slot) + sync_inode_to_raw(slot); + return 0; +} + +static int stub_ext_dirty(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct ext4_ext_path *path) +{ + return 0; +} + +static void stub_free_blocks(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ +} + +static int stub_orphan_add(handle_t *handle, struct inode *inode) +{ + return 0; +} + +static int stub_orphan_del(handle_t *handle, struct inode *inode) +{ + return 0; +} + +static int stub_mark_inode_used(struct super_block *sb, int ino) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + + ctx->mark_inode_used_calls++; + ctx->last_marked_ino = ino; + if (ctx->fail_mark_inode_used) + return ctx->fail_mark_inode_used; + return 0; +} + +static void stub_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block, + int len, bool state) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + + if (ctx->nr_bb_marks < TEST_MAX_BB_MARKS) { + ctx->bb_marks[ctx->nr_bb_marks].block = block; + ctx->bb_marks[ctx->nr_bb_marks].len = len; + ctx->bb_marks[ctx->nr_bb_marks].state = state; + } + ctx->nr_bb_marks++; +} + +static struct inode *stub_ext4_iget(struct super_block *sb, unsigned long ino, + ext4_iget_flags flags, + const char *function, unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + struct inode *inode; + struct ext4_inode *raw; + + ctx->iget_calls++; + if (ctx->fail_iget_on_call > 0 && + ctx->iget_calls == ctx->fail_iget_on_call) + return ERR_PTR(ctx->fail_iget ? ctx->fail_iget : -ENOENT); + if (ctx->fail_iget_ino && ino == ctx->fail_iget_ino) + return ERR_PTR(ctx->fail_iget ? ctx->fail_iget : -ENOENT); + if (ctx->fail_iget && !ctx->fail_iget_on_call && !ctx->fail_iget_ino) + return ERR_PTR(ctx->fail_iget); + + slot = find_slot_by_ino(ctx, ino); + if (!slot) + return ERR_PTR(-ENOENT); + + inode = &slot->ei.vfs_inode; + raw = (struct ext4_inode *)slot->raw_buf; + if (raw->i_mode) { + inode->i_mode = le16_to_cpu(raw->i_mode); + set_nlink(inode, le16_to_cpu(raw->i_links_count)); + inode->i_generation = le32_to_cpu(raw->i_generation); + i_size_write(inode, ext4_isize(sb, raw)); + slot->ei.i_flags = le32_to_cpu(raw->i_flags); + if (slot->ei.i_flags & EXT4_INLINE_DATA_FL) { + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + memcpy(slot->ei.i_data, raw->i_block, + sizeof(raw->i_block)); + } else if (slot->ei.i_flags & EXT4_EXTENTS_FL) { + struct ext4_extent_header *eh = + (struct ext4_extent_header *)raw->i_block; + struct ext4_extent_header *ieh = + ext_inode_hdr(&slot->ei.vfs_inode); + + if (eh->eh_magic == EXT4_EXT_MAGIC && + ieh->eh_entries == 0) + memcpy(slot->ei.i_data, raw->i_block, + sizeof(raw->i_block)); + } + } + + atomic_inc(&inode->i_count); + return inode; +} + +static int stub_map_blocks(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + ext4_fsblk_t pblk; + + if (ctx->fail_map_blocks) + return ctx->fail_map_blocks; + if (ctx->force_map_blocks_ret) { + map->m_pblk = ctx->force_map_pblk; + map->m_flags = ctx->force_map_flags; + if (ctx->force_map_blocks_ret > 0) + map->m_len = ctx->force_map_blocks_ret; + return ctx->force_map_blocks_ret; + } + + if (S_ISREG(inode->i_mode) && + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { + kunit_deactivate_static_stub(test, ext4_map_blocks); + int ret = ext4_ext_map_blocks(handle, inode, map, flags); + + kunit_activate_static_stub(test, ext4_map_blocks, + stub_map_blocks); + return ret; + } + + slot = find_slot(ctx, inode); + if (!slot || map->m_lblk >= TEST_MAX_LBLOCKS) + return -EFSCORRUPTED; + + pblk = slot->lblk_to_pblk[map->m_lblk]; + if (pblk) { + map->m_pblk = pblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED; + return 1; + } + + if (!(flags & EXT4_GET_BLOCKS_CREATE)) { + map->m_pblk = 0; + map->m_flags = 0; + return 0; + } + + pblk = alloc_mock_pblk(ctx); + if (!pblk) + return -ENOSPC; + + slot->lblk_to_pblk[map->m_lblk] = pblk; + map->m_pblk = pblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED | EXT4_MAP_NEW; + return 1; +} + +static struct buffer_head *stub_ext4_getblk(handle_t *handle, + struct inode *inode, + ext4_lblk_t block, int map_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + struct fc_mock_block *blk; + ext4_fsblk_t pblk; + + slot = find_slot(ctx, inode); + if (!slot || block >= TEST_MAX_LBLOCKS) + return ERR_PTR(-EFSCORRUPTED); + + pblk = slot->lblk_to_pblk[block]; + if (!pblk) { + if (!(map_flags & EXT4_GET_BLOCKS_CREATE)) + return NULL; + pblk = alloc_mock_pblk(ctx); + if (!pblk) + return ERR_PTR(-ENOSPC); + slot->lblk_to_pblk[block] = pblk; + } + + blk = get_mock_block(ctx, pblk); + if (!blk) + return ERR_PTR(-EFSCORRUPTED); + + get_bh(&blk->bh); + return &blk->bh; +} + +static struct ext4_ext_path *stub_find_extent(struct inode *inode, + ext4_lblk_t block, + struct ext4_ext_path *path, + int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct ext4_ext_path *ret; + + if (ctx->fail_find_extent) + return ERR_PTR(ctx->fail_find_extent); + + kunit_deactivate_static_stub(test, ext4_find_extent); + ret = ext4_find_extent(inode, block, path, flags); + kunit_activate_static_stub(test, ext4_find_extent, stub_find_extent); + return ret; +} + +static struct ext4_ext_path *stub_insert_extent(handle_t *handle, + struct inode *inode, + struct ext4_ext_path *path, + struct ext4_extent *newext, + int gb_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct ext4_ext_path *ret; + + if (ctx->fail_insert_extent) { + ext4_free_ext_path(path); + return ERR_PTR(ctx->fail_insert_extent); + } + + kunit_deactivate_static_stub(test, ext4_ext_insert_extent); + ret = ext4_ext_insert_extent(handle, inode, path, newext, gb_flags); + kunit_activate_static_stub(test, ext4_ext_insert_extent, + stub_insert_extent); + return ret; +} + +static int stub_es_lookup_extent(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t *next_lblk, + struct extent_status *es, u64 *pseq) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + int ret; + + if (ctx->use_custom_es_lookup) { + *es = ctx->custom_es; + return ctx->custom_es_ret; + } + + kunit_deactivate_static_stub(test, ext4_es_lookup_extent); + ret = ext4_es_lookup_extent(inode, lblk, next_lblk, es, pseq); + kunit_activate_static_stub(test, ext4_es_lookup_extent, + stub_es_lookup_extent); + return ret; +} + +static int stub_fc_get_buf(journal_t *journal, struct buffer_head **bh_out) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct buffer_head *bh; + int fc_off; + + *bh_out = NULL; + ctx->fc_get_buf_calls++; + if (ctx->fail_fc_get_buf_on_call > 0 && + ctx->fc_get_buf_calls == ctx->fail_fc_get_buf_on_call) + return ctx->fail_fc_get_buf ? ctx->fail_fc_get_buf : -ENOSPC; + if (ctx->fail_fc_get_buf && !ctx->fail_fc_get_buf_on_call) + return ctx->fail_fc_get_buf; + + if (journal->j_fc_off + journal->j_fc_first >= journal->j_fc_last) + return -EINVAL; + + fc_off = journal->j_fc_off; + if (fc_off >= TEST_MAX_FC_BUFS) + return -ENOSPC; + + journal->j_fc_off++; + bh = &ctx->fc_bhs[fc_off]; + memset(bh->b_data, 0, journal->j_blocksize); + set_buffer_uptodate(bh); + clear_buffer_write_io_error(bh); + get_bh(bh); + journal->j_fc_wbuf[fc_off] = bh; + *bh_out = bh; + return 0; +} + +static void stub_fc_submit_bh(struct super_block *sb, bool is_tail) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct buffer_head *bh = EXT4_SB(sb)->s_fc_bh; + + ctx->fc_submit_bh_calls++; + if (is_tail) + ctx->fc_submit_tail_calls++; + set_buffer_dirty(bh); + if (ctx->fail_fc_wait_bufs) { + clear_buffer_uptodate(bh); + set_buffer_write_io_error(bh); + } else { + set_buffer_uptodate(bh); + clear_buffer_write_io_error(bh); + } + EXT4_SB(sb)->s_fc_bh = NULL; +} + +static int stub_fc_issue_flush(struct block_device *bdev) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + + ctx->fc_flush_calls++; + ctx->last_flushed_bdev = bdev; + return 0; +} + +static int mock_submit_inode_data_buffers(struct jbd2_inode *jinode) +{ + struct inode *inode = jinode->i_vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct fc_test_ctx *ctx = container_of(sbi->s_es, struct fc_test_ctx, es); + + return ctx->submit_inode_data_err; +} + +/* + * Wrapper for journal->j_fc_cleanup_callback used during ext4_fc_commit() tests. + * Calls the real ext4_fc_cleanup() and, on fallback commits (tid != 0), marks + * the mock transaction as committed so jbd2_complete_transaction() returns + * immediately without waiting for a kjournald2 thread. + */ +static void test_j_fc_cleanup_cb(journal_t *journal, int full, tid_t tid) +{ + ext4_fc_cleanup_test(journal, full, tid); + if (!full && tid != 0) { + write_lock(&journal->j_state_lock); + journal->j_commit_request = tid; + journal->j_commit_sequence = tid; + journal->j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + write_unlock(&journal->j_state_lock); + } +} + +/* --- Suite Setup & Teardown --- */ + +static void fc_cleanup_all(void *priv) +{ + struct fc_test_ctx *ctx = priv; + int i; + + ctx->sbi->s_mount_state &= ~EXT4_FC_REPLAY; + if (ctx->journal.j_private) { + /* + * Run cleanup twice: the first pass frees FC_Q_MAIN and + * splices FC_Q_STAGING onto FC_Q_MAIN; the second frees the + * spliced staging entries. + */ + ext4_fc_cleanup_test(&ctx->journal, 1, 999999); + ext4_fc_cleanup_test(&ctx->journal, 1, 999999); + } + ext4_fc_replay_cleanup(ctx->sb); + + for (i = 0; i < TEST_MAX_INODES; i++) { + if (!ctx->inodes[i].allocated) + continue; + down_write(&ctx->inodes[i].ei.i_data_sem); + ext4_es_remove_extent(&ctx->inodes[i].ei.vfs_inode, 0, + EXT_MAX_BLOCKS); + up_write(&ctx->inodes[i].ei.i_data_sem); + ext4_fc_free_inode_snap_test(&ctx->inodes[i].ei.vfs_inode); + } + + if (ctx->es_shrinker_inited) { + ext4_es_unregister_shrinker(ctx->sbi); + ext4_es_destroy_stats(ctx->sbi); + } + deactivate_super(ctx->sb); +} + +static int fast_commit_test_init(struct kunit *test) +{ + static struct lock_class_key fc_test_commit_key; + struct fc_test_ctx *ctx; + struct ext4_sb_info *sbi; + struct super_block *sb; + struct fs_context *fc; + int i, err; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); + + sbi = kunit_kzalloc(test, sizeof(*sbi), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, sbi); + + fc = fs_context_for_mount(&fc_fs_type, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fc)); + sb = sget_fc(fc, NULL, fc_set_anon); + put_fs_context(fc); + KUNIT_ASSERT_FALSE(test, IS_ERR(sb)); + + ctx->sb = sb; + ctx->sbi = sbi; + test->priv = ctx; + + /* Superblock and ext4_sb_info setup */ + sb->s_blocksize = TEST_BLK_SIZE; + sb->s_blocksize_bits = TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_bdi = &noop_backing_dev_info; + sb->s_fs_info = sbi; + sb->s_op = &fc_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &fc_test_qops; +#endif + strscpy(sb->s_id, "ext4-fc-test", sizeof(sb->s_id)); + + ctx->bdev.bd_mapping = &ctx->bd_mapping; + sb->s_bdev = &ctx->bdev; + + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(TEST_INODE_SIZE); + ctx->es.s_inodes_count = cpu_to_le32(1024); + ctx->es.s_first_data_block = cpu_to_le32(1); + ctx->es.s_feature_compat = + cpu_to_le32(EXT4_FEATURE_COMPAT_DIR_INDEX | + EXT4_FEATURE_COMPAT_FAST_COMMIT); + ctx->es.s_feature_incompat = + cpu_to_le32(EXT4_FEATURE_INCOMPAT_FILETYPE | + EXT4_FEATURE_INCOMPAT_EXTENTS | + EXT4_FEATURE_INCOMPAT_INLINE_DATA); + ctx->es.s_feature_ro_compat = + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + + sbi->s_sb = sb; + sbi->s_es = &ctx->es; + sbi->s_sbh = &ctx->sb_bh; + sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO; + sbi->s_inode_size = TEST_INODE_SIZE; + sbi->s_want_extra_isize = TEST_EXTRA_ISIZE; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE; + sbi->s_blocks_per_group = 32768; + sbi->s_inodes_per_group = 1024; + sbi->s_inodes_per_block = TEST_BLK_SIZE / TEST_INODE_SIZE; + sbi->s_csum_seed = TEST_CSUM_SEED; + sbi->s_cluster_bits = 0; + sbi->s_cluster_ratio = 1; + set_opt(sb, ERRORS_CONT); + set_opt2(sb, JOURNAL_FAST_COMMIT); + + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + atomic_set(&sbi->s_fc_subtid, 0); + INIT_LIST_HEAD(&sbi->s_orphan); + mutex_init(&sbi->s_orphan_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + up_write(&sb->s_umount); + + err = kunit_add_action_or_reset(test, fc_cleanup_all, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + err = ext4_es_register_shrinker(sbi); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->es_shrinker_inited = true; + ctx->shrinker_count = sbi->s_es_shrinker->count_objects; + ctx->shrinker_scan = sbi->s_es_shrinker->scan_objects; + WRITE_ONCE(sbi->s_es_shrinker->count_objects, fc_dummy_shrinker_count); + WRITE_ONCE(sbi->s_es_shrinker->scan_objects, fc_dummy_shrinker_scan); + + /* Mock journal, running transaction, and handle setup */ + rwlock_init(&ctx->journal.j_state_lock); + spin_lock_init(&ctx->journal.j_list_lock); + mutex_init(&ctx->journal.j_barrier); + lockdep_init_map(&ctx->journal.j_trans_commit_map, "jbd2_handle", + &fc_test_commit_key, 0); + init_waitqueue_head(&ctx->journal.j_wait_transaction_locked); + init_waitqueue_head(&ctx->journal.j_wait_done_commit); + init_waitqueue_head(&ctx->journal.j_wait_commit); + init_waitqueue_head(&ctx->journal.j_wait_updates); + init_waitqueue_head(&ctx->journal.j_wait_reserved); + init_waitqueue_head(&ctx->journal.j_fc_wait); + atomic_set(&ctx->journal.j_reserved_credits, 0); + ctx->journal.j_private = sb; + ctx->journal.j_blocksize = TEST_BLK_SIZE; + ctx->journal.j_dev = &ctx->bdev; + ctx->journal.j_fs_dev = &ctx->bdev; + ctx->journal.j_flags = JBD2_BARRIER; + ctx->journal.j_task = current; + ctx->journal.j_fc_first = 100; + ctx->journal.j_fc_last = 100 + TEST_MAX_FC_BUFS; + ctx->journal.j_fc_off = 0; + ctx->journal.j_fc_wbuf = ctx->fc_wbuf; + ctx->journal.j_stats.ts_tid = 1; + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->journal.j_submit_inode_data_buffers = + mock_submit_inode_data_buffers; + + ctx->running_txn.t_tid = 10; + ctx->running_txn.t_state = T_RUNNING; + atomic_set(&ctx->running_txn.t_updates, 0); + ctx->journal.j_running_transaction = &ctx->running_txn; + ctx->handle.h_transaction = &ctx->running_txn; + + sbi->s_journal = &ctx->journal; + ext4_fc_init(sb, &ctx->journal); + ctx->journal.j_fc_cleanup_callback = test_j_fc_cleanup_cb; + + for (i = 0; i < TEST_MAX_FC_BUFS; i++) { + struct buffer_head *bh = &ctx->fc_bhs[i]; + + bh->b_data = ctx->fc_buf_data[i]; + bh->b_size = TEST_BLK_SIZE; + bh->b_blocknr = 500 + i; + bh->b_bdev = &ctx->bdev; + atomic_set(&bh->b_count, 1); + set_buffer_uptodate(bh); + set_buffer_mapped(bh); + } + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + struct buffer_head *bh = &ctx->blocks[i].bh; + + bh->b_data = ctx->blocks[i].data; + bh->b_size = TEST_BLK_SIZE; + bh->b_blocknr = TEST_FIRST_PBLK + i; + bh->b_bdev = &ctx->bdev; + atomic_set(&bh->b_count, 1); + set_buffer_uptodate(bh); + set_buffer_mapped(bh); + } + + ctx->journal_mode = EXT4_INODE_ORDERED_DATA_MODE; + + kunit_activate_static_stub(test, ext4_inode_journal_mode, + stub_inode_journal_mode); + kunit_activate_static_stub(test, ext4_da_update_reserve_space, + stub_da_update_reserve_space); + kunit_activate_static_stub(test, ext4_da_release_space, + stub_da_release_space); + kunit_activate_static_stub(test, ext4_get_inode_loc, + stub_get_inode_loc); + kunit_activate_static_stub(test, ext4_get_inode_loc_noio, + stub_get_inode_loc_noio); + kunit_activate_static_stub(test, ext4_get_fc_inode_loc, + stub_get_fc_inode_loc); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + stub_handle_dirty_metadata); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + stub_mark_iloc_dirty); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + stub_mark_inode_dirty); + kunit_activate_static_stub(test, __ext4_ext_dirty, + stub_ext_dirty); + kunit_activate_static_stub(test, ext4_free_blocks, + stub_free_blocks); + kunit_activate_static_stub(test, ext4_orphan_add, + stub_orphan_add); + kunit_activate_static_stub(test, ext4_orphan_del, + stub_orphan_del); + kunit_activate_static_stub(test, ext4_mark_inode_used, + stub_mark_inode_used); + kunit_activate_static_stub(test, ext4_mb_mark_bb, + stub_mb_mark_bb); + kunit_activate_static_stub(test, __ext4_iget, + stub_ext4_iget); + kunit_activate_static_stub(test, ext4_map_blocks, + stub_map_blocks); + kunit_activate_static_stub(test, ext4_getblk, + stub_ext4_getblk); + kunit_activate_static_stub(test, ext4_find_extent, + stub_find_extent); + kunit_activate_static_stub(test, ext4_ext_insert_extent, + stub_insert_extent); + kunit_activate_static_stub(test, ext4_es_lookup_extent, + stub_es_lookup_extent); + kunit_activate_static_stub(test, ext4_fc_get_buf, + stub_fc_get_buf); + kunit_activate_static_stub(test, ext4_fc_submit_bh, + stub_fc_submit_bh); + kunit_activate_static_stub(test, ext4_fc_issue_flush, + stub_fc_issue_flush); + + init_mock_inode_slot(ctx, &ctx->inodes[0], TEST_ROOT_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[1], TEST_DIR_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[2], TEST_FILE1_INO, + S_IFREG | 0644); + init_mock_inode_slot(ctx, &ctx->inodes[3], TEST_FILE2_INO, + S_IFREG | 0644); + init_mock_inode_slot(ctx, &ctx->inodes[4], TEST_SUBDIR_INO, + S_IFDIR | 0755); + + return 0; +} + +/* ========================================================================= + * 1. Initialization, Eligibility, and Snapshot Stat Helpers + * ========================================================================= + */ + +static void test_fc_init_and_eligibility(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode = get_mock_inode(ctx, TEST_FILE1_INO); + struct ext4_inode_info *ei = EXT4_I(inode); + journal_t *tmp_journal; + atomic64_t max_stat = ATOMIC64_INIT(0); + int snap_err = EXT4_FC_SNAP_ERR_NONE; + + tmp_journal = kunit_kzalloc(test, sizeof(*tmp_journal), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, tmp_journal); + + /* + * 1) ext4_fc_init sets j_fc_replay_callback unconditionally, but sets + * j_fc_cleanup_callback only when JOURNAL_FAST_COMMIT is enabled. + */ + clear_opt2(sb, JOURNAL_FAST_COMMIT); + ext4_fc_init(sb, tmp_journal); + KUNIT_EXPECT_NOT_NULL(test, tmp_journal->j_fc_replay_callback); + KUNIT_EXPECT_NULL(test, tmp_journal->j_fc_cleanup_callback); + + set_opt2(sb, JOURNAL_FAST_COMMIT); + ext4_fc_init(sb, tmp_journal); + KUNIT_EXPECT_NOT_NULL(test, tmp_journal->j_fc_replay_callback); + KUNIT_EXPECT_NOT_NULL(test, tmp_journal->j_fc_cleanup_callback); + + /* 2) ext4_fc_init_inode clears state and resets ranges */ + ei->i_fc_lblk_start = 42; + ei->i_fc_lblk_len = 10; + ext4_set_inode_state(inode, EXT4_STATE_FC_COMMITTING); + ext4_set_inode_state(inode, EXT4_STATE_FC_REQUEUE); + ext4_fc_init_inode(inode); + KUNIT_EXPECT_EQ(test, ei->i_fc_lblk_start, 0U); + KUNIT_EXPECT_EQ(test, ei->i_fc_lblk_len, 0U); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, EXT4_STATE_FC_COMMITTING)); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, EXT4_STATE_FC_REQUEUE)); + KUNIT_EXPECT_TRUE(test, list_empty(&ei->i_fc_list)); + KUNIT_EXPECT_TRUE(test, list_empty(&ei->i_fc_dilist)); + KUNIT_EXPECT_NULL(test, ei->i_fc_snap); + + /* 3) ext4_fc_disabled and ext4_fc_eligible transitions */ + KUNIT_EXPECT_FALSE(test, ext4_fc_disabled_test(sb)); + KUNIT_EXPECT_TRUE(test, ext4_fc_eligible_test(sb)); + + ctx->sbi->s_mount_state |= EXT4_FC_REPLAY; + KUNIT_EXPECT_TRUE(test, ext4_fc_disabled_test(sb)); + KUNIT_EXPECT_FALSE(test, ext4_fc_eligible_test(sb)); + ctx->sbi->s_mount_state &= ~EXT4_FC_REPLAY; + + ext4_set_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + KUNIT_EXPECT_FALSE(test, ext4_fc_disabled_test(sb)); + KUNIT_EXPECT_FALSE(test, ext4_fc_eligible_test(sb)); + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + + clear_opt2(sb, JOURNAL_FAST_COMMIT); + KUNIT_EXPECT_TRUE(test, ext4_fc_disabled_test(sb)); + KUNIT_EXPECT_FALSE(test, ext4_fc_eligible_test(sb)); + set_opt2(sb, JOURNAL_FAST_COMMIT); + + /* 4) ext4_fc_set_snap_err preserves first error */ + ext4_fc_set_snap_err_test(&snap_err, EXT4_FC_SNAP_ERR_ES_MISS); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_ES_MISS); + ext4_fc_set_snap_err_test(&snap_err, EXT4_FC_SNAP_ERR_NOMEM); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_ES_MISS); + + /* 5) ext4_fc_snap_stats_update_max monotonically updates max */ + ext4_fc_snap_stats_update_max_test(&max_stat, 100); + KUNIT_EXPECT_EQ(test, atomic64_read(&max_stat), 100LL); + ext4_fc_snap_stats_update_max_test(&max_stat, 50); + KUNIT_EXPECT_EQ(test, atomic64_read(&max_stat), 100LL); + ext4_fc_snap_stats_update_max_test(&max_stat, 250); + KUNIT_EXPECT_EQ(test, atomic64_read(&max_stat), 250LL); +} + +/* ========================================================================= + * 2. Ineligibility Marking (ext4_fc_mark_ineligible) + * ========================================================================= + */ + +static void test_fc_mark_ineligible(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + + /* 1) No-op when fast commit is disabled */ + clear_opt2(sb, JOURNAL_FAST_COMMIT); + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_XATTR, &ctx->handle); + KUNIT_EXPECT_FALSE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_XATTR], + 0U); + set_opt2(sb, JOURNAL_FAST_COMMIT); + + /* 2) Valid handle records t_tid and sets EXT4_MF_FC_INELIGIBLE */ + ctx->running_txn.t_tid = 10; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_XATTR, &ctx->handle); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 10U); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_XATTR], + 1U); + + /* 3) Higher TID advances s_fc_ineligible_tid; lower TID does not */ + ctx->running_txn.t_tid = 15; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_RESIZE, &ctx->handle); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 15U); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_RESIZE], + 1U); + + ctx->running_txn.t_tid = 12; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_RESIZE, &ctx->handle); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 15U); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_RESIZE], + 2U); + + /* 4) NULL handle uses journal->j_running_transaction when present */ + ctx->running_txn.t_tid = 20; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_NOMEM, NULL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 20U); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_NOMEM], + 1U); + + /* 5) NULL handle with no running transaction sets flag without tid update */ + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + sbi->s_fc_ineligible_tid = 0; + ctx->journal.j_running_transaction = NULL; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_RENAME_DIR, NULL); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 0U); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_RENAME_DIR], + 1U); + + ctx->journal.j_running_transaction = &ctx->running_txn; + ctx->running_txn.t_tid = 10; + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); +} + +/* ========================================================================= + * 3. Inode and Logical Range Tracking + * ========================================================================= + */ + +static void test_fc_track_inode_and_range(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct ext4_inode_info *ei2 = EXT4_I(file2); + + /* 1) Directory inodes are ignored by track_inode and track_range */ + ext4_fc_track_inode(&ctx->handle, dir); + ext4_fc_track_range(&ctx->handle, dir, 0, 5); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(dir)->i_fc_list)); + + /* 2) Data journalling inode marks fs ineligible */ + ctx->journal_mode = EXT4_INODE_JOURNAL_DATA_MODE; + ext4_fc_track_inode(&ctx->handle, file1); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_INODE_JOURNAL_DATA], + 1U); + KUNIT_EXPECT_TRUE(test, list_empty(&ei1->i_fc_list)); + ctx->journal_mode = EXT4_INODE_ORDERED_DATA_MODE; + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + sbi->s_fc_ineligible_tid = 0; + + /* 3) Inline data inode marks fs ineligible on track_range */ + ext4_set_inode_flag(file1, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(file1, EXT4_STATE_MAY_INLINE_DATA); + ei1->i_inline_off = 164; + ext4_fc_track_range(&ctx->handle, file1, 0, 1); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_XATTR], + 1U); + ext4_clear_inode_flag(file1, EXT4_INODE_INLINE_DATA); + ext4_clear_inode_state(file1, EXT4_STATE_MAY_INLINE_DATA); + ei1->i_inline_off = 0; + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + sbi->s_fc_ineligible_tid = 0; + + /* 4) Special inode (< EXT4_FIRST_INO) does not record range */ + file1->i_ino = EXT4_ROOT_INO; + ext4_fc_track_range(&ctx->handle, file1, 5, 10); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 0U); + list_del_init(&ei1->i_fc_list); + file1->i_ino = TEST_FILE1_INO; + ei1->i_sync_tid = 0; + + /* + * 5) Range tracking within the same TID merges disjoint and overlapping + * ranges into their bounding interval, and subsequent track_inode + * in the same TID preserves the range. + */ + ctx->running_txn.t_tid = 10; + ext4_fc_track_inode(&ctx->handle, file1); + KUNIT_EXPECT_EQ(test, ei1->i_sync_tid, 10U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 0U); + KUNIT_EXPECT_FALSE(test, list_empty(&ei1->i_fc_list)); + + /* Initial range [10, 20] -> start=10, len=11 */ + ext4_fc_track_range(&ctx->handle, file1, 10, 20); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 10U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 11U); + + /* Expand right [25, 30] -> [10, 30], start=10, len=21 */ + ext4_fc_track_range(&ctx->handle, file1, 25, 30); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 10U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 21U); + + /* Expand left [4, 8] -> [4, 30], start=4, len=27 */ + ext4_fc_track_range(&ctx->handle, file1, 4, 8); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 4U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 27U); + + /* Contained sub-range [12, 18] -> unchanged [4, 30] */ + ext4_fc_track_range(&ctx->handle, file1, 12, 18); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 4U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 27U); + + /* Calling track_inode again in same TID keeps tracked range intact */ + ext4_fc_track_inode(&ctx->handle, file1); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 4U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 27U); + + /* + * 6) Tracking while EXT4_STATE_FC_COMMITTING is set marks the inode + * with EXT4_STATE_FC_REQUEUE, and tracking in a new TID resets the + * previous range. + */ + ext4_set_inode_state(file1, EXT4_STATE_FC_COMMITTING); + ctx->running_txn.t_tid = 11; + ext4_fc_track_range(&ctx->handle, file1, 50, 55); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(file1, EXT4_STATE_FC_REQUEUE)); + KUNIT_EXPECT_EQ(test, ei1->i_sync_tid, 11U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 50U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 6U); + ext4_clear_inode_state(file1, EXT4_STATE_FC_COMMITTING); + ext4_clear_inode_state(file1, EXT4_STATE_FC_REQUEUE); + + /* + * 7) Tracking a new inode while JBD2_FAST_COMMIT_ONGOING is set + * enqueues it on FC_Q_STAGING rather than FC_Q_MAIN. + */ + ctx->journal.j_flags |= JBD2_FAST_COMMIT_ONGOING; + ext4_fc_track_inode(&ctx->handle, file2); + KUNIT_EXPECT_FALSE(test, list_empty(&sbi->s_fc_q[FC_Q_STAGING])); + KUNIT_EXPECT_PTR_EQ(test, + list_first_entry(&sbi->s_fc_q[FC_Q_STAGING], + struct ext4_inode_info, i_fc_list), + ei2); + ctx->journal.j_flags &= ~JBD2_FAST_COMMIT_ONGOING; +} + +/* ========================================================================= + * 4. Dentry Update Tracking and Inode Deletion (ext4_fc_del) + * ========================================================================= + */ + +struct fc_del_wait_work { + struct work_struct work; + struct inode *inode; +}; + +static void fc_del_unblock_worker(struct work_struct *work) +{ + struct fc_del_wait_work *w = + container_of(work, struct fc_del_wait_work, work); + struct inode *inode = w->inode; + int alloc_ctx; + + /* + * Simulate the commit thread finishing data flush and transitioning + * FLUSHING_DATA -> COMMITTING -> done while ext4_fc_del() is waiting. + */ + alloc_ctx = ext4_fc_lock(inode->i_sb); + ext4_clear_inode_state(inode, EXT4_STATE_FC_FLUSHING_DATA); + ext4_set_inode_state(inode, EXT4_STATE_FC_COMMITTING); + ext4_fc_wake_inode_state_test(inode, EXT4_STATE_FC_FLUSHING_DATA); + ext4_fc_unlock(inode->i_sb, alloc_ctx); + + alloc_ctx = ext4_fc_lock(inode->i_sb); + ext4_clear_inode_state(inode, EXT4_STATE_FC_COMMITTING); + ext4_fc_wake_inode_state_test(inode, EXT4_STATE_FC_COMMITTING); + ext4_fc_unlock(inode->i_sb, alloc_ctx); +} + +static void test_fc_track_dentry_and_del(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct dentry *dentries; + struct dentry *d_parent, *d_f1, *d_f1_link, *d_f2; + struct ext4_fc_dentry_update *fcd; + struct fc_del_wait_work wait_work; + + dentries = kunit_kcalloc(test, 4, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + d_parent = &dentries[0]; + d_f1 = &dentries[1]; + d_f1_link = &dentries[2]; + d_f2 = &dentries[3]; + + init_mock_dentry(d_parent, NULL, "dir", dir, sb); + init_mock_dentry(d_f1, d_parent, "file1", file1, sb); + init_mock_dentry(d_f1_link, d_parent, "file1_ln", file1, sb); + init_mock_dentry(d_f2, d_parent, "file2", file2, sb); + + /* 1) Encrypted parent directory marks fs ineligible */ + dir->i_flags |= S_ENCRYPTED; + ext4_fc_track_create(&ctx->handle, d_f1); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_ENCRYPTED_FILENAME], + 1U); + KUNIT_EXPECT_TRUE(test, list_empty(&sbi->s_fc_dentry_q[FC_Q_MAIN])); + dir->i_flags &= ~S_ENCRYPTED; + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + sbi->s_fc_ineligible_tid = 0; + + /* 2) Track create, link, and unlink onto MAIN and STAGING queues */ + ext4_fc_track_create(&ctx->handle, d_f1); + KUNIT_EXPECT_FALSE(test, list_empty(&sbi->s_fc_dentry_q[FC_Q_MAIN])); + KUNIT_EXPECT_FALSE(test, list_empty(&ei1->i_fc_dilist)); + + fcd = list_first_entry(&sbi->s_fc_dentry_q[FC_Q_MAIN], + struct ext4_fc_dentry_update, fcd_list); + KUNIT_EXPECT_EQ(test, fcd->fcd_op, EXT4_FC_TAG_CREAT); + KUNIT_EXPECT_EQ(test, fcd->fcd_parent, (int)TEST_DIR_INO); + KUNIT_EXPECT_EQ(test, fcd->fcd_ino, (int)TEST_FILE1_INO); + KUNIT_EXPECT_STREQ(test, (const char *)fcd->fcd_name.name.name, "file1"); + + ext4_fc_track_link(&ctx->handle, file1, d_f1_link); + ext4_fc_track_unlink(&ctx->handle, d_f1_link); + + ctx->journal.j_flags |= JBD2_FULL_COMMIT_ONGOING; + ext4_fc_track_create(&ctx->handle, d_f2); + KUNIT_EXPECT_FALSE(test, list_empty(&sbi->s_fc_dentry_q[FC_Q_STAGING])); + ctx->journal.j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + + /* + * 3) ext4_fc_del removes file2's CREAT entry from s_fc_dentry_q and + * i_fc_dilist even when file2 is not on s_fc_q. + */ + ext4_fc_del(file2); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(file2)->i_fc_dilist)); + KUNIT_EXPECT_TRUE(test, list_empty(&sbi->s_fc_dentry_q[FC_Q_STAGING])); + + /* + * 4) ext4_fc_del waits for EXT4_STATE_FC_FLUSHING_DATA and + * EXT4_STATE_FC_COMMITTING to clear before deleting file1. + */ + ext4_fc_track_inode(&ctx->handle, file1); + ext4_set_inode_state(file1, EXT4_STATE_FC_FLUSHING_DATA); + wait_work.inode = file1; + INIT_WORK_ONSTACK(&wait_work.work, fc_del_unblock_worker); + schedule_work(&wait_work.work); + + ext4_fc_del(file1); + flush_work(&wait_work.work); + destroy_work_on_stack(&wait_work.work); + + KUNIT_EXPECT_TRUE(test, list_empty(&ei1->i_fc_list)); + KUNIT_EXPECT_TRUE(test, list_empty(&ei1->i_fc_dilist)); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(file1, EXT4_STATE_FC_FLUSHING_DATA)); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(file1, EXT4_STATE_FC_COMMITTING)); +} + +/* ========================================================================= + * 5. Space Reservation, Padding, and TLV Writing + * ========================================================================= + */ + +static void test_fc_reserve_space_and_tlv_writing(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct ext4_fc_tl tl; + struct ext4_fc_tail tail; + u8 payload[600]; + u8 *dst; + u32 crc = 0; + + memset(payload, 0xAB, sizeof(payload)); + + /* 1) Request exceeding bsize - EXT4_FC_TAG_BASE_LEN fails immediately */ + dst = ext4_fc_reserve_space_test(sb, + TEST_BLK_SIZE - EXT4_FC_TAG_BASE_LEN + 1, + &crc); + KUNIT_EXPECT_NULL(test, dst); + KUNIT_EXPECT_EQ(test, ctx->fc_get_buf_calls, 0); + + /* 2) ext4_fc_get_buf failure on initial block returns NULL */ + ctx->fail_fc_get_buf = -ENOSPC; + dst = ext4_fc_reserve_space_test(sb, 32, &crc); + KUNIT_EXPECT_NULL(test, dst); + ctx->fail_fc_get_buf = 0; + + /* + * 3) Add a 600-byte TLV into block 0 (takes 604 bytes), then add + * another 600-byte TLV. The second TLV does not fit in the + * remaining 420 bytes of block 0, so ext4_fc_reserve_space writes + * an EXT4_FC_TAG_PAD TLV of length 416 (420 - 4), submits block 0, + * and allocates block 1. + */ + KUNIT_EXPECT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, + sizeof(payload), payload, &crc)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, + (unsigned int)(EXT4_FC_TAG_BASE_LEN + sizeof(payload))); + KUNIT_EXPECT_EQ(test, ctx->fc_submit_bh_calls, 0U); + + KUNIT_EXPECT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, + sizeof(payload), payload, &crc)); + KUNIT_EXPECT_EQ(test, ctx->fc_submit_bh_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->fc_submit_tail_calls, 0U); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, + (unsigned int)(TEST_BLK_SIZE + EXT4_FC_TAG_BASE_LEN + + sizeof(payload))); + + /* Verify PAD TLV was written at offset 604 of block 0 */ + memcpy(&tl, ctx->fc_buf_data[0] + EXT4_FC_TAG_BASE_LEN + sizeof(payload), + EXT4_FC_TAG_BASE_LEN); + KUNIT_EXPECT_EQ(test, le16_to_cpu(tl.fc_tag), (u16)EXT4_FC_TAG_PAD); + KUNIT_EXPECT_EQ(test, le16_to_cpu(tl.fc_len), + (u16)(TEST_BLK_SIZE - 2 * EXT4_FC_TAG_BASE_LEN - + sizeof(payload))); + + /* 4) Write tail tag into block 1 and verify rounding + tail submission */ + KUNIT_EXPECT_EQ(test, ext4_fc_write_tail_test(sb, crc), 0); + KUNIT_EXPECT_EQ(test, ctx->fc_submit_bh_calls, 2U); + KUNIT_EXPECT_EQ(test, ctx->fc_submit_tail_calls, 1U); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, (unsigned int)(2 * TEST_BLK_SIZE)); + + memcpy(&tl, ctx->fc_buf_data[1] + EXT4_FC_TAG_BASE_LEN + sizeof(payload), + EXT4_FC_TAG_BASE_LEN); + memcpy(&tail, + ctx->fc_buf_data[1] + 2 * EXT4_FC_TAG_BASE_LEN + sizeof(payload), + sizeof(tail)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(tl.fc_tag), (u16)EXT4_FC_TAG_TAIL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(tail.fc_tid), 10U); + + /* 5) Missing inode snapshot increments snap_fail_no_snap */ + KUNIT_EXPECT_EQ(test, ext4_fc_write_inode_test(file1, &crc), + -ECANCELED); + KUNIT_EXPECT_EQ(test, ext4_fc_write_inode_data_test(file1, &crc), + -ECANCELED); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_no_snap), + 2LL); +} + +/* ========================================================================= + * 6. Inode and Extent Status Range Snapshotting + * ========================================================================= + */ + +static void test_fc_snapshot_inode_and_ranges(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct dentry d_parent, d_f2; + struct inode **inodes = NULL; + unsigned int nr_inodes = 0, nr_ranges = 0; + int snap_err = EXT4_FC_SNAP_ERR_NONE; + u32 crc = 0; + + /* 1) ext4_get_inode_loc_noio failure records EXT4_FC_SNAP_ERR_INODE_LOC */ + ctx->fail_get_inode_loc_noio = -EAGAIN; + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, &nr_ranges, + &snap_err), + -EAGAIN); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_INODE_LOC); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_inode_loc), + 1LL); + ctx->fail_get_inode_loc_noio = 0; + + /* 2) ES miss on tracked range records EXT4_FC_SNAP_ERR_ES_MISS */ + snap_err = EXT4_FC_SNAP_ERR_NONE; + ext4_fc_track_range(&ctx->handle, file1, 0, 3); + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, &nr_ranges, + &snap_err), + -EAGAIN); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_ES_MISS); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_es_miss), + 1LL); + + /* 3) Delayed extent in ES tree records EXT4_FC_SNAP_ERR_ES_DELAYED */ + snap_err = EXT4_FC_SNAP_ERR_NONE; + down_write(&ei1->i_data_sem); + ext4_es_insert_delayed_extent(file1, 0, 4, false, false); + up_write(&ei1->i_data_sem); + ext4_fc_track_range(&ctx->handle, file1, 0, 3); + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, &nr_ranges, + &snap_err), + -EAGAIN); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_ES_DELAYED); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_es_delayed), + 1LL); + down_write(&ei1->i_data_sem); + ext4_es_remove_extent(file1, 0, EXT_MAX_BLOCKS); + up_write(&ei1->i_data_sem); + + /* 4) Unsupported ES status records EXT4_FC_SNAP_ERR_ES_OTHER */ + snap_err = EXT4_FC_SNAP_ERR_NONE; + ctx->use_custom_es_lookup = true; + ctx->custom_es_ret = 1; + ctx->custom_es.es_lblk = 0; + ctx->custom_es.es_len = 4; + ctx->custom_es.es_pblk = 0; + ext4_es_set_referenced(&ctx->custom_es); + ext4_fc_track_range(&ctx->handle, file1, 0, 3); + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, &nr_ranges, + &snap_err), + -EAGAIN); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_ES_OTHER); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_es_other), + 1LL); + ctx->use_custom_es_lookup = false; + + /* 5) Exceeding EXT4_FC_SNAPSHOT_MAX_RANGES returns -E2BIG */ + snap_err = EXT4_FC_SNAP_ERR_NONE; + down_write(&ei1->i_data_sem); + ext4_es_insert_extent(file1, 0, 4, 200, EXTENT_STATUS_WRITTEN, false); + up_write(&ei1->i_data_sem); + ext4_fc_track_range(&ctx->handle, file1, 0, 3); + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 2048, &nr_ranges, + &snap_err), + -E2BIG); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_RANGES_CAP); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_ranges_cap), + 1LL); + + /* + * 6) Snapshot mixed written, hole, unwritten, and large (>32768) + * extents, verifying automatic splitting at EXT_INIT_MAX_LEN (32768) + * and EXT_UNWRITTEN_MAX_LEN (32767). + */ + down_write(&ei1->i_data_sem); + ext4_es_remove_extent(file1, 0, EXT_MAX_BLOCKS); + /* [0, 3]: written at pblk 200 */ + ext4_es_insert_extent(file1, 0, 4, 200, EXTENT_STATUS_WRITTEN, false); + /* [4, 5]: hole */ + ext4_es_insert_extent(file1, 4, 2, 0, EXTENT_STATUS_HOLE, false); + /* [6, 40005]: 40000 unwritten blocks at pblk 1000 (splits into 32767 + 7233) */ + ext4_es_insert_extent(file1, 6, 40000, 1000, EXTENT_STATUS_UNWRITTEN, + false); + up_write(&ei1->i_data_sem); + + snap_err = EXT4_FC_SNAP_ERR_NONE; + ext4_fc_track_range(&ctx->handle, file1, 1, 40005); + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, &nr_ranges, + &snap_err), + 0); + /* 1 written [1..3] + 1 hole [4..5] + 2 split unwritten [6..32772, 32773..40005] = 4 */ + KUNIT_EXPECT_EQ(test, nr_ranges, 4U); + KUNIT_EXPECT_NOT_NULL(test, ei1->i_fc_snap); + + /* Serialize the snapshotted inode and ranges into fast commit buffer */ + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + KUNIT_EXPECT_EQ(test, ext4_fc_write_inode_data_test(file1, &crc), 0); + KUNIT_EXPECT_EQ(test, ext4_fc_write_inode_test(file1, &crc), 0); + + /* + * 7) Count and snapshot both s_fc_q[MAIN] inodes and create-only + * inodes from s_fc_dentry_q[MAIN]. + */ + init_mock_dentry(&d_parent, NULL, "dir", dir, sb); + init_mock_dentry(&d_f2, &d_parent, "file2", file2, sb); + ext4_fc_track_create(&ctx->handle, &d_f2); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(file2)->i_fc_list)); + KUNIT_EXPECT_EQ(test, ext4_fc_count_snapshot_inodes_test(sb), 2U); + + KUNIT_EXPECT_EQ(test, + ext4_fc_alloc_snapshot_inodes_test(sb, &inodes, + &nr_inodes), + 0); + KUNIT_EXPECT_EQ(test, nr_inodes, 2U); + KUNIT_ASSERT_NOT_NULL(test, inodes); + + /* Capacity smaller than queued inode count returns -E2BIG */ + snap_err = EXT4_FC_SNAP_ERR_NONE; + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inodes_test(&ctx->journal, inodes, 1, + &nr_inodes, &nr_ranges, + &snap_err), + -E2BIG); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_INODES_CAP); + + snap_err = EXT4_FC_SNAP_ERR_NONE; + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inodes_test(&ctx->journal, inodes, 2, + &nr_inodes, &nr_ranges, + &snap_err), + 0); + KUNIT_EXPECT_EQ(test, nr_inodes, 2U); + /* Create-only inode (file2) is marked EXT4_STATE_FC_COMMITTING */ + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(file2, EXT4_STATE_FC_COMMITTING)); + KUNIT_EXPECT_NOT_NULL(test, EXT4_I(file2)->i_fc_snap); + kvfree(inodes); +} + +/* ========================================================================= + * 7. Fast Commit Cleanup, Stats, and Procfs Output (ext4_fc_info_show) + * ========================================================================= + */ + +static void test_fc_cleanup_and_stats(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct ext4_inode_info *ei2 = EXT4_I(file2); + struct seq_file seq = {}; + char *buf; + + /* + * 1) Fast commit cleanup (full = 0): + * - file1 (no FC_REQUEUE) is removed from FC_Q_MAIN and reset. + * - file2 (FC_REQUEUE set) is requeued and preserves its range. + */ + ctx->running_txn.t_tid = 10; + ext4_fc_track_range(&ctx->handle, file1, 2, 5); + ext4_fc_track_range(&ctx->handle, file2, 8, 12); + ext4_set_inode_state(file1, EXT4_STATE_FC_COMMITTING); + ext4_set_inode_state(file2, EXT4_STATE_FC_COMMITTING); + ext4_set_inode_state(file2, EXT4_STATE_FC_REQUEUE); + sbi->s_fc_bytes = 512; + + ext4_fc_cleanup_test(&ctx->journal, 0, 10); + KUNIT_EXPECT_TRUE(test, list_empty(&ei1->i_fc_list)); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 0U); + KUNIT_EXPECT_FALSE(test, list_empty(&ei2->i_fc_list)); + KUNIT_EXPECT_EQ(test, ei2->i_fc_lblk_start, 8U); + KUNIT_EXPECT_EQ(test, ei2->i_fc_lblk_len, 5U); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(file2, EXT4_STATE_FC_REQUEUE)); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(file2, EXT4_STATE_FC_COMMITTING)); + /* Fast commit cleanup does not reset s_fc_bytes */ + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, 512U); + + /* + * 2) Full commit cleanup (full = 1): + * - Inodes with i_sync_tid > tid are requeued; inodes with + * i_sync_tid <= tid are removed and reset. + * - s_fc_ineligible_tid is cleared only when tid >= s_fc_ineligible_tid. + * - s_fc_bytes is reset to 0. + */ + ctx->running_txn.t_tid = 15; + ext4_fc_track_range(&ctx->handle, file1, 1, 3); + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_XATTR, &ctx->handle); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 15U); + + /* Full commit of TID 10: file2 (tid 10) removed, file1 (tid 15) kept */ + ext4_fc_cleanup_test(&ctx->journal, 1, 10); + KUNIT_EXPECT_TRUE(test, list_empty(&ei2->i_fc_list)); + KUNIT_EXPECT_FALSE(test, list_empty(&ei1->i_fc_list)); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, 0U); + + /* Full commit of TID 15: file1 removed and ineligibility cleared */ + ext4_fc_cleanup_test(&ctx->journal, 1, 15); + KUNIT_EXPECT_TRUE(test, list_empty(&ei1->i_fc_list)); + KUNIT_EXPECT_FALSE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 0U); + + /* + * 3) ext4_fc_update_stats and ext4_fc_info_show formatting + */ + memset(&sbi->s_fc_stats, 0, sizeof(sbi->s_fc_stats)); + ext4_fc_update_stats_test(sb, EXT4_FC_STATUS_OK, 40000, 2, 10); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_num_commits, 1UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_numblks, 2UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.s_fc_avg_commit_time, 40000ULL); + + /* EWMA update: (80000 + 40000 * 3) / 4 = 50000 */ + ext4_fc_update_stats_test(sb, EXT4_FC_STATUS_OK, 80000, 3, 10); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_num_commits, 2UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_numblks, 5UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.s_fc_avg_commit_time, 50000ULL); + + ext4_fc_update_stats_test(sb, EXT4_FC_STATUS_INELIGIBLE, 0, 0, 10); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_ineligible_commits, 1UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 0UL); + + ext4_fc_update_stats_test(sb, EXT4_FC_STATUS_FAILED, 0, 0, 10); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_ineligible_commits, 2UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 1UL); + + ext4_fc_update_stats_test(sb, EXT4_FC_STATUS_SKIPPED, 0, 0, 10); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_skipped_commits, 1UL); + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + seq.buf = buf; + seq.size = PAGE_SIZE; + seq.private = sb; + + /* Non-start token produces no output */ + KUNIT_EXPECT_EQ(test, ext4_fc_info_show(&seq, NULL), 0); + KUNIT_EXPECT_EQ(test, seq.count, 0UL); + + /* SEQ_START_TOKEN outputs full stats table */ + KUNIT_EXPECT_EQ(test, ext4_fc_info_show(&seq, SEQ_START_TOKEN), 0); + KUNIT_EXPECT_GT(test, seq.count, 0UL); + KUNIT_EXPECT_NOT_NULL(test, strstr(buf, "fc stats:\n2 commits\n2 ineligible\n5 numblks\n50us avg_commit_time")); + KUNIT_EXPECT_NOT_NULL(test, strstr(buf, "Ineligible reasons:")); + KUNIT_EXPECT_NOT_NULL(test, strstr(buf, "Snapshot stats:")); + KUNIT_EXPECT_NOT_NULL(test, strstr(buf, "Snapshot failures:")); +} + +/* ========================================================================= + * 8. Top-Level Commit Paths and Fallbacks (ext4_fc_commit) + * ========================================================================= + */ + +static void test_fc_commit_paths(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct ext4_fc_tl tl; + + /* 1) Already-committed TID is skipped (-EALREADY) */ + ctx->journal.j_commit_sequence = 10; + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_skipped_commits, 1UL); + + /* 1b) JOURNAL_FAST_COMMIT disabled delegates to jbd2_complete_transaction */ + clear_opt2(sb, JOURNAL_FAST_COMMIT); + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_skipped_commits, 1UL); + set_opt2(sb, JOURNAL_FAST_COMMIT); + + /* 1c) jbd2_fc_begin_commit failure (ts_tid == 0 -> -EINVAL) records FAILED */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 10; + ctx->journal.j_stats.ts_tid = 0; + ctx->journal.j_running_transaction = NULL; + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 1UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_ineligible_commits, 1UL); + ctx->journal.j_stats.ts_tid = 1; + ctx->journal.j_running_transaction = &ctx->running_txn; + sbi->s_fc_stats.fc_failed_commits = 0; + sbi->s_fc_stats.fc_ineligible_commits = 0; + + /* 2) Ineligible filesystem falls back to full commit */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->running_txn.t_tid = 10; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_XATTR, &ctx->handle); + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_ineligible_commits, 1UL); + ctx->journal.j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + sbi->s_fc_ineligible_tid = 0; + + /* 3) Data flush failure (-EIO) clears FLUSHING_DATA and falls back */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->running_txn.t_tid = 10; + ext4_fc_track_inode(&ctx->handle, file1); + WRITE_ONCE(ei1->jinode->i_flags, JI_WRITE_DATA); + ctx->submit_inode_data_err = -EIO; + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(file1, EXT4_STATE_FC_FLUSHING_DATA)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 1UL); + ctx->journal.j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + WRITE_ONCE(ei1->jinode->i_flags, 0); + ctx->submit_inode_data_err = 0; + + /* 4) Snapshot ES miss (-EAGAIN) records INELIGIBLE status and falls back */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->running_txn.t_tid = 10; + ext4_fc_track_range(&ctx->handle, file1, 0, 1); + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_ineligible_commits, 3UL); + /* Failed commits count does not increment on -EAGAIN */ + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 1UL); + ctx->journal.j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + + /* 5) jbd2_fc_wait_bufs I/O failure (-EIO) records FAILED status */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->running_txn.t_tid = 10; + ctx->journal.j_fc_off = 0; + sbi->s_fc_bytes = 0; + ext4_fc_track_inode(&ctx->handle, file1); + ctx->fail_fc_wait_bufs = true; + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 2UL); + ctx->journal.j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + ctx->fail_fc_wait_bufs = false; + + /* + * 6) Two consecutive successful fast commits in the same TID, with an + * external journal device (j_fs_dev != j_dev) triggering cache flush. + */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->running_txn.t_tid = 10; + ctx->journal.j_fc_off = 0; + sbi->s_fc_bytes = 0; + atomic_set(&sbi->s_fc_subtid, 0); + ctx->journal.j_fs_dev = &ctx->ext_jdev; + ctx->fc_flush_calls = 0; + + down_write(&ei1->i_data_sem); + ext4_es_insert_extent(file1, 0, 2, 200, EXTENT_STATUS_WRITTEN, false); + up_write(&ei1->i_data_sem); + ext4_fc_track_range(&ctx->handle, file1, 0, 1); + + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, atomic_read(&sbi->s_fc_subtid), 1); + KUNIT_EXPECT_EQ(test, ctx->fc_flush_calls, 1U); + KUNIT_EXPECT_PTR_EQ(test, ctx->last_flushed_bdev, &ctx->ext_jdev); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, (unsigned int)TEST_BLK_SIZE); + + /* Block 0 starts with EXT4_FC_TAG_HEAD */ + memcpy(&tl, ctx->fc_buf_data[0], EXT4_FC_TAG_BASE_LEN); + KUNIT_EXPECT_EQ(test, le16_to_cpu(tl.fc_tag), (u16)EXT4_FC_TAG_HEAD); + + /* Second fast commit in the same TID (block 1 starts with INODE, not HEAD) */ + ext4_fc_track_inode(&ctx->handle, file1); + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, atomic_read(&sbi->s_fc_subtid), 2); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, (unsigned int)(2 * TEST_BLK_SIZE)); + memcpy(&tl, ctx->fc_buf_data[1], EXT4_FC_TAG_BASE_LEN); + KUNIT_EXPECT_EQ(test, le16_to_cpu(tl.fc_tag), (u16)EXT4_FC_TAG_INODE); + + ctx->journal.j_fs_dev = &ctx->bdev; +} + +/* ========================================================================= + * 9. Replay Regions, Modified Inode Tracking, and Scan Validation + * ========================================================================= + */ + +static void test_fc_replay_regions_and_scan(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct ext4_fc_replay_state *state = &sbi->s_fc_replay_state; + struct ext4_fc_tl tl; + struct ext4_fc_head head; + int i; + + /* + * 1) ext4_fc_record_regions and ext4_fc_replay_check_excluded across + * dynamic krealloc (> EXT4_FC_REPLAY_REALLOC_INCREMENT = 4) + */ + for (i = 0; i < 6; i++) { + KUNIT_EXPECT_EQ(test, + ext4_fc_record_regions(sb, 12 + i, i * 10, + 100 + i * 10, 5, 1), + 0); + } + KUNIT_EXPECT_EQ(test, state->fc_regions_used, 6); + KUNIT_EXPECT_EQ(test, state->fc_regions_valid, 6); + KUNIT_EXPECT_GE(test, state->fc_regions_size, 6); + + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 100)); + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 104)); + KUNIT_EXPECT_FALSE(test, ext4_fc_replay_check_excluded(sb, 105)); + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 152)); + + /* Unvalidated scan region (replay = 0) is not excluded until validated */ + KUNIT_EXPECT_EQ(test, + ext4_fc_record_regions(sb, 99, 0, 500, 10, 0), + 0); + KUNIT_EXPECT_EQ(test, state->fc_regions_used, 7); + KUNIT_EXPECT_EQ(test, state->fc_regions_valid, 6); + KUNIT_EXPECT_FALSE(test, ext4_fc_replay_check_excluded(sb, 502)); + + /* Next replay=1 addition resyncs fc_regions_used to fc_regions_valid */ + KUNIT_EXPECT_EQ(test, + ext4_fc_record_regions(sb, 100, 0, 600, 4, 1), + 0); + KUNIT_EXPECT_EQ(test, state->fc_regions_used, 7); + KUNIT_EXPECT_EQ(test, state->fc_regions_valid, 7); + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 601)); + + /* 2) ext4_fc_record_modified_inode deduplication and krealloc growth */ + for (i = 0; i < 6; i++) { + KUNIT_EXPECT_EQ(test, + ext4_fc_record_modified_inode_test(sb, 20 + i), + 0); + /* Duplicate ino is ignored */ + KUNIT_EXPECT_EQ(test, + ext4_fc_record_modified_inode_test(sb, 20 + i), + 0); + } + KUNIT_EXPECT_EQ(test, state->fc_modified_inodes_used, 6); + + ext4_fc_replay_cleanup(sb); + memset(state, 0, sizeof(*state)); + + /* 3) ext4_fc_value_len_isvalid_test and tag2str */ + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_ADD_RANGE, + sizeof(struct ext4_fc_add_range))); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_ADD_RANGE, 1)); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_DEL_RANGE, + sizeof(struct ext4_fc_del_range))); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_CREAT, + sizeof(struct ext4_fc_dentry_info) + 1)); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_CREAT, + sizeof(struct ext4_fc_dentry_info))); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_LINK, + sizeof(struct ext4_fc_dentry_info) + + EXT4_NAME_LEN + 1)); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_INODE, + sizeof(struct ext4_fc_inode) + + EXT4_GOOD_OLD_INODE_SIZE)); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_INODE, + sizeof(struct ext4_fc_inode) + + TEST_INODE_SIZE + 1)); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_PAD, 0)); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_TAIL, + sizeof(struct ext4_fc_tail))); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_TAIL, + sizeof(struct ext4_fc_tail) - 1)); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_HEAD, + sizeof(struct ext4_fc_head))); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, 0x9999, 8)); + KUNIT_EXPECT_STREQ(test, tag2str(EXT4_FC_TAG_HEAD), "HEAD"); + KUNIT_EXPECT_STREQ(test, tag2str(0x9999), "ERROR"); + + /* 4) Scan error cases */ + /* Block 0 not starting with HEAD returns 0 (early stop) */ + memset(ctx->fc_buf_data[0], 0, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + 0); + + /* Unexpected block offset returns -EFSCORRUPTED */ + state->fc_replay_expected_off = 2; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 1, 10), + -EFSCORRUPTED); + + /* HEAD with unsupported features returns -EOPNOTSUPP */ + memset(state, 0, sizeof(*state)); + memset(ctx->fc_buf_data[0], 0, TEST_BLK_SIZE); + tl.fc_tag = cpu_to_le16(EXT4_FC_TAG_HEAD); + tl.fc_len = cpu_to_le16(sizeof(head)); + head.fc_features = cpu_to_le32(0x1); + head.fc_tid = cpu_to_le32(10); + memcpy(ctx->fc_buf_data[0], &tl, EXT4_FC_TAG_BASE_LEN); + memcpy(ctx->fc_buf_data[0] + EXT4_FC_TAG_BASE_LEN, &head, sizeof(head)); + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + -EOPNOTSUPP); + + /* HEAD with wrong TID returns JBD2_FC_REPLAY_STOP */ + memset(state, 0, sizeof(*state)); + head.fc_features = 0; + head.fc_tid = cpu_to_le32(99); + memcpy(ctx->fc_buf_data[0] + EXT4_FC_TAG_BASE_LEN, &head, sizeof(head)); + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + JBD2_FC_REPLAY_STOP); + + /* + * Corrupted TAIL CRC on first commit stops cleanly with + * JBD2_FC_REPLAY_STOP without failing journal recovery. + */ + memset(state, 0, sizeof(*state)); + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + ctx->running_txn.t_tid = 10; + head.fc_tid = cpu_to_le32(10); + { + u32 crc = 0; + + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, sizeof(head), + (u8 *)&head, &crc); + ext4_fc_write_tail_test(sb, crc); + } + /* Corrupt last byte of tail.fc_crc */ + ctx->fc_buf_data[0][2 * EXT4_FC_TAG_BASE_LEN + sizeof(head) + + offsetof(struct ext4_fc_tail, fc_crc)] ^= 0xFF; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + JBD2_FC_REPLAY_STOP); + KUNIT_EXPECT_EQ(test, state->fc_replay_num_tags, 0); + + /* + * 5) Valid first commit in block 0 followed by a corrupted second + * commit in block 1 stops cleanly with JBD2_FC_REPLAY_STOP and + * keeps fc_replay_num_tags from block 0. + */ + memset(state, 0, sizeof(*state)); + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + { + u32 crc = 0; + + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, sizeof(head), + (u8 *)&head, &crc); + ext4_fc_write_tail_test(sb, crc); + } + /* Block 1 has an invalid TLV (tag=0) */ + memset(ctx->fc_buf_data[1], 0, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_EXPECT_EQ(test, state->fc_replay_num_tags, 2); + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[1], + PASS_SCAN, 1, 10), + JBD2_FC_REPLAY_STOP); + KUNIT_EXPECT_EQ(test, state->fc_replay_num_tags, 2); + ext4_fc_replay_cleanup(sb); + memset(state, 0, sizeof(*state)); +} + +/* ========================================================================= + * 10. Replay of Inode, Create, Link, and Unlink Tags + * ========================================================================= + */ + +static void test_fc_replay_inode_and_dentries(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *root = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *subdir = get_mock_inode(ctx, TEST_SUBDIR_INO); + struct fc_mock_inode_slot *f1_slot = find_slot(ctx, file1); + struct dentry *dentries; + struct dentry *d_dir, *d_f1, *d_f1_link, *d_subdir, *d_f1_overwrite; + struct ext4_dir_entry_2 *de = NULL; + struct buffer_head *bh; + struct qstr q_f1 = QSTR_INIT("file1", 5); + struct qstr q_f1_ln = QSTR_INIT("file1_ln", 8); + struct qstr q_subdir = QSTR_INIT("subdir", 6); + struct ext4_fc_head head = { + .fc_features = 0, + .fc_tid = cpu_to_le32(10), + }; + u32 crc = 0; + int snap_err = EXT4_FC_SNAP_ERR_NONE; + + dentries = kunit_kcalloc(test, 5, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + d_dir = &dentries[0]; + d_f1 = &dentries[1]; + d_f1_link = &dentries[2]; + d_subdir = &dentries[3]; + d_f1_overwrite = &dentries[4]; + + /* Initialize parent directory on-disk block */ + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root, dir), 0); + + init_mock_dentry(d_dir, NULL, "dir", dir, sb); + init_mock_dentry(d_f1, d_dir, "file1", file1, sb); + init_mock_dentry(d_f1_link, d_dir, "file1_ln", file1, sb); + init_mock_dentry(d_subdir, d_dir, "subdir", subdir, sb); + + /* Prepare file1 and subdir snapshots */ + file1->i_generation = 0x4242; + i_size_write(file1, 2048); + sync_inode_to_raw(f1_slot); + sync_inode_to_raw(find_slot(ctx, subdir)); + KUNIT_ASSERT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, NULL, &snap_err), + 0); + KUNIT_ASSERT_EQ(test, + ext4_fc_snapshot_inode_test(subdir, 0, NULL, &snap_err), + 0); + + /* + * Build a fast commit block containing: + * HEAD -> INODE(file1) -> CREAT(file1) -> LINK(file1_ln) -> + * INODE(subdir) -> CREAT(subdir) -> UNLINK(file1) -> TAIL + */ + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + ctx->running_txn.t_tid = 10; + + ext4_fc_track_create(&ctx->handle, d_f1); + ext4_fc_track_link(&ctx->handle, file1, d_f1_link); + ext4_fc_track_create(&ctx->handle, d_subdir); + ext4_fc_track_unlink(&ctx->handle, d_f1); + + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, + sizeof(head), (u8 *)&head, &crc)); + /* Commit all queued dentry updates into block 0 */ + { + struct ext4_fc_dentry_update *fcd; + + list_for_each_entry(fcd, &sbi->s_fc_dentry_q[FC_Q_MAIN], fcd_list) { + struct ext4_fc_dentry_info fcd_info = { + .fc_parent_ino = cpu_to_le32(fcd->fcd_parent), + .fc_ino = cpu_to_le32(fcd->fcd_ino), + }; + u8 d_buf[64]; + int dlen = fcd->fcd_name.name.len; + + if (fcd->fcd_op == EXT4_FC_TAG_CREAT) { + struct inode *c_ino = + get_mock_inode(ctx, fcd->fcd_ino); + KUNIT_ASSERT_EQ(test, + ext4_fc_write_inode_test(c_ino, &crc), + 0); + } + memcpy(d_buf, &fcd_info, sizeof(fcd_info)); + memcpy(d_buf + sizeof(fcd_info), + fcd->fcd_name.name.name, dlen); + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, fcd->fcd_op, + sizeof(fcd_info) + dlen, + d_buf, &crc)); + } + } + KUNIT_ASSERT_EQ(test, ext4_fc_write_tail_test(sb, crc), 0); + + /* Clear file1 generation in raw_buf to verify replay restores it */ + ((struct ext4_inode *)f1_slot->raw_buf)->i_generation = 0; + file1->i_generation = 0; + + /* Scan and replay block 0 */ + memset(&sbi->s_fc_replay_state, 0, sizeof(sbi->s_fc_replay_state)); + KUNIT_ASSERT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_EXPECT_EQ(test, sbi->s_fc_replay_state.fc_replay_num_tags, 8); + + /* Error injection: ext4_get_fc_inode_loc failure aborts INODE replay */ + ctx->fail_get_fc_inode_loc = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -EIO); + ctx->fail_get_fc_inode_loc = 0; + + /* Error injection: sync_dirty_buffer failure aborts INODE replay */ + sbi->s_fc_replay_state.fc_replay_num_tags = 8; + ctx->fail_sync_dirty_buffer = true; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -EIO); + ctx->fail_sync_dirty_buffer = false; + + /* Successful full replay of block 0 */ + sbi->s_fc_replay_state.fc_replay_num_tags = 8; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_EXPECT_EQ(test, sbi->s_fc_replay_state.fc_replay_num_tags, 0); + + /* Calling PASS_REPLAY once fc_replay_num_tags == 0 runs bitmaps & stops */ + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 1, 10), + 0); + + /* Verify replayed state: file1 generation restored, file1 unlinked, file1_ln & subdir present */ + KUNIT_EXPECT_EQ(test, file1->i_generation, 0x4242U); + + bh = ext4_find_entry_test(dir, &q_f1, &de, NULL); + KUNIT_EXPECT_NULL(test, bh); + + bh = ext4_find_entry_test(dir, &q_f1_ln, &de, NULL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_FILE1_INO); + brelse(bh); + + bh = ext4_find_entry_test(dir, &q_subdir, &de, NULL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_SUBDIR_INO); + brelse(bh); + + /* + * Exercise additional replay branches: + * - LINK on an already-existing entry ("file1_ln") ignores -EEXIST + * - UNLINK on an already-removed entry ("file1") returns 0 + * - UNLINK when dentry points to a different inode (simulating + * rename-overwrite) leaves the dentry intact + * - INODE replay of an inline-data inode copies raw_fc_inode->i_block + */ + { + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct fc_mock_inode_slot *f2_slot = find_slot(ctx, file2); + struct ext4_inode *raw_f2 = (struct ext4_inode *)f2_slot->raw_buf; + struct ext4_fc_dentry_info fcd_info; + u8 d_buf[64]; + + /* Prepare inline-data file2 snapshot */ + ext4_clear_inode_flag(file2, EXT4_INODE_EXTENTS); + ext4_set_inode_flag(file2, EXT4_INODE_INLINE_DATA); + sync_inode_to_raw(f2_slot); + memcpy(raw_f2->i_block, "inline-test-payload", 20); + KUNIT_ASSERT_EQ(test, + ext4_fc_snapshot_inode_test(file2, 0, NULL, + &snap_err), + 0); + memset(raw_f2->i_block, 0, sizeof(raw_f2->i_block)); + + /* Build block: HEAD -> LINK(file1_ln) -> UNLINK(file1) -> INODE(file2) -> TAIL */ + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + crc = 0; + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, + sizeof(head), + (u8 *)&head, &crc)); + + /* LINK("file1_ln") when "file1_ln" already exists */ + fcd_info.fc_parent_ino = cpu_to_le32(TEST_DIR_INO); + fcd_info.fc_ino = cpu_to_le32(TEST_FILE1_INO); + memcpy(d_buf, &fcd_info, sizeof(fcd_info)); + memcpy(d_buf + sizeof(fcd_info), "file1_ln", 8); + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_LINK, + sizeof(fcd_info) + 8, + d_buf, &crc)); + + /* UNLINK("file1", ino=TEST_FILE1_INO) */ + memcpy(d_buf, &fcd_info, sizeof(fcd_info)); + memcpy(d_buf + sizeof(fcd_info), "file1", 5); + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_UNLINK, + sizeof(fcd_info) + 5, + d_buf, &crc)); + + /* INODE(file2) with inline data */ + KUNIT_ASSERT_EQ(test, ext4_fc_write_inode_test(file2, &crc), 0); + KUNIT_ASSERT_EQ(test, ext4_fc_write_tail_test(sb, crc), 0); + + /* 1) Replay when "file1" does not exist (UNLINK no-op) */ + sbi->s_fc_replay_state.fc_replay_num_tags = 5; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_EXPECT_EQ(test, + memcmp(raw_f2->i_block, "inline-test-payload", 20), + 0); + + /* 2) Add "file1" pointing to file2, then replay UNLINK(file1, ino=file1) */ + init_mock_dentry(d_f1_overwrite, d_dir, "file1", file2, sb); + KUNIT_ASSERT_EQ(test, + __ext4_link(dir, file2, &d_f1_overwrite->d_name, + d_f1_overwrite), + 0); + + sbi->s_fc_replay_state.fc_replay_num_tags = 5; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + + /* Verify "file1" still points to file2 after UNLINK(file1, ino=file1) */ + bh = ext4_find_entry_test(dir, &q_f1, &de, NULL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), + (u32)TEST_FILE2_INO); + brelse(bh); + } + + ext4_fc_replay_cleanup(sb); +} + +/* ========================================================================= + * 11. Replay of Extent Ranges and End-to-End Commit-to-Replay Round-Trip + * ========================================================================= + */ + +static void test_fc_replay_ranges_and_end_to_end(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *root = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct fc_mock_inode_slot *f1_slot = find_slot(ctx, file1); + struct dentry d_dir, d_f1; + struct ext4_map_blocks map; + struct ext4_dir_entry_2 *de = NULL; + struct buffer_head *bh; + struct qstr q_f1 = QSTR_INIT("e2e_file", 8); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root, dir), 0); + init_mock_dentry(&d_dir, NULL, "dir", dir, sb); + init_mock_dentry(&d_f1, &d_dir, "e2e_file", file1, sb); + + /* + * Set up file1 modifications for a real ext4_fc_commit(): + * - [0, 3]: written extent at pblk 300 + * - [4, 5]: hole (DEL_RANGE) + * - [6, 9]: unwritten extent at pblk 310 + */ + ctx->journal.j_commit_sequence = 9; + ctx->running_txn.t_tid = 10; + ctx->journal.j_fc_off = 0; + sbi->s_fc_bytes = 0; + + i_size_write(file1, 10 * TEST_BLK_SIZE); + file1->i_generation = 0x7777; + sync_inode_to_raw(f1_slot); + + down_write(&ei1->i_data_sem); + ext4_es_insert_extent(file1, 0, 4, 300, EXTENT_STATUS_WRITTEN, false); + ext4_es_insert_extent(file1, 4, 2, 0, EXTENT_STATUS_HOLE, false); + ext4_es_insert_extent(file1, 6, 4, 310, EXTENT_STATUS_UNWRITTEN, false); + up_write(&ei1->i_data_sem); + + ext4_fc_track_create(&ctx->handle, &d_f1); + ext4_fc_track_range(&ctx->handle, file1, 0, 9); + + /* Execute real ext4_fc_commit() */ + KUNIT_ASSERT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, ctx->journal.j_fc_off, 1U); + + /* + * Simulate pre-crash on-disk state before replay: + * - [0, 3] was mapped to old pblk 250 (to exercise pblk remap & + * old block bitmap freeing in ext4_fc_replay_add_range) + * - [4, 5] was mapped to pblk 260 (to exercise DEL_RANGE removal) + * - [6, 9] was mapped to pblk 310 as written (to exercise state toggle) + */ + ext4_ext_tree_init(NULL, file1); + { + struct ext4_ext_path *path; + struct ext4_extent ex; + + memset(&ex, 0, sizeof(ex)); + ex.ee_block = cpu_to_le32(0); + ex.ee_len = cpu_to_le16(4); + ext4_ext_store_pblock(&ex, 250); + path = ext4_find_extent(file1, 0, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + down_write(&ei1->i_data_sem); + path = ext4_ext_insert_extent(NULL, file1, path, &ex, 0); + up_write(&ei1->i_data_sem); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + ext4_free_ext_path(path); + + memset(&ex, 0, sizeof(ex)); + ex.ee_block = cpu_to_le32(4); + ex.ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(&ex, 260); + path = ext4_find_extent(file1, 4, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + down_write(&ei1->i_data_sem); + path = ext4_ext_insert_extent(NULL, file1, path, &ex, 0); + up_write(&ei1->i_data_sem); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + ext4_free_ext_path(path); + + memset(&ex, 0, sizeof(ex)); + ex.ee_block = cpu_to_le32(6); + ex.ee_len = cpu_to_le16(4); + ext4_ext_store_pblock(&ex, 310); + path = ext4_find_extent(file1, 6, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + down_write(&ei1->i_data_sem); + path = ext4_ext_insert_extent(NULL, file1, path, &ex, 0); + up_write(&ei1->i_data_sem); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + ext4_free_ext_path(path); + } + + /* Run PASS_SCAN followed by PASS_REPLAY on the committed block */ + ctx->nr_bb_marks = 0; + memset(&sbi->s_fc_replay_state, 0, sizeof(sbi->s_fc_replay_state)); + KUNIT_ASSERT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_EXPECT_GT(test, sbi->s_fc_replay_state.fc_replay_num_tags, 0); + /* Both ADD_RANGE extents ([0,3]->300 and [6,9]->310) are excluded */ + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 300)); + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 312)); + + KUNIT_ASSERT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_ASSERT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 1, 10), + 0); + + /* 1) Verify directory entry "e2e_file" was created in dir */ + bh = ext4_find_entry_test(dir, &q_f1, &de, NULL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_FILE1_INO); + brelse(bh); + + /* 2) Verify [0, 3] is mapped to new pblk 300 (written) */ + map.m_lblk = 0; + map.m_len = 4; + KUNIT_EXPECT_EQ(test, ext4_ext_map_blocks(NULL, file1, &map, 0), 4); + KUNIT_EXPECT_EQ(test, map.m_pblk, 300ULL); + KUNIT_EXPECT_TRUE(test, (map.m_flags & EXT4_MAP_MAPPED) != 0); + + /* 3) Verify [4, 5] hole was punched by DEL_RANGE */ + map.m_lblk = 4; + map.m_len = 2; + KUNIT_EXPECT_EQ(test, ext4_ext_map_blocks(NULL, file1, &map, 0), 0); + + /* 4) Verify [6, 9] is mapped to pblk 310 as unwritten */ + map.m_lblk = 6; + map.m_len = 4; + KUNIT_EXPECT_EQ(test, ext4_ext_map_blocks(NULL, file1, &map, 0), 4); + KUNIT_EXPECT_EQ(test, map.m_pblk, 310ULL); + KUNIT_EXPECT_TRUE(test, (map.m_flags & EXT4_MAP_UNWRITTEN) != 0); + + /* 5) Verify ext4_mb_mark_bb was invoked to free old blocks & mark new ones */ + KUNIT_EXPECT_GT(test, ctx->nr_bb_marks, 0U); + + /* + * 6) Error handling in ADD_RANGE and DEL_RANGE replay: + * - DEL_RANGE when ext4_map_blocks fails propagates error + * - ADD_RANGE when ext4_map_blocks, ext4_find_extent, or + * ext4_ext_insert_extent fails propagates error + * - ADD_RANGE / DEL_RANGE when ext4_iget fails returns 0 + */ + { + struct ext4_fc_del_range del_arg; + struct ext4_fc_add_range add_arg; + struct ext4_extent *ex = (struct ext4_extent *)add_arg.fc_ex; + u32 crc = 0; + + /* DEL_RANGE: ext4_iget failure returns 0; ext4_map_blocks failure returns -EIO */ + sbi->s_fc_bh = NULL; + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + del_arg.fc_ino = cpu_to_le32(TEST_FILE1_INO); + del_arg.fc_lblk = cpu_to_le32(0); + del_arg.fc_len = cpu_to_le32(2); + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_DEL_RANGE, + sizeof(del_arg), + (u8 *)&del_arg, &crc)); + + sbi->s_fc_replay_state.fc_replay_num_tags = 1; + ctx->fail_iget = -ENOENT; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + 0); + ctx->fail_iget = 0; + + sbi->s_fc_replay_state.fc_replay_num_tags = 1; + ctx->fail_map_blocks = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -EIO); + ctx->fail_map_blocks = 0; + + /* ADD_RANGE on unmapped range [20, 21]: test map_blocks, find_extent, insert_extent failures */ + sbi->s_fc_bh = NULL; + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + memset(&add_arg, 0, sizeof(add_arg)); + add_arg.fc_ino = cpu_to_le32(TEST_FILE1_INO); + ex->ee_block = cpu_to_le32(20); + ex->ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(ex, 400); + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_ADD_RANGE, + sizeof(add_arg), + (u8 *)&add_arg, &crc)); + + sbi->s_fc_replay_state.fc_replay_num_tags = 1; + ctx->fail_map_blocks = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -EIO); + ctx->fail_map_blocks = 0; + + sbi->s_fc_replay_state.fc_replay_num_tags = 1; + ctx->fail_find_extent = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -EIO); + ctx->fail_find_extent = 0; + + sbi->s_fc_replay_state.fc_replay_num_tags = 1; + ctx->fail_insert_extent = -ENOSPC; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -ENOSPC); + ctx->fail_insert_extent = 0; + } + + ext4_fc_replay_cleanup(sb); + KUNIT_EXPECT_FALSE(test, (sbi->s_mount_state & EXT4_FC_REPLAY) != 0); +} + +static struct kunit_case fast_commit_test_cases[] = { + KUNIT_CASE(test_fc_init_and_eligibility), + KUNIT_CASE(test_fc_mark_ineligible), + KUNIT_CASE(test_fc_track_inode_and_range), + KUNIT_CASE(test_fc_track_dentry_and_del), + KUNIT_CASE(test_fc_reserve_space_and_tlv_writing), + KUNIT_CASE(test_fc_snapshot_inode_and_ranges), + KUNIT_CASE(test_fc_cleanup_and_stats), + KUNIT_CASE(test_fc_commit_paths), + KUNIT_CASE(test_fc_replay_regions_and_scan), + KUNIT_CASE(test_fc_replay_inode_and_dentries), + KUNIT_CASE(test_fc_replay_ranges_and_end_to_end), + {} +}; + +static struct kunit_suite fast_commit_test_suite = { + .name = "ext4_fast_commit_test", + .init = fast_commit_test_init, + .test_cases = fast_commit_test_cases, +}; + +kunit_test_suites(&fast_commit_test_suite); + +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/fast_commit.c b/fs/ext4/fast_commit.c index 5f12449b97ec9e..9beb423b208f80 100644 --- a/fs/ext4/fast_commit.c +++ b/fs/ext4/fast_commit.c @@ -14,6 +14,7 @@ #include #include +#include /* * Ext4 Fast Commits * ----------------- @@ -661,11 +662,25 @@ void ext4_fc_track_range(handle_t *handle, struct inode *inode, ext4_lblk_t star trace_ext4_fc_track_range(handle, inode, start, end, ret); } -static void ext4_fc_submit_bh(struct super_block *sb, bool is_tail) +int ext4_fc_get_buf(journal_t *journal, struct buffer_head **bh) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_fc_get_buf, journal, bh); + return jbd2_fc_get_buf(journal, bh); +} + +int ext4_fc_issue_flush(struct block_device *bdev) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_fc_issue_flush, bdev); + return blkdev_issue_flush(bdev); +} + +void ext4_fc_submit_bh(struct super_block *sb, bool is_tail) { blk_opf_t write_flags = JBD2_JOURNAL_REQ_FLAGS; struct buffer_head *bh = EXT4_SB(sb)->s_fc_bh; + KUNIT_STATIC_STUB_REDIRECT(ext4_fc_submit_bh, sb, is_tail); + /* Add REQ_FUA | REQ_PREFLUSH only its tail */ if (test_opt(sb, BARRIER) && is_tail) write_flags |= REQ_FUA | REQ_PREFLUSH; @@ -707,7 +722,7 @@ static u8 *ext4_fc_reserve_space(struct super_block *sb, int len, u32 *crc) return NULL; if (!sbi->s_fc_bh) { - ret = jbd2_fc_get_buf(EXT4_SB(sb)->s_journal, &bh); + ret = ext4_fc_get_buf(EXT4_SB(sb)->s_journal, &bh); if (ret) return NULL; sbi->s_fc_bh = bh; @@ -737,7 +752,7 @@ static u8 *ext4_fc_reserve_space(struct super_block *sb, int len, u32 *crc) ext4_fc_submit_bh(sb, false); - ret = jbd2_fc_get_buf(EXT4_SB(sb)->s_journal, &bh); + ret = ext4_fc_get_buf(EXT4_SB(sb)->s_journal, &bh); if (ret) return NULL; sbi->s_fc_bh = bh; @@ -1427,7 +1442,7 @@ static int ext4_fc_perform_commit(journal_t *journal, tid_t commit_tid) */ if (journal->j_fs_dev != journal->j_dev && journal->j_flags & JBD2_BARRIER) { - ret = blkdev_issue_flush(journal->j_fs_dev); + ret = ext4_fc_issue_flush(journal->j_fs_dev); if (ret) return ret; } @@ -2026,7 +2041,7 @@ static int ext4_fc_replay_inode(struct super_block *sb, out: iput(inode); if (!ret) - blkdev_issue_flush(sb->s_bdev); + ext4_fc_issue_flush(sb->s_bdev); return ret; } @@ -2789,3 +2804,158 @@ void ext4_fc_destroy_dentry_cache(void) kmem_cache_destroy(ext4_fc_range_cachep); kmem_cache_destroy(ext4_fc_dentry_cachep); } + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +void ext4_fc_set_snap_err_test(int *snap_err, int err) +{ + ext4_fc_set_snap_err(snap_err, err); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_set_snap_err_test); + +bool ext4_fc_disabled_test(struct super_block *sb) +{ + return ext4_fc_disabled(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_disabled_test); + +bool ext4_fc_eligible_test(struct super_block *sb) +{ + return ext4_fc_eligible(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_eligible_test); + +void ext4_fc_snap_stats_update_max_test(atomic64_t *stat, u64 value) +{ + ext4_fc_snap_stats_update_max(stat, value); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_snap_stats_update_max_test); + +void ext4_fc_wake_inode_state_test(struct inode *inode, int bit) +{ + ext4_fc_wake_inode_state(inode, bit); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_wake_inode_state_test); + +u8 *ext4_fc_reserve_space_test(struct super_block *sb, int len, u32 *crc) +{ + return ext4_fc_reserve_space(sb, len, crc); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_reserve_space_test); + +int ext4_fc_write_tail_test(struct super_block *sb, u32 crc) +{ + return ext4_fc_write_tail(sb, crc); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_write_tail_test); + +bool ext4_fc_add_tlv_test(struct super_block *sb, u16 tag, u16 len, u8 *val, + u32 *crc) +{ + return ext4_fc_add_tlv(sb, tag, len, val, crc); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_add_tlv_test); + +int ext4_fc_write_inode_test(struct inode *inode, u32 *crc) +{ + return ext4_fc_write_inode(inode, crc); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_write_inode_test); + +int ext4_fc_write_inode_data_test(struct inode *inode, u32 *crc) +{ + return ext4_fc_write_inode_data(inode, crc); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_write_inode_data_test); + +void ext4_fc_free_inode_snap_test(struct inode *inode) +{ + ext4_fc_free_inode_snap(inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_free_inode_snap_test); + +int ext4_fc_snapshot_inode_test(struct inode *inode, + unsigned int nr_ranges_total, + unsigned int *nr_rangesp, int *snap_err) +{ + return ext4_fc_snapshot_inode(inode, nr_ranges_total, nr_rangesp, + snap_err); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_snapshot_inode_test); + +unsigned int ext4_fc_count_snapshot_inodes_test(struct super_block *sb) +{ + return ext4_fc_count_snapshot_inodes(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_count_snapshot_inodes_test); + +int ext4_fc_alloc_snapshot_inodes_test(struct super_block *sb, + struct inode ***inodesp, + unsigned int *nr_inodesp) +{ + return ext4_fc_alloc_snapshot_inodes(sb, inodesp, nr_inodesp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_alloc_snapshot_inodes_test); + +int ext4_fc_snapshot_inodes_test(journal_t *journal, struct inode **inodes, + unsigned int inodes_size, + unsigned int *nr_inodesp, + unsigned int *nr_rangesp, int *snap_err) +{ + return ext4_fc_snapshot_inodes(journal, inodes, inodes_size, + nr_inodesp, nr_rangesp, snap_err); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_snapshot_inodes_test); + +void ext4_fc_update_stats_test(struct super_block *sb, int status, + u64 commit_time, int nblks, tid_t commit_tid) +{ + ext4_fc_update_stats(sb, status, commit_time, nblks, commit_tid); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_update_stats_test); + +void ext4_fc_cleanup_test(journal_t *journal, int full, tid_t tid) +{ + ext4_fc_cleanup(journal, full, tid); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_cleanup_test); + +int ext4_fc_record_modified_inode_test(struct super_block *sb, int ino) +{ + return ext4_fc_record_modified_inode(sb, ino); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_record_modified_inode_test); + +bool ext4_fc_value_len_isvalid_test(struct ext4_sb_info *sbi, int tag, int len) +{ + return ext4_fc_value_len_isvalid(sbi, tag, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_value_len_isvalid_test); + +int ext4_fc_replay_test(journal_t *journal, struct buffer_head *bh, + enum passtype pass, int off, tid_t expected_tid) +{ + return ext4_fc_replay(journal, bh, pass, off, expected_tid); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_replay_test); + +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_get_buf); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_submit_bh); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_issue_flush); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_init_inode); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_del); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_mark_ineligible); +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_fc_track_unlink); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_unlink); +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_fc_track_link); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_link); +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_fc_track_create); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_create); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_inode); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_range); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_commit); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_record_regions); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_replay_check_excluded); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_replay_cleanup); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_init); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_info_show); +#endif diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c index 8b9833ea38027e..c836923d018a09 100644 --- a/fs/ext4/ialloc.c +++ b/fs/ext4/ialloc.c @@ -827,6 +827,8 @@ int ext4_mark_inode_used(struct super_block *sb, int ino) int bit; int err; + KUNIT_STATIC_STUB_REDIRECT(ext4_mark_inode_used, sb, ino); + if (ino < EXT4_FIRST_INO(sb) || ino > max_ino) return -EFSCORRUPTED; @@ -1701,4 +1703,5 @@ int ext4_init_inode_table(struct super_block *sb, ext4_group_t group, #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_new_inode); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mark_inode_used); #endif diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 9fe324cda5e669..49560ca27036d9 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -5959,6 +5959,8 @@ int ext4_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc) int inodes_per_block, inode_offset; unsigned long ino = inode->i_ino; + KUNIT_STATIC_STUB_REDIRECT(ext4_get_inode_loc_noio, inode, iloc); + iloc->bh = NULL; if (ino < EXT4_ROOT_INO || ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count)) @@ -6000,6 +6002,8 @@ int ext4_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc) int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino, struct ext4_iloc *iloc) { + KUNIT_STATIC_STUB_REDIRECT(ext4_get_fc_inode_loc, sb, ino, iloc); + return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL); } @@ -8023,6 +8027,8 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf) } #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_inode_loc_noio); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_fc_inode_loc); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_get_block_prep); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_update_reserve_space); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_release_space); diff --git a/fs/ext4/mballoc.c b/fs/ext4/mballoc.c index 2ecf5aa77e68db..b346f8bbee8970 100644 --- a/fs/ext4/mballoc.c +++ b/fs/ext4/mballoc.c @@ -4269,6 +4269,8 @@ void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block, int err = 0; unsigned int clen, thisgrp_len; + KUNIT_STATIC_STUB_REDIRECT(ext4_mb_mark_bb, sb, block, len, state); + while (len > 0) { ext4_get_group_no_and_offset(sb, block, &group, &blkoff); @@ -7439,7 +7441,6 @@ EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_group_number); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_release); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_block_bitmap_nowait); EXPORT_SYMBOL_FOR_EXT4_TEST(mb_set_bits); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_init_inode); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_mark_context); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_new_blocks); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_blocks); From 3ca8192f7950445d4319dab9dffc33f171bdb987 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Thu, 5 Nov 2026 20:33:11 +0000 Subject: [PATCH 1560/2102] ext4: expand KUnit tests for fs/ext4/inode.c Expand the ext4_inode_test KUnit test suite in fs/ext4/inode-test.c from 1 parameterized test (16 timestamp decoding subtests) to 26 test cases (41 subtests total) to comprehensively exercise fs/ext4/inode.c using an in-memory VFS superblock, mock block device, and deterministic block pool without requiring a mounted block device: - Extra timestamp encoding and 64-bit round-trips across all 16 boundary vectors, 256-byte inodes with 34-bit seconds + nanoseconds, and 128-byte old inodes storing signed 32-bit seconds with zeroed nanoseconds. - Raw inode CRC32C checksum computation and verification (ext4_inode_csum_set and ext4_inode_csum_verify) across legacy non-csum filesystems, 128-byte inodes (16-bit lo CRC), 256-byte inodes with i_extra_isize = 0 vs >= 4 (32-bit CRC), and bit-flip corruptions. - Inode block count encoding and decoding (ext4_inode_blocks_set and ext4_inode_blocks) across 32-bit 512B sectors, 48-bit huge_file sectors, and EXT4_HUGE_FILE_FL filesystem block units. - VFS-to-raw inode serialization and writeback paths (ext4_fill_raw_inode, ext4_reserve_inode_write, ext4_mark_iloc_dirty, __ext4_mark_inode_dirty, ext4_dirty_inode, ext4_inode_attach_jinode, ext4_write_inode, and ext4_sync_inode_metadata), including inline data preservation, project IDs, lazytime neighbor timestamp flushes, emergency read-only -EROFS handling, and buffer I/O error propagation. - Dynamic extra-isize expansion (__ext4_expand_extra_isize, ext4_try_to_expand_extra_isize, and ext4_expand_extra_isize), including corrupted/invalid size guards, EXT4_STATE_NO_EXPAND, xattr_sem contention, and shifting in-body extended attributes forward. - On-disk inode location lookup (__ext4_get_inode_loc, ext4_get_inode_loc, ext4_get_inode_loc_noio, and ext4_get_fc_inode_loc), including zero-I/O uninitialized/unused inode table optimization, neighbor bitmap occupancy checks, readahead window calculation, and read -EIO handling. - Inode loading and validation (__ext4_iget) across EXT4_IGET_NORMAL, EXT4_IGET_SPECIAL, EXT4_IGET_HANDLE, EXT4_IGET_EA_INODE, EXT4_IGET_NOWAIT, and EXT4_IGET_BAD, special device rdev encodings, fast symlinks, and corruption rejections (bad CRC, unlinked ino, bad mode, reserved ino < first_ino, bad extra_isize, conflicting flags, oversize indirect i_size, bad i_file_acl, and bad extent header). - Inode eviction (ext4_evict_inode) across live inodes, unlinked regular files (truncating data extents, setting i_dtime, and freeing the inode), and unlinked fast symlinks. - Fast symlink classification, ext4_can_truncate, inode flag propagation (ext4_set_inode_flags), address_space_operations selection (ext4_set_aops), folio order caps (ext4_set_inode_mapping_order), project ID lookup (ext4_get_projid), DIO alignment checks (ext4_dio_alignment), and STATX_BTIME / STATX_DIOALIGN / STATX_WRITE_ATOMIC / STATX_ATTR_* reporting in ext4_getattr and ext4_file_getattr. - Delayed allocation space accounting (ext4_da_reserve_space, ext4_da_update_reserve_space, ext4_da_release_space, and ext4_nonda_switch) and bigalloc shared-cluster pending reservations (ext4_clu_alloc_state, ext4_insert_delayed_blocks, and ext4_da_map_blocks). - Logical-to-physical block mapping (ext4_map_blocks, ext4_get_block, ext4_get_block_unwritten, ext4_da_get_block_prep, ext4_getblk, ext4_bread, ext4_bread_batch, and ext4_walk_page_buffers) across ES hits, extent allocation, unwritten extents, zeroout, and batch reads. - iomap mapping callbacks (ext4_iomap_begin, ext4_iomap_ops, and ext4_iomap_report_ops, including bigalloc multi-block IOMAP_ATOMIC writes), buffered write_begin/write_end (ext4_da_aops and ext4_aops), bmap, invalidate_folio, release_folio, and ext4_page_mkwrite. - Transaction credit helpers (ext4_meta_trans_blocks, ext4_chunk_trans_extent, and ext4_chunk_trans_blocks), ext4_break_layouts, ext4_update_disksize_before_punch, partial-block and EOF zeroing (ext4_zero_partial_blocks, ext4_block_zero_eof, and ext4_truncate_page_cache_block_range), ext4_punch_hole, ext4_truncate, and ext4_setattr. Add thin KUNIT_STATIC_STUB_REDIRECT wrappers for buffer-cache lookup and inode freeing (ext4_sb_getblk, ext4_sb_find_get_block, ext4_sb_getblk_unmovable, ext4_read_bh_nowait, ext4_read_bh_lock, ext4_sb_breadahead_unmovable, and ext4_free_inode) and export the tested entry points and static-helper wrappers with EXPORT_SYMBOL_FOR_EXT4_TEST. Signed-off-by: Theodore Ts'o --- fs/ext4/ext4.h | 29 + fs/ext4/ialloc.c | 3 + fs/ext4/inode-test.c | 3500 +++++++++++++++++++++++++++++++++++++++++- fs/ext4/inode.c | 150 +- fs/ext4/page-io.c | 1 + fs/ext4/super.c | 18 +- 6 files changed, 3689 insertions(+), 12 deletions(-) diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index ae773eb08895e7..bbe930023d1185 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -3291,6 +3291,35 @@ extern void ext4_da_update_reserve_space(struct inode *inode, extern int ext4_issue_zeroout(handle_t *handle, struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk, ext4_lblk_t len); +struct buffer_head *ext4_sb_getblk(struct super_block *sb, ext4_fsblk_t block); +struct buffer_head *ext4_sb_find_get_block(struct super_block *sb, + ext4_fsblk_t block); +struct buffer_head *ext4_sb_getblk_unmovable(struct super_block *sb, + ext4_fsblk_t block); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_inode_csum_verify_test(struct inode *inode, struct ext4_inode *raw, + struct ext4_inode_info *ei); +int ext4_inode_blocks_set_test(struct ext4_inode *raw_inode, + struct ext4_inode_info *ei); +blkcnt_t ext4_inode_blocks_test(struct ext4_inode *raw_inode, + struct ext4_inode_info *ei); +int ext4_fill_raw_inode_test(struct inode *inode, + struct ext4_inode *raw_inode); +int ext4_expand_extra_isize_test(struct inode *inode, + unsigned int new_extra_isize, + struct ext4_iloc *iloc, + handle_t *handle, int *no_expand); +int ext4_try_to_expand_extra_isize_test(struct inode *inode, + unsigned int new_extra_isize, + struct ext4_iloc *iloc, + handle_t *handle); +int ext4_da_reserve_space_test(struct inode *inode, int nr_resv); +int ext4_clu_alloc_state_test(struct inode *inode, ext4_lblk_t lblk); +int ext4_insert_delayed_blocks_test(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len); +int ext4_da_map_blocks_test(struct inode *inode, struct ext4_map_blocks *map); +int ext4_nonda_switch_test(struct super_block *sb); +#endif static inline bool is_special_ino(struct super_block *sb, unsigned long ino) { diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c index c836923d018a09..e4c75c56fc1705 100644 --- a/fs/ext4/ialloc.c +++ b/fs/ext4/ialloc.c @@ -250,6 +250,8 @@ void ext4_free_inode(handle_t *handle, struct inode *inode) int fatal = 0, err, count, cleared; struct ext4_group_info *grp; + KUNIT_STATIC_STUB_REDIRECT(ext4_free_inode, handle, inode); + if (!sb) { printk(KERN_ERR "EXT4-fs: %s:%d: inode on " "nonexistent device\n", __func__, __LINE__); @@ -363,6 +365,7 @@ void ext4_free_inode(handle_t *handle, struct inode *inode) brelse(bitmap_bh); ext4_std_error(sb, fatal); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_inode); struct orlov_stats { __u64 free_clusters; diff --git a/fs/ext4/inode-test.c b/fs/ext4/inode-test.c index 749af7ad4e09c2..4881736e87426f 100644 --- a/fs/ext4/inode-test.c +++ b/fs/ext4/inode-test.c @@ -1,14 +1,32 @@ // SPDX-License-Identifier: GPL-2.0 /* - * KUnit test of ext4 inode that verify the seconds part of [a/c/m] - * timestamps in ext4 inode structs are decoded correctly. + * KUnit tests for fs/ext4/inode.c */ #include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include #include +#include #include "ext4.h" +#include "ext4_jbd2.h" +#include "ext4_extents.h" +#include "xattr.h" +#include "truncate.h" /* * For constructing the nonnegative timestamp lower bound value. @@ -233,7 +251,6 @@ static time64_t get_32bit_time(const struct timestamp_expectation * const test) return UPPER_MSB_0; } - /* * Test data is derived from the table in the Inode Timestamps section of * Documentation/filesystems/ext4/inodes.rst. @@ -267,8 +284,3483 @@ static void inode_test_xtimestamp_decoding(struct kunit *test) test_param->extra_bits); } +/* ------------------------------------------------------------------------- + * Mock filesystem, block pool, and VFS inode fixture for fs/ext4/inode.c + * ------------------------------------------------------------------------- + */ + +#define INODE_TEST_BLK_SIZE 4096 +#define INODE_TEST_BLK_BITS 12 +#define INODE_TEST_TOTAL_BLKS 32768 +#define INODE_TEST_INODE_SIZE 256 +#define INODE_TEST_EXTRA_ISIZE 32 +#define INODE_TEST_INODES_PER_BLK (INODE_TEST_BLK_SIZE / INODE_TEST_INODE_SIZE) +#define INODE_TEST_INODES_PER_GRP 2048 +#define INODE_TEST_FIRST_INO 11 +#define INODE_TEST_PRIMARY_INO 12 +#define INODE_TEST_CSUM_SEED 0x5a3c9e71U + +#define INODE_TEST_IBITMAP_BLK 10 +#define INODE_TEST_ITABLE_BLK0 20 +#define INODE_TEST_ITABLE_BLK1 21 +#define INODE_TEST_META_BLK0 50 +#define INODE_TEST_META_BLK1 51 +#define INODE_TEST_DATA_BLK0 100 +#define INODE_TEST_DATA_NBLKS 8 +#define INODE_TEST_POOL_SIZE 16 +#define INODE_TEST_MAX_TRACKED_INODES 32 + +struct inode_test_blk { + bool in_use; + bool in_cache; + ext4_fsblk_t blocknr; + struct buffer_head bh; + char cache_buf[INODE_TEST_BLK_SIZE] __aligned(8); + char disk_buf[INODE_TEST_BLK_SIZE] __aligned(8); +}; + +struct inode_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct ext4_group_desc gdp; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + struct dentry root_dentry; + + struct ext4_inode_info ei; + struct ext4_inode_info scratch_ei; + union { + struct ext4_inode raw; + u8 bytes[INODE_TEST_INODE_SIZE]; + } scratch_raw; + struct inode *tracked_inodes[INODE_TEST_MAX_TRACKED_INODES]; + unsigned int nr_tracked_inodes; + + struct inode_test_blk pool[INODE_TEST_POOL_SIZE]; + + bool fail_group_desc; + bool fail_getblk; + bool fail_read_eio; + int fail_zeroout_err; + int fail_alloc_err; + int fail_orphan_err; + + ext4_fsblk_t next_alloc_pblk; + unsigned int alloc_calls; + unsigned int free_calls; + ext4_fsblk_t last_free_pblk; + unsigned long last_free_count; + unsigned long total_freed_blocks; + unsigned int zeroout_calls; + ext4_lblk_t last_zeroout_lblk; + ext4_fsblk_t last_zeroout_pblk; + ext4_lblk_t last_zeroout_len; + unsigned int read_nowait_calls; + unsigned int read_lock_calls; + unsigned int readahead_calls; + ext4_fsblk_t first_readahead_blk; + ext4_fsblk_t last_readahead_blk; + unsigned int orphan_add_calls; + unsigned int orphan_del_calls; + unsigned int free_inode_calls; +}; + +static unsigned long inode_test_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long inode_test_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +static void inode_test_init_ei_fields(struct ext4_inode_info *ei) +{ + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_flags = 0; + ext4_clear_state_flags(ei); + spin_lock_init(&ei->i_raw_lock); + ei->i_prealloc_node = RB_ROOT; + atomic_set(&ei->i_prealloc_active, 0); + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + ei->i_es_all_nr = 0; + ei->i_es_shk_nr = 0; + ei->i_es_shrink_lblk = 0; + ei->i_es_seq = 0; + ei->i_reserved_data_blocks = 0; + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); +#ifdef CONFIG_QUOTA + ei->i_reserved_quota = 0; + memset(&ei->i_dquot, 0, sizeof(ei->i_dquot)); +#endif + ei->jinode = NULL; + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + ei->i_sync_tid = 0; + ei->i_datasync_tid = 0; + INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_metadata_bhs = NULL; + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = INODE_TEST_EXTRA_ISIZE; + ei->i_csum_seed = INODE_TEST_CSUM_SEED; +} + +static void inode_test_cleanup_ext4_trees(struct inode *inode) +{ + struct ext4_inode_info *ei = EXT4_I(inode); + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct rb_node *node; + + down_write(&ei->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + while ((node = rb_first(&ei->i_pending_tree.root)) != NULL) { + struct pending_reservation *pr; + + pr = rb_entry(node, struct pending_reservation, rb_node); + ext4_remove_pending(inode, EXT4_C2B(sbi, pr->lclu)); + } + up_write(&ei->i_data_sem); +} + +static struct inode *inode_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_test_init_ei_fields(ei); + return &ei->vfs_inode; +} + +static void inode_test_destroy_inode(struct inode *inode) +{ + inode_test_cleanup_ext4_trees(inode); + kfree(ext4_i_metadata_bhs(inode)); + EXT4_I(inode)->i_metadata_bhs = NULL; +} + +static void inode_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static const struct super_operations inode_test_sops = { + .alloc_inode = inode_test_alloc_inode, + .evict_inode = ext4_evict_inode, + .destroy_inode = inode_test_destroy_inode, + .free_inode = inode_test_free_inode, + .drop_inode = inode_just_drop, +}; + +#ifdef CONFIG_QUOTA +static qsize_t *inode_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations inode_test_qops = { + .get_reserved_space = inode_test_get_reserved_space, +}; +#endif + +static int inode_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type inode_test_fs_type = { + .name = "ext4_inode_kunit", + .init_fs_context = inode_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static struct inode_test_blk *inode_test_find_blk(struct inode_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + int i; + + for (i = 0; i < INODE_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && ctx->pool[i].blocknr == blocknr) + return &ctx->pool[i]; + } + return NULL; +} + +static struct inode_test_blk *inode_test_find_blk_by_bh( + struct inode_test_ctx *ctx, struct buffer_head *bh) +{ + int i; + + for (i = 0; i < INODE_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && &ctx->pool[i].bh == bh) + return &ctx->pool[i]; + } + return NULL; +} + +static struct inode_test_blk *inode_test_setup_blk(struct inode_test_ctx *ctx, + int idx, + ext4_fsblk_t blocknr, + bool in_cache, + bool uptodate) +{ + struct inode_test_blk *slot = &ctx->pool[idx]; + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->in_cache = in_cache; + slot->blocknr = blocknr; + slot->bh.b_bdev = &ctx->bdev; + slot->bh.b_blocknr = blocknr; + slot->bh.b_size = INODE_TEST_BLK_SIZE; + slot->bh.b_data = slot->cache_buf; + atomic_set(&slot->bh.b_count, 1); + if (uptodate) + set_buffer_uptodate(&slot->bh); + return slot; +} + +/* --- Static Stubs --- */ + +static struct ext4_group_desc *inode_test_get_group_desc_stub( + struct super_block *sb, ext4_group_t block_group, + struct buffer_head **bh) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx || ctx->fail_group_desc || block_group != 0) + return NULL; + if (bh) + *bh = NULL; + return &ctx->gdp; +} + +static struct buffer_head *inode_test_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + struct inode_test_blk *slot; + + if (!ctx || ctx->fail_getblk) + return NULL; + slot = inode_test_find_blk(ctx, block); + if (!slot) + return NULL; + slot->in_cache = true; + get_bh(&slot->bh); + return &slot->bh; +} + +static struct buffer_head *inode_test_sb_find_get_block_stub( + struct super_block *sb, ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + struct inode_test_blk *slot; + + if (!ctx) + return NULL; + slot = inode_test_find_blk(ctx, block); + if (!slot || !slot->in_cache) + return NULL; + get_bh(&slot->bh); + return &slot->bh; +} + +static struct buffer_head *inode_test_sb_getblk_unmovable_stub( + struct super_block *sb, ext4_fsblk_t block) +{ + return inode_test_sb_getblk_stub(sb, block); +} + +static struct buffer_head *inode_test_ext_getblk_stub(struct inode *inode, + ext4_fsblk_t pblk, + gfp_t gfp_flags) +{ + struct buffer_head *bh; + + bh = inode_test_sb_getblk_stub(inode->i_sb, pblk); + if (bh) { + set_buffer_uptodate(bh); + set_buffer_verified(bh); + } + return bh; +} + +static void inode_test_read_bh_nowait_stub(struct buffer_head *bh, + blk_opf_t op_flags, + bio_end_io_t end_io, + bool simu_fail) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + struct inode_test_blk *slot; + + if (!ctx) { + unlock_buffer(bh); + return; + } + ctx->read_nowait_calls++; + if (ctx->fail_read_eio || simu_fail) { + clear_buffer_uptodate(bh); + unlock_buffer(bh); + return; + } + slot = inode_test_find_blk_by_bh(ctx, bh); + if (!slot) + slot = inode_test_find_blk(ctx, bh->b_blocknr); + if (slot) { + if (bh->b_folio) + memcpy_to_folio(bh->b_folio, bh_offset(bh), + slot->disk_buf, bh->b_size); + else + memcpy(bh->b_data, slot->disk_buf, bh->b_size); + set_buffer_uptodate(bh); + } else { + clear_buffer_uptodate(bh); + } + unlock_buffer(bh); +} + +static int inode_test_read_bh_lock_stub(struct buffer_head *bh, + blk_opf_t op_flags, bool wait) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + struct inode_test_blk *slot; + + if (!ctx) + return -EIO; + ctx->read_lock_calls++; + lock_buffer(bh); + if (ctx->fail_read_eio) { + clear_buffer_uptodate(bh); + unlock_buffer(bh); + return wait ? -EIO : 0; + } + slot = inode_test_find_blk_by_bh(ctx, bh); + if (!slot) + slot = inode_test_find_blk(ctx, bh->b_blocknr); + if (!slot) { + clear_buffer_uptodate(bh); + unlock_buffer(bh); + return wait ? -EIO : 0; + } + if (bh->b_folio) + memcpy_to_folio(bh->b_folio, bh_offset(bh), slot->disk_buf, + bh->b_size); + else + memcpy(bh->b_data, slot->disk_buf, bh->b_size); + set_buffer_uptodate(bh); + unlock_buffer(bh); + return 0; +} + +static void inode_test_breadahead_stub(struct super_block *sb, sector_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return; + if (ctx->readahead_calls == 0) + ctx->first_readahead_blk = block; + ctx->last_readahead_blk = block; + ctx->readahead_calls++; +} + +static ext4_fsblk_t inode_test_mb_new_blocks_stub( + handle_t *handle, struct ext4_allocation_request *ar, int *errp) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + ext4_fsblk_t pblk; + + if (!ctx) { + *errp = -EIO; + return 0; + } + if (ctx->fail_alloc_err) { + *errp = ctx->fail_alloc_err; + return 0; + } + ctx->alloc_calls++; + pblk = ctx->next_alloc_pblk; + ctx->next_alloc_pblk += ar->len; + *errp = 0; + return pblk; +} + +static void inode_test_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, + ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) + brelse(bh); + if (!ctx) + return; + ctx->free_calls++; + ctx->last_free_pblk = block; + ctx->last_free_count = count; + ctx->total_freed_blocks += count; +} + +static int inode_test_issue_zeroout_stub(handle_t *handle, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + ext4_lblk_t len) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + ctx->zeroout_calls++; + ctx->last_zeroout_lblk = lblk; + ctx->last_zeroout_pblk = pblk; + ctx->last_zeroout_len = len; + return ctx->fail_zeroout_err; +} + +static int inode_test_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + if (bh) { + set_buffer_uptodate(bh); + set_buffer_dirty(bh); + } + return 0; +} + +static int inode_test_ext_dirty_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct ext4_ext_path *path) +{ + if (path && path->p_bh) { + ext4_extent_block_csum_set_test(inode, + ext_block_hdr(path->p_bh)); + set_buffer_verified(path->p_bh); + } + return 0; +} + +static int inode_test_orphan_add_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + if (ctx->fail_orphan_err) + return ctx->fail_orphan_err; + ctx->orphan_add_calls++; + return 0; +} + +static int inode_test_orphan_del_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + ctx->orphan_del_calls++; + return 0; +} + +static void inode_test_free_inode_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (ctx) + ctx->free_inode_calls++; + ext4_clear_inode(inode); +} + +/* --- Fixture Setup & Cleanup --- */ + +static void inode_test_track_iget_inode(struct kunit *test, + struct inode_test_ctx *ctx, + struct inode *inode) +{ + KUNIT_ASSERT_LT(test, ctx->nr_tracked_inodes, + (unsigned int)INODE_TEST_MAX_TRACKED_INODES); + ctx->tracked_inodes[ctx->nr_tracked_inodes++] = inode; +} + +static void inode_test_put_tracked_inode(struct inode_test_ctx *ctx, + struct inode *inode) +{ + unsigned int i; + + for (i = 0; i < ctx->nr_tracked_inodes; i++) { + if (ctx->tracked_inodes[i] == inode) { + ctx->tracked_inodes[i] = + ctx->tracked_inodes[--ctx->nr_tracked_inodes]; + ctx->tracked_inodes[ctx->nr_tracked_inodes] = NULL; + iput(inode); + return; + } + } + iput(inode); +} + +static void inode_test_reset_mock_inode(struct inode_test_ctx *ctx, umode_t mode) +{ + struct ext4_inode_info *ei = &ctx->ei; + struct inode *inode = &ei->vfs_inode; + struct mapping_metadata_bhs *mmb = ext4_i_metadata_bhs(inode); + + truncate_inode_pages_final(&inode->i_data); + inode_io_list_del(inode); + ext4_fc_del(inode); + if (mmb) + mmb_invalidate(mmb); + inode_test_cleanup_ext4_trees(inode); + if (ei->jinode) { + jbd2_free_inode(ei->jinode); + ei->jinode = NULL; + } + + inode_state_assign_raw(inode, 0); + inode->i_ino = INODE_TEST_PRIMARY_INO; + inode->i_mode = mode; + inode->i_blkbits = ctx->sb->s_blocksize_bits; + inode->i_flags = S_NOQUOTA; + set_nlink(inode, 1); + i_uid_write(inode, 0); + i_gid_write(inode, 0); + inode->i_size = 0; + inode->i_blocks = 0; + inode->i_generation = 1; + inode->i_rdev = 0; + ei->i_disksize = 0; + ei->i_flags = 0; + ei->i_file_acl = 0; + ei->i_dtime = 0; + ei->i_inline_off = 0; + ei->i_inline_size = 0; + ei->i_extra_isize = INODE_TEST_EXTRA_ISIZE; + ei->i_reserved_data_blocks = 0; + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ext4_clear_state_flags(ei); + memset(ei->i_data, 0, sizeof(ei->i_data)); + + if (S_ISREG(mode) || S_ISDIR(mode)) { + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_ext_tree_init(NULL, inode); + } + if (S_ISREG(mode)) + ext4_set_aops(inode); +} + +static void inode_test_cleanup(void *data) +{ + struct inode_test_ctx *ctx = data; + struct inode *inode = &ctx->ei.vfs_inode; + struct mapping_metadata_bhs *mmb; + unsigned int i; + + ctx->sbi.s_journal = NULL; + + for (i = 0; i < ctx->nr_tracked_inodes; i++) { + struct inode *ti = ctx->tracked_inodes[i]; + + if (ti) { + spin_lock(&ti->i_lock); + inode_state_clear(ti, I_DIRTY_TIME); + spin_unlock(&ti->i_lock); + iput(ti); + ctx->tracked_inodes[i] = NULL; + } + } + ctx->nr_tracked_inodes = 0; + + truncate_inode_pages_final(&inode->i_data); + inode_io_list_del(inode); + ext4_fc_del(inode); + mmb = ext4_i_metadata_bhs(inode); + if (mmb) + mmb_invalidate(mmb); + inode_test_cleanup_ext4_trees(inode); + if (ctx->ei.jinode) { + jbd2_free_inode(ctx->ei.jinode); + ctx->ei.jinode = NULL; + } + + deactivate_super(ctx->sb); + rcu_barrier(); + + ext4_es_unregister_shrinker(&ctx->sbi); + ext4_es_destroy_stats(&ctx->sbi); + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + + kfree(mmb); + kfree(ctx); +} + +static struct inode_test_ctx *inode_test_setup(struct kunit *test) +{ + struct inode_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *inode, *root_inode; + int err, i; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + fc = fs_context_for_mount(&inode_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &inode_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &inode_test_qops; +#endif + sb->s_blocksize = INODE_TEST_BLK_SIZE; + sb->s_blocksize_bits = INODE_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_inode_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = INODE_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(1); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + ctx->es.s_inodes_count = cpu_to_le32(INODE_TEST_INODES_PER_GRP); + ctx->es.s_inodes_per_group = cpu_to_le32(INODE_TEST_INODES_PER_GRP); + ctx->es.s_first_ino = cpu_to_le32(INODE_TEST_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(INODE_TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(INODE_TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(INODE_TEST_EXTRA_ISIZE); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_blocks_count_set(&ctx->es, INODE_TEST_TOTAL_BLKS); + ext4_set_feature_extents(sb); + ext4_set_feature_extra_isize(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + ext4_set_feature_huge_file(sb); + ext4_set_feature_large_file(sb); + ext4_set_feature_dir_index(sb); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + sbi->s_inode_size = INODE_TEST_INODE_SIZE; + sbi->s_inodes_per_block = INODE_TEST_INODES_PER_BLK; + sbi->s_inodes_per_group = INODE_TEST_INODES_PER_GRP; + sbi->s_first_ino = INODE_TEST_FIRST_INO; + sbi->s_want_extra_isize = INODE_TEST_EXTRA_ISIZE; + sbi->s_blocks_per_group = INODE_TEST_TOTAL_BLKS; + sbi->s_clusters_per_group = INODE_TEST_TOTAL_BLKS; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = 1; + sbi->s_gdb_count = 1; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = INODE_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_bitmap_maxbytes = 0x1ff7ffff000ULL; + sbi->s_extent_max_zeroout_kb = 32; + sbi->s_csum_seed = INODE_TEST_CSUM_SEED; + + ext4_inode_bitmap_set(sb, &ctx->gdp, INODE_TEST_IBITMAP_BLK); + ext4_inode_table_set(sb, &ctx->gdp, INODE_TEST_ITABLE_BLK0); + + set_opt(sb, ERRORS_CONT); + set_opt(sb, ORDERED_DATA); + set_opt(sb, DELALLOC); + set_opt(sb, XATTR_USER); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + err = percpu_counter_init(&sbi->s_freeclusters_counter, + max_t(s64, 4096, + EXT4_FREECLUSTERS_WATERMARK + 1024), + GFP_KERNEL); + if (err) { + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, + GFP_KERNEL); + if (err) { + percpu_counter_destroy(&sbi->s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = ext4_es_register_shrinker(sbi); + if (err) { + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sbi->s_es_shrinker->count_objects = inode_test_shrinker_count; + sbi->s_es_shrinker->scan_objects = inode_test_shrinker_scan; + + /* Initialize mock block pool */ + inode_test_setup_blk(ctx, 0, INODE_TEST_IBITMAP_BLK, true, true); + inode_test_setup_blk(ctx, 1, INODE_TEST_ITABLE_BLK0, true, true); + inode_test_setup_blk(ctx, 2, INODE_TEST_ITABLE_BLK1, true, true); + inode_test_setup_blk(ctx, 3, INODE_TEST_META_BLK0, true, true); + inode_test_setup_blk(ctx, 4, INODE_TEST_META_BLK1, true, true); + for (i = 0; i < INODE_TEST_DATA_NBLKS; i++) + inode_test_setup_blk(ctx, 5 + i, INODE_TEST_DATA_BLK0 + i, + true, true); + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0; + + /* Initialize standalone mock inode */ + inode = &ctx->ei.vfs_inode; + init_rwsem(&ctx->ei.i_data_sem); + inode_init_once(inode); + inode->i_sb = sb; + inode->i_mapping = &inode->i_data; + inode->i_data.host = inode; + mapping_set_gfp_mask(&inode->i_data, GFP_HIGHUSER_MOVABLE); + init_rwsem(&inode->i_rwsem); + init_rwsem(&inode->i_data.invalidate_lock); + spin_lock_init(&inode->i_lock); + inode->__i_nlink = 1; + atomic_set(&inode->i_count, 1); + inode_test_init_ei_fields(&ctx->ei); + + ctx->root_dentry.d_sb = sb; + ctx->root_dentry.d_inode = inode; + + root_inode = new_inode(sb); + if (!root_inode) { + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to allocate root inode"); + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to allocate root dentry"); + } + sb->s_flags |= SB_ACTIVE; + + up_write(&sb->s_umount); + + kunit_activate_static_stub(test, ext4_get_group_desc, + inode_test_get_group_desc_stub); + kunit_activate_static_stub(test, ext4_sb_getblk, + inode_test_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_sb_find_get_block, + inode_test_sb_find_get_block_stub); + kunit_activate_static_stub(test, ext4_sb_getblk_unmovable, + inode_test_sb_getblk_unmovable_stub); + kunit_activate_static_stub(test, ext4_ext_getblk, + inode_test_ext_getblk_stub); + kunit_activate_static_stub(test, ext4_read_bh_nowait, + inode_test_read_bh_nowait_stub); + kunit_activate_static_stub(test, ext4_read_bh_lock, + inode_test_read_bh_lock_stub); + kunit_activate_static_stub(test, ext4_sb_breadahead_unmovable, + inode_test_breadahead_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + inode_test_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + inode_test_free_blocks_stub); + kunit_activate_static_stub(test, ext4_issue_zeroout, + inode_test_issue_zeroout_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + inode_test_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_ext_dirty, + inode_test_ext_dirty_stub); + kunit_activate_static_stub(test, ext4_orphan_add, + inode_test_orphan_add_stub); + kunit_activate_static_stub(test, ext4_orphan_del, + inode_test_orphan_del_stub); + kunit_activate_static_stub(test, ext4_free_inode, + inode_test_free_inode_stub); + + err = kunit_add_action_or_reset(test, inode_test_cleanup, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + + return ctx; +} + +static struct ext4_inode *inode_test_raw_slot(struct inode_test_ctx *ctx, + unsigned long ino, bool disk) +{ + unsigned int grp_off = (ino - 1) % INODE_TEST_INODES_PER_GRP; + ext4_fsblk_t blk = INODE_TEST_ITABLE_BLK0 + + (grp_off / INODE_TEST_INODES_PER_BLK); + unsigned int byte_off = (grp_off % INODE_TEST_INODES_PER_BLK) * + INODE_TEST_INODE_SIZE; + struct inode_test_blk *slot = inode_test_find_blk(ctx, blk); + char *base = disk ? slot->disk_buf : slot->cache_buf; + + return (struct ext4_inode *)(base + byte_off); +} + +static void inode_test_stamp_raw_csum(struct inode_test_ctx *ctx, + unsigned long ino, + struct ext4_inode *raw) +{ + struct ext4_inode_info *tmp_ei = &ctx->scratch_ei; + struct inode *tmp_inode = &tmp_ei->vfs_inode; + __le32 inum = cpu_to_le32(ino); + __le32 gen = raw->i_generation; + u32 csum; + + memset(tmp_ei, 0, sizeof(*tmp_ei)); + tmp_inode->i_sb = ctx->sb; + tmp_inode->i_ino = ino; + tmp_ei->i_extra_isize = le16_to_cpu(raw->i_extra_isize); + csum = ext4_chksum(ctx->sbi.s_csum_seed, (u8 *)&inum, sizeof(inum)); + tmp_ei->i_csum_seed = ext4_chksum(csum, (u8 *)&gen, sizeof(gen)); + ext4_inode_csum_set(tmp_inode, raw, tmp_ei); +} + +static void inode_test_prepare_valid_raw_inode(struct inode_test_ctx *ctx, + unsigned long ino, umode_t mode) +{ + struct inode_test_blk *slot; + struct ext4_inode *raw; + struct ext4_extent_header *eh; + unsigned int grp_off = (ino - 1) % INODE_TEST_INODES_PER_GRP; + ext4_fsblk_t blk = INODE_TEST_ITABLE_BLK0 + + (grp_off / INODE_TEST_INODES_PER_BLK); + + slot = inode_test_find_blk(ctx, blk); + clear_buffer_uptodate(&slot->bh); + raw = inode_test_raw_slot(ctx, ino, true); + memset(raw, 0, INODE_TEST_INODE_SIZE); + + raw->i_mode = cpu_to_le16(mode); + raw->i_links_count = cpu_to_le16(1); + raw->i_extra_isize = cpu_to_le16(INODE_TEST_EXTRA_ISIZE); + raw->i_generation = cpu_to_le32(7); + if (S_ISREG(mode) || S_ISDIR(mode)) { + raw->i_flags = cpu_to_le32(EXT4_EXTENTS_FL); + eh = (struct ext4_extent_header *)raw->i_block; + eh->eh_magic = EXT4_EXT_MAGIC; + eh->eh_entries = 0; + eh->eh_max = cpu_to_le16(4); + eh->eh_depth = 0; + } + inode_test_stamp_raw_csum(ctx, ino, raw); +} + +/* ------------------------------------------------------------------------- + * 1. Timestamp Encoding & Macro Round-Trip Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_xtimestamp_encoding_roundtrip(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct ext4_inode_info *ei = &ctx->ei; + struct inode *inode = &ei->vfs_inode; + struct ext4_inode *raw = &ctx->scratch_raw.raw; + struct timespec64 ts_in, ts_out; + size_t i; + + for (i = 0; i < ARRAY_SIZE(test_data); i++) { + __le32 encoded_extra = ext4_encode_extra_time(test_data[i].expected); + __le32 encoded_base = cpu_to_le32((s32)test_data[i].expected.tv_sec); + + KUNIT_EXPECT_EQ_MSG(test, le32_to_cpu(encoded_extra), + test_data[i].extra_bits, + "%s", test_data[i].test_case_name); + ts_out = ext4_decode_extra_time(encoded_base, encoded_extra); + KUNIT_EXPECT_EQ(test, ts_out.tv_sec, + test_data[i].expected.tv_sec); + KUNIT_EXPECT_EQ(test, ts_out.tv_nsec, + test_data[i].expected.tv_nsec); + } + + /* 256-byte inode with extra_isize = 32: full 34-bit + nsec round-trip */ + ts_in.tv_sec = 0x240001234LL; + ts_in.tv_nsec = 987654321L; + inode_set_atime_to_ts(inode, ts_in); + ts_in.tv_sec = 0x190005678LL; + ts_in.tv_nsec = 123456789L; + inode_set_mtime_to_ts(inode, ts_in); + ts_in.tv_sec = 0x310009abcLL; + ts_in.tv_nsec = 555666777L; + inode_set_ctime_to_ts(inode, ts_in); + ei->i_crtime.tv_sec = 0x22000def0LL; + ei->i_crtime.tv_nsec = 444333222L; + + EXT4_INODE_SET_ATIME(inode, raw); + EXT4_INODE_SET_MTIME(inode, raw); + EXT4_INODE_SET_CTIME(inode, raw); + EXT4_EINODE_SET_XTIME(i_crtime, ei, raw); + + inode_set_atime(inode, 0, 0); + inode_set_mtime(inode, 0, 0); + inode_set_ctime(inode, 0, 0); + ei->i_crtime = (struct timespec64){}; + + EXT4_INODE_GET_ATIME(inode, raw); + EXT4_INODE_GET_MTIME(inode, raw); + EXT4_INODE_GET_CTIME(inode, raw); + EXT4_EINODE_GET_XTIME(i_crtime, ei, raw); + + KUNIT_EXPECT_EQ(test, inode_get_atime_sec(inode), 0x240001234LL); + KUNIT_EXPECT_EQ(test, inode_get_atime_nsec(inode), 987654321L); + KUNIT_EXPECT_EQ(test, inode_get_mtime_sec(inode), 0x190005678LL); + KUNIT_EXPECT_EQ(test, inode_get_mtime_nsec(inode), 123456789L); + KUNIT_EXPECT_EQ(test, inode_get_ctime_sec(inode), 0x310009abcLL); + KUNIT_EXPECT_EQ(test, inode_get_ctime_nsec(inode), 555666777L); + KUNIT_EXPECT_EQ(test, ctx->ei.i_crtime.tv_sec, 0x22000def0LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_crtime.tv_nsec, 444333222L); + + /* 128-byte old inode: 32-bit signed seconds only, extra ignored, nsec=0 */ + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + ctx->ei.i_extra_isize = 0; + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + + inode_set_mtime(inode, S32_MAX, 500); + inode_set_atime(inode, S32_MIN, 700); + EXT4_INODE_SET_MTIME(inode, raw); + EXT4_INODE_SET_ATIME(inode, raw); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_mtime_extra), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_atime_extra), 0U); + + inode_set_mtime(inode, 0, 999); + inode_set_atime(inode, 0, 999); + EXT4_INODE_GET_MTIME(inode, raw); + EXT4_INODE_GET_ATIME(inode, raw); + + KUNIT_EXPECT_EQ(test, inode_get_mtime_sec(inode), (time64_t)S32_MAX); + KUNIT_EXPECT_EQ(test, inode_get_mtime_nsec(inode), 0L); + KUNIT_EXPECT_EQ(test, inode_get_atime_sec(inode), (time64_t)S32_MIN); + KUNIT_EXPECT_EQ(test, inode_get_atime_nsec(inode), 0L); + + ctx->sbi.s_inode_size = INODE_TEST_INODE_SIZE; + ctx->ei.i_extra_isize = INODE_TEST_EXTRA_ISIZE; +} + +/* ------------------------------------------------------------------------- + * 2. Inode Checksum Calculation & Verification Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_csum_set_and_verify(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_inode *raw = &ctx->scratch_raw.raw; + + raw->i_mode = cpu_to_le16(S_IFREG | 0644); + raw->i_links_count = cpu_to_le16(1); + raw->i_extra_isize = cpu_to_le16(INODE_TEST_EXTRA_ISIZE); + + /* Full 32-bit checksum (256B inode, extra_isize = 32) */ + ext4_inode_csum_set(inode, raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + + /* Bit flip in low 16 bits fails */ + raw->i_checksum_lo ^= cpu_to_le16(0x0001); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + raw->i_checksum_lo ^= cpu_to_le16(0x0001); + + /* Bit flip in high 16 bits fails */ + raw->i_checksum_hi ^= cpu_to_le16(0x8000); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + raw->i_checksum_hi ^= cpu_to_le16(0x8000); + + /* Bit flip in raw inode body and in-body xattr tail (byte 200) fails */ + raw->i_mode ^= cpu_to_le16(0x0002); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + raw->i_mode ^= cpu_to_le16(0x0002); + ctx->scratch_raw.bytes[200] ^= 0x01; + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + ctx->scratch_raw.bytes[200] ^= 0x01; + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + + /* Non-Linux creator OS bypasses checksum verification */ + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_HURD); + raw->i_checksum_lo ^= cpu_to_le16(0xffff); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + + /* Disabled metadata_csum feature bypasses checksum verification */ + ext4_clear_feature_metadata_csum(ctx->sb); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + ext4_set_feature_metadata_csum(ctx->sb); + + /* 256B inode with extra_isize = 0 (excludes i_checksum_hi): 16-bit */ + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + ctx->ei.i_extra_isize = 0; + raw->i_extra_isize = 0; + raw->i_checksum_hi = cpu_to_le16(0xbeef); + ext4_inode_csum_set(inode, raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_checksum_hi), 0xbeef); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + raw->i_checksum_lo ^= cpu_to_le16(0x0010); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + + /* 256B inode with extra_isize = 4 (includes i_checksum_hi): 32-bit */ + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + ctx->ei.i_extra_isize = 4; + raw->i_extra_isize = cpu_to_le16(4); + ext4_inode_csum_set(inode, raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + raw->i_checksum_hi ^= cpu_to_le16(0x0001); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + + /* 128B old inode: 16-bit checksum in i_checksum_lo only */ + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + ctx->ei.i_extra_isize = 0; + ext4_inode_csum_set(inode, raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + raw->i_checksum_lo ^= cpu_to_le16(0x0100); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); +} + +/* ------------------------------------------------------------------------- + * 3. i_blocks Encoding & Decoding Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_blocks_encode_decode(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_inode *raw = &ctx->scratch_raw.raw; + blkcnt_t large_sectors; + int err; + + /* 32-bit sector count clears EXT4_INODE_HUGE_FILE */ + ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE); + inode->i_blocks = 0x12345678ULL; + err = ext4_inode_blocks_set_test(raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_blocks_lo), 0x12345678U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_blocks_high), 0); + KUNIT_EXPECT_EQ(test, ext4_inode_blocks_test(raw, &ctx->ei), + (blkcnt_t)0x12345678ULL); + + /* > 32-bit without huge_file feature fails with -EFSCORRUPTED */ + ext4_clear_feature_huge_file(ctx->sb); + inode->i_blocks = 0x100000000ULL; + err = ext4_inode_blocks_set_test(raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + ext4_set_feature_huge_file(ctx->sb); + + /* 48-bit sector count with huge_file feature (still sector units) */ + ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE); + inode->i_blocks = 0xabcd12345678ULL; + err = ext4_inode_blocks_set_test(raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_blocks_lo), 0x12345678U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_blocks_high), 0xabcd); + KUNIT_EXPECT_EQ(test, ext4_inode_blocks_test(raw, &ctx->ei), + (blkcnt_t)0xabcd12345678ULL); + + /* > 48-bit sector count scales by fs-block units and sets HUGE_FILE */ + large_sectors = 0x0002000000000008ULL; /* multiple of 8 (4K / 512B) */ + inode->i_blocks = large_sectors; + err = ext4_inode_blocks_set_test(raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)); + KUNIT_EXPECT_EQ(test, ext4_inode_blocks_test(raw, &ctx->ei), + large_sectors); +} + +/* ------------------------------------------------------------------------- + * 4. Raw Inode Serialization (ext4_fill_raw_inode) Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_fill_raw_inode(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_inode *raw = &ctx->scratch_raw.raw; + dev_t small_dev, large_dev; + int err; + + /* 32-bit uid/gid, 48-bit file_acl, 64-bit disksize & iversion, projid */ + ext4_set_feature_project(ctx->sb); + i_uid_write(inode, 0x12345678U); + i_gid_write(inode, 0x9abcdef0U); + ctx->ei.i_projid = make_kprojid(&init_user_ns, 0x55aa1122U); + ctx->ei.i_file_acl = 0x000344556677ULL; + ctx->ei.i_disksize = 0x0000000511223344LL; + inode_set_iversion_queried(inode, 0x000000078899aabbULL); + + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_low), 0x5678); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_high), 0x1234); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_gid_low), 0xdef0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_gid_high), 0x9abc); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_projid), 0x55aa1122U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_file_acl_lo), 0x44556677U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_file_acl_high), 0x0003); + KUNIT_EXPECT_EQ(test, ext4_isize(ctx->sb, raw), 0x0000000511223344LL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_disk_version), 0x8899aabbU); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_version_hi), 0x00000007U); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + + /* Non-default projid without PROJECT feature returns -EFSCORRUPTED */ + ext4_clear_feature_project(ctx->sb); + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + ctx->ei.i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + + /* NO_UID32 masks uid/gid high bits; HURD_COMPAT skips file_acl_high */ + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + raw->osd2.hurd2.h_i_mode_high = 0x7777; + set_opt(ctx->sb, NO_UID32); + set_opt2(ctx->sb, HURD_COMPAT); + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_high), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_gid_high), 0); + KUNIT_EXPECT_EQ(test, raw->osd2.hurd2.h_i_mode_high, 0x7777); + clear_opt(ctx->sb, NO_UID32); + clear_opt2(ctx->sb, HURD_COMPAT); + + /* Deleted inode (i_dtime != 0) clears uid_high/gid_high unless orphan */ + ctx->ei.i_dtime = 100; + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_high), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_gid_high), 0); + + ext4_set_inode_state(inode, EXT4_STATE_ORPHAN_FILE); + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_high), 0x1234); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_gid_high), 0x9abc); + ext4_clear_inode_state(inode, EXT4_STATE_ORPHAN_FILE); + ctx->ei.i_dtime = 0; + + /* EA_INODE stores raw iversion without shifting out flag bit */ + ext4_set_inode_flag(inode, EXT4_INODE_EA_INODE); + inode_set_iversion_raw(inode, 0x00000002cafebabeULL); + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_disk_version), 0xcafebabeU); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_version_hi), 0x00000002U); + ext4_clear_inode_flag(inode, EXT4_INODE_EA_INODE); + + /* Inline-data inode preserves raw_inode->i_block contents */ + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + raw->i_block[0] = cpu_to_le32(0xdeadbeefU); + ctx->ei.i_data[0] = cpu_to_le32(0x11111111U); + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_inline_off = 164; + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_block[0]), 0xdeadbeefU); + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ctx->ei.i_inline_off = 0; + + /* Special device inode encodes old vs new rdev into i_block[0]/[1] */ + inode->i_mode = S_IFCHR | 0600; + small_dev = MKDEV(8, 3); + inode->i_rdev = small_dev; + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, old_decode_dev(le32_to_cpu(raw->i_block[0])), + small_dev); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_block[1]), 0U); + + large_dev = MKDEV(512, 1024); + inode->i_rdev = large_dev; + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_block[0]), 0U); + KUNIT_EXPECT_EQ(test, new_decode_dev(le32_to_cpu(raw->i_block[1])), + large_dev); +} + +/* ------------------------------------------------------------------------- + * 5. Inode Dirtying, LARGE_FILE Promotion, and Lazytime Neighbor Flush + * ------------------------------------------------------------------------- + */ + +static void inode_test_mark_dirty_and_update(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *itable = inode_test_find_blk(ctx, + INODE_TEST_ITABLE_BLK0); + struct ext4_inode *raw; + struct ext4_inode *neighbor_raw; + struct inode *neighbor; + struct ext4_iloc iloc = {}; + handle_t *handle; + int ref_before, err; + + /* + * 1. EXT4_STATE_NEW + LARGE_FILE feature promotion in + * ext4_reserve_inode_write() / ext4_mark_iloc_dirty(). + */ + ext4_clear_feature_large_file(ctx->sb); + ext4_set_inode_state(inode, EXT4_STATE_NEW); + ctx->ei.i_disksize = 0x100000000LL; + inode->i_size = ctx->ei.i_disksize; + raw = inode_test_raw_slot(ctx, INODE_TEST_PRIMARY_INO, false); + memset(raw, 0xff, INODE_TEST_INODE_SIZE); + + handle = ext4_journal_start(inode, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + err = ext4_reserve_inode_write(handle, inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + err = ext4_mark_iloc_dirty(handle, inode, &iloc); + ext4_journal_stop(handle); + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, ext4_test_inode_state(inode, EXT4_STATE_NEW)); + KUNIT_EXPECT_TRUE(test, ext4_has_feature_large_file(ctx->sb)); + KUNIT_EXPECT_EQ(test, ext4_isize(ctx->sb, raw), 0x100000000LL); + KUNIT_EXPECT_TRUE(test, + !!(inode_state_read_once(inode) & I_METADATA_WRITEBACK)); + + /* + * 2. SB_LAZYTIME opportunistic neighbor timestamp flush + automatic + * extra_isize expansion via __ext4_mark_inode_dirty(). + */ + inode_test_prepare_valid_raw_inode(ctx, 13, S_IFREG | 0644); + memcpy(itable->cache_buf, itable->disk_buf, INODE_TEST_BLK_SIZE); + set_buffer_uptodate(&itable->bh); + + neighbor = ext4_iget(ctx->sb, 13, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(neighbor)); + inode_test_track_iget_inode(test, ctx, neighbor); + + inode_set_mtime(neighbor, 0x55667788LL, 1234); + spin_lock(&neighbor->i_lock); + inode_state_set(neighbor, I_DIRTY_TIME); + spin_unlock(&neighbor->i_lock); + + ctx->sb->s_flags |= SB_LAZYTIME; + ctx->ei.i_extra_isize = 16; + ctx->sbi.s_want_extra_isize = 32; + + handle = ext4_journal_start(inode, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + err = __ext4_mark_inode_dirty(handle, inode, __func__, __LINE__); + ext4_journal_stop(handle); + ctx->sb->s_flags &= ~SB_LAZYTIME; + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_extra_isize, (u16)32); + KUNIT_EXPECT_FALSE(test, + !!(inode_state_read_once(neighbor) & I_DIRTY_TIME)); + neighbor_raw = inode_test_raw_slot(ctx, 13, false); + KUNIT_EXPECT_EQ(test, le32_to_cpu(neighbor_raw->i_mtime), 0x55667788U); + KUNIT_EXPECT_EQ(test, + ext4_inode_csum_verify_test(neighbor, neighbor_raw, + EXT4_I(neighbor)), 1); + + /* 3. ext4_dirty_inode() updates raw inode on I_DIRTY_SYNC */ + inode_set_ctime(inode, 0x12340000LL, 0); + ext4_dirty_inode(inode, I_DIRTY_SYNC); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_ctime), 0x12340000U); + + /* 4. Emergency RO state returns -EROFS and drops iloc.bh cleanly */ + err = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + ref_before = atomic_read(&itable->bh.b_count); + set_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + err = ext4_mark_iloc_dirty(NULL, inode, &iloc); + clear_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, err, -EROFS); + KUNIT_EXPECT_EQ(test, atomic_read(&itable->bh.b_count), ref_before - 1); +} + +/* ------------------------------------------------------------------------- + * 6. Extra Isize Expansion Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_expand_extra_isize(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_iloc iloc = {}; + struct ext4_inode *raw; + struct ext4_xattr_ibody_header *ihdr; + struct ext4_xattr_entry *entry; + int no_expand = 0; + int err; + + err = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + raw = ext4_raw_inode(&iloc); + + /* Corrupted current i_extra_isize (unaligned or oversize) */ + ctx->ei.i_extra_isize = 13; + err = ext4_expand_extra_isize_test(inode, 32, &iloc, NULL, &no_expand); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + + ctx->ei.i_extra_isize = 200; + err = ext4_expand_extra_isize_test(inode, 204, &iloc, NULL, &no_expand); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + + /* Invalid target new_extra_isize */ + ctx->ei.i_extra_isize = 16; + KUNIT_EXPECT_EQ(test, + ext4_expand_extra_isize_test(inode, 12, &iloc, NULL, + &no_expand), -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_expand_extra_isize_test(inode, 200, &iloc, NULL, + &no_expand), -EINVAL); + + /* Clean expansion without xattrs zeroes newly covered extra space */ + memset((u8 *)raw + EXT4_GOOD_OLD_INODE_SIZE + 16, 0xaa, 32); + err = ext4_expand_extra_isize_test(inode, 32, &iloc, NULL, &no_expand); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_extra_isize, (u16)32); + KUNIT_EXPECT_EQ(test, *((u8 *)raw + EXT4_GOOD_OLD_INODE_SIZE + 16), 0); + KUNIT_EXPECT_EQ(test, *((u8 *)raw + EXT4_GOOD_OLD_INODE_SIZE + 31), 0); + KUNIT_EXPECT_EQ(test, *((u8 *)raw + EXT4_GOOD_OLD_INODE_SIZE + 32), + 0xaa); + + /* Guard checks in ext4_try_to_expand_extra_isize() */ + ctx->ei.i_extra_isize = 16; + ext4_set_inode_state(inode, EXT4_STATE_NO_EXPAND); + KUNIT_EXPECT_EQ(test, + ext4_try_to_expand_extra_isize_test(inode, 32, &iloc, + NULL), -EOVERFLOW); + ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND); + + ctx->sb->s_flags &= ~SB_ACTIVE; + KUNIT_EXPECT_EQ(test, + ext4_try_to_expand_extra_isize_test(inode, 32, &iloc, + NULL), -EBUSY); + ctx->sb->s_flags |= SB_ACTIVE; + + down_read(&ctx->ei.xattr_sem); + err = ext4_try_to_expand_extra_isize_test(inode, 32, &iloc, NULL); + up_read(&ctx->ei.xattr_sem); + KUNIT_EXPECT_EQ(test, err, -EBUSY); + + /* Expansion with valid in-body xattr shifts entry forward cleanly */ + memset(raw, 0, INODE_TEST_INODE_SIZE); + ctx->ei.i_extra_isize = 16; + raw->i_extra_isize = cpu_to_le16(16); + ext4_set_inode_state(inode, EXT4_STATE_XATTR); + ihdr = IHDR(inode, raw); + ihdr->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC); + entry = IFIRST(ihdr); + entry->e_name_len = 1; + entry->e_name_index = EXT4_XATTR_INDEX_USER; + entry->e_name[0] = 'k'; + entry->e_value_size = cpu_to_le32(4); + entry->e_value_offs = cpu_to_le16(INODE_TEST_INODE_SIZE - + EXT4_GOOD_OLD_INODE_SIZE - 16 - + sizeof(__u32) - 4); + memcpy((char *)IFIRST(ihdr) + le16_to_cpu(entry->e_value_offs), + "val!", 4); + inode_test_stamp_raw_csum(ctx, inode->i_ino, raw); + + /* ext4_expand_extra_isize() locks xattr_sem and consumes iloc.bh */ + err = ext4_expand_extra_isize(inode, 32, &iloc); + ctx->sb->s_flags &= ~SB_ACTIVE; + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_extra_isize, (u16)32); + ihdr = IHDR(inode, raw); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ihdr->h_magic), + (u32)EXT4_XATTR_MAGIC); +} + +/* ------------------------------------------------------------------------- + * 7. Inode Location Lookup (get_inode_loc / noio / fc_inode_loc) Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_get_inode_loc_variants(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *itable = inode_test_find_blk(ctx, + INODE_TEST_ITABLE_BLK0); + struct inode_test_blk *ibitmap = inode_test_find_blk(ctx, + INODE_TEST_IBITMAP_BLK); + struct ext4_iloc iloc = {}; + struct ext4_inode *raw; + int err; + + /* Out-of-range inode numbers */ + inode->i_ino = 1; + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc(inode, &iloc), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc_noio(inode, &iloc), + -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, ext4_get_fc_inode_loc(ctx->sb, 99999, &iloc), + -EFSCORRUPTED); + inode->i_ino = INODE_TEST_PRIMARY_INO; + + /* Missing group descriptor -> -EIO */ + ctx->fail_group_desc = true; + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc(inode, &iloc), -EIO); + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc_noio(inode, &iloc), -EIO); + ctx->fail_group_desc = false; + + /* Invalid inode table block in group descriptor -> -EFSCORRUPTED */ + ext4_inode_table_set(ctx->sb, &ctx->gdp, 1); + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc(inode, &iloc), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc_noio(inode, &iloc), + -EFSCORRUPTED); + ext4_inode_table_set(ctx->sb, &ctx->gdp, INODE_TEST_ITABLE_BLK0); + + /* noio variant: uncached -> -EAGAIN, non-uptodate -> -EAGAIN, hit -> 0 */ + itable->in_cache = false; + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc_noio(inode, &iloc), -EAGAIN); + itable->in_cache = true; + clear_buffer_uptodate(&itable->bh); + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc_noio(inode, &iloc), -EAGAIN); + KUNIT_EXPECT_EQ(test, atomic_read(&itable->bh.b_count), 1); + + set_buffer_uptodate(&itable->bh); + err = ext4_get_inode_loc_noio(inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, iloc.offset, + (unsigned long)((INODE_TEST_PRIMARY_INO - 1) * + INODE_TEST_INODE_SIZE)); + brelse(iloc.bh); + + /* + * Skip-I/O optimization: non-uptodate itable block + uptodate inode + * bitmap with ONLY primary inode bit set -> zero I/O reads! + */ + clear_buffer_uptodate(&itable->bh); + memset(itable->disk_buf, 0x77, INODE_TEST_BLK_SIZE); + memset(ibitmap->cache_buf, 0, INODE_TEST_BLK_SIZE); + ext4_set_bit(INODE_TEST_PRIMARY_INO - 1, ibitmap->cache_buf); + set_buffer_uptodate(&ibitmap->bh); + ctx->read_nowait_calls = 0; + i_uid_write(inode, 0x4242); + + err = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 0U); + raw = ext4_raw_inode(&iloc); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_low), 0x4242); + /* Neighbor slot was zeroed rather than read from 0x77 disk_buf */ + KUNIT_EXPECT_EQ(test, (u8)itable->cache_buf[0], 0); + brelse(iloc.bh); + + /* + * Neighbor inode bit also set in bitmap -> cannot skip I/O; performs + * disk read and triggers inode table readahead window calculation. + */ + clear_buffer_uptodate(&itable->bh); + ext4_set_bit(INODE_TEST_PRIMARY_INO, ibitmap->cache_buf); + ctx->sbi.s_inode_readahead_blks = 4; + ctx->read_nowait_calls = 0; + ctx->readahead_calls = 0; + + err = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + KUNIT_EXPECT_GT(test, ctx->readahead_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->first_readahead_blk, + (ext4_fsblk_t)INODE_TEST_ITABLE_BLK0); + KUNIT_EXPECT_EQ(test, (u8)itable->cache_buf[0], 0x77); + brelse(iloc.bh); + ctx->sbi.s_inode_readahead_blks = 0; + + /* Disk read -EIO propagates cleanly with balanced bh refcount */ + clear_buffer_uptodate(&itable->bh); + ctx->fail_read_eio = true; + err = ext4_get_fc_inode_loc(ctx->sb, INODE_TEST_PRIMARY_INO, &iloc); + ctx->fail_read_eio = false; + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&itable->bh.b_count), 1); +} + +/* ------------------------------------------------------------------------- + * 8. __ext4_iget() Valid Modes, Caching, & Special Inode Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_iget_validation_and_modes(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct ext4_inode *raw; + struct inode *inode, *cached; + + /* Illegal & special ino checks before VFS lookup */ + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_iget(ctx->sb, 0, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_iget(ctx->sb, 0, EXT4_IGET_HANDLE)), + -ESTALE); + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_iget(ctx->sb, 8, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_iget(ctx->sb, 99999, EXT4_IGET_HANDLE)), + -ESTALE); + + /* EXT4_IGET_NOWAIT returns -ENOENT when inode is not cached */ + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_iget(ctx->sb, 14, EXT4_IGET_NOWAIT)), + -ENOENT); + + /* Valid regular file inode load & cached NOWAIT / check_igot_inode */ + ext4_set_feature_project(ctx->sb); + inode_test_prepare_valid_raw_inode(ctx, 14, S_IFREG | 0640); + raw = inode_test_raw_slot(ctx, 14, true); + raw->i_uid_low = cpu_to_le16(0x2222); + raw->i_uid_high = cpu_to_le16(0x1111); + raw->i_gid_low = cpu_to_le16(0x4444); + raw->i_gid_high = cpu_to_le16(0x3333); + raw->i_projid = cpu_to_le32(77); + raw->i_size_lo = cpu_to_le32(8192); + raw->i_disk_version = cpu_to_le32(9); + raw->i_version_hi = cpu_to_le32(2); + inode_test_stamp_raw_csum(ctx, 14, raw); + + inode = ext4_iget(ctx->sb, 14, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + KUNIT_EXPECT_EQ(test, i_uid_read(inode), 0x11112222U); + KUNIT_EXPECT_EQ(test, i_gid_read(inode), 0x33334444U); + KUNIT_EXPECT_EQ(test, from_kprojid(&init_user_ns, EXT4_I(inode)->i_projid), + 77U); + KUNIT_EXPECT_EQ(test, i_size_read(inode), 8192LL); + KUNIT_EXPECT_EQ(test, inode_peek_iversion(inode), + (0x2ULL << 32) | 9ULL); + + cached = ext4_iget(ctx->sb, 14, EXT4_IGET_NOWAIT); + KUNIT_ASSERT_PTR_EQ(test, cached, inode); + iput(cached); + + /* Cached non-EA inode rejected when EXT4_IGET_EA_INODE requested */ + cached = ext4_iget(ctx->sb, 14, EXT4_IGET_EA_INODE); + KUNIT_EXPECT_EQ(test, PTR_ERR(cached), -EFSCORRUPTED); + + /* Valid fast symlink sets cached i_link */ + inode_test_prepare_valid_raw_inode(ctx, 15, S_IFLNK | 0777); + raw = inode_test_raw_slot(ctx, 15, true); + raw->i_flags = 0; + raw->i_size_lo = cpu_to_le32(11); + memcpy(raw->i_block, "target/path", 11); + inode_test_stamp_raw_csum(ctx, 15, raw); + + inode = ext4_iget(ctx->sb, 15, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + KUNIT_EXPECT_STREQ(test, inode->i_link, "target/path"); + + /* Valid character & block device special inodes (old & new rdev) */ + inode_test_prepare_valid_raw_inode(ctx, 16, S_IFCHR | 0600); + raw = inode_test_raw_slot(ctx, 16, true); + raw->i_block[0] = cpu_to_le32(old_encode_dev(MKDEV(4, 64))); + inode_test_stamp_raw_csum(ctx, 16, raw); + + inode = ext4_iget(ctx->sb, 16, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + KUNIT_EXPECT_EQ(test, inode->i_rdev, MKDEV(4, 64)); + + inode_test_prepare_valid_raw_inode(ctx, 17, S_IFBLK | 0600); + raw = inode_test_raw_slot(ctx, 17, true); + raw->i_block[0] = 0; + raw->i_block[1] = cpu_to_le32(new_encode_dev(MKDEV(300, 700))); + inode_test_stamp_raw_csum(ctx, 17, raw); + + inode = ext4_iget(ctx->sb, 17, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + KUNIT_EXPECT_EQ(test, inode->i_rdev, MKDEV(300, 700)); + + /* Uninitialized EXT4_BOOT_LOADER_INO requires EXT4_IGET_BAD */ + inode_test_prepare_valid_raw_inode(ctx, EXT4_BOOT_LOADER_INO, 0); + raw = inode_test_raw_slot(ctx, EXT4_BOOT_LOADER_INO, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, EXT4_BOOT_LOADER_INO, raw); + + inode = ext4_iget(ctx->sb, EXT4_BOOT_LOADER_INO, EXT4_IGET_SPECIAL); + KUNIT_EXPECT_EQ(test, PTR_ERR(inode), -EFSCORRUPTED); + + inode_test_prepare_valid_raw_inode(ctx, EXT4_BOOT_LOADER_INO, 0); + raw = inode_test_raw_slot(ctx, EXT4_BOOT_LOADER_INO, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, EXT4_BOOT_LOADER_INO, raw); + + inode = ext4_iget(ctx->sb, EXT4_BOOT_LOADER_INO, + EXT4_IGET_SPECIAL | EXT4_IGET_BAD); + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + KUNIT_EXPECT_TRUE(test, is_bad_inode(inode)); + cached = ext4_iget(ctx->sb, EXT4_BOOT_LOADER_INO, EXT4_IGET_SPECIAL); + KUNIT_EXPECT_EQ(test, PTR_ERR(cached), -EFSCORRUPTED); +} + +/* ------------------------------------------------------------------------- + * 9. __ext4_iget() On-Disk Corruption Rejection Matrix + * ------------------------------------------------------------------------- + */ + +static void inode_test_iget_corruptions(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct ext4_inode *raw; + struct inode *inode; + + /* 1. Unallocated inode with EXT4_IGET_HANDLE -> -ESTALE */ + inode_test_prepare_valid_raw_inode(ctx, 18, 0); + raw = inode_test_raw_slot(ctx, 18, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, 18, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 18, EXT4_IGET_HANDLE)), + -ESTALE); + + /* 2. Unaligned i_extra_isize -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 19, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 19, true); + raw->i_extra_isize = cpu_to_le16(5); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 19, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 3. Oversize i_extra_isize -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 20, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 20, true); + raw->i_extra_isize = cpu_to_le16(132); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 20, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 4. Bad checksum -> -EFSBADCRC (and EXT4_FC_REPLAY bypasses it) */ + inode_test_prepare_valid_raw_inode(ctx, 21, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 21, true); + raw->i_checksum_lo ^= cpu_to_le16(0x00ff); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 21, EXT4_IGET_NORMAL)), + -EFSBADCRC); + + inode_test_prepare_valid_raw_inode(ctx, 21, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 21, true); + raw->i_checksum_lo ^= cpu_to_le16(0x00ff); + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + inode = ext4_iget(ctx->sb, 21, EXT4_IGET_NORMAL); + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + + /* 5. Deleted inode (nlink=0) -> -ESTALE normally, allowed in ORPHAN_FS */ + inode_test_prepare_valid_raw_inode(ctx, 22, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 22, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, 22, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 22, EXT4_IGET_NORMAL)), + -ESTALE); + + inode_test_prepare_valid_raw_inode(ctx, 22, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 22, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, 22, raw); + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + inode = ext4_iget(ctx->sb, 22, EXT4_IGET_NORMAL); + ctx->sbi.s_mount_state &= ~EXT4_ORPHAN_FS; + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_put_tracked_inode(ctx, inode); + + /* 6. Unallocated special inode -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 7, S_IFREG | 0600); + raw = inode_test_raw_slot(ctx, 7, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, 7, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 7, EXT4_IGET_SPECIAL)), + -EFSCORRUPTED); + + /* 7. Conflicting INLINE_DATA | EXTENTS flags -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 23, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 23, true); + raw->i_flags = cpu_to_le32(EXT4_INLINE_DATA_FL | EXT4_EXTENTS_FL); + inode_test_stamp_raw_csum(ctx, 23, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 23, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 8. Indirect file i_size exceeding s_bitmap_maxbytes -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 24, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 24, true); + raw->i_flags = 0; + memset(raw->i_block, 0, sizeof(raw->i_block)); + raw->i_size_high = cpu_to_le32(0x1000); + inode_test_stamp_raw_csum(ctx, 24, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 24, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 9. Directory with INDEX flag when dir_index disabled -> -EFSCORRUPTED */ + ext4_clear_feature_dir_index(ctx->sb); + inode_test_prepare_valid_raw_inode(ctx, 25, S_IFDIR | 0755); + raw = inode_test_raw_slot(ctx, 25, true); + raw->i_flags |= cpu_to_le32(EXT4_INDEX_FL); + inode_test_stamp_raw_csum(ctx, 25, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 25, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + ext4_set_feature_dir_index(ctx->sb); + + /* 10. Out-of-range i_file_acl block -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 26, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 26, true); + raw->i_file_acl_lo = cpu_to_le32(INODE_TEST_TOTAL_BLKS + 100); + inode_test_stamp_raw_csum(ctx, 26, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 26, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 11. Corrupted extent header magic -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 27, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 27, true); + raw->i_block[0] = 0; + inode_test_stamp_raw_csum(ctx, 27, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 27, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 12. Symlink with IMMUTABLE flag & fast symlink with embedded NUL */ + inode_test_prepare_valid_raw_inode(ctx, 28, S_IFLNK | 0777); + raw = inode_test_raw_slot(ctx, 28, true); + raw->i_flags = cpu_to_le32(EXT4_IMMUTABLE_FL); + raw->i_size_lo = cpu_to_le32(3); + memcpy(raw->i_block, "abc", 3); + inode_test_stamp_raw_csum(ctx, 28, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 28, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + inode_test_prepare_valid_raw_inode(ctx, 28, S_IFLNK | 0777); + raw = inode_test_raw_slot(ctx, 28, true); + raw->i_flags = 0; + raw->i_size_lo = cpu_to_le32(5); + memcpy(raw->i_block, "ab\0cd", 5); + inode_test_stamp_raw_csum(ctx, 28, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 28, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 13. Bogus i_mode (0) with nlink > 0 & CASEFOLD without feature */ + inode_test_prepare_valid_raw_inode(ctx, 29, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 29, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + inode_test_prepare_valid_raw_inode(ctx, 30, S_IFDIR | 0755); + raw = inode_test_raw_slot(ctx, 30, true); + raw->i_flags |= cpu_to_le32(EXT4_CASEFOLD_FL); + inode_test_stamp_raw_csum(ctx, 30, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 30, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 14. EA_INODE opened without EXT4_IGET_EA_INODE: -ESTALE vs -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 31, S_IFREG | 0600); + raw = inode_test_raw_slot(ctx, 31, true); + raw->i_flags |= cpu_to_le32(EXT4_EA_INODE_FL); + inode_test_stamp_raw_csum(ctx, 31, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 31, EXT4_IGET_HANDLE)), + -ESTALE); + + inode_test_prepare_valid_raw_inode(ctx, 31, S_IFREG | 0600); + raw = inode_test_raw_slot(ctx, 31, true); + raw->i_flags |= cpu_to_le32(EXT4_EA_INODE_FL); + inode_test_stamp_raw_csum(ctx, 31, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 31, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); +} + +/* ------------------------------------------------------------------------- + * 10. Fast Symlink Classification & ext4_can_truncate() Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_fast_symlink_and_can_truncate(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + + /* Fast symlink classification with/without external xattr & EA_INODE */ + inode_test_reset_mock_inode(ctx, S_IFLNK | 0777); + inode->i_size = 20; + inode->i_blocks = 0; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 1); + + /* External xattr block accounts for 8 512B sectors when !EA_INODE */ + ctx->ei.i_file_acl = INODE_TEST_META_BLK0; + inode->i_blocks = 8; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 1); + inode->i_blocks = 16; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 0); + + /* With EA_INODE feature, fast symlink depends on 0 < i_size < 60 */ + ext4_set_feature_ea_inode(ctx->sb); + inode->i_size = 0; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 0); + inode->i_size = 20; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 1); + inode->i_size = EXT4_N_BLOCKS * 4; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 0); + ext4_clear_feature_ea_inode(ctx->sb); + + /* Inline-data symlink is not classified as a legacy fast symlink */ + inode->i_size = 20; + inode->i_blocks = 8; + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_inline_off = 164; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 0); + + /* ext4_can_truncate() across file types and fast vs slow symlinks */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 1); + + inode_test_reset_mock_inode(ctx, S_IFDIR | 0755); + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 1); + + inode_test_reset_mock_inode(ctx, S_IFIFO | 0600); + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 0); + + inode_test_reset_mock_inode(ctx, S_IFCHR | 0600); + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 0); + + inode_test_reset_mock_inode(ctx, S_IFLNK | 0777); + inode->i_blocks = 0; + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 0); + inode->i_blocks = 8; + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 1); +} + +/* ------------------------------------------------------------------------- + * 11. VFS Inode Flags, Address Space Ops, and Folio Order Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_flags_aops_mapping_order(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + const struct address_space_operations *da_aops, *nodelalloc_aops; + const struct address_space_operations *jdata_aops; + + /* 1. ext4_set_inode_flags() flag translation & S_DAX policy */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + ctx->ei.i_flags = EXT4_SYNC_FL | EXT4_APPEND_FL | EXT4_IMMUTABLE_FL | + EXT4_NOATIME_FL | EXT4_DIRSYNC_FL | EXT4_VERITY_FL; + ext4_set_inode_flags(inode, true); + KUNIT_EXPECT_EQ(test, + inode->i_flags & (S_SYNC | S_APPEND | S_IMMUTABLE | + S_NOATIME | S_DIRSYNC | S_VERITY), + (unsigned int)(S_SYNC | S_APPEND | S_IMMUTABLE | + S_NOATIME | S_DIRSYNC | S_VERITY)); + + ctx->ei.i_flags = 0; + ext4_set_inode_flags(inode, false); + KUNIT_EXPECT_EQ(test, + inode->i_flags & (S_SYNC | S_APPEND | S_IMMUTABLE | + S_NOATIME | S_DIRSYNC), 0U); + + /* S_DAX enabled when BDEV_IS_DAX + DAX_ALWAYS on regular extent file */ + set_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + set_opt(ctx->sb, DAX_ALWAYS); + ext4_set_inode_flags(inode, true); + if (IS_ENABLED(CONFIG_FS_DAX)) + KUNIT_EXPECT_TRUE(test, IS_DAX(inode)); + + /* DAX_NEVER and JOURNAL_DATA both suppress S_DAX */ + clear_opt(ctx->sb, DAX_ALWAYS); + set_opt2(ctx->sb, DAX_NEVER); + inode->i_flags &= ~S_DAX; + ext4_set_inode_flags(inode, true); + KUNIT_EXPECT_FALSE(test, IS_DAX(inode)); + clear_opt2(ctx->sb, DAX_NEVER); + + clear_opt(ctx->sb, DELALLOC); + ctx->ei.i_flags = EXT4_DAX_FL | EXT4_JOURNAL_DATA_FL; + ctx->sbi.s_journal = (journal_t *)1; + ext4_set_inode_flags(inode, true); + ctx->sbi.s_journal = NULL; + set_opt(ctx->sb, DELALLOC); + KUNIT_EXPECT_FALSE(test, IS_DAX(inode)); + clear_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + + /* 2. ext4_set_aops() dispatch across delalloc, ordered, journalled */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + set_opt(ctx->sb, DELALLOC); + ext4_set_aops(inode); + da_aops = inode->i_mapping->a_ops; + KUNIT_EXPECT_NOT_NULL(test, da_aops); + + clear_opt(ctx->sb, DELALLOC); + ext4_set_aops(inode); + nodelalloc_aops = inode->i_mapping->a_ops; + KUNIT_EXPECT_PTR_NE(test, da_aops, nodelalloc_aops); + + ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + ctx->sbi.s_journal = (journal_t *)1; + ext4_set_aops(inode); + ctx->sbi.s_journal = NULL; + jdata_aops = inode->i_mapping->a_ops; + KUNIT_EXPECT_PTR_NE(test, jdata_aops, da_aops); + KUNIT_EXPECT_PTR_NE(test, jdata_aops, nodelalloc_aops); + set_opt(ctx->sb, DELALLOC); + + /* 3. ext4_set_inode_mapping_order() clamping */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + ctx->sbi.s_min_folio_order = 0; + ctx->sbi.s_max_folio_order = 3; + ext4_set_inode_mapping_order(inode); + if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) { + KUNIT_EXPECT_EQ(test, + mapping_min_folio_order(inode->i_mapping), 0U); + KUNIT_EXPECT_EQ(test, + mapping_max_folio_order(inode->i_mapping), 3U); + + ctx->sbi.s_min_folio_order = 1; + ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + ext4_set_inode_mapping_order(inode); + KUNIT_EXPECT_EQ(test, + mapping_max_folio_order(inode->i_mapping), 1U); + } + ctx->sbi.s_min_folio_order = 0; + ctx->sbi.s_max_folio_order = 0; +} + +/* ------------------------------------------------------------------------- + * 12. Project ID, DIO Alignment, and getattr / file_getattr Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_projid_dio_and_getattr(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct path path = { .dentry = &ctx->root_dentry }; + struct kstat stat = {}; + kprojid_t projid = {}; + int err; + + /* ext4_get_projid(): -EOPNOTSUPP without feature, value with feature */ + ctx->ei.i_projid = make_kprojid(&init_user_ns, 314); + ext4_clear_feature_project(ctx->sb); + KUNIT_EXPECT_EQ(test, ext4_get_projid(inode, &projid), -EOPNOTSUPP); + ext4_set_feature_project(ctx->sb); + KUNIT_EXPECT_EQ(test, ext4_get_projid(inode, &projid), 0); + KUNIT_EXPECT_EQ(test, from_kprojid(&init_user_ns, projid), 314U); + + /* ext4_dio_alignment(): 1 default, blocksize encrypted, 0 jdata/inline */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ext4_dio_alignment(inode), 1U); + + inode->i_flags |= S_ENCRYPTED; + KUNIT_EXPECT_EQ(test, ext4_dio_alignment(inode), + (u32)INODE_TEST_BLK_SIZE); + inode->i_flags &= ~S_ENCRYPTED; + + clear_opt(ctx->sb, DELALLOC); + ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + ctx->sbi.s_journal = (journal_t *)1; + KUNIT_EXPECT_EQ(test, ext4_dio_alignment(inode), 0U); + ctx->sbi.s_journal = NULL; + ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + set_opt(ctx->sb, DELALLOC); + + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ctx->ei.i_inline_off = 164; + KUNIT_EXPECT_EQ(test, ext4_dio_alignment(inode), 0U); + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ctx->ei.i_inline_off = 0; + + /* ext4_getattr() omits delalloc; ext4_file_getattr() includes it */ + inode->i_size = 8192; + inode->i_blocks = 16; + ctx->ei.i_reserved_data_blocks = 2; + ctx->ei.i_crtime.tv_sec = 0x56781234LL; + ctx->ei.i_crtime.tv_nsec = 999L; + ctx->ei.i_flags |= EXT4_APPEND_FL | EXT4_IMMUTABLE_FL | EXT4_NODUMP_FL; + ctx->sbi.s_awu_min = 4096; + ctx->sbi.s_awu_max = 16384; + + err = ext4_getattr(&nop_mnt_idmap, &path, &stat, + STATX_BASIC_STATS | STATX_BTIME | + STATX_DIOALIGN | STATX_WRITE_ATOMIC, 0); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, stat.blocks, 16ULL); + + memset(&stat, 0, sizeof(stat)); + err = ext4_file_getattr(&nop_mnt_idmap, &path, &stat, + STATX_BASIC_STATS | STATX_BTIME | + STATX_DIOALIGN | STATX_WRITE_ATOMIC, 0); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, !!(stat.result_mask & STATX_BTIME)); + KUNIT_EXPECT_EQ(test, stat.btime.tv_sec, 0x56781234LL); + KUNIT_EXPECT_EQ(test, stat.btime.tv_nsec, 999L); + /* 16 on-disk sectors + 2 reserved 4K blocks (16 sectors) = 32 sectors */ + KUNIT_EXPECT_EQ(test, stat.blocks, 32ULL); + KUNIT_EXPECT_EQ(test, stat.attributes & (STATX_ATTR_APPEND | + STATX_ATTR_IMMUTABLE | + STATX_ATTR_NODUMP), + (u64)(STATX_ATTR_APPEND | STATX_ATTR_IMMUTABLE | + STATX_ATTR_NODUMP)); + KUNIT_EXPECT_EQ(test, stat.dio_mem_align, 512U); + KUNIT_EXPECT_EQ(test, stat.dio_offset_align, 512U); + KUNIT_EXPECT_EQ(test, stat.atomic_write_unit_min, 4096U); + KUNIT_EXPECT_EQ(test, stat.atomic_write_unit_max, 16384U); + + /* Inline-data file reports simulated 512B sectors from i_size */ + ctx->ei.i_reserved_data_blocks = 0; + inode->i_blocks = 0; + inode->i_size = 1200; + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_inline_off = 164; + memset(&stat, 0, sizeof(stat)); + err = ext4_file_getattr(&nop_mnt_idmap, &path, &stat, + STATX_BASIC_STATS, 0); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, stat.blocks, 3ULL); + ctx->sbi.s_awu_min = 0; + ctx->sbi.s_awu_max = 0; +} + +/* ------------------------------------------------------------------------- + * 13. Delayed Allocation Reservation, Claim, Release & Nonda Switch Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_da_reserve_and_release(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + int err; + + percpu_counter_set(&ctx->sbi.s_freeclusters_counter, + max_t(s64, 100, EXT4_FREECLUSTERS_WATERMARK + 100)); + percpu_counter_set(&ctx->sbi.s_dirtyclusters_counter, 0); + + /* Reserve 5 clusters */ + err = ext4_da_reserve_space_test(inode, 5); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 5U); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_dirtyclusters_counter), + 5LL); + + /* Claim 2 clusters via ext4_da_update_reserve_space() */ + ext4_da_update_reserve_space(inode, 2, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 3U); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_dirtyclusters_counter), + 3LL); + + /* Release 2 clusters via ext4_da_release_space() */ + ext4_da_release_space(inode, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 3U); + ext4_da_release_space(inode, 2); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + + /* Underflow in update_reserve_space clamps to 0 cleanly */ + kunit_warning_suppress(test) { + ext4_da_update_reserve_space(inode, 4, 0); + } + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 0U); + + /* Underflow in release_space clamps to 0 cleanly */ + err = ext4_da_reserve_space_test(inode, 1); + KUNIT_EXPECT_EQ(test, err, 0); + kunit_warning_suppress(test) { + ext4_da_release_space(inode, 3); + } + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 0U); + + /* Exhausted free clusters -> -ENOSPC & ext4_nonda_switch() */ + KUNIT_EXPECT_EQ(test, ext4_nonda_switch_test(ctx->sb), 0); + percpu_counter_set(&ctx->sbi.s_freeclusters_counter, 2); + percpu_counter_set(&ctx->sbi.s_dirtyclusters_counter, 4); + KUNIT_EXPECT_EQ(test, ext4_nonda_switch_test(ctx->sb), 1); + + percpu_counter_set(&ctx->sbi.s_freeclusters_counter, 0); + percpu_counter_set(&ctx->sbi.s_dirtyclusters_counter, 0); + KUNIT_EXPECT_EQ(test, ext4_da_reserve_space_test(inode, 1), -ENOSPC); +} + +/* ------------------------------------------------------------------------- + * 14. Bigalloc Delayed Allocation & Cluster Sharing Accounting Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_enable_bigalloc(struct inode_test_ctx *ctx, + unsigned int cluster_ratio) +{ + ext4_set_feature_bigalloc(ctx->sb); + ctx->sbi.s_cluster_ratio = cluster_ratio; + ctx->sbi.s_cluster_bits = ilog2(cluster_ratio); + ctx->sbi.s_clusters_per_group = + ctx->sbi.s_blocks_per_group / cluster_ratio; +} + +static void inode_test_insert_leaf_extent(struct inode *inode, ext4_lblk_t lblk, + u16 len, ext4_fsblk_t pblk, + bool unwritten) +{ + struct ext4_extent_header *eh = ext_inode_hdr(inode); + unsigned int idx = le16_to_cpu(eh->eh_entries); + struct ext4_extent *ex = EXT_FIRST_EXTENT(eh) + idx; + + ex->ee_block = cpu_to_le32(lblk); + ex->ee_len = cpu_to_le16(len); + if (unwritten) + ext4_ext_mark_unwritten(ex); + ext4_ext_store_pblock(ex, pblk); + eh->eh_entries = cpu_to_le16(idx + 1); + ext4_es_remove_extent(inode, lblk, len); +} + +static void inode_test_da_bigalloc_clusters(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_map_blocks map = {}; + struct buffer_head bh = {}; + int state_unalloc, state_delayed, state_mapped; + int err; + + inode_test_enable_bigalloc(ctx, 4); + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + /* Pre-populate written extent at lblk 4 (lclu 1) -> pblk 104 */ + inode_test_insert_leaf_extent(inode, 4, 1, INODE_TEST_DATA_BLK0 + 4, + false); + /* Pre-populate unwritten extent at lblk 8 (lclu 2) -> pblk 108 */ + inode_test_insert_leaf_extent(inode, 8, 2, 108, true); + + down_write(&ctx->ei.i_data_sem); + state_unalloc = ext4_clu_alloc_state_test(inode, 0); + state_mapped = ext4_clu_alloc_state_test(inode, 5); + up_write(&ctx->ei.i_data_sem); + KUNIT_EXPECT_EQ(test, state_unalloc, 0); + KUNIT_EXPECT_EQ(test, state_mapped, 2); + + /* 1. First block in unallocated cluster 0 reserves 1 cluster */ + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 0, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_delay(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_new(&bh)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + + down_write(&ctx->ei.i_data_sem); + state_delayed = ext4_clu_alloc_state_test(inode, 2); + up_write(&ctx->ei.i_data_sem); + KUNIT_EXPECT_EQ(test, state_delayed, 1); + + /* 2. Sibling block in cluster 0 shares existing delalloc reservation */ + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 1, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_delay(&bh)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + + /* Multi-block ext4_da_map_blocks() across [lblk 2..3] in cluster 0 */ + map = (struct ext4_map_blocks){ .m_lblk = 2, .m_len = 2 }; + err = ext4_da_map_blocks_test(inode, &map); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, map.m_len, 2U); + KUNIT_EXPECT_TRUE(test, !!(map.m_flags & EXT4_MAP_DELAYED)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + + map = (struct ext4_map_blocks){ .m_lblk = 0, .m_len = 4 }; + err = ext4_da_map_blocks_test(inode, &map); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, map.m_len, 4U); + KUNIT_EXPECT_TRUE(test, !!(map.m_flags & EXT4_MAP_DELAYED)); + + /* + * 3. Delayed block in cluster 1 (sharing written lblk 4) reserves 0 new + * clusters and records a pending reservation on cluster 1! + */ + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 5, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_delay(&bh)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 4)); + + /* 4. Already-written block 4 maps directly without BH_Delay */ + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 4, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_mapped(&bh)); + KUNIT_EXPECT_FALSE(test, buffer_delay(&bh)); + KUNIT_EXPECT_EQ(test, (ext4_fsblk_t)bh.b_blocknr, + (ext4_fsblk_t)(INODE_TEST_DATA_BLK0 + 4)); + + /* + * 5. Unwritten block 8 sets BH_Unwritten | BH_New | BH_Mapped; + * delayed sibling hole block 10 in the same cluster 2 records a + * pending reservation without reserving an extra cluster. + */ + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 8, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_unwritten(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_new(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_mapped(&bh)); + KUNIT_EXPECT_EQ(test, (ext4_fsblk_t)bh.b_blocknr, 108ULL); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 8)); + + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 10, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_delay(&bh)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 8)); + + /* Removing ES extents releases the 1 reserved cluster via da_release */ + down_write(&ctx->ei.i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + up_write(&ctx->ei.i_data_sem); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 0U); +} + +/* ------------------------------------------------------------------------- + * 15. ext4_map_blocks() Lookup, Caching, Allocation, Zeroout & Validity Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_map_blocks_paths(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_map_blocks map = {}; + struct extent_status es = {}; + handle_t *handle; + int ret; + + /* 1. Out-of-range logical block -> -EFSCORRUPTED */ + map.m_lblk = EXT_MAX_BLOCKS; + map.m_len = 1; + KUNIT_EXPECT_EQ(test, ext4_map_blocks(NULL, inode, &map, 0), + -EFSCORRUPTED); + + /* 2. CACHED_NOWAIT miss returns 0 without querying extent tree */ + inode_test_insert_leaf_extent(inode, 0, 2, INODE_TEST_DATA_BLK0, false); + map = (struct ext4_map_blocks){ .m_lblk = 0, .m_len = 2 }; + ret = ext4_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CACHED_NOWAIT); + KUNIT_EXPECT_EQ(test, ret, 0); + + /* 3. ES miss queries extent tree, caches written extent; NOWAIT hits */ + map = (struct ext4_map_blocks){ .m_lblk = 0, .m_len = 2 }; + ret = ext4_map_blocks(NULL, inode, &map, 0); + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, map.m_pblk, (ext4_fsblk_t)INODE_TEST_DATA_BLK0); + KUNIT_EXPECT_TRUE(test, !!(map.m_flags & EXT4_MAP_MAPPED)); + + map = (struct ext4_map_blocks){ .m_lblk = 1, .m_len = 1 }; + ret = ext4_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CACHED_NOWAIT); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, map.m_pblk, + (ext4_fsblk_t)(INODE_TEST_DATA_BLK0 + 1)); + + /* 4. ES delayed & hole hits */ + down_write(&ctx->ei.i_data_sem); + KUNIT_EXPECT_EQ(test, ext4_insert_delayed_blocks_test(inode, 4, 2), 0); + ext4_es_insert_extent(inode, 6, 2, ~0, EXTENT_STATUS_HOLE, 0); + up_write(&ctx->ei.i_data_sem); + + map = (struct ext4_map_blocks){ .m_lblk = 4, .m_len = 2 }; + ret = ext4_map_blocks(NULL, inode, &map, 0); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_TRUE(test, !!(map.m_flags & EXT4_MAP_DELAYED)); + + map = (struct ext4_map_blocks){ .m_lblk = 6, .m_len = 2 }; + ret = ext4_map_blocks(NULL, inode, &map, 0); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_flags, 0U); + + /* 5. Block allocation + EXT4_GET_BLOCKS_CREATE_ZERO & zeroout error */ + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0 + 2; + ctx->zeroout_calls = 0; + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 4); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + map = (struct ext4_map_blocks){ .m_lblk = 10, .m_len = 2 }; + ret = ext4_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE_ZERO); + ext4_journal_stop(handle); + + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, map.m_pblk, + (ext4_fsblk_t)(INODE_TEST_DATA_BLK0 + 2)); + KUNIT_EXPECT_TRUE(test, !!(map.m_flags & EXT4_MAP_NEW)); + KUNIT_EXPECT_EQ(test, ctx->zeroout_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_lblk, 10U); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_len, 2U); + + /* Failed zeroout returns error BEFORE caching written extent in ES */ + ctx->fail_zeroout_err = -EIO; + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 4); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + map = (struct ext4_map_blocks){ .m_lblk = 12, .m_len = 1 }; + ret = ext4_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE_ZERO); + ext4_journal_stop(handle); + ctx->fail_zeroout_err = 0; + + KUNIT_EXPECT_EQ(test, ret, -EIO); + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 12, NULL, &es, NULL), + 1); + KUNIT_EXPECT_FALSE(test, ext4_es_is_written(&es)); + KUNIT_EXPECT_TRUE(test, ext4_es_is_hole(&es)); + + /* 6. check_block_validity() rejects out-of-bounds pblk in extent */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + inode_test_insert_leaf_extent(inode, 0, 1, INODE_TEST_TOTAL_BLKS + 50, + false); + map = (struct ext4_map_blocks){ .m_lblk = 0, .m_len = 1 }; + KUNIT_EXPECT_EQ(test, ext4_map_blocks(NULL, inode, &map, 0), + -EFSCORRUPTED); +} + +/* ------------------------------------------------------------------------- + * 16. ext4_get_block, getblk, bread, bread_batch & walk_page_buffers Tests + * ------------------------------------------------------------------------- + */ + +static int inode_test_walk_cb(handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + int *visited = (int *)bh->b_private; + + (*visited)++; + if (*visited < 0) + return -EINVAL; + return 0; +} + +static void inode_test_get_block_bread_and_walk_buffers(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *dblk0 = inode_test_find_blk(ctx, + INODE_TEST_DATA_BLK0); + struct inode_test_blk *dblk1 = inode_test_find_blk(ctx, + INODE_TEST_DATA_BLK0 + 1); + struct buffer_head bh = {}; + struct buffer_head *res_bh; + struct buffer_head *batch[3] = {}; + struct buffer_head ring[4] = {}; + int visited[4] = { 0, 0, 0, 0 }; + int partial = 0; + handle_t *handle; + int i, err; + + /* 1. ext4_get_block() inline -ERANGE, hole lookup, mapped & create */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_inline_off = 164; + bh.b_size = INODE_TEST_BLK_SIZE; + KUNIT_EXPECT_EQ(test, ext4_get_block(inode, 0, &bh, 0), -ERANGE); + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ctx->ei.i_inline_off = 0; + + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + KUNIT_EXPECT_EQ(test, ext4_get_block(inode, 0, &bh, 0), 0); + KUNIT_EXPECT_FALSE(test, buffer_mapped(&bh)); + + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0; + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 4); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + err = ext4_get_block_unwritten(inode, 0, &bh, 1); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_mapped(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_unwritten(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_new(&bh)); + + /* 2. ext4_getblk() hole -> NULL, CREATE new block zeroes & dirties bh */ + res_bh = ext4_getblk(NULL, inode, 5, 0); + KUNIT_EXPECT_NULL(test, res_bh); + + clear_buffer_uptodate(&dblk1->bh); + memset(dblk1->cache_buf, 0xcd, INODE_TEST_BLK_SIZE); + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0 + 1; + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 4); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + res_bh = ext4_getblk(handle, inode, 1, EXT4_GET_BLOCKS_CREATE); + ext4_journal_stop(handle); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(res_bh)); + KUNIT_EXPECT_TRUE(test, buffer_uptodate(res_bh)); + KUNIT_EXPECT_EQ(test, (u8)dblk1->cache_buf[0], 0); + brelse(res_bh); + + /* 3. ext4_bread() disk read & -EIO error cleanup */ + inode_test_reset_mock_inode(ctx, S_IFDIR | 0755); + inode_test_insert_leaf_extent(inode, 0, 1, INODE_TEST_DATA_BLK0, false); + inode_test_insert_leaf_extent(inode, 2, 1, INODE_TEST_DATA_BLK0 + 1, + false); + clear_buffer_uptodate(&dblk0->bh); + memset(dblk0->disk_buf, 0x3c, INODE_TEST_BLK_SIZE); + ctx->read_lock_calls = 0; + + res_bh = ext4_bread(NULL, inode, 0, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(res_bh)); + KUNIT_EXPECT_EQ(test, ctx->read_lock_calls, 1U); + KUNIT_EXPECT_EQ(test, (u8)res_bh->b_data[0], 0x3c); + brelse(res_bh); + + clear_buffer_uptodate(&dblk0->bh); + ctx->fail_read_eio = true; + res_bh = ext4_bread(NULL, inode, 0, 0); + ctx->fail_read_eio = false; + KUNIT_EXPECT_EQ(test, PTR_ERR(res_bh), -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&dblk0->bh.b_count), 1); + + /* 4. ext4_bread_batch() across [mapped, hole, mapped] & -EIO cleanup */ + clear_buffer_uptodate(&dblk0->bh); + clear_buffer_uptodate(&dblk1->bh); + memset(dblk1->disk_buf, 0x99, INODE_TEST_BLK_SIZE); + err = ext4_bread_batch(inode, 0, 3, true, batch); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_NOT_NULL(test, batch[0]); + KUNIT_EXPECT_NULL(test, batch[1]); + KUNIT_EXPECT_NOT_NULL(test, batch[2]); + KUNIT_EXPECT_EQ(test, (u8)batch[2]->b_data[0], 0x99); + for (i = 0; i < 3; i++) + brelse(batch[i]); + + memset(batch, 0, sizeof(batch)); + clear_buffer_uptodate(&dblk0->bh); + ctx->fail_read_eio = true; + err = ext4_bread_batch(inode, 0, 3, true, batch); + ctx->fail_read_eio = false; + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&dblk0->bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&dblk1->bh.b_count), 1); + + /* 5. ext4_walk_page_buffers() sub-page range, partial & error stop */ + for (i = 0; i < 4; i++) { + ring[i].b_size = 1024; + ring[i].b_this_page = &ring[(i + 1) % 4]; + ring[i].b_private = &visited[i]; + if (i != 3) + set_buffer_uptodate(&ring[i]); + } + err = ext4_walk_page_buffers(NULL, inode, &ring[0], 1024, 3072, + &partial, inode_test_walk_cb); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, visited[0], 0); + KUNIT_EXPECT_EQ(test, visited[1], 1); + KUNIT_EXPECT_EQ(test, visited[2], 1); + KUNIT_EXPECT_EQ(test, visited[3], 0); + KUNIT_EXPECT_EQ(test, partial, 1); + + set_buffer_uptodate(&ring[3]); + partial = 0; + err = ext4_walk_page_buffers(NULL, inode, &ring[0], 1024, 3072, + &partial, inode_test_walk_cb); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, partial, 0); + + visited[1] = -2; + err = ext4_walk_page_buffers(NULL, inode, &ring[0], 1024, 3072, + NULL, inode_test_walk_cb); + KUNIT_EXPECT_EQ(test, err, -EINVAL); + KUNIT_EXPECT_EQ(test, visited[2], 2); +} + +/* ------------------------------------------------------------------------- + * 17. ext4_iomap_begin, ext4_iomap_report_ops, and Atomic Writes Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_iomap_and_atomic_writes(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct iomap iomap = {}; + struct iomap srcmap = {}; + struct iomap_iter iter = {}; + int err; + + /* 1. Offset past EXT4_MAX_LOGICAL_BLOCK -> -EINVAL */ + err = ext4_iomap_begin(inode, + ((loff_t)EXT4_MAX_LOGICAL_BLOCK + 1) << 12, + 4096, 0, &iomap, &srcmap); + KUNIT_EXPECT_EQ(test, err, -EINVAL); + + /* 2. Inline-data: iomap_begin warns & returns -ERANGE; report works */ + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_inline_off = 164; + ctx->ei.i_inline_size = 60; + inode->i_size = 24; + + kunit_warning_suppress(test) { + err = ext4_iomap_begin(inode, 0, 24, 0, &iomap, &srcmap); + } + KUNIT_EXPECT_EQ(test, err, -ERANGE); + + iter = (struct iomap_iter){ + .inode = inode, .pos = 0, .len = 24, .flags = IOMAP_REPORT, + }; + err = ext4_iomap_report_ops.iomap_next(&iter, &iter.iomap, + &iter.srcmap); + KUNIT_EXPECT_GT(test, err, 0); + KUNIT_EXPECT_EQ(test, iter.iomap.type, (u16)IOMAP_INLINE); + + iter = (struct iomap_iter){ + .inode = inode, .pos = 60, .len = 24, .flags = IOMAP_REPORT, + }; + err = ext4_iomap_report_ops.iomap_next(&iter, &iter.iomap, + &iter.srcmap); + KUNIT_EXPECT_EQ(test, err, -ENOENT); + + /* 3. Indirect report past s_bitmap_maxbytes returns IOMAP_HOLE */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + memset(ctx->ei.i_data, 0, sizeof(ctx->ei.i_data)); + iter = (struct iomap_iter){ + .inode = inode, + .pos = ctx->sbi.s_bitmap_maxbytes, + .len = 4096, + .flags = IOMAP_REPORT, + }; + err = ext4_iomap_report_ops.iomap_next(&iter, &iter.iomap, + &iter.srcmap); + KUNIT_EXPECT_GT(test, err, 0); + KUNIT_EXPECT_EQ(test, iter.iomap.type, (u16)IOMAP_HOLE); + + /* Indirect DIO write to hole inside i_size returns -ENOTBLK */ + inode->i_size = 8192; + err = ext4_iomap_begin(inode, 0, 4096, IOMAP_WRITE | IOMAP_DIRECT, + &iomap, &srcmap); + KUNIT_EXPECT_EQ(test, err, -ENOTBLK); + + /* 4. Read mappings (MAPPED, UNWRITTEN, DELALLOC, HOLE, DAX offset) */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + inode->i_size = 16384; + ctx->sbi.s_dax_part_off = 0x200000ULL; + down_write(&ctx->ei.i_data_sem); + ext4_es_insert_extent(inode, 0, 1, INODE_TEST_DATA_BLK0, + EXTENT_STATUS_WRITTEN, 0); + ext4_es_insert_extent(inode, 1, 1, INODE_TEST_DATA_BLK0 + 1, + EXTENT_STATUS_UNWRITTEN, 0); + KUNIT_EXPECT_EQ(test, ext4_insert_delayed_blocks_test(inode, 2, 1), 0); + ext4_es_insert_extent(inode, 3, 1, ~0, EXTENT_STATUS_HOLE, 0); + up_write(&ctx->ei.i_data_sem); + + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 0, 4096, IOMAP_DAX, &iomap, + &srcmap), 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_MAPPED); + KUNIT_EXPECT_EQ(test, iomap.addr, + ((u64)INODE_TEST_DATA_BLK0 << 12) + + (IS_ENABLED(CONFIG_FS_DAX) ? 0x200000ULL : 0ULL)); + ctx->sbi.s_dax_part_off = 0; + + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 4096, 4096, 0, &iomap, &srcmap), + 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_UNWRITTEN); + + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 8192, 4096, 0, &iomap, &srcmap), + 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_DELALLOC); + + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 12288, 4096, 0, &iomap, + &srcmap), 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_HOLE); + + iter = (struct iomap_iter){ + .inode = inode, .pos = 0, .len = 4096, .flags = 0, + }; + err = ext4_iomap_ops.iomap_next(&iter, &iter.iomap, &iter.srcmap); + KUNIT_EXPECT_GT(test, err, 0); + KUNIT_EXPECT_EQ(test, iter.iomap.type, (u16)IOMAP_MAPPED); + KUNIT_EXPECT_EQ(test, iter.iomap.addr, + (u64)INODE_TEST_DATA_BLK0 << 12); + + /* 5. DIO write: NOWAIT -> -EAGAIN, inside i_size -> UNWRITTEN */ + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 12288, 4096, + IOMAP_WRITE | IOMAP_DIRECT | + IOMAP_NOWAIT, &iomap, &srcmap), + -EAGAIN); + + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0 + 3; + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 12288, 4096, + IOMAP_WRITE | IOMAP_DIRECT, &iomap, + &srcmap), 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_UNWRITTEN); + KUNIT_EXPECT_TRUE(test, !!(iomap.flags & IOMAP_F_NEW)); + + /* 6. Bigalloc multi-block atomic write across mixed [written + hole] */ + inode_test_enable_bigalloc(ctx, 4); + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + inode->i_size = 16384; + /* Pre-populate lblk 0..1 as written at pblk 100..101; lblk 2..3 hole */ + inode_test_insert_leaf_extent(inode, 0, 2, INODE_TEST_DATA_BLK0, false); + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0 + 2; + ctx->zeroout_calls = 0; + + err = ext4_iomap_begin(inode, 0, 16384, + IOMAP_WRITE | IOMAP_DIRECT | IOMAP_ATOMIC, + &iomap, &srcmap); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_MAPPED); + KUNIT_EXPECT_EQ(test, iomap.length, 16384ULL); + KUNIT_EXPECT_EQ(test, iomap.addr, (u64)INODE_TEST_DATA_BLK0 << 12); + KUNIT_EXPECT_TRUE(test, !!(iomap.flags & IOMAP_F_ATOMIC_BIO)); + KUNIT_EXPECT_GT(test, ctx->zeroout_calls, 0U); +} + +/* ------------------------------------------------------------------------- + * 18. Transaction Credits, Layout Breaking & Disksize Update Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_trans_credits_and_disksize(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + int ext_credits, ind_credits, chunk_ext, chunk_jdata; + int err; + + /* 1. ext4_meta_trans_blocks() & ext4_chunk_trans_*() */ + ctx->sbi.s_groups_count = 4; + ctx->sbi.s_gdb_count = 2; + ext_credits = ext4_meta_trans_blocks(inode, 8, 2, 1); + KUNIT_EXPECT_GT(test, ext_credits, 0); + + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ind_credits = ext4_meta_trans_blocks(inode, 8, 2, 1); + KUNIT_EXPECT_GT(test, ind_credits, 0); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ctx->sbi.s_groups_count = 1; + ctx->sbi.s_gdb_count = 1; + + chunk_ext = ext4_chunk_trans_extent(inode, 5); + KUNIT_EXPECT_EQ(test, ext4_chunk_trans_blocks(inode, 5), chunk_ext); + + clear_opt(ctx->sb, DELALLOC); + ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + ctx->sbi.s_journal = (journal_t *)1; + chunk_jdata = ext4_chunk_trans_extent(inode, 5); + ctx->sbi.s_journal = NULL; + ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + set_opt(ctx->sb, DELALLOC); + KUNIT_EXPECT_EQ(test, chunk_jdata, chunk_ext + 5); + + /* 2. ext4_break_layouts() requires invalidate_lock held */ + kunit_warning_suppress(test) { + err = ext4_break_layouts(inode); + } + KUNIT_EXPECT_EQ(test, err, -EINVAL); + + filemap_invalidate_lock(inode->i_mapping); + err = ext4_break_layouts(inode); + filemap_invalidate_unlock(inode->i_mapping); + KUNIT_EXPECT_EQ(test, err, 0); + + /* 3. ext4_update_disksize_before_punch() */ + inode->i_size = 12000; + ctx->ei.i_disksize = 4096; + + inode_lock(inode); + /* Punch past i_size is a no-op */ + KUNIT_EXPECT_EQ(test, + ext4_update_disksize_before_punch(inode, 16384, 4096), + 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 4096LL); + + /* Punch within [0, 8192) advances i_disksize to 8192 */ + KUNIT_EXPECT_EQ(test, + ext4_update_disksize_before_punch(inode, 4096, 4096), + 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 8192LL); + + /* Punch extending past i_size clamps i_disksize to i_size (12000) */ + KUNIT_EXPECT_EQ(test, + ext4_update_disksize_before_punch(inode, 8192, 8192), + 0); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 12000LL); +} + +/* ------------------------------------------------------------------------- + * 19. Partial Block Zeroing, EOF Zeroing & Pagecache Truncate Range Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_zero_partial_and_eof(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *dblk0 = inode_test_find_blk(ctx, + INODE_TEST_DATA_BLK0); + struct inode_test_blk *dblk1 = inode_test_find_blk(ctx, + INODE_TEST_DATA_BLK0 + 1); + struct folio *folio; + unsigned int partial_zeroed = 0; + u8 *kaddr; + int err; + + /* + * Map lblk 0 -> pblk 100 (written), leave lblk 1 as a hole, and map + * lblk 2 -> pblk 101 (written). + */ + inode->i_size = 12288; + ctx->ei.i_disksize = 12288; + inode_test_insert_leaf_extent(inode, 0, 1, INODE_TEST_DATA_BLK0, false); + inode_test_insert_leaf_extent(inode, 2, 1, INODE_TEST_DATA_BLK0 + 1, + false); + memset(dblk0->disk_buf, 0x5a, INODE_TEST_BLK_SIZE); + memset(dblk1->disk_buf, 0xa5, INODE_TEST_BLK_SIZE); + + /* 1. Single-block interior zeroing [512, 1536) sets START | END */ + err = ext4_zero_partial_blocks(inode, 512, 1024, &partial_zeroed); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, partial_zeroed, + (unsigned int)(EXT4_PARTIAL_ZERO_START | + EXT4_PARTIAL_ZERO_END)); + + folio = filemap_get_folio(inode->i_mapping, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + kaddr = kmap_local_folio(folio, 0); + KUNIT_EXPECT_EQ(test, kaddr[511], 0x5a); + KUNIT_EXPECT_EQ(test, kaddr[512], 0x00); + KUNIT_EXPECT_EQ(test, kaddr[1535], 0x00); + KUNIT_EXPECT_EQ(test, kaddr[1536], 0x5a); + kunmap_local(kaddr); + folio_put(folio); + + /* 2. Multi-block [3000, 5000): lblk 0 mapped, lblk 1 hole -> START */ + partial_zeroed = 0; + err = ext4_zero_partial_blocks(inode, 3000, 2000, &partial_zeroed); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, partial_zeroed, + (unsigned int)EXT4_PARTIAL_ZERO_START); + + /* Zero EOF tail [8500, 12288) in lblk 2 -> pblk 101 */ + KUNIT_EXPECT_EQ(test, ext4_block_zero_eof(inode, 8192, 12288), 0); + KUNIT_EXPECT_EQ(test, ext4_block_zero_eof(inode, 9000, 8500), 0); + + err = ext4_block_zero_eof(inode, 8500, 12288); + KUNIT_ASSERT_EQ(test, err, 0); + + folio = filemap_get_folio(inode->i_mapping, 8192 >> PAGE_SHIFT); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + kaddr = kmap_local_folio(folio, offset_in_folio(folio, 8192)); + KUNIT_EXPECT_EQ(test, kaddr[307], 0xa5); + KUNIT_EXPECT_EQ(test, kaddr[308], 0x00); + KUNIT_EXPECT_EQ(test, kaddr[4095], 0x00); + kunmap_local(kaddr); + folio_put(folio); + + /* 3. ext4_truncate_page_cache_block_range() evicts full folio 0 */ + err = ext4_truncate_page_cache_block_range(inode, 0, + INODE_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, err, 0); + err = ext4_truncate_page_cache_block_range(inode, 0, + max_t(loff_t, PAGE_SIZE, INODE_TEST_BLK_SIZE)); + KUNIT_EXPECT_EQ(test, err, 0); + folio = filemap_get_folio(inode->i_mapping, 0); + KUNIT_EXPECT_TRUE(test, IS_ERR(folio)); + if (!IS_ERR(folio)) + folio_put(folio); +} + +/* ------------------------------------------------------------------------- + * 20. ext4_punch_hole() & ext4_truncate() End-to-End Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_punch_hole_and_truncate(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct file *dummy_file; + struct extent_status es = {}; + int err; + + dummy_file = kunit_kzalloc(test, sizeof(*dummy_file), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dummy_file); + dummy_file->f_inode = inode; + dummy_file->f_mapping = inode->i_mapping; + + /* Set up 4-block written extent [lblk 0..3 -> pblk 100..103] */ + inode->i_size = 4 * INODE_TEST_BLK_SIZE; + ctx->ei.i_disksize = inode->i_size; + inode->i_blocks = 32; + inode_test_insert_leaf_extent(inode, 0, 4, INODE_TEST_DATA_BLK0, false); + down_write(&ctx->ei.i_data_sem); + ext4_es_insert_extent(inode, 0, 4, INODE_TEST_DATA_BLK0, + EXTENT_STATUS_WRITTEN, 0); + up_write(&ctx->ei.i_data_sem); + + /* 1. Punch past i_size is a no-op */ + inode_lock(inode); + err = ext4_punch_hole(dummy_file, 5 * INODE_TEST_BLK_SIZE, + INODE_TEST_BLK_SIZE); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 0UL); + + /* 2. Punch middle 2 blocks [4096, 12288) -> frees pblk 101..102 */ + inode_lock(inode); + err = ext4_punch_hole(dummy_file, INODE_TEST_BLK_SIZE, + 2 * INODE_TEST_BLK_SIZE); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 2UL); + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 1, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_hole(&es)); + KUNIT_EXPECT_EQ(test, es.es_len, 2U); + + /* 3. Truncate down to 1 block (4096B) -> frees trailing pblk 103 */ + ctx->total_freed_blocks = 0; + ctx->orphan_add_calls = 0; + ctx->orphan_del_calls = 0; + inode->i_size = INODE_TEST_BLK_SIZE; + inode_lock(inode); + err = ext4_truncate(inode); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->orphan_add_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->orphan_del_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 1UL); + KUNIT_EXPECT_EQ(test, ctx->last_free_pblk, + (ext4_fsblk_t)(INODE_TEST_DATA_BLK0 + 3)); + + /* 4. Truncate to 0 sets EXT4_STATE_DA_ALLOC_CLOSE & frees pblk 100 */ + ctx->total_freed_blocks = 0; + inode->i_size = 0; + inode_lock(inode); + err = ext4_truncate(inode); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(inode, + EXT4_STATE_DA_ALLOC_CLOSE)); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 1UL); + KUNIT_EXPECT_EQ(test, ctx->last_free_pblk, + (ext4_fsblk_t)INODE_TEST_DATA_BLK0); +} + +/* ------------------------------------------------------------------------- + * 21. ext4_inode_attach_jinode, ext4_write_inode & ext4_sync_inode_metadata + * ------------------------------------------------------------------------- + */ + +static void inode_test_write_and_sync_metadata(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *itable = inode_test_find_blk(ctx, + INODE_TEST_ITABLE_BLK0); + struct writeback_control wbc = { .sync_mode = WB_SYNC_ALL }; + struct ext4_inode *raw; + int err; + + /* 1. ext4_inode_attach_jinode(): no-op without journal, allocs with */ + KUNIT_EXPECT_EQ(test, ext4_inode_attach_jinode(inode), 0); + KUNIT_EXPECT_NULL(test, ctx->ei.jinode); + + ctx->sbi.s_journal = (journal_t *)1; + err = ext4_inode_attach_jinode(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_NOT_NULL(test, ctx->ei.jinode); + /* Idempotent when jinode is already attached */ + KUNIT_EXPECT_EQ(test, ext4_inode_attach_jinode(inode), 0); + ctx->sbi.s_journal = NULL; + if (ctx->ei.jinode) { + jbd2_free_inode(ctx->ei.jinode); + ctx->ei.jinode = NULL; + } + + /* 2. ext4_write_inode(): 0 in nojournal, -EROFS in emergency state */ + KUNIT_EXPECT_EQ(test, ext4_write_inode(inode, &wbc), 0); + set_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, ext4_write_inode(inode, &wbc), -EROFS); + clear_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + + /* 3. ext4_sync_inode_metadata(): warns & fails if journal present */ + ctx->sbi.s_journal = (journal_t *)1; + kunit_warning_suppress(test) { + err = ext4_sync_inode_metadata(inode, &wbc); + } + ctx->sbi.s_journal = NULL; + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + + /* Clean nojournal metadata sync flushes dirty raw inode & returns 0 */ + i_uid_write(inode, 0x7788); + ext4_dirty_inode(inode, I_DIRTY_SYNC); + clear_buffer_mapped(&itable->bh); + clear_buffer_write_io_error(&itable->bh); + err = ext4_sync_inode_metadata(inode, &wbc); + KUNIT_EXPECT_EQ(test, err, 0); + raw = inode_test_raw_slot(ctx, INODE_TEST_PRIMARY_INO, false); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_low), 0x7788); + + /* Simulated buffer write error returns -EIO */ + set_buffer_write_io_error(&itable->bh); + err = ext4_sync_inode_metadata(inode, &wbc); + clear_buffer_write_io_error(&itable->bh); + KUNIT_EXPECT_EQ(test, err, -EIO); +} + +/* ------------------------------------------------------------------------- + * 22. ext4_evict_inode() Live, Unlinked Regular & Fast Symlink Eviction Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_evict_inode_paths(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct ext4_inode *raw; + struct inode *ig; + + /* 1. Live inode (i_nlink == 1): evicts cleanly without freeing inode */ + inode_test_prepare_valid_raw_inode(ctx, 24, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 24, true); + raw->i_size_lo = cpu_to_le32(4096); + inode_test_stamp_raw_csum(ctx, 24, raw); + ig = ext4_iget(ctx->sb, 24, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(ig)); + ctx->free_inode_calls = 0; + ctx->total_freed_blocks = 0; + iput(ig); + KUNIT_EXPECT_EQ(test, ctx->free_inode_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 0UL); + + /* + * 2. Unlinked regular file (i_nlink == 0) with 2 mapped blocks: + * truncates data blocks, sets i_dtime, updates raw inode, and calls + * ext4_free_inode(). + */ + { + u32 t_before, t_after, dtime; + + inode_test_prepare_valid_raw_inode(ctx, 25, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 25, true); + raw->i_size_lo = cpu_to_le32(8192); + inode_test_stamp_raw_csum(ctx, 25, raw); + ig = ext4_iget(ctx->sb, 25, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(ig)); + inode_test_insert_leaf_extent(ig, 0, 2, INODE_TEST_DATA_BLK0, + false); + ig->i_blocks = 16; + clear_nlink(ig); + ctx->free_inode_calls = 0; + ctx->total_freed_blocks = 0; + raw = inode_test_raw_slot(ctx, 25, false); + raw->i_dtime = cpu_to_le32(0xdeadbeefU); + inode_test_stamp_raw_csum(ctx, 25, raw); + t_before = (__u32)ktime_get_real_seconds(); + iput(ig); + t_after = (__u32)ktime_get_real_seconds(); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 2UL); + KUNIT_EXPECT_EQ(test, ctx->free_inode_calls, 1U); + raw = inode_test_raw_slot(ctx, 25, false); + dtime = le32_to_cpu(raw->i_dtime); + KUNIT_EXPECT_LE(test, (u32)(dtime - t_before), + (u32)(t_after - t_before)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_size_lo), 0U); + } + + /* + * 3. Unlinked fast symlink (i_nlink == 0): clears inline i_data target + * without treating bytes as block pointers and frees the inode. + */ + inode_test_prepare_valid_raw_inode(ctx, 26, S_IFLNK | 0777); + raw = inode_test_raw_slot(ctx, 26, true); + raw->i_flags = 0; + raw->i_size_lo = cpu_to_le32(11); + memcpy(raw->i_block, "target/path", 11); + inode_test_stamp_raw_csum(ctx, 26, raw); + ig = ext4_iget(ctx->sb, 26, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(ig)); + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(ig), 1); + clear_nlink(ig); + ctx->free_inode_calls = 0; + ctx->total_freed_blocks = 0; + iput(ig); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 0UL); + KUNIT_EXPECT_EQ(test, ctx->free_inode_calls, 1U); +} + +/* ------------------------------------------------------------------------- + * 23. Buffered Write (ext4_da_aops & ext4_aops) and Folio Operations Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_buffered_write_and_folio_ops(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct address_space *mapping = inode->i_mapping; + struct folio *folio = NULL; + void *fsdata = NULL; + u8 *kaddr; + int ret; + + /* + * 1. Delayed-allocation buffered write to hole [0, 128): + * reserves 1 delalloc block and updates i_size while deferring + * i_disksize update until writeback. + */ + inode_lock(inode); + ret = mapping->a_ops->write_begin(NULL, mapping, 0, 128, &folio, + &fsdata); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_ASSERT_NOT_NULL(test, folio); + kaddr = kmap_local_folio(folio, 0); + memset(kaddr, 0xab, 128); + kunmap_local(kaddr); + ret = mapping->a_ops->write_end(NULL, mapping, 0, 128, 128, folio, + fsdata); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 128); + KUNIT_EXPECT_EQ(test, inode->i_size, 128LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 0LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + + /* + * 2. Delayed-allocation write into an already-written block past i_size + * (placed on folio index 1 regardless of PAGE_SIZE) updates both + * i_size and i_disksize immediately. + */ + { + loff_t wpos = max_t(loff_t, PAGE_SIZE, INODE_TEST_BLK_SIZE); + ext4_lblk_t wlblk = wpos >> INODE_TEST_BLK_BITS; + + inode_test_insert_leaf_extent(inode, wlblk, 1, + INODE_TEST_DATA_BLK0 + 1, false); + inode_lock(inode); + ret = mapping->a_ops->write_begin(NULL, mapping, wpos, 64, + &folio, &fsdata); + KUNIT_ASSERT_EQ(test, ret, 0); + kaddr = kmap_local_folio(folio, offset_in_folio(folio, wpos)); + memset(kaddr, 0xcd, 64); + kunmap_local(kaddr); + ret = mapping->a_ops->write_end(NULL, mapping, wpos, 64, 64, + folio, fsdata); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 64); + KUNIT_EXPECT_EQ(test, inode->i_size, wpos + 64); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, wpos + 64); + + /* Full folio invalidation detaches buffers cleanly */ + folio = filemap_lock_folio(mapping, wpos >> PAGE_SHIFT); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + KUNIT_EXPECT_NOT_NULL(test, folio_buffers(folio)); + mapping->a_ops->invalidate_folio(folio, 0, folio_size(folio)); + KUNIT_EXPECT_NULL(test, folio_buffers(folio)); + folio_unlock(folio); + folio_put(folio); + } + + /* 3. Non-delalloc buffered write (ext4_aops) allocates pblk directly */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + clear_opt(ctx->sb, DELALLOC); + ext4_set_aops(inode); + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0; + ctx->alloc_calls = 0; + + inode_lock(inode); + ret = mapping->a_ops->write_begin(NULL, mapping, 0, 256, &folio, + &fsdata); + KUNIT_ASSERT_EQ(test, ret, 0); + kaddr = kmap_local_folio(folio, 0); + memset(kaddr, 0xef, 256); + kunmap_local(kaddr); + ret = mapping->a_ops->write_end(NULL, mapping, 0, 256, 256, folio, + fsdata); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 256); + KUNIT_EXPECT_EQ(test, ctx->alloc_calls, 1U); + KUNIT_EXPECT_EQ(test, inode->i_size, 256LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 256LL); + + /* 4. a_ops->bmap, partial invalidate_folio & release_folio */ + KUNIT_EXPECT_EQ(test, (ext4_fsblk_t)mapping->a_ops->bmap(mapping, 0), + (ext4_fsblk_t)INODE_TEST_DATA_BLK0); + KUNIT_EXPECT_EQ(test, (ext4_fsblk_t)mapping->a_ops->bmap(mapping, 5), + 0ULL); + + folio = filemap_lock_folio(mapping, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + folio_set_checked(folio); + KUNIT_EXPECT_FALSE(test, mapping->a_ops->release_folio(folio, + GFP_KERNEL)); + folio_clear_checked(folio); + /* Dirty buffer still pins folio buffers */ + KUNIT_EXPECT_FALSE(test, mapping->a_ops->release_folio(folio, + GFP_KERNEL)); + /* Partial invalidation preserves buffer ring */ + mapping->a_ops->invalidate_folio(folio, 128, 128); + KUNIT_EXPECT_NOT_NULL(test, folio_buffers(folio)); + + clear_buffer_dirty(folio_buffers(folio)); + folio_clear_dirty_for_io(folio); + KUNIT_EXPECT_TRUE(test, mapping->a_ops->release_folio(folio, + GFP_KERNEL)); + KUNIT_EXPECT_NULL(test, folio_buffers(folio)); + folio_unlock(folio); + folio_put(folio); + set_opt(ctx->sb, DELALLOC); +} + +/* ------------------------------------------------------------------------- + * 24. ext4_setattr() Permission, Mode, Extend & Shrink Truncate Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_setattr(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *dblk0 = inode_test_find_blk(ctx, + INODE_TEST_DATA_BLK0); + struct dentry dentry = { .d_sb = ctx->sb, .d_inode = inode }; + struct iattr attr = {}; + struct folio *folio; + u8 *kaddr; + u64 iv_before; + int err; + + /* 1. S_IMMUTABLE and S_APPEND permission rejections */ + inode->i_flags |= S_IMMUTABLE; + attr = (struct iattr){ .ia_valid = ATTR_MODE, .ia_mode = S_IFREG | 0600 }; + inode_lock(inode); + KUNIT_EXPECT_EQ(test, ext4_setattr(&nop_mnt_idmap, &dentry, &attr), + -EPERM); + inode_unlock(inode); + inode->i_flags &= ~S_IMMUTABLE; + + inode->i_flags |= S_APPEND; + inode_lock(inode); + KUNIT_EXPECT_EQ(test, ext4_setattr(&nop_mnt_idmap, &dentry, &attr), + -EPERM); + inode_unlock(inode); + inode->i_flags &= ~S_APPEND; + + /* 2. Directory ATTR_SIZE -> -EINVAL; indirect > maxbytes -> -EFBIG */ + inode->i_mode = S_IFDIR | 0755; + attr = (struct iattr){ .ia_valid = ATTR_SIZE, .ia_size = 0 }; + inode_lock(inode); + KUNIT_EXPECT_EQ(test, ext4_setattr(&nop_mnt_idmap, &dentry, &attr), + -EINVAL); + inode_unlock(inode); + + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + memset(ctx->ei.i_data, 0, sizeof(ctx->ei.i_data)); + attr = (struct iattr){ + .ia_valid = ATTR_SIZE, + .ia_size = ctx->sbi.s_bitmap_maxbytes + 4096, + }; + inode_lock(inode); + KUNIT_EXPECT_EQ(test, ext4_setattr(&nop_mnt_idmap, &dentry, &attr), + -EFBIG); + inode_unlock(inode); + + /* 3. ATTR_MODE chmod updates mode & increments iversion */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + iv_before = inode_peek_iversion(inode); + attr = (struct iattr){ .ia_valid = ATTR_MODE, .ia_mode = S_IFREG | 0600 }; + inode_lock(inode); + err = ext4_setattr(&nop_mnt_idmap, &dentry, &attr); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, inode->i_mode & 0777, 0600); + KUNIT_EXPECT_GT(test, inode_peek_iversion(inode), iv_before); + + /* + * 4. ATTR_SIZE extend (2000 -> 8192) zeroes EOF tail [2000, 4096) in + * mapped block 0 and advances i_size and i_disksize. + */ + inode->i_size = 2000; + ctx->ei.i_disksize = 2000; + inode->i_blocks = 16; + inode_test_insert_leaf_extent(inode, 0, 2, INODE_TEST_DATA_BLK0, false); + memset(dblk0->disk_buf, 0x77, INODE_TEST_BLK_SIZE); + + attr = (struct iattr){ .ia_valid = ATTR_SIZE, .ia_size = 8192 }; + inode_lock(inode); + err = ext4_setattr(&nop_mnt_idmap, &dentry, &attr); + inode_unlock(inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 8192LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 8192LL); + + folio = filemap_get_folio(inode->i_mapping, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + kaddr = kmap_local_folio(folio, 0); + KUNIT_EXPECT_EQ(test, kaddr[1999], 0x77); + KUNIT_EXPECT_EQ(test, kaddr[2000], 0x00); + KUNIT_EXPECT_EQ(test, kaddr[4095], 0x00); + kunmap_local(kaddr); + folio_put(folio); + + /* 5. ATTR_SIZE shrink (8192 -> 4096) frees trailing block 1 */ + ctx->total_freed_blocks = 0; + attr = (struct iattr){ .ia_valid = ATTR_SIZE, .ia_size = 4096 }; + inode_lock(inode); + err = ext4_setattr(&nop_mnt_idmap, &dentry, &attr); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 4096LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 4096LL); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 1UL); +} + +/* ------------------------------------------------------------------------- + * 25. ext4_page_mkwrite() Delalloc, Block-Alloc, Fast-Path & Truncate Tests + * ------------------------------------------------------------------------- + */ + +static vm_fault_t inode_test_call_page_mkwrite(struct vm_area_struct *vma, + struct folio *folio) +{ + struct vm_fault vmf = { + .vma = vma, + .page = folio_page(folio, 0), + }; + + return ext4_page_mkwrite(&vmf); +} + +static void inode_test_page_mkwrite(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct file *dummy_file; + struct vm_area_struct *vma; + struct folio *folio; + vm_fault_t ret; + + dummy_file = kunit_kzalloc(test, sizeof(*dummy_file), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dummy_file); + dummy_file->f_inode = inode; + dummy_file->f_mapping = inode->i_mapping; + dummy_file->f_mode = FMODE_NOCMTIME; + + vma = kunit_kzalloc(test, sizeof(*vma), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, vma); + vma->vm_file = dummy_file; + + inode->i_size = 4096; + ctx->ei.i_disksize = 4096; + folio = __filemap_get_folio(inode->i_mapping, 0, + FGP_CREAT | FGP_LOCK, GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + folio_zero_segment(folio, 0, folio_size(folio)); + folio_mark_uptodate(folio); + folio_unlock(folio); + + /* 1. S_IMMUTABLE rejects write fault with VM_FAULT_SIGBUS */ + inode->i_flags |= S_IMMUTABLE; + KUNIT_EXPECT_TRUE(test, + inode_test_call_page_mkwrite(vma, folio) == + VM_FAULT_SIGBUS); + inode->i_flags &= ~S_IMMUTABLE; + + /* 2. Delalloc fault reserves 1 delayed block & returns LOCKED */ + ret = inode_test_call_page_mkwrite(vma, folio); + KUNIT_EXPECT_TRUE(test, ret == VM_FAULT_LOCKED); + if (ret & VM_FAULT_LOCKED) + folio_unlock(folio); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + folio_put(folio); + + /* 3. Non-delalloc fault allocates pblk; repeat fault hits fast-path */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + clear_opt(ctx->sb, DELALLOC); + ext4_set_aops(inode); + inode->i_size = 4096; + ctx->ei.i_disksize = 4096; + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0; + ctx->alloc_calls = 0; + + folio = __filemap_get_folio(inode->i_mapping, 0, + FGP_CREAT | FGP_LOCK, GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + folio_zero_segment(folio, 0, folio_size(folio)); + folio_mark_uptodate(folio); + folio_unlock(folio); + + ret = inode_test_call_page_mkwrite(vma, folio); + KUNIT_EXPECT_TRUE(test, ret == VM_FAULT_LOCKED); + if (ret & VM_FAULT_LOCKED) + folio_unlock(folio); + KUNIT_EXPECT_EQ(test, ctx->alloc_calls, 1U); + + /* Second fault sees all buffers mapped and skips journal_start/alloc */ + ret = inode_test_call_page_mkwrite(vma, folio); + KUNIT_EXPECT_TRUE(test, ret == VM_FAULT_LOCKED); + if (ret & VM_FAULT_LOCKED) + folio_unlock(folio); + KUNIT_EXPECT_EQ(test, ctx->alloc_calls, 1U); + + /* 4. Folio beyond truncated i_size returns VM_FAULT_NOPAGE */ + folio_put(folio); + folio = __filemap_get_folio(inode->i_mapping, 2, + FGP_CREAT | FGP_LOCK, GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + folio_unlock(folio); + KUNIT_EXPECT_TRUE(test, + inode_test_call_page_mkwrite(vma, folio) == + VM_FAULT_NOPAGE); + folio_put(folio); + set_opt(ctx->sb, DELALLOC); +} + static struct kunit_case ext4_inode_test_cases[] = { KUNIT_CASE_PARAM(inode_test_xtimestamp_decoding, ext4_inode_gen_params), + KUNIT_CASE(inode_test_xtimestamp_encoding_roundtrip), + KUNIT_CASE(inode_test_csum_set_and_verify), + KUNIT_CASE(inode_test_blocks_encode_decode), + KUNIT_CASE(inode_test_fill_raw_inode), + KUNIT_CASE(inode_test_mark_dirty_and_update), + KUNIT_CASE(inode_test_expand_extra_isize), + KUNIT_CASE(inode_test_get_inode_loc_variants), + KUNIT_CASE(inode_test_iget_validation_and_modes), + KUNIT_CASE(inode_test_iget_corruptions), + KUNIT_CASE(inode_test_fast_symlink_and_can_truncate), + KUNIT_CASE(inode_test_flags_aops_mapping_order), + KUNIT_CASE(inode_test_projid_dio_and_getattr), + KUNIT_CASE(inode_test_da_reserve_and_release), + KUNIT_CASE(inode_test_da_bigalloc_clusters), + KUNIT_CASE(inode_test_map_blocks_paths), + KUNIT_CASE(inode_test_get_block_bread_and_walk_buffers), + KUNIT_CASE(inode_test_iomap_and_atomic_writes), + KUNIT_CASE(inode_test_trans_credits_and_disksize), + KUNIT_CASE(inode_test_zero_partial_and_eof), + KUNIT_CASE(inode_test_punch_hole_and_truncate), + KUNIT_CASE(inode_test_write_and_sync_metadata), + KUNIT_CASE(inode_test_evict_inode_paths), + KUNIT_CASE(inode_test_buffered_write_and_folio_ops), + KUNIT_CASE(inode_test_setattr), + KUNIT_CASE(inode_test_page_mkwrite), {} }; @@ -279,5 +3771,5 @@ static struct kunit_suite ext4_inode_test_suite = { kunit_test_suites(&ext4_inode_test_suite); -MODULE_DESCRIPTION("KUnit test of ext4 inode timestamp decoding"); +MODULE_DESCRIPTION("KUnit tests for ext4 inode operations"); MODULE_LICENSE("GPL v2"); diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 49560ca27036d9..28fc6ec46cf490 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -126,6 +126,7 @@ void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw, EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) raw->i_checksum_hi = cpu_to_le16(csum >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_csum_set); /* * Clear the disksize-grow-pending state and wake up all waiters. @@ -228,6 +229,7 @@ int ext4_inode_is_fast_symlink(struct inode *inode) return S_ISLNK(inode->i_mode) && inode->i_size && (inode->i_size < EXT4_N_BLOCKS * 4); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_is_fast_symlink); /* * Called at the last iput() if i_nlink is zero. @@ -400,6 +402,7 @@ void ext4_evict_inode(struct inode *inode) ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL); ext4_clear_inode(inode); /* We must guarantee clearing of inode... */ } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_evict_inode); #ifdef CONFIG_QUOTA qsize_t *ext4_get_reserved_space(struct inode *inode) @@ -1082,6 +1085,7 @@ int ext4_get_block(struct inode *inode, sector_t iblock, return _ext4_get_block(inode, iblock, bh, create ? EXT4_GET_BLOCKS_CREATE : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_block); /* * Get block function used when preparing for buffered write if we require @@ -1108,10 +1112,34 @@ int ext4_get_block_unwritten(struct inode *inode, sector_t iblock, return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_block_unwritten); /* Maximum number of blocks we map for direct IO at once. */ #define DIO_MAX_BLOCKS 4096 +struct buffer_head *ext4_sb_getblk(struct super_block *sb, ext4_fsblk_t block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_getblk, sb, block); + return sb_getblk(sb, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_getblk); + +struct buffer_head *ext4_sb_find_get_block(struct super_block *sb, + ext4_fsblk_t block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_find_get_block, sb, block); + return sb_find_get_block(sb, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_find_get_block); + +struct buffer_head *ext4_sb_getblk_unmovable(struct super_block *sb, + ext4_fsblk_t block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_getblk_unmovable, sb, block); + return getblk_unmovable(sb->s_bdev, block, sb->s_blocksize); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_getblk_unmovable); + /* * `handle' can be NULL if create is zero */ @@ -1141,15 +1169,14 @@ struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode, return ERR_PTR(err); if (nowait) - return sb_find_get_block(inode->i_sb, map.m_pblk); + return ext4_sb_find_get_block(inode->i_sb, map.m_pblk); /* * Since bh could introduce extra ref count such as referred by * journal_head etc. Try to avoid using __GFP_MOVABLE here * as it may fail the migration when journal_head remains. */ - bh = getblk_unmovable(inode->i_sb->s_bdev, map.m_pblk, - inode->i_sb->s_blocksize); + bh = ext4_sb_getblk_unmovable(inode->i_sb, map.m_pblk); if (unlikely(!bh)) return ERR_PTR(-ENOMEM); @@ -1210,6 +1237,7 @@ struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode, } return bh; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_bread); /* Read a contiguous batch of blocks. */ int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count, @@ -1253,6 +1281,7 @@ int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count, } return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_bread_batch); int ext4_walk_page_buffers(handle_t *handle, struct inode *inode, struct buffer_head *head, @@ -1284,6 +1313,7 @@ int ext4_walk_page_buffers(handle_t *handle, struct inode *inode, } return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_walk_page_buffers); /* * Helper for handling dirtying of journalled data. We also mark the folio as @@ -4058,12 +4088,14 @@ int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length, return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_iomap_begin); static DEFINE_IOMAP_ITER_NEXT(ext4_iomap_next, ext4_iomap_begin); const struct iomap_ops ext4_iomap_ops = { .iomap_next = ext4_iomap_next, }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_iomap_ops); static int ext4_iomap_begin_report(struct inode *inode, loff_t offset, loff_t length, unsigned int flags, @@ -4121,6 +4153,7 @@ static DEFINE_IOMAP_ITER_NEXT(ext4_iomap_next_report, ext4_iomap_begin_report); const struct iomap_ops ext4_iomap_report_ops = { .iomap_next = ext4_iomap_next_report, }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_iomap_report_ops); static int ext4_iomap_map_blocks(struct inode *inode, loff_t offset, loff_t length, struct ext4_map_blocks *map, @@ -4719,6 +4752,7 @@ void ext4_set_aops(struct inode *inode) else inode->i_mapping->a_ops = &ext4_aops; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_aops); /* * Here we can't skip an unwritten buffer even though it usually reads zero @@ -5125,6 +5159,7 @@ int ext4_block_zero_eof(struct inode *inode, loff_t from, loff_t end) trace_ext4_block_zero_eof(inode, from, length, did_zero, zero_written); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_zero_eof); /* * Zero out the unaligned head and tail of the [lstart, lstart+length) @@ -5185,6 +5220,7 @@ int ext4_zero_partial_blocks(struct inode *inode, loff_t lstart, loff_t length, } return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_zero_partial_blocks); int ext4_can_truncate(struct inode *inode) { @@ -5196,6 +5232,7 @@ int ext4_can_truncate(struct inode *inode) return !ext4_inode_is_fast_symlink(inode); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_can_truncate); /* * We have to make sure i_disksize gets properly updated before we truncate @@ -5241,6 +5278,7 @@ int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset, return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_disksize_before_punch); static inline void ext4_truncate_folio(struct inode *inode, loff_t start, loff_t end) @@ -5303,6 +5341,7 @@ int ext4_truncate_page_cache_block_range(struct inode *inode, truncate_pagecache_range(inode, start, end - 1); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_truncate_page_cache_block_range); static void ext4_wait_dax_page(struct inode *inode) { @@ -5318,6 +5357,7 @@ int ext4_break_layouts(struct inode *inode) return dax_break_layout_inode(inode, ext4_wait_dax_page); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_break_layouts); /* * ext4_punch_hole: punches a hole in a file by releasing the blocks @@ -5445,6 +5485,7 @@ int ext4_punch_hole(struct file *file, loff_t offset, loff_t length) ext4_journal_stop(handle); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_punch_hole); int ext4_inode_attach_jinode(struct inode *inode) { @@ -5475,6 +5516,7 @@ int ext4_inode_attach_jinode(struct inode *inode) jbd2_free_inode(jinode); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_attach_jinode); /* * ext4_truncate() @@ -5609,6 +5651,7 @@ int ext4_truncate(struct inode *inode) trace_ext4_truncate_exit(inode); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_truncate); static inline u64 ext4_inode_peek_iversion(const struct inode *inode) { @@ -5800,7 +5843,7 @@ static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino, } block += (inode_offset / inodes_per_block); - bh = sb_getblk(sb, block); + bh = ext4_sb_getblk(sb, block); if (unlikely(!bh)) return -ENOMEM; if (ext4_buffer_uptodate(bh)) @@ -5829,7 +5872,8 @@ static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino, * is locked, and blocking here would folio_lock() against a * block_read_full_folio() that locks bh the other way round. */ - bitmap_bh = sb_find_get_block(sb, ext4_inode_bitmap(sb, gdp)); + bitmap_bh = ext4_sb_find_get_block(sb, + ext4_inode_bitmap(sb, gdp)); if (unlikely(!bitmap_bh)) goto make_io; @@ -5986,7 +6030,7 @@ int ext4_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc) } block += inode_offset / inodes_per_block; - bh = sb_find_get_block(sb, block); + bh = ext4_sb_find_get_block(sb, block); if (!bh) return -EAGAIN; if (!ext4_buffer_uptodate(bh)) { @@ -6065,6 +6109,7 @@ void ext4_set_inode_flags(struct inode *inode, bool init) S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX| S_ENCRYPTED|S_CASEFOLD|S_VERITY); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_inode_flags); static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode, struct ext4_inode_info *ei) @@ -6121,6 +6166,7 @@ int ext4_get_projid(struct inode *inode, kprojid_t *projid) *projid = EXT4_I(inode)->i_projid; return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_projid); /* * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of @@ -6273,6 +6319,7 @@ void ext4_set_inode_mapping_order(struct inode *inode) mapping_set_folio_order_range(inode->i_mapping, min_order, max_order); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_inode_mapping_order); static int ext4_iget_match(struct inode *inode, u64 ino, void *data) { @@ -6887,6 +6934,7 @@ int ext4_write_inode(struct inode *inode, struct writeback_control *wbc) return ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal, EXT4_I(inode)->i_sync_tid); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_write_inode); int ext4_sync_inode_metadata(struct inode *inode, struct writeback_control *wbc) { @@ -6917,6 +6965,7 @@ int ext4_sync_inode_metadata(struct inode *inode, struct writeback_control *wbc) brelse(iloc.bh); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sync_inode_metadata); /* * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate @@ -7267,6 +7316,7 @@ int ext4_setattr(const struct mnt_idmap *idmap, struct dentry *dentry, error = rc; return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_setattr); u32 ext4_dio_alignment(struct inode *inode) { @@ -7280,6 +7330,7 @@ u32 ext4_dio_alignment(struct inode *inode) return i_blocksize(inode); return 1; /* use the iomap defaults */ } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dio_alignment); int ext4_getattr(const struct mnt_idmap *idmap, const struct path *path, struct kstat *stat, u32 request_mask, unsigned int query_flags) @@ -7347,6 +7398,7 @@ int ext4_getattr(const struct mnt_idmap *idmap, const struct path *path, generic_fillattr(idmap, request_mask, inode, stat); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_getattr); int ext4_file_getattr(const struct mnt_idmap *idmap, const struct path *path, struct kstat *stat, @@ -7381,6 +7433,7 @@ int ext4_file_getattr(const struct mnt_idmap *idmap, stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_file_getattr); static int ext4_index_trans_blocks(struct inode *inode, int lblocks, int pextents) @@ -7433,6 +7486,7 @@ int ext4_meta_trans_blocks(struct inode *inode, int lblocks, int pextents, return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_meta_trans_blocks); /* * Calculate the journal credits for modifying the number of blocks @@ -7450,6 +7504,7 @@ int ext4_chunk_trans_extent(struct inode *inode, int nrblocks) ret += nrblocks; return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_chunk_trans_extent); /* * Calculate the journal credits for a chunk of data modification. @@ -7464,6 +7519,7 @@ int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks) { return ext4_meta_trans_blocks(inode, nrblocks, 1, 1); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_chunk_trans_blocks); /* * The caller must have previously called ext4_reserve_inode_write(). @@ -7541,6 +7597,7 @@ ext4_reserve_inode_write(handle_t *handle, struct inode *inode, ext4_std_error(inode->i_sb, err); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_reserve_inode_write); static int __ext4_expand_extra_isize(struct inode *inode, unsigned int new_extra_isize, @@ -7698,6 +7755,7 @@ int ext4_expand_extra_isize(struct inode *inode, ext4_journal_stop(handle); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_expand_extra_isize); /* * What we do here is to mark the in-core inode as clean with respect to inode @@ -7764,6 +7822,7 @@ void ext4_dirty_inode(struct inode *inode, int flags) ext4_mark_inode_dirty(handle, inode); ext4_journal_stop(handle); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dirty_inode); int ext4_change_inode_journal_flag(struct inode *inode, int val) { @@ -8025,8 +8084,87 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf) sb_end_pagefault(inode->i_sb); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_page_mkwrite); #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_inode_csum_verify_test(struct inode *inode, struct ext4_inode *raw, + struct ext4_inode_info *ei) +{ + return ext4_inode_csum_verify(inode, raw, ei); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_csum_verify_test); + +int ext4_inode_blocks_set_test(struct ext4_inode *raw_inode, + struct ext4_inode_info *ei) +{ + return ext4_inode_blocks_set(raw_inode, ei); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_blocks_set_test); + +blkcnt_t ext4_inode_blocks_test(struct ext4_inode *raw_inode, + struct ext4_inode_info *ei) +{ + return ext4_inode_blocks(raw_inode, ei); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_blocks_test); + +int ext4_fill_raw_inode_test(struct inode *inode, struct ext4_inode *raw_inode) +{ + return ext4_fill_raw_inode(inode, raw_inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fill_raw_inode_test); + +int ext4_expand_extra_isize_test(struct inode *inode, + unsigned int new_extra_isize, + struct ext4_iloc *iloc, + handle_t *handle, int *no_expand) +{ + return __ext4_expand_extra_isize(inode, new_extra_isize, iloc, + handle, no_expand); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_expand_extra_isize_test); + +int ext4_try_to_expand_extra_isize_test(struct inode *inode, + unsigned int new_extra_isize, + struct ext4_iloc *iloc, + handle_t *handle) +{ + return ext4_try_to_expand_extra_isize(inode, new_extra_isize, + *iloc, handle); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_try_to_expand_extra_isize_test); + +int ext4_da_reserve_space_test(struct inode *inode, int nr_resv) +{ + return ext4_da_reserve_space(inode, nr_resv); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_reserve_space_test); + +int ext4_clu_alloc_state_test(struct inode *inode, ext4_lblk_t lblk) +{ + return ext4_clu_alloc_state(inode, lblk); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_clu_alloc_state_test); + +int ext4_insert_delayed_blocks_test(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len) +{ + return ext4_insert_delayed_blocks(inode, lblk, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_insert_delayed_blocks_test); + +int ext4_da_map_blocks_test(struct inode *inode, struct ext4_map_blocks *map) +{ + return ext4_da_map_blocks(inode, map); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_map_blocks_test); + +int ext4_nonda_switch_test(struct super_block *sb) +{ + return ext4_nonda_switch(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_nonda_switch_test); + EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_inode_loc_noio); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_fc_inode_loc); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_get_block_prep); diff --git a/fs/ext4/page-io.c b/fs/ext4/page-io.c index 791e61228f418d..059827b961ec83 100644 --- a/fs/ext4/page-io.c +++ b/fs/ext4/page-io.c @@ -301,6 +301,7 @@ void ext4_end_io_rsv_work(struct work_struct *work) i_rsv_conversion_work); ext4_do_flush_completed_IO(&ei->vfs_inode, &ei->i_rsv_conversion_list); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_end_io_rsv_work); ext4_io_end_t *ext4_init_io_end(struct inode *inode, gfp_t flags) { diff --git a/fs/ext4/super.c b/fs/ext4/super.c index 517ab0de184138..47da1e456d6d32 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -196,6 +196,9 @@ static inline void __ext4_read_bh(struct buffer_head *bh, blk_opf_t op_flags, void ext4_read_bh_nowait(struct buffer_head *bh, blk_opf_t op_flags, bio_end_io_t end_io, bool simu_fail) { + KUNIT_STATIC_STUB_REDIRECT(ext4_read_bh_nowait, bh, op_flags, + end_io, simu_fail); + BUG_ON(!buffer_locked(bh)); if (ext4_buffer_uptodate(bh)) { @@ -204,6 +207,7 @@ void ext4_read_bh_nowait(struct buffer_head *bh, blk_opf_t op_flags, } __ext4_read_bh(bh, op_flags, end_io, simu_fail); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_bh_nowait); int ext4_read_bh(struct buffer_head *bh, blk_opf_t op_flags, bio_end_io_t end_io, bool simu_fail) @@ -225,6 +229,8 @@ int ext4_read_bh(struct buffer_head *bh, blk_opf_t op_flags, int ext4_read_bh_lock(struct buffer_head *bh, blk_opf_t op_flags, bool wait) { + KUNIT_STATIC_STUB_REDIRECT(ext4_read_bh_lock, bh, op_flags, wait); + lock_buffer(bh); if (!wait) { ext4_read_bh_nowait(bh, op_flags, NULL, false); @@ -232,6 +238,7 @@ int ext4_read_bh_lock(struct buffer_head *bh, blk_opf_t op_flags, bool wait) } return ext4_read_bh(bh, op_flags, NULL, false); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_bh_lock); /* * This works like __bread_gfp() except it uses ERR_PTR for error @@ -293,8 +300,11 @@ struct buffer_head *ext4_sb_bread_nofail(struct super_block *sb, void ext4_sb_breadahead_unmovable(struct super_block *sb, sector_t block) { - struct buffer_head *bh = bdev_getblk(sb->s_bdev, block, - sb->s_blocksize, GFP_NOWAIT); + struct buffer_head *bh; + + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_breadahead_unmovable, sb, block); + + bh = bdev_getblk(sb->s_bdev, block, sb->s_blocksize, GFP_NOWAIT); if (likely(bh)) { if (trylock_buffer(bh)) @@ -302,6 +312,7 @@ void ext4_sb_breadahead_unmovable(struct super_block *sb, sector_t block) brelse(bh); } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_breadahead_unmovable); static int ext4_verify_csum_type(struct super_block *sb, struct ext4_super_block *es) @@ -413,6 +424,7 @@ void ext4_inode_bitmap_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_bitmap_set); void ext4_inode_table_set(struct super_block *sb, struct ext4_group_desc *bg, ext4_fsblk_t blk) @@ -421,6 +433,7 @@ void ext4_inode_table_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_inode_table_hi = cpu_to_le32(blk >> 32); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_table_set); void ext4_free_group_clusters_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) @@ -1611,6 +1624,7 @@ void ext4_clear_inode(struct inode *inode) } fscrypt_put_encryption_info(inode); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_clear_inode); static struct inode *ext4_nfs_get_inode(struct super_block *sb, u64 ino, u32 generation) From c5c8038b5d4c75d813f71ed9af9a50f02d5f4f5d Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Fri, 6 Nov 2026 04:38:31 +0000 Subject: [PATCH 1561/2102] ext4: add KUnit tests for fs/ext4/ialloc.c Add the ext4_ialloc_test KUnit test suite in fs/ext4/ialloc-test.c (28 test cases, 33 subtests total) to comprehensively exercise inode bitmap management, group selection heuristics, inode allocation, freeing, orphan lookup, and lazy inode table initialization in fs/ext4/ialloc.c using an in-memory VFS superblock, mock block device, and deterministic block pool without requiring a mounted block device: - Bitmap padding and asynchronous read completion helpers (ext4_mark_bitmap_end and ext4_end_bitmap_read) across unaligned and byte-aligned start/end bit boundaries, partial single-byte updates, no-op guards, BLK_STS_OK completion, and BLK_STS_IOERR / BIO_QUIET failure handling. - Inode bitmap validation and loading (ext4_validate_inode_bitmap and ext4_read_inode_bitmap), covering CRC32C verification, out-of-group metadata block overlap detection, EXT4_FC_REPLAY and buffer_verified short-circuits, cache hits vs. synchronous disk reads, lazy EXT4_BG_INODE_UNINIT bitmap initialization, and fault injection across ext4_get_group_desc, ext4_sb_getblk, and ext4_read_bh. - Inode freeing (ext4_free_inode) across regular files and directories, bitmap bit clearing, group descriptor, flex_bg, and percpu counter updates, CRC32C recomputation, guard rejections (NULL i_sb, i_count > 1, i_nlink > 0, reserved ino < EXT4_FIRST_INO, and out-of-range ino), double-free corruption marking, pre-corrupt bitmap skips (vs. EXT4_FC_REPLAY), and journal get_write_access error handling. - Orlov directory group allocator (find_group_orlov) across root and EXT4_INODE_TOPDIR spreading (hashed qstr and NULL qstr), subdirectory co-location, i_last_alloc_group hints, max_dirs / min_inodes / min_clusters thresholds, flex_bg constituent group packing, and two-pass linear fallback when percpu counters are inflated or all groups are exhausted. - Non-directory group allocator (find_group_other) with and without flex_bg, covering parent group preference, last-allocated group spreading, quadratic hash probing, cyclic linear search, and modulo wraparound. - Recently-deleted inode buffer-cache checks (recently_deleted) across EXT4_BG_INODE_UNINIT, bg_itable_unused bounds, uncached or non-uptodate inode table blocks, zero i_dtime, and clean (60s) vs. dirty (360s) buffer_dirty() recency windows, plus find_inode_bit scanning across non-journaled skipping, journaled (s_journal) bypass, and recently_deleted_ino fallback. - On-disk inode reservation during fast-commit replay (ext4_mark_inode_used) across uninitialized EXT4_BG_INODE_UNINIT and EXT4_BG_BLOCK_UNINIT groups, overhead cluster calculation, bg_itable_unused updates, idempotency on already-set bits, and invalid ino, inode/block bitmap read and wait, dirty-metadata, and sync_dirty_buffer error paths. - Extended attribute transaction credit estimation (ext4_xattr_credits_for_new_inode) across POSIX default ACL inheritance, security xattrs, and encryption contexts. - Full new-inode allocation (__ext4_new_inode) across regular files, directories, symlinks, and special files, flag inheritance and masking (EXT4_FL_INHERITED and ext4_mask_flags), EXT4_EA_INODE_FL inline-data suppression, UID/GID ownership overrides, SGID inheritance, EXT4_INODE_PROJINHERIT project ID propagation, explicit goal and s_inode_goal targeting, uninitialized group setup, corrupt/reserved bit skipping, EXT4_FC_REPLAY goal allocation, ext4_new_inode_start_handle, and error paths (-EPERM, emergency -EIO/-EROFS, -ENOMEM, -ENOSPC, duplicate inode hash -EIO, write-access and dirty-metadata failures, and ext4_init_security / ext4_mark_inode_dirty rollback). - Orphan inode lookup and validation (ext4_orphan_get), group free-inode and used-directory summation (ext4_count_free_inodes and ext4_count_dirs, including 64-bit high-16-bit fields), and lazy inode table zeroing (ext4_init_inode_table) across already-zeroed, uninit, partially used, full, bogus bg_itable_unused, and zeroout error cases. Route buffer-cache lookups in ialloc.c through ext4_sb_getblk() and ext4_sb_find_get_block(), extract ext4_itable_zeroout() with KUNIT_STATIC_STUB_REDIRECT, add KUNIT_STATIC_STUB_REDIRECT hooks in ext4_read_bh(), __ext4_journal_get_write_access(), and ext4_init_security(), and export the tested entry points and static-helper wrappers with EXPORT_SYMBOL_FOR_EXT4_TEST. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 2 +- fs/ext4/bitmap.c | 5 + fs/ext4/ext4.h | 21 + fs/ext4/ext4_jbd2.c | 4 + fs/ext4/ialloc-test.c | 2731 ++++++++++++++++++++++++++++++++++++++ fs/ext4/ialloc.c | 93 +- fs/ext4/super.c | 17 + fs/ext4/xattr_security.c | 4 + 8 files changed, 2865 insertions(+), 12 deletions(-) create mode 100644 fs/ext4/ialloc-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 7bd91839c3ce0c..72198aff5b4516 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -18,7 +18,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ extents_status-test.o xattr-test.o \ namei-test.o inline-test.o \ - fast_commit-test.o + fast_commit-test.o ialloc-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/bitmap.c b/fs/ext4/bitmap.c index 87760fabdd2eba..f9c22427891f20 100644 --- a/fs/ext4/bitmap.c +++ b/fs/ext4/bitmap.c @@ -15,6 +15,7 @@ unsigned int ext4_count_free(char *bitmap, unsigned int numchars) { return numchars * BITS_PER_BYTE - memweight(bitmap, numchars); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_count_free); int ext4_inode_bitmap_csum_verify(struct super_block *sb, struct ext4_group_desc *gdp, @@ -39,6 +40,7 @@ int ext4_inode_bitmap_csum_verify(struct super_block *sb, return provided == calculated; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_bitmap_csum_verify); void ext4_inode_bitmap_csum_set(struct super_block *sb, struct ext4_group_desc *gdp, @@ -57,6 +59,7 @@ void ext4_inode_bitmap_csum_set(struct super_block *sb, if (sbi->s_desc_size >= EXT4_BG_INODE_BITMAP_CSUM_HI_END) gdp->bg_inode_bitmap_csum_hi = cpu_to_le16(csum >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_bitmap_csum_set); int ext4_block_bitmap_csum_verify(struct super_block *sb, struct ext4_group_desc *gdp, @@ -80,6 +83,7 @@ int ext4_block_bitmap_csum_verify(struct super_block *sb, return provided == calculated; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_bitmap_csum_verify); void ext4_block_bitmap_csum_set(struct super_block *sb, struct ext4_group_desc *gdp, @@ -97,3 +101,4 @@ void ext4_block_bitmap_csum_set(struct super_block *sb, if (sbi->s_desc_size >= EXT4_BG_BLOCK_BITMAP_CSUM_HI_END) gdp->bg_block_bitmap_csum_hi = cpu_to_le16(csum >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_bitmap_csum_set); diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index bbe930023d1185..b7be93b0674672 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -3089,9 +3089,30 @@ extern struct inode * ext4_orphan_get(struct super_block *, unsigned long); extern unsigned long ext4_count_free_inodes(struct super_block *); extern unsigned long ext4_count_dirs(struct super_block *); extern void ext4_mark_bitmap_end(int start_bit, int end_bit, char *bitmap); +int ext4_itable_zeroout(struct super_block *sb, ext4_fsblk_t blk, int num, + int barrier); extern int ext4_init_inode_table(struct super_block *sb, ext4_group_t group, int barrier); void ext4_end_bitmap_read(struct bio *bio); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_validate_inode_bitmap_test(struct super_block *sb, + struct ext4_group_desc *desc, + ext4_group_t block_group, + struct buffer_head *bh); +struct buffer_head *ext4_read_inode_bitmap_test(struct super_block *sb, + ext4_group_t block_group); +int ext4_find_group_orlov_test(struct super_block *sb, struct inode *parent, + ext4_group_t *group, umode_t mode, + const struct qstr *qstr); +int ext4_find_group_other_test(struct super_block *sb, struct inode *parent, + ext4_group_t *group, umode_t mode); +int ext4_recently_deleted_test(struct super_block *sb, ext4_group_t group, + int ino); +int ext4_find_inode_bit_test(struct super_block *sb, ext4_group_t group, + struct buffer_head *bitmap, unsigned long *ino); +int ext4_xattr_credits_for_new_inode_test(struct inode *dir, mode_t mode, + bool encrypt); +#endif /* fast_commit.c */ int ext4_fc_get_buf(journal_t *journal, struct buffer_head **bh); diff --git a/fs/ext4/ext4_jbd2.c b/fs/ext4/ext4_jbd2.c index b6d84057009c51..3e6c9ce108aded 100644 --- a/fs/ext4/ext4_jbd2.c +++ b/fs/ext4/ext4_jbd2.c @@ -252,6 +252,9 @@ int __ext4_journal_get_write_access(const char *where, unsigned int line, { int err; + KUNIT_STATIC_STUB_REDIRECT(__ext4_journal_get_write_access, where, line, + handle, sb, bh, trigger_type); + might_sleep(); if (ext4_handle_valid(handle)) { @@ -271,6 +274,7 @@ int __ext4_journal_get_write_access(const char *where, unsigned int line, &EXT4_SB(sb)->s_journal_triggers[trigger_type].tr_triggers); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_journal_get_write_access); /* * The ext4 forget function must perform a revoke if we are freeing data diff --git a/fs/ext4/ialloc-test.c b/fs/ext4/ialloc-test.c new file mode 100644 index 00000000000000..c68b60c9596140 --- /dev/null +++ b/fs/ext4/ialloc-test.c @@ -0,0 +1,2731 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/ialloc.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "ext4_extents.h" +#include "xattr.h" +#include "acl.h" + +/* + * Multi-group mock filesystem geometry: + * - 4 block groups, 1024-byte blocks (8192 bits per bitmap block) + * - 64 inodes per group (256 total inodes), 256-byte inodes (4 per block) + * - 16 inode table blocks per group, 1024 blocks (clusters) per group + * - s_first_data_block = 1, s_first_ino = 11 (inodes 1..10 reserved in bg 0) + * - sparse_super enabled: groups 0, 1, 3 have backup super + 1 gdb (2 base + * clusters), while group 2 has 0 base clusters (18 total overhead clusters, + * leaving 1024 - 18 = 1006 free clusters after init). + */ +#define IALLOC_TEST_NGROUPS 4U +#define IALLOC_TEST_BLK_SIZE 1024U +#define IALLOC_TEST_BLK_BITS 10U +#define IALLOC_TEST_BLOCKS_PER_GRP 1024U +#define IALLOC_TEST_FIRST_DATA_BLK 1U +#define IALLOC_TEST_TOTAL_BLKS (IALLOC_TEST_FIRST_DATA_BLK + \ + IALLOC_TEST_NGROUPS * IALLOC_TEST_BLOCKS_PER_GRP) +#define IALLOC_TEST_INODE_SIZE 256U +#define IALLOC_TEST_EXTRA_ISIZE 32U +#define IALLOC_TEST_INODES_PER_BLK (IALLOC_TEST_BLK_SIZE / IALLOC_TEST_INODE_SIZE) +#define IALLOC_TEST_INODES_PER_GRP 64U +#define IALLOC_TEST_ITB_PER_GRP (IALLOC_TEST_INODES_PER_GRP / \ + IALLOC_TEST_INODES_PER_BLK) +#define IALLOC_TEST_TOTAL_INODES (IALLOC_TEST_NGROUPS * IALLOC_TEST_INODES_PER_GRP) +#define IALLOC_TEST_FIRST_INO 11U +#define IALLOC_TEST_BG0_FREE_INODES (IALLOC_TEST_INODES_PER_GRP - \ + (IALLOC_TEST_FIRST_INO - 1U)) +#define IALLOC_TEST_DEFAULT_FREE_CLU 800U +#define IALLOC_TEST_CSUM_SEED 0x6d4b29a3U + +#define IALLOC_TEST_GDESC_BLK 2ULL +#define IALLOC_TEST_POOL_SIZE 32U +#define IALLOC_TEST_MAX_TRACKED_INODES 32U + +struct ialloc_test_blk { + bool in_use; + bool in_cache; + bool marked_dirty; + ext4_fsblk_t blocknr; + struct buffer_head bh; + char cache_buf[IALLOC_TEST_BLK_SIZE] __aligned(8); + char disk_buf[IALLOC_TEST_BLK_SIZE] __aligned(8); +}; + +struct ialloc_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + struct buffer_head gdesc_bh; + char gdesc_buf[IALLOC_TEST_BLK_SIZE] __aligned(8); + bool gdesc_marked_dirty; + + struct ext4_group_desc gdps[IALLOC_TEST_NGROUPS]; + struct ext4_group_info *grp_infos[IALLOC_TEST_NGROUPS]; + struct ext4_group_info *grp_info_ptrs[16]; + struct ext4_group_info **grp_info_slice[1]; + + struct flex_groups flex_grps[IALLOC_TEST_NGROUPS]; + struct flex_groups *flex_grp_ptrs[IALLOC_TEST_NGROUPS]; + + struct inode *root_inode; + + struct ext4_inode_info standalone_ei; + struct inode *tracked_inodes[IALLOC_TEST_MAX_TRACKED_INODES]; + unsigned int nr_tracked_inodes; + bool evict_skip_free; + + struct ialloc_test_blk pool[IALLOC_TEST_POOL_SIZE]; + + /* Fault injection and call tracking */ + u32 fail_gdp_mask; + bool fail_getblk; + bool fail_read_eio; + bool fail_alloc_inode; + bool fail_sync_dirty_buffer; + int fail_bbitmap_err; + int fail_wait_bbitmap_err; + int fail_write_access_err; + int fail_write_access_on_call; + int fail_dirty_metadata_err; + int fail_dirty_metadata_on_call; + int fail_mark_inode_dirty_err; +#ifdef CONFIG_EXT4_FS_SECURITY + int fail_init_security_err; +#endif + int fail_itable_zeroout_err; + int fail_iget_err; + struct inode *iget_inode; + + unsigned int read_bh_calls; + unsigned int write_access_calls; + unsigned int dirty_metadata_calls; + unsigned int zeroout_calls; + ext4_fsblk_t last_zeroout_blk; + int last_zeroout_num; + int last_zeroout_barrier; +}; + +static inline ext4_fsblk_t ialloc_test_group_start(ext4_group_t g) +{ + return IALLOC_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * IALLOC_TEST_BLOCKS_PER_GRP; +} + +static inline ext4_fsblk_t ialloc_test_bbitmap_blk(ext4_group_t g) +{ + return ialloc_test_group_start(g) + 2; +} + +static inline ext4_fsblk_t ialloc_test_ibitmap_blk(ext4_group_t g) +{ + return ialloc_test_group_start(g) + 3; +} + +static inline ext4_fsblk_t ialloc_test_itable_blk(ext4_group_t g) +{ + return ialloc_test_group_start(g) + 4; +} + +static inline void clear_bitmap_uptodate(struct buffer_head *bh) +{ + clear_bit(BH_BITMAP_UPTODATE, &bh->b_state); +} + +static void ialloc_test_init_ei_fields(struct ext4_inode_info *ei) +{ + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_flags = 0; + ext4_clear_state_flags(ei); + spin_lock_init(&ei->i_raw_lock); + ei->i_prealloc_node = RB_ROOT; + atomic_set(&ei->i_prealloc_active, 0); + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + ei->i_es_all_nr = 0; + ei->i_es_shk_nr = 0; + ei->i_es_shrink_lblk = 0; + ei->i_es_seq = 0; + ei->i_reserved_data_blocks = 0; + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); +#ifdef CONFIG_QUOTA + ei->i_reserved_quota = 0; + memset(&ei->i_dquot, 0, sizeof(ei->i_dquot)); +#endif +#ifdef CONFIG_FS_ENCRYPTION + ei->i_crypt_info = NULL; +#endif + ei->jinode = NULL; + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + ei->i_sync_tid = 0; + ei->i_datasync_tid = 0; + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_metadata_bhs = NULL; + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = IALLOC_TEST_EXTRA_ISIZE; + ei->i_csum_seed = IALLOC_TEST_CSUM_SEED; + ei->i_last_alloc_group = ~0U; +} + +static struct inode *ialloc_test_alloc_inode(struct super_block *sb) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ext4_inode_info *ei; + + if (ctx && ctx->fail_alloc_inode) + return NULL; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + ialloc_test_init_ei_fields(ei); + return &ei->vfs_inode; +} + +static void ialloc_test_evict_inode(struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + truncate_inode_pages_final(&inode->i_data); + if (ctx && !ctx->evict_skip_free && + !inode->i_nlink && !is_bad_inode(inode)) { + ext4_free_inode(NULL, inode); + return; + } + ext4_clear_inode(inode); +} + +static void ialloc_test_destroy_inode(struct inode *inode) +{ + kfree(ext4_i_metadata_bhs(inode)); + EXT4_I(inode)->i_metadata_bhs = NULL; +} + +static void ialloc_test_free_inode_mem(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **ialloc_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *ialloc_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations ialloc_test_qops = { + .get_reserved_space = ialloc_test_get_reserved_space, +}; +#endif + +static const struct super_operations ialloc_test_sops = { + .alloc_inode = ialloc_test_alloc_inode, + .evict_inode = ialloc_test_evict_inode, + .destroy_inode = ialloc_test_destroy_inode, + .free_inode = ialloc_test_free_inode_mem, + .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = ialloc_test_get_dquots, +#endif +}; + +static int ialloc_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type ialloc_test_fs_type = { + .name = "ext4_ialloc_kunit", + .init_fs_context = ialloc_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static struct ialloc_test_blk *ialloc_test_find_blk(struct ialloc_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + unsigned int i; + + for (i = 0; i < IALLOC_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && ctx->pool[i].blocknr == blocknr) + return &ctx->pool[i]; + } + return NULL; +} + +static struct ialloc_test_blk *ialloc_test_find_blk_by_bh( + struct ialloc_test_ctx *ctx, struct buffer_head *bh) +{ + unsigned int i; + + for (i = 0; i < IALLOC_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && &ctx->pool[i].bh == bh) + return &ctx->pool[i]; + } + return NULL; +} + +static struct ialloc_test_blk *ialloc_test_setup_blk(struct ialloc_test_ctx *ctx, + ext4_fsblk_t blocknr, + bool in_cache, + bool uptodate) +{ + struct ialloc_test_blk *slot = ialloc_test_find_blk(ctx, blocknr); + unsigned int i; + + if (!slot) { + for (i = 0; i < IALLOC_TEST_POOL_SIZE; i++) { + if (!ctx->pool[i].in_use) { + slot = &ctx->pool[i]; + break; + } + } + } + if (!slot) + return NULL; + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->in_cache = in_cache; + slot->blocknr = blocknr; + slot->bh.b_bdev = &ctx->bdev; + slot->bh.b_blocknr = blocknr; + slot->bh.b_size = IALLOC_TEST_BLK_SIZE; + slot->bh.b_data = slot->cache_buf; + atomic_set(&slot->bh.b_count, 1); + if (uptodate) + set_buffer_uptodate(&slot->bh); + return slot; +} + +/* --- Static Stubs --- */ + +static struct ext4_group_desc *ialloc_test_get_group_desc_stub( + struct super_block *sb, ext4_group_t block_group, + struct buffer_head **bh) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx || block_group >= EXT4_SB(sb)->s_groups_count) + return NULL; + if (block_group < 32 && (ctx->fail_gdp_mask & BIT(block_group))) + return NULL; + if (bh) + *bh = &ctx->gdesc_bh; + return &ctx->gdps[block_group]; +} + +static struct buffer_head *ialloc_test_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ialloc_test_blk *slot; + + if (!ctx || ctx->fail_getblk) + return NULL; + slot = ialloc_test_find_blk(ctx, block); + if (!slot) + return NULL; + slot->in_cache = true; + get_bh(&slot->bh); + return &slot->bh; +} + +static struct buffer_head *ialloc_test_sb_find_get_block_stub( + struct super_block *sb, ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ialloc_test_blk *slot; + + if (!ctx) + return NULL; + slot = ialloc_test_find_blk(ctx, block); + if (!slot || !slot->in_cache) + return NULL; + get_bh(&slot->bh); + return &slot->bh; +} + +static int ialloc_test_read_bh_stub(struct buffer_head *bh, blk_opf_t op_flags, + bio_end_io_t end_io, bool simu_fail) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ialloc_test_blk *slot; + bool fail; + + if (!ctx) { + unlock_buffer(bh); + return -EIO; + } + ctx->read_bh_calls++; + slot = ialloc_test_find_blk_by_bh(ctx, bh); + fail = ctx->fail_read_eio || simu_fail || !slot; + + if (!fail) + memcpy(bh->b_data, slot->disk_buf, bh->b_size); + + if (end_io) { + struct bio *bio = bio_alloc(NULL, 0, REQ_OP_READ, GFP_KERNEL); + + if (bio) { + bio->bi_private = bh; + bio->bi_status = fail ? BLK_STS_IOERR : BLK_STS_OK; + end_io(bio); + return fail ? -EIO : 0; + } + } + + if (fail) { + clear_buffer_uptodate(bh); + } else { + set_buffer_uptodate(bh); + set_bitmap_uptodate(bh); + } + unlock_buffer(bh); + return fail ? -EIO : 0; +} + +static struct buffer_head *ialloc_test_read_bbitmap_nowait_stub( + struct super_block *sb, ext4_group_t block_group, + bool ignore_locked) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ialloc_test_blk *slot; + + if (!ctx) + return ERR_PTR(-EIO); + if (ctx->fail_bbitmap_err) + return ERR_PTR(ctx->fail_bbitmap_err); + slot = ialloc_test_find_blk(ctx, ialloc_test_bbitmap_blk(block_group)); + if (!slot) + return ERR_PTR(-ENOMEM); + set_buffer_uptodate(&slot->bh); + set_bitmap_uptodate(&slot->bh); + set_buffer_verified(&slot->bh); + get_bh(&slot->bh); + return &slot->bh; +} + +static int ialloc_test_wait_bbitmap_stub(struct super_block *sb, + ext4_group_t block_group, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + return ctx->fail_wait_bbitmap_err; +} + +static int ialloc_test_get_write_access_stub( + const char *where, unsigned int line, handle_t *handle, + struct super_block *sb, struct buffer_head *bh, + enum ext4_journal_trigger_type trigger_type) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + ctx->write_access_calls++; + if (ctx->fail_write_access_err && + (!ctx->fail_write_access_on_call || + ctx->write_access_calls == ctx->fail_write_access_on_call)) + return ctx->fail_write_access_err; + return 0; +} + +static int ialloc_test_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ialloc_test_blk *slot; + + if (!ctx) + return 0; + ctx->dirty_metadata_calls++; + if (ctx->fail_dirty_metadata_err && + (!ctx->fail_dirty_metadata_on_call || + ctx->dirty_metadata_calls == ctx->fail_dirty_metadata_on_call)) + return ctx->fail_dirty_metadata_err; + + if (bh) { + set_buffer_uptodate(bh); + if (bh == &ctx->gdesc_bh) { + ctx->gdesc_marked_dirty = true; + } else { + slot = ialloc_test_find_blk_by_bh(ctx, bh); + if (slot) + slot->marked_dirty = true; + } + if (ctx->fail_sync_dirty_buffer) { + clear_buffer_mapped(bh); + set_buffer_dirty(bh); + } else { + clear_buffer_dirty(bh); + } + } + return 0; +} + +static int ialloc_test_mark_inode_dirty_stub(handle_t *handle, + struct inode *inode, + const char *func, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + return ctx->fail_mark_inode_dirty_err; +} + +#ifdef CONFIG_EXT4_FS_SECURITY +static int ialloc_test_init_security_stub(handle_t *handle, + struct inode *inode, + struct inode *dir, + const struct qstr *qstr) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + return ctx->fail_init_security_err; +} +#endif + +static int ialloc_test_itable_zeroout_stub(struct super_block *sb, + ext4_fsblk_t blk, int num, + int barrier) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + ctx->zeroout_calls++; + ctx->last_zeroout_blk = blk; + ctx->last_zeroout_num = num; + ctx->last_zeroout_barrier = barrier; + return ctx->fail_itable_zeroout_err; +} + +static struct inode *ialloc_test_iget_stub(struct super_block *sb, + unsigned long ino, + ext4_iget_flags flags, + const char *function, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return ERR_PTR(-EIO); + if (ctx->fail_iget_err) + return ERR_PTR(ctx->fail_iget_err); + if (!ctx->iget_inode) + return ERR_PTR(-ENOENT); + ihold(ctx->iget_inode); + return ctx->iget_inode; +} + +/* --- Fixture Helpers & Cleanup --- */ + +static void ialloc_test_track_inode(struct kunit *test, + struct ialloc_test_ctx *ctx, + struct inode *inode) +{ + if (inode_state_read_once(inode) & I_NEW) + unlock_new_inode(inode); + KUNIT_ASSERT_LT(test, ctx->nr_tracked_inodes, + IALLOC_TEST_MAX_TRACKED_INODES); + ctx->tracked_inodes[ctx->nr_tracked_inodes++] = inode; +} + +static void ialloc_test_untrack_inode(struct ialloc_test_ctx *ctx, + struct inode *inode) +{ + unsigned int i; + + for (i = 0; i < ctx->nr_tracked_inodes; i++) { + if (ctx->tracked_inodes[i] == inode) { + ctx->tracked_inodes[i] = + ctx->tracked_inodes[--ctx->nr_tracked_inodes]; + ctx->tracked_inodes[ctx->nr_tracked_inodes] = NULL; + return; + } + } +} + +static void ialloc_test_sync_ibitmap_csum(struct ialloc_test_ctx *ctx, + ext4_group_t g, bool sync_disk) +{ + struct ialloc_test_blk *slot; + + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(g)); + if (!slot) + return; + ext4_inode_bitmap_csum_set(ctx->sb, &ctx->gdps[g], &slot->bh); + ext4_group_desc_csum_set(ctx->sb, g, &ctx->gdps[g]); + if (sync_disk) + memcpy(slot->disk_buf, slot->cache_buf, IALLOC_TEST_BLK_SIZE); +} + +static void ialloc_test_enable_flex_bg(struct ialloc_test_ctx *ctx, + unsigned int log_groups_per_flex) +{ + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + ext4_group_t g, fg; + + ext4_set_feature_flex_bg(sb); + sbi->s_log_groups_per_flex = log_groups_per_flex; + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) { + atomic_set(&ctx->flex_grps[g].free_inodes, 0); + atomic_set(&ctx->flex_grps[g].used_dirs, 0); + atomic64_set(&ctx->flex_grps[g].free_clusters, 0); + } + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) { + fg = ext4_flex_group(sbi, g); + atomic_add(ext4_free_inodes_count(sb, &ctx->gdps[g]), + &ctx->flex_grps[fg].free_inodes); + atomic_add(ext4_used_dirs_count(sb, &ctx->gdps[g]), + &ctx->flex_grps[fg].used_dirs); + atomic64_add(ext4_free_group_clusters(sb, &ctx->gdps[g]), + &ctx->flex_grps[fg].free_clusters); + } +} + +static void ialloc_test_prep_standalone_free_inode(struct ialloc_test_ctx *ctx, + unsigned long ino, + umode_t mode) +{ + struct ext4_inode_info *ei = &ctx->standalone_ei; + struct inode *inode = &ei->vfs_inode; + + memset(ei, 0, sizeof(*ei)); + init_rwsem(&ei->i_data_sem); + inode_init_once(inode); + inode->i_sb = ctx->sb; + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = ctx->sb->s_blocksize_bits; + inode->i_flags = S_NOQUOTA; + inode->i_mapping = &inode->i_data; + inode->i_data.host = inode; + mapping_set_gfp_mask(&inode->i_data, GFP_HIGHUSER_MOVABLE); + init_rwsem(&inode->i_rwsem); + init_rwsem(&inode->i_data.invalidate_lock); + spin_lock_init(&inode->i_lock); + inode_state_assign_raw(inode, I_FREEING); + inode->__i_nlink = 0; + atomic_set(&inode->i_count, 1); + ialloc_test_init_ei_fields(ei); +} + +static void ialloc_test_cleanup(void *data) +{ + struct ialloc_test_ctx *ctx = data; + handle_t *handle; + unsigned int i; + + ctx->evict_skip_free = true; + ctx->sbi.s_journal = NULL; + + while ((handle = ext4_journal_current_handle()) != NULL) + ext4_journal_stop(handle); + + for (i = 0; i < ctx->nr_tracked_inodes; i++) { + struct inode *ti = ctx->tracked_inodes[i]; + + if (ti) { + if (inode_state_read_once(ti) & I_NEW) + unlock_new_inode(ti); + spin_lock(&ti->i_lock); + inode_state_clear(ti, I_DIRTY_TIME); + spin_unlock(&ti->i_lock); + set_nlink(ti, 1); + iput(ti); + ctx->tracked_inodes[i] = NULL; + } + } + ctx->nr_tracked_inodes = 0; + + if (ctx->root_inode) { + set_nlink(ctx->root_inode, 2); + ctx->root_inode = NULL; + } + + deactivate_super(ctx->sb); + rcu_barrier(); + + percpu_counter_destroy(&ctx->sbi.s_dirs_counter); + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + + kfree(ctx); +} + +static int ialloc_test_init(struct kunit *test) +{ + struct ialloc_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + ext4_group_t g; + unsigned int bit; + s64 total_free_inodes = 0; + s64 total_free_clusters = 0; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + fc = fs_context_for_mount(&ialloc_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &ialloc_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &ialloc_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = IALLOC_TEST_BLK_SIZE; + sb->s_blocksize_bits = IALLOC_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_ialloc_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = IALLOC_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(IALLOC_TEST_FIRST_DATA_BLK); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + ctx->es.s_inodes_count = cpu_to_le32(IALLOC_TEST_TOTAL_INODES); + ctx->es.s_inodes_per_group = cpu_to_le32(IALLOC_TEST_INODES_PER_GRP); + ctx->es.s_blocks_per_group = cpu_to_le32(IALLOC_TEST_BLOCKS_PER_GRP); + ctx->es.s_clusters_per_group = cpu_to_le32(IALLOC_TEST_BLOCKS_PER_GRP); + ctx->es.s_first_ino = cpu_to_le32(IALLOC_TEST_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(IALLOC_TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(IALLOC_TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(IALLOC_TEST_EXTRA_ISIZE); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_blocks_count_set(&ctx->es, IALLOC_TEST_TOTAL_BLKS); + + ext4_set_feature_sparse_super(sb); + ext4_set_feature_extents(sb); + ext4_set_feature_extra_isize(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + ext4_set_feature_dir_index(sb); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + ctx->gdesc_bh.b_data = ctx->gdesc_buf; + ctx->gdesc_bh.b_size = IALLOC_TEST_BLK_SIZE; + ctx->gdesc_bh.b_blocknr = IALLOC_TEST_GDESC_BLK; + ctx->gdesc_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->gdesc_bh.b_count, 1); + set_buffer_uptodate(&ctx->gdesc_bh); + + sbi->s_inode_size = IALLOC_TEST_INODE_SIZE; + sbi->s_inodes_per_block = IALLOC_TEST_INODES_PER_BLK; + sbi->s_inodes_per_group = IALLOC_TEST_INODES_PER_GRP; + sbi->s_itb_per_group = IALLOC_TEST_ITB_PER_GRP; + sbi->s_first_ino = IALLOC_TEST_FIRST_INO; + sbi->s_want_extra_isize = IALLOC_TEST_EXTRA_ISIZE; + sbi->s_blocks_per_group = IALLOC_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = IALLOC_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = IALLOC_TEST_NGROUPS; + sbi->s_gdb_count = 1; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = IALLOC_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_bitmap_maxbytes = 0x1ff7ffff000ULL; + sbi->s_csum_seed = IALLOC_TEST_CSUM_SEED; + sbi->s_hash_seed[0] = 0x12345678U; + sbi->s_hash_seed[1] = 0x9abcdef0U; + sbi->s_hash_seed[2] = 0x13579bdfU; + sbi->s_hash_seed[3] = 0x2468ace0U; + + set_opt(sb, ERRORS_CONT); + set_opt(sb, ORDERED_DATA); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + /* Wire RCU-indexed group_info and flex_groups tables */ + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) { + struct ialloc_test_blk *iblk, *bblk; + u32 free_inos = (g == 0) ? IALLOC_TEST_BG0_FREE_INODES : + IALLOC_TEST_INODES_PER_GRP; + + ctx->grp_infos[g] = kunit_kzalloc(test, + sizeof(*ctx->grp_infos[g]), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->grp_infos[g]); + init_rwsem(&ctx->grp_infos[g]->alloc_sem); + ctx->grp_infos[g]->bb_state = 0; + ctx->grp_info_ptrs[g] = ctx->grp_infos[g]; + ctx->flex_grp_ptrs[g] = &ctx->flex_grps[g]; + + ext4_block_bitmap_set(sb, &ctx->gdps[g], + ialloc_test_bbitmap_blk(g)); + ext4_inode_bitmap_set(sb, &ctx->gdps[g], + ialloc_test_ibitmap_blk(g)); + ext4_inode_table_set(sb, &ctx->gdps[g], + ialloc_test_itable_blk(g)); + ext4_free_inodes_set(sb, &ctx->gdps[g], free_inos); + ext4_used_dirs_set(sb, &ctx->gdps[g], (g == 0) ? 1U : 0U); + ext4_itable_unused_set(sb, &ctx->gdps[g], free_inos); + ext4_free_group_clusters_set(sb, &ctx->gdps[g], + IALLOC_TEST_DEFAULT_FREE_CLU); + + iblk = ialloc_test_setup_blk(ctx, ialloc_test_ibitmap_blk(g), + true, true); + bblk = ialloc_test_setup_blk(ctx, ialloc_test_bbitmap_blk(g), + true, true); + if (!iblk || !bblk) { + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "block pool setup failed"); + } + + /* Mark reserved bits 0..9 in group 0 and end padding 64..8191 */ + if (g == 0) { + for (bit = 0; bit < IALLOC_TEST_FIRST_INO - 1; bit++) + ext4_set_bit(bit, iblk->cache_buf); + } + ext4_mark_bitmap_end(IALLOC_TEST_INODES_PER_GRP, + IALLOC_TEST_BLK_SIZE * 8, + iblk->cache_buf); + set_bitmap_uptodate(&iblk->bh); + set_buffer_verified(&iblk->bh); + + ext4_block_bitmap_csum_set(sb, &ctx->gdps[g], &bblk->bh); + memcpy(bblk->disk_buf, bblk->cache_buf, IALLOC_TEST_BLK_SIZE); + set_bitmap_uptodate(&bblk->bh); + set_buffer_verified(&bblk->bh); + + ialloc_test_sync_ibitmap_csum(ctx, g, true); + + total_free_inodes += free_inos; + total_free_clusters += IALLOC_TEST_DEFAULT_FREE_CLU; + } + ctx->grp_info_slice[0] = ctx->grp_info_ptrs; + rcu_assign_pointer(sbi->s_group_info, ctx->grp_info_slice); + rcu_assign_pointer(sbi->s_flex_groups, ctx->flex_grp_ptrs); + + err = percpu_counter_init(&sbi->s_freeclusters_counter, + total_free_clusters, GFP_KERNEL); + if (err) { + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = percpu_counter_init(&sbi->s_freeinodes_counter, + total_free_inodes, GFP_KERNEL); + if (err) { + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = percpu_counter_init(&sbi->s_dirs_counter, 1, GFP_KERNEL); + if (err) { + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + + /* Create hashed VFS root directory inode (EXT4_ROOT_INO = 2) */ + ctx->root_inode = new_inode(sb); + if (!ctx->root_inode) { + percpu_counter_destroy(&ctx->sbi.s_dirs_counter); + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to allocate root_inode"); + } + ctx->root_inode->i_ino = EXT4_ROOT_INO; + ctx->root_inode->i_mode = S_IFDIR | 0755; + ctx->root_inode->i_op = &simple_dir_inode_operations; + set_nlink(ctx->root_inode, 2); + EXT4_I(ctx->root_inode)->i_block_group = 0; + insert_inode_locked(ctx->root_inode); + unlock_new_inode(ctx->root_inode); + + sb->s_root = d_make_root(ctx->root_inode); + if (!sb->s_root) { + percpu_counter_destroy(&ctx->sbi.s_dirs_counter); + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + deactivate_locked_super(sb); + rcu_barrier(); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to allocate s_root"); + } + + up_write(&sb->s_umount); + + err = kunit_add_action_or_reset(test, ialloc_test_cleanup, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + kunit_activate_static_stub(test, ext4_get_group_desc, + ialloc_test_get_group_desc_stub); + kunit_activate_static_stub(test, ext4_sb_getblk, + ialloc_test_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_sb_find_get_block, + ialloc_test_sb_find_get_block_stub); + kunit_activate_static_stub(test, ext4_read_bh, + ialloc_test_read_bh_stub); + kunit_activate_static_stub(test, ext4_read_block_bitmap_nowait, + ialloc_test_read_bbitmap_nowait_stub); + kunit_activate_static_stub(test, ext4_wait_block_bitmap, + ialloc_test_wait_bbitmap_stub); + kunit_activate_static_stub(test, __ext4_journal_get_write_access, + ialloc_test_get_write_access_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + ialloc_test_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + ialloc_test_mark_inode_dirty_stub); +#ifdef CONFIG_EXT4_FS_SECURITY + kunit_activate_static_stub(test, ext4_init_security, + ialloc_test_init_security_stub); +#endif + kunit_activate_static_stub(test, ext4_itable_zeroout, + ialloc_test_itable_zeroout_stub); + kunit_activate_static_stub(test, __ext4_iget, + ialloc_test_iget_stub); + + return 0; +} + +/* ========================================================================= + * 1. Bitmap Helpers: ext4_mark_bitmap_end & ext4_end_bitmap_read + * ========================================================================= + */ + +struct mark_bitmap_end_param { + const char *desc; + int start_bit; + int end_bit; +}; + +static const struct mark_bitmap_end_param mark_bitmap_end_params[] = { + { "unaligned_start_to_aligned_end", 67, 128 }, + { "byte_aligned_memset_only", 64, 128 }, + { "single_partial_byte_no_memset", 3, 8 }, + { "unaligned_within_second_byte", 10, 16 }, + { "equal_start_and_end_noop", 64, 64 }, + { "start_greater_than_end_noop", 75, 64 }, +}; + +static void mark_bitmap_end_param_to_desc(const struct mark_bitmap_end_param *p, + char *desc) +{ + strscpy(desc, p->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(mark_bitmap_end, mark_bitmap_end_params, + mark_bitmap_end_param_to_desc); + +static void ialloc_test_mark_bitmap_end(struct kunit *test) +{ + const struct mark_bitmap_end_param *p = test->param_value; + char bitmap[24] = {}; + int bit; + + ext4_mark_bitmap_end(p->start_bit, p->end_bit, bitmap); + + for (bit = 0; bit < (int)sizeof(bitmap) * 8; bit++) { + bool expected = (p->start_bit < p->end_bit) && + (bit >= p->start_bit && bit < p->end_bit); + + KUNIT_EXPECT_EQ_MSG(test, (bool)ext4_test_bit(bit, bitmap), + expected, "%s: unexpected value at bit %d", + p->desc, bit); + } +} + +static void ialloc_test_end_bitmap_read_ok(struct kunit *test) +{ + struct buffer_head bh = {}; + struct bio *bio; + + atomic_set(&bh.b_count, 1); + lock_buffer(&bh); + + bio = bio_alloc(NULL, 0, REQ_OP_READ, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bio); + bio->bi_private = &bh; + bio->bi_status = BLK_STS_OK; + + ext4_end_bitmap_read(bio); + + KUNIT_EXPECT_FALSE(test, buffer_locked(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_uptodate(&bh)); + KUNIT_EXPECT_TRUE(test, bitmap_uptodate(&bh)); +} + +static void ialloc_test_end_bitmap_read_ioerr(struct kunit *test) +{ + struct buffer_head bh = {}; + struct bio *bio; + + atomic_set(&bh.b_count, 1); + lock_buffer(&bh); + + bio = bio_alloc(NULL, 0, REQ_OP_READ, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bio); + bio->bi_private = &bh; + bio->bi_status = BLK_STS_IOERR; + bio_set_flag(bio, BIO_QUIET); + + ext4_end_bitmap_read(bio); + + KUNIT_EXPECT_FALSE(test, buffer_locked(&bh)); + KUNIT_EXPECT_FALSE(test, buffer_uptodate(&bh)); + KUNIT_EXPECT_FALSE(test, bitmap_uptodate(&bh)); + KUNIT_EXPECT_TRUE(test, test_bit(BH_Quiet, &bh.b_state)); +} + +/* ========================================================================= + * 2. Inode Bitmap Validation: ext4_validate_inode_bitmap_test + * ========================================================================= + */ + +static void ialloc_test_validate_ibitmap_csum(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *slot; + s64 free_before; + int err; + + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* 64-bit group descriptor valid CRC */ + clear_buffer_verified(&slot->bh); + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[1], 1, &slot->bh); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, (bool)buffer_verified(&slot->bh)); + KUNIT_EXPECT_FALSE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + + /* 32-bit group descriptor valid CRC (low 16-bit checksum only) */ + ext4_clear_feature_64bit(sb); + ctx->sbi.s_desc_size = EXT4_MIN_DESC_SIZE; + ext4_inode_bitmap_csum_set(sb, &ctx->gdps[1], &slot->bh); + clear_buffer_verified(&slot->bh); + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[1], 1, &slot->bh); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, (bool)buffer_verified(&slot->bh)); + + /* Restore 64-bit descriptor and corrupt bitmap byte */ + ext4_set_feature_64bit(sb); + ctx->sbi.s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + ialloc_test_sync_ibitmap_csum(ctx, 1, false); + clear_buffer_verified(&slot->bh); + slot->cache_buf[0] ^= 0x01; + free_before = percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter); + + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[1], 1, &slot->bh); + KUNIT_EXPECT_EQ(test, err, -EFSBADCRC); + KUNIT_EXPECT_FALSE(test, (bool)buffer_verified(&slot->bh)); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter), + free_before - IALLOC_TEST_INODES_PER_GRP); +} + +static void ialloc_test_validate_ibitmap_short_circuits(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *slot; + int err; + + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* Corrupt byte, but EXT4_FC_REPLAY skips validation */ + clear_buffer_verified(&slot->bh); + slot->cache_buf[0] ^= 0xff; + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[2], 2, &slot->bh); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, (bool)buffer_verified(&slot->bh)); + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + + /* Already buffer_verified short-circuits before checking CRC */ + set_buffer_verified(&slot->bh); + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[2], 2, &slot->bh); + KUNIT_EXPECT_EQ(test, err, 0); + + /* Out-of-range group (NULL ext4_get_group_info) -> -EFSCORRUPTED */ + clear_buffer_verified(&slot->bh); + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[2], + IALLOC_TEST_NGROUPS + 1, + &slot->bh); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + + /* Pre-marked IBITMAP_CORRUPT -> -EFSCORRUPTED */ + set_bit(EXT4_GROUP_INFO_IBITMAP_CORRUPT_BIT, + &ctx->grp_infos[2]->bb_state); + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[2], 2, &slot->bh); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + +#ifdef CONFIG_EXT4_DEBUG + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, slot); + clear_buffer_verified(&slot->bh); + ctx->sbi.s_simulate_fail = EXT4_SIM_IBITMAP_CRC; + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[3], 3, &slot->bh); + KUNIT_EXPECT_EQ(test, err, -EFSBADCRC); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_simulate_fail, 0UL); +#endif +} + +/* ========================================================================= + * 3. Reading Inode Bitmaps: ext4_read_inode_bitmap_test + * ========================================================================= + */ + +static void ialloc_test_read_ibitmap_disk_and_cache(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *slot; + struct buffer_head *bh; + + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* Put distinctive valid bitmap on disk and invalidate cache flags */ + ext4_set_bit(5, slot->disk_buf); + memcpy(slot->cache_buf, slot->disk_buf, IALLOC_TEST_BLK_SIZE); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + memset(slot->cache_buf, 0, IALLOC_TEST_BLK_SIZE); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_bh_calls, 1U); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(5, bh->b_data)); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)buffer_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)buffer_verified(bh)); + brelse(bh); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), 1); + + /* Second read hits bitmap_uptodate fast path with zero I/O */ + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_bh_calls, 1U); + brelse(bh); + + /* buffer_uptodate && !bitmap_uptodate promotes bitmap_uptodate without I/O */ + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_bh_calls, 1U); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)buffer_verified(bh)); + brelse(bh); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), 1); +} + +static void ialloc_test_read_ibitmap_uninit(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *slot0, *slot1; + struct buffer_head *bh; + unsigned int bit; + + /* Group 1 with EXT4_BG_INODE_UNINIT initializes in memory without I/O */ + slot1 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot1); + memset(slot1->cache_buf, 0xaa, IALLOC_TEST_BLK_SIZE); + clear_bitmap_uptodate(&slot1->bh); + clear_buffer_uptodate(&slot1->bh); + clear_buffer_verified(&slot1->bh); + ctx->gdps[1].bg_flags |= cpu_to_le16(EXT4_BG_INODE_UNINIT); + + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_bh_calls, 0U); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)buffer_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)buffer_verified(bh)); + for (bit = 0; bit < IALLOC_TEST_INODES_PER_GRP; bit++) + KUNIT_EXPECT_FALSE_MSG(test, (bool)ext4_test_bit(bit, bh->b_data), + "expected bit %u cleared", bit); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_test_bit(IALLOC_TEST_INODES_PER_GRP, + bh->b_data)); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_test_bit(IALLOC_TEST_BLK_SIZE * 8 - 1, + bh->b_data)); + brelse(bh); + + /* Group 0 marked EXT4_BG_INODE_UNINIT is rejected as corrupt */ + slot0 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(0)); + KUNIT_ASSERT_NOT_NULL(test, slot0); + clear_bitmap_uptodate(&slot0->bh); + clear_buffer_uptodate(&slot0->bh); + ctx->gdps[0].bg_flags |= cpu_to_le16(EXT4_BG_INODE_UNINIT); + + bh = ext4_read_inode_bitmap_test(sb, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, atomic_read(&slot0->bh.b_count), 1); +} + +static void ialloc_test_read_ibitmap_errors(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *slot; + struct buffer_head *bh; + + /* NULL group descriptor */ + ctx->fail_gdp_mask = BIT(1); + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + ctx->fail_gdp_mask = 0; + + /* Invalid bitmap_blk <= s_first_data_block (1) */ + ext4_inode_bitmap_set(sb, &ctx->gdps[1], IALLOC_TEST_FIRST_DATA_BLK); + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + + /* Invalid bitmap_blk >= ext4_blocks_count(es) */ + ctx->grp_infos[1]->bb_state = 0; + ext4_inode_bitmap_set(sb, &ctx->gdps[1], IALLOC_TEST_TOTAL_BLKS); + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + ctx->grp_infos[1]->bb_state = 0; + ext4_inode_bitmap_set(sb, &ctx->gdps[1], ialloc_test_ibitmap_blk(1)); + + /* ext4_sb_getblk allocation failure */ + ctx->fail_getblk = true; + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -ENOMEM); + ctx->fail_getblk = false; + + /* Disk read I/O failure */ + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_uptodate(&slot->bh); + ctx->fail_read_eio = true; + bh = ext4_read_inode_bitmap_test(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EIO); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[2])); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), 1); + ctx->fail_read_eio = false; + + /* Bad CRC after successful disk read */ + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, slot); + slot->disk_buf[0] ^= 0x80; + clear_bitmap_uptodate(&slot->bh); + clear_buffer_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + bh = ext4_read_inode_bitmap_test(sb, 3); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSBADCRC); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[3])); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), 1); +} + +/* ========================================================================= + * 4. Freeing Inodes: ext4_free_inode + * ========================================================================= + */ + +static void ialloc_test_free_inode_reg_and_dir(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk; + s64 free_before, dirs_before; + + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + + /* Mark bit 2 (ino 67, reg) and bit 3 (ino 68, dir) allocated in group 1 */ + ext4_set_bit(2, iblk->cache_buf); + ext4_set_bit(3, iblk->cache_buf); + ext4_free_inodes_set(sb, &ctx->gdps[1], 62); + ext4_used_dirs_set(sb, &ctx->gdps[1], 1); + percpu_counter_add(&ctx->sbi.s_freeinodes_counter, -2); + percpu_counter_add(&ctx->sbi.s_dirs_counter, 1); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + ialloc_test_enable_flex_bg(ctx, 1); + + free_before = percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter); + dirs_before = percpu_counter_sum_positive(&ctx->sbi.s_dirs_counter); + + /* Free regular file ino 67 (group 1, bit 2, flex_group 0) */ + ialloc_test_prep_standalone_free_inode(ctx, 67, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(2, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[1]), 63U); + KUNIT_EXPECT_EQ(test, ext4_used_dirs_count(sb, &ctx->gdps[1]), 1U); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter), + free_before + 1); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_dirs_counter), + dirs_before); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->flex_grps[0].free_inodes), + (int)(IALLOC_TEST_BG0_FREE_INODES + 63)); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->flex_grps[0].used_dirs), 2); + KUNIT_EXPECT_TRUE(test, iblk->marked_dirty); + KUNIT_EXPECT_TRUE(test, ctx->gdesc_marked_dirty); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_inode_bitmap_csum_verify(sb, &ctx->gdps[1], + &iblk->bh)); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_group_desc_csum_verify(sb, 1, + &ctx->gdps[1])); + + /* Free directory ino 68 (group 1, bit 3, flex_group 0) */ + ialloc_test_prep_standalone_free_inode(ctx, 68, S_IFDIR | 0755); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(3, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[1]), 64U); + KUNIT_EXPECT_EQ(test, ext4_used_dirs_count(sb, &ctx->gdps[1]), 0U); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter), + free_before + 2); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_dirs_counter), + dirs_before - 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->flex_grps[0].used_dirs), 1); +} + +static void ialloc_test_free_inode_guards(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk0, *iblk1; + struct inode *inode = &ctx->standalone_ei.vfs_inode; + + iblk0 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(0)); + iblk1 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk0); + KUNIT_ASSERT_NOT_NULL(test, iblk1); + + ext4_set_bit(0, iblk1->cache_buf); /* ino 65 */ + ext4_free_inodes_set(sb, &ctx->gdps[1], 63); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + + /* NULL i_sb is ignored */ + ialloc_test_prep_standalone_free_inode(ctx, 65, S_IFREG | 0644); + inode->i_sb = NULL; + ext4_free_inode(NULL, inode); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(0, iblk1->cache_buf)); + + /* i_count > 1 is rejected before clear_inode */ + ialloc_test_prep_standalone_free_inode(ctx, 65, S_IFREG | 0644); + atomic_set(&inode->i_count, 2); + ext4_free_inode(NULL, inode); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(0, iblk1->cache_buf)); + KUNIT_EXPECT_FALSE(test, !!(inode_state_read_once(inode) & I_CLEAR)); + + /* i_nlink > 0 is rejected before clear_inode */ + ialloc_test_prep_standalone_free_inode(ctx, 65, S_IFREG | 0644); + set_nlink(inode, 1); + ext4_free_inode(NULL, inode); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(0, iblk1->cache_buf)); + KUNIT_EXPECT_FALSE(test, !!(inode_state_read_once(inode) & I_CLEAR)); + + /* Reserved ino < EXT4_FIRST_INO(sb) clears VFS inode then errors out */ + ialloc_test_prep_standalone_free_inode(ctx, 5, S_IFREG | 0644); + ext4_free_inode(NULL, inode); + KUNIT_EXPECT_TRUE(test, !!(inode_state_read_once(inode) & I_CLEAR)); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(4, iblk0->cache_buf)); + + /* Out-of-range ino > s_inodes_count clears VFS inode then errors out */ + ialloc_test_prep_standalone_free_inode(ctx, IALLOC_TEST_TOTAL_INODES + 1, + S_IFREG | 0644); + ext4_free_inode(NULL, inode); + KUNIT_EXPECT_TRUE(test, !!(inode_state_read_once(inode) & I_CLEAR)); +} + +static void ialloc_test_free_inode_corrupt_and_journal_errors(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk1, *iblk2, *iblk3; + + /* 1. Double-free (bit already clear) marks group bitmap corrupt */ + iblk1 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk1); + ialloc_test_prep_standalone_free_inode(ctx, 66, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[1]), 64U); + + /* 2. Pre-corrupt group skips bitmap clear unless EXT4_FC_REPLAY */ + iblk2 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, iblk2); + ext4_set_bit(0, iblk2->cache_buf); /* ino 129 */ + ext4_free_inodes_set(sb, &ctx->gdps[2], 63); + ialloc_test_sync_ibitmap_csum(ctx, 2, true); + set_bit(EXT4_GROUP_INFO_IBITMAP_CORRUPT_BIT, + &ctx->grp_infos[2]->bb_state); + + ialloc_test_prep_standalone_free_inode(ctx, 129, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(0, iblk2->cache_buf)); + + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + ialloc_test_prep_standalone_free_inode(ctx, 129, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(0, iblk2->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[2]), 64U); + + /* 3. Write-access failure on bitmap_bh (1st) vs bh2 (2nd) */ + iblk3 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, iblk3); + ext4_set_bit(0, iblk3->cache_buf); /* ino 193 */ + ext4_free_inodes_set(sb, &ctx->gdps[3], 63); + ialloc_test_sync_ibitmap_csum(ctx, 3, true); + + ctx->write_access_calls = 0; + ctx->fail_write_access_err = -EIO; + ctx->fail_write_access_on_call = 1; + ialloc_test_prep_standalone_free_inode(ctx, 193, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(0, iblk3->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[3]), 63U); + + ctx->write_access_calls = 0; + ctx->fail_write_access_on_call = 2; + iblk3->marked_dirty = false; + ialloc_test_prep_standalone_free_inode(ctx, 193, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(0, iblk3->cache_buf)); + KUNIT_EXPECT_TRUE(test, iblk3->marked_dirty); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[3]), 63U); + ctx->fail_write_access_err = 0; + ctx->fail_write_access_on_call = 0; +} + +/* ========================================================================= + * 5. Orlov Directory Allocator: ext4_find_group_orlov_test + * ========================================================================= + */ + +static void ialloc_test_orlov_topdir_spread(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct qstr qname = QSTR_INIT("projects", 8); + struct inode *subdir; + ext4_group_t grp = 0; + int ret; + + /* + * Configure group 2 as the unique above-average group with the lowest + * directory count (0 used_dirs, 64 free_inodes, 900 free_clusters). + */ + ext4_used_dirs_set(sb, &ctx->gdps[0], 5); + ext4_used_dirs_set(sb, &ctx->gdps[1], 4); + ext4_used_dirs_set(sb, &ctx->gdps[2], 0); + ext4_used_dirs_set(sb, &ctx->gdps[3], 6); + ext4_free_group_clusters_set(sb, &ctx->gdps[2], 900); + + ret = ext4_find_group_orlov_test(sb, ctx->root_inode, &grp, + S_IFDIR | 0755, &qname); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); + + /* qstr == NULL uses random start, still converges on best group 2 */ + grp = 0; + ret = ext4_find_group_orlov_test(sb, ctx->root_inode, &grp, + S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); + + /* Non-root directory with EXT4_INODE_TOPDIR also uses topdir spread */ + subdir = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, subdir); + subdir->i_ino = 65; + subdir->i_mode = S_IFDIR | 0755; + EXT4_I(subdir)->i_block_group = 1; + ext4_set_inode_flag(subdir, EXT4_INODE_TOPDIR); + ialloc_test_track_inode(test, ctx, subdir); + + grp = 0; + ret = ext4_find_group_orlov_test(sb, subdir, &grp, S_IFDIR | 0755, + &qname); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); +} + +static void ialloc_test_orlov_subdir_and_thresholds(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *parent; + ext4_group_t grp = 0; + int ret; + + parent = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, parent); + parent->i_ino = 65; + parent->i_mode = S_IFDIR | 0755; + EXT4_I(parent)->i_block_group = 1; + ialloc_test_track_inode(test, ctx, parent); + + /* Healthy parent_group (1) is preferred */ + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 1U); + + /* i_last_alloc_group overrides parent_group */ + EXT4_I(parent)->i_last_alloc_group = 3; + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); + EXT4_I(parent)->i_last_alloc_group = ~0U; + + /* Group 1 exceeds max_dirs -> advances cyclically to group 2 */ + ext4_used_dirs_set(sb, &ctx->gdps[1], 40); + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); + ext4_used_dirs_set(sb, &ctx->gdps[1], 0); + + /* Group 1 below min_inodes -> advances to group 2 */ + ext4_free_inodes_set(sb, &ctx->gdps[1], 2); + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); + ext4_free_inodes_set(sb, &ctx->gdps[1], IALLOC_TEST_INODES_PER_GRP); + + /* Group 1 below min_clusters -> advances to group 2 */ + ext4_free_group_clusters_set(sb, &ctx->gdps[1], 10); + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); +} + +static void ialloc_test_orlov_flex_bg_and_fallback(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *parent; + ext4_group_t grp = 0; + ext4_group_t g; + int ret; + + parent = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, parent); + parent->i_ino = 12; + parent->i_mode = S_IFDIR | 0755; + EXT4_I(parent)->i_block_group = 0; + ialloc_test_track_inode(test, ctx, parent); + + /* + * Flex size 2: flex 0 = {0, 1} has excessive dirs; flex 1 = {2, 3} + * is healthy, with group 2 full (0 free inodes) and group 3 having 64 + * free inodes -> packs into first available constituent group 3. + */ + ext4_used_dirs_set(sb, &ctx->gdps[0], 30); + ext4_used_dirs_set(sb, &ctx->gdps[1], 30); + ext4_free_inodes_set(sb, &ctx->gdps[2], 0); + ext4_free_inodes_set(sb, &ctx->gdps[3], 64); + percpu_counter_set(&ctx->sbi.s_dirs_counter, 60); + percpu_counter_set(&ctx->sbi.s_freeinodes_counter, + IALLOC_TEST_BG0_FREE_INODES + 64 + 0 + 64); + ialloc_test_enable_flex_bg(ctx, 1); + + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); + + /* Disable flex_bg and test fallback_retry with inflated counter */ + ctx->sbi.s_log_groups_per_flex = 0; + ext4_clear_feature_flex_bg(sb); + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) { + ext4_used_dirs_set(sb, &ctx->gdps[g], 50); + ext4_free_inodes_set(sb, &ctx->gdps[g], (g == 3) ? 1U : 0U); + } + /* Counter claims 200 free inodes (avefreei = 50), only bg 3 has 1 */ + percpu_counter_set(&ctx->sbi.s_freeinodes_counter, 200); + + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); + + /* All groups completely full -> returns -1 */ + ext4_free_inodes_set(sb, &ctx->gdps[3], 0); + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, -1); +} + +/* ========================================================================= + * 6. Non-Directory Group Allocator: ext4_find_group_other_test + * ========================================================================= + */ + +static void ialloc_test_find_group_other_non_flex(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *parent; + ext4_group_t grp = 0; + ext4_group_t g; + int ret; + + parent = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, parent); + parent->i_ino = 65; + parent->i_mode = S_IFDIR | 0755; + EXT4_I(parent)->i_block_group = 1; + ialloc_test_track_inode(test, ctx, parent); + + /* 1. Parent group 1 has both free inodes and free clusters */ + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 1U); + + /* + * 2. Quadratic hash probe when parent group 1 has 0 free inodes: + * start = (1 + 65) % 4 = 2; step i = 1 -> (2 + 1) % 4 = 3. + */ + ext4_free_inodes_set(sb, &ctx->gdps[1], 0); + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); + + /* + * 3. Linear fallback when no group has free clusters: + * starts at parent_group = 1, ++*group checks 2 first. + */ + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) + ext4_free_group_clusters_set(sb, &ctx->gdps[g], 0); + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); + + /* 4. Returns -1 when all groups have 0 free inodes */ + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) + ext4_free_inodes_set(sb, &ctx->gdps[g], 0); + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, -1); +} + +static void ialloc_test_find_group_other_flex_bg(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *parent; + ext4_group_t grp = 0; + int ret; + + parent = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, parent); + parent->i_ino = 65; + parent->i_mode = S_IFDIR | 0755; + EXT4_I(parent)->i_block_group = 1; + ialloc_test_track_inode(test, ctx, parent); + + /* + * Flex size 2: parent (i_ino = 65) in bg 1 (flex 0 = {0, 1}) spreads + * by parent->i_ino % flex_size -> bg 1 first, then falls back to bg 0. + */ + ialloc_test_enable_flex_bg(ctx, 1); + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 1U); + + ext4_free_inodes_set(sb, &ctx->gdps[1], 0); + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 0U); + + /* Flex 0 full, i_last_alloc_group = 2 (flex 1 = {2, 3}) retries flex 1 -> bg 3 */ + ext4_free_inodes_set(sb, &ctx->gdps[0], 0); + ialloc_test_enable_flex_bg(ctx, 1); + EXT4_I(parent)->i_last_alloc_group = 2; + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); + + /* Flex 0 full and i_last_alloc_group unset -> Orlov fallback picks flex 1 -> bg 3 */ + EXT4_I(parent)->i_last_alloc_group = ~0U; + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); +} + +/* ========================================================================= + * 7. Recently Deleted & Bit Search: recently_deleted & find_inode_bit + * ========================================================================= + */ + +static void ialloc_test_recently_deleted(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *it_slot; + struct ext4_inode *raw; + u32 now; + + /* 1. EXT4_BG_INODE_UNINIT returns 0 immediately */ + ctx->gdps[1].bg_flags |= cpu_to_le16(EXT4_BG_INODE_UNINIT); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 0), 0); + ctx->gdps[1].bg_flags &= ~cpu_to_le16(EXT4_BG_INODE_UNINIT); + + /* 2. Inode >= (64 - itable_unused) was never used -> returns 0 */ + ext4_itable_unused_set(sb, &ctx->gdps[1], 54); /* 0..9 used */ + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 10), 0); + + /* 3. Uncached inode table block -> returns 0 */ + it_slot = ialloc_test_setup_blk(ctx, ialloc_test_itable_blk(1), + false, true); + KUNIT_ASSERT_NOT_NULL(test, it_slot); + raw = (struct ext4_inode *)(it_slot->cache_buf + + 2 * IALLOC_TEST_INODE_SIZE); + now = ktime_get_real_seconds(); + raw->i_dtime = cpu_to_le32(now - 10); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 0); + + /* 4. Cached but !buffer_uptodate -> returns 0 */ + it_slot->in_cache = true; + clear_buffer_uptodate(&it_slot->bh); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 0); + set_buffer_uptodate(&it_slot->bh); + + /* 5. dtime == 0 -> returns 0 */ + raw->i_dtime = 0; + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 0); + + /* 6. Clean buffer uses 60s window; dirty buffer extends to 360s */ + now = ktime_get_real_seconds(); + raw->i_dtime = cpu_to_le32(now - 20); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 1); + + raw->i_dtime = cpu_to_le32(now - 120); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 0); + + set_buffer_dirty(&it_slot->bh); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 1); + + raw->i_dtime = cpu_to_le32(now - 400); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 0); + clear_buffer_dirty(&it_slot->bh); +} + +static void ialloc_test_find_inode_bit(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk, *it_slot; + struct ext4_inode *raw1; + unsigned long ino; + unsigned int bit; + int ret; + + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + ext4_itable_unused_set(sb, &ctx->gdps[1], 0); + + /* Mark all bits except bit 1 (recently deleted) and bit 6 (old) */ + for (bit = 0; bit < IALLOC_TEST_INODES_PER_GRP; bit++) { + if (bit != 1 && bit != 6) + ext4_set_bit(bit, iblk->cache_buf); + } + it_slot = ialloc_test_setup_blk(ctx, ialloc_test_itable_blk(1), + true, true); + KUNIT_ASSERT_NOT_NULL(test, it_slot); + raw1 = (struct ext4_inode *)(it_slot->cache_buf + IALLOC_TEST_INODE_SIZE); + raw1->i_dtime = cpu_to_le32((u32)ktime_get_real_seconds() - 10); + + /* No-journal mode skips recently deleted bit 1 in favor of bit 6 */ + ino = 0; + ret = ext4_find_inode_bit_test(sb, 1, &iblk->bh, &ino); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ino, 6UL); + + /* Journaled mode ignores recently_deleted and picks bit 1 directly */ + ctx->sbi.s_journal = (journal_t *)1UL; + ino = 0; + ret = ext4_find_inode_bit_test(sb, 1, &iblk->bh, &ino); + ctx->sbi.s_journal = NULL; + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ino, 1UL); + + /* Fallback: when bit 6 is also allocated, returns recently deleted bit 1 */ + ext4_set_bit(6, iblk->cache_buf); + ino = 0; + ret = ext4_find_inode_bit_test(sb, 1, &iblk->bh, &ino); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ino, 1UL); + + /* Full bitmap returns 0 */ + ext4_set_bit(1, iblk->cache_buf); + ino = 0; + ret = ext4_find_inode_bit_test(sb, 1, &iblk->bh, &ino); + KUNIT_EXPECT_EQ(test, ret, 0); +} + +/* ========================================================================= + * 8. Marking Specific Inodes Used: ext4_mark_inode_used + * ========================================================================= + */ + +static void ialloc_test_mark_inode_used_uninit(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk, *bblk; + int err; + + /* + * Configure group 2 with both EXT4_BG_INODE_UNINIT and + * EXT4_BG_BLOCK_UNINIT. Group 2 has no backup superblock, so overhead + * is 1 (bbitmap) + 1 (ibitmap) + 16 (itable) = 18 clusters -> 1006 free. + */ + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(2)); + bblk = ialloc_test_find_blk(ctx, ialloc_test_bbitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + KUNIT_ASSERT_NOT_NULL(test, bblk); + + clear_bitmap_uptodate(&iblk->bh); + clear_buffer_uptodate(&iblk->bh); + clear_buffer_verified(&iblk->bh); + ctx->gdps[2].bg_flags = cpu_to_le16(EXT4_BG_INODE_UNINIT | + EXT4_BG_BLOCK_UNINIT); + ext4_free_group_clusters_set(sb, &ctx->gdps[2], 0); + ext4_itable_unused_set(sb, &ctx->gdps[2], 64); + ext4_free_inodes_set(sb, &ctx->gdps[2], 64); + ext4_group_desc_csum_set(sb, 2, &ctx->gdps[2]); + + /* Inode 135 is in group 2, bit 6 ((135 - 1) % 64 == 6) */ + err = ext4_mark_inode_used(sb, 135); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, + le16_to_cpu(ctx->gdps[2].bg_flags) & + (EXT4_BG_INODE_UNINIT | EXT4_BG_BLOCK_UNINIT), 0); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, &ctx->gdps[2]), + 1006U); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(6, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_itable_unused_count(sb, &ctx->gdps[2]), 57U); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[2]), 63U); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_block_bitmap_csum_verify(sb, &ctx->gdps[2], + &bblk->bh)); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_inode_bitmap_csum_verify(sb, &ctx->gdps[2], + &iblk->bh)); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_group_desc_csum_verify(sb, 2, + &ctx->gdps[2])); + + /* Idempotent when bit 6 is already set */ + err = ext4_mark_inode_used(sb, 135); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[2]), 63U); + + /* Lower bit 2 (ino 131) decrements free_inodes without raising itable_unused */ + err = ext4_mark_inode_used(sb, 131); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(2, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_itable_unused_count(sb, &ctx->gdps[2]), 57U); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[2]), 62U); +} + +static void ialloc_test_mark_inode_used_errors(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk; + + /* Bounds checks: below EXT4_FIRST_INO and above max_ino */ + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 10), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, + ext4_mark_inode_used(sb, IALLOC_TEST_TOTAL_INODES + 1), + -EFSCORRUPTED); + + /* Inode bitmap read I/O failure */ + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + clear_bitmap_uptodate(&iblk->bh); + clear_buffer_uptodate(&iblk->bh); + ctx->fail_read_eio = true; + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 65), -EIO); + ctx->fail_read_eio = false; + + /* Dirty metadata error on group 2 (ino 129) */ + ctx->fail_dirty_metadata_err = -EIO; + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 129), -EIO); + ctx->fail_dirty_metadata_err = 0; + + /* sync_dirty_buffer I/O error on unmapped dirty buffer (ino 130) */ + ctx->fail_sync_dirty_buffer = true; + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 130), -EIO); + ctx->fail_sync_dirty_buffer = false; + + /* Block bitmap read and wait failures during EXT4_BG_BLOCK_UNINIT init */ + ctx->gdps[3].bg_flags |= cpu_to_le16(EXT4_BG_BLOCK_UNINIT); + ext4_group_desc_csum_set(sb, 3, &ctx->gdps[3]); + ctx->fail_bbitmap_err = -EIO; + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 193), -EIO); + ctx->fail_bbitmap_err = 0; + + ctx->fail_wait_bbitmap_err = -EFSCORRUPTED; + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 194), -EFSCORRUPTED); + ctx->fail_wait_bbitmap_err = 0; +} + +/* ========================================================================= + * 9. Xattr Credits & Inode Allocation: __ext4_new_inode + * ========================================================================= + */ + +#ifdef CONFIG_EXT4_FS_POSIX_ACL +static struct posix_acl *ialloc_test_err_get_inode_acl(struct inode *inode, + int type, bool rcu) +{ + return ERR_PTR(-EIO); +} + +static const struct inode_operations ialloc_test_err_acl_iops = { + .get_inode_acl = ialloc_test_err_get_inode_acl, +}; +#endif + +static void ialloc_test_xattr_credits_for_new_inode(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + int base, enc_creds, base_ea, enc_ea_creds; + + base = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, false); + KUNIT_ASSERT_GE(test, base, 0); + if (!IS_ENABLED(CONFIG_SECURITY)) + KUNIT_EXPECT_EQ(test, base, 0); + + /* Without ea_inode, encryption xattr adds 7 credits */ + enc_creds = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, true); + KUNIT_EXPECT_EQ(test, enc_creds, base + 7); + + /* With ea_inode on 1024B blocks, 40B fscrypt context adds 17 credits */ + ext4_set_feature_ea_inode(sb); + base_ea = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, false); + enc_ea_creds = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, + true); + KUNIT_EXPECT_EQ(test, enc_ea_creds, base_ea + 17); + ext4_clear_feature_ea_inode(sb); + +#ifdef CONFIG_EXT4_FS_POSIX_ACL + { + struct posix_acl *acl; + const struct inode_operations *orig_iops; + int reg_acl, dir_acl, err_acl; + + acl = posix_acl_alloc(1, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, acl); + set_cached_acl(ctx->root_inode, ACL_TYPE_DEFAULT, acl); + posix_acl_release(acl); + + reg_acl = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, + false); + dir_acl = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFDIR | 0755, + false); + KUNIT_EXPECT_EQ(test, reg_acl, base + 7); + KUNIT_EXPECT_EQ(test, dir_acl, base + 14); + forget_cached_acl(ctx->root_inode, ACL_TYPE_DEFAULT); + + orig_iops = ctx->root_inode->i_op; + ctx->root_inode->i_op = &ialloc_test_err_acl_iops; + sb->s_flags |= SB_POSIXACL; + err_acl = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, + false); + sb->s_flags &= ~SB_POSIXACL; + ctx->root_inode->i_op = orig_iops; + KUNIT_EXPECT_EQ(test, err_acl, -EIO); + } +#endif +} + +static void ialloc_test_new_inode_types_and_flags(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + handle_t *nojournal; + struct ialloc_test_blk *iblk0; + struct inode *reg, *dir, *lnk, *fifo, *ea_ino; + __le32 inum_le, gen_le; + u32 expected_seed; + s64 free_after_reg; + + nojournal = ext4_journal_start_sb(sb, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(nojournal)); + + ext4_set_feature_inline_data(sb); + ialloc_test_enable_flex_bg(ctx, 1); + EXT4_I(ctx->root_inode)->i_flags = EXT4_SYNC_FL | EXT4_NODUMP_FL | + EXT4_DIRSYNC_FL | EXT4_TOPDIR_FL | + EXT4_EXTENTS_FL; + + /* 1. Regular file in group 0 (first free bit is 10 -> ino 11) */ + reg = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, + NULL, 0, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(reg)); + ialloc_test_track_inode(test, ctx, reg); + KUNIT_EXPECT_EQ(test, reg->i_ino, 11UL); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(reg, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(reg)->eh_magic), + le16_to_cpu(EXT4_EXT_MAGIC)); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_state(reg, EXT4_STATE_NEW)); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(reg, EXT4_STATE_MAY_INLINE_DATA)); + KUNIT_EXPECT_EQ(test, + EXT4_I(reg)->i_flags & + (EXT4_SYNC_FL | EXT4_NODUMP_FL | EXT4_DIRSYNC_FL | + EXT4_TOPDIR_FL), + (u32)(EXT4_SYNC_FL | EXT4_NODUMP_FL)); + KUNIT_EXPECT_EQ(test, EXT4_I(reg)->i_extra_isize, + (u16)IALLOC_TEST_EXTRA_ISIZE); + + inum_le = cpu_to_le32(reg->i_ino); + gen_le = cpu_to_le32(reg->i_generation); + expected_seed = ext4_chksum(ctx->sbi.s_csum_seed, (u8 *)&inum_le, + sizeof(inum_le)); + expected_seed = ext4_chksum(expected_seed, (u8 *)&gen_le, + sizeof(gen_le)); + KUNIT_EXPECT_EQ(test, EXT4_I(reg)->i_csum_seed, expected_seed); + + /* + * 2. Directory inherits DIRSYNC (unlike regular files), still strips + * non-inheritable TOPDIR, and increments directory counters. + */ + dir = ext4_new_inode(nojournal, ctx->root_inode, S_IFDIR | 0755, + NULL, 12, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(dir)); + ialloc_test_track_inode(test, ctx, dir); + KUNIT_EXPECT_EQ(test, dir->i_ino, 12UL); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(dir, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, + EXT4_I(dir)->i_flags & + (EXT4_SYNC_FL | EXT4_NODUMP_FL | EXT4_DIRSYNC_FL | + EXT4_TOPDIR_FL), + (u32)(EXT4_SYNC_FL | EXT4_NODUMP_FL | + EXT4_DIRSYNC_FL)); + KUNIT_EXPECT_EQ(test, ext4_used_dirs_count(sb, &ctx->gdps[0]), 2U); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->flex_grps[0].used_dirs), 2); + + /* 3. Symlink gets EXT4_INODE_EXTENTS; FIFO does not */ + lnk = ext4_new_inode(nojournal, ctx->root_inode, S_IFLNK | 0777, + NULL, 13, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(lnk)); + ialloc_test_track_inode(test, ctx, lnk); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(lnk, EXT4_INODE_EXTENTS)); + + fifo = ext4_new_inode(nojournal, ctx->root_inode, S_IFIFO | 0600, + NULL, 14, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fifo)); + ialloc_test_track_inode(test, ctx, fifo); + KUNIT_EXPECT_FALSE(test, ext4_test_inode_flag(fifo, EXT4_INODE_EXTENTS)); + + /* 4. EXT4_EA_INODE_FL suppresses EXT4_STATE_MAY_INLINE_DATA */ + ea_ino = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0600, + NULL, 15, NULL, EXT4_EA_INODE_FL); + KUNIT_ASSERT_FALSE(test, IS_ERR(ea_ino)); + ialloc_test_track_inode(test, ctx, ea_ino); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(ea_ino, + EXT4_STATE_MAY_INLINE_DATA)); + + /* 5. Full lifecycle round-trip: unlink + iput frees ino 11 back */ + iblk0 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(0)); + KUNIT_ASSERT_NOT_NULL(test, iblk0); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(10, iblk0->cache_buf)); + free_after_reg = percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter); + + ialloc_test_untrack_inode(ctx, reg); + clear_nlink(reg); + iput(reg); + + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(10, iblk0->cache_buf)); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter), + free_after_reg + 1); + + ext4_journal_stop(nojournal); +} + +static void ialloc_test_new_inode_ownership_and_projid(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + handle_t *nojournal; + uid_t explicit_owner[2] = { 1001, 2002 }; + struct inode *ino_own, *ino_grpid, *ino_sgid; + + nojournal = ext4_journal_start_sb(sb, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(nojournal)); + + i_gid_write(ctx->root_inode, 3003); + ext4_set_feature_project(sb); + EXT4_I(ctx->root_inode)->i_projid = make_kprojid(&init_user_ns, 42); + ext4_set_inode_flag(ctx->root_inode, EXT4_INODE_PROJINHERIT); + + /* Explicit owner overrides uid/gid and inherits projid 42 */ + ino_own = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0640, + NULL, 0, explicit_owner, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_own)); + ialloc_test_track_inode(test, ctx, ino_own); + KUNIT_EXPECT_EQ(test, i_uid_read(ino_own), 1001U); + KUNIT_EXPECT_EQ(test, i_gid_read(ino_own), 2002U); + KUNIT_EXPECT_EQ(test, + from_kprojid(&init_user_ns, EXT4_I(ino_own)->i_projid), + 42U); + + /* Without PROJINHERIT on parent, child gets EXT4_DEF_PROJID (0) and GRPID gid */ + ext4_clear_inode_flag(ctx->root_inode, EXT4_INODE_PROJINHERIT); + set_opt(sb, GRPID); + ino_grpid = ext4_new_inode(nojournal, ctx->root_inode, S_IFDIR | 0750, + NULL, 0, NULL, 0); + clear_opt(sb, GRPID); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_grpid)); + ialloc_test_track_inode(test, ctx, ino_grpid); + KUNIT_EXPECT_EQ(test, i_gid_read(ino_grpid), 3003U); + KUNIT_EXPECT_FALSE(test, !!(ino_grpid->i_mode & S_ISGID)); + KUNIT_EXPECT_EQ(test, + from_kprojid(&init_user_ns, EXT4_I(ino_grpid)->i_projid), + 0U); + + /* Standard inode_init_owner propagates parent's S_ISGID to child dir */ + ctx->root_inode->i_mode |= S_ISGID; + ino_sgid = ext4_new_inode(nojournal, ctx->root_inode, S_IFDIR | 0755, + NULL, 0, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_sgid)); + ialloc_test_track_inode(test, ctx, ino_sgid); + KUNIT_EXPECT_EQ(test, i_gid_read(ino_sgid), 3003U); + KUNIT_EXPECT_TRUE(test, !!(ino_sgid->i_mode & S_ISGID)); + + ext4_journal_stop(nojournal); +} + +static void ialloc_test_new_inode_goal_uninit_and_corrupt_skip(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + handle_t *nojournal; + struct ialloc_test_blk *iblk0, *iblk2; + struct inode *ino_goal, *ino_sb_goal, *ino_skip, *ino_started; + struct inode *ino_replay; + + nojournal = ext4_journal_start_sb(sb, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(nojournal)); + + /* 1. Explicit goal = 140 in uninitialized group 2 (bit 11) */ + iblk2 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, iblk2); + clear_bitmap_uptodate(&iblk2->bh); + clear_buffer_uptodate(&iblk2->bh); + clear_buffer_verified(&iblk2->bh); + ctx->gdps[2].bg_flags = cpu_to_le16(EXT4_BG_INODE_UNINIT | + EXT4_BG_BLOCK_UNINIT); + ext4_group_desc_csum_set(sb, 2, &ctx->gdps[2]); + + ino_goal = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, + NULL, 140, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_goal)); + ialloc_test_track_inode(test, ctx, ino_goal); + KUNIT_EXPECT_EQ(test, ino_goal->i_ino, 140UL); + KUNIT_EXPECT_EQ(test, + le16_to_cpu(ctx->gdps[2].bg_flags) & + (EXT4_BG_INODE_UNINIT | EXT4_BG_BLOCK_UNINIT), 0); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, &ctx->gdps[2]), + 1006U); + KUNIT_EXPECT_EQ(test, ext4_itable_unused_count(sb, &ctx->gdps[2]), 52U); + + /* 2. sbi->s_inode_goal = 200 (group 3, bit 7) used when goal == 0 */ + ctx->sbi.s_inode_goal = 200; + ino_sb_goal = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, + NULL, 0, NULL, 0); + ctx->sbi.s_inode_goal = 0; + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_sb_goal)); + ialloc_test_track_inode(test, ctx, ino_sb_goal); + KUNIT_EXPECT_EQ(test, ino_sb_goal->i_ino, 200UL); + + /* + * 3. Reserved bit 3 (ino 4 < EXT4_FIRST_INO) cleared in group 0: + * marks group 0 IBITMAP_CORRUPT and advances to group 1 (ino 65). + */ + iblk0 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(0)); + KUNIT_ASSERT_NOT_NULL(test, iblk0); + ext4_clear_bit(3, iblk0->cache_buf); + ialloc_test_sync_ibitmap_csum(ctx, 0, true); + + ino_skip = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, + NULL, 4, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_skip)); + ialloc_test_track_inode(test, ctx, ino_skip); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[0])); + KUNIT_EXPECT_EQ(test, ino_skip->i_ino, 65UL); + + ext4_journal_stop(nojournal); + + /* 4. ext4_new_inode_start_handle (handle == NULL) starts handle */ + KUNIT_ASSERT_NULL(test, ext4_journal_current_handle()); + ino_started = ext4_new_inode_start_handle(&nop_mnt_idmap, + ctx->root_inode, + S_IFREG | 0644, NULL, 66, + NULL, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_started)); + ialloc_test_track_inode(test, ctx, ino_started); + KUNIT_EXPECT_EQ(test, ino_started->i_ino, 66UL); + KUNIT_ASSERT_NOT_NULL(test, ext4_journal_current_handle()); + ext4_journal_stop(ext4_journal_current_handle()); + KUNIT_EXPECT_NULL(test, ext4_journal_current_handle()); + + /* + * 5. EXT4_FC_REPLAY with handle == NULL allocates exact goal ino 15 in + * group 0 despite IBITMAP_CORRUPT and without starting a handle. + */ + ext4_set_bit(3, iblk0->cache_buf); + ialloc_test_sync_ibitmap_csum(ctx, 0, true); + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + ino_replay = ext4_new_inode(NULL, ctx->root_inode, S_IFREG | 0644, + NULL, 15, NULL, 0); + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_replay)); + ialloc_test_track_inode(test, ctx, ino_replay); + KUNIT_EXPECT_EQ(test, ino_replay->i_ino, 15UL); + KUNIT_EXPECT_NULL(test, ext4_journal_current_handle()); +} + +static void ialloc_test_new_inode_errors(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + handle_t *nojournal; + struct inode *unlinked_dir, *dup_existing, *res; + struct ialloc_test_blk *iblk; + ext4_group_t g; + + nojournal = ext4_journal_start_sb(sb, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(nojournal)); + + /* 1. NULL dir or unlinked dir -> -EPERM */ + res = ext4_new_inode(nojournal, NULL, S_IFREG | 0644, NULL, 0, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EPERM); + + unlinked_dir = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, unlinked_dir); + unlinked_dir->i_ino = 50; + unlinked_dir->i_mode = S_IFDIR | 0755; + clear_nlink(unlinked_dir); + ialloc_test_track_inode(test, ctx, unlinked_dir); + res = ext4_new_inode(nojournal, unlinked_dir, S_IFREG | 0644, NULL, 0, + NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EPERM); + + /* 2. Emergency shutdown (-EIO) and emergency RO (-EROFS) */ + set_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 0, NULL, 0); + clear_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + + set_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 0, NULL, 0); + clear_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EROFS); + + /* 3. VFS alloc_inode failure -> -ENOMEM */ + ctx->fail_alloc_inode = true; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 0, NULL, 0); + ctx->fail_alloc_inode = false; + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -ENOMEM); + + /* 4. Journal write-access and dirty-metadata failures in group 1 */ + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + + ctx->write_access_calls = 0; + ctx->fail_write_access_err = -EIO; + ctx->fail_write_access_on_call = 1; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 70, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(5, iblk->cache_buf)); + + ctx->write_access_calls = 0; + ctx->fail_write_access_on_call = 2; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 71, NULL, 0); + ctx->fail_write_access_err = 0; + ctx->fail_write_access_on_call = 0; + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(6, iblk->cache_buf)); + ext4_clear_bit(6, iblk->cache_buf); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + + ctx->dirty_metadata_calls = 0; + ctx->fail_dirty_metadata_err = -EIO; + ctx->fail_dirty_metadata_on_call = 1; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 71, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + ext4_clear_bit(6, iblk->cache_buf); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + + ctx->dirty_metadata_calls = 0; + ctx->fail_dirty_metadata_on_call = 2; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 71, NULL, 0); + ctx->fail_dirty_metadata_err = 0; + ctx->fail_dirty_metadata_on_call = 0; + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + ext4_clear_bit(6, iblk->cache_buf); + ext4_free_inodes_set(sb, &ctx->gdps[1], 64); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + +#ifdef CONFIG_EXT4_FS_SECURITY + /* 5. ext4_init_security failure rolls back allocated inode bit */ + ctx->fail_init_security_err = -EACCES; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 70, NULL, 0); + ctx->fail_init_security_err = 0; + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EACCES); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(5, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[1]), 64U); +#endif + + /* 6. ext4_mark_inode_dirty failure rolls back allocated inode bit */ + ctx->fail_mark_inode_dirty_err = -EIO; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 70, NULL, 0); + ctx->fail_mark_inode_dirty_err = 0; + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(5, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[1]), 64U); + + /* + * 7. Doubly-allocated inode (insert_inode_locked collision): + * Pre-hash ino 140 in VFS cache, leave only bg 2 non-empty with bit 11 + * clear -> marks bg 2 IBITMAP_CORRUPT and returns -EIO. + */ + dup_existing = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, dup_existing); + dup_existing->i_ino = 140; + dup_existing->i_mode = S_IFREG | 0644; + KUNIT_ASSERT_EQ(test, insert_inode_locked(dup_existing), 0); + ialloc_test_track_inode(test, ctx, dup_existing); + + ext4_free_inodes_set(sb, &ctx->gdps[0], 0); + ext4_free_inodes_set(sb, &ctx->gdps[1], 0); + ext4_free_inodes_set(sb, &ctx->gdps[3], 0); + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 140, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[2])); + + /* 8. Descriptor claims free inodes in bg 3, but bitmap is all ones -> -ENOSPC */ + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + memset(iblk->cache_buf, 0xff, IALLOC_TEST_BLK_SIZE); + ialloc_test_sync_ibitmap_csum(ctx, 3, true); + ext4_free_inodes_set(sb, &ctx->gdps[2], 0); + ext4_free_inodes_set(sb, &ctx->gdps[3], 5); + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 193, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -ENOSPC); + + /* 9. All groups report 0 free inodes -> -ENOSPC before loop */ + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) + ext4_free_inodes_set(sb, &ctx->gdps[g], 0); + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 0, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -ENOSPC); + + ext4_journal_stop(nojournal); +} + +/* ========================================================================= + * 10. Orphans, Counters, & Lazy Init: ext4_orphan_get, ext4_count_*, + * ext4_init_inode_table + * ========================================================================= + */ + +static void ialloc_test_orphan_get(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk1; + struct inode *orphan, *got; + + /* Bounds checks */ + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_orphan_get(sb, 5)), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_orphan_get(sb, IALLOC_TEST_TOTAL_INODES + 1)), + -EFSCORRUPTED); + + /* Clear bit in bitmap -> -EFSCORRUPTED */ + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_orphan_get(sb, 65)), -EFSCORRUPTED); + + /* Mark bit 0 (ino 65) allocated in group 1 */ + iblk1 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk1); + ext4_set_bit(0, iblk1->cache_buf); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + + /* Bitmap read error propagates */ + clear_bitmap_uptodate(&iblk1->bh); + clear_buffer_uptodate(&iblk1->bh); + ctx->fail_read_eio = true; + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_orphan_get(sb, 65)), -EIO); + ctx->fail_read_eio = false; + set_buffer_uptodate(&iblk1->bh); + set_bitmap_uptodate(&iblk1->bh); + set_buffer_verified(&iblk1->bh); + + /* ext4_iget error propagates */ + ctx->fail_iget_err = -EIO; + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_orphan_get(sb, 65)), -EIO); + ctx->fail_iget_err = 0; + + /* Prepare mock orphan inode */ + orphan = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, orphan); + orphan->i_ino = 65; + ialloc_test_track_inode(test, ctx, orphan); + ctx->iget_inode = orphan; + + /* 1. Valid unlinked orphan (i_nlink == 0, NEXT_ORPHAN <= max_ino) */ + orphan->i_mode = S_IFREG | 0644; + clear_nlink(orphan); + orphan->i_blocks = 8; + NEXT_ORPHAN(orphan) = 0; + got = ext4_orphan_get(sb, 65); + KUNIT_ASSERT_PTR_EQ(test, got, orphan); + iput(got); + + /* 2. Valid live truncating regular file orphan (i_nlink == 1) */ + set_nlink(orphan, 1); + ext4_set_inode_flag(orphan, EXT4_INODE_EXTENTS); + got = ext4_orphan_get(sb, 65); + KUNIT_ASSERT_PTR_EQ(test, got, orphan); + iput(got); + + /* 3. Live non-truncatable FIFO (i_nlink == 1) -> -EFSCORRUPTED */ + orphan->i_mode = S_IFIFO | 0600; + got = ext4_orphan_get(sb, 65); + KUNIT_EXPECT_EQ(test, PTR_ERR(got), -EFSCORRUPTED); + + /* 4. Unlinked orphan with NEXT_ORPHAN > max_ino zeroes i_blocks */ + orphan->i_mode = S_IFREG | 0644; + clear_nlink(orphan); + orphan->i_blocks = 24; + NEXT_ORPHAN(orphan) = IALLOC_TEST_TOTAL_INODES + 50; + got = ext4_orphan_get(sb, 65); + KUNIT_EXPECT_EQ(test, PTR_ERR(got), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, orphan->i_blocks, (blkcnt_t)0); + + /* 5. Unlinked bad_inode zeroes i_blocks and returns -EFSCORRUPTED */ + NEXT_ORPHAN(orphan) = 0; + orphan->i_blocks = 16; + make_bad_inode(orphan); + got = ext4_orphan_get(sb, 65); + KUNIT_EXPECT_EQ(test, PTR_ERR(got), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, orphan->i_blocks, (blkcnt_t)0); +} + +static void ialloc_test_count_free_inodes_and_dirs(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + /* Include 64-bit high-16-bit values (0x10000 + low) and a NULL gdp */ + ext4_free_inodes_set(sb, &ctx->gdps[0], 10); + ext4_free_inodes_set(sb, &ctx->gdps[1], 0x10020); + ext4_free_inodes_set(sb, &ctx->gdps[2], 999); /* masked out below */ + ext4_free_inodes_set(sb, &ctx->gdps[3], 5); + + ext4_used_dirs_set(sb, &ctx->gdps[0], 2); + ext4_used_dirs_set(sb, &ctx->gdps[1], 0x20003); + ext4_used_dirs_set(sb, &ctx->gdps[2], 777); /* masked out below */ + ext4_used_dirs_set(sb, &ctx->gdps[3], 4); + + ctx->fail_gdp_mask = BIT(2); + + KUNIT_EXPECT_EQ(test, ext4_count_free_inodes(sb), 0x1002fUL); + KUNIT_EXPECT_EQ(test, ext4_count_dirs(sb), 0x20009UL); +} + +static void ialloc_test_init_inode_table(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + int err; + + /* 1. Already EXT4_BG_INODE_ZEROED is a no-op */ + ctx->gdps[1].bg_flags = cpu_to_le16(EXT4_BG_INODE_ZEROED); + err = ext4_init_inode_table(sb, 1, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->zeroout_calls, 0U); + + /* 2. Uninitialized group 1 zeroes all 16 blocks with barrier = 1 */ + ctx->gdps[1].bg_flags = cpu_to_le16(EXT4_BG_INODE_UNINIT); + err = ext4_init_inode_table(sb, 1, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->zeroout_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_blk, ialloc_test_itable_blk(1)); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_num, 16); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_barrier, 1); + KUNIT_EXPECT_TRUE(test, + !!(le16_to_cpu(ctx->gdps[1].bg_flags) & + EXT4_BG_INODE_ZEROED)); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_group_desc_csum_verify(sb, 1, + &ctx->gdps[1])); + + /* + * 3. Initialized group 2 with itable_unused = 54 -> used_inos = 10 -> + * used_blks = DIV_ROUND_UP(10, 4) = 3 -> zeroes remaining 13 blocks. + */ + ctx->gdps[2].bg_flags = 0; + ext4_itable_unused_set(sb, &ctx->gdps[2], 54); + err = ext4_init_inode_table(sb, 2, 0); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->zeroout_calls, 2U); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_blk, + ialloc_test_itable_blk(2) + 3); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_num, 13); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_barrier, 0); + KUNIT_EXPECT_TRUE(test, + !!(le16_to_cpu(ctx->gdps[2].bg_flags) & + EXT4_BG_INODE_ZEROED)); + + /* 4. Full inode table (itable_unused = 0 -> num = 0) skips zeroout, sets ZEROED */ + ctx->gdps[3].bg_flags = 0; + ext4_itable_unused_set(sb, &ctx->gdps[3], 0); + err = ext4_init_inode_table(sb, 3, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->zeroout_calls, 2U); + KUNIT_EXPECT_TRUE(test, + !!(le16_to_cpu(ctx->gdps[3].bg_flags) & + EXT4_BG_INODE_ZEROED)); + + /* 5. Corrupt itable_unused > inodes_per_group returns 1 without ZEROED */ + ctx->gdps[3].bg_flags = 0; + ext4_itable_unused_set(sb, &ctx->gdps[3], 100); + err = ext4_init_inode_table(sb, 3, 0); + KUNIT_EXPECT_EQ(test, err, 1); + KUNIT_EXPECT_FALSE(test, + !!(le16_to_cpu(ctx->gdps[3].bg_flags) & + EXT4_BG_INODE_ZEROED)); + + /* 6. Group 0 with used_inos (4) < EXT4_FIRST_INO (11) returns 1 */ + ctx->gdps[0].bg_flags = 0; + ext4_itable_unused_set(sb, &ctx->gdps[0], 60); + err = ext4_init_inode_table(sb, 0, 0); + KUNIT_EXPECT_EQ(test, err, 1); + KUNIT_EXPECT_FALSE(test, + !!(le16_to_cpu(ctx->gdps[0].bg_flags) & + EXT4_BG_INODE_ZEROED)); + + /* 7. Zeroout I/O failure (-EIO) and emergency RO (-EROFS) */ + ctx->gdps[3].bg_flags = cpu_to_le16(EXT4_BG_INODE_UNINIT); + ctx->fail_itable_zeroout_err = -EIO; + err = ext4_init_inode_table(sb, 3, 0); + ctx->fail_itable_zeroout_err = 0; + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_FALSE(test, + !!(le16_to_cpu(ctx->gdps[3].bg_flags) & + EXT4_BG_INODE_ZEROED)); + + set_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + err = ext4_init_inode_table(sb, 3, 0); + clear_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, err, -EROFS); +} + +static struct kunit_case ialloc_test_cases[] = { + KUNIT_CASE_PARAM(ialloc_test_mark_bitmap_end, + mark_bitmap_end_gen_params), + KUNIT_CASE(ialloc_test_end_bitmap_read_ok), + KUNIT_CASE(ialloc_test_end_bitmap_read_ioerr), + KUNIT_CASE(ialloc_test_validate_ibitmap_csum), + KUNIT_CASE(ialloc_test_validate_ibitmap_short_circuits), + KUNIT_CASE(ialloc_test_read_ibitmap_disk_and_cache), + KUNIT_CASE(ialloc_test_read_ibitmap_uninit), + KUNIT_CASE(ialloc_test_read_ibitmap_errors), + KUNIT_CASE(ialloc_test_free_inode_reg_and_dir), + KUNIT_CASE(ialloc_test_free_inode_guards), + KUNIT_CASE(ialloc_test_free_inode_corrupt_and_journal_errors), + KUNIT_CASE(ialloc_test_orlov_topdir_spread), + KUNIT_CASE(ialloc_test_orlov_subdir_and_thresholds), + KUNIT_CASE(ialloc_test_orlov_flex_bg_and_fallback), + KUNIT_CASE(ialloc_test_find_group_other_non_flex), + KUNIT_CASE(ialloc_test_find_group_other_flex_bg), + KUNIT_CASE(ialloc_test_recently_deleted), + KUNIT_CASE(ialloc_test_find_inode_bit), + KUNIT_CASE(ialloc_test_mark_inode_used_uninit), + KUNIT_CASE(ialloc_test_mark_inode_used_errors), + KUNIT_CASE(ialloc_test_xattr_credits_for_new_inode), + KUNIT_CASE(ialloc_test_new_inode_types_and_flags), + KUNIT_CASE(ialloc_test_new_inode_ownership_and_projid), + KUNIT_CASE(ialloc_test_new_inode_goal_uninit_and_corrupt_skip), + KUNIT_CASE(ialloc_test_new_inode_errors), + KUNIT_CASE(ialloc_test_orphan_get), + KUNIT_CASE(ialloc_test_count_free_inodes_and_dirs), + KUNIT_CASE(ialloc_test_init_inode_table), + {} +}; + +static struct kunit_suite ialloc_test_suite = { + .name = "ext4_ialloc_test", + .init = ialloc_test_init, + .test_cases = ialloc_test_cases, +}; + +kunit_test_suites(&ialloc_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 inode allocation and deallocation"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c index e4c75c56fc1705..3f24063d50e80c 100644 --- a/fs/ext4/ialloc.c +++ b/fs/ext4/ialloc.c @@ -66,6 +66,7 @@ void ext4_mark_bitmap_end(int start_bit, int end_bit, char *bitmap) if (i < end_bit) memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mark_bitmap_end); void ext4_end_bitmap_read(struct bio *bio) { @@ -78,6 +79,7 @@ void ext4_end_bitmap_read(struct bio *bio) } unlock_buffer(bh); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_end_bitmap_read); static int ext4_validate_inode_bitmap(struct super_block *sb, struct ext4_group_desc *desc, @@ -144,7 +146,7 @@ ext4_read_inode_bitmap(struct super_block *sb, ext4_group_t block_group) EXT4_GROUP_INFO_IBITMAP_CORRUPT); return ERR_PTR(-EFSCORRUPTED); } - bh = sb_getblk(sb, bitmap_blk); + bh = ext4_sb_getblk(sb, bitmap_blk); if (unlikely(!bh)) { ext4_warning(sb, "Cannot read inode bitmap - " "block_group = %u, inode_bitmap = %llu", @@ -757,7 +759,7 @@ static int recently_deleted(struct super_block *sb, ext4_group_t group, int ino) ino >= EXT4_INODES_PER_GROUP(sb) - ext4_itable_unused_count(sb, gdp))) return 0; - bh = sb_find_get_block(sb, ext4_inode_table(sb, gdp) + + bh = ext4_sb_find_get_block(sb, ext4_inode_table(sb, gdp) + (ino / inodes_per_block)); if (!bh || !buffer_uptodate(bh)) /* @@ -937,6 +939,7 @@ int ext4_mark_inode_used(struct super_block *sb, int ino) brelse(inode_bitmap_bh); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mark_inode_used); static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode, bool encrypt) @@ -1443,6 +1446,7 @@ struct inode *__ext4_new_inode(const struct mnt_idmap *idmap, brelse(inode_bitmap_bh); return ERR_PTR(err); } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_new_inode); /* Verify that we are loading a valid orphan from disk */ struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino) @@ -1516,6 +1520,7 @@ struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino) brelse(bitmap_bh); return ERR_PTR(err); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_get); unsigned long ext4_count_free_inodes(struct super_block *sb) { @@ -1566,6 +1571,7 @@ unsigned long ext4_count_free_inodes(struct super_block *sb) return desc_count; #endif } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_count_free_inodes); /* Called at mount-time, super-block is locked */ unsigned long ext4_count_dirs(struct super_block * sb) @@ -1581,6 +1587,26 @@ unsigned long ext4_count_dirs(struct super_block * sb) } return count; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_count_dirs); + +int ext4_itable_zeroout(struct super_block *sb, ext4_fsblk_t blk, int num, + int barrier) +{ + int ret; + + KUNIT_STATIC_STUB_REDIRECT(ext4_itable_zeroout, sb, blk, num, barrier); + + ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS); + if (ret < 0) + return ret; + if (barrier) { + ret = blkdev_issue_flush(sb->s_bdev); + if (ret) + return ret; + } + return 0; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_itable_zeroout); /* * Zeroes not yet zeroed inode table - just write zeroes through the whole @@ -1677,14 +1703,9 @@ int ext4_init_inode_table(struct super_block *sb, ext4_group_t group, ext4_debug("going to zero out inode table in group %d\n", group); - ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS); - if (ret < 0) + ret = ext4_itable_zeroout(sb, blk, num, barrier); + if (ret) goto err_out; - if (barrier) { - ret = blkdev_issue_flush(sb->s_bdev); - if (ret) - goto err_out; - } skip_zeroout: ext4_lock_group(sb, group); @@ -1703,8 +1724,58 @@ int ext4_init_inode_table(struct super_block *sb, ext4_group_t group, out: return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_inode_table); #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) -EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_new_inode); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mark_inode_used); +int ext4_validate_inode_bitmap_test(struct super_block *sb, + struct ext4_group_desc *desc, + ext4_group_t block_group, + struct buffer_head *bh) +{ + return ext4_validate_inode_bitmap(sb, desc, block_group, bh); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_validate_inode_bitmap_test); + +struct buffer_head *ext4_read_inode_bitmap_test(struct super_block *sb, + ext4_group_t block_group) +{ + return ext4_read_inode_bitmap(sb, block_group); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_inode_bitmap_test); + +int ext4_find_group_orlov_test(struct super_block *sb, struct inode *parent, + ext4_group_t *group, umode_t mode, + const struct qstr *qstr) +{ + return find_group_orlov(sb, parent, group, mode, qstr); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_group_orlov_test); + +int ext4_find_group_other_test(struct super_block *sb, struct inode *parent, + ext4_group_t *group, umode_t mode) +{ + return find_group_other(sb, parent, group, mode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_group_other_test); + +int ext4_recently_deleted_test(struct super_block *sb, ext4_group_t group, + int ino) +{ + return recently_deleted(sb, group, ino); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_recently_deleted_test); + +int ext4_find_inode_bit_test(struct super_block *sb, ext4_group_t group, + struct buffer_head *bitmap, unsigned long *ino) +{ + return find_inode_bit(sb, group, bitmap, ino); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_inode_bit_test); + +int ext4_xattr_credits_for_new_inode_test(struct inode *dir, mode_t mode, + bool encrypt) +{ + return ext4_xattr_credits_for_new_inode(dir, mode, encrypt); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_credits_for_new_inode_test); #endif diff --git a/fs/ext4/super.c b/fs/ext4/super.c index 47da1e456d6d32..0768ba540637c0 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -212,6 +212,9 @@ EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_bh_nowait); int ext4_read_bh(struct buffer_head *bh, blk_opf_t op_flags, bio_end_io_t end_io, bool simu_fail) { + KUNIT_STATIC_STUB_REDIRECT(ext4_read_bh, bh, op_flags, + end_io, simu_fail); + BUG_ON(!buffer_locked(bh)); if (ext4_buffer_uptodate(bh)) { @@ -226,6 +229,7 @@ int ext4_read_bh(struct buffer_head *bh, blk_opf_t op_flags, return 0; return -EIO; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_bh); int ext4_read_bh_lock(struct buffer_head *bh, blk_opf_t op_flags, bool wait) { @@ -359,6 +363,7 @@ ext4_fsblk_t ext4_block_bitmap(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_bitmap); ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb, struct ext4_group_desc *bg) @@ -367,6 +372,7 @@ ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_bitmap); ext4_fsblk_t ext4_inode_table(struct super_block *sb, struct ext4_group_desc *bg) @@ -375,6 +381,7 @@ ext4_fsblk_t ext4_inode_table(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_table); __u32 ext4_free_group_clusters(struct super_block *sb, struct ext4_group_desc *bg) @@ -392,6 +399,7 @@ __u32 ext4_free_inodes_count(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(READ_ONCE(bg->bg_free_inodes_count_hi)) << 16 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_inodes_count); __u32 ext4_used_dirs_count(struct super_block *sb, struct ext4_group_desc *bg) @@ -400,6 +408,7 @@ __u32 ext4_used_dirs_count(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_used_dirs_count); __u32 ext4_itable_unused_count(struct super_block *sb, struct ext4_group_desc *bg) @@ -408,6 +417,7 @@ __u32 ext4_itable_unused_count(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_itable_unused_count); void ext4_block_bitmap_set(struct super_block *sb, struct ext4_group_desc *bg, ext4_fsblk_t blk) @@ -416,6 +426,7 @@ void ext4_block_bitmap_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_bitmap_set); void ext4_inode_bitmap_set(struct super_block *sb, struct ext4_group_desc *bg, ext4_fsblk_t blk) @@ -451,6 +462,7 @@ void ext4_free_inodes_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) WRITE_ONCE(bg->bg_free_inodes_count_hi, cpu_to_le16(count >> 16)); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_inodes_set); void ext4_used_dirs_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) @@ -459,6 +471,7 @@ void ext4_used_dirs_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_used_dirs_set); void ext4_itable_unused_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) @@ -467,6 +480,7 @@ void ext4_itable_unused_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_itable_unused_hi = cpu_to_le16(count >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_itable_unused_set); static void __ext4_update_tstamp(__le32 *lo, __u8 *hi, time64_t now) { @@ -1165,6 +1179,7 @@ void ext4_mark_group_bitmap_corrupted(struct super_block *sb, } } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mark_group_bitmap_corrupted); void ext4_update_dynamic_rev(struct super_block *sb) { @@ -3376,6 +3391,7 @@ int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group, return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_group_desc_csum_verify); void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group, struct ext4_group_desc *gdp) @@ -3384,6 +3400,7 @@ void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group, return; gdp->bg_checksum = ext4_group_desc_csum(sb, block_group, gdp); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_group_desc_csum_set); /* Called at mount-time, super-block is locked */ static int ext4_check_descriptors(struct super_block *sb, diff --git a/fs/ext4/xattr_security.c b/fs/ext4/xattr_security.c index af5b8a93fed13a..c3919643d64f27 100644 --- a/fs/ext4/xattr_security.c +++ b/fs/ext4/xattr_security.c @@ -4,6 +4,7 @@ * Handler for storing security labels as extended attributes. */ +#include #include #include #include @@ -55,9 +56,12 @@ int ext4_init_security(handle_t *handle, struct inode *inode, struct inode *dir, const struct qstr *qstr) { + KUNIT_STATIC_STUB_REDIRECT(ext4_init_security, + handle, inode, dir, qstr); return security_inode_init_security(inode, dir, qstr, &ext4_initxattrs, handle); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_security); const struct xattr_handler ext4_xattr_security_handler = { .prefix = XATTR_SECURITY_PREFIX, From 0dad7bef55f9b22fb71d9b9138a7a3562dee6a55 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Fri, 6 Nov 2026 14:04:38 +0000 Subject: [PATCH 1562/2102] ext4: add KUnit tests for fs/ext4/balloc.c Add the ext4_balloc_test KUnit test suite in fs/ext4/balloc-test.c (29 test cases, 43 subtests total) to comprehensively exercise block bitmap management, group descriptor and overhead calculations, cluster pool reservation, allocation retry policy, metadata block allocation, and goal block selection in fs/ext4/balloc.c using an in-memory VFS superblock, mock block device, and deterministic block pool without requiring a mounted block device: - Block-to-group and cluster-offset mapping (ext4_get_group_number and ext4_get_group_no_and_offset) across 1K and 4K block sizes, standard shift-based vs. non-standard do_div group geometries, bigalloc multi-block clusters, s_first_data_block offsets, >32-bit physical block numbers, and optional NULL output pointers. - Backup superblock placement (ext4_bg_has_super) across dense filesystems, sparse_super powers of 3, 5, and 7, and sparse_super2 explicit s_backup_bgs configurations. - Group descriptor table and base metadata block counts (ext4_bg_num_gdb and ext4_num_base_meta_blocks) across traditional GDT layouts with s_reserved_gdt_blocks and hybrid meta_bg filesystems spanning pre-s_first_meta_bg and meta_bg descriptor groups. - Group overhead and post-init free cluster accounting (ext4_free_clusters_after_init, ext4_num_overhead_clusters, and num_clusters_in_group) across standard groups, partial final groups, external flex_bg metadata, spanning inode tables, and bigalloc shared-cluster layouts. - Group descriptor and group info lookup (ext4_get_group_desc and ext4_get_group_info) across multi-block descriptor tables, bounds checks, missing descriptor buffers, and NULL RCU slice guards. - Block bitmap validation, reading, prefetching, and lazy initialization (ext4_read_block_bitmap_nowait, ext4_wait_block_bitmap, and ext4_read_block_bitmap), covering CRC32C verification, in-group and out-of-group metadata bit validation with and without flex_bg, bitmap tail padding checks, EXT4_FC_REPLAY and buffer_verified short-circuits, cold disk reads vs. cached buffer promotions, REQ_RAHEAD locked-buffer prefetching, EXT4_BG_BLOCK_UNINIT lazy bitmap initialization (CRC32C, legacy CRC16 GDT_CSUM, and unchecksummed fallback), group 0 and oversized base-metadata corruption guards, and simulated getblk / I/O errors. - Free cluster reservation and pool accounting (ext4_claim_free_clusters and ext4_has_free_clusters) across above-watermark fast paths, unprivileged limits, bigalloc r_blocks scaling, root-reserved pool access via s_resuid, non-root s_resgid supplementary group membership, EXT4_MB_USE_ROOT_BLOCKS, and CAP_SYS_RESOURCE, plus EXT4_MB_USE_RESERVED internal pool access. - Allocation retry policy (ext4_should_retry_alloc) across non-journaled mounts, pending mballoc free retries up to the 3-attempt limit with s_sra_exceeded_retry_limit accounting, free-space rechecks, and s_discard_work flushing under s_retry_alloc_pending. - Metadata block allocation (ext4_new_meta_blocks), free cluster summation (ext4_count_free_clusters across corrupt bitmaps, 64-bit high free-cluster counts, and unloaded descriptor blocks), and inode goal block selection (ext4_inode_to_goal_block across flex_bg directory vs. regular file placement, delalloc, and nodelalloc PID colouring). Route the block bitmap buffer lookup in ext4_read_block_bitmap_nowait() through ext4_sb_getblk() so KUnit tests can intercept buffer-cache lookups via its existing static stub hook, and export the remaining non-static balloc.c entry points with EXPORT_SYMBOL_FOR_EXT4_TEST. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 3 +- fs/ext4/balloc-test.c | 2400 +++++++++++++++++++++++++++++++++++++++++ fs/ext4/balloc.c | 11 +- 3 files changed, 2412 insertions(+), 2 deletions(-) create mode 100644 fs/ext4/balloc-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 72198aff5b4516..7d0ae7fd444868 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -18,7 +18,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ extents_status-test.o xattr-test.o \ namei-test.o inline-test.o \ - fast_commit-test.o ialloc-test.o + fast_commit-test.o ialloc-test.o \ + balloc-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/balloc-test.c b/fs/ext4/balloc-test.c new file mode 100644 index 00000000000000..b15d50907324f3 --- /dev/null +++ b/fs/ext4/balloc-test.c @@ -0,0 +1,2400 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/balloc.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "mballoc.h" + +/* + * Default multi-group mock filesystem geometry: + * - 4 active block groups (capacity up to 32 groups across 2 GDT blocks) + * - 1024-byte blocks (8192 bits per bitmap block, 16 64-byte GDs per block) + * - s_first_data_block = 1, 1024 blocks (clusters) per group (total 4097) + * - 64 inodes per group, 16 inode table blocks per group + * - sparse_super + metadata_csum + 64bit enabled, s_gdb_count = 1: + * - Groups 0, 1, 3 have super + 1 gdb (2 base blocks) + bbitmap + ibitmap + + * 16 itable blocks = 20 overhead clusters -> 1004 free clusters. + * - Group 2 has 0 base blocks + bbitmap + ibitmap + 16 itable blocks = + * 18 overhead clusters -> 1006 free clusters. + */ +#define BALLOC_TEST_NGROUPS 4U +#define BALLOC_TEST_MAX_GROUPS 32U +#define BALLOC_TEST_GDESC_BLKS 2U +#define BALLOC_TEST_BLK_SIZE 1024U +#define BALLOC_TEST_BLK_BITS 10U +#define BALLOC_TEST_BLOCKS_PER_GRP 1024U +#define BALLOC_TEST_FIRST_DATA_BLK 1U +#define BALLOC_TEST_TOTAL_BLKS (BALLOC_TEST_FIRST_DATA_BLK + \ + BALLOC_TEST_NGROUPS * \ + BALLOC_TEST_BLOCKS_PER_GRP) +#define BALLOC_TEST_INODE_SIZE 256U +#define BALLOC_TEST_INODES_PER_GRP 64U +#define BALLOC_TEST_ITB_PER_GRP 16U +#define BALLOC_TEST_CSUM_SEED 0x5a3c91e7U +#define BALLOC_TEST_GDESC_BLK0 2ULL +#define BALLOC_TEST_POOL_SIZE 16U + +struct balloc_test_blk { + bool in_use; + ext4_fsblk_t blocknr; + struct buffer_head bh; + char cache_buf[BALLOC_TEST_BLK_SIZE] __aligned(8); + char disk_buf[BALLOC_TEST_BLK_SIZE] __aligned(8); +}; + +struct balloc_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + + struct ext4_group_desc gdps[BALLOC_TEST_MAX_GROUPS] __aligned(8); + struct buffer_head gdesc_bh[BALLOC_TEST_GDESC_BLKS]; + struct buffer_head *gdesc_bh_ptrs[BALLOC_TEST_GDESC_BLKS]; + + struct ext4_group_info *grp_infos[BALLOC_TEST_MAX_GROUPS]; + struct ext4_group_info *grp_info_slice0[16]; + struct ext4_group_info *grp_info_slice1[16]; + struct ext4_group_info **grp_info_slices[BALLOC_TEST_GDESC_BLKS]; + + struct inode *test_inode; + journal_t journal; + + struct balloc_test_blk pool[BALLOC_TEST_POOL_SIZE]; + + bool fcc_inited; + bool dcc_inited; + bool fic_inited; + bool sra_inited; + + /* Credential override tracking for deterministic cleanup */ + const struct cred *saved_cred; + struct cred *override_cred; + + /* Discard work tracking */ + unsigned int discard_work_runs; + int discard_saw_retry_pending; + s64 discard_release_clusters; + bool discard_wait_retry_pending; + + /* Stub fault injection and call capture */ + bool fail_getblk; + bool fail_read_eio; + unsigned int read_nowait_calls; + blk_opf_t last_read_op_flags; + + unsigned int mb_new_blocks_calls; + struct ext4_allocation_request last_ar; + ext4_fsblk_t mock_alloc_blk; + unsigned int mock_alloc_len; + int mock_alloc_err; +}; + +static inline ext4_fsblk_t balloc_test_group_start(ext4_group_t g) +{ + return BALLOC_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * BALLOC_TEST_BLOCKS_PER_GRP; +} + +static inline unsigned int balloc_test_default_base_blks(ext4_group_t g) +{ + return (g == 2) ? 0U : 2U; +} + +static inline ext4_fsblk_t balloc_test_bbitmap_blk(ext4_group_t g) +{ + return balloc_test_group_start(g) + balloc_test_default_base_blks(g); +} + +static inline ext4_fsblk_t balloc_test_ibitmap_blk(ext4_group_t g) +{ + return balloc_test_bbitmap_blk(g) + 1; +} + +static inline ext4_fsblk_t balloc_test_itable_blk(ext4_group_t g) +{ + return balloc_test_bbitmap_blk(g) + 2; +} + +static inline void clear_bitmap_uptodate(struct buffer_head *bh) +{ + clear_bit(BH_BITMAP_UPTODATE, &bh->b_state); +} + +static struct inode *balloc_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_orphan); + inode_init_once(&ei->vfs_inode); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); +#ifdef CONFIG_QUOTA + memset(&ei->i_dquot, 0, sizeof(ei->i_dquot)); +#endif + return &ei->vfs_inode; +} + +static void balloc_test_free_inode_mem(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **balloc_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *balloc_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations balloc_test_qops = { + .get_reserved_space = balloc_test_get_reserved_space, +}; +#endif + +static const struct super_operations balloc_test_sops = { + .alloc_inode = balloc_test_alloc_inode, + .free_inode = balloc_test_free_inode_mem, + .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = balloc_test_get_dquots, +#endif +}; + +static int balloc_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type balloc_test_fs_type = { + .name = "ext4_balloc_kunit", + .init_fs_context = balloc_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static struct balloc_test_blk *balloc_test_find_blk(struct balloc_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + unsigned int i; + + for (i = 0; i < BALLOC_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && ctx->pool[i].blocknr == blocknr) + return &ctx->pool[i]; + } + return NULL; +} + +static struct balloc_test_blk * +balloc_test_find_blk_by_bh(struct balloc_test_ctx *ctx, struct buffer_head *bh) +{ + unsigned int i; + + for (i = 0; i < BALLOC_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && &ctx->pool[i].bh == bh) + return &ctx->pool[i]; + } + return NULL; +} + +static struct balloc_test_blk * +balloc_test_setup_blk(struct balloc_test_ctx *ctx, ext4_fsblk_t blocknr, + bool uptodate) +{ + struct balloc_test_blk *slot = balloc_test_find_blk(ctx, blocknr); + unsigned int i; + + if (!slot) { + for (i = 0; i < BALLOC_TEST_POOL_SIZE; i++) { + if (!ctx->pool[i].in_use) { + slot = &ctx->pool[i]; + break; + } + } + } + if (!slot) + return NULL; + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->blocknr = blocknr; + slot->bh.b_bdev = &ctx->bdev; + slot->bh.b_blocknr = blocknr; + slot->bh.b_size = BALLOC_TEST_BLK_SIZE; + slot->bh.b_data = slot->cache_buf; + atomic_set(&slot->bh.b_count, 1); + if (uptodate) + set_buffer_uptodate(&slot->bh); + return slot; +} + +static void balloc_test_sync_bbitmap_csum(struct balloc_test_ctx *ctx, + ext4_group_t g, bool sync_disk) +{ + struct ext4_group_desc *gdp = &ctx->gdps[g]; + struct balloc_test_blk *slot; + + slot = balloc_test_find_blk(ctx, ext4_block_bitmap(ctx->sb, gdp)); + if (slot) { + ext4_block_bitmap_csum_set(ctx->sb, gdp, &slot->bh); + if (sync_disk) + memcpy(slot->disk_buf, slot->cache_buf, + BALLOC_TEST_BLK_SIZE); + } + ext4_group_desc_csum_set(ctx->sb, g, gdp); +} + +static void balloc_test_discard_work_fn(struct work_struct *work) +{ + struct ext4_sb_info *sbi = + container_of(work, struct ext4_sb_info, s_discard_work); + struct balloc_test_ctx *ctx = + container_of(sbi, struct balloc_test_ctx, sbi); + + if (ctx->discard_wait_retry_pending) { + ktime_t deadline = ktime_add_ms(ktime_get(), 500); + + while (!atomic_read(&sbi->s_retry_alloc_pending) && + ktime_before(ktime_get(), deadline)) + usleep_range(100, 500); + } + + ctx->discard_work_runs++; + ctx->discard_saw_retry_pending = atomic_read(&sbi->s_retry_alloc_pending); + if (ctx->discard_release_clusters) + percpu_counter_add(&sbi->s_freeclusters_counter, + ctx->discard_release_clusters); +} + +static void balloc_test_restore_creds(struct balloc_test_ctx *ctx) +{ + if (ctx->saved_cred) { + revert_creds(ctx->saved_cred); + ctx->saved_cred = NULL; + } + if (ctx->override_cred) { + put_cred(ctx->override_cred); + ctx->override_cred = NULL; + } +} + +static void balloc_test_override_creds(struct kunit *test, + struct balloc_test_ctx *ctx, + uid_t uid, gid_t gid, bool cap_sys_res, + int supp_gid) +{ + struct cred *cred; + + balloc_test_restore_creds(ctx); + + cred = prepare_creds(); + KUNIT_ASSERT_NOT_NULL(test, cred); + ctx->override_cred = cred; + + cred->uid = KUIDT_INIT(uid); + cred->euid = KUIDT_INIT(uid); + cred->suid = KUIDT_INIT(uid); + cred->fsuid = KUIDT_INIT(uid); + cred->gid = KGIDT_INIT(gid); + cred->egid = KGIDT_INIT(gid); + cred->sgid = KGIDT_INIT(gid); + cred->fsgid = KGIDT_INIT(gid); + cap_clear(cred->cap_effective); + cap_clear(cred->cap_permitted); + cap_clear(cred->cap_inheritable); + cap_clear(cred->cap_ambient); + if (cap_sys_res) { + cap_raise(cred->cap_permitted, CAP_SYS_RESOURCE); + cap_raise(cred->cap_effective, CAP_SYS_RESOURCE); + } +#ifdef CONFIG_MULTIUSER + { + struct group_info *gi = groups_alloc(supp_gid >= 0 ? 1 : 0); + + KUNIT_ASSERT_NOT_NULL(test, gi); + if (supp_gid >= 0) { + gi->gid[0] = KGIDT_INIT((gid_t)supp_gid); + groups_sort(gi); + } + set_groups(cred, gi); + put_group_info(gi); + } +#endif + ctx->saved_cred = override_creds(cred); +} + +/* --- Static Stubs --- */ + +static struct buffer_head *balloc_test_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct balloc_test_ctx *ctx = test ? test->priv : NULL; + struct balloc_test_blk *slot; + + if (!ctx || ctx->fail_getblk) + return NULL; + slot = balloc_test_find_blk(ctx, block); + if (!slot) + return NULL; + get_bh(&slot->bh); + return &slot->bh; +} + +static void balloc_test_read_bh_nowait_stub(struct buffer_head *bh, + blk_opf_t op_flags, + bio_end_io_t end_io, + bool simu_fail) +{ + struct kunit *test = kunit_get_current_test(); + struct balloc_test_ctx *ctx = test ? test->priv : NULL; + struct balloc_test_blk *slot; + bool fail; + + if (!ctx) { + unlock_buffer(bh); + return; + } + ctx->read_nowait_calls++; + ctx->last_read_op_flags = op_flags; + + if (simu_fail) { + clear_buffer_uptodate(bh); + unlock_buffer(bh); + return; + } + + clear_buffer_verified(bh); + slot = balloc_test_find_blk_by_bh(ctx, bh); + fail = ctx->fail_read_eio || !slot; + if (!fail) + memcpy(bh->b_data, slot->disk_buf, bh->b_size); + + if (end_io) { + struct bio *bio = bio_alloc(NULL, 0, REQ_OP_READ, GFP_KERNEL); + + if (bio) { + bio->bi_private = bh; + bio->bi_status = fail ? BLK_STS_IOERR : BLK_STS_OK; + end_io(bio); + return; + } + } + + if (fail) { + clear_buffer_uptodate(bh); + } else { + set_buffer_uptodate(bh); + set_bitmap_uptodate(bh); + } + unlock_buffer(bh); +} + +static ext4_fsblk_t +balloc_test_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, int *errp) +{ + struct kunit *test = kunit_get_current_test(); + struct balloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) { + *errp = -EIO; + return 0; + } + ctx->mb_new_blocks_calls++; + ctx->last_ar = *ar; + *errp = ctx->mock_alloc_err; + if (ctx->mock_alloc_err) + return 0; + if (ctx->mock_alloc_len) + ar->len = ctx->mock_alloc_len; + return ctx->mock_alloc_blk; +} + +/* --- Fixture Setup & Teardown --- */ + +static void balloc_test_cleanup(struct balloc_test_ctx *ctx) +{ + unsigned int i; + + balloc_test_restore_creds(ctx); + + for (i = 0; i < BALLOC_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && buffer_locked(&ctx->pool[i].bh)) + unlock_buffer(&ctx->pool[i].bh); + } + + cancel_work_sync(&ctx->sbi.s_discard_work); + ctx->sbi.s_journal = NULL; + + if (ctx->test_inode) { + spin_lock(&ctx->test_inode->i_lock); + inode_state_clear(ctx->test_inode, I_DIRTY_ALL); + spin_unlock(&ctx->test_inode->i_lock); + iput(ctx->test_inode); + ctx->test_inode = NULL; + } + + if (ctx->sb) { + deactivate_super(ctx->sb); + rcu_barrier(); + ctx->sb = NULL; + } + + if (ctx->sra_inited) + percpu_counter_destroy(&ctx->sbi.s_sra_exceeded_retry_limit); + if (ctx->fic_inited) + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + if (ctx->dcc_inited) + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + if (ctx->fcc_inited) + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(balloc_test_cleanup_action, balloc_test_cleanup, + struct balloc_test_ctx *); + +static int balloc_test_init(struct kunit *test) +{ + struct balloc_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + ext4_group_t g; + s64 total_free_clusters = 0; + s64 total_free_inodes = 0; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + for (g = 0; g < BALLOC_TEST_MAX_GROUPS; g++) { + ctx->grp_infos[g] = kunit_kzalloc(test, + sizeof(*ctx->grp_infos[g]), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->grp_infos[g]); + } + + INIT_WORK(&ctx->sbi.s_discard_work, balloc_test_discard_work_fn); + rwlock_init(&ctx->journal.j_state_lock); + + err = kunit_add_action_or_reset(test, balloc_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + fc = fs_context_for_mount(&balloc_test_fs_type, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fc)); + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + KUNIT_ASSERT_FALSE(test, IS_ERR(sb)); + + sbi = &ctx->sbi; + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &balloc_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &balloc_test_qops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = BALLOC_TEST_BLK_SIZE; + sb->s_blocksize_bits = BALLOC_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + strscpy(sb->s_id, "ext4_balloc_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = BALLOC_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + root_inode = new_inode(sb); + if (!root_inode) { + deactivate_locked_super(sb); + rcu_barrier(); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc root_inode"); + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + deactivate_locked_super(sb); + rcu_barrier(); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc s_root"); + } + + up_write(&sb->s_umount); + ctx->sb = sb; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(BALLOC_TEST_FIRST_DATA_BLK); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_inodes_count = cpu_to_le32(BALLOC_TEST_NGROUPS * + BALLOC_TEST_INODES_PER_GRP); + ctx->es.s_inodes_per_group = cpu_to_le32(BALLOC_TEST_INODES_PER_GRP); + ctx->es.s_blocks_per_group = cpu_to_le32(BALLOC_TEST_BLOCKS_PER_GRP); + ctx->es.s_clusters_per_group = cpu_to_le32(BALLOC_TEST_BLOCKS_PER_GRP); + ctx->es.s_inode_size = cpu_to_le16(BALLOC_TEST_INODE_SIZE); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_blocks_count_set(&ctx->es, BALLOC_TEST_TOTAL_BLKS); + + ext4_set_feature_sparse_super(sb); + ext4_set_feature_extents(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + for (g = 0; g < BALLOC_TEST_GDESC_BLKS; g++) { + ctx->gdesc_bh[g].b_data = (char *)&ctx->gdps[g * 16]; + ctx->gdesc_bh[g].b_size = BALLOC_TEST_BLK_SIZE; + ctx->gdesc_bh[g].b_blocknr = BALLOC_TEST_GDESC_BLK0 + g; + ctx->gdesc_bh[g].b_bdev = &ctx->bdev; + atomic_set(&ctx->gdesc_bh[g].b_count, 1); + set_buffer_uptodate(&ctx->gdesc_bh[g]); + ctx->gdesc_bh_ptrs[g] = &ctx->gdesc_bh[g]; + } + rcu_assign_pointer(sbi->s_group_desc, ctx->gdesc_bh_ptrs); + + sbi->s_inode_size = BALLOC_TEST_INODE_SIZE; + sbi->s_inodes_per_block = BALLOC_TEST_BLK_SIZE / BALLOC_TEST_INODE_SIZE; + sbi->s_inodes_per_group = BALLOC_TEST_INODES_PER_GRP; + sbi->s_itb_per_group = BALLOC_TEST_ITB_PER_GRP; + sbi->s_blocks_per_group = BALLOC_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = BALLOC_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = BALLOC_TEST_NGROUPS; + sbi->s_gdb_count = 1; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = BALLOC_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_csum_seed = BALLOC_TEST_CSUM_SEED; + sbi->s_resuid = make_kuid(&init_user_ns, EXT4_DEF_RESUID); + sbi->s_resgid = make_kgid(&init_user_ns, EXT4_DEF_RESGID); + + set_opt(sb, ERRORS_CONT); + set_opt(sb, DELALLOC); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + for (g = 0; g < BALLOC_TEST_MAX_GROUPS; g++) { + init_rwsem(&ctx->grp_infos[g]->alloc_sem); + ctx->grp_infos[g]->bb_state = 0; + if (g < 16) + ctx->grp_info_slice0[g] = ctx->grp_infos[g]; + else + ctx->grp_info_slice1[g - 16] = ctx->grp_infos[g]; + } + ctx->grp_info_slices[0] = ctx->grp_info_slice0; + ctx->grp_info_slices[1] = ctx->grp_info_slice1; + rcu_assign_pointer(sbi->s_group_info, ctx->grp_info_slices); + + for (g = 0; g < BALLOC_TEST_NGROUPS; g++) { + struct balloc_test_blk *bblk; + unsigned int overhead = balloc_test_default_base_blks(g) + + 2U + BALLOC_TEST_ITB_PER_GRP; + u32 free_clu = BALLOC_TEST_BLOCKS_PER_GRP - overhead; + unsigned int bit; + + ext4_block_bitmap_set(sb, &ctx->gdps[g], + balloc_test_bbitmap_blk(g)); + ext4_inode_bitmap_set(sb, &ctx->gdps[g], + balloc_test_ibitmap_blk(g)); + ext4_inode_table_set(sb, &ctx->gdps[g], + balloc_test_itable_blk(g)); + ext4_free_group_clusters_set(sb, &ctx->gdps[g], free_clu); + ext4_free_inodes_set(sb, &ctx->gdps[g], + BALLOC_TEST_INODES_PER_GRP); + ctx->grp_infos[g]->bb_free = free_clu; + + bblk = balloc_test_setup_blk(ctx, balloc_test_bbitmap_blk(g), + true); + KUNIT_ASSERT_NOT_NULL(test, bblk); + + for (bit = 0; bit < overhead; bit++) + ext4_set_bit(bit, bblk->cache_buf); + ext4_mark_bitmap_end(BALLOC_TEST_BLOCKS_PER_GRP, + BALLOC_TEST_BLK_SIZE * 8, + bblk->cache_buf); + set_bitmap_uptodate(&bblk->bh); + set_buffer_verified(&bblk->bh); + balloc_test_sync_bbitmap_csum(ctx, g, true); + + total_free_clusters += free_clu; + total_free_inodes += BALLOC_TEST_INODES_PER_GRP; + } + + err = percpu_counter_init(&sbi->s_freeclusters_counter, + total_free_clusters, GFP_KERNEL); + if (!err) + ctx->fcc_inited = true; + KUNIT_ASSERT_EQ(test, err, 0); + + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + if (!err) + ctx->dcc_inited = true; + KUNIT_ASSERT_EQ(test, err, 0); + + err = percpu_counter_init(&sbi->s_freeinodes_counter, + total_free_inodes, GFP_KERNEL); + if (!err) + ctx->fic_inited = true; + KUNIT_ASSERT_EQ(test, err, 0); + + err = percpu_counter_init(&sbi->s_sra_exceeded_retry_limit, 0, + GFP_KERNEL); + if (!err) + ctx->sra_inited = true; + KUNIT_ASSERT_EQ(test, err, 0); + + ctx->test_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, ctx->test_inode); + ctx->test_inode->i_ino = EXT4_FIRST_INO(sb); + ctx->test_inode->i_mode = S_IFREG | 0644; + ctx->test_inode->i_blkbits = BALLOC_TEST_BLK_BITS; + inode_set_bytes(ctx->test_inode, 0); + EXT4_I(ctx->test_inode)->i_block_group = 0; + + kunit_activate_static_stub(test, ext4_sb_getblk, + balloc_test_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_read_bh_nowait, + balloc_test_read_bh_nowait_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + balloc_test_mb_new_blocks_stub); + + return 0; +} + +/* ========================================================================= + * 1. Group Number & Offset Calculation + * ========================================================================= + */ + +struct group_offset_param { + const char *desc; + unsigned char blocksize_bits; + unsigned int cluster_bits; + u32 blocks_per_group; + u32 first_data_block; + bool std_group_size; + ext4_fsblk_t block; + ext4_group_t expected_group; + ext4_grpblk_t expected_offset; +}; + +static const struct group_offset_param group_offset_params[] = { + { + .desc = "std_1k_bg0_first_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 8192, + .first_data_block = 1, + .std_group_size = true, + .block = 1, + .expected_group = 0, + .expected_offset = 0, + }, + { + .desc = "std_1k_bg0_last_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 8192, + .first_data_block = 1, + .std_group_size = true, + .block = 8192, + .expected_group = 0, + .expected_offset = 8191, + }, + { + .desc = "std_1k_bg1_first_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 8192, + .first_data_block = 1, + .std_group_size = true, + .block = 8193, + .expected_group = 1, + .expected_offset = 0, + }, + { + .desc = "std_1k_bg3_interior_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 8192, + .first_data_block = 1, + .std_group_size = true, + .block = 25000, + .expected_group = 3, + .expected_offset = 423, + }, + { + .desc = "std_4k_bg0_last_block", + .blocksize_bits = 12, + .cluster_bits = 0, + .blocks_per_group = 32768, + .first_data_block = 0, + .std_group_size = true, + .block = 32767, + .expected_group = 0, + .expected_offset = 32767, + }, + { + .desc = "std_4k_bg1_first_block", + .blocksize_bits = 12, + .cluster_bits = 0, + .blocks_per_group = 32768, + .first_data_block = 0, + .std_group_size = true, + .block = 32768, + .expected_group = 1, + .expected_offset = 0, + }, + { + .desc = "std_4k_above_32bit_blocknr", + .blocksize_bits = 12, + .cluster_bits = 0, + .blocks_per_group = 32768, + .first_data_block = 0, + .std_group_size = true, + .block = 0x100008005ULL, + .expected_group = 131073, + .expected_offset = 5, + }, + { + .desc = "nonstd_bg0_last_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 1000, + .first_data_block = 1, + .std_group_size = false, + .block = 1000, + .expected_group = 0, + .expected_offset = 999, + }, + { + .desc = "nonstd_bg1_first_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 1000, + .first_data_block = 1, + .std_group_size = false, + .block = 1001, + .expected_group = 1, + .expected_offset = 0, + }, + { + .desc = "nonstd_bg2_interior_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 1000, + .first_data_block = 1, + .std_group_size = false, + .block = 2346, + .expected_group = 2, + .expected_offset = 345, + }, + { + .desc = "bigalloc_std_cluster_start", + .blocksize_bits = 12, + .cluster_bits = 3, + .blocks_per_group = 262144, + .first_data_block = 0, + .std_group_size = true, + .block = 16, + .expected_group = 0, + .expected_offset = 2, + }, + { + .desc = "bigalloc_std_cluster_end_same_offset", + .blocksize_bits = 12, + .cluster_bits = 3, + .blocks_per_group = 262144, + .first_data_block = 0, + .std_group_size = true, + .block = 23, + .expected_group = 0, + .expected_offset = 2, + }, + { + .desc = "bigalloc_std_next_cluster", + .blocksize_bits = 12, + .cluster_bits = 3, + .blocks_per_group = 262144, + .first_data_block = 0, + .std_group_size = true, + .block = 24, + .expected_group = 0, + .expected_offset = 3, + }, + { + .desc = "bigalloc_std_bg2_offset", + .blocksize_bits = 12, + .cluster_bits = 3, + .blocks_per_group = 262144, + .first_data_block = 0, + .std_group_size = true, + .block = 524303, + .expected_group = 2, + .expected_offset = 1, + }, + { + .desc = "bigalloc_nonstd_bg3_offset", + .blocksize_bits = 10, + .cluster_bits = 2, + .blocks_per_group = 600, + .first_data_block = 1, + .std_group_size = false, + .block = 1820, + .expected_group = 3, + .expected_offset = 4, + }, +}; + +static void group_offset_param_get_desc(const struct group_offset_param *p, + char *desc) +{ + strscpy(desc, p->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(group_offset, group_offset_params, + group_offset_param_get_desc); + +static void test_group_no_and_offset_matrix(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + const struct group_offset_param *p = test->param_value; + ext4_group_t grp = 0xdeadbeefU; + ext4_grpblk_t off = 0x7654321; + + sb->s_blocksize_bits = p->blocksize_bits; + sb->s_blocksize = 1UL << p->blocksize_bits; + sbi->s_cluster_bits = p->cluster_bits; + sbi->s_cluster_ratio = 1U << p->cluster_bits; + sbi->s_blocks_per_group = p->blocks_per_group; + sbi->s_clusters_per_group = p->blocks_per_group >> p->cluster_bits; + ctx->es.s_first_data_block = cpu_to_le32(p->first_data_block); + if (p->std_group_size) + set_opt2(sb, STD_GROUP_SIZE); + else + clear_opt2(sb, STD_GROUP_SIZE); + + KUNIT_EXPECT_EQ(test, ext4_get_group_number(sb, p->block), + p->expected_group); + + ext4_get_group_no_and_offset(sb, p->block, &grp, &off); + KUNIT_EXPECT_EQ(test, grp, p->expected_group); + KUNIT_EXPECT_EQ(test, off, p->expected_offset); +} + +static void test_group_no_and_offset_optional_out_ptrs(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + ext4_group_t grp = 999; + ext4_grpblk_t off = 999; + + /* Block 2060 = first_data_block (1) + 2 * 1024 + 11 */ + ext4_get_group_no_and_offset(sb, 2060, &grp, NULL); + KUNIT_EXPECT_EQ(test, grp, 2U); + + ext4_get_group_no_and_offset(sb, 2060, NULL, &off); + KUNIT_EXPECT_EQ(test, off, 11); + + /* Both output pointers NULL must be a safe no-op */ + ext4_get_group_no_and_offset(sb, 2060, NULL, NULL); +} + +/* ========================================================================= + * 2. Backup Superblock Placement (ext4_bg_has_super) + * ========================================================================= + */ + +static void test_bg_has_super_dense_all_groups(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + static const ext4_group_t groups[] = { 0, 1, 2, 3, 4, 6, 8, 15, 22 }; + unsigned int i; + + ext4_clear_feature_sparse_super(sb); + ext4_clear_feature_sparse_super2(sb); + + for (i = 0; i < ARRAY_SIZE(groups); i++) + KUNIT_EXPECT_EQ_MSG(test, ext4_bg_has_super(sb, groups[i]), 1, + "dense group %u should have super", + groups[i]); +} + +static void test_bg_has_super_sparse_super_powers(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + static const ext4_group_t with_super[] = { + 0, 1, 3, 9, 27, 81, 5, 25, 125, 7, 49, 343 + }; + static const ext4_group_t without_super[] = { + 2, 4, 6, 8, 10, 11, 15, 21, 35, 45, 63, 77 + }; + unsigned int i; + + ext4_set_feature_sparse_super(sb); + ext4_clear_feature_sparse_super2(sb); + + for (i = 0; i < ARRAY_SIZE(with_super); i++) + KUNIT_EXPECT_EQ_MSG(test, ext4_bg_has_super(sb, with_super[i]), + 1, "sparse_super group %u expected 1", + with_super[i]); + + for (i = 0; i < ARRAY_SIZE(without_super); i++) + KUNIT_EXPECT_EQ_MSG(test, + ext4_bg_has_super(sb, without_super[i]), 0, + "sparse_super group %u expected 0", + without_super[i]); +} + +static void test_bg_has_super_sparse_super2_explicit_backups(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + ext4_set_feature_sparse_super2(sb); + ctx->es.s_backup_bgs[0] = cpu_to_le32(6); + ctx->es.s_backup_bgs[1] = cpu_to_le32(42); + + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 0), 1); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 6), 1); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 42), 1); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 3), 0); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 5), 0); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 7), 0); + + /* Single backup group configured (s_backup_bgs[1] == 0) */ + ctx->es.s_backup_bgs[0] = cpu_to_le32(12); + ctx->es.s_backup_bgs[1] = cpu_to_le32(0); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 0), 1); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 12), 1); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 6), 0); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 42), 0); +} + +/* ========================================================================= + * 3. GDT & Base Metadata Blocks (ext4_bg_num_gdb, ext4_num_base_meta_blocks) + * ========================================================================= + */ + +static void test_bg_num_gdb_and_base_meta_non_metabg(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + ext4_clear_feature_meta_bg(sb); + ext4_set_feature_sparse_super(sb); + ctx->sbi.s_gdb_count = 4; + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(7); + + /* Groups with super: 1 super + 4 gdb + 7 reserved_gdt = 12 blocks */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 0), 4UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 0), 12U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 3), 4UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 3), 12U); + + /* Groups without super: 0 gdb and reserved_gdt is not present */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 2), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 2), 0U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 15), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 15), 0U); +} + +static void test_bg_num_gdb_and_base_meta_hybrid_metabg(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + /* + * s_desc_per_block = 16, s_first_meta_bg = 2: + * - Groups 0..31 (metagroups 0..1) use traditional GDT layout with + * s_first_meta_bg (2) GDT blocks + s_reserved_gdt_blocks (9) when + * backup super is present. + * - Groups >= 32 (metagroups >= 2) place 1 descriptor block in the + * 1st, 2nd, and last group of each 16-group metagroup, with no + * reserved GDT blocks. + */ + ext4_set_feature_meta_bg(sb); + ext4_set_feature_sparse_super(sb); + ctx->sbi.s_gdb_count = 5; + ctx->es.s_first_meta_bg = cpu_to_le32(2); + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(9); + + /* Pre-meta_bg groups with super: 1 + 2 + 9 = 12 */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 0), 2UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 0), 12U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 27), 2UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 27), 12U); + + /* Pre-meta_bg groups without super */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 2), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 2), 0U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 31), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 31), 0U); + + /* Metagroup 2 (groups 32..47): first=32, second=33, last=47 (no super) */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 32), 1UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 32), 1U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 33), 1UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 33), 1U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 47), 1UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 47), 1U); + + /* Interior meta_bg group with neither super nor meta gdb */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 34), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 34), 0U); + + /* Group 125 (5^3 in metagroup 112..127): super=1, meta_gdb=0 -> 1 */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 125), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 125), 1U); + + /* Group 49 (7^2, second of 48..63): super=1, meta_gdb=1 -> 2 */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 49), 1UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 49), 2U); +} + +/* ========================================================================= + * 4. Overhead & Free Clusters After Init (ext4_free_clusters_after_init) + * ========================================================================= + */ + +static void +test_free_clusters_after_init_standard_and_partial_last(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 0, &ctx->gdps[0]), + 1004U); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 1006U); + + /* Shrink total blocks so last group 3 has only 300 blocks (20 overhead) */ + ext4_blocks_count_set(&ctx->es, balloc_test_group_start(3) + 300); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 3, &ctx->gdps[3]), + 280U); + /* Non-last group 1 still uses full s_blocks_per_group (1024) */ + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 1, &ctx->gdps[1]), + 1004U); +} + +static void +test_free_clusters_after_init_external_and_spanning_meta(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + ext4_fsblk_t g2_start = balloc_test_group_start(2); + + /* + * Group 2 has 0 base metadata blocks. Relocate its bitmaps and inode + * table into group 0 -> 0 overhead clusters in group 2 -> 1024 free. + */ + ext4_block_bitmap_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 50); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 51); + ext4_inode_table_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 52); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 1024U); + + /* + * Inode table of 16 blocks starting 6 blocks before group 2 overlaps + * 10 blocks [g2_start .. g2_start + 9] inside group 2 -> 1014 free. + */ + ext4_inode_table_set(sb, &ctx->gdps[2], g2_start - 6); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 1014U); + + /* + * Inode table starting 5 blocks before end of group 2 overlaps 5 + * blocks [g2_end - 4 .. g2_end] inside group 2 -> 1019 free. + */ + ext4_inode_table_set(sb, &ctx->gdps[2], + g2_start + BALLOC_TEST_BLOCKS_PER_GRP - 5); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 1019U); +} + +static void +test_free_clusters_after_init_bigalloc_cluster_sharing(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + ext4_fsblk_t g1_start = balloc_test_group_start(1); + ext4_fsblk_t g2_start = balloc_test_group_start(2); + + /* 4 blocks per cluster -> 1024 / 4 = 256 clusters per full group */ + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + sbi->s_clusters_per_group = 256; + sbi->s_itb_per_group = 8; + + /* + * Case 1 (border overlap with base_clusters): + * Group 1 has 2 base blocks (offsets 0..1 -> base_clusters = 1, clu 0). + * Place 8-block itable at offsets 2..9 (clusters 0..2, overlapping + * border clu 0), bbitmap at offset 12 (clu 3), ibitmap at offset 16 + * (clu 4) -> 5 unique overhead clusters (0..4) -> 251 free clusters. + */ + ext4_inode_table_set(sb, &ctx->gdps[1], g1_start + 2); + ext4_block_bitmap_set(sb, &ctx->gdps[1], g1_start + 12); + ext4_inode_bitmap_set(sb, &ctx->gdps[1], g1_start + 16); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 1, &ctx->gdps[1]), + 251U); + + /* + * Case 2 (bitmaps inside base_clusters): + * Base blocks at offsets 0..1 (clu 0), bbitmap at offset 2 (clu 0), + * ibitmap at offset 3 (clu 0), 8-block itable at offsets 4..11 + * (clusters 1..2) -> 3 overhead clusters (0..2) -> 253 free clusters. + */ + ext4_block_bitmap_set(sb, &ctx->gdps[1], g1_start + 2); + ext4_inode_bitmap_set(sb, &ctx->gdps[1], g1_start + 3); + ext4_inode_table_set(sb, &ctx->gdps[1], g1_start + 4); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 1, &ctx->gdps[1]), + 253U); + + /* + * Case 3 (bbitmap and ibitmap sharing the same non-base cluster): + * Group 2 has 0 base clusters. bbitmap at offset 0 (clu 0), ibitmap at + * offset 1 (clu 0), 8-block itable at offsets 4..11 (clusters 1..2) -> + * 3 overhead clusters -> 253 free clusters. + */ + ext4_block_bitmap_set(sb, &ctx->gdps[2], g2_start + 0); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], g2_start + 1); + ext4_inode_table_set(sb, &ctx->gdps[2], g2_start + 4); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 253U); + + /* + * Case 4 (bitmaps sharing tail cluster of inode table): + * Group 2 with 6-block itable at offsets 0..5 (clusters 0..1), bbitmap + * at offset 6 (clu 1), ibitmap at offset 7 (clu 1) -> 2 overhead + * clusters (0..1) -> 254 free clusters. + */ + sbi->s_itb_per_group = 6; + ext4_inode_table_set(sb, &ctx->gdps[2], g2_start + 0); + ext4_block_bitmap_set(sb, &ctx->gdps[2], g2_start + 6); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], g2_start + 7); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 254U); + + /* + * Case 5 (partial last group rounding up blocks to clusters): + * Group 3 with 301 blocks -> EXT4_NUM_B2C(4, 301) = 76 clusters; + * external metadata -> 0 overhead in group 3 -> 76 free clusters. + */ + ext4_blocks_count_set(&ctx->es, balloc_test_group_start(3) + 301); + ext4_block_bitmap_set(sb, &ctx->gdps[3], balloc_test_group_start(0) + 40); + ext4_inode_bitmap_set(sb, &ctx->gdps[3], balloc_test_group_start(0) + 44); + ext4_inode_table_set(sb, &ctx->gdps[3], balloc_test_group_start(0) + 48); + /* Group 3 has 2 base blocks = 1 base cluster -> 76 - 1 = 75 free */ + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 3, &ctx->gdps[3]), + 75U); +} + +/* ========================================================================= + * 5. Group Descriptor & Group Info Lookup + * ========================================================================= + */ + +static void test_get_group_desc_lookup_and_bounds(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct buffer_head *bh = NULL; + struct ext4_group_desc *desc; + + /* Expand to 20 groups spanning gdesc_bh[0] (0..15) and gdesc_bh[1] (16..19) */ + ctx->sbi.s_groups_count = 20; + + desc = ext4_get_group_desc(sb, 0, &bh); + KUNIT_EXPECT_PTR_EQ(test, desc, &ctx->gdps[0]); + KUNIT_EXPECT_PTR_EQ(test, bh, &ctx->gdesc_bh[0]); + + desc = ext4_get_group_desc(sb, 15, &bh); + KUNIT_EXPECT_PTR_EQ(test, desc, &ctx->gdps[15]); + KUNIT_EXPECT_PTR_EQ(test, bh, &ctx->gdesc_bh[0]); + + desc = ext4_get_group_desc(sb, 16, &bh); + KUNIT_EXPECT_PTR_EQ(test, desc, &ctx->gdps[16]); + KUNIT_EXPECT_PTR_EQ(test, bh, &ctx->gdesc_bh[1]); + + desc = ext4_get_group_desc(sb, 19, NULL); + KUNIT_EXPECT_PTR_EQ(test, desc, &ctx->gdps[19]); + + /* Out-of-range block_group >= s_groups_count returns NULL */ + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + KUNIT_EXPECT_NULL(test, ext4_get_group_desc(sb, 20, &bh)); + KUNIT_EXPECT_TRUE(test, !!(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + + /* Missing group descriptor buffer_head slot returns NULL */ + ctx->gdesc_bh_ptrs[1] = NULL; + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + KUNIT_EXPECT_NULL(test, ext4_get_group_desc(sb, 16, &bh)); + KUNIT_EXPECT_TRUE(test, !!(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); +} + +static void test_get_group_info_lookup_and_null_guards(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + ctx->sbi.s_groups_count = 20; + + KUNIT_EXPECT_PTR_EQ(test, ext4_get_group_info(sb, 0), + ctx->grp_infos[0]); + KUNIT_EXPECT_PTR_EQ(test, ext4_get_group_info(sb, 15), + ctx->grp_infos[15]); + KUNIT_EXPECT_PTR_EQ(test, ext4_get_group_info(sb, 16), + ctx->grp_infos[16]); + KUNIT_EXPECT_PTR_EQ(test, ext4_get_group_info(sb, 19), + ctx->grp_infos[19]); + + /* Out-of-bounds group returns NULL */ + KUNIT_EXPECT_NULL(test, ext4_get_group_info(sb, 20)); + + /* NULL second-level slice returns NULL only for that slice */ + ctx->grp_info_slices[1] = NULL; + KUNIT_EXPECT_PTR_EQ(test, ext4_get_group_info(sb, 15), + ctx->grp_infos[15]); + KUNIT_EXPECT_NULL(test, ext4_get_group_info(sb, 16)); + + /* NULL s_group_info table returns NULL */ + rcu_assign_pointer(ctx->sbi.s_group_info, NULL); + KUNIT_EXPECT_NULL(test, ext4_get_group_info(sb, 0)); +} + +/* ========================================================================= + * 6. Block Bitmap Validation (CSUM, Metadata Self-Checks, Padding, Flags) + * ========================================================================= + */ + +static void test_read_block_bitmap_validates_csum(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + s64 free_before; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* 1. Unverified buffer with valid CRC32C verifies and sets BH_Verified */ + clear_buffer_verified(&slot->bh); + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[1])); + put_bh(bh); + +#ifdef CONFIG_EXT4_DEBUG + /* Simulated CRC failure triggers -EFSBADCRC and resets s_simulate_fail */ + clear_buffer_verified(&slot->bh); + ctx->sbi.s_simulate_fail = EXT4_SIM_BBITMAP_CRC; + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSBADCRC); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_simulate_fail, 0UL); + ctx->grp_infos[1]->bb_state = 0; + percpu_counter_add(&ctx->sbi.s_freeclusters_counter, + ctx->grp_infos[1]->bb_free); +#endif + + /* 2. Corrupting free-space bit without updating csum -> -EFSBADCRC */ + free_before = percpu_counter_sum(&ctx->sbi.s_freeclusters_counter); + clear_buffer_verified(&slot->bh); + slot->cache_buf[40] ^= 0x01; + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_TRUE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSBADCRC); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[1])); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_freeclusters_counter), + free_before - ctx->grp_infos[1]->bb_free); + + /* + * 3. Subsequent read on already-corrupt group returns -EFSCORRUPTED + * immediately without subtracting bb_free a second time. + */ + slot->cache_buf[40] ^= 0x01; + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_TRUE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_freeclusters_counter), + free_before - ctx->grp_infos[1]->bb_free); +} + +static void test_read_block_bitmap_validates_metadata_bits(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + static const unsigned int meta_bits[] = { + 0, /* block bitmap in group 2 */ + 1, /* inode bitmap in group 2 */ + 2, /* first inode table block in group 2 */ + 10, /* middle inode table block in group 2 */ + 17, /* last inode table block in group 2 */ + }; + unsigned int i; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* Clearing any in-group metadata bit (with valid CRC) -> -EFSCORRUPTED */ + for (i = 0; i < ARRAY_SIZE(meta_bits); i++) { + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_clear_bit(meta_bits[i], slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED, + "cleared bit %u should fail validation", + meta_bits[i]); + KUNIT_EXPECT_TRUE_MSG(test, + EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[2]), + "bit %u should mark BBITMAP_CORRUPT", + meta_bits[i]); + + ext4_set_bit(meta_bits[i], slot->cache_buf); + } + + /* Out-of-group block bitmap (< start and >= end) without FLEX_BG */ + { + struct balloc_test_blk *slot1, *slot3; + + slot1 = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + slot3 = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, slot1); + KUNIT_ASSERT_NOT_NULL(test, slot3); + + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot1->bh); + ext4_block_bitmap_set(sb, &ctx->gdps[2], + balloc_test_bbitmap_blk(1)); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot3->bh); + ext4_block_bitmap_set(sb, &ctx->gdps[2], + balloc_test_bbitmap_blk(3)); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + ext4_block_bitmap_set(sb, &ctx->gdps[2], + balloc_test_bbitmap_blk(2)); + balloc_test_sync_bbitmap_csum(ctx, 1, false); + balloc_test_sync_bbitmap_csum(ctx, 3, false); + } + + /* Out-of-group inode bitmap without FLEX_BG -> -EFSCORRUPTED */ + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 5); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], balloc_test_ibitmap_blk(2)); + + /* Inode table before start or past end of group without FLEX_BG */ + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_inode_table_set(sb, &ctx->gdps[2], balloc_test_group_start(1) + 50); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_inode_table_set(sb, &ctx->gdps[2], + balloc_test_group_start(2) + + BALLOC_TEST_BLOCKS_PER_GRP - 8); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + /* With FLEX_BG enabled, out-of-group metadata skips per-group bit check */ + ext4_set_feature_flex_bg(sb); + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 5); + ext4_inode_table_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 20); + ext4_clear_bit(1, slot->cache_buf); + ext4_clear_bit(2, slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + put_bh(bh); +} + +static void test_read_block_bitmap_validates_padding(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* 1. Zero bit at first padding bit (1024) -> -EFSCORRUPTED */ + clear_buffer_verified(&slot->bh); + ext4_clear_bit(1024, slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 3, false); + bh = ext4_read_block_bitmap(sb, 3); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[3])); + ext4_set_bit(1024, slot->cache_buf); + + /* 2. Zero bit at very last bit of bitmap block (8191) -> -EFSCORRUPTED */ + ctx->grp_infos[3]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_clear_bit(8191, slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 3, false); + bh = ext4_read_block_bitmap(sb, 3); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + ext4_set_bit(8191, slot->cache_buf); + + /* 3. Partial last group (300 blocks): unset bit 300 in padding fails */ + ctx->grp_infos[3]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_blocks_count_set(&ctx->es, balloc_test_group_start(3) + 300); + balloc_test_sync_bbitmap_csum(ctx, 3, false); + bh = ext4_read_block_bitmap(sb, 3); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + /* Setting padding bits 300..1023 makes the partial last group valid */ + ctx->grp_infos[3]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_mark_bitmap_end(300, BALLOC_TEST_BLK_SIZE * 8, slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 3, false); + bh = ext4_read_block_bitmap(sb, 3); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + put_bh(bh); + + /* 4. Full 8192-cluster group (bitmap_size == offset) has no padding */ + ctx->sbi.s_blocks_per_group = 8192; + ctx->sbi.s_clusters_per_group = 8192; + ctx->es.s_blocks_per_group = cpu_to_le32(8192); + ctx->es.s_clusters_per_group = cpu_to_le32(8192); + ext4_blocks_count_set(&ctx->es, 1 + 4 * 8192); + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(0)); + KUNIT_ASSERT_NOT_NULL(test, slot); + clear_buffer_verified(&slot->bh); + ext4_clear_bit(8191, slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 0, false); + + bh = ext4_read_block_bitmap(sb, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + put_bh(bh); +} + +static void test_read_block_bitmap_validation_short_circuits(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* + * 1. EXT4_FC_REPLAY skips csum and corrupt-flag checks without setting + * BH_Verified. + */ + clear_buffer_verified(&slot->bh); + slot->cache_buf[50] ^= 0xff; + set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT, + &ctx->grp_infos[1]->bb_state); + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_FALSE(test, buffer_verified(bh)); + put_bh(bh); + + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + slot->cache_buf[50] ^= 0xff; + + /* 2. Already buffer_verified(bh) short-circuits before checking grp */ + set_buffer_verified(&slot->bh); + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + put_bh(bh); + + /* 3. NULL ext4_group_info when !buffer_verified returns -EFSCORRUPTED */ + clear_buffer_verified(&slot->bh); + ctx->grp_infos[1]->bb_state = 0; + rcu_assign_pointer(ctx->sbi.s_group_info, NULL); + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); +} + +/* ========================================================================= + * 7. Block Bitmap Reading, Prefetching, and Lazy Initialization + * ========================================================================= + */ + +static void test_read_block_bitmap_disk_and_cache_paths(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* 1. Cold read from disk populates cache, runs end_io, and validates */ + memset(slot->cache_buf, 0, sizeof(slot->cache_buf)); + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + KUNIT_EXPECT_TRUE(test, ctx->last_read_op_flags == + (blk_opf_t)(REQ_META | REQ_PRIO)); + KUNIT_EXPECT_TRUE(test, buffer_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + KUNIT_EXPECT_FALSE(test, buffer_new(bh)); + put_bh(bh); + + /* 2. Warm read hits bitmap_uptodate(bh) without issuing I/O */ + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + put_bh(bh); + + /* + * 3. Initialized group with BH_Uptodate set and BH_BITMAP_UPTODATE + * clear promotes BH_BITMAP_UPTODATE and validates without disk I/O. + */ + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + put_bh(bh); +} + +static void test_read_block_bitmap_nowait_prefetch_locked(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + int ref_before; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* 1. Locked buffer with ignore_locked=true returns NULL without leaking ref */ + ref_before = atomic_read(&slot->bh.b_count); + lock_buffer(&slot->bh); + bh = ext4_read_block_bitmap_nowait(sb, 2, true); + unlock_buffer(&slot->bh); + + KUNIT_EXPECT_NULL(test, bh); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), ref_before); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 0U); + + /* 2. Uncached unlocked buffer with ignore_locked=true sets REQ_RAHEAD */ + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + + bh = ext4_read_block_bitmap_nowait(sb, 2, true); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + KUNIT_EXPECT_TRUE(test, ctx->last_read_op_flags == + (blk_opf_t)(REQ_META | REQ_PRIO | REQ_RAHEAD)); + KUNIT_EXPECT_EQ(test, ext4_wait_block_bitmap(sb, 2, bh), 0); + put_bh(bh); +} + +static void test_read_block_bitmap_uninit_group(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + unsigned int bit; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* + * Mark group 1 EXT4_BG_BLOCK_UNINIT and poison cache_buf with 0xa5. + * Lazy init must zero the bitmap, set metadata bits 0..19, leave + * data bits 20..1023 free, set padding bits 1024..8191, and skip I/O. + */ + memset(slot->cache_buf, 0xa5, sizeof(slot->cache_buf)); + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + ctx->gdps[1].bg_flags = cpu_to_le16(EXT4_BG_BLOCK_UNINIT); + ext4_group_desc_csum_set(sb, 1, &ctx->gdps[1]); + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 0U); + KUNIT_EXPECT_TRUE(test, buffer_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + + for (bit = 0; bit < 20; bit++) + KUNIT_EXPECT_TRUE_MSG(test, + (bool)ext4_test_bit(bit, bh->b_data), + "metadata bit %u must be set", bit); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(20, bh->b_data)); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(1023, bh->b_data)); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(1024, bh->b_data)); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(8191, bh->b_data)); + + KUNIT_EXPECT_EQ(test, ext4_count_free(bh->b_data, 1024 / 8), + ext4_free_clusters_after_init(sb, 1, &ctx->gdps[1])); + put_bh(bh); + + /* + * Legacy GDT_CSUM (CRC16 without metadata_csum) with FLEX_BG external + * metadata on group 2 (0 base blocks, bitmaps & itable in group 3) + * initializes all 1024 data bits in group 2 to free without I/O. + */ + { + struct balloc_test_blk *ext_slot; + ext4_fsblk_t ext_bbitmap = balloc_test_group_start(3) + 50; + + ext4_clear_feature_metadata_csum(sb); + ext4_set_feature_gdt_csum(sb); + ext4_set_feature_flex_bg(sb); + + ext_slot = balloc_test_setup_blk(ctx, ext_bbitmap, false); + KUNIT_ASSERT_NOT_NULL(test, ext_slot); + memset(ext_slot->cache_buf, 0x5a, sizeof(ext_slot->cache_buf)); + + ext4_block_bitmap_set(sb, &ctx->gdps[2], ext_bbitmap); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], ext_bbitmap + 1); + ext4_inode_table_set(sb, &ctx->gdps[2], ext_bbitmap + 2); + ctx->gdps[2].bg_flags = cpu_to_le16(EXT4_BG_BLOCK_UNINIT); + ext4_group_desc_csum_set(sb, 2, &ctx->gdps[2]); + + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 0U); + KUNIT_EXPECT_EQ(test, ext4_count_free(bh->b_data, 1024 / 8), + 1024U); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(1024, bh->b_data)); + put_bh(bh); + + ext4_clear_feature_flex_bg(sb); + } + + /* + * Without GDT checksums (neither metadata_csum nor gdt_csum), + * EXT4_BG_BLOCK_UNINIT is ignored and bitmap is read from disk. + */ + ext4_clear_feature_metadata_csum(sb); + ext4_clear_feature_gdt_csum(sb); + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + put_bh(bh); +} + +static void test_read_block_bitmap_uninit_errors(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot0, *slot1; + struct buffer_head *bh; + s64 free_clu_before, free_ino_before; + + slot0 = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(0)); + slot1 = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot0); + KUNIT_ASSERT_NOT_NULL(test, slot1); + + /* 1. Group 0 marked EXT4_BG_BLOCK_UNINIT is rejected -> -EFSCORRUPTED */ + clear_buffer_uptodate(&slot0->bh); + clear_bitmap_uptodate(&slot0->bh); + ctx->gdps[0].bg_flags = cpu_to_le16(EXT4_BG_BLOCK_UNINIT); + ext4_group_desc_csum_set(sb, 0, &ctx->gdps[0]); + + bh = ext4_read_block_bitmap(sb, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + /* + * 2. Group 1 marked EXT4_BG_BLOCK_UNINIT with bad GDT checksum fails + * with -EFSBADCRC and marks BOTH block and inode bitmaps corrupt. + */ + free_clu_before = percpu_counter_sum(&ctx->sbi.s_freeclusters_counter); + free_ino_before = percpu_counter_sum(&ctx->sbi.s_freeinodes_counter); + clear_buffer_uptodate(&slot1->bh); + clear_bitmap_uptodate(&slot1->bh); + ctx->gdps[1].bg_flags = cpu_to_le16(EXT4_BG_BLOCK_UNINIT); + ctx->gdps[1].bg_checksum = cpu_to_le16(0xdead); + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSBADCRC); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[1])); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_freeclusters_counter), + free_clu_before - ctx->grp_infos[1]->bb_free); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_freeinodes_counter), + free_ino_before - BALLOC_TEST_INODES_PER_GRP); + + /* + * 3. Base metadata clusters exceeding bitmap block size ((bit_max >> 3) + * >= bh->b_size) returns -EFSCORRUPTED instead of overflowing bh. + */ + ctx->grp_infos[1]->bb_state = 0; + clear_buffer_uptodate(&slot1->bh); + clear_bitmap_uptodate(&slot1->bh); + ctx->sbi.s_gdb_count = BALLOC_TEST_BLK_SIZE * 8; + ext4_group_desc_csum_set(sb, 1, &ctx->gdps[1]); + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); +} + +static void test_read_and_wait_block_bitmap_errors(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + int ref_before; + + /* 1. Out-of-range block group -> -EFSCORRUPTED */ + bh = ext4_read_block_bitmap(sb, 99); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + /* 2. Block bitmap <= s_first_data_block (1) -> -EFSCORRUPTED + corrupt */ + ext4_block_bitmap_set(sb, &ctx->gdps[2], BALLOC_TEST_FIRST_DATA_BLK); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[2])); + + /* 3. Block bitmap >= ext4_blocks_count(es) -> -EFSCORRUPTED + corrupt */ + ctx->grp_infos[2]->bb_state = 0; + ext4_block_bitmap_set(sb, &ctx->gdps[2], BALLOC_TEST_TOTAL_BLKS); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[2])); + ext4_block_bitmap_set(sb, &ctx->gdps[2], balloc_test_bbitmap_blk(2)); + + /* 4. ext4_sb_getblk allocation failure -> -ENOMEM without corrupt flag */ + ctx->grp_infos[2]->bb_state = 0; + ctx->fail_getblk = true; + bh = ext4_read_block_bitmap(sb, 2); + ctx->fail_getblk = false; + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -ENOMEM); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[2])); + + /* 5. Async read I/O failure -> -EIO, marks corrupt, releases bh ref */ + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot); + ref_before = atomic_read(&slot->bh.b_count); + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + ctx->fail_read_eio = true; + + bh = ext4_read_block_bitmap(sb, 2); + ctx->fail_read_eio = false; + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EIO); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[2])); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), ref_before); + +#ifdef CONFIG_EXT4_DEBUG + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + ctx->sbi.s_simulate_fail = EXT4_SIM_BBITMAP_EIO; + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EIO); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_simulate_fail, 0UL); +#endif + + /* 6. ext4_wait_block_bitmap guards on BH_New and group descriptor */ + clear_buffer_new(&slot->bh); + KUNIT_EXPECT_EQ(test, ext4_wait_block_bitmap(sb, 99, &slot->bh), 0); + set_buffer_new(&slot->bh); + KUNIT_EXPECT_EQ(test, ext4_wait_block_bitmap(sb, 99, &slot->bh), + -EFSCORRUPTED); + clear_buffer_new(&slot->bh); +} + +/* ========================================================================= + * 8. Free Cluster Reservation & Pool Accounting (ext4_claim_free_clusters) + * ========================================================================= + */ + +static void balloc_test_set_cluster_pools(struct balloc_test_ctx *ctx, + s64 free_clu, s64 dirty_clu, + u64 r_blocks, s64 resv_clu) +{ + percpu_counter_set(&ctx->sbi.s_freeclusters_counter, free_clu); + percpu_counter_set(&ctx->sbi.s_dirtyclusters_counter, dirty_clu); + ctx->es.s_r_blocks_count_lo = cpu_to_le32(lower_32_bits(r_blocks)); + ctx->es.s_r_blocks_count_hi = cpu_to_le32(upper_32_bits(r_blocks)); + atomic64_set(&ctx->sbi.s_resv_clusters, resv_clu); +} + +static void +test_claim_free_clusters_unprivileged_and_bigalloc(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + + sbi->s_resuid = KUIDT_INIT(500); + sbi->s_resgid = GLOBAL_ROOT_GID; + balloc_test_override_creds(test, ctx, 1000, 1000, false, -1); + + /* Above-watermark fast path */ + balloc_test_set_cluster_pools(ctx, 100000, 10, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 25, 0), 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_dirtyclusters_counter), + 35LL); + + /* + * Exact unprivileged limit: + * free=100, dirty=20, r_blocks=30, resv=15 -> usable = 100 - 20 - 45 = 35 + */ + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 36, 0), -ENOSPC); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_dirtyclusters_counter), + 20LL); + + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 35, 0), 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_dirtyclusters_counter), + 55LL); + + /* + * Bigalloc (cluster_bits = 2 -> 4 blocks/cluster): + * r_blocks_count = 120 blocks -> 30 reserved clusters -> usable = 35. + */ + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + balloc_test_set_cluster_pools(ctx, 100, 20, 120, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 36, 0), -ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 35, 0), 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_dirtyclusters_counter), + 55LL); + + balloc_test_restore_creds(ctx); +} + +static void test_claim_free_clusters_root_and_reserved_pools(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + + /* + * Pool layout: free=100, dirty=20, r_blocks=30, resv=15: + * - Unprivileged limit: 35 clusters (100 - 20 - 30 - 15) + * - Root-pool limit: 65 clusters (100 - 20 - 15; resv protected) + * - Internal resv limit: 80 clusters (100 - 20; EXT4_MB_USE_RESERVED) + */ + sbi->s_resuid = KUIDT_INIT(500); + sbi->s_resgid = GLOBAL_ROOT_GID; + + /* 1. Matching s_resuid grants root pool (65), still protects resv (66) */ + balloc_test_override_creds(test, ctx, 500, 1000, false, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 66, 0), -ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 65, 0), 0); + + /* + * 2. s_resgid == GLOBAL_ROOT_GID (0) does NOT grant root blocks via + * group membership even when caller's fsgid is 0. + */ + balloc_test_override_creds(test, ctx, 1000, 0, false, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 36, 0), -ENOSPC); + +#ifdef CONFIG_MULTIUSER + /* 3. Non-root s_resgid grants root pool only when caller is in group */ + sbi->s_resgid = KGIDT_INIT(2000); + balloc_test_override_creds(test, ctx, 1000, 1000, false, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 36, 0), -ENOSPC); + + balloc_test_override_creds(test, ctx, 1000, 1000, false, 2000); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 66, 0), -ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 65, 0), 0); + sbi->s_resgid = GLOBAL_ROOT_GID; +#endif + + /* 4. EXT4_MB_USE_ROOT_BLOCKS grants root pool to unprivileged caller */ + balloc_test_override_creds(test, ctx, 1000, 1000, false, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, + ext4_claim_free_clusters(sbi, 66, + EXT4_MB_USE_ROOT_BLOCKS), + -ENOSPC); + KUNIT_EXPECT_EQ(test, + ext4_claim_free_clusters(sbi, 65, + EXT4_MB_USE_ROOT_BLOCKS), + 0); + + /* 5. CAP_SYS_RESOURCE grants root pool regardless of uid/gid/flags */ + balloc_test_override_creds(test, ctx, 1000, 1000, true, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 66, 0), -ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 65, 0), 0); + + /* 6. EXT4_MB_USE_RESERVED dips into s_resv_clusters up to 80 clusters */ + balloc_test_override_creds(test, ctx, 1000, 1000, false, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, + ext4_claim_free_clusters(sbi, 81, EXT4_MB_USE_RESERVED), + -ENOSPC); + KUNIT_EXPECT_EQ(test, + ext4_claim_free_clusters(sbi, 80, EXT4_MB_USE_RESERVED), + 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_dirtyclusters_counter), + 100LL); + + balloc_test_restore_creds(ctx); +} + +/* ========================================================================= + * 9. Allocation Retry Policy (ext4_should_retry_alloc) + * ========================================================================= + */ + +static void +test_should_retry_alloc_no_journal_and_retry_limit(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + int retries = 1; + + /* Without a journal, returns 0 without incrementing *retries */ + sbi->s_journal = NULL; + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 0); + KUNIT_EXPECT_EQ(test, retries, 1); + + /* With journal and pending mb frees, retries 1..3 succeed, 4th stops */ + sbi->s_journal = &ctx->journal; + atomic_set(&sbi->s_mb_free_pending, 4); + retries = 0; + + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 1); + KUNIT_EXPECT_EQ(test, retries, 1); + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 1); + KUNIT_EXPECT_EQ(test, retries, 2); + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 1); + KUNIT_EXPECT_EQ(test, retries, 3); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&sbi->s_sra_exceeded_retry_limit), + 0LL); + + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 0); + KUNIT_EXPECT_EQ(test, retries, 4); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&sbi->s_sra_exceeded_retry_limit), + 1LL); +} + +static void +test_should_retry_alloc_free_space_and_discard_flush(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + int retries; + + sbi->s_journal = &ctx->journal; + atomic_set(&sbi->s_mb_free_pending, 0); + clear_opt(sb, DISCARD); + balloc_test_override_creds(test, ctx, 1000, 1000, false, -1); + + /* 1. No pending frees, no discard, 0 free clusters -> returns 0 */ + balloc_test_set_cluster_pools(ctx, 10, 10, 0, 0); + retries = 0; + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 0); + KUNIT_EXPECT_EQ(test, retries, 1); + KUNIT_EXPECT_EQ(test, ctx->discard_work_runs, 0U); + + /* 2. Free cluster available -> returns 1 */ + balloc_test_set_cluster_pools(ctx, 11, 10, 0, 0); + retries = 0; + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 1); + + /* + * 3. With DISCARD enabled, flushes s_discard_work while holding + * s_retry_alloc_pending == 1 and rechecks free clusters afterward. + */ + set_opt(sb, DISCARD); + balloc_test_set_cluster_pools(ctx, 10, 10, 0, 0); + ctx->discard_release_clusters = 8; + ctx->discard_wait_retry_pending = true; + schedule_work(&sbi->s_discard_work); + + retries = 0; + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 1); + ctx->discard_wait_retry_pending = false; + KUNIT_EXPECT_EQ(test, ctx->discard_work_runs, 1U); + KUNIT_EXPECT_EQ(test, ctx->discard_saw_retry_pending, 1); + KUNIT_EXPECT_EQ(test, atomic_read(&sbi->s_retry_alloc_pending), 0); + + balloc_test_restore_creds(ctx); +} + +/* ========================================================================= + * 10. Metadata Block Allocation (ext4_new_meta_blocks) + * ========================================================================= + */ + +static void test_new_meta_blocks_alloc_and_delalloc_quota(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct inode *inode = ctx->test_inode; + unsigned long count; + ext4_fsblk_t blk; + int err = -EINVAL; + + /* 1. count == NULL defaults ar.len to 1; non-delalloc skips quota */ + ctx->mock_alloc_blk = 1234ULL; + ctx->mock_alloc_len = 0; + ctx->mock_alloc_err = 0; + inode_set_bytes(inode, 0); + + blk = ext4_new_meta_blocks(NULL, inode, 500ULL, EXT4_MB_USE_ROOT_BLOCKS, + NULL, &err); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, blk, 1234ULL); + KUNIT_EXPECT_PTR_EQ(test, ctx->last_ar.inode, inode); + KUNIT_EXPECT_EQ(test, ctx->last_ar.goal, 500ULL); + KUNIT_EXPECT_EQ(test, ctx->last_ar.len, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_ar.flags, + (unsigned int)EXT4_MB_USE_ROOT_BLOCKS); + KUNIT_EXPECT_EQ(test, inode_get_bytes(inode), 0LL); + + /* + * 2. Partial allocation (requested 8 clusters, granted 3) with + * EXT4_MB_DELALLOC_RESERVED and bigalloc (4 blocks/cluster = 4096B + * per cluster) updates *count to 3 and charges 12288 quota bytes. + */ + ctx->sbi.s_cluster_bits = 2; + ctx->sbi.s_cluster_ratio = 4; + ctx->mock_alloc_blk = 2400ULL; + ctx->mock_alloc_len = 3; + ctx->mock_alloc_err = 0; + count = 8; + + blk = ext4_new_meta_blocks(NULL, inode, 2048ULL, + EXT4_MB_DELALLOC_RESERVED, &count, &err); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, blk, 2400ULL); + KUNIT_EXPECT_EQ(test, count, 3UL); + KUNIT_EXPECT_EQ(test, inode_get_bytes(inode), 12288LL); + + /* 3. Error from ext4_mb_new_blocks does not charge quota bytes */ + ctx->mock_alloc_err = -ENOSPC; + count = 4; + blk = ext4_new_meta_blocks(NULL, inode, 2048ULL, + EXT4_MB_DELALLOC_RESERVED, &count, &err); + KUNIT_EXPECT_EQ(test, err, -ENOSPC); + KUNIT_EXPECT_EQ(test, blk, 0ULL); + KUNIT_EXPECT_EQ(test, inode_get_bytes(inode), 12288LL); +} + +/* ========================================================================= + * 11. Free Cluster Summation (ext4_count_free_clusters) + * ========================================================================= + */ + +static void +test_count_free_clusters_corrupt_and_64bit_groups(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot2; + + slot2 = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot2); + + /* Default 4 groups: 1004 + 1004 + 1006 + 1004 = 4018 free clusters */ + KUNIT_EXPECT_EQ(test, ext4_count_free_clusters(sb), 4018ULL); + + /* Corrupt bitmap flag on group 2 excludes its 1006 clusters -> 3012 */ + clear_buffer_verified(&slot2->bh); + set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT, + &ctx->grp_infos[2]->bb_state); + KUNIT_EXPECT_EQ(test, ext4_count_free_clusters(sb), 3012ULL); + + /* NULL s_group_info still sums all valid group descriptors -> 4018 */ + set_buffer_verified(&slot2->bh); + rcu_assign_pointer(ctx->sbi.s_group_info, NULL); + KUNIT_EXPECT_EQ(test, ext4_count_free_clusters(sb), 4018ULL); + rcu_assign_pointer(ctx->sbi.s_group_info, ctx->grp_info_slices); + ctx->grp_infos[2]->bb_state = 0; + +#ifndef EXT4FS_DEBUG + /* 64-bit group descriptors with bg_free_blocks_count_hi > 0 */ + ctx->sbi.s_groups_count = 2; + ext4_free_group_clusters_set(sb, &ctx->gdps[0], 0x10005U); + ext4_free_group_clusters_set(sb, &ctx->gdps[1], 0x20003U); + KUNIT_EXPECT_EQ(test, ext4_count_free_clusters(sb), 0x30008ULL); + + /* Unloaded group descriptor block is skipped cleanly */ + ctx->sbi.s_groups_count = 20; + ctx->gdesc_bh_ptrs[1] = NULL; + KUNIT_EXPECT_EQ(test, ext4_count_free_clusters(sb), + 0x30008ULL + 1006ULL + 1004ULL); +#endif +} + +/* ========================================================================= + * 12. Inode Goal Block Selection (ext4_inode_to_goal_block) + * ========================================================================= + */ + +static void test_inode_to_goal_block_flex_bg_and_delalloc(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode = ctx->test_inode; + + ctx->sbi.s_groups_count = 8; + ext4_blocks_count_set(&ctx->es, 1 + 8 * BALLOC_TEST_BLOCKS_PER_GRP); + set_opt(sb, DELALLOC); + + /* flex_size = 2 (< EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME = 4): stays in bg 3 */ + ctx->sbi.s_log_groups_per_flex = 1; + EXT4_I(inode)->i_block_group = 3; + inode->i_mode = S_IFDIR | 0755; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(3)); + inode->i_mode = S_IFREG | 0644; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(3)); + + /* + * flex_size = 4 (== EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME): + * - Directories and special/symlink inodes map to 1st group of flex_bg + * - Regular files map to 2nd group of flex_bg (flex_start + 1) + */ + ctx->sbi.s_log_groups_per_flex = 2; + + EXT4_I(inode)->i_block_group = 3; + inode->i_mode = S_IFDIR | 0755; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(0)); + inode->i_mode = S_IFLNK | 0777; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(0)); + inode->i_mode = S_IFREG | 0644; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(1)); + + EXT4_I(inode)->i_block_group = 6; + inode->i_mode = S_IFDIR | 0755; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(4)); + inode->i_mode = S_IFREG | 0644; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(5)); +} + +static void test_inode_to_goal_block_nodelalloc_colour(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode = ctx->test_inode; + ext4_fsblk_t g0_start = balloc_test_group_start(0); + ext4_fsblk_t g3_start = balloc_test_group_start(3); + ext4_fsblk_t goal_full, goal_partial; + u32 rem; + + clear_opt(sb, DELALLOC); + ctx->sbi.s_log_groups_per_flex = 0; + inode->i_mode = S_IFREG | 0644; + + /* + * Full group 0 (1024 blocks -> step = 64) vs partial last group 3 with + * last_block - g3_start == 320 (321 blocks -> step = 20). Both calls + * execute in the same kthread, so (task_pid_nr(current) % 16) is fixed. + */ + ext4_blocks_count_set(&ctx->es, g3_start + 321); + + EXT4_I(inode)->i_block_group = 0; + goal_full = ext4_inode_to_goal_block(inode); + KUNIT_EXPECT_GE(test, goal_full, g0_start); + KUNIT_EXPECT_LE(test, goal_full, g0_start + 15 * 64); + div_u64_rem(goal_full - g0_start, 64, &rem); + KUNIT_EXPECT_EQ(test, rem, 0U); + + EXT4_I(inode)->i_block_group = 3; + goal_partial = ext4_inode_to_goal_block(inode); + KUNIT_EXPECT_GE(test, goal_partial, g3_start); + KUNIT_EXPECT_LE(test, goal_partial, g3_start + 15 * 20); + div_u64_rem(goal_partial - g3_start, 20, &rem); + KUNIT_EXPECT_EQ(test, rem, 0U); + KUNIT_EXPECT_EQ(test, (goal_full - g0_start) * 20, + (goal_partial - g3_start) * 64); + + /* Partial last group with < 16 blocks yields colour step 0 -> g3_start */ + ext4_blocks_count_set(&ctx->es, g3_start + 16); + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), g3_start); +} + +static struct kunit_case balloc_test_cases[] = { + KUNIT_CASE_PARAM(test_group_no_and_offset_matrix, + group_offset_gen_params), + KUNIT_CASE(test_group_no_and_offset_optional_out_ptrs), + KUNIT_CASE(test_bg_has_super_dense_all_groups), + KUNIT_CASE(test_bg_has_super_sparse_super_powers), + KUNIT_CASE(test_bg_has_super_sparse_super2_explicit_backups), + KUNIT_CASE(test_bg_num_gdb_and_base_meta_non_metabg), + KUNIT_CASE(test_bg_num_gdb_and_base_meta_hybrid_metabg), + KUNIT_CASE(test_free_clusters_after_init_standard_and_partial_last), + KUNIT_CASE(test_free_clusters_after_init_external_and_spanning_meta), + KUNIT_CASE(test_free_clusters_after_init_bigalloc_cluster_sharing), + KUNIT_CASE(test_get_group_desc_lookup_and_bounds), + KUNIT_CASE(test_get_group_info_lookup_and_null_guards), + KUNIT_CASE(test_read_block_bitmap_validates_csum), + KUNIT_CASE(test_read_block_bitmap_validates_metadata_bits), + KUNIT_CASE(test_read_block_bitmap_validates_padding), + KUNIT_CASE(test_read_block_bitmap_validation_short_circuits), + KUNIT_CASE(test_read_block_bitmap_disk_and_cache_paths), + KUNIT_CASE(test_read_block_bitmap_nowait_prefetch_locked), + KUNIT_CASE(test_read_block_bitmap_uninit_group), + KUNIT_CASE(test_read_block_bitmap_uninit_errors), + KUNIT_CASE(test_read_and_wait_block_bitmap_errors), + KUNIT_CASE(test_claim_free_clusters_unprivileged_and_bigalloc), + KUNIT_CASE(test_claim_free_clusters_root_and_reserved_pools), + KUNIT_CASE(test_should_retry_alloc_no_journal_and_retry_limit), + KUNIT_CASE(test_should_retry_alloc_free_space_and_discard_flush), + KUNIT_CASE(test_new_meta_blocks_alloc_and_delalloc_quota), + KUNIT_CASE(test_count_free_clusters_corrupt_and_64bit_groups), + KUNIT_CASE(test_inode_to_goal_block_flex_bg_and_delalloc), + KUNIT_CASE(test_inode_to_goal_block_nodelalloc_colour), + {} +}; + +static struct kunit_suite balloc_test_suite = { + .name = "ext4_balloc_test", + .init = balloc_test_init, + .test_cases = balloc_test_cases, +}; + +kunit_test_suites(&balloc_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 block allocation helpers in balloc.c"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/balloc.c b/fs/ext4/balloc.c index 778fe8788f06e1..d2f0f27bbc9aab 100644 --- a/fs/ext4/balloc.c +++ b/fs/ext4/balloc.c @@ -243,6 +243,7 @@ unsigned ext4_free_clusters_after_init(struct super_block *sb, return num_clusters_in_group(sb, block_group) - ext4_num_overhead_clusters(sb, block_group, gdp); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_clusters_after_init); /* * The free blocks are managed by bitmaps. A file system contains several @@ -489,7 +490,7 @@ ext4_read_block_bitmap_nowait(struct super_block *sb, ext4_group_t block_group, EXT4_GROUP_INFO_BBITMAP_CORRUPT); return ERR_PTR(-EFSCORRUPTED); } - bh = sb_getblk(sb, bitmap_blk); + bh = ext4_sb_getblk(sb, bitmap_blk); if (unlikely(!bh)) { ext4_warning(sb, "Cannot get buffer for block bitmap - " "block_group = %u, block_bitmap = %llu", @@ -611,6 +612,7 @@ ext4_read_block_bitmap(struct super_block *sb, ext4_group_t block_group) } return bh; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_block_bitmap); /** * ext4_has_free_clusters() @@ -678,6 +680,7 @@ int ext4_claim_free_clusters(struct ext4_sb_info *sbi, } else return -ENOSPC; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_claim_free_clusters); /** * ext4_should_retry_alloc() - check if a block allocation should be retried @@ -724,6 +727,7 @@ int ext4_should_retry_alloc(struct super_block *sb, int *retries) (void) jbd2_journal_force_commit_nested(sbi->s_journal); return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_should_retry_alloc); /* * ext4_new_meta_blocks() -- allocate block for meta data (indexing) blocks @@ -764,6 +768,7 @@ ext4_fsblk_t ext4_new_meta_blocks(handle_t *handle, struct inode *inode, } return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_new_meta_blocks); /** * ext4_count_free_clusters() -- count filesystem free clusters @@ -877,6 +882,7 @@ int ext4_bg_has_super(struct super_block *sb, ext4_group_t group) return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_bg_has_super); static unsigned long ext4_bg_num_gdb_meta(struct super_block *sb, ext4_group_t group) @@ -923,6 +929,7 @@ unsigned long ext4_bg_num_gdb(struct super_block *sb, ext4_group_t group) return ext4_bg_num_gdb_meta(sb,group); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_bg_num_gdb); /* * This function returns the number of file system metadata blocks at @@ -949,6 +956,7 @@ unsigned int ext4_num_base_meta_blocks(struct super_block *sb, } return num; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_num_base_meta_blocks); static unsigned int ext4_num_base_meta_clusters(struct super_block *sb, ext4_group_t block_group) @@ -1004,4 +1012,5 @@ ext4_fsblk_t ext4_inode_to_goal_block(struct inode *inode) ((last_block - bg_start) / 16); return bg_start + colour; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_to_goal_block); From 07ab120f16454ba028de16a2e660b75c6b5c6467 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Fri, 6 Nov 2026 15:31:04 +0000 Subject: [PATCH 1563/2102] ext4: add KUnit tests for fs/ext4/orphan.c Add the ext4_orphan_test KUnit test suite in fs/ext4/orphan-test.c (22 test cases, 25 subtests total when CONFIG_QUOTA is enabled; 21 test cases, 24 subtests otherwise) to comprehensively exercise orphan inode tracking, orphan file management, and mount-time orphan recovery in fs/ext4/orphan.c using an in-memory VFS superblock, mock block device, and deterministic buffer pool without requiring a mounted block device: - Orphan block geometry and empty-state checks (ext4_inodes_per_orphan_block across 1K, 2K, 4K, and 64K block sizes, and ext4_orphan_file_empty across disabled feature, zero-block files, and multi-block occupancy transitions). - Superblock linked-list orphan insertion (ext4_orphan_add), covering no-journal and bad-inode early exits, I_NEW unlocked insertion and deletion, idempotency when already tracked via i_orphan or EXT4_STATE_ORPHAN_FILE, LIFO chaining across regular, directory, and symlink inodes with superblock CRC32C updates, NEXT_ORPHAN boundary checks at s_inodes_count vs. s_inodes_count + 1, and journal/iloc error rollbacks without leaking buffer references or leaving stray s_orphan entries. - Superblock linked-list orphan removal (ext4_orphan_del), covering untracked inodes, no-journal early exit vs. EXT4_ORPHAN_FS recovery mode, head/middle/tail unlinking, NULL-handle in-core-only cleanup, and error propagation across superblock and predecessor/target inode journal operations. - Orphan-file insertion and deletion (ext4_orphan_file_add and ext4_orphan_file_del), covering EXT4_JTR_ORPHAN_FILE trigger wiring, slot claiming and freeing, circular block-ring wrap-around and final slot allocation, -ENOSPC fallback to the superblock linked list when all orphan blocks are full, non-ENOSPC journal write-access and dirty-metadata error propagation without fallback, NULL-handle state cleanup, and out-of-range block index warning guards. - Orphan-file JBD2 frozen-buffer checksum trigger and lifecycle management (ext4_orphan_file_block_trigger on live and frozen buffers, ext4_init_orphan_info, ext4_orphan_file_block_csum_verify with and without metadata_csum, the 512-block EXT4_MAX_ORPHAN_FILE_BLOCKS size boundary, partial-load error cleanup on iget/bread/hole/bad-magic/ bad-checksum failures, and ext4_release_orphan_info). - End-to-end mount-time orphan recovery (ext4_orphan_cleanup and ext4_process_orphan), covering empty-fs, read-only bdev, incompatible ROCOMPAT features, and EXT4_ERROR_FS skip guards, unlinked file and fast-symlink eviction, linked-inode truncation, combined linked-list and orphan-file recovery with corrupt-slot skipping and SB_RDONLY restoration, truncate failure handling via ext4_orphan_del(NULL, ...) and mid-loop EXT4_ERROR_FS abort, and quota activation/teardown paths under CONFIG_QUOTA and CONFIG_QFMT_V2. Add a KUNIT_STATIC_STUB_REDIRECT hook to ext4_truncate() in fs/ext4/inode.c for truncate failure injection during orphan recovery, and export the remaining non-static fs/ext4/orphan.c entry points with EXPORT_SYMBOL_FOR_EXT4_TEST. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 2 +- fs/ext4/inode.c | 2 + fs/ext4/orphan-test.c | 2372 +++++++++++++++++++++++++++++++++++++++++ fs/ext4/orphan.c | 5 + fs/ext4/super.c | 1 + 5 files changed, 2381 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/orphan-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 7d0ae7fd444868..9bad2bff0de969 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -19,7 +19,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ extents_status-test.o xattr-test.o \ namei-test.o inline-test.o \ fast_commit-test.o ialloc-test.o \ - balloc-test.o + balloc-test.o orphan-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 28fc6ec46cf490..9368a68db28941 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -5553,6 +5553,8 @@ int ext4_truncate(struct inode *inode) int err = 0, err2; handle_t *handle; + KUNIT_STATIC_STUB_REDIRECT(ext4_truncate, inode); + /* * There is a possibility that we're either freeing the inode * or it's a completely new inode. In those cases we might not diff --git a/fs/ext4/orphan-test.c b/fs/ext4/orphan-test.c new file mode 100644 index 00000000000000..bd60976a840d2f --- /dev/null +++ b/fs/ext4/orphan-test.c @@ -0,0 +1,2372 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/orphan.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "ext4_extents.h" +#include "xattr.h" + +/* + * Mock filesystem geometry: + * - 2 block groups, 1024-byte blocks (254 orphan entries per orphan block) + * - 64 inodes per group (128 total inodes), 256-byte inodes + * - s_first_ino = 11, s_orphan_file_inum = 12 + */ +#define ORPHAN_TEST_NGROUPS 2U +#define ORPHAN_TEST_BLK_SIZE 1024U +#define ORPHAN_TEST_BLK_BITS 10U +#define ORPHAN_TEST_BLOCKS_PER_GRP 1024U +#define ORPHAN_TEST_FIRST_DATA_BLK 1U +#define ORPHAN_TEST_TOTAL_BLKS (ORPHAN_TEST_FIRST_DATA_BLK + \ + ORPHAN_TEST_NGROUPS * \ + ORPHAN_TEST_BLOCKS_PER_GRP) +#define ORPHAN_TEST_INODE_SIZE 256U +#define ORPHAN_TEST_EXTRA_ISIZE 32U +#define ORPHAN_TEST_INODES_PER_BLK (ORPHAN_TEST_BLK_SIZE / \ + ORPHAN_TEST_INODE_SIZE) +#define ORPHAN_TEST_INODES_PER_GRP 64U +#define ORPHAN_TEST_ITB_PER_GRP (ORPHAN_TEST_INODES_PER_GRP / \ + ORPHAN_TEST_INODES_PER_BLK) +#define ORPHAN_TEST_TOTAL_INODES (ORPHAN_TEST_NGROUPS * \ + ORPHAN_TEST_INODES_PER_GRP) +#define ORPHAN_TEST_FIRST_INO 11U +#define ORPHAN_TEST_ORPHAN_INO 12U +#define ORPHAN_TEST_CSUM_SEED 0x4d7a19c5U +#define ORPHAN_TEST_OF_CSUM_SEED 0x91e23b77U +#define ORPHAN_TEST_INODES_PER_OB 254U + +#define ORPHAN_TEST_GDESC_BLK 2ULL +#define ORPHAN_TEST_OB_BASE_BLK 500ULL +#define ORPHAN_TEST_MAX_OB_BLKS 4U +#define ORPHAN_TEST_MAX_SLOTS 16U + +struct orphan_test_ibitmap { + struct buffer_head bh; + char buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); +}; + +struct orphan_test_ob_blk { + bool present; + int bread_err; + bool return_hole; + struct buffer_head bh; + char buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); +}; + +struct orphan_test_inode_slot { + bool in_use; + unsigned long ino; + bool handoff_to_iget; + struct inode *inode; + struct buffer_head iloc_bh; + char raw_buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); +}; + +struct orphan_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + struct buffer_head gdesc_bh; + char gdesc_buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); + + struct ext4_group_desc gdps[ORPHAN_TEST_NGROUPS]; + struct ext4_group_info *grp_infos[ORPHAN_TEST_NGROUPS]; + struct ext4_group_info *grp_info_ptrs[16]; + struct ext4_group_info **grp_info_slice[1]; + struct orphan_test_ibitmap ibitmaps[ORPHAN_TEST_NGROUPS]; + + journal_t mock_journal; + handle_t mock_handle; + + struct orphan_test_ob_blk ob_pool[ORPHAN_TEST_MAX_OB_BLKS]; + struct ext4_orphan_block static_binfo[ORPHAN_TEST_MAX_OB_BLKS]; + + /* Shared read-only block used for 512-block max-size boundary test */ + bool use_boundary_bh; + struct buffer_head boundary_bh; + char boundary_buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); + char frozen_buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); +#ifdef CONFIG_QUOTA + char qf_name[16]; +#endif + + struct orphan_test_inode_slot slots[ORPHAN_TEST_MAX_SLOTS]; + bool orphan_info_allocated; + bool enable_real_evict; + + /* Fault injection controls */ + int fail_write_access_err; + int fail_write_access_on_call; + int fail_dirty_metadata_err; + int fail_dirty_metadata_on_call; + int fail_get_iloc_err; + int fail_get_iloc_on_call; + int fail_mark_iloc_err; + int fail_mark_iloc_on_call; + int fail_mark_inode_dirty_err; + int fail_iget_err; + unsigned long fail_iget_ino; + int stub_truncate_err; + + /* Call tracking & verification state */ + unsigned int write_access_calls; + enum ext4_journal_trigger_type last_trigger_type; + unsigned int dirty_metadata_calls; + unsigned int get_iloc_calls; + unsigned int mark_iloc_calls; + unsigned int iget_calls; + unsigned int truncate_calls; + bool saw_rw_during_cleanup; + + unsigned long freed_inos[ORPHAN_TEST_MAX_SLOTS]; + unsigned int nr_freed_inos; + ext4_fsblk_t last_freed_blk; + unsigned long total_freed_blks; +}; + +static inline ext4_fsblk_t orphan_test_ibitmap_blk(ext4_group_t g) +{ + return ORPHAN_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * ORPHAN_TEST_BLOCKS_PER_GRP + 3ULL; +} + +static inline ext4_fsblk_t orphan_test_bbitmap_blk(ext4_group_t g) +{ + return ORPHAN_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * ORPHAN_TEST_BLOCKS_PER_GRP + 2ULL; +} + +static inline ext4_fsblk_t orphan_test_itable_blk(ext4_group_t g) +{ + return ORPHAN_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * ORPHAN_TEST_BLOCKS_PER_GRP + 4ULL; +} + +static void orphan_test_sb_upd_work(struct work_struct *work) +{ +} + +static void orphan_test_err_timer(struct timer_list *t) +{ +} + +static void orphan_test_init_ei_fields(struct ext4_inode_info *ei) +{ + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_flags = 0; + ext4_clear_state_flags(ei); + spin_lock_init(&ei->i_raw_lock); + ei->i_prealloc_node = RB_ROOT; + atomic_set(&ei->i_prealloc_active, 0); + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + ei->i_es_all_nr = 0; + ei->i_es_shk_nr = 0; + ei->i_es_shrink_lblk = 0; + ei->i_es_seq = 0; + ei->i_reserved_data_blocks = 0; + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); +#ifdef CONFIG_QUOTA + ei->i_reserved_quota = 0; + memset(&ei->i_dquot, 0, sizeof(ei->i_dquot)); +#endif +#ifdef CONFIG_FS_ENCRYPTION + ei->i_crypt_info = NULL; +#endif + ei->jinode = NULL; + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + ei->i_sync_tid = 0; + ei->i_datasync_tid = 0; + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_metadata_bhs = NULL; + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = ORPHAN_TEST_EXTRA_ISIZE; + ei->i_csum_seed = ORPHAN_TEST_OF_CSUM_SEED; + ei->i_last_alloc_group = ~0U; +} + +static struct inode *orphan_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + orphan_test_init_ei_fields(ei); + return &ei->vfs_inode; +} + +static void orphan_test_evict_inode(struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (ctx && ctx->enable_real_evict) { + ext4_evict_inode(inode); + return; + } + truncate_inode_pages_final(&inode->i_data); + ext4_clear_inode(inode); +} + +static void orphan_test_destroy_inode(struct inode *inode) +{ + kfree(ext4_i_metadata_bhs(inode)); + EXT4_I(inode)->i_metadata_bhs = NULL; +} + +static void orphan_test_free_inode_mem(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **orphan_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *orphan_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations orphan_test_qops = { + .get_reserved_space = orphan_test_get_reserved_space, + .alloc_dquot = dquot_alloc, + .destroy_dquot = dquot_destroy, + .get_next_id = dquot_get_next_id, +}; +#endif + +static const struct super_operations orphan_test_sops = { + .alloc_inode = orphan_test_alloc_inode, + .evict_inode = orphan_test_evict_inode, + .destroy_inode = orphan_test_destroy_inode, + .free_inode = orphan_test_free_inode_mem, + .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = orphan_test_get_dquots, +#endif +}; + +static int orphan_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type orphan_test_fs_type = { + .name = "ext4_orphan_kunit", + .init_fs_context = orphan_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +/* --- Slot & Orphan Block Helpers --- */ + +static struct orphan_test_inode_slot * +orphan_test_find_slot(struct orphan_test_ctx *ctx, unsigned long ino) +{ + unsigned int i; + + for (i = 0; i < ORPHAN_TEST_MAX_SLOTS; i++) { + if (ctx->slots[i].in_use && ctx->slots[i].ino == ino) + return &ctx->slots[i]; + } + return NULL; +} + +static void orphan_test_set_ibitmap_bit(struct orphan_test_ctx *ctx, + unsigned long ino, bool set) +{ + ext4_group_t g = (ino - 1) / ORPHAN_TEST_INODES_PER_GRP; + unsigned int bit = (ino - 1) % ORPHAN_TEST_INODES_PER_GRP; + + if (g >= ORPHAN_TEST_NGROUPS) + return; + if (set) + ext4_set_bit(bit, ctx->ibitmaps[g].buf); + else + ext4_clear_bit(bit, ctx->ibitmaps[g].buf); +} + +static struct orphan_test_inode_slot * +orphan_test_create_inode(struct kunit *test, struct orphan_test_ctx *ctx, + unsigned long ino, umode_t mode, unsigned int nlink) +{ + struct orphan_test_inode_slot *slot = NULL; + struct ext4_extent_header *eh; + struct inode *inode; + unsigned int i; + + for (i = 0; i < ORPHAN_TEST_MAX_SLOTS; i++) { + if (!ctx->slots[i].in_use) { + slot = &ctx->slots[i]; + break; + } + } + KUNIT_ASSERT_NOT_NULL(test, slot); + + inode = new_inode(ctx->sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->ino = ino; + slot->inode = inode; + slot->iloc_bh.b_data = slot->raw_buf; + slot->iloc_bh.b_size = ORPHAN_TEST_BLK_SIZE; + slot->iloc_bh.b_bdev = &ctx->bdev; + slot->iloc_bh.b_blocknr = orphan_test_itable_blk(0) + i; + atomic_set(&slot->iloc_bh.b_count, 1); + set_buffer_uptodate(&slot->iloc_bh); + + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = ctx->sb->s_blocksize_bits; + inode->i_flags |= S_NOQUOTA; + set_nlink(inode, nlink); + EXT4_I(inode)->i_block_group = (ino - 1) / ORPHAN_TEST_INODES_PER_GRP; + + if (S_ISREG(mode) || S_ISDIR(mode)) { + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + eh = ext_inode_hdr(inode); + memset(eh, 0, sizeof(EXT4_I(inode)->i_data)); + eh->eh_magic = EXT4_EXT_MAGIC; + eh->eh_entries = 0; + eh->eh_max = cpu_to_le16((sizeof(EXT4_I(inode)->i_data) - + sizeof(*eh)) / + sizeof(struct ext4_extent)); + eh->eh_depth = 0; + } + + orphan_test_set_ibitmap_bit(ctx, ino, true); + return slot; +} + +static void orphan_test_add_single_extent(struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + unsigned short len) +{ + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex = EXT_FIRST_EXTENT(eh); + + eh->eh_entries = cpu_to_le16(1); + ex->ee_block = cpu_to_le32(lblk); + ex->ee_len = cpu_to_le16(len); + ext4_ext_store_pblock(ex, pblk); + inode->i_blocks = (blkcnt_t)len << (inode->i_blkbits - 9); +} + +static __u32 orphan_test_calc_ob_csum(struct super_block *sb, __u32 seed, + ext4_fsblk_t blocknr, const void *data) +{ + __le64 dsk_block_nr = cpu_to_le64(blocknr); + size_t payload_bytes = sb->s_blocksize - + sizeof(struct ext4_orphan_block_tail); + __u32 csum; + + csum = crc32c(seed, &dsk_block_nr, sizeof(dsk_block_nr)); + return crc32c(csum, data, payload_bytes); +} + +static void orphan_test_seal_ob_bh(struct super_block *sb, __u32 seed, + struct buffer_head *bh, __u32 magic) +{ + struct ext4_orphan_block_tail *ot; + __u32 csum; + + ot = (struct ext4_orphan_block_tail *)(bh->b_data + sb->s_blocksize - + sizeof(*ot)); + ot->ob_magic = cpu_to_le32(magic); + csum = orphan_test_calc_ob_csum(sb, seed, bh->b_blocknr, bh->b_data); + ot->ob_checksum = cpu_to_le32(csum); +} + +static void orphan_test_setup_static_orphan_file(struct orphan_test_ctx *ctx, + int num_blocks) +{ + struct super_block *sb = ctx->sb; + struct ext4_orphan_info *oi = &ctx->sbi.s_orphan_info; + int i; + + ext4_set_feature_orphan_file(sb); + oi->of_blocks = num_blocks; + oi->of_csum_seed = ORPHAN_TEST_OF_CSUM_SEED; + oi->of_binfo = ctx->static_binfo; + ctx->orphan_info_allocated = false; + + for (i = 0; i < num_blocks; i++) { + struct orphan_test_ob_blk *oblk = &ctx->ob_pool[i]; + + memset(oblk, 0, sizeof(*oblk)); + oblk->present = true; + oblk->bh.b_data = oblk->buf; + oblk->bh.b_size = sb->s_blocksize; + oblk->bh.b_bdev = &ctx->bdev; + oblk->bh.b_blocknr = ORPHAN_TEST_OB_BASE_BLK + i; + atomic_set(&oblk->bh.b_count, 1); + set_buffer_uptodate(&oblk->bh); + orphan_test_seal_ob_bh(sb, oi->of_csum_seed, &oblk->bh, + EXT4_ORPHAN_BLOCK_MAGIC); + + ctx->static_binfo[i].ob_bh = &oblk->bh; + atomic_set(&ctx->static_binfo[i].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB); + } +} + +static void orphan_test_reset_faults(struct orphan_test_ctx *ctx) +{ + ctx->fail_write_access_err = 0; + ctx->fail_write_access_on_call = 0; + ctx->fail_dirty_metadata_err = 0; + ctx->fail_dirty_metadata_on_call = 0; + ctx->fail_get_iloc_err = 0; + ctx->fail_get_iloc_on_call = 0; + ctx->fail_mark_iloc_err = 0; + ctx->fail_mark_iloc_on_call = 0; + ctx->fail_mark_inode_dirty_err = 0; + ctx->fail_iget_err = 0; + ctx->fail_iget_ino = 0; + ctx->stub_truncate_err = 0; + + ctx->write_access_calls = 0; + ctx->last_trigger_type = EXT4_JTR_NONE; + ctx->dirty_metadata_calls = 0; + ctx->get_iloc_calls = 0; + ctx->mark_iloc_calls = 0; + ctx->iget_calls = 0; + ctx->truncate_calls = 0; + ctx->saw_rw_during_cleanup = false; + ctx->nr_freed_inos = 0; + ctx->last_freed_blk = 0; + ctx->total_freed_blks = 0; + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; +} + +static bool orphan_test_was_ino_freed(const struct orphan_test_ctx *ctx, + unsigned long ino) +{ + unsigned int i; + + for (i = 0; i < ctx->nr_freed_inos; i++) { + if (ctx->freed_inos[i] == ino) + return true; + } + return false; +} + +static int orphan_test_call_add(handle_t *handle, struct inode *inode) +{ + int err; + + inode_lock(inode); + err = ext4_orphan_add(handle, inode); + inode_unlock(inode); + return err; +} + +static int orphan_test_call_del(handle_t *handle, struct inode *inode) +{ + int err; + + inode_lock(inode); + err = ext4_orphan_del(handle, inode); + inode_unlock(inode); + return err; +} + +/* --- KUnit Static Stubs --- */ + +static int +orphan_test_get_write_access_stub(const char *where, unsigned int line, + handle_t *handle, struct super_block *sb, + struct buffer_head *bh, + enum ext4_journal_trigger_type trigger_type) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + + ctx->write_access_calls++; + ctx->last_trigger_type = trigger_type; + if (ctx->fail_write_access_err && + (!ctx->fail_write_access_on_call || + ctx->write_access_calls == (unsigned int)ctx->fail_write_access_on_call)) + return ctx->fail_write_access_err; + return 0; +} + +static int orphan_test_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + + ctx->dirty_metadata_calls++; + if (ctx->fail_dirty_metadata_err && + (!ctx->fail_dirty_metadata_on_call || + ctx->dirty_metadata_calls == (unsigned int)ctx->fail_dirty_metadata_on_call)) + return ctx->fail_dirty_metadata_err; + + if (bh) { + set_buffer_uptodate(bh); + clear_buffer_dirty(bh); + } + return 0; +} + +static int orphan_test_get_inode_loc_stub(struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + struct orphan_test_inode_slot *slot; + + if (!ctx) + return -EIO; + + ctx->get_iloc_calls++; + if (ctx->fail_get_iloc_err && + (!ctx->fail_get_iloc_on_call || + ctx->get_iloc_calls == (unsigned int)ctx->fail_get_iloc_on_call)) + return ctx->fail_get_iloc_err; + + slot = orphan_test_find_slot(ctx, inode->i_ino); + if (!slot) + return -ENOENT; + + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = EXT4_I(inode)->i_block_group; + return 0; +} + +static int orphan_test_mark_iloc_dirty_stub(handle_t *handle, + struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + int err = 0; + + if (ctx) { + ctx->mark_iloc_calls++; + if (ctx->fail_mark_iloc_err && + (!ctx->fail_mark_iloc_on_call || + ctx->mark_iloc_calls == (unsigned int)ctx->fail_mark_iloc_on_call)) + err = ctx->fail_mark_iloc_err; + } + + /* Real ext4_mark_iloc_dirty() always drops iloc->bh */ + brelse(iloc->bh); + iloc->bh = NULL; + return err; +} + +static int orphan_test_mark_inode_dirty_stub(handle_t *handle, + struct inode *inode, + const char *func, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + return ctx->fail_mark_inode_dirty_err; +} + +static struct inode *orphan_test_iget_stub(struct super_block *sb, + unsigned long ino, + ext4_iget_flags flags, + const char *function, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + struct orphan_test_inode_slot *slot; + struct inode *inode; + + if (!ctx) + return ERR_PTR(-EIO); + + ctx->iget_calls++; + if (ctx->fail_iget_err && + (!ctx->fail_iget_ino || ctx->fail_iget_ino == ino)) + return ERR_PTR(ctx->fail_iget_err); + + slot = orphan_test_find_slot(ctx, ino); + if (!slot || !slot->inode) + return ERR_PTR(-ENOENT); + + inode = slot->inode; + if (slot->handoff_to_iget) + slot->inode = NULL; + else + ihold(inode); + return inode; +} + +static struct buffer_head *orphan_test_getblk_stub(handle_t *handle, + struct inode *inode, + ext4_lblk_t block, + int map_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + struct orphan_test_ob_blk *oblk; + + if (!ctx) + return ERR_PTR(-EIO); + + if (ctx->use_boundary_bh) { + get_bh(&ctx->boundary_bh); + return &ctx->boundary_bh; + } + + if (block >= ORPHAN_TEST_MAX_OB_BLKS) + return ERR_PTR(-EFSCORRUPTED); + + oblk = &ctx->ob_pool[block]; + if (oblk->bread_err) + return ERR_PTR(oblk->bread_err); + if (oblk->return_hole || !oblk->present) + return NULL; + + get_bh(&oblk->bh); + return &oblk->bh; +} + +static struct ext4_group_desc * +orphan_test_get_group_desc_stub(struct super_block *sb, + ext4_group_t block_group, + struct buffer_head **bh) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx || block_group >= ORPHAN_TEST_NGROUPS) + return NULL; + if (bh) + *bh = &ctx->gdesc_bh; + return &ctx->gdps[block_group]; +} + +static struct buffer_head *orphan_test_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + ext4_group_t g; + + if (!ctx) + return NULL; + + for (g = 0; g < ORPHAN_TEST_NGROUPS; g++) { + if (block == orphan_test_ibitmap_blk(g)) { + get_bh(&ctx->ibitmaps[g].bh); + return &ctx->ibitmaps[g].bh; + } + } + return NULL; +} + +static void orphan_test_free_inode_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (ctx) { + if (!sb_rdonly(inode->i_sb)) + ctx->saw_rw_during_cleanup = true; + if (ctx->nr_freed_inos < ORPHAN_TEST_MAX_SLOTS) + ctx->freed_inos[ctx->nr_freed_inos++] = inode->i_ino; + orphan_test_set_ibitmap_bit(ctx, inode->i_ino, false); + } + ext4_clear_inode(inode); +} + +static void orphan_test_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, + ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (bh) + brelse(bh); + if (!ctx) + return; + ctx->last_freed_blk = block; + ctx->total_freed_blks += count; +} + +static int orphan_test_truncate_stub(struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + + ctx->truncate_calls++; + if (!sb_rdonly(inode->i_sb)) + ctx->saw_rw_during_cleanup = true; + return ctx->stub_truncate_err; +} + +/* --- Fixture Setup & Teardown --- */ + +static void orphan_test_cleanup(struct orphan_test_ctx *ctx) +{ + handle_t *handle; + unsigned int i; + + ctx->enable_real_evict = false; + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state &= ~EXT4_ORPHAN_FS; + + while ((handle = ext4_journal_current_handle()) != NULL) + ext4_journal_stop(handle); + + if (ctx->orphan_info_allocated) { + ext4_release_orphan_info(ctx->sb); + ctx->orphan_info_allocated = false; + } + memset(&ctx->sbi.s_orphan_info, 0, sizeof(ctx->sbi.s_orphan_info)); + INIT_LIST_HEAD(&ctx->sbi.s_orphan); + + for (i = 0; i < ORPHAN_TEST_MAX_SLOTS; i++) { + struct inode *inode = ctx->slots[i].inode; + + if (!inode) + continue; + INIT_LIST_HEAD(&EXT4_I(inode)->i_orphan); + ext4_clear_inode_state(inode, EXT4_STATE_ORPHAN_FILE); + spin_lock(&inode->i_lock); + inode_state_clear(inode, I_DIRTY_TIME | I_NEW); + spin_unlock(&inode->i_lock); + set_nlink(inode, 1); + iput(inode); + ctx->slots[i].inode = NULL; + } + + deactivate_super(ctx->sb); + rcu_barrier(); + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(orphan_test_cleanup_action, orphan_test_cleanup, + struct orphan_test_ctx *); + +static int orphan_test_init(struct kunit *test) +{ + struct orphan_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + ext4_group_t g; + unsigned int bit; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + if (!ctx->bdev.bd_stats) { + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bd_stats"); + } + + fc = fs_context_for_mount(&orphan_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &orphan_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &orphan_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = ORPHAN_TEST_BLK_SIZE; + sb->s_blocksize_bits = ORPHAN_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_orphan_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = ORPHAN_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + /* Writable bdev by default so ext4_orphan_cleanup can proceed */ + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(ORPHAN_TEST_FIRST_DATA_BLK); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + ctx->es.s_inodes_count = cpu_to_le32(ORPHAN_TEST_TOTAL_INODES); + ctx->es.s_inodes_per_group = cpu_to_le32(ORPHAN_TEST_INODES_PER_GRP); + ctx->es.s_blocks_per_group = cpu_to_le32(ORPHAN_TEST_BLOCKS_PER_GRP); + ctx->es.s_clusters_per_group = cpu_to_le32(ORPHAN_TEST_BLOCKS_PER_GRP); + ctx->es.s_first_ino = cpu_to_le32(ORPHAN_TEST_FIRST_INO); + ctx->es.s_orphan_file_inum = cpu_to_le32(ORPHAN_TEST_ORPHAN_INO); + ctx->es.s_inode_size = cpu_to_le16(ORPHAN_TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(ORPHAN_TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(ORPHAN_TEST_EXTRA_ISIZE); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_blocks_count_set(&ctx->es, ORPHAN_TEST_TOTAL_BLKS); + + ext4_set_feature_sparse_super(sb); + ext4_set_feature_extents(sb); + ext4_set_feature_extra_isize(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + + /* Keep sb_bh unmapped so ext4_commit_super() skips bh_submit I/O */ + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + ext4_superblock_csum_set(sb); + + ctx->gdesc_bh.b_data = ctx->gdesc_buf; + ctx->gdesc_bh.b_size = ORPHAN_TEST_BLK_SIZE; + ctx->gdesc_bh.b_blocknr = ORPHAN_TEST_GDESC_BLK; + ctx->gdesc_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->gdesc_bh.b_count, 1); + set_buffer_uptodate(&ctx->gdesc_bh); + + sbi->s_inode_size = ORPHAN_TEST_INODE_SIZE; + sbi->s_inodes_per_block = ORPHAN_TEST_INODES_PER_BLK; + sbi->s_inodes_per_group = ORPHAN_TEST_INODES_PER_GRP; + sbi->s_itb_per_group = ORPHAN_TEST_ITB_PER_GRP; + sbi->s_first_ino = ORPHAN_TEST_FIRST_INO; + sbi->s_want_extra_isize = ORPHAN_TEST_EXTRA_ISIZE; + sbi->s_blocks_per_group = ORPHAN_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = ORPHAN_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = ORPHAN_TEST_NGROUPS; + sbi->s_gdb_count = 1; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = ORPHAN_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_bitmap_maxbytes = 0x1ff7ffff000ULL; + sbi->s_csum_seed = ORPHAN_TEST_CSUM_SEED; + + mutex_init(&sbi->s_orphan_lock); + INIT_LIST_HEAD(&sbi->s_orphan); + sbi->s_journal = &ctx->mock_journal; + sbi->s_journal_triggers[EXT4_JTR_ORPHAN_FILE].sb = sb; + sbi->s_journal_triggers[EXT4_JTR_ORPHAN_FILE].tr_triggers.t_frozen = + ext4_orphan_file_block_trigger; + + set_opt(sb, ERRORS_CONT); + set_opt(sb, ORDERED_DATA); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + INIT_WORK(&sbi->s_sb_upd_work, orphan_test_sb_upd_work); + timer_setup(&sbi->s_err_report, orphan_test_err_timer, 0); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + for (g = 0; g < ORPHAN_TEST_NGROUPS; g++) { + struct orphan_test_ibitmap *ibm = &ctx->ibitmaps[g]; + + ctx->grp_infos[g] = kunit_kzalloc(test, + sizeof(*ctx->grp_infos[g]), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->grp_infos[g]); + init_rwsem(&ctx->grp_infos[g]->alloc_sem); + ctx->grp_infos[g]->bb_state = 0; + ctx->grp_info_ptrs[g] = ctx->grp_infos[g]; + + ext4_block_bitmap_set(sb, &ctx->gdps[g], + orphan_test_bbitmap_blk(g)); + ext4_inode_bitmap_set(sb, &ctx->gdps[g], + orphan_test_ibitmap_blk(g)); + ext4_inode_table_set(sb, &ctx->gdps[g], + orphan_test_itable_blk(g)); + + ibm->bh.b_data = ibm->buf; + ibm->bh.b_size = ORPHAN_TEST_BLK_SIZE; + ibm->bh.b_bdev = &ctx->bdev; + ibm->bh.b_blocknr = orphan_test_ibitmap_blk(g); + atomic_set(&ibm->bh.b_count, 1); + if (g == 0) { + for (bit = 0; bit < ORPHAN_TEST_FIRST_INO - 1; bit++) + ext4_set_bit(bit, ibm->buf); + } + ext4_mark_bitmap_end(ORPHAN_TEST_INODES_PER_GRP, + ORPHAN_TEST_BLK_SIZE * 8, ibm->buf); + set_buffer_uptodate(&ibm->bh); + set_bitmap_uptodate(&ibm->bh); + set_buffer_verified(&ibm->bh); + } + ctx->grp_info_slice[0] = ctx->grp_info_ptrs; + rcu_assign_pointer(sbi->s_group_info, ctx->grp_info_slice); + + root_inode = new_inode(sb); + if (!root_inode) { + deactivate_locked_super(sb); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc root_inode"); + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + deactivate_locked_super(sb); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to create s_root"); + } + + up_write(&sb->s_umount); + + kunit_activate_static_stub(test, __ext4_journal_get_write_access, + orphan_test_get_write_access_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + orphan_test_dirty_metadata_stub); + kunit_activate_static_stub(test, ext4_get_inode_loc, + orphan_test_get_inode_loc_stub); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + orphan_test_mark_iloc_dirty_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + orphan_test_mark_inode_dirty_stub); + kunit_activate_static_stub(test, __ext4_iget, + orphan_test_iget_stub); + kunit_activate_static_stub(test, ext4_getblk, + orphan_test_getblk_stub); + kunit_activate_static_stub(test, ext4_get_group_desc, + orphan_test_get_group_desc_stub); + kunit_activate_static_stub(test, ext4_sb_getblk, + orphan_test_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_free_inode, + orphan_test_free_inode_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + orphan_test_free_blocks_stub); + + err = kunit_add_action_or_reset(test, orphan_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->enable_real_evict = true; + return 0; +} + +/* ========================================================================= + * 1. Geometry & Empty-State Helpers + * ========================================================================= + */ + +struct orphan_blksize_param { + const char *desc; + unsigned long blocksize; + unsigned char blocksize_bits; + int expected_inodes_per_ob; +}; + +static const struct orphan_blksize_param orphan_blksize_params[] = { + { "1K_blocksize", 1024, 10, 254 }, + { "2K_blocksize", 2048, 11, 510 }, + { "4K_blocksize", 4096, 12, 1022 }, + { "64K_blocksize", 65536, 16, 16382 }, +}; + +KUNIT_ARRAY_PARAM_DESC(orphan_blksize, orphan_blksize_params, desc); + +static void test_inodes_per_orphan_block_param(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + const struct orphan_blksize_param *p = test->param_value; + + ctx->sb->s_blocksize = p->blocksize; + ctx->sb->s_blocksize_bits = p->blocksize_bits; + + KUNIT_EXPECT_EQ(test, ext4_inodes_per_orphan_block(ctx->sb), + p->expected_inodes_per_ob); +} + +static void test_orphan_file_empty(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + /* 1. Feature disabled returns 1 regardless of s_orphan_info */ + ext4_clear_feature_orphan_file(sb); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); + + /* 2. Feature enabled with 0 blocks returns 1 */ + ext4_set_feature_orphan_file(sb); + ctx->sbi.s_orphan_info.of_blocks = 0; + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); + + /* 3. Multi-block orphan file with all slots free returns 1 */ + orphan_test_setup_static_orphan_file(ctx, 3); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); + + /* 4. Occupied entry in a non-first block makes file non-empty (0) */ + atomic_set(&ctx->static_binfo[2].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB - 1); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 0); + + /* 5. Restoring free count returns 1 again */ + atomic_set(&ctx->static_binfo[2].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); +} + +/* ========================================================================= + * 2. Superblock Linked-List ext4_orphan_add() + * ========================================================================= + */ + +static void test_orphan_add_early_exits_and_idempotency(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2, *s3, *s4; + int err; + + s1 = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 16, S_IFREG | 0644, 0); + s3 = orphan_test_create_inode(test, ctx, 17, S_IFREG | 0644, 0); + s4 = orphan_test_create_inode(test, ctx, 18, S_IFREG | 0644, 0); + + /* 1. !sbi->s_journal -> no-op returning 0 */ + ctx->sbi.s_journal = NULL; + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); + ctx->sbi.s_journal = &ctx->mock_journal; + + /* 2. is_bad_inode(inode) -> no-op returning 0 */ + make_bad_inode(s2->inode); + err = orphan_test_call_add(&ctx->mock_handle, s2->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s2->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); + + /* 3. Idempotent when already on sbi->s_orphan list */ + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + + orphan_test_reset_faults(ctx); + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->dirty_metadata_calls, 0U); + + /* 4. Idempotent when already tracked via EXT4_STATE_ORPHAN_FILE */ + ext4_set_inode_state(s3->inode, EXT4_STATE_ORPHAN_FILE); + EXT4_I(s3->inode)->i_orphan_idx = 0; + err = orphan_test_call_add(&ctx->mock_handle, s3->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); + + /* 5. I_NEW inode can be added & deleted without holding i_rwsem */ + spin_lock(&s4->inode->i_lock); + inode_state_set(s4->inode, I_NEW); + spin_unlock(&s4->inode->i_lock); + + err = ext4_orphan_add(&ctx->mock_handle, s4->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 18U); + + err = ext4_orphan_del(&ctx->mock_handle, s4->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + + spin_lock(&s4->inode->i_lock); + inode_state_clear(s4->inode, I_NEW); + spin_unlock(&s4->inode->i_lock); +} + +static void test_orphan_add_list_chaining_and_csum(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2, *s3; + __le32 csum_before; + int err; + + s1 = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 20, S_IFDIR | 0755, 0); + s3 = orphan_test_create_inode(test, ctx, 25, S_IFLNK | 0777, 0); + + /* Corrupt s_checksum first so we verify ext4_superblock_csum_set() */ + ctx->es.s_checksum = 0; + csum_before = ctx->es.s_checksum; + + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s1->inode), 0U); + KUNIT_EXPECT_NE(test, le32_to_cpu(ctx->es.s_checksum), + le32_to_cpu(csum_before)); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + err = orphan_test_call_add(&ctx->mock_handle, s2->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 20U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s2->inode), 15U); + + err = orphan_test_call_add(&ctx->mock_handle, s3->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 25U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s3->inode), 20U); + + /* In-memory list head order must match LIFO insertion: s3 -> s2 -> s1 */ + KUNIT_EXPECT_PTR_EQ(test, ctx->sbi.s_orphan.next, + &EXT4_I(s3->inode)->i_orphan); + KUNIT_EXPECT_PTR_EQ(test, EXT4_I(s3->inode)->i_orphan.next, + &EXT4_I(s2->inode)->i_orphan); + KUNIT_EXPECT_PTR_EQ(test, EXT4_I(s2->inode)->i_orphan.next, + &EXT4_I(s1->inode)->i_orphan); +} + +static void test_orphan_add_next_orphan_bounds(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s_valid, *s_oob; + int err; + + s_valid = orphan_test_create_inode(test, ctx, 18, S_IFREG | 0644, 0); + s_oob = orphan_test_create_inode(test, ctx, 19, S_IFREG | 0644, 0); + + /* + * 1. NEXT_ORPHAN == s_inodes_count (valid upper boundary): + * inode is treated as already on-disk; skip on-disk modification, + * link into in-memory s_orphan, and brelse(iloc.bh). + */ + NEXT_ORPHAN(s_valid->inode) = ORPHAN_TEST_TOTAL_INODES; + ctx->es.s_last_orphan = cpu_to_le32(15); + orphan_test_reset_faults(ctx); + + err = orphan_test_call_add(&ctx->mock_handle, s_valid->inode); + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, list_empty(&EXT4_I(s_valid->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s_valid->inode), + ORPHAN_TEST_TOTAL_INODES); + KUNIT_EXPECT_EQ(test, ctx->dirty_metadata_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->mark_iloc_calls, 0U); + KUNIT_EXPECT_EQ(test, atomic_read(&s_valid->iloc_bh.b_count), 1); + + /* + * 2. NEXT_ORPHAN == s_inodes_count + 1 (invalid / garbage): + * must overwrite NEXT_ORPHAN with old s_last_orphan (15), update + * s_last_orphan to 19, and dirty both sb and iloc. + */ + NEXT_ORPHAN(s_oob->inode) = ORPHAN_TEST_TOTAL_INODES + 1; + orphan_test_reset_faults(ctx); + + err = orphan_test_call_add(&ctx->mock_handle, s_oob->inode); + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, list_empty(&EXT4_I(s_oob->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 19U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s_oob->inode), 15U); + KUNIT_EXPECT_EQ(test, ctx->dirty_metadata_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->mark_iloc_calls, 1U); + KUNIT_EXPECT_EQ(test, atomic_read(&s_oob->iloc_bh.b_count), 1); +} + +static void test_orphan_add_list_error_paths(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2; + int err; + + s1 = orphan_test_create_inode(test, ctx, 21, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 22, S_IFREG | 0644, 0); + + /* 1. ext4_journal_get_write_access(s_sbh) fails */ + orphan_test_reset_faults(ctx); + ctx->fail_write_access_err = -EIO; + ctx->fail_write_access_on_call = 1; + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_NE(test, ctx->sbi.s_mount_state & EXT4_ERROR_FS, 0); + + /* 2. ext4_reserve_inode_write (ext4_get_inode_loc) fails */ + orphan_test_reset_faults(ctx); + ctx->fail_get_iloc_err = -EIO; + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + /* + * 3. ext4_handle_dirty_metadata(s_sbh) fails while ext4_mark_iloc_dirty + * succeeds: must still consume iloc.bh and unlink from s_orphan! + */ + orphan_test_reset_faults(ctx); + ctx->fail_dirty_metadata_err = -EIO; + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, ctx->mark_iloc_calls, 1U); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + /* + * 4. ext4_handle_dirty_metadata(s_sbh) succeeds while + * ext4_mark_iloc_dirty fails: err = rc and rollback from s_orphan. + */ + orphan_test_reset_faults(ctx); + ctx->es.s_last_orphan = 0; + ctx->fail_mark_iloc_err = -ENOSPC; + err = orphan_test_call_add(&ctx->mock_handle, s2->inode); + KUNIT_EXPECT_EQ(test, err, -ENOSPC); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s2->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, atomic_read(&s2->iloc_bh.b_count), 1); +} + +/* ========================================================================= + * 3. Superblock Linked-List ext4_orphan_del() + * ========================================================================= + */ + +static void test_orphan_del_early_exits(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s_untracked; + int err; + + s1 = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s_untracked = orphan_test_create_inode(test, ctx, 16, S_IFREG | 0644, 0); + + /* 1. Untracked inode is a fast no-op */ + orphan_test_reset_faults(ctx); + err = orphan_test_call_del(&ctx->mock_handle, s_untracked->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->get_iloc_calls, 0U); + + /* Add s1 to orphan list */ + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_ASSERT_EQ(test, err, 0); + + /* 2. !s_journal && !(s_mount_state & EXT4_ORPHAN_FS) -> early return 0 */ + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state &= ~EXT4_ORPHAN_FS; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + + /* 3. !s_journal WITH EXT4_ORPHAN_FS proceeds with full deletion */ + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); +} + +static void test_orphan_del_list_positions_and_null_handle(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2, *s3; + int err; + + s1 = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 20, S_IFREG | 0644, 0); + s3 = orphan_test_create_inode(test, ctx, 25, S_IFREG | 0644, 0); + + /* Build chain: s_last_orphan -> 25 (s3) -> 20 (s2) -> 15 (s1) -> 0 */ + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s2->inode), + 0); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s3->inode), + 0); + + /* 1. Delete middle entry (s2 = 20): s3->NEXT_ORPHAN becomes 15 */ + err = orphan_test_call_del(&ctx->mock_handle, s2->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s2->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s2->inode), 0U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s3->inode), 15U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 25U); + + /* 2. Delete tail entry (s1 = 15): s3->NEXT_ORPHAN becomes 0 */ + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s1->inode), 0U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s3->inode), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 25U); + + /* 3. Delete head entry (s3 = 25): s_last_orphan becomes 0 */ + err = orphan_test_call_del(&ctx->mock_handle, s3->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->sbi.s_orphan)); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s3->inode), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + + /* 4. handle == NULL removes in-core entry without on-disk updates */ + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + orphan_test_reset_faults(ctx); + + err = orphan_test_call_del(NULL, s1->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, ctx->get_iloc_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); +} + +static void test_orphan_del_list_error_paths(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2; + int err; + + s1 = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 20, S_IFREG | 0644, 0); + + /* 1. Initial ext4_reserve_inode_write fails -> still unlinks in-core */ + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + orphan_test_reset_faults(ctx); + ctx->fail_get_iloc_err = -EIO; + ctx->fail_get_iloc_on_call = 1; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + /* 2. Head delete: ext4_journal_get_write_access(s_sbh) fails */ + ctx->es.s_last_orphan = 0; + NEXT_ORPHAN(s1->inode) = 0; + orphan_test_reset_faults(ctx); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + orphan_test_reset_faults(ctx); + /* Call 1 is reserve_inode_write(s1); call 2 is get_write_access(s_sbh) */ + ctx->fail_write_access_err = -EIO; + ctx->fail_write_access_on_call = 2; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + /* 3. Head delete: ext4_handle_dirty_metadata(s_sbh) fails */ + ctx->es.s_last_orphan = 0; + NEXT_ORPHAN(s1->inode) = 0; + orphan_test_reset_faults(ctx); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + orphan_test_reset_faults(ctx); + ctx->fail_dirty_metadata_err = -EIO; + ctx->fail_dirty_metadata_on_call = 1; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + /* 4. Non-head delete: ext4_reserve_inode_write(i_prev) fails */ + ctx->es.s_last_orphan = 0; + NEXT_ORPHAN(s1->inode) = 0; + NEXT_ORPHAN(s2->inode) = 0; + orphan_test_reset_faults(ctx); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s2->inode), + 0); + + orphan_test_reset_faults(ctx); + /* Call 1 is s1 iloc; call 2 is i_prev (s2) iloc */ + ctx->fail_get_iloc_err = -EIO; + ctx->fail_get_iloc_on_call = 2; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s2->inode), 15U); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&s2->iloc_bh.b_count), 1); + + /* 5. Non-head delete: ext4_mark_iloc_dirty(i_prev) fails */ + list_add(&EXT4_I(s1->inode)->i_orphan, &EXT4_I(s2->inode)->i_orphan); + orphan_test_reset_faults(ctx); + ctx->fail_mark_iloc_err = -EIO; + ctx->fail_mark_iloc_on_call = 1; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&s2->iloc_bh.b_count), 1); + + /* 6. Final ext4_mark_iloc_dirty(inode) fails on head delete */ + orphan_test_reset_faults(ctx); + ctx->fail_mark_iloc_err = -ENOSPC; + ctx->fail_mark_iloc_on_call = 1; + err = orphan_test_call_del(&ctx->mock_handle, s2->inode); + KUNIT_EXPECT_EQ(test, err, -ENOSPC); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s2->inode), 0U); + KUNIT_EXPECT_EQ(test, atomic_read(&s2->iloc_bh.b_count), 1); +} + +/* ========================================================================= + * 4. Orphan-File ext4_orphan_add() & ext4_orphan_del() + * ========================================================================= + */ + +static void test_orphan_file_add_and_del_basic(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct orphan_test_inode_slot *s1; + unsigned int blk, off; + __le32 *bdata; + int err; + + orphan_test_setup_static_orphan_file(ctx, 2); + s1 = orphan_test_create_inode(test, ctx, 24, S_IFREG | 0644, 0); + + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_TRUE(test, ext4_inode_orphan_tracked(s1->inode)); + KUNIT_EXPECT_EQ(test, ctx->last_trigger_type, EXT4_JTR_ORPHAN_FILE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 0); + + blk = EXT4_I(s1->inode)->i_orphan_idx / ORPHAN_TEST_INODES_PER_OB; + off = EXT4_I(s1->inode)->i_orphan_idx % ORPHAN_TEST_INODES_PER_OB; + KUNIT_ASSERT_LT(test, blk, 2U); + KUNIT_EXPECT_EQ(test, off, 0U); + bdata = (__le32 *)ctx->static_binfo[blk].ob_bh->b_data; + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata[off]), 24U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[blk].ob_free_entries), + (int)(ORPHAN_TEST_INODES_PER_OB - 1)); + + /* Delete from orphan file and verify slot & state restoration */ + orphan_test_reset_faults(ctx); + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_FALSE(test, ext4_inode_orphan_tracked(s1->inode)); + KUNIT_EXPECT_EQ(test, ctx->last_trigger_type, EXT4_JTR_ORPHAN_FILE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata[off]), 0U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[blk].ob_free_entries), + (int)ORPHAN_TEST_INODES_PER_OB); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); +} + +static void test_orphan_file_add_block_wraparound_and_last_slot(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2; + __le32 *bdata; + unsigned int j; + int b, err; + + orphan_test_setup_static_orphan_file(ctx, 3); + s1 = orphan_test_create_inode(test, ctx, 30, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 31, S_IFREG | 0644, 0); + + /* + * Mark blocks 0 and 1 full (0 free), and leave ONLY the very last slot + * (ORPHAN_TEST_INODES_PER_OB - 1 = 253) free in block 2. Then test a + * second add when only block 0 has 1 slot free, guaranteeing + * wrap-around across the circular block ring regardless of CPU id. + */ + atomic_set(&ctx->static_binfo[0].ob_free_entries, 0); + atomic_set(&ctx->static_binfo[1].ob_free_entries, 0); + atomic_set(&ctx->static_binfo[2].ob_free_entries, 1); + bdata = (__le32 *)ctx->static_binfo[2].ob_bh->b_data; + for (j = 0; j < ORPHAN_TEST_INODES_PER_OB - 1; j++) + bdata[j] = cpu_to_le32(100 + j); + bdata[ORPHAN_TEST_INODES_PER_OB - 1] = 0; + + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(s1->inode)->i_orphan_idx, + 2 * ORPHAN_TEST_INODES_PER_OB + + (ORPHAN_TEST_INODES_PER_OB - 1)); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(bdata[ORPHAN_TEST_INODES_PER_OB - 1]), 30U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[2].ob_free_entries), 0); + + /* Now make only block 0 slot (ORPHAN_TEST_INODES_PER_OB - 1) free */ + for (b = 0; b < 3; b++) + atomic_set(&ctx->static_binfo[b].ob_free_entries, 0); + atomic_set(&ctx->static_binfo[0].ob_free_entries, 1); + bdata = (__le32 *)ctx->static_binfo[0].ob_bh->b_data; + for (j = 0; j < ORPHAN_TEST_INODES_PER_OB - 1; j++) + bdata[j] = cpu_to_le32(100 + j); + bdata[ORPHAN_TEST_INODES_PER_OB - 1] = 0; + + err = orphan_test_call_add(&ctx->mock_handle, s2->inode); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(s2->inode)->i_orphan_idx, + ORPHAN_TEST_INODES_PER_OB - 1); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(bdata[ORPHAN_TEST_INODES_PER_OB - 1]), 31U); +} + +static void test_orphan_file_add_enospc_fallback_and_write_err(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s_fb, *s_err, *s_dirty_err; + int err; + + orphan_test_setup_static_orphan_file(ctx, 2); + s_fb = orphan_test_create_inode(test, ctx, 32, S_IFREG | 0644, 0); + s_err = orphan_test_create_inode(test, ctx, 33, S_IFREG | 0644, 0); + s_dirty_err = orphan_test_create_inode(test, ctx, 34, S_IFREG | 0644, 0); + + /* + * 1. Full orphan file (all ob_free_entries == 0): + * ext4_orphan_file_add() returns -ENOSPC, and ext4_orphan_add() + * falls back to the superblock linked list! + */ + atomic_set(&ctx->static_binfo[0].ob_free_entries, 0); + atomic_set(&ctx->static_binfo[1].ob_free_entries, 0); + + err = orphan_test_call_add(&ctx->mock_handle, s_fb->inode); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s_fb->inode, + EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_FALSE(test, list_empty(&EXT4_I(s_fb->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 32U); + + /* + * 2. Non-ENOSPC error (-EIO from ext4_journal_get_write_access): + * must restore ob_free_entries via atomic_inc and return -EIO + * directly WITHOUT falling back to the superblock linked list! + */ + atomic_set(&ctx->static_binfo[0].ob_free_entries, 5); + atomic_set(&ctx->static_binfo[1].ob_free_entries, 0); + orphan_test_reset_faults(ctx); + ctx->fail_write_access_err = -EIO; + ctx->fail_write_access_on_call = 1; + + err = orphan_test_call_add(&ctx->mock_handle, s_err->inode); + + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[0].ob_free_entries), 5); + KUNIT_EXPECT_FALSE(test, ext4_inode_orphan_tracked(s_err->inode)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 32U); + + /* + * 3. Non-ENOSPC error (-EIO from ext4_handle_dirty_metadata): + * propagates -EIO directly without falling back to s_last_orphan. + */ + orphan_test_reset_faults(ctx); + ctx->fail_dirty_metadata_err = -EIO; + ctx->fail_dirty_metadata_on_call = 1; + + err = orphan_test_call_add(&ctx->mock_handle, s_dirty_err->inode); + + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(s_dirty_err->inode, + EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_PTR_EQ(test, ctx->sbi.s_orphan.next, + &EXT4_I(s_fb->inode)->i_orphan); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 32U); +} + +static void test_orphan_file_del_edge_and_error_paths(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1; + __le32 *bdata; + int err; + + orphan_test_setup_static_orphan_file(ctx, 2); + s1 = orphan_test_create_inode(test, ctx, 35, S_IFREG | 0644, 0); + bdata = (__le32 *)ctx->static_binfo[1].ob_bh->b_data; + + /* 1. handle == NULL clears in-core state without touching orphan block */ + bdata[4] = cpu_to_le32(35); + atomic_set(&ctx->static_binfo[1].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB - 1); + EXT4_I(s1->inode)->i_orphan_idx = 1 * ORPHAN_TEST_INODES_PER_OB + 4; + ext4_set_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE); + + err = orphan_test_call_del(NULL, s1->inode); + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata[4]), 35U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[1].ob_free_entries), + (int)(ORPHAN_TEST_INODES_PER_OB - 1)); + + /* 2. Out-of-range blk >= oi->of_blocks hits WARN_ON_ONCE guard safely */ + EXT4_I(s1->inode)->i_orphan_idx = 2 * ORPHAN_TEST_INODES_PER_OB; + ext4_set_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE); + orphan_test_reset_faults(ctx); + + kunit_warning_suppress(test) { + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + } + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); + + /* 3. ext4_journal_get_write_access error leaves bdata[off] intact */ + EXT4_I(s1->inode)->i_orphan_idx = 1 * ORPHAN_TEST_INODES_PER_OB + 4; + ext4_set_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE); + orphan_test_reset_faults(ctx); + ctx->fail_write_access_err = -EIO; + + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata[4]), 35U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[1].ob_free_entries), + (int)(ORPHAN_TEST_INODES_PER_OB - 1)); + + /* 4. ext4_handle_dirty_metadata error propagates after clearing slot */ + EXT4_I(s1->inode)->i_orphan_idx = 1 * ORPHAN_TEST_INODES_PER_OB + 4; + ext4_set_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE); + orphan_test_reset_faults(ctx); + ctx->fail_dirty_metadata_err = -ENOSPC; + + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + + KUNIT_EXPECT_EQ(test, err, -ENOSPC); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata[4]), 0U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[1].ob_free_entries), + (int)ORPHAN_TEST_INODES_PER_OB); +} + +/* ========================================================================= + * 5. Trigger, Init & Release of Orphan File Info + * ========================================================================= + */ + +static void test_orphan_file_block_trigger_and_frozen_data(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct jbd2_buffer_trigger_type *triggers = + &ctx->sbi.s_journal_triggers[EXT4_JTR_ORPHAN_FILE].tr_triggers; + struct buffer_head *bh; + struct ext4_orphan_block_tail *ot; + __le32 *bdata, *fdata; + __u32 expected_csum; + + orphan_test_setup_static_orphan_file(ctx, 1); + bh = ctx->static_binfo[0].ob_bh; + ot = (struct ext4_orphan_block_tail *)(bh->b_data + sb->s_blocksize - + sizeof(*ot)); + bdata = (__le32 *)bh->b_data; + bdata[0] = cpu_to_le32(42); + ot->ob_checksum = 0; + + /* 1. Trigger with data == bh->b_data computes valid block checksum */ + ext4_orphan_file_block_trigger(triggers, bh, bh->b_data, bh->b_size); + expected_csum = orphan_test_calc_ob_csum(sb, ORPHAN_TEST_OF_CSUM_SEED, + bh->b_blocknr, bh->b_data); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ot->ob_checksum), expected_csum); + + /* 2. Trigger with separate JBD2 frozen buffer hashes @data, not bh */ + memset(ctx->frozen_buf, 0, sizeof(ctx->frozen_buf)); + fdata = (__le32 *)ctx->frozen_buf; + fdata[0] = cpu_to_le32(99); + fdata[10] = cpu_to_le32(105); + + ext4_orphan_file_block_trigger(triggers, bh, ctx->frozen_buf, + bh->b_size); + expected_csum = orphan_test_calc_ob_csum(sb, ORPHAN_TEST_OF_CSUM_SEED, + bh->b_blocknr, + ctx->frozen_buf); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ot->ob_checksum), expected_csum); +} + +static void test_init_and_release_orphan_info_lifecycle(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_orphan_info *oi = &ctx->sbi.s_orphan_info; + struct orphan_test_inode_slot *of_slot; + struct ext4_orphan_block_tail *ot; + __le32 *bdata; + int i, err; + + /* 1. Feature disabled: init and release are clean no-ops */ + ext4_clear_feature_orphan_file(sb); + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, oi->of_blocks, 0); + KUNIT_EXPECT_NULL(test, oi->of_binfo); + ext4_release_orphan_info(sb); + + /* 2. Valid 2-block orphan file load and release */ + ext4_set_feature_orphan_file(sb); + of_slot = orphan_test_create_inode(test, ctx, ORPHAN_TEST_ORPHAN_INO, + S_IFREG | 0600, 1); + of_slot->inode->i_size = 2 * ORPHAN_TEST_BLK_SIZE; + EXT4_I(of_slot->inode)->i_csum_seed = ORPHAN_TEST_OF_CSUM_SEED; + + for (i = 0; i < 2; i++) { + struct orphan_test_ob_blk *oblk = &ctx->ob_pool[i]; + + memset(oblk, 0, sizeof(*oblk)); + oblk->present = true; + oblk->bh.b_data = oblk->buf; + oblk->bh.b_size = sb->s_blocksize; + oblk->bh.b_bdev = &ctx->bdev; + oblk->bh.b_blocknr = ORPHAN_TEST_OB_BASE_BLK + i; + atomic_set(&oblk->bh.b_count, 1); + set_buffer_uptodate(&oblk->bh); + } + /* Populate 3 active entries in block 0, 0 entries in block 1 */ + bdata = (__le32 *)ctx->ob_pool[0].buf; + bdata[0] = cpu_to_le32(20); + bdata[5] = cpu_to_le32(21); + bdata[253] = cpu_to_le32(22); + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, + &ctx->ob_pool[0].bh, EXT4_ORPHAN_BLOCK_MAGIC); + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, + &ctx->ob_pool[1].bh, EXT4_ORPHAN_BLOCK_MAGIC); + + err = ext4_init_orphan_info(sb); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->orphan_info_allocated = true; + + KUNIT_EXPECT_EQ(test, oi->of_blocks, 2); + KUNIT_EXPECT_EQ(test, oi->of_csum_seed, ORPHAN_TEST_OF_CSUM_SEED); + KUNIT_ASSERT_NOT_NULL(test, oi->of_binfo); + KUNIT_EXPECT_EQ(test, atomic_read(&oi->of_binfo[0].ob_free_entries), + (int)(ORPHAN_TEST_INODES_PER_OB - 3)); + KUNIT_EXPECT_EQ(test, atomic_read(&oi->of_binfo[1].ob_free_entries), + (int)ORPHAN_TEST_INODES_PER_OB); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 0); + KUNIT_EXPECT_EQ(test, atomic_read(&of_slot->inode->i_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 2); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[1].bh.b_count), 2); + + /* Release drops every block bh reference and frees of_binfo */ + ext4_release_orphan_info(sb); + ctx->orphan_info_allocated = false; + memset(oi, 0, sizeof(*oi)); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[1].bh.b_count), 1); + + /* + * 3. With metadata_csum disabled, ext4_orphan_file_block_csum_verify() + * returns 1 even if ob_checksum does not match. + */ + ext4_clear_feature_metadata_csum(sb); + of_slot->inode->i_size = ORPHAN_TEST_BLK_SIZE; + ot = (struct ext4_orphan_block_tail *)(ctx->ob_pool[0].buf + + sb->s_blocksize - sizeof(*ot)); + ot->ob_checksum = cpu_to_le32(0xdeadbeefU); + + err = ext4_init_orphan_info(sb); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->orphan_info_allocated = true; + + ext4_release_orphan_info(sb); + ctx->orphan_info_allocated = false; + memset(oi, 0, sizeof(*oi)); +} + +static void test_init_orphan_info_max_blocks_boundary(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_orphan_info *oi = &ctx->sbi.s_orphan_info; + struct orphan_test_inode_slot *of_slot; + int err; + + ext4_set_feature_orphan_file(sb); + of_slot = orphan_test_create_inode(test, ctx, ORPHAN_TEST_ORPHAN_INO, + S_IFREG | 0600, 1); + EXT4_I(of_slot->inode)->i_csum_seed = ORPHAN_TEST_OF_CSUM_SEED; + + /* + * 1. Size 1 byte over max(EXT4_MAX_ORPHAN_FILE_BLOCKS << blkbits, 2M) + * (2 MiB = 2048 1 KiB blocks) fails with -EFSCORRUPTED. + */ + of_slot->inode->i_size = (2LL << 20) + 1; + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, atomic_read(&of_slot->inode->i_count), 1); + + /* 2. Exact 2 MiB (2048-block) limit succeeds and releases all bh refs */ + memset(ctx->boundary_buf, 0, sizeof(ctx->boundary_buf)); + ctx->boundary_bh.b_data = ctx->boundary_buf; + ctx->boundary_bh.b_size = sb->s_blocksize; + ctx->boundary_bh.b_bdev = &ctx->bdev; + ctx->boundary_bh.b_blocknr = ORPHAN_TEST_OB_BASE_BLK; + atomic_set(&ctx->boundary_bh.b_count, 1); + set_buffer_uptodate(&ctx->boundary_bh); + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, + &ctx->boundary_bh, EXT4_ORPHAN_BLOCK_MAGIC); + + ctx->use_boundary_bh = true; + of_slot->inode->i_size = 2LL << 20; + + err = ext4_init_orphan_info(sb); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->orphan_info_allocated = true; + KUNIT_EXPECT_EQ(test, oi->of_blocks, 2048); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->boundary_bh.b_count), 2049); + + ext4_release_orphan_info(sb); + ctx->orphan_info_allocated = false; + memset(oi, 0, sizeof(*oi)); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->boundary_bh.b_count), 1); +} + +static void test_init_orphan_info_error_paths_and_cleanup(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_orphan_info *oi = &ctx->sbi.s_orphan_info; + struct orphan_test_inode_slot *of_slot; + struct ext4_orphan_block_tail *ot; + int i, err; + + ext4_set_feature_orphan_file(sb); + + /* 1. ext4_iget failure returns error immediately */ + ctx->fail_iget_err = -ENOENT; + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -ENOENT); + orphan_test_reset_faults(ctx); + + /* Prepare 2-block orphan inode where block 0 loads cleanly */ + of_slot = orphan_test_create_inode(test, ctx, ORPHAN_TEST_ORPHAN_INO, + S_IFREG | 0600, 1); + of_slot->inode->i_size = 2 * ORPHAN_TEST_BLK_SIZE; + EXT4_I(of_slot->inode)->i_csum_seed = ORPHAN_TEST_OF_CSUM_SEED; + + for (i = 0; i < 2; i++) { + struct orphan_test_ob_blk *oblk = &ctx->ob_pool[i]; + + memset(oblk, 0, sizeof(*oblk)); + oblk->present = true; + oblk->bh.b_data = oblk->buf; + oblk->bh.b_size = sb->s_blocksize; + oblk->bh.b_bdev = &ctx->bdev; + oblk->bh.b_blocknr = ORPHAN_TEST_OB_BASE_BLK + i; + atomic_set(&oblk->bh.b_count, 1); + set_buffer_uptodate(&oblk->bh); + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, &oblk->bh, + EXT4_ORPHAN_BLOCK_MAGIC); + } + + /* 2. Block 1 ext4_bread returns ERR_PTR(-EIO) -> block 0 brelse'd */ + ctx->ob_pool[1].bread_err = -EIO; + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&of_slot->inode->i_count), 1); + memset(oi, 0, sizeof(*oi)); + ctx->ob_pool[1].bread_err = 0; + + /* 3. Block 1 ext4_bread returns NULL (unmapped hole) -> -EIO */ + ctx->ob_pool[1].return_hole = true; + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 1); + memset(oi, 0, sizeof(*oi)); + ctx->ob_pool[1].return_hole = false; + + /* 4. Block 1 has invalid ob_magic -> ext4_error + -EIO + brelse */ + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, + &ctx->ob_pool[1].bh, 0xbad0bad0U); + orphan_test_reset_faults(ctx); + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_NE(test, ctx->sbi.s_mount_state & EXT4_ERROR_FS, 0); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[1].bh.b_count), 1); + memset(oi, 0, sizeof(*oi)); + + /* 5. Block 1 has valid magic but corrupted ob_checksum -> -EIO */ + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, + &ctx->ob_pool[1].bh, EXT4_ORPHAN_BLOCK_MAGIC); + ot = (struct ext4_orphan_block_tail *)(ctx->ob_pool[1].buf + + sb->s_blocksize - sizeof(*ot)); + ot->ob_checksum = cpu_to_le32(le32_to_cpu(ot->ob_checksum) ^ 0x1U); + orphan_test_reset_faults(ctx); + + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_NE(test, ctx->sbi.s_mount_state & EXT4_ERROR_FS, 0); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[1].bh.b_count), 1); + memset(oi, 0, sizeof(*oi)); +} + +/* ========================================================================= + * 6. End-to-End Orphan Recovery: ext4_orphan_cleanup() & ext4_process_orphan() + * ========================================================================= + */ + +static void test_orphan_cleanup_skip_guards(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + __le32 saved_ro_compat; + + /* 1. Empty s_last_orphan and empty orphan file -> fast return */ + ctx->es.s_last_orphan = 0; + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + + /* 2. Read-only block device skips orphan cleanup */ + ctx->es.s_last_orphan = cpu_to_le32(15); + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + + /* 3. Unknown ROCOMPAT feature fails ext4_feature_set_ok(sb, 0) */ + saved_ro_compat = ctx->es.s_feature_ro_compat; + ctx->es.s_feature_ro_compat |= cpu_to_le32(0x80000000U); + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + ctx->es.s_feature_ro_compat = saved_ro_compat; + + /* 4a. EXT4_ERROR_FS on SB_RDONLY mount preserves s_last_orphan */ + ctx->sbi.s_mount_state |= EXT4_ERROR_FS; + sb->s_flags |= SB_RDONLY; + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + sb->s_flags &= ~SB_RDONLY; + + /* 4b. EXT4_ERROR_FS on R/W mount clears s_last_orphan to 0 */ + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; +} + +static void +test_orphan_cleanup_linked_list_unlinked_and_truncated(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct orphan_test_inode_slot *s_unlinked, *s_trunc, *s_symlink; + + /* + * Match ext4_fill_super() no-journal recovery state: + * s_journal = NULL, s_mount_state |= EXT4_ORPHAN_FS. + */ + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + set_opt(sb, DEBUG); + + /* + * Build on-disk orphan chain: + * s_last_orphan -> 15 (unlinked reg w/ extent) -> 16 (linked truncate + * w/ extent) -> 17 (unlinked fast symlink) -> 0 + */ + s_unlinked = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s_unlinked->handoff_to_iget = true; + orphan_test_add_single_extent(s_unlinked->inode, 0, 200ULL, 2); + NEXT_ORPHAN(s_unlinked->inode) = 16; + + s_trunc = orphan_test_create_inode(test, ctx, 16, S_IFREG | 0644, 1); + s_trunc->handoff_to_iget = true; + s_trunc->inode->i_size = 0; + EXT4_I(s_trunc->inode)->i_disksize = 2 * ORPHAN_TEST_BLK_SIZE; + orphan_test_add_single_extent(s_trunc->inode, 0, 300ULL, 2); + NEXT_ORPHAN(s_trunc->inode) = 17; + + s_symlink = orphan_test_create_inode(test, ctx, 17, S_IFLNK | 0777, 0); + s_symlink->handoff_to_iget = true; + s_symlink->inode->i_size = 8; + memcpy(EXT4_I(s_symlink->inode)->i_data, "target12", 8); + NEXT_ORPHAN(s_symlink->inode) = 0; + + ctx->es.s_last_orphan = cpu_to_le32(15); + + ext4_orphan_cleanup(sb, &ctx->es); + + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->sbi.s_orphan)); + KUNIT_EXPECT_EQ(test, ctx->nr_freed_inos, 2U); + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 15)); + KUNIT_EXPECT_FALSE(test, orphan_test_was_ino_freed(ctx, 16)); + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 17)); + /* Both s_unlinked (2 blks) and s_trunc (2 blks) freed their extents */ + KUNIT_EXPECT_EQ(test, ctx->total_freed_blks, 4UL); +} + +static void +test_orphan_cleanup_orphan_file_and_rdonly_restore(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct orphan_test_inode_slot *s_list, *s_of_del, *s_of_trunc, *s_of_only; + __le32 *bdata0, *bdata1; + + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + sb->s_flags |= SB_RDONLY; + + orphan_test_setup_static_orphan_file(ctx, 2); + bdata0 = (__le32 *)ctx->static_binfo[0].ob_bh->b_data; + bdata1 = (__le32 *)ctx->static_binfo[1].ob_bh->b_data; + + /* 1. Linked-list unlinked orphan (ino 15) */ + s_list = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s_list->handoff_to_iget = true; + NEXT_ORPHAN(s_list->inode) = 0; + ctx->es.s_last_orphan = cpu_to_le32(15); + + /* + * 2. Orphan file entries: + * - Block 0 slot 2: valid unlinked orphan (ino 16) + * - Block 0 slot 10: unallocated ino 99 -> ext4_orphan_get() fails, + * loop must continue to remaining entries! + * - Block 1 slot 5: valid linked truncate orphan (ino 18) + */ + s_of_del = orphan_test_create_inode(test, ctx, 16, S_IFREG | 0644, 0); + s_of_del->handoff_to_iget = true; + bdata0[2] = cpu_to_le32(16); + bdata0[10] = cpu_to_le32(99); + atomic_set(&ctx->static_binfo[0].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB - 2); + + s_of_trunc = orphan_test_create_inode(test, ctx, 18, S_IFREG | 0644, 1); + s_of_trunc->handoff_to_iget = true; + s_of_trunc->inode->i_size = 0; + orphan_test_add_single_extent(s_of_trunc->inode, 0, 400ULL, 1); + bdata1[5] = cpu_to_le32(18); + atomic_set(&ctx->static_binfo[1].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB - 1); + + ext4_orphan_cleanup(sb, &ctx->es); + + /* SB_RDONLY was cleared during cleanup and restored upon return */ + KUNIT_EXPECT_TRUE(test, ctx->saw_rw_during_cleanup); + KUNIT_EXPECT_NE(test, sb->s_flags & SB_RDONLY, 0UL); + + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 15)); + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 16)); + KUNIT_EXPECT_FALSE(test, orphan_test_was_ino_freed(ctx, 18)); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blks, 1UL); + + /* Valid orphan-file slots were cleared; bad slot 10 was skipped */ + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata0[2]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata0[10]), 99U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata1[5]), 0U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[0].ob_free_entries), + (int)(ORPHAN_TEST_INODES_PER_OB - 1)); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[1].ob_free_entries), + (int)ORPHAN_TEST_INODES_PER_OB); + + /* + * 3. s_last_orphan == 0 with non-empty orphan file: + * must NOT early-return at (!es->s_last_orphan && orphan_file_empty). + */ + bdata0[10] = 0; + atomic_set(&ctx->static_binfo[0].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB); + s_of_only = orphan_test_create_inode(test, ctx, 19, S_IFREG | 0644, 0); + s_of_only->handoff_to_iget = true; + bdata1[8] = cpu_to_le32(19); + atomic_set(&ctx->static_binfo[1].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB - 1); + orphan_test_reset_faults(ctx); + + ext4_orphan_cleanup(sb, &ctx->es); + + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 19)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata1[8]), 0U); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); +} + +static void +test_orphan_cleanup_list_errors_and_truncate_fail(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct orphan_test_inode_slot *s1, *s2; + + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + + /* + * 1. Reserved / invalid orphan ino (< EXT4_FIRST_INO) on s_last_orphan: + * ext4_orphan_get() returns -EFSCORRUPTED, loop clears s_last_orphan + * and breaks cleanly. + */ + ctx->es.s_last_orphan = cpu_to_le32(5); + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + + /* + * 2. ext4_truncate() fails (-EIO) on linked orphan s1 (20), which + * points to s2 (21): + * - ext4_process_orphan() removes s1 from in-core s_orphan via + * ext4_orphan_del(NULL, s1) and sets EXT4_ERROR_FS via + * ext4_std_error(). + * - Next loop iteration detects EXT4_ERROR_FS, clears s_last_orphan, + * and aborts recovery before touching s2 (21). + */ + orphan_test_reset_faults(ctx); + kunit_activate_static_stub(test, ext4_truncate, + orphan_test_truncate_stub); + ctx->stub_truncate_err = -EIO; + + s1 = orphan_test_create_inode(test, ctx, 20, S_IFREG | 0644, 1); + s1->handoff_to_iget = true; + NEXT_ORPHAN(s1->inode) = 21; + + s2 = orphan_test_create_inode(test, ctx, 21, S_IFREG | 0644, 0); + s2->handoff_to_iget = true; + NEXT_ORPHAN(s2->inode) = 0; + + ctx->es.s_last_orphan = cpu_to_le32(20); + + ext4_orphan_cleanup(sb, &ctx->es); + kunit_deactivate_static_stub(test, ext4_truncate); + + KUNIT_EXPECT_EQ(test, ctx->truncate_calls, 1U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->sbi.s_orphan)); + KUNIT_EXPECT_FALSE(test, orphan_test_was_ino_freed(ctx, 21)); + KUNIT_EXPECT_NOT_NULL(test, s2->inode); +} + +#ifdef CONFIG_QUOTA +static void test_orphan_cleanup_quota_paths(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct orphan_test_inode_slot *s1, *s2; + + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + sb->s_flags |= SB_RDONLY; + strscpy(ctx->qf_name, "aquota.user", sizeof(ctx->qf_name)); + + /* + * 1. Exercise journaled quota mount hook (ext4_quota_on_mount) and, + * when CONFIG_QFMT_V2 is also enabled, ext4_enable_quotas() success + * (s_usr_quota_inum == 0 -> quota_update = 1) on SB_RDONLY orphan + * recovery. Hold s_umount to satisfy lockdep in s_qf_names RCU + * dereference (matching mount-time ext4_fill_super context). + */ + rcu_assign_pointer(ctx->sbi.s_qf_names[USRQUOTA], ctx->qf_name); +#if IS_ENABLED(CONFIG_QFMT_V2) + ext4_set_feature_quota(sb); + ctx->es.s_usr_quota_inum = 0; +#endif + + s1 = orphan_test_create_inode(test, ctx, 28, S_IFREG | 0644, 0); + s1->handoff_to_iget = true; + NEXT_ORPHAN(s1->inode) = 0; + ctx->es.s_last_orphan = cpu_to_le32(28); + + down_write(&sb->s_umount); + ext4_orphan_cleanup(sb, &ctx->es); + rcu_assign_pointer(ctx->sbi.s_qf_names[USRQUOTA], NULL); + up_write(&sb->s_umount); + + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 28)); + KUNIT_EXPECT_NE(test, sb->s_flags & SB_RDONLY, 0UL); + +#if IS_ENABLED(CONFIG_QFMT_V2) + /* + * 2. Exercise ext4_enable_quotas() failure path: missing quota inode 3 + * triggers ext4_error() (setting EXT4_ERROR_FS), logs the quota + * turn-on error, aborts s_last_orphan recovery while clearing + * s_last_orphan to 0, and still restores SB_RDONLY. + */ + orphan_test_reset_faults(ctx); + ctx->es.s_usr_quota_inum = cpu_to_le32(EXT4_USR_QUOTA_INO); + s2 = orphan_test_create_inode(test, ctx, 29, S_IFREG | 0644, 0); + s2->handoff_to_iget = true; + NEXT_ORPHAN(s2->inode) = 0; + ctx->es.s_last_orphan = cpu_to_le32(29); + + down_write(&sb->s_umount); + ext4_orphan_cleanup(sb, &ctx->es); + up_write(&sb->s_umount); + + KUNIT_EXPECT_NE(test, ctx->sbi.s_mount_state & EXT4_ERROR_FS, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_FALSE(test, orphan_test_was_ino_freed(ctx, 29)); + KUNIT_EXPECT_NE(test, sb->s_flags & SB_RDONLY, 0UL); +#else + (void)s2; +#endif +} +#endif + +static struct kunit_case orphan_test_cases[] = { + KUNIT_CASE_PARAM(test_inodes_per_orphan_block_param, + orphan_blksize_gen_params), + KUNIT_CASE(test_orphan_file_empty), + KUNIT_CASE(test_orphan_add_early_exits_and_idempotency), + KUNIT_CASE(test_orphan_add_list_chaining_and_csum), + KUNIT_CASE(test_orphan_add_next_orphan_bounds), + KUNIT_CASE(test_orphan_add_list_error_paths), + KUNIT_CASE(test_orphan_del_early_exits), + KUNIT_CASE(test_orphan_del_list_positions_and_null_handle), + KUNIT_CASE(test_orphan_del_list_error_paths), + KUNIT_CASE(test_orphan_file_add_and_del_basic), + KUNIT_CASE(test_orphan_file_add_block_wraparound_and_last_slot), + KUNIT_CASE(test_orphan_file_add_enospc_fallback_and_write_err), + KUNIT_CASE(test_orphan_file_del_edge_and_error_paths), + KUNIT_CASE(test_orphan_file_block_trigger_and_frozen_data), + KUNIT_CASE(test_init_and_release_orphan_info_lifecycle), + KUNIT_CASE(test_init_orphan_info_max_blocks_boundary), + KUNIT_CASE(test_init_orphan_info_error_paths_and_cleanup), + KUNIT_CASE(test_orphan_cleanup_skip_guards), + KUNIT_CASE(test_orphan_cleanup_linked_list_unlinked_and_truncated), + KUNIT_CASE(test_orphan_cleanup_orphan_file_and_rdonly_restore), + KUNIT_CASE(test_orphan_cleanup_list_errors_and_truncate_fail), +#ifdef CONFIG_QUOTA + KUNIT_CASE(test_orphan_cleanup_quota_paths), +#endif + {} +}; + +static struct kunit_suite orphan_test_suite = { + .name = "ext4_orphan_test", + .init = orphan_test_init, + .test_cases = orphan_test_cases, +}; + +kunit_test_suites(&orphan_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 orphan inode handling"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/orphan.c b/fs/ext4/orphan.c index e04e90039fef2a..847eca2d866a1e 100644 --- a/fs/ext4/orphan.c +++ b/fs/ext4/orphan.c @@ -511,6 +511,7 @@ void ext4_orphan_cleanup(struct super_block *sb, struct ext4_super_block *es) #endif sb->s_flags = s_flags; /* Restore SB_RDONLY status */ } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_cleanup); void ext4_release_orphan_info(struct super_block *sb) { @@ -523,6 +524,7 @@ void ext4_release_orphan_info(struct super_block *sb) brelse(oi->of_binfo[i].ob_bh); kvfree(oi->of_binfo); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_release_orphan_info); static struct ext4_orphan_block_tail *ext4_orphan_block_tail( struct super_block *sb, @@ -570,6 +572,7 @@ void ext4_orphan_file_block_trigger(struct jbd2_buffer_trigger_type *triggers, ot = ext4_orphan_block_tail(sb, bh); ot->ob_checksum = cpu_to_le32(csum); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_file_block_trigger); int ext4_init_orphan_info(struct super_block *sb) { @@ -658,6 +661,7 @@ int ext4_init_orphan_info(struct super_block *sb) iput(inode); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_orphan_info); int ext4_orphan_file_empty(struct super_block *sb) { @@ -673,3 +677,4 @@ int ext4_orphan_file_empty(struct super_block *sb) return 0; return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_file_empty); diff --git a/fs/ext4/super.c b/fs/ext4/super.c index 0768ba540637c0..d03d5dd8d6eb00 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -355,6 +355,7 @@ void ext4_superblock_csum_set(struct super_block *sb) es->s_checksum = ext4_superblock_csum(es); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_superblock_csum_set); ext4_fsblk_t ext4_block_bitmap(struct super_block *sb, struct ext4_group_desc *bg) From 05f2b6927ab5511f43cce8564ce799d87544033f Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Fri, 6 Nov 2026 16:01:20 +0000 Subject: [PATCH 1564/2102] ext4: add KUnit tests for fs/ext4/block_validity.c Add the ext4_block_validity_test KUnit test suite in fs/ext4/block_validity-test.c (16 test cases, 40 subtests total) to comprehensively exercise system-zone rbtree construction, RCU release, block range validation, reserved journal inode protection, and indirect block reference checking in fs/ext4/block_validity.c using an in-memory VFS superblock and mock block device without requiring a mounted disk: - Bounds and 64-bit overflow checks (ext4_sb_block_valid and ext4_inode_block_valid) across 1KiB (s_first_data_block = 1) and 4KiB (s_first_data_block = 0) geometries, exact end-of-filesystem single and multi-block spans, 64-bit u64 addition wrap-around, >32-bit block counts under EXT4_FEATURE_INCOMPAT_64BIT, and high-32-bit masking when 64bit is cleared. - System-zone lifecycle management (ext4_setup_system_zone and ext4_release_system_zone), covering pre-setup NULL behavior, RCU publication and teardown, and idempotent double-release handling. - Multi-group sparse_super and flex_bg layouts (including groups with zero base metadata blocks and relocated bitmaps/inode tables) as well as DEBUG mount-option tree printing (debug_print_tree). - System-zone rbtree merging (add_system_zone and can_merge) across left-neighbor merges, right-neighbor merges, 3-way bridge merges, and 64-bit (>2^32) group descriptor metadata zones, plus parameterized interval-overlap geometries (adjacent, single-block, boundary straddling, interior, exact, and enclosing spans). - Corrupt overlapping group metadata detection (-EFSCORRUPTED) across block bitmap, inode bitmap, inode table, and cross-group collisions, verifying partial rbtree cleanup without publishing s_system_blks. - Reserved journal inode protection (ext4_protect_reserved_inode), verifying non-block-aligned i_size rounding, multi-extent and sparse hole mapping, journal-inode ownership vs. regular/NULL inode rejection, can_merge() isolation between adjacent ino=0 and journal zones, disabled-feature/zero-inum/empty-inode skips, and -EINVAL, ext4_iget, ext4_map_blocks, and metadata-overlap (-EFSCORRUPTED + EXT4_ERROR_FS) failure paths. - Block reference array validation (ext4_check_blockref, ext4_ind_check_inode, and ext4_check_indirect_blockref) across empty and sparse arrays, metadata and out-of-bounds corruption reporting, active journal inode (s_journal->j_inode) bypass, and integration with ext4_map_blocks() block validity checks. Export the five runtime entry points in fs/ext4/block_validity.c with EXPORT_SYMBOL_FOR_EXT4_TEST for the ext4-test KUnit module. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 3 +- fs/ext4/block_validity-test.c | 1520 +++++++++++++++++++++++++++++++++ fs/ext4/block_validity.c | 6 + 3 files changed, 1528 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/block_validity-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 9bad2bff0de969..5c6afff5f12ac6 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -19,7 +19,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ extents_status-test.o xattr-test.o \ namei-test.o inline-test.o \ fast_commit-test.o ialloc-test.o \ - balloc-test.o orphan-test.o + balloc-test.o orphan-test.o \ + block_validity-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/block_validity-test.c b/fs/ext4/block_validity-test.c new file mode 100644 index 00000000000000..f7667099ac6ca5 --- /dev/null +++ b/fs/ext4/block_validity-test.c @@ -0,0 +1,1520 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/block_validity.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_extents.h" +#include "ext4_jbd2.h" +#include "xattr.h" + +/* + * Default mock filesystem geometry: + * - 4 block groups, 1024-byte blocks, s_first_data_block = 1 + * - 1024 blocks per group -> total blocks = 4097 (valid blocks 0..4096) + * - sparse_super enabled, s_gdb_count = 1, s_reserved_gdt_blocks = 2: + * group 0 (blocks 1..1024): 4 base meta blocks (1..4) + * group 1 (blocks 1025..2048): 4 base meta blocks (1025..1028) + * group 2 (blocks 2049..3072): 0 base meta blocks (sparse_super) + * group 3 (blocks 3073..4096): 4 base meta blocks (3073..3076) + * - 32 inodes per group (128 total), 256-byte inodes -> 8 inode table + * blocks per group + */ +#define BV_TEST_NGROUPS 4U +#define BV_TEST_BLK_SIZE 1024U +#define BV_TEST_BLK_BITS 10U +#define BV_TEST_BLOCKS_PER_GRP 1024U +#define BV_TEST_FIRST_DATA_BLK 1U +#define BV_TEST_TOTAL_BLKS (BV_TEST_FIRST_DATA_BLK + \ + BV_TEST_NGROUPS * \ + BV_TEST_BLOCKS_PER_GRP) +#define BV_TEST_INODE_SIZE 256U +#define BV_TEST_EXTRA_ISIZE 32U +#define BV_TEST_INODES_PER_BLK (BV_TEST_BLK_SIZE / BV_TEST_INODE_SIZE) +#define BV_TEST_INODES_PER_GRP 32U +#define BV_TEST_ITB_PER_GRP (BV_TEST_INODES_PER_GRP / \ + BV_TEST_INODES_PER_BLK) +#define BV_TEST_TOTAL_INODES (BV_TEST_NGROUPS * \ + BV_TEST_INODES_PER_GRP) +#define BV_TEST_FIRST_INO 11U +#define BV_TEST_GDB_COUNT 1U +#define BV_TEST_RSV_GDT_BLKS 2U +#define BV_TEST_GDESC_BLK 2ULL +#define BV_TEST_MAX_SLOTS 8U + +struct bv_test_inode_slot { + bool in_use; + unsigned long ino; + struct inode *inode; +}; + +struct bv_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + struct buffer_head gdesc_bh; + char gdesc_buf[BV_TEST_BLK_SIZE] __aligned(8); + char ind_buf[BV_TEST_BLK_SIZE] __aligned(8); + + struct ext4_group_desc gdps[BV_TEST_NGROUPS]; + journal_t mock_journal; + + struct bv_test_inode_slot slots[BV_TEST_MAX_SLOTS]; + + /* Fault injection and call tracking */ + int fail_iget_err; + unsigned int iget_calls; + ext4_iget_flags last_iget_flags; + + int fail_map_err; + unsigned int fail_map_on_call; + unsigned int map_calls; +}; + +static inline ext4_fsblk_t bv_group_first_blk(ext4_group_t g) +{ + return BV_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * BV_TEST_BLOCKS_PER_GRP; +} + +/* + * Number of base metadata blocks in group @g under the default 4-group + * sparse_super configuration (groups 0, 1, 3 have super + 1 gdb + 2 rsv_gdt; + * group 2 has 0). + */ +static inline unsigned int bv_default_base_meta(ext4_group_t g) +{ + if (g == 2) + return 0; + return 1U + BV_TEST_GDB_COUNT + BV_TEST_RSV_GDT_BLKS; +} + +static inline ext4_fsblk_t bv_default_bbitmap_blk(ext4_group_t g) +{ + return bv_group_first_blk(g) + bv_default_base_meta(g); +} + +static inline ext4_fsblk_t bv_default_ibitmap_blk(ext4_group_t g) +{ + return bv_default_bbitmap_blk(g) + 1ULL; +} + +static inline ext4_fsblk_t bv_default_itable_blk(ext4_group_t g) +{ + return bv_default_ibitmap_blk(g) + 1ULL; +} + +static inline ext4_fsblk_t bv_default_first_free_blk(ext4_group_t g) +{ + return bv_default_itable_blk(g) + BV_TEST_ITB_PER_GRP; +} + +static void bv_test_sb_upd_work(struct work_struct *work) +{ +} + +static void bv_test_err_timer(struct timer_list *t) +{ +} + +static unsigned long bv_dummy_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long bv_dummy_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +static void bv_test_init_ei_fields(struct ext4_inode_info *ei) +{ + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_flags = 0; + ext4_clear_state_flags(ei); + spin_lock_init(&ei->i_raw_lock); + ei->i_prealloc_node = RB_ROOT; + atomic_set(&ei->i_prealloc_active, 0); + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + ei->i_es_all_nr = 0; + ei->i_es_shk_nr = 0; + ei->i_es_shrink_lblk = 0; + ei->i_es_seq = 0; + ei->i_reserved_data_blocks = 0; + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); +#ifdef CONFIG_QUOTA + ei->i_reserved_quota = 0; + memset(&ei->i_dquot, 0, sizeof(ei->i_dquot)); +#endif +#ifdef CONFIG_FS_ENCRYPTION + ei->i_crypt_info = NULL; +#endif + ei->jinode = NULL; + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + ei->i_sync_tid = 0; + ei->i_datasync_tid = 0; + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_metadata_bhs = NULL; + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = BV_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; +} + +static struct inode *bv_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + bv_test_init_ei_fields(ei); + return &ei->vfs_inode; +} + +static void bv_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + ext4_clear_inode(inode); +} + +static void bv_test_destroy_inode(struct inode *inode) +{ + kfree(ext4_i_metadata_bhs(inode)); + EXT4_I(inode)->i_metadata_bhs = NULL; +} + +static void bv_test_free_inode_mem(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static const struct super_operations bv_test_sops = { + .alloc_inode = bv_test_alloc_inode, + .evict_inode = bv_test_evict_inode, + .destroy_inode = bv_test_destroy_inode, + .free_inode = bv_test_free_inode_mem, + .drop_inode = inode_just_drop, +}; + +static int bv_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type bv_test_fs_type = { + .name = "ext4_bv_kunit", + .init_fs_context = bv_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +/* --- Helpers & Static Stubs --- */ + +static void bv_release_system_zone_locked(struct super_block *sb) +{ + down_write(&sb->s_umount); + ext4_release_system_zone(sb); + up_write(&sb->s_umount); +} + +static struct bv_test_inode_slot * +bv_find_slot(struct bv_test_ctx *ctx, unsigned long ino) +{ + unsigned int i; + + for (i = 0; i < BV_TEST_MAX_SLOTS; i++) { + if (ctx->slots[i].in_use && ctx->slots[i].ino == ino) + return &ctx->slots[i]; + } + return NULL; +} + +static struct inode *bv_create_inode(struct kunit *test, + struct bv_test_ctx *ctx, + unsigned long ino, umode_t mode, + bool use_extents) +{ + struct bv_test_inode_slot *slot = NULL; + struct ext4_extent_header *eh; + struct inode *inode; + unsigned int i; + + for (i = 0; i < BV_TEST_MAX_SLOTS; i++) { + if (!ctx->slots[i].in_use) { + slot = &ctx->slots[i]; + break; + } + } + KUNIT_ASSERT_NOT_NULL(test, slot); + + inode = new_inode(ctx->sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + + slot->in_use = true; + slot->ino = ino; + slot->inode = inode; + + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = ctx->sb->s_blocksize_bits; + inode->i_flags |= S_NOQUOTA; + set_nlink(inode, 1); + EXT4_I(inode)->i_block_group = (ino - 1) / BV_TEST_INODES_PER_GRP; + memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data)); + + if (use_extents) { + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + eh = ext_inode_hdr(inode); + eh->eh_magic = EXT4_EXT_MAGIC; + eh->eh_entries = 0; + eh->eh_max = cpu_to_le16((sizeof(EXT4_I(inode)->i_data) - + sizeof(*eh)) / + sizeof(struct ext4_extent)); + eh->eh_depth = 0; + } + + return inode; +} + +static void bv_append_extent(struct kunit *test, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + unsigned short len) +{ + struct ext4_extent_header *eh = ext_inode_hdr(inode); + u16 entries = le16_to_cpu(eh->eh_entries); + struct ext4_extent *ex; + + KUNIT_ASSERT_LT(test, entries, le16_to_cpu(eh->eh_max)); + ex = EXT_FIRST_EXTENT(eh) + entries; + ex->ee_block = cpu_to_le32(lblk); + ex->ee_len = cpu_to_le16(len); + ext4_ext_store_pblock(ex, pblk); + eh->eh_entries = cpu_to_le16(entries + 1); +} + +static void bv_set_group_meta(struct super_block *sb, + struct ext4_group_desc *gdp, + ext4_fsblk_t bbitmap, ext4_fsblk_t ibitmap, + ext4_fsblk_t itable) +{ + ext4_block_bitmap_set(sb, gdp, bbitmap); + ext4_inode_bitmap_set(sb, gdp, ibitmap); + ext4_inode_table_set(sb, gdp, itable); +} + +static void bv_clear_fs_error(struct bv_test_ctx *ctx) +{ + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + ctx->es.s_last_error_block = 0; + ctx->es.s_last_error_ino = 0; + ctx->es.s_last_error_errcode = 0; +} + +static struct ext4_group_desc * +bv_get_group_desc_stub(struct super_block *sb, ext4_group_t block_group, + struct buffer_head **bh) +{ + struct kunit *test = kunit_get_current_test(); + struct bv_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx || block_group >= BV_TEST_NGROUPS) + return NULL; + if (bh) + *bh = &ctx->gdesc_bh; + return &ctx->gdps[block_group]; +} + +static struct inode *bv_iget_stub(struct super_block *sb, unsigned long ino, + ext4_iget_flags flags, const char *function, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct bv_test_ctx *ctx = test ? test->priv : NULL; + struct bv_test_inode_slot *slot; + + if (!ctx) + return ERR_PTR(-EIO); + + ctx->iget_calls++; + ctx->last_iget_flags = flags; + if (ctx->fail_iget_err) + return ERR_PTR(ctx->fail_iget_err); + + slot = bv_find_slot(ctx, ino); + if (!slot || !slot->inode) + return ERR_PTR(-ENOENT); + + ihold(slot->inode); + return slot->inode; +} + +static int bv_map_blocks_fault_stub(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct bv_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + + ctx->map_calls++; + if (ctx->fail_map_err && + (!ctx->fail_map_on_call || + ctx->map_calls == ctx->fail_map_on_call)) + return ctx->fail_map_err; + + map->m_pblk = bv_default_first_free_blk(0) + map->m_lblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED; + return 1; +} + +/* --- Fixture Setup & Teardown --- */ + +static void bv_test_cleanup(struct bv_test_ctx *ctx) +{ + unsigned int i; + + ctx->sbi.s_journal = NULL; + bv_release_system_zone_locked(ctx->sb); + + for (i = 0; i < BV_TEST_MAX_SLOTS; i++) { + struct inode *inode = ctx->slots[i].inode; + + if (!inode) + continue; + spin_lock(&inode->i_lock); + inode_state_clear(inode, I_DIRTY_TIME | I_NEW); + spin_unlock(&inode->i_lock); + set_nlink(inode, 1); + iput(inode); + ctx->slots[i].inode = NULL; + ctx->slots[i].in_use = false; + } + + deactivate_super(ctx->sb); + ext4_es_unregister_shrinker(&ctx->sbi); + ext4_es_destroy_stats(&ctx->sbi); + rcu_barrier(); + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(bv_test_cleanup_action, bv_test_cleanup, + struct bv_test_ctx *); + +static int bv_test_init(struct kunit *test) +{ + struct bv_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + ext4_group_t g; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + if (!ctx->bdev.bd_stats) { + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bd_stats"); + } + + fc = fs_context_for_mount(&bv_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &bv_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = BV_TEST_BLK_SIZE; + sb->s_blocksize_bits = BV_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_bv_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = BV_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(BV_TEST_FIRST_DATA_BLK); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + ctx->es.s_inodes_count = cpu_to_le32(BV_TEST_TOTAL_INODES); + ctx->es.s_inodes_per_group = cpu_to_le32(BV_TEST_INODES_PER_GRP); + ctx->es.s_blocks_per_group = cpu_to_le32(BV_TEST_BLOCKS_PER_GRP); + ctx->es.s_clusters_per_group = cpu_to_le32(BV_TEST_BLOCKS_PER_GRP); + ctx->es.s_first_ino = cpu_to_le32(BV_TEST_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(BV_TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(BV_TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(BV_TEST_EXTRA_ISIZE); + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(BV_TEST_RSV_GDT_BLKS); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_blocks_count_set(&ctx->es, BV_TEST_TOTAL_BLKS); + + ext4_set_feature_sparse_super(sb); + ext4_set_feature_extents(sb); + ext4_set_feature_extra_isize(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + ctx->gdesc_bh.b_data = ctx->gdesc_buf; + ctx->gdesc_bh.b_size = BV_TEST_BLK_SIZE; + ctx->gdesc_bh.b_blocknr = BV_TEST_GDESC_BLK; + ctx->gdesc_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->gdesc_bh.b_count, 1); + set_buffer_uptodate(&ctx->gdesc_bh); + + sbi->s_inode_size = BV_TEST_INODE_SIZE; + sbi->s_inodes_per_block = BV_TEST_INODES_PER_BLK; + sbi->s_inodes_per_group = BV_TEST_INODES_PER_GRP; + sbi->s_itb_per_group = BV_TEST_ITB_PER_GRP; + sbi->s_first_ino = BV_TEST_FIRST_INO; + sbi->s_want_extra_isize = BV_TEST_EXTRA_ISIZE; + sbi->s_blocks_per_group = BV_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = BV_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = BV_TEST_NGROUPS; + sbi->s_gdb_count = BV_TEST_GDB_COUNT; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = BV_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_bitmap_maxbytes = 0x1ff7ffff000ULL; + + mutex_init(&sbi->s_orphan_lock); + INIT_LIST_HEAD(&sbi->s_orphan); + set_opt(sb, ERRORS_CONT); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + INIT_WORK(&sbi->s_sb_upd_work, bv_test_sb_upd_work); + timer_setup(&sbi->s_err_report, bv_test_err_timer, 0); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + for (g = 0; g < BV_TEST_NGROUPS; g++) { + bv_set_group_meta(sb, &ctx->gdps[g], + bv_default_bbitmap_blk(g), + bv_default_ibitmap_blk(g), + bv_default_itable_blk(g)); + } + + err = ext4_es_register_shrinker(sbi); + if (err) { + deactivate_locked_super(sb); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + WRITE_ONCE(sbi->s_es_shrinker->count_objects, bv_dummy_shrinker_count); + WRITE_ONCE(sbi->s_es_shrinker->scan_objects, bv_dummy_shrinker_scan); + + root_inode = new_inode(sb); + if (!root_inode) { + deactivate_locked_super(sb); + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc root_inode"); + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + deactivate_locked_super(sb); + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to create s_root"); + } + + up_write(&sb->s_umount); + + kunit_activate_static_stub(test, ext4_get_group_desc, + bv_get_group_desc_stub); + kunit_activate_static_stub(test, __ext4_iget, bv_iget_stub); + + err = kunit_add_action_or_reset(test, bv_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + return 0; +} + +/* --- Parameterized Test 1: Bounds & 64-bit Overflow Checks --- */ + +struct bv_bounds_case { + const char *desc; + u32 first_data_blk; + ext4_fsblk_t total_blks; + bool enable_64bit; + ext4_fsblk_t start_blk; + unsigned int count; + int expected; +}; + +static const struct bv_bounds_case bv_bounds_cases[] = { + { + .desc = "1k_block_0_below_first_data", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 0, + .count = 1, + .expected = 0, + }, + { + .desc = "1k_block_1_equals_first_data", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 1, + .count = 1, + .expected = 0, + }, + { + .desc = "1k_block_2_just_above_first_data", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 2, + .count = 1, + .expected = 1, + }, + { + .desc = "4k_block_0_equals_first_data", + .first_data_blk = 0, + .total_blks = 4096, + .enable_64bit = true, + .start_blk = 0, + .count = 1, + .expected = 0, + }, + { + .desc = "4k_block_1_just_above_first_data", + .first_data_blk = 0, + .total_blks = 4096, + .enable_64bit = true, + .start_blk = 1, + .count = 1, + .expected = 1, + }, + { + .desc = "exact_last_single_block", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 4096, + .count = 1, + .expected = 1, + }, + { + .desc = "multiblock_ending_at_last_block", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 4093, + .count = 4, + .expected = 1, + }, + { + .desc = "multiblock_exceeding_end_by_one", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 4093, + .count = 5, + .expected = 0, + }, + { + .desc = "start_at_blocks_count", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 4097, + .count = 1, + .expected = 0, + }, + { + .desc = "u64_wrap_around_into_in_bounds_value", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = U64_MAX - 3ULL, + .count = 10, + .expected = 0, + }, + { + .desc = "u64_max_single_block_overflow", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = U64_MAX, + .count = 1, + .expected = 0, + }, + { + .desc = "64bit_high_block_at_exact_end", + .first_data_blk = 0, + .total_blks = (1ULL << 33) + 64ULL, + .enable_64bit = true, + .start_blk = (1ULL << 33) + 60ULL, + .count = 4, + .expected = 1, + }, + { + .desc = "32bit_fs_ignores_high_blocks_count", + .first_data_blk = 0, + .total_blks = (1ULL << 33) + 4096ULL, + .enable_64bit = false, + .start_blk = (1ULL << 33) + 10ULL, + .count = 1, + .expected = 0, + }, +}; + +KUNIT_ARRAY_PARAM_DESC(bv_bounds, bv_bounds_cases, desc); + +static void test_sb_block_valid_bounds(struct kunit *test) +{ + const struct bv_bounds_case *tc = test->param_value; + struct bv_test_ctx *ctx = test->priv; + struct inode *inode; + + ctx->es.s_first_data_block = cpu_to_le32(tc->first_data_blk); + ext4_blocks_count_set(&ctx->es, tc->total_blks); + if (tc->enable_64bit) + ext4_set_feature_64bit(ctx->sb); + else + ext4_clear_feature_64bit(ctx->sb); + + inode = bv_create_inode(test, ctx, 12, S_IFREG | 0644, true); + + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, tc->start_blk, + tc->count), + tc->expected); + KUNIT_EXPECT_EQ(test, + ext4_inode_block_valid(inode, tc->start_blk, tc->count), + tc->expected); +} + +/* --- Test 2: Setup and Release Lifecycle (noblock_validity / RCU) --- */ + +static void test_release_system_zone_lifecycle(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + ext4_fsblk_t meta_blk = bv_default_bbitmap_blk(0); + ext4_fsblk_t data_blk = bv_default_first_free_blk(0); + + /* + * Before ext4_setup_system_zone(), s_system_blks is NULL: releasing is + * a safe no-op and metadata block numbers pass validity as long as + * they are within (s_first_data_block, blocks_count]. + */ + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); + bv_release_system_zone_locked(ctx->sb); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, meta_blk, 1), + 1); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, + BV_TEST_FIRST_DATA_BLK, 1), + 0); + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + KUNIT_EXPECT_NOT_NULL(test, + rcu_access_pointer(ctx->sbi.s_system_blks)); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, meta_blk, 1), + 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, data_blk, 1), + 1); + + /* + * Releasing clears s_system_blks immediately and frees the rbtree via + * RCU; repeating release when already NULL remains a safe no-op. + */ + bv_release_system_zone_locked(ctx->sb); + rcu_barrier(); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, meta_blk, 1), + 1); + + bv_release_system_zone_locked(ctx->sb); +} + +/* --- Test 3: Multi-group sparse_super, flex_bg, and DEBUG Tree Print --- */ + +static void test_setup_multigroup_sparse_super_and_flex_bg(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + ext4_fsblk_t g2_bbitmap = 20ULL; + ext4_fsblk_t g2_ibitmap = 22ULL; + ext4_fsblk_t g2_itable = 30ULL; + + /* + * Relocate group 2's bitmaps and inode table into group 0 (flex_bg + * layout). Since group 2 also has 0 base metadata blocks under + * sparse_super, every block in group 2 (2049..3072) becomes valid for + * data, while group 0 gains three separated system zones. + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[2], g2_bbitmap, g2_ibitmap, + g2_itable); + set_opt(ctx->sb, DEBUG); + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + + /* Group 0 contiguous metadata [1..14] rejected; gap [15..19] valid */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 14, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 15, 5), 1); + + /* Relocated group 2 metadata inside group 0 and surrounding gaps */ + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, g2_bbitmap, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 21, 1), 1); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, g2_ibitmap, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 23, 7), 1); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, g2_itable, 1), 0); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, + g2_itable + BV_TEST_ITB_PER_GRP - 1, + 1), + 0); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, + g2_itable + BV_TEST_ITB_PER_GRP, + 10), + 1); + + /* Group 1 [1025..1038] protected, 1024 and 1039 valid */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 1024, 1), 1); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 1025, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 1038, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 1039, 1), 1); + + /* Group 2 [2049..3072] has zero metadata blocks at all */ + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(ctx->sb, 2), 0U); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, + bv_group_first_blk(2), + BV_TEST_BLOCKS_PER_GRP), + 1); + + /* Group 3 (backup superblock 3^1): [3073..3086] protected, 3087+ ok */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 3073, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 3086, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 3087, 10), 1); +} + +/* --- Test 4: Left, Right, and 3-Way Bridge Merging (+ 64-bit Zones) --- */ + +static void test_rbtree_left_right_and_bridge_merges(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + ext4_fsblk_t hi_base = (1ULL << 33) + 100ULL; + + ext4_blocks_count_set(&ctx->es, hi_base + 512ULL); + + /* + * Group 0: base_meta = [1..4], bbitmap = 5 (merges left -> [1..5]), + * ibitmap = 14 (standalone [14..14]), itable = [6..13] (bridges + * [1..5] on the left AND [14..14] on the right into [1..14]). + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[0], 5ULL, 14ULL, 6ULL); + + /* + * Group 2 (0 base meta): bbitmap = 2100, ibitmap = 2099 (inserted left + * of 2100 and merges right into [2099..2100]), itable = [2110..2117]. + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[2], 2100ULL, 2099ULL, 2110ULL); + + /* + * Group 3: relocate bbitmap/ibitmap/itable above 2^32 to exercise + * 64-bit group descriptor blocks and 3-way merge above 4G blocks: + * bbitmap = hi_base, ibitmap = hi_base + 9, itable = hi_base + 1..8 + * -> merged 10-block 64-bit zone [hi_base .. hi_base + 9]. + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[3], hi_base, hi_base + 9ULL, + hi_base + 1ULL); + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + + /* Group 0 bridged zone [1..14] */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 5, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 6, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 13, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 14, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 15, 1), 1); + + /* Group 2 right-merged zone [2099..2100] and separate [2110..2117] */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2098, 1), 1); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2099, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2100, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2101, 9), 1); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2110, 8), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2118, 1), 1); + + /* Group 3 64-bit bridged zone [hi_base .. hi_base + 9] */ + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, hi_base - 1ULL, 1), + 1); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, hi_base, 1), + 0); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, hi_base + 5ULL, 1), + 0); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, hi_base + 9ULL, 1), + 0); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, hi_base + 10ULL, 4), + 1); +} + +/* --- Parameterized Test 5: Interval Overlap Geometries --- */ + +/* + * Tests against an isolated 8-block system zone [50, 58) (blocks 50..57) + * surrounded by valid data blocks on both sides. + */ +struct bv_overlap_case { + const char *desc; + ext4_fsblk_t start_blk; + unsigned int count; + int expected; +}; + +static const struct bv_overlap_case bv_overlap_cases[] = { + { + .desc = "strictly_before_adjacent", + .start_blk = 46, + .count = 4, + .expected = 1, + }, + { + .desc = "strictly_after_adjacent", + .start_blk = 58, + .count = 4, + .expected = 1, + }, + { + .desc = "single_first_block_of_zone", + .start_blk = 50, + .count = 1, + .expected = 0, + }, + { + .desc = "single_interior_block_of_zone", + .start_blk = 54, + .count = 1, + .expected = 0, + }, + { + .desc = "single_last_block_of_zone", + .start_blk = 57, + .count = 1, + .expected = 0, + }, + { + .desc = "straddle_left_boundary_by_one", + .start_blk = 47, + .count = 4, + .expected = 0, + }, + { + .desc = "straddle_right_boundary_by_one", + .start_blk = 57, + .count = 4, + .expected = 0, + }, + { + .desc = "strictly_inside_zone", + .start_blk = 52, + .count = 3, + .expected = 0, + }, + { + .desc = "exact_zone_span", + .start_blk = 50, + .count = 8, + .expected = 0, + }, + { + .desc = "strictly_enclosing_entire_zone", + .start_blk = 45, + .count = 20, + .expected = 0, + }, +}; + +KUNIT_ARRAY_PARAM_DESC(bv_overlap, bv_overlap_cases, desc); + +static void test_sb_block_valid_interval_overlaps(struct kunit *test) +{ + const struct bv_overlap_case *tc = test->param_value; + struct bv_test_ctx *ctx = test->priv; + struct inode *inode; + + /* Place group 2's 8-block inode table at [50..57] */ + bv_set_group_meta(ctx->sb, &ctx->gdps[2], 2049ULL, 2050ULL, 50ULL); + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + + inode = bv_create_inode(test, ctx, 13, S_IFREG | 0644, true); + + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, tc->start_blk, + tc->count), + tc->expected); + KUNIT_EXPECT_EQ(test, + ext4_inode_block_valid(inode, tc->start_blk, tc->count), + tc->expected); +} + +/* --- Parameterized Test 6: Corrupt Overlapping Group Metadata --- */ + +struct bv_corrupt_meta_case { + const char *desc; + ext4_group_t grp; + ext4_fsblk_t bbitmap; + ext4_fsblk_t ibitmap; + ext4_fsblk_t itable; +}; + +static const struct bv_corrupt_meta_case bv_corrupt_meta_cases[] = { + { + .desc = "bbitmap_overlaps_group0_base_meta", + .grp = 0, + .bbitmap = 2, + .ibitmap = 6, + .itable = 7, + }, + { + .desc = "ibitmap_collides_with_bbitmap", + .grp = 0, + .bbitmap = 20, + .ibitmap = 20, + .itable = 30, + }, + { + .desc = "itable_collides_with_ibitmap", + .grp = 0, + .bbitmap = 20, + .ibitmap = 25, + .itable = 25, + }, + { + .desc = "group2_bbitmap_collides_with_group0_itable", + .grp = 2, + .bbitmap = 10, + .ibitmap = 2050, + .itable = 2051, + }, +}; + +KUNIT_ARRAY_PARAM_DESC(bv_corrupt_meta, bv_corrupt_meta_cases, desc); + +static void test_setup_corrupt_group_metadata_overlaps(struct kunit *test) +{ + const struct bv_corrupt_meta_case *tc = test->param_value; + struct bv_test_ctx *ctx = test->priv; + + bv_set_group_meta(ctx->sb, &ctx->gdps[tc->grp], tc->bbitmap, + tc->ibitmap, tc->itable); + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EFSCORRUPTED); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + +/* --- Test 7: Journal Reserved Inode Ownership & can_merge Isolation --- */ + +static void test_journal_inode_protection_and_ino_isolation(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *j_inode; + struct inode *reg_inode; + + /* + * Place group 2's block bitmap at block 20 (ino = 0) while group 0's + * metadata occupies [1..14] (ino = 0). + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[2], 20ULL, 2050ULL, 2051ULL); + + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, true); + reg_inode = bv_create_inode(test, ctx, 14, S_IFREG | 0644, true); + + /* + * Non-block-aligned i_size (7 blocks + 1 byte -> rounds up to 8 logical + * blocks 0..7) with 4 real extents, an interior sparse hole at lblk 2, + * and a trailing sparse hole at lblk 7: + * - lblk [0..1] -> pblk [15..16] (right-adjacent to [1..14] ino=0) + * - lblk 2 -> sparse hole (n == 0) + * - lblk [3..4] -> pblk [18..19] (left-adjacent to [20..20] ino=0) + * - lblk 5 -> pblk [201..201] (ino=8) + * - lblk 6 -> pblk [200..200] (merges right with 201 -> [200..201]) + * - lblk 7 -> sparse hole (n == 0) + */ + i_size_write(j_inode, 7 * BV_TEST_BLK_SIZE + 1); + bv_append_extent(test, j_inode, 0, 15ULL, 2); + bv_append_extent(test, j_inode, 3, 18ULL, 2); + bv_append_extent(test, j_inode, 5, 201ULL, 1); + bv_append_extent(test, j_inode, 6, 200ULL, 1); + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 1U); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->last_iget_flags & EXT4_IGET_SPECIAL)); + KUNIT_EXPECT_EQ(test, atomic_read(&j_inode->i_count), 1); + + /* Journal blocks are rejected for NULL and regular inodes */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 15, 2), 0); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(reg_inode, 15, 2), 0); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(reg_inode, 18, 2), 0); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(reg_inode, 200, 2), 0); + + /* Journal inode is permitted on all of its own extents */ + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(j_inode, 15, 2), 1); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(j_inode, 18, 2), 1); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(j_inode, 200, 2), 1); + + /* + * Verify can_merge() kept ino=0 and ino=8 zones separate on both the + * left ([1..14] vs [15..16]) and right ([18..19] vs [20..20]): the + * journal inode must still be rejected on adjacent group metadata. + */ + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(j_inode, 14, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(j_inode, 20, 1), 0); + + /* Unmapped physical gap block 17 remains valid for regular files */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 17, 1), 1); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(reg_inode, 17, 1), 1); +} + +/* --- Test 8: Disabled Journal Feature, Zero inum, and Empty Journal --- */ + +static void test_journal_disabled_or_empty_skips_zones(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *j_inode; + + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, true); + i_size_write(j_inode, 2 * BV_TEST_BLK_SIZE); + bv_append_extent(test, j_inode, 0, 100ULL, 2); + + /* Case 1: s_journal_inum set, but HAS_JOURNAL feature cleared */ + ext4_clear_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 100, 2), 1); + bv_release_system_zone_locked(ctx->sb); + + /* Case 2: HAS_JOURNAL set, but s_journal_inum == 0 */ + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = 0; + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + bv_release_system_zone_locked(ctx->sb); + + /* Case 3: HAS_JOURNAL + valid s_journal_inum, but i_size == 0 */ + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + i_size_write(j_inode, 0); + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 1U); + KUNIT_EXPECT_EQ(test, atomic_read(&j_inode->i_count), 1); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 100, 2), 1); +} + +/* --- Test 9: Journal Reserved Inode Error Paths --- */ + +static void test_journal_inode_invalid_inum(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + + ext4_set_feature_journal(ctx->sb); + + /* Below EXT4_ROOT_INO (e.g. EXT4_BAD_INO = 1) */ + ctx->es.s_journal_inum = cpu_to_le32(EXT4_BAD_INO); + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); + + /* Above s_inodes_count */ + ctx->es.s_journal_inum = cpu_to_le32(BV_TEST_TOTAL_INODES + 1); + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + +static void test_journal_inode_iget_error(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + ctx->fail_iget_err = -EIO; + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EIO); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 1U); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + +static void test_journal_inode_map_blocks_error(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *j_inode; + + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, true); + i_size_write(j_inode, 3 * BV_TEST_BLK_SIZE); + + /* Fail on 2nd ext4_map_blocks call after 1st extent was inserted */ + ctx->fail_map_err = -EIO; + ctx->fail_map_on_call = 2; + kunit_activate_static_stub(test, ext4_map_blocks, + bv_map_blocks_fault_stub); + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EIO); + KUNIT_EXPECT_EQ(test, ctx->map_calls, 2U); + KUNIT_EXPECT_EQ(test, atomic_read(&j_inode->i_count), 1); + KUNIT_EXPECT_FALSE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + +static void test_journal_inode_overlap_sets_fs_error(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *j_inode; + + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, true); + i_size_write(j_inode, 2 * BV_TEST_BLK_SIZE); + + /* Extent at block 10 collides with group 0's inode table [7..14] */ + bv_append_extent(test, j_inode, 0, 10ULL, 2); + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_error_ino), + (u32)EXT4_JOURNAL_INO); + KUNIT_EXPECT_EQ(test, ctx->es.s_last_error_errcode, + EXT4_ERR_EFSCORRUPTED); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + +/* --- Test 10: ext4_check_blockref and Indirect Macros --- */ + +static void test_check_blockref_valid_and_sparse(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *inode; + __le32 zero_refs[4] = { 0, 0, 0, 0 }; + __le32 mixed_refs[5] = { + 0, + cpu_to_le32(15), + 0, + cpu_to_le32(1039), + cpu_to_le32(4096), + }; + __le32 bad_first = cpu_to_le32(7); + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + inode = bv_create_inode(test, ctx, 15, S_IFREG | 0644, false); + + /* max == 0 does not inspect entries */ + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, inode, + &bad_first, 0), + 0); + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, inode, + zero_refs, ARRAY_SIZE(zero_refs)), + 0); + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, inode, + mixed_refs, ARRAY_SIZE(mixed_refs)), + 0); + KUNIT_EXPECT_FALSE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); +} + +static void +test_check_blockref_corrupt_entries_and_journal_bypass(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *reg_inode; + struct inode *j_inode; + __le32 meta_refs[4] = { + cpu_to_le32(15), + 0, + cpu_to_le32(7), + cpu_to_le32(9), + }; + __le32 oob_refs[2] = { + cpu_to_le32(16), + cpu_to_le32(BV_TEST_TOTAL_BLKS), + }; + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + reg_inode = bv_create_inode(test, ctx, 16, S_IFREG | 0644, false); + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, false); + + /* Stops at the first metadata block (7) and records error details */ + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, reg_inode, + meta_refs, ARRAY_SIZE(meta_refs)), + -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_EQ(test, le64_to_cpu(ctx->es.s_last_error_block), 7ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_error_ino), 16U); + + /* Out-of-bounds block reference also triggers -EFSCORRUPTED */ + bv_clear_fs_error(ctx); + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, reg_inode, + oob_refs, ARRAY_SIZE(oob_refs)), + -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_EQ(test, le64_to_cpu(ctx->es.s_last_error_block), + (u64)BV_TEST_TOTAL_BLKS); + + /* Active journal inode (s_journal->j_inode) bypasses blockref checks */ + bv_clear_fs_error(ctx); + ctx->mock_journal.j_inode = j_inode; + ctx->sbi.s_journal = &ctx->mock_journal; + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, j_inode, + meta_refs, ARRAY_SIZE(meta_refs)), + 0); + KUNIT_EXPECT_FALSE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); +} + +static void test_ind_check_inode_and_indirect_blockref(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + unsigned int max_addrs = EXT4_ADDR_PER_BLOCK(ctx->sb); + struct buffer_head ind_bh; + struct inode *inode; + __le32 *addrs; + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + inode = bv_create_inode(test, ctx, 17, S_IFREG | 0644, false); + + /* ext4_ind_check_inode() checks direct slots i_data[0..11] */ + EXT4_I(inode)->i_data[0] = cpu_to_le32(15); + EXT4_I(inode)->i_data[EXT4_NDIR_BLOCKS - 1] = cpu_to_le32(20); + KUNIT_EXPECT_EQ(test, ext4_ind_check_inode(inode), 0); + + EXT4_I(inode)->i_data[EXT4_NDIR_BLOCKS - 1] = cpu_to_le32(6); + KUNIT_EXPECT_EQ(test, ext4_ind_check_inode(inode), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, le64_to_cpu(ctx->es.s_last_error_block), 6ULL); + + /* + * ext4_check_indirect_blockref() checks all EXT4_ADDR_PER_BLOCK(sb) + * entries (256 for 1KiB blocks), including the final slot. + */ + bv_clear_fs_error(ctx); + memset(&ind_bh, 0, sizeof(ind_bh)); + memset(ctx->ind_buf, 0, sizeof(ctx->ind_buf)); + ind_bh.b_data = ctx->ind_buf; + ind_bh.b_size = BV_TEST_BLK_SIZE; + addrs = (__le32 *)ind_bh.b_data; + + addrs[0] = cpu_to_le32(15); + addrs[max_addrs / 2] = cpu_to_le32(1039); + addrs[max_addrs - 1] = cpu_to_le32(4096); + KUNIT_EXPECT_EQ(test, ext4_check_indirect_blockref(inode, &ind_bh), 0); + KUNIT_EXPECT_FALSE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + + addrs[max_addrs - 1] = cpu_to_le32(1029); + KUNIT_EXPECT_EQ(test, ext4_check_indirect_blockref(inode, &ind_bh), + -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, le64_to_cpu(ctx->es.s_last_error_block), 1029ULL); +} + +/* --- Test 11: Integration with ext4_map_blocks() Validity Check --- */ + +static void test_map_blocks_rejects_extent_in_system_zone(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct ext4_map_blocks map; + struct inode *bad_inode; + struct inode *ok_inode; + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + + ok_inode = bv_create_inode(test, ctx, 18, S_IFREG | 0644, true); + bv_append_extent(test, ok_inode, 0, 25ULL, 3); + memset(&map, 0, sizeof(map)); + map.m_lblk = 0; + map.m_len = 3; + KUNIT_EXPECT_EQ(test, ext4_map_blocks(NULL, ok_inode, &map, 0), 3); + KUNIT_EXPECT_FALSE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + + /* Corrupt extent mapped onto group 0's inode table [7..14] */ + bad_inode = bv_create_inode(test, ctx, 19, S_IFREG | 0644, true); + bv_append_extent(test, bad_inode, 0, 8ULL, 2); + memset(&map, 0, sizeof(map)); + map.m_lblk = 0; + map.m_len = 2; + KUNIT_EXPECT_EQ(test, ext4_map_blocks(NULL, bad_inode, &map, 0), + -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_EQ(test, le64_to_cpu(ctx->es.s_last_error_block), 8ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_error_ino), 19U); +} + +static struct kunit_case ext4_block_validity_test_cases[] = { + KUNIT_CASE_PARAM(test_sb_block_valid_bounds, bv_bounds_gen_params), + KUNIT_CASE(test_release_system_zone_lifecycle), + KUNIT_CASE(test_setup_multigroup_sparse_super_and_flex_bg), + KUNIT_CASE(test_rbtree_left_right_and_bridge_merges), + KUNIT_CASE_PARAM(test_sb_block_valid_interval_overlaps, + bv_overlap_gen_params), + KUNIT_CASE_PARAM(test_setup_corrupt_group_metadata_overlaps, + bv_corrupt_meta_gen_params), + KUNIT_CASE(test_journal_inode_protection_and_ino_isolation), + KUNIT_CASE(test_journal_disabled_or_empty_skips_zones), + KUNIT_CASE(test_journal_inode_invalid_inum), + KUNIT_CASE(test_journal_inode_iget_error), + KUNIT_CASE(test_journal_inode_map_blocks_error), + KUNIT_CASE(test_journal_inode_overlap_sets_fs_error), + KUNIT_CASE(test_check_blockref_valid_and_sparse), + KUNIT_CASE(test_check_blockref_corrupt_entries_and_journal_bypass), + KUNIT_CASE(test_ind_check_inode_and_indirect_blockref), + KUNIT_CASE(test_map_blocks_rejects_extent_in_system_zone), + {} +}; + +static struct kunit_suite ext4_block_validity_test_suite = { + .name = "ext4_block_validity_test", + .init = bv_test_init, + .test_cases = ext4_block_validity_test_cases, +}; + +kunit_test_suites(&ext4_block_validity_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 block validity (system zone) tracking"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/block_validity.c b/fs/ext4/block_validity.c index 3a31e3d718c95a..53b042f36a6961 100644 --- a/fs/ext4/block_validity.c +++ b/fs/ext4/block_validity.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include "ext4.h" @@ -269,6 +270,7 @@ int ext4_setup_system_zone(struct super_block *sb) kfree(system_blks); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_setup_system_zone); /* * Called when the filesystem is unmounted or when remounting it with @@ -291,6 +293,7 @@ void ext4_release_system_zone(struct super_block *sb) if (system_blks) call_rcu(&system_blks->rcu, ext4_destroy_system_zone); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_release_system_zone); int ext4_sb_block_valid(struct super_block *sb, struct inode *inode, ext4_fsblk_t start_blk, unsigned int count) @@ -334,6 +337,7 @@ int ext4_sb_block_valid(struct super_block *sb, struct inode *inode, rcu_read_unlock(); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_block_valid); /* * Returns 1 if the passed-in block region (start_blk, @@ -345,6 +349,7 @@ int ext4_inode_block_valid(struct inode *inode, ext4_fsblk_t start_blk, { return ext4_sb_block_valid(inode->i_sb, inode, start_blk, count); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_block_valid); int ext4_check_blockref(const char *function, unsigned int line, struct inode *inode, __le32 *p, unsigned int max) @@ -367,4 +372,5 @@ int ext4_check_blockref(const char *function, unsigned int line, } return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_blockref); From 9627baed418bf1200a5ec7309958f620d6e3d318 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:17:44 +0000 Subject: [PATCH 1565/2102] ext4: check multi-block overlap on left traversal in add_system_zone() When walking system_blks->root to insert [start_blk, start_blk + count), add_system_zone() takes the left branch whenever start_blk < entry->start_blk instead of checking that the entire range ends at or before entry->start_blk (unlike ext4_sb_block_valid(), which checks start_blk + count - 1 < entry->start_blk). As a result, a corrupt multi-block metadata range (such as a group's inode table or a reserved journal inode extent mapped in ext4_protect_reserved_inode() before sbi->s_system_blks is published) that starts strictly before an existing system zone and extends into or across it traverses rb_left instead of returning -EFSCORRUPTED. This inserts overlapping intervals into system_blks->root and breaks the disjoint-interval invariant relied upon by ext4_sb_block_valid() (for example, a lookup on blocks past entry->start_blk + entry->count branches right and misses the overlapping zone stored in rb_left). A corrupt 64-bit start_blk whose start_blk + count wraps around u64 can similarly corrupt the rbtree ordering. Reject zero-length or u64-wrapping ranges up front and require start_blk + count <= entry->start_blk before taking rb_left in add_system_zone(). Add KUnit regression tests in fs/ext4/block_validity-test.c covering group metadata and journal extents that partially overlap from the left, completely enclose an existing system zone, or wrap 64-bit block numbers. Fixes: bf9a379d0980 ("ext4: don't allow overlapping system zones") Signed-off-by: Theodore Ts'o --- fs/ext4/block_validity-test.c | 68 +++++++++++++++++++++++++++++++++++ fs/ext4/block_validity.c | 5 ++- 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/fs/ext4/block_validity-test.c b/fs/ext4/block_validity-test.c index f7667099ac6ca5..8d3af4093a3cb8 100644 --- a/fs/ext4/block_validity-test.c +++ b/fs/ext4/block_validity-test.c @@ -1114,6 +1114,27 @@ static const struct bv_corrupt_meta_case bv_corrupt_meta_cases[] = { .ibitmap = 2050, .itable = 2051, }, + { + .desc = "itable_starts_before_and_overlaps_bbitmap", + .grp = 0, + .bbitmap = 20, + .ibitmap = 40, + .itable = 15, + }, + { + .desc = "itable_starts_before_and_encloses_ibitmap", + .grp = 2, + .bbitmap = 50, + .ibitmap = 55, + .itable = 52, + }, + { + .desc = "itable_u64_wrap_around_overflow", + .grp = 2, + .bbitmap = 2049, + .ibitmap = 2050, + .itable = U64_MAX - 2ULL, + }, }; KUNIT_ARRAY_PARAM_DESC(bv_corrupt_meta, bv_corrupt_meta_cases, desc); @@ -1317,6 +1338,52 @@ static void test_journal_inode_overlap_sets_fs_error(struct kunit *test) KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); } +static void test_journal_extent_left_overlap_rejected(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *j_inode; + + /* + * Place group 2's block bitmap at block 20 (ino = 0) and map a + * multi-block journal extent at [18..21] that starts strictly before + * block 20 and extends across it. During ext4_setup_system_zone(), + * s_system_blks is still NULL when ext4_map_blocks() runs, so + * add_system_zone() must catch this left-traversal overlap. + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[2], 20ULL, 2050ULL, 2051ULL); + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, true); + i_size_write(j_inode, 4 * BV_TEST_BLK_SIZE); + bv_append_extent(test, j_inode, 0, 18ULL, 4); + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_error_ino), + (u32)EXT4_JOURNAL_INO); + KUNIT_EXPECT_EQ(test, ctx->es.s_last_error_errcode, + EXT4_ERR_EFSCORRUPTED); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); + + /* + * Also verify a journal extent [1020..1040] that completely encloses + * group 1's entire metadata zone [1025..1038]. + */ + bv_clear_fs_error(ctx); + ext4_es_remove_extent(j_inode, 0, EXT_MAX_BLOCKS); + ext_inode_hdr(j_inode)->eh_entries = 0; + i_size_write(j_inode, 21 * BV_TEST_BLK_SIZE); + bv_append_extent(test, j_inode, 0, 1020ULL, 21); + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + /* --- Test 10: ext4_check_blockref and Indirect Macros --- */ static void test_check_blockref_valid_and_sparse(struct kunit *test) @@ -1501,6 +1568,7 @@ static struct kunit_case ext4_block_validity_test_cases[] = { KUNIT_CASE(test_journal_inode_iget_error), KUNIT_CASE(test_journal_inode_map_blocks_error), KUNIT_CASE(test_journal_inode_overlap_sets_fs_error), + KUNIT_CASE(test_journal_extent_left_overlap_rejected), KUNIT_CASE(test_check_blockref_valid_and_sparse), KUNIT_CASE(test_check_blockref_corrupt_entries_and_journal_bypass), KUNIT_CASE(test_ind_check_inode_and_indirect_blockref), diff --git a/fs/ext4/block_validity.c b/fs/ext4/block_validity.c index 53b042f36a6961..34468932e461d9 100644 --- a/fs/ext4/block_validity.c +++ b/fs/ext4/block_validity.c @@ -75,10 +75,13 @@ static int add_system_zone(struct ext4_system_blocks *system_blks, struct rb_node **n = &system_blks->root.rb_node, *node; struct rb_node *parent = NULL, *new_node; + if (!count || (start_blk + count < start_blk)) + return -EFSCORRUPTED; + while (*n) { parent = *n; entry = rb_entry(parent, struct ext4_system_zone, node); - if (start_blk < entry->start_blk) + if (start_blk + count <= entry->start_blk) n = &(*n)->rb_left; else if (start_blk >= (entry->start_blk + entry->count)) n = &(*n)->rb_right; From fe3d20e702a8905ecd91716614f04771dd9cf3e4 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:20:32 +0000 Subject: [PATCH 1566/2102] ext4: enable full feature coverage in fs/ext4/.kunitconfig Enable CONFIG_EXT4_FS_POSIX_ACL, CONFIG_EXT4_FS_SECURITY, CONFIG_FS_VERITY, CONFIG_FS_ENCRYPTION, CONFIG_QUOTA, CONFIG_QFMT_V2, and CONFIG_UNICODE in fs/ext4/.kunitconfig so conditional ext4 source files and feature-gated code paths (POSIX ACLs, security xattrs, fs-verity, fscrypt, quota accounting, and UTF-8 casefolding) are compiled and exercised during KUnit runs. Fix mock superblock and test setup bugs in existing KUnit suites exposed by enabling these Kconfig options: - Provide .get_dquots callbacks in mock super_operations under CONFIG_QUOTA in block_validity-test.c, extents-test.c, fast_commit-test.c, inline-test.c, inode-test.c, mballoc-test.c, namei-test.c, and xattr-test.c so dquot_drop() does not dereference a NULL callback during ext4_clear_inode(). - Populate sb->s_cop = &ext4_cryptops under CONFIG_FS_ENCRYPTION in balloc-test.c, extents-test.c, fast_commit-test.c, inline-test.c, inode-test.c, mballoc-test.c, and xattr-test.c so fscrypt_put_encryption_info() can resolve inode_info_offs safely on eviction. - Fix test_namei_casefold_lookup_and_strict() under CONFIG_UNICODE in namei-test.c to propagate EXT4_INODE_CASEFOLD to S_CASEFOLD on the VFS directory inode via ext4_set_inode_flags(). Signed-off-by: Theodore Ts'o --- fs/ext4/.kunitconfig | 7 +++++++ fs/ext4/balloc-test.c | 3 +++ fs/ext4/block_validity-test.c | 10 ++++++++++ fs/ext4/extents-test.c | 16 ++++++++++++++-- fs/ext4/fast_commit-test.c | 16 ++++++++++++++-- fs/ext4/inline-test.c | 16 +++++++++++++++- fs/ext4/inode-test.c | 27 +++++++++++++++++++-------- fs/ext4/mballoc-test.c | 13 +++++++++++++ fs/ext4/namei-test.c | 14 ++++++++++++-- fs/ext4/xattr-test.c | 16 ++++++++++++++-- 10 files changed, 121 insertions(+), 17 deletions(-) diff --git a/fs/ext4/.kunitconfig b/fs/ext4/.kunitconfig index bf51da7cd9fc7d..17103c583fdb7d 100644 --- a/fs/ext4/.kunitconfig +++ b/fs/ext4/.kunitconfig @@ -1,3 +1,10 @@ CONFIG_KUNIT=y CONFIG_EXT4_FS=y +CONFIG_EXT4_FS_POSIX_ACL=y +CONFIG_EXT4_FS_SECURITY=y CONFIG_EXT4_KUNIT_TESTS=y +CONFIG_FS_VERITY=y +CONFIG_FS_ENCRYPTION=y +CONFIG_QUOTA=y +CONFIG_QFMT_V2=y +CONFIG_UNICODE=y diff --git a/fs/ext4/balloc-test.c b/fs/ext4/balloc-test.c index b15d50907324f3..ab076c0edf9994 100644 --- a/fs/ext4/balloc-test.c +++ b/fs/ext4/balloc-test.c @@ -535,6 +535,9 @@ static int balloc_test_init(struct kunit *test) sb->s_op = &balloc_test_sops; #ifdef CONFIG_QUOTA sb->dq_op = &balloc_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; #endif sb->s_flags |= SB_ACTIVE; sb->s_blocksize = BALLOC_TEST_BLK_SIZE; diff --git a/fs/ext4/block_validity-test.c b/fs/ext4/block_validity-test.c index 8d3af4093a3cb8..97817befd6e783 100644 --- a/fs/ext4/block_validity-test.c +++ b/fs/ext4/block_validity-test.c @@ -228,12 +228,22 @@ static void bv_test_free_inode_mem(struct inode *inode) kfree(EXT4_I(inode)); } +#ifdef CONFIG_QUOTA +static struct dquot __rcu **bv_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + static const struct super_operations bv_test_sops = { .alloc_inode = bv_test_alloc_inode, .evict_inode = bv_test_evict_inode, .destroy_inode = bv_test_destroy_inode, .free_inode = bv_test_free_inode_mem, .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = bv_test_get_dquots, +#endif }; static int bv_test_init_fs_context(struct fs_context *fc) diff --git a/fs/ext4/extents-test.c b/fs/ext4/extents-test.c index cb1ef31490d02e..bc548829310368 100644 --- a/fs/ext4/extents-test.c +++ b/fs/ext4/extents-test.c @@ -153,9 +153,12 @@ static unsigned long ext_dummy_shrinker_scan(struct shrinker *shrink, return SHRINK_STOP; } -static const struct super_operations ext_dummy_sops = {}; - #ifdef CONFIG_QUOTA +static struct dquot __rcu **ext_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + static qsize_t *ext_get_reserved_space(struct inode *inode) { return &EXT4_I(inode)->i_reserved_quota; @@ -166,6 +169,12 @@ static const struct dquot_operations ext_dummy_qops = { }; #endif +static const struct super_operations ext_dummy_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = ext_get_dquots, +#endif +}; + static int ext_init_fs_context(struct fs_context *fc) { return 0; @@ -467,6 +476,9 @@ static int extents_kunit_init(struct kunit *test) sb->s_op = &ext_dummy_sops; #ifdef CONFIG_QUOTA sb->dq_op = &ext_dummy_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; #endif sb->s_blocksize = 4096; sb->s_blocksize_bits = 12; diff --git a/fs/ext4/fast_commit-test.c b/fs/ext4/fast_commit-test.c index be416cb3653ee9..07cb9c043cd2c1 100644 --- a/fs/ext4/fast_commit-test.c +++ b/fs/ext4/fast_commit-test.c @@ -135,9 +135,12 @@ struct fc_test_ctx { int custom_es_ret; }; -static const struct super_operations fc_test_sops = {}; - #ifdef CONFIG_QUOTA +static struct dquot __rcu **fc_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + static qsize_t *fc_test_get_reserved_space(struct inode *inode) { return &EXT4_I(inode)->i_reserved_quota; @@ -148,6 +151,12 @@ static const struct dquot_operations fc_test_qops = { }; #endif +static const struct super_operations fc_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = fc_test_get_dquots, +#endif +}; + static unsigned long fc_dummy_shrinker_count(struct shrinker *shrink, struct shrink_control *sc) { @@ -886,6 +895,9 @@ static int fast_commit_test_init(struct kunit *test) sb->s_op = &fc_test_sops; #ifdef CONFIG_QUOTA sb->dq_op = &fc_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; #endif strscpy(sb->s_id, "ext4-fc-test", sizeof(sb->s_id)); diff --git a/fs/ext4/inline-test.c b/fs/ext4/inline-test.c index efc068c1f823db..0198ce8311c73e 100644 --- a/fs/ext4/inline-test.c +++ b/fs/ext4/inline-test.c @@ -66,7 +66,18 @@ struct inline_test_ctx { static struct inline_test_ctx *t_ctx; -static const struct super_operations inline_test_sops = {}; +#ifdef CONFIG_QUOTA +static struct dquot __rcu **inline_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations inline_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = inline_test_get_dquots, +#endif +}; static bool test_release_folio(struct folio *folio, gfp_t wait) { @@ -265,6 +276,9 @@ static int inline_test_init(struct kunit *test) ctx->sb.s_bdi = &noop_backing_dev_info; ctx->sb.s_fs_info = &ctx->sbi; ctx->sb.s_op = &inline_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + ctx->sb.s_cop = &ext4_cryptops; +#endif snprintf(ctx->sb.s_id, sizeof(ctx->sb.s_id), "ext4-inline-test"); init_rwsem(&ctx->sb.s_umount); diff --git a/fs/ext4/inode-test.c b/fs/ext4/inode-test.c index 4881736e87426f..8a3d753b7079b5 100644 --- a/fs/ext4/inode-test.c +++ b/fs/ext4/inode-test.c @@ -462,15 +462,12 @@ static void inode_test_free_inode(struct inode *inode) kfree(EXT4_I(inode)); } -static const struct super_operations inode_test_sops = { - .alloc_inode = inode_test_alloc_inode, - .evict_inode = ext4_evict_inode, - .destroy_inode = inode_test_destroy_inode, - .free_inode = inode_test_free_inode, - .drop_inode = inode_just_drop, -}; - #ifdef CONFIG_QUOTA +static struct dquot __rcu **inode_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + static qsize_t *inode_test_get_reserved_space(struct inode *inode) { return &EXT4_I(inode)->i_reserved_quota; @@ -481,6 +478,17 @@ static const struct dquot_operations inode_test_qops = { }; #endif +static const struct super_operations inode_test_sops = { + .alloc_inode = inode_test_alloc_inode, + .evict_inode = ext4_evict_inode, + .destroy_inode = inode_test_destroy_inode, + .free_inode = inode_test_free_inode, + .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = inode_test_get_dquots, +#endif +}; + static int inode_test_init_fs_context(struct fs_context *fc) { return 0; @@ -960,6 +968,9 @@ static struct inode_test_ctx *inode_test_setup(struct kunit *test) sb->s_op = &inode_test_sops; #ifdef CONFIG_QUOTA sb->dq_op = &inode_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; #endif sb->s_blocksize = INODE_TEST_BLK_SIZE; sb->s_blocksize_bits = INODE_TEST_BLK_BITS; diff --git a/fs/ext4/mballoc-test.c b/fs/ext4/mballoc-test.c index 6f70bff5c83a75..bd5dabf74b6fba 100644 --- a/fs/ext4/mballoc-test.c +++ b/fs/ext4/mballoc-test.c @@ -56,9 +56,19 @@ static void mbt_free_inode(struct inode *inode) kfree(EXT4_I(inode)); } +#ifdef CONFIG_QUOTA +static struct dquot __rcu **mbt_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + static const struct super_operations mbt_sops = { .alloc_inode = mbt_alloc_inode, .free_inode = mbt_free_inode, +#ifdef CONFIG_QUOTA + .get_dquots = mbt_get_dquots, +#endif }; static int mbt_init_fs_context(struct fs_context *fc) @@ -95,6 +105,9 @@ static int mbt_mb_init(struct super_block *sb) */ INIT_LIST_HEAD(&sb->s_inodes); sb->s_op = &mbt_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif ret = ext4_mb_init(sb); if (ret != 0) diff --git a/fs/ext4/namei-test.c b/fs/ext4/namei-test.c index 6dde9e5cc3327e..cce3f8d5b36da7 100644 --- a/fs/ext4/namei-test.c +++ b/fs/ext4/namei-test.c @@ -84,9 +84,12 @@ struct namei_test_ctx { unsigned int mark_inode_dirty_calls; }; -static const struct super_operations namei_test_sops = {}; - #ifdef CONFIG_QUOTA +static struct dquot __rcu **namei_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + static qsize_t *namei_test_get_reserved_space(struct inode *inode) { return &EXT4_I(inode)->i_reserved_quota; @@ -97,6 +100,12 @@ static const struct dquot_operations namei_test_qops = { }; #endif +static const struct super_operations namei_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = namei_test_get_dquots, +#endif +}; + static void init_mock_inode_slot(struct namei_test_ctx *ctx, struct mock_inode_slot *slot, unsigned long ino, umode_t mode) @@ -2278,6 +2287,7 @@ static void test_namei_casefold_lookup_and_strict(struct kunit *test) ctx->es.s_feature_incompat |= cpu_to_le32(EXT4_FEATURE_INCOMPAT_CASEFOLD); ext4_set_inode_flag(dir, EXT4_INODE_CASEFOLD); + ext4_set_inode_flags(dir, true); KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); init_mock_dentry(&parent_dentry, NULL, "cfdir", dir, &ctx->sb); diff --git a/fs/ext4/xattr-test.c b/fs/ext4/xattr-test.c index 30ee5c337284f8..981bf145585121 100644 --- a/fs/ext4/xattr-test.c +++ b/fs/ext4/xattr-test.c @@ -79,9 +79,12 @@ struct xattr_test_ctx { unsigned int dirty_metadata_calls; }; -static const struct super_operations xattr_test_sops = {}; - #ifdef CONFIG_QUOTA +static struct dquot __rcu **xattr_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + static qsize_t *xattr_test_get_reserved_space(struct inode *inode) { return &EXT4_I(inode)->i_reserved_quota; @@ -92,6 +95,12 @@ static const struct dquot_operations xattr_test_qops = { }; #endif +static const struct super_operations xattr_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = xattr_test_get_dquots, +#endif +}; + static void init_mock_inode_slot(struct xattr_test_ctx *ctx, struct mock_inode_slot *slot, unsigned long ino) @@ -477,6 +486,9 @@ static int xattr_test_init(struct kunit *test) sb->s_op = &xattr_test_sops; #ifdef CONFIG_QUOTA sb->dq_op = &xattr_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; #endif sb->s_blocksize = TEST_BLK_SIZE; sb->s_blocksize_bits = TEST_BLK_BITS; From 7ea85135209d7815db99d931e27e5bc99f4d5dd0 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:20:45 +0000 Subject: [PATCH 1567/2102] ext4: add KUnit tests for fs/ext4/super.c Add a KUnit test suite (ext4_super_test) covering superblock validation, geometry checks, metadata checksums, mount options, overhead/statfs accounting, and persistent error recording in fs/ext4/super.c: - Feature flag compatibility in ext4_feature_set_ok() and ext4_check_feature_compatibility() across RW/RO mounts, bigalloc constraints, Hurd creator-OS restrictions, DAX, and encryption levels. - Inode, block-group, cluster-size, and directory hash initialization in ext4_inode_info_init(), ext4_block_group_meta_init(), ext4_handle_clustersize(), and ext4_hash_info_init(). - Filesystem geometry validation in ext4_check_geometry(), descriptor location arithmetic in descriptor_loc() (linear and meta_bg), superblock and group descriptor CRC16/CRC32C verification, descriptor overlap checks in ext4_check_descriptors(), and flex_bg counter aggregation in ext4_fill_flex_info() / ext4_alloc_flex_bg_array(). - Maximum file size helpers ext4_max_size() / ext4_max_bitmap_size(), stripe selection in ext4_get_stripe_size(), reserved cluster defaults in ext4_set_resv_clusters(), overhead calculation in count_overhead() and ext4_calculate_overhead(), and space reporting in ext4_statfs(). - Mount option defaults, parsing, consistency checks, remount guards, on-disk s_mount_opts parsing, and _ext4_show_options() formatting. - Error translation, first/last error persistence in save_error_info(), and superblock state flushing in ext4_update_super(). Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 45 ++ fs/ext4/super-test.c | 1345 ++++++++++++++++++++++++++++++++++++++++++ fs/ext4/super.c | 219 +++++++ 4 files changed, 1610 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/super-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 5c6afff5f12ac6..ca1a1201cbfeed 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -20,7 +20,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ namei-test.o inline-test.o \ fast_commit-test.o ialloc-test.o \ balloc-test.o orphan-test.o \ - block_validity-test.o + block_validity-test.o super-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index b7be93b0674672..81d3f48c44c1a3 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -3437,6 +3437,51 @@ extern unsigned int ext4_num_base_meta_blocks(struct super_block *sb, ext4_group_t block_group); extern void print_daily_error_info(struct timer_list *t); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_errno_to_code_test(int err); +extern void ext4_save_error_info_test(struct super_block *sb, int error, + __u32 ino, __u64 block, + const char *func, unsigned int line); +extern void ext4_update_super_test(struct super_block *sb); +extern int ext4_check_descriptors_test(struct super_block *sb, + ext4_fsblk_t sb_block, + ext4_group_t *first_not_zeroed); +extern loff_t ext4_max_size_test(int blkbits, int has_huge_files); +extern loff_t ext4_max_bitmap_size_test(int bits, int has_huge_files); +extern ext4_fsblk_t ext4_descriptor_loc_test(struct super_block *sb, + ext4_fsblk_t logical_sb_block, + int nr); +extern unsigned long ext4_get_stripe_size_test(struct ext4_sb_info *sbi); +extern int ext4_count_overhead_test(struct super_block *sb, ext4_group_t grp, + char *buf); +extern void ext4_set_resv_clusters_test(struct super_block *sb); +extern void ext4_set_def_opts_test(struct super_block *sb, + struct ext4_super_block *es); +extern int ext4_handle_clustersize_test(struct super_block *sb); +extern int ext4_inode_info_init_test(struct super_block *sb, + struct ext4_super_block *es); +extern int ext4_init_metadata_csum_test(struct super_block *sb, + struct ext4_super_block *es); +extern int ext4_check_feature_compatibility_test(struct super_block *sb, + struct ext4_super_block *es, + int silent); +extern int ext4_check_geometry_test(struct super_block *sb, + struct ext4_super_block *es); +extern int ext4_hash_info_init_test(struct super_block *sb); +extern int ext4_block_group_meta_init_test(struct super_block *sb, int silent); +extern int ext4_fill_flex_info_test(struct super_block *sb); +extern void ext4_flex_groups_free_test(struct ext4_sb_info *sbi); +extern int ext4_show_options_test(struct seq_file *seq, struct super_block *sb, + int nodefs); +extern int ext4_statfs_test(struct dentry *dentry, struct kstatfs *buf); +extern int ext4_parse_and_apply_options_test(struct super_block *sb, + const char *options, + bool is_remount); +extern int ext4_parse_sb_mount_options_test(struct super_block *sb, + unsigned long *journal_devnum, + unsigned int *journal_ioprio); +#endif + extern __printf(7, 8) void __ext4_error(struct super_block *, const char *, unsigned int, bool, int, __u64, const char *, ...); diff --git a/fs/ext4/super-test.c b/fs/ext4/super-test.c new file mode 100644 index 00000000000000..606798ef0258cc --- /dev/null +++ b/fs/ext4/super-test.c @@ -0,0 +1,1345 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/super.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" + +#define SUPER_TEST_NGROUPS 4U +#define SUPER_TEST_BLK_SIZE 1024U +#define SUPER_TEST_BLK_BITS 10U +#define SUPER_TEST_BLOCKS_PER_GRP 1024U +#define SUPER_TEST_FIRST_DATA_BLK 1U +#define SUPER_TEST_TOTAL_BLKS (SUPER_TEST_FIRST_DATA_BLK + \ + SUPER_TEST_NGROUPS * \ + SUPER_TEST_BLOCKS_PER_GRP) +#define SUPER_TEST_INODE_SIZE 256U +#define SUPER_TEST_EXTRA_ISIZE 32U +#define SUPER_TEST_INODES_PER_BLK (SUPER_TEST_BLK_SIZE / \ + SUPER_TEST_INODE_SIZE) +#define SUPER_TEST_INODES_PER_GRP 32U +#define SUPER_TEST_ITB_PER_GRP (SUPER_TEST_INODES_PER_GRP / \ + SUPER_TEST_INODES_PER_BLK) +#define SUPER_TEST_TOTAL_INODES (SUPER_TEST_NGROUPS * \ + SUPER_TEST_INODES_PER_GRP) +#define SUPER_TEST_FIRST_INO 11U +#define SUPER_TEST_GDB_COUNT 1U +#define SUPER_TEST_RSV_GDT_BLKS 2U + +struct super_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + struct ext4_group_desc gdps[8]; + journal_t mock_journal; + struct inode *journal_inode; + bool counters_inited; +}; + +static struct kunit *active_super_test; + +static struct inode *super_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = SUPER_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void super_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void super_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **super_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations super_test_sops = { + .alloc_inode = super_test_alloc_inode, + .free_inode = super_test_free_inode, + .evict_inode = super_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = super_test_get_dquots, +#endif +}; + +static void super_test_sb_upd_work(struct work_struct *work) +{ +} + +static void super_test_err_timer(struct timer_list *t) +{ +} + +static int super_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type super_test_fs_type = { + .name = "ext4_super_kunit", + .init_fs_context = super_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static inline ext4_fsblk_t super_group_first_blk(ext4_group_t g) +{ + return SUPER_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * SUPER_TEST_BLOCKS_PER_GRP; +} + +static inline unsigned int super_default_base_meta(ext4_group_t g) +{ + if (g == 2) + return 0; + return 1U + SUPER_TEST_GDB_COUNT + SUPER_TEST_RSV_GDT_BLKS; +} + +static void super_setup_default_groups(struct super_test_ctx *ctx) +{ + struct super_block *sb = ctx->sb; + ext4_group_t g; + + memset(ctx->gdps, 0, sizeof(ctx->gdps)); + for (g = 0; g < SUPER_TEST_NGROUPS; g++) { + ext4_fsblk_t base = super_group_first_blk(g) + + super_default_base_meta(g); + + ext4_block_bitmap_set(sb, &ctx->gdps[g], base); + ext4_inode_bitmap_set(sb, &ctx->gdps[g], base + 1); + ext4_inode_table_set(sb, &ctx->gdps[g], base + 2); + ctx->gdps[g].bg_flags = cpu_to_le16(EXT4_BG_INODE_ZEROED); + ext4_group_desc_csum_set(sb, g, &ctx->gdps[g]); + } +} + +static struct ext4_group_desc * +super_get_group_desc_stub(struct super_block *sb, ext4_group_t block_group, + struct buffer_head **bh) +{ + struct kunit *test = active_super_test; + struct super_test_ctx *ctx; + + if (!test) + return NULL; + ctx = test->priv; + if (!ctx || sb != ctx->sb || block_group >= ARRAY_SIZE(ctx->gdps)) + return NULL; + if (bh) + *bh = NULL; + return &ctx->gdps[block_group]; +} + +static struct inode *super_iget_stub(struct super_block *sb, unsigned long ino, + ext4_iget_flags flags, + const char *function, unsigned int line) +{ + struct kunit *test = active_super_test; + struct super_test_ctx *ctx; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx || sb != ctx->sb || !ctx->journal_inode || + ctx->journal_inode->i_ino != ino) + return ERR_PTR(-ENOENT); + + ihold(ctx->journal_inode); + return ctx->journal_inode; +} + +static void super_test_cleanup(struct super_test_ctx *ctx) +{ +#ifdef CONFIG_QUOTA + int i; +#endif + + active_super_test = NULL; + ctx->sbi.s_journal = NULL; + + if (ctx->journal_inode) { + iput(ctx->journal_inode); + ctx->journal_inode = NULL; + } + + ext4_flex_groups_free_test(&ctx->sbi); + +#ifdef CONFIG_QUOTA + for (i = 0; i < EXT4_MAXQUOTAS; i++) { + kfree(rcu_access_pointer(ctx->sbi.s_qf_names[i])); + rcu_assign_pointer(ctx->sbi.s_qf_names[i], NULL); + } +#endif + fscrypt_free_dummy_policy(&ctx->sbi.s_dummy_enc_policy); + + deactivate_super(ctx->sb); + rcu_barrier(); + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + if (ctx->counters_inited) { + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + } + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(super_test_cleanup_action, super_test_cleanup, + struct super_test_ctx *); + +static int super_test_init(struct kunit *test) +{ + struct super_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + active_super_test = test; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + if (!ctx->bdev.bd_stats) { + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bd_stats"); + } + + fc = fs_context_for_mount(&super_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + err = percpu_counter_init(&sbi->s_freeclusters_counter, 0, GFP_KERNEL); + if (err) + goto err_sb; + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + if (err) { + percpu_counter_destroy(&sbi->s_freeclusters_counter); + goto err_sb; + } + err = percpu_counter_init(&sbi->s_freeinodes_counter, 0, GFP_KERNEL); + if (err) { + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeclusters_counter); + goto err_sb; + } + ctx->counters_inited = true; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &super_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = SUPER_TEST_BLK_SIZE; + sb->s_blocksize_bits = SUPER_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_super_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = SUPER_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(SUPER_TEST_FIRST_DATA_BLK); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + ctx->es.s_inodes_count = cpu_to_le32(SUPER_TEST_TOTAL_INODES); + ctx->es.s_inodes_per_group = cpu_to_le32(SUPER_TEST_INODES_PER_GRP); + ctx->es.s_blocks_per_group = cpu_to_le32(SUPER_TEST_BLOCKS_PER_GRP); + ctx->es.s_clusters_per_group = cpu_to_le32(SUPER_TEST_BLOCKS_PER_GRP); + ctx->es.s_first_ino = cpu_to_le32(SUPER_TEST_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(SUPER_TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(SUPER_TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(SUPER_TEST_EXTRA_ISIZE); + ctx->es.s_desc_size = cpu_to_le16(EXT4_MIN_DESC_SIZE_64BIT); + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(SUPER_TEST_RSV_GDT_BLKS); + ctx->es.s_errors = cpu_to_le16(EXT4_ERRORS_RO); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + generate_random_uuid(ctx->es.s_uuid); + ext4_blocks_count_set(&ctx->es, SUPER_TEST_TOTAL_BLKS); + + ext4_set_feature_sparse_super(sb); + ext4_set_feature_extents(sb); + ext4_set_feature_extra_isize(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + sbi->s_csum_seed = ext4_chksum(~0, ctx->es.s_uuid, + sizeof(ctx->es.s_uuid)); + ext4_superblock_csum_set(sb); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + sbi->s_sb_block = 1; + sbi->s_inode_size = SUPER_TEST_INODE_SIZE; + sbi->s_inodes_per_block = SUPER_TEST_INODES_PER_BLK; + sbi->s_inodes_per_group = SUPER_TEST_INODES_PER_GRP; + sbi->s_itb_per_group = SUPER_TEST_ITB_PER_GRP; + sbi->s_first_ino = SUPER_TEST_FIRST_INO; + sbi->s_want_extra_isize = SUPER_TEST_EXTRA_ISIZE; + sbi->s_blocks_per_group = SUPER_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = SUPER_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = SUPER_TEST_NGROUPS; + sbi->s_gdb_count = SUPER_TEST_GDB_COUNT; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = SUPER_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_resuid = make_kuid(&init_user_ns, EXT4_DEF_RESUID); + sbi->s_resgid = make_kgid(&init_user_ns, EXT4_DEF_RESGID); + sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ; + sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME; + sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME; + sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS; + sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT; + sbi->s_err_report_sec = 86400; + + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + INIT_WORK(&sbi->s_sb_upd_work, super_test_sb_upd_work); + timer_setup(&sbi->s_err_report, super_test_err_timer, 0); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + super_setup_default_groups(ctx); + + root_inode = new_inode(sb); + if (!root_inode) { + err = -ENOMEM; + goto err_counters; + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_flags |= S_NOQUOTA; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + err = -ENOMEM; + goto err_counters; + } + + up_write(&sb->s_umount); + + kunit_activate_static_stub(test, ext4_get_group_desc, + super_get_group_desc_stub); + kunit_activate_static_stub(test, __ext4_iget, super_iget_stub); + + err = kunit_add_action_or_reset(test, super_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + return 0; + +err_counters: + percpu_counter_destroy(&sbi->s_freeinodes_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeclusters_counter); +err_sb: + active_super_test = NULL; + deactivate_locked_super(sb); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + return err; +} + +static void test_feature_set_and_compatibility(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_super_block *es = &ctx->es; + __le32 orig_incompat = es->s_feature_incompat; + __le32 orig_ro_compat = es->s_feature_ro_compat; + + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 1); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + 0); + + /* Unknown incompat flag must fail on both RW and RO */ + es->s_feature_incompat = orig_incompat | cpu_to_le32(0x80000000U); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 0); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + es->s_feature_incompat = orig_incompat; + + /* Unknown ro_compat flag fails RW, succeeds RO */ + es->s_feature_ro_compat = orig_ro_compat | cpu_to_le32(0x80000000U); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 0); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 1), 1); + es->s_feature_ro_compat = orig_ro_compat; + + /* RO_COMPAT_READONLY forces SB_RDONLY on RW mount request */ + ext4_set_feature_readonly(sb); + sb->s_flags &= ~SB_RDONLY; + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 1); + KUNIT_EXPECT_TRUE(test, sb_rdonly(sb)); + sb->s_flags &= ~SB_RDONLY; + es->s_feature_ro_compat = orig_ro_compat; + + /* bigalloc requires extents and s_first_data_block == 0 on RW */ + ext4_set_feature_bigalloc(sb); + ext4_clear_feature_extents(sb); + es->s_first_data_block = 0; + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 0); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 1), 1); + + ext4_set_feature_extents(sb); + es->s_first_data_block = cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 0); + es->s_first_data_block = 0; + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 1); + es->s_first_data_block = cpu_to_le32(SUPER_TEST_FIRST_DATA_BLK); + es->s_feature_ro_compat = orig_ro_compat; + es->s_feature_incompat = orig_incompat; + + /* Hurd creator OS sets HURD_COMPAT and rejects 64bit and ea_inode */ + es->s_creator_os = cpu_to_le32(EXT4_OS_HURD); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + KUNIT_EXPECT_NE(test, test_opt2(sb, HURD_COMPAT), 0); + + ext4_clear_feature_64bit(sb); + ext4_set_feature_ea_inode(sb); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + + ext4_clear_feature_ea_inode(sb); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + 0); + clear_opt2(sb, HURD_COMPAT); + es->s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + es->s_feature_incompat = orig_incompat; + +#ifdef CONFIG_FS_DAX + /* DAX_ALWAYS rejects inline_data and non-DAX block devices */ + set_opt(sb, DAX_ALWAYS); + ext4_set_feature_inline_data(sb); + set_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + + ext4_clear_feature_inline_data(sb); + clear_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + + set_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + 0); + clear_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + clear_opt(sb, DAX_ALWAYS); +#endif + + /* Non-zero s_encryption_level with encrypt feature is rejected */ + ext4_set_feature_encrypt(sb); + es->s_encryption_level = 1; + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + es->s_encryption_level = 0; + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + 0); + ext4_clear_feature_encrypt(sb); +} + +static void test_inode_info_init(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + + /* EXT4_GOOD_OLD_REV forces 128-byte inodes and first_ino == 11 */ + es->s_rev_level = cpu_to_le32(EXT4_GOOD_OLD_REV); + es->s_inode_size = cpu_to_le16(512); + es->s_first_ino = cpu_to_le32(99); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sbi->s_inode_size, EXT4_GOOD_OLD_INODE_SIZE); + KUNIT_EXPECT_EQ(test, sbi->s_first_ino, + (unsigned int)EXT4_GOOD_OLD_FIRST_INO); + + /* EXT4_DYNAMIC_REV validation of s_first_ino and s_inode_size */ + es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + es->s_first_ino = cpu_to_le32(10); + es->s_inode_size = cpu_to_le16(256); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + es->s_first_ino = cpu_to_le32(11); + es->s_inode_size = cpu_to_le16(64); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + es->s_inode_size = cpu_to_le16(192); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + es->s_inode_size = cpu_to_le16(2048); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + /* 128-byte inode uses 1-second timestamp granularity */ + es->s_inode_size = cpu_to_le16(128); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sb->s_time_gran, (u32)NSEC_PER_SEC); + KUNIT_EXPECT_EQ(test, sb->s_time_max, EXT4_NON_EXTRA_TIMESTAMP_MAX); + KUNIT_EXPECT_EQ(test, sb->s_time_min, EXT4_TIMESTAMP_MIN); + + /* 256-byte inode enables nanosecond extra timestamps and extra_isize */ + es->s_inode_size = cpu_to_le16(256); + es->s_want_extra_isize = cpu_to_le16(200); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + es->s_want_extra_isize = cpu_to_le16(32); + es->s_min_extra_isize = cpu_to_le16(200); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + es->s_min_extra_isize = cpu_to_le16(64); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sb->s_time_gran, 1U); + KUNIT_EXPECT_EQ(test, sb->s_time_max, EXT4_EXTRA_TIMESTAMP_MAX); + KUNIT_EXPECT_EQ(test, sbi->s_want_extra_isize, 64U); +} + +static void test_block_group_meta_and_clustersize(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + + /* Without 64bit, descriptor size is forced to 32 bytes */ + ext4_clear_feature_64bit(sb); + es->s_desc_size = cpu_to_le16(128); + es->s_state = cpu_to_le16(EXT4_VALID_FS | EXT4_FC_REPLAY); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), 0); + KUNIT_EXPECT_EQ(test, sbi->s_desc_size, + (unsigned long)EXT4_MIN_DESC_SIZE); + KUNIT_EXPECT_EQ(test, sbi->s_mount_state, + (unsigned short)EXT4_VALID_FS); + + /* With 64bit, s_desc_size must be a power of 2 in [64, 1024] */ + ext4_set_feature_64bit(sb); + es->s_desc_size = cpu_to_le16(32); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + es->s_desc_size = cpu_to_le16(96); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + es->s_desc_size = cpu_to_le16(2048); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + + es->s_desc_size = cpu_to_le16(64); + es->s_blocks_per_group = 0; + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + es->s_blocks_per_group = cpu_to_le32(SUPER_TEST_BLOCKS_PER_GRP); + + /* Invalid s_inodes_per_group bounds and alignment */ + es->s_inodes_per_group = cpu_to_le32(2); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + es->s_inodes_per_group = cpu_to_le32(SUPER_TEST_BLK_SIZE * 8 + 8); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + es->s_inodes_per_group = cpu_to_le32(36); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + + es->s_inodes_per_group = cpu_to_le32(SUPER_TEST_INODES_PER_GRP); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), 0); + KUNIT_EXPECT_EQ(test, sbi->s_itb_per_group, + (unsigned long)SUPER_TEST_ITB_PER_GRP); + KUNIT_EXPECT_EQ(test, sbi->s_desc_per_block, 16UL); + + /* Non-bigalloc clustersize checks */ + es->s_log_block_size = 0; + es->s_log_cluster_size = cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + es->s_log_cluster_size = 0; + sbi->s_blocks_per_group = SUPER_TEST_BLK_SIZE * 8 + 8; + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + sbi->s_blocks_per_group = SUPER_TEST_BLK_SIZE * 8; + es->s_clusters_per_group = cpu_to_le32(SUPER_TEST_BLK_SIZE * 8 - 4); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + es->s_clusters_per_group = cpu_to_le32(SUPER_TEST_BLK_SIZE * 4); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + clear_opt2(sb, STD_GROUP_SIZE); + es->s_clusters_per_group = cpu_to_le32(SUPER_TEST_BLK_SIZE * 8); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_cluster_ratio, 1); + KUNIT_EXPECT_EQ(test, sbi->s_cluster_bits, 0); + KUNIT_EXPECT_NE(test, test_opt2(sb, STD_GROUP_SIZE), 0); + + /* Bigalloc clustersize checks: 4K blocks, 16K clusters (ratio 4) */ + ext4_set_feature_bigalloc(sb); + sb->s_blocksize = 4096; + sb->s_blocksize_bits = 12; + es->s_log_block_size = cpu_to_le32(2); + es->s_log_cluster_size = cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + es->s_log_cluster_size = cpu_to_le32(4); + sbi->s_blocks_per_group = 4096; + es->s_clusters_per_group = cpu_to_le32(512); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + es->s_clusters_per_group = cpu_to_le32(1024); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_cluster_bits, 2); + KUNIT_EXPECT_EQ(test, sbi->s_cluster_ratio, 4); +} + +static void test_hash_info_init(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + + es->s_def_hash_version = DX_HASH_LAST + 1; + KUNIT_EXPECT_EQ(test, ext4_hash_info_init_test(sb), -EINVAL); + + es->s_def_hash_version = DX_HASH_SIPHASH; + KUNIT_EXPECT_EQ(test, ext4_hash_info_init_test(sb), -EINVAL); + + es->s_def_hash_version = DX_HASH_HALF_MD4; + es->s_hash_seed[0] = cpu_to_le32(0x11223344U); + es->s_hash_seed[1] = cpu_to_le32(0x55667788U); + es->s_hash_seed[2] = cpu_to_le32(0x99aabbccU); + es->s_hash_seed[3] = cpu_to_le32(0xddeeff00U); + ext4_set_feature_dir_index(sb); + es->s_flags = cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH); + sbi->s_hash_unsigned = 0; + + KUNIT_EXPECT_EQ(test, ext4_hash_info_init_test(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_def_hash_version, + (unsigned char)DX_HASH_HALF_MD4); + KUNIT_EXPECT_EQ(test, sbi->s_hash_seed[0], 0x11223344U); + KUNIT_EXPECT_EQ(test, sbi->s_hash_seed[1], 0x55667788U); + KUNIT_EXPECT_EQ(test, sbi->s_hash_seed[2], 0x99aabbccU); + KUNIT_EXPECT_EQ(test, sbi->s_hash_seed[3], 0xddeeff00U); + KUNIT_EXPECT_EQ(test, sbi->s_hash_unsigned, 3); + + /* Unflagged dir_index superblock gets native hash signedness flag */ + es->s_flags = 0; + sbi->s_hash_unsigned = 0; + KUNIT_EXPECT_EQ(test, ext4_hash_info_init_test(sb), 0); + KUNIT_EXPECT_NE(test, le32_to_cpu(es->s_flags) & + (EXT2_FLAGS_SIGNED_HASH | EXT2_FLAGS_UNSIGNED_HASH), + 0U); +} + +static void test_check_geometry(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + + /* Excessive s_reserved_gdt_blocks (> blocksize / 4) */ + es->s_reserved_gdt_blocks = cpu_to_le16(SUPER_TEST_BLK_SIZE / 4 + 1); + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), -EINVAL); + es->s_reserved_gdt_blocks = cpu_to_le16(SUPER_TEST_RSV_GDT_BLKS); + + /* Filesystem block count exceeding device capacity */ + ctx->bdev.bd_nr_sectors = 1000; + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), -EINVAL); + ctx->bdev.bd_nr_sectors = 0; + + /* s_first_data_block >= blocks_count */ + es->s_first_data_block = cpu_to_le32(SUPER_TEST_TOTAL_BLKS); + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), -EINVAL); + + /* s_first_data_block == 0 on 1K blocksize without bigalloc */ + es->s_first_data_block = 0; + es->s_log_block_size = 0; + sbi->s_cluster_ratio = 1; + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), -EINVAL); + es->s_first_data_block = cpu_to_le32(SUPER_TEST_FIRST_DATA_BLK); + + /* Inode count mismatch against groups_count * inodes_per_group */ + es->s_inodes_count = cpu_to_le32(SUPER_TEST_TOTAL_INODES + 1); + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), -EINVAL); + + /* Valid 5-group geometry with partial final group */ + ext4_blocks_count_set(es, SUPER_TEST_FIRST_DATA_BLK + + 4 * SUPER_TEST_BLOCKS_PER_GRP + 200); + es->s_inodes_count = cpu_to_le32(5 * SUPER_TEST_INODES_PER_GRP); + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sbi->s_groups_count, 5U); +} + +static void test_descriptor_loc(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_super_block *es = &ctx->es; + + /* Non-meta_bg places descriptor blocks linearly after superblock */ + ext4_clear_feature_meta_bg(sb); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 0), 2ULL); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 2), 4ULL); + + /* + * With meta_bg and s_desc_per_block == 16 on 1K blocks: + * - nr == 0 -> bg 0 (has_super): block 2 for both first_data_block + * 1 and 0 (compensated) + * - nr == 1 -> bg 16 (no backup super under sparse_super): first + * block of group 16 + * - nr == 2 -> bg 32 ( still no backup super; 32 is power of 2): + * first block of group 32 + */ + ext4_set_feature_meta_bg(sb); + es->s_first_meta_bg = 0; + es->s_first_data_block = cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 0), 2ULL); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 1), + ext4_group_first_block_no(sb, 16)); + + es->s_first_data_block = 0; + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 0, 0), 2ULL); + + /* Hybrid s_first_meta_bg == 2 uses linear layout for nr < 2 */ + es->s_first_data_block = cpu_to_le32(1); + es->s_first_meta_bg = cpu_to_le32(2); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 0), 2ULL); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 1), 3ULL); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 2), + ext4_group_first_block_no(sb, 32)); +} + +static void test_superblock_and_group_desc_csum(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + struct ext4_group_desc gdp = {}; + + /* Superblock checksum type, verification, and seed derivation */ + es->s_checksum_type = 99; + KUNIT_EXPECT_EQ(test, ext4_init_metadata_csum_test(sb, es), -EINVAL); + + es->s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_superblock_csum_set(sb); + es->s_checksum ^= cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_init_metadata_csum_test(sb, es), -EFSBADCRC); + + ext4_clear_feature_csum_seed(sb); + ext4_superblock_csum_set(sb); + sbi->s_csum_seed = 0; + KUNIT_EXPECT_EQ(test, ext4_init_metadata_csum_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sbi->s_csum_seed, + ext4_chksum(~0, es->s_uuid, sizeof(es->s_uuid))); + + ext4_set_feature_csum_seed(sb); + es->s_checksum_seed = cpu_to_le32(0xdeadbeefU); + ext4_superblock_csum_set(sb); + KUNIT_EXPECT_EQ(test, ext4_init_metadata_csum_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sbi->s_csum_seed, 0xdeadbeefU); + + /* 32-byte vs 64-byte free_group_clusters accessor/mutator */ + sbi->s_desc_size = EXT4_MIN_DESC_SIZE; + ext4_free_group_clusters_set(sb, &gdp, 0x12345678U); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, &gdp), 0x5678U); + + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + ext4_free_group_clusters_set(sb, &gdp, 0x12345678U); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, &gdp), 0x12345678U); + + /* metadata_csum (CRC32C) group descriptor verification */ + ext4_group_desc_csum_set(sb, 3, &gdp); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 3, &gdp), 1); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 2, &gdp), 0); + gdp.bg_block_bitmap_hi = cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 3, &gdp), 0); + + /* Legacy gdt_csum (CRC16) verification across 64-byte descriptor */ + ext4_clear_feature_metadata_csum(sb); + ext4_set_feature_gdt_csum(sb); + ext4_group_desc_csum_set(sb, 1, &gdp); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 1, &gdp), 1); + gdp.bg_free_blocks_count_hi ^= cpu_to_le16(1); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 1, &gdp), 0); + + /* No checksum features enabled -> verify always succeeds */ + ext4_clear_feature_gdt_csum(sb); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 1, &gdp), 1); +} + +static void test_check_descriptors_and_flex_info(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct flex_groups *fg0, *fg1; + ext4_group_t first_not_zeroed = 0; + + ctx->gdps[2].bg_flags = 0; + ext4_group_desc_csum_set(sb, 2, &ctx->gdps[2]); + KUNIT_EXPECT_EQ(test, + ext4_check_descriptors_test(sb, 1, &first_not_zeroed), + 1); + KUNIT_EXPECT_EQ(test, first_not_zeroed, 2U); + + /* Block bitmap overlapping superblock fails RW, tolerated on RO */ + ext4_block_bitmap_set(sb, &ctx->gdps[0], 1); + ext4_group_desc_csum_set(sb, 0, &ctx->gdps[0]); + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 0); + sb->s_flags |= SB_RDONLY; + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 1); + sb->s_flags &= ~SB_RDONLY; + + /* Inode table overlapping GDT block (block 2) fails RW */ + super_setup_default_groups(ctx); + ext4_inode_table_set(sb, &ctx->gdps[0], 2); + ext4_group_desc_csum_set(sb, 0, &ctx->gdps[0]); + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 0); + + /* Out-of-group bitmap fails without flex_bg, succeeds with flex_bg */ + super_setup_default_groups(ctx); + ext4_block_bitmap_set(sb, &ctx->gdps[1], 20); + ext4_group_desc_csum_set(sb, 1, &ctx->gdps[1]); + sb->s_flags |= SB_RDONLY; + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 0); + sb->s_flags &= ~SB_RDONLY; + + ext4_set_feature_flex_bg(sb); + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 1); + + /* Bad group descriptor checksum fails RW, tolerated on RO */ + ctx->gdps[1].bg_checksum ^= cpu_to_le16(0xffff); + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 0); + sb->s_flags |= SB_RDONLY; + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 1); + sb->s_flags &= ~SB_RDONLY; + + /* Flex-bg allocation and per-flex-group counter aggregation */ + super_setup_default_groups(ctx); + ctx->es.s_log_groups_per_flex = 32; + KUNIT_EXPECT_EQ(test, ext4_fill_flex_info_test(sb), 1); + KUNIT_EXPECT_EQ(test, sbi->s_log_groups_per_flex, 0U); + + ext4_free_group_clusters_set(sb, &ctx->gdps[0], 100); + ext4_free_inodes_set(sb, &ctx->gdps[0], 10); + ext4_used_dirs_set(sb, &ctx->gdps[0], 2); + ext4_free_group_clusters_set(sb, &ctx->gdps[1], 150); + ext4_free_inodes_set(sb, &ctx->gdps[1], 12); + ext4_used_dirs_set(sb, &ctx->gdps[1], 3); + ext4_free_group_clusters_set(sb, &ctx->gdps[2], 200); + ext4_free_inodes_set(sb, &ctx->gdps[2], 14); + ext4_used_dirs_set(sb, &ctx->gdps[2], 1); + ext4_free_group_clusters_set(sb, &ctx->gdps[3], 250); + ext4_free_inodes_set(sb, &ctx->gdps[3], 16); + ext4_used_dirs_set(sb, &ctx->gdps[3], 4); + + ctx->es.s_log_groups_per_flex = 1; + KUNIT_EXPECT_EQ(test, ext4_fill_flex_info_test(sb), 1); + KUNIT_EXPECT_EQ(test, sbi->s_flex_groups_allocated, 2); + + fg0 = sbi_array_rcu_deref(sbi, s_flex_groups, 0); + fg1 = sbi_array_rcu_deref(sbi, s_flex_groups, 1); + KUNIT_EXPECT_EQ(test, atomic64_read(&fg0->free_clusters), 250LL); + KUNIT_EXPECT_EQ(test, atomic_read(&fg0->free_inodes), 22); + KUNIT_EXPECT_EQ(test, atomic_read(&fg0->used_dirs), 5); + KUNIT_EXPECT_EQ(test, atomic64_read(&fg1->free_clusters), 450LL); + KUNIT_EXPECT_EQ(test, atomic_read(&fg1->free_inodes), 30); + KUNIT_EXPECT_EQ(test, atomic_read(&fg1->used_dirs), 5); + + /* Growing the flex_bg array preserves populated entries */ + KUNIT_EXPECT_EQ(test, ext4_alloc_flex_bg_array(sb, 8), 0); + KUNIT_EXPECT_EQ(test, sbi->s_flex_groups_allocated, 4); + fg0 = sbi_array_rcu_deref(sbi, s_flex_groups, 0); + KUNIT_EXPECT_EQ(test, atomic64_read(&fg0->free_clusters), 250LL); +} + +static void test_max_sizes_stripe_and_resv_clusters(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + + /* Without huge_file, 2^32 - 1 512B sectors caps max extent file size */ + KUNIT_EXPECT_EQ(test, ext4_max_size_test(10, 0), + (((1LL << 32) - 1) >> 1) << 10); + KUNIT_EXPECT_EQ(test, ext4_max_size_test(12, 0), + (((1LL << 32) - 1) >> 3) << 12); + + /* With huge_file, 32-bit ee_block caps max size at (2^32 - 1) blocks */ + KUNIT_EXPECT_EQ(test, ext4_max_size_test(10, 1), + ((1LL << 32) - 1) << 10); + KUNIT_EXPECT_EQ(test, ext4_max_size_test(12, 1), + min_t(loff_t, ((1LL << 32) - 1) << 12, + MAX_LFS_FILESIZE)); + + /* Indirect bitmap max size is strictly smaller with !huge_file on 4K */ + KUNIT_EXPECT_LT(test, ext4_max_bitmap_size_test(12, 0), + ext4_max_bitmap_size_test(12, 1)); + KUNIT_EXPECT_EQ(test, ext4_max_bitmap_size_test(10, 1), + (12LL + 256 + 65536 + 16777216) << 10); + + /* Stripe priority: mount s_stripe -> raid_stripe_width -> stride */ + sbi->s_blocks_per_group = 1024; + sbi->s_stripe = 64; + ctx->es.s_raid_stripe_width = cpu_to_le32(128); + ctx->es.s_raid_stride = cpu_to_le16(16); + KUNIT_EXPECT_EQ(test, ext4_get_stripe_size_test(sbi), 64UL); + + sbi->s_stripe = 2048; + KUNIT_EXPECT_EQ(test, ext4_get_stripe_size_test(sbi), 128UL); + + ctx->es.s_raid_stripe_width = cpu_to_le32(2048); + KUNIT_EXPECT_EQ(test, ext4_get_stripe_size_test(sbi), 16UL); + + ctx->es.s_raid_stride = cpu_to_le16(1); + KUNIT_EXPECT_EQ(test, ext4_get_stripe_size_test(sbi), 0UL); + + /* Reserved clusters: skipped without extents, 2% up to 4096 cap */ + atomic64_set(&sbi->s_resv_clusters, 7); + ext4_clear_feature_extents(sb); + ext4_blocks_count_set(&ctx->es, 5000); + ext4_set_resv_clusters_test(sb); + KUNIT_EXPECT_EQ(test, atomic64_read(&sbi->s_resv_clusters), 7LL); + + ext4_set_feature_extents(sb); + ext4_set_resv_clusters_test(sb); + KUNIT_EXPECT_EQ(test, atomic64_read(&sbi->s_resv_clusters), 100LL); + + ext4_blocks_count_set(&ctx->es, 500000); + ext4_set_resv_clusters_test(sb); + KUNIT_EXPECT_EQ(test, atomic64_read(&sbi->s_resv_clusters), 4096LL); +} + +static void test_overhead_and_statfs(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct kstatfs st = {}; + char *buf; + + buf = kunit_kzalloc(test, SUPER_TEST_BLK_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + + /* + * Non-bigalloc per-group overhead: + * - groups 0, 1, 3: 1 (super) + 1 (gdb) + 2 (rsv_gdt) + 8 (itb) + 2 + * = 14 + * - group 2 (sparse_super): 0 + 0 + 0 + 8 (itb) + 2 = 10 + * Total with s_first_data_block == 1: 1 + 14 + 14 + 10 + 14 = 53 + */ + KUNIT_EXPECT_EQ(test, ext4_count_overhead_test(sb, 0, buf), 14); + KUNIT_EXPECT_EQ(test, ext4_count_overhead_test(sb, 2, buf), 10); + KUNIT_EXPECT_EQ(test, ext4_calculate_overhead(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_overhead, 53UL); + + /* Loaded internal journal adds j_total_len clusters */ + ctx->mock_journal.j_total_len = 64; + sbi->s_journal = &ctx->mock_journal; + KUNIT_EXPECT_EQ(test, ext4_calculate_overhead(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_overhead, 117UL); + sbi->s_journal = NULL; + + /* Unloaded internal journal falls back to ext4_get_journal_inode() */ + ctx->journal_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, ctx->journal_inode); + ctx->journal_inode->i_ino = EXT4_JOURNAL_INO; + ctx->journal_inode->i_mode = S_IFREG | 0600; + ctx->journal_inode->i_flags |= S_NOQUOTA; + set_nlink(ctx->journal_inode, 1); + i_size_write(ctx->journal_inode, 32 * SUPER_TEST_BLK_SIZE); + ext4_set_feature_journal(sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + KUNIT_EXPECT_EQ(test, ext4_calculate_overhead(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_overhead, 85UL); + ext4_clear_feature_journal(sb); + ctx->es.s_journal_inum = 0; + + /* Bigalloc deduplicates metadata blocks sharing the same cluster */ + ext4_set_feature_bigalloc(sb); + ctx->es.s_first_data_block = 0; + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + sbi->s_clusters_per_group = SUPER_TEST_BLOCKS_PER_GRP / 4; + sbi->s_groups_count = 1; + ext4_block_bitmap_set(sb, &ctx->gdps[0], 2); + ext4_inode_bitmap_set(sb, &ctx->gdps[0], 3); + ext4_inode_table_set(sb, &ctx->gdps[0], 4); + memset(buf, 0, SUPER_TEST_BLK_SIZE); + /* Cluster 0 holds super+gdb+bbitmap+ibitmap; clusters 1..2 hold itb */ + KUNIT_EXPECT_EQ(test, ext4_count_overhead_test(sb, 0, buf), 3); + + /* Restore 1:1 geometry and verify ext4_statfs accounting & clamping */ + ext4_clear_feature_bigalloc(sb); + ctx->es.s_first_data_block = cpu_to_le32(SUPER_TEST_FIRST_DATA_BLK); + sbi->s_cluster_bits = 0; + sbi->s_cluster_ratio = 1; + sbi->s_clusters_per_group = SUPER_TEST_BLOCKS_PER_GRP; + sbi->s_groups_count = SUPER_TEST_NGROUPS; + sbi->s_overhead = 53; + ext4_r_blocks_count_set(&ctx->es, 100); + atomic64_set(&sbi->s_resv_clusters, 20); + percpu_counter_set(&sbi->s_freeclusters_counter, 500); + percpu_counter_set(&sbi->s_dirtyclusters_counter, 50); + percpu_counter_set(&sbi->s_freeinodes_counter, 90); + + KUNIT_EXPECT_EQ(test, ext4_statfs_test(sb->s_root, &st), 0); + KUNIT_EXPECT_EQ(test, st.f_type, (long)EXT4_SUPER_MAGIC); + KUNIT_EXPECT_EQ(test, st.f_blocks, (u64)(SUPER_TEST_TOTAL_BLKS - 53)); + KUNIT_EXPECT_EQ(test, st.f_bfree, 450ULL); + KUNIT_EXPECT_EQ(test, st.f_bavail, 330ULL); + KUNIT_EXPECT_EQ(test, st.f_files, (u64)SUPER_TEST_TOTAL_INODES); + KUNIT_EXPECT_EQ(test, st.f_ffree, 90ULL); + KUNIT_EXPECT_EQ(test, st.f_namelen, (long)EXT4_NAME_LEN); + + /* MINIX_DF omits s_overhead; dirty > free clamps f_bfree/f_bavail */ + set_opt(sb, MINIX_DF); + percpu_counter_set(&sbi->s_freeclusters_counter, 30); + percpu_counter_set(&sbi->s_dirtyclusters_counter, 80); + KUNIT_EXPECT_EQ(test, ext4_statfs_test(sb->s_root, &st), 0); + KUNIT_EXPECT_EQ(test, st.f_blocks, (u64)SUPER_TEST_TOTAL_BLKS); + KUNIT_EXPECT_EQ(test, st.f_bfree, 0ULL); + KUNIT_EXPECT_EQ(test, st.f_bavail, 0ULL); +} + +static void test_mount_options_and_show_options(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + unsigned int ioprio = 0; + struct seq_file seq = {}; + char *out; + + out = kunit_kzalloc(test, 1024, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, out); + + /* Superblock default mount options */ + sbi->s_mount_opt = 0; + sbi->s_mount_opt2 = 0; + es->s_default_mount_opts = cpu_to_le32(EXT4_DEFM_DISCARD | + EXT4_DEFM_NOBARRIER | + EXT4_DEFM_JMODE_WBACK); + es->s_errors = cpu_to_le16(EXT4_ERRORS_CONTINUE); + ext4_set_feature_fast_commit(sb); + ext4_set_def_opts_test(sb, es); + + KUNIT_EXPECT_NE(test, test_opt(sb, DISCARD), 0); + KUNIT_EXPECT_EQ(test, test_opt(sb, BARRIER), 0); + KUNIT_EXPECT_EQ(test, test_opt(sb, DATA_FLAGS), + EXT4_MOUNT_WRITEBACK_DATA); + KUNIT_EXPECT_NE(test, test_opt(sb, ERRORS_CONT), 0); + KUNIT_EXPECT_NE(test, test_opt(sb, JOURNAL_CHECKSUM), 0); + KUNIT_EXPECT_NE(test, test_opt2(sb, JOURNAL_FAST_COMMIT), 0); + sbi->s_def_mount_opt = sbi->s_mount_opt; + sbi->s_def_mount_opt2 = sbi->s_mount_opt2; + + /* Valid option string parsing and application */ + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "nodelalloc,minixdf,commit=15,stripe=32,errors=panic", + false), + 0); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "resuid=1000,resgid=2000,inode_readahead_blks=64", + false), + 0); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "max_dir_size_kb=512", false), + 0); + KUNIT_EXPECT_EQ(test, test_opt(sb, DELALLOC), 0); + KUNIT_EXPECT_NE(test, test_opt(sb, MINIX_DF), 0); + KUNIT_EXPECT_EQ(test, sbi->s_commit_interval, 15UL * HZ); + KUNIT_EXPECT_EQ(test, sbi->s_stripe, 32UL); + KUNIT_EXPECT_EQ(test, from_kuid(&init_user_ns, sbi->s_resuid), 1000U); + KUNIT_EXPECT_EQ(test, from_kgid(&init_user_ns, sbi->s_resgid), 2000U); + KUNIT_EXPECT_EQ(test, sbi->s_inode_readahead_blks, 64U); + KUNIT_EXPECT_EQ(test, sbi->s_max_dir_size_kb, 512U); + KUNIT_EXPECT_NE(test, test_opt(sb, ERRORS_PANIC), 0); + + /* Invalid parameter values and consistency rejections */ + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "inode_readahead_blks=3", false), + -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "mb_optimize_scan=2", false), + -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "debug_want_extra_isize=200", false), + -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "debug_want_extra_isize=5", false), + -EINVAL); +#ifdef CONFIG_QUOTA + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "prjquota", false), + -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "usrjquota=aquota.user", false), + -EINVAL); +#endif + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "test_dummy_encryption", false), + -EINVAL); + + /* Remount restrictions on data= mode changes */ + sbi->s_journal = &ctx->mock_journal; + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "data=ordered", true), + -EINVAL); +#ifdef CONFIG_FS_DAX + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "dax=never", false), + 0); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "dax=always", true), + -EINVAL); +#else + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "dax=never", false), + -EINVAL); +#endif + sbi->s_journal = NULL; + + /* On-disk es->s_mount_opts parsing and malformed fallback */ + strscpy_pad(es->s_mount_opts, "nodiscard,commit=25,journal_ioprio=5"); + KUNIT_EXPECT_EQ(test, + ext4_parse_sb_mount_options_test(sb, NULL, &ioprio), + 0); + KUNIT_EXPECT_EQ(test, test_opt(sb, DISCARD), 0); + KUNIT_EXPECT_EQ(test, sbi->s_commit_interval, 25UL * HZ); + KUNIT_EXPECT_EQ(test, IOPRIO_PRIO_DATA(ioprio), 5UL); + + strscpy_pad(es->s_mount_opts, "nonexistent_opt=1"); + KUNIT_EXPECT_EQ(test, + ext4_parse_sb_mount_options_test(sb, NULL, NULL), 0); + + /* _ext4_show_options and ext4_seq_options_show formatting */ + seq.buf = out; + seq.size = 1023; + seq.private = sb; + KUNIT_EXPECT_EQ(test, ext4_show_options_test(&seq, sb, 0), 0); + out[seq.count] = '\0'; + KUNIT_EXPECT_NOT_NULL(test, strstr(out, ",minixdf")); + KUNIT_EXPECT_NOT_NULL(test, strstr(out, ",commit=25")); + KUNIT_EXPECT_NOT_NULL(test, strstr(out, ",stripe=32")); + KUNIT_EXPECT_NOT_NULL(test, strstr(out, ",errors=panic")); + + memset(out, 0, 1024); + seq.count = 0; + KUNIT_EXPECT_EQ(test, ext4_seq_options_show(&seq, NULL), 0); + out[seq.count] = '\0'; + KUNIT_EXPECT_TRUE(test, str_has_prefix(out, "rw\n")); + KUNIT_EXPECT_NOT_NULL(test, strstr(out, "\nresuid=1000\n")); +} + +static void test_error_recording_and_update_super(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + __le32 saved_wtime; + + KUNIT_EXPECT_EQ(test, ext4_errno_to_code_test(EIO), EXT4_ERR_EIO); + KUNIT_EXPECT_EQ(test, ext4_errno_to_code_test(ENOMEM), EXT4_ERR_ENOMEM); + KUNIT_EXPECT_EQ(test, ext4_errno_to_code_test(EFSCORRUPTED), + EXT4_ERR_EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, ext4_errno_to_code_test(ENOSPC), EXT4_ERR_ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_errno_to_code_test(999), EXT4_ERR_UNKNOWN); + + /* First error defaults 0 -> EFSCORRUPTED; second updates last only */ + ext4_save_error_info_test(sb, 0, 17, 1024, "first_fn", 111); + ext4_save_error_info_test(sb, EIO, 29, 2048, "second_fn", 222); + + KUNIT_EXPECT_EQ(test, sbi->s_add_error_count, 2U); + KUNIT_EXPECT_EQ(test, sbi->s_first_error_code, EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, sbi->s_last_error_code, EIO); + + sbi->s_kbytes_written = 100; + percpu_counter_set(&sbi->s_freeclusters_counter, 321); + percpu_counter_set(&sbi->s_freeinodes_counter, 45); + + ext4_update_super_test(sb); + + KUNIT_EXPECT_EQ(test, sbi->s_add_error_count, 0U); + KUNIT_EXPECT_NE(test, le16_to_cpu(es->s_state) & EXT4_ERROR_FS, 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_error_count), 2U); + KUNIT_EXPECT_EQ(test, es->s_first_error_errcode, + (u8)EXT4_ERR_EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_first_error_ino), 17U); + KUNIT_EXPECT_EQ(test, le64_to_cpu(es->s_first_error_block), 1024ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_first_error_line), 111U); + KUNIT_EXPECT_STREQ(test, (char *)es->s_first_error_func, "first_fn"); + + KUNIT_EXPECT_EQ(test, es->s_last_error_errcode, (u8)EXT4_ERR_EIO); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_last_error_ino), 29U); + KUNIT_EXPECT_EQ(test, le64_to_cpu(es->s_last_error_block), 2048ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_last_error_line), 222U); + KUNIT_EXPECT_STREQ(test, (char *)es->s_last_error_func, "second_fn"); + + KUNIT_EXPECT_EQ(test, ext4_free_blocks_count(es), 321ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_free_inodes_count), 45U); + KUNIT_EXPECT_EQ(test, le64_to_cpu(es->s_kbytes_written), 100ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_checksum), + le32_to_cpu(ext4_superblock_csum(es))); + + /* Read-only superblock update must not touch s_wtime */ + es->s_wtime = cpu_to_le32(123456U); + saved_wtime = es->s_wtime; + sb->s_flags |= SB_RDONLY; + ext4_update_super_test(sb); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_wtime), + le32_to_cpu(saved_wtime)); +} + +static struct kunit_case ext4_super_test_cases[] = { + KUNIT_CASE(test_feature_set_and_compatibility), + KUNIT_CASE(test_inode_info_init), + KUNIT_CASE(test_block_group_meta_and_clustersize), + KUNIT_CASE(test_hash_info_init), + KUNIT_CASE(test_check_geometry), + KUNIT_CASE(test_descriptor_loc), + KUNIT_CASE(test_superblock_and_group_desc_csum), + KUNIT_CASE(test_check_descriptors_and_flex_info), + KUNIT_CASE(test_max_sizes_stripe_and_resv_clusters), + KUNIT_CASE(test_overhead_and_statfs), + KUNIT_CASE(test_mount_options_and_show_options), + KUNIT_CASE(test_error_recording_and_update_super), + {} +}; + +static struct kunit_suite ext4_super_test_suite = { + .name = "ext4_super_test", + .init = super_test_init, + .test_cases = ext4_super_test_cases, +}; + +kunit_test_suites(&ext4_super_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 superblock validation and options"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/super.c b/fs/ext4/super.c index d03d5dd8d6eb00..cccbb2e3ad5f98 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -336,6 +336,7 @@ __le32 ext4_superblock_csum(struct ext4_super_block *es) return cpu_to_le32(csum); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_superblock_csum); static int ext4_superblock_csum_verify(struct super_block *sb, struct ext4_super_block *es) @@ -3199,6 +3200,7 @@ int ext4_seq_options_show(struct seq_file *seq, void *offset) seq_putc(seq, '\n'); return rc; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_seq_options_show); static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es, int read_only) @@ -3304,6 +3306,7 @@ int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup) ext4_kvfree_array_rcu(old_groups); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_alloc_flex_bg_array); static int ext4_fill_flex_info(struct super_block *sb) { @@ -3777,6 +3780,7 @@ int ext4_feature_set_ok(struct super_block *sb, int readonly) #endif /* CONFIG_QUOTA */ return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_feature_set_ok); /* * This function is called once a day by default if we have errors logged @@ -4388,6 +4392,7 @@ int ext4_calculate_overhead(struct super_block *sb) kvfree(buf); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_calculate_overhead); static void ext4_set_resv_clusters(struct super_block *sb) { @@ -7743,4 +7748,218 @@ module_exit(ext4_exit_fs) #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_bread); + +int ext4_errno_to_code_test(int err) +{ + return ext4_errno_to_code(err); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_errno_to_code_test); + +void ext4_save_error_info_test(struct super_block *sb, int error, + __u32 ino, __u64 block, + const char *func, unsigned int line) +{ + save_error_info(sb, error, ino, block, func, line); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_save_error_info_test); + +void ext4_update_super_test(struct super_block *sb) +{ + ext4_update_super(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_super_test); + +int ext4_check_descriptors_test(struct super_block *sb, + ext4_fsblk_t sb_block, + ext4_group_t *first_not_zeroed) +{ + return ext4_check_descriptors(sb, sb_block, first_not_zeroed); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_descriptors_test); + +loff_t ext4_max_size_test(int blkbits, int has_huge_files) +{ + return ext4_max_size(blkbits, has_huge_files); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_max_size_test); + +loff_t ext4_max_bitmap_size_test(int bits, int has_huge_files) +{ + return ext4_max_bitmap_size(bits, has_huge_files); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_max_bitmap_size_test); + +ext4_fsblk_t ext4_descriptor_loc_test(struct super_block *sb, + ext4_fsblk_t logical_sb_block, int nr) +{ + return descriptor_loc(sb, logical_sb_block, nr); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_descriptor_loc_test); + +unsigned long ext4_get_stripe_size_test(struct ext4_sb_info *sbi) +{ + return ext4_get_stripe_size(sbi); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_stripe_size_test); + +int ext4_count_overhead_test(struct super_block *sb, ext4_group_t grp, + char *buf) +{ + return count_overhead(sb, grp, buf); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_count_overhead_test); + +void ext4_set_resv_clusters_test(struct super_block *sb) +{ + ext4_set_resv_clusters(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_resv_clusters_test); + +void ext4_set_def_opts_test(struct super_block *sb, + struct ext4_super_block *es) +{ + ext4_set_def_opts(sb, es); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_def_opts_test); + +int ext4_handle_clustersize_test(struct super_block *sb) +{ + return ext4_handle_clustersize(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_handle_clustersize_test); + +int ext4_inode_info_init_test(struct super_block *sb, + struct ext4_super_block *es) +{ + return ext4_inode_info_init(sb, es); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_info_init_test); + +int ext4_init_metadata_csum_test(struct super_block *sb, + struct ext4_super_block *es) +{ + return ext4_init_metadata_csum(sb, es); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_metadata_csum_test); + +int ext4_check_feature_compatibility_test(struct super_block *sb, + struct ext4_super_block *es, + int silent) +{ + return ext4_check_feature_compatibility(sb, es, silent); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_feature_compatibility_test); + +int ext4_check_geometry_test(struct super_block *sb, + struct ext4_super_block *es) +{ + return ext4_check_geometry(sb, es); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_geometry_test); + +int ext4_hash_info_init_test(struct super_block *sb) +{ + return ext4_hash_info_init(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_hash_info_init_test); + +int ext4_block_group_meta_init_test(struct super_block *sb, int silent) +{ + return ext4_block_group_meta_init(sb, silent); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_group_meta_init_test); + +int ext4_fill_flex_info_test(struct super_block *sb) +{ + return ext4_fill_flex_info(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fill_flex_info_test); + +void ext4_flex_groups_free_test(struct ext4_sb_info *sbi) +{ + ext4_flex_groups_free(sbi); + rcu_assign_pointer(sbi->s_flex_groups, NULL); + sbi->s_flex_groups_allocated = 0; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_flex_groups_free_test); + +int ext4_show_options_test(struct seq_file *seq, struct super_block *sb, + int nodefs) +{ + return _ext4_show_options(seq, sb, nodefs); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_show_options_test); + +int ext4_statfs_test(struct dentry *dentry, struct kstatfs *buf) +{ + return ext4_statfs(dentry, buf); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_statfs_test); + +int ext4_parse_and_apply_options_test(struct super_block *sb, + const char *options, bool is_remount) +{ + struct ext4_fs_context *ctx; + struct fs_context *fc; + char *opts_copy = NULL; + int ret; + + if (options) { + opts_copy = kstrdup(options, GFP_KERNEL); + if (!opts_copy) + return -ENOMEM; + } + + fc = kzalloc_obj(*fc); + if (!fc) { + kfree(opts_copy); + return -ENOMEM; + } + + ctx = kzalloc_obj(*ctx); + if (!ctx) { + kfree(fc); + kfree(opts_copy); + return -ENOMEM; + } + + fc->fs_private = ctx; + fc->s_fs_info = EXT4_SB(sb); + fc->purpose = is_remount ? FS_CONTEXT_FOR_RECONFIGURE : + FS_CONTEXT_FOR_MOUNT; + + ret = parse_options(fc, opts_copy); + if (ret == 0) { + down_write(&sb->s_umount); + ret = ext4_check_opt_consistency(fc, sb); + if (ret == 0) + ext4_apply_options(fc, sb); + up_write(&sb->s_umount); + } + + kfree(opts_copy); + ext4_fc_free(fc); + kfree(fc); + return ret; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_parse_and_apply_options_test); + +int ext4_parse_sb_mount_options_test(struct super_block *sb, + unsigned long *journal_devnum, + unsigned int *journal_ioprio) +{ + struct ext4_fs_context m_ctx = {}; + int ret; + + down_write(&sb->s_umount); + ret = parse_apply_sb_mount_options(sb, &m_ctx); + up_write(&sb->s_umount); + + if (journal_devnum) + *journal_devnum = m_ctx.journal_devnum; + if (journal_ioprio) + *journal_ioprio = m_ctx.journal_ioprio; + return ret; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_parse_sb_mount_options_test); #endif From f316c4350ef62ad23b5c0e657921ae008979492f Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:36:15 +0000 Subject: [PATCH 1568/2102] ext4: add KUnit tests for fs/ext4/sysfs.c Add a KUnit test suite (ext4_sysfs_test) covering ext4 sysfs attribute show/store handlers, feature capability attributes, and sysfs/procfs registration in fs/ext4/sysfs.c: - Generic pointer attributes across sbi, superblock, and explicit targets (attr_pointer_ui, attr_pointer_ul, attr_pointer_pi negative value rejection, attr_pointer_u8, attr_pointer_u64 LE64 decoding, attr_pointer_string 32-byte bounding, and attr_pointer_atomic). - Range-checked read-write attributes: inode_readahead_blks power-of-2 and upper-bound enforcement, reserved_clusters bounds against total clusters, mb_best_avail_max_trim_order <= 64, mb_group_prealloc <= s_clusters_per_group, and err_report_sec <= 1 year. - Computed read-only attributes: delayed_allocation_blocks cluster-to- block scaling, session_write_kbytes and lifetime_write_kbytes sector accounting, sra_exceeded_retry_limit percpu summation, 40-bit error timestamps (first_error_time / last_error_time), and journal_task. - Feature capability attributes under /sys/fs/ext4/features, error injection via trigger_fs_error, and lifecycle coverage of ext4_register_sysfs(), ext4_notify_error_sysfs(), and ext4_unregister_sysfs(). Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 3 +- fs/ext4/ext4.h | 8 + fs/ext4/sysfs-test.c | 679 +++++++++++++++++++++++++++++++++++++++++++ fs/ext4/sysfs.c | 55 ++++ 4 files changed, 744 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/sysfs-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index ca1a1201cbfeed..ff489dff825dbb 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -20,7 +20,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ namei-test.o inline-test.o \ fast_commit-test.o ialloc-test.o \ balloc-test.o orphan-test.o \ - block_validity-test.o super-test.o + block_validity-test.o super-test.o \ + sysfs-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index 81d3f48c44c1a3..a704783e4356e3 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -4074,6 +4074,14 @@ extern int ext4_register_sysfs(struct super_block *sb); extern void ext4_unregister_sysfs(struct super_block *sb); extern int __init ext4_init_sysfs(void); extern void ext4_exit_sysfs(void); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern ssize_t ext4_sysfs_attr_show_test(struct ext4_sb_info *sbi, + const char *name, char *buf); +extern ssize_t ext4_sysfs_attr_store_test(struct ext4_sb_info *sbi, + const char *name, const char *buf, + size_t len); +extern ssize_t ext4_sysfs_feat_show_test(const char *name, char *buf); +#endif /* block_validity */ extern void ext4_release_system_zone(struct super_block *sb); diff --git a/fs/ext4/sysfs-test.c b/fs/ext4/sysfs-test.c new file mode 100644 index 00000000000000..eca33ff625087e --- /dev/null +++ b/fs/ext4/sysfs-test.c @@ -0,0 +1,679 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/sysfs.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" + +#define SYSFS_TEST_BLK_SIZE 4096U +#define SYSFS_TEST_BLK_BITS 12U +#define SYSFS_TEST_TOTAL_BLKS 4096U +#define SYSFS_TEST_CLUSTERS_PER_GRP 256U + +struct sysfs_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct inode buddy_inode; + struct buffer_head sb_bh; + journal_t mock_journal; + bool counters_inited; +}; + +static struct inode *sysfs_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = 32; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void sysfs_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void sysfs_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **sysfs_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations sysfs_test_sops = { + .alloc_inode = sysfs_test_alloc_inode, + .free_inode = sysfs_test_free_inode, + .evict_inode = sysfs_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = sysfs_test_get_dquots, +#endif +}; + +static void sysfs_test_sb_upd_work(struct work_struct *work) +{ +} + +static void sysfs_test_err_timer(struct timer_list *t) +{ +} + +static int sysfs_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type sysfs_test_fs_type = { + .name = "ext4_sysfs_kunit", + .init_fs_context = sysfs_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void sysfs_test_cleanup(struct sysfs_test_ctx *ctx) +{ + ctx->sbi.s_journal = NULL; + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + deactivate_super(ctx->sb); + rcu_barrier(); + + if (ctx->counters_inited) { + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_sra_exceeded_retry_limit); + } + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(sysfs_test_cleanup_action, sysfs_test_cleanup, + struct sysfs_test_ctx *); + +static int sysfs_test_init(struct kunit *test) +{ + struct sysfs_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + if (!ctx->bdev.bd_stats) { + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bd_stats"); + } + + fc = fs_context_for_mount(&sysfs_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + if (err) + goto err_sb; + err = percpu_counter_init(&sbi->s_sra_exceeded_retry_limit, 0, + GFP_KERNEL); + if (err) { + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + goto err_sb; + } + ctx->counters_inited = true; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &sysfs_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = SYSFS_TEST_BLK_SIZE; + sb->s_blocksize_bits = SYSFS_TEST_BLK_BITS; + strscpy(sb->s_id, "ext4_sysfs_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = SYSFS_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + inode_init_once(&ctx->buddy_inode); + ctx->buddy_inode.i_sb = sb; + sbi->s_buddy_cache = &ctx->buddy_inode; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ext4_blocks_count_set(&ctx->es, SYSFS_TEST_TOTAL_BLKS); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + sbi->s_clusters_per_group = SYSFS_TEST_CLUSTERS_PER_GRP; + set_opt(sb, ERRORS_CONT); + + mutex_init(&sbi->s_error_notify_mutex); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + INIT_WORK(&sbi->s_sb_upd_work, sysfs_test_sb_upd_work); + timer_setup(&sbi->s_err_report, sysfs_test_err_timer, 0); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + root_inode = new_inode(sb); + if (!root_inode) { + err = -ENOMEM; + goto err_counters; + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_flags |= S_NOQUOTA; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + err = -ENOMEM; + goto err_counters; + } + + up_write(&sb->s_umount); + + err = kunit_add_action_or_reset(test, sysfs_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + return 0; + +err_counters: + percpu_counter_destroy(&sbi->s_sra_exceeded_retry_limit); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); +err_sb: + deactivate_locked_super(sb); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + return err; +} + +static void test_generic_pointer_attrs(struct kunit *test) +{ + struct sysfs_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + char *buf; + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_show_test(sbi, "no_such_attr", buf), + (ssize_t)-ENOENT); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "no_such_attr", + "1", 1), + (ssize_t)-ENOENT); + + /* Explicit pointer RO attr: max_writeback_mb_bump == 128 */ + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, + "max_writeback_mb_bump", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "128\n"); + + /* RW sbi unsigned int (attr_pointer_ui) and unsigned long (ul) */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "inode_goal", + " 42\n", 5), + (ssize_t)5); + KUNIT_EXPECT_EQ(test, sbi->s_inode_goal, 42U); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "inode_goal", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "42\n"); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "last_trim_minblks", + "1048576", 7), + (ssize_t)7); + KUNIT_EXPECT_EQ(test, sbi->s_last_trim_minblks, 1048576UL); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "last_trim_minblks", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "1048576\n"); + + /* RW positive int (attr_pointer_pi) rejects negative values */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_ratelimit_burst", + "-1", 2), + (ssize_t)-EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_ratelimit_burst", + "0x80000000", 10), + (ssize_t)-EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_ratelimit_burst", + "15", 2), + (ssize_t)2); + KUNIT_EXPECT_EQ(test, sbi->s_err_ratelimit_state.burst, 15); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "err_ratelimit_burst", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "15\n"); + + /* RO atomic_t on sbi */ + atomic_set(&sbi->s_warning_count, 9); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "warning_count", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "9\n"); + + /* RO superblock LE32, U8, LE64, and fixed-size string attrs */ + es->s_error_count = cpu_to_le32(77); + es->s_first_error_errcode = EXT4_ERR_EIO; + es->s_first_error_block = cpu_to_le64(0x123456789abcULL); + memset(es->s_first_error_func, 'A', sizeof(es->s_first_error_func)); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "errors_count", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "77\n"); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "first_error_errcode", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "2\n"); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "first_error_block", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "20015998343868\n"); + + /* Non-NUL-terminated 32-byte s_first_error_func is bounded to 32 */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_show_test(sbi, "first_error_func", + buf), + (ssize_t)33); + KUNIT_EXPECT_EQ(test, buf[32], '\n'); +} + +static void test_validated_rw_attrs(struct kunit *test) +{ + struct sysfs_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + char *buf; + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + + /* inode_readahead_blks: 0 or power-of-2 <= 0x40000000 */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "inode_readahead_blks", + "0", 1), + (ssize_t)1); + KUNIT_EXPECT_EQ(test, sbi->s_inode_readahead_blks, 0U); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "inode_readahead_blks", + "0x40000000", 10), + (ssize_t)10); + KUNIT_EXPECT_EQ(test, sbi->s_inode_readahead_blks, 0x40000000U); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "inode_readahead_blks", + "3", 1), + (ssize_t)-EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "inode_readahead_blks", + "0x80000000", 10), + (ssize_t)-EINVAL); + + /* + * reserved_clusters: 4096 blocks >> 2 cluster_bits == 1024 clusters; + * valid range is [0, 1023]. + */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "reserved_clusters", + "1023", 4), + (ssize_t)4); + KUNIT_EXPECT_EQ(test, atomic64_read(&sbi->s_resv_clusters), 1023LL); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "reserved_clusters", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "1023\n"); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "reserved_clusters", + "1024", 4), + (ssize_t)-EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "reserved_clusters", + "0xffffffffffffffff", 18), + (ssize_t)-EINVAL); + + /* mb_best_avail_max_trim_order: [0, 64] */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, + "mb_best_avail_max_trim_order", "64", 2), + (ssize_t)2); + KUNIT_EXPECT_EQ(test, sbi->s_mb_best_avail_max_trim_order, 64U); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, + "mb_best_avail_max_trim_order", "65", 2), + (ssize_t)-EINVAL); + + /* mb_group_prealloc: [0, s_clusters_per_group == 256] */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "mb_group_prealloc", + "256", 3), + (ssize_t)3); + KUNIT_EXPECT_EQ(test, sbi->s_mb_group_prealloc, 256U); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "mb_group_prealloc", + "257", 3), + (ssize_t)-EINVAL); + + /* err_report_sec: <= 365 * 24 * 60 * 60 (31536000) */ + sbi->s_err_report_sec = 0; + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_report_sec", + "3600", 4), + (ssize_t)4); + KUNIT_EXPECT_EQ(test, sbi->s_err_report_sec, 3600UL); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_report_sec", + "31536000", 8), + (ssize_t)8); + KUNIT_EXPECT_EQ(test, sbi->s_err_report_sec, 31536000UL); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "err_report_sec", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "31536000\n"); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_report_sec", + "31536001", 8), + (ssize_t)-EINVAL); +} + +static void test_computed_ro_and_error_time_attrs(struct kunit *test) +{ + struct sysfs_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + char expected_pid[32]; + char *buf; + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + + /* 7 dirty clusters * 4 blocks/cluster == 28 delayed allocation blks */ + percpu_counter_set(&sbi->s_dirtyclusters_counter, 7); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, + "delayed_allocation_blocks", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "28\n"); + + /* (50 - 10) sectors >> 1 == 20 KB session, + 100 == 120 KB lifetime */ + sbi->s_sectors_written_start = 10; + sbi->s_kbytes_written = 100; + part_stat_lock(); + part_stat_add(&ctx->bdev, sectors[STAT_WRITE], 50); + part_stat_unlock(); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "session_write_kbytes", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "20\n"); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "lifetime_write_kbytes", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "120\n"); + + /* sra_exceeded_retry_limit sums percpu counter */ + percpu_counter_set(&sbi->s_sra_exceeded_retry_limit, 13); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, + "sra_exceeded_retry_limit", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "13\n"); + + /* 40-bit timestamp formatting: (2 << 32) + 100 == 8589934692 */ + es->s_first_error_time = cpu_to_le32(100); + es->s_first_error_time_hi = 2; + es->s_last_error_time = cpu_to_le32(250); + es->s_last_error_time_hi = 0; + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "first_error_time", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "8589934692\n"); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "last_error_time", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "250\n"); + + /* journal_task emits "\n" without journal, or j_task PID */ + sbi->s_journal = NULL; + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "journal_task", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "\n"); + + ctx->mock_journal.j_task = current; + sbi->s_journal = &ctx->mock_journal; + snprintf(expected_pid, sizeof(expected_pid), "%d\n", + task_pid_vnr(current)); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "journal_task", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, expected_pid); + sbi->s_journal = NULL; +} + +static void test_feature_attrs_and_trigger_error(struct kunit *test) +{ + struct sysfs_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + static const char * const feat_names[] = { + "lazy_itable_init", + "batched_discard", + "meta_bg_resize", + "metadata_csum_seed", + "fast_commit", +#ifdef CONFIG_FS_ENCRYPTION + "encryption", + "test_dummy_encryption_v2", +#endif +#if IS_ENABLED(CONFIG_UNICODE) + "casefold", +#endif +#ifdef CONFIG_FS_VERITY + "verity", +#endif +#if IS_ENABLED(CONFIG_UNICODE) && defined(CONFIG_FS_ENCRYPTION) + "encrypted_casefold", +#endif + }; + char *buf; + size_t i; + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + + for (i = 0; i < ARRAY_SIZE(feat_names); i++) { + KUNIT_EXPECT_GT_MSG(test, + ext4_sysfs_feat_show_test(feat_names[i], + buf), + (ssize_t)0, "feat=%s", feat_names[i]); + KUNIT_EXPECT_STREQ_MSG(test, buf, "supported\n", + "feat=%s", feat_names[i]); + } + KUNIT_EXPECT_EQ(test, ext4_sysfs_feat_show_test("unknown_feat", buf), + (ssize_t)-ENOENT); + + /* Empty newline write to trigger_fs_error is a no-op */ + sbi->s_journal = &ctx->mock_journal; + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "trigger_fs_error", + "\n", 1), + (ssize_t)1); + KUNIT_EXPECT_EQ(test, sbi->s_mount_state & EXT4_ERROR_FS, 0); + + /* Non-empty message records error state via ext4_error() */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "trigger_fs_error", + "kunit injected\n", 15), + (ssize_t)15); + KUNIT_EXPECT_NE(test, sbi->s_mount_state & EXT4_ERROR_FS, 0); + if (IS_ENABLED(CONFIG_PRINTK)) + KUNIT_EXPECT_STREQ(test, sbi->s_last_error_func, + "trigger_test_error"); + else + KUNIT_EXPECT_STREQ(test, sbi->s_last_error_func, ""); + sbi->s_journal = NULL; +} + +static void test_sysfs_register_notify_and_unregister(struct kunit *test) +{ + struct sysfs_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + + KUNIT_ASSERT_EQ(test, ext4_register_sysfs(sb), 0); + KUNIT_EXPECT_EQ(test, (int)sbi->s_kobj.state_in_sysfs, 1); + + ext4_notify_error_sysfs(sbi); + + ext4_unregister_sysfs(sb); + KUNIT_EXPECT_EQ(test, (int)sbi->s_kobj.state_in_sysfs, 0); + kobject_put(&sbi->s_kobj); + wait_for_completion(&sbi->s_kobj_unregister); +} + +static struct kunit_case ext4_sysfs_test_cases[] = { + KUNIT_CASE(test_generic_pointer_attrs), + KUNIT_CASE(test_validated_rw_attrs), + KUNIT_CASE(test_computed_ro_and_error_time_attrs), + KUNIT_CASE(test_feature_attrs_and_trigger_error), + KUNIT_CASE(test_sysfs_register_notify_and_unregister), + {} +}; + +static struct kunit_suite ext4_sysfs_test_suite = { + .name = "ext4_sysfs_test", + .init = sysfs_test_init, + .test_cases = ext4_sysfs_test_cases, +}; + +kunit_test_suites(&ext4_sysfs_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 sysfs and procfs interfaces"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/sysfs.c b/fs/ext4/sysfs.c index 923b375e017faa..faa76f02109919 100644 --- a/fs/ext4/sysfs.c +++ b/fs/ext4/sysfs.c @@ -602,6 +602,7 @@ void ext4_notify_error_sysfs(struct ext4_sb_info *sbi) sysfs_notify(&sbi->s_kobj, NULL, "errors_count"); mutex_unlock(&sbi->s_error_notify_mutex); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_notify_error_sysfs); static struct kobject *ext4_root; @@ -642,6 +643,7 @@ int ext4_register_sysfs(struct super_block *sb) } return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_register_sysfs); void ext4_unregister_sysfs(struct super_block *sb) { @@ -654,6 +656,7 @@ void ext4_unregister_sysfs(struct super_block *sb) kobject_del(&sbi->s_kobj); mutex_unlock(&sbi->s_error_notify_mutex); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_unregister_sysfs); int __init ext4_init_sysfs(void) { @@ -696,3 +699,55 @@ void ext4_exit_sysfs(void) ext4_proc_root = NULL; } +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +static struct attribute *ext4_find_attr_test(struct attribute **list, + const char *name) +{ + for (; *list; list++) { + if (strcmp((*list)->name, name) == 0) + return *list; + } + return NULL; +} + +ssize_t ext4_sysfs_attr_show_test(struct ext4_sb_info *sbi, const char *name, + char *buf) +{ + struct attribute *attr = ext4_find_attr_test(ext4_attrs, name); + + if (!attr) + return -ENOENT; + return ext4_attr_show(&sbi->s_kobj, attr, buf); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sysfs_attr_show_test); + +ssize_t ext4_sysfs_attr_store_test(struct ext4_sb_info *sbi, const char *name, + const char *buf, size_t len) +{ + struct attribute *attr = ext4_find_attr_test(ext4_attrs, name); + + if (!attr) + return -ENOENT; + return ext4_attr_store(&sbi->s_kobj, attr, buf, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sysfs_attr_store_test); + +ssize_t ext4_sysfs_feat_show_test(const char *name, char *buf) +{ + struct attribute *attr = ext4_find_attr_test(ext4_feat_attrs, name); + struct ext4_sb_info *dummy_sbi; + ssize_t ret; + + if (!attr) + return -ENOENT; + /* struct ext4_sb_info is too large to place on the stack */ + dummy_sbi = kzalloc_obj(*dummy_sbi); + if (!dummy_sbi) + return -ENOMEM; + ret = ext4_attr_show(&dummy_sbi->s_kobj, attr, buf); + kfree(dummy_sbi); + return ret; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sysfs_feat_show_test); +#endif + From 6fa4f16326dba7c5e6f1b0399f777da3321ad365 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:23:24 +0000 Subject: [PATCH 1569/2102] ext4: add KUnit tests for fs/ext4/ioctl.c Add a KUnit test suite (ext4_ioctl_test) covering superblock online tuning, backup superblock propagation, inode data swapping, fileattr validation, forced shutdown, and ioctl dispatch in fs/ext4/ioctl.c: - Superblock modification callbacks (ext4_sb_setlabel, ext4_sb_setuuid, and ext4_sb_setparams across error behavior, mount counts, 64-bit reserved blocks, 32-bit split reserved uid/gid, hash/RAID/encoding fields, mount_opts, DIR_INDEX / CSUM_SEED feature edits, and FORCE_FSCK). - Parameter validation and normalization in ext4_validate_tune_sb_params (-E2BIG mount_opts, -EOPNOTSUPP flags/feature clears, reserved_blocks and hash algorithm bounds, DIR_INDEX hash seed initialization, and CASEFOLD encoding defaults). - Primary and sparse_super backup superblock updates via ext4_update_backup_sb, ext4_update_superblocks_fn (including EXT4_FLAGS_RESIZING contention and unjournaled >2 backup updates), and ext4_update_overhead skip/force semantics. - Inode swap rollback invariants in swap_inode_data (swapped vs preserved flags, extent status cache clearing, double-swap round-trip) and metadata_csum seed recalculation in ext4_reset_inode_seed. - Immutable enforcement, DAX mutual-exclusion rules (including inline directories and verity-in-progress), and end-to-end ext4_fileattr_get / ext4_fileattr_set flag masking and VFS flag synchronization. - Forced shutdown state transitions (ext4_force_shutdown) and ext4_ioctl / ext4_compat_ioctl dispatch checks. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 33 ++ fs/ext4/ioctl-test.c | 1198 ++++++++++++++++++++++++++++++++++++++++++ fs/ext4/ioctl.c | 249 ++++++--- 4 files changed, 1411 insertions(+), 71 deletions(-) create mode 100644 fs/ext4/ioctl-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index ff489dff825dbb..c1853050886326 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -21,7 +21,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ fast_commit-test.o ialloc-test.o \ balloc-test.o orphan-test.o \ block_validity-test.o super-test.o \ - sysfs-test.o + sysfs-test.o ioctl-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index a704783e4356e3..afde7567c66196 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -3370,6 +3370,39 @@ int ext4_fileattr_get(struct dentry *dentry, struct file_kattr *fa); extern void ext4_reset_inode_seed(struct inode *inode); int ext4_update_overhead(struct super_block *sb, bool force); int ext4_force_shutdown(struct super_block *sb, u32 flags); +int ext4_ioctl_sync_bh(struct buffer_head *bh); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +struct ext4_tune_sb_params; +void ext4_sb_setlabel_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg); +void ext4_sb_setuuid_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg); +void ext4_sb_setparams_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg); +int ext4_validate_tune_sb_params_test(struct super_block *sb, + struct ext4_tune_sb_params *params); +int ext4_update_primary_sb_test(struct super_block *sb, handle_t *handle, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg); +int ext4_update_backup_sb_test(struct super_block *sb, handle_t *handle, + ext4_group_t grp, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg); +int ext4_update_superblocks_fn_test(struct super_block *sb, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg); +void ext4_swap_inode_data_test(struct inode *inode1, struct inode *inode2); +int ext4_ioctl_check_immutable_test(struct inode *inode, __u32 new_projid, + unsigned int flags); +bool ext4_dax_compatible_test(struct inode *inode, unsigned int oldflags, + unsigned int flags); +#endif /* migrate.c */ extern int ext4_ext_migrate(struct inode *); diff --git a/fs/ext4/ioctl-test.c b/fs/ext4/ioctl-test.c new file mode 100644 index 00000000000000..8cdb4f7dd639be --- /dev/null +++ b/fs/ext4/ioctl-test.c @@ -0,0 +1,1198 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/ioctl.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" + +#define IOCTL_TEST_NGROUPS 8U +#define IOCTL_TEST_BLK_SIZE 1024U +#define IOCTL_TEST_BLK_BITS 10U +#define IOCTL_TEST_BLOCKS_PER_GRP 1024U +#define IOCTL_TEST_FIRST_DATA_BLK 1U +#define IOCTL_TEST_TOTAL_BLKS (IOCTL_TEST_FIRST_DATA_BLK + \ + IOCTL_TEST_NGROUPS * \ + IOCTL_TEST_BLOCKS_PER_GRP) +#define IOCTL_TEST_INODE_SIZE 256U +#define IOCTL_TEST_EXTRA_ISIZE 32U +#define IOCTL_TEST_INODES_PER_GRP 32U +#define IOCTL_TEST_TOTAL_INODES (IOCTL_TEST_NGROUPS * \ + IOCTL_TEST_INODES_PER_GRP) +#define IOCTL_TEST_FIRST_INO 11U + +struct ioctl_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct folio *bh_folio; + struct buffer_head sb_bh; + u8 primary_sb_buf[IOCTL_TEST_BLK_SIZE]; + struct buffer_head backup_bhs[IOCTL_TEST_NGROUPS]; + u8 backup_sb_bufs[IOCTL_TEST_NGROUPS][IOCTL_TEST_BLK_SIZE]; + struct buffer_head iloc_bh; + u8 iloc_buf[IOCTL_TEST_BLK_SIZE]; + int sync_bh_calls; + int sync_bh_err; + bool es_shrinker_inited; +}; + +static struct kunit *active_ioctl_test; + +static struct inode *ioctl_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = IOCTL_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void ioctl_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void ioctl_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **ioctl_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations ioctl_test_sops = { + .alloc_inode = ioctl_test_alloc_inode, + .free_inode = ioctl_test_free_inode, + .evict_inode = ioctl_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = ioctl_test_get_dquots, +#endif +}; + +static void ioctl_test_sb_upd_work(struct work_struct *work) +{ +} + +static void ioctl_test_err_timer(struct timer_list *t) +{ +} + +static int ioctl_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type ioctl_test_fs_type = { + .name = "ext4_ioctl_kunit", + .init_fs_context = ioctl_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static struct buffer_head *ioctl_sb_bread_stub(struct super_block *sb, + sector_t block, + blk_opf_t op_flags) +{ + struct kunit *test = active_ioctl_test; + struct ioctl_test_ctx *ctx; + ext4_group_t g; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return ERR_PTR(-EIO); + + for (g = 0; g < IOCTL_TEST_NGROUPS; g++) { + ext4_fsblk_t grp_blk = ext4_group_first_block_no(sb, g); + + if ((ext4_fsblk_t)block == grp_blk) { + struct buffer_head *bh = &ctx->backup_bhs[g]; + + get_bh(bh); + return bh; + } + } + + return ERR_PTR(-ENOENT); +} + +static int ioctl_sync_bh_stub(struct buffer_head *bh) +{ + struct kunit *test = active_ioctl_test; + struct ioctl_test_ctx *ctx; + + if (!test) + return 0; + ctx = test->priv; + if (!ctx) + return 0; + + ctx->sync_bh_calls++; + return ctx->sync_bh_err; +} + +static int ioctl_get_inode_loc_stub(struct inode *inode, struct ext4_iloc *iloc) +{ + struct kunit *test = active_ioctl_test; + struct ioctl_test_ctx *ctx; + + if (!test) + return -EIO; + ctx = test->priv; + if (!ctx) + return -EIO; + + get_bh(&ctx->iloc_bh); + iloc->bh = &ctx->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int ioctl_mark_iloc_dirty_stub(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + brelse(iloc->bh); + iloc->bh = NULL; + return 0; +} + +static void ioctl_init_mock_bh(struct buffer_head *bh, + struct block_device *bdev, struct folio *folio, + u8 *data, size_t size, sector_t blocknr) +{ + memset(bh, 0, sizeof(*bh)); + bh->b_bdev = bdev; + bh->b_folio = folio; + bh->b_data = (char *)data; + bh->b_size = size; + bh->b_blocknr = blocknr; + atomic_set(&bh->b_count, 2); + set_buffer_uptodate(bh); +} + +static void ioctl_sync_backups_from_primary(struct ioctl_test_ctx *ctx) +{ + struct super_block *sb = ctx->sb; + ext4_group_t g; + + ext4_superblock_csum_set(sb); + for (g = 0; g < IOCTL_TEST_NGROUPS; g++) { + struct ext4_super_block *bes; + + bes = (struct ext4_super_block *)ctx->backup_sb_bufs[g]; + memcpy(bes, ctx->es, sizeof(*bes)); + bes->s_block_group_nr = cpu_to_le16(g); + if (ext4_has_feature_metadata_csum(sb)) + bes->s_checksum = ext4_superblock_csum(bes); + } +} + +static void ioctl_test_cleanup(struct ioctl_test_ctx *ctx) +{ + active_ioctl_test = NULL; + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + if (ctx->sb) { + deactivate_super(ctx->sb); + rcu_barrier(); + } + + if (ctx->es_shrinker_inited) { + ext4_es_unregister_shrinker(&ctx->sbi); + ext4_es_destroy_stats(&ctx->sbi); + } + + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + + if (ctx->bh_folio) + folio_put(ctx->bh_folio); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(ioctl_test_cleanup_action, ioctl_test_cleanup, + struct ioctl_test_ctx *); + +static int ioctl_test_init(struct kunit *test) +{ + struct ioctl_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + ext4_group_t g; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + if (!ctx->bdev.bd_stats) { + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bd_stats"); + } + + ctx->bh_folio = folio_alloc(GFP_KERNEL, 0); + if (!ctx->bh_folio) { + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bh_folio"); + } + + fc = fs_context_for_mount(&ioctl_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + folio_put(ctx->bh_folio); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + folio_put(ctx->bh_folio); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + INIT_WORK(&sbi->s_sb_upd_work, ioctl_test_sb_upd_work); + timer_setup(&sbi->s_err_report, ioctl_test_err_timer, 0); + + err = percpu_counter_init(&sbi->s_freeclusters_counter, 0, GFP_KERNEL); + if (err) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + if (err) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = percpu_counter_init(&sbi->s_freeinodes_counter, 0, GFP_KERNEL); + if (err) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_es_lock); + INIT_LIST_HEAD(&sbi->s_es_list); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &ioctl_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = IOCTL_TEST_BLK_SIZE; + sb->s_blocksize_bits = IOCTL_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_ioctl_kunit", sizeof(sb->s_id)); + + err = ext4_es_register_shrinker(sbi); + if (err) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->es_shrinker_inited = true; + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = IOCTL_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + ctx->es = (struct ext4_super_block *)ctx->primary_sb_buf; + ctx->es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es->s_first_ino = cpu_to_le32(IOCTL_TEST_FIRST_INO); + ctx->es->s_inode_size = cpu_to_le16(IOCTL_TEST_INODE_SIZE); + ctx->es->s_want_extra_isize = cpu_to_le16(IOCTL_TEST_EXTRA_ISIZE); + ctx->es->s_min_extra_isize = cpu_to_le16(IOCTL_TEST_EXTRA_ISIZE); + ctx->es->s_first_data_block = cpu_to_le32(IOCTL_TEST_FIRST_DATA_BLK); + ctx->es->s_blocks_per_group = cpu_to_le32(IOCTL_TEST_BLOCKS_PER_GRP); + ctx->es->s_clusters_per_group = cpu_to_le32(IOCTL_TEST_BLOCKS_PER_GRP); + ctx->es->s_inodes_per_group = cpu_to_le32(IOCTL_TEST_INODES_PER_GRP); + ctx->es->s_inodes_count = cpu_to_le32(IOCTL_TEST_TOTAL_INODES); + ext4_blocks_count_set(ctx->es, IOCTL_TEST_TOTAL_BLKS); + ctx->es->s_checksum_type = EXT4_CRC32C_CHKSUM; + ctx->es->s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_EXTENTS | + EXT4_FEATURE_INCOMPAT_64BIT); + ctx->es->s_feature_ro_compat = + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER | + EXT4_FEATURE_RO_COMPAT_METADATA_CSUM | + EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE); + generate_random_uuid(ctx->es->s_uuid); + + ioctl_init_mock_bh(&ctx->sb_bh, &ctx->bdev, ctx->bh_folio, + ctx->primary_sb_buf, IOCTL_TEST_BLK_SIZE, + IOCTL_TEST_FIRST_DATA_BLK); + for (g = 0; g < IOCTL_TEST_NGROUPS; g++) { + ext4_fsblk_t blk = IOCTL_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * IOCTL_TEST_BLOCKS_PER_GRP; + + ioctl_init_mock_bh(&ctx->backup_bhs[g], &ctx->bdev, + ctx->bh_folio, ctx->backup_sb_bufs[g], + IOCTL_TEST_BLK_SIZE, blk); + } + ioctl_init_mock_bh(&ctx->iloc_bh, &ctx->bdev, ctx->bh_folio, + ctx->iloc_buf, IOCTL_TEST_BLK_SIZE, 20); + + sbi->s_es = ctx->es; + sbi->s_sbh = &ctx->sb_bh; + sbi->s_blocks_per_group = IOCTL_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = IOCTL_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_inodes_per_group = IOCTL_TEST_INODES_PER_GRP; + sbi->s_groups_count = IOCTL_TEST_NGROUPS; + sbi->s_inode_size = IOCTL_TEST_INODE_SIZE; + sbi->s_first_ino = IOCTL_TEST_FIRST_INO; + sbi->s_want_extra_isize = IOCTL_TEST_EXTRA_ISIZE; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_csum_seed = ext4_chksum(~0, ctx->es->s_uuid, + sizeof(ctx->es->s_uuid)); + + ioctl_sync_backups_from_primary(ctx); + + root_inode = new_inode(sb); + if (!root_inode) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc root_inode"); + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_flags |= S_NOQUOTA; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc s_root"); + } + + up_write(&sb->s_umount); + + err = kunit_add_action_or_reset(test, ioctl_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + active_ioctl_test = test; + + kunit_activate_static_stub(test, ext4_sb_bread, ioctl_sb_bread_stub); + kunit_activate_static_stub(test, ext4_ioctl_sync_bh, + ioctl_sync_bh_stub); + kunit_activate_static_stub(test, ext4_get_inode_loc, + ioctl_get_inode_loc_stub); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + ioctl_mark_iloc_dirty_stub); + + return 0; +} + +/* + * Verify ext4_sb_setlabel, ext4_sb_setuuid, and ext4_sb_setparams across all + * superblock tuneable fields, split 64-bit / 32-bit fields, feature masks, + * and FORCE_FSCK state marking. + */ +static void test_sb_callbacks_and_setparams(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = ctx->es; + struct ext4_tune_sb_params params; + char label[EXT4_LABEL_MAX] = "ext4_kunit_lbl"; + u8 uuid[UUID_SIZE]; + int i; + + ext4_sb_setlabel_test(sbi, es, label); + KUNIT_EXPECT_MEMEQ(test, es->s_volume_name, label, EXT4_LABEL_MAX); + + for (i = 0; i < UUID_SIZE; i++) + uuid[i] = 0xa0 + i; + ext4_sb_setuuid_test(sbi, es, uuid); + KUNIT_EXPECT_MEMEQ(test, es->s_uuid, uuid, UUID_SIZE); + + memset(¶ms, 0, sizeof(params)); + sbi->s_def_hash_version = DX_HASH_TEA; + sbi->s_csum_seed = 0xdeadbeefU; + params.set_flags = EXT4_TUNE_FL_ERRORS_BEHAVIOR | + EXT4_TUNE_FL_MNT_COUNT | + EXT4_TUNE_FL_MAX_MNT_COUNT | + EXT4_TUNE_FL_CHECKINTRVAL | + EXT4_TUNE_FL_LAST_CHECK_TIME | + EXT4_TUNE_FL_RESERVED_BLOCKS | + EXT4_TUNE_FL_RESERVED_UID | + EXT4_TUNE_FL_RESERVED_GID | + EXT4_TUNE_FL_DEFAULT_MNT_OPTS | + EXT4_TUNE_FL_DEF_HASH_ALG | + EXT4_TUNE_FL_RAID_STRIDE | + EXT4_TUNE_FL_RAID_STRIPE_WIDTH | + EXT4_TUNE_FL_ENCODING | + EXT4_TUNE_FL_ENCODING_FLAGS | + EXT4_TUNE_FL_MOUNT_OPTS | + EXT4_TUNE_FL_EDIT_FEATURES | + EXT4_TUNE_FL_FORCE_FSCK; + params.errors_behavior = EXT4_ERRORS_RO; + params.mnt_count = 7; + params.max_mnt_count = 42; + params.checkinterval = 86400; + params.last_check_time = 1700000000ULL; + params.reserved_blocks = 0x100000055ULL; + params.reserved_uid = 0x12345678U; + params.reserved_gid = 0x87654321U; + params.default_mnt_opts = EXT4_DEFM_ACL | EXT4_DEFM_XATTR_USER; + params.def_hash_alg = DX_HASH_HALF_MD4; + params.raid_stride = 16; + params.raid_stripe_width = 128; + params.encoding = EXT4_ENC_UTF8_12_1; + params.encoding_flags = SB_ENC_STRICT_MODE_FL; + strscpy(params.mount_opts, "nodelalloc,noatime", + sizeof(params.mount_opts)); + params.set_feature_compat_mask = EXT4_FEATURE_COMPAT_DIR_INDEX; + params.set_feature_incompat_mask = EXT4_FEATURE_INCOMPAT_CSUM_SEED; + params.set_feature_ro_compat_mask = EXT4_FEATURE_RO_COMPAT_PROJECT; + + ext4_sb_setparams_test(sbi, es, ¶ms); + + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_errors), EXT4_ERRORS_RO); + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_mnt_count), 7); + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_max_mnt_count), 42); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_checkinterval), 86400U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_lastcheck), 1700000000U); + KUNIT_EXPECT_EQ(test, ext4_r_blocks_count(es), 0x100000055ULL); + KUNIT_EXPECT_EQ(test, ext4_get_resuid(es), 0x12345678U); + KUNIT_EXPECT_EQ(test, ext4_get_resgid(es), 0x87654321U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_default_mount_opts), + (u32)(EXT4_DEFM_ACL | EXT4_DEFM_XATTR_USER)); + /* EDIT_FEATURES + DIR_INDEX overrides s_def_hash_version from sbi */ + KUNIT_EXPECT_EQ(test, es->s_def_hash_version, DX_HASH_TEA); + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_raid_stride), 16); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_raid_stripe_width), 128U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_encoding), EXT4_ENC_UTF8_12_1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_encoding_flags), + SB_ENC_STRICT_MODE_FL); + KUNIT_EXPECT_STREQ(test, (char *)es->s_mount_opts, + "nodelalloc,noatime"); + KUNIT_EXPECT_NE(test, + le32_to_cpu(es->s_feature_compat) & + EXT4_FEATURE_COMPAT_DIR_INDEX, 0U); + KUNIT_EXPECT_NE(test, + le32_to_cpu(es->s_feature_incompat) & + EXT4_FEATURE_INCOMPAT_CSUM_SEED, 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_checksum_seed), 0xdeadbeefU); + KUNIT_EXPECT_NE(test, + le32_to_cpu(es->s_feature_ro_compat) & + EXT4_FEATURE_RO_COMPAT_PROJECT, 0U); + KUNIT_EXPECT_NE(test, le16_to_cpu(es->s_state) & EXT4_ERROR_FS, 0); +} + +/* + * Verify ext4_validate_tune_sb_params rejects malformed mount_opts, invalid + * flags, out-of-range parameters, unsupported feature edits, and standalone + * encoding updates, while normalizing DIR_INDEX and CASEFOLD enablement. + */ +static void test_validate_tune_sb_params(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = ctx->es; + struct ext4_tune_sb_params params; + uuid_t uu; + + /* Unterminated mount_opts -> -E2BIG */ + memset(¶ms, 0, sizeof(params)); + memset(params.mount_opts, 'a', sizeof(params.mount_opts)); + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -E2BIG); + + /* Unknown set_flags bit -> -EOPNOTSUPP */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = 0x80000000U; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EOPNOTSUPP); + + /* Invalid errors_behavior -> -EINVAL */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_ERRORS_BEHAVIOR; + params.errors_behavior = EXT4_ERRORS_PANIC + 1; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + + /* Reserved blocks > blocks_count / 2 -> -EINVAL, <= half -> 0 */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_RESERVED_BLOCKS; + params.reserved_blocks = ext4_blocks_count(es) / 2 + 1; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + params.reserved_blocks = ext4_blocks_count(es) / 2; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + 0); + + /* Hash algorithm validation: SIPHASH and > DX_HASH_LAST rejected */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_DEF_HASH_ALG; + params.def_hash_alg = DX_HASH_SIPHASH; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + params.def_hash_alg = DX_HASH_LAST + 1; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + params.def_hash_alg = DX_HASH_HALF_MD4; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + 0); + + /* Mutual exclusion of FEATURES and EDIT_FEATURES */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_FEATURES | EXT4_TUNE_FL_EDIT_FEATURES; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + + /* Clearing an existing feature via FEATURES -> -EOPNOTSUPP */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_FEATURES; + params.feature_compat = le32_to_cpu(es->s_feature_compat); + params.feature_incompat = 0; + params.feature_ro_compat = le32_to_cpu(es->s_feature_ro_compat); + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EOPNOTSUPP); + + /* Enabling DIR_INDEX via FEATURES initializes hash seed & default alg */ + memset(sbi->s_hash_seed, 0, sizeof(sbi->s_hash_seed)); + sbi->s_def_hash_version = 0; + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_FEATURES; + params.feature_compat = le32_to_cpu(es->s_feature_compat) | + EXT4_FEATURE_COMPAT_DIR_INDEX; + params.feature_incompat = le32_to_cpu(es->s_feature_incompat); + params.feature_ro_compat = le32_to_cpu(es->s_feature_ro_compat) | + EXT4_FEATURE_RO_COMPAT_DIR_NLINK; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + 0); + KUNIT_EXPECT_NE(test, params.set_flags & EXT4_TUNE_FL_EDIT_FEATURES, + 0U); + KUNIT_EXPECT_EQ(test, params.set_feature_compat_mask, + (u32)EXT4_FEATURE_COMPAT_DIR_INDEX); + KUNIT_EXPECT_EQ(test, params.set_feature_ro_compat_mask, + (u32)EXT4_FEATURE_RO_COMPAT_DIR_NLINK); + memcpy(&uu, sbi->s_hash_seed, UUID_SIZE); + KUNIT_EXPECT_FALSE(test, uuid_is_null(&uu)); + KUNIT_EXPECT_EQ(test, sbi->s_def_hash_version, DX_HASH_HALF_MD4); + + /* Encoding without CASEFOLD -> -EINVAL; with CASEFOLD -> UTF8_12_1 */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_ENCODING; + params.encoding = EXT4_ENC_UTF8_12_1; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_EDIT_FEATURES; + params.set_feature_incompat_mask = EXT4_FEATURE_INCOMPAT_CASEFOLD; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + 0); + KUNIT_EXPECT_EQ(test, params.encoding, EXT4_ENC_UTF8_12_1); + KUNIT_EXPECT_EQ(test, params.encoding_flags, 0); +} + +/* + * Verify ext4_update_backup_sb, ext4_update_superblocks_fn, and + * ext4_update_overhead across primary + 4 sparse_super backup groups (1, 3, + * 5, 7), covering both journaled (first 2 backups) and unjournaled (remaining + * backups) update paths, EXT4_FLAGS_RESIZING contention, and overhead skip + * conditions. + */ +static void test_update_superblocks_and_overhead(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + static const ext4_group_t backup_grps[] = { 1, 3, 5, 7 }; + char new_label[EXT4_LABEL_MAX] = "updated_label"; + int i; + + /* Group 2 has no backup superblock under sparse_super */ + KUNIT_EXPECT_EQ(test, + ext4_update_backup_sb_test(sb, NULL, 2, + ext4_sb_setlabel_test, + new_label), + 0); + + /* Contention guard when EXT4_FLAGS_RESIZING is already set */ + set_bit(EXT4_FLAGS_RESIZING, &sbi->s_ext4_flags); + KUNIT_EXPECT_EQ(test, + ext4_update_superblocks_fn_test(sb, + ext4_sb_setlabel_test, + new_label), + -EBUSY); + clear_bit(EXT4_FLAGS_RESIZING, &sbi->s_ext4_flags); + + /* Full superblock update across primary (grp 0) + 4 backups */ + ctx->sync_bh_calls = 0; + KUNIT_EXPECT_EQ(test, + ext4_update_superblocks_fn_test(sb, + ext4_sb_setlabel_test, + new_label), + 0); + KUNIT_EXPECT_FALSE(test, + test_bit(EXT4_FLAGS_RESIZING, &sbi->s_ext4_flags)); + /* 1 primary + 4 backup superblocks synced */ + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 5); + KUNIT_EXPECT_MEMEQ(test, ctx->es->s_volume_name, new_label, + EXT4_LABEL_MAX); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es->s_checksum), + le32_to_cpu(ext4_superblock_csum(ctx->es))); + + for (i = 0; i < ARRAY_SIZE(backup_grps); i++) { + ext4_group_t g = backup_grps[i]; + struct ext4_super_block *bes; + + bes = (struct ext4_super_block *)ctx->backup_sb_bufs[g]; + KUNIT_EXPECT_MEMEQ(test, bes->s_volume_name, new_label, + EXT4_LABEL_MAX); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bes->s_checksum), + le32_to_cpu(ext4_superblock_csum(bes))); + } + + /* ext4_update_overhead skip & force behavior */ + ctx->sync_bh_calls = 0; + sbi->s_overhead = 0; + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, false), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 0); + + sbi->s_overhead = 77; + sb->s_flags |= SB_RDONLY; + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, true), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 0); + sb->s_flags &= ~SB_RDONLY; + + set_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, true), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 0); + clear_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, false), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 5); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es->s_overhead_clusters), 77U); + + /* Matching s_overhead skips when !force, updates when force == true */ + ctx->sync_bh_calls = 0; + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, false), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 0); + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, true), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 5); +} + +/* + * Verify swap_inode_data swaps i_data, i_disksize, i_size, i_version, + * atime/mtime, and EXT4_FL_SHOULD_SWAP flags while preserving non-swapped + * flags, clears both extent-status caches, and restores exact state when + * invoked a second time. Also verify ext4_reset_inode_seed. + */ +static void test_swap_inode_data_and_seed(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode1, *inode2; + struct ext4_inode_info *ei1, *ei2; + struct timespec64 at1 = { .tv_sec = 1000, .tv_nsec = 111 }; + struct timespec64 at2 = { .tv_sec = 2000, .tv_nsec = 222 }; + struct timespec64 mt1 = { .tv_sec = 3000, .tv_nsec = 333 }; + struct timespec64 mt2 = { .tv_sec = 4000, .tv_nsec = 444 }; + __le32 orig_data1[EXT4_N_BLOCKS]; + __le32 orig_data2[EXT4_N_BLOCKS]; + u32 seed1, seed2; + int i; + + inode1 = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, inode1); + inode2 = new_inode(sb); + if (!inode2) { + iput(inode1); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc inode2"); + } + ei1 = EXT4_I(inode1); + ei2 = EXT4_I(inode2); + + for (i = 0; i < EXT4_N_BLOCKS; i++) { + ei1->i_data[i] = cpu_to_le32(0x100 + i); + ei2->i_data[i] = cpu_to_le32(0x200 + i); + } + memcpy(orig_data1, ei1->i_data, sizeof(orig_data1)); + memcpy(orig_data2, ei2->i_data, sizeof(orig_data2)); + + ei1->i_flags = EXT4_EXTENTS_FL | EXT4_HUGE_FILE_FL | EXT4_IMMUTABLE_FL; + ei2->i_flags = EXT4_NOATIME_FL; + ei1->i_disksize = 0x11000; + ei2->i_disksize = 0x22000; + i_size_write(inode1, 0x10500); + i_size_write(inode2, 0x20500); + inode_set_iversion_raw(inode1, 10); + inode_set_iversion_raw(inode2, 20); + inode_set_atime_to_ts(inode1, at1); + inode_set_atime_to_ts(inode2, at2); + inode_set_mtime_to_ts(inode1, mt1); + inode_set_mtime_to_ts(inode2, mt2); + + ext4_es_insert_extent(inode1, 0, 4, 50, EXTENT_STATUS_WRITTEN, false); + ext4_es_insert_extent(inode2, 8, 2, 60, EXTENT_STATUS_WRITTEN, false); + KUNIT_EXPECT_EQ(test, ei1->i_es_all_nr, 1U); + KUNIT_EXPECT_EQ(test, ei2->i_es_all_nr, 1U); + + ext4_swap_inode_data_test(inode1, inode2); + + KUNIT_EXPECT_MEMEQ(test, ei1->i_data, orig_data2, sizeof(orig_data2)); + KUNIT_EXPECT_MEMEQ(test, ei2->i_data, orig_data1, sizeof(orig_data1)); + KUNIT_EXPECT_EQ(test, ei1->i_flags, (u32)EXT4_IMMUTABLE_FL); + KUNIT_EXPECT_EQ(test, ei2->i_flags, + (u32)(EXT4_NOATIME_FL | EXT4_EXTENTS_FL | + EXT4_HUGE_FILE_FL)); + KUNIT_EXPECT_EQ(test, ei1->i_disksize, (loff_t)0x22000); + KUNIT_EXPECT_EQ(test, ei2->i_disksize, (loff_t)0x11000); + KUNIT_EXPECT_EQ(test, i_size_read(inode1), (loff_t)0x20500); + KUNIT_EXPECT_EQ(test, i_size_read(inode2), (loff_t)0x10500); + KUNIT_EXPECT_EQ(test, inode_peek_iversion_raw(inode1), 20ULL); + KUNIT_EXPECT_EQ(test, inode_peek_iversion_raw(inode2), 10ULL); + KUNIT_EXPECT_EQ(test, inode_get_atime_sec(inode1), 2000LL); + KUNIT_EXPECT_EQ(test, inode_get_mtime_sec(inode1), 4000LL); + KUNIT_EXPECT_EQ(test, ei1->i_es_all_nr, 0U); + KUNIT_EXPECT_EQ(test, ei2->i_es_all_nr, 0U); + + /* Second swap restores exact pre-swap attributes */ + ext4_swap_inode_data_test(inode1, inode2); + KUNIT_EXPECT_MEMEQ(test, ei1->i_data, orig_data1, sizeof(orig_data1)); + KUNIT_EXPECT_MEMEQ(test, ei2->i_data, orig_data2, sizeof(orig_data2)); + KUNIT_EXPECT_EQ(test, ei1->i_flags, + (u32)(EXT4_EXTENTS_FL | EXT4_HUGE_FILE_FL | + EXT4_IMMUTABLE_FL)); + KUNIT_EXPECT_EQ(test, ei2->i_flags, (u32)EXT4_NOATIME_FL); + KUNIT_EXPECT_EQ(test, ei1->i_disksize, (loff_t)0x11000); + KUNIT_EXPECT_EQ(test, i_size_read(inode1), (loff_t)0x10500); + + /* ext4_reset_inode_seed with and without metadata_csum */ + inode1->i_ino = 42; + inode1->i_generation = 7; + ei1->i_csum_seed = 0; + ext4_reset_inode_seed(inode1); + seed1 = ei1->i_csum_seed; + KUNIT_EXPECT_NE(test, seed1, 0U); + + inode1->i_generation = 8; + ext4_reset_inode_seed(inode1); + seed2 = ei1->i_csum_seed; + KUNIT_EXPECT_NE(test, seed2, seed1); + + ext4_clear_feature_metadata_csum(sb); + ei1->i_csum_seed = 0x12345678U; + ext4_reset_inode_seed(inode1); + KUNIT_EXPECT_EQ(test, ei1->i_csum_seed, 0x12345678U); + + iput(inode1); + iput(inode2); +} + +/* + * Verify ext4_ioctl_check_immutable, dax_compatible, ext4_fileattr_get, and + * ext4_fileattr_set flag masking, mode checks, quota-file protection, and + * end-to-end VFS inode flag synchronization. + */ +static void test_immutable_dax_and_fileattr(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *reg_inode, *dir_inode; + struct dentry *reg_dentry, *dir_dentry; + struct ext4_inode_info *rei, *dei; + struct file_kattr fa; + + reg_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, reg_inode); + dir_inode = new_inode(sb); + if (!dir_inode) { + iput(reg_inode); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc dir_inode"); + } + reg_inode->i_ino = 100; + reg_inode->i_mode = S_IFREG | 0644; + dir_inode->i_ino = 101; + dir_inode->i_mode = S_IFDIR | 0755; + rei = EXT4_I(reg_inode); + dei = EXT4_I(dir_inode); + + reg_dentry = d_alloc_anon(sb); + if (!reg_dentry) { + iput(dir_inode); + iput(reg_inode); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc reg_dentry"); + } + d_instantiate(reg_dentry, reg_inode); + dir_dentry = d_alloc_anon(sb); + if (!dir_dentry) { + dput(reg_dentry); + iput(dir_inode); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc dir_dentry"); + } + d_instantiate(dir_dentry, dir_inode); + + /* ext4_ioctl_check_immutable */ + ext4_set_feature_project(sb); + rei->i_projid = make_kprojid(&init_user_ns, 10); + rei->i_flags = EXT4_IMMUTABLE_FL | EXT4_NOATIME_FL; + KUNIT_EXPECT_EQ(test, + ext4_ioctl_check_immutable_test(reg_inode, 10, + EXT4_IMMUTABLE_FL | EXT4_NOATIME_FL), + 0); + /* Clearing IMMUTABLE_FL is allowed here (CAP_LINUX_IMMUTABLE checked in VFS) */ + KUNIT_EXPECT_EQ(test, + ext4_ioctl_check_immutable_test(reg_inode, 10, + EXT4_NOATIME_FL), + 0); + /* Changing other flags or projid while keeping IMMUTABLE_FL -> -EPERM */ + KUNIT_EXPECT_EQ(test, + ext4_ioctl_check_immutable_test(reg_inode, 10, + EXT4_IMMUTABLE_FL), + -EPERM); + KUNIT_EXPECT_EQ(test, + ext4_ioctl_check_immutable_test(reg_inode, 11, + EXT4_IMMUTABLE_FL | EXT4_NOATIME_FL), + -EPERM); + + /* dax_compatible */ + KUNIT_EXPECT_FALSE(test, + ext4_dax_compatible_test(reg_inode, EXT4_VERITY_FL, + EXT4_DAX_FL)); + KUNIT_EXPECT_FALSE(test, + ext4_dax_compatible_test(reg_inode, + EXT4_INLINE_DATA_FL, + EXT4_DAX_FL)); + KUNIT_EXPECT_FALSE(test, + ext4_dax_compatible_test(reg_inode, EXT4_DAX_FL, + EXT4_JOURNAL_DATA_FL)); + /* Inline directory MAY toggle DAX_FL */ + KUNIT_EXPECT_TRUE(test, + ext4_dax_compatible_test(dir_inode, + EXT4_INLINE_DATA_FL, + EXT4_INLINE_DATA_FL | + EXT4_DAX_FL)); + /* VERITY_IN_PROGRESS blocks enabling DAX_FL */ + ext4_set_inode_state(reg_inode, EXT4_STATE_VERITY_IN_PROGRESS); + KUNIT_EXPECT_FALSE(test, + ext4_dax_compatible_test(reg_inode, 0, EXT4_DAX_FL)); + ext4_clear_inode_state(reg_inode, EXT4_STATE_VERITY_IN_PROGRESS); + + /* ext4_fileattr_get: strips PROJINHERIT on reg file, keeps on dir */ + rei->i_flags = EXT4_NOATIME_FL | EXT4_PROJINHERIT_FL | EXT4_RESERVED_FL; + dei->i_flags = EXT4_NOATIME_FL | EXT4_PROJINHERIT_FL; + dei->i_projid = make_kprojid(&init_user_ns, 25); + + memset(&fa, 0, sizeof(fa)); + KUNIT_EXPECT_EQ(test, ext4_fileattr_get(reg_dentry, &fa), 0); + KUNIT_EXPECT_EQ(test, fa.flags, (u32)EXT4_NOATIME_FL); + KUNIT_EXPECT_EQ(test, fa.fsx_projid, 10U); + + memset(&fa, 0, sizeof(fa)); + KUNIT_EXPECT_EQ(test, ext4_fileattr_get(dir_dentry, &fa), 0); + KUNIT_EXPECT_EQ(test, fa.flags, + (u32)(EXT4_NOATIME_FL | EXT4_PROJINHERIT_FL)); + KUNIT_EXPECT_EQ(test, fa.fsx_projid, 25U); + + /* ext4_fileattr_set error paths and success path */ + ext4_clear_feature_project(sb); + rei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + rei->i_flags = 0; + + /* Flag outside EXT4_FL_USER_VISIBLE -> -EOPNOTSUPP */ + memset(&fa, 0, sizeof(fa)); + fileattr_fill_flags(&fa, EXT4_RESERVED_FL); + KUNIT_EXPECT_EQ(test, + ext4_fileattr_set(&nop_mnt_idmap, reg_dentry, &fa), + -EOPNOTSUPP); + + /* Directory-only flag on regular file -> -EOPNOTSUPP */ + memset(&fa, 0, sizeof(fa)); + fileattr_fill_flags(&fa, EXT4_PROJINHERIT_FL); + KUNIT_EXPECT_EQ(test, + ext4_fileattr_set(&nop_mnt_idmap, reg_dentry, &fa), + -EOPNOTSUPP); + + /* Quota file cannot be modified -> -EPERM */ + reg_inode->i_flags |= S_NOQUOTA; + memset(&fa, 0, sizeof(fa)); + fileattr_fill_flags(&fa, EXT4_NOATIME_FL); + KUNIT_EXPECT_EQ(test, + ext4_fileattr_set(&nop_mnt_idmap, reg_dentry, &fa), + -EPERM); + reg_inode->i_flags &= ~S_NOQUOTA; + + /* CASEFOLD_FL without casefold feature -> -EOPNOTSUPP */ + memset(&fa, 0, sizeof(fa)); + fileattr_fill_flags(&fa, EXT4_CASEFOLD_FL); + KUNIT_EXPECT_EQ(test, + ext4_fileattr_set(&nop_mnt_idmap, dir_dentry, &fa), + -EOPNOTSUPP); + + /* End-to-end setflags on regular file updates ei->i_flags & VFS flags */ + memset(&fa, 0, sizeof(fa)); + fileattr_fill_flags(&fa, EXT4_NOATIME_FL | EXT4_SYNC_FL | + EXT4_NODUMP_FL); + KUNIT_EXPECT_EQ(test, + ext4_fileattr_set(&nop_mnt_idmap, reg_dentry, &fa), + 0); + KUNIT_EXPECT_EQ(test, + rei->i_flags & (EXT4_NOATIME_FL | EXT4_SYNC_FL | + EXT4_NODUMP_FL), + (u32)(EXT4_NOATIME_FL | EXT4_SYNC_FL | EXT4_NODUMP_FL)); + KUNIT_EXPECT_NE(test, reg_inode->i_flags & S_NOATIME, 0U); + KUNIT_EXPECT_NE(test, reg_inode->i_flags & S_SYNC, 0U); + + dput(reg_dentry); + dput(dir_dentry); +} + +/* + * Verify ext4_force_shutdown state transitions and ext4_ioctl / + * ext4_compat_ioctl command dispatch for unknown commands, feature-gated + * commands, mode checks, FITRIM preconditions, and EXT4_IOC_CLEAR_ES_CACHE. + */ +static void test_force_shutdown_and_ioctl_dispatch(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode; + struct dentry *dentry; + struct vfsmount mnt = { + .mnt_root = sb->s_root, + .mnt_sb = sb, + .mnt_idmap = &nop_mnt_idmap, + }; + + inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + inode->i_ino = 200; + inode->i_mode = S_IFREG | 0644; + dentry = d_alloc_anon(sb); + if (!dentry) { + iput(inode); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc dentry"); + } + d_instantiate(dentry, inode); + + { + struct file filp = { + .f_inode = inode, + .f_path = { + .mnt = &mnt, + .dentry = dentry, + }, + .f_mode = FMODE_READ | FMODE_WRITE, + }; + + /* Unknown command dispatch */ + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, 0xffffffffU, 0), + -ENOTTY); +#ifdef CONFIG_COMPAT + KUNIT_EXPECT_EQ(test, ext4_compat_ioctl(&filp, 0xffffffffU, 0), + -ENOIOCTLCMD); +#endif + + /* Encryption and verity ioctls return -EOPNOTSUPP when off */ + KUNIT_EXPECT_EQ(test, + ext4_ioctl(&filp, FS_IOC_SET_ENCRYPTION_POLICY, + 0), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_ioctl(&filp, FS_IOC_GET_ENCRYPTION_POLICY, + 0), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_ioctl(&filp, FS_IOC_ENABLE_VERITY, 0), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_ioctl(&filp, FS_IOC_MEASURE_VERITY, 0), + -EOPNOTSUPP); +#ifdef CONFIG_COMPAT + KUNIT_EXPECT_EQ(test, + ext4_compat_ioctl(&filp, FS_IOC_ENABLE_VERITY, + 0), + -EOPNOTSUPP); +#endif + + /* SETVERSION rejected with -ENOTTY when metadata_csum is on */ + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, EXT4_IOC_SETVERSION, 0), + -ENOTTY); + + /* FITRIM: no discard -> -EOPNOTSUPP; NOLOAD+journal -> -EROFS */ + ctx->bdev_queue.limits.max_discard_sectors = 0; + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, FITRIM, 0), + -EOPNOTSUPP); + + ctx->bdev_queue.limits.max_discard_sectors = 1024; + set_opt(sb, NOLOAD); + ext4_set_feature_journal(sb); + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, FITRIM, 0), -EROFS); + clear_opt(sb, NOLOAD); + ext4_clear_feature_journal(sb); + + /* MOVE_EXT and SWAP_BOOT require FMODE_WRITE -> -EBADF on RO */ + filp.f_mode = FMODE_READ; + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, EXT4_IOC_MOVE_EXT, 0), + -EBADF); + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, EXT4_IOC_SWAP_BOOT, 0), + -EBADF); + filp.f_mode = FMODE_READ | FMODE_WRITE; + + /* EXT4_IOC_CLEAR_ES_CACHE empties inode extent status tree */ + ext4_es_insert_extent(inode, 0, 8, 120, EXTENT_STATUS_WRITTEN, + false); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_es_all_nr, 1U); + KUNIT_EXPECT_EQ(test, + ext4_ioctl(&filp, EXT4_IOC_CLEAR_ES_CACHE, 0), + 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_es_all_nr, 0U); + } + + /* ext4_force_shutdown validation, NOLOGFLUSH state, and idempotency */ + KUNIT_EXPECT_EQ(test, + ext4_force_shutdown(sb, EXT4_GOING_FLAGS_NOLOGFLUSH + 1), + -EINVAL); + set_opt(sb, DISCARD); + KUNIT_EXPECT_EQ(test, + ext4_force_shutdown(sb, EXT4_GOING_FLAGS_NOLOGFLUSH), + 0); + KUNIT_EXPECT_TRUE(test, ext4_forced_shutdown(sb)); + KUNIT_EXPECT_EQ(test, test_opt(sb, DISCARD), 0U); + /* Repeat shutdown call is a no-op returning 0 */ + KUNIT_EXPECT_EQ(test, + ext4_force_shutdown(sb, EXT4_GOING_FLAGS_DEFAULT), + 0); + + dput(dentry); +} + +static struct kunit_case ioctl_test_cases[] = { + KUNIT_CASE(test_sb_callbacks_and_setparams), + KUNIT_CASE(test_validate_tune_sb_params), + KUNIT_CASE(test_update_superblocks_and_overhead), + KUNIT_CASE(test_swap_inode_data_and_seed), + KUNIT_CASE(test_immutable_dax_and_fileattr), + KUNIT_CASE(test_force_shutdown_and_ioctl_dispatch), + {} +}; + +static struct kunit_suite ioctl_test_suite = { + .name = "ext4_ioctl_test", + .init = ioctl_test_init, + .test_cases = ioctl_test_cases, +}; + +kunit_test_suites(&ioctl_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 ioctl operations"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/ioctl.c b/fs/ext4/ioctl.c index 368005d318d957..83630cd40712c8 100644 --- a/fs/ext4/ioctl.c +++ b/fs/ext4/ioctl.c @@ -27,6 +27,7 @@ #include "fsmap.h" #include #include +#include typedef void ext4_update_sb_callback(struct ext4_sb_info *sbi, struct ext4_super_block *es, @@ -55,6 +56,13 @@ static void ext4_sb_setuuid(struct ext4_sb_info *sbi, memcpy(es->s_uuid, (__u8 *)arg, UUID_SIZE); } +int ext4_ioctl_sync_bh(struct buffer_head *bh) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_ioctl_sync_bh, bh); + return sync_dirty_buffer(bh); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ioctl_sync_bh); + static int ext4_update_primary_sb(struct super_block *sb, handle_t *handle, ext4_update_sb_callback func, @@ -89,7 +97,7 @@ int ext4_update_primary_sb(struct super_block *sb, handle_t *handle, err = ext4_handle_dirty_metadata(handle, NULL, bh); if (err) goto out_err; - err = sync_dirty_buffer(bh); + err = ext4_ioctl_sync_bh(bh); out_err: ext4_std_error(sb, err); return err; @@ -167,7 +175,7 @@ static int ext4_update_backup_sb(struct super_block *sb, BUFFER_TRACE(bh, "marking dirty"); mark_buffer_dirty(bh); } - err = sync_dirty_buffer(bh); + err = ext4_ioctl_sync_bh(bh); out_bh: brelse(bh); @@ -361,6 +369,7 @@ void ext4_reset_inode_seed(struct inode *inode) csum = ext4_chksum(sbi->s_csum_seed, (__u8 *)&inum, sizeof(inum)); ei->i_csum_seed = ext4_chksum(csum, (__u8 *)&gen, sizeof(gen)); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_reset_inode_seed); /* * Swap the information from the given @inode and the inode @@ -854,6 +863,7 @@ int ext4_force_shutdown(struct super_block *sb, u32 flags) fserror_report_shutdown(sb, GFP_KERNEL); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_force_shutdown); static int ext4_ioctl_shutdown(struct super_block *sb, unsigned long arg) { @@ -1007,6 +1017,7 @@ int ext4_fileattr_get(struct dentry *dentry, struct file_kattr *fa) return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fileattr_get); int ext4_fileattr_set(const struct mnt_idmap *idmap, struct dentry *dentry, struct file_kattr *fa) @@ -1037,6 +1048,7 @@ int ext4_fileattr_set(const struct mnt_idmap *idmap, out: return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fileattr_set); /* So that the fiemap access checks can't overflow on 32 bit machines. */ #define FIEMAP_MAX_EXTENTS (UINT_MAX / sizeof(struct fiemap_extent)) @@ -1390,77 +1402,68 @@ static void ext4_sb_setparams(struct ext4_sb_info *sbi, } } -static int ext4_ioctl_set_tune_sb(struct file *filp, - struct ext4_tune_sb_params __user *in) +static int ext4_validate_tune_sb_params(struct super_block *sb, + struct ext4_tune_sb_params *params) { - struct ext4_tune_sb_params params; - struct super_block *sb = file_inode(filp)->i_sb; struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; int enabling_casefold = 0; - int ret; - - if (!capable(CAP_SYS_ADMIN)) - return -EPERM; - - if (copy_from_user(¶ms, in, sizeof(params))) - return -EFAULT; - if (strnlen(params.mount_opts, sizeof(params.mount_opts)) == - sizeof(params.mount_opts)) + if (strnlen(params->mount_opts, sizeof(params->mount_opts)) == + sizeof(params->mount_opts)) return -E2BIG; - if ((params.set_flags & ~TUNE_OPS_SUPPORTED) != 0) + if ((params->set_flags & ~TUNE_OPS_SUPPORTED) != 0) return -EOPNOTSUPP; - if ((params.set_flags & EXT4_TUNE_FL_ERRORS_BEHAVIOR) && - (params.errors_behavior > EXT4_ERRORS_PANIC)) + if ((params->set_flags & EXT4_TUNE_FL_ERRORS_BEHAVIOR) && + (params->errors_behavior > EXT4_ERRORS_PANIC)) return -EINVAL; - if ((params.set_flags & EXT4_TUNE_FL_RESERVED_BLOCKS) && - (params.reserved_blocks > ext4_blocks_count(sbi->s_es) / 2)) + if ((params->set_flags & EXT4_TUNE_FL_RESERVED_BLOCKS) && + (params->reserved_blocks > ext4_blocks_count(sbi->s_es) / 2)) return -EINVAL; - if ((params.set_flags & EXT4_TUNE_FL_DEF_HASH_ALG) && - ((params.def_hash_alg > DX_HASH_LAST) || - (params.def_hash_alg == DX_HASH_SIPHASH))) + if ((params->set_flags & EXT4_TUNE_FL_DEF_HASH_ALG) && + ((params->def_hash_alg > DX_HASH_LAST) || + (params->def_hash_alg == DX_HASH_SIPHASH))) return -EINVAL; - if ((params.set_flags & EXT4_TUNE_FL_FEATURES) && - (params.set_flags & EXT4_TUNE_FL_EDIT_FEATURES)) + if ((params->set_flags & EXT4_TUNE_FL_FEATURES) && + (params->set_flags & EXT4_TUNE_FL_EDIT_FEATURES)) return -EINVAL; - if (params.set_flags & EXT4_TUNE_FL_FEATURES) { - params.set_feature_compat_mask = - params.feature_compat & + if (params->set_flags & EXT4_TUNE_FL_FEATURES) { + params->set_feature_compat_mask = + params->feature_compat & ~le32_to_cpu(es->s_feature_compat); - params.set_feature_incompat_mask = - params.feature_incompat & + params->set_feature_incompat_mask = + params->feature_incompat & ~le32_to_cpu(es->s_feature_incompat); - params.set_feature_ro_compat_mask = - params.feature_ro_compat & + params->set_feature_ro_compat_mask = + params->feature_ro_compat & ~le32_to_cpu(es->s_feature_ro_compat); - params.clear_feature_compat_mask = - ~params.feature_compat & + params->clear_feature_compat_mask = + ~params->feature_compat & le32_to_cpu(es->s_feature_compat); - params.clear_feature_incompat_mask = - ~params.feature_incompat & + params->clear_feature_incompat_mask = + ~params->feature_incompat & le32_to_cpu(es->s_feature_incompat); - params.clear_feature_ro_compat_mask = - ~params.feature_ro_compat & + params->clear_feature_ro_compat_mask = + ~params->feature_ro_compat & le32_to_cpu(es->s_feature_ro_compat); - params.set_flags |= EXT4_TUNE_FL_EDIT_FEATURES; + params->set_flags |= EXT4_TUNE_FL_EDIT_FEATURES; } - if (params.set_flags & EXT4_TUNE_FL_EDIT_FEATURES) { - if ((params.set_feature_compat_mask & + if (params->set_flags & EXT4_TUNE_FL_EDIT_FEATURES) { + if ((params->set_feature_compat_mask & ~EXT4_TUNE_SET_COMPAT_SUPP) || - (params.set_feature_incompat_mask & + (params->set_feature_incompat_mask & ~EXT4_TUNE_SET_INCOMPAT_SUPP) || - (params.set_feature_ro_compat_mask & + (params->set_feature_ro_compat_mask & ~EXT4_TUNE_SET_RO_COMPAT_SUPP) || - (params.clear_feature_compat_mask & + (params->clear_feature_compat_mask & ~EXT4_TUNE_CLEAR_COMPAT_SUPP) || - (params.clear_feature_incompat_mask & + (params->clear_feature_incompat_mask & ~EXT4_TUNE_CLEAR_INCOMPAT_SUPP) || - (params.clear_feature_ro_compat_mask & + (params->clear_feature_ro_compat_mask & ~EXT4_TUNE_CLEAR_RO_COMPAT_SUPP)) return -EOPNOTSUPP; @@ -1468,34 +1471,35 @@ static int ext4_ioctl_set_tune_sb(struct file *filp, * Filter out the features that are already set from * the set_mask. */ - params.set_feature_compat_mask &= + params->set_feature_compat_mask &= ~le32_to_cpu(es->s_feature_compat); - params.set_feature_incompat_mask &= + params->set_feature_incompat_mask &= ~le32_to_cpu(es->s_feature_incompat); - params.set_feature_ro_compat_mask &= + params->set_feature_ro_compat_mask &= ~le32_to_cpu(es->s_feature_ro_compat); - if ((params.set_feature_incompat_mask & - EXT4_FEATURE_INCOMPAT_CASEFOLD)) { + if (params->set_feature_incompat_mask & + EXT4_FEATURE_INCOMPAT_CASEFOLD) { enabling_casefold = 1; - if (!(params.set_flags & EXT4_TUNE_FL_ENCODING)) { - params.encoding = EXT4_ENC_UTF8_12_1; - params.set_flags |= EXT4_TUNE_FL_ENCODING; + if (!(params->set_flags & EXT4_TUNE_FL_ENCODING)) { + params->encoding = EXT4_ENC_UTF8_12_1; + params->set_flags |= EXT4_TUNE_FL_ENCODING; } - if (!(params.set_flags & EXT4_TUNE_FL_ENCODING_FLAGS)) { - params.encoding_flags = 0; - params.set_flags |= EXT4_TUNE_FL_ENCODING_FLAGS; + if (!(params->set_flags & + EXT4_TUNE_FL_ENCODING_FLAGS)) { + params->encoding_flags = 0; + params->set_flags |= + EXT4_TUNE_FL_ENCODING_FLAGS; } } - if ((params.set_feature_compat_mask & - EXT4_FEATURE_COMPAT_DIR_INDEX)) { - uuid_t uu; + if (params->set_feature_compat_mask & + EXT4_FEATURE_COMPAT_DIR_INDEX) { + uuid_t uu; memcpy(&uu, sbi->s_hash_seed, UUID_SIZE); if (uuid_is_null(&uu)) - generate_random_uuid((char *) - &sbi->s_hash_seed); - if (params.set_flags & EXT4_TUNE_FL_DEF_HASH_ALG) - sbi->s_def_hash_version = params.def_hash_alg; + generate_random_uuid((char *)&sbi->s_hash_seed); + if (params->set_flags & EXT4_TUNE_FL_DEF_HASH_ALG) + sbi->s_def_hash_version = params->def_hash_alg; else if (sbi->s_def_hash_version == 0) sbi->s_def_hash_version = DX_HASH_HALF_MD4; if (!(es->s_flags & @@ -1510,21 +1514,42 @@ static int ext4_ioctl_set_tune_sb(struct file *filp, } } } - if (params.set_flags & EXT4_TUNE_FL_ENCODING) { + if (params->set_flags & EXT4_TUNE_FL_ENCODING) { if (!enabling_casefold) return -EINVAL; - if (params.encoding == 0) - params.encoding = EXT4_ENC_UTF8_12_1; - else if (params.encoding != EXT4_ENC_UTF8_12_1) + if (params->encoding == 0) + params->encoding = EXT4_ENC_UTF8_12_1; + else if (params->encoding != EXT4_ENC_UTF8_12_1) return -EINVAL; } - if (params.set_flags & EXT4_TUNE_FL_ENCODING_FLAGS) { + if (params->set_flags & EXT4_TUNE_FL_ENCODING_FLAGS) { if (!enabling_casefold) return -EINVAL; - if (params.encoding_flags & ~SB_ENC_SUPP_MASK) + if (params->encoding_flags & ~SB_ENC_SUPP_MASK) return -EINVAL; } + return 0; +} + +static int ext4_ioctl_set_tune_sb(struct file *filp, + struct ext4_tune_sb_params __user *in) +{ + struct ext4_tune_sb_params params; + struct super_block *sb = file_inode(filp)->i_sb; + struct ext4_sb_info *sbi = EXT4_SB(sb); + int ret; + + if (!capable(CAP_SYS_ADMIN)) + return -EPERM; + + if (copy_from_user(¶ms, in, sizeof(params))) + return -EFAULT; + + ret = ext4_validate_tune_sb_params(sb, ¶ms); + if (ret) + return ret; + ret = mnt_want_write_file(filp); if (ret) return ret; @@ -1933,6 +1958,7 @@ long ext4_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { return __ext4_ioctl(filp, cmd, arg); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ioctl); #ifdef CONFIG_COMPAT long ext4_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) @@ -2009,6 +2035,7 @@ long ext4_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) } return ext4_ioctl(file, cmd, (unsigned long) compat_ptr(arg)); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_compat_ioctl); #endif static void set_overhead(struct ext4_sb_info *sbi, @@ -2029,3 +2056,85 @@ int ext4_update_overhead(struct super_block *sb, bool force) return 0; return ext4_update_superblocks_fn(sb, set_overhead, &sbi->s_overhead); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_overhead); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +void ext4_sb_setlabel_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg) +{ + ext4_sb_setlabel(sbi, es, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_setlabel_test); + +void ext4_sb_setuuid_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg) +{ + ext4_sb_setuuid(sbi, es, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_setuuid_test); + +void ext4_sb_setparams_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg) +{ + ext4_sb_setparams(sbi, es, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_setparams_test); + +int ext4_validate_tune_sb_params_test(struct super_block *sb, + struct ext4_tune_sb_params *params) +{ + return ext4_validate_tune_sb_params(sb, params); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_validate_tune_sb_params_test); + +int ext4_update_primary_sb_test(struct super_block *sb, handle_t *handle, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg) +{ + return ext4_update_primary_sb(sb, handle, func, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_primary_sb_test); + +int ext4_update_backup_sb_test(struct super_block *sb, handle_t *handle, + ext4_group_t grp, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg) +{ + return ext4_update_backup_sb(sb, handle, grp, func, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_backup_sb_test); + +int ext4_update_superblocks_fn_test(struct super_block *sb, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg) +{ + return ext4_update_superblocks_fn(sb, func, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_superblocks_fn_test); + +void ext4_swap_inode_data_test(struct inode *inode1, struct inode *inode2) +{ + swap_inode_data(inode1, inode2); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_swap_inode_data_test); + +int ext4_ioctl_check_immutable_test(struct inode *inode, __u32 new_projid, + unsigned int flags) +{ + return ext4_ioctl_check_immutable(inode, new_projid, flags); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ioctl_check_immutable_test); + +bool ext4_dax_compatible_test(struct inode *inode, unsigned int oldflags, + unsigned int flags) +{ + return dax_compatible(inode, oldflags, flags); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dax_compatible_test); +#endif From c70aa271b595f9381f3a1bc8198b4bd24a64a83b Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:23:48 +0000 Subject: [PATCH 1570/2102] ext4: add KUnit tests for fs/ext4/resize.c Add a KUnit test suite (ext4_resize_test) covering online filesystem resizing, group validation, flex_bg table packing, backup descriptor reservation, and meta_bg conversion in fs/ext4/resize.c: - Precondition checks in ext4_resize_begin() and EXT4_FLAGS_RESIZING mutual exclusion with ext4_resize_end(). - Backup group iteration in ext4_list_backups() (sparse_super powers of 3/5/7, dense non-sparse sequence, and sparse_super2 s_backup_bgs) and reserved GDT validation in verify_reserved_gdb(). - Group geometry and overlap validation in verify_group_input() across partial prior groups, reserved-block ratios, out-of-bounds bitmaps and inode tables, bitmap collisions, and superblock/GDT overhead overlaps. - Flex group batch sizing in alloc_flex_gd(), descriptor flag and partial-group initialization in ext4_setup_next_flex_gd(), and packed metadata table placement and -ENOSPC handling in ext4_alloc_group_tables(). - Online partial-last-group extension in ext4_group_extend() updating superblock counts, block bitmaps, buddy caches, and backup superblocks. - Group addition in ext4_group_add() including backup reserved GDT updates via reserve_backup_gdb(), resize_inode validation and meta_bg conversion in ext4_convert_meta_bg(), and end-to-end ext4_resize_fs() growth across reserved GDT consumption into meta_bg. Route raw sb_getblk() calls in resize.c through ext4_sb_getblk() and wrap sb_issue_zeroout() in ext4_resize_issue_zeroout() with KUNIT_STATIC_STUB_REDIRECT so resize metadata I/O can be exercised deterministically in memory. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 3 +- fs/ext4/ext4.h | 32 + fs/ext4/resize-test.c | 1336 +++++++++++++++++++++++++++++++++++++++++ fs/ext4/resize.c | 102 +++- 4 files changed, 1448 insertions(+), 25 deletions(-) create mode 100644 fs/ext4/resize-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index c1853050886326..6163d47f3627aa 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -21,7 +21,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ fast_commit-test.o ialloc-test.o \ balloc-test.o orphan-test.o \ block_validity-test.o super-test.o \ - sysfs-test.o ioctl-test.o + sysfs-test.o ioctl-test.o \ + resize-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index afde7567c66196..1f9c044f7e2483 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -688,6 +688,17 @@ enum { GROUP_TABLE_COUNT, }; +/* + * ext4_new_flex_group_data is used by 64bit-resize interface to add a flex + * group each time. + */ +struct ext4_new_flex_group_data { + struct ext4_new_group_data *groups; + __u16 *bg_flags; + ext4_group_t resize_bg; + ext4_group_t count; +}; + /* * Flags used by ext4_map_blocks() */ @@ -3432,6 +3443,8 @@ extern bool ext4_empty_dir(struct inode *inode); /* resize.c */ extern void ext4_kvfree_array_rcu(void *to_free); +extern int ext4_resize_issue_zeroout(struct super_block *sb, sector_t blk, + sector_t nr_blks, gfp_t gfp_mask); extern int ext4_group_add(struct super_block *sb, struct ext4_new_group_data *input); extern int ext4_group_extend(struct super_block *sb, @@ -3441,6 +3454,25 @@ extern int ext4_resize_fs(struct super_block *sb, ext4_fsblk_t n_blocks_count); extern unsigned int ext4_list_backups(struct super_block *sb, unsigned int *three, unsigned int *five, unsigned int *seven); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_verify_group_input_test(struct super_block *sb, + struct ext4_new_group_data *input); +extern struct ext4_new_flex_group_data * +ext4_alloc_flex_gd_test(unsigned int flexbg_size, ext4_group_t o_group, + ext4_group_t n_group); +extern void ext4_free_flex_gd_test(struct ext4_new_flex_group_data *flex_gd); +extern int ext4_alloc_group_tables_test(struct super_block *sb, + struct ext4_new_flex_group_data *flex_gd, + unsigned int flexbg_size); +extern int ext4_verify_reserved_gdb_test(struct super_block *sb, + ext4_group_t end, + struct buffer_head *primary); +extern int ext4_setup_next_flex_gd_test(struct super_block *sb, + struct ext4_new_flex_group_data *flex_gd, + ext4_fsblk_t n_blocks_count); +extern int ext4_convert_meta_bg_test(struct super_block *sb, + struct inode *inode); +#endif /* super.c */ extern struct buffer_head *ext4_sb_bread(struct super_block *sb, diff --git a/fs/ext4/resize-test.c b/fs/ext4/resize-test.c new file mode 100644 index 00000000000000..81c9fd96816c6a --- /dev/null +++ b/fs/ext4/resize-test.c @@ -0,0 +1,1336 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/resize.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "mballoc.h" + +#define RESIZE_TEST_BLK_SIZE 1024U +#define RESIZE_TEST_BLK_BITS 10U +#define RESIZE_TEST_BLOCKS_PER_GRP 1024U +#define RESIZE_TEST_FIRST_DATA_BLK 1U +#define RESIZE_TEST_INODE_SIZE 256U +#define RESIZE_TEST_EXTRA_ISIZE 32U +#define RESIZE_TEST_INODES_PER_GRP 32U +#define RESIZE_TEST_ITB_PER_GRP 8U +#define RESIZE_TEST_DESC_SIZE 64U +#define RESIZE_TEST_DESC_PER_BLK 16U +#define RESIZE_TEST_DESC_PER_BLK_BITS 4U + +struct resize_mock_blk { + struct list_head node; + ext4_fsblk_t blocknr; + struct buffer_head bh; + u8 *data; +}; + +struct resize_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct folio *bh_folio; + struct list_head blks; + struct buffer_head iloc_bh; + u8 iloc_buf[RESIZE_TEST_BLK_SIZE]; + struct inode *resize_inode; + ext4_fsblk_t device_blocks; + ext4_fsblk_t last_freed_blk; + unsigned long last_freed_count; + int zeroout_calls; + sector_t zeroout_blks; + int zeroout_err; + bool sb_getblk_fail; + bool mb_inited; +}; + +static struct kunit *active_resize_test; + +static struct inode *resize_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = RESIZE_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void resize_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void resize_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **resize_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations resize_test_sops = { + .alloc_inode = resize_test_alloc_inode, + .free_inode = resize_test_free_inode, + .evict_inode = resize_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = resize_test_get_dquots, +#endif +}; + +static int resize_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static void resize_test_sb_upd_work(struct work_struct *work) +{ +} + +static void resize_test_err_timer(struct timer_list *t) +{ +} + +static struct file_system_type resize_test_fs_type = { + .name = "ext4_resize_kunit", + .init_fs_context = resize_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void resize_init_mock_bh(struct buffer_head *bh, struct folio *folio, + u8 *data, size_t size, sector_t blocknr) +{ + memset(bh, 0, sizeof(*bh)); + bh->b_folio = folio; + bh->b_data = (char *)data; + bh->b_size = size; + bh->b_blocknr = blocknr; + atomic_set(&bh->b_count, 2); + set_buffer_uptodate(bh); +} + +static struct buffer_head *resize_lookup_bh(struct resize_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct resize_mock_blk *blk; + + list_for_each_entry(blk, &ctx->blks, node) { + if (blk->blocknr == blocknr) + return &blk->bh; + } + return NULL; +} + +static struct buffer_head *resize_get_or_create_bh(struct resize_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct buffer_head *bh; + struct resize_mock_blk *blk; + + bh = resize_lookup_bh(ctx, blocknr); + if (bh) { + get_bh(bh); + return bh; + } + + blk = kzalloc_obj(*blk); + if (!blk) + return NULL; + blk->data = kzalloc(RESIZE_TEST_BLK_SIZE, GFP_KERNEL); + if (!blk->data) { + kfree(blk); + return NULL; + } + blk->blocknr = blocknr; + resize_init_mock_bh(&blk->bh, ctx->bh_folio, blk->data, + RESIZE_TEST_BLK_SIZE, blocknr); + list_add_tail(&blk->node, &ctx->blks); + get_bh(&blk->bh); + return &blk->bh; +} + +static struct buffer_head *resize_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + + if (!test) + return NULL; + ctx = test->priv; + if (!ctx || sb != ctx->sb || ctx->sb_getblk_fail) + return NULL; + + return resize_get_or_create_bh(ctx, block); +} + +static struct buffer_head *resize_sb_bread_stub(struct super_block *sb, + sector_t block, + blk_opf_t op_flags) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + struct buffer_head *bh; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return ERR_PTR(-EIO); + if ((ext4_fsblk_t)block >= ctx->device_blocks) + return ERR_PTR(-EIO); + + bh = resize_get_or_create_bh(ctx, block); + if (!bh) + return ERR_PTR(-ENOMEM); + return bh; +} + +static int resize_zeroout_stub(struct super_block *sb, sector_t blk, + sector_t nr_blks, gfp_t gfp_mask) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + sector_t i; + + if (!test) + return 0; + ctx = test->priv; + if (!ctx) + return 0; + if (ctx->zeroout_err) + return ctx->zeroout_err; + + ctx->zeroout_calls++; + ctx->zeroout_blks += nr_blks; + for (i = 0; i < nr_blks; i++) { + struct buffer_head *bh = resize_lookup_bh(ctx, blk + i); + + if (bh) + memset(bh->b_data, 0, bh->b_size); + } + return 0; +} + +static struct inode *resize_iget_stub(struct super_block *sb, unsigned long ino, + ext4_iget_flags flags, + const char *function, unsigned int line) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + + if (!test) + return ERR_PTR(-ENOENT); + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return ERR_PTR(-ENOENT); + if (ino == EXT4_RESIZE_INO && ctx->resize_inode) { + ihold(ctx->resize_inode); + return ctx->resize_inode; + } + return ERR_PTR(-ENOENT); +} + +static int resize_get_inode_loc_stub(struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + + if (!test) + return -EIO; + ctx = test->priv; + if (!ctx) + return -EIO; + + get_bh(&ctx->iloc_bh); + iloc->bh = &ctx->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int resize_mark_iloc_dirty_stub(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + brelse(iloc->bh); + iloc->bh = NULL; + return 0; +} + +static int resize_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + return 0; +} + +static void resize_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + + if (!test) + return; + ctx = test->priv; + if (!ctx) + return; + + ctx->last_freed_blk = block; + ctx->last_freed_count = count; + if (bh) + brelse(bh); +} + +static void resize_test_cleanup(struct resize_test_ctx *ctx) +{ + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct flex_groups **flex_groups; + struct resize_mock_blk *blk, *tmp; + unsigned int i; + + active_resize_test = NULL; + + cancel_work_sync(&sbi->s_sb_upd_work); + timer_delete_sync(&sbi->s_err_report); + + if (ctx->resize_inode) { + iput(ctx->resize_inode); + ctx->resize_inode = NULL; + } + + if (ctx->mb_inited && sb) { + ext4_mb_release(sb); + ctx->mb_inited = false; + } + + if (sb) { + deactivate_super(sb); + ctx->sb = NULL; + } + rcu_barrier(); + + percpu_counter_destroy(&sbi->s_freeclusters_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeinodes_counter); + + flex_groups = rcu_access_pointer(sbi->s_flex_groups); + if (flex_groups) { + for (i = 0; i < sbi->s_flex_groups_allocated; i++) + kvfree(flex_groups[i]); + kvfree(flex_groups); + rcu_assign_pointer(sbi->s_flex_groups, NULL); + sbi->s_flex_groups_allocated = 0; + } + + kvfree(rcu_access_pointer(sbi->s_group_desc)); + rcu_assign_pointer(sbi->s_group_desc, NULL); + + list_for_each_entry_safe(blk, tmp, &ctx->blks, node) { + list_del(&blk->node); + kfree(blk->data); + kfree(blk); + } + + if (ctx->bh_folio) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + } + + if (ctx->bdev.bd_stats) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + } +} + +KUNIT_DEFINE_ACTION_WRAPPER(resize_test_cleanup_action, resize_test_cleanup, + struct resize_test_ctx *); + +static int resize_test_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +/* + * Configure an in-memory ext4 filesystem with @ngroups initial groups, + * optional @reserved_gdb reserved GDT blocks (enabling RESIZE_INODE and + * populating the resize inode's DIND + reserved GDT blocks), optional + * flex_bg (@log_flex > 0), and @last_grp_blks blocks in the final group. + */ +static void resize_configure_fs(struct kunit *test, ext4_group_t ngroups, + u16 reserved_gdb, u8 log_flex, + u32 last_grp_blks) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = ctx->es; + struct buffer_head **group_desc; + unsigned long gdb_count; + ext4_fsblk_t total_blks = RESIZE_TEST_FIRST_DATA_BLK; + ext4_fsblk_t total_free_blks = 0; + u32 total_inodes = ngroups * RESIZE_TEST_INODES_PER_GRP; + ext4_group_t g; + int ret; + + KUNIT_ASSERT_GT(test, ngroups, 0U); + KUNIT_ASSERT_LE(test, last_grp_blks, RESIZE_TEST_BLOCKS_PER_GRP); + + es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + es->s_log_block_size = cpu_to_le32(0); + es->s_log_cluster_size = cpu_to_le32(0); + es->s_first_data_block = cpu_to_le32(RESIZE_TEST_FIRST_DATA_BLK); + es->s_blocks_per_group = cpu_to_le32(RESIZE_TEST_BLOCKS_PER_GRP); + es->s_clusters_per_group = cpu_to_le32(RESIZE_TEST_BLOCKS_PER_GRP); + es->s_inodes_per_group = cpu_to_le32(RESIZE_TEST_INODES_PER_GRP); + es->s_inodes_count = cpu_to_le32(total_inodes); + es->s_free_inodes_count = cpu_to_le32(total_inodes - 10); + es->s_first_ino = cpu_to_le32(11); + es->s_inode_size = cpu_to_le16(RESIZE_TEST_INODE_SIZE); + es->s_desc_size = cpu_to_le16(RESIZE_TEST_DESC_SIZE); + es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + es->s_state = cpu_to_le16(EXT4_VALID_FS); + es->s_errors = cpu_to_le16(EXT4_ERRORS_CONTINUE); + es->s_checksum_type = EXT4_CRC32C_CHKSUM; + es->s_reserved_gdt_blocks = cpu_to_le16(reserved_gdb); + generate_random_uuid(es->s_uuid); + + ext4_set_feature_extents(sb); + ext4_set_feature_64bit(sb); + ext4_set_feature_filetype(sb); + ext4_set_feature_sparse_super(sb); + ext4_set_feature_metadata_csum(sb); + if (reserved_gdb > 0) + ext4_set_feature_resize_inode(sb); + if (log_flex > 0) { + ext4_set_feature_flex_bg(sb); + es->s_log_groups_per_flex = log_flex; + sbi->s_log_groups_per_flex = log_flex; + } + + sbi->s_csum_seed = ext4_chksum(~0, es->s_uuid, sizeof(es->s_uuid)); + sbi->s_groups_count = ngroups; + gdb_count = DIV_ROUND_UP(ngroups, RESIZE_TEST_DESC_PER_BLK); + sbi->s_gdb_count = gdb_count; + + group_desc = kvcalloc(gdb_count, sizeof(*group_desc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, group_desc); + rcu_assign_pointer(sbi->s_group_desc, group_desc); + for (g = 0; g < gdb_count; g++) { + struct buffer_head *bh; + + bh = resize_get_or_create_bh(ctx, + RESIZE_TEST_FIRST_DATA_BLK + 1 + g); + KUNIT_ASSERT_NOT_NULL(test, bh); + brelse(bh); + group_desc[g] = bh; + } + + for (g = 0; g < ngroups; g++) { + u32 grp_blks = (g == ngroups - 1) ? + last_grp_blks : RESIZE_TEST_BLOCKS_PER_GRP; + ext4_fsblk_t start = ext4_group_first_block_no(sb, g); + unsigned int overhead = ext4_bg_num_gdb(sb, g); + unsigned int used_meta; + ext4_fsblk_t bb_blk, ib_blk, it_blk; + struct buffer_head *bb_bh, *ib_bh; + struct ext4_group_desc *gdp; + u32 free_blks; + + if (ext4_bg_has_super(sb, g)) + overhead += 1 + reserved_gdb; + + bb_blk = start + overhead; + ib_blk = bb_blk + 1; + it_blk = ib_blk + 1; + used_meta = overhead + 2 + RESIZE_TEST_ITB_PER_GRP; + if (g == 0 && reserved_gdb > 0) + used_meta++; + + bb_bh = resize_get_or_create_bh(ctx, bb_blk); + ib_bh = resize_get_or_create_bh(ctx, ib_blk); + KUNIT_ASSERT_NOT_NULL(test, bb_bh); + KUNIT_ASSERT_NOT_NULL(test, ib_bh); + + mb_set_bits(bb_bh->b_data, 0, used_meta); + ext4_mark_bitmap_end(grp_blks, sb->s_blocksize * 8, + bb_bh->b_data); + ext4_mark_bitmap_end(RESIZE_TEST_INODES_PER_GRP, + sb->s_blocksize * 8, ib_bh->b_data); + + gdp = ext4_get_group_desc(sb, g, NULL); + KUNIT_ASSERT_NOT_NULL(test, gdp); + memset(gdp, 0, RESIZE_TEST_DESC_SIZE); + ext4_block_bitmap_set(sb, gdp, bb_blk); + ext4_inode_bitmap_set(sb, gdp, ib_blk); + ext4_inode_table_set(sb, gdp, it_blk); + free_blks = grp_blks - used_meta; + ext4_free_group_clusters_set(sb, gdp, free_blks); + ext4_free_inodes_set(sb, gdp, RESIZE_TEST_INODES_PER_GRP); + ext4_itable_unused_set(sb, gdp, RESIZE_TEST_INODES_PER_GRP); + gdp->bg_flags = cpu_to_le16(EXT4_BG_INODE_ZEROED); + ext4_block_bitmap_csum_set(sb, gdp, bb_bh); + ext4_inode_bitmap_csum_set(sb, gdp, ib_bh); + ext4_group_desc_csum_set(sb, g, gdp); + + brelse(bb_bh); + brelse(ib_bh); + + total_blks += grp_blks; + total_free_blks += free_blks; + } + + ext4_blocks_count_set(es, total_blks); + ext4_free_blocks_count_set(es, total_free_blks); + ext4_r_blocks_count_set(es, div_u64(total_blks, 20)); + sbi->s_blockfile_groups = ngroups; + + if (reserved_gdb > 0) { + ext4_fsblk_t dind_blk; + struct buffer_head *dind_bh; + __le32 *dind_data; + unsigned int res; + unsigned int total_rsv_blks = 1; + + dind_blk = ext4_group_first_block_no(sb, 0) + 1 + gdb_count + + reserved_gdb + 2 + RESIZE_TEST_ITB_PER_GRP; + dind_bh = resize_get_or_create_bh(ctx, dind_blk); + KUNIT_ASSERT_NOT_NULL(test, dind_bh); + dind_data = (__le32 *)dind_bh->b_data; + + for (res = 0; res < reserved_gdb; res++) { + ext4_fsblk_t pri_blk = RESIZE_TEST_FIRST_DATA_BLK + 1 + + gdb_count + res; + struct buffer_head *pri_bh; + __le32 *pri_data; + unsigned int three = 1, five = 5, seven = 7; + unsigned int bgrp, idx = 0; + + dind_data[(gdb_count + res) % + EXT4_ADDR_PER_BLOCK(sb)] = + cpu_to_le32(pri_blk); + pri_bh = resize_get_or_create_bh(ctx, pri_blk); + KUNIT_ASSERT_NOT_NULL(test, pri_bh); + pri_data = (__le32 *)pri_bh->b_data; + + while ((bgrp = ext4_list_backups(sb, &three, &five, + &seven)) < ngroups) { + pri_data[idx++] = cpu_to_le32( + bgrp * RESIZE_TEST_BLOCKS_PER_GRP + + pri_blk); + } + total_rsv_blks += 1 + idx; + brelse(pri_bh); + } + brelse(dind_bh); + + ctx->resize_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, ctx->resize_inode); + ctx->resize_inode->i_ino = EXT4_RESIZE_INO; + ctx->resize_inode->i_mode = S_IFREG | 0600; + ctx->resize_inode->i_blkbits = RESIZE_TEST_BLK_BITS; + ctx->resize_inode->i_blocks = total_rsv_blks * + (RESIZE_TEST_BLK_SIZE >> 9); + EXT4_I(ctx->resize_inode)->i_data[EXT4_DIND_BLOCK] = + cpu_to_le32(dind_blk); + } + + if (log_flex > 0) { + ret = ext4_fill_flex_info_test(sb); + KUNIT_ASSERT_EQ(test, ret, 1); + } + + ret = ext4_mb_init(sb); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->mb_inited = true; + + ret = percpu_counter_init(&sbi->s_freeclusters_counter, + total_free_blks, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_freeinodes_counter, + total_inodes - 10, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + + ext4_calculate_overhead(sb); + es->s_overhead_clusters = cpu_to_le32(sbi->s_overhead); + ext4_superblock_csum_set(sb); +} + +static int resize_test_init(struct kunit *test) +{ + struct resize_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct buffer_head *sbh; + int ret; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + INIT_LIST_HEAD(&ctx->blks); + ctx->device_blocks = 1 + 64 * RESIZE_TEST_BLOCKS_PER_GRP; + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->bdev.bd_stats != NULL); + + ctx->bh_folio = folio_alloc(GFP_KERNEL, 0); + if (!ctx->bh_folio) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "folio_alloc failed"); + } + + fc = fs_context_for_mount(&resize_test_fs_type, 0); + if (IS_ERR(fc)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "fs_context_for_mount failed: %ld", + PTR_ERR(fc)); + } + sb = sget_fc(fc, NULL, resize_test_set_super); + put_fs_context(fc); + if (IS_ERR(sb)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "sget_fc failed: %ld", PTR_ERR(sb)); + } + ctx->sb = sb; + sbi = &ctx->sbi; + INIT_WORK(&sbi->s_sb_upd_work, resize_test_sb_upd_work); + timer_setup(&sbi->s_err_report, resize_test_err_timer, 0); + up_write(&sb->s_umount); + + ret = kunit_add_action_or_reset(test, resize_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, ret, 0); + + sb->s_fs_info = sbi; + sb->s_op = &resize_test_sops; + sb->s_blocksize = RESIZE_TEST_BLK_SIZE; + sb->s_blocksize_bits = RESIZE_TEST_BLK_BITS; + sb->s_magic = EXT4_SUPER_MAGIC; + sb->s_maxbytes = MAX_LFS_FILESIZE; + INIT_LIST_HEAD(&sb->s_inodes); +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + + strscpy(sb->s_id, "ext4_resize_kunit", sizeof(sb->s_id)); + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = RESIZE_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + sbi->s_sb = sb; + sbi->s_blockgroup_lock = &ctx->bgl; + bgl_lock_init(&ctx->bgl); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_es_lock); + INIT_LIST_HEAD(&sbi->s_es_list); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10); + + sbi->s_blocks_per_group = RESIZE_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = RESIZE_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_inodes_per_group = RESIZE_TEST_INODES_PER_GRP; + sbi->s_inode_size = RESIZE_TEST_INODE_SIZE; + sbi->s_inodes_per_block = RESIZE_TEST_BLK_SIZE / RESIZE_TEST_INODE_SIZE; + sbi->s_itb_per_group = RESIZE_TEST_ITB_PER_GRP; + sbi->s_desc_size = RESIZE_TEST_DESC_SIZE; + sbi->s_desc_per_block = RESIZE_TEST_DESC_PER_BLK; + sbi->s_desc_per_block_bits = RESIZE_TEST_DESC_PER_BLK_BITS; + sbi->s_first_ino = 11; + sbi->s_mount_state = EXT4_VALID_FS; + set_opt(sb, ERRORS_CONT); + + sbh = resize_get_or_create_bh(ctx, RESIZE_TEST_FIRST_DATA_BLK); + KUNIT_ASSERT_NOT_NULL(test, sbh); + brelse(sbh); + sbi->s_sbh = sbh; + ctx->es = (struct ext4_super_block *)sbh->b_data; + sbi->s_es = ctx->es; + + resize_init_mock_bh(&ctx->iloc_bh, ctx->bh_folio, ctx->iloc_buf, + RESIZE_TEST_BLK_SIZE, 99); + + active_resize_test = test; + kunit_activate_static_stub(test, ext4_sb_getblk, resize_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_sb_bread, resize_sb_bread_stub); + kunit_activate_static_stub(test, ext4_resize_issue_zeroout, + resize_zeroout_stub); + kunit_activate_static_stub(test, __ext4_iget, resize_iget_stub); + kunit_activate_static_stub(test, ext4_get_inode_loc, + resize_get_inode_loc_stub); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + resize_mark_iloc_dirty_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + resize_mark_inode_dirty_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + resize_free_blocks_stub); + + return 0; +} + +/* + * Test 1: ext4_resize_begin() precondition checks and EXT4_FLAGS_RESIZING + * mutual exclusion with ext4_resize_end(). + */ +static void test_resize_begin_and_end_guards(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + resize_configure_fs(test, 2, 0, 0, RESIZE_TEST_BLOCKS_PER_GRP); + + /* Non-zero s_reserved_gdt_blocks without resize_inode -> -EFSCORRUPTED */ + ctx->es->s_reserved_gdt_blocks = cpu_to_le16(2); + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), -EFSCORRUPTED); + ctx->es->s_reserved_gdt_blocks = 0; + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + + /* Mounted from backup superblock -> -EPERM */ + ctx->sbi.s_sbh->b_blocknr = 1025; + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), -EPERM); + ctx->sbi.s_sbh->b_blocknr = RESIZE_TEST_FIRST_DATA_BLK; + + /* Filesystem has recorded errors -> -EPERM */ + ctx->sbi.s_mount_state |= EXT4_ERROR_FS; + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), -EPERM); + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + + /* sparse_super2 online resize unsupported -> -EOPNOTSUPP */ + ext4_set_feature_sparse_super2(sb); + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), -EOPNOTSUPP); + ext4_clear_feature_sparse_super2(sb); + + /* Valid begin acquires EXT4_FLAGS_RESIZING; second call gets -EBUSY */ + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), 0); + KUNIT_EXPECT_TRUE(test, test_bit(EXT4_FLAGS_RESIZING, + &ctx->sbi.s_ext4_flags)); + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), -EBUSY); + + /* ext4_resize_end releases lock so subsequent begin succeeds */ + KUNIT_EXPECT_EQ(test, ext4_resize_end(sb, false), 0); + KUNIT_EXPECT_FALSE(test, test_bit(EXT4_FLAGS_RESIZING, + &ctx->sbi.s_ext4_flags)); + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), 0); + KUNIT_EXPECT_EQ(test, ext4_resize_end(sb, false), 0); +} + +/* + * Test 2: ext4_list_backups() sequence generation (sparse_super, dense, and + * sparse_super2) and verify_reserved_gdb() validation. + */ +static void test_list_backups_and_verify_reserved_gdb(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + static const unsigned int expected_sparse[] = { + 1, 3, 5, 7, 9, 25, 27, 49, 81 + }; + unsigned int three, five, seven; + struct buffer_head *pri_bh; + __le32 *pri_data; + unsigned int i; + + resize_configure_fs(test, 4, 0, 0, RESIZE_TEST_BLOCKS_PER_GRP); + + /* 1. sparse_super yields sorted powers of 3, 5, and 7 */ + three = 1; + five = 5; + seven = 7; + for (i = 0; i < ARRAY_SIZE(expected_sparse); i++) { + KUNIT_EXPECT_EQ_MSG(test, + ext4_list_backups(sb, &three, &five, &seven), + expected_sparse[i], "sparse index %u", i); + } + + /* 2. Without sparse_super: every consecutive group 1, 2, 3, 4 */ + ext4_clear_feature_sparse_super(sb); + three = 1; + five = 5; + seven = 7; + for (i = 1; i <= 4; i++) + KUNIT_EXPECT_EQ(test, + ext4_list_backups(sb, &three, &five, &seven), + i); + ext4_set_feature_sparse_super(sb); + + /* 3. sparse_super2: reads s_backup_bgs[0..1], skipping 0, then UINT_MAX */ + ext4_set_feature_sparse_super2(sb); + ctx->es->s_backup_bgs[0] = 0; + ctx->es->s_backup_bgs[1] = cpu_to_le32(12); + three = 1; + five = 5; + seven = 7; + KUNIT_EXPECT_EQ(test, ext4_list_backups(sb, &three, &five, &seven), 12U); + KUNIT_EXPECT_EQ(test, ext4_list_backups(sb, &three, &five, &seven), + UINT_MAX); + ext4_clear_feature_sparse_super2(sb); + + /* 4. verify_reserved_gdb: valid backup list for groups < 10 (5 backups) */ + pri_bh = resize_get_or_create_bh(ctx, 3); + KUNIT_ASSERT_NOT_NULL(test, pri_bh); + pri_data = (__le32 *)pri_bh->b_data; + for (i = 0; i < 5; i++) + pri_data[i] = cpu_to_le32(expected_sparse[i] * + RESIZE_TEST_BLOCKS_PER_GRP + 3); + KUNIT_EXPECT_EQ(test, ext4_verify_reserved_gdb_test(sb, 10, pri_bh), 5); + + /* Corrupted backup block entry -> -EINVAL */ + pri_data[2] = cpu_to_le32(99999); + KUNIT_EXPECT_EQ(test, ext4_verify_reserved_gdb_test(sb, 10, pri_bh), + -EINVAL); + + /* Exceeding EXT4_ADDR_PER_BLOCK (256 on 1K blocks) -> -EFBIG */ + ext4_clear_feature_sparse_super(sb); + for (i = 0; i <= 257 && i < RESIZE_TEST_BLK_SIZE / sizeof(__le32); i++) + pri_data[i] = cpu_to_le32((i + 1) * RESIZE_TEST_BLOCKS_PER_GRP + + 3); + /* + * Allocate an oversized buffer temporarily so 257 entries can match + * before hitting ++gdbackups > EXT4_ADDR_PER_BLOCK(sb) (256). + */ + { + __le32 *big_buf = kunit_kcalloc(test, 260, sizeof(__le32), + GFP_KERNEL); + u8 *orig_data = (u8 *)pri_bh->b_data; + + KUNIT_ASSERT_NOT_NULL(test, big_buf); + for (i = 0; i < 258; i++) + big_buf[i] = cpu_to_le32((i + 1) * + RESIZE_TEST_BLOCKS_PER_GRP + + 3); + pri_bh->b_data = (char *)big_buf; + KUNIT_EXPECT_EQ(test, + ext4_verify_reserved_gdb_test(sb, 259, pri_bh), + -EFBIG); + pri_bh->b_data = (char *)orig_data; + } + brelse(pri_bh); +} + +/* + * Test 3: verify_group_input() boundary and overlap checks when adding sparse + * backup group 3 (which carries superblock + GDT overhead at group start). + */ +static void test_verify_group_input_rejections_and_acceptance(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_new_group_data input; + ext4_fsblk_t start; + unsigned int overhead; + + /* Configure 3 full groups (0..2); next group to add is sparse group 3 */ + resize_configure_fs(test, 3, 1, 0, RESIZE_TEST_BLOCKS_PER_GRP); + start = ext4_blocks_count(ctx->es); + /* Group 3 has backup super (1) + 1 GDT + 1 reserved GDT = 3 blocks */ + overhead = 3; + + memset(&input, 0, sizeof(input)); + input.group = 3; + input.blocks_count = RESIZE_TEST_BLOCKS_PER_GRP; + input.reserved_blocks = 50; + input.block_bitmap = start + overhead; + input.inode_bitmap = start + overhead + 1; + input.inode_table = start + overhead + 2; + + /* 1. Wrong group number */ + input.group = 4; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.group = 3; + + /* 2. Previous last group not full */ + ext4_blocks_count_set(ctx->es, start - 10); + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + ext4_blocks_count_set(ctx->es, start); + + /* 3. reserved_blocks > blocks_count / 5 */ + input.reserved_blocks = 205; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.reserved_blocks = 50; + + /* 4. blocks_count smaller than metadata (free_blocks_count < 0) */ + input.blocks_count = 10; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.blocks_count = RESIZE_TEST_BLOCKS_PER_GRP; + + /* 5. Last block beyond underlying device -> -EIO */ + ctx->device_blocks = start + 100; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), -EIO); + ctx->device_blocks = 1 + 64 * RESIZE_TEST_BLOCKS_PER_GRP; + + /* 6. Bitmaps or inode table outside [start, end) */ + input.block_bitmap = start - 1; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.block_bitmap = start + overhead; + + input.inode_bitmap = start + RESIZE_TEST_BLOCKS_PER_GRP; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_bitmap = start + overhead + 1; + + input.inode_table = start + RESIZE_TEST_BLOCKS_PER_GRP - + RESIZE_TEST_ITB_PER_GRP + 1; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_table = start + overhead + 2; + + /* 7. Bitmap collision and bitmap inside inode table */ + input.inode_bitmap = input.block_bitmap; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_bitmap = input.inode_table + 3; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_bitmap = start + overhead + 1; + + input.block_bitmap = input.inode_table; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.block_bitmap = start + overhead; + + /* 8. Bitmaps or inode table overlapping superblock/GDT overhead */ + input.block_bitmap = start + overhead - 1; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.block_bitmap = start + overhead; + + input.inode_bitmap = start; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_bitmap = start + overhead + 1; + + input.inode_table = start + 1; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_table = start + overhead + 2; + + /* 9. Valid group input accepted with exact free_clusters_count */ + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), 0); + /* 1024 - 2 (bitmaps) - 3 (overhead) - 8 (itable) = 1011 */ + KUNIT_EXPECT_EQ(test, input.free_clusters_count, 1011U); +} + +/* + * Test 4: alloc_flex_gd(), ext4_setup_next_flex_gd(), and + * ext4_alloc_group_tables() packed flex_bg layout and -ENOSPC handling. + */ +static void test_alloc_setup_flex_gd_and_group_tables(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_new_flex_group_data *flex_gd; + ext4_fsblk_t g4_start; + + /* 4 initial groups (1 flex_bg of size 4, log_flex = 2), meta_bg mode */ + resize_configure_fs(test, 4, 0, 2, RESIZE_TEST_BLOCKS_PER_GRP); + ext4_set_feature_meta_bg(sb); + ctx->es->s_first_meta_bg = 0; + + /* 1. alloc_flex_gd shrinks allocation when adding only 1 group (4..4) */ + flex_gd = ext4_alloc_flex_gd_test(16, 4, 4); + KUNIT_ASSERT_NOT_NULL(test, flex_gd); + KUNIT_EXPECT_EQ(test, flex_gd->resize_bg, 1U); + ext4_free_flex_gd_test(flex_gd); + + /* 2. Full flex_bg batch (groups 4..7, with group 7 partial = 500 blks) */ + flex_gd = ext4_alloc_flex_gd_test(4, 3, 7); + KUNIT_ASSERT_NOT_NULL(test, flex_gd); + KUNIT_EXPECT_EQ(test, flex_gd->resize_bg, 4U); + + /* No-op when target equals current blocks_count */ + KUNIT_EXPECT_EQ(test, + ext4_setup_next_flex_gd_test(sb, flex_gd, + ext4_blocks_count(ctx->es)), + 0); + + /* Setup groups 4, 5, 6 (1024 blks each) + group 7 (500 blks) */ + KUNIT_EXPECT_EQ(test, + ext4_setup_next_flex_gd_test(sb, flex_gd, + 1 + 7 * 1024 + 500), + 1); + KUNIT_EXPECT_EQ(test, flex_gd->count, 4U); + KUNIT_EXPECT_EQ(test, flex_gd->groups[0].group, 4U); + KUNIT_EXPECT_EQ(test, flex_gd->groups[3].group, 7U); + KUNIT_EXPECT_EQ(test, flex_gd->groups[3].blocks_count, 500U); + /* Final group clears BG_BLOCK_UNINIT under group_desc_csum */ + KUNIT_EXPECT_NE(test, flex_gd->bg_flags[0] & EXT4_BG_BLOCK_UNINIT, 0); + KUNIT_EXPECT_EQ(test, flex_gd->bg_flags[3] & EXT4_BG_BLOCK_UNINIT, 0); + + /* + * 3. ext4_alloc_group_tables: group 4 has no super/meta_bg overhead + * (group 5 has sparse backup super -> overhead=1, stopping contiguous + * span at end of group 4). All 4 block bitmaps, 4 inode bitmaps, and + * 4*8=32 inode table blocks (40 blocks total) pack into group 4! + */ + g4_start = ext4_group_first_block_no(sb, 4); + KUNIT_EXPECT_EQ(test, ext4_alloc_group_tables_test(sb, flex_gd, 4), 0); + KUNIT_EXPECT_EQ(test, flex_gd->groups[0].block_bitmap, g4_start); + KUNIT_EXPECT_EQ(test, flex_gd->groups[3].block_bitmap, g4_start + 3); + KUNIT_EXPECT_EQ(test, flex_gd->groups[0].inode_bitmap, g4_start + 4); + KUNIT_EXPECT_EQ(test, flex_gd->groups[3].inode_bitmap, g4_start + 7); + KUNIT_EXPECT_EQ(test, flex_gd->groups[0].inode_table, g4_start + 8); + KUNIT_EXPECT_EQ(test, flex_gd->groups[3].inode_table, g4_start + 32); + /* Group 4 hosts all 40 metadata blocks -> BG_BLOCK_UNINIT cleared */ + KUNIT_EXPECT_EQ(test, flex_gd->bg_flags[0] & EXT4_BG_BLOCK_UNINIT, 0); + KUNIT_EXPECT_EQ(test, flex_gd->groups[0].free_clusters_count, + 1024U - 40U); + + /* 4. Insufficient space in flex_gd returns -ENOSPC */ + flex_gd->count = 1; + flex_gd->groups[0].group = 4; + flex_gd->groups[0].blocks_count = 5; + flex_gd->groups[0].mdata_blocks = 0; + KUNIT_EXPECT_EQ(test, ext4_alloc_group_tables_test(sb, flex_gd, 4), + -ENOSPC); + + ext4_free_flex_gd_test(flex_gd); +} + +/* + * Test 5: ext4_group_extend() validation and partial-last-group online + * extension updating superblock, block bitmap, buddy cache, and backup SB. + */ +static void test_group_extend_partial_last_group(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_super_block *es = ctx->es; + struct ext4_super_block *backup_es; + struct buffer_head *b1_bh; + ext4_fsblk_t o_blks, o_free; + s64 free_before; + + /* 2 groups: group 0 full (1024 blks), group 1 partial (600 blks) */ + resize_configure_fs(test, 2, 0, 0, 600); + o_blks = ext4_blocks_count(es); + o_free = ext4_free_blocks_count(es); + KUNIT_ASSERT_EQ(test, o_blks, 1ULL + 1024ULL + 600ULL); + + /* No-op for 0 and o_blocks_count */ + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, 0), 0); + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, o_blks), 0); + + /* Shrink attempt -> -EINVAL */ + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, o_blks - 10), -EINVAL); + + /* Target beyond underlying device -> -ENOSPC */ + ctx->device_blocks = o_blks + 100; + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, o_blks + 200), -ENOSPC); + ctx->device_blocks = 1 + 64 * RESIZE_TEST_BLOCKS_PER_GRP; + + /* Extend group 1 by 300 blocks (from 600 to 900 blocks) */ + free_before = percpu_counter_sum(&ctx->sbi.s_freeclusters_counter); + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, o_blks + 300), 0); + KUNIT_EXPECT_EQ(test, ext4_blocks_count(es), o_blks + 300); + KUNIT_EXPECT_EQ(test, ext4_free_blocks_count(es), o_free + 300); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_freeclusters_counter), + free_before + 300); + + /* Extend past group 1 boundary clamps to end of group 1 (+124 blocks) */ + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, o_blks + 800), 0); + KUNIT_EXPECT_EQ(test, ext4_blocks_count(es), 1ULL + 2048ULL); + + /* Once group 1 is full, further ext4_group_extend returns -EPERM */ + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, 1ULL + 2200ULL), + -EPERM); + + /* Backup superblock in group 1 (block 1025) reflects new size */ + b1_bh = resize_lookup_bh(ctx, ext4_group_first_block_no(sb, 1)); + KUNIT_ASSERT_NOT_NULL(test, b1_bh); + backup_es = (struct ext4_super_block *)b1_bh->b_data; + KUNIT_EXPECT_EQ(test, ext4_blocks_count(backup_es), 1ULL + 2048ULL); + KUNIT_EXPECT_EQ(test, le16_to_cpu(backup_es->s_block_group_nr), 1U); +} + +/* + * Test 6: ext4_group_add() error guards and adding non-sparse group 2 plus + * sparse backup group 3 (exercising reserve_backup_gdb() on resize_inode). + */ +static void test_group_add_with_resize_inode_and_backup_gdb(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_new_group_data input; + struct buffer_head *pri_bh; + __le32 *pri_data; + blkcnt_t rsv_iblocks_before; + ext4_fsblk_t start; + + /* 2 initial groups, 1 reserved GDT block (at block 3) */ + resize_configure_fs(test, 2, 1, 0, RESIZE_TEST_BLOCKS_PER_GRP); + + /* 1. Overflow guards on blocks_count and s_inodes_count */ + memset(&input, 0, sizeof(input)); + input.group = 2; + input.blocks_count = 1024; + ext4_blocks_count_set(ctx->es, ~0ULL - 100); + KUNIT_EXPECT_EQ(test, ext4_group_add(sb, &input), -EINVAL); + ext4_blocks_count_set(ctx->es, 1 + 2 * RESIZE_TEST_BLOCKS_PER_GRP); + + ctx->es->s_inodes_count = cpu_to_le32(~0U - 10); + KUNIT_EXPECT_EQ(test, ext4_group_add(sb, &input), -EINVAL); + ctx->es->s_inodes_count = cpu_to_le32(2 * RESIZE_TEST_INODES_PER_GRP); + + /* 2. Add group 2 (no backup super, overhead = 0) */ + start = ext4_blocks_count(ctx->es); + memset(&input, 0, sizeof(input)); + input.group = 2; + input.blocks_count = RESIZE_TEST_BLOCKS_PER_GRP; + input.block_bitmap = start; + input.inode_bitmap = start + 1; + input.inode_table = start + 2; + + KUNIT_EXPECT_EQ(test, ext4_group_add(sb, &input), 0); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_groups_count, 3U); + + /* 3. Add group 3 (sparse backup super -> overhead = 3, reserves backup) */ + start = ext4_blocks_count(ctx->es); + memset(&input, 0, sizeof(input)); + input.group = 3; + input.blocks_count = RESIZE_TEST_BLOCKS_PER_GRP; + input.block_bitmap = start + 3; + input.inode_bitmap = start + 4; + input.inode_table = start + 5; + + /* Without resize_inode feature -> -EPERM */ + ext4_clear_feature_resize_inode(sb); + KUNIT_EXPECT_EQ(test, ext4_group_add(sb, &input), -EPERM); + ext4_set_feature_resize_inode(sb); + + rsv_iblocks_before = ctx->resize_inode->i_blocks; + KUNIT_EXPECT_EQ(test, ext4_group_add(sb, &input), 0); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_groups_count, 4U); + + /* + * reserve_backup_gdb() must append group 3's reserved GDT block + * (3 * 1024 + 3 = 3075) at index 1 (after group 1's backup) in + * primary reserved GDT block 3 and increment resize_inode->i_blocks. + */ + pri_bh = resize_lookup_bh(ctx, 3); + KUNIT_ASSERT_NOT_NULL(test, pri_bh); + pri_data = (__le32 *)pri_bh->b_data; + KUNIT_EXPECT_EQ(test, le32_to_cpu(pri_data[1]), 3U * 1024U + 3U); + KUNIT_EXPECT_EQ(test, ctx->resize_inode->i_blocks, + rsv_iblocks_before + (RESIZE_TEST_BLK_SIZE >> 9)); +} + +/* + * Test 7: ext4_convert_meta_bg() sanity validation of resize_inode and + * conversion from resize_inode to meta_bg. + */ +static void test_convert_meta_bg_validation_and_conversion(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *rinode; + ext4_fsblk_t dind_blk = 42; + + resize_configure_fs(test, 16, 0, 0, RESIZE_TEST_BLOCKS_PER_GRP); + ext4_set_feature_resize_inode(sb); + + rinode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, rinode); + rinode->i_blkbits = RESIZE_TEST_BLK_BITS; + rinode->i_blocks = RESIZE_TEST_BLK_SIZE >> 9; + EXT4_I(rinode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(dind_blk); + + /* 1. Non-zero s_reserved_gdt_blocks -> -EPERM */ + ctx->es->s_reserved_gdt_blocks = cpu_to_le16(1); + KUNIT_EXPECT_EQ(test, ext4_convert_meta_bg_test(sb, rinode), -EPERM); + ctx->es->s_reserved_gdt_blocks = 0; + + /* 2. Wrong i_blocks on resize_inode -> -EINVAL */ + rinode->i_blocks = 8; + KUNIT_EXPECT_EQ(test, ext4_convert_meta_bg_test(sb, rinode), -EINVAL); + rinode->i_blocks = RESIZE_TEST_BLK_SIZE >> 9; + + /* 3. Unexpected direct block pointer or missing DIND -> -EINVAL */ + EXT4_I(rinode)->i_data[0] = cpu_to_le32(10); + KUNIT_EXPECT_EQ(test, ext4_convert_meta_bg_test(sb, rinode), -EINVAL); + EXT4_I(rinode)->i_data[0] = 0; + + EXT4_I(rinode)->i_data[EXT4_DIND_BLOCK] = 0; + KUNIT_EXPECT_EQ(test, ext4_convert_meta_bg_test(sb, rinode), -EINVAL); + EXT4_I(rinode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(dind_blk); + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + + /* 4. Valid conversion clears RESIZE_INODE, sets META_BG, frees DIND */ + KUNIT_EXPECT_EQ(test, ext4_convert_meta_bg_test(sb, rinode), 0); + KUNIT_EXPECT_FALSE(test, ext4_has_feature_resize_inode(sb)); + KUNIT_EXPECT_TRUE(test, ext4_has_feature_meta_bg(sb)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es->s_first_meta_bg), 1U); + KUNIT_EXPECT_EQ(test, ctx->last_freed_blk, dind_blk); + KUNIT_EXPECT_EQ(test, ctx->last_freed_count, 1UL); + KUNIT_EXPECT_EQ(test, rinode->i_blocks, 0ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(rinode)->i_data[EXT4_DIND_BLOCK]), + 0U); + + iput(rinode); +} + +/* + * Test 8: End-to-end ext4_resize_fs() across error guards, bigalloc cluster + * rounding, consuming reserved GDT blocks (16 -> 32 groups via add_new_gdb), + * converting resize_inode -> meta_bg, and growing into meta_bg (32 -> 34 + * groups via add_new_gdb_meta_bg). + */ +static void test_resize_fs_across_resize_inode_to_meta_bg(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + ext4_fsblk_t o_blks, target_blks, dind_blk; + + /* + * Start with 16 groups (1 full 64-byte GDT block), 1 reserved GDT + * block (allowing growth to 32 groups before meta_bg conversion), and + * flex_bg of 4 groups (log_flex = 2). + */ + resize_configure_fs(test, 16, 1, 2, RESIZE_TEST_BLOCKS_PER_GRP); + o_blks = ext4_blocks_count(ctx->es); + dind_blk = le32_to_cpu( + EXT4_I(ctx->resize_inode)->i_data[EXT4_DIND_BLOCK]); + + /* 1. Beyond device -> -ENOSPC; shrink -> -EINVAL; same size -> 0 */ + KUNIT_EXPECT_EQ(test, ext4_resize_fs(sb, ctx->device_blocks + 100), + -ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_resize_fs(sb, o_blks - 100), -EINVAL); + KUNIT_EXPECT_EQ(test, ext4_resize_fs(sb, o_blks), 0); + + /* 2. Simultaneous resize_inode + meta_bg -> -EINVAL */ + ext4_set_feature_meta_bg(sb); + KUNIT_EXPECT_EQ(test, ext4_resize_fs(sb, o_blks + 1024), -EINVAL); + ext4_clear_feature_meta_bg(sb); + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + + /* 3. Grow from 16 groups to 34 groups across GDT & meta_bg boundary */ + target_blks = RESIZE_TEST_FIRST_DATA_BLK + + 34ULL * RESIZE_TEST_BLOCKS_PER_GRP; + KUNIT_EXPECT_EQ(test, ext4_resize_fs(sb, target_blks), 0); + + KUNIT_EXPECT_EQ(test, ctx->sbi.s_groups_count, 34U); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_gdb_count, 3UL); + KUNIT_EXPECT_EQ(test, ext4_blocks_count(ctx->es), target_blks); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ctx->es->s_reserved_gdt_blocks), 0U); + KUNIT_EXPECT_FALSE(test, ext4_has_feature_resize_inode(sb)); + KUNIT_EXPECT_TRUE(test, ext4_has_feature_meta_bg(sb)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es->s_first_meta_bg), 2U); + KUNIT_EXPECT_EQ(test, ctx->last_freed_blk, dind_blk); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es->s_inodes_count), + 34U * RESIZE_TEST_INODES_PER_GRP); +} + +static struct kunit_case ext4_resize_test_cases[] = { + KUNIT_CASE(test_resize_begin_and_end_guards), + KUNIT_CASE(test_list_backups_and_verify_reserved_gdb), + KUNIT_CASE(test_verify_group_input_rejections_and_acceptance), + KUNIT_CASE(test_alloc_setup_flex_gd_and_group_tables), + KUNIT_CASE(test_group_extend_partial_last_group), + KUNIT_CASE(test_group_add_with_resize_inode_and_backup_gdb), + KUNIT_CASE(test_convert_meta_bg_validation_and_conversion), + KUNIT_CASE(test_resize_fs_across_resize_inode_to_meta_bg), + {} +}; + +static struct kunit_suite ext4_resize_test_suite = { + .name = "ext4_resize_test", + .init = resize_test_init, + .test_cases = ext4_resize_test_cases, +}; + +kunit_test_suites(&ext4_resize_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 online filesystem resizing"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/resize.c b/fs/ext4/resize.c index 8e61f1e22c51c3..8bc79819ef1607 100644 --- a/fs/ext4/resize.c +++ b/fs/ext4/resize.c @@ -13,6 +13,7 @@ #include #include #include +#include #include "ext4_jbd2.h" @@ -42,6 +43,16 @@ void ext4_kvfree_array_rcu(void *to_free) synchronize_rcu(); kvfree(to_free); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_kvfree_array_rcu); + +int ext4_resize_issue_zeroout(struct super_block *sb, sector_t blk, + sector_t nr_blks, gfp_t gfp_mask) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_resize_issue_zeroout, sb, blk, + nr_blks, gfp_mask); + return sb_issue_zeroout(sb, blk, nr_blks, gfp_mask); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_resize_issue_zeroout); int ext4_resize_begin(struct super_block *sb) { @@ -94,6 +105,7 @@ int ext4_resize_begin(struct super_block *sb) return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_resize_begin); int ext4_resize_end(struct super_block *sb, bool update_backups) { @@ -103,6 +115,7 @@ int ext4_resize_end(struct super_block *sb, bool update_backups) return ext4_update_overhead(sb, true); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_resize_end); static ext4_grpblk_t ext4_group_overhead_blocks(struct super_block *sb, ext4_group_t group) { @@ -209,21 +222,6 @@ static int verify_group_input(struct super_block *sb, return err; } -/* - * ext4_new_flex_group_data is used by 64bit-resize interface to add a flex - * group each time. - */ -struct ext4_new_flex_group_data { - struct ext4_new_group_data *groups; /* new_group_data for groups - in the flex group */ - __u16 *bg_flags; /* block group flags of groups - in @groups */ - ext4_group_t resize_bg; /* number of allocated - new_group_data */ - ext4_group_t count; /* number of groups in @groups - */ -}; - /* * Avoiding memory allocation failures due to too many groups added each time. */ @@ -424,7 +422,7 @@ static struct buffer_head *bclean(handle_t *handle, struct super_block *sb, struct buffer_head *bh; int err; - bh = sb_getblk(sb, blk); + bh = ext4_sb_getblk(sb, blk); if (unlikely(!bh)) return ERR_PTR(-ENOMEM); BUFFER_TRACE(bh, "get_write_access"); @@ -488,7 +486,7 @@ static int set_flexbg_block_bitmap(struct super_block *sb, handle_t *handle, if (err < 0) return err; - bh = sb_getblk(sb, flex_gd->groups[group].block_bitmap); + bh = ext4_sb_getblk(sb, flex_gd->groups[group].block_bitmap); if (unlikely(!bh)) return -ENOMEM; @@ -577,7 +575,7 @@ static int setup_new_flex_group_blocks(struct super_block *sb, if (err < 0) goto out; - gdb = sb_getblk(sb, block); + gdb = ext4_sb_getblk(sb, block); if (unlikely(!gdb)) { err = -ENOMEM; goto out; @@ -606,8 +604,8 @@ static int setup_new_flex_group_blocks(struct super_block *sb, * table blocks */ if (ext4_bg_has_super(sb, group)) { - err = sb_issue_zeroout(sb, gdblocks + start + 1, - reserved_gdb, GFP_NOFS); + err = ext4_resize_issue_zeroout(sb, gdblocks + start + 1, + reserved_gdb, GFP_NOFS); if (err) goto out; } @@ -621,8 +619,8 @@ static int setup_new_flex_group_blocks(struct super_block *sb, block = group_data[i].inode_table; ext4_debug("clear inode table blocks %#04llx -> %#04lx\n", block, sbi->s_itb_per_group); - err = sb_issue_zeroout(sb, block, sbi->s_itb_per_group, - GFP_NOFS); + err = ext4_resize_issue_zeroout(sb, block, sbi->s_itb_per_group, + GFP_NOFS); if (err) goto out; @@ -766,6 +764,7 @@ unsigned int ext4_list_backups(struct super_block *sb, unsigned int *three, return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_list_backups); /* * Check that all of the backup GDT blocks are held in the primary GDT block. @@ -1181,7 +1180,7 @@ static void update_backups(struct super_block *sb, sector_t blk_off, char *data, else backup_block = first_block + has_super; - bh = sb_getblk(sb, backup_block); + bh = ext4_sb_getblk(sb, backup_block); if (unlikely(!bh)) { err = -ENOMEM; break; @@ -1294,7 +1293,7 @@ static int ext4_add_new_descs(handle_t *handle, struct super_block *sb, static struct buffer_head *ext4_get_bitmap(struct super_block *sb, __u64 block) { - struct buffer_head *bh = sb_getblk(sb, block); + struct buffer_head *bh = ext4_sb_getblk(sb, block); if (unlikely(!bh)) return NULL; if (!bh_uptodate_or_lock(bh)) { @@ -1765,6 +1764,7 @@ int ext4_group_add(struct super_block *sb, struct ext4_new_group_data *input) iput(inode); return err; } /* ext4_group_add */ +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_group_add); /* * extend a group without checking assuming that checking has been done. @@ -1896,6 +1896,7 @@ int ext4_group_extend(struct super_block *sb, struct ext4_super_block *es, return ext4_group_extend_no_check(sb, o_blocks_count, add); } /* ext4_group_extend */ +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_group_extend); static int num_desc_blocks(struct super_block *sb, ext4_group_t groups) @@ -2192,3 +2193,56 @@ int ext4_resize_fs(struct super_block *sb, ext4_fsblk_t n_blocks_count) ext4_blocks_count(es)); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_resize_fs); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_verify_group_input_test(struct super_block *sb, + struct ext4_new_group_data *input) +{ + return verify_group_input(sb, input); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_verify_group_input_test); + +struct ext4_new_flex_group_data * +ext4_alloc_flex_gd_test(unsigned int flexbg_size, ext4_group_t o_group, + ext4_group_t n_group) +{ + return alloc_flex_gd(flexbg_size, o_group, n_group); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_alloc_flex_gd_test); + +void ext4_free_flex_gd_test(struct ext4_new_flex_group_data *flex_gd) +{ + free_flex_gd(flex_gd); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_flex_gd_test); + +int ext4_alloc_group_tables_test(struct super_block *sb, + struct ext4_new_flex_group_data *flex_gd, + unsigned int flexbg_size) +{ + return ext4_alloc_group_tables(sb, flex_gd, flexbg_size); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_alloc_group_tables_test); + +int ext4_verify_reserved_gdb_test(struct super_block *sb, ext4_group_t end, + struct buffer_head *primary) +{ + return verify_reserved_gdb(sb, end, primary); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_verify_reserved_gdb_test); + +int ext4_setup_next_flex_gd_test(struct super_block *sb, + struct ext4_new_flex_group_data *flex_gd, + ext4_fsblk_t n_blocks_count) +{ + return ext4_setup_next_flex_gd(sb, flex_gd, n_blocks_count); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_setup_next_flex_gd_test); + +int ext4_convert_meta_bg_test(struct super_block *sb, struct inode *inode) +{ + return ext4_convert_meta_bg(sb, inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_convert_meta_bg_test); +#endif From 00ab256f98e3a6f313b9ecc6da510f90604fd9e1 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:24:16 +0000 Subject: [PATCH 1571/2102] ext4: add KUnit tests for fs/ext4/migrate.c Add the ext4_migrate_test KUnit suite in fs/ext4/migrate-test.c to test online inode format migration between indirect block maps and extent trees in fs/ext4/migrate.c: - ext4_ext_migrate() precondition guards, fast symlink no-op handling, and temporary inode allocation error propagation - direct and single-indirect physically contiguous block coalescing, sparse logical hole preservation, and indirect metadata freeing - double-indirect and triple-indirect tree traversal and multi-level extent tree construction with proper i_csum_seed propagation - error rollback freeing allocated temporary extent tree blocks while preserving the original indirect inode layout - ext4_ext_swap_inode_data() concurrent block allocation detection via EXT4_STATE_EXT_MIGRATE (-EAGAIN) - ext4_ind_migrate() conversion of empty and single-extent inodes back to direct block maps and rejection of unsupported layouts Export ext4_ext_migrate(), ext4_ind_migrate(), and a KUnit wrapper for ext4_ext_swap_inode_data() via EXPORT_SYMBOL_FOR_EXT4_TEST. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 8 +- fs/ext4/migrate-test.c | 1061 ++++++++++++++++++++++++++++++++++++++++ fs/ext4/migrate.c | 11 + 4 files changed, 1079 insertions(+), 3 deletions(-) create mode 100644 fs/ext4/migrate-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 6163d47f3627aa..fafd9600cacb0b 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -22,7 +22,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ balloc-test.o orphan-test.o \ block_validity-test.o super-test.o \ sysfs-test.o ioctl-test.o \ - resize-test.o + resize-test.o migrate-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index 1f9c044f7e2483..b648df826a5d4c 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -3418,6 +3418,10 @@ bool ext4_dax_compatible_test(struct inode *inode, unsigned int oldflags, /* migrate.c */ extern int ext4_ext_migrate(struct inode *); extern int ext4_ind_migrate(struct inode *inode); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_ext_swap_inode_data_test(handle_t *handle, struct inode *inode, + struct inode *tmp_inode); +#endif /* namei.c */ extern int ext4_init_new_dir(handle_t *handle, struct inode *dir, @@ -3734,8 +3738,8 @@ static inline ext4_fsblk_t ext4_free_blocks_count(struct ext4_super_block *es) static inline void ext4_blocks_count_set(struct ext4_super_block *es, ext4_fsblk_t blk) { - es->s_blocks_count_lo = cpu_to_le32((u32)blk); - es->s_blocks_count_hi = cpu_to_le32(blk >> 32); + es->s_blocks_count_lo = cpu_to_le32(lower_32_bits(blk)); + es->s_blocks_count_hi = cpu_to_le32(upper_32_bits(blk)); } static inline void ext4_free_blocks_count_set(struct ext4_super_block *es, diff --git a/fs/ext4/migrate-test.c b/fs/ext4/migrate-test.c new file mode 100644 index 00000000000000..a17830489e3636 --- /dev/null +++ b/fs/ext4/migrate-test.c @@ -0,0 +1,1061 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/migrate.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_extents.h" +#include "ext4_jbd2.h" + +#define MIGRATE_TEST_BLK_SIZE 1024U +#define MIGRATE_TEST_BLK_BITS 10U +#define MIGRATE_TEST_BLOCKS_PER_GRP 1024U +#define MIGRATE_TEST_NGROUPS 8U +#define MIGRATE_TEST_FIRST_DATA_BLK 1U +#define MIGRATE_TEST_TOTAL_BLKS (MIGRATE_TEST_FIRST_DATA_BLK + \ + MIGRATE_TEST_NGROUPS * \ + MIGRATE_TEST_BLOCKS_PER_GRP) +#define MIGRATE_TEST_INODE_SIZE 256U +#define MIGRATE_TEST_EXTRA_ISIZE 32U +#define MIGRATE_TEST_INODES_PER_GRP 32U +#define MIGRATE_MAX_FREED_REC 32U + +struct migrate_mock_blk { + struct list_head node; + ext4_fsblk_t blocknr; + struct buffer_head bh; + u8 *data; +}; + +struct migrate_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct folio *bh_folio; + struct list_head blks; + ext4_fsblk_t device_blocks; + ext4_fsblk_t next_alloc_pblk; + int new_inode_err; + ext4_fsblk_t freed_blks[MIGRATE_MAX_FREED_REC]; + unsigned int freed_cnt; + bool rwsem_inited; + bool es_shrinker_inited; +}; + +static struct kunit *active_migrate_test; + +static struct inode *migrate_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = MIGRATE_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void migrate_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void migrate_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **migrate_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations migrate_test_sops = { + .alloc_inode = migrate_test_alloc_inode, + .free_inode = migrate_test_free_inode, + .evict_inode = migrate_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = migrate_test_get_dquots, +#endif +}; + +static int migrate_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static void migrate_test_sb_upd_work(struct work_struct *work) +{ +} + +static void migrate_test_err_timer(struct timer_list *t) +{ +} + +static struct file_system_type migrate_test_fs_type = { + .name = "ext4_migrate_kunit", + .init_fs_context = migrate_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void migrate_init_mock_bh(struct buffer_head *bh, struct folio *folio, + u8 *data, size_t size, sector_t blocknr) +{ + memset(bh, 0, sizeof(*bh)); + bh->b_folio = folio; + bh->b_data = (char *)data; + bh->b_size = size; + bh->b_blocknr = blocknr; + atomic_set(&bh->b_count, 2); + set_buffer_uptodate(bh); + set_buffer_mapped(bh); +} + +static struct buffer_head *migrate_lookup_bh(struct migrate_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct migrate_mock_blk *blk; + + list_for_each_entry(blk, &ctx->blks, node) { + if (blk->blocknr == blocknr) + return &blk->bh; + } + return NULL; +} + +static struct buffer_head *migrate_get_or_create_bh(struct migrate_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct buffer_head *bh; + struct migrate_mock_blk *blk; + + bh = migrate_lookup_bh(ctx, blocknr); + if (bh) { + get_bh(bh); + return bh; + } + + blk = kzalloc_obj(*blk); + if (!blk) + return NULL; + blk->data = kzalloc(MIGRATE_TEST_BLK_SIZE, GFP_KERNEL); + if (!blk->data) { + kfree(blk); + return NULL; + } + blk->blocknr = blocknr; + migrate_init_mock_bh(&blk->bh, ctx->bh_folio, blk->data, + MIGRATE_TEST_BLK_SIZE, blocknr); + list_add_tail(&blk->node, &ctx->blks); + get_bh(&blk->bh); + return &blk->bh; +} + +static struct buffer_head *migrate_sb_bread_stub(struct super_block *sb, + sector_t block, + blk_opf_t op_flags) +{ + struct kunit *test = active_migrate_test; + struct migrate_test_ctx *ctx; + struct buffer_head *bh; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return ERR_PTR(-EIO); + if ((ext4_fsblk_t)block >= ctx->device_blocks) + return ERR_PTR(-EIO); + + bh = migrate_get_or_create_bh(ctx, block); + if (!bh) + return ERR_PTR(-ENOMEM); + return bh; +} + +static struct buffer_head *migrate_ext_getblk_stub(struct inode *inode, + ext4_fsblk_t pblk, + gfp_t gfp_flags) +{ + struct kunit *test = active_migrate_test; + struct migrate_test_ctx *ctx; + + if (!test) + return NULL; + ctx = test->priv; + if (!ctx) + return NULL; + + return migrate_get_or_create_bh(ctx, pblk); +} + +static int migrate_ext_dirty_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct ext4_ext_path *path) +{ + if (path && path->p_bh) { + ext4_extent_block_csum_set_test(inode, + ext_block_hdr(path->p_bh)); + set_buffer_verified(path->p_bh); + } + return 0; +} + +static int migrate_handle_dirty_metadata_stub(const char *where, + unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + if (bh) + set_buffer_uptodate(bh); + return 0; +} + +static int migrate_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + return 0; +} + +static struct inode *migrate_new_inode_stub(const struct mnt_idmap *idmap, + handle_t *handle, + struct inode *dir, umode_t mode, + const struct qstr *qstr, + __u32 goal, uid_t *owner, + __u32 i_flags, int handle_type, + unsigned int line_no, int nblocks) +{ + struct kunit *test = active_migrate_test; + struct migrate_test_ctx *ctx; + struct inode *inode; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx) + return ERR_PTR(-EIO); + if (ctx->new_inode_err) + return ERR_PTR(ctx->new_inode_err); + + inode = new_inode(dir->i_sb); + if (!inode) + return ERR_PTR(-ENOMEM); + + inode->i_ino = 99; + inode->i_mode = mode; + inode->i_blkbits = dir->i_sb->s_blocksize_bits; + inode->i_flags |= S_NOQUOTA; + EXT4_I(inode)->i_flags = i_flags; + EXT4_I(inode)->i_csum_seed = 0xabcdef01U; + if (owner) { + i_uid_write(inode, owner[0]); + i_gid_write(inode, owner[1]); + } + inode_state_set_raw(inode, I_NEW); + return inode; +} + +static ext4_fsblk_t migrate_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, + int *errp) +{ + struct kunit *test = active_migrate_test; + struct migrate_test_ctx *ctx; + ext4_fsblk_t pblk; + + if (!test) { + *errp = -EIO; + return 0; + } + ctx = test->priv; + pblk = ctx->next_alloc_pblk; + ctx->next_alloc_pblk += ar->len; + ar->inode->i_blocks += (blkcnt_t)ar->len << + (ar->inode->i_blkbits - 9); + *errp = 0; + return pblk; +} + +static void migrate_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = active_migrate_test; + struct migrate_test_ctx *ctx; + blkcnt_t sectors; + unsigned long i; + + if (!test) + return; + ctx = test->priv; + for (i = 0; i < count && ctx->freed_cnt < MIGRATE_MAX_FREED_REC; i++) + ctx->freed_blks[ctx->freed_cnt++] = block + i; + + sectors = (blkcnt_t)count << (inode->i_blkbits - 9); + if (inode->i_blocks >= sectors) + inode->i_blocks -= sectors; + if (bh) + brelse(bh); +} + +static bool migrate_was_freed(struct migrate_test_ctx *ctx, ext4_fsblk_t blk) +{ + unsigned int i; + + for (i = 0; i < ctx->freed_cnt; i++) { + if (ctx->freed_blks[i] == blk) + return true; + } + return false; +} + +KUNIT_DEFINE_ACTION_WRAPPER(migrate_iput_action, iput, struct inode *); + +static struct inode *migrate_make_test_inode(struct kunit *test, unsigned long ino, + umode_t mode) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + int ret; + + inode = new_inode(ctx->sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = MIGRATE_TEST_BLK_BITS; + inode->i_flags |= S_NOQUOTA; + EXT4_I(inode)->i_csum_seed = 0x55aa55aaU; + ret = kunit_add_action_or_reset(test, migrate_iput_action, inode); + KUNIT_ASSERT_EQ(test, ret, 0); + return inode; +} + +static void migrate_test_cleanup(struct migrate_test_ctx *ctx) +{ + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct migrate_mock_blk *blk, *tmp; + + active_migrate_test = NULL; + + cancel_work_sync(&sbi->s_sb_upd_work); + timer_delete_sync(&sbi->s_err_report); + + if (sb) { + deactivate_super(sb); + ctx->sb = NULL; + } + rcu_barrier(); + + if (ctx->es_shrinker_inited) { + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + ctx->es_shrinker_inited = false; + } + + percpu_counter_destroy(&sbi->s_freeclusters_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeinodes_counter); + + if (ctx->rwsem_inited) { + percpu_free_rwsem(&sbi->s_writepages_rwsem); + ctx->rwsem_inited = false; + } + + list_for_each_entry_safe(blk, tmp, &ctx->blks, node) { + list_del(&blk->node); + kfree(blk->data); + kfree(blk); + } + + if (ctx->bh_folio) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + } + + if (ctx->bdev.bd_stats) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + } +} + +KUNIT_DEFINE_ACTION_WRAPPER(migrate_test_cleanup_action, migrate_test_cleanup, + struct migrate_test_ctx *); + +static int migrate_test_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static int migrate_test_init(struct kunit *test) +{ + struct migrate_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct buffer_head *sbh; + struct inode *root_inode; + int ret; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + INIT_LIST_HEAD(&ctx->blks); + ctx->device_blocks = MIGRATE_TEST_TOTAL_BLKS; + ctx->next_alloc_pblk = 900; + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->bdev.bd_stats != NULL); + + ctx->bh_folio = folio_alloc(GFP_KERNEL, 0); + if (!ctx->bh_folio) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "folio_alloc failed"); + } + + fc = fs_context_for_mount(&migrate_test_fs_type, 0); + if (IS_ERR(fc)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "fs_context_for_mount failed: %ld", + PTR_ERR(fc)); + } + sb = sget_fc(fc, NULL, migrate_test_set_super); + put_fs_context(fc); + if (IS_ERR(sb)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "sget_fc failed: %ld", PTR_ERR(sb)); + } + ctx->sb = sb; + sbi = &ctx->sbi; + INIT_WORK(&sbi->s_sb_upd_work, migrate_test_sb_upd_work); + timer_setup(&sbi->s_err_report, migrate_test_err_timer, 0); + up_write(&sb->s_umount); + + ret = kunit_add_action_or_reset(test, migrate_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, ret, 0); + + sb->s_fs_info = sbi; + sb->s_op = &migrate_test_sops; + sb->s_blocksize = MIGRATE_TEST_BLK_SIZE; + sb->s_blocksize_bits = MIGRATE_TEST_BLK_BITS; + sb->s_magic = EXT4_SUPER_MAGIC; + sb->s_maxbytes = MAX_LFS_FILESIZE; + INIT_LIST_HEAD(&sb->s_inodes); +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + + strscpy(sb->s_id, "ext4_migrate_kunit", sizeof(sb->s_id)); + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = MIGRATE_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + sbi->s_sb = sb; + sbi->s_blockgroup_lock = &ctx->bgl; + bgl_lock_init(&ctx->bgl); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_es_lock); + INIT_LIST_HEAD(&sbi->s_es_list); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10); + + ret = percpu_init_rwsem(&sbi->s_writepages_rwsem); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->rwsem_inited = true; + + ret = percpu_counter_init(&sbi->s_freeclusters_counter, 4096, + GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_freeinodes_counter, 200, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + + ret = ext4_es_register_shrinker(sbi); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->es_shrinker_inited = true; + + sbi->s_blocks_per_group = MIGRATE_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = MIGRATE_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = MIGRATE_TEST_NGROUPS; + sbi->s_inodes_per_group = MIGRATE_TEST_INODES_PER_GRP; + sbi->s_inode_size = MIGRATE_TEST_INODE_SIZE; + sbi->s_inodes_per_block = MIGRATE_TEST_BLK_SIZE / + MIGRATE_TEST_INODE_SIZE; + sbi->s_first_ino = 11; + sbi->s_mount_state = EXT4_VALID_FS; + set_opt(sb, ERRORS_CONT); + + sbh = migrate_get_or_create_bh(ctx, MIGRATE_TEST_FIRST_DATA_BLK); + KUNIT_ASSERT_NOT_NULL(test, sbh); + brelse(sbh); + sbi->s_sbh = sbh; + ctx->es = (struct ext4_super_block *)sbh->b_data; + sbi->s_es = ctx->es; + + ctx->es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es->s_first_data_block = cpu_to_le32(MIGRATE_TEST_FIRST_DATA_BLK); + ctx->es->s_blocks_per_group = cpu_to_le32(MIGRATE_TEST_BLOCKS_PER_GRP); + ctx->es->s_clusters_per_group = + cpu_to_le32(MIGRATE_TEST_BLOCKS_PER_GRP); + ctx->es->s_inodes_per_group = cpu_to_le32(MIGRATE_TEST_INODES_PER_GRP); + ctx->es->s_inodes_count = cpu_to_le32(MIGRATE_TEST_NGROUPS * + MIGRATE_TEST_INODES_PER_GRP); + ctx->es->s_inode_size = cpu_to_le16(MIGRATE_TEST_INODE_SIZE); + ctx->es->s_checksum_type = EXT4_CRC32C_CHKSUM; + generate_random_uuid(ctx->es->s_uuid); + ext4_blocks_count_set(ctx->es, MIGRATE_TEST_TOTAL_BLKS); + ext4_set_feature_extents(sb); + ext4_set_feature_64bit(sb); + ext4_set_feature_metadata_csum(sb); + sbi->s_csum_seed = ext4_chksum(~0, ctx->es->s_uuid, + sizeof(ctx->es->s_uuid)); + ext4_superblock_csum_set(sb); + + root_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, root_inode); + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_blkbits = MIGRATE_TEST_BLK_BITS; + root_inode->i_flags |= S_NOQUOTA; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + KUNIT_ASSERT_NOT_NULL(test, sb->s_root); + sb->s_flags |= SB_ACTIVE; + + active_migrate_test = test; + kunit_activate_static_stub(test, ext4_sb_bread, migrate_sb_bread_stub); + kunit_activate_static_stub(test, ext4_ext_getblk, + migrate_ext_getblk_stub); + kunit_activate_static_stub(test, __ext4_ext_dirty, + migrate_ext_dirty_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + migrate_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + migrate_mark_inode_dirty_stub); + kunit_activate_static_stub(test, __ext4_new_inode, + migrate_new_inode_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + migrate_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + migrate_free_blocks_stub); + + return 0; +} + +/* + * Test 1: ext4_ext_migrate() precondition guards, fast symlink no-op, and + * temporary inode allocation failure handling. + */ +static void test_ext_migrate_precondition_checks_and_fast_symlink(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode, *symlink; + + inode = migrate_make_test_inode(test, 12, S_IFREG | 0644); + + /* 1. Filesystem lacks extents feature -> -EINVAL */ + ext4_clear_feature_extents(sb); + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EINVAL); + ext4_set_feature_extents(sb); + + /* 2. Inode already uses extents -> -EINVAL */ + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EINVAL); + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + + /* 3. Inline-data inode -> -EINVAL */ + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + EXT4_I(inode)->i_inline_off = 164; + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EINVAL); + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + EXT4_I(inode)->i_inline_off = 0; + + /* 4. Fast symlink (S_IFLNK && i_blocks == 0) is a clean no-op */ + symlink = migrate_make_test_inode(test, 13, S_IFLNK | 0777); + symlink->i_blocks = 0; + memcpy(EXT4_I(symlink)->i_data, "target/path", 11); + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(symlink), 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(symlink, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_MEMEQ(test, EXT4_I(symlink)->i_data, "target/path", 11); + + /* 5. Temporary inode allocation failure (-ENOSPC) propagates */ + ctx->new_inode_err = -ENOSPC; + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -ENOSPC); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + ctx->new_inode_err = 0; +} + +/* + * Test 2: ext4_ext_migrate() coalesces contiguous direct + single-indirect + * runs across the EXT4_NDIR_BLOCKS boundary, preserves sparse holes, and + * frees the indirect metadata block. + */ +static void test_ext_migrate_direct_and_ind_coalescing_and_holes(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + struct buffer_head *ind_bh; + __le32 *ind_data; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + + inode = migrate_make_test_inode(test, 14, S_IFREG | 0644); + i_size_write(inode, 25 * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 8 * (MIGRATE_TEST_BLK_SIZE >> 9); + + /* Direct [0..2] -> 100..102; hole [3..10]; Direct [11] -> 200 */ + EXT4_I(inode)->i_data[0] = cpu_to_le32(100); + EXT4_I(inode)->i_data[1] = cpu_to_le32(101); + EXT4_I(inode)->i_data[2] = cpu_to_le32(102); + EXT4_I(inode)->i_data[11] = cpu_to_le32(200); + + /* IND block 500: [0..1] (lblks 12..13) -> 201..202; [10] (lblk 22) -> 350 */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(500); + ind_bh = migrate_get_or_create_bh(ctx, 500); + KUNIT_ASSERT_NOT_NULL(test, ind_bh); + ind_data = (__le32 *)ind_bh->b_data; + ind_data[0] = cpu_to_le32(201); + ind_data[1] = cpu_to_le32(202); + ind_data[10] = cpu_to_le32(350); + brelse(ind_bh); + + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + + eh = ext_inode_hdr(inode); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_magic), + le16_to_cpu(EXT4_EXT_MAGIC)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_depth), 0U); + KUNIT_ASSERT_EQ(test, le16_to_cpu(eh->eh_entries), 3U); + + ex = EXT_FIRST_EXTENT(eh); + /* Extent 0: lblk [0..2] -> pblk 100 */ + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 0U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ex[0].ee_len), 3U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[0]), 100ULL); + + /* Extent 1: lblk [11..13] coalesced across DIRECT/IND -> pblk 200 */ + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 11U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ex[1].ee_len), 3U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[1]), 200ULL); + + /* Extent 2: lblk [22..22] -> pblk 350 */ + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[2].ee_block), 22U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ex[2].ee_len), 1U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[2]), 350ULL); + + /* Indirect metadata block 500 was freed */ + KUNIT_EXPECT_TRUE(test, migrate_was_freed(ctx, 500)); +} + +/* + * Test 3: ext4_ext_migrate() across DIRECT, IND, DIND, and TIND sparse blocks + * (> 4 discontiguous extents, growing a depth-1 extent tree) and freeing all + * indirect metadata blocks at every level. + */ +static void test_ext_migrate_dind_tind_and_multilevel_tree(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + struct buffer_head *bh; + struct ext4_ext_path *path; + static const struct { + ext4_lblk_t lblk; + ext4_fsblk_t pblk; + } expected[] = { + { 0, 100 }, + { 5, 110 }, + { 15, 120 }, + { 780, 130 }, + { 131341, 140 }, + { 131345, 150 }, + }; + static const ext4_fsblk_t expected_freed_meta[] = { + 510, 520, 521, 530, 531, 532 + }; + unsigned int i; + + inode = migrate_make_test_inode(test, 15, S_IFREG | 0644); + i_size_write(inode, 140000ULL * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 12 * (MIGRATE_TEST_BLK_SIZE >> 9); + + /* Direct: lblk 0 -> 100, lblk 5 -> 110 */ + EXT4_I(inode)->i_data[0] = cpu_to_le32(100); + EXT4_I(inode)->i_data[5] = cpu_to_le32(110); + + /* IND (510): entry 3 (lblk 12 + 3 = 15) -> 120 */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(510); + bh = migrate_get_or_create_bh(ctx, 510); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[3] = cpu_to_le32(120); + brelse(bh); + + /* DIND (520) -> [2] = 521 -> [0] (lblk 12 + 256 + 512 = 780) -> 130 */ + EXT4_I(inode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(520); + bh = migrate_get_or_create_bh(ctx, 520); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[2] = cpu_to_le32(521); + brelse(bh); + + bh = migrate_get_or_create_bh(ctx, 521); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[0] = cpu_to_le32(130); + brelse(bh); + + /* + * TIND (530) -> [1] = 531 -> [0] = 532 -> [1] (lblk 12 + 256 + 65536 + + * 65536 + 1 = 131341 -> 140) and [5] (lblk 131345 -> 150). + */ + EXT4_I(inode)->i_data[EXT4_TIND_BLOCK] = cpu_to_le32(530); + bh = migrate_get_or_create_bh(ctx, 530); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[1] = cpu_to_le32(531); + brelse(bh); + + bh = migrate_get_or_create_bh(ctx, 531); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[0] = cpu_to_le32(532); + brelse(bh); + + bh = migrate_get_or_create_bh(ctx, 532); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[1] = cpu_to_le32(140); + ((__le32 *)bh->b_data)[5] = cpu_to_le32(150); + brelse(bh); + + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_depth), 1U); + + for (i = 0; i < ARRAY_SIZE(expected); i++) { + struct ext4_extent ex; + + path = ext4_find_extent(inode, expected[i].lblk, NULL, + EXT4_EX_FORCE_CACHE); + KUNIT_ASSERT_FALSE_MSG(test, IS_ERR(path), + "find_extent failed at idx %u", i); + if (!path[path->p_depth].p_ext) { + ext4_free_ext_path(path); + KUNIT_FAIL_AND_ABORT(test, + "missing extent at idx %u", i); + } + ex = *path[path->p_depth].p_ext; + ext4_free_ext_path(path); + KUNIT_EXPECT_EQ_MSG(test, le32_to_cpu(ex.ee_block), + expected[i].lblk, "lblk idx %u", i); + KUNIT_EXPECT_EQ_MSG(test, ext4_ext_pblock(&ex), + expected[i].pblk, "pblk idx %u", i); + } + + for (i = 0; i < ARRAY_SIZE(expected_freed_meta); i++) { + KUNIT_EXPECT_TRUE_MSG(test, + migrate_was_freed(ctx, + expected_freed_meta[i]), + "expected meta block %llu freed", + expected_freed_meta[i]); + } +} + +/* + * Test 4: When reading an indirect block fails midway after tmp_inode has + * already grown a depth-1 extent tree, free_ext_block() / free_ext_idx() + * frees the allocated temporary extent metadata block and leaves the original + * inode untouched. + */ +static void test_ext_migrate_error_rollback_frees_tmp_extent_blocks(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + ext4_fsblk_t expected_leaf_blk = ctx->next_alloc_pblk; + + inode = migrate_make_test_inode(test, 16, S_IFREG | 0644); + inode->i_blocks = 12; + + /* + * 6 discontiguous direct blocks flush 5 extents into tmp_inode + * (the 6th stays buffered in lb), growing tmp_inode past eh_max=4 + * to a depth-1 extent leaf block before EXT4_IND_BLOCK is read. + */ + EXT4_I(inode)->i_data[0] = cpu_to_le32(100); + EXT4_I(inode)->i_data[2] = cpu_to_le32(110); + EXT4_I(inode)->i_data[4] = cpu_to_le32(120); + EXT4_I(inode)->i_data[6] = cpu_to_le32(130); + EXT4_I(inode)->i_data[8] = cpu_to_le32(140); + EXT4_I(inode)->i_data[10] = cpu_to_le32(150); + /* Unreadable IND block beyond device_blocks triggers -EIO rollback */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = + cpu_to_le32(MIGRATE_TEST_TOTAL_BLKS + 50); + + (void)ext4_ext_migrate(inode); + + /* Temporary extent leaf block allocated during build must be freed */ + KUNIT_EXPECT_TRUE(test, migrate_was_freed(ctx, expected_leaf_blk)); + /* Original inode remains indirect with intact direct pointers */ + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[0]), 100U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[8]), 140U); +} + +/* + * Test 5: ext4_ext_swap_inode_data() returns -EAGAIN without modifying the + * target inode or freeing its indirect blocks if EXT4_STATE_EXT_MIGRATE was + * cleared by a concurrent allocation. + */ +static void test_ext_swap_inode_data_detects_concurrent_allocation(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode, *tmp_inode; + handle_t *handle; + int ret; + + inode = migrate_make_test_inode(test, 17, S_IFREG | 0644); + EXT4_I(inode)->i_data[0] = cpu_to_le32(210); + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(550); + + tmp_inode = migrate_make_test_inode(test, 18, S_IFREG | 0644); + handle = ext4_journal_start(inode, EXT4_HT_MIGRATE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ext4_ext_tree_init(handle, tmp_inode); + + /* EXT4_STATE_EXT_MIGRATE intentionally NOT set on inode */ + ret = ext4_ext_swap_inode_data_test(handle, inode, tmp_inode); + ext4_journal_stop(handle); + + KUNIT_EXPECT_EQ(test, ret, -EAGAIN); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[0]), 210U); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_IND_BLOCK]), + 550U); + KUNIT_EXPECT_FALSE(test, migrate_was_freed(ctx, 550)); +} + +/* + * Test 6: ext4_ind_migrate() converts an empty 0-extent file and a 1-extent + * file with a leading sparse hole ([3..7] -> 200..204) to direct block mapping. + */ +static void test_ind_migrate_empty_and_single_direct_extent(struct kunit *test) +{ + struct inode *inode; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + handle_t *handle; + unsigned int i; + + /* 1. Empty 0-extent file */ + inode = migrate_make_test_inode(test, 19, S_IFREG | 0644); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + handle = ext4_journal_start(inode, EXT4_HT_MIGRATE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ext4_ext_tree_init(handle, inode); + ext4_journal_stop(handle); + + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + for (i = 0; i < EXT4_N_BLOCKS; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[i]), 0U); + + /* 2. Single extent covering logical blocks [3..7] -> physical 200..204 */ + inode = migrate_make_test_inode(test, 20, S_IFREG | 0644); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + handle = ext4_journal_start(inode, EXT4_HT_MIGRATE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ext4_ext_tree_init(handle, inode); + ext4_journal_stop(handle); + + eh = ext_inode_hdr(inode); + eh->eh_entries = cpu_to_le16(1); + ex = EXT_FIRST_EXTENT(eh); + ex->ee_block = cpu_to_le32(3); + ex->ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(ex, 200); + + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + for (i = 0; i < 3; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[i]), 0U); + for (i = 3; i <= 7; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[i]), + 200U + (i - 3)); + for (i = 8; i < EXT4_N_BLOCKS; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[i]), 0U); +} + +/* + * Test 7: ext4_ind_migrate() rejects non-extents, bigalloc, multi-extent, + * non-zero depth, >= EXT4_NDIR_BLOCKS logical range, and >32-bit filesystems. + */ +static void test_ind_migrate_rejections(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + handle_t *handle; + + inode = migrate_make_test_inode(test, 21, S_IFREG | 0644); + + /* 1. Inode without EXT4_INODE_EXTENTS -> -EINVAL */ + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EINVAL); + + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + handle = ext4_journal_start(inode, EXT4_HT_MIGRATE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ext4_ext_tree_init(handle, inode); + ext4_journal_stop(handle); + + /* 2. Filesystem without extents feature -> -EINVAL */ + ext4_clear_feature_extents(sb); + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EINVAL); + ext4_set_feature_extents(sb); + + /* 3. bigalloc enabled -> -EOPNOTSUPP */ + ext4_set_feature_bigalloc(sb); + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EOPNOTSUPP); + ext4_clear_feature_bigalloc(sb); + + /* 4. Extent reaching EXT4_NDIR_BLOCKS (end = 10 + 3 - 1 = 12) */ + eh = ext_inode_hdr(inode); + eh->eh_entries = cpu_to_le16(1); + ex = EXT_FIRST_EXTENT(eh); + ex[0].ee_block = cpu_to_le32(10); + ex[0].ee_len = cpu_to_le16(3); + ext4_ext_store_pblock(&ex[0], 200); + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EOPNOTSUPP); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + + /* 5. More than 1 extent (eh_entries == 2) -> -EOPNOTSUPP */ + ex[0].ee_block = cpu_to_le32(0); + ex[0].ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(&ex[0], 200); + ex[1].ee_block = cpu_to_le32(4); + ex[1].ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(&ex[1], 210); + eh->eh_entries = cpu_to_le16(2); + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EOPNOTSUPP); + + /* 6. Filesystem > EXT4_MAX_BLOCK_FILE_PHYS -> -EOPNOTSUPP */ + eh->eh_entries = cpu_to_le16(1); + ext4_blocks_count_set(ctx->es, (ext4_fsblk_t)EXT4_MAX_BLOCK_FILE_PHYS + + 100ULL); + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EOPNOTSUPP); + ext4_blocks_count_set(ctx->es, MIGRATE_TEST_TOTAL_BLKS); +} + +static struct kunit_case ext4_migrate_test_cases[] = { + KUNIT_CASE(test_ext_migrate_precondition_checks_and_fast_symlink), + KUNIT_CASE(test_ext_migrate_direct_and_ind_coalescing_and_holes), + KUNIT_CASE(test_ext_migrate_dind_tind_and_multilevel_tree), + KUNIT_CASE(test_ext_migrate_error_rollback_frees_tmp_extent_blocks), + KUNIT_CASE(test_ext_swap_inode_data_detects_concurrent_allocation), + KUNIT_CASE(test_ind_migrate_empty_and_single_direct_extent), + KUNIT_CASE(test_ind_migrate_rejections), + {} +}; + +static struct kunit_suite ext4_migrate_test_suite = { + .name = "ext4_migrate_test", + .init = migrate_test_init, + .test_cases = ext4_migrate_test_cases, +}; + +kunit_test_suites(&ext4_migrate_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 indirect/extent inode migration"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/migrate.c b/fs/ext4/migrate.c index cdef31eaa490ca..807bd30341e689 100644 --- a/fs/ext4/migrate.c +++ b/fs/ext4/migrate.c @@ -615,6 +615,7 @@ int ext4_ext_migrate(struct inode *inode) iput(tmp_inode); return retval; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_migrate); /* * Migrate a simple extent-based inode to use the i_blocks[] array @@ -703,3 +704,13 @@ int ext4_ind_migrate(struct inode *inode) ext4_writepages_up_write(inode->i_sb, alloc_ctx); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ind_migrate); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_ext_swap_inode_data_test(handle_t *handle, struct inode *inode, + struct inode *tmp_inode) +{ + return ext4_ext_swap_inode_data(handle, inode, tmp_inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_swap_inode_data_test); +#endif From 7ac9b4174f1ec6d0f675fac3244b09aedc0f45a0 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:24:29 +0000 Subject: [PATCH 1572/2102] ext4: add KUnit tests for fs/ext4/indirect.c Add the ext4_indirect_test KUnit suite in fs/ext4/indirect-test.c to test legacy direct, single-, double-, and triple-indirect block mapping, truncation, and hole punching in fs/ext4/indirect.c: - ext4_block_to_path() offset decomposition, boundary distance, and out-of-range block rejection, plus ext4_ind_trans_blocks() credits - ext4_ind_map_blocks() read-only lookup across contiguous runs, EXT4_MAP_BOUNDARY detection, and multi-level hole span calculation - ext4_ind_map_blocks() allocation and branch splicing across direct, IND, DIND, and TIND depths - error handling (out-of-range logical/physical blocks, bigalloc rejection, indirect read I/O failure, corrupt indirect blockref) and partial branch allocation unwind freeing intermediate metadata blocks - ext4_ind_truncate() partial shared-branch truncation, indirect root detachment, and full truncation to zero - ext4_ind_remove_space() hole punching within direct blocks, across mixed levels, and converging on shared IND and DIND blocks - corrupt block pointer rejection in ext4_clear_blocks() and ext4_free_branches() Route indirect block buffer lookups through ext4_sb_getblk(), add a KUnit static stub redirect to ext4_sb_bread_nofail(), and export the indirect mapping and truncation entry points for KUnit testing. Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 3 +- fs/ext4/ext4.h | 4 + fs/ext4/indirect-test.c | 1293 +++++++++++++++++++++++++++++++++++++++ fs/ext4/indirect.c | 18 +- fs/ext4/super.c | 7 +- 5 files changed, 1321 insertions(+), 4 deletions(-) create mode 100644 fs/ext4/indirect-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index fafd9600cacb0b..503acc94640970 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -22,7 +22,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ balloc-test.o orphan-test.o \ block_validity-test.o super-test.o \ sysfs-test.o ioctl-test.o \ - resize-test.o migrate-test.o + resize-test.o migrate-test.o \ + indirect-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index b648df826a5d4c..03689d55e7513e 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -3371,6 +3371,10 @@ extern int ext4_ind_trans_blocks(struct inode *inode, int nrblocks); extern void ext4_ind_truncate(handle_t *, struct inode *inode); extern int ext4_ind_remove_space(handle_t *handle, struct inode *inode, ext4_lblk_t start, ext4_lblk_t end); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_block_to_path_test(struct inode *inode, ext4_lblk_t i_block, + ext4_lblk_t offsets[4], int *boundary); +#endif /* ioctl.c */ extern long ext4_ioctl(struct file *, unsigned int, unsigned long); diff --git a/fs/ext4/indirect-test.c b/fs/ext4/indirect-test.c new file mode 100644 index 00000000000000..8d4a430ecb272c --- /dev/null +++ b/fs/ext4/indirect-test.c @@ -0,0 +1,1293 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/indirect.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" + +#define IND_TEST_BLK_SIZE 1024U +#define IND_TEST_BLK_BITS 10U +#define IND_TEST_PTRS_PER_BLK (IND_TEST_BLK_SIZE / sizeof(__le32)) +#define IND_TEST_BLOCKS_PER_GRP 1024U +#define IND_TEST_NGROUPS 8U +#define IND_TEST_FIRST_DATA_BLK 1U +#define IND_TEST_TOTAL_BLKS (IND_TEST_FIRST_DATA_BLK + \ + IND_TEST_NGROUPS * \ + IND_TEST_BLOCKS_PER_GRP) +#define IND_TEST_INODE_SIZE 256U +#define IND_TEST_EXTRA_ISIZE 32U +#define IND_TEST_INODES_PER_GRP 32U +#define IND_TEST_MAX_FREED_REC 128U + +#define IND_TEST_IND_BASE EXT4_NDIR_BLOCKS +#define IND_TEST_DIND_BASE (IND_TEST_IND_BASE + \ + IND_TEST_PTRS_PER_BLK) +#define IND_TEST_TIND_BASE (IND_TEST_DIND_BASE + \ + IND_TEST_PTRS_PER_BLK * \ + IND_TEST_PTRS_PER_BLK) +#define IND_TEST_MAX_LBLK (IND_TEST_TIND_BASE + \ + IND_TEST_PTRS_PER_BLK * \ + IND_TEST_PTRS_PER_BLK * \ + IND_TEST_PTRS_PER_BLK) + +struct ind_mock_blk { + struct list_head node; + ext4_fsblk_t blocknr; + struct buffer_head bh; + u8 *data; +}; + +struct ind_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct folio *bh_folio; + struct list_head blks; + ext4_fsblk_t device_blocks; + ext4_fsblk_t next_alloc_pblk; + unsigned int alloc_calls; + unsigned int fail_alloc_on_call; + int fail_alloc_err; + int read_bh_err; + ext4_fsblk_t freed_blks[IND_TEST_MAX_FREED_REC]; + unsigned int freed_cnt; + bool rwsem_inited; + bool es_shrinker_inited; +}; + +static struct kunit *active_ind_test; + +static struct inode *ind_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = IND_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void ind_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void ind_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **ind_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations ind_test_sops = { + .alloc_inode = ind_test_alloc_inode, + .free_inode = ind_test_free_inode, + .evict_inode = ind_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = ind_test_get_dquots, +#endif +}; + +static int ind_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static void ind_test_sb_upd_work(struct work_struct *work) +{ +} + +static void ind_test_err_timer(struct timer_list *t) +{ +} + +static struct file_system_type ind_test_fs_type = { + .name = "ext4_indirect_kunit", + .init_fs_context = ind_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void ind_init_mock_bh(struct buffer_head *bh, struct folio *folio, + u8 *data, size_t size, sector_t blocknr) +{ + memset(bh, 0, sizeof(*bh)); + bh->b_folio = folio; + bh->b_data = (char *)data; + bh->b_size = size; + bh->b_blocknr = blocknr; + atomic_set(&bh->b_count, 2); + set_buffer_uptodate(bh); + set_buffer_mapped(bh); +} + +static struct buffer_head *ind_lookup_bh(struct ind_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct ind_mock_blk *blk; + + list_for_each_entry(blk, &ctx->blks, node) { + if (blk->blocknr == blocknr) + return &blk->bh; + } + return NULL; +} + +static struct buffer_head *ind_get_or_create_bh(struct ind_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct buffer_head *bh; + struct ind_mock_blk *blk; + + bh = ind_lookup_bh(ctx, blocknr); + if (bh) { + get_bh(bh); + return bh; + } + + blk = kzalloc_obj(*blk); + if (!blk) + return NULL; + blk->data = kzalloc(IND_TEST_BLK_SIZE, GFP_KERNEL); + if (!blk->data) { + kfree(blk); + return NULL; + } + blk->blocknr = blocknr; + ind_init_mock_bh(&blk->bh, ctx->bh_folio, blk->data, + IND_TEST_BLK_SIZE, blocknr); + list_add_tail(&blk->node, &ctx->blks); + get_bh(&blk->bh); + return &blk->bh; +} + +static struct buffer_head *ind_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = active_ind_test; + struct ind_test_ctx *ctx; + + if (!test) + return NULL; + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return NULL; + + return ind_get_or_create_bh(ctx, block); +} + +static struct buffer_head *ind_sb_bread_nofail_stub(struct super_block *sb, + sector_t block) +{ + struct kunit *test = active_ind_test; + struct ind_test_ctx *ctx; + struct buffer_head *bh; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return ERR_PTR(-EIO); + if ((ext4_fsblk_t)block >= ctx->device_blocks) + return ERR_PTR(-EIO); + + bh = ind_get_or_create_bh(ctx, block); + if (!bh) + return ERR_PTR(-ENOMEM); + return bh; +} + +static int ind_read_bh_stub(struct buffer_head *bh, blk_opf_t op_flags, + bio_end_io_t end_io, bool simu_fail) +{ + struct kunit *test = active_ind_test; + struct ind_test_ctx *ctx; + + if (!test) { + unlock_buffer(bh); + return -EIO; + } + ctx = test->priv; + if (ctx->read_bh_err) { + unlock_buffer(bh); + return ctx->read_bh_err; + } + + set_buffer_uptodate(bh); + unlock_buffer(bh); + return 0; +} + +static int ind_handle_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + if (bh) + set_buffer_uptodate(bh); + return 0; +} + +static int ind_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + return 0; +} + +static ext4_fsblk_t ind_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, + int *errp) +{ + struct kunit *test = active_ind_test; + struct ind_test_ctx *ctx; + ext4_fsblk_t pblk; + + if (!test) { + *errp = -EIO; + return 0; + } + ctx = test->priv; + ctx->alloc_calls++; + if (ctx->fail_alloc_on_call && + ctx->alloc_calls == ctx->fail_alloc_on_call) { + *errp = ctx->fail_alloc_err; + return 0; + } + + pblk = ctx->next_alloc_pblk; + ctx->next_alloc_pblk += ar->len; + ar->inode->i_blocks += (blkcnt_t)ar->len << + (ar->inode->i_blkbits - 9); + *errp = 0; + return pblk; +} + +static void ind_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = active_ind_test; + struct ind_test_ctx *ctx; + ext4_fsblk_t start_blk = block; + blkcnt_t sectors; + unsigned long i; + + if (!test) + return; + ctx = test->priv; + if (!start_blk && bh) + start_blk = bh->b_blocknr; + + for (i = 0; i < count && ctx->freed_cnt < IND_TEST_MAX_FREED_REC; i++) + ctx->freed_blks[ctx->freed_cnt++] = start_blk + i; + + sectors = (blkcnt_t)count << (inode->i_blkbits - 9); + if (inode->i_blocks >= sectors) + inode->i_blocks -= sectors; + if (bh) + brelse(bh); +} + +static bool ind_was_freed(struct ind_test_ctx *ctx, ext4_fsblk_t blk) +{ + unsigned int i; + + for (i = 0; i < ctx->freed_cnt; i++) { + if (ctx->freed_blks[i] == blk) + return true; + } + return false; +} + +static __le32 *ind_blk_ptrs(struct kunit *test, ext4_fsblk_t blk) +{ + struct ind_test_ctx *ctx = test->priv; + struct buffer_head *bh; + + bh = ind_get_or_create_bh(ctx, blk); + KUNIT_ASSERT_NOT_NULL(test, bh); + brelse(bh); + return (__le32 *)bh->b_data; +} + +static struct inode *ind_make_test_inode(struct kunit *test, unsigned long ino) +{ + struct ind_test_ctx *ctx = test->priv; + struct inode *inode; + + inode = new_inode(ctx->sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + inode->i_ino = ino; + inode->i_mode = S_IFREG | 0644; + inode->i_blkbits = IND_TEST_BLK_BITS; + inode->i_flags |= S_NOQUOTA; + EXT4_I(inode)->i_block_group = 0; + return inode; +} + +static void ind_test_cleanup(struct ind_test_ctx *ctx) +{ + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ind_mock_blk *blk, *tmp; + + active_ind_test = NULL; + + cancel_work_sync(&sbi->s_sb_upd_work); + timer_delete_sync(&sbi->s_err_report); + + if (sb) { + deactivate_super(sb); + ctx->sb = NULL; + } + rcu_barrier(); + + if (ctx->es_shrinker_inited) { + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + ctx->es_shrinker_inited = false; + } + + percpu_counter_destroy(&sbi->s_freeclusters_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeinodes_counter); + + if (ctx->rwsem_inited) { + percpu_free_rwsem(&sbi->s_writepages_rwsem); + ctx->rwsem_inited = false; + } + + list_for_each_entry_safe(blk, tmp, &ctx->blks, node) { + list_del(&blk->node); + kfree(blk->data); + kfree(blk); + } + + if (ctx->bh_folio) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + } + + if (ctx->bdev.bd_stats) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + } +} + +KUNIT_DEFINE_ACTION_WRAPPER(ind_test_cleanup_action, ind_test_cleanup, + struct ind_test_ctx *); + +static int ind_test_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static int ind_test_init(struct kunit *test) +{ + struct ind_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct buffer_head *sbh; + struct inode *root_inode; + int ret; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + INIT_LIST_HEAD(&ctx->blks); + ctx->device_blocks = IND_TEST_TOTAL_BLKS; + ctx->next_alloc_pblk = 1000; + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->bdev.bd_stats != NULL); + + ctx->bh_folio = folio_alloc(GFP_KERNEL, 0); + if (!ctx->bh_folio) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "folio_alloc failed"); + } + + fc = fs_context_for_mount(&ind_test_fs_type, 0); + if (IS_ERR(fc)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "fs_context_for_mount failed: %ld", + PTR_ERR(fc)); + } + sb = sget_fc(fc, NULL, ind_test_set_super); + put_fs_context(fc); + if (IS_ERR(sb)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "sget_fc failed: %ld", PTR_ERR(sb)); + } + ctx->sb = sb; + sbi = &ctx->sbi; + INIT_WORK(&sbi->s_sb_upd_work, ind_test_sb_upd_work); + timer_setup(&sbi->s_err_report, ind_test_err_timer, 0); + up_write(&sb->s_umount); + + ret = kunit_add_action_or_reset(test, ind_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, ret, 0); + + sb->s_fs_info = sbi; + sb->s_op = &ind_test_sops; + sb->s_blocksize = IND_TEST_BLK_SIZE; + sb->s_blocksize_bits = IND_TEST_BLK_BITS; + sb->s_magic = EXT4_SUPER_MAGIC; + sb->s_maxbytes = MAX_LFS_FILESIZE; + INIT_LIST_HEAD(&sb->s_inodes); +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + + strscpy(sb->s_id, "ext4_indirect_kunit", sizeof(sb->s_id)); + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = IND_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + sbi->s_sb = sb; + sbi->s_blockgroup_lock = &ctx->bgl; + bgl_lock_init(&ctx->bgl); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_es_lock); + INIT_LIST_HEAD(&sbi->s_es_list); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10); + + ret = percpu_init_rwsem(&sbi->s_writepages_rwsem); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->rwsem_inited = true; + + ret = percpu_counter_init(&sbi->s_freeclusters_counter, 4096, + GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_freeinodes_counter, 200, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + + ret = ext4_es_register_shrinker(sbi); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->es_shrinker_inited = true; + + sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); + sbi->s_blocks_per_group = IND_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = IND_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = IND_TEST_NGROUPS; + sbi->s_inodes_per_group = IND_TEST_INODES_PER_GRP; + sbi->s_inode_size = IND_TEST_INODE_SIZE; + sbi->s_inodes_per_block = IND_TEST_BLK_SIZE / IND_TEST_INODE_SIZE; + sbi->s_first_ino = 11; + sbi->s_mount_state = EXT4_VALID_FS; + sbi->s_bitmap_maxbytes = ext4_max_bitmap_size_test(IND_TEST_BLK_BITS, + 1); + set_opt(sb, ERRORS_CONT); + + sbh = ind_get_or_create_bh(ctx, IND_TEST_FIRST_DATA_BLK); + KUNIT_ASSERT_NOT_NULL(test, sbh); + clear_buffer_mapped(sbh); + brelse(sbh); + sbi->s_sbh = sbh; + ctx->es = (struct ext4_super_block *)sbh->b_data; + sbi->s_es = ctx->es; + + ctx->es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es->s_first_data_block = cpu_to_le32(IND_TEST_FIRST_DATA_BLK); + ctx->es->s_blocks_per_group = cpu_to_le32(IND_TEST_BLOCKS_PER_GRP); + ctx->es->s_clusters_per_group = cpu_to_le32(IND_TEST_BLOCKS_PER_GRP); + ctx->es->s_inodes_per_group = cpu_to_le32(IND_TEST_INODES_PER_GRP); + ctx->es->s_inodes_count = cpu_to_le32(IND_TEST_NGROUPS * + IND_TEST_INODES_PER_GRP); + ctx->es->s_inode_size = cpu_to_le16(IND_TEST_INODE_SIZE); + ctx->es->s_checksum_type = EXT4_CRC32C_CHKSUM; + generate_random_uuid(ctx->es->s_uuid); + ext4_blocks_count_set(ctx->es, IND_TEST_TOTAL_BLKS); + ext4_set_feature_64bit(sb); + ext4_set_feature_metadata_csum(sb); + sbi->s_csum_seed = ext4_chksum(~0, ctx->es->s_uuid, + sizeof(ctx->es->s_uuid)); + ext4_superblock_csum_set(sb); + + root_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, root_inode); + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_blkbits = IND_TEST_BLK_BITS; + root_inode->i_flags |= S_NOQUOTA; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + KUNIT_ASSERT_NOT_NULL(test, sb->s_root); + sb->s_flags |= SB_ACTIVE; + + active_ind_test = test; + kunit_activate_static_stub(test, ext4_sb_getblk, ind_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_sb_bread_nofail, + ind_sb_bread_nofail_stub); + kunit_activate_static_stub(test, ext4_read_bh, ind_read_bh_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + ind_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + ind_mark_inode_dirty_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + ind_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + ind_free_blocks_stub); + + return 0; +} + +/* + * Test 1: ext4_block_to_path() across direct, single-, double-, and + * triple-indirect boundaries plus out-of-range block rejection, and + * ext4_ind_trans_blocks() credit estimation. + */ +static void test_block_to_path_and_trans_blocks(struct kunit *test) +{ + struct inode *inode = ind_make_test_inode(test, 12); + ext4_lblk_t offsets[4]; + int boundary = -1; + + /* Direct: block 0 and block 11 (boundary = 0) */ + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, 0, offsets, &boundary), + 1); + KUNIT_EXPECT_EQ(test, offsets[0], 0U); + KUNIT_EXPECT_EQ(test, boundary, 11); + + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, 11, offsets, &boundary), + 1); + KUNIT_EXPECT_EQ(test, offsets[0], 11U); + KUNIT_EXPECT_EQ(test, boundary, 0); + + /* Single-indirect: first (12) and last (267) */ + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_IND_BASE, + offsets, &boundary), 2); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_IND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 0U); + KUNIT_EXPECT_EQ(test, boundary, 255); + + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_DIND_BASE - 1, + offsets, &boundary), 2); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_IND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 255U); + KUNIT_EXPECT_EQ(test, boundary, 0); + + /* Double-indirect: first (268), end of first IND (523), last (65803) */ + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_DIND_BASE, + offsets, &boundary), 3); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_DIND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 0U); + KUNIT_EXPECT_EQ(test, offsets[2], 0U); + KUNIT_EXPECT_EQ(test, boundary, 255); + + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_DIND_BASE + 255, + offsets, &boundary), 3); + KUNIT_EXPECT_EQ(test, offsets[1], 0U); + KUNIT_EXPECT_EQ(test, offsets[2], 255U); + KUNIT_EXPECT_EQ(test, boundary, 0); + + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_TIND_BASE - 1, + offsets, &boundary), 3); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_DIND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 255U); + KUNIT_EXPECT_EQ(test, offsets[2], 255U); + KUNIT_EXPECT_EQ(test, boundary, 0); + + /* Triple-indirect: first (65804) and last (16843019) */ + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_TIND_BASE, + offsets, &boundary), 4); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_TIND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 0U); + KUNIT_EXPECT_EQ(test, offsets[2], 0U); + KUNIT_EXPECT_EQ(test, offsets[3], 0U); + KUNIT_EXPECT_EQ(test, boundary, 255); + + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_MAX_LBLK - 1, + offsets, NULL), 4); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_TIND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 255U); + KUNIT_EXPECT_EQ(test, offsets[2], 255U); + KUNIT_EXPECT_EQ(test, offsets[3], 255U); + + /* Out-of-range block returns 0 */ + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_MAX_LBLK, + offsets, NULL), 0); + + /* ext4_ind_trans_blocks(): DIV_ROUND_UP(nrblocks, 256) + 4 */ + KUNIT_EXPECT_EQ(test, ext4_ind_trans_blocks(inode, 1), 5); + KUNIT_EXPECT_EQ(test, ext4_ind_trans_blocks(inode, 256), 5); + KUNIT_EXPECT_EQ(test, ext4_ind_trans_blocks(inode, 257), 6); + KUNIT_EXPECT_EQ(test, ext4_ind_trans_blocks(inode, 512), 6); + + iput(inode); +} + +/* + * Test 2: ext4_ind_map_blocks() read-only lookup for contiguous mapped runs, + * EXT4_MAP_BOUNDARY detection, and multi-level unallocated hole span sizing. + */ +static void test_ind_map_blocks_lookup_mapped_and_holes(struct kunit *test) +{ + struct inode *inode = ind_make_test_inode(test, 13); + struct ext4_map_blocks map; + unsigned int i; + int ret; + + /* Map direct [0..3] -> [100..103], hole at [4], [5..11] -> [205..211] */ + for (i = 0; i < 4; i++) + EXT4_I(inode)->i_data[i] = cpu_to_le32(100 + i); + for (i = 5; i < EXT4_NDIR_BLOCKS; i++) + EXT4_I(inode)->i_data[i] = cpu_to_le32(200 + i); + + /* Contiguous direct run [0..3] stops at hole [4], not at boundary */ + memset(&map, 0, sizeof(map)); + map.m_lblk = 0; + map.m_len = 10; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 4); + KUNIT_EXPECT_EQ(test, map.m_pblk, 100ULL); + KUNIT_EXPECT_EQ(test, map.m_len, 4U); + KUNIT_EXPECT_TRUE(test, map.m_flags & EXT4_MAP_MAPPED); + KUNIT_EXPECT_FALSE(test, map.m_flags & EXT4_MAP_BOUNDARY); + + /* Contiguous direct run [5..11] hits end of direct array -> BOUNDARY */ + memset(&map, 0, sizeof(map)); + map.m_lblk = 5; + map.m_len = 10; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 7); + KUNIT_EXPECT_EQ(test, map.m_pblk, 205ULL); + KUNIT_EXPECT_EQ(test, map.m_len, 7U); + KUNIT_EXPECT_EQ(test, map.m_flags & (EXT4_MAP_MAPPED | EXT4_MAP_BOUNDARY), + (unsigned int)(EXT4_MAP_MAPPED | EXT4_MAP_BOUNDARY)); + + /* Direct hole at [4]: hole length is 1 */ + memset(&map, 0, sizeof(map)); + map.m_lblk = 4; + map.m_len = 5; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_pblk, 0ULL); + KUNIT_EXPECT_EQ(test, map.m_len, 1U); + + /* Absent IND subtree at lblk = 20 (offsets = [12, 8]) -> 256 - 8 = 248 */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_IND_BASE + 8; + map.m_len = 500; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_len, 248U); + + /* + * Absent DIND subtree at offsets = [13, 2, 10]: + * remaining blocks in DIND = (255 - 2) * 256 + (256 - 10) = 65014. + */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_DIND_BASE + 2 * IND_TEST_PTRS_PER_BLK + 10; + map.m_len = 100000; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_len, 65014U); + + iput(inode); +} + +/* + * Test 3: ext4_ind_map_blocks() block allocation and branch splicing across + * direct, single-indirect, double-indirect, and triple-indirect levels. + */ +static void test_ind_map_blocks_alloc_direct_ind_dind_tind(struct kunit *test) +{ + struct inode *inode = ind_make_test_inode(test, 14); + struct ext4_map_blocks map, check; + handle_t *handle; + int ret; + + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 8); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + + /* 1. Multi-block direct allocation at [2..5] */ + memset(&map, 0, sizeof(map)); + map.m_lblk = 2; + map.m_len = 4; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 4); + KUNIT_EXPECT_EQ(test, map.m_flags & (EXT4_MAP_NEW | EXT4_MAP_MAPPED), + (unsigned int)(EXT4_MAP_NEW | EXT4_MAP_MAPPED)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[1]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[2]), + (u32)map.m_pblk); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[5]), + (u32)(map.m_pblk + 3)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[6]), 0U); + + /* 2. Direct allocation clamped at direct boundary [9..11] */ + memset(&map, 0, sizeof(map)); + map.m_lblk = 9; + map.m_len = 6; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 3); + KUNIT_EXPECT_TRUE(test, map.m_flags & EXT4_MAP_BOUNDARY); + + /* 3. Single-indirect allocation at [15..19] */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_IND_BASE + 3; + map.m_len = 5; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_NE(test, le32_to_cpu(EXT4_I(inode)->i_data[EXT4_IND_BLOCK]), + 0U); + + memset(&check, 0, sizeof(check)); + check.m_lblk = IND_TEST_IND_BASE + 3; + check.m_len = 10; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &check, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_EQ(test, check.m_pblk, map.m_pblk); + + /* 4. Double-indirect allocation at DIND_BASE + 300 (len = 3) */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_DIND_BASE + 300; + map.m_len = 3; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 3); + KUNIT_EXPECT_NE(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_DIND_BLOCK]), + 0U); + + memset(&check, 0, sizeof(check)); + check.m_lblk = IND_TEST_DIND_BASE + 300; + check.m_len = 5; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &check, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 3); + KUNIT_EXPECT_EQ(test, check.m_pblk, map.m_pblk); + + /* 5. Triple-indirect allocation at TIND_BASE + 5 (len = 2) */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_TIND_BASE + 5; + map.m_len = 2; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_NE(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_TIND_BLOCK]), + 0U); + + memset(&check, 0, sizeof(check)); + check.m_lblk = IND_TEST_TIND_BASE + 5; + check.m_len = 4; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &check, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, check.m_pblk, map.m_pblk); + + ext4_journal_stop(handle); + iput(inode); +} + +/* + * Test 4: ext4_ind_map_blocks() error paths and partial branch unwind in + * ext4_alloc_branch() when an intermediate indirect or leaf allocation fails. + */ +static void test_ind_map_blocks_errors_and_alloc_branch_unwind(struct kunit *test) +{ + struct ind_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode = ind_make_test_inode(test, 15); + struct ext4_map_blocks map; + struct buffer_head *ind_bh; + ext4_fsblk_t alloc_base; + handle_t *handle; + int ret; + + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 8); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + + /* 1. Out-of-range m_lblk -> -EIO */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_MAX_LBLK; + map.m_len = 1; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -EIO); + + /* 2. Allocating on an indirect inode with bigalloc -> -EFSCORRUPTED */ + ext4_set_feature_bigalloc(sb); + memset(&map, 0, sizeof(map)); + map.m_lblk = 0; + map.m_len = 1; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + ext4_clear_feature_bigalloc(sb); + + /* 3. Out-of-range indirect block pointer on lookup -> -EFSCORRUPTED */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = + cpu_to_le32(IND_TEST_TOTAL_BLKS + 10); + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_IND_BASE; + map.m_len = 1; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + + /* 4. Non-uptodate IND block read I/O failure -> -EIO */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(300); + ind_bh = ind_get_or_create_bh(ctx, 300); + KUNIT_ASSERT_NOT_NULL(test, ind_bh); + clear_buffer_uptodate(ind_bh); + ctx->read_bh_err = -EIO; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -EIO); + ctx->read_bh_err = 0; + + /* + * 5. Non-uptodate IND block containing invalid blockref (block 1 == + * s_first_data_block) fails ext4_check_indirect_blockref() -> -EIO. + */ + ((__le32 *)ind_bh->b_data)[0] = cpu_to_le32(IND_TEST_FIRST_DATA_BLK); + clear_buffer_uptodate(ind_bh); + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -EIO); + brelse(ind_bh); + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = 0; + + /* + * 6. Partial TIND branch unwind: TIND (call 1), DIND (call 2), and + * IND (call 3) metadata blocks succeed; leaf data allocation (call 4) + * fails with -ENOSPC. All 3 metadata blocks must be freed and + * i_data[EXT4_TIND_BLOCK] must remain 0. + */ + ctx->freed_cnt = 0; + ctx->alloc_calls = 0; + ctx->fail_alloc_on_call = 4; + ctx->fail_alloc_err = -ENOSPC; + alloc_base = ctx->next_alloc_pblk; + + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_TIND_BASE + 9; + map.m_len = 2; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_TIND_BLOCK]), + 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, alloc_base)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, alloc_base + 1)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, alloc_base + 2)); + KUNIT_EXPECT_EQ(test, inode->i_blocks, 0ULL); + + ctx->fail_alloc_on_call = 0; + ctx->fail_alloc_err = 0; + ext4_journal_stop(handle); + iput(inode); +} + +/* + * Test 5: ext4_ind_truncate() partial shared-branch truncation inside DIND, + * boundary truncation detaching IND, and full truncation to i_size = 0. + */ +static void test_ind_truncate_partial_and_full(struct kunit *test) +{ + struct ind_test_ctx *ctx = test->priv; + struct inode *inode = ind_make_test_inode(test, 16); + __le32 *ind, *dind, *dind_c0, *dind_c1, *tind, *tind_d0, *tind_i0; + handle_t *handle; + unsigned int i; + + /* Direct [0..11] -> [100..111] */ + for (i = 0; i < EXT4_NDIR_BLOCKS; i++) + EXT4_I(inode)->i_data[i] = cpu_to_le32(100 + i); + + /* IND (500): [0..5] -> [600..605] */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(500); + ind = ind_blk_ptrs(test, 500); + for (i = 0; i < 6; i++) + ind[i] = cpu_to_le32(600 + i); + + /* DIND (501): child0 (502) -> [700..705], child1 (503) -> [710..713] */ + EXT4_I(inode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(501); + dind = ind_blk_ptrs(test, 501); + dind[0] = cpu_to_le32(502); + dind[1] = cpu_to_le32(503); + dind_c0 = ind_blk_ptrs(test, 502); + for (i = 0; i < 6; i++) + dind_c0[i] = cpu_to_le32(700 + i); + dind_c1 = ind_blk_ptrs(test, 503); + for (i = 0; i < 4; i++) + dind_c1[i] = cpu_to_le32(710 + i); + + /* TIND (504) -> DIND (505) -> IND (506) -> data (800) */ + EXT4_I(inode)->i_data[EXT4_TIND_BLOCK] = cpu_to_le32(504); + tind = ind_blk_ptrs(test, 504); + tind[0] = cpu_to_le32(505); + tind_d0 = ind_blk_ptrs(test, 505); + tind_d0[0] = cpu_to_le32(506); + tind_i0 = ind_blk_ptrs(test, 506); + tind_i0[0] = cpu_to_le32(800); + + ext4_es_insert_extent(inode, 0, 100000, 100, EXTENT_STATUS_WRITTEN, 0); + + handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, 8); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + + /* + * Step A: Truncate to last_block = DIND_BASE + 3. + * DIND[0][0..2] (700..702) survive; DIND[0][3..5] (703..705), + * DIND[1] (503, 710..713), and TIND (504, 505, 506, 800) are freed. + */ + i_size_write(inode, (loff_t)(IND_TEST_DIND_BASE + 3) * + IND_TEST_BLK_SIZE); + down_write(&EXT4_I(inode)->i_data_sem); + ext4_ind_truncate(handle, inode); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, i_size_read(inode)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[EXT4_DIND_BLOCK]), + 501U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(dind[0]), 502U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(dind[1]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(dind_c0[2]), 702U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(dind_c0[3]), 0U); + KUNIT_EXPECT_FALSE(test, ind_was_freed(ctx, 702)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 703)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 705)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 503)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 710)); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_TIND_BLOCK]), + 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 504)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 506)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 800)); + + /* + * Step B: Truncate to last_block = IND_BASE (12). + * Direct [0..11] survive; IND (500) and remaining DIND (501, 502) + * are detached and freed. + */ + ctx->freed_cnt = 0; + i_size_write(inode, (loff_t)IND_TEST_IND_BASE * IND_TEST_BLK_SIZE); + down_write(&EXT4_I(inode)->i_data_sem); + ext4_ind_truncate(handle, inode); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_IND_BLOCK]), 0U); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_DIND_BLOCK]), + 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 500)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 600)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 501)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 502)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[11]), 111U); + + /* Step C: Truncate to 0 frees all remaining direct blocks */ + ctx->freed_cnt = 0; + i_size_write(inode, 0); + down_write(&EXT4_I(inode)->i_data_sem); + ext4_ind_truncate(handle, inode); + up_write(&EXT4_I(inode)->i_data_sem); + + for (i = 0; i < EXT4_NDIR_BLOCKS; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[i]), + 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 100)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 111)); + + ext4_journal_stop(handle); + iput(inode); +} + +/* + * Test 6: ext4_ind_remove_space() hole punching within direct blocks, across + * different tree levels (n < n2), and within the same indirect level (n == n2) + * converging on a shared IND or DIND block. + */ +static void test_ind_remove_space_levels_and_convergence(struct kunit *test) +{ + struct ind_test_ctx *ctx = test->priv; + struct inode *inode = ind_make_test_inode(test, 17); + __le32 *ind, *dind, *c0, *c1, *c2; + handle_t *handle; + unsigned int i; + int ret; + + handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, 8); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + + /* Empty/out-of-range ranges are no-ops */ + down_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ext4_ind_remove_space(handle, inode, 5, 5), 0); + KUNIT_EXPECT_EQ(test, + ext4_ind_remove_space(handle, inode, + IND_TEST_MAX_LBLK + 10, + IND_TEST_MAX_LBLK + 20), 0); + up_write(&EXT4_I(inode)->i_data_sem); + + /* Populate direct [0..11], IND (510), and DIND (511 -> 512, 513, 514) */ + for (i = 0; i < EXT4_NDIR_BLOCKS; i++) + EXT4_I(inode)->i_data[i] = cpu_to_le32(120 + i); + + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(510); + ind = ind_blk_ptrs(test, 510); + for (i = 0; i < 12; i++) + ind[i] = cpu_to_le32(620 + i); + + EXT4_I(inode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(511); + dind = ind_blk_ptrs(test, 511); + dind[0] = cpu_to_le32(512); + dind[1] = cpu_to_le32(513); + dind[2] = cpu_to_le32(514); + c0 = ind_blk_ptrs(test, 512); + c1 = ind_blk_ptrs(test, 513); + c2 = ind_blk_ptrs(test, 514); + for (i = 0; i < 8; i++) { + c0[i] = cpu_to_le32(720 + i); + c1[i] = cpu_to_le32(740 + i); + c2[i] = cpu_to_le32(760 + i); + } + + /* 1. Direct-only hole punch [3, 8) */ + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_remove_space(handle, inode, 3, 8); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[2]), 122U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[3]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[7]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[8]), 128U); + + /* 2. Same-level IND convergence [IND_BASE + 3, IND_BASE + 8) */ + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_remove_space(handle, inode, IND_TEST_IND_BASE + 3, + IND_TEST_IND_BASE + 8); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ind[2]), 622U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ind[3]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ind[7]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ind[8]), 628U); + + /* + * 3. Same-level DIND convergence across 3 IND children: + * [DIND_BASE + 4, DIND_BASE + 2 * 256 + 3) frees c0[4..7], the entire + * middle c1 (513 + 740..747), and c2[0..2], preserving c0[0..3] and + * c2[3..7]. + */ + ctx->freed_cnt = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_remove_space(handle, inode, IND_TEST_DIND_BASE + 4, + IND_TEST_DIND_BASE + + 2 * IND_TEST_PTRS_PER_BLK + 3); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c0[3]), 723U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c0[4]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(dind[1]), 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 513)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 740)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c2[2]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c2[3]), 763U); + + /* + * 4. Cross-level punch (n = 1 < n2 = 3): [10, DIND_BASE + 2) frees + * direct [10..11], entire IND (510), and c0[0..1], preserving c0[2..3]. + */ + ctx->freed_cnt = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_remove_space(handle, inode, 10, IND_TEST_DIND_BASE + 2); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[9]), 129U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[10]), 0U); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_IND_BLOCK]), 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 510)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c0[1]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c0[2]), 722U); + + ext4_journal_stop(handle); + iput(inode); +} + +/* + * Test 7: Corrupt out-of-range block pointers in ext4_clear_blocks() and + * ext4_free_branches() record filesystem errors without freeing invalid blocks. + */ +static void test_ind_free_corrupt_block_numbers(struct kunit *test) +{ + struct ind_test_ctx *ctx = test->priv; + struct inode *inode = ind_make_test_inode(test, 18); + ext4_fsblk_t bad_blk = IND_TEST_TOTAL_BLKS + 77; + handle_t *handle; + + handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, 4); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + + EXT4_I(inode)->i_data[0] = cpu_to_le32(bad_blk); + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(bad_blk + 1); + i_size_write(inode, 0); + + down_write(&EXT4_I(inode)->i_data_sem); + ext4_ind_truncate(handle, inode); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_TRUE(test, ctx->sbi.s_mount_state & EXT4_ERROR_FS); + KUNIT_EXPECT_FALSE(test, ind_was_freed(ctx, bad_blk)); + KUNIT_EXPECT_FALSE(test, ind_was_freed(ctx, bad_blk + 1)); + + ext4_journal_stop(handle); + iput(inode); +} + +static struct kunit_case ext4_indirect_test_cases[] = { + KUNIT_CASE(test_block_to_path_and_trans_blocks), + KUNIT_CASE(test_ind_map_blocks_lookup_mapped_and_holes), + KUNIT_CASE(test_ind_map_blocks_alloc_direct_ind_dind_tind), + KUNIT_CASE(test_ind_map_blocks_errors_and_alloc_branch_unwind), + KUNIT_CASE(test_ind_truncate_partial_and_full), + KUNIT_CASE(test_ind_remove_space_levels_and_convergence), + KUNIT_CASE(test_ind_free_corrupt_block_numbers), + {} +}; + +static struct kunit_suite ext4_indirect_test_suite = { + .name = "ext4_indirect_test", + .init = ind_test_init, + .test_cases = ext4_indirect_test_cases, +}; + +kunit_test_suites(&ext4_indirect_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 indirect block mapping and truncation"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/indirect.c b/fs/ext4/indirect.c index 15c978f37a5c66..fd6d60f0323da9 100644 --- a/fs/ext4/indirect.c +++ b/fs/ext4/indirect.c @@ -163,7 +163,7 @@ static Indirect *ext4_get_branch(struct inode *inode, int depth, ret = -EFSCORRUPTED; goto failure; } - bh = sb_getblk(sb, key); + bh = ext4_sb_getblk(sb, key); if (unlikely(!bh)) { ret = -ENOMEM; goto failure; @@ -354,7 +354,8 @@ static int ext4_alloc_branch(handle_t *handle, if (i == 0) continue; - bh = branch[i].bh = sb_getblk(ar->inode->i_sb, new_blocks[i-1]); + bh = branch[i].bh = ext4_sb_getblk(ar->inode->i_sb, + new_blocks[i - 1]); if (unlikely(!bh)) { err = -ENOMEM; goto failed; @@ -688,6 +689,7 @@ int ext4_ind_map_blocks(handle_t *handle, struct inode *inode, trace_ext4_ind_map_blocks_exit(inode, flags, map, err); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ind_map_blocks); /* * Calculate number of indirect blocks touched by mapping @nrblocks logically @@ -702,6 +704,7 @@ int ext4_ind_trans_blocks(struct inode *inode, int nrblocks) */ return DIV_ROUND_UP(nrblocks, EXT4_ADDR_PER_BLOCK(inode->i_sb)) + 4; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ind_trans_blocks); static int ext4_ind_trunc_restart_fn(handle_t *handle, struct inode *inode, struct buffer_head *bh, int *dropped) @@ -1230,6 +1233,7 @@ void ext4_ind_truncate(handle_t *handle, struct inode *inode) ; } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ind_truncate); /** * ext4_ind_remove_space - remove space from the range @@ -1489,3 +1493,13 @@ int ext4_ind_remove_space(handle_t *handle, struct inode *inode, } goto cleanup; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ind_remove_space); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_block_to_path_test(struct inode *inode, ext4_lblk_t i_block, + ext4_lblk_t offsets[4], int *boundary) +{ + return ext4_block_to_path(inode, i_block, offsets, boundary); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_to_path_test); +#endif diff --git a/fs/ext4/super.c b/fs/ext4/super.c index cccbb2e3ad5f98..880f664d6c04b0 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -296,11 +296,16 @@ struct buffer_head *ext4_sb_bread_unmovable(struct super_block *sb, struct buffer_head *ext4_sb_bread_nofail(struct super_block *sb, sector_t block) { - gfp_t gfp = mapping_gfp_constraint(sb->s_bdev->bd_mapping, + gfp_t gfp; + + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_bread_nofail, sb, block); + + gfp = mapping_gfp_constraint(sb->s_bdev->bd_mapping, ~__GFP_FS) | __GFP_MOVABLE | __GFP_NOFAIL; return __ext4_sb_bread_gfp(sb, block, 0, gfp); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_bread_nofail); void ext4_sb_breadahead_unmovable(struct super_block *sb, sector_t block) { From 863963517288e7438f10ac638b425e8d593cf4bb Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:24:47 +0000 Subject: [PATCH 1573/2102] ext4: expand KUnit tests in fs/ext4/extents-test.c for file range operations Expand ext4_extents_test to cover high-level file-range operations and reporting entry points in fs/ext4/extents.c: - ext4_fallocate() mode validation (unsupported flags, encrypted collapse/insert rejection, FALLOC_FL_WRITE_ZEROES device limit check, non-extent inode rejection), preallocation with and without FALLOC_FL_KEEP_SIZE, and hole punching via FALLOC_FL_PUNCH_HOLE - ext4_zero_range() via FALLOC_FL_ZERO_RANGE (written-to-unwritten split and EOF extension) and FALLOC_FL_WRITE_ZEROES (block zeroouts, unwritten-to-written conversion, and orphan tracking across EOF) - ext4_collapse_range() alignment/EOF validation, block freeing, left-shift of trailing extents, and adjacent extent coalescing - ext4_insert_range() alignment/EOF/maxbytes validation, mid-extent splitting, right-shift of trailing extents, and i_size growth - ext4_convert_unwritten_extents(), ext4_convert_unwritten_extents_atomic(), and ext4_convert_unwritten_io_end_vec() IO completion conversions - ext4_fiemap() and ext4_get_es_cache() range checks, FIEMAP_FLAG_CACHE precaching, external xattr reporting, and status extent reporting Signed-off-by: Theodore Ts'o --- fs/ext4/extents-test.c | 528 ++++++++++++++++++++++++++++++++++++++++- fs/ext4/extents.c | 6 + 2 files changed, 532 insertions(+), 2 deletions(-) diff --git a/fs/ext4/extents-test.c b/fs/ext4/extents-test.c index bc548829310368..6458345ea958c3 100644 --- a/fs/ext4/extents-test.c +++ b/fs/ext4/extents-test.c @@ -15,8 +15,11 @@ #include #include #include +#include +#include #include #include +#include #include #include "ext4.h" @@ -71,6 +74,13 @@ static struct kunit_ctx { int last_free_flags; unsigned long total_freed_blocks; + unsigned int zeroout_calls; + ext4_lblk_t last_zeroout_lblk; + ext4_lblk_t last_zeroout_len; + unsigned int orphan_add_calls; + unsigned int orphan_del_calls; + struct dentry k_dentry; + bool fail_getblk; } k_ctx; @@ -200,21 +210,31 @@ static void ext_init_mock_inode(struct ext4_inode_info *ei, inode->i_sb = sb; inode->i_ino = ino; inode->i_mode = S_IFREG | 0644; + set_nlink(inode, 1); inode->i_blkbits = sb->s_blocksize_bits; - inode->i_flags |= S_NOQUOTA; + inode->i_flags |= S_NOQUOTA | S_NOSEC; inode->i_mapping = &inode->i_data; + inode_set_iversion(inode, 1); spin_lock_init(&inode->i_lock); i_size_ordered_init(inode); init_rwsem(&inode->i_rwsem); + address_space_init_once(&inode->i_data); init_rwsem(&inode->i_data.invalidate_lock); + inode->i_data.host = inode; inode_state_set_raw(inode, I_DIRTY_SYNC | I_DIRTY_DATASYNC); ext4_es_init_tree(&ei->i_es_tree); ext4_init_pending_tree(&ei->i_pending_tree); rwlock_init(&ei->i_es_lock); INIT_LIST_HEAD(&ei->i_es_list); + INIT_LIST_HEAD(&ei->i_orphan); + INIT_LIST_HEAD(&ei->i_fc_list); + INIT_LIST_HEAD(&ei->i_fc_dilist); + spin_lock_init(&ei->i_fc_lock); init_rwsem(&ei->i_data_sem); + init_rwsem(&ei->xattr_sem); + spin_lock_init(&ei->i_raw_lock); spin_lock_init(&ei->i_block_reservation_lock); rwlock_init(&ei->i_prealloc_lock); ei->i_prealloc_node = RB_ROOT; @@ -271,6 +291,7 @@ static void extents_kunit_exit(struct kunit *test) kfree(k_ctx.meta_blocks); kfree(sbi->s_es); + kfree(bdev->bd_queue); kfree(bdev->bd_mapping); kfree(bdev); kfree(sbi); @@ -496,16 +517,22 @@ static int extents_kunit_init(struct kunit *test) err = -ENOMEM; goto out_bdev; } + sb->s_bdev->bd_queue = kzalloc_obj(struct request_queue); + if (!sb->s_bdev->bd_queue) { + err = -ENOMEM; + goto out_bdev_mapping; + } sbi->s_es = kzalloc_obj(struct ext4_super_block); if (!sbi->s_es) { err = -ENOMEM; - goto out_bdev_mapping; + goto out_bdev_queue; } sbi->s_es->s_first_data_block = cpu_to_le32(1); sbi->s_es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); ext4_blocks_count_set(sbi->s_es, EXT_TOTAL_BLOCKS); set_opt(sb, ERRORS_CONT); + sbi->s_bitmap_maxbytes = 1ULL << 40; sbi->s_blocks_per_group = 32768; sbi->s_clusters_per_group = 32768; sbi->s_cluster_ratio = 1; @@ -513,12 +540,20 @@ static int extents_kunit_init(struct kunit *test) sbi->s_desc_per_block = 64; sbi->s_groups_count = 32; sbi->s_extent_max_zeroout_kb = 32; + mutex_init(&sbi->s_orphan_lock); + INIT_LIST_HEAD(&sbi->s_orphan); spin_lock_init(&sbi->s_bdev_wb_lock); spin_lock_init(&sbi->s_error_lock); spin_lock_init(&sbi->s_md_lock); + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); ratelimit_state_init(&sbi->s_warning_ratelimit_state, DEFAULT_RATELIMIT_INTERVAL, DEFAULT_RATELIMIT_BURST); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); err = percpu_counter_init(&sbi->s_freeclusters_counter, 100000, GFP_KERNEL); @@ -628,6 +663,8 @@ static int extents_kunit_init(struct kunit *test) percpu_counter_destroy(&sbi->s_freeclusters_counter); out_es: kfree(sbi->s_es); +out_bdev_queue: + kfree(sb->s_bdev->bd_queue); out_bdev_mapping: kfree(sb->s_bdev->bd_mapping); out_bdev: @@ -2458,6 +2495,487 @@ static void test_ext_fast_commit_replay(struct kunit *test) 10ULL << (inode->i_sb->s_blocksize_bits - 9)); } +static int ext_range_ext_zeroout_stub(handle_t *handle, struct inode *inode, + struct ext4_extent *ex) +{ + k_ctx.zeroout_calls++; + k_ctx.last_zeroout_lblk = le32_to_cpu(ex->ee_block); + k_ctx.last_zeroout_len = ext4_ext_get_actual_len(ex); + return 0; +} + +static int ext_range_issue_zeroout_stub(handle_t *handle, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + ext4_lblk_t len) +{ + k_ctx.zeroout_calls++; + k_ctx.last_zeroout_lblk = lblk; + k_ctx.last_zeroout_len = len; + return 0; +} + +static int ext_orphan_add_stub(handle_t *handle, struct inode *inode) +{ + k_ctx.orphan_add_calls++; + return 0; +} + +static int ext_orphan_del_stub(handle_t *handle, struct inode *inode) +{ + k_ctx.orphan_del_calls++; + return 0; +} + +static void ext_setup_range_test(struct kunit *test, struct inode *inode, + struct file *file) +{ + kunit_activate_static_stub(test, ext4_ext_zeroout, + ext_range_ext_zeroout_stub); + kunit_activate_static_stub(test, ext4_issue_zeroout, + ext_range_issue_zeroout_stub); + kunit_activate_static_stub(test, ext4_orphan_add, ext_orphan_add_stub); + kunit_activate_static_stub(test, ext4_orphan_del, ext_orphan_del_stub); + + ext_reset_tree(inode); + inode->i_size = 0; + EXT4_I(inode)->i_disksize = 0; + inode->i_blocks = 0; + + k_ctx.next_alloc_pblk = EXT_ALLOC_BASE_PBLK; + k_ctx.alloc_calls = 0; + k_ctx.free_calls = 0; + k_ctx.total_freed_blocks = 0; + k_ctx.zeroout_calls = 0; + k_ctx.orphan_add_calls = 0; + k_ctx.orphan_del_calls = 0; + + if (file) { + struct file tmp = { + .f_path = { .dentry = &k_ctx.k_dentry }, + .f_inode = inode, + .f_mapping = inode->i_mapping, + .f_mode = FMODE_READ | FMODE_WRITE | + FMODE_NOCMTIME, + }; + + memset(&k_ctx.k_dentry, 0, sizeof(k_ctx.k_dentry)); + k_ctx.k_dentry.d_inode = inode; + memcpy(file, &tmp, sizeof(tmp)); + } +} + +static void ext_expect_extent_at(struct kunit *test, struct inode *inode, + ext4_lblk_t lblk, unsigned short exp_len, + ext4_fsblk_t exp_pblk, bool exp_unwritten) +{ + struct ext4_ext_path *path; + struct ext4_extent ex; + bool found = false; + int err = 0; + + down_read(&EXT4_I(inode)->i_data_sem); + path = ext4_find_extent(inode, lblk, NULL, EXT4_EX_NOCACHE); + if (IS_ERR(path)) { + err = PTR_ERR(path); + } else { + if (path[path->p_depth].p_ext) { + ex = *path[path->p_depth].p_ext; + found = true; + } + ext4_free_ext_path(path); + } + up_read(&EXT4_I(inode)->i_data_sem); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_TRUE(test, found); + + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex.ee_block), lblk); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), exp_len); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex), exp_pblk); + KUNIT_EXPECT_EQ(test, !!ext4_ext_is_unwritten(&ex), exp_unwritten); +} + +/* + * Verify ext4_fallocate() mode validation (unsupported flags, encrypted + * collapse/insert rejection, WRITE_ZEROES without bdev support, non-extent + * preallocation rejection), preallocation with and without FALLOC_FL_KEEP_SIZE, + * and hole punching via FALLOC_FL_PUNCH_HOLE. + */ +static void test_fallocate_modes_and_prealloc(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct file file; + long ret; + + ext_setup_range_test(test, inode, &file); + + /* Unsupported mode flag -> -EOPNOTSUPP */ + ret = ext4_fallocate(&file, 0x40000000, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + + /* FALLOC_FL_WRITE_ZEROES without unmap sectors -> -EOPNOTSUPP */ + ret = ext4_fallocate(&file, FALLOC_FL_WRITE_ZEROES, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + + /* Encrypted inode rejects COLLAPSE_RANGE and INSERT_RANGE */ + inode->i_flags |= S_ENCRYPTED; + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + inode->i_flags &= ~S_ENCRYPTED; + + /* Non-extent (indirect) inode rejects fallocate preallocation */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ret = ext4_fallocate(&file, 0, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + + /* Preallocate [0, 4 blocks) with FALLOC_FL_KEEP_SIZE: i_size stays 0 */ + ret = ext4_fallocate(&file, FALLOC_FL_KEEP_SIZE, 0, 4 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 0LL); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 0LL); + ext_expect_extent_at(test, inode, 0, 4, EXT_ALLOC_BASE_PBLK, true); + + /* Extend allocation across [2, 6 blocks) without KEEP_SIZE */ + ret = ext4_fallocate(&file, 0, 2 * 4096, 4 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 6LL * 4096); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 6LL * 4096); + ext_expect_extent_at(test, inode, 0, 6, EXT_ALLOC_BASE_PBLK, true); + + /* Punch middle [2, 4) with FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE */ + ret = ext4_fallocate(&file, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, + 2 * 4096, 2 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 6LL * 4096); + KUNIT_EXPECT_EQ(test, k_ctx.total_freed_blocks, 2UL); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_entries), 2); + ext_expect_extent_at(test, inode, 0, 2, EXT_ALLOC_BASE_PBLK, true); + ext_expect_extent_at(test, inode, 4, 2, EXT_ALLOC_BASE_PBLK + 4, true); +} + +/* + * Verify ext4_zero_range() via both FALLOC_FL_ZERO_RANGE (splitting written + * extents to unwritten and allocating unwritten blocks past EOF) and + * FALLOC_FL_WRITE_ZEROES (issuing block zeroouts, converting to written, and + * tracking orphan state when extending i_disksize). + */ +static void test_zero_range_and_write_zeroes(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct super_block *sb = inode->i_sb; + struct file file; + long ret; + + /* Part A: FALLOC_FL_ZERO_RANGE across written tail + past EOF */ + ext_setup_range_test(test, inode, &file); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 6, 200, false, 0), 0); + inode->i_size = 6LL * 4096; + EXT4_I(inode)->i_disksize = 6LL * 4096; + + ret = ext4_fallocate(&file, FALLOC_FL_ZERO_RANGE, 2 * 4096, 6 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 8LL * 4096); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 8LL * 4096); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_entries), 3); + ext_expect_extent_at(test, inode, 0, 2, 200, false); + ext_expect_extent_at(test, inode, 2, 4, 202, true); + ext_expect_extent_at(test, inode, 6, 2, EXT_ALLOC_BASE_PBLK, true); + + /* Part B: FALLOC_FL_WRITE_ZEROES over unwritten + hole past EOF */ + ext_setup_range_test(test, inode, &file); + sb->s_bdev->bd_queue->limits.max_wzeroes_unmap_sectors = 1024; + + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 2, 300, true, 0), 0); + inode->i_size = 2LL * 4096; + EXT4_I(inode)->i_disksize = 2LL * 4096; + + ret = ext4_fallocate(&file, FALLOC_FL_WRITE_ZEROES, 0, 4 * 4096); + sb->s_bdev->bd_queue->limits.max_wzeroes_unmap_sectors = 0; + + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_GE(test, k_ctx.zeroout_calls, 2U); + KUNIT_EXPECT_GE(test, k_ctx.orphan_add_calls, 1U); + KUNIT_EXPECT_EQ(test, k_ctx.orphan_del_calls, 1U); + KUNIT_EXPECT_EQ(test, inode->i_size, 4LL * 4096); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 4LL * 4096); + ext_expect_extent_at(test, inode, 0, 2, 300, false); + ext_expect_extent_at(test, inode, 2, 2, EXT_ALLOC_BASE_PBLK, false); +} + +/* + * Verify ext4_collapse_range() validation checks, block removal, left-shift of + * subsequent extents, adjacent extent coalescing after collapse, and i_size + * reduction. + */ +static void test_collapse_range(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct file file; + long ret; + + ext_setup_range_test(test, inode, &file); + inode->i_size = 10LL * 4096; + EXT4_I(inode)->i_disksize = 10LL * 4096; + + /* Block-unaligned offset or length -> -EINVAL */ + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, 512, 4096); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, 4096, 512); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + /* Non-extent inode -> -EOPNOTSUPP */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + + /* Collapsing up to or beyond i_size -> -EINVAL */ + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, + 8 * 4096, 2 * 4096); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + /* + * Build [0, 2)@200 writ, [2, 4)@500 writ, [4, 7)@202 writ, and + * [8, 10)@600 unwrit. Collapsing [2, 4) frees [2, 4)@500, shifts + * [4, 7)@202 left to [2, 5)@202 where it merges with [0, 2)@200 into + * [0, 5)@200, and shifts [8, 10)@600 left to [6, 8)@600. + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 2, 200, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 2, 2, 500, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 4, 3, 202, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 8, 2, 600, true, 0), 0); + + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, + 2 * 4096, 2 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, k_ctx.total_freed_blocks, 2UL); + KUNIT_EXPECT_EQ(test, inode->i_size, 8LL * 4096); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 8LL * 4096); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_entries), 2); + ext_expect_extent_at(test, inode, 0, 5, 200, false); + ext_expect_extent_at(test, inode, 6, 2, 600, true); +} + +/* + * Verify ext4_insert_range() alignment, EOF, and s_maxbytes checks, as well as + * mid-extent splitting, right-shift of trailing extents, and i_size growth. + */ +static void test_insert_range(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct file file; + long ret; + + ext_setup_range_test(test, inode, &file); + inode->i_size = 10LL * 4096; + EXT4_I(inode)->i_disksize = 10LL * 4096; + + /* Block-unaligned offset or length -> -EINVAL */ + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 1024, 4096); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 4096, 1024); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + /* Non-extent inode -> -EOPNOTSUPP */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + + /* Offset at or beyond i_size -> -EINVAL */ + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 10 * 4096, 4096); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + /* Length exceeding s_maxbytes - i_size -> -EFBIG */ + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 4096, + round_down(inode->i_sb->s_maxbytes, 4096)); + KUNIT_EXPECT_EQ(test, ret, -EFBIG); + + /* + * Insert 3-block hole at lblk 2 inside [0, 6)@200 writ with trailing + * [8, 10)@400 unwrit: produces [0, 2)@200 writ, [5, 9)@202 writ, and + * [11, 13)@400 unwrit, with i_size = 13 blocks. + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 6, 200, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 8, 2, 400, true, 0), 0); + + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, + 2 * 4096, 3 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 13LL * 4096); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 13LL * 4096); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_entries), 3); + ext_expect_extent_at(test, inode, 0, 2, 200, false); + ext_expect_extent_at(test, inode, 5, 4, 202, false); + ext_expect_extent_at(test, inode, 11, 2, 400, true); +} + +/* + * Verify unwritten-to-written IO completion conversion helpers: + * ext4_convert_unwritten_extents(), ext4_convert_unwritten_extents_atomic() + * across a split unwritten mapping, and ext4_convert_unwritten_io_end_vec(). + */ +static void test_convert_unwritten_extents_and_io_end(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + ext4_io_end_t io_end = {}; + struct ext4_io_end_vec vec1 = {}, vec2 = {}; + ext4_lblk_t converted = 0; + int err; + + /* 1. ext4_convert_unwritten_extents() on middle of unwritten extent */ + ext_setup_range_test(test, inode, NULL); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 6, 200, true, 0), 0); + + err = ext4_convert_unwritten_extents(NULL, inode, 2 * 4096, 2 * 4096, + &converted); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, converted, 2U); + ext_expect_extent_at(test, inode, 0, 2, 200, true); + ext_expect_extent_at(test, inode, 2, 2, 202, false); + ext_expect_extent_at(test, inode, 4, 2, 204, true); + + /* 2. ext4_convert_unwritten_extents_atomic() across split unwritten */ + ext_setup_range_test(test, inode, NULL); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 2, 200, true, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 2, 3, 300, true, 0), 0); + + err = ext4_convert_unwritten_extents_atomic(NULL, inode, 0, 5 * 4096); + KUNIT_ASSERT_EQ(test, err, 0); + ext_expect_extent_at(test, inode, 0, 2, 200, false); + ext_expect_extent_at(test, inode, 2, 3, 300, false); + + /* 3. ext4_convert_unwritten_io_end_vec() across multiple vecs */ + ext_setup_range_test(test, inode, NULL); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 8, 200, true, 0), 0); + + io_end.inode = inode; + INIT_LIST_HEAD(&io_end.list_vec); + vec1.offset = 1 * 4096; + vec1.size = 2 * 4096; + vec2.offset = 5 * 4096; + vec2.size = 2 * 4096; + list_add_tail(&vec1.list, &io_end.list_vec); + list_add_tail(&vec2.list, &io_end.list_vec); + + err = ext4_convert_unwritten_io_end_vec(NULL, &io_end); + KUNIT_ASSERT_EQ(test, err, 0); + ext_expect_extent_at(test, inode, 0, 1, 200, true); + ext_expect_extent_at(test, inode, 1, 2, 201, false); + ext_expect_extent_at(test, inode, 3, 2, 203, true); + ext_expect_extent_at(test, inode, 5, 2, 205, false); + ext_expect_extent_at(test, inode, 7, 1, 207, true); +} + +/* + * Verify ext4_fiemap() (range checks, FIEMAP_FLAG_CACHE precaching, data and + * external xattr reporting) and ext4_get_es_cache() (flag checks, precaching, + * and reporting mapped + delayed status extents). + */ +static void test_ext_fiemap_and_get_es_cache(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct fiemap_extent_info fieinfo = {}; + struct extent_status es = {}; + int err; + + ext_setup_range_test(test, inode, NULL); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 3, 200, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 6, 2, 300, true, 0), 0); + inode->i_size = 10LL * 4096; + EXT4_I(inode)->i_disksize = 10LL * 4096; + + /* Zero-length FIEMAP -> -EINVAL */ + err = ext4_fiemap(inode, &fieinfo, 0, 0); + KUNIT_EXPECT_EQ(test, err, -EINVAL); + + /* Start past maxbytes on non-extent inode -> -EFBIG */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + err = ext4_fiemap(inode, &fieinfo, + EXT4_SB(inode->i_sb)->s_bitmap_maxbytes + 4096, 4096); + KUNIT_EXPECT_EQ(test, err, -EFBIG); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + + /* Count-only data FIEMAP with FIEMAP_FLAG_CACHE populates ES cache */ + memset(&fieinfo, 0, sizeof(fieinfo)); + fieinfo.fi_flags = FIEMAP_FLAG_CACHE; + err = ext4_fiemap(inode, &fieinfo, 0, 10 * 4096); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, fieinfo.fi_flags & FIEMAP_FLAG_CACHE, 0U); + KUNIT_EXPECT_EQ(test, fieinfo.fi_extents_mapped, 2U); + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 0, NULL, &es, NULL), + 1); + + /* FIEMAP_FLAG_XATTR with no xattrs vs external i_file_acl block */ + memset(&fieinfo, 0, sizeof(fieinfo)); + fieinfo.fi_flags = FIEMAP_FLAG_XATTR; + err = ext4_fiemap(inode, &fieinfo, 0, 4096); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, fieinfo.fi_extents_mapped, 0U); + + EXT4_I(inode)->i_file_acl = 750; + memset(&fieinfo, 0, sizeof(fieinfo)); + fieinfo.fi_flags = FIEMAP_FLAG_XATTR; + err = ext4_fiemap(inode, &fieinfo, 0, 4096); + EXT4_I(inode)->i_file_acl = 0; + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, fieinfo.fi_extents_mapped, 1U); + + /* ext4_get_es_cache: unsupported flag -> -EBADR, len == 0 -> -EINVAL */ + memset(&fieinfo, 0, sizeof(fieinfo)); + fieinfo.fi_flags = FIEMAP_FLAG_XATTR; + err = ext4_get_es_cache(inode, &fieinfo, 0, 4096); + KUNIT_EXPECT_EQ(test, err, -EBADR); + + memset(&fieinfo, 0, sizeof(fieinfo)); + err = ext4_get_es_cache(inode, &fieinfo, 0, 0); + KUNIT_EXPECT_EQ(test, err, -EINVAL); + + /* + * Populate ES tree with written, hole, delayed, and unwritten entries + * and verify ext4_get_es_cache reports all 4 entries. + */ + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + ext4_es_insert_extent(inode, 0, 3, 200, EXTENT_STATUS_WRITTEN, 0); + ext4_es_insert_extent(inode, 3, 1, ~0, EXTENT_STATUS_HOLE, 0); + ext4_es_insert_delayed_extent(inode, 4, 2, false, false); + ext4_es_insert_extent(inode, 6, 2, 300, EXTENT_STATUS_UNWRITTEN, 0); + up_write(&EXT4_I(inode)->i_data_sem); + + memset(&fieinfo, 0, sizeof(fieinfo)); + err = ext4_get_es_cache(inode, &fieinfo, 0, 10 * 4096); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, fieinfo.fi_extents_mapped, 4U); + + /* + * Build a depth-1 tree (5 discontiguous extents), clear ES cache, and + * verify FIEMAP_FLAG_CACHE precaches external leaf extents + holes. + */ + ext_setup_range_test(test, inode, NULL); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 1, 200, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 2, 1, 202, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 4, 1, 204, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 6, 1, 206, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 8, 1, 208, false, 0), 0); + inode->i_size = 10LL * 4096; + EXT4_I(inode)->i_disksize = 10LL * 4096; + + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + up_write(&EXT4_I(inode)->i_data_sem); + + memset(&fieinfo, 0, sizeof(fieinfo)); + fieinfo.fi_flags = FIEMAP_FLAG_CACHE; + err = ext4_get_es_cache(inode, &fieinfo, 0, 10 * 4096); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, fieinfo.fi_flags & FIEMAP_FLAG_CACHE, 0U); + KUNIT_EXPECT_GE(test, fieinfo.fi_extents_mapped, 5U); +} + static const struct kunit_ext_test_param test_split_convert_params[] = { /* unwrit to writ splits */ { .desc = "split unwrit extent to 2 extents and convert 1st half writ", @@ -3018,6 +3536,12 @@ static struct kunit_case extents_test_cases[] = { KUNIT_CASE(test_clu_mapped), KUNIT_CASE(test_ext_credits_calculation), KUNIT_CASE(test_ext_fast_commit_replay), + KUNIT_CASE(test_fallocate_modes_and_prealloc), + KUNIT_CASE(test_zero_range_and_write_zeroes), + KUNIT_CASE(test_collapse_range), + KUNIT_CASE(test_insert_range), + KUNIT_CASE(test_convert_unwritten_extents_and_io_end), + KUNIT_CASE(test_ext_fiemap_and_get_es_cache), {} }; diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index 0a442844b954e5..cbe187914fe2a0 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -5106,6 +5106,7 @@ long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len) inode_unlock(inode); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fallocate); /* * This function converts a range of blocks to written extents. The caller of @@ -5201,6 +5202,7 @@ int ext4_convert_unwritten_extents_atomic(handle_t *handle, struct inode *inode, return ret > 0 ? ret2 : ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_convert_unwritten_extents_atomic); /* * This function convert a range of blocks to written extents @@ -5293,6 +5295,7 @@ int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode, return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_convert_unwritten_extents); int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end) { @@ -5324,6 +5327,7 @@ int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end) return ret < 0 ? ret : err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_convert_unwritten_io_end_vec); static int ext4_iomap_xattr_fiemap(struct inode *inode, struct iomap *iomap) { @@ -5436,6 +5440,7 @@ int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, inode_unlock_shared(inode); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fiemap); int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo, __u64 start, __u64 len) @@ -5483,6 +5488,7 @@ int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo, */ return ext4_fill_es_cache_info(inode, start_blk, len_blks, fieinfo); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_es_cache); /* * ext4_ext_shift_path_extents: From 983cf5038127c3a2798cba867929e2bd8df3a84e Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:25:07 +0000 Subject: [PATCH 1574/2102] ext4: add KUnit tests for fs/ext4/fsmap.c Add KUnit test suite ext4_fsmap_test in fs/ext4/fsmap-test.c covering FS_IOC_GETFSMAP reverse-mapping queries in fs/ext4/fsmap.c: - ext4_fsmap_from_internal() and ext4_fsmap_to_internal() block/byte conversions across 1K, 4K, and 64K block sizes - ext4_getfsmap() validation of flags, device IDs, inverted keys, out-of-range physical offsets, and missing group descriptors - fixed per-group metadata synthesis (superblock, GDT, reserved GDT, block bitmap, inode bitmap, inode table), free extents, and EXT4_FMR_OWN_UNKNOWN gaps in the middle and at EOFS - flex_bg adjacent fixed-metadata merging and cross-group free-extent coalescing via gfi_lastfree - 1K s_first_data_block offset handling, bigalloc cluster scaling, and META_BG reserved-GDT suppression - count-only queries, bounded continuation-key pagination, formatter abort propagation, and external journal device reporting Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 2 +- fs/ext4/fsmap-test.c | 796 +++++++++++++++++++++++++++++++++++++++++++ fs/ext4/fsmap.c | 3 + fs/ext4/mballoc.c | 3 + 4 files changed, 803 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/fsmap-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 503acc94640970..e1964407be242e 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -23,7 +23,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ block_validity-test.o super-test.o \ sysfs-test.o ioctl-test.o \ resize-test.o migrate-test.o \ - indirect-test.o + indirect-test.o fsmap-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/fsmap-test.c b/fs/ext4/fsmap-test.c new file mode 100644 index 00000000000000..0142dd7d2ec3a0 --- /dev/null +++ b/fs/ext4/fsmap-test.c @@ -0,0 +1,796 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/fsmap.c (FS_IOC_GETFSMAP reverse-mapping queries). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "fsmap.h" +#include "mballoc.h" + +#define FSMAP_TEST_MAX_GROUPS 4 +#define FSMAP_TEST_MAX_CLUSTERS_PER_GRP 1024 +#define FSMAP_TEST_MAX_RECS 24 +#define FSMAP_TEST_DATADEV MKDEV(8, 1) +#define FSMAP_TEST_LOGDEV MKDEV(8, 2) + +/* + * Matches struct bdev_inode layout in block/bdev.c so file_bdev() resolves + * &bdev via container_of(bdev_file->f_mapping->host, ...). + */ +struct fsmap_mock_bdev_inode { + struct block_device bdev; + struct inode vfs_inode; +}; + +struct fsmap_rec_sink { + struct ext4_fsmap recs[FSMAP_TEST_MAX_RECS]; + unsigned int count; + unsigned int abort_after; + int fail_err; +}; + +struct fsmap_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct buffer_head sbh; + char sbh_data[4096]; + + struct fsmap_mock_bdev_inode data_bdev; + struct fsmap_mock_bdev_inode log_bdev; + struct file log_bdev_file; + journal_t mock_journal; + + struct buffer_head gdb_bh; + struct buffer_head *gdb_bh_arr[1]; + u8 gdb_data[4096]; + + DECLARE_BITMAP(grp_bms[FSMAP_TEST_MAX_GROUPS], + FSMAP_TEST_MAX_CLUSTERS_PER_GRP); +}; + +static struct fsmap_test_ctx *fsmap_active_ctx; + +static void fsmap_noop_work(struct work_struct *work) +{ +} + +static void fsmap_noop_timer(struct timer_list *timer) +{ +} + +static const struct super_operations fsmap_test_sops = {}; + +static int fsmap_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static int fsmap_test_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static struct file_system_type fsmap_test_fs_type = { + .name = "ext4-fsmap-test", + .init_fs_context = fsmap_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void fsmap_cleanup_ctx(void *data) +{ + struct fsmap_test_ctx *ctx = data; + + fsmap_active_ctx = NULL; + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + if (ctx->sb) + deactivate_super(ctx->sb); + if (ctx->data_bdev.bdev.bd_stats) + free_percpu(ctx->data_bdev.bdev.bd_stats); + if (ctx->log_bdev.bdev.bd_stats) + free_percpu(ctx->log_bdev.bdev.bd_stats); +} + +static int fsmap_query_range_stub(struct super_block *sb, + ext4_group_t group, + ext4_grpblk_t first, + ext4_grpblk_t end, + ext4_mballoc_query_range_fn meta_formatter, + ext4_mballoc_query_range_fn formatter, + void *priv) +{ + struct fsmap_test_ctx *ctx = fsmap_active_ctx; + ext4_grpblk_t max_clu = EXT4_CLUSTERS_PER_GROUP(sb); + ext4_grpblk_t first_free, start, next; + unsigned long *bm; + int error; + + if (!ctx || group >= FSMAP_TEST_MAX_GROUPS) + return -EINVAL; + + bm = ctx->grp_bms[group]; + if ((unsigned long)end >= EXT4_CLUSTERS_PER_GROUP(sb)) + end = max_clu - 1; + + first_free = find_next_zero_bit(bm, max_clu, 0); + start = max_t(ext4_grpblk_t, first_free, first); + + if (meta_formatter && start != first) { + if (start > end) + start = end; + error = meta_formatter(sb, group, first, start - first, priv); + if (error) + return error; + } + + while (start <= end) { + start = find_next_zero_bit(bm, end + 1, start); + if (start > end) + break; + next = find_next_bit(bm, end + 1, start); + + error = formatter(sb, group, start, next - start, priv); + if (error) + return error; + + start = next + 1; + } + + return 0; +} + +static int fsmap_collect_cb(struct ext4_fsmap *fmr, void *priv) +{ + struct fsmap_rec_sink *sink = priv; + + if (sink->fail_err) + return sink->fail_err; + + if (sink->count < FSMAP_TEST_MAX_RECS) + sink->recs[sink->count] = *fmr; + sink->count++; + + if (sink->abort_after && sink->count >= sink->abort_after) + return EXT4_QUERY_RANGE_ABORT; + + return EXT4_QUERY_RANGE_CONTINUE; +} + +static void fsmap_mark_clusters_used(struct fsmap_test_ctx *ctx, + ext4_group_t agno, + ext4_grpblk_t start_clu, + ext4_grpblk_t len_clu) +{ + bitmap_set(ctx->grp_bms[agno], start_clu, len_clu); +} + +static void fsmap_set_group_tables(struct fsmap_test_ctx *ctx, + ext4_group_t agno, + ext4_fsblk_t blk_bm, + ext4_fsblk_t ino_bm, + ext4_fsblk_t itable) +{ + struct super_block *sb = ctx->sb; + struct ext4_group_desc *gdp; + + gdp = (struct ext4_group_desc *)(ctx->gdb_data + + agno * EXT4_DESC_SIZE(sb)); + ext4_block_bitmap_set(sb, gdp, blk_bm); + ext4_inode_bitmap_set(sb, gdp, ino_bm); + ext4_inode_table_set(sb, gdp, itable); +} + +static struct fsmap_test_ctx *fsmap_create_ctx(struct kunit *test, + unsigned int blocksize_bits, + unsigned int cluster_bits, + ext4_group_t groups_count, + ext4_grpblk_t blocks_per_group) +{ + struct fsmap_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + unsigned int blocksize = 1U << blocksize_bits; + ext4_fsblk_t bofs = (blocksize == 1024) ? 1 : 0; + int err; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + + sbi = &ctx->sbi; + INIT_WORK(&sbi->s_sb_upd_work, fsmap_noop_work); + timer_setup(&sbi->s_err_report, fsmap_noop_timer, 0); + err = kunit_add_action_or_reset(test, fsmap_cleanup_ctx, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + inode_init_once(&ctx->data_bdev.vfs_inode); + address_space_init_once(&ctx->data_bdev.vfs_inode.i_data); + ctx->data_bdev.vfs_inode.i_data.host = &ctx->data_bdev.vfs_inode; + ctx->data_bdev.bdev.bd_dev = FSMAP_TEST_DATADEV; + ctx->data_bdev.bdev.bd_mapping = &ctx->data_bdev.vfs_inode.i_data; + ctx->data_bdev.bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->data_bdev.bdev.bd_stats != NULL); + + inode_init_once(&ctx->log_bdev.vfs_inode); + address_space_init_once(&ctx->log_bdev.vfs_inode.i_data); + ctx->log_bdev.vfs_inode.i_data.host = &ctx->log_bdev.vfs_inode; + ctx->log_bdev.bdev.bd_dev = FSMAP_TEST_LOGDEV; + ctx->log_bdev.bdev.bd_mapping = &ctx->log_bdev.vfs_inode.i_data; + ctx->log_bdev.bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->log_bdev.bdev.bd_stats != NULL); + ctx->log_bdev_file.f_mapping = &ctx->log_bdev.vfs_inode.i_data; + + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + + fc = fs_context_for_mount(&fsmap_test_fs_type, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fc)); + sb = sget_fc(fc, NULL, fsmap_test_set_super); + put_fs_context(fc); + KUNIT_ASSERT_FALSE(test, IS_ERR(sb)); + up_write(&sb->s_umount); + + ctx->sb = sb; + + sb->s_fs_info = sbi; + sb->s_op = &fsmap_test_sops; + sb->s_bdev = &ctx->data_bdev.bdev; + sb->s_blocksize = blocksize; + sb->s_blocksize_bits = blocksize_bits; + strscpy(sb->s_id, "ext4-fsmap", sizeof(sb->s_id)); + + ctx->sbh.b_data = ctx->sbh_data; + ctx->sbh.b_size = blocksize; + ctx->sbh.b_bdev = sb->s_bdev; + atomic_set(&ctx->sbh.b_count, 2); + set_buffer_uptodate(&ctx->sbh); + clear_buffer_mapped(&ctx->sbh); + + sbi->s_sb = sb; + sbi->s_es = &ctx->es; + sbi->s_sbh = &ctx->sbh; + set_opt(sb, ERRORS_CONT); + + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_first_data_block = cpu_to_le32(bofs); + ctx->es.s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_64BIT); + ctx->es.s_desc_size = cpu_to_le16(64); + ext4_blocks_count_set(&ctx->es, + bofs + (ext4_fsblk_t)groups_count * + blocks_per_group); + + sbi->s_desc_size = 64; + sbi->s_desc_per_block = blocksize / sbi->s_desc_size; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); + sbi->s_groups_count = groups_count; + sbi->s_blocks_per_group = blocks_per_group; + sbi->s_cluster_bits = cluster_bits; + sbi->s_cluster_ratio = 1U << cluster_bits; + sbi->s_clusters_per_group = blocks_per_group >> cluster_bits; + sbi->s_itb_per_group = 8; + sbi->s_gdb_count = 1; + + ctx->gdb_bh.b_data = ctx->gdb_data; + ctx->gdb_bh.b_size = blocksize; + ctx->gdb_bh.b_bdev = sb->s_bdev; + atomic_set(&ctx->gdb_bh.b_count, 2); + set_buffer_uptodate(&ctx->gdb_bh); + ctx->gdb_bh_arr[0] = &ctx->gdb_bh; + rcu_assign_pointer(sbi->s_group_desc, ctx->gdb_bh_arr); + + fsmap_active_ctx = ctx; + kunit_activate_static_stub(test, ext4_mballoc_query_range, + fsmap_query_range_stub); + + return ctx; +} + +static void fsmap_init_full_range_head(struct ext4_fsmap_head *head, + unsigned int count) +{ + memset(head, 0, sizeof(*head)); + head->fmh_count = count; + head->fmh_keys[1].fmr_device = UINT_MAX; + head->fmh_keys[1].fmr_physical = U64_MAX; + head->fmh_keys[1].fmr_owner = U64_MAX; + head->fmh_keys[1].fmr_flags = UINT_MAX; +} + +static void fsmap_expect_rec(struct kunit *test, const struct ext4_fsmap *rec, + u32 exp_dev, u64 exp_phys, u64 exp_len, + u64 exp_owner) +{ + KUNIT_EXPECT_EQ(test, (u32)rec->fmr_device, exp_dev); + KUNIT_EXPECT_EQ(test, rec->fmr_physical, exp_phys); + KUNIT_EXPECT_EQ(test, rec->fmr_length, exp_len); + KUNIT_EXPECT_EQ(test, rec->fmr_owner, exp_owner); + KUNIT_EXPECT_EQ(test, rec->fmr_flags, (u32)FMR_OF_SPECIAL_OWNER); +} + +/* + * Verify ext4_fsmap_from_internal() and ext4_fsmap_to_internal() block-to-byte + * and byte-to-block scaling across 1K, 4K, and 64K block sizes. + */ +static void test_fsmap_unit_conversions(struct kunit *test) +{ + static const unsigned int shifts[] = { 10, 12, 16 }; + struct fsmap_test_ctx *ctx; + struct ext4_fsmap internal = {}; + struct ext4_fsmap roundtrip = {}; + struct fsmap uapi = {}; + int i; + + ctx = fsmap_create_ctx(test, 12, 0, 1, 256); + + for (i = 0; i < ARRAY_SIZE(shifts); i++) { + unsigned int bits = shifts[i]; + + ctx->sb->s_blocksize_bits = bits; + ctx->sb->s_blocksize = 1U << bits; + + memset(&uapi, 0xaa, sizeof(uapi)); + internal.fmr_device = new_encode_dev(FSMAP_TEST_DATADEV); + internal.fmr_flags = FMR_OF_SPECIAL_OWNER; + internal.fmr_physical = 42; + internal.fmr_owner = EXT4_FMR_OWN_INODES; + internal.fmr_length = 17; + + ext4_fsmap_from_internal(ctx->sb, &uapi, &internal); + KUNIT_EXPECT_EQ(test, uapi.fmr_device, + (u32)internal.fmr_device); + KUNIT_EXPECT_EQ(test, uapi.fmr_flags, internal.fmr_flags); + KUNIT_EXPECT_EQ(test, uapi.fmr_physical, 42ULL << bits); + KUNIT_EXPECT_EQ(test, uapi.fmr_owner, EXT4_FMR_OWN_INODES); + KUNIT_EXPECT_EQ(test, uapi.fmr_offset, 0ULL); + KUNIT_EXPECT_EQ(test, uapi.fmr_length, 17ULL << bits); + KUNIT_EXPECT_EQ(test, uapi.fmr_reserved[0], 0U); + KUNIT_EXPECT_EQ(test, uapi.fmr_reserved[1], 0U); + KUNIT_EXPECT_EQ(test, uapi.fmr_reserved[2], 0U); + + /* Non-block-aligned byte tails truncate down to whole blocks */ + uapi.fmr_physical += (1ULL << bits) - 1; + uapi.fmr_length += (1ULL << bits) - 1; + ext4_fsmap_to_internal(ctx->sb, &roundtrip, &uapi); + KUNIT_EXPECT_EQ(test, roundtrip.fmr_device, + internal.fmr_device); + KUNIT_EXPECT_EQ(test, roundtrip.fmr_flags, internal.fmr_flags); + KUNIT_EXPECT_EQ(test, roundtrip.fmr_physical, 42ULL); + KUNIT_EXPECT_EQ(test, roundtrip.fmr_owner, EXT4_FMR_OWN_INODES); + KUNIT_EXPECT_EQ(test, roundtrip.fmr_length, 17ULL); + } +} + +/* + * Verify ext4_getfsmap() input flag, device ID, key ordering, out-of-range + * physical start, and missing group descriptor (-EFSCORRUPTED) checks. + */ +static void test_getfsmap_invalid_flags_devices_and_keys(struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *sink; + u32 datadev = new_encode_dev(FSMAP_TEST_DATADEV); + int err; + + sink = kunit_kzalloc(test, sizeof(*sink), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sink); + ctx = fsmap_create_ctx(test, 12, 0, 1, 256); + fsmap_set_group_tables(ctx, 0, 2, 3, 4); + fsmap_mark_clusters_used(ctx, 0, 0, 12); + + /* Invalid fmh_iflags -> -EINVAL */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_iflags = ~FMH_IF_VALID; + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + /* Unrecognized low or high device ID -> -EINVAL */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = new_encode_dev(MKDEV(9, 9)); + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[1].fmr_device = new_encode_dev(MKDEV(9, 9)); + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + /* Inverted device, physical block, or owner keys -> -EINVAL */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = UINT_MAX; + head.fmh_keys[1].fmr_device = 0; + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = datadev; + head.fmh_keys[1].fmr_device = datadev; + head.fmh_keys[0].fmr_physical = 50; + head.fmh_keys[1].fmr_physical = 40; + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + /* Equal low+len and high physical with owner 0 == 0 -> -EINVAL */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = datadev; + head.fmh_keys[1].fmr_device = datadev; + head.fmh_keys[0].fmr_physical = 20; + head.fmh_keys[0].fmr_length = 10; + head.fmh_keys[1].fmr_physical = 30; + head.fmh_keys[1].fmr_owner = 0; + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + /* Low key starting past eofs returns 0 entries cleanly */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = datadev; + head.fmh_keys[1].fmr_device = datadev; + head.fmh_keys[0].fmr_physical = 500; + head.fmh_keys[1].fmr_physical = 600; + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, head.fmh_entries, 0U); + KUNIT_EXPECT_EQ(test, head.fmh_oflags, (u32)FMH_OF_DEV_T); + + /* Missing group descriptor returns -EFSCORRUPTED */ + ctx->gdb_bh_arr[0] = NULL; + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + set_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + clear_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + ctx->gdb_bh_arr[0] = &ctx->gdb_bh; + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); +} + +/* + * Verify synthesis of fixed per-group metadata (SB, GDT, reserved GDT, block + * bitmap, inode bitmap, inode table), free extents, and EXT4_FMR_OWN_UNKNOWN + * gaps both in the middle and at the very end of the filesystem. + */ +static void test_getfsmap_fixed_metadata_and_unknown_gaps(struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *sink; + u32 datadev = new_encode_dev(FSMAP_TEST_DATADEV); + int err; + + sink = kunit_kzalloc(test, sizeof(*sink), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sink); + ctx = fsmap_create_ctx(test, 12, 0, 1, 256); + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(2); + + /* + * Group 0 layout [0, 256): + * 0 : superblock (OWN_FS, len 1) + * 1 : GDT (OWN_GDT, len 1) + * 2..3 : reserved GDT (OWN_RESV_GDT, len 2) + * 4 : block bitmap (OWN_BLKBM, len 1) + * 5 : inode bitmap (OWN_INOBM, len 1) + * 6..13 : inode table (OWN_INODES, len 8) + * 14..19 : allocated user data (OWN_UNKNOWN, len 6) + * 20..99 : free space (OWN_FREE, len 80) + * 100..109: allocated user data (OWN_UNKNOWN, len 10) + * 110..249: free space (OWN_FREE, len 140) + * 250..255: allocated user data at EOFS (OWN_UNKNOWN, len 6) + */ + fsmap_set_group_tables(ctx, 0, 4, 5, 6); + fsmap_mark_clusters_used(ctx, 0, 0, 20); + fsmap_mark_clusters_used(ctx, 0, 100, 10); + fsmap_mark_clusters_used(ctx, 0, 250, 6); + + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, head.fmh_entries, 11U); + KUNIT_ASSERT_EQ(test, sink->count, 11U); + + fsmap_expect_rec(test, &sink->recs[0], datadev, 0, 1, EXT4_FMR_OWN_FS); + fsmap_expect_rec(test, &sink->recs[1], datadev, 1, 1, EXT4_FMR_OWN_GDT); + fsmap_expect_rec(test, &sink->recs[2], datadev, 2, 2, + EXT4_FMR_OWN_RESV_GDT); + fsmap_expect_rec(test, &sink->recs[3], datadev, 4, 1, + EXT4_FMR_OWN_BLKBM); + fsmap_expect_rec(test, &sink->recs[4], datadev, 5, 1, + EXT4_FMR_OWN_INOBM); + fsmap_expect_rec(test, &sink->recs[5], datadev, 6, 8, + EXT4_FMR_OWN_INODES); + fsmap_expect_rec(test, &sink->recs[6], datadev, 14, 6, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[7], datadev, 20, 80, + EXT4_FMR_OWN_FREE); + fsmap_expect_rec(test, &sink->recs[8], datadev, 100, 10, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[9], datadev, 110, 140, + EXT4_FMR_OWN_FREE); + fsmap_expect_rec(test, &sink->recs[10], datadev, 250, 6, + EXT4_FMR_OWN_UNKNOWN); +} + +/* + * Verify flex_bg adjacent fixed-metadata merging via + * ext4_getfsmap_merge_fixed_metadata() and cross-group free-extent coalescing + * via info->gfi_lastfree. + */ +static void test_getfsmap_cross_group_free_and_fixed_meta_coalescing( + struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *sink; + u32 datadev = new_encode_dev(FSMAP_TEST_DATADEV); + int err; + + sink = kunit_kzalloc(test, sizeof(*sink), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sink); + ctx = fsmap_create_ctx(test, 12, 0, 2, 256); + /* SPARSE_SUPER2 with 0 backup groups -> group 1 has no SB/GDT */ + ctx->es.s_feature_compat = cpu_to_le32(EXT4_FEATURE_COMPAT_SPARSE_SUPER2); + + /* + * Flex_bg-packed metadata in group 0 for both groups 0 and 1: + * 0 : SB (len 1) + * 1 : GDT (len 1) + * 2..3 : group 0 + group 1 block bitmaps -> merged len 2! + * 4..5 : group 0 + group 1 inode bitmaps -> merged len 2! + * 6..21 : group 0 + group 1 inode tables (8 + 8) -> merged len 16! + * 22..255 (grp 0) + 256..511 (grp 1): contiguous free space across + * group boundary -> coalesced via gfi_lastfree into [22, 512) len 490! + */ + fsmap_set_group_tables(ctx, 0, 2, 4, 6); + fsmap_set_group_tables(ctx, 1, 3, 5, 14); + fsmap_mark_clusters_used(ctx, 0, 0, 22); + + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, head.fmh_entries, 6U); + + fsmap_expect_rec(test, &sink->recs[0], datadev, 0, 1, EXT4_FMR_OWN_FS); + fsmap_expect_rec(test, &sink->recs[1], datadev, 1, 1, EXT4_FMR_OWN_GDT); + fsmap_expect_rec(test, &sink->recs[2], datadev, 2, 2, + EXT4_FMR_OWN_BLKBM); + fsmap_expect_rec(test, &sink->recs[3], datadev, 4, 2, + EXT4_FMR_OWN_INOBM); + fsmap_expect_rec(test, &sink->recs[4], datadev, 6, 16, + EXT4_FMR_OWN_INODES); + fsmap_expect_rec(test, &sink->recs[5], datadev, 22, 490, + EXT4_FMR_OWN_FREE); +} + +/* + * Verify 1K blocksize (s_first_data_block == 1), bigalloc cluster-to-block + * scaling, and META_BG suppression of reserved GDT blocks. + */ +static void test_getfsmap_1k_bofs_bigalloc_and_meta_bg(struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *sink; + u32 datadev = new_encode_dev(FSMAP_TEST_DATADEV); + int err; + + sink = kunit_kzalloc(test, sizeof(*sink), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sink); + + /* + * 1K blocks (s_first_data_block = 1), cluster_bits = 2 (4 blks/clu), + * 1 group of 256 blocks (64 clusters) covering fsblks [1, 257). + * Enable META_BG with s_first_meta_bg = 0 and verify s_reserved_gdt_blocks + * is ignored. + */ + ctx = fsmap_create_ctx(test, 10, 2, 1, 256); + ext4_set_feature_meta_bg(ctx->sb); + ext4_set_feature_bigalloc(ctx->sb); + ctx->es.s_first_meta_bg = 0; + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(5); + + /* + * Cluster 0 = fsblks [1, 5): SB(1), GDT(2), BLKBM(3), INOBM(4) + * Clusters 1..2 = fsblks [5, 13): INODES (len 8) + * Clusters 3..4 = fsblks [13, 21): allocated data (OWN_UNKNOWN, len 8) + * Clusters 5..63 = fsblks [21, 257): free (OWN_FREE, len 236) + */ + fsmap_set_group_tables(ctx, 0, 3, 4, 5); + fsmap_mark_clusters_used(ctx, 0, 0, 5); + + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + /* Note: block 0 before s_first_data_block=1 is reported as gap [0, 1) */ + KUNIT_ASSERT_EQ(test, head.fmh_entries, 8U); + + fsmap_expect_rec(test, &sink->recs[0], datadev, 0, 1, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[1], datadev, 1, 1, EXT4_FMR_OWN_FS); + fsmap_expect_rec(test, &sink->recs[2], datadev, 2, 1, EXT4_FMR_OWN_GDT); + fsmap_expect_rec(test, &sink->recs[3], datadev, 3, 1, + EXT4_FMR_OWN_BLKBM); + fsmap_expect_rec(test, &sink->recs[4], datadev, 4, 1, + EXT4_FMR_OWN_INOBM); + fsmap_expect_rec(test, &sink->recs[5], datadev, 5, 8, + EXT4_FMR_OWN_INODES); + fsmap_expect_rec(test, &sink->recs[6], datadev, 13, 8, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[7], datadev, 21, 236, + EXT4_FMR_OWN_FREE); +} + +/* + * Verify count-only queries (fmh_count == 0), bounded pagination with + * continuation keys (non-zero low fmr_length), and formatter abort propagation. + */ +static void test_getfsmap_count_only_pagination_and_abort(struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *full, *page, *cb_abort; + unsigned int collected = 0; + int err; + + full = kunit_kzalloc(test, sizeof(*full), GFP_KERNEL); + page = kunit_kzalloc(test, sizeof(*page), GFP_KERNEL); + cb_abort = kunit_kzalloc(test, sizeof(*cb_abort), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, full); + KUNIT_ASSERT_NOT_NULL(test, page); + KUNIT_ASSERT_NOT_NULL(test, cb_abort); + + ctx = fsmap_create_ctx(test, 12, 0, 1, 256); + fsmap_set_group_tables(ctx, 0, 2, 3, 4); + fsmap_mark_clusters_used(ctx, 0, 0, 16); + + /* Reference full run: SB(0), GDT(1), BLKBM(2), INOBM(3), INODES(4..11), + * UNKNOWN(12..15), FREE(16..255) -> 7 records. + */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, full); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, full->count, 7U); + + /* 1. Count-only mode (fmh_count == 0) does not invoke formatter */ + fsmap_init_full_range_head(&head, 0); + err = ext4_getfsmap(ctx->sb, &head, NULL, NULL); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, head.fmh_entries, 7U); + + /* 2. Paginate 2 records at a time using last record as low key */ + fsmap_init_full_range_head(&head, 2); + while (true) { + unsigned int prev_count = page->count; + + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, page); + collected += head.fmh_entries; + if (err == 0) + break; + KUNIT_ASSERT_EQ(test, err, EXT4_QUERY_RANGE_ABORT); + KUNIT_ASSERT_EQ(test, head.fmh_entries, 2U); + KUNIT_ASSERT_GT(test, page->count, prev_count); + head.fmh_keys[0] = page->recs[page->count - 1]; + } + KUNIT_ASSERT_EQ(test, collected, 7U); + KUNIT_ASSERT_EQ(test, page->count, 7U); + for (unsigned int i = 0; i < 7; i++) { + KUNIT_EXPECT_EQ(test, page->recs[i].fmr_physical, + full->recs[i].fmr_physical); + KUNIT_EXPECT_EQ(test, page->recs[i].fmr_length, + full->recs[i].fmr_length); + KUNIT_EXPECT_EQ(test, page->recs[i].fmr_owner, + full->recs[i].fmr_owner); + } + + /* 3. Formatter-initiated abort stops immediately */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + cb_abort->abort_after = 3; + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, cb_abort); + KUNIT_EXPECT_EQ(test, err, EXT4_QUERY_RANGE_ABORT); + KUNIT_EXPECT_EQ(test, cb_abort->count, 3U); + + /* 4. Formatter error return propagates directly */ + memset(cb_abort, 0, sizeof(*cb_abort)); + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + cb_abort->fail_err = -EFAULT; + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, cb_abort); + KUNIT_EXPECT_EQ(test, err, -EFAULT); + KUNIT_EXPECT_EQ(test, cb_abort->count, 0U); +} + +/* + * Verify external journal device reporting (EXT4_FMR_OWN_LOG and leading gap) + * across multi-device wildcard queries and log-device-targeted queries. + */ +static void test_getfsmap_external_logdev_and_multi_device(struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *sink; + u32 datadev = new_encode_dev(FSMAP_TEST_DATADEV); + u32 logdev = new_encode_dev(FSMAP_TEST_LOGDEV); + int err; + + sink = kunit_kzalloc(test, sizeof(*sink), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sink); + ctx = fsmap_create_ctx(test, 12, 0, 1, 128); + fsmap_set_group_tables(ctx, 0, 2, 3, 4); + fsmap_mark_clusters_used(ctx, 0, 0, 12); + + KUNIT_ASSERT_PTR_EQ(test, file_bdev(&ctx->log_bdev_file), + &ctx->log_bdev.bdev); + ctx->mock_journal.j_blk_offset = 16; + ctx->mock_journal.j_total_len = 64; + ctx->sbi.s_journal = &ctx->mock_journal; + ctx->sbi.s_journal_bdev_file = &ctx->log_bdev_file; + + /* Multi-device query [0, UINT_MAX] emits datadev (6 recs) + logdev (2) */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, head.fmh_entries, 8U); + KUNIT_EXPECT_EQ(test, (u32)sink->recs[0].fmr_device, datadev); + fsmap_expect_rec(test, &sink->recs[6], logdev, 0, 16, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[7], logdev, 16, 64, + EXT4_FMR_OWN_LOG); + + /* Targeted query against only logdev starting at 0 */ + memset(sink, 0, sizeof(*sink)); + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = logdev; + head.fmh_keys[1].fmr_device = logdev; + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, head.fmh_entries, 2U); + fsmap_expect_rec(test, &sink->recs[0], logdev, 0, 16, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[1], logdev, 16, 64, + EXT4_FMR_OWN_LOG); + + /* Logdev query with physical > 0 returns 0 entries */ + memset(sink, 0, sizeof(*sink)); + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = logdev; + head.fmh_keys[0].fmr_physical = 80; + head.fmh_keys[1].fmr_device = logdev; + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, head.fmh_entries, 0U); +} + +static struct kunit_case fsmap_test_cases[] = { + KUNIT_CASE(test_fsmap_unit_conversions), + KUNIT_CASE(test_getfsmap_invalid_flags_devices_and_keys), + KUNIT_CASE(test_getfsmap_fixed_metadata_and_unknown_gaps), + KUNIT_CASE(test_getfsmap_cross_group_free_and_fixed_meta_coalescing), + KUNIT_CASE(test_getfsmap_1k_bofs_bigalloc_and_meta_bg), + KUNIT_CASE(test_getfsmap_count_only_pagination_and_abort), + KUNIT_CASE(test_getfsmap_external_logdev_and_multi_device), + {} +}; + +static struct kunit_suite fsmap_test_suite = { + .name = "ext4_fsmap_test", + .test_cases = fsmap_test_cases, +}; + +kunit_test_suites(&fsmap_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 FS_IOC_GETFSMAP implementation"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/fsmap.c b/fs/ext4/fsmap.c index 8b1138d2dc8efe..f41c2298d1969c 100644 --- a/fs/ext4/fsmap.c +++ b/fs/ext4/fsmap.c @@ -26,6 +26,7 @@ void ext4_fsmap_from_internal(struct super_block *sb, struct fsmap *dest, dest->fmr_reserved[1] = 0; dest->fmr_reserved[2] = 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fsmap_from_internal); /* Convert an fsmap to an ext4_fsmap. */ void ext4_fsmap_to_internal(struct super_block *sb, struct ext4_fsmap *dest, @@ -37,6 +38,7 @@ void ext4_fsmap_to_internal(struct super_block *sb, struct ext4_fsmap *dest, dest->fmr_owner = src->fmr_owner; dest->fmr_length = src->fmr_length >> sb->s_blocksize_bits; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fsmap_to_internal); /* getfsmap query state */ struct ext4_getfsmap_info { @@ -790,3 +792,4 @@ int ext4_getfsmap(struct super_block *sb, struct ext4_fsmap_head *head, head->fmh_oflags = FMH_OF_DEV_T; return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_getfsmap); diff --git a/fs/ext4/mballoc.c b/fs/ext4/mballoc.c index b346f8bbee8970..81a4f45906d337 100644 --- a/fs/ext4/mballoc.c +++ b/fs/ext4/mballoc.c @@ -7151,6 +7151,9 @@ ext4_mballoc_query_range( struct ext4_buddy e4b; int error; + KUNIT_STATIC_STUB_REDIRECT(ext4_mballoc_query_range, sb, group, first, + end, meta_formatter, formatter, priv); + error = ext4_mb_load_buddy(sb, group, &e4b); if (error) return error; From 0940fb9b934c9d33957804cca20db725d943d386 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:25:23 +0000 Subject: [PATCH 1575/2102] ext4: add KUnit tests for fs/ext4/move_extent.c Add a KUnit test suite (ext4_move_extent_test) covering online extent swapping and validation helpers in fs/ext4/move_extent.c: - Ordered i_data_sem lock acquisition/release in ext4_double_down_write_data_sem() and ext4_double_up_write_data_sem() - File, feature, and mode checks in mext_check_validity() (same inode, cross-sb, non-regular, bigalloc, DAX, data journaling, encrypted, non-extent, SUID/SGID, immutable/append, swapfile, quota, zero size) - Sub-page alignment, EXT_MAX_BLOCKS bounds, and EOF clamping in mext_check_adjust_range() - End-to-end ext4_move_extents() across origin/donor holes, unwritten extent moves, written MEXT_COPY_DATA with extent splitting and page cache preservation, unwritten-origin zeroing, and -EBUSY release Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 3 +- fs/ext4/ext4.h | 8 + fs/ext4/move_extent-test.c | 1023 ++++++++++++++++++++++++++++++++++++ fs/ext4/move_extent.c | 21 +- 4 files changed, 1052 insertions(+), 3 deletions(-) create mode 100644 fs/ext4/move_extent-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index e1964407be242e..5cf735df76567b 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -23,7 +23,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ block_validity-test.o super-test.o \ sysfs-test.o ioctl-test.o \ resize-test.o migrate-test.o \ - indirect-test.o fsmap-test.o + indirect-test.o fsmap-test.o \ + move_extent-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index 03689d55e7513e..29277a79c65bd8 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -4250,6 +4250,14 @@ extern void ext4_double_up_write_data_sem(struct inode *orig_inode, extern int ext4_move_extents(struct file *o_filp, struct file *d_filp, __u64 start_orig, __u64 start_donor, __u64 len, __u64 *moved_len); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_mext_check_validity_test(struct inode *orig_inode, + struct inode *donor_inode); +extern int ext4_mext_check_adjust_range_test(struct inode *orig_inode, + struct inode *donor_inode, + __u64 orig_start, + __u64 donor_start, __u64 *len); +#endif /* page-io.c */ /* diff --git a/fs/ext4/move_extent-test.c b/fs/ext4/move_extent-test.c new file mode 100644 index 00000000000000..a3e002f1410932 --- /dev/null +++ b/fs/ext4/move_extent-test.c @@ -0,0 +1,1023 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/move_extent.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_extents.h" +#include "ext4_jbd2.h" + +#define MEXT_TEST_BLK_SIZE 4096U +#define MEXT_TEST_BLK_BITS 12U +#define MEXT_TEST_BLOCKS_PER_GRP 32768U +#define MEXT_TEST_NGROUPS 8U +#define MEXT_TEST_FIRST_DATA_BLK 1U +#define MEXT_TEST_TOTAL_BLKS (MEXT_TEST_FIRST_DATA_BLK + \ + MEXT_TEST_NGROUPS * \ + MEXT_TEST_BLOCKS_PER_GRP) +#define MEXT_MAX_META_BLKS 16U +#define MEXT_META_BASE_PBLK 1000U + +struct mext_meta_blk { + ext4_fsblk_t pblk; + struct buffer_head bh; + u8 data[MEXT_TEST_BLK_SIZE]; + bool in_use; +}; + +struct mext_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct address_space bdev_mapping; + struct buffer_head sbh; + u8 sbh_data[MEXT_TEST_BLK_SIZE]; + struct mext_meta_blk *meta_blks; + ext4_fsblk_t next_meta_pblk; + struct inode *orig_inode; + struct inode *donor_inode; + struct dentry orig_dentry; + struct dentry donor_dentry; + struct file orig_file; + struct file donor_file; + bool es_shrinker_inited; + bool counters_inited; +}; + +static struct kunit *active_mext_test; + +static void mext_noop_work(struct work_struct *work) +{ +} + +static void mext_noop_timer(struct timer_list *t) +{ +} + +static unsigned long mext_dummy_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long mext_dummy_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +static struct inode *mext_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void mext_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void mext_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **mext_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *mext_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations mext_dummy_qops = { + .get_reserved_space = mext_get_reserved_space, +}; +#endif + +static const struct super_operations mext_test_sops = { + .alloc_inode = mext_test_alloc_inode, + .free_inode = mext_test_free_inode, + .evict_inode = mext_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = mext_get_dquots, +#endif +}; + +static int mext_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static int mext_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static struct file_system_type mext_test_fs_type = { + .name = "ext4_move_extent_test", + .init_fs_context = mext_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static int mext_ext_dirty_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct ext4_ext_path *path) +{ + if (path && path->p_bh) { + ext4_extent_block_csum_set_test(inode, + ext_block_hdr(path->p_bh)); + set_buffer_verified(path->p_bh); + } + return 0; +} + +static int mext_handle_dirty_metadata_stub(const char *where, + unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + if (bh) + set_buffer_uptodate(bh); + return 0; +} + +static int mext_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + return 0; +} + +static struct buffer_head *mext_ext_getblk_stub(struct inode *inode, + ext4_fsblk_t pblk, + gfp_t gfp_flags) +{ + struct kunit *test = active_mext_test; + struct mext_test_ctx *ctx; + struct mext_meta_blk *slot = NULL; + unsigned int i; + + if (!test) + return NULL; + ctx = test->priv; + if (!ctx || !ctx->meta_blks) + return NULL; + + for (i = 0; i < MEXT_MAX_META_BLKS; i++) { + if (ctx->meta_blks[i].in_use && + ctx->meta_blks[i].pblk == pblk) { + slot = &ctx->meta_blks[i]; + break; + } + } + + if (!slot) { + for (i = 0; i < MEXT_MAX_META_BLKS; i++) { + if (!ctx->meta_blks[i].in_use) { + slot = &ctx->meta_blks[i]; + break; + } + } + if (!slot) + return NULL; + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->pblk = pblk; + slot->bh.b_data = slot->data; + slot->bh.b_size = inode->i_sb->s_blocksize; + slot->bh.b_blocknr = pblk; + slot->bh.b_bdev = inode->i_sb->s_bdev; + atomic_set(&slot->bh.b_count, 1); + set_buffer_uptodate(&slot->bh); + set_buffer_mapped(&slot->bh); + } + + get_bh(&slot->bh); + return &slot->bh; +} + +static ext4_fsblk_t mext_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, + int *errp) +{ + struct kunit *test = active_mext_test; + struct mext_test_ctx *ctx; + ext4_fsblk_t pblk; + + if (!test) { + *errp = -EIO; + return 0; + } + ctx = test->priv; + pblk = ctx->next_meta_pblk; + ctx->next_meta_pblk += ar->len; + *errp = 0; + return pblk; +} + +static void mext_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ +} + +static int mext_journal_data_mode_stub(struct inode *inode) +{ + return EXT4_INODE_JOURNAL_DATA_MODE; +} + +static void mext_init_mock_file(struct file *filp, struct dentry *dentry, + struct inode *inode) +{ + struct file tmp = { + .f_path = { .dentry = dentry }, + .f_inode = inode, + .f_mapping = inode->i_mapping, + .f_mode = FMODE_READ | FMODE_WRITE | FMODE_NOCMTIME, + }; + + memset(dentry, 0, sizeof(*dentry)); + dentry->d_inode = inode; + memcpy(filp, &tmp, sizeof(*filp)); +} + +static struct inode *mext_create_test_inode(struct kunit *test, + struct super_block *sb, + unsigned long ino, + ext4_lblk_t size_blks) +{ + struct ext4_extent_header *eh; + struct inode *inode; + + inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + + inode->i_ino = ino; + inode->i_mode = S_IFREG | 0644; + set_nlink(inode, 1); + inode->i_blkbits = sb->s_blocksize_bits; + /* + * Note: leave S_NOQUOTA clear so ext4_is_quota_file(inode) is false. + */ + inode->i_flags |= S_NOSEC; + inode_state_set_raw(inode, + I_DIRTY_SYNC | I_DIRTY_DATASYNC | I_DIRTY_PAGES); + mapping_set_gfp_mask(&inode->i_data, GFP_KERNEL); + + EXT4_I(inode)->i_csum_seed = 0x13572468U; + EXT4_I(inode)->i_disksize = (loff_t)size_blks << sb->s_blocksize_bits; + i_size_write(inode, EXT4_I(inode)->i_disksize); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_set_aops(inode); + + eh = ext_inode_hdr(inode); + memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data)); + eh->eh_magic = EXT4_EXT_MAGIC; + eh->eh_entries = 0; + eh->eh_max = cpu_to_le16(ext4_ext_space_root_idx_test(inode, 0)); + eh->eh_depth = 0; + + return inode; +} + +static void mext_insert_extent(struct kunit *test, struct inode *inode, + ext4_lblk_t lblk, u16 len, ext4_fsblk_t pblk, + bool unwritten) +{ + struct ext4_extent newex = {}; + struct ext4_ext_path *path; + + newex.ee_block = cpu_to_le32(lblk); + newex.ee_len = cpu_to_le16(len); + if (unwritten) + ext4_ext_mark_unwritten(&newex); + ext4_ext_store_pblock(&newex, pblk); + + inode_lock(inode); + down_write(&EXT4_I(inode)->i_data_sem); + path = ext4_find_extent(inode, lblk, NULL, 0); + if (!IS_ERR(path)) + path = ext4_ext_insert_extent(NULL, inode, path, &newex, 0); + up_write(&EXT4_I(inode)->i_data_sem); + inode_unlock(inode); + + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + ext4_free_ext_path(path); +} + +static void mext_populate_folio_block(struct kunit *test, struct inode *inode, + ext4_lblk_t lblk, u8 pattern) +{ + loff_t pos = (loff_t)lblk << inode->i_blkbits; + size_t bsize = i_blocksize(inode); + struct folio *folio; + u8 *addr; + + folio = __filemap_get_folio(inode->i_mapping, pos >> PAGE_SHIFT, + FGP_CREAT | FGP_LOCK, GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + + addr = folio_address(folio); + memset(addr + offset_in_folio(folio, pos), pattern, bsize); + folio_mark_uptodate(folio); + folio_unlock(folio); + folio_put(folio); +} + +static void mext_assert_mapped_block(struct kunit *test, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t exp_pblk, + unsigned int exp_flag) +{ + struct ext4_map_blocks map = { + .m_lblk = lblk, + .m_len = 1, + }; + int ret; + + inode_lock(inode); + ret = ext4_map_blocks(NULL, inode, &map, 0); + inode_unlock(inode); + + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, map.m_pblk, exp_pblk); + KUNIT_EXPECT_TRUE(test, (map.m_flags & exp_flag) != 0); + if (exp_flag == EXT4_MAP_MAPPED) + KUNIT_EXPECT_EQ(test, map.m_flags & EXT4_MAP_UNWRITTEN, 0U); + else if (exp_flag == EXT4_MAP_UNWRITTEN) + KUNIT_EXPECT_EQ(test, map.m_flags & EXT4_MAP_MAPPED, 0U); +} + +static void mext_cleanup_ctx(void *data) +{ + struct mext_test_ctx *ctx = data; + + active_mext_test = NULL; + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + if (ctx->orig_inode) { + iput(ctx->orig_inode); + ctx->orig_inode = NULL; + } + if (ctx->donor_inode) { + iput(ctx->donor_inode); + ctx->donor_inode = NULL; + } + + if (ctx->sb) { + deactivate_super(ctx->sb); + ctx->sb = NULL; + } + rcu_barrier(); + + if (ctx->es_shrinker_inited) { + ext4_es_unregister_shrinker(&ctx->sbi); + ext4_es_destroy_stats(&ctx->sbi); + ctx->es_shrinker_inited = false; + } + if (ctx->counters_inited) { + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + ctx->counters_inited = false; + } + + if (ctx->bdev.bd_stats) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + } +} + +static struct mext_test_ctx *mext_setup_ctx(struct kunit *test) +{ + struct mext_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + int err; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->es = kunit_kzalloc(test, sizeof(*ctx->es), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->es); + ctx->meta_blks = kunit_kcalloc(test, MEXT_MAX_META_BLKS, + sizeof(*ctx->meta_blks), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->meta_blks); + ctx->next_meta_pblk = MEXT_META_BASE_PBLK; + + fc = fs_context_for_mount(&mext_test_fs_type, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fc)); + sb = sget_fc(fc, NULL, mext_set_super); + put_fs_context(fc); + KUNIT_ASSERT_FALSE(test, IS_ERR(sb)); + up_write(&sb->s_umount); + ctx->sb = sb; + + INIT_WORK(&ctx->sbi.s_sb_upd_work, mext_noop_work); + timer_setup(&ctx->sbi.s_err_report, mext_noop_timer, 0); + + err = kunit_add_action_or_reset(test, mext_cleanup_ctx, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->bdev.bd_stats != NULL); + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bdev_mapping; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + + sb->s_bdev = &ctx->bdev; + sb->s_blocksize = MEXT_TEST_BLK_SIZE; + sb->s_blocksize_bits = MEXT_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_magic = EXT4_SUPER_MAGIC; + sb->s_op = &mext_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &mext_dummy_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_fs_info = &ctx->sbi; + strscpy(sb->s_id, "ext4_mext_kunit", sizeof(sb->s_id)); + + ctx->sbh.b_data = ctx->sbh_data; + ctx->sbh.b_size = MEXT_TEST_BLK_SIZE; + ctx->sbh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sbh.b_count, 2); + set_buffer_uptodate(&ctx->sbh); + clear_buffer_mapped(&ctx->sbh); + + ctx->es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es->s_first_data_block = cpu_to_le32(MEXT_TEST_FIRST_DATA_BLK); + ctx->es->s_log_block_size = cpu_to_le32(2); + ctx->es->s_log_cluster_size = cpu_to_le32(2); + ctx->es->s_blocks_per_group = cpu_to_le32(MEXT_TEST_BLOCKS_PER_GRP); + ctx->es->s_clusters_per_group = cpu_to_le32(MEXT_TEST_BLOCKS_PER_GRP); + ctx->es->s_inodes_per_group = cpu_to_le32(8192); + ctx->es->s_inodes_count = cpu_to_le32(MEXT_TEST_NGROUPS * 8192); + ctx->es->s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_EXTENTS); + ext4_blocks_count_set(ctx->es, MEXT_TEST_TOTAL_BLKS); + + bgl_lock_init(&ctx->bgl); + ctx->sbi.s_sb = sb; + ctx->sbi.s_es = ctx->es; + ctx->sbi.s_sbh = &ctx->sbh; + ctx->sbi.s_blockgroup_lock = &ctx->bgl; + ctx->sbi.s_blocks_per_group = MEXT_TEST_BLOCKS_PER_GRP; + ctx->sbi.s_clusters_per_group = MEXT_TEST_BLOCKS_PER_GRP; + ctx->sbi.s_cluster_ratio = 1; + ctx->sbi.s_cluster_bits = 0; + ctx->sbi.s_groups_count = MEXT_TEST_NGROUPS; + ctx->sbi.s_desc_size = EXT4_MIN_DESC_SIZE; + ctx->sbi.s_desc_per_block = MEXT_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE; + ctx->sbi.s_inodes_per_group = 8192; + ctx->sbi.s_inode_size = sizeof(struct ext4_inode); + ctx->sbi.s_inodes_per_block = MEXT_TEST_BLK_SIZE / + sizeof(struct ext4_inode); + ctx->sbi.s_bitmap_maxbytes = MAX_LFS_FILESIZE; + set_opt(sb, ERRORS_CONT); + + mutex_init(&ctx->sbi.s_orphan_lock); + INIT_LIST_HEAD(&ctx->sbi.s_orphan); + spin_lock_init(&ctx->sbi.s_bdev_wb_lock); + spin_lock_init(&ctx->sbi.s_error_lock); + spin_lock_init(&ctx->sbi.s_md_lock); + INIT_LIST_HEAD(&ctx->sbi.s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&ctx->sbi.s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&ctx->sbi.s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&ctx->sbi.s_fc_dentry_q[FC_Q_STAGING]); + mutex_init(&ctx->sbi.s_fc_lock); + ratelimit_state_init(&ctx->sbi.s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + ratelimit_state_init(&ctx->sbi.s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + ratelimit_state_init(&ctx->sbi.s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + + err = percpu_counter_init(&ctx->sbi.s_freeclusters_counter, 65536, + GFP_KERNEL); + KUNIT_ASSERT_EQ(test, err, 0); + err = percpu_counter_init(&ctx->sbi.s_dirtyclusters_counter, 0, + GFP_KERNEL); + if (err) { + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + KUNIT_FAIL_AND_ABORT(test, "dirtyclusters counter init failed"); + } + ctx->counters_inited = true; + + err = ext4_es_register_shrinker(&ctx->sbi); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->sbi.s_es_shrinker->count_objects = mext_dummy_shrinker_count; + ctx->sbi.s_es_shrinker->scan_objects = mext_dummy_shrinker_scan; + ctx->es_shrinker_inited = true; + + ctx->orig_inode = mext_create_test_inode(test, sb, 21, 16); + ctx->donor_inode = mext_create_test_inode(test, sb, 22, 16); + mext_init_mock_file(&ctx->orig_file, &ctx->orig_dentry, + ctx->orig_inode); + mext_init_mock_file(&ctx->donor_file, &ctx->donor_dentry, + ctx->donor_inode); + + test->priv = ctx; + active_mext_test = test; + + kunit_activate_static_stub(test, __ext4_ext_dirty, + mext_ext_dirty_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + mext_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + mext_mark_inode_dirty_stub); + kunit_activate_static_stub(test, ext4_ext_getblk, + mext_ext_getblk_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + mext_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + mext_free_blocks_stub); + + return ctx; +} + +static void test_double_data_sem_lock_order(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *low = ctx->orig_inode; + struct inode *high = ctx->donor_inode; + + if (low > high) + swap(low, high); + + /* Acquire with first < second */ + ext4_double_down_write_data_sem(low, high); + KUNIT_EXPECT_TRUE(test, rwsem_is_locked(&EXT4_I(low)->i_data_sem)); + KUNIT_EXPECT_TRUE(test, rwsem_is_locked(&EXT4_I(high)->i_data_sem)); + ext4_double_up_write_data_sem(low, high); + KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&EXT4_I(low)->i_data_sem)); + KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&EXT4_I(high)->i_data_sem)); + + /* Acquire with first > second */ + ext4_double_down_write_data_sem(high, low); + KUNIT_EXPECT_TRUE(test, rwsem_is_locked(&EXT4_I(low)->i_data_sem)); + KUNIT_EXPECT_TRUE(test, rwsem_is_locked(&EXT4_I(high)->i_data_sem)); + ext4_double_up_write_data_sem(high, low); + KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&EXT4_I(low)->i_data_sem)); + KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&EXT4_I(high)->i_data_sem)); +} + +static void test_mext_check_validity_rejections(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *orig = ctx->orig_inode; + struct inode *donor = ctx->donor_inode; + struct super_block *other_sb; + __u64 moved_len = 99; + int ret; + + /* Valid baseline */ + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), 0); + + /* Same inode rejected both directly and via ext4_move_extents() */ + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, orig), + -EINVAL); + ret = ext4_move_extents(&ctx->orig_file, &ctx->orig_file, 0, 0, 1, + &moved_len); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + KUNIT_EXPECT_EQ(test, moved_len, 0ULL); + + /* Cross-superblock rejected */ + other_sb = kunit_kzalloc(test, sizeof(*other_sb), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, other_sb); + donor->i_sb = other_sb; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + donor->i_sb = ctx->sb; + + /* Non-regular files rejected */ + orig->i_mode = S_IFIFO | 0644; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + ret = ext4_move_extents(&ctx->orig_file, &ctx->donor_file, 0, 0, 1, + &moved_len); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + orig->i_mode = S_IFREG | 0644; + + donor->i_mode = S_IFDIR | 0755; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + donor->i_mode = S_IFREG | 0644; + + /* Bigalloc feature rejected */ + ext4_set_feature_bigalloc(ctx->sb); + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + ext4_clear_feature_bigalloc(ctx->sb); + +#if IS_ENABLED(CONFIG_FS_DAX) + /* DAX inode rejected */ + orig->i_flags |= S_DAX; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + orig->i_flags &= ~S_DAX; +#endif + + /* Data journaling mode rejected */ + kunit_activate_static_stub(test, ext4_inode_journal_mode, + mext_journal_data_mode_stub); + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + kunit_deactivate_static_stub(test, ext4_inode_journal_mode); + + /* Encrypted inode rejected */ + donor->i_flags |= S_ENCRYPTED; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + donor->i_flags &= ~S_ENCRYPTED; + + /* Non-extent inode rejected */ + ext4_clear_inode_flag(orig, EXT4_INODE_EXTENTS); + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + ext4_set_inode_flag(orig, EXT4_INODE_EXTENTS); + + /* SUID / SGID on donor rejected */ + donor->i_mode |= S_ISUID; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + donor->i_mode = (donor->i_mode & ~S_ISUID) | S_ISGID; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + donor->i_mode &= ~S_ISGID; + + /* Immutable / append-only donor rejected with -EPERM */ + donor->i_flags |= S_IMMUTABLE; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EPERM); + donor->i_flags = (donor->i_flags & ~S_IMMUTABLE) | S_APPEND; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EPERM); + donor->i_flags &= ~S_APPEND; + + /* Swapfile rejected with -ETXTBSY */ + orig->i_flags |= S_SWAPFILE; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -ETXTBSY); + orig->i_flags &= ~S_SWAPFILE; + + /* Quota file (S_NOQUOTA without EXT4_INODE_EA_INODE) rejected */ + orig->i_flags |= S_NOQUOTA; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + ext4_set_inode_flag(orig, EXT4_INODE_EA_INODE); + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), 0); + ext4_clear_inode_flag(orig, EXT4_INODE_EA_INODE); + orig->i_flags &= ~S_NOQUOTA; + + /* Zero-byte file rejected with -EINVAL */ + i_size_write(donor, 0); + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + i_size_write(donor, EXT4_I(donor)->i_disksize); +} + +static void test_mext_check_adjust_range(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *orig = ctx->orig_inode; + struct inode *donor = ctx->donor_inode; + __u64 len; + int ret; + + /* Sub-page block alignment check when blocksize (1024) < PAGE_SIZE */ + orig->i_blkbits = 10; + donor->i_blkbits = 10; + i_size_write(orig, max_t(loff_t, 32 * 1024, 4 * PAGE_SIZE)); + i_size_write(donor, max_t(loff_t, 32 * 1024, 4 * PAGE_SIZE)); + + len = 4; + ret = ext4_mext_check_adjust_range_test(orig, donor, 1, 2, &len); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + len = 4; + ret = ext4_mext_check_adjust_range_test(orig, donor, 1, + 1 + (PAGE_SIZE >> 10), &len); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, len, 4ULL); + + orig->i_blkbits = MEXT_TEST_BLK_BITS; + donor->i_blkbits = MEXT_TEST_BLK_BITS; + + /* EXT_MAX_BLOCKS boundary and sum-overflow checks */ + len = 1; + KUNIT_EXPECT_EQ(test, + ext4_mext_check_adjust_range_test(orig, donor, + EXT_MAX_BLOCKS, + EXT_MAX_BLOCKS, &len), + -EINVAL); + + len = (u64)EXT_MAX_BLOCKS + 1; + KUNIT_EXPECT_EQ(test, + ext4_mext_check_adjust_range_test(orig, donor, 0, 0, + &len), + -EINVAL); + + len = 4; + KUNIT_EXPECT_EQ(test, + ext4_mext_check_adjust_range_test(orig, donor, + EXT_MAX_BLOCKS - 4, + EXT_MAX_BLOCKS - 4, + &len), + -EINVAL); + + /* Clamping to shorter EOF (including partial trailing block i_size) */ + i_size_write(orig, 5 * MEXT_TEST_BLK_SIZE + 100); /* orig_eof = 6 */ + i_size_write(donor, 4 * MEXT_TEST_BLK_SIZE); /* donor_eof = 4 */ + + len = 12; + ret = ext4_mext_check_adjust_range_test(orig, donor, 1, 1, &len); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, len, 3ULL); + + /* Start at or beyond EOF clamps len to 0 and returns -EINVAL */ + len = 4; + ret = ext4_mext_check_adjust_range_test(orig, donor, 4, 4, &len); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + KUNIT_EXPECT_EQ(test, len, 0ULL); +} + +static void test_move_extents_holes_and_unwritten(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *orig = ctx->orig_inode; + struct inode *donor = ctx->donor_inode; + __u64 moved_len = 0; + int ret; + + /* + * orig: [0, 2) hole, [2, 4) unwritten -> pblk 202..203, + * [4, 6) unwritten -> pblk 204..205 + * donor: [0, 2) unwritten -> pblk 300..301, [2, 4) hole, + * [4, 6) unwritten -> pblk 304..305 + * + * Expected across [0, 6) (clamped from requested len = 16 to EOF = 6): + * - [0, 2): skipped in ext4_move_extents() because orig is a hole + * - [2, 4): skipped via MEXT_SKIP_EXTENT because donor is a hole + * - [4, 6): swapped via MEXT_MOVE_EXTENT (both unwritten) + */ + i_size_write(orig, 6 * MEXT_TEST_BLK_SIZE); + EXT4_I(orig)->i_disksize = 6 * MEXT_TEST_BLK_SIZE; + i_size_write(donor, 6 * MEXT_TEST_BLK_SIZE); + EXT4_I(donor)->i_disksize = 6 * MEXT_TEST_BLK_SIZE; + + mext_insert_extent(test, orig, 2, 4, 202, true); + mext_insert_extent(test, donor, 0, 2, 300, true); + mext_insert_extent(test, donor, 4, 2, 304, true); + + ret = ext4_move_extents(&ctx->orig_file, &ctx->donor_file, 0, 0, 16, + &moved_len); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, moved_len, 2ULL); + + /* [2, 4) on orig remained on pblk 202..203; [4, 6) swapped to 304..305 */ + mext_assert_mapped_block(test, orig, 2, 202, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, orig, 3, 203, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, orig, 4, 304, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, orig, 5, 305, EXT4_MAP_UNWRITTEN); + + /* [0, 2) on donor remained 300..301; [4, 6) received 204..205 */ + mext_assert_mapped_block(test, donor, 0, 300, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, 4, 204, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, 5, 205, EXT4_MAP_UNWRITTEN); +} + +static void test_move_extents_written_copy_data_and_split(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *orig = ctx->orig_inode; + struct inode *donor = ctx->donor_inode; + ext4_lblk_t stride = max_t(ext4_lblk_t, 1, + PAGE_SIZE >> MEXT_TEST_BLK_BITS); + ext4_lblk_t ext1 = stride; + ext4_lblk_t ext2 = 3 * stride; + ext4_lblk_t total_blks = ext2 + 3; + ext4_lblk_t moved_lblks[] = { ext1, ext2, ext2 + 1 }; + ext4_lblk_t lblk; + __u64 moved_len = 0; + unsigned int i; + int ret; + + /* + * orig: [0, total_blks) written -> pblk 400.., uptodate folios + * donor: [ext1, ext1 + 1) written -> pblk 501, + * [ext1 + 1, ext2) hole, + * [ext2, ext2 + 2) unwritten -> pblk 503..504 + * + * Spacing donor extents by @stride ensures distinct pagecache folios on + * 16K/64K PAGE_SIZE kernels so dirtying ext1's folio does not make + * ext2's folio unreleasable (-EBUSY). + * + * Moving [ext1, ext2 + 2) exercises MEXT_COPY_DATA, left/right extent + * splits on orig, donor hole skipping, written preservation on orig, + * mark_unwritten=1 on donor, and page cache data preservation. + */ + i_size_write(orig, (loff_t)total_blks * MEXT_TEST_BLK_SIZE); + EXT4_I(orig)->i_disksize = (loff_t)total_blks * MEXT_TEST_BLK_SIZE; + i_size_write(donor, (loff_t)total_blks * MEXT_TEST_BLK_SIZE); + EXT4_I(donor)->i_disksize = (loff_t)total_blks * MEXT_TEST_BLK_SIZE; + + mext_insert_extent(test, orig, 0, total_blks, 400, false); + mext_insert_extent(test, donor, ext1, 1, 501, false); + mext_insert_extent(test, donor, ext2, 2, 503, true); + + for (lblk = 0; lblk < total_blks; lblk++) + mext_populate_folio_block(test, orig, lblk, 0xA0 + lblk); + + ret = ext4_move_extents(&ctx->orig_file, &ctx->donor_file, ext1, ext1, + ext2 + 2 - ext1, &moved_len); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, moved_len, 3ULL); + + /* Verify orig mappings: leading/hole/trailing unchanged; moved swapped */ + mext_assert_mapped_block(test, orig, 0, 400, EXT4_MAP_MAPPED); + mext_assert_mapped_block(test, orig, ext1, 501, EXT4_MAP_MAPPED); + mext_assert_mapped_block(test, orig, ext1 + 1, 400 + ext1 + 1, + EXT4_MAP_MAPPED); + mext_assert_mapped_block(test, orig, ext2, 503, EXT4_MAP_MAPPED); + mext_assert_mapped_block(test, orig, ext2 + 1, 504, EXT4_MAP_MAPPED); + mext_assert_mapped_block(test, orig, ext2 + 2, 400 + ext2 + 2, + EXT4_MAP_MAPPED); + + /* Donor's swapped extents are marked unwritten to avoid leaking data */ + mext_assert_mapped_block(test, donor, ext1, 400 + ext1, + EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, ext2, 400 + ext2, + EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, ext2 + 1, 400 + ext2 + 1, + EXT4_MAP_UNWRITTEN); + + /* Verify cached bytes in orig's moved folios were preserved & dirtied */ + for (i = 0; i < ARRAY_SIZE(moved_lblks); i++) { + loff_t pos; + struct folio *folio; + u8 *addr; + + lblk = moved_lblks[i]; + pos = (loff_t)lblk << orig->i_blkbits; + folio = filemap_get_folio(orig->i_mapping, pos >> PAGE_SHIFT); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + KUNIT_EXPECT_TRUE(test, folio_test_uptodate(folio)); + KUNIT_EXPECT_TRUE(test, folio_test_dirty(folio)); + addr = folio_address(folio); + KUNIT_EXPECT_EQ(test, addr[offset_in_folio(folio, pos)], + (u8)(0xA0 + lblk)); + folio_put(folio); + } +} + +static void test_move_extents_unwritten_orig_and_ebusy(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *orig = ctx->orig_inode; + struct inode *donor = ctx->donor_inode; + ext4_lblk_t stride = max_t(ext4_lblk_t, 1, + PAGE_SIZE >> MEXT_TEST_BLK_BITS); + ext4_lblk_t ebusy_lblk = max_t(ext4_lblk_t, 2, stride); + ext4_lblk_t total_blks = ebusy_lblk + 2; + struct folio *donor_folio; + __u64 moved_len = 0; + int ret; + + /* + * Part 1: orig unwritten [0, 2) -> 600..601 (no pre-populated folios), + * donor written [0, 2) -> 700..701. Exercises MEXT_COPY_DATA through + * mext_folio_mkuptodate()'s non-uptodate unwritten buffer zeroing path. + */ + i_size_write(orig, (loff_t)total_blks * MEXT_TEST_BLK_SIZE); + EXT4_I(orig)->i_disksize = (loff_t)total_blks * MEXT_TEST_BLK_SIZE; + i_size_write(donor, (loff_t)total_blks * MEXT_TEST_BLK_SIZE); + EXT4_I(donor)->i_disksize = (loff_t)total_blks * MEXT_TEST_BLK_SIZE; + + mext_insert_extent(test, orig, 0, 2, 600, true); + mext_insert_extent(test, donor, 0, 2, 700, false); + + ret = ext4_move_extents(&ctx->orig_file, &ctx->donor_file, 0, 0, 2, + &moved_len); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, moved_len, 2ULL); + + mext_assert_mapped_block(test, orig, 0, 700, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, orig, 1, 701, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, 0, 600, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, 1, 601, EXT4_MAP_UNWRITTEN); + + /* + * Part 2: non-releasable folio on donor triggers -EBUSY from + * filemap_release_folio() without altering extent mappings. + */ + mext_insert_extent(test, orig, ebusy_lblk, 1, 602, true); + mext_insert_extent(test, donor, ebusy_lblk, 1, 702, true); + + donor_folio = __filemap_get_folio(donor->i_mapping, + ((loff_t)ebusy_lblk << + donor->i_blkbits) >> PAGE_SHIFT, + FGP_CREAT | FGP_LOCK, GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(donor_folio)); + if (!folio_buffers(donor_folio)) + create_empty_buffers(donor_folio, MEXT_TEST_BLK_SIZE, 0); + folio_set_checked(donor_folio); + folio_unlock(donor_folio); + + ret = ext4_move_extents(&ctx->orig_file, &ctx->donor_file, + ebusy_lblk, ebusy_lblk, 1, &moved_len); + folio_clear_checked(donor_folio); + folio_put(donor_folio); + + KUNIT_EXPECT_EQ(test, ret, -EBUSY); + KUNIT_EXPECT_EQ(test, moved_len, 0ULL); + mext_assert_mapped_block(test, orig, ebusy_lblk, 602, + EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, ebusy_lblk, 702, + EXT4_MAP_UNWRITTEN); +} + +static struct kunit_case move_extent_test_cases[] = { + KUNIT_CASE(test_double_data_sem_lock_order), + KUNIT_CASE(test_mext_check_validity_rejections), + KUNIT_CASE(test_mext_check_adjust_range), + KUNIT_CASE(test_move_extents_holes_and_unwritten), + KUNIT_CASE(test_move_extents_written_copy_data_and_split), + KUNIT_CASE(test_move_extents_unwritten_orig_and_ebusy), + {} +}; + +static struct kunit_suite move_extent_test_suite = { + .name = "ext4_move_extent_test", + .test_cases = move_extent_test_cases, +}; + +kunit_test_suites(&move_extent_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 move_extent"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/move_extent.c b/fs/ext4/move_extent.c index e5450e83da8064..15f4126c5c5129 100644 --- a/fs/ext4/move_extent.c +++ b/fs/ext4/move_extent.c @@ -40,6 +40,7 @@ ext4_double_down_write_data_sem(struct inode *first, struct inode *second) down_write_nested(&EXT4_I(first)->i_data_sem, I_DATA_SEM_OTHER); } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_double_down_write_data_sem); /** * ext4_double_up_write_data_sem - Release two inodes' write lock of i_data_sem @@ -55,6 +56,7 @@ ext4_double_up_write_data_sem(struct inode *orig_inode, up_write(&EXT4_I(orig_inode)->i_data_sem); up_write(&EXT4_I(donor_inode)->i_data_sem); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_double_up_write_data_sem); /* Grab and lock folio on both @inode1 and @inode2 by inode order. */ static int mext_folio_double_lock(struct inode *inode1, struct inode *inode2, @@ -667,8 +669,23 @@ int ext4_move_extents(struct file *o_filp, struct file *d_filp, __u64 orig_blk, unlock_two_nondirectories(orig_inode, donor_inode); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_move_extents); #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_double_down_write_data_sem); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_double_up_write_data_sem); +int ext4_mext_check_validity_test(struct inode *orig_inode, + struct inode *donor_inode) +{ + return mext_check_validity(orig_inode, donor_inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mext_check_validity_test); + +int ext4_mext_check_adjust_range_test(struct inode *orig_inode, + struct inode *donor_inode, + __u64 orig_start, __u64 donor_start, + __u64 *len) +{ + return mext_check_adjust_range(orig_inode, donor_inode, orig_start, + donor_start, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mext_check_adjust_range_test); #endif From 0af3bcba3a0b2dbd48510be71c4feeff1d42765f Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:25:57 +0000 Subject: [PATCH 1576/2102] ext4: add KUnit tests for fs/ext4/mmp.c Add a KUnit test suite (ext4_mmp_test) covering multi-mount protection checksums, block I/O validation, and mount state transitions in fs/ext4/mmp.c: - CRC32C generation and verification in ext4_mmp_csum_set() and ext4_mmp_csum_verify() with and without METADATA_CSUM - Block read/write error handling, magic validation (-EFSCORRUPTED), CRC mismatch handling (-EFSBADCRC), and buffer cleanup in read_mmp_block() and write_mmp_block() - ext4_multi_mount_protect() validation of out-of-range MMP blocks, EXT4_MMP_SEQ_FSCK rejection (-EBUSY), EXT4_MMP_SEQ_CLEAN claim and ext4_stop_mmpd() teardown, active/racing node sequence conflicts, check_interval clamping, interrupted waits (-ETIMEDOUT), and kthread startup failure Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 20 +- fs/ext4/mmp-test.c | 661 +++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/mmp.c | 117 ++++++-- 4 files changed, 770 insertions(+), 30 deletions(-) create mode 100644 fs/ext4/mmp-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 5cf735df76567b..cb0d7b6edf6dae 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -24,7 +24,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ sysfs-test.o ioctl-test.o \ resize-test.o migrate-test.o \ indirect-test.o fsmap-test.o \ - move_extent-test.o + move_extent-test.o mmp-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index 29277a79c65bd8..9cf1dd6351a720 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -4285,9 +4285,25 @@ extern void ext4_iomap_end_bio(struct bio *bio); /* mmp.c */ extern int ext4_multi_mount_protect(struct super_block *, ext4_fsblk_t); - -/* mmp.c */ extern void ext4_stop_mmpd(struct ext4_sb_info *sbi); +extern int ext4_mmp_submit_write(struct buffer_head *bh); +extern int ext4_mmp_load_bh(struct super_block *sb, struct buffer_head **bh, + ext4_fsblk_t mmp_block); +extern long ext4_mmp_wait_timeout(long timeout); +extern struct task_struct *ext4_mmp_run_thread(struct super_block *sb, + const char *bdevname, + int bdevname_len); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_mmp_csum_verify_test(struct super_block *sb, + struct mmp_struct *mmp); +extern void ext4_mmp_csum_set_test(struct super_block *sb, + struct mmp_struct *mmp); +extern int ext4_read_mmp_block_test(struct super_block *sb, + struct buffer_head **bh, + ext4_fsblk_t mmp_block); +extern int ext4_write_mmp_block_test(struct super_block *sb, + struct buffer_head *bh); +#endif /* verity.c */ extern const struct fsverity_operations ext4_verityops; diff --git a/fs/ext4/mmp-test.c b/fs/ext4/mmp-test.c new file mode 100644 index 00000000000000..e8496e8940f5ed --- /dev/null +++ b/fs/ext4/mmp-test.c @@ -0,0 +1,661 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/mmp.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" + +#define MMP_TEST_BLK_SIZE 4096U +#define MMP_TEST_BLK_BITS 12U +#define MMP_TEST_FIRST_DATA_BLK 1ULL +#define MMP_TEST_TOTAL_BLKS 1024ULL +#define MMP_TEST_VALID_BLK 10ULL +#define MMP_MAX_WAITS 8U + +struct mmp_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct address_space bdev_mapping; + struct buffer_head sbh; + u8 sbh_data[MMP_TEST_BLK_SIZE]; + + /* Simulated on-disk MMP block and in-memory buffer_head */ + u8 disk_buf[MMP_TEST_BLK_SIZE]; + struct buffer_head mmp_bh; + u8 bh_buf[MMP_TEST_BLK_SIZE]; + + /* Deterministic I/O, sleep, and kthread fault injection */ + int load_nomem; + int load_err_on_call; + unsigned int load_calls; + ext4_fsblk_t last_load_blk; + + int write_err_on_call; + unsigned int write_calls; + + unsigned int wait_calls; + long wait_timeouts[MMP_MAX_WAITS]; + long wait_ret_on_call; + unsigned int wait_ret_target_call; + unsigned int mutate_seq_on_wait_call; + u32 mutated_seq; + + int run_thread_err; + unsigned int run_thread_calls; +}; + +static struct kunit *active_mmp_test; + +static void mmp_noop_work(struct work_struct *work) +{ +} + +static void mmp_noop_timer(struct timer_list *t) +{ +} + +static const struct super_operations mmp_test_sops = {}; + +static int mmp_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static int mmp_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static struct file_system_type mmp_test_fs_type = { + .name = "ext4_mmp_test", + .init_fs_context = mmp_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static int mmp_dummy_kthread_fn(void *data) +{ + while (!kthread_should_stop()) { + set_current_state(TASK_INTERRUPTIBLE); + if (!kthread_should_stop()) + schedule(); + } + __set_current_state(TASK_RUNNING); + return 0; +} + +static int mmp_submit_write_stub(struct buffer_head *bh) +{ + struct kunit *test = active_mmp_test; + struct mmp_test_ctx *ctx; + + if (!test) + return -EIO; + ctx = test->priv; + ctx->write_calls++; + if (ctx->write_err_on_call && + ctx->write_calls == (unsigned int)ctx->write_err_on_call) { + clear_buffer_uptodate(bh); + return -EIO; + } + + memcpy(ctx->disk_buf, bh->b_data, MMP_TEST_BLK_SIZE); + set_buffer_uptodate(bh); + return 0; +} + +static int mmp_load_bh_stub(struct super_block *sb, struct buffer_head **bh, + ext4_fsblk_t mmp_block) +{ + struct kunit *test = active_mmp_test; + struct mmp_test_ctx *ctx; + + if (!test) + return -EIO; + ctx = test->priv; + ctx->load_calls++; + ctx->last_load_blk = mmp_block; + + if (ctx->load_nomem && !*bh) + return -ENOMEM; + + if (!*bh) { + *bh = &ctx->mmp_bh; + get_bh(*bh); + } + + if (ctx->load_err_on_call && + ctx->load_calls == (unsigned int)ctx->load_err_on_call) + return -EIO; + + memcpy((*bh)->b_data, ctx->disk_buf, MMP_TEST_BLK_SIZE); + set_buffer_uptodate(*bh); + return 0; +} + +static long mmp_wait_timeout_stub(long timeout) +{ + struct kunit *test = active_mmp_test; + struct mmp_test_ctx *ctx; + + if (!test) + return 1; + ctx = test->priv; + if (ctx->wait_calls < MMP_MAX_WAITS) + ctx->wait_timeouts[ctx->wait_calls] = timeout; + ctx->wait_calls++; + + if (ctx->mutate_seq_on_wait_call && + ctx->wait_calls == ctx->mutate_seq_on_wait_call) { + struct mmp_struct *disk_mmp = (struct mmp_struct *)ctx->disk_buf; + + disk_mmp->mmp_seq = cpu_to_le32(ctx->mutated_seq); + strscpy(disk_mmp->mmp_nodename, "other-node", + sizeof(disk_mmp->mmp_nodename)); + ext4_mmp_csum_set_test(ctx->sb, disk_mmp); + } + + if (ctx->wait_ret_target_call && + ctx->wait_calls == ctx->wait_ret_target_call) + return ctx->wait_ret_on_call; + + return 0; +} + +static struct task_struct *mmp_run_thread_stub(struct super_block *sb, + const char *bdevname, + int bdevname_len) +{ + struct kunit *test = active_mmp_test; + struct mmp_test_ctx *ctx; + + if (!test) + return ERR_PTR(-EINVAL); + ctx = test->priv; + ctx->run_thread_calls++; + if (ctx->run_thread_err) + return ERR_PTR(ctx->run_thread_err); + + return kthread_run(mmp_dummy_kthread_fn, NULL, "kunit-mmpd"); +} + +static void mmp_init_disk_block(struct mmp_test_ctx *ctx, u32 seq, + u16 check_interval) +{ + struct mmp_struct *mmp = (struct mmp_struct *)ctx->disk_buf; + + memset(ctx->disk_buf, 0, sizeof(ctx->disk_buf)); + mmp->mmp_magic = cpu_to_le32(EXT4_MMP_MAGIC); + mmp->mmp_seq = cpu_to_le32(seq); + mmp->mmp_time = cpu_to_le64(1700000000ULL); + strscpy(mmp->mmp_nodename, "init-node", sizeof(mmp->mmp_nodename)); + strscpy(mmp->mmp_bdevname, "init-bdev", sizeof(mmp->mmp_bdevname)); + mmp->mmp_check_interval = cpu_to_le16(check_interval); + ext4_mmp_csum_set_test(ctx->sb, mmp); +} + +static void mmp_reset_counters(struct mmp_test_ctx *ctx) +{ + ctx->load_nomem = 0; + ctx->load_err_on_call = 0; + ctx->load_calls = 0; + ctx->last_load_blk = 0; + ctx->write_err_on_call = 0; + ctx->write_calls = 0; + ctx->wait_calls = 0; + memset(ctx->wait_timeouts, 0, sizeof(ctx->wait_timeouts)); + ctx->wait_ret_on_call = 0; + ctx->wait_ret_target_call = 0; + ctx->mutate_seq_on_wait_call = 0; + ctx->mutated_seq = 0; + ctx->run_thread_err = 0; + ctx->run_thread_calls = 0; +} + +static void mmp_cleanup_ctx(void *data) +{ + struct mmp_test_ctx *ctx = data; + + active_mmp_test = NULL; + + if (ctx->sbi.s_mmp_tsk) + ext4_stop_mmpd(&ctx->sbi); + ctx->sbi.s_mmp_bh = NULL; + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + if (ctx->sb) { + ctx->sb->s_fs_info = NULL; + deactivate_super(ctx->sb); + ctx->sb = NULL; + } + if (ctx->bdev.bd_stats) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + } +} + +static struct mmp_test_ctx *mmp_setup_ctx(struct kunit *test) +{ + struct mmp_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + int err; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->es = kunit_kzalloc(test, sizeof(*ctx->es), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->es); + + fc = fs_context_for_mount(&mmp_test_fs_type, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fc)); + sb = sget_fc(fc, NULL, mmp_set_super); + put_fs_context(fc); + KUNIT_ASSERT_FALSE(test, IS_ERR(sb)); + up_write(&sb->s_umount); + ctx->sb = sb; + + INIT_WORK(&ctx->sbi.s_sb_upd_work, mmp_noop_work); + timer_setup(&ctx->sbi.s_err_report, mmp_noop_timer, 0); + + err = kunit_add_action_or_reset(test, mmp_cleanup_ctx, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->bdev.bd_stats != NULL); + strscpy(ctx->bdev_disk.disk_name, "mmp_bdev", + sizeof(ctx->bdev_disk.disk_name)); + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bdev_mapping; + + sb->s_bdev = &ctx->bdev; + sb->s_blocksize = MMP_TEST_BLK_SIZE; + sb->s_blocksize_bits = MMP_TEST_BLK_BITS; + sb->s_magic = EXT4_SUPER_MAGIC; + sb->s_op = &mmp_test_sops; + sb->s_fs_info = &ctx->sbi; + strscpy(sb->s_id, "ext4_mmp_kunit", sizeof(sb->s_id)); + + ctx->sbh.b_data = ctx->sbh_data; + ctx->sbh.b_size = MMP_TEST_BLK_SIZE; + ctx->sbh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sbh.b_count, 2); + set_buffer_uptodate(&ctx->sbh); + clear_buffer_mapped(&ctx->sbh); + + ctx->mmp_bh.b_data = ctx->bh_buf; + ctx->mmp_bh.b_size = MMP_TEST_BLK_SIZE; + ctx->mmp_bh.b_blocknr = MMP_TEST_VALID_BLK; + ctx->mmp_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->mmp_bh.b_count, 2); + set_buffer_mapped(&ctx->mmp_bh); + + ctx->es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es->s_first_data_block = cpu_to_le32(MMP_TEST_FIRST_DATA_BLK); + ctx->es->s_mmp_block = cpu_to_le64(MMP_TEST_VALID_BLK); + ctx->es->s_mmp_update_interval = cpu_to_le16(EXT4_MMP_MIN_CHECK_INTERVAL); + ctx->es->s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_MMP); + ctx->es->s_feature_ro_compat = + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + ext4_blocks_count_set(ctx->es, MMP_TEST_TOTAL_BLKS); + + ctx->sbi.s_sb = sb; + ctx->sbi.s_es = ctx->es; + ctx->sbi.s_sbh = &ctx->sbh; + ctx->sbi.s_csum_seed = 0x9abcdef0U; + set_opt(sb, ERRORS_CONT); + spin_lock_init(&ctx->sbi.s_bdev_wb_lock); + spin_lock_init(&ctx->sbi.s_error_lock); + ratelimit_state_init(&ctx->sbi.s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + ratelimit_state_init(&ctx->sbi.s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + ratelimit_state_init(&ctx->sbi.s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + + test->priv = ctx; + active_mmp_test = test; + + kunit_activate_static_stub(test, ext4_mmp_submit_write, + mmp_submit_write_stub); + kunit_activate_static_stub(test, ext4_mmp_load_bh, + mmp_load_bh_stub); + kunit_activate_static_stub(test, ext4_mmp_wait_timeout, + mmp_wait_timeout_stub); + kunit_activate_static_stub(test, ext4_mmp_run_thread, + mmp_run_thread_stub); + + return ctx; +} + +static void test_mmp_csum_set_and_verify(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + struct mmp_struct *mmp; + __le32 orig_csum; + + mmp = kunit_kzalloc(test, sizeof(*mmp), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, mmp); + + mmp->mmp_magic = cpu_to_le32(EXT4_MMP_MAGIC); + mmp->mmp_seq = cpu_to_le32(EXT4_MMP_SEQ_CLEAN); + strscpy(mmp->mmp_nodename, "node-a", sizeof(mmp->mmp_nodename)); + + /* Without METADATA_CSUM, set is a no-op and verify always returns 1 */ + ext4_clear_feature_metadata_csum(ctx->sb); + mmp->mmp_checksum = cpu_to_le32(0xdeadbeefU); + ext4_mmp_csum_set_test(ctx->sb, mmp); + KUNIT_EXPECT_EQ(test, le32_to_cpu(mmp->mmp_checksum), 0xdeadbeefU); + KUNIT_EXPECT_EQ(test, ext4_mmp_csum_verify_test(ctx->sb, mmp), 1); + + /* With METADATA_CSUM, set computes CRC32C and verify detects tampering */ + ext4_set_feature_metadata_csum(ctx->sb); + mmp->mmp_checksum = 0; + ext4_mmp_csum_set_test(ctx->sb, mmp); + orig_csum = mmp->mmp_checksum; + KUNIT_EXPECT_NE(test, le32_to_cpu(orig_csum), 0U); + KUNIT_EXPECT_EQ(test, ext4_mmp_csum_verify_test(ctx->sb, mmp), 1); + + /* Flipping payload field or csum seed invalidates verification */ + mmp->mmp_seq = cpu_to_le32(7); + KUNIT_EXPECT_EQ(test, ext4_mmp_csum_verify_test(ctx->sb, mmp), 0); + mmp->mmp_seq = cpu_to_le32(EXT4_MMP_SEQ_CLEAN); + KUNIT_EXPECT_EQ(test, ext4_mmp_csum_verify_test(ctx->sb, mmp), 1); + + ctx->sbi.s_csum_seed ^= 1U; + KUNIT_EXPECT_EQ(test, ext4_mmp_csum_verify_test(ctx->sb, mmp), 0); +} + +static void test_read_and_write_mmp_block(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + struct buffer_head *bh = NULL; + struct mmp_struct *mmp; + int base_ref; + int ret; + + /* Write populates checksum and persists block into disk_buf */ + mmp = (struct mmp_struct *)ctx->mmp_bh.b_data; + memset(ctx->mmp_bh.b_data, 0, MMP_TEST_BLK_SIZE); + mmp->mmp_magic = cpu_to_le32(EXT4_MMP_MAGIC); + mmp->mmp_seq = cpu_to_le32(19); + ret = ext4_write_mmp_block_test(ctx->sb, &ctx->mmp_bh); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->write_calls, 1U); + KUNIT_EXPECT_EQ(test, + ext4_mmp_csum_verify_test(ctx->sb, + (struct mmp_struct *)ctx->disk_buf), 1); + + /* Simulated write I/O error returns -EIO */ + ctx->write_err_on_call = 2; + KUNIT_EXPECT_EQ(test, ext4_write_mmp_block_test(ctx->sb, &ctx->mmp_bh), + -EIO); + ctx->write_err_on_call = 0; + + /* Valid read allocates/populates bh and verifies magic + checksum */ + base_ref = atomic_read(&ctx->mmp_bh.b_count); + ret = ext4_read_mmp_block_test(ctx->sb, &bh, MMP_TEST_VALID_BLK); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_ASSERT_PTR_EQ(test, bh, &ctx->mmp_bh); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref + 1); + + /* Re-reading with existing bh refreshes contents without leaking ref */ + ((struct mmp_struct *)ctx->disk_buf)->mmp_seq = cpu_to_le32(23); + ext4_mmp_csum_set_test(ctx->sb, (struct mmp_struct *)ctx->disk_buf); + ret = ext4_read_mmp_block_test(ctx->sb, &bh, MMP_TEST_VALID_BLK); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(((struct mmp_struct *)bh->b_data)->mmp_seq), + 23U); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref + 1); + brelse(bh); + bh = NULL; + + /* -ENOMEM when bh allocation fails */ + ctx->load_nomem = 1; + KUNIT_EXPECT_EQ(test, + ext4_read_mmp_block_test(ctx->sb, &bh, + MMP_TEST_VALID_BLK), + -ENOMEM); + KUNIT_EXPECT_NULL(test, bh); + ctx->load_nomem = 0; + + /* -EIO read failure releases bh and resets *bh to NULL */ + mmp_reset_counters(ctx); + ctx->load_err_on_call = 1; + KUNIT_EXPECT_EQ(test, + ext4_read_mmp_block_test(ctx->sb, &bh, + MMP_TEST_VALID_BLK), + -EIO); + KUNIT_EXPECT_NULL(test, bh); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref); + + /* Bad magic returns -EFSCORRUPTED and cleans up bh */ + mmp_reset_counters(ctx); + ((struct mmp_struct *)ctx->disk_buf)->mmp_magic = cpu_to_le32(0x1234U); + KUNIT_EXPECT_EQ(test, + ext4_read_mmp_block_test(ctx->sb, &bh, + MMP_TEST_VALID_BLK), + -EFSCORRUPTED); + KUNIT_EXPECT_NULL(test, bh); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref); + + /* Bad checksum returns -EFSBADCRC and cleans up bh */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_CLEAN, 5); + ((struct mmp_struct *)ctx->disk_buf)->mmp_checksum ^= cpu_to_le32(1U); + KUNIT_EXPECT_EQ(test, + ext4_read_mmp_block_test(ctx->sb, &bh, + MMP_TEST_VALID_BLK), + -EFSBADCRC); + KUNIT_EXPECT_NULL(test, bh); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref); +} + +static void test_mmp_invalid_block_and_io_errors(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + + /* Block below s_first_data_block (1) or >= blocks_count (1024) */ + KUNIT_EXPECT_EQ(test, ext4_multi_mount_protect(ctx->sb, 0), -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_TOTAL_BLKS), + -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->load_calls, 0U); + + /* Initial read failure propagates error */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_CLEAN, 5); + mmp_reset_counters(ctx); + ctx->load_err_on_call = 1; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -EIO); + + /* Write failure when claiming MMP block */ + mmp_reset_counters(ctx); + ctx->write_err_on_call = 1; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -EIO); + + /* Post-write verification read failure */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_CLEAN, 5); + mmp_reset_counters(ctx); + ctx->load_err_on_call = 2; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -EIO); +} + +static void test_mmp_clean_and_fsck_sequences(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + struct mmp_struct *disk_mmp = (struct mmp_struct *)ctx->disk_buf; + int base_ref; + int ret; + + /* EXT4_MMP_SEQ_FSCK fails immediately with -EBUSY without sleeping */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_FSCK, 5); + mmp_reset_counters(ctx); + ret = ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK); + KUNIT_EXPECT_EQ(test, ret, -EBUSY); + KUNIT_EXPECT_EQ(test, ctx->wait_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->write_calls, 0U); + + /* + * EXT4_MMP_SEQ_CLEAN skips pre-claim wait, writes a valid sequence + * <= EXT4_MMP_SEQ_MAX, starts kmmpd, and ext4_stop_mmpd() cleans up. + */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_CLEAN, 5); + mmp_reset_counters(ctx); + base_ref = atomic_read(&ctx->mmp_bh.b_count); + + ret = ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->wait_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->write_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->run_thread_calls, 1U); + KUNIT_EXPECT_LE(test, le32_to_cpu(disk_mmp->mmp_seq), EXT4_MMP_SEQ_MAX); + KUNIT_EXPECT_NOT_NULL(test, ctx->sbi.s_mmp_tsk); + KUNIT_EXPECT_PTR_EQ(test, ctx->sbi.s_mmp_bh, &ctx->mmp_bh); + KUNIT_EXPECT_STREQ(test, + ((struct mmp_struct *)ctx->mmp_bh.b_data)->mmp_bdevname, + "mmp_bdev"); + + ext4_stop_mmpd(&ctx->sbi); + KUNIT_EXPECT_NULL(test, ctx->sbi.s_mmp_tsk); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref); + ctx->sbi.s_mmp_bh = NULL; +} + +static void test_mmp_active_seq_conflict_and_claim(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + int ret; + + /* + * Case 1: Active sequence on disk; s_mmp_update_interval = 3 (floored + * to 5), disk mmp_check_interval = 12 (overrides 5 -> wait_time = 25s). + * Remote node updates mmp_seq during wait #1 -> fails with -EBUSY. + */ + ctx->es->s_mmp_update_interval = cpu_to_le16(3); + mmp_init_disk_block(ctx, 100, 12); + mmp_reset_counters(ctx); + ctx->mutate_seq_on_wait_call = 1; + ctx->mutated_seq = 101; + + ret = ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK); + KUNIT_EXPECT_EQ(test, ret, -EBUSY); + KUNIT_EXPECT_EQ(test, ctx->wait_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->wait_timeouts[0], (long)(25 * HZ)); + KUNIT_EXPECT_EQ(test, ctx->write_calls, 0U); + + /* + * Case 2: Stale sequence unchanged on wait #1, but racing mounter + * overwrites mmp_seq during post-claim wait #2 -> fails with -EBUSY. + */ + mmp_init_disk_block(ctx, 100, 12); + mmp_reset_counters(ctx); + ctx->mutate_seq_on_wait_call = 2; + ctx->mutated_seq = 0x5555U; + + ret = ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK); + KUNIT_EXPECT_EQ(test, ret, -EBUSY); + KUNIT_EXPECT_EQ(test, ctx->wait_calls, 2U); + KUNIT_EXPECT_EQ(test, ctx->wait_timeouts[0], (long)(25 * HZ)); + KUNIT_EXPECT_EQ(test, ctx->wait_timeouts[1], (long)(25 * HZ)); + KUNIT_EXPECT_EQ(test, ctx->write_calls, 1U); + + /* + * Case 3: Stale sequence with large check_interval = 80 (wait_time + * capped to 80 + 60 = 140s via min(2*x+1, x+60)) succeeds cleanly. + */ + mmp_init_disk_block(ctx, 100, 80); + mmp_reset_counters(ctx); + + ret = ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->wait_calls, 2U); + KUNIT_EXPECT_EQ(test, ctx->wait_timeouts[0], (long)(140 * HZ)); + KUNIT_EXPECT_EQ(test, ctx->wait_timeouts[1], (long)(140 * HZ)); + + ext4_stop_mmpd(&ctx->sbi); + ctx->sbi.s_mmp_bh = NULL; +} + +static void test_mmp_interrupted_waits_and_kthread_failure(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + + /* Signal interruption on pre-claim wait returns -ETIMEDOUT */ + mmp_init_disk_block(ctx, 77, 5); + mmp_reset_counters(ctx); + ctx->wait_ret_target_call = 1; + ctx->wait_ret_on_call = 3 * HZ; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -ETIMEDOUT); + + /* Signal interruption on post-claim wait returns -ETIMEDOUT */ + mmp_init_disk_block(ctx, 77, 5); + mmp_reset_counters(ctx); + ctx->wait_ret_target_call = 2; + ctx->wait_ret_on_call = 2 * HZ; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -ETIMEDOUT); + + /* kthread creation failure returns -ENOMEM and leaves s_mmp_tsk NULL */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_CLEAN, 5); + mmp_reset_counters(ctx); + ctx->run_thread_err = -ENOMEM; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -ENOMEM); + KUNIT_EXPECT_NULL(test, ctx->sbi.s_mmp_tsk); + ctx->sbi.s_mmp_bh = NULL; +} + +static struct kunit_case mmp_test_cases[] = { + KUNIT_CASE(test_mmp_csum_set_and_verify), + KUNIT_CASE(test_read_and_write_mmp_block), + KUNIT_CASE(test_mmp_invalid_block_and_io_errors), + KUNIT_CASE(test_mmp_clean_and_fsck_sequences), + KUNIT_CASE(test_mmp_active_seq_conflict_and_claim), + KUNIT_CASE(test_mmp_interrupted_waits_and_kthread_failure), + {} +}; + +static struct kunit_suite mmp_test_suite = { + .name = "ext4_mmp_test", + .test_cases = mmp_test_cases, +}; + +kunit_test_suites(&mmp_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 multi-mount protection (MMP)"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/mmp.c b/fs/ext4/mmp.c index 4b18ddef468d71..9e9eac6060afec 100644 --- a/fs/ext4/mmp.c +++ b/fs/ext4/mmp.c @@ -1,4 +1,5 @@ // SPDX-License-Identifier: GPL-2.0 +#include #include #include #include @@ -35,6 +36,20 @@ static void ext4_mmp_csum_set(struct super_block *sb, struct mmp_struct *mmp) mmp->mmp_checksum = ext4_mmp_csum(sb, mmp); } +int ext4_mmp_submit_write(struct buffer_head *bh) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_mmp_submit_write, bh); + + lock_buffer(bh); + bh_submit(bh, REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO, + bh_end_write); + wait_on_buffer(bh); + if (unlikely(buffer_write_io_error(bh))) + return -EIO; + return 0; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_submit_write); + /* * Write the MMP block using REQ_SYNC to try to get the block on-disk * faster. @@ -45,13 +60,7 @@ static int write_mmp_block_thawed(struct super_block *sb, struct mmp_struct *mmp = (struct mmp_struct *)(bh->b_data); ext4_mmp_csum_set(sb, mmp); - lock_buffer(bh); - bh_submit(bh, REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO, - bh_end_write); - wait_on_buffer(bh); - if (unlikely(buffer_write_io_error(bh))) - return -EIO; - return 0; + return ext4_mmp_submit_write(bh); } static int write_mmp_block(struct super_block *sb, struct buffer_head *bh) @@ -64,6 +73,35 @@ static int write_mmp_block(struct super_block *sb, struct buffer_head *bh) return write_mmp_block_thawed(sb, bh); } +int ext4_mmp_load_bh(struct super_block *sb, struct buffer_head **bh, + ext4_fsblk_t mmp_block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_mmp_load_bh, sb, bh, mmp_block); + + /* + * This would be sb_bread(sb, mmp_block), except we need to be sure + * that the MD RAID device cache has been bypassed, and that the read + * is not blocked in the elevator. + */ + if (!*bh) { + *bh = sb_getblk(sb, mmp_block); + if (!*bh) + return -ENOMEM; + } + + lock_buffer(*bh); + return ext4_read_bh(*bh, REQ_META | REQ_PRIO, NULL, false); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_load_bh); + +long ext4_mmp_wait_timeout(long timeout) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_mmp_wait_timeout, timeout); + + return schedule_timeout_interruptible(timeout); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_wait_timeout); + /* * Read the MMP block. It _must_ be read from disk and hence we clear the * uptodate flag on the buffer. @@ -77,19 +115,7 @@ static int read_mmp_block(struct super_block *sb, struct buffer_head **bh, if (*bh) clear_buffer_uptodate(*bh); - /* This would be sb_bread(sb, mmp_block), except we need to be sure - * that the MD RAID device cache has been bypassed, and that the read - * is not blocked in the elevator. */ - if (!*bh) { - *bh = sb_getblk(sb, mmp_block); - if (!*bh) { - ret = -ENOMEM; - goto warn_exit; - } - } - - lock_buffer(*bh); - ret = ext4_read_bh(*bh, REQ_META | REQ_PRIO, NULL, false); + ret = ext4_mmp_load_bh(sb, bh, mmp_block); if (ret) goto warn_exit; @@ -185,8 +211,7 @@ static int kmmpd(void *data) diff = jiffies - last_update_time; if (diff < mmp_update_interval * HZ) - schedule_timeout_interruptible(mmp_update_interval * - HZ - diff); + ext4_mmp_wait_timeout(mmp_update_interval * HZ - diff); /* * We need to make sure that more than mmp_check_interval @@ -250,6 +275,16 @@ static int kmmpd(void *data) return retval; } +struct task_struct *ext4_mmp_run_thread(struct super_block *sb, + const char *bdevname, int bdevname_len) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_mmp_run_thread, sb, bdevname, + bdevname_len); + + return kthread_run(kmmpd, sb, "kmmpd-%.*s", bdevname_len, bdevname); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_run_thread); + void ext4_stop_mmpd(struct ext4_sb_info *sbi) { if (sbi->s_mmp_tsk) { @@ -258,6 +293,7 @@ void ext4_stop_mmpd(struct ext4_sb_info *sbi) sbi->s_mmp_tsk = NULL; } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_stop_mmpd); /* * Get a random new sequence number but make sure it is not greater than @@ -323,7 +359,7 @@ int ext4_multi_mount_protect(struct super_block *sb, ext4_warning(sb, "MMP interval %u higher than expected, please" " wait.\n", wait_time * 2); - if (schedule_timeout_interruptible(HZ * wait_time) != 0) { + if (ext4_mmp_wait_timeout(HZ * wait_time) != 0) { ext4_warning(sb, "MMP startup interrupted, failing mount\n"); retval = -ETIMEDOUT; goto failed; @@ -358,7 +394,7 @@ int ext4_multi_mount_protect(struct super_block *sb, /* * wait for MMP interval and check mmp_seq. */ - if (schedule_timeout_interruptible(HZ * wait_time) != 0) { + if (ext4_mmp_wait_timeout(HZ * wait_time) != 0) { ext4_warning(sb, "MMP startup interrupted, failing mount"); retval = -ETIMEDOUT; goto failed; @@ -384,9 +420,8 @@ int ext4_multi_mount_protect(struct super_block *sb, /* * Start a kernel thread to update the MMP block periodically. */ - EXT4_SB(sb)->s_mmp_tsk = kthread_run(kmmpd, sb, "kmmpd-%.*s", - (int)sizeof(mmp->mmp_bdevname), - mmp->mmp_bdevname); + EXT4_SB(sb)->s_mmp_tsk = ext4_mmp_run_thread(sb, mmp->mmp_bdevname, + (int)sizeof(mmp->mmp_bdevname)); if (IS_ERR(EXT4_SB(sb)->s_mmp_tsk)) { EXT4_SB(sb)->s_mmp_tsk = NULL; ext4_warning(sb, "Unable to create kmmpd thread for %s.", @@ -401,3 +436,31 @@ int ext4_multi_mount_protect(struct super_block *sb, brelse(bh); return retval; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_multi_mount_protect); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_mmp_csum_verify_test(struct super_block *sb, struct mmp_struct *mmp) +{ + return ext4_mmp_csum_verify(sb, mmp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_csum_verify_test); + +void ext4_mmp_csum_set_test(struct super_block *sb, struct mmp_struct *mmp) +{ + ext4_mmp_csum_set(sb, mmp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_csum_set_test); + +int ext4_read_mmp_block_test(struct super_block *sb, struct buffer_head **bh, + ext4_fsblk_t mmp_block) +{ + return read_mmp_block(sb, bh, mmp_block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_mmp_block_test); + +int ext4_write_mmp_block_test(struct super_block *sb, struct buffer_head *bh) +{ + return write_mmp_block(sb, bh); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_write_mmp_block_test); +#endif From dedf8d3fe774ccfb0cbe5b4d07cecd46a62f48bd Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 11 Nov 2026 16:26:13 +0000 Subject: [PATCH 1577/2102] ext4: add KUnit tests for fs/ext4/dir.c Add a KUnit test suite (ext4_dir_test) in fs/ext4/dir-test.c covering directory entry validation, hash-cookie helpers, directory llseek, and both linear and HTree directory iteration in fs/ext4/dir.c: - __ext4_check_dir_entry() and ext4_check_all_de() validation across valid blocks (including fake '.', '..', and metadata_csum tail entries, as well as encrypted+casefolded extended-hash entries) and corrupt rec_len, alignment, name_len, block-end slack, overrun, out-of-bounds inode numbers, and full-block '.' entries. - is_dx_dir(), get_dtype(), and 32-bit vs 64-bit HTree telldir hash position conversions (hash2pos, pos2maj_hash, pos2min_hash, and ext4_get_htree_eof). - ext4_dir_operations open(), llseek() (64-bit and 32-bit HTree EOF bounds vs non-DX s_bitmap_maxbytes/SEEK_END bounds and cookie invalidation), and release(). - ext4_htree_store_dirent() rbtree ordering across major/minor hashes, 64-bit hash collision chaining, and ext4_htree_free_dir_info(). - Linear ext4_readdir() across multi-block directories with sparse holes, deleted entries, stop/resume, unaligned f_pos revalidation on i_version change, bad checksum and corrupt entry skipping, and ERR_BAD_DX_DIR fallback clearing EXT4_INODE_INDEX. - HTree ext4_dx_readdir() across multi-leaf next_hash continuations, mid-collision extra_fname stop/resume, EOF handling, seek reset, and mid-iteration i_version refill. Export ext4_dir_operations, expose thin KUnit wrappers for static helpers in fs/ext4/dir.c, and add a KUNIT_STATIC_STUB_REDIRECT hook to ext4_htree_fill_tree(). Signed-off-by: Theodore Ts'o --- fs/ext4/Makefile | 3 +- fs/ext4/dir-test.c | 993 +++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/dir.c | 33 ++ fs/ext4/ext4.h | 8 + fs/ext4/namei.c | 4 + 5 files changed, 1040 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/dir-test.c diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index cb0d7b6edf6dae..a427f6f361e5ac 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -24,7 +24,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ sysfs-test.o ioctl-test.o \ resize-test.o migrate-test.o \ indirect-test.o fsmap-test.o \ - move_extent-test.o mmp-test.o + move_extent-test.o mmp-test.o \ + dir-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/dir-test.c b/fs/ext4/dir-test.c new file mode 100644 index 00000000000000..7ec661919760da --- /dev/null +++ b/fs/ext4/dir-test.c @@ -0,0 +1,993 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 directory entry validation, linear/HTree readdir, + * hash-cookie conversions, and directory llseek (fs/ext4/dir.c). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" + +#define DIR_TEST_BLK_SIZE 1024 +#define DIR_TEST_BLK_BITS 10 +#define DIR_TEST_INODE_SIZE 256 +#define DIR_TEST_EXTRA_ISIZE (sizeof(struct ext4_inode) - \ + EXT4_GOOD_OLD_INODE_SIZE) +#define DIR_TEST_FIRST_PBLK 200 +#define DIR_TEST_MAX_BLOCKS 16 +#define DIR_TEST_MAX_LBLOCKS 8 +#define DIR_TEST_CSUM_SEED 0x4d3c2b1aU + +#define DIR_TEST_ROOT_INO EXT4_ROOT_INO +#define DIR_TEST_DIR_INO 12 +#define DIR_TEST_MAX_EMIT 32 + +struct dir_mock_block { + bool in_use; + struct buffer_head bh; + char data[DIR_TEST_BLK_SIZE] __aligned(8); +}; + +struct dir_emit_record { + char name[32]; + u64 ino; + loff_t offset; + unsigned int d_type; +}; + +struct dir_capture_ctx { + struct dir_context ctx; + int count; + int max_emit; + struct inode *bump_iversion_after_first; + struct dir_emit_record recs[DIR_TEST_MAX_EMIT]; +}; + +struct dir_test_ctx { + struct super_block sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct block_device bdev; + struct address_space bd_mapping; + struct buffer_head sb_bh; + + struct ext4_inode_info dir_ei; + ext4_fsblk_t lblk_to_pblk[DIR_TEST_MAX_LBLOCKS]; + struct dir_mock_block blocks[DIR_TEST_MAX_BLOCKS]; + + struct dentry dentry; + struct file filp; + struct dir_capture_ctx cap; + + int fail_map_blocks; + int fail_getblk; + int htree_mode; + int htree_fill_calls; + __u32 last_fill_start_hash; + __u32 last_fill_start_minor; +}; + +enum dir_htree_stub_mode { + DIR_HTREE_STUB_NONE = 0, + DIR_HTREE_STUB_BAD_DX, + DIR_HTREE_STUB_TWO_BATCH, +}; + +static const struct super_operations dir_test_sops = { +}; + +static void init_mock_dir_file(struct dir_test_ctx *ctx, fmode_t extra_mode) +{ + struct inode *dir = &ctx->dir_ei.vfs_inode; + struct file tmp = { + .f_path = { .dentry = &ctx->dentry }, + .f_inode = dir, + .f_mapping = dir->i_mapping, + .f_op = &ext4_dir_operations, + .f_mode = FMODE_READ | FMODE_LSEEK | FMODE_PREAD | extra_mode, + }; + + memset(&ctx->dentry, 0, sizeof(ctx->dentry)); + spin_lock_init(&ctx->dentry.d_lock); + seqcount_spinlock_init(&ctx->dentry.d_seq, &ctx->dentry.d_lock); + ctx->dentry.d_parent = &ctx->dentry; + ctx->dentry.d_sb = &ctx->sb; + ctx->dentry.d_inode = dir; + ctx->dentry.__d_name.name = (const unsigned char *)"testdir"; + ctx->dentry.__d_name.len = 7; + + memcpy(&ctx->filp, &tmp, sizeof(ctx->filp)); + spin_lock_init(&ctx->filp.f_lock); + mutex_init(&ctx->filp.f_pos_lock); + /* + * Pre-populate the readahead window across our mock block range so + * ext4_readdir() does not issue block-device pagecache readahead I/O. + */ + ctx->filp.f_ra.start = 0; + ctx->filp.f_ra.size = 4096; +} + +static bool dir_capture_actor(struct dir_context *dctx, const char *name, + int namelen, loff_t offset, u64 ino, + unsigned int d_type) +{ + struct dir_capture_ctx *cap = + container_of(dctx, struct dir_capture_ctx, ctx); + + if (cap->max_emit > 0 && cap->count >= cap->max_emit) + return false; + + if (cap->count < DIR_TEST_MAX_EMIT) { + struct dir_emit_record *rec = &cap->recs[cap->count]; + int copy_len = min_t(int, namelen, sizeof(rec->name) - 1); + + memcpy(rec->name, name, copy_len); + rec->name[copy_len] = '\0'; + rec->ino = ino; + rec->offset = offset; + rec->d_type = d_type; + } + cap->count++; + + if (cap->bump_iversion_after_first && cap->count == 1) { + inode_inc_iversion(cap->bump_iversion_after_first); + cap->bump_iversion_after_first = NULL; + } + + return true; +} + +static void reset_capture(struct dir_capture_ctx *cap, loff_t pos, int max_emit) +{ + memset(cap, 0, sizeof(*cap)); + cap->ctx.actor = dir_capture_actor; + cap->ctx.pos = pos; + cap->max_emit = max_emit; +} + +static struct buffer_head *alloc_dir_lblk(struct dir_test_ctx *ctx, + ext4_lblk_t lblk) +{ + int i; + + if (lblk >= DIR_TEST_MAX_LBLOCKS) + return NULL; + + if (ctx->lblk_to_pblk[lblk]) { + unsigned long idx = ctx->lblk_to_pblk[lblk] - + DIR_TEST_FIRST_PBLK; + + return &ctx->blocks[idx].bh; + } + + for (i = 0; i < DIR_TEST_MAX_BLOCKS; i++) { + if (!ctx->blocks[i].in_use) { + struct buffer_head *bh = &ctx->blocks[i].bh; + + ctx->blocks[i].in_use = true; + memset(ctx->blocks[i].data, 0, DIR_TEST_BLK_SIZE); + set_buffer_uptodate(bh); + clear_buffer_verified(bh); + ctx->lblk_to_pblk[lblk] = DIR_TEST_FIRST_PBLK + i; + return bh; + } + } + return NULL; +} + +static struct ext4_dir_entry_2 *write_de(char *buf, unsigned int offset, + u32 ino, u16 rec_len, u8 file_type, + const char *name) +{ + struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)(buf + offset); + size_t nlen = strlen(name); + + memset(de, 0, rec_len); + de->inode = cpu_to_le32(ino); + de->rec_len = ext4_rec_len_to_disk(rec_len, DIR_TEST_BLK_SIZE); + de->name_len = (u8)nlen; + de->file_type = file_type; + memcpy(de->name, name, nlen); + return de; +} + +static int store_stub_dirent(struct file *dir_file, __u32 hash, + __u32 minor_hash, u32 ino, u8 file_type, + const char *name) +{ + struct ext4_dir_entry_2 de = { + .inode = cpu_to_le32(ino), + .file_type = file_type, + }; + struct fscrypt_str ent_name = { + .name = (unsigned char *)name, + .len = strlen(name), + }; + + return ext4_htree_store_dirent(dir_file, hash, minor_hash, + &de, &ent_name); +} + +/* --- KUnit Static Stubs --- */ + +static int dir_map_blocks_stub(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct dir_test_ctx *ctx = test->priv; + ext4_fsblk_t pblk; + + if (ctx->fail_map_blocks) + return ctx->fail_map_blocks; + if (map->m_lblk >= DIR_TEST_MAX_LBLOCKS) + return 0; + + pblk = ctx->lblk_to_pblk[map->m_lblk]; + if (!pblk) { + map->m_pblk = 0; + map->m_len = 1; + map->m_flags = 0; + return 0; + } + + map->m_pblk = pblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED; + return 1; +} + +static struct buffer_head *dir_getblk_stub(handle_t *handle, + struct inode *inode, + ext4_lblk_t block, int map_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct dir_test_ctx *ctx = test->priv; + ext4_fsblk_t pblk; + struct buffer_head *bh; + + if (ctx->fail_getblk) + return ERR_PTR(ctx->fail_getblk); + if (block >= DIR_TEST_MAX_LBLOCKS) + return NULL; + + pblk = ctx->lblk_to_pblk[block]; + if (!pblk) + return NULL; + + bh = &ctx->blocks[pblk - DIR_TEST_FIRST_PBLK].bh; + get_bh(bh); + return bh; +} + +static int dir_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + return 0; +} + +static int dir_htree_fill_tree_stub(struct file *dir_file, __u32 start_hash, + __u32 start_minor_hash, __u32 *next_hash) +{ + struct kunit *test = kunit_get_current_test(); + struct dir_test_ctx *ctx = test->priv; + int err; + + ctx->htree_fill_calls++; + ctx->last_fill_start_hash = start_hash; + ctx->last_fill_start_minor = start_minor_hash; + + if (ctx->htree_mode == DIR_HTREE_STUB_BAD_DX) + return ERR_BAD_DX_DIR; + + if (ctx->htree_mode == DIR_HTREE_STUB_TWO_BATCH) { + int count = 0; + + if (start_hash < 0x2000) { + if (start_hash == 0 && start_minor_hash == 0) { + err = store_stub_dirent(dir_file, 0, 0, + DIR_TEST_DIR_INO, + EXT4_FT_DIR, "."); + if (err) + return err; + count++; + } + if (start_hash < 2 || + (start_hash == 2 && start_minor_hash == 0)) { + err = store_stub_dirent(dir_file, 2, 0, + DIR_TEST_ROOT_INO, + EXT4_FT_DIR, ".."); + if (err) + return err; + count++; + } + if (start_hash < 0x1000 || + (start_hash == 0x1000 && + start_minor_hash <= 0x55)) { + err = store_stub_dirent(dir_file, 0x1000, 0x55, + 21, EXT4_FT_REG_FILE, + "coll_a"); + if (err) + return err; + err = store_stub_dirent(dir_file, 0x1000, 0x55, + 22, EXT4_FT_SYMLINK, + "coll_b"); + if (err) + return err; + count += 2; + } + *next_hash = 0x2000; + return count; + } + + if (start_hash <= 0x2000) { + err = store_stub_dirent(dir_file, 0x2000, 0x09, + 23, EXT4_FT_DIR, "leaf2_sub"); + if (err) + return err; + *next_hash = ~0U; + return 1; + } + + *next_hash = ~0U; + return 0; + } + + *next_hash = ~0U; + return 0; +} + +static int dir_test_init(struct kunit *test) +{ + struct dir_test_ctx *ctx; + struct inode *dir; + int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); + test->priv = ctx; + + ctx->sb.s_blocksize = DIR_TEST_BLK_SIZE; + ctx->sb.s_blocksize_bits = DIR_TEST_BLK_BITS; + ctx->sb.s_magic = EXT4_SUPER_MAGIC; + ctx->sb.s_maxbytes = 64ULL * DIR_TEST_BLK_SIZE; + ctx->sb.s_op = &dir_test_sops; + ctx->sb.s_fs_info = &ctx->sbi; + ctx->sb.s_bdev = &ctx->bdev; + ctx->bdev.bd_mapping = &ctx->bd_mapping; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + init_rwsem(&ctx->sb.s_umount); + strscpy(ctx->sb.s_id, "ext4_dir_kunit", sizeof(ctx->sb.s_id)); + + ctx->sbi.s_sb = &ctx->sb; + ctx->sbi.s_es = &ctx->es; + ctx->sbi.s_sbh = &ctx->sb_bh; + ctx->sbi.s_inode_size = DIR_TEST_INODE_SIZE; + ctx->sbi.s_first_ino = EXT4_GOOD_OLD_FIRST_INO; + ctx->sbi.s_bitmap_maxbytes = 16ULL * DIR_TEST_BLK_SIZE; + ctx->sbi.s_csum_seed = DIR_TEST_CSUM_SEED; + set_opt(&ctx->sb, ERRORS_CONT); + spin_lock_init(&ctx->sbi.s_bdev_wb_lock); + spin_lock_init(&ctx->sbi.s_error_lock); + spin_lock_init(&ctx->sbi.s_md_lock); + ratelimit_state_init(&ctx->sbi.s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + ctx->es.s_inodes_count = cpu_to_le32(1024); + ctx->es.s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(DIR_TEST_INODE_SIZE); + ctx->es.s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_FILETYPE); + ctx->es.s_feature_compat = cpu_to_le32(EXT4_FEATURE_COMPAT_DIR_INDEX); + ctx->es.s_feature_ro_compat = + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = DIR_TEST_BLK_SIZE; + ctx->sb_bh.b_blocknr = 1; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + + for (i = 0; i < DIR_TEST_MAX_BLOCKS; i++) { + struct buffer_head *bh = &ctx->blocks[i].bh; + + bh->b_data = ctx->blocks[i].data; + bh->b_size = DIR_TEST_BLK_SIZE; + bh->b_blocknr = DIR_TEST_FIRST_PBLK + i; + atomic_set(&bh->b_count, 1); + set_buffer_uptodate(bh); + } + + dir = &ctx->dir_ei.vfs_inode; + dir->i_sb = &ctx->sb; + dir->i_ino = DIR_TEST_DIR_INO; + dir->i_mode = S_IFDIR | 0755; + dir->i_blkbits = DIR_TEST_BLK_BITS; + dir->i_mapping = &dir->i_data; + dir->i_data.host = dir; + set_nlink(dir, 2); + atomic_set(&dir->i_count, 1); + spin_lock_init(&dir->i_lock); + i_size_ordered_init(dir); + init_rwsem(&dir->i_rwsem); + INIT_LIST_HEAD(&dir->i_io_list); + INIT_LIST_HEAD(&dir->i_wb_list); + INIT_LIST_HEAD(&dir->i_lru); + INIT_HLIST_NODE(&dir->i_hash); + inode_state_set_raw(dir, I_DIRTY); + inode_set_iversion_raw(dir, 10); + + init_rwsem(&ctx->dir_ei.xattr_sem); + init_rwsem(&ctx->dir_ei.i_data_sem); + INIT_LIST_HEAD(&ctx->dir_ei.i_orphan); + INIT_LIST_HEAD(&ctx->dir_ei.i_fc_list); + spin_lock_init(&ctx->dir_ei.i_fc_lock); + spin_lock_init(&ctx->dir_ei.i_raw_lock); + ctx->dir_ei.i_extra_isize = DIR_TEST_EXTRA_ISIZE; + ctx->dir_ei.i_csum_seed = DIR_TEST_CSUM_SEED ^ DIR_TEST_DIR_INO; + + init_mock_dir_file(ctx, FMODE_64BITHASH); + + kunit_activate_static_stub(test, ext4_map_blocks, dir_map_blocks_stub); + kunit_activate_static_stub(test, ext4_getblk, dir_getblk_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + dir_dirty_metadata_stub); + + return 0; +} + +/* + * Test 1: Validate __ext4_check_dir_entry() and ext4_check_all_de() across + * valid directory blocks (including fake '.' / '..' / csum tail entries and + * casefold+encrypted extended-hash entries) and every corruption condition. + */ +static void test_check_dir_entry_and_all_de(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + struct buffer_head *bh; + struct ext4_dir_entry_2 *de; + unsigned int tail_len = sizeof(struct ext4_dir_entry_tail); + char *buf; + + bh = alloc_dir_lblk(ctx, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + buf = bh->b_data; + + /* Valid block: '.', '..', 'alpha', and a 12-byte csum tail */ + write_de(buf, 0, DIR_TEST_DIR_INO, 12, EXT4_FT_DIR, "."); + write_de(buf, 12, DIR_TEST_ROOT_INO, 12, EXT4_FT_DIR, ".."); + write_de(buf, 24, 15, DIR_TEST_BLK_SIZE - 24 - tail_len, + EXT4_FT_REG_FILE, "alpha"); + ext4_initialize_dirent_tail(bh, DIR_TEST_BLK_SIZE); + + KUNIT_EXPECT_EQ(test, ext4_check_all_de(dir, bh, buf, + DIR_TEST_BLK_SIZE), 0); + + /* 1. rec_len smaller than minimal (8 < 12) */ + de = (struct ext4_dir_entry_2 *)(buf + 24); + de->rec_len = cpu_to_le16(8); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + &ctx->filp, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + KUNIT_EXPECT_EQ(test, ext4_check_all_de(dir, bh, buf, + DIR_TEST_BLK_SIZE), + -EFSCORRUPTED); + + /* 2. rec_len not a multiple of 4 (14 % 4 != 0) */ + de->rec_len = cpu_to_le16(14); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + + /* 3. rec_len too small for name_len (name_len=10 needs 20 bytes) */ + de->name_len = 10; + de->rec_len = cpu_to_le16(16); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + + /* + * 4. Casefolded + encrypted directory requires space for + * ext4_dir_entry_hash (+8 bytes) on regular entries, while fake + * entries ('.', '..', csum tail) remain 12 bytes. + */ + dir->i_flags |= S_CASEFOLD | S_ENCRYPTED; + write_de(buf, 24, 15, 16, EXT4_FT_REG_FILE, "ab"); + de = (struct ext4_dir_entry_2 *)(buf + 24); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + write_de(buf, 24, 15, DIR_TEST_BLK_SIZE - 24 - tail_len, + EXT4_FT_REG_FILE, "ab"); + ext4_initialize_dirent_tail(bh, DIR_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, ext4_check_all_de(dir, bh, buf, + DIR_TEST_BLK_SIZE), 0); + dir->i_flags &= ~(S_CASEFOLD | S_ENCRYPTED); + + /* 5. Directory entry overrun (next_offset > size) */ + de = (struct ext4_dir_entry_2 *)(buf + 24); + de->rec_len = cpu_to_le16(DIR_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + + /* 6. Entry too close to block end (leaves only 8 bytes < 12) */ + de->rec_len = cpu_to_le16(DIR_TEST_BLK_SIZE - 24 - 8); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + + /* 7. Inode number out of bounds (> s_inodes_count) */ + de->rec_len = cpu_to_le16(DIR_TEST_BLK_SIZE - 24 - tail_len); + de->inode = cpu_to_le32(2048); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + + /* 8. '.' directory entry cannot span to the end of the block */ + write_de(buf, 0, DIR_TEST_DIR_INO, DIR_TEST_BLK_SIZE, EXT4_FT_DIR, "."); + de = (struct ext4_dir_entry_2 *)buf; + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 0), 1); +} + +/* + * Test 2: Verify is_dx_dir(), get_dtype(), and 32-bit / 64-bit HTree telldir + * hash-position cookie helpers. + */ +static void test_dx_detection_and_hash_pos_cookies(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + __u32 major = 0xaabbccdeU; + __u32 minor = 0x12345678U; + loff_t pos; + + /* Without DIR_INDEX feature, is_dx_dir() is always 0 */ + ext4_clear_feature_dir_index(&ctx->sb); + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, DIR_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, ext4_is_dx_dir_test(dir), 0); + + /* With DIR_INDEX: multi-block dir without INDEX or inline is non-dx */ + ext4_set_feature_dir_index(&ctx->sb); + ext4_clear_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, 2 * DIR_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, ext4_is_dx_dir_test(dir), 0); + + /* Single-block dir with DIR_INDEX is treated as dx-capable */ + i_size_write(dir, DIR_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, ext4_is_dx_dir_test(dir), 1); + + /* Multi-block dir with EXT4_INODE_INDEX is dx */ + i_size_write(dir, 4 * DIR_TEST_BLK_SIZE); + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + KUNIT_EXPECT_EQ(test, ext4_is_dx_dir_test(dir), 1); + ext4_clear_inode_flag(dir, EXT4_INODE_INDEX); + + /* Inline-data dir with DIR_INDEX is treated as dx */ + ext4_set_inode_flag(dir, EXT4_INODE_INLINE_DATA); + ctx->dir_ei.i_inline_off = 160; + KUNIT_EXPECT_EQ(test, ext4_is_dx_dir_test(dir), 1); + ext4_clear_inode_flag(dir, EXT4_INODE_INLINE_DATA); + ctx->dir_ei.i_inline_off = 0; + + /* get_dtype() mapping with and without FILETYPE feature */ + KUNIT_EXPECT_EQ(test, get_dtype(&ctx->sb, EXT4_FT_REG_FILE), DT_REG); + KUNIT_EXPECT_EQ(test, get_dtype(&ctx->sb, EXT4_FT_DIR), DT_DIR); + KUNIT_EXPECT_EQ(test, get_dtype(&ctx->sb, EXT4_FT_SYMLINK), DT_LNK); + KUNIT_EXPECT_EQ(test, get_dtype(&ctx->sb, EXT4_FT_DIR_CSUM), + DT_UNKNOWN); + ext4_clear_feature_filetype(&ctx->sb); + KUNIT_EXPECT_EQ(test, get_dtype(&ctx->sb, EXT4_FT_REG_FILE), + DT_UNKNOWN); + ext4_set_feature_filetype(&ctx->sb); + + /* 64-bit hash cookie round-trip */ + ctx->filp.f_mode = FMODE_READ | FMODE_64BITHASH; + KUNIT_EXPECT_EQ(test, ext4_get_htree_eof_test(&ctx->filp), + (loff_t)EXT4_HTREE_EOF_64BIT); + pos = ext4_dir_hash2pos_test(&ctx->filp, major, minor); + KUNIT_EXPECT_EQ(test, ext4_dir_pos2maj_hash_test(&ctx->filp, pos), + major & ~1U); + KUNIT_EXPECT_EQ(test, ext4_dir_pos2min_hash_test(&ctx->filp, pos), + minor); + + /* 32-bit hash cookie round-trip */ + ctx->filp.f_mode = FMODE_READ | FMODE_32BITHASH; + KUNIT_EXPECT_EQ(test, ext4_get_htree_eof_test(&ctx->filp), + (loff_t)EXT4_HTREE_EOF_32BIT); + pos = ext4_dir_hash2pos_test(&ctx->filp, major, minor); + KUNIT_EXPECT_EQ(test, pos, (loff_t)(major >> 1)); + KUNIT_EXPECT_EQ(test, ext4_dir_pos2maj_hash_test(&ctx->filp, pos), + major & ~1U); + KUNIT_EXPECT_EQ(test, ext4_dir_pos2min_hash_test(&ctx->filp, pos), 0U); +} + +/* + * Test 3: Verify ext4_dir_operations open(), llseek(), and release() across + * 64-bit dx dirs, 32-bit dx dirs, and non-dx indirect/extent linear dirs. + */ +static void test_dir_open_llseek_and_release(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + struct dir_private_info *info; + loff_t ret; + + KUNIT_ASSERT_EQ(test, ext4_dir_operations.open(dir, &ctx->filp), 0); + info = ctx->filp.private_data; + KUNIT_ASSERT_NOT_NULL(test, info); + + /* 1. DX directory with 64-bit hash cookies */ + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, 2 * DIR_TEST_BLK_SIZE); + ctx->filp.f_mode = FMODE_READ | FMODE_LSEEK | FMODE_64BITHASH; + info->cookie = inode_query_iversion(dir); + + ret = ext4_dir_operations.llseek(&ctx->filp, EXT4_HTREE_EOF_64BIT, + SEEK_SET); + KUNIT_EXPECT_EQ(test, ret, (loff_t)EXT4_HTREE_EOF_64BIT); + KUNIT_EXPECT_FALSE(test, inode_eq_iversion(dir, info->cookie)); + + ret = ext4_dir_operations.llseek(&ctx->filp, -1, SEEK_SET); + KUNIT_EXPECT_EQ(test, ret, (loff_t)-EINVAL); + + /* 2. DX directory with 32-bit hash cookies caps at 32-bit EOF */ + ctx->filp.f_mode = FMODE_READ | FMODE_LSEEK | FMODE_32BITHASH; + ret = ext4_dir_operations.llseek(&ctx->filp, EXT4_HTREE_EOF_32BIT, + SEEK_SET); + KUNIT_EXPECT_EQ(test, ret, (loff_t)EXT4_HTREE_EOF_32BIT); + ret = ext4_dir_operations.llseek(&ctx->filp, + (loff_t)EXT4_HTREE_EOF_32BIT + 1, + SEEK_SET); + KUNIT_EXPECT_EQ(test, ret, (loff_t)-EINVAL); + + /* 3. Non-DX indirect directory uses s_bitmap_maxbytes and i_size */ + ext4_clear_inode_flag(dir, EXT4_INODE_INDEX); + ext4_clear_inode_flag(dir, EXT4_INODE_EXTENTS); + i_size_write(dir, 3 * DIR_TEST_BLK_SIZE); + info->cookie = inode_query_iversion(dir); + + ret = ext4_dir_operations.llseek(&ctx->filp, 0, SEEK_END); + KUNIT_EXPECT_EQ(test, ret, (loff_t)(3 * DIR_TEST_BLK_SIZE)); + KUNIT_EXPECT_FALSE(test, inode_eq_iversion(dir, info->cookie)); + + ret = ext4_dir_operations.llseek(&ctx->filp, + ctx->sbi.s_bitmap_maxbytes + 1, + SEEK_SET); + KUNIT_EXPECT_EQ(test, ret, (loff_t)-EINVAL); + + KUNIT_EXPECT_EQ(test, ext4_dir_operations.release(dir, &ctx->filp), 0); + ctx->filp.private_data = NULL; +} + +/* + * Test 4: Verify ext4_htree_store_dirent() rbtree sorting across major and + * minor hashes, exact 64-bit hash collision chaining, and cleanup via + * ext4_htree_free_dir_info(). + */ +static void test_htree_store_dirent_and_free(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + struct dir_private_info *info; + int err; + + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, 2 * DIR_TEST_BLK_SIZE); + KUNIT_ASSERT_EQ(test, ext4_dir_operations.open(dir, &ctx->filp), 0); + info = ctx->filp.private_data; + + /* Insert out of hash order, including 3 colliding entries at 0x200:7 */ + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x400, 0x10, 34, + EXT4_FT_REG_FILE, "fourth"), 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x100, 0x20, 31, + EXT4_FT_DIR, "first"), 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x400, 0x05, 33, + EXT4_FT_SYMLINK, "third"), 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x200, 0x07, 32, + EXT4_FT_REG_FILE, "c1"), 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x200, 0x07, 35, + EXT4_FT_REG_FILE, "c2"), 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x200, 0x07, 36, + EXT4_FT_REG_FILE, "c3"), 0); + + /* Pre-prime cookie and next_hash so ext4_dx_readdir drains info->root */ + info->cookie = inode_query_iversion(dir); + info->next_hash = ~0U; + reset_capture(&ctx->cap, 0, 0); + + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 6); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "first"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[0].d_type, (unsigned int)DT_DIR); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, "c1"); + /* Collision list inserts after head: c1 -> c3 -> c2 */ + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[2].name, "c3"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[3].name, "c2"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[4].name, "third"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[4].d_type, (unsigned int)DT_LNK); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[5].name, "fourth"); + KUNIT_EXPECT_EQ(test, ctx->cap.ctx.pos, (loff_t)EXT4_HTREE_EOF_64BIT); + + /* Re-populate nodes so release exercises non-empty free_rb_tree_fname */ + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x300, 0x01, 40, + EXT4_FT_REG_FILE, "leftover1"), + 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x300, 0x01, 41, + EXT4_FT_REG_FILE, "leftover2"), + 0); + KUNIT_EXPECT_EQ(test, ext4_dir_operations.release(dir, &ctx->filp), 0); + ctx->filp.private_data = NULL; +} + +/* + * Test 5: Verify linear ext4_readdir() across multi-block directories with + * sparse holes, deleted entries, dir_emit() stop/resume, i_version change + * mid-entry revalidation, checksum/corruption block skipping, and + * ERR_BAD_DX_DIR fallback clearing EXT4_INODE_INDEX. + */ +static void test_linear_readdir(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + struct buffer_head *bh0, *bh2, *bh3; + unsigned int tail_len = sizeof(struct ext4_dir_entry_tail); + loff_t resume_pos; + int err; + + /* + * 4-block non-indexed linear directory: + * lblk 0: '.', '..', deleted (ino=0), 'file_a', 'sym_b' + csum tail + * lblk 1: sparse hole (unmapped) + * lblk 2: 'sub_c', 'fifo_d' + csum tail + * lblk 3: 'last_e' + csum tail + */ + ext4_clear_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, 4 * DIR_TEST_BLK_SIZE); + dir->i_blocks = (4 * DIR_TEST_BLK_SIZE) >> 9; + + bh0 = alloc_dir_lblk(ctx, 0); + bh2 = alloc_dir_lblk(ctx, 2); + bh3 = alloc_dir_lblk(ctx, 3); + KUNIT_ASSERT_NOT_NULL(test, bh0); + KUNIT_ASSERT_NOT_NULL(test, bh2); + KUNIT_ASSERT_NOT_NULL(test, bh3); + + write_de(bh0->b_data, 0, DIR_TEST_DIR_INO, 12, EXT4_FT_DIR, "."); + write_de(bh0->b_data, 12, DIR_TEST_ROOT_INO, 12, EXT4_FT_DIR, ".."); + write_de(bh0->b_data, 24, 0, 16, EXT4_FT_REG_FILE, "deleted"); + write_de(bh0->b_data, 40, 51, 20, EXT4_FT_REG_FILE, "file_a"); + write_de(bh0->b_data, 60, 52, DIR_TEST_BLK_SIZE - 60 - tail_len, + EXT4_FT_SYMLINK, "sym_b"); + ext4_initialize_dirent_tail(bh0, DIR_TEST_BLK_SIZE); + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh0), 0); + + write_de(bh2->b_data, 0, 53, 16, EXT4_FT_DIR, "sub_c"); + write_de(bh2->b_data, 16, 54, DIR_TEST_BLK_SIZE - 16 - tail_len, + EXT4_FT_FIFO, "fifo_d"); + ext4_initialize_dirent_tail(bh2, DIR_TEST_BLK_SIZE); + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh2), 0); + + write_de(bh3->b_data, 0, 55, DIR_TEST_BLK_SIZE - tail_len, + EXT4_FT_REG_FILE, "last_e"); + ext4_initialize_dirent_tail(bh3, DIR_TEST_BLK_SIZE); + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh3), 0); + + KUNIT_ASSERT_EQ(test, ext4_dir_operations.open(dir, &ctx->filp), 0); + + /* 1. Stop after 3 emitted entries ('.', '..', 'file_a'), then resume */ + reset_capture(&ctx->cap, 0, 3); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 3); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "."); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, ".."); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[2].name, "file_a"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[2].d_type, (unsigned int)DT_REG); + + resume_pos = ctx->cap.ctx.pos; + KUNIT_EXPECT_EQ(test, resume_pos, (loff_t)60); + + reset_capture(&ctx->cap, resume_pos, 0); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 4); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "sym_b"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[0].d_type, (unsigned int)DT_LNK); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, "sub_c"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[1].d_type, (unsigned int)DT_DIR); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[2].name, "fifo_d"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[2].d_type, (unsigned int)DT_FIFO); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[3].name, "last_e"); + + /* + * 2. Unaligned ctx->pos (44, inside 'file_a' at [40..60)) combined + * with an i_version bump triggers block-start rescan and snaps to 60. + */ + inode_inc_iversion(dir); + reset_capture(&ctx->cap, 44, 1); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 1); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "sym_b"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[0].offset, (loff_t)60); + + /* + * 3. Corrupt block 0 checksum and corrupt second entry in block 2: + * ext4_readdir() skips block 0, emits 'sub_c' from block 2 before + * skipping the rest of block 2, and still emits 'last_e' from block 3. + */ + clear_buffer_verified(bh0); + bh0->b_data[DIR_TEST_BLK_SIZE - 1] ^= 0xff; + ((struct ext4_dir_entry_2 *)(bh2->b_data + 16))->rec_len = + cpu_to_le16(8); + + reset_capture(&ctx->cap, 0, 0); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 2); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "sub_c"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, "last_e"); + + /* + * 4. ERR_BAD_DX_DIR fallback when !metadata_csum clears + * EXT4_INODE_INDEX and falls back to linear block scanning. + */ + ext4_clear_feature_metadata_csum(&ctx->sb); + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + write_de(bh3->b_data, 0, 55, DIR_TEST_BLK_SIZE, + EXT4_FT_REG_FILE, "last_e"); + kunit_activate_static_stub(test, ext4_htree_fill_tree, + dir_htree_fill_tree_stub); + ctx->htree_mode = DIR_HTREE_STUB_BAD_DX; + + reset_capture(&ctx->cap, 3 * DIR_TEST_BLK_SIZE, 0); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, ext4_test_inode_flag(dir, EXT4_INODE_INDEX)); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 1); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "last_e"); + + KUNIT_EXPECT_EQ(test, ext4_dir_operations.release(dir, &ctx->filp), 0); + ctx->filp.private_data = NULL; +} + +/* + * Test 6: Verify ext4_dx_readdir() across multi-batch leaf refills, + * mid-collision-chain stop & extra_fname resumption, EOF short-circuit, + * f_pos seek tree reset, and mid-stream i_version invalidation. + */ +static void test_dx_readdir(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + loff_t saved_pos, seek_pos; + int err; + + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, 2 * DIR_TEST_BLK_SIZE); + kunit_activate_static_stub(test, ext4_htree_fill_tree, + dir_htree_fill_tree_stub); + ctx->htree_mode = DIR_HTREE_STUB_TWO_BATCH; + + KUNIT_ASSERT_EQ(test, ext4_dir_operations.open(dir, &ctx->filp), 0); + + /* + * 1. Stop after 3 entries ('.', '..', and first collision entry): + * leaves the second colliding entry queued on info->extra_fname. + */ + reset_capture(&ctx->cap, 0, 3); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->htree_fill_calls, 1); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 3); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "."); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, ".."); + /* Collision chain at 0x1000:0x55 emits coll_a then coll_b */ + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[2].name, "coll_a"); + saved_pos = ctx->cap.ctx.pos; + + /* + * 2. Resume from saved_pos: emits leftover 'coll_b' from extra_fname + * without refilling batch 1, then refills at next_hash=0x2000 for + * 'leaf2_sub', and finishes at EXT4_HTREE_EOF_64BIT. + */ + reset_capture(&ctx->cap, saved_pos, 0); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->htree_fill_calls, 2); + KUNIT_EXPECT_EQ(test, ctx->last_fill_start_hash, 0x2000U); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 2); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "coll_b"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, "leaf2_sub"); + KUNIT_EXPECT_EQ(test, ctx->cap.ctx.pos, (loff_t)EXT4_HTREE_EOF_64BIT); + + /* 3. Calling again at HTREE_EOF returns 0 immediately without refill */ + reset_capture(&ctx->cap, ctx->cap.ctx.pos, 0); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->cap.count, 0); + KUNIT_EXPECT_EQ(test, ctx->htree_fill_calls, 2); + + /* + * 4. Seeking to a 64-bit hash cookie resets the cached state and + * refills starting from (pos2maj_hash, pos2min_hash); bumping + * i_version after the first entry forces an rbtree refill mid-walk. + */ + seek_pos = ext4_dir_hash2pos_test(&ctx->filp, 0x1000, 0x55); + reset_capture(&ctx->cap, seek_pos, 0); + ctx->cap.bump_iversion_after_first = dir; + + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_GE(test, ctx->htree_fill_calls, 4); + KUNIT_EXPECT_GE(test, ctx->cap.count, 3); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "coll_a"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, "coll_b"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[ctx->cap.count - 1].name, + "leaf2_sub"); + + KUNIT_EXPECT_EQ(test, ext4_dir_operations.release(dir, &ctx->filp), 0); + ctx->filp.private_data = NULL; +} + +static struct kunit_case ext4_dir_test_cases[] = { + KUNIT_CASE(test_check_dir_entry_and_all_de), + KUNIT_CASE(test_dx_detection_and_hash_pos_cookies), + KUNIT_CASE(test_dir_open_llseek_and_release), + KUNIT_CASE(test_htree_store_dirent_and_free), + KUNIT_CASE(test_linear_readdir), + KUNIT_CASE(test_dx_readdir), + {} +}; + +static struct kunit_suite ext4_dir_test_suite = { + .name = "ext4_dir_test", + .init = dir_test_init, + .test_cases = ext4_dir_test_cases, +}; + +kunit_test_suites(&ext4_dir_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 directory operations"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/dir.c b/fs/ext4/dir.c index f9b6aaabcd1772..43f4f2d451aa89 100644 --- a/fs/ext4/dir.c +++ b/fs/ext4/dir.c @@ -712,3 +712,36 @@ const struct file_operations ext4_dir_operations = { .release = ext4_release_dir, .setlease = generic_setlease, }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dir_operations); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_is_dx_dir_test(struct inode *inode) +{ + return is_dx_dir(inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_is_dx_dir_test); + +loff_t ext4_dir_hash2pos_test(struct file *filp, __u32 major, __u32 minor) +{ + return hash2pos(filp, major, minor); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dir_hash2pos_test); + +__u32 ext4_dir_pos2maj_hash_test(struct file *filp, loff_t pos) +{ + return pos2maj_hash(filp, pos); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dir_pos2maj_hash_test); + +__u32 ext4_dir_pos2min_hash_test(struct file *filp, loff_t pos) +{ + return pos2min_hash(filp, pos); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dir_pos2min_hash_test); + +loff_t ext4_get_htree_eof_test(struct file *filp) +{ + return ext4_get_htree_eof(filp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_htree_eof_test); +#endif diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index 9cf1dd6351a720..646c017dda1c61 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -3069,6 +3069,14 @@ static inline unsigned char get_dtype(struct super_block *sb, int filetype) } extern int ext4_check_all_de(struct inode *dir, struct buffer_head *bh, void *buf, int buf_size); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_is_dx_dir_test(struct inode *inode); +extern loff_t ext4_dir_hash2pos_test(struct file *filp, __u32 major, + __u32 minor); +extern __u32 ext4_dir_pos2maj_hash_test(struct file *filp, loff_t pos); +extern __u32 ext4_dir_pos2min_hash_test(struct file *filp, loff_t pos); +extern loff_t ext4_get_htree_eof_test(struct file *filp); +#endif /* fsync.c */ extern int ext4_sync_file(struct file *, loff_t, loff_t, int); diff --git a/fs/ext4/namei.c b/fs/ext4/namei.c index ed590010b04631..b2753daad49f4a 100644 --- a/fs/ext4/namei.c +++ b/fs/ext4/namei.c @@ -36,6 +36,7 @@ #include #include #include +#include #include "ext4.h" #include "ext4_jbd2.h" @@ -1002,6 +1003,9 @@ int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash, __u32 hashval; struct fscrypt_str tmp_str; + KUNIT_STATIC_STUB_REDIRECT(ext4_htree_fill_tree, dir_file, start_hash, + start_minor_hash, next_hash); + dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n", start_hash, start_minor_hash)); dir = file_inode(dir_file); From bae28a1b11f422d0214654800d9425e042295c71 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Thu, 19 Nov 2026 13:23:01 +0000 Subject: [PATCH 1578/2102] ext4: add KUnit regression tests for inode migration fixes Add KUnit regression tests in fs/ext4/migrate-test.c covering the ext4_ext_migrate() bug fixes in the tree: - test_ext_migrate_caps_long_run_at_init_max_len(): verify that a contiguous run longer than EXT_INIT_MAX_LEN is split into multiple initialized extents, covering commit b0a3f2c102e8 ("ext4: cap migration extent length at EXT_INIT_MAX_LEN"). - test_ext_migrate_survives_handle_restart(): verify that a handle restart during extent insertion does not abort migration, covering commit 3b6aee59883c ("ext4: clear journal restart indication after inserting extent"). - test_ext_migrate_reports_concurrent_allocation() and an -EIO check in test_ext_migrate_error_rollback_frees_tmp_extent_blocks(): verify that migration errors are returned to the caller instead of being overwritten, covering commit 82e2a5743b6a ("ext4: don't clobber the migration error in ext4_ext_migrate()"). - test_ext_migrate_credit_or_dirty_failure_keeps_live_blocks(): verify that post-swap ext4_journal_ensure_credits() or ext4_mark_inode_dirty() failures leave tmp_inode empty on eviction and do not free the migrated inode's extent blocks, covering commit 047061e6a6da ("ext4: don't free the tmp_inode tree after a partial migration swap"), commit ed8c07b7692c ("ext4: drop tmp inode ownership before migration cleanup"), and commit 7c1f0eea4a9b ("ext4: fix failed migrate freeing extent tree blocks"). Add KUNIT_STATIC_STUB_REDIRECT() hooks and EXPORT_SYMBOL_FOR_EXT4_TEST() exports for ext4_datasem_ensure_credits() in fs/ext4/extents.c and __ext4_journal_ensure_credits() in fs/ext4/ext4_jbd2.c so the KUnit tests can emulate transaction restarts, concurrent block allocations, and post-swap credit failures without a journal. Signed-off-by: Theodore Ts'o --- fs/ext4/ext4_jbd2.c | 4 + fs/ext4/extents.c | 4 + fs/ext4/migrate-test.c | 329 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 334 insertions(+), 3 deletions(-) diff --git a/fs/ext4/ext4_jbd2.c b/fs/ext4/ext4_jbd2.c index 3e6c9ce108aded..23e53c9cc0ceda 100644 --- a/fs/ext4/ext4_jbd2.c +++ b/fs/ext4/ext4_jbd2.c @@ -186,6 +186,9 @@ handle_t *__ext4_journal_start_reserved(handle_t *handle, unsigned int line, int __ext4_journal_ensure_credits(handle_t *handle, int check_cred, int extend_cred, int revoke_cred) { + KUNIT_STATIC_STUB_REDIRECT(__ext4_journal_ensure_credits, handle, + check_cred, extend_cred, revoke_cred); + if (!ext4_handle_valid(handle)) return 0; if (is_handle_aborted(handle)) @@ -197,6 +200,7 @@ int __ext4_journal_ensure_credits(handle_t *handle, int check_cred, revoke_cred = max(0, revoke_cred - handle->h_revoke_credits); return ext4_journal_extend(handle, extend_cred, revoke_cred); } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_journal_ensure_credits); static void ext4_journal_abort_handle(const char *caller, unsigned int line, const char *err_fn, diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index cbe187914fe2a0..10d36012ade492 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -142,12 +142,16 @@ int ext4_datasem_ensure_credits(handle_t *handle, struct inode *inode, int ret; int dropped = 0; + KUNIT_STATIC_STUB_REDIRECT(ext4_datasem_ensure_credits, handle, inode, + check_cred, restart_cred, revoke_cred); + ret = ext4_journal_ensure_credits_fn(handle, check_cred, restart_cred, revoke_cred, ext4_ext_trunc_restart_fn(inode, &dropped)); if (dropped) down_write(&EXT4_I(inode)->i_data_sem); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_datasem_ensure_credits); /* * could return: diff --git a/fs/ext4/migrate-test.c b/fs/ext4/migrate-test.c index a17830489e3636..5a616827e78c89 100644 --- a/fs/ext4/migrate-test.c +++ b/fs/ext4/migrate-test.c @@ -68,6 +68,18 @@ struct migrate_test_ctx { int new_inode_err; ext4_fsblk_t freed_blks[MIGRATE_MAX_FREED_REC]; unsigned int freed_cnt; + unsigned int datasem_restarts; + struct inode *race_inode; + int mark_dirty_err; + struct inode *mark_dirty_err_inode; + int ensure_credits_err; + struct inode *ensure_credits_after_swap_inode; + bool evict_tmp_seen; + loff_t evict_tmp_isize; + blkcnt_t evict_tmp_iblocks; + u16 evict_tmp_eh_entries; + u16 evict_tmp_eh_depth; + __u32 evict_tmp_csum_seed; bool rwsem_inited; bool es_shrinker_inited; }; @@ -113,6 +125,19 @@ static void migrate_test_free_inode(struct inode *inode) static void migrate_test_evict_inode(struct inode *inode) { + struct kunit *test = active_migrate_test; + + if (test && test->priv && inode->i_ino == 99) { + struct migrate_test_ctx *ctx = test->priv; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + + ctx->evict_tmp_seen = true; + ctx->evict_tmp_isize = i_size_read(inode); + ctx->evict_tmp_iblocks = inode->i_blocks; + ctx->evict_tmp_eh_entries = le16_to_cpu(eh->eh_entries); + ctx->evict_tmp_eh_depth = le16_to_cpu(eh->eh_depth); + ctx->evict_tmp_csum_seed = EXT4_I(inode)->i_csum_seed; + } truncate_inode_pages_final(&inode->i_data); ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); clear_inode(inode); @@ -270,6 +295,31 @@ static int migrate_handle_dirty_metadata_stub(const char *where, static int migrate_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, const char *func, unsigned int line) { + struct kunit *test = active_migrate_test; + + if (test && test->priv) { + struct migrate_test_ctx *ctx = test->priv; + + if (ctx->mark_dirty_err && inode == ctx->mark_dirty_err_inode) + return ctx->mark_dirty_err; + } + return 0; +} + +static int migrate_ensure_credits_stub(handle_t *handle, int check_cred, + int extend_cred, int revoke_cred) +{ + struct kunit *test = active_migrate_test; + + if (test && test->priv) { + struct migrate_test_ctx *ctx = test->priv; + + if (ctx->ensure_credits_err && + ctx->ensure_credits_after_swap_inode && + ext4_test_inode_flag(ctx->ensure_credits_after_swap_inode, + EXT4_INODE_EXTENTS)) + return ctx->ensure_credits_err; + } return 0; } @@ -365,6 +415,36 @@ static bool migrate_was_freed(struct migrate_test_ctx *ctx, ext4_fsblk_t blk) return false; } +/* + * Emulate ext4_datasem_ensure_credits() having to restart the transaction: + * i_data_sem is dropped and re-acquired and 1 is returned. + */ +static int migrate_datasem_restart_stub(handle_t *handle, struct inode *inode, + int check_cred, int restart_cred, + int revoke_cred) +{ + struct migrate_test_ctx *ctx = active_migrate_test->priv; + + up_write(&EXT4_I(inode)->i_data_sem); + down_write(&EXT4_I(inode)->i_data_sem); + ctx->datasem_restarts++; + return 1; +} + +/* + * Emulate a block allocation racing with the migration of + * ctx->race_inode, which clears EXT4_STATE_EXT_MIGRATE on it. + */ +static int migrate_datasem_race_stub(handle_t *handle, struct inode *inode, + int check_cred, int restart_cred, + int revoke_cred) +{ + struct migrate_test_ctx *ctx = active_migrate_test->priv; + + ext4_clear_inode_state(ctx->race_inode, EXT4_STATE_EXT_MIGRATE); + return 0; +} + KUNIT_DEFINE_ACTION_WRAPPER(migrate_iput_action, iput, struct inode *); static struct inode *migrate_make_test_inode(struct kunit *test, unsigned long ino, @@ -849,8 +929,8 @@ static void test_ext_migrate_dind_tind_and_multilevel_tree(struct kunit *test) /* * Test 4: When reading an indirect block fails midway after tmp_inode has * already grown a depth-1 extent tree, free_ext_block() / free_ext_idx() - * frees the allocated temporary extent metadata block and leaves the original - * inode untouched. + * frees the allocated temporary extent metadata block, leaves the original + * inode untouched, and ext4_ext_migrate() returns the error. */ static void test_ext_migrate_error_rollback_frees_tmp_extent_blocks(struct kunit *test) { @@ -876,7 +956,8 @@ static void test_ext_migrate_error_rollback_frees_tmp_extent_blocks(struct kunit EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(MIGRATE_TEST_TOTAL_BLKS + 50); - (void)ext4_ext_migrate(inode); + /* The read error is reported to the caller, not swallowed */ + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EIO); /* Temporary extent leaf block allocated during build must be freed */ KUNIT_EXPECT_TRUE(test, migrate_was_freed(ctx, expected_leaf_blk)); @@ -1038,6 +1119,244 @@ static void test_ind_migrate_rejections(struct kunit *test) ext4_blocks_count_set(ctx->es, MIGRATE_TEST_TOTAL_BLKS); } +/* + * Test 8: ext4_ext_migrate() splits a physically and logically contiguous + * run longer than EXT_INIT_MAX_LEN into multiple initialized extents rather + * than encoding the raw length into ee_len, which would turn the extent + * into an unwritten one (or wrap ee_len) and lose the file data. + */ +static void test_ext_migrate_caps_long_run_at_init_max_len(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + const unsigned int per_blk = MIGRATE_TEST_BLK_SIZE / sizeof(__le32); + const unsigned int nr_ind = 128; + const ext4_fsblk_t data_pblk = 2000; + const ext4_fsblk_t ind_pblk = 600, dind_pblk = 700; + const ext4_lblk_t len = EXT4_NDIR_BLOCKS + per_blk + nr_ind * per_blk; + const int max_len = EXT_INIT_MAX_LEN; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + struct buffer_head *bh; + struct inode *inode; + ext4_fsblk_t pblk = data_pblk; + unsigned int i, j; + + /* 12 + 256 + 128 * 256 = 33036 blocks > EXT_INIT_MAX_LEN */ + KUNIT_ASSERT_GT(test, len, (ext4_lblk_t)max_len); + ext4_blocks_count_set(ctx->es, data_pblk + len + 1024); + + inode = migrate_make_test_inode(test, 22, S_IFREG | 0644); + i_size_write(inode, (loff_t)len * MIGRATE_TEST_BLK_SIZE); + + for (i = 0; i < EXT4_NDIR_BLOCKS; i++) + EXT4_I(inode)->i_data[i] = cpu_to_le32(pblk++); + + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(ind_pblk); + bh = migrate_get_or_create_bh(ctx, ind_pblk); + KUNIT_ASSERT_NOT_NULL(test, bh); + for (j = 0; j < per_blk; j++) + ((__le32 *)bh->b_data)[j] = cpu_to_le32(pblk++); + brelse(bh); + + EXT4_I(inode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(dind_pblk); + bh = migrate_get_or_create_bh(ctx, dind_pblk); + KUNIT_ASSERT_NOT_NULL(test, bh); + for (i = 0; i < nr_ind; i++) + ((__le32 *)bh->b_data)[i] = cpu_to_le32(dind_pblk + 1 + i); + brelse(bh); + + for (i = 0; i < nr_ind; i++) { + bh = migrate_get_or_create_bh(ctx, dind_pblk + 1 + i); + KUNIT_ASSERT_NOT_NULL(test, bh); + for (j = 0; j < per_blk; j++) + ((__le32 *)bh->b_data)[j] = cpu_to_le32(pblk++); + brelse(bh); + } + inode->i_blocks = (blkcnt_t)(len + 2 + nr_ind) * + (MIGRATE_TEST_BLK_SIZE >> 9); + + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + eh = ext_inode_hdr(inode); + if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) || + !eh->eh_entries) + return; + + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_depth), 0U); + ex = EXT_FIRST_EXTENT(eh); + + /* Extent 0: lblk [0..32767] -> data_pblk, initialized */ + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 0U); + KUNIT_EXPECT_FALSE(test, ext4_ext_is_unwritten(&ex[0])); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), max_len); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[0]), data_pblk); + + /* Extent 1: remainder of the run, initialized */ + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2U); + if (le16_to_cpu(eh->eh_entries) < 2) + return; + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), (u32)max_len); + KUNIT_EXPECT_FALSE(test, ext4_ext_is_unwritten(&ex[1])); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[1]), + (int)len - max_len); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[1]), data_pblk + max_len); + + /* Indirect metadata blocks were released */ + KUNIT_EXPECT_TRUE(test, migrate_was_freed(ctx, ind_pblk)); + KUNIT_EXPECT_TRUE(test, migrate_was_freed(ctx, dind_pblk + 1)); +} + +/* + * Test 9: A transaction restart while inserting an extent into tmp_inode + * (ext4_datasem_ensure_credits() returning 1) is not an error; migration + * still completes and builds every extent. + */ +static void test_ext_migrate_survives_handle_restart(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + struct inode *inode; + + kunit_activate_static_stub(test, ext4_datasem_ensure_credits, + migrate_datasem_restart_stub); + + inode = migrate_make_test_inode(test, 23, S_IFREG | 0644); + i_size_write(inode, 12 * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 4 * (MIGRATE_TEST_BLK_SIZE >> 9); + + /* Three discontiguous runs: [0..1] -> 100, [4] -> 200, [8] -> 300 */ + EXT4_I(inode)->i_data[0] = cpu_to_le32(100); + EXT4_I(inode)->i_data[1] = cpu_to_le32(101); + EXT4_I(inode)->i_data[4] = cpu_to_le32(200); + EXT4_I(inode)->i_data[8] = cpu_to_le32(300); + + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), 0); + KUNIT_EXPECT_EQ(test, ctx->datasem_restarts, 3U); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) + return; + + eh = ext_inode_hdr(inode); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3U); + if (le16_to_cpu(eh->eh_entries) != 3) + return; + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 0U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 2); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[0]), 100ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 4U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[1]), 200ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[2].ee_block), 8U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[2]), 300ULL); +} + +/* + * Test 10: If a concurrent block allocation invalidates the migration, + * ext4_ext_migrate() reports -EAGAIN instead of claiming success, and the + * inode keeps its indirect block map. + */ +static void test_ext_migrate_reports_concurrent_allocation(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + + kunit_activate_static_stub(test, ext4_datasem_ensure_credits, + migrate_datasem_race_stub); + + inode = migrate_make_test_inode(test, 24, S_IFREG | 0644); + i_size_write(inode, 4 * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 2 * (MIGRATE_TEST_BLK_SIZE >> 9); + EXT4_I(inode)->i_data[0] = cpu_to_le32(100); + EXT4_I(inode)->i_data[3] = cpu_to_le32(200); + ctx->race_inode = inode; + + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EAGAIN); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[0]), 100U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[3]), 200U); + + ctx->race_inode = NULL; +} + +/* + * Test 11: Verify ext4_ext_migrate() clears tmp_inode's in-memory extent + * header, i_size, i_blocks, and csum_seed even when ext4_journal_ensure_credits() + * fails after swap or when ext4_mark_inode_dirty() fails inside + * ext4_ext_swap_inode_data(), so neither free_ext_block() nor + * ext4_evict_inode() frees the migrated inode's live blocks. + */ +static void test_ext_migrate_credit_or_dirty_failure_keeps_live_blocks( + struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + ext4_fsblk_t ext_idx_pblk; + unsigned int i; + + /* + * 1. Six discontiguous direct blocks produce a depth-1 extent tree + * (exceeding the 4 inline root extents). Failing + * __ext4_journal_ensure_credits() with -EROFS after swapping must + * still leave tmp_inode empty when evicted. + */ + kunit_activate_static_stub(test, __ext4_journal_ensure_credits, + migrate_ensure_credits_stub); + inode = migrate_make_test_inode(test, 25, S_IFREG | 0644); + i_size_write(inode, 12 * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 6 * (MIGRATE_TEST_BLK_SIZE >> 9); + for (i = 0; i < 6; i++) + EXT4_I(inode)->i_data[i * 2] = cpu_to_le32(100 + i * 10); + + ctx->evict_tmp_seen = false; + ctx->ensure_credits_after_swap_inode = inode; + ctx->ensure_credits_err = -EROFS; + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EROFS); + ctx->ensure_credits_err = 0; + ctx->ensure_credits_after_swap_inode = NULL; + + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_depth), 1U); + KUNIT_ASSERT_TRUE(test, ctx->evict_tmp_seen); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_isize, 0LL); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_iblocks, (blkcnt_t)0); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_eh_entries, 0U); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_eh_depth, 0U); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_csum_seed, 0xabcdef01U); + + /* + * 2. Failing ext4_mark_inode_dirty() inside ext4_ext_swap_inode_data() + * after ownership moved to inode must NOT free inode's new extent index + * block via free_ext_block(handle, tmp_inode). + */ + inode = migrate_make_test_inode(test, 26, S_IFREG | 0644); + i_size_write(inode, 12 * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 6 * (MIGRATE_TEST_BLK_SIZE >> 9); + for (i = 0; i < 6; i++) + EXT4_I(inode)->i_data[i * 2] = cpu_to_le32(200 + i * 10); + + ext_idx_pblk = ctx->next_alloc_pblk; + ctx->freed_cnt = 0; + ctx->evict_tmp_seen = false; + ctx->mark_dirty_err = -EIO; + ctx->mark_dirty_err_inode = inode; + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EIO); + ctx->mark_dirty_err = 0; + ctx->mark_dirty_err_inode = NULL; + + KUNIT_EXPECT_FALSE(test, migrate_was_freed(ctx, ext_idx_pblk)); + KUNIT_ASSERT_TRUE(test, ctx->evict_tmp_seen); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_isize, 0LL); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_iblocks, (blkcnt_t)0); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_eh_entries, 0U); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_eh_depth, 0U); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_csum_seed, 0xabcdef01U); +} + static struct kunit_case ext4_migrate_test_cases[] = { KUNIT_CASE(test_ext_migrate_precondition_checks_and_fast_symlink), KUNIT_CASE(test_ext_migrate_direct_and_ind_coalescing_and_holes), @@ -1046,6 +1365,10 @@ static struct kunit_case ext4_migrate_test_cases[] = { KUNIT_CASE(test_ext_swap_inode_data_detects_concurrent_allocation), KUNIT_CASE(test_ind_migrate_empty_and_single_direct_extent), KUNIT_CASE(test_ind_migrate_rejections), + KUNIT_CASE(test_ext_migrate_caps_long_run_at_init_max_len), + KUNIT_CASE(test_ext_migrate_survives_handle_restart), + KUNIT_CASE(test_ext_migrate_reports_concurrent_allocation), + KUNIT_CASE(test_ext_migrate_credit_or_dirty_failure_keeps_live_blocks), {} }; From dacbba76c2d0d057772d2c4ac5f253191aa9bf46 Mon Sep 17 00:00:00 2001 From: Jeff Barnes Date: Fri, 2 Oct 2026 18:26:39 -0400 Subject: [PATCH 1579/2102] tracing/user_events: Fail fork when event state duplication fails Registered user events are retained across fork, but duplicating their state for a child with a separate mm can fail. Both user_event_mm_dup() and user_events_fork() currently return void, so allocation failure silently creates a child without the inherited registration state. The child can consequently retain a stale copy-on-write enable word and miss later event enable and disable updates. Return an error from user_event_mm_dup() and user_events_fork(), and perform the duplication in copy_process() while failure can still be unwound. Return -ENOMEM when the child user_event_mm or any of its enablers cannot be duplicated. Add a cleanup path so successfully acquired user-events state is removed if a later fork operation fails. Preserve the existing CLONE_VM behavior and its task reference accounting. A deterministic allocation-failure test on upstream master previously allowed fork() to succeed while the child missed an enablement update. With this change, the same fork fails with ENOMEM. The complete user_events ABI suite passes. Cc: stable@vger.kernel.org Fixes: 7235759084a4 ("tracing/user_events: Use remote writes for event enablement") Link: https://patch.msgid.link/20261002222639.1964370-1-jeffbarnes@linux.microsoft.com Signed-off-by: Jeff Barnes Reviewed-by: Beau Belgrave Signed-off-by: Steven Rostedt --- include/linux/user_events.h | 16 +++++++--------- kernel/fork.c | 8 ++++++-- kernel/trace/trace_events_user.c | 8 +++++--- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/include/linux/user_events.h b/include/linux/user_events.h index 57d1ff0060901a..75f1841267275c 100644 --- a/include/linux/user_events.h +++ b/include/linux/user_events.h @@ -27,28 +27,26 @@ struct user_event_mm { struct rcu_work put_rwork; }; -extern void user_event_mm_dup(struct task_struct *t, - struct user_event_mm *old_mm); +int user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm); extern void user_event_mm_remove(struct task_struct *t); -static inline void user_events_fork(struct task_struct *t, - u64 clone_flags) +static inline int user_events_fork(struct task_struct *t, u64 clone_flags) { struct user_event_mm *old_mm; if (!t || !current->user_event_mm) - return; + return 0; old_mm = current->user_event_mm; if (clone_flags & CLONE_VM) { t->user_event_mm = old_mm; refcount_inc(&old_mm->tasks); - return; + return 0; } - user_event_mm_dup(t, old_mm); + return user_event_mm_dup(t, old_mm); } static inline void user_events_execve(struct task_struct *t) @@ -67,9 +65,9 @@ static inline void user_events_exit(struct task_struct *t) user_event_mm_remove(t); } #else -static inline void user_events_fork(struct task_struct *t, - u64 clone_flags) +static inline int user_events_fork(struct task_struct *t, u64 clone_flags) { + return 0; } static inline void user_events_execve(struct task_struct *t) diff --git a/kernel/fork.c b/kernel/fork.c index 5efceb8d58a78b..cdba6ba6335d2d 100644 --- a/kernel/fork.c +++ b/kernel/fork.c @@ -2328,9 +2328,12 @@ __latent_entropy struct task_struct *copy_process( retval = copy_mm(clone_flags, p); if (retval) goto bad_fork_cleanup_signal; - retval = copy_namespaces(clone_flags, p); + retval = user_events_fork(p, clone_flags); if (retval) goto bad_fork_cleanup_mm; + retval = copy_namespaces(clone_flags, p); + if (retval) + goto bad_fork_cleanup_user_events; retval = copy_io(clone_flags, p); if (retval) goto bad_fork_cleanup_namespaces; @@ -2598,7 +2601,6 @@ __latent_entropy struct task_struct *copy_process( trace_task_newtask(p, clone_flags); uprobe_copy_process(p, clone_flags); - user_events_fork(p, clone_flags); copy_oom_score_adj(clone_flags, p); @@ -2625,6 +2627,8 @@ __latent_entropy struct task_struct *copy_process( exit_io_context(p); bad_fork_cleanup_namespaces: exit_nsproxy_namespaces(p); +bad_fork_cleanup_user_events: + user_events_exit(p); bad_fork_cleanup_mm: sched_cache_fork_cleanup(p); if (p->mm) { diff --git a/kernel/trace/trace_events_user.c b/kernel/trace/trace_events_user.c index e29e1c772aa7d6..c561443f794703 100644 --- a/kernel/trace/trace_events_user.c +++ b/kernel/trace/trace_events_user.c @@ -868,7 +868,7 @@ void user_event_mm_remove(struct task_struct *t) queue_rcu_work(system_percpu_wq, &mm->put_rwork); } -void user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm) +int user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm) { struct user_event_mm *mm = user_event_mm_alloc(t); struct user_event_enabler *enabler; @@ -877,7 +877,7 @@ void user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm) t->user_event_mm = NULL; if (!mm) - return; + return -ENOMEM; rcu_read_lock(); @@ -889,10 +889,12 @@ void user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm) rcu_read_unlock(); user_event_mm_attach(mm, t); - return; + return 0; error: rcu_read_unlock(); user_event_mm_destroy(mm); + + return -ENOMEM; } static bool current_user_event_enabler_exists(unsigned long uaddr, From f8b462c497549e9991299156ed0e019eae8524f1 Mon Sep 17 00:00:00 2001 From: Jarkko Sakkinen Date: Thu, 12 Nov 2026 05:44:45 +0200 Subject: [PATCH 1580/2102] KEYS: trusted: Update static calls before init Given that the static calls are updated only after ->init() returns, an added trusted key can race with the callback initializations. This can ultimately lead into null dereference as static_call() is used unchecked. Address the bug by updating the static calls before invoking ->init(), and roll back on failure. Cc: stable@vger.kernel.org # v5.15+ Fixes: 31de287345f4 ("KEYS: trusted: Rollback init_trusted() consistently") Signed-off-by: Jarkko Sakkinen --- security/keys/trusted-keys/trusted_core.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/security/keys/trusted-keys/trusted_core.c b/security/keys/trusted-keys/trusted_core.c index 0509d9955f2a6f..11d7d296d063c2 100644 --- a/security/keys/trusted-keys/trusted_core.c +++ b/security/keys/trusted-keys/trusted_core.c @@ -373,14 +373,19 @@ static int __init init_trusted(void) if (!get_random) get_random = kernel_get_random; + static_call_update(trusted_key_seal, trusted_key_sources[i].ops->seal); + static_call_update(trusted_key_unseal, trusted_key_sources[i].ops->unseal); + static_call_update(trusted_key_get_random, get_random); + migratable = trusted_key_sources[i].ops->migratable; + ret = trusted_key_sources[i].ops->init(); if (!ret) { - static_call_update(trusted_key_seal, trusted_key_sources[i].ops->seal); - static_call_update(trusted_key_unseal, trusted_key_sources[i].ops->unseal); - static_call_update(trusted_key_get_random, get_random); - trusted_key_exit = trusted_key_sources[i].ops->exit; - migratable = trusted_key_sources[i].ops->migratable; + } else { + static_call_update(trusted_key_seal, NULL); + static_call_update(trusted_key_unseal, NULL); + static_call_update(trusted_key_get_random, NULL); + migratable = 0; } if (!ret || ret != -ENODEV) From b8d381d5ed7980db0bcdccdb61bb65f10f08f907 Mon Sep 17 00:00:00 2001 From: Jarkko Sakkinen Date: Thu, 12 Nov 2026 05:44:45 +0200 Subject: [PATCH 1581/2102] KEYS: trusted: TEE: Synchronize session lifetime The parent TEE device can remove the client device while live instances keep trusted.ko loaded. Guard session context state with a mutex, publish pvt_data.dev before registering key_type_trusted and sanitize pvt_data on probe failure and removal. When an active TEE has not been bound, reject seal, unseal and get_random with -ENODEV. Cc: stable@vger.kernel.org # v5.15+ Fixes: 0a95ebc91305 ("KEYS: trusted: Introduce TEE based Trusted Keys") Reviewed-by: Sumit Garg Signed-off-by: Jarkko Sakkinen --- security/keys/trusted-keys/trusted_tee.c | 86 ++++++++++++++++++------ 1 file changed, 65 insertions(+), 21 deletions(-) diff --git a/security/keys/trusted-keys/trusted_tee.c b/security/keys/trusted-keys/trusted_tee.c index 6e465c8bef5e5b..ad9c7baddcef4a 100644 --- a/security/keys/trusted-keys/trusted_tee.c +++ b/security/keys/trusted-keys/trusted_tee.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -56,6 +57,8 @@ struct trusted_key_tee_private { }; static struct trusted_key_tee_private pvt_data; +/* Do not hold this mutex across key type registration or unregistration. */ +static DEFINE_MUTEX(trusted_key_tee_mutex); /* * Have the TEE seal(encrypt) the symmetric key @@ -67,6 +70,12 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob) struct tee_param param[4]; struct tee_shm *reg_shm = NULL; + mutex_lock(&trusted_key_tee_mutex); + if (!pvt_data.ctx) { + ret = -ENODEV; + goto out_unlock; + } + memset(&inv_arg, 0, sizeof(inv_arg)); memset(¶m, 0, sizeof(param)); @@ -74,7 +83,8 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob) sizeof(p->key) + sizeof(p->blob)); if (IS_ERR(reg_shm)) { dev_err(pvt_data.dev, "shm register failed\n"); - return PTR_ERR(reg_shm); + ret = PTR_ERR(reg_shm); + goto out_unlock; } inv_arg.func = TA_CMD_SEAL; @@ -100,7 +110,8 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob) } tee_shm_free(reg_shm); - +out_unlock: + mutex_unlock(&trusted_key_tee_mutex); return ret; } @@ -114,6 +125,12 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob) struct tee_param param[4]; struct tee_shm *reg_shm = NULL; + mutex_lock(&trusted_key_tee_mutex); + if (!pvt_data.ctx) { + ret = -ENODEV; + goto out_unlock; + } + memset(&inv_arg, 0, sizeof(inv_arg)); memset(¶m, 0, sizeof(param)); @@ -121,7 +138,8 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob) sizeof(p->key) + sizeof(p->blob)); if (IS_ERR(reg_shm)) { dev_err(pvt_data.dev, "shm register failed\n"); - return PTR_ERR(reg_shm); + ret = PTR_ERR(reg_shm); + goto out_unlock; } inv_arg.func = TA_CMD_UNSEAL; @@ -147,7 +165,8 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob) } tee_shm_free(reg_shm); - +out_unlock: + mutex_unlock(&trusted_key_tee_mutex); return ret; } @@ -161,13 +180,20 @@ static int trusted_tee_get_random(unsigned char *key, size_t key_len) struct tee_param param[4]; struct tee_shm *reg_shm = NULL; + mutex_lock(&trusted_key_tee_mutex); + if (!pvt_data.ctx) { + ret = -ENODEV; + goto out_unlock; + } + memset(&inv_arg, 0, sizeof(inv_arg)); memset(¶m, 0, sizeof(param)); reg_shm = tee_shm_register_kernel_buf(pvt_data.ctx, key, key_len); if (IS_ERR(reg_shm)) { dev_err(pvt_data.dev, "key shm register failed\n"); - return PTR_ERR(reg_shm); + ret = PTR_ERR(reg_shm); + goto out_unlock; } inv_arg.func = TA_CMD_GET_RANDOM; @@ -189,7 +215,8 @@ static int trusted_tee_get_random(unsigned char *key, size_t key_len) } tee_shm_free(reg_shm); - +out_unlock: + mutex_unlock(&trusted_key_tee_mutex); return ret; } @@ -205,50 +232,67 @@ static int optee_ctx_match(struct tee_ioctl_version_data *ver, const void *data) static int trusted_key_probe(struct tee_client_device *rng_device) { struct device *dev = &rng_device->dev; + struct tee_context *ctx; int ret; struct tee_ioctl_open_session_arg sess_arg; + mutex_lock(&trusted_key_tee_mutex); + if (pvt_data.ctx) { + ret = -EBUSY; + goto out_unlock; + } + memset(&sess_arg, 0, sizeof(sess_arg)); - pvt_data.ctx = tee_client_open_context(NULL, optee_ctx_match, NULL, - NULL); - if (IS_ERR(pvt_data.ctx)) - return -ENODEV; + ctx = tee_client_open_context(NULL, optee_ctx_match, NULL, NULL); + if (IS_ERR(ctx)) { + ret = -ENODEV; + goto out_unlock; + } memcpy(sess_arg.uuid, rng_device->id.uuid.b, TEE_IOCTL_UUID_LEN); sess_arg.clnt_login = TEE_IOCTL_LOGIN_REE_KERNEL; sess_arg.num_params = 0; - ret = tee_client_open_session(pvt_data.ctx, &sess_arg, NULL); + ret = tee_client_open_session(ctx, &sess_arg, NULL); if ((ret < 0) || (sess_arg.ret != 0)) { dev_err(dev, "tee_client_open_session failed, err: %x\n", sess_arg.ret); ret = -EINVAL; goto out_ctx; } + pvt_data.ctx = ctx; pvt_data.session_id = sess_arg.session; - - ret = register_key_type(&key_type_trusted); - if (ret < 0) - goto out_sess; - pvt_data.dev = dev; + mutex_unlock(&trusted_key_tee_mutex); - return 0; + ret = register_key_type(&key_type_trusted); + if (!ret) + return 0; -out_sess: - tee_client_close_session(pvt_data.ctx, pvt_data.session_id); + mutex_lock(&trusted_key_tee_mutex); + tee_client_close_session(ctx, pvt_data.session_id); out_ctx: - tee_client_close_context(pvt_data.ctx); - + tee_client_close_context(ctx); + pvt_data.ctx = NULL; + pvt_data.dev = NULL; + pvt_data.session_id = 0; +out_unlock: + mutex_unlock(&trusted_key_tee_mutex); return ret; } static void trusted_key_remove(struct tee_client_device *dev) { unregister_key_type(&key_type_trusted); + + mutex_lock(&trusted_key_tee_mutex); tee_client_close_session(pvt_data.ctx, pvt_data.session_id); tee_client_close_context(pvt_data.ctx); + pvt_data.ctx = NULL; + pvt_data.dev = NULL; + pvt_data.session_id = 0; + mutex_unlock(&trusted_key_tee_mutex); } static const struct tee_client_device_id trusted_key_id_table[] = { From a361f81c2db79f92e5af145d7728ab757d81f55d Mon Sep 17 00:00:00 2001 From: Jarkko Sakkinen Date: Wed, 4 Nov 2026 04:07:05 +0200 Subject: [PATCH 1582/2102] KEYS: trusted: TEE: Disable sysfs bind attributes Suppress sysfs bind and unbind attributes on trusted_key_driver so that userspace cannot unbind the driver and unregister key_type_trusted while the trusted module remains loaded. Reviewed-by: Sumit Garg Signed-off-by: Jarkko Sakkinen --- security/keys/trusted-keys/trusted_tee.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/security/keys/trusted-keys/trusted_tee.c b/security/keys/trusted-keys/trusted_tee.c index ad9c7baddcef4a..87ea549f7f0b97 100644 --- a/security/keys/trusted-keys/trusted_tee.c +++ b/security/keys/trusted-keys/trusted_tee.c @@ -307,7 +307,8 @@ static struct tee_client_driver trusted_key_driver = { .remove = trusted_key_remove, .id_table = trusted_key_id_table, .driver = { - .name = DRIVER_NAME, + .name = DRIVER_NAME, + .suppress_bind_attrs = true, }, }; From 899af9ffd2671351e5402d572934dd59b5e91ae5 Mon Sep 17 00:00:00 2001 From: Sinan Turunc Date: Sat, 21 Nov 2026 11:13:07 +0000 Subject: [PATCH 1583/2102] KEYS: serialise key instantiation against keyctl_chown_key() keyctl_chown_key() looks up the target key by calling lookup_user_key() with the KEY_LOOKUP_PARTIAL flag. That flag lets a caller with CAP_SYS_ADMIN change the UID of an uninstantiated key during construction. When the UID changes, keyctl_chown_key() replaces key->user under key->sem and drops the old reference with key_user_put(). __key_instantiate_and_link() and key_reject_and_link() hold key_construction_mutex during instantiation, but neither function takes key->sem. Both functions increment key->user->nikeys, and __key_instantiate_and_link() also calls key->type->instantiate() without holding key->sem. When a key is in quota and its size changes, key_payload_reserve() reads key->user seven times without key->sem. Those reads include spin_lock_irqsave(&key->user->lock, flags) at the start and spin_unlock_irqrestore(&key->user->lock, flags) at the end. If keyctl_chown_key() swaps key->user between those two calls, key_payload_reserve() unlocks the new owner's spinlock and leaves the old spinlock held. By source inspection, key_user_put() can also kfree() the old struct key_user while instantiation still dereferences it. That struct key_user use-after-free was found by reading the code and did not trigger during our KASAN runs. ===================================== WARNING: bad unlock balance detected! 7.4.0-rc2-g23c62304dde2 #3 Not tainted ------------------------------------- request-key/163 is trying to release lock (&candidate->lock) at: [] key_payload_reserve+0x29f/0x370 but there are no more locks to release! other info that might help us debug this: locks held by request-key/163: 2, on CPU#3: #0: ffffffff871c10a0 (key_construction_mutex){+.+.}-{4:4}, at: __key_instantiate_and_link+0x38/0x370 #1: ffff88800de4a8b8 (&candidate->lock){..-.}-{3:3}, at: key_payload_reserve+0x160/0x370 Call Trace: lock_release+0x286/0x2e0 _raw_spin_unlock_irqrestore+0x1a/0x50 key_payload_reserve+0x29f/0x370 generic_key_instantiate+0x42/0x230 __key_instantiate_and_link+0xd7/0x370 key_instantiate_and_link+0x40d/0x4b0 keyctl_instantiate_key_common+0x2d2/0x450 keyctl_instantiate_key+0x167/0x180 __do_sys_keyctl+0x391/0x550 Take key->sem for write with down_write_nested(&key->sem, 2) inside key_construction_mutex in __key_instantiate_and_link() and key_reject_and_link(). Fixes: 5801649d8b83 ("[PATCH] keys: let keyctl_chown() change a key's owner") Cc: stable@vger.kernel.org Signed-off-by: Sinan Turunc Reviewed-by: Jarkko Sakkinen Link: https://lore.kernel.org/r/20261121111246.3478-1-enscrpt@pm.me Signed-off-by: Jarkko Sakkinen --- security/keys/key.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/security/keys/key.c b/security/keys/key.c index 3f1f0fc137109a..df31d1024340ef 100644 --- a/security/keys/key.c +++ b/security/keys/key.c @@ -441,6 +441,7 @@ static int __key_instantiate_and_link(struct key *key, ret = -EBUSY; mutex_lock(&key_construction_mutex); + down_write_nested(&key->sem, 2); /* can't instantiate twice */ if (key->state == KEY_IS_UNINSTANTIATED) { @@ -473,6 +474,7 @@ static int __key_instantiate_and_link(struct key *key, } } + up_write(&key->sem); mutex_unlock(&key_construction_mutex); /* wake up anyone waiting for a key to be constructed */ @@ -609,6 +611,7 @@ int key_reject_and_link(struct key *key, } mutex_lock(&key_construction_mutex); + down_write_nested(&key->sem, 2); /* can't instantiate twice */ if (key->state == KEY_IS_UNINSTANTIATED) { @@ -632,6 +635,7 @@ int key_reject_and_link(struct key *key, key_invalidate(authkey); } + up_write(&key->sem); mutex_unlock(&key_construction_mutex); if (keyring && link_ret == 0) From 484dc27f031229b374446cf038fa9c7a84d0f725 Mon Sep 17 00:00:00 2001 From: Guicai Ma Date: Thu, 19 Nov 2026 21:24:47 -0500 Subject: [PATCH 1584/2102] KEYS: Fix userspace buffer overflow in keyctl_pkey_e_d_s() Commit cb481e59ea6c ("KEYS: fix overflow in keyctl_pkey_params_get_2()") changed keyctl_pkey_params_get_2() to set params->out_len to the maximum output size of the operation instead of uparams.out_len, so that the kernel buffer allocated in keyctl_pkey_e_d_s() is large enough. Because uparams.out_len is no longer kept, keyctl_pkey_e_d_s() copies ret bytes to _out without checking whether the result fits in the caller's buffer. If a smaller out_len was passed, copy_to_user() writes past the end of _out instead of failing with -EOVERFLOW. uparams.out_len cannot simply be required to be at least the maximum output size in keyctl_pkey_params_get_2(), since KEYCTL_PKEY_DECRYPT with enc=pkcs1 can return a plaintext shorter than max_dec_size into a matching smaller buffer. Pass uparams.out_len back to keyctl_pkey_e_d_s() and return -EOVERFLOW before copy_to_user() if ret exceeds it. Cc: stable@vger.kernel.org # v7.2+ Fixes: cb481e59ea6c ("KEYS: fix overflow in keyctl_pkey_params_get_2()") Signed-off-by: Guicai Ma Reviewed-by: Jarkko Sakkinen Signed-off-by: Jarkko Sakkinen --- security/keys/keyctl_pkey.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/security/keys/keyctl_pkey.c b/security/keys/keyctl_pkey.c index e7121523b9c9ac..b5f82804b5ad1f 100644 --- a/security/keys/keyctl_pkey.c +++ b/security/keys/keyctl_pkey.c @@ -113,7 +113,8 @@ static int keyctl_pkey_params_get(key_serial_t id, static int keyctl_pkey_params_get_2(const struct keyctl_pkey_params __user *_params, const char __user *_info, int op, - struct kernel_pkey_params *params) + struct kernel_pkey_params *params, + u32 *user_out_len) { struct keyctl_pkey_params uparams; struct kernel_pkey_query info; @@ -183,6 +184,8 @@ static int keyctl_pkey_params_get_2(const struct keyctl_pkey_params __user *_par } params->in_len = uparams.in_len; + if (user_out_len) + *user_out_len = uparams.out_len; switch (op) { case KEYCTL_PKEY_VERIFY: @@ -264,10 +267,12 @@ long keyctl_pkey_e_d_s(int op, void __user *_out) { struct kernel_pkey_params params; + u32 user_out_len; void *in, *out; long ret; - ret = keyctl_pkey_params_get_2(_params, _info, op, ¶ms); + ret = keyctl_pkey_params_get_2(_params, _info, op, ¶ms, + &user_out_len); if (ret < 0) goto error_params; @@ -310,6 +315,10 @@ long keyctl_pkey_e_d_s(int op, if (ret < 0) goto error_out; + if (ret > user_out_len) { + ret = -EOVERFLOW; + goto error_out; + } if (copy_to_user(_out, out, ret) != 0) ret = -EFAULT; @@ -349,7 +358,7 @@ long keyctl_pkey_verify(const struct keyctl_pkey_params __user *_params, long ret; ret = keyctl_pkey_params_get_2(_params, _info, KEYCTL_PKEY_VERIFY, - ¶ms); + ¶ms, NULL); if (ret < 0) goto out_free_params; From 94cd215923495a0e1031b86dc7d246ef3c33cc73 Mon Sep 17 00:00:00 2001 From: Jarkko Sakkinen Date: Mon, 23 Nov 2026 22:54:48 +0200 Subject: [PATCH 1585/2102] KEYS: Fix asym key overflow in keyctl_pkey_verify() While verifying a variable-length signature shorter than info.max_sig_size, memdup_user() reads past the end of the caller's _in2 and passes trailing bytes to ->asym_verify_signature(). Set params->in2_len to uparams.in2_len in the KEYCTL_PKEY_VERIFY case. Cc: stable@vger.kernel.org # v7.2+ Closes: https://sashiko.dev/#/bug/linux-dd9ad2ca-a846-4d0d-89d6-aa262ffd40f1 Fixes: cb481e59ea6c ("KEYS: fix overflow in keyctl_pkey_params_get_2()") Signed-off-by: Jarkko Sakkinen --- security/keys/keyctl_pkey.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/keys/keyctl_pkey.c b/security/keys/keyctl_pkey.c index b5f82804b5ad1f..662226576954b5 100644 --- a/security/keys/keyctl_pkey.c +++ b/security/keys/keyctl_pkey.c @@ -176,7 +176,7 @@ static int keyctl_pkey_params_get_2(const struct keyctl_pkey_params __user *_par goto out_up_key_sem; } - params->out_len = info.max_sig_size; + params->in2_len = uparams.in2_len; break; default: ret = -EOPNOTSUPP; From 95d366cb57752fb8821488676f607ebd0050fa9e Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Mon, 23 Nov 2026 20:45:42 +0100 Subject: [PATCH 1586/2102] bpf: Let the bpf_fastcall boundary cover the longest pattern A subprog can have bpf_fastcall patterns of different length: *(u64 *)(r10 - 8) = r2 *(u64 *)(r10 - 16) = r1 call bpf_get_smp_processor_id r1 = *(u64 *)(r10 - 16) r2 = *(u64 *)(r10 - 8) *(u64 *)(r10 - 16) = r1 call bpf_get_smp_processor_id r1 = *(u64 *)(r10 - 16) r0 = *(u64 *)(r10 - 8) For each pattern, take the offset just above its highest spill slot: 0 for the first pattern here, -8 for the second. Currently mark_fastcall_pattern_for_call() keeps the lowest of these offsets in fastcall_stack_off, the bpf_fastcall boundary of the subprog, which is -8 here. check_fastcall_stack_contract() looks only at accesses below the boundary, so the last load, at -8, does not switch the rewrite off. bpf_remove_fastcall_spills_fills() then removes all three pairs of a spill and a fill, and the load reads a slot that nothing wrote, while the verifier took it for a slot with the type of R2. Keep the highest of these offsets instead: every slot of every pattern is below it. Start from S16_MIN, the value that says that nothing is rewritten. Stop at 0, as min() did, because a pattern in code that never runs may end above the frame pointer. Fixes: 5b5f51bff1b6 ("bpf: no_caller_saved_registers attribute for helper calls") Signed-off-by: Alexei Starovoitov Signed-off-by: Kumar Kartikeya Dwivedi Link: https://patch.msgid.link/adbe7671c30f744adf6682d6431b9d818039cefb.1795462417.git.memxor@gmail.com --- kernel/bpf/verifier.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 9b228ffbe3fe97..01a74e166e89ff 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -19933,7 +19933,11 @@ static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; else subprog->keep_fastcall_stack = 1; - subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); + /* + * The upper end of the longest pattern: no slot of a pattern is above it. Code that never + * runs may have a pattern that ends above the frame pointer. + */ + subprog->fastcall_stack_off = max(subprog->fastcall_stack_off, min_t(s16, off, 0)); } static int mark_fastcall_patterns(struct bpf_verifier_env *env) @@ -19944,6 +19948,7 @@ static int mark_fastcall_patterns(struct bpf_verifier_env *env) int s, i; for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { + subprog->fastcall_stack_off = S16_MIN; /* find lowest stack spill offset used in this subprog */ lowest_off = 0; for (i = subprog->start; i < (subprog + 1)->start; ++i) { From d734667216e3fe13f0d81231f0e5691816ec42f4 Mon Sep 17 00:00:00 2001 From: Yazen Ghannam Date: Mon, 23 Nov 2026 17:26:59 -0600 Subject: [PATCH 1587/2102] x86/mce/amd: Fix bank lookup in amd_mce_usable_address() amd_mce_usable_address() reads the per-CPU smca_banks array at index m->bank on the running CPU. The index is not checked, and the bank belongs to m->extcpu, not to whichever CPU is decoding. m->bank is unbounded here. apei_mce_report_mem_error() sets it to -1, which is 255 in the u8 field, and apei_smca_report_x86_error() takes it from a firmware CPER record (BERT or GHES). Both reach this function through the decoder chain, which runs from a workqueue on any CPU. Bank counts can differ per CPU on SMCA systems. So the read can land past the end of the array, or on a CPU where that bank means something else. Use m->extcpu for both the bound and the lookup. A bank number outside that CPU's range makes the record inconsistent. Don't act on such a record: report its address as not usable. Fixes: 821f5fe4dbcb ("x86/mce: Add support for physical address valid bit") Signed-off-by: Yazen Ghannam Signed-off-by: Borislav Petkov (AMD) Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261123232701.1923094-2-yazen.ghannam@amd.com --- arch/x86/kernel/cpu/mce/amd.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/arch/x86/kernel/cpu/mce/amd.c b/arch/x86/kernel/cpu/mce/amd.c index 1cc20b855b7e8d..255d09cd85443e 100644 --- a/arch/x86/kernel/cpu/mce/amd.c +++ b/arch/x86/kernel/cpu/mce/amd.c @@ -837,7 +837,10 @@ bool amd_mce_usable_address(struct mce *m) return false; } - if (this_cpu_ptr(smca_banks)[m->bank].paddrv) + if (m->bank >= per_cpu(mce_num_banks, m->extcpu)) + return false; + + if (per_cpu(smca_banks, m->extcpu)[m->bank].paddrv) return m->status & MCI_STATUS_PADDRV; /* Check poison bit for all other bank types. */ From a4b5c8d6de914d4a9d78b1f5a30e0e66c031d650 Mon Sep 17 00:00:00 2001 From: Jerome Mohm Date: Sat, 14 Nov 2026 12:59:14 +0100 Subject: [PATCH 1588/2102] vsock/bpf: fix zero-length, MSG_OOB and MSG_ERRQUEUE reads On a vsock socket in a sockmap, vsock_bpf_recvmsg() sends zero-length, MSG_OOB and MSG_ERRQUEUE reads down the sockmap path whenever the psock queue has data or nothing is queued at all. That path copies from the psock queue and waits for data, and it handles none of these reads: - a zero-length read with data in the psock queue spins with the socket lock held, and the delivery worker blocks on that lock; - MSG_ERRQUEUE consumes stream bytes from the psock queue, and the zero-length MSG_ERRQUEUE read that MSG_ZEROCOPY users make to collect completions gets -EAGAIN or blocks instead of reading the error queue; - MSG_OOB consumes ordinary stream bytes or waits for data, where a connected native socket returns -EOPNOTSUPP. Hand these reads to __vsock_recvmsg(), the path of a socket outside a sockmap, which does not wait for any of them. They now take one path, so the order of the checks no longer matters. Discovered by an LLM. Fixes: 634f1a7110b4 ("vsock: support sockmap") Suggested-by: Alexei Starovoitov Cc: stable@vger.kernel.org Signed-off-by: Jerome Mohm Acked-by: Stefano Garzarella Link: https://patch.msgid.link/20261114-kbh3-1-022-fix-v2-v6-1-96b6029bbffa@eldare.de Signed-off-by: Jakub Kicinski --- net/vmw_vsock/vsock_bpf.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/net/vmw_vsock/vsock_bpf.c b/net/vmw_vsock/vsock_bpf.c index 9049d26486460c..c9b399f37720d3 100644 --- a/net/vmw_vsock/vsock_bpf.c +++ b/net/vmw_vsock/vsock_bpf.c @@ -80,6 +80,9 @@ static int vsock_bpf_recvmsg(struct sock *sk, struct msghdr *msg, struct vsock_sock *vsk; int copied; + if (unlikely(!len || (flags & (MSG_OOB | MSG_ERRQUEUE)))) + return __vsock_recvmsg(sk, msg, len, flags); + psock = sk_psock_get(sk); if (unlikely(!psock)) return __vsock_recvmsg(sk, msg, len, flags); From cfd56c8720f897c65ff00d4815df06946739e445 Mon Sep 17 00:00:00 2001 From: Jerome Mohm Date: Sat, 14 Nov 2026 12:59:15 +0100 Subject: [PATCH 1589/2102] vsock/bpf: release sock lock while waiting for data in recvmsg vsock_bpf_recvmsg() sleeps in vsock_msg_wait_data() with the socket lock held, so the virtio delivery worker, which needs that lock, deadlocks with the reader and all vsock rx on that worker stops. Release the lock around the wait. The reader can then wake without data, so the wait also has to loop; the fix needs both halves. The loop ends on data, the timeout, a signal (the sleep returns at once while one is pending), a lost transport after a failed connect(), or a state in which __vsock_recvmsg() would not wait. Those states go to __vsock_recvmsg(), so a non-blocking read now sees them before -EAGAIN. A blocking read interrupted by a signal now gets -EINTR, or restarts, instead of -EAGAIN. One tested difference remains: a reader asleep at a virtio transport reset gets -ENOTCONN, where a native socket gets -ECONNRESET (0 on seqpacket). Discovered by an LLM. Fixes: 634f1a7110b4 ("vsock: support sockmap") Suggested-by: Alexei Starovoitov Cc: stable@vger.kernel.org Signed-off-by: Jerome Mohm Acked-by: Stefano Garzarella Link: https://patch.msgid.link/20261114-kbh3-1-022-fix-v2-v6-2-96b6029bbffa@eldare.de Signed-off-by: Jakub Kicinski --- net/vmw_vsock/vsock_bpf.c | 42 +++++++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/net/vmw_vsock/vsock_bpf.c b/net/vmw_vsock/vsock_bpf.c index c9b399f37720d3..41307759da9997 100644 --- a/net/vmw_vsock/vsock_bpf.c +++ b/net/vmw_vsock/vsock_bpf.c @@ -34,24 +34,37 @@ static bool vsock_has_data(struct sock *sk, struct sk_psock *psock) return vsock_sk_has_data(sk, psock); } -static bool vsock_msg_wait_data(struct sock *sk, struct sk_psock *psock, long timeo) +/* __vsock_recvmsg() doesn't wait in these states. */ +static bool vsock_rx_done(struct sock *sk) { - bool ret; - - DEFINE_WAIT_FUNC(wait, woken_wake_function); + return sk->sk_err || sk->sk_state != TCP_ESTABLISHED || + (sk->sk_shutdown & RCV_SHUTDOWN) || + (vsock_sk(sk)->peer_shutdown & SEND_SHUTDOWN); +} - if (sk->sk_shutdown & RCV_SHUTDOWN) - return true; +static int vsock_msg_wait_data(struct sock *sk, struct sk_psock *psock, + long timeo) +{ + struct vsock_sock *vsk = vsock_sk(sk); + int ret = 0; - if (!timeo) - return false; + DEFINE_WAIT_FUNC(wait, woken_wake_function); add_wait_queue(sk_sleep(sk), &wait); sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk); - ret = vsock_has_data(sk, psock); - if (!ret) { - wait_woken(&wait, TASK_INTERRUPTIBLE, timeo); - ret = vsock_has_data(sk, psock); + while (vsk->transport && !vsock_has_data(sk, psock) && + !vsock_rx_done(sk)) { + if (!timeo) { + ret = -EAGAIN; + break; + } + if (signal_pending(current)) { + ret = sock_intr_errno(timeo); + break; + } + release_sock(sk); + timeo = wait_woken(&wait, TASK_INTERRUPTIBLE, timeo); + lock_sock(sk); } sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk); remove_wait_queue(sk_sleep(sk), &wait); @@ -105,10 +118,9 @@ static int vsock_bpf_recvmsg(struct sock *sk, struct msghdr *msg, while (copied == 0) { long timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); - if (!vsock_msg_wait_data(sk, psock, timeo)) { - copied = -EAGAIN; + copied = vsock_msg_wait_data(sk, psock, timeo); + if (copied) break; - } if (sk_psock_queue_empty(psock)) { release_sock(sk); From d1be830de8cbce6122f32ac968ae20591a35043b Mon Sep 17 00:00:00 2001 From: Jun Yang Date: Tue, 17 Nov 2026 19:04:49 +0800 Subject: [PATCH 1590/2102] sctp: preserve stream scheduler across outq teardown sctp_outq_init() clears the installed scheduler when it reinitializes an outqueue after teardown. The streams still have scheduler-specific state that the old scheduler needs to release if the scheduler changes. Initialize the queue counters and flags individually so that sctp_sched_set_sched() can use the installed scheduler. A new association is zero-allocated and starts with the socket's default scheduler as before. When the socket default matches the installed scheduler, streams retain their PRIO priorities and WFQ weights. FC and WFQ also retain fc_length, including bytes charged for purged chunks. Those chunks were queued on the stream and the accounting converges as new data flows. Fixes: 5bbbbe32a431 ("sctp: introduce stream scheduler foundations") Cc: stable@kernel.org Reported-by: TencentOS Corvus AI Link: https://lore.kernel.org/r/20261104105507.62743-1-juny24602@gmail.com Signed-off-by: Jun Yang Acked-by: Xin Long Link: https://patch.msgid.link/20261117110459.44083-1-juny24602@gmail.com Signed-off-by: Jakub Kicinski --- net/sctp/outqueue.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/net/sctp/outqueue.c b/net/sctp/outqueue.c index e92fb9da4647a7..3dafa6e6cab3b7 100644 --- a/net/sctp/outqueue.c +++ b/net/sctp/outqueue.c @@ -190,9 +190,12 @@ static inline int sctp_cacc_skip(struct sctp_transport *primary, */ void sctp_outq_init(struct sctp_association *asoc, struct sctp_outq *q) { - memset(q, 0, sizeof(struct sctp_outq)); - q->asoc = asoc; + q->out_qlen = 0; + q->error = 0; + q->outstanding_bytes = 0; + q->fast_rtx = 0; + q->cork = 0; INIT_LIST_HEAD(&q->out_chunk_list); INIT_LIST_HEAD(&q->control_chunk_list); INIT_LIST_HEAD(&q->retransmit); From d34d54bb9bbe57c648f68819dd520995618eb196 Mon Sep 17 00:00:00 2001 From: Prasanna Kumar T S M Date: Wed, 18 Nov 2026 19:50:25 +0530 Subject: [PATCH 1591/2102] EDAC/versalnet: Fix device_register() error handling in init_one_mc() When device_register() fails, it must be followed by put_device() rather than kfree(), because device_register() calls device_initialize() which sets up the device refcount. The matching release function versal_edac_release() handles the actual kfree(). To simplify error handling and avoid complex unwinding, split device_register() into device_initialize() and device_add(). Initialize the device early so put_device() can be used in all error paths. Fixes: d5fe2fec6c40 ("EDAC: Add a driver for the AMD Versal NET DDR controller") Signed-off-by: Prasanna Kumar T S M Co-developed-by: Shubhrajyoti Datta Signed-off-by: Shubhrajyoti Datta Signed-off-by: Borislav Petkov (AMD) Reviewed-by: Radhey Shyam Pandey Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261118142213.100581-2-shubhrajyoti.datta@amd.com --- drivers/edac/versalnet_edac.c | 36 +++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/drivers/edac/versalnet_edac.c b/drivers/edac/versalnet_edac.c index d59ba3904cda65..a3440dedc04495 100644 --- a/drivers/edac/versalnet_edac.c +++ b/drivers/edac/versalnet_edac.c @@ -70,8 +70,6 @@ #define XDDR5_BUS_WIDTH_32 1 #define XDDR5_BUS_WIDTH_16 2 -#define MC_NAME_LEN 32 - /** * struct ecc_error_info - ECC error log information. * @burstpos: Burst position. @@ -777,7 +775,6 @@ static int init_one_mc(struct mc_priv *priv, struct platform_device *pdev, int i u32 num_chans, rank, dwidth, config; struct edac_mc_layer layers[2]; struct mem_ctl_info *mci; - char name[MC_NAME_LEN]; struct device *dev; enum dev_type dt; int rc; @@ -817,28 +814,31 @@ static int init_one_mc(struct mc_priv *priv, struct platform_device *pdev, int i if (!dev) return rc; + dev->release = versal_edac_release; + device_initialize(dev); + + rc = dev_set_name(dev, "versal-net-ddrmc5-edac-%d", i); + if (rc) + goto err_put_dev; + + rc = device_add(dev); + if (rc) + goto err_put_dev; + mci = edac_mc_alloc(i, ARRAY_SIZE(layers), layers, sizeof(struct mc_priv)); if (!mci) { edac_printk(KERN_ERR, EDAC_MC, "Failed memory allocation for MC%d\n", i); - goto err_dev_free; + rc = -ENOMEM; + goto err_dev_del; } - sprintf(name, "versal-net-ddrmc5-edac-%d", i); - - dev->init_name = name; - dev->release = versal_edac_release; - - rc = device_register(dev); - if (rc) - goto err_mc_free; - mci->pdev = dev; mc_init(mci, dev); rc = edac_mc_add_mc(mci); if (rc) { edac_printk(KERN_ERR, EDAC_MC, "Failed to register MC%d with EDAC core\n", i); - goto err_unreg; + goto err_mc_free; } priv->mci[i] = mci; @@ -848,12 +848,12 @@ static int init_one_mc(struct mc_priv *priv, struct platform_device *pdev, int i return 0; -err_unreg: - device_unregister(mci->pdev); err_mc_free: edac_mc_free(mci); -err_dev_free: - kfree(dev); +err_dev_del: + device_del(dev); +err_put_dev: + put_device(dev); return rc; } From c5aabb4fcbec182ac6e27fb04430d56780d0935a Mon Sep 17 00:00:00 2001 From: "Nikhil P. Rao" Date: Tue, 17 Nov 2026 19:18:54 +0000 Subject: [PATCH 1592/2102] ionic: reject Tx ring sizes below the minimum ionic_tx_cq_service() wakes a stopped Tx queue only once IONIC_TSO_DESCS_NEEDED (44) descriptors are free. The threshold is sized for a 64 KB TSO skb at a 1500 byte MSS and assumes the ring can have that many free; a Tx ring of 32 or fewer descriptors cannot, so a stopped queue is never woken and the netdev watchdog fires. ionic_set_ringparam() only checks that the size is a power of 2, and the ethtool core only checks the maximum, so such sizes are accepted. Reject Tx ring sizes below IONIC_MIN_TXRX_DESC. The stall was confirmed from the wake and stop thresholds, not reproduced. Tested on an AMD Pensando NIC: "ethtool -G tx 32" is rejected and leaves the ring unchanged, and "ethtool -G tx 64" is accepted. Fixes: 061b9bedbef1 ("ionic: Rework Tx start/stop flow") Cc: stable@vger.kernel.org Reported-by: sashiko-bot@kernel.org # Running on a local machine Signed-off-by: Nikhil P. Rao Reviewed-by: Brett Creeley Link: https://patch.msgid.link/20261117-b4-ionic-tso-max-segs-v2-1-f9792566c5d5@amd.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/pensando/ionic/ionic_ethtool.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c b/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c index 119ac720c0787a..3518fbf5882d98 100644 --- a/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c +++ b/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c @@ -708,6 +708,13 @@ static int ionic_set_ringparam(struct net_device *netdev, return -EINVAL; } + if (ring->tx_pending < IONIC_MIN_TXRX_DESC) { + NL_SET_ERR_MSG_FMT_MOD(extack, + "Tx descriptor count must be at least %d", + IONIC_MIN_TXRX_DESC); + return -EINVAL; + } + /* if nothing to do return success */ if (ring->tx_pending == lif->ntxq_descs && ring->rx_pending == lif->nrxq_descs && From 0778833b9602b2f1b331e2a2d69243847aea95d0 Mon Sep 17 00:00:00 2001 From: "Nikhil P. Rao" Date: Tue, 17 Nov 2026 19:18:55 +0000 Subject: [PATCH 1593/2102] ionic: limit TSO segments to the minimum Tx ring size ionic uses one Tx descriptor per TSO segment, and a Tx ring holds at most num_descs - 1 of them. The driver does not set tso_max_segs, so the stack can hand it GSO skbs with more segments than the Tx ring can hold. ionic_tx() then stops the queue waiting for descriptors that can never become free, and the netdev watchdog fires repeatedly. This was hit in production: guest TCP traffic with an MSS below 64 produced 64 KB GSO skbs on the default 1024-entry ring. Raise the minimum Tx ring size to IONIC_MIN_TX_DESC (128), for the hwstamp and kdump Tx rings as well, and set tso_max_segs to IONIC_MIN_TX_DESC - 1 so that every Tx ring can hold the largest TSO skb. Larger GSO skbs are segmented in software. 127 segments still covers a 64 KB skb at the 536 byte default MSS. IONIC_MIN_TXRX_DESC now only applies to Rx, so rename it to IONIC_MIN_RX_DESC. Tested on an AMD Pensando NIC with GSO frames of about 1500 segments, injected through a tap with a virtio-net header and redirected to the ionic netdev with tc mirred: without this patch the Tx queue stalls and the watchdog fires, and with it they are sent. Cc: stable@vger.kernel.org # 6.18.x and older: be1b70ab21cb: net: init Fixes: 0f3154e6bcb3 ("ionic: Add Tx and Rx handling") Cc: stable@vger.kernel.org Suggested-by: Jakub Kicinski Link: https://lore.kernel.org/all/20261112082753.6ee90fc8@kernel.org/ Signed-off-by: Nikhil P. Rao Reviewed-by: Brett Creeley Link: https://patch.msgid.link/20261117-b4-ionic-tso-max-segs-v2-2-f9792566c5d5@amd.com Signed-off-by: Jakub Kicinski --- drivers/net/ethernet/pensando/ionic/ionic_dev.h | 3 ++- drivers/net/ethernet/pensando/ionic/ionic_ethtool.c | 4 ++-- drivers/net/ethernet/pensando/ionic/ionic_lif.c | 10 ++++++---- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/drivers/net/ethernet/pensando/ionic/ionic_dev.h b/drivers/net/ethernet/pensando/ionic/ionic_dev.h index db90e39a1442d2..4b3e244e6bbb2d 100644 --- a/drivers/net/ethernet/pensando/ionic/ionic_dev.h +++ b/drivers/net/ethernet/pensando/ionic/ionic_dev.h @@ -16,7 +16,8 @@ #define IONIC_MAX_TX_DESC 8192 #define IONIC_MAX_RX_DESC 16384 -#define IONIC_MIN_TXRX_DESC 64 +#define IONIC_MIN_RX_DESC 64 +#define IONIC_MIN_TX_DESC 128 #define IONIC_DEF_TXRX_DESC 1024 #define IONIC_RX_FILL_THRESHOLD 16 #define IONIC_RX_FILL_DIV 8 diff --git a/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c b/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c index 3518fbf5882d98..24fd34b4cfccc6 100644 --- a/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c +++ b/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c @@ -708,10 +708,10 @@ static int ionic_set_ringparam(struct net_device *netdev, return -EINVAL; } - if (ring->tx_pending < IONIC_MIN_TXRX_DESC) { + if (ring->tx_pending < IONIC_MIN_TX_DESC) { NL_SET_ERR_MSG_FMT_MOD(extack, "Tx descriptor count must be at least %d", - IONIC_MIN_TXRX_DESC); + IONIC_MIN_TX_DESC); return -EINVAL; } diff --git a/drivers/net/ethernet/pensando/ionic/ionic_lif.c b/drivers/net/ethernet/pensando/ionic/ionic_lif.c index 22d1e4b6d61be8..339a3c4c5b4327 100644 --- a/drivers/net/ethernet/pensando/ionic/ionic_lif.c +++ b/drivers/net/ethernet/pensando/ionic/ionic_lif.c @@ -997,7 +997,7 @@ int ionic_lif_create_hwstamp_txq(struct ionic_lif *lif) features = IONIC_Q_F_2X_CQ_DESC | IONIC_TXQ_F_HWSTAMP; - num_desc = IONIC_MIN_TXRX_DESC; + num_desc = IONIC_MIN_TX_DESC; desc_sz = sizeof(struct ionic_txq_desc); comp_sz = 2 * sizeof(struct ionic_txq_comp); @@ -1062,7 +1062,7 @@ int ionic_lif_create_hwstamp_rxq(struct ionic_lif *lif) features = IONIC_Q_F_2X_CQ_DESC | IONIC_RXQ_F_HWSTAMP; - num_desc = IONIC_MIN_TXRX_DESC; + num_desc = IONIC_MIN_RX_DESC; desc_sz = sizeof(struct ionic_rxq_desc); comp_sz = 2 * sizeof(struct ionic_rxq_comp); sg_desc_sz = sizeof(struct ionic_rxq_sg_desc); @@ -1642,6 +1642,8 @@ static int ionic_init_nic_features(struct ionic_lif *lif) netdev->features |= netdev->hw_features; netdev->vlan_features |= netdev->features & ~NETIF_F_VLAN_FEATURES; + netif_set_tso_max_segs(netdev, IONIC_MIN_TX_DESC - 1); + netdev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE; @@ -3284,8 +3286,8 @@ int ionic_lif_alloc(struct ionic *ionic) lif->index = 0; if (is_kdump_kernel()) { - lif->ntxq_descs = IONIC_MIN_TXRX_DESC; - lif->nrxq_descs = IONIC_MIN_TXRX_DESC; + lif->ntxq_descs = IONIC_MIN_TX_DESC; + lif->nrxq_descs = IONIC_MIN_RX_DESC; } else { lif->ntxq_descs = IONIC_DEF_TXRX_DESC; lif->nrxq_descs = IONIC_DEF_TXRX_DESC; From 348730838f0f742ad496d1165eb011b7ecaab031 Mon Sep 17 00:00:00 2001 From: Shubhrajyoti Datta Date: Wed, 18 Nov 2026 19:50:26 +0530 Subject: [PATCH 1594/2102] EDAC/versalnet: Use designated initializer for rpmsg_channel_info Replace field-by-field assignment of struct rpmsg_channel_info with a designated initializer. The old strscpy() call used strlen() as the destination size, which truncated the channel name. Use the string literal (via EDAC_RPMSG_CHAN_NAME) in the initializer so the full name is passed to rpmsg_create_ept(). [ bp: Drop EDAC_ prefix and align members vertically. ] Fixes: d5fe2fec6c40 ("EDAC: Add a driver for the AMD Versal NET DDR controller") Signed-off-by: Shubhrajyoti Datta Signed-off-by: Borislav Petkov (AMD) Reviewed-by: Radhey Shyam Pandey Cc: Link: https://patch.msgid.link/20261118142213.100581-3-shubhrajyoti.datta@amd.com --- drivers/edac/versalnet_edac.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/drivers/edac/versalnet_edac.c b/drivers/edac/versalnet_edac.c index a3440dedc04495..9dcb38cf3ba977 100644 --- a/drivers/edac/versalnet_edac.c +++ b/drivers/edac/versalnet_edac.c @@ -70,6 +70,8 @@ #define XDDR5_BUS_WIDTH_32 1 #define XDDR5_BUS_WIDTH_16 2 +#define RPMSG_CHAN_NAME "error_ipc" + /** * struct ecc_error_info - ECC error log information. * @burstpos: Burst position. @@ -713,21 +715,21 @@ static int rpmsg_cb(struct rpmsg_device *rpdev, void *data, } static struct rpmsg_device_id amd_rpmsg_id_table[] = { - { .name = "error_ipc" }, + { .name = RPMSG_CHAN_NAME }, { }, }; MODULE_DEVICE_TABLE(rpmsg, amd_rpmsg_id_table); static int rpmsg_probe(struct rpmsg_device *rpdev) { - struct rpmsg_channel_info chinfo; + struct rpmsg_channel_info chinfo = { + .src = RPMSG_ADDR_ANY, + .dst = rpdev->dst, + .name = RPMSG_CHAN_NAME, + }; struct mc_priv *pg; pg = (struct mc_priv *)amd_rpmsg_id_table[0].driver_data; - chinfo.src = RPMSG_ADDR_ANY; - chinfo.dst = rpdev->dst; - strscpy(chinfo.name, amd_rpmsg_id_table[0].name, - strlen(amd_rpmsg_id_table[0].name)); pg->ept = rpmsg_create_ept(rpdev, rpmsg_cb, NULL, chinfo); if (!pg->ept) From a95cfe28d0d96b68826498aab90e494b9f6bd22c Mon Sep 17 00:00:00 2001 From: Shubhrajyoti Datta Date: Wed, 18 Nov 2026 19:50:27 +0530 Subject: [PATCH 1595/2102] EDAC/versalnet: Fix use-after-free in remove_one_mc() device_unregister() drops the last reference on the device and invokes versal_edac_release() which calls kfree(dev). The subsequent call to edac_mc_del_mc(mci->pdev) then dereferences the freed pointer. Save the device pointer, call edac_mc_del_mc() and edac_mc_free() first, then device_unregister() last so the device is freed only after all users are done with it. [ bp: Massage commit message. ] Fixes: d5fe2fec6c40 ("EDAC: Add a driver for the AMD Versal NET DDR controller") Signed-off-by: Shubhrajyoti Datta Signed-off-by: Borislav Petkov (AMD) Reviewed-by: Radhey Shyam Pandey Cc: Link: https://patch.msgid.link/20261118142213.100581-4-shubhrajyoti.datta@amd.com --- drivers/edac/versalnet_edac.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/edac/versalnet_edac.c b/drivers/edac/versalnet_edac.c index 9dcb38cf3ba977..729cf66c5c793c 100644 --- a/drivers/edac/versalnet_edac.c +++ b/drivers/edac/versalnet_edac.c @@ -765,11 +765,14 @@ static void versal_edac_release(struct device *dev) static void remove_one_mc(struct mc_priv *priv, int i) { struct mem_ctl_info *mci; + struct device *dev; mci = priv->mci[i]; - device_unregister(mci->pdev); - edac_mc_del_mc(mci->pdev); + dev = mci->pdev; + + edac_mc_del_mc(dev); edac_mc_free(mci); + device_unregister(dev); } static int init_one_mc(struct mc_priv *priv, struct platform_device *pdev, int i) From cbaaeff649b7aa09170cb31db001e5468c2726c0 Mon Sep 17 00:00:00 2001 From: Shihuang Liu Date: Wed, 18 Nov 2026 23:35:41 +0800 Subject: [PATCH 1596/2102] net: sock_reuseport: Check program type on the migration path A BPF_PROG_TYPE_SOCKET_FILTER program can be loaded with expected_attach_type set to BPF_SK_REUSEPORT_SELECT_OR_MIGRATE and attached to a SO_REUSEPORT TCP group. Closing a listener that still has queued children then runs it with a struct sk_reuseport_kern context even though it was verified against struct sk_buff, which KASAN reports as a stack-out-of-bounds in ___bpf_prog_run(). Reaching this without CAP_BPF requires kernel.unprivileged_bpf_disabled=0; with CONFIG_BPF_UNPRIV_DEFAULT_OFF=y, the Kconfig default, the sysctl starts at 2. reuseport_migrate_sock() decides from prog->expected_attach_type alone, a field user space sets that does not identify the program type. Require BPF_PROG_TYPE_SK_REUSEPORT there and in reuseport_stop_listen_sock(); socket filters still work as selectors, so the selection path is unchanged. Fixes: d5e4ddaeb6ab ("bpf: Support socket migration by eBPF.") Signed-off-by: Shihuang Liu Signed-off-by: Alexei Starovoitov Reviewed-by: Kuniyuki Iwashima Acked-by: Jakub Kicinski Link: https://patch.msgid.link/20261118153541.172499-1-shlomojune6@gmail.com --- net/core/sock_reuseport.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/net/core/sock_reuseport.c b/net/core/sock_reuseport.c index b9e5648fa4c515..e039e35f39a90a 100644 --- a/net/core/sock_reuseport.c +++ b/net/core/sock_reuseport.c @@ -461,6 +461,18 @@ void reuseport_detach_sock(struct sock *sk) } EXPORT_SYMBOL(reuseport_detach_sock); +/* + * Only a BPF_PROG_TYPE_SK_REUSEPORT program is verified against + * struct sk_reuseport_kern, which is the context bpf_run_sk_reuseport() + * passes to it. expected_attach_type is set by user space and does not + * identify the program type. + */ +static bool reuseport_is_migration_prog(const struct bpf_prog *prog) +{ + return prog && prog->type == BPF_PROG_TYPE_SK_REUSEPORT && + prog->expected_attach_type == BPF_SK_REUSEPORT_SELECT_OR_MIGRATE; +} + void reuseport_stop_listen_sock(struct sock *sk) { if (sk->sk_protocol == IPPROTO_TCP) { @@ -475,7 +487,7 @@ void reuseport_stop_listen_sock(struct sock *sk) lockdep_is_held(&reuseport_lock)); if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_migrate_req) || - (prog && prog->expected_attach_type == BPF_SK_REUSEPORT_SELECT_OR_MIGRATE)) { + reuseport_is_migration_prog(prog)) { /* Migration capable, move sk from the listening section * to the closed section. */ @@ -645,7 +657,7 @@ struct sock *reuseport_migrate_sock(struct sock *sk, hash = migrating_sk->sk_hash; prog = rcu_dereference(reuse->prog); - if (!prog || prog->expected_attach_type != BPF_SK_REUSEPORT_SELECT_OR_MIGRATE) { + if (!reuseport_is_migration_prog(prog)) { if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_migrate_req)) goto select_by_hash; goto failure; From 4c2abd86d10720ce4a2330c2ca01cca39bd727ab Mon Sep 17 00:00:00 2001 From: Shance Luo Date: Thu, 19 Nov 2026 15:53:30 +0800 Subject: [PATCH 1597/2102] x86/CPU: Fix FPDSS on Hygon Hygon family 0x18 CPUs are affected by the same floating-point divider issue as AMD Zen1: the divider can leave partial results of previous operations behind, which another attacker thread can sample. Enable the mitigation. Signed-off-by: Shance Luo Signed-off-by: Borislav Petkov (AMD) Cc: Link: https://patch.msgid.link/20261119075330.961-1-luoshance@hygon.cn --- arch/x86/kernel/cpu/hygon.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/x86/kernel/cpu/hygon.c b/arch/x86/kernel/cpu/hygon.c index ec51c2b9a257cc..0bccb934fbf855 100644 --- a/arch/x86/kernel/cpu/hygon.c +++ b/arch/x86/kernel/cpu/hygon.c @@ -228,6 +228,9 @@ static void init_hygon(struct cpuinfo_x86 *c) /* Hygon CPUs don't need fencing after x2APIC/TSC_DEADLINE MSR writes. */ clear_cpu_cap(c, X86_FEATURE_APIC_MSRS_FENCE); + + pr_notice_once("Hygon FPDSS bug detected, enabling mitigation.\n"); + msr_set_bit(MSR_AMD64_FP_CFG, MSR_AMD64_FP_CFG_ZEN1_DENORM_FIX_BIT); } static void cpu_detect_tlb_hygon(struct cpuinfo_x86 *c) From 884e88175b95a03ea9f4dc8c89acca5d5b33cbd2 Mon Sep 17 00:00:00 2001 From: Waiman Long Date: Mon, 23 Nov 2026 23:28:00 -0500 Subject: [PATCH 1598/2102] tick/sched: Make tick_nohz_full_mask and HK_TYPE_KERNEL_NOISE cpumask consistent When the nohz_full boot parameter is first set, the cpu list parameter is passed directly to tick_nohz_full_setup() to set up tick_nohz_full_mask cpumask. Then the HK_TYPE_KERNEL_NOISE cpumask will be set up as the inverse of given cpu list parameter. Some of the timer code and RCU uses tick_nohz_full_mask directly while other timer code, scheduler and other subsystems use the HK_TYPE_KERNEL_NOISE cpumask. With CONFIG_PM_SLEEP_SMP && !CONFIG_PM_SLEEP_SMP_NONZERO_CPU config options, the boot CPU will be cleared from tick_nohz_full_mask if set while the corresponding HK_TYPE_KERNEL_NOISE cpumask isn't touched. The nohz_full entry in kernel-parameters.txt does state that the boot CPU will be forced outside the range to maintain the timekeeping. So it makes sense that the HK_TYPE_KERNEL_NOISE should be modified accordingly. Fix this inconsistency problem by adding a new cpumask_set_cpu() init function to be called by tick_nohz_init() when the boot CPU is cleared from tick_nohz_full_mask. In the special case that "nohz_full=0" and CPU 0 is cleared in tick_nohz_init(), tick_nohz_full_running will be set to false. However, housekeeping_enabled(HK_TYPE_KERNEL_NOISE) will stil be true with housekeeping_cpumask(HK_TYPE_KERNEL_NOISE) equal to cpu_possible_mask. So some unneeded code paths will be activated, but no harm will be done other than wasting some CPU cycles. Another problem that needs further thought but is not handled in this patch is when arch_irq_work_has_interrupt() turns out to be false. When this happens, tick_nohz_full_mask will be cleared and tick_nohz_full_running will be set back to false in tick_nohz_init(). PM_SLEEP_SMP_NONZERO_CPU depends on ARCH_SUSPEND_NONZERO_CPU which can only be set for the PowerPC architecture. Moreover CONFIG_PM_SLEEP_SMP is on by default, it means most kernels will not allow CPU 0 to be set in the tick_nohz_full_mask and hence should be set in HK_TYPE_KERNEL_NOISE cpumask. Fixes: 6f1982fedd59 ("sched/isolation: Handle the nohz_full= parameter") Signed-off-by: Waiman Long Reviewed-by: Frederic Weisbecker Reviewed-by: Ridong Chen Acked-by: Guopeng Zhang Tested-by: Guopeng Zhang Signed-off-by: Tejun Heo --- include/linux/sched/isolation.h | 2 ++ kernel/sched/isolation.c | 11 +++++++++++ kernel/time/tick-sched.c | 6 ++++++ 3 files changed, 19 insertions(+) diff --git a/include/linux/sched/isolation.h b/include/linux/sched/isolation.h index cf0fd03dd7a24e..ae5109450ac922 100644 --- a/include/linux/sched/isolation.h +++ b/include/linux/sched/isolation.h @@ -44,6 +44,7 @@ extern bool housekeeping_enabled(enum hk_type type); extern void housekeeping_affine(struct task_struct *t, enum hk_type type); extern bool housekeeping_test_cpu(int cpu, enum hk_type type); extern int housekeeping_update(struct cpumask *isol_mask); +extern void __init housekeeping_set_cpu(int cpu, enum hk_type type); extern void __init housekeeping_init(void); #else @@ -72,6 +73,7 @@ static inline bool housekeeping_test_cpu(int cpu, enum hk_type type) } static inline int housekeeping_update(struct cpumask *isol_mask) { return 0; } +static inline void housekeeping_set_cpu(int cpu, enum hk_type type) { } static inline void housekeeping_init(void) { } #endif /* CONFIG_CPU_ISOLATION */ diff --git a/kernel/sched/isolation.c b/kernel/sched/isolation.c index 156025ef81b75a..c0c8b8862cbdc3 100644 --- a/kernel/sched/isolation.c +++ b/kernel/sched/isolation.c @@ -120,6 +120,17 @@ bool housekeeping_test_cpu(int cpu, enum hk_type type) } EXPORT_SYMBOL_GPL(housekeeping_test_cpu); +void __init housekeeping_set_cpu(int cpu, enum hk_type type) +{ + /* Only CPU setting of HK_TYPE_KERNEL_NOISE is currently supported */ + if (type != HK_TYPE_KERNEL_NOISE) + return; + + if (static_branch_unlikely(&housekeeping_overridden) && + READ_ONCE(housekeeping.flags) & BIT(type)) + cpumask_set_cpu(cpu, housekeeping_cpumask_dereference(type)); +} + int housekeeping_update(struct cpumask *isol_mask) { struct cpumask *trial, *old = NULL; diff --git a/kernel/time/tick-sched.c b/kernel/time/tick-sched.c index 6c3fea38671397..9c92b122ef6027 100644 --- a/kernel/time/tick-sched.c +++ b/kernel/time/tick-sched.c @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -671,6 +672,11 @@ void __init tick_nohz_init(void) pr_warn("NO_HZ: Clearing %d from nohz_full range " "for timekeeping\n", cpu); cpumask_clear_cpu(cpu, tick_nohz_full_mask); + housekeeping_set_cpu(cpu, HK_TYPE_KERNEL_NOISE); + if (cpumask_empty(tick_nohz_full_mask)) { + tick_nohz_full_running = false; + return; + } } } From c99f50e4acf86bfbbe313d79f281d83be1763260 Mon Sep 17 00:00:00 2001 From: Karl Mehltretter Date: Tue, 24 Nov 2026 04:16:42 +0100 Subject: [PATCH 1599/2102] cgroup/rstat: disable preemption in css_rstat_updated() BPF programs can call css_rstat_updated() with preemption enabled. The kfunc calls __css_rstat_updated(), which requires preemption to be disabled while it queues an rstat update. A cgroup iterator can hit the lockdep assertion on both RT and non-RT kernels. The cgroup_hierarchical_stats selftest can also hit it on PREEMPT_RT: spin_lock_irqsave() on trace_cgroup_path_lock leaves preemption and interrupts enabled there. Disable preemption in the BPF wrapper after validating the CPU and before calling __css_rstat_updated(). Fixes: 36df6e3dbd7e ("cgroup: make css_rstat_updated nmi safe") Reported-by: Jiayuan Chen Closes: https://lore.kernel.org/r/20251119111402.153727-1-jiayuan.chen@linux.dev/ Signed-off-by: Karl Mehltretter Acked-by: Shakeel Butt Signed-off-by: Tejun Heo --- kernel/cgroup/rstat.c | 1 + 1 file changed, 1 insertion(+) diff --git a/kernel/cgroup/rstat.c b/kernel/cgroup/rstat.c index de816a43db9f0a..d72fe721cea057 100644 --- a/kernel/cgroup/rstat.c +++ b/kernel/cgroup/rstat.c @@ -131,6 +131,7 @@ __bpf_kfunc void css_rstat_updated(struct cgroup_subsys_state *css, int cpu) if (unlikely(cpu < 0 || cpu >= nr_cpu_ids || !cpu_possible(cpu))) return; + guard(preempt)(); __css_rstat_updated(css, cpu); } From e3464357e282d164ce873bfb4e259996cea3a564 Mon Sep 17 00:00:00 2001 From: Mani Tofigh Date: Mon, 23 Nov 2026 12:21:34 -0500 Subject: [PATCH 1600/2102] mm/shmem: don't drop a folio whose swap write failed shmem_swapin_folio() drops a large folio that does not fit the mapping from the swap cache if the folio is neither dirty nor under writeback. The folio can belong to another file and be under swap writeback, when the swap entry was freed and reused before the swap cache lookup. Swap write completion does not take the folio lock. On a failed write, swap_write_end() marks the folio dirty and then ends writeback. Since dirty is tested first, the folio can look clean and written: CPU0 (swapin of file Y) CPU1 (swapout of file X) ----------------------- ------------------------ shmem_swapin_folio() folio_test_dirty() == false swap_write_end(), failed write folio_mark_dirty() folio_end_writeback() folio_test_writeback() == false swap_cache_del_folio() /* X's data is lost */ The next swapin of X reads the slot whose write failed. Test writeback first. Both flags are in folio->flags. If the writeback test sees the write ended, the dirty test then sees the dirty bit set before it. With the fix, a folio whose swap write failed stays in the swap cache. Fixes: fc2c19648d68 ("mm/shmem: fix swapin livelock on a mismatched large swap cache folio") Suggested-by: Chris Mason Cc: stable@vger.kernel.org Signed-off-by: Mani Tofigh Reviewed-by: Nhat Pham Reviewed-by: Baolin Wang Link: https://patch.msgid.link/20261123-shmem-swap-write-failed-v1-1-41a0115dfbf1@columbia.edu Signed-off-by: David Hildenbrand (Arm) --- mm/shmem.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/mm/shmem.c b/mm/shmem.c index c7a9c4c375ba19..a5713109c843c9 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -2687,10 +2687,12 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index, * A large folio that does not fit the mapping, e.g. because its swap * entries were freed and reused, would be found again on every retry. * Drop it from the swap cache so the retry can swap in a fitting one. + * A failed swap write sets dirty and then ends writeback without the + * folio lock, so test writeback before dirty. */ if (error == -EEXIST && folio && folio_test_large(folio) && - !folio_test_anon(folio) && !folio_test_dirty(folio) && - !folio_test_writeback(folio)) + !folio_test_anon(folio) && !folio_test_writeback(folio) && + !folio_test_dirty(folio)) swap_cache_del_folio(folio); unlock: if (folio) From 93f9a0afce028b7a8902b8ff2afb8697e3e625d2 Mon Sep 17 00:00:00 2001 From: Manuel Ebner Date: Wed, 18 Nov 2026 20:06:52 +0100 Subject: [PATCH 1601/2102] docs: soundwire: stream: harmonize diagrams In example 3 and 4 the slave interfaces are in an equal relation to the master interface. Reflect this with equal arrows. Signed-off-by: Manuel Ebner Link: https://patch.msgid.link/20261118190655.1179347-2-manuelebnerli@mailbox.org Signed-off-by: Vinod Koul --- Documentation/driver-api/soundwire/stream.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Documentation/driver-api/soundwire/stream.rst b/Documentation/driver-api/soundwire/stream.rst index d6620129963356..58b05f2d0b0eb8 100644 --- a/Documentation/driver-api/soundwire/stream.rst +++ b/Documentation/driver-api/soundwire/stream.rst @@ -67,11 +67,11 @@ Slaves are using single port. :: | | | | | | +---------------+ - | +----------------------> | Slave | + | +------------------------+ Slave | | | Interface | | | 2 | | | | - +----------------------------> | R | + +------------------------------+ R | | (Data) | +---------------+ @@ -93,11 +93,11 @@ one or more speakers. :: | | | | | | +---------------+ - | +----------------------> | Slave | + | +------------------------+ Slave | | | Interface | | | 2 | | | | - +----------------------------> | L + R | + +------------------------------+ L + R | | (Data) | +---------------+ From ed601f5d59a3085b3a519ea3ad58879a8f2e6023 Mon Sep 17 00:00:00 2001 From: Charles Keepax Date: Wed, 11 Nov 2026 16:24:44 +0000 Subject: [PATCH 1602/2102] soundwire: Improve channel min/max comments Presently, the comments for the minimum and maximum channels are misleading. In the SoundWire/Disco specification these are actually channel indexes not a count of the number of channels. So for example min_ch=4 and max_ch=5 means that 1 or 2 channels are supported. Update the comments associated with the structure to make this more clear. Signed-off-by: Charles Keepax Reviewed-by: Pierre-Louis Bossart Link: https://patch.msgid.link/20261111162445.1371853-2-ckeepax@opensource.cirrus.com Signed-off-by: Vinod Koul --- include/linux/soundwire/sdw.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/linux/soundwire/sdw.h b/include/linux/soundwire/sdw.h index f710e5932b4b23..b8f5ad39e9b37b 100644 --- a/include/linux/soundwire/sdw.h +++ b/include/linux/soundwire/sdw.h @@ -289,8 +289,8 @@ struct sdw_dp0_prop { * @ch_prep_timeout: Port-specific timeout value, in milliseconds * @imp_def_interrupts: If set, each bit corresponds to support for * implementation-defined interrupts - * @max_ch: Maximum channels supported - * @min_ch: Minimum channels supported + * @max_ch: Maximum Channel Number of this Audio Port + * @min_ch: Minimum Channel Number of this Audio Port * @num_channels: Number of discrete channels supported * @num_ch_combinations: Number of channel combinations supported * @channels: Discrete channels supported From 48fe747f750b78a3a124c96754a48ff81e207a43 Mon Sep 17 00:00:00 2001 From: Charles Keepax Date: Wed, 11 Nov 2026 16:24:45 +0000 Subject: [PATCH 1603/2102] soundwire: Assume default maximum valid channel if not specified The SoundWire/DisCo specification defines all the supported channel properties as optional and states that in the case none are specified defaults of min_ch=0 and max_ch=7 should be used. If both properties are not present in the DisCo the current code results in min_ch=0 and max_ch=0. As min_ch and max_ch are both channel indexes, users can't discern if they should interpret this as the default case (1-8 channels supported) or the DisCo specified a single valid channel of 0 (1 channel supported). In the case there are no valid supported channel properties populate max_ch with 7 as the specification suggests, to avoid the ambiguity. Also as the specification says only parse the channel number properties if there is no channel number list. Signed-off-by: Charles Keepax Reviewed-by: Pierre-Louis Bossart Link: https://patch.msgid.link/20261111162445.1371853-3-ckeepax@opensource.cirrus.com Signed-off-by: Vinod Koul --- drivers/soundwire/mipi_disco.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/drivers/soundwire/mipi_disco.c b/drivers/soundwire/mipi_disco.c index 259ad98b5b7a9a..2dad95f8e1ab2c 100644 --- a/drivers/soundwire/mipi_disco.c +++ b/drivers/soundwire/mipi_disco.c @@ -284,12 +284,6 @@ static int sdw_slave_read_dpn(struct sdw_slave *slave, "mipi-sdw-imp-def-dpn-interrupts-supported", &dpn[i].imp_def_interrupts); - fwnode_property_read_u32(node, "mipi-sdw-min-channel-number", - &dpn[i].min_ch); - - fwnode_property_read_u32(node, "mipi-sdw-max-channel-number", - &dpn[i].max_ch); - nval = fwnode_property_count_u32(node, "mipi-sdw-channel-number-list"); if (nval > 0) { dpn[i].num_channels = nval; @@ -307,6 +301,14 @@ static int sdw_slave_read_dpn(struct sdw_slave *slave, dpn[i].channels, dpn[i].num_channels); if (ret < 0) return ret; + } else { + fwnode_property_read_u32(node, "mipi-sdw-min-channel-number", + &dpn[i].min_ch); + + ret = fwnode_property_read_u32(node, "mipi-sdw-max-channel-number", + &dpn[i].max_ch); + if (ret) + dpn[i].max_ch = 7; } nval = fwnode_property_count_u32(node, "mipi-sdw-channel-combination-list"); From b4f63023d7cc2cd824f982a6f76ceb462b51fed7 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Tue, 24 Nov 2026 08:56:43 +0100 Subject: [PATCH 1604/2102] mm/huge_memory: use NOFS when allocating while splitting folios Splitting a file folio might allocate memory for the xarray and call filemap_release_folio(). If either ends up in direct reclaim or compaction with __GFP_FS, we can deadlock on the folio lock. For example, when reclaim evicts the inode through the dcache shrinker it can wait in truncate_inode_pages_final() for the folio that we hold locked: try_split_folio() folio_lock(A) split_folio_to_list(A) xas_split_alloc() try_to_free_pages() super_cache_scan() prune_dcache_sb() iput_final() evict() truncate_inode_pages_final() folio_lock(A) This example requires that nothing else holds a reference on the inode, and can be triggered most easily with FUSE, which evicts inodes on the last reference. We really must not allocate with __GFP_FS while holding a folio lock. As Willy explains [1], direct compaction can also trigger deadlocks. Further, xas_split_alloc() charges the XArray nodes to the memcg, and on cgroup v1, memcg reclaim waits for file folios under writeback if __GFP_FS is set. That can deadlock if writeback waits for a folio lock that we hold, for example with ext4. Let's fix it by splitting folios in a NOFS scope, so callers don't have to care. A NOFS scope also covers allocations that filesystems make with their own gfp flags, for example in filemap_release_folio(). On NFS, splitting folios with pending writes or ongoing writes to fscache might now fail slightly more often, until these writes have completed. On netfs, only folios that are being written to fscache are affected. All fairly irrelevant. This has medium urgency. Fixes: 6b24ca4a1a8d ("mm: Use multi-index entries in the page cache") Fixes: eef88fe45ac9 ("s390/uv: Split large folios in gmap_make_secure()") Fixes: 789763523fb4 ("xarray: honor XA_FLAGS_ACCOUNT in xas_split_alloc()") Cc: stable@vger.kernel.org Reported-by: Chris Mason Reviewed-by: Jose A. Perez de Azpillaga Tested-by: Gregory Price (Meta) Reviewed-by: Gregory Price (Meta) Reviewed-by: Barry Song Reviewed-by: Baolin Wang Reviewed-by: Zi Yan Acked-by: Lorenzo Stoakes (ARM) Reviewed-by: Chris Down Link: https://lore.kernel.org/r/awSgk1VTUsiVQOAT@casper.infradead.org [1] Link: https://patch.msgid.link/20261124-migrate_reclaim_deadlock-v2-1-03cc147e1e36@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/huge_memory.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/mm/huge_memory.c b/mm/huge_memory.c index a6da3d9bb9a152..d065b26a94dfac 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -4425,11 +4425,20 @@ static int __folio_split(struct folio *folio, unsigned int new_order, const bool is_swapcache = folio_test_swapcache(folio); int old_order = folio_order(folio); struct folio *new_folio, *next; + unsigned int nofs_flags; int ret; VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); VM_WARN_ON_ONCE_FOLIO(!folio_test_large(folio), folio); + /* + * We might allocate memory while holding the folio lock. Direct + * reclaim or compaction could try evicting the inode, isolating and + * locking our folio, or wait for writeback on cgroup v1, to then + * deadlock on folio locks. + */ + nofs_flags = memalloc_nofs_save(); + if (folio != page_folio(split_at) || folio != page_folio(lock_at)) { ret = -EINVAL; goto out; @@ -4478,6 +4487,7 @@ static int __folio_split(struct folio *folio, unsigned int new_order, if (is_pmd_order(old_order)) count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED); count_mthp_stat(old_order, !ret ? MTHP_STAT_SPLIT : MTHP_STAT_SPLIT_FAILED); + memalloc_nofs_restore(nofs_flags); return ret; } From 51fdc28d34659c9a956ecdcc3554213d0ca34f99 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Tue, 24 Nov 2026 08:56:44 +0100 Subject: [PATCH 1605/2102] mm/migrate: allocate destination folios before locking a batch Allocating memory while holding folio locks is problematic, as we would require a NOFS scope to avoid deadlocks. Migration locks folios and can end up triggering direct reclaim or compaction with __GFP_FS. For example, reclaim can evict an inode through the dcache shrinker, and wait in truncate_inode_pages_final() for a folio that we hold locked: migrate_pages_batch() migrate_folio_unmap(A) folio_trylock(A) migrate_folio_unmap(B) get_new_folio() try_to_free_pages() super_cache_scan() prune_dcache_sb() iput_final() evict() truncate_inode_pages_final() folio_lock(A) This example requires that nothing else holds a reference on the inode, and can be triggered most easily with FUSE, which evicts inodes on the last reference. Allocating in a NOFS scope would be one option, but it would have rather bad side effects, such as direct compaction not migrating file folios and the OOM killer not being invoked. So let's fix it by allocating all destination folios of a batch before locking any source folio. Now, we no longer allocate destination folios while holding folio locks, which also avoids holding these locks during direct reclaim or compaction for these allocations: an improvement on its own. We keep the destination folio of a folio that we have to retry, instead of freeing it and allocating a new one. If we would have to allocate while already holding folio locks, which can happen when retrying a failed split for longterm pinning, we leave the folio to the synchronous fallback in migrate_pages_sync() instead, which migrates folios one by one. Note that nfs_migrate_folio() still writes back the folio while holding its lock in MIGRATE_SYNC mode, which allocates memory. This must be sorted out in NFS code independently. This has medium urgency. Fixes: 5dfab109d519 ("migrate_pages: batch _unmap and _move") Cc: stable@vger.kernel.org Reported-by: Chris Mason Tested-by: Gregory Price (Meta) Reviewed-by: Gregory Price (Meta) Reviewed-by: Zi Yan Reviewed-by: Chris Down Link: https://patch.msgid.link/20261124-migrate_reclaim_deadlock-v2-2-03cc147e1e36@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/migrate.c | 133 +++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 96 insertions(+), 37 deletions(-) diff --git a/mm/migrate.c b/mm/migrate.c index 65869b8acec54c..7841968dd1f528 100644 --- a/mm/migrate.c +++ b/mm/migrate.c @@ -1230,25 +1230,15 @@ static void migrate_folio_done(struct folio *src, } /* Obtain the lock on page, remove all ptes. */ -static int migrate_folio_unmap(new_folio_t get_new_folio, - free_folio_t put_new_folio, unsigned long private, - struct folio *src, struct folio **dstp, enum migrate_mode mode, - struct list_head *ret) +static int migrate_folio_unmap(struct folio *src, struct folio *dst, + enum migrate_mode mode, struct list_head *ret) { - struct folio *dst; int rc = -EAGAIN; int old_folio_state = 0; struct anon_vma *anon_vma = NULL; bool locked = false; bool dst_locked = false; - dst = get_new_folio(src, private); - if (!dst) - return -ENOMEM; - *dstp = dst; - - dst->migrate_info = 0; - if (!folio_trylock(src)) { if (mode == MIGRATE_ASYNC) goto out; @@ -1374,7 +1364,8 @@ static int migrate_folio_unmap(new_folio_t get_new_folio, migrate_folio_undo_src(src, old_folio_state & FOLIO_WAS_MAPPED, anon_vma, locked, ret); - migrate_folio_undo_dst(dst, dst_locked, put_new_folio, private); + if (dst_locked) + folio_unlock(dst); return rc; } @@ -1819,6 +1810,25 @@ static void migrate_folios_undo(struct list_head *src_folios, } } +static void migrate_folio_free_dst(struct folio *dst, + free_folio_t put_new_folio, unsigned long private) +{ + list_del(&dst->lru); + dst->private = NULL; + migrate_folio_undo_dst(dst, false, put_new_folio, private); +} + +static void migrate_folios_undo_unused(struct list_head *pending_folios, + struct list_head *new_folios, free_folio_t put_new_folio, + unsigned long private, struct list_head *from) +{ + struct folio *dst, *tmp; + + list_for_each_entry_safe(dst, tmp, new_folios, lru) + migrate_folio_free_dst(dst, put_new_folio, private); + list_splice(pending_folios, from); +} + /* * migrate_pages_batch() first unmaps folios in the from list as many as * possible, then move the unmapped folios. @@ -1841,8 +1851,10 @@ static int migrate_pages_batch(struct list_head *from, int pass = 0; bool is_thp = false; bool is_large = false; - struct folio *folio, *folio2, *dst = NULL; + struct folio *folio, *dst, *tmp; int rc, rc_saved = 0, nr_pages; + LIST_HEAD(pending_folios); + LIST_HEAD(new_folios); LIST_HEAD(unmap_folios); LIST_HEAD(dst_folios); bool nosplit = (reason == MR_NUMA_MISPLACED); @@ -1855,7 +1867,13 @@ static int migrate_pages_batch(struct list_head *from, thp_retry = 0; nr_retry_pages = 0; - list_for_each_entry_safe(folio, folio2, from, lru) { + /* + * Prepare the source folios, and allocate the destination + * folios before locking any source folio. We must be careful + * when allocating memory while holding folio locks, so just + * avoid it. + */ + list_for_each_entry_safe(folio, tmp, from, lru) { is_large = folio_test_large(folio); is_thp = folio_test_pmd_mappable(folio); nr_pages = folio_nr_pages(folio); @@ -1935,21 +1953,24 @@ static int migrate_pages_batch(struct list_head *from, continue; } - rc = migrate_folio_unmap(get_new_folio, put_new_folio, - private, folio, &dst, mode, ret_folios); /* - * The rules are: - * 0: folio will be put on unmap_folios list, - * dst folio put on dst_folios list - * -EAGAIN: stay on the from list - * -ENOMEM: stay on the from list - * Other errno: put on ret_folios list + * Don't allocate while holding folio locks, but leave + * the folio to the one-by-one fallback in + * migrate_pages_sync(). */ - switch(rc) { - case -ENOMEM: + if (!list_empty(&unmap_folios)) { + retry++; + thp_retry += is_thp; + nr_retry_pages += nr_pages; + continue; + } + + dst = get_new_folio(folio, private); + if (!dst) { /* * When memory is low, don't bother to try to migrate - * other folios, move unmapped folios, then exit. + * other folios, migrate the folios that we have + * destination folios for, then exit. */ nr_failed++; stats->nr_thp_failed += is_thp; @@ -1960,7 +1981,7 @@ static int migrate_pages_batch(struct list_head *from, if (!ret) { stats->nr_thp_split += is_thp; stats->nr_split++; - break; + continue; } else if (reason == MR_LONGTERM_PIN && ret == -EAGAIN) { /* @@ -1973,18 +1994,42 @@ static int migrate_pages_batch(struct list_head *from, /* Undo duplicated failure counting. */ nr_failed--; stats->nr_thp_failed -= is_thp; - break; + continue; } } - stats->nr_failed_pages += nr_pages + nr_retry_pages; - /* nr_failed isn't updated for not used */ - stats->nr_thp_failed += thp_retry; - rc_saved = rc; - if (list_empty(&unmap_folios)) - goto out; - else - goto move; + stats->nr_failed_pages += nr_pages; + rc_saved = -ENOMEM; + break; + } + /* Remember the source folio until we unmap it. */ + dst->private = folio; + list_move_tail(&folio->lru, &pending_folios); + list_add_tail(&dst->lru, &new_folios); + } + + /* + * Lock and unmap the source folios. Each destination folio + * remembers its source folio in ->private, so walk the + * destination folios. + */ + list_for_each_entry_safe(dst, tmp, &new_folios, lru) { + folio = dst->private; + is_thp = folio_test_pmd_mappable(folio); + nr_pages = folio_nr_pages(folio); + + cond_resched_tasks_rcu_qs(); + + rc = migrate_folio_unmap(folio, dst, mode, ret_folios); + /* + * The rules are: + * 0: folio will be put on unmap_folios list, + * dst folio put on dst_folios list + * -EAGAIN: stay on the pending_folios list, + * keep dst + * Other errno: put on ret_folios list, free dst + */ + switch (rc) { case -EAGAIN: retry++; thp_retry += is_thp; @@ -1992,7 +2037,7 @@ static int migrate_pages_batch(struct list_head *from, break; case 0: list_move_tail(&folio->lru, &unmap_folios); - list_add_tail(&dst->lru, &dst_folios); + list_move_tail(&dst->lru, &dst_folios); break; default: /* @@ -2001,12 +2046,24 @@ static int migrate_pages_batch(struct list_head *from, * removed from migration folio list and not * retried in the next outer loop. */ + migrate_folio_free_dst(dst, put_new_folio, + private); nr_failed++; stats->nr_thp_failed += is_thp; stats->nr_failed_pages += nr_pages; break; } } + + if (rc_saved) { + stats->nr_failed_pages += nr_retry_pages; + /* We return rc_saved, so don't update nr_failed. */ + stats->nr_thp_failed += thp_retry; + rc = rc_saved; + if (list_empty(&unmap_folios)) + goto out; + goto move; + } } nr_failed += retry; stats->nr_thp_failed += thp_retry; @@ -2036,6 +2093,8 @@ static int migrate_pages_batch(struct list_head *from, /* Cleanup remaining folios */ migrate_folios_undo(&unmap_folios, &dst_folios, put_new_folio, private, ret_folios); + migrate_folios_undo_unused(&pending_folios, &new_folios, put_new_folio, + private, from); return rc; } From 05a8c5ba73a4ff24b76dca0bc1d3bacb638d7def Mon Sep 17 00:00:00 2001 From: Chaitanya Kumar Borah Date: Fri, 13 Nov 2026 13:18:49 +0530 Subject: [PATCH 1606/2102] drm/i915/dip: Write the DIP header last MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On platforms with SDP transmission line registers, the packets anchored to them are double buffered in the transcoder (TC) clock domain. The packet registers are in the core display (CD) clock domain and the whole packet is clock crossed on the write of the header (dword 0), so Bspec requires the data to be programmed first and the header last. hsw_write_infoframe() writes the header first, so the packet is crossed before its payload is in place and the previous payload keeps being sent. This hits the AS SDP, and the VSC SDP whenever an AS SDP is enabled, which is whenever VRR is possible since commit 6a1712052859 ("drm/i915/dp: Enable AS SDP whenever VRR is possible or PR !async"). With CMN_SDP_TL, enabled by commit bfa597238073 ("drm/i915/dip: Enable Common SDP Transmission line"), it also hits the GMP and VSC SDPs: on NVL, entering HDR on an eDP panel leaves the image discoloured and scaled until the headers are rewritten. Write the payload, including the ECC zero fill, first and the header last for all packets. Packets double buffered in the CD domain have no ordering requirement and Bspec recommends using the same order for all packets, so use it on all platforms. v2: Always write the header last, without the platform check. (Ville) Bspec: 75640, 71197, 74384 Fixes: e1123e617e51 ("drm/i915/vrr: Program EMP_AS_SDP_TL for DP AS SDP") Closes: https://gitlab.freedesktop.org/drm/i915/kernel/-/work_items/17732 Closes: https://gitlab.freedesktop.org/drm/xe/kernel/-/work_items/9746 Cc: # v6.17+ Cc: Ankit Nautiyal Cc: Suraj Kandpal Cc: Xiao Lu Cc: Ville Syrjälä Signed-off-by: Chaitanya Kumar Borah Reviewed-by: Ankit Nautiyal Link: https://patch.msgid.link/20261113074849.30768-1-chaitanya.kumar.borah@intel.com (cherry picked from commit ac7db76062c72cf95c713eb48788f08cbcf18f11) Signed-off-by: Joonas Lahtinen --- drivers/gpu/drm/i915/display/intel_hdmi.c | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/i915/display/intel_hdmi.c b/drivers/gpu/drm/i915/display/intel_hdmi.c index b6fa1a1558b82f..a095f5f273bb6c 100644 --- a/drivers/gpu/drm/i915/display/intel_hdmi.c +++ b/drivers/gpu/drm/i915/display/intel_hdmi.c @@ -535,18 +535,27 @@ void hsw_write_infoframe(struct intel_encoder *encoder, val &= ~hsw_infoframe_enable(type); intel_de_write(display, ctl_reg, val); - for (i = 0; i < len; i += 4) { + /* Program the payload first, the header (dword 0) is written last. */ + for (i = 4; i < len; i += 4) intel_de_write(display, hsw_dip_data_reg(display, cpu_transcoder, type, i >> 2), - *data); - data++; - } + data[i >> 2]); /* Write every possible data byte to force correct ECC calculation. */ for (; i < data_size; i += 4) intel_de_write(display, hsw_dip_data_reg(display, cpu_transcoder, type, i >> 2), 0); + /* + * Packets double buffered in the transcoder clock domain are clock + * crossed on the write of the header, so it has to come after the + * payload. Packets double buffered in the core display clock domain + * have no ordering requirement, so use the same order for all of them. + */ + intel_de_write(display, + hsw_dip_data_reg(display, cpu_transcoder, type, 0), + data[0]); + /* Wa_14013475917 */ if (!(IS_DISPLAY_VER(display, 13, 14) && crtc_state->has_psr && !crtc_state->has_panel_replay && type == DP_SDP_VSC)) From a2bdc43c05f92628c824fbee497d0f1e7bc47893 Mon Sep 17 00:00:00 2001 From: Oliver Hartkopp Date: Fri, 20 Nov 2026 12:28:55 +0100 Subject: [PATCH 1607/2102] can: bcm: copy the CAN frames outside of lock_sock() bcm_sendmsg() copies the CAN frames of TX_SETUP, RX_SETUP and TX_SEND from user space while holding lock_sock(). A copy that faults or stalls, e.g. on a FUSE backed mapping, holds lock_sock() for its whole duration. bcm_notify() takes lock_sock() of every CAN_BCM socket in the namespace of a vanishing CAN device while holding RTNL, independent of the binding of the socket. So a stalled copy on any CAN_BCM socket can block RTNL on the unregistration or namespace change of a CAN device in this namespace, e.g. of a vcan device in an unprivileged user and network namespace. Copy the CAN frames that the opcode handler reads to kernel memory before lock_sock() and hand them to the handlers with a kvec based msghdr. bcm_tx_setup(), bcm_rx_setup() and bcm_tx_send() keep their checks and read the frames with memcpy_from_msg() as before. Up to sizeof(struct canfd_frame) bytes, i.e. a single CAN FD frame or up to four CAN CC frames, are copied to a buffer on the stack, more frames to a kvmalloc() buffer of up to MAX_NFRAMES + 1 CAN FD frames. As the frames are copied before lock_sock() now, a failing copy is reported before the error conditions that are checked under lock_sock(). This is in line with POSIX, which does not define an order in which multiple error conditions are detected and reported. The generic SOL_SOCKET options in sk_setsockopt() and sk_getsockopt(), e.g. SO_ATTACH_FILTER, still access user space under the socket lock. This is not specific to CAN_BCM and not addressed by this patch. Fixes: ffd980f976e7 ("[CAN]: Add broadcast manager (bcm) protocol") Cc: stable@vger.kernel.org Signed-off-by: Oliver Hartkopp Link: https://patch.msgid.link/20261120-can-bcmlock-memcg-v7-1-f6b84f5257b1@hartkopp.net Signed-off-by: Marc Kleine-Budde --- net/can/bcm.c | 55 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/net/can/bcm.c b/net/can/bcm.c index 7bd2aa39777af4..3f4c8d82833767 100644 --- a/net/can/bcm.c +++ b/net/can/bcm.c @@ -1643,6 +1643,11 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) struct bcm_sock *bo = bcm_sk(sk); int ifindex; struct bcm_msg_head msg_head; + struct msghdr fmsg = {}; /* CAN frames copied to kernel memory */ + struct kvec kv; + struct canfd_frame sframe; /* stack buffer for up to CANFD_MTU bytes */ + void *frames = &sframe; + size_t flen = 0; int cfsiz; int ret; /* read bytes or error codes as return value */ @@ -1663,6 +1668,47 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) if ((size - MHSIZ) % cfsiz) return -EINVAL; + /* Copy the CAN frames from user space before lock_sock(), so a + * stalled copy can not block bcm_notify() waiting for lock_sock() + * under RTNL. Only the frames the opcode handler reads are copied. + * The handlers keep their checks and read the frames from fmsg. + */ + switch (msg_head.opcode) { + case TX_SETUP: + if (msg_head.nframes >= 1 && msg_head.nframes <= MAX_NFRAMES) + flen = msg_head.nframes * cfsiz; + break; + + case RX_SETUP: + if (!(msg_head.flags & RX_FILTER_ID) && + msg_head.nframes <= MAX_NFRAMES + 1) + flen = msg_head.nframes * cfsiz; + break; + + case TX_SEND: + if (msg_head.nframes == 1 && size == cfsiz + MHSIZ) + flen = cfsiz; + break; + } + + /* a message with missing frames still fails in the handler */ + flen = min(flen, msg_data_left(msg)); + + if (flen > sizeof(sframe)) { + frames = kvmalloc(flen, GFP_KERNEL); + if (!frames) + return -ENOMEM; + } + + if (!copy_from_iter_full(frames, flen, &msg->msg_iter)) { + ret = -EFAULT; + goto out_free; + } + + kv.iov_base = frames; + kv.iov_len = flen; + iov_iter_kvec(&fmsg.msg_iter, ITER_SOURCE, &kv, 1, flen); + lock_sock(sk); /* Re-validate under the socket lock: a concurrent bcm_notify() @@ -1721,11 +1767,11 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) switch (msg_head.opcode) { case TX_SETUP: - ret = bcm_tx_setup(&msg_head, msg, ifindex, sk); + ret = bcm_tx_setup(&msg_head, &fmsg, ifindex, sk); break; case RX_SETUP: - ret = bcm_rx_setup(&msg_head, msg, ifindex, sk); + ret = bcm_rx_setup(&msg_head, &fmsg, ifindex, sk); break; case TX_DELETE: @@ -1759,7 +1805,7 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) if ((msg_head.nframes != 1) || (size != cfsiz + MHSIZ)) ret = -EINVAL; else - ret = bcm_tx_send(msg, ifindex, sk, cfsiz); + ret = bcm_tx_send(&fmsg, ifindex, sk, cfsiz); break; default: @@ -1769,6 +1815,9 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) out_release: release_sock(sk); +out_free: + if (frames != &sframe) + kvfree(frames); return ret; } From 2caf66eca1bcbe77e47cd52e183bc65c25fa93b7 Mon Sep 17 00:00:00 2001 From: Oliver Hartkopp Date: Fri, 20 Nov 2026 12:28:56 +0100 Subject: [PATCH 1608/2102] can: bcm: do not remove the procfs entry in bcm_notify() bcm_notify() removes the procfs entry of a CAN_BCM socket that is bound to a vanishing CAN device with remove_proc_entry() while holding RTNL. remove_proc_entry() waits for all running readers of this entry. A reader of /proc/net/can-bcm/ that stalls in its copy to user space, e.g. on a FUSE backed mapping, therefore blocks RTNL on the unregistration or namespace change of the bound CAN device. The entry has been removed in bcm_notify() so that a later bcm_connect() of the unbound socket can register it again without a "proc_dir_entry already registered" warning. The CAN_BCM socket itself stays usable after a NETDEV_UNREGISTER: bcm_notify() only unbinds it and reports ENODEV, so the application can connect() the socket again, e.g. to a re-created CAN device. The name of the procfs entry is the inode number of the socket, which does not change until the socket is closed. Keep the procfs entry until bcm_release() instead, which removes it after the socket has left the notifier list and without holding RTNL. bcm_connect() only creates the entry, if it does not exist yet. bcm_proc_show() reports an unbound socket as "unbound" instead of showing the cleared ifindex as "any". As bcm_proc_show() can now run while the socket is bound or unbound, it reads bo->ifindex locklessly with READ_ONCE() and the writers use WRITE_ONCE(). The NETDEV_DOWN handling in bcm_notify(), which runs without lock_sock(), reads bo->bound and bo->ifindex with READ_ONCE() as well. bo->ifindex is still only modified under lock_sock(). A concurrent bind or unbind may show an intermediate state in the procfs output, which is acceptable for this debug information. Fixes: 76fe372ccb81 ("can: bcm: Remove proc entry when dev is unregistered.") Cc: stable@vger.kernel.org Signed-off-by: Oliver Hartkopp Link: https://patch.msgid.link/20261120-can-bcmlock-memcg-v7-2-f6b84f5257b1@hartkopp.net Signed-off-by: Marc Kleine-Budde --- net/can/bcm.c | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/net/can/bcm.c b/net/can/bcm.c index 3f4c8d82833767..1595b7720c9819 100644 --- a/net/can/bcm.c +++ b/net/can/bcm.c @@ -219,11 +219,16 @@ static int bcm_proc_show(struct seq_file *m, void *v) struct net *net = m->private; struct sock *sk = (struct sock *)pde_data(m->file->f_inode); struct bcm_sock *bo = bcm_sk(sk); + int ifindex = READ_ONCE(bo->ifindex); struct bcm_op *op; seq_printf(m, ">>> sock inode %s", bo->procname); seq_printf(m, " / dropped %lu", bo->dropped_usr_msgs); - seq_printf(m, " / bound %s", bcm_proc_getifname(net, ifname, bo->ifindex)); + if (READ_ONCE(bo->bound)) + seq_printf(m, " / bound %s", + bcm_proc_getifname(net, ifname, ifindex)); + else + seq_puts(m, " / unbound"); seq_printf(m, " <<<\n"); rcu_read_lock(); @@ -1866,19 +1871,9 @@ static void bcm_notify(struct bcm_sock *bo, unsigned long msg, /* remove device reference, if this is our bound device */ if (bo->bound && bo->ifindex == dev->ifindex) { -#if IS_ENABLED(CONFIG_PROC_FS) - if (sock_net(sk)->can.bcmproc_dir && bo->bcm_proc_read) { - remove_proc_entry(bo->procname, sock_net(sk)->can.bcmproc_dir); - bo->bcm_proc_read = NULL; - } -#endif - /* Paired with the lockless fast-path check in - * bcm_sendmsg(); bo->ifindex itself is only ever - * accessed under lock_sock() so it needs no - * annotation. - */ + /* pairs with the lockless check in bcm_sendmsg() */ WRITE_ONCE(bo->bound, 0); - bo->ifindex = 0; + WRITE_ONCE(bo->ifindex, 0); notify_enodev = 1; } @@ -1892,7 +1887,8 @@ static void bcm_notify(struct bcm_sock *bo, unsigned long msg, break; case NETDEV_DOWN: - if (bo->bound && bo->ifindex == dev->ifindex) { + if (READ_ONCE(bo->bound) && + READ_ONCE(bo->ifindex) == dev->ifindex) { sk->sk_err = ENETDOWN; if (!sock_flag(sk, SOCK_DEAD)) sk_error_report(sk); @@ -2013,7 +2009,7 @@ static int bcm_release(struct socket *sock) /* remove device reference */ if (bo->bound) { WRITE_ONCE(bo->bound, 0); - bo->ifindex = 0; + WRITE_ONCE(bo->ifindex, 0); } sock_orphan(sk); @@ -2060,16 +2056,17 @@ static int bcm_connect(struct socket *sock, struct sockaddr_unsized *uaddr, int goto fail; } - bo->ifindex = dev->ifindex; + WRITE_ONCE(bo->ifindex, dev->ifindex); dev_put(dev); } else { /* no interface reference for ifindex = 0 ('any' CAN device) */ - bo->ifindex = 0; + WRITE_ONCE(bo->ifindex, 0); } #if IS_ENABLED(CONFIG_PROC_FS) - if (net->can.bcmproc_dir) { + /* create the procfs entry once, it is removed in bcm_release() */ + if (net->can.bcmproc_dir && !bo->bcm_proc_read) { /* use unique socket inode number as filename */ snprintf(bo->procname, sizeof(bo->procname), "%llu", sock_i_ino(sk)); From f7c5b6e1968449bf4c9ca7f25b1d70b385c313e3 Mon Sep 17 00:00:00 2001 From: Oliver Hartkopp Date: Fri, 20 Nov 2026 12:28:57 +0100 Subject: [PATCH 1609/2102] can: raw: use a private mutex instead of lock_sock() raw_notify() takes lock_sock() of the sockets that are bound to a vanishing CAN device while holding RTNL. Any path that holds the socket lock while accessing user space can therefore block RTNL. Since commit 43c973a0887d ("can: raw, isotp: copy socket options outside of lock_sock()") the CAN_RAW specific socket options copy their values outside of the socket lock, but the generic SOL_SOCKET options in sk_setsockopt() and sk_getsockopt() still access user space under sockopt_lock_sock(), e.g. for SO_ATTACH_FILTER, SO_LINGER or SO_TXTIME. A stalled copy, e.g. on a FUSE backed mapping, then blocks raw_notify() and RTNL on the unregistration or namespace change of the bound CAN device. CAN_RAW only uses lock_sock() to serialize its own state: the binding, the filters and the CAN_RAW socket options. It does not use the socket backlog, as raw_rcv() queues the frames directly to the socket. Replace lock_sock() with the mutex conf_lock in struct raw_sock. The generic socket options do not take this mutex, so they can not block raw_notify() anymore. No user space access happens while the mutex is held. The memory allocations for the CAN receivers in can_rx_register() are still done under the mutex, as they have been under lock_sock() before. Sashiko suggested to hold not only the filter copy in raw_getsockopt() under the new conf_lock mutex but to also protect ro->raw_vcid_opts. This change will be addressed in a follow-up patch as it goes beyond a simple lock replacement intended for stable. Fixes: c18ce101f2e4 ("[CAN]: Add raw protocol") Cc: stable@vger.kernel.org # depends on "can: raw, isotp: copy socket options outside of lock_sock()" Tested-by: Oliver Hartkopp Signed-off-by: Oliver Hartkopp Link: https://patch.msgid.link/20261120-can-bcmlock-memcg-v7-3-f6b84f5257b1@hartkopp.net Signed-off-by: Marc Kleine-Budde --- net/can/raw.c | 41 ++++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/net/can/raw.c b/net/can/raw.c index f14270b56f5219..b69eaadc5e93ae 100644 --- a/net/can/raw.c +++ b/net/can/raw.c @@ -103,6 +103,7 @@ struct raw_sock { struct can_filter dfilter; /* default/single filter */ struct can_filter *filter; /* pointer to filter(s) */ struct uniqframe __percpu *uniq; + struct mutex conf_lock; /* protects bind, filters and setsockopt */ }; static LIST_HEAD(raw_notifier_list); @@ -319,7 +320,7 @@ static void raw_notify(struct raw_sock *ro, unsigned long msg, /* Lockless fast path, ro->bind_dev covers a concurrent bind(). * Read it before ro->dev, pairs with smp_store_release() in - * raw_bind(). A stale ro->bind_dev only costs a lock_sock(). + * raw_bind(). A stale ro->bind_dev only costs a mutex_lock(). */ bind_dev = smp_load_acquire(&ro->bind_dev); if (READ_ONCE(ro->dev) != dev && @@ -328,9 +329,9 @@ static void raw_notify(struct raw_sock *ro, unsigned long msg, switch (msg) { case NETDEV_UNREGISTER: - lock_sock(sk); + mutex_lock(&ro->conf_lock); if (ro->dev != dev) { - release_sock(sk); + mutex_unlock(&ro->conf_lock); break; } @@ -351,7 +352,7 @@ static void raw_notify(struct raw_sock *ro, unsigned long msg, sk->sk_err = ENODEV; if (!sock_flag(sk, SOCK_DEAD)) sk_error_report(sk); - release_sock(sk); + mutex_unlock(&ro->conf_lock); break; case NETDEV_DOWN: @@ -401,6 +402,7 @@ static int raw_init(struct sock *sk) ro->ifindex = 0; ro->dev = NULL; ro->bind_dev = NULL; + mutex_init(&ro->conf_lock); /* set default filter to single entry dfilter */ ro->dfilter.can_id = 0; @@ -451,7 +453,7 @@ static int raw_release(struct socket *sock) list_del(&ro->notifier); spin_unlock(&raw_notifier_lock); - lock_sock(sk); + mutex_lock(&ro->conf_lock); /* remove current filters & unregister * the tracked reference ro->dev keeps the device's receive lists @@ -474,11 +476,11 @@ static int raw_release(struct socket *sock) ro->dev = NULL; ro->count = 0; + mutex_unlock(&ro->conf_lock); + sock_orphan(sk); sock->sk = NULL; - release_sock(sk); - sock_prot_inuse_add(net, sk->sk_prot, -1); sock_put(sk); @@ -500,8 +502,8 @@ static int raw_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int len if (addr->can_family != AF_CAN) return -EINVAL; - /* lock_sock() serializes the binding with raw_notify() */ - lock_sock(sk); + /* ro->conf_lock serializes the binding with raw_notify() */ + mutex_lock(&ro->conf_lock); if (ro->bound && addr->can_ifindex == ro->ifindex) goto out; @@ -581,7 +583,7 @@ static int raw_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int len sk_error_report(sk); } - release_sock(sk); + mutex_unlock(&ro->conf_lock); return err; } @@ -621,7 +623,7 @@ static int raw_setsockopt_locked(struct socket *sock, int optname, * * The reg_state check is only a shortcut: On a concurrent * unregistration or namespace change raw_notify() waits for - * lock_sock() and removes the filters set here. + * ro->conf_lock and removes the filters set here. */ dev = ro->dev; if (ro->bound && dev && @@ -730,6 +732,7 @@ static int raw_setsockopt(struct socket *sock, int level, int optname, sockptr_t optval, unsigned int optlen) { struct sock *sk = sock->sk; + struct raw_sock *ro = raw_sk(sk); struct can_filter *filter = NULL; /* dyn. alloc'ed filters */ struct can_filter sfilter; /* single filter */ union { @@ -744,9 +747,9 @@ static int raw_setsockopt(struct socket *sock, int level, int optname, if (level != SOL_CAN_RAW) return -EINVAL; - /* Copy the option values from user space before lock_sock(), so a - * stalled copy can not block raw_notify() waiting for lock_sock() - * under RTNL. + /* Copy the option values from user space before taking ro->conf_lock, + * so a stalled copy can not block raw_notify() waiting for + * ro->conf_lock under RTNL. */ switch (optname) { case CAN_RAW_FILTER: @@ -798,11 +801,11 @@ static int raw_setsockopt(struct socket *sock, int level, int optname, return -EFAULT; } - lock_sock(sk); + mutex_lock(&ro->conf_lock); err = raw_setsockopt_locked(sock, optname, &val, filter, count); - release_sock(sk); + mutex_unlock(&ro->conf_lock); /* on error free the filters allocated for CAN_RAW_FILTER above */ if (err && count > 1) @@ -831,7 +834,7 @@ static int raw_getsockopt(struct socket *sock, int level, int optname, struct can_filter *filter = NULL; int err = 0; - lock_sock(sk); + mutex_lock(&ro->conf_lock); if (ro->count > 0) { int fsize = ro->count * sizeof(struct can_filter); @@ -843,7 +846,7 @@ static int raw_getsockopt(struct socket *sock, int level, int optname, } else { if (len > fsize) len = fsize; - /* copy to user space after release_sock() */ + /* copy to user space after mutex_unlock() */ filter = kmemdup(ro->filter, len, GFP_KERNEL); if (!filter) err = -ENOMEM; @@ -851,7 +854,7 @@ static int raw_getsockopt(struct socket *sock, int level, int optname, } else { len = 0; } - release_sock(sk); + mutex_unlock(&ro->conf_lock); if (filter) { if (copy_to_iter(filter, len, &opt->iter_out) != len) From c781fc329528ca26db2c4005d1e6efb92aa256e6 Mon Sep 17 00:00:00 2001 From: Oliver Hartkopp Date: Fri, 20 Nov 2026 12:28:58 +0100 Subject: [PATCH 1610/2102] can: isotp: use a private mutex instead of lock_sock() isotp_notify() takes lock_sock() of a socket that is bound to a vanishing CAN device while holding RTNL. Any path that holds the socket lock while accessing user space can therefore block RTNL. Since commit 43c973a0887d ("can: raw, isotp: copy socket options outside of lock_sock()") the CAN_ISOTP specific socket options copy their values outside of the socket lock, but the generic SOL_SOCKET options in sk_setsockopt() and sk_getsockopt() still access user space under sockopt_lock_sock(), e.g. for SO_ATTACH_FILTER, SO_LINGER or SO_TXTIME. CAN_ISOTP only uses lock_sock() to serialize the binding and the CAN_ISOTP socket options. It does not use the socket backlog, as the received PDUs are queued directly to the socket. Replace lock_sock() with the mutex conf_lock in struct isotp_sock. The generic socket options do not take this mutex, so they can not block isotp_notify() anymore. No user space access happens while the mutex is held. The memory allocations for the CAN receivers in isotp_bind() are still done under the mutex, as they have been under lock_sock() before. isotp_release() drops the mutex before synchronize_rcu() and the hrtimer cancellation, as the socket has already left the notifier list at this point. Following a Sashiko feedback for raw.c it would make sense to copy the content in isotp_getsockopt() under the new conf_lock mutex too. This change will be addressed in a follow-up patch as it goes beyond a simple lock replacement intended for stable. Fixes: e057dd3fc20f ("can: add ISO 15765-2:2016 transport protocol") Cc: stable@vger.kernel.org # depends on "can: raw, isotp: copy socket options outside of lock_sock()" Tested-by: Oliver Hartkopp Signed-off-by: Oliver Hartkopp Link: https://patch.msgid.link/20261120-can-bcmlock-memcg-v7-4-f6b84f5257b1@hartkopp.net Signed-off-by: Marc Kleine-Budde --- net/can/isotp.c | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/net/can/isotp.c b/net/can/isotp.c index 7a90ba3f1cf1c4..8229b6a69ecd0f 100644 --- a/net/can/isotp.c +++ b/net/can/isotp.c @@ -182,6 +182,7 @@ struct isotp_sock { struct list_head notifier; wait_queue_head_t wait; spinlock_t rx_lock; /* protect single thread state machine */ + struct mutex conf_lock; /* protects bind and setsockopt */ }; static LIST_HEAD(isotp_notifier_list); @@ -1497,7 +1498,7 @@ static int isotp_release(struct socket *sock) list_del(&so->notifier); spin_unlock(&isotp_notifier_lock); - lock_sock(sk); + mutex_lock(&so->conf_lock); /* remove current filters & unregister * the tracked reference so->dev keeps the device's receive lists @@ -1519,6 +1520,8 @@ static int isotp_release(struct socket *sock) WRITE_ONCE(so->bound, 0); so->dev = NULL; + mutex_unlock(&so->conf_lock); + /* Always wait for a grace period before touching the timers below. * A concurrent NETDEV_UNREGISTER may have already unregistered our * filters and cleared so->bound in isotp_notify() without waiting @@ -1535,7 +1538,6 @@ static int isotp_release(struct socket *sock) sock_orphan(sk); sock->sk = NULL; - release_sock(sk); sock_prot_inuse_add(net, sk->sk_prot, -1); sock_put(sk); @@ -1585,8 +1587,8 @@ static int isotp_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int l if (!addr->can_ifindex) return -ENODEV; - /* lock_sock() serializes the binding with isotp_notify() */ - lock_sock(sk); + /* so->conf_lock serializes the binding with isotp_notify() */ + mutex_lock(&so->conf_lock); if (so->bound) { err = -EINVAL; @@ -1596,7 +1598,7 @@ static int isotp_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int l /* A transmission or reception that outlived a previous binding * (unbound by NETDEV_UNREGISTER) may still be draining; the FC/echo * and RX watchdog timers bound how long this takes. Checked together - * with so->bound in the same lock_sock() section above, so there is + * with so->bound in the same so->conf_lock section above, so there is * no window in which a concurrent isotp_notify() could be missed. */ if (READ_ONCE(so->tx.state) != ISOTP_IDLE || @@ -1686,7 +1688,7 @@ static int isotp_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int l sk_error_report(sk); } - release_sock(sk); + mutex_unlock(&so->conf_lock); return err; } @@ -1790,6 +1792,7 @@ static int isotp_setsockopt(struct socket *sock, int level, int optname, { struct sock *sk = sock->sk; + struct isotp_sock *so = isotp_sk(sk); union { struct can_isotp_options opt; struct can_isotp_fc_options rxfc; @@ -1802,7 +1805,7 @@ static int isotp_setsockopt(struct socket *sock, int level, int optname, if (level != SOL_CAN_ISOTP) return -EINVAL; - /* copy the option values from user space before lock_sock() */ + /* copy the option values from user space before taking so->conf_lock */ switch (optname) { case CAN_ISOTP_OPTS: size = sizeof(val.opt); @@ -1831,9 +1834,9 @@ static int isotp_setsockopt(struct socket *sock, int level, int optname, if (copy_from_sockptr(&val, optval, size)) return -EFAULT; - lock_sock(sk); + mutex_lock(&so->conf_lock); ret = isotp_setsockopt_locked(sock, optname, &val); - release_sock(sk); + mutex_unlock(&so->conf_lock); return ret; } @@ -1906,9 +1909,9 @@ static void isotp_notify(struct isotp_sock *so, unsigned long msg, switch (msg) { case NETDEV_UNREGISTER: - lock_sock(sk); + mutex_lock(&so->conf_lock); if (so->dev != dev) { - release_sock(sk); + mutex_unlock(&so->conf_lock); break; } @@ -1932,7 +1935,7 @@ static void isotp_notify(struct isotp_sock *so, unsigned long msg, sk->sk_err = ENODEV; if (!sock_flag(sk, SOCK_DEAD)) sk_error_report(sk); - release_sock(sk); + mutex_unlock(&so->conf_lock); break; case NETDEV_DOWN: @@ -1991,6 +1994,7 @@ static int isotp_init(struct sock *sk) so->ifindex = 0; so->bound = 0; so->dev = NULL; + mutex_init(&so->conf_lock); so->opt.flags = CAN_ISOTP_DEFAULT_FLAGS; so->opt.ext_address = CAN_ISOTP_DEFAULT_EXT_ADDRESS; From bcea265a4c045c9119e5623d0959b27bb2a74340 Mon Sep 17 00:00:00 2001 From: Oliver Hartkopp Date: Fri, 20 Nov 2026 12:28:59 +0100 Subject: [PATCH 1611/2102] can: bcm: use a private mutex instead of lock_sock() bcm_notify() takes lock_sock() of every CAN_BCM socket in the namespace of a vanishing CAN device while holding RTNL. Any path that holds the socket lock while accessing user space can therefore block RTNL. With "can: bcm: copy the CAN frames outside of lock_sock()" the CAN frames of bcm_sendmsg() are copied outside of the socket lock, but the generic SOL_SOCKET options in sk_setsockopt() and sk_getsockopt() still access user space under sockopt_lock_sock(), e.g. for SO_ATTACH_FILTER, SO_LINGER or SO_TXTIME. CAN_BCM only uses lock_sock() to serialize the binding and the bcm_op lists. It does not use the socket backlog, as the BCM messages are queued directly to the socket. Replace lock_sock() with the mutex conf_lock in struct bcm_sock. The generic socket options do not take this mutex, so they can not block bcm_notify() anymore. No user space access happens while the mutex is held. The memory allocations for the bcm_ops and the CAN receivers are still done under the mutex, as they have been under lock_sock() before. bcm_release() removes the procfs entry before taking the mutex, as remove_proc_entry() waits for readers that may stall in their copy to user space. The socket has already left the notifier list at this point. Fixes: ffd980f976e7 ("[CAN]: Add broadcast manager (bcm) protocol") Cc: stable@vger.kernel.org # depends on "can: bcm: copy the CAN frames outside of lock_sock()" Tested-by: Oliver Hartkopp Signed-off-by: Oliver Hartkopp Link: https://patch.msgid.link/20261120-can-bcmlock-memcg-v7-5-f6b84f5257b1@hartkopp.net Signed-off-by: Marc Kleine-Budde --- net/can/bcm.c | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/net/can/bcm.c b/net/can/bcm.c index 1595b7720c9819..dc9e2890490acc 100644 --- a/net/can/bcm.c +++ b/net/can/bcm.c @@ -145,6 +145,7 @@ struct bcm_sock { unsigned long dropped_usr_msgs; struct proc_dir_entry *bcm_proc_read; char procname [32]; /* inode number in decimal with \0 */ + struct mutex conf_lock; /* protects bind and the bcm_op lists */ }; static LIST_HEAD(bcm_notifier_list); @@ -1673,8 +1674,8 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) if ((size - MHSIZ) % cfsiz) return -EINVAL; - /* Copy the CAN frames from user space before lock_sock(), so a - * stalled copy can not block bcm_notify() waiting for lock_sock() + /* Copy the CAN frames from user space before taking bo->conf_lock, so a + * stalled copy can not block bcm_notify() waiting for bo->conf_lock * under RTNL. Only the frames the opcode handler reads are copied. * The handlers keep their checks and read the frames from fmsg. */ @@ -1714,12 +1715,12 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) kv.iov_len = flen; iov_iter_kvec(&fmsg.msg_iter, ITER_SOURCE, &kv, 1, flen); - lock_sock(sk); + mutex_lock(&bo->conf_lock); - /* Re-validate under the socket lock: a concurrent bcm_notify() + /* Re-validate under bo->conf_lock: a concurrent bcm_notify() * may have unbound this socket (device removal) after the * lockless fast-path check above. bo->ifindex is only ever - * mutated under lock_sock(), so reading it here - instead of + * mutated under bo->conf_lock, so reading it here - instead of * before taking the lock - guarantees it can't be observed * torn against bo->bound. */ @@ -1819,7 +1820,7 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) } out_release: - release_sock(sk); + mutex_unlock(&bo->conf_lock); out_free: if (frames != &sframe) kvfree(frames); @@ -1843,7 +1844,7 @@ static void bcm_notify(struct bcm_sock *bo, unsigned long msg, switch (msg) { case NETDEV_UNREGISTER: - lock_sock(sk); + mutex_lock(&bo->conf_lock); /* rx_ops: remove device specific receive entries */ list_for_each_entry(op, &bo->rx_ops, list) { @@ -1877,7 +1878,7 @@ static void bcm_notify(struct bcm_sock *bo, unsigned long msg, notify_enodev = 1; } - release_sock(sk); + mutex_unlock(&bo->conf_lock); if (notify_enodev) { sk->sk_err = ENODEV; @@ -1930,6 +1931,7 @@ static int bcm_init(struct sock *sk) bo->ifindex = 0; bo->dropped_usr_msgs = 0; bo->bcm_proc_read = NULL; + mutex_init(&bo->conf_lock); INIT_LIST_HEAD(&bo->tx_ops); INIT_LIST_HEAD(&bo->rx_ops); @@ -1969,15 +1971,14 @@ static int bcm_release(struct socket *sock) list_del(&bo->notifier); spin_unlock(&bcm_notifier_lock); - /* bcm_notify() can not access this socket anymore */ - lock_sock(sk); - #if IS_ENABLED(CONFIG_PROC_FS) /* remove procfs entry */ if (net->can.bcmproc_dir && bo->bcm_proc_read) remove_proc_entry(bo->procname, net->can.bcmproc_dir); #endif /* CONFIG_PROC_FS */ + mutex_lock(&bo->conf_lock); + list_for_each_entry_safe(op, next, &bo->tx_ops, list) { list_del_rcu(&op->list); bcm_remove_op(op); @@ -2012,10 +2013,11 @@ static int bcm_release(struct socket *sock) WRITE_ONCE(bo->ifindex, 0); } + mutex_unlock(&bo->conf_lock); + sock_orphan(sk); sock->sk = NULL; - release_sock(sk); sock_prot_inuse_add(net, sk->sk_prot, -1); sock_put(sk); @@ -2034,7 +2036,7 @@ static int bcm_connect(struct socket *sock, struct sockaddr_unsized *uaddr, int if (len < BCM_MIN_NAMELEN) return -EINVAL; - lock_sock(sk); + mutex_lock(&bo->conf_lock); if (bo->bound) { ret = -EISCONN; @@ -2086,7 +2088,7 @@ static int bcm_connect(struct socket *sock, struct sockaddr_unsized *uaddr, int WRITE_ONCE(bo->bound, 1); fail: - release_sock(sk); + mutex_unlock(&bo->conf_lock); return ret; } From 4b558c0ccb62637788d5b643a17eba5757ce1ba5 Mon Sep 17 00:00:00 2001 From: Oliver Hartkopp Date: Fri, 20 Nov 2026 12:29:00 +0100 Subject: [PATCH 1612/2102] can: isotp: always start the rx timeout in ISOTP_WAIT_DATA state The rx timeout is only started at the end of isotp_send_fc() and for consecutive frames inside a block in isotp_rcv_cf(). So so->rx.state can stay in ISOTP_WAIT_DATA without a running rx timeout: - isotp_send_fc() returns early, when it can not allocate the skb or does not find the CAN device anymore - isotp_rcv_ff() does not send a flow control frame in listen mode - isotp_rcv_cf() has stopped the rx timeout and does not restart it at the end of a block, when the flow control frame is not sent - isotp_rcv_cf() has stopped the rx timeout before it drops a consecutive frame with an invalid length (reported by Sashiko) On a bound socket the next first frame or single frame resets the state. But when the CAN device has been removed, no further CAN frame is received and so->rx.state remains in ISOTP_WAIT_DATA. isotp_bind() then rejects a new binding with -EAGAIN until the socket is closed. Start the rx timeout in isotp_rcv_ff() and isotp_rcv_cf() whenever the reception continues in ISOTP_WAIT_DATA state, before a flow control frame is sent. isotp_send_fc() restarts the rx timeout as before. All this runs under so->rx_lock, so the order of the rx timeout start and the transmission of the flow control frame does not matter. In listen mode a first frame that is not followed by consecutive frames now leads to ETIMEDOUT, like a missing consecutive frame inside a block already does. So a listening socket reports a missing consecutive frame consistently, independent of its position in the PDU. Check the length of a consecutive frame first in isotp_rcv_cf(), so that an invalid frame is dropped without stopping the rx timeout. An invalid frame also no longer updates the timestamp for CAN_ISOTP_FORCE_RXSTMIN. Fixes: e057dd3fc20f ("can: add ISO 15765-2:2016 transport protocol") Cc: stable@vger.kernel.org Reported-by: Sashiko Closes: https://lore.kernel.org/linux-can/179504035916.3136.12986898667697830880@kernel.org/ Signed-off-by: Oliver Hartkopp Link: https://patch.msgid.link/20261120-can-bcmlock-memcg-v7-6-f6b84f5257b1@hartkopp.net Signed-off-by: Marc Kleine-Budde --- net/can/isotp.c | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/net/can/isotp.c b/net/can/isotp.c index 8229b6a69ecd0f..0b7db1ead7a904 100644 --- a/net/can/isotp.c +++ b/net/can/isotp.c @@ -634,6 +634,10 @@ static int isotp_rcv_ff(struct sock *sk, struct canfd_frame *cf, int ae) so->rx.sn = 1; WRITE_ONCE(so->rx.state, ISOTP_WAIT_DATA); + /* start rx timeout, isotp_send_fc() restarts it */ + hrtimer_start(&so->rxtimer, ktime_set(ISOTP_FC_TIMEOUT, 0), + HRTIMER_MODE_REL_SOFT); + /* no creation of flow control frames */ if (so->opt.flags & CAN_ISOTP_LISTEN_MODE) return 0; @@ -650,6 +654,17 @@ static int isotp_rcv_cf(struct sock *sk, struct canfd_frame *cf, int ae, struct sk_buff *nskb; int i; + /* CFs are never longer than the FF */ + if (cf->len > so->rx.ll_dl) + return 1; + + /* CFs have usually the LL_DL length */ + if (cf->len < so->rx.ll_dl) { + /* this is only allowed for the last CF */ + if (so->rx.len - so->rx.idx > so->rx.ll_dl - ae - N_PCI_SZ) + return 1; + } + if (READ_ONCE(so->rx.state) != ISOTP_WAIT_DATA) return 0; @@ -662,6 +677,7 @@ static int isotp_rcv_cf(struct sock *sk, struct canfd_frame *cf, int ae, so->lastrxcf_tstamp = skb->tstamp; } + /* stop the rx timeout only for valid CFs (checked above) */ hrtimer_cancel(&so->rxtimer); /* isotp_rx_timer_handler() may have raced us for so->rx.state @@ -670,17 +686,6 @@ static int isotp_rcv_cf(struct sock *sk, struct canfd_frame *cf, int ae, if (READ_ONCE(so->rx.state) != ISOTP_WAIT_DATA) return 1; - /* CFs are never longer than the FF */ - if (cf->len > so->rx.ll_dl) - return 1; - - /* CFs have usually the LL_DL length */ - if (cf->len < so->rx.ll_dl) { - /* this is only allowed for the last CF */ - if (so->rx.len - so->rx.idx > so->rx.ll_dl - ae - N_PCI_SZ) - return 1; - } - if ((cf->data[ae] & 0x0F) != so->rx.sn) { /* wrong sn detected - report 'illegal byte sequence' */ sk->sk_err = EILSEQ; @@ -726,13 +731,13 @@ static int isotp_rcv_cf(struct sock *sk, struct canfd_frame *cf, int ae, return 0; } + /* start rx timeout, isotp_send_fc() restarts it */ + hrtimer_start(&so->rxtimer, ktime_set(ISOTP_FC_TIMEOUT, 0), + HRTIMER_MODE_REL_SOFT); + /* perform blocksize handling, if enabled */ - if (!so->rxfc.bs || ++so->rx.bs < so->rxfc.bs) { - /* start rx timeout watchdog */ - hrtimer_start(&so->rxtimer, ktime_set(ISOTP_FC_TIMEOUT, 0), - HRTIMER_MODE_REL_SOFT); + if (!so->rxfc.bs || ++so->rx.bs < so->rxfc.bs) return 0; - } /* no creation of flow control frames */ if (so->opt.flags & CAN_ISOTP_LISTEN_MODE) From da0eaf6fd9bba61000508a4f84127e7c63b92861 Mon Sep 17 00:00:00 2001 From: Oliver Hartkopp Date: Fri, 20 Nov 2026 12:29:01 +0100 Subject: [PATCH 1613/2102] can: isotp: reject socket options while a transfer is active isotp_setsockopt_locked() only checks so->bound before it changes the CAN_ISOTP socket options. When the bound CAN device is unregistered, isotp_notify() clears so->bound, but a transmission or reception that is already in progress is not stopped and may still be draining. isotp_sendmsg() claims so->tx.state and rechecks so->bound. After that it can block in sock_alloc_send_skb(), while the device is unregistered and so->bound is cleared. A concurrent setsockopt() can then change so->opt, so->ll and so->tx.ll_dl, before isotp_sendmsg() reads so->ll.mtu and so->tx.ll_dl again to build the CAN frame for the skb that has been allocated with the former so->ll.mtu. isotp_bind() already rejects a new binding while so->tx.state or so->rx.state are not ISOTP_IDLE for the same reason. Add this check to isotp_setsockopt_locked() and return -EAGAIN, so the socket options can only be changed when no transfer is active. As the transmission and the reception always end by their timeouts at the latest, this state is only temporary. isotp_sendmsg() reads the CAN_ISOTP_EXTEND_ADDR and CAN_ISOTP_WAIT_TX_DONE flags at its beginning, before the transfer is claimed. Read them after the claim and the so->bound recheck instead, so that all socket options used by isotp_sendmsg() are covered by this check. Fixes: e057dd3fc20f ("can: add ISO 15765-2:2016 transport protocol") Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-d1d3ef49-c24e-4f3a-91ce-20f8fb222684 Cc: stable@vger.kernel.org Signed-off-by: Oliver Hartkopp Link: https://patch.msgid.link/20261120-can-bcmlock-memcg-v7-7-f6b84f5257b1@hartkopp.net Signed-off-by: Marc Kleine-Budde --- net/can/isotp.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/net/can/isotp.c b/net/can/isotp.c index 0b7db1ead7a904..642fec500af9df 100644 --- a/net/can/isotp.c +++ b/net/can/isotp.c @@ -1128,8 +1128,8 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) struct can_skb_ext *csx; struct net_device *dev; struct canfd_frame *cf; - int ae = (so->opt.flags & CAN_ISOTP_EXTEND_ADDR) ? 1 : 0; - int wait_tx_done = (so->opt.flags & CAN_ISOTP_WAIT_TX_DONE) ? 1 : 0; + int ae; + int wait_tx_done; s64 hrtimer_sec = ISOTP_ECHO_TIMEOUT; struct hrtimer *tx_hrt = &so->echotimer; u32 new_state = ISOTP_SENDING; @@ -1188,6 +1188,10 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) goto err_out_drop; } + /* read the options after the claim of the transfer */ + ae = (so->opt.flags & CAN_ISOTP_EXTEND_ADDR) ? 1 : 0; + wait_tx_done = (so->opt.flags & CAN_ISOTP_WAIT_TX_DONE) ? 1 : 0; + /* PDU size > default => try max_pdu_size */ if (size > so->tx.buflen && so->tx.buflen < max_pdu_size) { u8 *newbuf = kmalloc(max_pdu_size, GFP_KERNEL); @@ -1726,6 +1730,14 @@ static int isotp_setsockopt_locked(struct socket *sock, int optname, if (so->bound) return -EISCONN; + /* A transmission or reception that outlived a previous binding + * (unbound by NETDEV_UNREGISTER) may still be draining and uses the + * socket options, see isotp_bind(). + */ + if (READ_ONCE(so->tx.state) != ISOTP_IDLE || + READ_ONCE(so->rx.state) != ISOTP_IDLE) + return -EAGAIN; + switch (optname) { case CAN_ISOTP_OPTS: memcpy(&so->opt, val, sizeof(so->opt)); From 36da93199869c9a04091f2000efa24d5fa18aff8 Mon Sep 17 00:00:00 2001 From: Zhu Ling Date: Fri, 20 Nov 2026 12:29:02 +0100 Subject: [PATCH 1614/2102] can: netlink: fix static FD-NON-ISO mode validation Controllers with a static CAN_CTRLMODE_FD_NON_ISO mode (M_CAN v3.0.x and v3.1.x, PEAK pcan_usb_fd with firmware < 2.x) do not require the 'fd-non-iso' option to be provided when CAN FD is not switched on by the IFLA_CAN_CTRLMODE request. Since commit 6742ca18cb41 ("can: netlink: add userland error messages") ctrlstatic_missing is calculated before this exception is applied to ctrlstatic, which is not evaluated afterwards. As a result every IFLA_CAN_CTRLMODE request on such controllers that does not contain 'fd-non-iso on' is rejected with -EOPNOTSUPP and "missing required FD-NON-ISO static control mode", e.g. 'fd off', 'loopback on' or 'one-shot on', regardless of the current CAN FD state. Apply the exception to ctrlstatic_missing instead. The exception must only relax the requirement to *provide* the static FD-NON-ISO mode. It must not allow to *switch off* a static mode: before the above mentioned commit a request like 'fd-non-iso off' passed the check and removed the static CAN_CTRLMODE_FD_NON_ISO bit from priv->ctrlmode. As can_get_static_ctrlmode() derives the static modes from priv->ctrlmode, this information was lost permanently. Therefore reject any request that explicitly switches off a static control mode with a dedicated error message. With this check in place a static mode can never be cleared by the 'priv->ctrlmode &= ~cm->mask' operation as every static bit in cm->mask is also set in maskedflags. The request is rejected independent of the resulting CAN FD state, as accepting it while CAN FD is switched off would remove the static mode from priv->ctrlmode as well. Older kernels without the above mentioned commit do not need this fix. They can lose the static FD-NON-ISO mode by an explicit 'fd-non-iso off' too, but this only changes the reported control mode while the hardware keeps using non-ISO CAN FD. [Hartkopp: reject switching off static control modes instead of restoring them, extend the commit message (Sashiko review)] Fixes: 6742ca18cb41 ("can: netlink: add userland error messages") Cc: stable@vger.kernel.org Signed-off-by: Zhu Ling Link: https://lore.kernel.org/all/tencent_3A964832542399A780E646D6A6246335C409@qq.com/ Link: https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261115095746.709371-1-mkl%40pengutronix.de Signed-off-by: Oliver Hartkopp Link: https://patch.msgid.link/20261120-can-bcmlock-memcg-v7-8-f6b84f5257b1@hartkopp.net Signed-off-by: Marc Kleine-Budde --- drivers/net/can/dev/netlink.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/drivers/net/can/dev/netlink.c b/drivers/net/can/dev/netlink.c index 081dfddda00088..521e2496e2cc38 100644 --- a/drivers/net/can/dev/netlink.c +++ b/drivers/net/can/dev/netlink.c @@ -330,9 +330,17 @@ static int can_ctrlmode_changelink(struct net_device *dev, return -EOPNOTSUPP; } + /* static control modes can not be switched off */ + if (deactivated & ctrlstatic) { + NL_SET_ERR_MSG_FMT(extack, + "static control mode %s can not be switched off", + can_get_ctrlmode_str(deactivated & ctrlstatic)); + return -EOPNOTSUPP; + } + /* do not check for static fd-non-iso if 'fd' is disabled */ if (!(maskedflags & CAN_CTRLMODE_FD)) - ctrlstatic &= ~CAN_CTRLMODE_FD_NON_ISO; + ctrlstatic_missing &= ~CAN_CTRLMODE_FD_NON_ISO; if (ctrlstatic_missing) { NL_SET_ERR_MSG_FMT(extack, From 0bfb76b7c9274566cbcfe264e376dc18ad405059 Mon Sep 17 00:00:00 2001 From: Zhu Ling Date: Sat, 5 Sep 2026 00:20:58 +0800 Subject: [PATCH 1615/2102] can: netlink: fix IFLA_CAN_BITRATE_MAX attribute sizing can_fill_info() emits IFLA_CAN_BITRATE_MAX with nla_put(), which consumes space for both the attribute header and its aligned payload. However, can_get_size() accounts for the payload only. The resulting underestimate can make filling the netlink response fail with -EMSGSIZE when the skb has no remaining slack. Use nla_total_size() to account for the complete attribute. Fixes: 2290aefa2e90 ("can: dev: Add support for limiting configured bitrate") Cc: stable@vger.kernel.org Signed-off-by: Zhu Ling Reviewed-by: Marc Kleine-Budde Link: https://patch.msgid.link/tencent_D1C873B86B0E92011A264B0E196B911D5308@qq.com Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-3924d490-baed-49dc-880a-6fd1163cf08d Signed-off-by: Marc Kleine-Budde --- drivers/net/can/dev/netlink.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/can/dev/netlink.c b/drivers/net/can/dev/netlink.c index 521e2496e2cc38..10e7ccaf40fbf0 100644 --- a/drivers/net/can/dev/netlink.c +++ b/drivers/net/can/dev/netlink.c @@ -833,7 +833,7 @@ static size_t can_get_size(const struct net_device *dev) if (priv->bitrate_const) /* IFLA_CAN_BITRATE_CONST */ size += nla_total_size(sizeof(*priv->bitrate_const) * priv->bitrate_const_cnt); - size += sizeof(priv->bitrate_max); /* IFLA_CAN_BITRATE_MAX */ + size += nla_total_size(sizeof(priv->bitrate_max)); /* IFLA_CAN_BITRATE_MAX */ size += can_ctrlmode_ext_get_size(); /* IFLA_CAN_CTRLMODE_EXT */ size += can_data_bittiming_get_size(dev, &priv->fd, From 3949d692d64642d8921e4ad0d0e91ba73a668a4c Mon Sep 17 00:00:00 2001 From: Zhu Ling Date: Fri, 4 Sep 2026 23:26:40 +0800 Subject: [PATCH 1616/2102] can: netlink: fix CAN XL PWM attribute sizing can_pwm_fill_info() emits the PWM capability limits whenever pwm_const is present, regardless of whether TMS is enabled. In contrast, can_pwm_get_size() currently returns 0 when TMS is disabled. It therefore underestimates the required netlink message size by the nested attribute header and 6 u32 attributes. Always account for the PWM capability attributes when pwm_const is present, and account for the 3 runtime PWM values only when TMS is enabled. Fixes: 46552323fa67 ("can: netlink: add PWM netlink interface") Cc: stable@vger.kernel.org Signed-off-by: Zhu Ling Link: https://patch.msgid.link/tencent_9A525E0656A4F7D4CA9CFA1AB1A4BFC6D706@qq.com Reported-by: Sashiko Closes: https://sashiko.dev/#/bug/linux-3924d490-baed-49dc-880a-6fd1163cf08d Reviewed-by: Marc Kleine-Budde Signed-off-by: Marc Kleine-Budde --- drivers/net/can/dev/netlink.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/drivers/net/can/dev/netlink.c b/drivers/net/can/dev/netlink.c index 10e7ccaf40fbf0..7f597c975c6f4a 100644 --- a/drivers/net/can/dev/netlink.c +++ b/drivers/net/can/dev/netlink.c @@ -791,7 +791,7 @@ static size_t can_pwm_get_size(const struct can_pwm_const *pwm_const, { size_t size; - if (!pwm_const || !pwm_on) + if (!pwm_const) return 0; size = nla_total_size(0); /* nest IFLA_CAN_PWM */ @@ -803,9 +803,11 @@ static size_t can_pwm_get_size(const struct can_pwm_const *pwm_const, size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMO_MIN */ size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMO_MAX */ - size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMS */ - size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWML */ - size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMO */ + if (pwm_on) { + size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMS */ + size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWML */ + size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMO */ + } return size; } From 4dfaa1160683505334c7c1ea5959099679d7dc42 Mon Sep 17 00:00:00 2001 From: Marc Kleine-Budde Date: Sun, 25 Oct 2026 14:20:22 +0100 Subject: [PATCH 1617/2102] can: gs_usb: gs_can_start_xmit(): don't leak uninitialized memory over USB The driver allocates the transmission buffer using kmalloc(), which means the memory remains uninitialized. Then various headers are filled and, but only the actual CAN frame data payload (of length cfd->len or cf->len) is copied into the buffer, leaving the remaining buffer uninitialized. Fix this information leak, allocate the buffer with kzalloc(). Closes: https://sashiko.dev/#/bug/linux-0a8c0e8a-c623-426a-8db3-f55111f6cd84 Fixes: d08e973a77d1 ("can: gs_usb: Added support for the GS_USB CAN devices") Cc: stable@vger.kernel.org Signed-off-by: Marc Kleine-Budde --- drivers/net/can/usb/gs_usb.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/can/usb/gs_usb.c b/drivers/net/can/usb/gs_usb.c index 3b9b2f104d868e..15f28833f2debd 100644 --- a/drivers/net/can/usb/gs_usb.c +++ b/drivers/net/can/usb/gs_usb.c @@ -861,7 +861,7 @@ static netdev_tx_t gs_can_start_xmit(struct sk_buff *skb, if (!urb) goto nomem_urb; - hf = kmalloc(dev->hf_size_tx, GFP_ATOMIC); + hf = kzalloc(dev->hf_size_tx, GFP_ATOMIC); if (!hf) goto nomem_hf; From 8691992932377570ec79cbeb2ce5f24748bfe698 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Uwe=20Kleine-K=C3=B6nig=20=28The=20Capable=20Hub=29?= Date: Thu, 18 Jun 2026 16:01:47 +0200 Subject: [PATCH 1618/2102] can: flexcan: Fix probing for m68k/coldfire MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When determining the device details was reworked in commit 5e6c3454b405 ("net: can: Use device_get_match_data()") there was no replacement for the previous handling of non-of instantiated devices via the device's id_entry which then results in a NULL pointer exception. The only in-tree provider of such a device is arch/m68k/coldfire/device.c. Given the id_table only contains a single entry just hardcode the result of `platform_get_device_id(pdev)->driver_data` and drop the unused assignment to .driver_data from the table. While touching the id table, drop the unusual comma after the terminator entry. Fixes: 5e6c3454b405 ("net: can: Use device_get_match_data()") Cc: stable@vger.kernel.org Signed-off-by: Uwe Kleine-König (The Capable Hub) Link: https://patch.msgid.link/20260618140147.142489-2-u.kleine-koenig@baylibre.com Cc: Vincent Mailhol Cc: Rob Herring Cc: Marc Kleine-Budde Cc: linux-can@vger.kernel.org Cc: linux-kernel@vger.kernel.org Cc: Jean-Michel Hautbois Signed-off-by: Marc Kleine-Budde --- drivers/net/can/flexcan/flexcan-core.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/drivers/net/can/flexcan/flexcan-core.c b/drivers/net/can/flexcan/flexcan-core.c index 86b40abe9e767e..e9b82267821350 100644 --- a/drivers/net/can/flexcan/flexcan-core.c +++ b/drivers/net/can/flexcan/flexcan-core.c @@ -2077,10 +2077,9 @@ MODULE_DEVICE_TABLE(of, flexcan_of_match); static const struct platform_device_id flexcan_id_table[] = { { .name = "flexcan-mcf5441x", - .driver_data = (kernel_ulong_t)&fsl_mcf5441x_devtype_data, }, { /* sentinel */ - }, + } }; MODULE_DEVICE_TABLE(platform, flexcan_id_table); @@ -2148,6 +2147,15 @@ static int flexcan_probe(struct platform_device *pdev) return PTR_ERR(regs); devtype_data = device_get_match_data(&pdev->dev); + if (!devtype_data) + /* + * If the device was instantiated via the traditional platform + * mechanisms (i.e. not by device tree), device_get_match_data() + * returns NULL. The only remaining such device is mcf_flexcan0 + * (defined in arch/m68k/coldfire/device.c). Pick the right + * device type for that. + */ + devtype_data = &fsl_mcf5441x_devtype_data; if ((devtype_data->quirks & FLEXCAN_QUIRK_SUPPORT_FD) && !((devtype_data->quirks & From ae0f780d10e3b8782e5559c22e0360c76c7bece8 Mon Sep 17 00:00:00 2001 From: Ivan Verbovoy Date: Mon, 9 Nov 2026 06:21:11 +0200 Subject: [PATCH 1619/2102] soundwire: qcom: enable CPU interrupts only for MMIO controllers Commit b27be5a85ed3 ("soundwire: qcom: add EE-aware register layout for Shikra") dropped the ctrl->mmio check around the CPU interrupt enable in qcom_swrm_init(), which its message does not mention. The enable has been written for MMIO controllers only since they were added in commit 82f5c70c2651 ("soundwire: qcom: add support for mmio soundwire master devices"); a controller inside a codec, reached over SLIMbus, was left alone. On a Surface Duo (SM8150, a WCD9340 with one WSA8815 on its SoundWire) the amplifier no longer enumerates since: "SWR bus clsh detected" at boot, "link failed to connect" at each resume, and every stream fails with -110. With the check back it enumerates and plays again. Shikra's controller is MMIO and keeps the enable. Fixes: b27be5a85ed3 ("soundwire: qcom: add EE-aware register layout for Shikra") Signed-off-by: Ivan Verbovoy Reviewed-by: Srinivas Kandagatla Reviewed-by: Konrad Dybcio Link: https://patch.msgid.link/20261109-swrm-mmio-irq-v1-1-570fc05f22d7@gmail.com Signed-off-by: Vinod Koul --- drivers/soundwire/qcom.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/soundwire/qcom.c b/drivers/soundwire/qcom.c index 6e0c5fb10efad4..32690604538644 100644 --- a/drivers/soundwire/qcom.c +++ b/drivers/soundwire/qcom.c @@ -995,8 +995,9 @@ static int qcom_swrm_init(struct qcom_swrm_ctrl *ctrl) 0xFFFFFFFF); /* enable CPU IRQs for the selected EE window */ - ctrl->reg_write(ctrl, ctrl->reg_layout[SWRM_REG_INTERRUPT_CPU_EN], - SWRM_INTERRUPT_STATUS_RMSK); + if (ctrl->mmio) + ctrl->reg_write(ctrl, ctrl->reg_layout[SWRM_REG_INTERRUPT_CPU_EN], + SWRM_INTERRUPT_STATUS_RMSK); /* Set IRQ to PULSE */ ctrl->reg_write(ctrl, SWRM_COMP_CFG_ADDR, From 044b02cb3a8e2ea3d20be77b19825a2a30191a45 Mon Sep 17 00:00:00 2001 From: Bard Liao Date: Sun, 22 Nov 2026 19:44:42 +0800 Subject: [PATCH 1620/2102] soundwire: dmi-quirks: Add MSI Modern 16S AI+ quirk MSI Modern 16S AI+ has the ghost rt722 codec in the BIOS. Signed-off-by: Bard Liao Link: https://patch.msgid.link/20261122114442.2140276-1-yung-chuan.liao@linux.intel.com Signed-off-by: Vinod Koul --- drivers/soundwire/dmi-quirks.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/soundwire/dmi-quirks.c b/drivers/soundwire/dmi-quirks.c index 7156261743678a..1c3c57ebc2ea15 100644 --- a/drivers/soundwire/dmi-quirks.c +++ b/drivers/soundwire/dmi-quirks.c @@ -249,6 +249,13 @@ static const struct dmi_system_id adr_remap_quirk_table[] = { }, .driver_data = (void *)ghost_realtek, }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International Co., Ltd."), + DMI_MATCH(DMI_PRODUCT_NAME, "Modern 16S AI+ G3MG"), + }, + .driver_data = (void *)ghost_realtek, + }, { .matches = { DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), From 7cbbfda56518bfa9360e2f303654db9f01372dc1 Mon Sep 17 00:00:00 2001 From: Srinivas Kandagatla Date: Mon, 23 Nov 2026 17:14:09 +0000 Subject: [PATCH 1621/2102] dt-bindings: soundwire: qcom: describe multi-master v3.1.0+ Qualcomm SoundWire IPs can be paired to expose one logical bus with more than two DATA lanes. Add three properties that describe such a pair: qcom,multi-master-mode role in the pair ("primary" or "dependent") qcom,multi-master-peer to the other IP num-lanes DATA lanes each IP exposes locally Both nodes carry qcom,multi-master-mode / qcom,multi-master-peer / num-lanes. Reviewed-by: Krzysztof Kozlowski Signed-off-by: Srinivas Kandagatla Link: https://patch.msgid.link/20261123171411.444381-2-srinivas.kandagatla@oss.qualcomm.com Signed-off-by: Vinod Koul --- .../bindings/soundwire/qcom,soundwire.yaml | 108 ++++++++++++++++-- 1 file changed, 99 insertions(+), 9 deletions(-) diff --git a/Documentation/devicetree/bindings/soundwire/qcom,soundwire.yaml b/Documentation/devicetree/bindings/soundwire/qcom,soundwire.yaml index 81532cf69dd0c4..0ba3a979b68cb3 100644 --- a/Documentation/devicetree/bindings/soundwire/qcom,soundwire.yaml +++ b/Documentation/devicetree/bindings/soundwire/qcom,soundwire.yaml @@ -216,6 +216,36 @@ properties: maximum: 4 - const: 0xff + qcom,multi-master-mode: + description: + Role in v3.1.0+ multi-master mode. Both nodes set this; the + primary owns SWR_CLK, the dependent contributes DATA lanes + only. + $ref: /schemas/types.yaml#/definitions/string + enum: [ primary, dependent ] + + qcom,multi-master-peer: + description: + Peers in multi-master mode. Each entry is a + pair. Peer N's DPn slots + 1, 2, 3, ... occupy bus ports (offset+1), (offset+2), ... + $ref: /schemas/types.yaml#/definitions/phandle-array + items: + items: + - description: peer phandle + - description: bus port offset (last primary-local port) + minItems: 1 + + num-lanes: + description: + Number of DATA lanes this IP exposes locally. Required in + multi-master mode; on the primary it defines the boundary + between local bus lanes (0..num-lanes-1) and lanes contributed + by the dependent. + $ref: /schemas/types.yaml#/definitions/uint32 + minimum: 1 + maximum: 8 + label: maxItems: 1 @@ -225,21 +255,81 @@ required: - interrupts - clocks - clock-names - - '#sound-dai-cells' - '#address-cells' - '#size-cells' - - qcom,ports-offset1 - - qcom,ports-offset2 - -oneOf: - - required: - - qcom,ports-sinterval-low - - required: - - qcom,ports-sinterval allOf: - $ref: soundwire-controller.yaml# + # Single-master (no qcom,multi-master-mode): needs port config. + - if: + not: + required: + - qcom,multi-master-mode + then: + required: + - '#sound-dai-cells' + - qcom,ports-offset1 + - qcom,ports-offset2 + oneOf: + - required: + - qcom,ports-sinterval-low + - required: + - qcom,ports-sinterval + + # Multi-master primary: drives the bus, needs port config + MM props. + - if: + properties: + qcom,multi-master-mode: + const: primary + required: + - qcom,multi-master-mode + then: + properties: + compatible: + contains: + const: qcom,soundwire-v3.1.0 + required: + - '#sound-dai-cells' + - qcom,ports-offset1 + - qcom,ports-offset2 + - qcom,multi-master-peer + - num-lanes + oneOf: + - required: + - qcom,ports-sinterval-low + - required: + - qcom,ports-sinterval + + # Multi-master dependent: contributes DATA lanes only, no ports. + - if: + properties: + qcom,multi-master-mode: + const: dependent + required: + - qcom,multi-master-mode + then: + properties: + compatible: + contains: + const: qcom,soundwire-v3.1.0 + '#sound-dai-cells': false + qcom,din-ports: false + qcom,dout-ports: false + qcom,ports-word-length: false + qcom,ports-sinterval-low: false + qcom,ports-sinterval: false + qcom,ports-offset1: false + qcom,ports-offset2: false + qcom,ports-lane-control: false + qcom,ports-block-pack-mode: false + qcom,ports-hstart: false + qcom,ports-hstop: false + qcom,ports-block-group-count: false + required: + - qcom,multi-master-peer + - num-lanes + unevaluatedProperties: false examples: From 55207a5b69592e6ec1468baa2524b5a33845ff06 Mon Sep 17 00:00:00 2001 From: Srinivas Kandagatla Date: Mon, 23 Nov 2026 17:14:10 +0000 Subject: [PATCH 1622/2102] soundwire: qcom: add multi-master support v3.1.0+ Qualcomm SoundWire IPs can be paired to expose one logical bus with more than two DATA lanes. One IP owns SWR_CLK and drives the bus; the other contributes DATA lanes only and never issues commands. Logical ports on the primary are mapped to a lane; writes to a port whose lane falls in the dependent's range are routed to the matching register on the dependent IP, offset by the primary's lane count. The dependent IP has no sdw_bus of its own. Give it minimal runtime PM callbacks that only gate its hclk, and use a device link with DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE so the dependent resumes before the primary touches peer registers and suspends after it. Single-master deployments (no qcom,multi-master-mode in DT) are unaffected. Signed-off-by: Srinivas Kandagatla Link: https://patch.msgid.link/20261123171411.444381-3-srinivas.kandagatla@oss.qualcomm.com Signed-off-by: Vinod Koul --- drivers/soundwire/qcom.c | 278 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 260 insertions(+), 18 deletions(-) diff --git a/drivers/soundwire/qcom.c b/drivers/soundwire/qcom.c index 32690604538644..b8d7ced1df9020 100644 --- a/drivers/soundwire/qcom.c +++ b/drivers/soundwire/qcom.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -113,6 +114,7 @@ #define SWRM_DPn_PORT_HCTRL_BANK(offset, n, m) (offset + 0x100 * (n - 1) + 0x40 * m) #define SWRM_DPn_BLOCK_CTRL3_BANK(offset, n, m) (offset + 0x100 * (n - 1) + 0x40 * m) #define SWRM_DPn_SAMPLECTRL2_BANK(offset, n, m) (offset + 0x100 * (n - 1) + 0x40 * m) +#define SWRM_DPn_SLOT_STRIDE 0x100 #define SWR_V1_3_MSTR_MAX_REG_ADDR 0x1740 #define SWR_V2_0_MSTR_MAX_REG_ADDR 0x50ac @@ -187,6 +189,12 @@ enum { SWRM_OFFSET_DP_SAMPLECTRL2_BANK, }; +enum qcom_swrm_mm_role { + QCOM_SWRM_MM_NONE, + QCOM_SWRM_MM_PRIMARY, + QCOM_SWRM_MM_DEPENDENT, +}; + struct qcom_swrm_ctrl { struct sdw_bus bus; struct device *dev; @@ -195,6 +203,12 @@ struct qcom_swrm_ctrl { const unsigned int *reg_layout; void __iomem *mmio; struct reset_control *audio_cgcr; + u8 num_lanes; + struct qcom_swrm_ctrl *peer_ctrl; + u8 peer_first_lane; + u8 num_peer_lanes; + enum qcom_swrm_mm_role mm_role; + u32 peer_dpn_offset; #ifdef CONFIG_DEBUG_FS struct dentry *debugfs; #endif @@ -950,7 +964,9 @@ static int qcom_swrm_init(struct qcom_swrm_ctrl *ctrl) /* Enable Auto enumeration */ ctrl->reg_write(ctrl, SWRM_ENUMERATOR_CFG_ADDR, 1); - ctrl->intr_mask = SWRM_INTERRUPT_STATUS_RMSK; + /* dependent has no sdw_bus; keep IRQ dispatch masked */ + if (ctrl->mm_role != QCOM_SWRM_MM_DEPENDENT) + ctrl->intr_mask = SWRM_INTERRUPT_STATUS_RMSK; /* Mask soundwire interrupts */ if (ctrl->version < SWRM_VERSION_2_0_0) ctrl->reg_write(ctrl, ctrl->reg_layout[SWRM_REG_INTERRUPT_MASK_ADDR], @@ -994,10 +1010,11 @@ static int qcom_swrm_init(struct qcom_swrm_ctrl *ctrl) ctrl->reg_write(ctrl, ctrl->reg_layout[SWRM_REG_INTERRUPT_CLEAR], 0xFFFFFFFF); - /* enable CPU IRQs for the selected EE window */ - if (ctrl->mmio) + /* enable CPU IRQs for the selected EE window; dependent has no sdw_bus */ + if (ctrl->mmio && ctrl->mm_role != QCOM_SWRM_MM_DEPENDENT) { ctrl->reg_write(ctrl, ctrl->reg_layout[SWRM_REG_INTERRUPT_CPU_EN], SWRM_INTERRUPT_STATUS_RMSK); + } /* Set IRQ to PULSE */ ctrl->reg_write(ctrl, SWRM_COMP_CFG_ADDR, @@ -1092,9 +1109,48 @@ static int qcom_swrm_pre_bank_switch(struct sdw_bus *bus) u32p_replace_bits(&val, ctrl->cols_index, SWRM_MCP_FRAME_CTRL_BANK_COL_CTRL_BMSK); u32p_replace_bits(&val, ctrl->rows_index, SWRM_MCP_FRAME_CTRL_BANK_ROW_CTRL_BMSK); + if (ctrl->peer_ctrl) + ctrl->peer_ctrl->reg_write(ctrl->peer_ctrl, reg, val); + return ctrl->reg_write(ctrl, reg, val); } +static struct qcom_swrm_ctrl * +qcom_swrm_port_target(struct qcom_swrm_ctrl *ctrl, u8 port_num, u32 *reg) +{ + u8 lane; + + if (WARN_ON_ONCE(!port_num || port_num > ctrl->nports)) + return ctrl; + + lane = ctrl->pconfig[port_num].lane_control; + + if (ctrl->peer_ctrl && lane >= ctrl->peer_first_lane && + lane < ctrl->peer_first_lane + ctrl->num_peer_lanes) { + if (WARN_ON_ONCE(*reg < ctrl->peer_dpn_offset)) + return ctrl; + *reg -= ctrl->peer_dpn_offset; + return ctrl->peer_ctrl; + } + return ctrl; +} + +static int qcom_swrm_port_reg_write(struct qcom_swrm_ctrl *ctrl, u8 port_num, + u32 reg, u32 val) +{ + struct qcom_swrm_ctrl *tgt = qcom_swrm_port_target(ctrl, port_num, ®); + + return tgt->reg_write(tgt, reg, val); +} + +static int qcom_swrm_port_reg_read(struct qcom_swrm_ctrl *ctrl, u8 port_num, + u32 reg, u32 *val) +{ + struct qcom_swrm_ctrl *tgt = qcom_swrm_port_target(ctrl, port_num, ®); + + return tgt->reg_read(tgt, reg, val); +} + static int qcom_swrm_port_params(struct sdw_bus *bus, struct sdw_port_params *p_params, unsigned int bank) @@ -1102,8 +1158,9 @@ static int qcom_swrm_port_params(struct sdw_bus *bus, struct qcom_swrm_ctrl *ctrl = to_qcom_sdw(bus); u32 offset = ctrl->reg_layout[SWRM_OFFSET_DP_BLOCK_CTRL_1]; - return ctrl->reg_write(ctrl, SWRM_DPn_BLOCK_CTRL_1(offset, p_params->num), - p_params->bps - 1); + return qcom_swrm_port_reg_write(ctrl, p_params->num, + SWRM_DPn_BLOCK_CTRL_1(offset, p_params->num), + p_params->bps - 1); } static int qcom_swrm_transport_params(struct sdw_bus *bus, @@ -1124,7 +1181,7 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, value |= pcfg->off2 << SWRM_DP_PORT_CTRL_OFFSET2_SHFT; value |= pcfg->si & 0xff; - ret = ctrl->reg_write(ctrl, reg, value); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); if (ret) goto err; @@ -1133,7 +1190,7 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, value = (pcfg->si >> 8) & 0xff; reg = SWRM_DPn_SAMPLECTRL2_BANK(offset, params->port_num, bank); - ret = ctrl->reg_write(ctrl, reg, value); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); if (ret) goto err; } @@ -1143,7 +1200,10 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, reg = SWRM_DPn_PORT_CTRL_2_BANK(offset, params->port_num, bank); value = pcfg->lane_control; - ret = ctrl->reg_write(ctrl, reg, value); + if (ctrl->peer_ctrl && value >= ctrl->peer_first_lane && + value < ctrl->peer_first_lane + ctrl->num_peer_lanes) + value -= ctrl->peer_first_lane; + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); if (ret) goto err; } @@ -1154,7 +1214,7 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, reg = SWRM_DPn_BLOCK_CTRL2_BANK(offset, params->port_num, bank); value = pcfg->blk_group_count; - ret = ctrl->reg_write(ctrl, reg, value); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); if (ret) goto err; } @@ -1164,10 +1224,10 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, if (pcfg->hstart != SWR_INVALID_PARAM && pcfg->hstop != SWR_INVALID_PARAM) { value = (pcfg->hstop << 4) | pcfg->hstart; - ret = ctrl->reg_write(ctrl, reg, value); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); } else { value = (SWR_HSTOP_MAX_VAL << 4) | SWR_HSTART_MIN_VAL; - ret = ctrl->reg_write(ctrl, reg, value); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); } if (ret) @@ -1176,7 +1236,8 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, if (pcfg->bp_mode != SWR_INVALID_PARAM) { offset = ctrl->reg_layout[SWRM_OFFSET_DP_BLOCK_CTRL3_BANK]; reg = SWRM_DPn_BLOCK_CTRL3_BANK(offset, params->port_num, bank); - ret = ctrl->reg_write(ctrl, reg, pcfg->bp_mode); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, + pcfg->bp_mode); } err: @@ -1194,14 +1255,14 @@ static int qcom_swrm_port_enable(struct sdw_bus *bus, reg = SWRM_DPn_PORT_CTRL_BANK(offset, enable_ch->port_num, bank); - ctrl->reg_read(ctrl, reg, &val); + qcom_swrm_port_reg_read(ctrl, enable_ch->port_num, reg, &val); if (enable_ch->enable) val |= (enable_ch->ch_mask << SWRM_DP_PORT_CTRL_EN_CHAN_SHFT); else val &= ~(0xff << SWRM_DP_PORT_CTRL_EN_CHAN_SHFT); - return ctrl->reg_write(ctrl, reg, val); + return qcom_swrm_port_reg_write(ctrl, enable_ch->port_num, reg, val); } static const struct sdw_master_port_ops qcom_swrm_port_ops = { @@ -1614,6 +1675,103 @@ static int swrm_reg_show(struct seq_file *s_file, void *data) DEFINE_SHOW_ATTRIBUTE(swrm_reg); #endif +static int qcom_swrm_multi_master_setup(struct qcom_swrm_ctrl *ctrl) +{ + struct of_phandle_args args; + struct qcom_swrm_ctrl *peer; + struct platform_device *pdev; + u32 offset; + int ret; + + if (ctrl->peer_ctrl) { + dev_err(ctrl->dev, "multi-master peer already paired\n"); + return -EBUSY; + } + + ret = of_parse_phandle_with_fixed_args(ctrl->dev->of_node, + "qcom,multi-master-peer", + 1, 0, &args); + if (ret) + return -EINVAL; + + pdev = of_find_device_by_node(args.np); + of_node_put(args.np); + if (!pdev) + return -EPROBE_DEFER; + + /* + * Lock the peer device while we inspect its driver binding and + * drvdata. This prevents a concurrent sysfs unbind from dropping + * pdev->dev.driver between the check below and the drvdata read; + * it also covers the mid-probe case: if the peer has not finished + * binding yet, pdev->dev.driver is NULL and we defer so driver + * core reprobes us once it is bound. + */ + device_lock(&pdev->dev); + + if (!pdev->dev.driver) { + ret = -EPROBE_DEFER; + goto out_unlock; + } + + if (pdev->dev.driver != ctrl->dev->driver) { + ret = -EINVAL; + goto out_unlock; + } + + peer = platform_get_drvdata(pdev); + if (!peer || peer->mm_role != QCOM_SWRM_MM_DEPENDENT) { + ret = -EPROBE_DEFER; + goto out_unlock; + } + + if (peer->peer_ctrl) { + dev_err(ctrl->dev, "multi-master peer %s already claimed\n", + dev_name(&pdev->dev)); + ret = -EBUSY; + goto out_unlock; + } + + if (!ctrl->num_lanes || !peer->num_lanes || + ctrl->num_lanes + peer->num_lanes > SDW_MAX_LANES) { + ret = -EINVAL; + goto out_unlock; + } + + offset = args.args[0]; + if (offset < ctrl->num_lanes) { + dev_err(ctrl->dev, "qcom,multi-master-peer: offset %u < num-lanes %u\n", + offset, ctrl->num_lanes); + ret = -EINVAL; + goto out_unlock; + } + + /* + * The dependent's hclk is gated from its own runtime PM; keep it + * active while the primary is, and resume it now as the rest of + * probe programs the peer's registers. + */ + if (!device_link_add(ctrl->dev, &pdev->dev, + DL_FLAG_AUTOREMOVE_CONSUMER | DL_FLAG_PM_RUNTIME | + DL_FLAG_RPM_ACTIVE)) { + ret = -EINVAL; + goto out_unlock; + } + + ctrl->peer_first_lane = ctrl->num_lanes; + ctrl->num_peer_lanes = peer->num_lanes; + ctrl->peer_dpn_offset = offset * SWRM_DPn_SLOT_STRIDE; + /* publish the cross-refs last so readers never see partial state */ + ctrl->peer_ctrl = peer; + peer->peer_ctrl = ctrl; + + ret = 0; +out_unlock: + device_unlock(&pdev->dev); + put_device(&pdev->dev); + return ret; +} + static int qcom_swrm_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -1628,6 +1786,9 @@ static int qcom_swrm_probe(struct platform_device *pdev) if (!ctrl) return -ENOMEM; + if (!of_property_read_u32(dev->of_node, "num-lanes", &val)) + ctrl->num_lanes = val; + memset(ctrl->page1_cache, 0xff, sizeof(ctrl->page1_cache)); memset(ctrl->page2_cache, 0xff, sizeof(ctrl->page2_cache)); @@ -1689,9 +1850,19 @@ static int qcom_swrm_probe(struct platform_device *pdev) ctrl->bus.compute_params = &qcom_swrm_compute_params; ctrl->bus.clk_stop_timeout = 300; - ret = qcom_swrm_get_port_config(ctrl); - if (ret) - goto err_clk; + if (of_property_match_string(dev->of_node, "qcom,multi-master-mode", + "dependent") < 0) { + ret = qcom_swrm_get_port_config(ctrl); + if (ret) + goto err_clk; + } + + if (of_property_match_string(dev->of_node, "qcom,multi-master-mode", "primary") >= 0) { + ctrl->mm_role = QCOM_SWRM_MM_PRIMARY; + ret = qcom_swrm_multi_master_setup(ctrl); + if (ret) + goto err_clk; + } params = &ctrl->bus.params; params->max_dr_freq = DEFAULT_CLK_FREQ; @@ -1732,7 +1903,7 @@ static int qcom_swrm_probe(struct platform_device *pdev) "swr_wake_irq", ctrl); if (ret) { dev_err(dev, "Failed to request soundwire wake irq\n"); - goto err_init; + goto err_clk; } } @@ -1743,6 +1914,19 @@ static int qcom_swrm_probe(struct platform_device *pdev) ctrl->bus.controller_id = val; } + if (of_property_match_string(dev->of_node, "qcom,multi-master-mode", "dependent") >= 0) { + ctrl->mm_role = QCOM_SWRM_MM_DEPENDENT; + dev_dbg(dev, + "Qualcomm SoundWire multi-master dependent v%x.%x.%x registered (%u lanes)\n", + (ctrl->version >> 24) & 0xff, + (ctrl->version >> 16) & 0xff, + ctrl->version & 0xffff, ctrl->num_lanes); + /* runtime PM is driven by the primary through the device link */ + pm_runtime_set_active(dev); + pm_runtime_enable(dev); + return 0; + } + ret = sdw_bus_master_add(&ctrl->bus, dev, dev->fwnode); if (ret) { dev_err(dev, "Failed to register Soundwire controller (%d)\n", @@ -1751,6 +1935,15 @@ static int qcom_swrm_probe(struct platform_device *pdev) } qcom_swrm_init(ctrl); + + if (ctrl->mm_role == QCOM_SWRM_MM_PRIMARY && ctrl->peer_ctrl) { + ret = qcom_swrm_init(ctrl->peer_ctrl); + if (ret) { + dev_err(dev, "peer init failed: %d\n", ret); + goto err_master_add; + } + } + wait_for_completion_timeout(&ctrl->enumeration, msecs_to_jiffies(TIMEOUT_MS)); ret = qcom_swrm_register_dais(ctrl); @@ -1778,6 +1971,17 @@ static int qcom_swrm_probe(struct platform_device *pdev) err_master_add: sdw_bus_master_delete(&ctrl->bus); err_clk: + /* tear down cross-link + mask peer IRQs before devres frees us */ + if (ctrl->mm_role == QCOM_SWRM_MM_PRIMARY && ctrl->peer_ctrl) { + struct qcom_swrm_ctrl *peer = ctrl->peer_ctrl; + + peer->reg_write(peer, + peer->reg_layout[SWRM_REG_INTERRUPT_CPU_EN], 0); + /* disable peer SWRM; releases shared SWR_CLK */ + peer->reg_write(peer, SWRM_COMP_CFG_ADDR, 0); + peer->peer_ctrl = NULL; + ctrl->peer_ctrl = NULL; + } clk_disable_unprepare(ctrl->hclk); err_init: return ret; @@ -1787,7 +1991,35 @@ static void qcom_swrm_remove(struct platform_device *pdev) { struct qcom_swrm_ctrl *ctrl = dev_get_drvdata(&pdev->dev); + if (ctrl->mm_role == QCOM_SWRM_MM_DEPENDENT) { + pm_runtime_disable(&pdev->dev); + if (!pm_runtime_status_suspended(&pdev->dev)) + clk_disable_unprepare(ctrl->hclk); + return; + } + + /* delete bus before dropping peer_ctrl; in-flight ops deref it */ sdw_bus_master_delete(&ctrl->bus); + + if (ctrl->mm_role == QCOM_SWRM_MM_PRIMARY && ctrl->peer_ctrl) { + struct qcom_swrm_ctrl *peer = ctrl->peer_ctrl; + int ret; + + /* peer hclk may be gated by runtime PM */ + ret = pm_runtime_resume_and_get(peer->dev); + if (ret < 0) { + dev_err(&pdev->dev, "peer resume failed on remove: %d\n", ret); + } else { + peer->reg_write(peer, + peer->reg_layout[SWRM_REG_INTERRUPT_CPU_EN], 0); + /* disable peer SWRM; releases shared SWR_CLK */ + peer->reg_write(peer, SWRM_COMP_CFG_ADDR, 0); + pm_runtime_put(peer->dev); + } + peer->peer_ctrl = NULL; + ctrl->peer_ctrl = NULL; + } + clk_disable_unprepare(ctrl->hclk); } @@ -1796,6 +2028,10 @@ static int __maybe_unused swrm_runtime_resume(struct device *dev) struct qcom_swrm_ctrl *ctrl = dev_get_drvdata(dev); int ret; + /* no bus of its own; the primary restarts the link */ + if (ctrl->mm_role == QCOM_SWRM_MM_DEPENDENT) + return clk_prepare_enable(ctrl->hclk); + if (ctrl->wake_irq > 0) { if (!irqd_irq_disabled(irq_get_irq_data(ctrl->wake_irq))) disable_irq_nosync(ctrl->wake_irq); @@ -1864,6 +2100,12 @@ static int __maybe_unused swrm_runtime_suspend(struct device *dev) struct qcom_swrm_ctrl *ctrl = dev_get_drvdata(dev); int ret; + /* the primary has already stopped the bus clock */ + if (ctrl->mm_role == QCOM_SWRM_MM_DEPENDENT) { + clk_disable_unprepare(ctrl->hclk); + return 0; + } + swrm_wait_for_wr_fifo_done(ctrl); if (!ctrl->clock_stop_not_supported) { /* Mask bus clash interrupt */ From b6d625cb2a4b02ed8e9ce9251826d8534fb54296 Mon Sep 17 00:00:00 2001 From: Srinivas Kandagatla Date: Mon, 23 Nov 2026 17:14:11 +0000 Subject: [PATCH 1623/2102] soundwire: qcom: program MM_SYNC for multi-master The primary and dependent frame generators must lock to a single SWR_CLK for the shared bus to run. Program SWRM_V3_MM_SYNC_CONFIG on both sides at init, and re-apply on resume as the register does not survive a clock stop. Signed-off-by: Srinivas Kandagatla Link: https://patch.msgid.link/20261123171411.444381-4-srinivas.kandagatla@oss.qualcomm.com Signed-off-by: Vinod Koul --- drivers/soundwire/qcom.c | 56 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/drivers/soundwire/qcom.c b/drivers/soundwire/qcom.c index b8d7ced1df9020..258f7f9e54a24f 100644 --- a/drivers/soundwire/qcom.c +++ b/drivers/soundwire/qcom.c @@ -48,6 +48,18 @@ #define SWRM_V3_COMP_PARAMS_RD_FIFO_DEPTH GENMASK(23, 18) #define SWRM_COMP_MASTER_ID 0x104 + +#define SWRM_V3_MM_SYNC_CONFIG 0x108 +#define SWRM_V3_MM_SYNC_CONNECTED_MASTER_MASK GENMASK(15, 0) +#define SWRM_V3_MM_SYNC_IS_DEPENDENT_MASTER BIT(16) +#define SWRM_V3_MM_SYNC_MASK_CONTROL_BITS BIT(17) + +#define SWRM_V3_COMP_FEATURE_CFG 0x10 +#define SWRM_V3_COMP_FEATURE_CFG_BASE 0x00E +#define SWRM_V3_COMP_FEATURE_CFG_FORCE_MODE_EN BIT(9) +#define SWRM_V3_COMP_FEATURE_CFG_CLK_PIN_AVAIL BIT(10) +#define SWRM_V3_COMP_FEATURE_CFG_CLK_STOP_EXEC_ON_CMD_IGNORE BIT(12) + #define SWRM_V1_3_INTERRUPT_STATUS 0x200 #define SWRM_V2_0_INTERRUPT_STATUS 0x5000 #define SWRM_INTERRUPT_STATUS_RMSK GENMASK(16, 0) @@ -949,6 +961,43 @@ static bool swrm_wait_for_frame_gen_enabled(struct qcom_swrm_ctrl *ctrl) return false; } +static void qcom_swrm_program_mm_sync(struct qcom_swrm_ctrl *ctrl) +{ + struct qcom_swrm_ctrl *peer = ctrl->peer_ctrl; + u32 conn_mask; + + if (!peer) + return; + + if (peer->bus.controller_id < 1) { + dev_warn_once(ctrl->dev, + "multi-master peer has no qcom,controller-id; MM_SYNC skipped\n"); + return; + } + + conn_mask = BIT(peer->bus.controller_id - 1) & + SWRM_V3_MM_SYNC_CONNECTED_MASTER_MASK; + + if (ctrl->mm_role == QCOM_SWRM_MM_PRIMARY) { + ctrl->reg_write(ctrl, SWRM_V3_MM_SYNC_CONFIG, conn_mask); + ctrl->reg_write(ctrl, SWRM_V3_COMP_FEATURE_CFG, + SWRM_V3_COMP_FEATURE_CFG_BASE | + SWRM_V3_COMP_FEATURE_CFG_FORCE_MODE_EN | + SWRM_V3_COMP_FEATURE_CFG_CLK_PIN_AVAIL | + SWRM_V3_COMP_FEATURE_CFG_CLK_STOP_EXEC_ON_CMD_IGNORE); + return; + } + + ctrl->reg_write(ctrl, SWRM_V3_MM_SYNC_CONFIG, + SWRM_V3_MM_SYNC_IS_DEPENDENT_MASTER | + SWRM_V3_MM_SYNC_MASK_CONTROL_BITS | conn_mask); + + ctrl->reg_write(ctrl, SWRM_V3_COMP_FEATURE_CFG, + SWRM_V3_COMP_FEATURE_CFG_BASE | + SWRM_V3_COMP_FEATURE_CFG_FORCE_MODE_EN | + SWRM_V3_COMP_FEATURE_CFG_CLK_STOP_EXEC_ON_CMD_IGNORE); +} + static int qcom_swrm_init(struct qcom_swrm_ctrl *ctrl) { u32 val; @@ -977,6 +1026,8 @@ static int qcom_swrm_init(struct qcom_swrm_ctrl *ctrl) u32p_replace_bits(&val, SWRM_DEF_CMD_NO_PINGS, SWRM_MCP_CFG_MAX_NUM_OF_CMD_NO_PINGS_BMSK); ctrl->reg_write(ctrl, SWRM_MCP_CFG_ADDR, val); + qcom_swrm_program_mm_sync(ctrl); + if (ctrl->version == SWRM_VERSION_1_7_0) { ctrl->reg_write(ctrl, SWRM_LINK_MANAGER_EE, ctrl->ee); ctrl->reg_write(ctrl, SWRM_MCP_BUS_CTRL, @@ -2058,6 +2109,11 @@ static int __maybe_unused swrm_runtime_resume(struct device *dev) } else { reset_control_reset(ctrl->audio_cgcr); + qcom_swrm_program_mm_sync(ctrl); + /* dependent was resumed first via the device link */ + if (ctrl->mm_role == QCOM_SWRM_MM_PRIMARY && ctrl->peer_ctrl) + qcom_swrm_program_mm_sync(ctrl->peer_ctrl); + if (ctrl->version == SWRM_VERSION_1_7_0) { ctrl->reg_write(ctrl, SWRM_LINK_MANAGER_EE, ctrl->ee); ctrl->reg_write(ctrl, SWRM_MCP_BUS_CTRL, From 1cba791c9a1b34846d2c89da5220b5bdb8d32539 Mon Sep 17 00:00:00 2001 From: Lee Jones Date: Mon, 23 Nov 2026 07:54:22 +0000 Subject: [PATCH 1624/2102] soundwire: bus: Hold bus_lock when looking up slave devices sdw_get_slave() iterates over bus->slaves and requires bus->bus_lock to be held by the caller. However, sdw_handle_slave_status() and sdw_clear_slave_status() drop bus->bus_lock immediately before calling sdw_get_slave(). If a concurrent slave teardown unlinks the node via list_del_init() and frees the slave while bus->bus_lock is dropped, sdw_get_slave() can spin forever on the self-referential list entry or dereference freed memory. Keep bus->bus_lock held across the sdw_get_slave() lookup in sdw_handle_slave_status() and sdw_clear_slave_status(). Closes: https://sashiko.dev/#/bug/linux-b0e65a93-dfd4-4e3d-a96c-8f13ba0aafd2 Reviewed-by: Charles Keepax Tested-by: Charles Keepax Tested-by: HyeongJun An Signed-off-by: Lee Jones Link: https://patch.msgid.link/20261123075522.405347-2-lee@kernel.org Signed-off-by: Vinod Koul --- drivers/soundwire/bus.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/soundwire/bus.c b/drivers/soundwire/bus.c index aeaae5a57c89d8..15c66effbf4f44 100644 --- a/drivers/soundwire/bus.c +++ b/drivers/soundwire/bus.c @@ -1907,9 +1907,9 @@ int sdw_handle_slave_status(struct sdw_bus *bus, mutex_unlock(&bus->bus_lock); continue; } - mutex_unlock(&bus->bus_lock); slave = sdw_get_slave(bus, i); + mutex_unlock(&bus->bus_lock); if (!slave) continue; @@ -1954,9 +1954,9 @@ int sdw_handle_slave_status(struct sdw_bus *bus, mutex_unlock(&bus->bus_lock); continue; } - mutex_unlock(&bus->bus_lock); slave = sdw_get_slave(bus, i); + mutex_unlock(&bus->bus_lock); if (!slave) continue; @@ -2052,9 +2052,9 @@ void sdw_clear_slave_status(struct sdw_bus *bus, u32 request) mutex_unlock(&bus->bus_lock); continue; } - mutex_unlock(&bus->bus_lock); slave = sdw_get_slave(bus, i); + mutex_unlock(&bus->bus_lock); if (!slave) continue; From 8a2544fb697472139c639b69d6ff1e4d0f9d9492 Mon Sep 17 00:00:00 2001 From: Lee Jones Date: Mon, 23 Nov 2026 07:54:23 +0000 Subject: [PATCH 1625/2102] soundwire: sysfs: Use sysfs_emit_at() in array show callbacks words_show() and the show callbacks generated by sdw_dpn_array_attr() format firmware-supplied property arrays into the sysfs buffer using unbounded sprintf(buf + size, ...) loops. If firmware provides a large array count, sprintf() can write past PAGE_SIZE and corrupt kernel memory. Replace the sprintf(buf + size, ...) calls with bounds-checked sysfs_emit_at() calls. Closes: https://sashiko.dev/#/bug/linux-543ff498-3bed-412d-8972-4855c5aa6008 Reviewed-by: Charles Keepax Tested-by: Charles Keepax Tested-by: HyeongJun An Signed-off-by: Lee Jones Link: https://patch.msgid.link/20261123075522.405347-3-lee@kernel.org Signed-off-by: Vinod Koul --- drivers/soundwire/sysfs_slave.c | 6 +++--- drivers/soundwire/sysfs_slave_dpn.c | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/drivers/soundwire/sysfs_slave.c b/drivers/soundwire/sysfs_slave.c index a2ee064147e05a..35272cfe9fc8b5 100644 --- a/drivers/soundwire/sysfs_slave.c +++ b/drivers/soundwire/sysfs_slave.c @@ -161,9 +161,9 @@ static ssize_t words_show(struct device *dev, int i; for (i = 0; i < slave->prop.dp0_prop->num_words; i++) - size += sprintf(buf + size, "%d ", - slave->prop.dp0_prop->words[i]); - size += sprintf(buf + size, "\n"); + size += sysfs_emit_at(buf, size, "%d ", + slave->prop.dp0_prop->words[i]); + size += sysfs_emit_at(buf, size, "\n"); return size; } diff --git a/drivers/soundwire/sysfs_slave_dpn.c b/drivers/soundwire/sysfs_slave_dpn.c index d2561400da7713..16872ea64b1ffb 100644 --- a/drivers/soundwire/sysfs_slave_dpn.c +++ b/drivers/soundwire/sysfs_slave_dpn.c @@ -134,10 +134,10 @@ static ssize_t field##_dpn_show(struct sdw_slave *slave, \ for_each_set_bit(bit, &mask, 32) { \ if (bit == N) { \ for (j = 0; j < dpn[i].num_##field; j++) \ - size += sprintf(buf + size, \ - format_string, \ - dpn[i].field[j]); \ - size += sprintf(buf + size, "\n"); \ + size += sysfs_emit_at(buf, size, \ + format_string, \ + dpn[i].field[j]); \ + size += sysfs_emit_at(buf, size, "\n"); \ return size; \ } \ i++; \ From 9706b821199eed1189d7ec9b17625ca07abe5248 Mon Sep 17 00:00:00 2001 From: Lee Jones Date: Mon, 23 Nov 2026 07:54:24 +0000 Subject: [PATCH 1626/2102] soundwire: stream: Prevent m_rt_count underflow in sdw_stream_remove_master() stream->m_rt_count is incremented in sdw_stream_add_master() after sdw_master_port_alloc() succeeds. However, sdw_stream_add_slave() can allocate a master runtime without allocating master ports, and sdw_master_port_alloc() can fail after partially populating m_rt->port_list. When sdw_stream_remove_master() subsequently tears down the stream, it unconditionally decrements stream->m_rt_count, underflowing the counter when master ports were never allocated. Free any partially allocated master ports on allocation failure in sdw_master_port_alloc(), and only increment and decrement stream->m_rt_count when master ports are allocated. Closes: https://sashiko.dev/#/bug/linux-bce288e6-c97f-46dd-9fc3-023c33d56f36 Reviewed-by: Charles Keepax Tested-by: HyeongJun An Signed-off-by: Lee Jones Link: https://patch.msgid.link/20261123075522.405347-4-lee@kernel.org Signed-off-by: Vinod Koul --- drivers/soundwire/stream.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/drivers/soundwire/stream.c b/drivers/soundwire/stream.c index 31db368ba24b87..573ca35b0e8b79 100644 --- a/drivers/soundwire/stream.c +++ b/drivers/soundwire/stream.c @@ -1113,8 +1113,10 @@ static int sdw_master_port_alloc(struct sdw_master_runtime *m_rt, /* Iterate for number of ports to perform initialization */ for (i = 0; i < num_ports; i++) { p_rt = sdw_port_alloc(&m_rt->port_list); - if (!p_rt) + if (!p_rt) { + sdw_master_port_free(m_rt); return -ENOMEM; + } } return 0; @@ -2063,7 +2065,8 @@ int sdw_stream_add_master(struct sdw_bus *bus, if (ret) goto alloc_error; - stream->m_rt_count++; + if (sdw_master_port_allocated(m_rt)) + stream->m_rt_count++; } ret = sdw_master_rt_config(m_rt, stream_config); @@ -2110,9 +2113,10 @@ int sdw_stream_remove_master(struct sdw_bus *bus, if (m_rt->bus != bus) continue; + if (sdw_master_port_allocated(m_rt)) + stream->m_rt_count--; sdw_master_port_free(m_rt); sdw_master_rt_free(m_rt, stream); - stream->m_rt_count--; } if (list_empty(&stream->master_list)) From 8a681d3e04d6ddaee1412c53b6a5a9b4e01de69b Mon Sep 17 00:00:00 2001 From: Lee Jones Date: Mon, 23 Nov 2026 07:54:25 +0000 Subject: [PATCH 1627/2102] soundwire: stream: Clean up allocated runtime resources on config failure In sdw_stream_add_master() and sdw_stream_add_slave(), failures during runtime or port configuration jump directly to the unlock label, bypassing alloc_error and leaving newly allocated master/slave runtime and port structures attached to the stream and bus lists. Validate port and stream parameters before mutating runtime or stream state, track whether ports were newly allocated in the current invocation, and route configuration failures through alloc_error so all resources allocated by the failing call are released without leaving pre-existing state modified. Closes: https://sashiko.dev/#/bug/linux-546e137d-6e4d-4f22-99c3-8ccc8beb5350 Signed-off-by: Lee Jones Tested-by: HyeongJun An Link: https://patch.msgid.link/20261123075522.405347-5-lee@kernel.org Signed-off-by: Vinod Koul --- drivers/soundwire/stream.c | 86 +++++++++++++++++++++++++++----------- 1 file changed, 61 insertions(+), 25 deletions(-) diff --git a/drivers/soundwire/stream.c b/drivers/soundwire/stream.c index 573ca35b0e8b79..eccb279ea66246 100644 --- a/drivers/soundwire/stream.c +++ b/drivers/soundwire/stream.c @@ -1026,14 +1026,18 @@ static int sdw_slave_port_alloc(struct sdw_slave *slave, struct sdw_slave_runtime *s_rt, unsigned int num_config) { - struct sdw_port_runtime *p_rt; + struct sdw_port_runtime *p_rt, *_p_rt; int i; /* Iterate for number of ports to perform initialization */ for (i = 0; i < num_config; i++) { p_rt = sdw_port_alloc(&s_rt->port_list); - if (!p_rt) + if (!p_rt) { + list_for_each_entry_safe(p_rt, _p_rt, + &s_rt->port_list, port_node) + sdw_port_free(p_rt); return -ENOMEM; + } } return 0; @@ -1049,16 +1053,16 @@ static int sdw_slave_port_is_valid_range(struct device *dev, int num) return 0; } -static int sdw_slave_port_config(struct sdw_slave *slave, - struct sdw_slave_runtime *s_rt, - const struct sdw_port_config *port_config, - bool is_bpt_stream) +static int sdw_slave_port_config_valid(struct sdw_slave *slave, + struct sdw_slave_runtime *s_rt, + const struct sdw_stream_config *stream_config, + const struct sdw_port_config *port_config) { + bool is_bpt_stream = stream_config->type == SDW_STREAM_BPT; struct sdw_port_runtime *p_rt; int ret; - int i; + int i = 0; - i = 0; list_for_each_entry(p_rt, &s_rt->port_list, port_node) { if (!is_bpt_stream) { ret = sdw_slave_port_is_valid_range(&slave->dev, port_config[i].num); @@ -1069,18 +1073,32 @@ static int sdw_slave_port_config(struct sdw_slave *slave, * A port in the generic valid range may still be unsupported by * the Slave or unavailable for the requested stream direction. */ - if (!sdw_get_slave_dpn_prop(slave, s_rt->direction, + if (!sdw_get_slave_dpn_prop(slave, stream_config->direction, port_config[i].num)) { dev_err(&slave->dev, "port %u not supported for %s\n", port_config[i].num, - s_rt->direction == SDW_DATA_DIR_TX ? "TX" : "RX"); + stream_config->direction == SDW_DATA_DIR_TX ? + "TX" : "RX"); return -EINVAL; } } else if (port_config[i].num) { return -EINVAL; } + i++; + } + return 0; +} + +static int sdw_slave_port_config(struct sdw_slave_runtime *s_rt, + const struct sdw_port_config *port_config) +{ + struct sdw_port_runtime *p_rt; + int ret; + int i = 0; + + list_for_each_entry(p_rt, &s_rt->port_list, port_node) { ret = sdw_port_config(p_rt, port_config, i); if (ret < 0) return ret; @@ -2020,6 +2038,7 @@ int sdw_stream_add_master(struct sdw_bus *bus, struct sdw_stream_runtime *stream) { struct sdw_master_runtime *m_rt; + bool alloc_master_port = false; bool alloc_master_rt = false; int ret; @@ -2065,19 +2084,23 @@ int sdw_stream_add_master(struct sdw_bus *bus, if (ret) goto alloc_error; - if (sdw_master_port_allocated(m_rt)) + if (sdw_master_port_allocated(m_rt)) { + alloc_master_port = true; stream->m_rt_count++; + } } - ret = sdw_master_rt_config(m_rt, stream_config); - if (ret < 0) - goto unlock; - ret = sdw_config_stream(bus->dev, stream, stream_config, false); if (ret) - goto unlock; + goto alloc_error; + + ret = sdw_master_rt_config(m_rt, stream_config); + if (ret < 0) + goto alloc_error; ret = sdw_master_port_config(m_rt, port_config); + if (ret) + goto alloc_error; goto unlock; @@ -2085,6 +2108,10 @@ int sdw_stream_add_master(struct sdw_bus *bus, /* * we only cleanup what was allocated in this routine */ + if (alloc_master_port) { + sdw_master_port_free(m_rt); + stream->m_rt_count--; + } if (alloc_master_rt) sdw_master_rt_free(m_rt, stream); unlock: @@ -2150,6 +2177,7 @@ int sdw_stream_add_slave(struct sdw_slave *slave, struct sdw_slave_runtime *s_rt; struct sdw_master_runtime *m_rt; bool alloc_master_rt = false; + bool alloc_slave_port = false; bool alloc_slave_rt = false; int ret; @@ -2200,24 +2228,30 @@ int sdw_stream_add_slave(struct sdw_slave *slave, ret = sdw_slave_port_alloc(slave, s_rt, num_ports); if (ret) goto alloc_error; + + alloc_slave_port = true; } - ret = sdw_master_rt_config(m_rt, stream_config); + ret = sdw_slave_port_config_valid(slave, s_rt, stream_config, + port_config); if (ret) - goto unlock; + goto alloc_error; - ret = sdw_slave_rt_config(s_rt, stream_config); + ret = sdw_config_stream(&slave->dev, stream, stream_config, true); if (ret) - goto unlock; + goto alloc_error; - ret = sdw_config_stream(&slave->dev, stream, stream_config, true); + ret = sdw_master_rt_config(m_rt, stream_config); if (ret) - goto unlock; + goto alloc_error; - ret = sdw_slave_port_config(slave, s_rt, port_config, - stream->type == SDW_STREAM_BPT); + ret = sdw_slave_rt_config(s_rt, stream_config); if (ret) - goto unlock; + goto alloc_error; + + ret = sdw_slave_port_config(s_rt, port_config); + if (ret) + goto alloc_error; /* * Change stream state to CONFIGURED on first Slave add. @@ -2234,6 +2268,8 @@ int sdw_stream_add_slave(struct sdw_slave *slave, * is intentional, the 'master_rt_free' will call sdw_slave_rt_free() * internally. */ + if (alloc_slave_port) + sdw_slave_port_free(slave, stream); if (alloc_master_rt) sdw_master_rt_free(m_rt, stream); else if (alloc_slave_rt) From b9a8ed1254978b14ab3cd3f7e5d39a0c8fe55173 Mon Sep 17 00:00:00 2001 From: Lee Jones Date: Mon, 23 Nov 2026 07:54:26 +0000 Subject: [PATCH 1628/2102] soundwire: intel_ace2x: Protect bus.bpt_stream with bus_lock intel_ace2x_bpt_open_stream() checks and assigns cdns->bus.bpt_stream without holding cdns->bus.bus_lock. Concurrent BPT open requests can both observe a NULL cdns->bus.bpt_stream pointer, allocate separate streams, and overwrite cdns->bus.bpt_stream, leaking the first stream. In addition, failures after sdw_slave_bpt_stream_add() jump past sdw_stream_remove_master(), leaving the master runtime allocated by sdw_stream_add_slave() on the bus list. Hold cdns->bus.bus_lock when checking, assigning, and clearing cdns->bus.bpt_stream, and remove both slave and master stream runtimes on open failure. Closes: https://sashiko.dev/#/bug/linux-88535ed9-b7e9-4ede-93c7-59950c524c0b Signed-off-by: Lee Jones Fixes: 4c1ce9f37d8a ("soundwire: intel_ace2x: add BPT send_async/wait callbacks") Link: https://patch.msgid.link/20261123075522.405347-6-lee@kernel.org Signed-off-by: Vinod Koul --- drivers/soundwire/intel_ace2x.c | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/drivers/soundwire/intel_ace2x.c b/drivers/soundwire/intel_ace2x.c index 642b33ab552606..c964dd4a7c2263 100644 --- a/drivers/soundwire/intel_ace2x.c +++ b/drivers/soundwire/intel_ace2x.c @@ -83,16 +83,21 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * int len; int i; + mutex_lock(&cdns->bus.bus_lock); if (cdns->bus.bpt_stream) { + mutex_unlock(&cdns->bus.bus_lock); dev_err(cdns->dev, "%s: BPT stream already exists\n", __func__); return -EAGAIN; } stream = sdw_alloc_stream("BPT", SDW_STREAM_BPT); - if (!stream) + if (!stream) { + mutex_unlock(&cdns->bus.bus_lock); return -ENOMEM; + } cdns->bus.bpt_stream = stream; + mutex_unlock(&cdns->bus.bus_lock); ret = sdw_slave_bpt_stream_add(slave, stream); if (ret < 0) @@ -105,7 +110,7 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * if (!pdi0) { dev_err(cdns->dev, "%s: sdw_cdns_alloc_pdi0 failed\n", __func__); ret = -EINVAL; - goto remove_slave; + goto remove_master; } sdw_cdns_config_stream(cdns, 1, dir, pdi0); @@ -117,7 +122,7 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * if (!pdi1) { dev_err(cdns->dev, "%s: sdw_cdns_alloc_pdi1 failed\n", __func__); ret = -EINVAL; - goto remove_slave; + goto remove_master; } sdw_cdns_config_stream(cdns, 1, dir, pdi1); @@ -136,7 +141,7 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * pconfig = kzalloc_objs(*pconfig, 2); if (!pconfig) { ret = -ENOMEM; - goto remove_slave; + goto remove_master; } for (i = 0; i < 2 /* num_pdi */; i++) { @@ -149,7 +154,7 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * if (ret < 0) { dev_err(cdns->dev, "add master to stream failed:%d\n", ret); - goto remove_slave; + goto remove_master; } ret = sdw_prepare_stream(cdns->bus.bpt_stream); @@ -293,15 +298,16 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * dev_err(cdns->dev, "%s: remove master failed: %d\n", __func__, ret1); -remove_slave: ret1 = sdw_stream_remove_slave(slave, cdns->bus.bpt_stream); if (ret1 < 0) dev_err(cdns->dev, "%s: remove slave failed: %d\n", __func__, ret1); release_stream: + mutex_lock(&cdns->bus.bus_lock); sdw_release_stream(cdns->bus.bpt_stream); cdns->bus.bpt_stream = NULL; + mutex_unlock(&cdns->bus.bus_lock); return ret; } @@ -335,8 +341,10 @@ static void intel_ace2x_bpt_close_stream(struct sdw_intel *sdw, struct sdw_slave dev_err(cdns->dev, "%s: remove slave failed: %d\n", __func__, ret); + mutex_lock(&cdns->bus.bus_lock); sdw_release_stream(cdns->bus.bpt_stream); cdns->bus.bpt_stream = NULL; + mutex_unlock(&cdns->bus.bus_lock); } #define INTEL_BPT_MSG_BYTE_MIN 16 From d9ea256ee889f3db9f0bd07ce5d114ce92e31b4f Mon Sep 17 00:00:00 2001 From: Lee Jones Date: Mon, 23 Nov 2026 07:54:27 +0000 Subject: [PATCH 1629/2102] soundwire: qcom: Prevent pconfig buffer overflow in qcom_swrm_stream_alloc_ports() qcom_swrm_stream_alloc_ports() allocates the pconfig array with ctrl->nports elements, but only checks that the assigned port number pn is below maxport. When multiple slave ports map to the same master port via m_port_map or the stream requests more slave ports than ctrl->nports, nports increments past ctrl->nports and writes out of bounds of pconfig. Verify that nports is less than maxport before writing to pconfig[nports], and clear only the port_mask bits newly allocated during the loop before returning -EBUSY. Closes: https://sashiko.dev/#/bug/linux-543ea0c0-a6e5-4b03-a041-ea0a760802c1 Signed-off-by: Lee Jones Link: https://patch.msgid.link/20261123075522.405347-7-lee@kernel.org Signed-off-by: Vinod Koul --- drivers/soundwire/qcom.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/drivers/soundwire/qcom.c b/drivers/soundwire/qcom.c index 258f7f9e54a24f..65add9a74ffd93 100644 --- a/drivers/soundwire/qcom.c +++ b/drivers/soundwire/qcom.c @@ -1419,7 +1419,7 @@ static int qcom_swrm_stream_alloc_ports(struct qcom_swrm_ctrl *ctrl, struct sdw_slave_runtime *s_rt; struct sdw_port_runtime *p_rt; struct sdw_slave *slave; - unsigned long *port_mask; + unsigned long *port_mask, allocated = 0; int maxport, pn, nports = 0; unsigned int m_port; struct sdw_port_config *pconfig __free(kfree) = kzalloc_objs(*pconfig, @@ -1463,11 +1463,13 @@ static int qcom_swrm_stream_alloc_ports(struct qcom_swrm_ctrl *ctrl, else pn = find_first_zero_bit(port_mask, maxport); - if (pn >= maxport) { + if (pn >= maxport || nports >= maxport) { dev_err(ctrl->dev, "All ports busy\n"); + *port_mask &= ~allocated; return -EBUSY; } - set_bit(pn, port_mask); + if (!test_and_set_bit(pn, port_mask)) + __set_bit(pn, &allocated); pconfig[nports].num = pn; pconfig[nports].ch_mask = p_rt->ch_mask; nports++; From 9f2264b0730ab53993fa67460597824edae708bf Mon Sep 17 00:00:00 2001 From: Jiayuan Chen Date: Fri, 20 Nov 2026 12:04:35 +0800 Subject: [PATCH 1630/2102] tcp: fix shift-out-of-bounds in SYN-ACK retransmit timers req->num_timeout counts the SYN-ACK timeouts of a request and is used as a shift amount: /* tcp_reqsk_timeout() */ u64 timeout = (u64)req->timeout << req->num_timeout; /* tcp_fastopen_synack_timer() */ req->timeout << req->num_timeout Once it climbs past the width of the shifted type the shift is UB. Seen with tcp_synack_retries=255 and a peer that never completes the handshake: UBSAN: shift-out-of-bounds in ./include/net/tcp.h:917:34 shift exponent 64 is too large for 64-bit type 'long long unsigned int' Call Trace: dump_stack_lvl+0xc1/0xf0 dump_stack+0x10/0x20 __ubsan_handle_shift_out_of_bounds+0x1d1/0x390 reqsk_timer_handler.cold+0x1c/0x5d call_timer_fn+0x17d/0x510 __run_timers+0x662/0xab0 run_timer_softirq+0xdf/0x260 handle_softirqs+0x204/0x9b0 __irq_exit_rcu+0x13c/0x220 irq_exit_rcu+0xe/0x20 sysvec_apic_timer_interrupt+0x40/0xd0 asm_sysvec_apic_timer_interrupt+0x1b/0x20 The sysctl is not needed: TCP_SYNCNT=127 on the listener gets there too, and the TFO shift is 32-bit, so it is UB from num_timeout 32. The value can also wrap to 0 before the shift count is out of range, which arms a zero-length timer. E.g. with HZ=1000 and req->timeout == 1000, (u64)1000 << 61 and (u32)1000 << 29 are both 0. num_timeout is a 7-bit field. Once a retransmit limit is above 127 the "num_timeout >= limit" check can never be true, the request is never expired by that limit, and after the field wraps to 0 reqsk_timer_handler() decrements queue->young again on the next expiry. - split tcp_reqsk_timeout() into tcp_reqsk_timeout_sk() and cap the shift at 32 there, same as inet_csk_rto_backoff() in the next patch. req->timeout << 32 is already above tcp_rto_max(), so the clamped result does not change. - cap max_retries / max_syn_ack_retries at MAX_TCP_SYNCNT (127), the largest value the field can hold. The sysctl range is left alone: narrowing it would make setups that write 128..255 fail with -EINVAL, and the caps are needed anyway for TCP_DEFER_ACCEPT and the TFO "+ 1". 128..255 now act as 127. - cap the TCP_DEFER_ACCEPT conversion in secs_to_retrans() at 127 too; larger values kept an acked request from ever expiring. getsockopt() now reports at most 14527 instead of 29887 seconds. - route the TFO path through the same helper. - document that tcp_synack_retries values above 127 act as 127. Found by checking sysctl ranges against their users. Reproduced in a VM with UBSAN: tcp_synack_retries=255 and tcp_rto_max_ms=1000 on the server, and an iptables rule dropping the final ACK of the handshake. The splat shows up after about 64 seconds, and is gone with this patch. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Fixes: e6c022a4fa2d ("tcp: better retrans tracking for defer-accept") Cc: stable@vger.kernel.org Signed-off-by: Jiayuan Chen Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261120040447.195446-1-jiayuan.chen@linux.dev Signed-off-by: Paolo Abeni --- Documentation/networking/ip-sysctl.rst | 2 +- include/net/tcp.h | 14 ++++++++++---- net/ipv4/inet_connection_sock.c | 1 + net/ipv4/tcp.c | 2 +- net/ipv4/tcp_timer.c | 3 ++- 5 files changed, 15 insertions(+), 7 deletions(-) diff --git a/Documentation/networking/ip-sysctl.rst b/Documentation/networking/ip-sysctl.rst index d3523c9064a22b..0c48c29fbeeb70 100644 --- a/Documentation/networking/ip-sysctl.rst +++ b/Documentation/networking/ip-sysctl.rst @@ -956,7 +956,7 @@ tcp_stdurg - BOOLEAN tcp_synack_retries - INTEGER Number of times SYNACKs for a passive TCP connection attempt will - be retransmitted. Should not be higher than 255. Default value + be retransmitted. Values above 127 are treated as 127. Default value is 5, which corresponds to 31seconds till the last retransmission with the current initial RTO of 1second. With this the final timeout for a passive TCP connection will happen after 63seconds. diff --git a/include/net/tcp.h b/include/net/tcp.h index 5a638727d42091..d31a1f77d767b9 100644 --- a/include/net/tcp.h +++ b/include/net/tcp.h @@ -922,12 +922,18 @@ static inline u32 __tcp_set_rto(const struct tcp_sock *tp) return max(rto, 1U); } -static inline unsigned long tcp_reqsk_timeout(struct request_sock *req) +static inline unsigned long tcp_reqsk_timeout_sk(const struct sock *sk, + const struct request_sock *req) { - u64 timeout = (u64)req->timeout << req->num_timeout; + /* timeout << 32 is already above tcp_rto_max(). */ + u64 timeout = (u64)req->timeout << min_t(u8, req->num_timeout, 32); + + return (unsigned long)min_t(u64, timeout, tcp_rto_max(sk)); +} - return (unsigned long)min_t(u64, timeout, - tcp_rto_max(req->rsk_listener)); +static inline unsigned long tcp_reqsk_timeout(struct request_sock *req) +{ + return tcp_reqsk_timeout_sk(req->rsk_listener, req); } u32 tcp_delack_max(const struct sock *sk); diff --git a/net/ipv4/inet_connection_sock.c b/net/ipv4/inet_connection_sock.c index 9a3b05edb62bfc..aa0678a1823d9c 100644 --- a/net/ipv4/inet_connection_sock.c +++ b/net/ipv4/inet_connection_sock.c @@ -1082,6 +1082,7 @@ static void reqsk_timer_handler(struct timer_list *t) net = sock_net(sk_listener); max_syn_ack_retries = READ_ONCE(icsk->icsk_syn_retries) ? : READ_ONCE(net->ipv4.sysctl_tcp_synack_retries); + max_syn_ack_retries = min_t(int, max_syn_ack_retries, MAX_TCP_SYNCNT); /* Normally all the openreqs are young and become mature * (i.e. converted to established socket) for first timeout. * If synack was not acknowledged for 1 second, it means diff --git a/net/ipv4/tcp.c b/net/ipv4/tcp.c index 832b25ddd3c2ea..418842a2dfd98c 100644 --- a/net/ipv4/tcp.c +++ b/net/ipv4/tcp.c @@ -358,7 +358,7 @@ static u8 secs_to_retrans(int seconds, int timeout, int rto_max) int period = timeout; res = 1; - while (seconds > period && res < 255) { + while (seconds > period && res < MAX_TCP_SYNCNT) { res++; timeout <<= 1; if (timeout > rto_max) diff --git a/net/ipv4/tcp_timer.c b/net/ipv4/tcp_timer.c index 00debcba122b14..814fadb30749b0 100644 --- a/net/ipv4/tcp_timer.c +++ b/net/ipv4/tcp_timer.c @@ -468,6 +468,7 @@ static void tcp_fastopen_synack_timer(struct sock *sk, struct request_sock *req) */ max_retries = READ_ONCE(icsk->icsk_syn_retries) ? : READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_synack_retries) + 1; + max_retries = min_t(int, max_retries, MAX_TCP_SYNCNT); if (req->num_timeout >= max_retries) { tcp_write_err(sk); @@ -489,7 +490,7 @@ static void tcp_fastopen_synack_timer(struct sock *sk, struct request_sock *req) if (!tp->retrans_stamp) tp->retrans_stamp = tcp_time_stamp_ts(tp); tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, - req->timeout << req->num_timeout, false); + tcp_reqsk_timeout_sk(sk, req), false); } static bool tcp_rtx_probe0_timed_out(const struct sock *sk, From c5de2ce2fccdb7d3b48946179634eaa3d7ce2e7e Mon Sep 17 00:00:00 2001 From: Jiayuan Chen Date: Fri, 20 Nov 2026 12:04:36 +0800 Subject: [PATCH 1631/2102] tcp: fix shift-out-of-bounds in inet_csk_rto_backoff() icsk_backoff is used as a shift amount in inet_csk_rto_backoff(): u64 when = (u64)icsk->icsk_rto << icsk->icsk_backoff; It can go past 63 on the paths of both callers: - RTO: tcp_retransmit_timer() increments it on every backed-off RTO with no cap of its own, then an ICMP unreachable goes through tcp_ld_RTO_revert(). - zero window probe: tcp_send_probe0() increments it up to tcp_retries2, and tcp_probe_timer() calls the helper in its orphan check. commit 6d4634d1b091 ("net: Limit logical shift left of TCP probe0 timeout") clamped tcp_probe0_when() but not this one. Seen on the RTO path with tcp_retries2=255 and a silent peer: UBSAN: shift-out-of-bounds in ./include/net/inet_connection_sock.h:258:40 shift exponent 73 is too large for 64-bit type 'long long unsigned int' Call Trace: dump_stack_lvl+0xc1/0xf0 dump_stack+0x10/0x20 __ubsan_handle_shift_out_of_bounds+0x1d1/0x390 tcp_ld_RTO_revert.cold+0x16/0x92 tcp_v4_err+0xdb3/0x13e0 icmp_socket_deliver+0x1a7/0x390 icmp_unreach+0x2dd/0xe50 icmp_rcv+0x93e/0xe30 ip_protocol_deliver_rcu+0x36b/0x3e0 ip_local_deliver_finish+0x37d/0x620 ip_local_deliver+0x165/0x1d0 ip_rcv+0x284/0x320 __netif_receive_skb_one_core+0x16b/0x1c0 __netif_receive_skb+0x21/0x150 process_backlog+0x37e/0x1200 __napi_poll.constprop.0+0xa5/0x5e0 net_rx_action+0x4c0/0xf70 handle_softirqs+0x204/0x9b0 __irq_exit_rcu+0x13c/0x220 irq_exit_rcu+0xe/0x20 sysvec_apic_timer_interrupt+0x92/0xd0 tcp_retries2 does not need to be changed for the RTO path: with TCP_USER_TIMEOUT and TCP_RTO_MAX_MS set on the socket, retransmits_timed_out() only looks at the elapsed time. The zero window probe path gives the same splat from tcp_probe_timer(). On x86-64 the shift count is masked, and the u64 can already be 0 before that (e.g. icsk_rto == 200 and icsk_backoff == 61). An orphan that should be dead can then be seen as alive in tcp_probe_timer(), and tcp_ld_RTO_revert() can end up with a smaller RTO than intended. Cap the shift at 32: any non-zero icsk_rto << 32 exceeds TCP_RTO_MAX, so the min_t() result is what the unbounded math would give. The ilog2(TCP_RTO_MAX / TCP_RTO_MIN) + 1 bound of tcp_probe0_when() does not fit here, as icsk_rto has no TCP_RTO_MIN floor the way tcp_probe0_base() has. Found by checking sysctl ranges against their users. Reproduced the RTO path in a VM with UBSAN: a - r - b netns, tcp_retries2=255 and tcp_rto_max_ms=1000 on a, blackhole route on r for 75s, then switch it to unreachable. With this patch the splat is gone on both paths. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Reported-by: Kyuwon Cho Closes: https://lore.kernel.org/netdev/179499954853.1440581.6627074959099619480@gmail.com/ Suggested-by: Eric Dumazet Link: https://lore.kernel.org/netdev/CANn89i+=QRibXsm6tw-eVwhB3wjOtgF-MtVu0G--K5=oWP97+A@mail.gmail.com/ Cc: stable@vger.kernel.org Signed-off-by: Jiayuan Chen Tested-by: Kyuwon Cho Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261120040447.195446-2-jiayuan.chen@linux.dev Signed-off-by: Paolo Abeni --- include/net/inet_connection_sock.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/include/net/inet_connection_sock.h b/include/net/inet_connection_sock.h index 903499581db7e2..562e12033a5d3f 100644 --- a/include/net/inet_connection_sock.h +++ b/include/net/inet_connection_sock.h @@ -255,9 +255,10 @@ static inline unsigned long inet_csk_rto_backoff(const struct inet_connection_sock *icsk, unsigned long max_when) { - u64 when = (u64)icsk->icsk_rto << icsk->icsk_backoff; + u8 backoff = min_t(u8, 32U, icsk->icsk_backoff); + u64 when = (u64)icsk->icsk_rto << backoff; - return (unsigned long)min_t(u64, when, max_when); + return (unsigned long)min_t(u64, when, max_when); } struct sock *inet_csk_accept(struct sock *sk, struct proto_accept_arg *arg); From 6863183e8b65e833f8140e20d526282a725e040e Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 2 Nov 2026 13:59:20 +0100 Subject: [PATCH 1632/2102] x86/efi: Disregard the INITRD and MEMATTR config tables after kexec When the EFI stub loads the initrd itself, it describes its location and size to the core kernel via a LINUX_EFI_INITRD_MEDIA_GUID configuration table, which is allocated from EFI loader data, just like the initrd. On x86, the stub passes the same information via boot_params as well, which takes precedence, but the core kernel will fall back to the INITRD config table if boot_params does not describe an initrd. The EFI configuration table array is passed on to kexec'd kernels as-is, and so a kexec'd kernel that is booted without an initrd will pick up the INITRD config table that was installed during the original boot, and use the initrd it describes, which no longer exists at that point. Commit 6e62d1c6f2c7 ("efi: Wipe INITRD config table from memory after consumption") mitigated this by wiping the base and size fields of the table once it has been consumed. However, the memory holding the table is released to the page allocator as well, and so it may have been reused by the time the kexec occurs, in which case the kexec'd kernel will interpret whatever happens to be stored there as the base and size of the initrd, e.g., [ 0.000000] efi: ... INITRD=0x7c41cc18 ... [ 0.000000] RAMDISK: [mem 0x9090909090909090-0xd1e7d1e68aaeafff] [ 0.000000] Kernel panic - not syncing: Cannot find place for new RAMDISK of size 4708303772963442675 Crash kernels will find the stale table as well, and wipe it again, i.e., write to the memory of the crashed kernel that they are supposed to capture. Both kexec_file_load() and kexec-tools pass a SETUP_EFI setup_data entry to the next kernel when EFI is enabled, which the x86 EFI code already relies on to detect that it was booted via kexec. Such kernels are entered directly, bypassing the EFI stub, and so any INITRD config table they encounter is necessarily stale. So wire up efi_config_table_is_usable() for x86, and use it to disregard the INITRD config table when a SETUP_EFI setup_data entry is present. While at it, use the same mechanism to disregard the Memory Attributes table after kexec, which is currently achieved by overwriting its address in the firmware's config table array with EFI_INVALID_TABLE_ADDR in efi_reuse_config(). This only happens on 64-bit firmware, and only if the SETUP_EFI entry carries the address of an SMBIOS table, which kexec-tools does not provide on systems that only expose an SMBIOS3 entry point. In that case, the kexec'd kernel will parse the table, which may be stale as well, given that EDK2 based firmware allocates it from EFI boot services data, which is released to the page allocator after boot too, e.g., [ 0.000000] efi: memattr: Unexpected EFI Memory Attributes table version -1958647317 Reviewed-by: Ilias Apalodimas Tested-by: Jasmeet (Jazz) Bhatia Fixes: f4dc7fffa987 ("efi: libstub: unify initrd loading between architectures") Signed-off-by: Ard Biesheuvel --- arch/x86/platform/efi/efi.c | 26 ++++++++++++++++++++++++++ arch/x86/platform/efi/quirks.c | 4 ---- include/linux/efi.h | 3 +++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/arch/x86/platform/efi/efi.c b/arch/x86/platform/efi/efi.c index 5eb96c17883e86..c2817c7415ce68 100644 --- a/arch/x86/platform/efi/efi.c +++ b/arch/x86/platform/efi/efi.c @@ -432,6 +432,32 @@ static int __init efi_systab_init(unsigned long phys) return 0; } +/* + * kexec passes the firmware's config table array on to the next kernel as-is, + * but some of the tables it describes must be disregarded when booting via + * kexec, which is indicated by the presence of a SETUP_EFI setup_data entry: + * + * - The INITRD table is installed by the EFI stub to describe the initrd that + * it loaded. Both the table and the initrd are allocated from EFI loader + * data, which is released to the page allocator once the kernel is up and + * running, and so the table is stale by the time kexec boots the next kernel. + * + * - The Memory Attributes table may reside in EFI boot services data, which is + * released to the page allocator as well. Even if it is still intact, the + * sanity check in efi_memattr_init() may fail spuriously, given that only + * the runtime regions of the EFI memory map are passed on via kexec. Applying + * the permissions it describes is not critical, so just ignore it. + */ +bool __init x86_efi_config_table_is_usable(const efi_guid_t *guid, + unsigned long table) +{ + if (!efi_setup) + return true; + + return efi_guidcmp(*guid, LINUX_EFI_INITRD_MEDIA_GUID) && + efi_guidcmp(*guid, EFI_MEMORY_ATTRIBUTES_TABLE_GUID); +} + static int __init efi_config_init(const efi_config_table_type_t *arch_tables) { void *config_tables; diff --git a/arch/x86/platform/efi/quirks.c b/arch/x86/platform/efi/quirks.c index 02c56a02eb9bc4..d6d34dfa19e60b 100644 --- a/arch/x86/platform/efi/quirks.c +++ b/arch/x86/platform/efi/quirks.c @@ -611,10 +611,6 @@ int __init efi_reuse_config(u64 tables, int nr_tables) if (!efi_guidcmp(guid, SMBIOS_TABLE_GUID)) ((efi_config_table_64_t *)p)->table = data->smbios; - /* Do not bother to play with mem attr table across kexec */ - if (!efi_guidcmp(guid, EFI_MEMORY_ATTRIBUTES_TABLE_GUID)) - ((efi_config_table_64_t *)p)->table = EFI_INVALID_TABLE_ADDR; - p += sz; } early_memunmap(tablep, nr_tables * sz); diff --git a/include/linux/efi.h b/include/linux/efi.h index cc1df1577d5fb8..1bdb4639acef29 100644 --- a/include/linux/efi.h +++ b/include/linux/efi.h @@ -1355,10 +1355,13 @@ struct linux_efi_initrd { #define EFI_SECRET_TABLE_HEADER_GUID EFI_GUID(0x1e74f542, 0x71dd, 0x4d66, 0x96, 0x3e, 0xef, 0x42, 0x87, 0xff, 0x17, 0x3b) bool xen_efi_config_table_is_usable(const efi_guid_t *guid, unsigned long table); +bool x86_efi_config_table_is_usable(const efi_guid_t *guid, unsigned long table); static __always_inline bool efi_config_table_is_usable(const efi_guid_t *guid, unsigned long table) { + if (IS_ENABLED(CONFIG_X86) && !x86_efi_config_table_is_usable(guid, table)) + return false; if (!IS_ENABLED(CONFIG_XEN_EFI)) return true; return xen_efi_config_table_is_usable(guid, table); From cc919b0db7d322c65067801869bc6354669726dc Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Fri, 20 Nov 2026 16:35:10 +0100 Subject: [PATCH 1633/2102] efi/tpm: Allocate the event log from EFI loader data again The EFI stub currently allocates the TPM event log as EFI_ACPI_RECLAIM_MEMORY. On x86, this becomes an ACPI data entry in the E820 map. On a Framework Laptop 16 (AMD Ryzen AI 300 Series), the EFI allocator can place this allocation at different physical addresses across boots. Since x86 hibernation validates architecture-specific data from the firmware E820 map, this causes an otherwise valid hibernation image to be rejected on resume with the following error: Hibernate inconsistent memory map detected! PM: hibernation: Image mismatch: architecture specific data Allocating the event log as EFI_LOADER_DATA avoids changing the E820 map, but doing that alone would regress the kexec corruption issue fixed by commit 77d48d39e991 ("efistub/tpm: Use ACPI reclaim memory for event log to avoid corruption"): the E820 map that kexec passes on to the next kernel describes EFI loader data as ordinary RAM, and so the event log may get clobbered before the next kernel gets around to reserving it. So use the x86 implementation of efi_config_table_is_usable() to disregard the TPM event log table after kexec, just like the INITRD table, and go back to allocating it as EFI_LOADER_DATA. This is simpler than preserving the event log across kexec, e.g., by installing the memreserve table on x86 and using efi_mem_reserve_persistent(), and the utility of the event log after kexec is questionable to begin with. This also protects kexec'd kernels from a clobbered event log if the previous kernel predates the change above, and allocated the table from EFI loader data as well. The kexec issue was specific to x86, so other architectures can use EFI loader data as before. Tested-by: Jasmeet (Jazz) Bhatia Fixes: 77d48d39e991 ("efistub/tpm: Use ACPI reclaim memory for event log to avoid corruption") Signed-off-by: Ard Biesheuvel --- arch/x86/platform/efi/efi.c | 8 ++++++++ drivers/firmware/efi/libstub/tpm.c | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/arch/x86/platform/efi/efi.c b/arch/x86/platform/efi/efi.c index c2817c7415ce68..f569d9a7c5ab66 100644 --- a/arch/x86/platform/efi/efi.c +++ b/arch/x86/platform/efi/efi.c @@ -442,6 +442,13 @@ static int __init efi_systab_init(unsigned long phys) * data, which is released to the page allocator once the kernel is up and * running, and so the table is stale by the time kexec boots the next kernel. * + * - The TPM event log table is installed by the EFI stub too. It is allocated + * from EFI loader data rather than ACPI reclaim memory, as the latter would + * create an E820 entry that may move around between boots, which breaks + * resume from hibernation. It is reserved by the kernel, but the E820 map + * that kexec passes on describes it as ordinary RAM, and so it may get + * clobbered before the next kernel gets around to reserving it. + * * - The Memory Attributes table may reside in EFI boot services data, which is * released to the page allocator as well. Even if it is still intact, the * sanity check in efi_memattr_init() may fail spuriously, given that only @@ -455,6 +462,7 @@ bool __init x86_efi_config_table_is_usable(const efi_guid_t *guid, return true; return efi_guidcmp(*guid, LINUX_EFI_INITRD_MEDIA_GUID) && + efi_guidcmp(*guid, LINUX_EFI_TPM_EVENT_LOG_GUID) && efi_guidcmp(*guid, EFI_MEMORY_ATTRIBUTES_TABLE_GUID); } diff --git a/drivers/firmware/efi/libstub/tpm.c b/drivers/firmware/efi/libstub/tpm.c index 73f0011147323d..b8183bfdbaa3d2 100644 --- a/drivers/firmware/efi/libstub/tpm.c +++ b/drivers/firmware/efi/libstub/tpm.c @@ -96,7 +96,7 @@ static void efi_retrieve_tcg2_eventlog(int version, efi_physical_addr_t log_loca } /* Allocate space for the logs and copy them. */ - status = efi_bs_call(allocate_pool, EFI_ACPI_RECLAIM_MEMORY, + status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, sizeof(*log_tbl) + log_size, (void **)&log_tbl); if (status != EFI_SUCCESS) { From aa0d120a62da911101a4c2e266bd5adc1368064c Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 10 Nov 2026 12:58:21 +0100 Subject: [PATCH 1634/2102] efi/zboot: arm64: Add missing barrier after cache maintenance Prevent the I-cache from fetching stale data by issuing a barrier after the data cache maintenance completes but before performing the I-cache maintenance. Cc: Signed-off-by: Ard Biesheuvel --- drivers/firmware/efi/libstub/arm64.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/firmware/efi/libstub/arm64.c b/drivers/firmware/efi/libstub/arm64.c index e57cd3de0a00f4..d35c6dd7660108 100644 --- a/drivers/firmware/efi/libstub/arm64.c +++ b/drivers/firmware/efi/libstub/arm64.c @@ -109,6 +109,7 @@ void efi_cache_sync_image(unsigned long image_base, } while (size >= lsize); } + dsb(ish); asm("ic ialluis"); dsb(ish); isb(); From 7fdccfe74edc8fed4d11bd9d8e23d6442df393a4 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Fri, 20 Nov 2026 15:21:24 +0100 Subject: [PATCH 1635/2102] efi: Don't destroy runtime workqueue on efisubsys_init() failure Commit 98086df8b70c ("efi: add missed destroy_workqueue when efisubsys_init fails") added a destroy_workqueue(efi_rts_wq) call to the error cleanup path of efisubsys_init() without clearing EFI_RUNTIME_SERVICES in efi.flags, leaving __efi_queue_work() passing a freed workqueue pointer to queue_work() on any subsequent runtime service call (for instance via the rtc-efi device registered right before efi_kobj is created). Furthermore, since commit 13c6da02e767 ("efi: Allocate runtime workqueue before ACPI init"), efi_rts_wq is no longer allocated by efisubsys_init() at all, as efipostcore_init() allocates it earlier for consumers such as ACPI PRM that do not depend on /sys/firmware/efi. Drop the bogus destroy_workqueue() cleanup from efisubsys_init(). Fixes: 98086df8b70c ("efi: add missed destroy_workqueue when efisubsys_init fails") Fixes: 13c6da02e767 ("efi: Allocate runtime workqueue before ACPI init") Cc: stable@vger.kernel.org Signed-off-by: Ard Biesheuvel --- drivers/firmware/efi/efi.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/drivers/firmware/efi/efi.c b/drivers/firmware/efi/efi.c index 9d73aa5ebf9267..c5cebd4a75c06f 100644 --- a/drivers/firmware/efi/efi.c +++ b/drivers/firmware/efi/efi.c @@ -468,8 +468,7 @@ static int __init efisubsys_init(void) efi_kobj = kobject_create_and_add("efi", firmware_kobj); if (!efi_kobj) { pr_err("efi: Firmware registration failed.\n"); - error = -ENOMEM; - goto err_destroy_wq; + return -ENOMEM; } if (IS_ENABLED(CONFIG_PREEMPT_RT) && efi.runtime_supported_mask) { @@ -527,9 +526,6 @@ static int __init efisubsys_init(void) err_put: kobject_put(efi_kobj); efi_kobj = NULL; -err_destroy_wq: - if (efi_rts_wq) - destroy_workqueue(efi_rts_wq); return error; } From 044f27a852ba0658da793f9a45feb9474974674a Mon Sep 17 00:00:00 2001 From: zhangchujun Date: Fri, 20 Nov 2026 16:15:40 +0800 Subject: [PATCH 1636/2102] efivarfs: fix off-by-one in efivar_validate() variable name matching efivar_validate() passes utf8_size + 1 to variable_matches(), including the terminating NUL in the name length. However, variable_matches() expects the number of non-NUL characters. As a result, exact-name entries in variable_validate[] fail to match, causing some variables to use the wrong validator or bypass their intended validation. Fixes: 630ba0cc7a6d ("efi: Fix out-of-bounds read in variable_matches()") Cc: stable@vger.kernel.org Signed-off-by: zhangchujun Signed-off-by: Ard Biesheuvel --- fs/efivarfs/vars.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/efivarfs/vars.c b/fs/efivarfs/vars.c index 6833c3d24b541a..9f18bf48615cfc 100644 --- a/fs/efivarfs/vars.c +++ b/fs/efivarfs/vars.c @@ -274,7 +274,7 @@ efivar_validate(efi_guid_t vendor, efi_char16_t *var_name, u8 *data, if (efi_guidcmp(vendor, variable_validate[i].vendor)) continue; - if (variable_matches(utf8_name, utf8_size+1, name, &match)) { + if (variable_matches(utf8_name, utf8_size, name, &match)) { if (variable_validate[i].validate == NULL) break; kfree(utf8_name); From 569e1eb36b033f42a9c363ffe4bfbf50bdadae51 Mon Sep 17 00:00:00 2001 From: "Rafael J. Wysocki" Date: Thu, 19 Nov 2026 20:56:34 +0100 Subject: [PATCH 1637/2102] cpufreq: intel_pstate: Use dedicated lock in set_power_ctl_ee_state() Commit eee2a44e4e2b ("cpufreq: Improve suspend-resume synchronization") caused lockdep to complain about a possible circular locking dependency because intel_pstate_resume() is now called under cpus_read_lock, and it calls set_power_ctl_ee_state() that acquires intel_pstate_driver_lock which can be held around CPU hotplug locking. Fortunately, this cannot lead to a real deadlock because intel_pstate_resume() does not run in parallel with the other holders of intel_pstate_driver_lock, but in fact set_power_ctl_ee_state() need not use that particular lock either. Moreover, the original purpose of that lock is different, so using it in set_power_ctl_ee_state() is questionable. Accordingly, introduce a dedicated mutex for protecting MSR_IA32_POWER_CTL updates and power_ctl_ee_state accesses and make set_power_ctl_ee_state() use it instead of intel_pstate_driver_lock. Also take it directly in intel_pstate_resume() around the EE state restore. Fixes: eee2a44e4e2b ("cpufreq: Improve suspend-resume synchronization") Reported-by: "Borah, Chaitanya Kumar" Closes: https://lore.kernel.org/linux-pm/efcb1647-46fd-442a-bbda-283560d9df53@intel.com/ Signed-off-by: Rafael J. Wysocki Link: https://patch.msgid.link/2862244.mvXUDI8C0e@rafael.j.wysocki --- drivers/cpufreq/intel_pstate.c | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/drivers/cpufreq/intel_pstate.c b/drivers/cpufreq/intel_pstate.c index d3650a6e37b548..05c0ba06e1e311 100644 --- a/drivers/cpufreq/intel_pstate.c +++ b/drivers/cpufreq/intel_pstate.c @@ -1351,13 +1351,14 @@ static void intel_pstate_hwp_offline(struct cpudata *cpu) /* Enable bit for Dynamic Efficiency Control (DEC) */ #define POWER_CTL_DEC_ENABLE 27 +static DEFINE_MUTEX(power_ctl_update_lock); static int power_ctl_ee_state; -static void set_power_ctl_ee_state(bool input) +static void __set_power_ctl_ee_state(bool input) { u64 power_ctl; - guard(mutex)(&intel_pstate_driver_lock); + lockdep_assert_held(&power_ctl_update_lock); rdmsrq(MSR_IA32_POWER_CTL, power_ctl); if (input) { @@ -1370,6 +1371,13 @@ static void set_power_ctl_ee_state(bool input) wrmsrq(MSR_IA32_POWER_CTL, power_ctl); } +static void set_power_ctl_ee_state(bool input) +{ + guard(mutex)(&power_ctl_update_lock); + + __set_power_ctl_ee_state(input); +} + static void intel_pstate_hwp_enable(struct cpudata *cpudata); static void intel_pstate_hwp_reenable(struct cpudata *cpu) @@ -1398,11 +1406,13 @@ static int intel_pstate_resume(struct cpufreq_policy *policy) pr_debug("CPU %d resuming\n", cpu->cpu); - /* Only restore if the system default is changed */ - if (power_ctl_ee_state == POWER_CTL_EE_ENABLE) - set_power_ctl_ee_state(true); - else if (power_ctl_ee_state == POWER_CTL_EE_DISABLE) - set_power_ctl_ee_state(false); + scoped_guard(mutex, &power_ctl_update_lock) { + /* Only restore if the system default has changed */ + if (power_ctl_ee_state == POWER_CTL_EE_ENABLE) + __set_power_ctl_ee_state(true); + else if (power_ctl_ee_state == POWER_CTL_EE_DISABLE) + __set_power_ctl_ee_state(false); + } if (cpu->suspended && hwp_active) { mutex_lock(&intel_pstate_limits_lock); From bbebfac74dbcaedb21d73b496fd8ca179c40883c Mon Sep 17 00:00:00 2001 From: SungHwan Jung Date: Tue, 24 Nov 2026 18:49:23 +0900 Subject: [PATCH 1638/2102] ALSA: hda/realtek: Fix mic mute LED on Acer Predator PHN16-71 The mic mute LED on the Acer Predator PHN16-71 does not work and remains off regardless of the microphone mute state. Switch the existing quirk to ALC245_FIXUP_ACER_MICMUTE_LED, which includes the existing headset mic fixup and also fixes the mic mute LED. Fixes: d54c3cc224da ("ALSA: hda/realtek: Add quirk for Acer Predator PHN16-71") Signed-off-by: SungHwan Jung Link: https://patch.msgid.link/20261124094923.36856-1-onenowy@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 87a47f238e4c14..08200bd0247cb1 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -7583,7 +7583,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1025, 0x166c, "Acer Predator PH16-71", ALC2XX_FIXUP_HEADSET_MIC), SND_PCI_QUIRK(0x1025, 0x1679, "Acer Nitro 16 AN16-41", ALC2XX_FIXUP_HEADSET_MIC), SND_PCI_QUIRK(0x1025, 0x169a, "Acer Swift SFG16", ALC256_FIXUP_ACER_SFG16_MICMUTE_LED), - SND_PCI_QUIRK(0x1025, 0x170f, "Acer Predator PHN16-71", ALC2XX_FIXUP_HEADSET_MIC), + SND_PCI_QUIRK(0x1025, 0x170f, "Acer Predator PHN16-71", ALC245_FIXUP_ACER_MICMUTE_LED), SND_PCI_QUIRK(0x1025, 0x171e, "Acer Nitro ANV15-51", ALC245_FIXUP_ACER_MICMUTE_LED), SND_PCI_QUIRK(0x1025, 0x172c, "Acer Nitro ANV16-41", ALC2XX_FIXUP_HEADSET_MIC), SND_PCI_QUIRK(0x1025, 0x1731, "Acer Predator PHN16-72", ALC245_FIXUP_ACER_MICMUTE_LED), From 326e2cc4a65886d22f9de49a8e484db3d5cf1d29 Mon Sep 17 00:00:00 2001 From: Sophiel Zhou Date: Tue, 24 Nov 2026 17:00:51 +0800 Subject: [PATCH 1639/2102] ALSA: usb-audio: Enable native DSD for iBasso Macaron The iBasso Macaron (USB ID 262a:1a0b) exposes a UAC2 RAW_DATA playback altsetting (altset 4, bmFormats 0x80000000, 32-bit subslot), but ALSA reports it as SPECIAL without the DSD_RAW quirk, preventing native DSD playback. Add the device to the quirk flags table with QUIRK_FLAG_DSD_RAW. This makes the altsetting available as DSD_U32_BE. Tested with quirk_flags=262a:1a0b:dsd_raw and with the quirk enabled through the device table entry. DSD256 playback works. Signed-off-by: Sophiel Zhou Link: https://patch.msgid.link/20261124090051.37375-1-sophiel@zzy040330.moe Signed-off-by: Takashi Iwai --- sound/usb/quirks.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sound/usb/quirks.c b/sound/usb/quirks.c index 03172f8e971662..bcc93e50b4ef04 100644 --- a/sound/usb/quirks.c +++ b/sound/usb/quirks.c @@ -2810,6 +2810,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { QUIRK_FLAG_DSD_RAW), DEVICE_FLG(0x262a, 0x9302, /* ddHiFi TC44C */ QUIRK_FLAG_DSD_RAW), + DEVICE_FLG(0x262a, 0x1a0b, /* iBasso Macaron */ + QUIRK_FLAG_DSD_RAW), DEVICE_FLG(0x2772, 0x0502, /* Musical Fidelity M6s DAC */ 0), /* for avoiding QUIRK_FLAG_DSD_RAW with vendor match */ DEVICE_FLG(0x2912, 0x30c8, /* Audioengine D1 */ From 29f80379ebda03e8085cb5c8c7b9940d1662c6c1 Mon Sep 17 00:00:00 2001 From: Suyuan Wang Date: Tue, 24 Nov 2026 04:47:07 +0000 Subject: [PATCH 1640/2102] ALSA: mixart: Don't touch the mailbox when the BAR mapping failed snd_mixart_probe() calls snd_mixart_free() when pci_ioremap_bar() fails for either BAR. snd_mixart_free() then unconditionally calls snd_mixart_exit_mailbox(mgr); which masks the outbound mailbox interrupts by writing to MIXART_REG(mgr, MIXART_PCI_OMIMR_OFFSET), i.e. through mgr->mem[1].virt. mem[1].virt is still NULL if either BAR mapping fails, so the error path oopses on a write near address 0 instead of returning -EBUSY. Only call snd_mixart_exit_mailbox() when the register BAR is mapped. The rest of snd_mixart_free() already copes with a partly set up manager: iounmap() accepts NULL, and the IRQ and DMA buffers are checked before release. Found with a static analysis tool and checked by hand. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Co-developed-by: Kaixuan Li Signed-off-by: Kaixuan Li Signed-off-by: Suyuan Wang Link: https://patch.msgid.link/20261124-mixart-free-v1-1-13765d8d445b@gmail.com Signed-off-by: Takashi Iwai --- sound/pci/mixart/mixart.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sound/pci/mixart/mixart.c b/sound/pci/mixart/mixart.c index f451554cff5f1f..0266467734cad8 100644 --- a/sound/pci/mixart/mixart.c +++ b/sound/pci/mixart/mixart.c @@ -1066,8 +1066,9 @@ static int snd_mixart_free(struct mixart_mgr *mgr) snd_card_free(mgr->chip[i]->card); } - /* stop mailbox */ - snd_mixart_exit_mailbox(mgr); + /* stop mailbox, unless the register BAR was never mapped */ + if (mgr->mem[1].virt) + snd_mixart_exit_mailbox(mgr); /* release irq */ if (mgr->irq >= 0) From f90e53a046cea6eaec0e50efb50a9f3957ba9f16 Mon Sep 17 00:00:00 2001 From: Cong Nguyen Date: Tue, 24 Nov 2026 15:52:31 +0700 Subject: [PATCH 1641/2102] gpio: omap: do not unprepare the debounce clock twice on probe failure The debounce clock is now obtained with devm_clk_get_prepared(), so devres unprepares it when probe fails or the device is unbound. The error path added for a failing pm_runtime_resume_and_get() still calls clk_unprepare() on the same clock by hand. When pm_runtime_resume_and_get() fails and a debounce clock is present, the clock is unprepared twice. The second clk_unprepare() warns that the clock is already unprepared. Drop the manual clk_unprepare(). Fixes: 9df982f1f283 ("gpio: omap: handle debounce clock preparation failure") Signed-off-by: Cong Nguyen Reviewed-by: Alexander Sverdlin Reviewed-by: Andreas Kemnade Link: https://patch.msgid.link/20261124085231.3696739-1-congnt264@gmail.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-omap.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/drivers/gpio/gpio-omap.c b/drivers/gpio/gpio-omap.c index 0da628ae77bedc..0af26c3f71978f 100644 --- a/drivers/gpio/gpio-omap.c +++ b/drivers/gpio/gpio-omap.c @@ -1463,8 +1463,6 @@ static int omap_gpio_probe(struct platform_device *pdev) ret = pm_runtime_resume_and_get(dev); if (ret < 0) { pm_runtime_disable(dev); - if (bank->dbck_flag) - clk_unprepare(bank->dbck); return ret; } From 0ad50746fc640b68c24454500a513c4fd6293d75 Mon Sep 17 00:00:00 2001 From: Abhiraj Dutta Date: Mon, 23 Nov 2026 21:17:57 -0500 Subject: [PATCH 1642/2102] ALSA: hda/realtek: Fix duplicate LEDs on HP Spectre x360 16-f2xxx The EU0XXX fixup already sets up the mute and mic-mute LEDs, so chaining ALC245_FIXUP_HP_X360_MUTE_LEDS after it registers both LEDs twice (hda::mute_1 and hda::micmute_1 appear). Use the EU0XXX fixup directly. The original commit message also got the SSID wrong: under SOF the PCI SSID is 103c:891e, not 103c:0000. Fixes: e30ec632e1f0 ("ALSA: hda/realtek: Add quirk for HP Spectre x360 2-in-1 Laptop 16-f2xxx") Cc: stable@vger.kernel.org Signed-off-by: Abhiraj Dutta Link: https://patch.msgid.link/20261123-hp-spectre-16-f2-led-fix-v1-1-a2a333dceeb5@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 08200bd0247cb1..037a5abf1a3e69 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -4524,7 +4524,6 @@ enum { ALC256_FIXUP_HEADPHONE_AMP_VOL, ALC245_FIXUP_HP_SPECTRE_X360_EU0XXX, ALC245_FIXUP_HP_SPECTRE_X360_16_AA0XXX, - ALC245_FIXUP_HP_SPECTRE_X360_16_F2XXX, ALC245_FIXUP_HP_ZBOOK_FIREFLY_G12A, ALC285_FIXUP_ASUS_GA403U, ALC285_FIXUP_ASUS_GA403U_HEADSET_MIC, @@ -7227,12 +7226,6 @@ static const struct hda_fixup alc269_fixups[] = { .type = HDA_FIXUP_FUNC, .v.func = alc245_fixup_hp_spectre_x360_16_aa0xxx, }, - [ALC245_FIXUP_HP_SPECTRE_X360_16_F2XXX] = { - .type = HDA_FIXUP_FUNC, - .v.func = alc245_fixup_hp_spectre_x360_eu0xxx, - .chained = true, - .chain_id = ALC245_FIXUP_HP_X360_MUTE_LEDS - }, [ALC245_FIXUP_HP_ZBOOK_FIREFLY_G12A] = { .type = HDA_FIXUP_FUNC, .v.func = alc245_fixup_hp_zbook_firefly_g12a, @@ -7876,7 +7869,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8902, "HP OMEN 16", ALC285_FIXUP_HP_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x890e, "HP 255 G8 Notebook PC", ALC236_FIXUP_HP_MUTE_LED_COEFBIT2), SND_PCI_QUIRK(0x103c, 0x8919, "HP Pavilion Aero Laptop 13-be0xxx", ALC287_FIXUP_HP_GPIO_LED), - SND_PCI_QUIRK(0x103c, 0x891e, "HP Spectre x360 2-in-1 Laptop 16-f2xxx", ALC245_FIXUP_HP_SPECTRE_X360_16_F2XXX), + SND_PCI_QUIRK(0x103c, 0x891e, "HP Spectre x360 2-in-1 Laptop 16-f2xxx", ALC245_FIXUP_HP_SPECTRE_X360_EU0XXX), SND_PCI_QUIRK(0x103c, 0x896d, "HP ZBook Firefly 16 G9", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x896e, "HP EliteBook x360 830 G9", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8971, "HP EliteBook 830 G9", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), From 3a9e4cc5c0ffd8c0d7438a70ff84df4d4a9405c4 Mon Sep 17 00:00:00 2001 From: Lorenzo Argentieri Date: Mon, 23 Nov 2026 20:05:05 +0100 Subject: [PATCH 1643/2102] ALSA: hda/realtek: Enable speaker amp on ONEXPLAYER X1 i The internal speakers of the ONE-NETBOOK ONEXPLAYER X1 i (Intel Core Ultra 7 155H, ALC245, subsystem ID 1f75:1602) are almost inaudible on Linux. They are driven by a Realtek smart amplifier at I2C address 0x10, behind the ALC245 coefficient tunnel. The firmware leaves the amplifier unconfigured, and the Windows driver programs it at initialization. Add a fixup that replays the register writes of the Windows driver through the tunnel: coefficient 0x24 selects the amplifier, 0x25/0x26 hold the register address, 0x28 the value, and writing 0xb023 to 0x29 starts the transfer. Bit 5 of 0x29 is a self-clearing go bit; poll it instead of using a fixed delay (a write completes in about 200 us). The sequence was captured from Windows by the onexplayer2pro-audio-fix project and decoded here. Its reads and address probes were dropped, leaving 46 amplifier register writes. The fixup runs at every codec init, so the configuration is restored after system resume. Tested on ONEXPLAYER X1 i, BIOS 2.42, after a full power-off: a test tone played through the speakers and recorded by the internal microphone is about 50 dB louder with this fixup than without it. Link: https://github.com/feederchain/onexplayer2pro-audio-fix Signed-off-by: Lorenzo Argentieri Link: https://patch.msgid.link/20261123-oxp-x1-amp-v1-1-8b61da12d092@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 69 +++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index a6b5e8987294fc..ca7fcc271f30ec 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -1909,6 +1909,69 @@ static void alc298_fixup_alc1316_amp(struct hda_codec *codec, } } +/* + * The ONEXPLAYER X1 i drives its speakers through a Realtek smart amplifier at + * I2C address 0x10, reached over the ALC245 coefficient tunnel. The firmware + * leaves the amplifier unconfigured, so the speakers stay silent. The register + * writes below replay what the Windows driver does at initialization. + * + * Tunnel layout: coefficient 0x24 selects the amplifier, 0x25 and 0x26 carry + * the high and low halves of the register address, 0x28 the value, and 0x29 + * commits. Bit 5 of the commit word is a self-clearing go bit; a write takes + * about 200 us. + */ +static void alc245_onexplayer_amp_write(struct hda_codec *codec, u32 reg, u8 val) +{ + int i; + + alc_write_coef_idx(codec, 0x24, 0x0010); + alc_write_coef_idx(codec, 0x25, reg >> 16); + alc_write_coef_idx(codec, 0x26, reg & 0xffff); + alc_write_coef_idx(codec, 0x27, 0x0000); + alc_write_coef_idx(codec, 0x28, val); + alc_write_coef_idx(codec, 0x29, 0xb023); + + for (i = 0; i < 10; i++) { + if (!(alc_read_coef_idx(codec, 0x29) & 0x0020)) + return; + usleep_range(100, 200); + } + codec_warn(codec, "amp write timeout, reg 0x%x\n", reg); +} + +static void alc245_fixup_onexplayer_amp(struct hda_codec *codec, + const struct hda_fixup *fix, int action) +{ + static const struct { + u32 reg; + u8 val; + } init_seq[] = { + { 0xf10a, 0x09 }, { 0xf104, 0xf6 }, { 0xf105, 0x22 }, + { 0xf10b, 0x2c }, { 0xf10b, 0x7c }, { 0xc000, 0x01 }, + { 0xf20d, 0x00 }, { 0xf212, 0x3e }, { 0xc001, 0x02 }, + { 0xc003, 0x22 }, { 0xc004, 0x44 }, { 0xc005, 0x44 }, + { 0xc007, 0x64 }, { 0xc00e, 0xe7 }, { 0xf223, 0x7f }, + { 0xf224, 0xdb }, { 0xf225, 0xee }, { 0xf226, 0x3f }, + { 0xf227, 0x0f }, { 0xf21a, 0x78 }, { 0xf242, 0x3c }, + { 0xc120, 0x40 }, { 0xc125, 0x03 }, { 0xc321, 0x0b }, + { 0xc200, 0xd8 }, { 0xc201, 0x27 }, { 0xc202, 0x0f }, + { 0xc400, 0x0e }, { 0xc401, 0x43 }, { 0xc402, 0xe0 }, + { 0xc403, 0x00 }, { 0xc404, 0x4c }, { 0xc406, 0x40 }, + { 0xc407, 0x02 }, { 0xc408, 0x3f }, { 0xc300, 0x01 }, + { 0x41001888, 0x00 }, { 0xc121, 0x0b }, { 0xf102, 0x00 }, + { 0xf103, 0x00 }, { 0xf104, 0xf5 }, { 0xf105, 0x23 }, + { 0xf109, 0x00 }, { 0xf10a, 0x0b }, { 0xf10b, 0x4c }, + { 0xf10b, 0x5c }, + }; + int i; + + if (action != HDA_FIXUP_ACT_INIT) + return; + + for (i = 0; i < ARRAY_SIZE(init_seq); i++) + alc245_onexplayer_amp_write(codec, init_seq[i].reg, init_seq[i].val); +} + static void alc298_fixup_samsung_amp(struct hda_codec *codec, const struct hda_fixup *fix, int action) { @@ -4553,6 +4616,7 @@ enum { ALC256_FIXUP_ASUS_SPEAKER_COEFS, ALC245_FIXUP_MINISFORUM_V3_MIC_NO_PRESENCE, ALC287_FIXUP_TAS2781_I2C_DAC, + ALC245_FIXUP_ONEXPLAYER_AMP, }; /* A special fixup for Lenovo C940 and Yoga Duet 7; @@ -7472,6 +7536,10 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC245_FIXUP_BASS_HP_DAC }, + [ALC245_FIXUP_ONEXPLAYER_AMP] = { + .type = HDA_FIXUP_FUNC, + .v.func = alc245_fixup_onexplayer_amp, + }, }; static const struct hda_quirk alc269_fixup_tbl[] = { @@ -8750,6 +8818,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1f4c, 0xe001, "Minisforum V3 (SE)", ALC245_FIXUP_MINISFORUM_V3_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1f66, 0x0105, "Ayaneo Portable Game Player", ALC287_FIXUP_CS35L41_I2C_2), + SND_PCI_QUIRK(0x1f75, 0x1602, "ONEXPLAYER X1 i", ALC245_FIXUP_ONEXPLAYER_AMP), SND_PCI_QUIRK(0x2014, 0x800a, "Positivo ARN50", ALC269_FIXUP_LIMIT_INT_MIC_BOOST), SND_PCI_QUIRK(0x2039, 0x0001, "Inspur S14-G1", ALC295_FIXUP_CHROME_BOOK), SND_PCI_QUIRK(0x2145, 0x0001, "Star Labs StarFighter", ALC233_FIXUP_STARLABS_STARFIGHTER), From c871dbdeacfbb8a48d90406b8a96f3c41c3924b5 Mon Sep 17 00:00:00 2001 From: Arnav Kapoor Date: Mon, 23 Nov 2026 22:32:01 +0530 Subject: [PATCH 1644/2102] ALSA: hda: reject invalid values in the IEC958 switch put callbacks snd_hda_spdif_out_switch_put(), snd_hda_spdif_in_switch_put() and spdif_share_sw_put() treat any non-zero value as "on", so writes of values outside 0..1, such as 2, -1 or INT_MAX, to these boolean controls succeed instead of being rejected. snd_hda_mixer_amp_switch_put() in the same file already returns -EINVAL for them. Check the value in the same way before taking spdif_mutex. Signed-off-by: Arnav Kapoor Tested-by: HyeongJun An Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261123170203.243633-1-kapoorarnav43@gmail.com --- sound/hda/common/codec.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/sound/hda/common/codec.c b/sound/hda/common/codec.c index 51189e305ece67..0470f4e085f7bc 100644 --- a/sound/hda/common/codec.c +++ b/sound/hda/common/codec.c @@ -2353,6 +2353,9 @@ static int snd_hda_spdif_out_switch_put(struct snd_kcontrol *kcontrol, if (WARN_ON(codec->spdif_out.used <= idx)) return -EINVAL; + if (ucontrol->value.integer.value[0] < 0 || + ucontrol->value.integer.value[0] > 1) + return -EINVAL; guard(mutex)(&codec->spdif_mutex); spdif = snd_array_elem(&codec->spdif_out, idx); nid = spdif->nid; @@ -2557,9 +2560,11 @@ static int spdif_share_sw_put(struct snd_kcontrol *kcontrol, { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct hda_multi_out *mout = (void *)kcontrol->private_value; - bool val = !!ucontrol->value.integer.value[0]; + long val = ucontrol->value.integer.value[0]; int change; + if (val < 0 || val > 1) + return -EINVAL; guard(mutex)(&codec->spdif_mutex); change = mout->share_spdif != val; mout->share_spdif = val; @@ -2632,9 +2637,11 @@ static int snd_hda_spdif_in_switch_put(struct snd_kcontrol *kcontrol, { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); hda_nid_t nid = kcontrol->private_value; - unsigned int val = !!ucontrol->value.integer.value[0]; + long val = ucontrol->value.integer.value[0]; int change; + if (val < 0 || val > 1) + return -EINVAL; guard(mutex)(&codec->spdif_mutex); change = codec->spdif_in_enable != val; if (change) { From fa1658c34d1b874930d548510469f57419ceb631 Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Mon, 23 Nov 2026 10:05:35 +0000 Subject: [PATCH 1645/2102] sound: core: Check return value of device_create() The sound_insert_unit() function ignores the return value of device_create(). If device creation fails, the function still returns the allocated minor number as if registration succeeded. Add a helper function, sound_device_create(), to create the sound device and check the return value using PTR_ERR_OR_ZERO(). If device creation fails, remove the allocated sound unit from the sound loader list, unregister the character device when preclaim_oss is disabled, and free the allocated memory. Return the original error code to the caller instead of reporting successful registration. Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261123100535.3025-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/sound_core.c | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/sound/sound_core.c b/sound/sound_core.c index 10db8c69963035..90d59b14245d94 100644 --- a/sound/sound_core.c +++ b/sound/sound_core.c @@ -231,6 +231,21 @@ static struct sound_unit *__sound_remove_unit(struct sound_unit **list, int unit static DEFINE_SPINLOCK(sound_loader_lock); +/* + * Create the sound device and return an error if device creation fails. + */ + +static int sound_device_create(struct sound_unit *s, struct device *dev) +{ + struct device *device; + + device = device_create(&sound_class, dev, + MKDEV(SOUND_MAJOR, s->unit_minor), + NULL, "%s", s->name + 6); + + return PTR_ERR_OR_ZERO(device); +} + /* * Allocate the controlling structure and add it to the sound driver * list. Acquires locks as needed @@ -277,10 +292,20 @@ static int sound_insert_unit(struct sound_unit **list, const struct file_operati } } - device_create(&sound_class, dev, MKDEV(SOUND_MAJOR, s->unit_minor), - NULL, "%s", s->name+6); + r = sound_device_create(s, dev); + if (r) + goto err_remove_unit; + return s->unit_minor; +err_remove_unit: + if (!preclaim_oss) + __unregister_chrdev(SOUND_MAJOR, s->unit_minor, 1, s->name); + + spin_lock(&sound_loader_lock); + __sound_remove_unit(list, s->unit_minor); + spin_unlock(&sound_loader_lock); + fail: kfree(s); return r; From 2321b0b895394124f25b40ab91681c5639e3e1fe Mon Sep 17 00:00:00 2001 From: Martin Szathmari Date: Sun, 22 Nov 2026 22:58:57 +0100 Subject: [PATCH 1646/2102] ALSA: hda/realtek: Fix speaker on ASUS ExpertBook B7402FEA after Windows On the ASUS ExpertBook B7402FEA (ALC294, SSID 1043:1b02), the internal speaker is silent after a warm reboot from Windows. The Windows driver leaves two vendor coefficients in a state that the generic init path does not reset: - COEF 0x66 bit 4 is set, which mutes the speaker. - COEF 0x1b bit 10 is clear, which distorts the output once the speaker is unmuted. This is the same bit ALC294_FIXUP_ASUS_COEF_1B sets for the UX431DA. A cold boot clears both. Comparing all 256 coefficients of node 0x20 after a cold boot and after a reboot from Windows showed five differences; writing them back one at a time showed only these two matter. Add a fixup that clears COEF 0x66 bit 4 and sets COEF 0x1b bit 10 at init, so they are also restored on resume. ALC294_FIXUP_ASUS_COEF_1B is not reused because it chains to the GA401 pin fixup, which does not apply to this machine. Tested on a B7402FEA (BIOS 308): sound is clean after a reboot from Windows, and after suspend/resume with both bits forced back to the Windows values first. Signed-off-by: Martin Szathmari Link: https://patch.msgid.link/20261122215857.4580-1-martin.szathmari@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index ca7fcc271f30ec..f49021d0120c03 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -1116,6 +1116,21 @@ static void alc269vb_fixup_aspire_e1_coef(struct hda_codec *codec, alc_update_coef_idx(codec, 0x0d, 0x6000, 0x6000); } +/* + * After a warm reboot from Windows, bit 4 of COEF 0x66 is left set, which + * mutes the internal speaker, and bit 10 of COEF 0x1b is left clear, which + * distorts the output. Restore both at init and resume. + */ +static void alc294_fixup_asus_spk_coefs(struct hda_codec *codec, + const struct hda_fixup *fix, + int action) +{ + if (action != HDA_FIXUP_ACT_INIT) + return; + alc_update_coef_idx(codec, 0x66, 1 << 4, 0); + alc_update_coef_idx(codec, 0x1b, 0, 1 << 10); +} + static void alc269_fixup_pcm_44k(struct hda_codec *codec, const struct hda_fixup *fix, int action) { @@ -4435,6 +4450,7 @@ enum { ALC294_FIXUP_ASUS_ALLY_VERBS, ALC294_FIXUP_ASUS_HPE, ALC294_FIXUP_ASUS_COEF_1B, + ALC294_FIXUP_ASUS_SPK_COEFS, ALC294_FIXUP_ASUS_GX502_HP, ALC294_FIXUP_ASUS_GX502_PINS, ALC294_FIXUP_ASUS_GX502_VERBS, @@ -6313,6 +6329,10 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC289_FIXUP_ASUS_GA401, }, + [ALC294_FIXUP_ASUS_SPK_COEFS] = { + .type = HDA_FIXUP_FUNC, + .v.func = alc294_fixup_asus_spk_coefs, + }, [ALC285_FIXUP_HP_GPIO_LED] = { .type = HDA_FIXUP_FUNC, .v.func = alc285_fixup_hp_gpio_led, @@ -8275,6 +8295,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1043, 0x1a83, "ASUS UM5302LA", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x1043, 0x1a8e, "ASUS G712LWS", ALC294_FIXUP_LENOVO_MIC_LOCATION), SND_PCI_QUIRK(0x1043, 0x1a8f, "ASUS UX582ZS", ALC245_FIXUP_CS35L41_SPI_2), + SND_PCI_QUIRK(0x1043, 0x1b02, "ASUS ExpertBook B7402FEA", ALC294_FIXUP_ASUS_SPK_COEFS), SND_PCI_QUIRK(0x1043, 0x1b11, "ASUS UX431DA", ALC294_FIXUP_ASUS_COEF_1B), SND_PCI_QUIRK(0x1043, 0x1b13, "ASUS U41SV/GA403U", ALC285_FIXUP_ASUS_GA403U_HEADSET_MIC), SND_PCI_QUIRK(0x1043, 0x1b93, "ASUS G614JVR/JIR", ALC245_FIXUP_CS35L41_SPI_2), From 1e04af2e3e17d62bc6d82ee890a3218341cae9d1 Mon Sep 17 00:00:00 2001 From: Takashi Iwai Date: Tue, 24 Nov 2026 13:55:56 +0100 Subject: [PATCH 1647/2102] ALSA: hda/realtek: Fix regression on another Lenovo Legion 16IRX9H model There is yet another Lenovo Legion 16IRX9H model with the codec SSID 17aa:38cb that suffers from the same regression as stated in the commit 0b4d69e8d2b5 ("ALSA: hda/realtek: Fix regression on Lenovo Legion 16IRX9H"). Cover this device in the same way, too. Fixes: f2293e7b2ddd ("ALSA: hda/realtek: Enable all four speaker amps on Lenovo ThinkBook X G2 IAH") Cc: Reported-by: Edward Bentall Closes: https://lore.kernel.org/CACw1+JLf_0i+GvJ4POkFUrPo_AWNHp9X2aCxyQVFRcdrKbKVxQ@mail.gmail.com Link: https://patch.msgid.link/20261124125606.570355-1-tiwai@suse.de Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 037a5abf1a3e69..fb6f65de71f162 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -8584,6 +8584,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x17aa, 0x3834, "Lenovo IdeaPad Slim 9i 14ITL5", ALC287_FIXUP_YOGA7_14ITL_SPEAKERS), SND_PCI_QUIRK(0x17aa, 0x383d, "Legion Y9000X 2019", ALC285_FIXUP_LEGION_Y9000X_SPEAKERS), /* Legion 16IRX9H shares PCI SSID 17aa:3842 with Thinkpad X G2 below */ + HDA_CODEC_QUIRK(0x17aa, 0x38cb, "Lenovo Legion 16IRX9H", ALC287_FIXUP_TAS2781_I2C), HDA_CODEC_QUIRK(0x17aa, 0x38cd, "Lenovo Legion 16IRX9H", ALC287_FIXUP_TAS2781_I2C), SND_PCI_QUIRK(0x17aa, 0x3842, "ThinkBook X G2 IAH", ALC287_FIXUP_MG_RTKC_CSAMP_CS35L41_I2C_4_THINKPAD), /* IdeaPad Pro 5 14IAH10 shares PCI SSID 17aa:3843 with Yoga Book 9i; From c3c132d63840093a3ca4bd09e7434614c1bd07e3 Mon Sep 17 00:00:00 2001 From: Arshdeep Singh Date: Tue, 24 Nov 2026 18:50:56 +0530 Subject: [PATCH 1648/2102] ALSA: hda/realtek: Add quirk for HP Pavilion 15-cs3xxx The HP Pavilion 15-cs3006tx (ALC295, subsystem 103c:86e2) has no working mute LED by default. Booting with model=hp-mute-led-mic3 makes the LED work on this machine, so add a quirk entry for this SSID that applies the same fixup, ALC269_FIXUP_HP_MUTE_LED_MIC3. Testing: verified on the hardware with model=hp-mute-led-mic3, which selects the same fixup as this entry. alc269.o builds and checkpatch.pl --strict is clean. I have not booted a kernel built with this patch. Tooling: the working model option was found by manual testing, guided by an AI chat assistant (Claude). The table entry and this changelog were prepared with a coding agent (OpenAI Codex); I reviewed both. Signed-off-by: Arshdeep Singh Link: https://patch.msgid.link/20261124132056.57345-1-chahalarsh342@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index fb6f65de71f162..39b2f329dc84d5 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -7789,6 +7789,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x86c1, "HP Laptop 15-da3001TU", ALC236_FIXUP_HP_MUTE_LED_COEFBIT2), SND_PCI_QUIRK(0x103c, 0x86c7, "HP Envy AiO 32", ALC274_FIXUP_HP_ENVY_GPIO), SND_PCI_QUIRK(0x103c, 0x86c8, "HP Laptop 14s-dr1xxx", ALC236_FIXUP_HP_MUTE_LED_COEFBIT2), + SND_PCI_QUIRK(0x103c, 0x86e2, "HP Pavilion 15-cs3xxx", ALC269_FIXUP_HP_MUTE_LED_MIC3), SND_PCI_QUIRK(0x103c, 0x86e7, "HP Spectre x360 15-eb0xxx", ALC285_FIXUP_HP_SPECTRE_X360_EB1), SND_PCI_QUIRK(0x103c, 0x863e, "HP Spectre x360 15-df1xxx", ALC285_FIXUP_HP_SPECTRE_X360_DF1), SND_PCI_QUIRK(0x103c, 0x86e8, "HP Spectre x360 15-eb0xxx", ALC285_FIXUP_HP_SPECTRE_X360_EB1), From 97889ef32b771dfe8171d3e8beb5802dd3f95e1c Mon Sep 17 00:00:00 2001 From: Maciej Strozek Date: Fri, 20 Nov 2026 16:28:07 +0000 Subject: [PATCH 1649/2102] ASoC: SDCA: Use Function Extension info for FDL Add additional way of selecting files for FDL using Function Extension ID and Function Extension Version, following Windows' SDCA driver usage of those controls for FDL. Make sure the introduced FEID/FEV search path is separate from the 'legacy' SSID-only search path in case some vendors choose to re-use SSIDs for different SKUs and identify them by Function Extension controls instead. Signed-off-by: Maciej Strozek Reviewed-by: Charles Keepax Link: https://patch.msgid.link/20261120162807.1568409-1-mstrozek@opensource.cirrus.com Signed-off-by: Mark Brown --- sound/soc/sdca/sdca_fdl.c | 150 +++++++++++++++++++++++--------------- 1 file changed, 92 insertions(+), 58 deletions(-) diff --git a/sound/soc/sdca/sdca_fdl.c b/sound/soc/sdca/sdca_fdl.c index 7fc809707944d0..6c34e68fe729dd 100644 --- a/sound/soc/sdca/sdca_fdl.c +++ b/sound/soc/sdca/sdca_fdl.c @@ -147,47 +147,77 @@ int sdca_fdl_sync(struct device *dev, struct sdca_function_data *function, } EXPORT_SYMBOL_NS_GPL(sdca_fdl_sync, "SND_SOC_SDCA"); -static char *fdl_get_sku_filename(struct device *dev, - struct sdca_fdl_file *fdl_file) +static int fdl_get_sku_filename(struct sdca_interrupt *interrupt, + struct sdca_fdl_file *fdl_file, + char **disk_filename, + char **fallback_filename) { - struct device *parent = dev; + unsigned int adr = interrupt->function->desc->adr; + char extension[sizeof("fe0000v00/")] = ""; + struct device *parent = interrupt->dev; const char *product_vendor; const char *product_sku; + unsigned int id = 0, version = 0; + + regmap_read(interrupt->function_regmap, + SDW_SDCA_CTL(adr, SDCA_ENTITY_TYPE_ENTITY_0, + SDCA_CTL_ENTITY_0_FUNCTION_EXTENSION_ID, 0), + &id); + regmap_read(interrupt->function_regmap, + SDW_SDCA_CTL(adr, SDCA_ENTITY_TYPE_ENTITY_0, + SDCA_CTL_ENTITY_0_FUNCTION_EXTENSION_VERSION, 0), + &version); + + if (id || version) + snprintf(extension, sizeof(extension), "fe%xv%x/", id, version); /* * Try to find pci_dev manually because the card may not be ready to be * used for snd_soc_card_get_pci_ssid yet */ - while (parent) { - if (dev_is_pci(parent)) { - struct pci_dev *pci_dev = to_pci_dev(parent); - - return kasprintf(GFP_KERNEL, "sdca/%x/%x/%x/%x.bin", - fdl_file->vendor_id, - pci_dev->subsystem_vendor, - pci_dev->subsystem_device, - fdl_file->file_id); - } else { - parent = parent->parent; - } + while (parent && !dev_is_pci(parent)) + parent = parent->parent; + + if (parent) { + struct pci_dev *pci_dev = to_pci_dev(parent); + + *disk_filename = kasprintf(GFP_KERNEL, "sdca/%x/%x/%x/%s%x.bin", + fdl_file->vendor_id, + pci_dev->subsystem_vendor, + pci_dev->subsystem_device, + extension, fdl_file->file_id); + } else { + product_vendor = dmi_get_system_info(DMI_SYS_VENDOR); + if (!product_vendor || !strcmp(product_vendor, "Default string")) + product_vendor = dmi_get_system_info(DMI_BOARD_VENDOR); + if (!product_vendor || !strcmp(product_vendor, "Default string")) + product_vendor = dmi_get_system_info(DMI_CHASSIS_VENDOR); + if (!product_vendor) + product_vendor = "unknown"; + + product_sku = dmi_get_system_info(DMI_PRODUCT_SKU); + if (!product_sku || !strcmp(product_sku, "Default string")) + product_sku = dmi_get_system_info(DMI_PRODUCT_NAME); + if (!product_sku) + product_sku = "unknown"; + + *disk_filename = kasprintf(GFP_KERNEL, "sdca/%x/%s/%s/%s%x.bin", + fdl_file->vendor_id, product_vendor, + product_sku, extension, + fdl_file->file_id); + } + + *fallback_filename = kasprintf(GFP_KERNEL, "sdca/%x/%s%x.bin", + fdl_file->vendor_id, extension, + fdl_file->file_id); + + if (!*disk_filename || !*fallback_filename) { + kfree(*disk_filename); + kfree(*fallback_filename); + return -ENOMEM; } - product_vendor = dmi_get_system_info(DMI_SYS_VENDOR); - if (!product_vendor || !strcmp(product_vendor, "Default string")) - product_vendor = dmi_get_system_info(DMI_BOARD_VENDOR); - if (!product_vendor || !strcmp(product_vendor, "Default string")) - product_vendor = dmi_get_system_info(DMI_CHASSIS_VENDOR); - if (!product_vendor) - product_vendor = "unknown"; - - product_sku = dmi_get_system_info(DMI_PRODUCT_SKU); - if (!product_sku || !strcmp(product_sku, "Default string")) - product_sku = dmi_get_system_info(DMI_PRODUCT_NAME); - if (!product_sku) - product_sku = "unknown"; - - return kasprintf(GFP_KERNEL, "sdca/%x/%s/%s/%x.bin", fdl_file->vendor_id, - product_vendor, product_sku, fdl_file->file_id); + return 0; } static int fdl_load_file(struct sdca_interrupt *interrupt, @@ -197,7 +227,9 @@ static int fdl_load_file(struct sdca_interrupt *interrupt, struct sdca_fdl_data *fdl_data = &interrupt->function->fdl_data; struct acpi_sw_file *swf = NULL, *tmp; struct sdca_fdl_file *fdl_file; - char *disk_filename; + const char *source = "ACPI SWFT"; + const char *disk_source; + char *disk_filename, *fallback_filename; int ret; if (!set) { @@ -231,25 +263,17 @@ static int fdl_load_file(struct sdca_interrupt *interrupt, } } - disk_filename = fdl_get_sku_filename(dev, fdl_file); - if (!disk_filename) - return -ENOMEM; - - dev_dbg(dev, "FDL disk filename: %s\n", disk_filename); + ret = fdl_get_sku_filename(interrupt, fdl_file, + &disk_filename, &fallback_filename); + if (ret) + return ret; const struct firmware *firmware __free(firmware) = NULL; + disk_source = disk_filename; ret = firmware_request_nowarn(&firmware, disk_filename, dev); - kfree(disk_filename); if (ret) { - disk_filename = kasprintf(GFP_KERNEL, "sdca/%x/%x.bin", - fdl_file->vendor_id, fdl_file->file_id); - if (!disk_filename) - return -ENOMEM; - - dev_dbg(dev, "FDL disk filename: %s\n", disk_filename); - - ret = firmware_request_nowarn(&firmware, disk_filename, dev); - kfree(disk_filename); + disk_source = fallback_filename; + ret = firmware_request_nowarn(&firmware, fallback_filename, dev); } if (!ret) { @@ -259,25 +283,35 @@ static int fdl_load_file(struct sdca_interrupt *interrupt, tmp->file_length != firmware->size) { dev_err(dev, "bad disk SWF size\n"); } else if (!swf || swf->file_version <= tmp->file_version) { - dev_dbg(dev, "using SWF from disk\n"); swf = tmp; + source = disk_source; } } if (!swf) { - dev_err(dev, "failed to locate SWF\n"); - return -ENOENT; + dev_err(dev, "failed to locate SWF: %x-%x\n" + "Attempted FDL disk filename: %s\n" + "Attempted FDL fallback filename: %s\n", + fdl_file->vendor_id, fdl_file->file_id, + disk_filename, fallback_filename); + ret = -ENOENT; + } else { + dev_info(dev, "loading SWF: %x-%x-%x from %s\n", + swf->vendor_id, swf->file_id, swf->file_version, source); + + ret = sdca_ump_write_message(dev, interrupt->device_regmap, + interrupt->function_regmap, + interrupt->function, interrupt->entity, + SDCA_CTL_XU_FDL_MESSAGEOFFSET, + fdl_file->fdl_offset, + SDCA_CTL_XU_FDL_MESSAGELENGTH, swf->data, + swf->file_length - + offsetof(struct acpi_sw_file, data)); } - dev_info(dev, "loading SWF: %x-%x-%x\n", - swf->vendor_id, swf->file_id, swf->file_version); + kfree(disk_filename); + kfree(fallback_filename); - ret = sdca_ump_write_message(dev, interrupt->device_regmap, - interrupt->function_regmap, - interrupt->function, interrupt->entity, - SDCA_CTL_XU_FDL_MESSAGEOFFSET, fdl_file->fdl_offset, - SDCA_CTL_XU_FDL_MESSAGELENGTH, swf->data, - swf->file_length - offsetof(struct acpi_sw_file, data)); return ret; } From 1c1cd016da78596e33b14957ba3d61379e36e82f Mon Sep 17 00:00:00 2001 From: "James X. Nelson" Date: Sat, 21 Nov 2026 21:46:11 -0600 Subject: [PATCH 1650/2102] ASoC: amd: yc: Enable DMIC on MSI Crosshair A18 HX A8WGKG On the MSI Crosshair A18 HX A8WGKG (MS-184L), the ACP6x PCI function binds and the DMIC platform devices are created, but the machine driver does not register the capture card through the firmware detection path. Add an exact DMI match so the existing ACP6x machine driver exposes the internal microphone on this model, without affecting other MSI models. Tested on an A8WGKG, board MS-184L, BIOS E184LAMS.10B with Ubuntu OEM 7.3.0-1004-oem. The patched module logged "Enabling ACP DMIC support via DMI", and ALSA enumerated the DMIC capture device. After WirePlumber reprobed the audio card, speech from the built-in microphone was captured in Google Meet. ChatGPT/Codex helped diagnose the driver binding failure and draft the quirk and this changelog. The submitter performed the live microphone test. Link: https://bugs.launchpad.net/bugs/2175499 Signed-off-by: James X. Nelson Link: https://patch.msgid.link/20261122034611.26008-1-James@WeTheInter.net Signed-off-by: Mark Brown --- sound/soc/amd/yc/acp6x-mach.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sound/soc/amd/yc/acp6x-mach.c b/sound/soc/amd/yc/acp6x-mach.c index 766d493ba9cb2c..3e4626b968fa5f 100644 --- a/sound/soc/amd/yc/acp6x-mach.c +++ b/sound/soc/amd/yc/acp6x-mach.c @@ -584,6 +584,14 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { DMI_MATCH(DMI_PRODUCT_NAME, "Crosshair A16 HX D7WFKG"), } }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_EXACT_MATCH(DMI_BOARD_VENDOR, "Micro-Star International Co., Ltd."), + DMI_EXACT_MATCH(DMI_BOARD_NAME, "MS-184L"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Crosshair A18 HX A8WGKG"), + } + }, { .driver_data = &acp6x_card, .matches = { From 98fe26341049d608347f4a2830791c8fb2d8cf17 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Mon, 16 Nov 2026 18:02:12 +0700 Subject: [PATCH 1651/2102] ASoC: atmel: mchp-pdmc: Clear busy_stream in hw_free() busy_stream is set in hw_params() but only cleared in remove(), so the "Audio Filter" and "SINC Filter Order" controls keep returning -EBUSY after the first hw_params(). Add a hw_free() callback that clears busy_stream, to balance hw_params(), and drop the reset from remove(). Fixes: 2ed1a4a5c005 ("ASoC: atmel: mchp-pdmc: Retain Non-Runtime Controls") Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261116110212.522478-1-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-pdmc.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/sound/soc/atmel/mchp-pdmc.c b/sound/soc/atmel/mchp-pdmc.c index 039b2eba0d9de5..8b55d864f3d5fc 100644 --- a/sound/soc/atmel/mchp-pdmc.c +++ b/sound/soc/atmel/mchp-pdmc.c @@ -614,6 +614,15 @@ static int mchp_pdmc_hw_params(struct snd_pcm_substream *substream, return 0; } +static int mchp_pdmc_hw_free(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct mchp_pdmc *dd = snd_soc_dai_get_drvdata(dai); + + atomic_set(&dd->busy_stream, 0); + return 0; +} + static void mchp_pdmc_noise_filter_workaround(struct mchp_pdmc *dd) { u32 tmp, steps = 16; @@ -748,6 +757,7 @@ static const struct snd_soc_dai_ops mchp_pdmc_dai_ops = { .set_fmt = mchp_pdmc_set_fmt, .startup = mchp_pdmc_startup, .hw_params = mchp_pdmc_hw_params, + .hw_free = mchp_pdmc_hw_free, .trigger = mchp_pdmc_trigger, .pcm_new = &mchp_pdmc_pcm_new, .auto_selectable_formats = &mchp_selectable_formats, @@ -1121,8 +1131,6 @@ static void mchp_pdmc_remove(struct platform_device *pdev) { struct mchp_pdmc *dd = platform_get_drvdata(pdev); - atomic_set(&dd->busy_stream, 0); - if (!pm_runtime_status_suspended(dd->dev)) mchp_pdmc_runtime_suspend(dd->dev); From 673701e1c6bbf96fa93283cd19dd3f9092f8fa32 Mon Sep 17 00:00:00 2001 From: Brian Norris Date: Thu, 12 Nov 2026 11:19:37 -0800 Subject: [PATCH 1652/2102] ASoC: codecs: lpass: Discard pm_runtime_put_autosuspend() return values Printing warning messages on pm_runtime_put_autosuspend() returning negative values is not particularly useful. Returning an error code from pm_runtime_put_autosuspend() merely means that it has not queued up a timer or work item to check whether or not the device can be suspended and there are many perfectly valid situations in which that can happen, like after writing "on" to the device's runtime PM "control" attribute in sysfs for one example. Accordingly, update the LPASS macro codec drivers to simply discard the return value of pm_runtime_put_autosuspend(). This will facilitate a planned change of the pm_runtime_put_autosuspend() return type to void in the future, similar to commit 3afd8df02433 ("PM: runtime: Change pm_runtime_put() return type to void"). Signed-off-by: Brian Norris Link: https://patch.msgid.link/20261112111937.RESEND.1.I5cd238b1d4516d4d6980565e0a4e1b83d9abce63@changeid Signed-off-by: Mark Brown --- sound/soc/codecs/lpass-rx-macro.c | 4 +--- sound/soc/codecs/lpass-tx-macro.c | 4 +--- sound/soc/codecs/lpass-va-macro.c | 17 ++++------------- sound/soc/codecs/lpass-wsa-macro.c | 8 ++------ 4 files changed, 8 insertions(+), 25 deletions(-) diff --git a/sound/soc/codecs/lpass-rx-macro.c b/sound/soc/codecs/lpass-rx-macro.c index 5253ad4381888b..eadd52ea263083 100644 --- a/sound/soc/codecs/lpass-rx-macro.c +++ b/sound/soc/codecs/lpass-rx-macro.c @@ -3957,9 +3957,7 @@ static int rx_macro_probe(struct platform_device *pdev) if (ret) goto err_rpm_put; - ret = pm_runtime_put_autosuspend(dev); - if (ret < 0) - dev_warn(dev, "runtime PM put failed after probe: %d\n", ret); + pm_runtime_put_autosuspend(dev); return 0; diff --git a/sound/soc/codecs/lpass-tx-macro.c b/sound/soc/codecs/lpass-tx-macro.c index 6f2af4907cb84d..45dd079683b056 100644 --- a/sound/soc/codecs/lpass-tx-macro.c +++ b/sound/soc/codecs/lpass-tx-macro.c @@ -2407,9 +2407,7 @@ static int tx_macro_probe(struct platform_device *pdev) if (ret) goto err_rpm_put; - ret = pm_runtime_put_autosuspend(dev); - if (ret < 0) - dev_warn(dev, "runtime PM put failed after probe: %d\n", ret); + pm_runtime_put_autosuspend(dev); return 0; diff --git a/sound/soc/codecs/lpass-va-macro.c b/sound/soc/codecs/lpass-va-macro.c index af8308eacb0baa..eb8c07be92bb35 100644 --- a/sound/soc/codecs/lpass-va-macro.c +++ b/sound/soc/codecs/lpass-va-macro.c @@ -1391,7 +1391,7 @@ static int fsgen_gate_enable(struct clk_hw *hw) { struct va_macro *va = to_va_macro(hw); struct regmap *regmap = va->regmap; - int ret, rpm_ret; + int ret; ret = pm_runtime_resume_and_get(va->dev); if (ret < 0) @@ -1399,11 +1399,7 @@ static int fsgen_gate_enable(struct clk_hw *hw) ret = va_macro_mclk_enable(va, true); if (ret) { - rpm_ret = pm_runtime_put_autosuspend(va->dev); - if (rpm_ret < 0) - dev_warn(va->dev, - "runtime PM put failed in fsgen enable unwind: %d\n", - rpm_ret); + pm_runtime_put_autosuspend(va->dev); return ret; } if (va->has_swr_master) @@ -1417,7 +1413,6 @@ static void fsgen_gate_disable(struct clk_hw *hw) { struct va_macro *va = to_va_macro(hw); struct regmap *regmap = va->regmap; - int ret; if (va->has_swr_master) regmap_update_bits(regmap, CDC_VA_CLK_RST_CTRL_SWR_CONTROL, @@ -1425,9 +1420,7 @@ static void fsgen_gate_disable(struct clk_hw *hw) va_macro_mclk_enable(va, false); - ret = pm_runtime_put_autosuspend(va->dev); - if (ret < 0) - dev_warn(va->dev, "runtime PM put failed in fsgen disable: %d\n", ret); + pm_runtime_put_autosuspend(va->dev); } static int fsgen_gate_is_enabled(struct clk_hw *hw) @@ -1724,9 +1717,7 @@ static int va_macro_probe(struct platform_device *pdev) goto err_rpm_put; } - rpm_ret = pm_runtime_put_autosuspend(dev); - if (rpm_ret < 0) - dev_warn(dev, "runtime PM put failed after probe: %d\n", rpm_ret); + pm_runtime_put_autosuspend(dev); return 0; diff --git a/sound/soc/codecs/lpass-wsa-macro.c b/sound/soc/codecs/lpass-wsa-macro.c index 2b63954f783b35..f9646d1c09dd5d 100644 --- a/sound/soc/codecs/lpass-wsa-macro.c +++ b/sound/soc/codecs/lpass-wsa-macro.c @@ -2605,9 +2605,7 @@ static int wsa_swrm_clock(struct wsa_macro *wsa, bool enable) CDC_WSA_SWR_CLK_EN_MASK, 0); wsa_macro_mclk_enable(wsa, false); - ret = pm_runtime_put_autosuspend(wsa->dev); - if (ret < 0) - dev_warn(wsa->dev, "runtime PM put failed: %d\n", ret); + pm_runtime_put_autosuspend(wsa->dev); } return 0; @@ -2871,9 +2869,7 @@ static int wsa_macro_probe(struct platform_device *pdev) if (ret) goto err_rpm_put; - ret = pm_runtime_put_autosuspend(dev); - if (ret < 0) - dev_warn(dev, "runtime PM put failed after probe: %d\n", ret); + pm_runtime_put_autosuspend(dev); return 0; err_rpm_put: From ed3284607d65a60fb525ea3dd9417460e1ae66cd Mon Sep 17 00:00:00 2001 From: Brian Norris Date: Thu, 12 Nov 2026 11:19:38 -0800 Subject: [PATCH 1653/2102] ASoC: intel: atom: Discard pm_runtime_put_autosuspend() return value Propagating the pm_runtime_put_autosuspend() return value to callers is not particularly useful. Returning an error code from pm_runtime_put_autosuspend() merely means that it has not queued up a timer or work item to check whether or not the device can be suspended and there are many perfectly valid situations in which that can happen, like after writing "on" to the device's runtime PM "control" attribute in sysfs for one example. Modify sst_pm_runtime_put() to discard the pm_runtime_put_autosuspend() return value, change its return type to void, and update its callers in sst_power_control() accordingly. Note that in one error path for sst_power_control(), we would previously overwrite one error code (from "FW download fail") with the return code from pm_runtime_put_autosuspend(). This was probably an unexpected behavior, which is now changed to propagate the sst_load_fw() error code. This will facilitate a planned change of the pm_runtime_put_autosuspend() return type to void in the future, similar to commit 3afd8df02433 ("PM: runtime: Change pm_runtime_put() return type to void"). Signed-off-by: Brian Norris Acked-by: Cezary Rojewski Link: https://patch.msgid.link/20261112111937.RESEND.2.Ia8792ce5d04a55522d84afc8e71cc879721a5f49@changeid Signed-off-by: Mark Brown --- sound/soc/intel/atom/sst/sst.h | 2 +- sound/soc/intel/atom/sst/sst_drv_interface.c | 4 ++-- sound/soc/intel/atom/sst/sst_pvt.c | 9 ++------- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/sound/soc/intel/atom/sst/sst.h b/sound/soc/intel/atom/sst/sst.h index 4c759ba377ae18..42baeb7df02d21 100644 --- a/sound/soc/intel/atom/sst/sst.h +++ b/sound/soc/intel/atom/sst/sst.h @@ -487,7 +487,7 @@ int get_stream_id_mrfld(struct intel_sst_drv *sst_drv_ctx, u32 relocate_imr_addr_mrfld(u32 base_addr); void sst_add_to_dispatch_list_and_post(struct intel_sst_drv *sst, struct ipc_post *msg); -int sst_pm_runtime_put(struct intel_sst_drv *sst_drv); +void sst_pm_runtime_put(struct intel_sst_drv *sst_drv); int sst_shim_write(void __iomem *addr, int offset, int value); u32 sst_shim_read(void __iomem *addr, int offset); u64 sst_reg_read64(void __iomem *addr, int offset); diff --git a/sound/soc/intel/atom/sst/sst_drv_interface.c b/sound/soc/intel/atom/sst/sst_drv_interface.c index 2646c4632ca1ca..c99697b975d836 100644 --- a/sound/soc/intel/atom/sst/sst_drv_interface.c +++ b/sound/soc/intel/atom/sst/sst_drv_interface.c @@ -135,13 +135,13 @@ static int sst_power_control(struct device *dev, bool state) if (ret) { dev_err(dev, "FW download fail %d\n", ret); sst_set_fw_state_locked(ctx, SST_RESET); - ret = sst_pm_runtime_put(ctx); + sst_pm_runtime_put(ctx); } } } else { usage_count = GET_USAGE_COUNT(dev); dev_dbg(ctx->dev, "Disable: pm usage count: %d\n", usage_count); - return sst_pm_runtime_put(ctx); + sst_pm_runtime_put(ctx); } return ret; } diff --git a/sound/soc/intel/atom/sst/sst_pvt.c b/sound/soc/intel/atom/sst/sst_pvt.c index 0b0cfd70efbc26..913e232bf6ed98 100644 --- a/sound/soc/intel/atom/sst/sst_pvt.c +++ b/sound/soc/intel/atom/sst/sst_pvt.c @@ -255,14 +255,9 @@ int sst_prepare_and_post_msg(struct intel_sst_drv *sst, return ret; } -int sst_pm_runtime_put(struct intel_sst_drv *sst_drv) +void sst_pm_runtime_put(struct intel_sst_drv *sst_drv) { - int ret; - - ret = pm_runtime_put_autosuspend(sst_drv->dev); - if (ret < 0) - return ret; - return 0; + pm_runtime_put_autosuspend(sst_drv->dev); } void sst_fill_header_mrfld(union ipc_header_mrfld *header, From cbe3a1192e7cfd6ee46426f7f037f1b7e777f15e Mon Sep 17 00:00:00 2001 From: Brian Norris Date: Thu, 12 Nov 2026 11:19:39 -0800 Subject: [PATCH 1654/2102] ASoC: SOF: Discard pm_runtime_put_autosuspend() return values Printing error messages on pm_runtime_put_autosuspend() returning negative values is not particularly useful. Returning an error code from pm_runtime_put_autosuspend() merely means that it has not queued up a timer or work item to check whether or not the device can be suspended and there are many perfectly valid situations in which that can happen, like after writing "on" to the device's runtime PM "control" attribute in sysfs for one example. Accordingly, update the SOF driver to simply discard the return value of pm_runtime_put_autosuspend(). This will facilitate a planned change of the pm_runtime_put_autosuspend() return type to void in the future, similar to commit 3afd8df02433 ("PM: runtime: Change pm_runtime_put() return type to void"). Signed-off-by: Brian Norris Link: https://patch.msgid.link/20261112111937.RESEND.3.I90762189ee6537c5deb0725ede365d641607377e@changeid Signed-off-by: Mark Brown --- sound/soc/sof/control.c | 6 ++---- sound/soc/sof/sof-client-ipc-flood-test.c | 5 +---- sound/soc/sof/sof-client-ipc-kernel-injector.c | 4 +--- sound/soc/sof/sof-client-ipc-msg-injector.c | 6 ++---- sound/soc/sof/sof-client-probes.c | 18 ++++++------------ 5 files changed, 12 insertions(+), 27 deletions(-) diff --git a/sound/soc/sof/control.c b/sound/soc/sof/control.c index 74d997a4f6203c..8718c293c5b9a9 100644 --- a/sound/soc/sof/control.c +++ b/sound/soc/sof/control.c @@ -185,7 +185,7 @@ int snd_sof_bytes_ext_volatile_get(struct snd_kcontrol *kcontrol, unsigned int _ struct snd_soc_component *scomp = scontrol->scomp; struct snd_sof_dev *sdev = snd_soc_component_get_drvdata(scomp); const struct sof_ipc_tplg_ops *tplg_ops = sof_ipc_get_ops(sdev, tplg); - int ret, err; + int ret; /* ignore the ext_volatile_get call if the callbacks are not provided */ if (!tplg_ops || !tplg_ops->control || @@ -205,9 +205,7 @@ int snd_sof_bytes_ext_volatile_get(struct snd_kcontrol *kcontrol, unsigned int _ binary_data, size); - err = pm_runtime_put_autosuspend(scomp->dev); - if (err < 0) - dev_err_ratelimited(scomp->dev, "%s: failed to idle %d\n", __func__, err); + pm_runtime_put_autosuspend(scomp->dev); return ret; } diff --git a/sound/soc/sof/sof-client-ipc-flood-test.c b/sound/soc/sof/sof-client-ipc-flood-test.c index 0e8a0262b795ac..b0d8419addc72b 100644 --- a/sound/soc/sof/sof-client-ipc-flood-test.c +++ b/sound/soc/sof/sof-client-ipc-flood-test.c @@ -157,7 +157,6 @@ static ssize_t sof_ipc_flood_dfs_write(struct file *file, const char __user *buf unsigned long ipc_duration_ms = 0; bool flood_duration_test = false; unsigned long ipc_count = 0; - int err; char *string; int ret; @@ -223,9 +222,7 @@ static ssize_t sof_ipc_flood_dfs_write(struct file *file, const char __user *buf ret = sof_debug_ipc_flood_test(cdev, flood_duration_test, ipc_duration_ms, ipc_count); - err = pm_runtime_put_autosuspend(dev); - if (err < 0) - dev_err_ratelimited(dev, "debugfs write failed to idle %d\n", err); + pm_runtime_put_autosuspend(dev); /* return count if test is successful */ if (ret >= 0) diff --git a/sound/soc/sof/sof-client-ipc-kernel-injector.c b/sound/soc/sof/sof-client-ipc-kernel-injector.c index b5bca9258f4251..16deb117b7b955 100644 --- a/sound/soc/sof/sof-client-ipc-kernel-injector.c +++ b/sound/soc/sof/sof-client-ipc-kernel-injector.c @@ -66,9 +66,7 @@ static ssize_t sof_kernel_msg_inject_dfs_write(struct file *file, const char __u if (!ret) sof_client_ipc_rx_message(cdev, hdr, priv->kernel_buffer); - ret = pm_runtime_put_autosuspend(dev); - if (ret < 0) - dev_err_ratelimited(dev, "debugfs write failed to idle %d\n", ret); + pm_runtime_put_autosuspend(dev); return count; }; diff --git a/sound/soc/sof/sof-client-ipc-msg-injector.c b/sound/soc/sof/sof-client-ipc-msg-injector.c index c98307cf7eeee6..bd10fb39457aae 100644 --- a/sound/soc/sof/sof-client-ipc-msg-injector.c +++ b/sound/soc/sof/sof-client-ipc-msg-injector.c @@ -122,7 +122,7 @@ static int sof_msg_inject_send_message(struct sof_client_dev *cdev) { struct sof_msg_inject_priv *priv = cdev->data; struct device *dev = &cdev->auxdev.dev; - int ret, err; + int ret; ret = pm_runtime_resume_and_get(dev); if (ret < 0 && ret != -EACCES) { @@ -140,9 +140,7 @@ static int sof_msg_inject_send_message(struct sof_client_dev *cdev) dev_err(dev, "IPC message send failed: %d\n", ret); } - err = pm_runtime_put_autosuspend(dev); - if (err < 0) - dev_err_ratelimited(dev, "debugfs write failed to idle %d\n", err); + pm_runtime_put_autosuspend(dev); return ret; } diff --git a/sound/soc/sof/sof-client-probes.c b/sound/soc/sof/sof-client-probes.c index 286486945abd4f..b3ae232e578a6e 100644 --- a/sound/soc/sof/sof-client-probes.c +++ b/sound/soc/sof/sof-client-probes.c @@ -211,7 +211,7 @@ static ssize_t sof_probes_dfs_points_read(struct file *file, char __user *to, int remaining, offset; size_t num_desc; char *buf; - int i, ret, err; + int i, ret; if (priv->extractor_stream_tag == SOF_PROBES_INVALID_NODE_ID) { dev_warn(dev, "no extractor stream running\n"); @@ -258,9 +258,7 @@ static ssize_t sof_probes_dfs_points_read(struct file *file, char __user *to, kfree(desc); pm_error: - err = pm_runtime_put_autosuspend(dev); - if (err < 0) - dev_err_ratelimited(dev, "debugfs read failed to idle %d\n", err); + pm_runtime_put_autosuspend(dev); exit: kfree(buf); @@ -294,7 +292,7 @@ sof_probes_dfs_points_write(struct file *file, const char __user *from, struct sof_probe_point_desc *desc; u32 num_elems, *array; size_t bytes; - int ret, err; + int ret; if (priv->extractor_stream_tag == SOF_PROBES_INVALID_NODE_ID) { dev_warn(dev, "no extractor stream running\n"); @@ -327,9 +325,7 @@ sof_probes_dfs_points_write(struct file *file, const char __user *from, ret = count; } - err = pm_runtime_put_autosuspend(dev); - if (err < 0) - dev_err_ratelimited(dev, "debugfs write failed to idle %d\n", err); + pm_runtime_put_autosuspend(dev); exit: kfree(array); return ret; @@ -360,7 +356,7 @@ sof_probes_dfs_points_remove_write(struct file *file, const char __user *from, struct sof_probes_priv *priv = cdev->data; const struct sof_probes_ipc_ops *ipc = priv->ipc_ops; struct device *dev = &cdev->auxdev.dev; - int ret, err; + int ret; u32 *array; if (priv->extractor_stream_tag == SOF_PROBES_INVALID_NODE_ID) { @@ -385,9 +381,7 @@ sof_probes_dfs_points_remove_write(struct file *file, const char __user *from, ret = count; } - err = pm_runtime_put_autosuspend(dev); - if (err < 0) - dev_err_ratelimited(dev, "debugfs write failed to idle %d\n", err); + pm_runtime_put_autosuspend(dev); exit: kfree(array); return ret; From 573c689219af87f6d5a4bbf809c174e7f28a23a1 Mon Sep 17 00:00:00 2001 From: Elkin Cruz Date: Fri, 20 Nov 2026 19:04:42 +0000 Subject: [PATCH 1655/2102] regmap: guard DEFINE_FREE(regmap_field) against ERR_PTR values regmap_field_alloc() returns ERR_PTR() on allocation failure, never NULL. DEFINE_FREE(regmap_field, ...) currently checks only if (_T), which is true for ERR_PTR() values and causes __free(regmap_field) variables on error paths to pass an error pointer into regmap_field_free() -> kfree(). Guard the cleanup macro with !IS_ERR_OR_NULL(_T). Fixes: 37983fad7f3e ("regmap: define cleanup helper for regmap_field") Signed-off-by: Elkin Cruz Link: https://patch.msgid.link/20261120190442.2851983-1-elkin@google.com Signed-off-by: Mark Brown --- include/linux/regmap.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/linux/regmap.h b/include/linux/regmap.h index 7e888decc9fafd..5c2c95cac9578d 100644 --- a/include/linux/regmap.h +++ b/include/linux/regmap.h @@ -1485,7 +1485,7 @@ struct regmap_field *regmap_field_alloc(struct regmap *regmap, struct reg_field reg_field); void regmap_field_free(struct regmap_field *field); -DEFINE_FREE(regmap_field, struct regmap_field *, if (_T) regmap_field_free(_T)) +DEFINE_FREE(regmap_field, struct regmap_field *, if (!IS_ERR_OR_NULL(_T)) regmap_field_free(_T)) struct regmap_field *devm_regmap_field_alloc(struct device *dev, struct regmap *regmap, struct reg_field reg_field); From 533adbe092cafd04e0efeefa1fe792a58a0a1a57 Mon Sep 17 00:00:00 2001 From: Chen Liu <2508871010@qq.com> Date: Mon, 16 Nov 2026 14:16:10 +0800 Subject: [PATCH 1656/2102] ASoC: wcd937x: bound the DT channel mapping to the channel tables wcd9370_probe() copies qcom,{tx,rx}-channel-mapping into the per-channel tables with the length of the DT property as the loop bound. Nothing checks that the property describes no more channels than wcd937x_sdw_tx_ch_info[] (11 entries) and wcd937x_sdw_rx_ch_info[] (8 entries) hold. The DT binding requires exactly 12 entries for qcom,tx-channel-mapping ("adc1, adc2, adc3, dmic0, dmic1, mbhc, dmic2, dmic3, dmic4, dmic5, dmic6, dmic7"), while the driver's table stops at WCD937X_DMIC6, i.e. 11 channels. Any board that follows the binding therefore writes one entry past the end of the table; both boards in mainline that use the property do so (qcm6490-idp.dts and sm7150-xiaomi-davinci.dtsi both spell out 12 values). Both tables live in .data right next to each other, so the stray write lands in wcd937x_sdw_rx_ch_info[0].ch_mask. The 12th value, 4, stores WCD937X_SWRM_CH_MASK(4) == 0x8 into HPH_L; the codec then asks for SoundWire RX channel 4 (EN_CHAN = 0x8) while the AFE keeps sending two channels (active_channels_mask = 0x3). The CDC DMA never completes a block, the DSP never reports WRITE_DONE, and playback on the RX codec DMA path fails with -EIO after the wait_for_avail() timeout. Bound the length to the scratch buffer before reading the property and to the table size before filling it in, so that an over-long mapping is truncated instead of corrupting the RX table. Only the upper bound is involved: a missing property still yields a negative count, so the existing fallback (the read fails, "Static channel mapping not specified ..." is printed) keeps working unchanged. The overflow was found while debugging RX codec DMA playback (no WRITE_DONE from the DSP, playback failing with -EIO) on an SM7150 phone: a temporary printk showed exactly one entry of the runtime table differing from .data, which led to the 12th iteration of the loop. Diagnosis, patch and this changelog were produced with the help of an AI coding assistant (Claude, Anthropic); the submitter reviewed the change, built it for arm64 with W=1 and verified on that phone that playback now completes and that the codec enables the SoundWire RX channel it actually needs (EN_CHAN = 0x1 for HPH_L) instead of channel 4 (EN_CHAN = 0x8). Not done: qcm6490-idp was not booted, there was no KASAN or reproducer other than the phone, and the DT binding still advertises 12 TX channels while the table holds 11, so the last entry of a conforming mapping is now ignored instead of written out of bounds (binding update left as a follow-up). Fixes: c06c4f7cbea1 ("ASoC: codecs: wcd937x: Add static channel mapping support in wcd937x-sdw") Signed-off-by: Chen Liu <2508871010@qq.com> Link: https://patch.msgid.link/tencent_4D458B8B4F511E5B0F06C5C858627990C306@qq.com Signed-off-by: Mark Brown --- sound/soc/codecs/wcd937x-sdw.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sound/soc/codecs/wcd937x-sdw.c b/sound/soc/codecs/wcd937x-sdw.c index 57549518767ce9..5ad6b30d6555f4 100644 --- a/sound/soc/codecs/wcd937x-sdw.c +++ b/sound/soc/codecs/wcd937x-sdw.c @@ -1003,6 +1003,8 @@ static int wcd9370_probe(struct sdw_slave *pdev, if (wcd->is_tx) { master_ch_mask_size = of_property_count_u8_elems(dev->of_node, "qcom,tx-channel-mapping"); + master_ch_mask_size = min_t(int, master_ch_mask_size, + ARRAY_SIZE(master_ch_mask)); if (master_ch_mask_size) ret = of_property_read_u8_array(dev->of_node, "qcom,tx-channel-mapping", @@ -1010,6 +1012,8 @@ static int wcd9370_probe(struct sdw_slave *pdev, } else { master_ch_mask_size = of_property_count_u8_elems(dev->of_node, "qcom,rx-channel-mapping"); + master_ch_mask_size = min_t(int, master_ch_mask_size, + ARRAY_SIZE(master_ch_mask)); if (master_ch_mask_size) ret = of_property_read_u8_array(dev->of_node, "qcom,rx-channel-mapping", @@ -1023,6 +1027,8 @@ static int wcd9370_probe(struct sdw_slave *pdev, pdev->prop.source_ports = GENMASK(WCD937X_MAX_TX_SWR_PORTS, 0); pdev->prop.src_dpn_prop = wcd937x_dpn_prop; wcd->ch_info = &wcd937x_sdw_tx_ch_info[0]; + master_ch_mask_size = min_t(int, master_ch_mask_size, + ARRAY_SIZE(wcd937x_sdw_tx_ch_info)); for (i = 0; i < master_ch_mask_size; i++) wcd->ch_info[i].master_ch_mask = WCD937X_SWRM_CH_MASK(master_ch_mask[i]); @@ -1040,6 +1046,8 @@ static int wcd9370_probe(struct sdw_slave *pdev, pdev->prop.sink_ports = GENMASK(WCD937X_MAX_SWR_PORTS - 1, 0); pdev->prop.sink_dpn_prop = wcd937x_dpn_prop; wcd->ch_info = &wcd937x_sdw_rx_ch_info[0]; + master_ch_mask_size = min_t(int, master_ch_mask_size, + ARRAY_SIZE(wcd937x_sdw_rx_ch_info)); for (i = 0; i < master_ch_mask_size; i++) wcd->ch_info[i].master_ch_mask = WCD937X_SWRM_CH_MASK(master_ch_mask[i]); From a61c6405b2f9a26786a6c3dd1f56a11275b64b21 Mon Sep 17 00:00:00 2001 From: Ian Rogers Date: Thu, 19 Nov 2026 09:06:56 -0800 Subject: [PATCH 1657/2102] ASoC: rt1320-sdw: Reject unknown dev_id in FU Capture Volume handlers rt1320_sdw_init() registers the ASoC component and its "FU Capture Volume" control before SoundWire peripheral enumeration populates rt1320->dev_id (which starts at 0). Unlike rt1320_set_fu_capture_ctl(), the switch (rt1320->dev_id) blocks in rt1320_set_gain_get() and rt1320_set_gain_put() omit a default case. Reading "FU Capture Volume" before enumeration completes (or with an unrecognized dev_id) leaves 'regvalue' uninitialized on the stack and returns a value derived from it directly to userspace; writing the control similarly reads uninitialized 'regvalue', 'err', and 'reg_base'. Return -EINVAL in the default branch of all three switch statements, matching rt1320_set_fu_capture_ctl(). Found via an x86_64 LLVM=1 (Clang 21.1.8) allyesconfig audit with -Wconditional-uninitialized enabled; fix and changelog drafted with an AI coding assistant. Build-tested under LLVM=1 W=1 (-Werror) and -Wconditional-uninitialized; not tested on Realtek RT1320/RT1321 hardware. Fixes: 7bf9e646af9a ("ASoC: rt1321: Add RT1321 amplifier support") Signed-off-by: Ian Rogers Link: https://patch.msgid.link/20261119170656.1522183-1-irogers@google.com Signed-off-by: Mark Brown --- sound/soc/codecs/rt1320-sdw.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sound/soc/codecs/rt1320-sdw.c b/sound/soc/codecs/rt1320-sdw.c index 19079212ba6c04..6724012d5c09d5 100644 --- a/sound/soc/codecs/rt1320-sdw.c +++ b/sound/soc/codecs/rt1320-sdw.c @@ -2829,6 +2829,8 @@ static int rt1320_set_gain_put(struct snd_kcontrol *kcontrol, reg_base = SDW_SDCA_CTL(FUNC_NUM_MIC, RT1320_SDCA_ENT_FU113, RT1320_SDCA_CTL_FU_VOLUME, CH_01); regmap_read(rt1320->mbq_regmap, reg_base + i, ®value[i]); break; + default: + return -EINVAL; } gain_val[i] = ucontrol->value.integer.value[i]; @@ -2859,6 +2861,8 @@ static int rt1320_set_gain_put(struct snd_kcontrol *kcontrol, reg_base = SDW_SDCA_CTL(FUNC_NUM_MIC, RT1320_SDCA_ENT_FU113, RT1320_SDCA_CTL_FU_VOLUME, CH_01); err = regmap_write(rt1320->mbq_regmap, reg_base + i, gain_val[i]); break; + default: + return -EINVAL; } if (err < 0) @@ -2917,6 +2921,8 @@ static int rt1320_set_gain_get(struct snd_kcontrol *kcontrol, reg_base = SDW_SDCA_CTL(FUNC_NUM_MIC, RT1320_SDCA_ENT_FU113, RT1320_SDCA_CTL_FU_VOLUME, CH_01); regmap_read(rt1320->mbq_regmap, reg_base + i, ®value); break; + default: + return -EINVAL; } ctl = p->max - (((0x1e00 - regvalue) & 0xffff) / interval_offset); From aff174aab7db0052febe8040d41b189e6dde1177 Mon Sep 17 00:00:00 2001 From: Charles Keepax Date: Mon, 23 Nov 2026 11:52:05 +0000 Subject: [PATCH 1658/2102] ASoC: SDCA: Combine width_find_mask() and get_word_mask() Both of these functions take a bit width and return the ALSA mask bits for that width. Remove get_word_mask() and use width_find_mask() in all cases. As part of this the function is expanded with a few additional formats. The big endian versions are added to the mask, for the original dai driver users of width_find_mask() these would be added by the ASoC core, however that isn't true when used for ALSA constraint users of get_word_mask(). The 3LE versions are also added as the memory size shouldn't be a factor once on the SoundWire bus. Finally, support for the unsigned formats is removed relative to get_word_mask(), these are not commonly used and the SoundWire specification has no obvious mechanism to indicate if they are supported. So better these are only added once a user comes forward. Signed-off-by: Charles Keepax Tested-by: Srinivas Kandagatla Reviewed-by: Srinivas Kandagatla Link: https://patch.msgid.link/20261123115205.3498244-1-ckeepax@opensource.cirrus.com Signed-off-by: Mark Brown --- sound/soc/sdca/sdca_asoc.c | 56 ++++++++++++-------------------------- 1 file changed, 18 insertions(+), 38 deletions(-) diff --git a/sound/soc/sdca/sdca_asoc.c b/sound/soc/sdca/sdca_asoc.c index aaa84156f20a84..d58be660ced7f5 100644 --- a/sound/soc/sdca/sdca_asoc.c +++ b/sound/soc/sdca/sdca_asoc.c @@ -1214,19 +1214,28 @@ static u64 width_find_mask(unsigned int bits) { switch (bits) { case 0: - return SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_S16_LE | - SNDRV_PCM_FMTBIT_S20_LE | SNDRV_PCM_FMTBIT_S24_LE | - SNDRV_PCM_FMTBIT_S32_LE; + return SNDRV_PCM_FMTBIT_S8 | + SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE | + SNDRV_PCM_FMTBIT_S18_3LE | SNDRV_PCM_FMTBIT_S18_3BE | + SNDRV_PCM_FMTBIT_S20_LE | SNDRV_PCM_FMTBIT_S20_BE | + SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_S20_3BE | + SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S24_BE | + SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_S24_3BE | + SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S32_BE; case 8: return SNDRV_PCM_FMTBIT_S8; case 16: - return SNDRV_PCM_FMTBIT_S16_LE; + return SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE; + case 18: + return SNDRV_PCM_FMTBIT_S18_3LE | SNDRV_PCM_FMTBIT_S18_3BE; case 20: - return SNDRV_PCM_FMTBIT_S20_LE; + return SNDRV_PCM_FMTBIT_S20_LE | SNDRV_PCM_FMTBIT_S20_BE | + SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_S20_3BE; case 24: - return SNDRV_PCM_FMTBIT_S24_LE; + return SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S24_BE | + SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_S24_3BE; case 32: - return SNDRV_PCM_FMTBIT_S32_LE; + return SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S32_BE; default: return 0; } @@ -1510,35 +1519,6 @@ static int get_cluster_mask(struct device *dev, struct sdca_function_data *funct return 0; } -static u64 get_word_mask(unsigned int width) -{ - switch (width) { - case 8: - return SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_U8; - case 16: - return SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE | - SNDRV_PCM_FMTBIT_U16_LE | SNDRV_PCM_FMTBIT_U16_BE; - case 18: - return SNDRV_PCM_FMTBIT_S18_3LE | SNDRV_PCM_FMTBIT_U18_3LE | - SNDRV_PCM_FMTBIT_S18_3BE | SNDRV_PCM_FMTBIT_U18_3BE; - case 20: - return SNDRV_PCM_FMTBIT_S20_LE | SNDRV_PCM_FMTBIT_U20_LE | - SNDRV_PCM_FMTBIT_S20_BE | SNDRV_PCM_FMTBIT_U20_BE | - SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_U20_3LE | - SNDRV_PCM_FMTBIT_S20_3BE | SNDRV_PCM_FMTBIT_U20_3BE; - case 24: - return SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S24_BE | - SNDRV_PCM_FMTBIT_U24_LE | SNDRV_PCM_FMTBIT_U24_BE | - SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_U24_3LE | - SNDRV_PCM_FMTBIT_S24_3BE | SNDRV_PCM_FMTBIT_U24_3BE; - case 32: - return SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S32_BE | - SNDRV_PCM_FMTBIT_U32_LE | SNDRV_PCM_FMTBIT_U32_BE; - default: - return 0; - } -} - static int get_port_masks(struct sdw_slave *sdw, unsigned int port, struct snd_pcm_substream *substream, u64 *word_mask, unsigned int *ch_mask) @@ -1564,7 +1544,7 @@ static int get_port_masks(struct sdw_slave *sdw, unsigned int port, if (prop[i].num_words) { for (j = 0; j < prop[i].num_words; j++) - *word_mask |= get_word_mask(prop[i].words[j]); + *word_mask |= width_find_mask(prop[i].words[j]); } else { unsigned int max = prop[i].max_word; @@ -1572,7 +1552,7 @@ static int get_port_masks(struct sdw_slave *sdw, unsigned int port, max = 32; for (j = MAX(1, prop[i].min_word); j <= max; j++) - *word_mask |= get_word_mask(j); + *word_mask |= width_find_mask(j); } /* Only handle the number of channels for constraints. */ From 655e2421d693b8829da3ce79942be6f1275965c0 Mon Sep 17 00:00:00 2001 From: Markus Paltian Date: Mon, 23 Nov 2026 22:31:53 +0100 Subject: [PATCH 1659/2102] ASoC: amd: acp: Add Lenovo IdeaPad Slim 5 16AKP10 to ACP70 override table The internal mic of the Lenovo IdeaPad Slim 5 16AKP10 (83HY) is wired to the Conexant SN6140 HDA codec, but the BIOS still sets the ACP ACPI config flag. Add 83HY to the override table, as for the Lenovo models 83W5, 83V9, 83HN and 83Q6. Signed-off-by: Markus Paltian Link: https://patch.msgid.link/20261123213153.51026-1-paltian@gmx.de Signed-off-by: Mark Brown --- sound/soc/amd/acp-config.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/sound/soc/amd/acp-config.c b/sound/soc/amd/acp-config.c index d311ccc5131f3d..8affa0d9f5b6f2 100644 --- a/sound/soc/amd/acp-config.c +++ b/sound/soc/amd/acp-config.c @@ -72,6 +72,13 @@ static const struct dmi_system_id acp70_acpi_flag_override_table[] = { DMI_MATCH(DMI_PRODUCT_NAME, "83Q6"), }, }, + { + /* Lenovo IdeaPad Slim 5 16AKP10 (Krackan Point, ACP 7.0) */ + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "LENOVO"), + DMI_MATCH(DMI_PRODUCT_NAME, "83HY"), + }, + }, { .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK COMPUTER INC"), From b4dbaf7b9352db907f7d7b87a0091fea6bbccf5e Mon Sep 17 00:00:00 2001 From: Andrey Zakharov Date: Tue, 24 Nov 2026 14:36:55 +0300 Subject: [PATCH 1660/2102] firmware: cs_dsp: Replace strlcat() with seq_buf in KUnit tests strlcat() is being removed from the kernel. It runs an unbounded strlen() on the destination, and its size argument is not tied to the real buffer, see the issue below. The bin and wmfw tests fill a 512 byte buffer with a repeated string by calling strlcat() in a loop, and use the return value to detect that the buffer is full. Use seq_buf_init() and seq_buf_puts() and stop when seq_buf_has_overflowed() is true. kunit_kzalloc() returns a zeroed buffer, so seq_buf_init() is enough here. Tested: built with gcc 16.2.1 and ran the cs_dsp KUnit suites under QEMU (x86_64, kunit.py, REGMAP_BUILD): 5829 of 5829 tests pass, the same as without the patch. The tests do not look at the contents of the buffer, so I also checked it with a temporary assertion after the loop: strlen(infobuf) is 511 with the old strlcat() loop and with the new code, and the assertion fails if 510 is expected. Not tested: other architectures and any real hardware. Link: https://github.com/KSPP/linux/issues/370 Signed-off-by: Andrey Zakharov Reviewed-by: Richard Fitzgerald Link: https://patch.msgid.link/20261124113655.610791-1-dedemorow@gmail.com Signed-off-by: Mark Brown --- drivers/firmware/cirrus/test/cs_dsp_test_bin.c | 7 +++++-- drivers/firmware/cirrus/test/cs_dsp_test_wmfw.c | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/drivers/firmware/cirrus/test/cs_dsp_test_bin.c b/drivers/firmware/cirrus/test/cs_dsp_test_bin.c index 63416838f8653a..2f44b7a6e63791 100644 --- a/drivers/firmware/cirrus/test/cs_dsp_test_bin.c +++ b/drivers/firmware/cirrus/test/cs_dsp_test_bin.c @@ -17,6 +17,7 @@ #include #include #include +#include #include "../cs_dsp.h" @@ -2109,6 +2110,7 @@ static void bin_patch_name_and_info(struct kunit *test) unsigned int reg_inc_per_word = cs_dsp_mock_reg_addr_inc_per_unpacked_word(priv); u32 reg_val, payload_data; char *infobuf; + struct seq_buf sb; unsigned int alg_base_words, reg_addr; struct firmware *fw; @@ -2126,8 +2128,9 @@ static void bin_patch_name_and_info(struct kunit *test) infobuf = kunit_kzalloc(test, 512, GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, infobuf); - for (; strlcat(infobuf, "Waffle{Blah}\n", 512) < 512; ) - ; + seq_buf_init(&sb, infobuf, 512); + while (!seq_buf_has_overflowed(&sb)) + seq_buf_puts(&sb, "Waffle{Blah}\n"); cs_dsp_mock_bin_add_info(priv->local->bin_builder, infobuf); diff --git a/drivers/firmware/cirrus/test/cs_dsp_test_wmfw.c b/drivers/firmware/cirrus/test/cs_dsp_test_wmfw.c index 1de70e81a8687d..464a0cc79415e1 100644 --- a/drivers/firmware/cirrus/test/cs_dsp_test_wmfw.c +++ b/drivers/firmware/cirrus/test/cs_dsp_test_wmfw.c @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -1722,6 +1723,7 @@ static void wmfw_load_with_info(struct kunit *test) unsigned int reg_addr; u8 *payload_data, *readback; char *infobuf; + struct seq_buf sb; const unsigned int payload_size_bytes = 48; int ret; @@ -1745,8 +1747,9 @@ static void wmfw_load_with_info(struct kunit *test) infobuf = kunit_kzalloc(test, 512, GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, infobuf); - for (; strlcat(infobuf, "Waffle{Blah}\n", 512) < 512;) - ; + seq_buf_init(&sb, infobuf, 512); + while (!seq_buf_has_overflowed(&sb)) + seq_buf_puts(&sb, "Waffle{Blah}\n"); cs_dsp_mock_wmfw_add_info(local->wmfw_builder, infobuf); cs_dsp_mock_wmfw_add_info(local->wmfw_builder, "Another block of info"); From 2f49d514266a790fc13ac480b80f489132f7a703 Mon Sep 17 00:00:00 2001 From: Qianghua Wang Date: Tue, 17 Nov 2026 14:02:13 +0800 Subject: [PATCH 1661/2102] ASoC: sn624x: skip DMIC when ACPI DisCo has no MIC function Some OEM platforms, such as certain Samsung designs, use Senary SN624x for headset jack and speaker playback only: ACPI _DSD DisCo describes jack and speaker amp SDCA functions but omits the MIC array function because no on-board DMIC is routed to the codec. The driver still advertised the DMIC capture port and ran DMIC function init against registers that DisCo does not expose, which breaks bring-up on these machines. Probe the parsed DisCo function list before exposing the DMIC port and before running DMIC init. Apply AMP function init from the ACPI init tables when an amp function is present, using the same pattern as the existing jack and DMIC paths. Only omit DMIC when DisCo is present but lists no MIC function, so platforms without DisCo still use the OEM DMIC fallback. Do not fail amp init when there is no ACPI init table. Re-apply amp init tables after re-attach when FUN STATUS is idle but DisCo still supplies a table. Fixes: 12d9c9f8679c ("ASoC: codecs: add SN624x SDCA SoundWire driver") Signed-off-by: Qianghua Wang Link: https://patch.msgid.link/20261117060213.2327503-1-qianghua.wang@senarytech.com Signed-off-by: Mark Brown --- sound/soc/codecs/sn624x-sdca-sdw.c | 101 +++++++++++++++++++++++++++-- 1 file changed, 97 insertions(+), 4 deletions(-) diff --git a/sound/soc/codecs/sn624x-sdca-sdw.c b/sound/soc/codecs/sn624x-sdca-sdw.c index af6c0e7769b1e9..734c7eb91d908a 100644 --- a/sound/soc/codecs/sn624x-sdca-sdw.c +++ b/sound/soc/codecs/sn624x-sdca-sdw.c @@ -176,6 +176,9 @@ static int sn624x_uaj_ge35_apply_detected_mode(struct device *dev, SDW_SDCA_CTL(SN624X_FUNC_NUM_MIC_ARRAY, SN624X_SDCA_ENT_ENTITY0, \ SN624X_SDCA_CTL_FUNCTION_STATUS, 0) +#define SN624X_REG_AMP_FUN_STATUS_CTL \ + SDW_SDCA_CTL(SN624X_FUNC_NUM_SPEAKER_AMP, SN624X_SDCA_ENT_ENTITY0, \ + SN624X_SDCA_CTL_FUNCTION_STATUS, 0) /* * Write REQUESTED_PS then poll ACTUAL_PS with the shared SDCA helper * (sdca_asoc_pde_poll_actual_ps). Caller must not hand-roll ACTUAL_PS waits. @@ -1055,6 +1058,49 @@ static int sn624x_dmic_apply_defaults(struct device *dev, return sn624x_dmic_oem_fallback_init(dev, sn624x); } +/* + * Return true only when ACPI DisCo is present and lists no MIC function. + * Without DisCo, return false so the legacy OEM fallback path still runs. + */ +static bool sn624x_sdca_disco_omits_mic(const struct sdw_slave *slave) +{ + int i; + + if (!slave->sdca_data.interface_revision || !slave->sdca_data.num_functions) + return false; + for (i = 0; i < slave->sdca_data.num_functions; i++) { + const struct sdca_function_desc *desc = &slave->sdca_data.function[i]; + + if (desc->adr == SN624X_FUNC_NUM_MIC_ARRAY) + return false; + switch (desc->type) { + case SDCA_FUNCTION_TYPE_SMART_MIC: + case SDCA_FUNCTION_TYPE_SIMPLE_MIC: + return false; + default: + break; + } + } + return true; +} + +static int sn624x_amp_apply_defaults(struct device *dev, + struct sn624x_sdca_priv *sn624x) +{ + int ret; + + if (!sn624x || !sn624x->regmap || !sn624x->slave) + return -ENODEV; + if (!sn624x->amp_func) + return 0; + ret = sn624x_write_sdca_init_table(dev, sn624x, sn624x->amp_func, "amp"); + if (ret == -ENOENT) + return 0; + if (ret == 0) + usleep_range(1000, 1500); + return ret; +} + static int sn624x_sdca_jack_function_init(struct device *dev, struct sn624x_sdca_priv *sn624x) { @@ -1088,11 +1134,18 @@ static int sn624x_sdca_jack_function_init(struct device *dev, static int sn624x_sdca_dmic_function_init(struct device *dev, struct sn624x_sdca_priv *sn624x) { + struct sdw_slave *slave = sn624x->slave; unsigned int dmic_func_status; const struct reg_sequence clear_status = REG_SEQ0(SN624X_REG_DMIC_FUN_STATUS_CTL, 0x61); int ret; + if (sn624x_sdca_disco_omits_mic(slave)) { + dev_dbg(dev, + "sn624x: ACPI DisCo has no MIC function, skip DMIC init\n"); + return 0; + } + ret = regmap_read_bypassed(sn624x->regmap, SN624X_REG_DMIC_FUN_STATUS_CTL, &dmic_func_status); @@ -1104,6 +1157,39 @@ static int sn624x_sdca_dmic_function_init(struct device *dev, return 0; ret = sn624x_dmic_apply_defaults(dev, sn624x); + if (ret < 0) + return ret; + ret = regmap_multi_reg_write_bypassed(sn624x->regmap, &clear_status, 1); + if (ret < 0) + return ret; + usleep_range(1000, 1500); + return 0; +} + +static int sn624x_sdca_amp_function_init(struct device *dev, + struct sn624x_sdca_priv *sn624x) +{ + unsigned int amp_func_status; + const struct reg_sequence clear_status = + REG_SEQ0(SN624X_REG_AMP_FUN_STATUS_CTL, 0x61); + int ret; + + if (!sn624x->amp_func) + return 0; + ret = regmap_read_bypassed(sn624x->regmap, + SN624X_REG_AMP_FUN_STATUS_CTL, + &_func_status); + if (ret < 0) + return ret; + if (!(amp_func_status & (SN624X_JACK_FUN_NEEDS_INIT | + SN624X_JACK_FUN_HAS_BEEN_RESET))) { + if (!sn624x->amp_func->num_init_table) + return 0; + dev_dbg(dev, + "sn624x: amp FUN STATUS 0x%x, apply ACPI init table\n", + amp_func_status); + } + ret = sn624x_amp_apply_defaults(dev, sn624x); if (ret < 0) return ret; @@ -1161,6 +1247,11 @@ static int sn624x_sdca_io_init(struct device *dev, struct sdw_slave *slave) dev_err(dev, "sn624x: jack function init failed (%d)\n", ret); goto err; } + ret = sn624x_sdca_amp_function_init(dev, sn624x); + if (ret < 0) { + dev_err(dev, "sn624x: amp function init failed (%d)\n", ret); + goto err; + } ret = sn624x_sdca_dmic_function_init(dev, sn624x); if (ret < 0) { @@ -1253,8 +1344,9 @@ static int sn624x_sdca_read_prop(struct sdw_slave *slave) prop->use_domain_irq = true; prop->wake_capable = true; - prop->source_ports = BIT(SN624X_PORT_JACK_CAPTURE) | - BIT(SN624X_PORT_DMIC_CAPTURE); + prop->source_ports = BIT(SN624X_PORT_JACK_CAPTURE); + if (!sn624x_sdca_disco_omits_mic(slave)) + prop->source_ports |= BIT(SN624X_PORT_DMIC_CAPTURE); prop->sink_ports = BIT(SN624X_PORT_JACK_PLAYBACK) | BIT(SN624X_PORT_SPEAKER_PLAYBACK); @@ -1292,8 +1384,9 @@ static int sn624x_sdca_read_prop(struct sdw_slave *slave) prop->simple_clk_stop_capable = true; prop->lane_control_support = true; SN624X_DBG(&slave->dev, - "read_prop: src_ports=0x%x sink_ports=0x%x lane irq paging\n", - prop->source_ports, prop->sink_ports); + "read_prop: src_ports=0x%x sink_ports=0x%x disco_omits_mic=%d lane irq paging\n", + prop->source_ports, prop->sink_ports, + sn624x_sdca_disco_omits_mic(slave)); return 0; } From 2ebfb7a793b7da25ab767bcbf7bd753a27ca98f7 Mon Sep 17 00:00:00 2001 From: Ankit Nautiyal Date: Sun, 25 Oct 2026 18:17:20 +0530 Subject: [PATCH 1662/2102] drm/i915/dsc: Fix QP table index calculation for bpp selection The QP table rows increment in steps of 0.5 bpp, meaning each integer bpp step corresponds to 2 rows in the table. While refactoring the index calculation to support fractional bpp, the multiplier of 2 was dropped for the integer bpp portion. Also, the check for a fractional bpp of 0.5 or more compared fractional_bits against 5000 which was a leftover threshold from an earlier decimal-scaled (*10000) version of the change. Restore the missing factor of 2 in the integer part of the bpp calculation, and compare fractional_bits against 8 (0.5 in Q4 format, i.e. 8/16) instead of 5000, to correctly align the QP selection with the table layout. Also fix a typo in the native_420 comment: the second bpp sub-range was written as 4.5 to 4.8375 instead of 4.5 to 4.9375, inconsistent with the 9.875 value it maps to. v2: - Fix fractional_bits threshold. (Sashiko) - Fix typo in native_420 comment (4.8375 -> 4.9375). Fixes: 2df50cb46a4c ("drm/i915/dsc/mtl: Add support for fractional bpp") Cc: Ankit Nautiyal Cc: Suraj Kandpal Cc: Sui Jingfeng Cc: # v6.8+ Suggested-by: Ivan Aslamov Signed-off-by: Ankit Nautiyal Reviewed-by: Suraj Kandpal Reviewed-by: Krzysztof Karas Link: https://patch.msgid.link/20261025124720.953439-1-ankit.k.nautiyal@intel.com (cherry picked from commit e94662a4422098fffc71275c0440de1706d7bec8) Signed-off-by: Joonas Lahtinen --- drivers/gpu/drm/i915/display/intel_vdsc.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/i915/display/intel_vdsc.c b/drivers/gpu/drm/i915/display/intel_vdsc.c index 8f06c3a4d56dfd..a6556a6e45b7d3 100644 --- a/drivers/gpu/drm/i915/display/intel_vdsc.c +++ b/drivers/gpu/drm/i915/display/intel_vdsc.c @@ -211,7 +211,7 @@ calculate_rc_params(struct drm_dsc_config *vdsc_cfg) * For 420 format since bits_per_pixel (bpp) is set to target bpp * 2, * QP table values for target bpp 4.0 to 4.4375 (rounded to 4.0) are * actually for bpp 8 to 8.875 (rounded to 4.0 * 2 i.e 8). - * Similarly values for target bpp 4.5 to 4.8375 (rounded to 4.5) + * Similarly values for target bpp 4.5 to 4.9375 (rounded to 4.5) * are for bpp 9 to 9.875 (rounded to 4.5 * 2 i.e 9), and so on. */ bpp_i = bpp - 8; @@ -239,7 +239,7 @@ calculate_rc_params(struct drm_dsc_config *vdsc_cfg) range_bpg_offset & DSC_RANGE_BPG_OFFSET_MASK; } } else { - /* fractional bpp part * 10000 (for precision up to 4 decimal places) */ + /* fractional bpp part, in Q4 format */ int fractional_bits = fxp_q4_to_frac(vdsc_cfg->bits_per_pixel); static const s8 ofs_und6[] = { @@ -259,9 +259,9 @@ calculate_rc_params(struct drm_dsc_config *vdsc_cfg) * QP table rows have values in increment of 0.5. * So 6.0 bpp to 6.4375 will have index 0, 6.5 to 6.9375 will have index 1, * and so on. - * 0.5 fractional part with 4 decimal precision becomes 5000 + * 0.5 in Q4 fractional format is 8 (i.e. 8/16) */ - bpp_i = ((bpp - 6) + (fractional_bits < 5000 ? 0 : 1)); + bpp_i = (2 * (bpp - 6) + (fractional_bits < 8 ? 0 : 1)); for (buf_i = 0; buf_i < DSC_NUM_BUF_RANGES; buf_i++) { u8 range_bpg_offset; From c84770eb363544f58caba7350e5790134c5cff1e Mon Sep 17 00:00:00 2001 From: Ankit Nautiyal Date: Sat, 14 Nov 2026 12:31:14 +0530 Subject: [PATCH 1663/2102] drm/i915/dsc: Fix the helper range_bpg_offset() The helper used to compute range_bpg_offset() uses an incorrect divisor, causing the interpolation to occur in the reverse direction. This can result in incorrect DSC parameters and visual corruption on some panels. Correct the divisor used by the helper. Closes: https://gitlab.freedesktop.org/drm/xe/kernel/-/work_items/9247 Fixes: 3abe2824e1af ("drm/i915/dsc: Use helper to calculate range_bpg_offset") Cc: Ankit Nautiyal Cc: Suraj Kandpal Cc: Krzysztof Karas Cc: # v6.15+ Suggested-by: Ivan Aslamov Signed-off-by: Ankit Nautiyal Reviewed-by: Suraj Kandpal Reviewed-by: Krzysztof Karas Link: https://patch.msgid.link/20261114070114.3308451-1-ankit.k.nautiyal@intel.com (cherry picked from commit 12b7a4c7d991071a086ec5ae2ec019ab9459b2d9) Signed-off-by: Joonas Lahtinen --- drivers/gpu/drm/i915/display/intel_vdsc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/i915/display/intel_vdsc.c b/drivers/gpu/drm/i915/display/intel_vdsc.c index a6556a6e45b7d3..7a6452557a0caf 100644 --- a/drivers/gpu/drm/i915/display/intel_vdsc.c +++ b/drivers/gpu/drm/i915/display/intel_vdsc.c @@ -122,7 +122,7 @@ static int get_range_bpg_offset(int bpp_low, int offset_low, int bpp_high, int offset_high, int bpp) { return offset_low + DIV_ROUND_UP((offset_high - offset_low) * (bpp - bpp_low), - (bpp_low - bpp_high)); + (bpp_high - bpp_low)); } /* From 202103f76df364623ef3f64303f4ed070d41476b Mon Sep 17 00:00:00 2001 From: Ankit Nautiyal Date: Fri, 13 Nov 2026 17:41:06 +0530 Subject: [PATCH 1664/2102] drm/i915/bios: Add quirk to allow eDP joiner on ASUS ROG Strix SCAR 18 On Arrow Lake, VBT defaults the eDP pipe joiner enable bit to disabled, and commit 650471948e49 ("drm/i915/dp: Avoid joiner for eDP if not enabled in VBT") made the driver honor that default. On the ASUS ROG Strix SCAR 18 (G835LXG), the bit in VBT is left to the platform default instead of enabling it, even though the 3840x2400@240Hz panel requires the joiner to reach its native mode. As a result the mode is pruned and the panel is limited to 120Hz. Since the VBT bit cannot be relied upon globally for ARL (it is needed to block the joiner on at least one other machine), add a machine-specific quirk, to bypass the VBT restriction and allow the joiner on this machine. v2: set panel->vbt.edp.pipe_joiner_enable directly in intel_bios.c (Jani) Fixes: 650471948e49 ("drm/i915/dp: Avoid joiner for eDP if not enabled in VBT") Cc: Suraj Kandpal Cc: Jani Nikula Cc: # v7.1+ Closes: https://gitlab.freedesktop.org/drm/i915/kernel/-/work_items/16854 Signed-off-by: Ankit Nautiyal Reviewed-by: Suraj Kandpal Link: https://patch.msgid.link/20261113121106.3241899-1-ankit.k.nautiyal@intel.com (cherry picked from commit 6d00cec4c9becea6540f75820bc0837d14ea7611) Signed-off-by: Joonas Lahtinen --- drivers/gpu/drm/i915/display/intel_bios.c | 5 +++++ drivers/gpu/drm/i915/display/intel_quirks.c | 13 +++++++++++++ drivers/gpu/drm/i915/display/intel_quirks.h | 1 + 3 files changed, 19 insertions(+) diff --git a/drivers/gpu/drm/i915/display/intel_bios.c b/drivers/gpu/drm/i915/display/intel_bios.c index 7b6a6f8c3cf196..b77d1599482a76 100644 --- a/drivers/gpu/drm/i915/display/intel_bios.c +++ b/drivers/gpu/drm/i915/display/intel_bios.c @@ -41,6 +41,7 @@ #include "intel_display_types.h" #include "intel_display_utils.h" #include "intel_gmbus.h" +#include "intel_quirks.h" #include "intel_rom.h" #include "intel_vdsc.h" @@ -1575,6 +1576,10 @@ parse_edp(struct intel_display *display, if (display->vbt.version >= 261) panel->vbt.edp.pipe_joiner_enable = panel_bool(edp->pipe_joiner_enable, panel_type); + + /* Some machines need the joiner regardless of what VBT says */ + if (intel_has_quirk(display, QUIRK_ALLOW_EDP_JOINER)) + panel->vbt.edp.pipe_joiner_enable = true; } static void diff --git a/drivers/gpu/drm/i915/display/intel_quirks.c b/drivers/gpu/drm/i915/display/intel_quirks.c index e3303d5146e89c..ec3a79c87e73d1 100644 --- a/drivers/gpu/drm/i915/display/intel_quirks.c +++ b/drivers/gpu/drm/i915/display/intel_quirks.c @@ -108,6 +108,16 @@ static void quirk_enable_dpcd_backlight(struct intel_dp *intel_dp) drm_info(display->drm, "Applying Enable DPCD Backlight quirk\n"); } +/* + * VBT on some machines defaults the eDP pipe joiner to disabled even though + * the panel requires it to achieve its native mode, so allow it regardless. + */ +static void quirk_allow_edp_joiner(struct intel_display *display) +{ + intel_set_quirk(display, QUIRK_ALLOW_EDP_JOINER); + drm_info(display->drm, "Applying allow eDP joiner quirk\n"); +} + struct intel_quirk { int device; int subsystem_vendor; @@ -271,6 +281,9 @@ static struct intel_quirk intel_quirks[] = { /* Xiaomi Book Pro 14 2026 */ { 0xb081, 0x1d72, 0x2424, quirk_disable_psr2 }, { 0xb080, 0x1d72, 0x2424, quirk_disable_psr2 }, + + /* ASUS ROG Strix SCAR 18 G835LXG */ + { 0x7d67, 0x1043, 0x3b29, quirk_allow_edp_joiner }, }; static const struct intel_dpcd_quirk intel_dpcd_quirks[] = { diff --git a/drivers/gpu/drm/i915/display/intel_quirks.h b/drivers/gpu/drm/i915/display/intel_quirks.h index 4996419ae76bd7..c64d0fc39905ed 100644 --- a/drivers/gpu/drm/i915/display/intel_quirks.h +++ b/drivers/gpu/drm/i915/display/intel_quirks.h @@ -24,6 +24,7 @@ enum intel_quirk_id { QUIRK_DISABLE_EDP_PANEL_REPLAY, QUIRK_DISABLE_PSR2, QUIRK_ENABLE_DPCD_BACKLIGHT, + QUIRK_ALLOW_EDP_JOINER, }; void intel_init_quirks(struct intel_display *display); From e68e710ecc89a3b51b5ac89bf2b708ea2a3185d2 Mon Sep 17 00:00:00 2001 From: Ian Rogers Date: Thu, 19 Nov 2026 09:11:05 -0800 Subject: [PATCH 1665/2102] ASoC: tas2781: Initialize subblk_offset in tasdevice_process_block() When tasdevice_load_block_kernel() processes a per-channel firmware block (dev_idx != 0) for an amplifier channel whose is_loading flag is false, tasdevice_process_block() skips the channel via continue and returns an uninitialized stack variable subblk_offset, which the caller checks for negative error and adds to the firmware buffer offset. Initialize subblk_offset to 0. Found via Clang -Wconditional-uninitialized on an x86_64 allyesconfig build. Verified by building sound/soc/codecs/tas2781-fmwlib.o with LLVM=1 W=1 (-Werror) and -Wconditional-uninitialized; not runtime-tested on TAS2781 hardware. Fixes: 915f5eadebd2 ("ASoC: tas2781: firmware lib") Signed-off-by: Ian Rogers Link: https://patch.msgid.link/20261119171105.1538194-1-irogers@google.com Signed-off-by: Mark Brown --- sound/soc/codecs/tas2781-fmwlib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/codecs/tas2781-fmwlib.c b/sound/soc/codecs/tas2781-fmwlib.c index 527d5e0ab906fd..f5ac082e07f3d0 100644 --- a/sound/soc/codecs/tas2781-fmwlib.c +++ b/sound/soc/codecs/tas2781-fmwlib.c @@ -897,7 +897,7 @@ static int tasdevice_process_block(void *context, unsigned char *data, unsigned char dev_idx, int sublocksize) { struct tasdevice_priv *tas_priv = (struct tasdevice_priv *)context; - int subblk_offset, chn, chnend, rc; + int subblk_offset = 0, chn, chnend, rc; unsigned char subblk_typ = data[1]; int blktyp = dev_idx & 0xC0; int idx = dev_idx & 0x3F; From 1b28ee399b23c455211e0b654da3017b8edd119e Mon Sep 17 00:00:00 2001 From: Kuba Piecuch Date: Tue, 24 Nov 2026 10:31:14 +0000 Subject: [PATCH 1666/2102] sched_ext: Fix suspicious RCU usage in KF_RCU_PROTECTED kfuncs scx_bpf_dsq_peek() and scx_bpf_tid_to_task() call rcu_dereference() without taking rcu_read_lock() and rely on KF_RCU_PROTECTED instead. However, the verifier treats every non-sleepable program as being in an RCU read-side section, including bpf_timer callbacks. bpf_timer_cb() runs those from hrtimer softirq without rcu_read_lock(), so calling either kfunc from a bpf_timer callback triggers: WARNING: suspicious RCU usage kernel/sched/ext/ext.c:11170 suspicious rcu_dereference_check() usage! ... scx_bpf_dsq_peek+0x7d/0xd0 bpf_timer_cb+0xf9/0x130 The same happens from a sleepable program inside bpf_preempt_disable(). Both contexts are RCU readers, so this is a lockdep false positive, not a use-after-free. Every context accepted by KF_RCU_PROTECTED satisfies rcu_read_lock_any_held(). Use rcu_dereference_all() in both kfuncs, matching scx_prog_sched() and rhashtable_lookup(), and convert scx_bpf_cpu_curr() and scx_bpf_cid_curr() from guard(rcu)() + rcu_dereference() to rcu_dereference_all() as well to avoid redundant per-call RCU read-side lock/unlock overhead. This patch was written with the help of an AI coding assistant. Fixes: 44f5c8ec5b9a ("sched_ext: Add lockless peek operation for DSQs") Fixes: 41e3312861ea ("sched_ext: add p->scx.tid and SCX_OPS_TID_TO_TASK lookup") Signed-off-by: Kuba Piecuch Reviewed-by: Andrea Righi Signed-off-by: Tejun Heo --- kernel/sched/ext/ext.c | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c index e8c30a21e03e3f..b8702b81782a5a 100644 --- a/kernel/sched/ext/ext.c +++ b/kernel/sched/ext/ext.c @@ -11167,7 +11167,7 @@ __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id, return NULL; } - return rcu_dereference(dsq->first_task); + return rcu_dereference_all(dsq->first_task); } /** @@ -11908,8 +11908,6 @@ __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu, const struct bpf_prog_ { struct scx_sched *sch; - guard(rcu)(); - sch = scx_prog_sched(aux); if (unlikely(!sch)) return NULL; @@ -11917,7 +11915,7 @@ __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu, const struct bpf_prog_ if (!scx_cpu_valid(sch, cpu, NULL)) return NULL; - return rcu_dereference(cpu_rq(cpu)->donor); + return rcu_dereference_all(cpu_rq(cpu)->donor); } /** @@ -11933,15 +11931,13 @@ __bpf_kfunc struct task_struct *scx_bpf_cid_curr(s32 cid, const struct bpf_prog_ struct scx_sched *sch; s32 cpu; - guard(rcu)(); - sch = scx_prog_sched(aux); if (unlikely(!sch)) return NULL; cpu = scx_cid_to_cpu(sch, cid); if (cpu < 0) return NULL; - return rcu_dereference(cpu_rq(cpu)->donor); + return rcu_dereference_all(cpu_rq(cpu)->donor); } /** @@ -11958,7 +11954,7 @@ __bpf_kfunc struct task_struct *scx_bpf_tid_to_task(u64 tid) struct sched_ext_entity *scx; if (!scx_tid_to_task_enabled()) { - struct scx_sched *sch = rcu_dereference(scx_root); + struct scx_sched *sch = rcu_dereference_all(scx_root); if (sch) scx_error(sch, "scx_bpf_tid_to_task() called without SCX_OPS_TID_TO_TASK"); From e667a652dd0a6f6d0d89e2d0f80881ddabea1ead Mon Sep 17 00:00:00 2001 From: Cheng-Yang Chou Date: Mon, 23 Nov 2026 22:54:51 +0800 Subject: [PATCH 1667/2102] sched_ext: Don't request private stacks the JIT can't provide Since commit 4f8b122848db ("sched_ext: Add basic building blocks for nested sub-scheduler dispatching"), bpf_scx_check_member() requests a private stack for ops.dispatch(), and later also for ops.sub_caps_updated(), whenever CONFIG_EXT_SUB_SCHED is set, which is the default. The verifier fails the load with -EACCES if the JIT doesn't support private stacks, so on architectures whose JIT doesn't, like riscv64, no BPF scheduler that implements ops.dispatch() can be loaded. The private stack is only needed when these operations nest, which only happens with sub-schedulers. Don't request it if the JIT can't provide it, and refuse to attach sub-schedulers in that case. Root schedulers then load as they did before sub-scheduler support was added. Fixes: 4f8b122848db ("sched_ext: Add basic building blocks for nested sub-scheduler dispatching") Cc: stable@vger.kernel.org # v7.1+ Reported-by: JaeJoon Jung Link: https://lore.kernel.org/all/20260810031418.95364-1-rgbi3307@gmail.com/ Signed-off-by: Cheng-Yang Chou Reviewed-by: Andrea Righi [tj: Wrapped the switch in an if block instead of returning early.] Signed-off-by: Tejun Heo --- kernel/sched/ext/ext.c | 20 +++++++++++--------- kernel/sched/ext/sub.c | 6 ++++++ 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c index b8702b81782a5a..7eda101a0e47e2 100644 --- a/kernel/sched/ext/ext.c +++ b/kernel/sched/ext/ext.c @@ -9308,15 +9308,17 @@ static int bpf_scx_check_member(const struct btf_type *t, * sub-scheds and sub-scheds themselves but I don't know how to access * struct_ops from here. */ - switch (moff) { - case offsetof(struct sched_ext_ops, dispatch): - prog->aux->priv_stack_requested = true; - prog->aux->recursion_detected = scx_pstack_recursion_on_dispatch; - break; - case offsetof(struct sched_ext_ops, sub_caps_updated): - prog->aux->priv_stack_requested = true; - prog->aux->recursion_detected = scx_pstack_recursion_on_caps_updated; - break; + if (bpf_jit_supports_private_stack()) { + switch (moff) { + case offsetof(struct sched_ext_ops, dispatch): + prog->aux->priv_stack_requested = true; + prog->aux->recursion_detected = scx_pstack_recursion_on_dispatch; + break; + case offsetof(struct sched_ext_ops, sub_caps_updated): + prog->aux->priv_stack_requested = true; + prog->aux->recursion_detected = scx_pstack_recursion_on_caps_updated; + break; + } } #endif /* CONFIG_EXT_SUB_SCHED */ diff --git a/kernel/sched/ext/sub.c b/kernel/sched/ext/sub.c index d2a20114eaa23f..7c069a28976606 100644 --- a/kernel/sched/ext/sub.c +++ b/kernel/sched/ext/sub.c @@ -2246,6 +2246,12 @@ void scx_sub_enable_workfn(struct kthread_work *work) goto out_unlock; } + /* nesting ops need private stacks, see bpf_scx_check_member() */ + if (!bpf_jit_supports_private_stack()) { + ret = -EOPNOTSUPP; + goto out_unlock; + } + cgrp = cgroup_get_from_id(ops->sub_cgroup_id); if (IS_ERR(cgrp)) { ret = PTR_ERR(cgrp); From cfe3530f721cf26a06b9a7e1d08069bd56371b76 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Tue, 17 Nov 2026 09:53:34 +0700 Subject: [PATCH 1668/2102] ASoC: adi: axi-i2s: Use devm_clk_get_enabled() The AXI clock is enabled once in probe() and only disabled in remove(). Use devm_clk_get_enabled() to let devres handle this automatically, and drop the now unnecessary remove() callback. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261117025335.7455-2-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/adi/axi-i2s.c | 22 +++------------------- 1 file changed, 3 insertions(+), 19 deletions(-) diff --git a/sound/soc/adi/axi-i2s.c b/sound/soc/adi/axi-i2s.c index 2c4035ff6c2d2d..1eeb96b7fd606e 100644 --- a/sound/soc/adi/axi-i2s.c +++ b/sound/soc/adi/axi-i2s.c @@ -208,7 +208,7 @@ static int axi_i2s_probe(struct platform_device *pdev) if (IS_ERR(i2s->regmap)) return PTR_ERR(i2s->regmap); - i2s->clk = devm_clk_get(&pdev->dev, "axi"); + i2s->clk = devm_clk_get_enabled(&pdev->dev, "axi"); if (IS_ERR(i2s->clk)) return PTR_ERR(i2s->clk); @@ -216,10 +216,6 @@ static int axi_i2s_probe(struct platform_device *pdev) if (IS_ERR(i2s->clk_ref)) return PTR_ERR(i2s->clk_ref); - ret = clk_prepare_enable(i2s->clk); - if (ret) - return ret; - if (i2s->has_playback) { axi_i2s_dai.playback.channels_min = 2; axi_i2s_dai.playback.channels_max = 2; @@ -257,28 +253,17 @@ static int axi_i2s_probe(struct platform_device *pdev) ret = devm_snd_soc_register_component(&pdev->dev, &axi_i2s_component, &axi_i2s_dai, 1); if (ret) - goto err_clk_disable; + return ret; ret = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (ret) - goto err_clk_disable; + return ret; dev_info(&pdev->dev, "probed, capture %s, playback %s\n", str_enabled_disabled(i2s->has_capture), str_enabled_disabled(i2s->has_playback)); return 0; - -err_clk_disable: - clk_disable_unprepare(i2s->clk); - return ret; -} - -static void axi_i2s_dev_remove(struct platform_device *pdev) -{ - struct axi_i2s *i2s = platform_get_drvdata(pdev); - - clk_disable_unprepare(i2s->clk); } static const struct of_device_id axi_i2s_of_match[] = { @@ -293,7 +278,6 @@ static struct platform_driver axi_i2s_driver = { .of_match_table = axi_i2s_of_match, }, .probe = axi_i2s_probe, - .remove = axi_i2s_dev_remove, }; module_platform_driver(axi_i2s_driver); From 8bf6b562579e1899fab5ba8ade596bba0a8129e4 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Tue, 17 Nov 2026 09:53:35 +0700 Subject: [PATCH 1669/2102] ASoC: adi: axi-spdif: Use devm_clk_get_enabled() The AXI clock is enabled once in probe() and only disabled in remove(). Use devm_clk_get_enabled() to let devres handle this automatically, and drop the now unnecessary remove() callback. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261117025335.7455-3-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/adi/axi-spdif.c | 22 +++------------------- 1 file changed, 3 insertions(+), 19 deletions(-) diff --git a/sound/soc/adi/axi-spdif.c b/sound/soc/adi/axi-spdif.c index faa1fc7cb973ff..07363ddebb77a2 100644 --- a/sound/soc/adi/axi-spdif.c +++ b/sound/soc/adi/axi-spdif.c @@ -199,7 +199,7 @@ static int axi_spdif_probe(struct platform_device *pdev) if (IS_ERR(spdif->regmap)) return PTR_ERR(spdif->regmap); - spdif->clk = devm_clk_get(&pdev->dev, "axi"); + spdif->clk = devm_clk_get_enabled(&pdev->dev, "axi"); if (IS_ERR(spdif->clk)) return PTR_ERR(spdif->clk); @@ -207,10 +207,6 @@ static int axi_spdif_probe(struct platform_device *pdev) if (IS_ERR(spdif->clk_ref)) return PTR_ERR(spdif->clk_ref); - ret = clk_prepare_enable(spdif->clk); - if (ret) - return ret; - spdif->dma_data.addr = res->start + AXI_SPDIF_REG_TX_FIFO; spdif->dma_data.addr_width = 4; spdif->dma_data.maxburst = 1; @@ -226,24 +222,13 @@ static int axi_spdif_probe(struct platform_device *pdev) ret = devm_snd_soc_register_component(&pdev->dev, &axi_spdif_component, &axi_spdif_dai, 1); if (ret) - goto err_clk_disable; + return ret; ret = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (ret) - goto err_clk_disable; + return ret; return 0; - -err_clk_disable: - clk_disable_unprepare(spdif->clk); - return ret; -} - -static void axi_spdif_dev_remove(struct platform_device *pdev) -{ - struct axi_spdif *spdif = platform_get_drvdata(pdev); - - clk_disable_unprepare(spdif->clk); } static const struct of_device_id axi_spdif_of_match[] = { @@ -258,7 +243,6 @@ static struct platform_driver axi_spdif_driver = { .of_match_table = axi_spdif_of_match, }, .probe = axi_spdif_probe, - .remove = axi_spdif_dev_remove, }; module_platform_driver(axi_spdif_driver); From 279cd42031aef3567de140a0ce136e83a9b6dd25 Mon Sep 17 00:00:00 2001 From: Binbin Zhou Date: Tue, 24 Nov 2026 15:24:13 +0800 Subject: [PATCH 1670/2102] ASoC: loongson: Set dai_fmt for auto format selection .auto_selectable_formats only covers the signal format, clock gating and polarity, not the clock provider: the core takes that field from dai_link->dai_fmt. loongson_dai_links leaves .dai_fmt unset and only programmed the format from hw_params, which worked until both es8328 and loongson-i2s advertised .auto_selectable_formats. The core now sets SND_SOC_DAIFMT_I2S (1) without CLOCK_PROVIDER bits at bind time and es8328_set_dai_fmt() rejects it with -EINVAL. Set .dai_fmt from the board config, and drop the redundant snd_soc_runtime_set_dai_fmt() call from hw_params. Fixes: da659805e0b0 ("ASoC: loongson: Add Loongson-2K0300 CTCISZ Forever Pi sound card support") Signed-off-by: Binbin Zhou Link: https://patch.msgid.link/20261124072413.3282851-1-zhoubinbin@loongson.cn Signed-off-by: Mark Brown --- sound/soc/loongson/loongson_card.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/sound/soc/loongson/loongson_card.c b/sound/soc/loongson/loongson_card.c index b06b596047b88f..b4dc3cd6e4d65c 100644 --- a/sound/soc/loongson/loongson_card.c +++ b/sound/soc/loongson/loongson_card.c @@ -152,7 +152,7 @@ static int loongson_card_hw_params(struct snd_pcm_substream *substream, return ret; } - return snd_soc_runtime_set_dai_fmt(rtd, ls_card->cfg->fmt); + return 0; } static const struct snd_soc_ops loongson_ops = { @@ -312,6 +312,16 @@ static int loongson_asoc_card_probe(struct platform_device *pdev) card->dai_link = loongson_dai_links; card->num_links = ARRAY_SIZE(loongson_dai_links); + /* + * The DAI format is fixed per board. Describe it in the DAI link so + * that the ASoC core takes it into account when it auto-selects the + * format from the DAIs' .auto_selectable_formats. Otherwise the + * CLOCK_PROVIDER bits are lost and the codec is configured with a + * format it cannot accept (e.g. es8328_set_dai_fmt() rejecting it). + */ + for (unsigned int i = 0; i < card->num_links; i++) + loongson_dai_links[i].dai_fmt = ls_priv->cfg->fmt; + if (ls_priv->cfg->add_dapm_widgets) { card->dapm_widgets = loongson_asoc_dapm_widgets; card->num_dapm_widgets = ARRAY_SIZE(loongson_asoc_dapm_widgets); From 72296e02b46a34e52c8b97c5ebf95c2a970373fd Mon Sep 17 00:00:00 2001 From: Rodrigo Vivi Date: Fri, 20 Nov 2026 10:27:54 -0500 Subject: [PATCH 1671/2102] drm/xe/hwmon: Unregister hwmon before the device is unplugged hwmon was registered with devm, so its sysfs attributes stayed reachable after drm_dev_unplug() until devres teardown. A reader in that window accesses an unplugged device, e.g. the PMT energy read on BMG. Unregister it explicitly in xe_device_remove() and in the probe error path, before the device is unplugged. Removing the attributes waits for in-flight reads, so none can run afterwards. Cc: Karthik Poosa Cc: Michael J. Ruhl Reviewed-by: Michael J. Ruhl Fixes: fb1b70607f73 ("drm/xe/hwmon: Expose power attributes") Link: https://patch.msgid.link/20261120152753.1346010-2-rodrigo.vivi@intel.com Signed-off-by: Rodrigo Vivi (cherry picked from commit 6bae3d8f569445db5e3385b61efa5f9ba9eed3d3) Signed-off-by: Matthew Brost --- drivers/gpu/drm/xe/xe_device.c | 9 ++++++--- drivers/gpu/drm/xe/xe_hwmon.c | 22 +++++++++++++++++++--- drivers/gpu/drm/xe/xe_hwmon.h | 2 ++ 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/xe/xe_device.c b/drivers/gpu/drm/xe/xe_device.c index c41533644c928a..570bc944d78873 100644 --- a/drivers/gpu/drm/xe/xe_device.c +++ b/drivers/gpu/drm/xe/xe_device.c @@ -1091,7 +1091,7 @@ int xe_device_probe(struct xe_device *xe) err = xe_i2c_probe(xe); if (err) - goto err_unregister_display; + goto err_unregister_hwmon; for_each_gt(gt, xe, id) xe_gt_sanitize_freq(gt); @@ -1100,7 +1100,7 @@ int xe_device_probe(struct xe_device *xe) err = xe_sriov_init_late(xe); if (err) - goto err_unregister_display; + goto err_unregister_hwmon; detect_preproduction_hw(xe); @@ -1113,10 +1113,12 @@ int xe_device_probe(struct xe_device *xe) err = devm_add_action_or_reset(xe->drm.dev, xe_device_sanitize, xe); if (err) - goto err_unregister_display; + goto err_unregister_hwmon; return 0; +err_unregister_hwmon: + xe_hwmon_unregister(xe); err_unregister_display: xe_display_unregister(xe); drm_dev_unregister(&xe->drm); @@ -1126,6 +1128,7 @@ int xe_device_probe(struct xe_device *xe) void xe_device_remove(struct xe_device *xe) { + xe_hwmon_unregister(xe); xe_display_unregister(xe); drm_dev_unplug(&xe->drm); diff --git a/drivers/gpu/drm/xe/xe_hwmon.c b/drivers/gpu/drm/xe/xe_hwmon.c index daa3f61617a028..d81b90c9cb99a5 100644 --- a/drivers/gpu/drm/xe/xe_hwmon.c +++ b/drivers/gpu/drm/xe/xe_hwmon.c @@ -1688,9 +1688,9 @@ int xe_hwmon_register(struct xe_device *xe) drm_dbg(&xe->drm, "Register xe hwmon interface\n"); /* hwmon_dev points to device hwmon */ - hwmon->hwmon_dev = devm_hwmon_device_register_with_info(dev, "xe", hwmon, - &hwmon_chip_info, - hwmon_groups); + hwmon->hwmon_dev = hwmon_device_register_with_info(dev, "xe", hwmon, + &hwmon_chip_info, + hwmon_groups); if (IS_ERR(hwmon->hwmon_dev)) { err = PTR_ERR(hwmon->hwmon_dev); xe_log_err(xe, HWMON, err, @@ -1701,4 +1701,20 @@ int xe_hwmon_register(struct xe_device *xe) return 0; } + +/** + * xe_hwmon_unregister - Remove the hwmon interface + * @xe: xe device + * + * Called before the device is unplugged, so that no hwmon attribute can + * be accessed afterwards. + */ +void xe_hwmon_unregister(struct xe_device *xe) +{ + if (!xe->hwmon) + return; + + hwmon_device_unregister(xe->hwmon->hwmon_dev); + xe->hwmon = NULL; +} MODULE_IMPORT_NS("INTEL_PMT_TELEMETRY"); diff --git a/drivers/gpu/drm/xe/xe_hwmon.h b/drivers/gpu/drm/xe/xe_hwmon.h index d02c1bfe8c0a05..e67e0134f02a50 100644 --- a/drivers/gpu/drm/xe/xe_hwmon.h +++ b/drivers/gpu/drm/xe/xe_hwmon.h @@ -12,8 +12,10 @@ struct xe_device; #if IS_REACHABLE(CONFIG_HWMON) int xe_hwmon_register(struct xe_device *xe); +void xe_hwmon_unregister(struct xe_device *xe); #else static inline int xe_hwmon_register(struct xe_device *xe) { return 0; }; +static inline void xe_hwmon_unregister(struct xe_device *xe) { } #endif #endif /* _XE_HWMON_H_ */ From 98032adcb615473d3948f79f7b251d5be2ee6233 Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Fri, 20 Nov 2026 12:16:36 +0000 Subject: [PATCH 1672/2102] arm64: pi: Add an ISB after mapping the FDT in the initial ID map map_fdt() maps the FDT into the live initial ID map with only a DSB before the caller reads it, so the read can fault on a translation made speculatively before the mapping was written. This early in boot, VBAR_EL1 doesn't yet point at the kernel's vectors, and the kernel fails to boot. Add an ISB after the DSB. Fixes: 84b04d3e6bdb ("arm64: kernel: Create initial ID map from C code") Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Reviewed-by: Ryan Roberts Signed-off-by: Catalin Marinas --- arch/arm64/kernel/pi/map_kernel.c | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm64/kernel/pi/map_kernel.c b/arch/arm64/kernel/pi/map_kernel.c index fb44cbdd2f2927..f9338257adb7dc 100644 --- a/arch/arm64/kernel/pi/map_kernel.c +++ b/arch/arm64/kernel/pi/map_kernel.c @@ -211,6 +211,7 @@ static void *__init map_fdt(phys_addr_t fdt) fdt, PAGE_KERNEL, IDMAP_ROOT_LEVEL, (pte_t *)init_idmap_pg_dir, false, 0); dsb(ishst); + isb(); return (void *)fdt; } From bd63a4741f50844b3f8c2e1159affbf0a44aaa9d Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Fri, 20 Nov 2026 12:16:37 +0000 Subject: [PATCH 1673/2102] arm64: mm: Add an ISB after remapping the KPTI page-table slot kpti_map_pgtbl remaps a temporary slot with break-before-make, and kpti_mk_tbl_ng then reads the page tables through it. The make ends in a DSB alone, so the reads can fault on a translation of the slot made speculatively before the new entry was written. With the temporary page tables in TTBR1 the kernel's vectors are unmapped, and the boot hangs. Add an ISB after the DSB. Fixes: 47546a1912fc ("arm64: mm: install KPTI nG mappings with MMU enabled") Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Reviewed-by: Ryan Roberts Signed-off-by: Catalin Marinas --- arch/arm64/mm/proc.S | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm64/mm/proc.S b/arch/arm64/mm/proc.S index 99aacf03367da3..62e790a2a779c2 100644 --- a/arch/arm64/mm/proc.S +++ b/arch/arm64/mm/proc.S @@ -290,6 +290,7 @@ SYM_FUNC_ALIAS(__pi_idmap_cpu_replace_ttbr1, idmap_cpu_replace_ttbr1) orr pte, pte, pte_flags str pte, [temp_pte, #8 * (\level + 2)] dsb nshst + isb .endm /* From 8f3b845bc30b42e25341693313afa7425ed3c7a4 Mon Sep 17 00:00:00 2001 From: Fei Yang Date: Thu, 19 Nov 2026 16:46:35 -0800 Subject: [PATCH 1674/2102] drm/xe: Serialize migrate ULLS enter against a pending exit xe_migrate_ulls_exit() clears ulls.enabled as soon as the ULLS_EXIT job is pushed, and drops job_mutex without waiting for it. A page fault arriving in that window finds ULLS disabled and pushes a ULLS_ENTER job while the previous ULLS chain is still executing. ULLS_ENTER is not chained, so submit_exec_queue() publishes its ring tail with xe_lrc_set_ring_tail(). That only updates the saved tail in the context image, which is what a context restore loads RING_TAIL from. It is therefore correct for a context that is off the hardware - but the context only leaves the hardware once the exit job has retired. Submitted before then, that write races the postamble of the job preceding the exit job. The postamble publishes the same saved tail, and RING_TAIL, at the end of the exit job. If it lands after the CPU's write the tail is rewound behind the enter job, which the command streamer never executes. Its fence never signals, so job_cnt never drops, xe_exec_queue_is_idle() stays false and the exit worker re-arms itself forever while the context sits parked on the engine. Wait for the exit job's fence in the exit worker before dropping job_mutex. xe_migrate_ulls_enter() takes job_mutex to submit, so it is serialized behind the exit job retiring. The exit job carries no batch and is only pushed once the queue is idle, so the wait is short and depends on nothing else on the queue. Fixes: 8ab0d5ca31ca ("drm/xe: Add ULLS migration job support to migration layer") Signed-off-by: Fei Yang Reviewed-by: Matthew Brost Signed-off-by: Matthew Brost Link: https://patch.msgid.link/20261120004635.3902529-1-fei.yang@intel.com (cherry picked from commit 3001c11aba746af44be1053bf6517c7d6b71e0ec) Signed-off-by: Matthew Brost --- drivers/gpu/drm/xe/xe_migrate.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/drivers/gpu/drm/xe/xe_migrate.c b/drivers/gpu/drm/xe/xe_migrate.c index fffb3eb6c76ebe..786bff07b93701 100644 --- a/drivers/gpu/drm/xe/xe_migrate.c +++ b/drivers/gpu/drm/xe/xe_migrate.c @@ -187,6 +187,18 @@ * The PM reference is then dropped. If the queue was not idle, the worker * simply re-arms itself. * + * The worker waits for the "last" job to retire before dropping + * @xe_migrate.job_mutex, so a subsequent enter is serialized behind it. A + * "first" job is not chained, so it publishes its own ring tail with + * xe_lrc_set_ring_tail(), which updates the saved tail in the context image + * only. That is enough for a context which is off the hardware, since a + * context restore loads RING_TAIL from there, but the context is only off the + * hardware once the "last" job has retired. Submitted before then, the write + * races the postamble of the job preceding the "last" one, which puts that + * same saved tail - and RING_TAIL - at the end of the "last" job. The + * postamble landing second rewinds the tail behind the "first" job, which the + * command streamer then never executes. + * * Job state * --------- * @@ -761,6 +773,9 @@ static void xe_migrate_ulls_exit(struct work_struct *work) scoped_guard(mutex, &m->job_mutex) { if (xe_exec_queue_is_idle(m->q, 1)) { fence = __xe_migrate_job_push(m, job, ULLS_EXIT); + + /* Keep enter out until the context is off the HW */ + dma_fence_wait(fence, false); dma_fence_put(fence); xe_pm_runtime_put(xe); /* Pairs with PM get in enter */ From bb60ce2c3674ebdb803ff2bce0c0b6f30c80de4c Mon Sep 17 00:00:00 2001 From: Fuad Tabba Date: Fri, 20 Nov 2026 12:16:38 +0000 Subject: [PATCH 1675/2102] arm64: mm: Don't defer the barriers when installing a fixmap entry In lazy MMU mode, __set_pte(), which __set_fixmap() uses, only queues its DSB and ISB, but a caller can dereference the slot as soon as __set_fixmap() returns. On a CPU with BBML3, runtime changes to the linear map are made in lazy MMU mode. With 4K pages and 39-bit VAs, for example, such a change can update a top-level entry, which set_swapper_pgd() writes through FIX_PGD. That store can fault, and the kernel then warns about a spurious translation fault. When kgdb stops a CPU in lazy MMU mode, in_interrupt() is false and its breakpoint writes through FIX_TEXT_POKE0 can fault the same way, and fail. The kgdb problem predates BBML3 support. Emit the barriers directly in __set_fixmap(). Fixes: 5fdd05efa1cd ("arm64/mm: Batch barriers when updating kernel mappings") Cc: stable@vger.kernel.org Signed-off-by: Fuad Tabba Reviewed-by: Ryan Roberts Reviewed-by: Kevin Brodsky Signed-off-by: Catalin Marinas --- arch/arm64/mm/fixmap.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/arch/arm64/mm/fixmap.c b/arch/arm64/mm/fixmap.c index f66a0016dd02df..951004ad700c39 100644 --- a/arch/arm64/mm/fixmap.c +++ b/arch/arm64/mm/fixmap.c @@ -127,7 +127,9 @@ void __set_fixmap(enum fixed_addresses idx, ptep = fixmap_pte(addr); if (pgprot_val(flags)) { - __set_pte(ptep, pfn_pte(phys >> PAGE_SHIFT, flags)); + /* The slot must be usable on return, even in lazy MMU mode. */ + __set_pte_nosync(ptep, pfn_pte(phys >> PAGE_SHIFT, flags)); + emit_pte_barriers(); } else { __pte_clear(&init_mm, addr, ptep); flush_tlb_kernel_range(addr, addr+PAGE_SIZE); From c901e8fddd3a23353bb12c9d93b9a5fc482ac8f5 Mon Sep 17 00:00:00 2001 From: Adrian Ambrozewicz Date: Tue, 24 Nov 2026 11:20:32 +0200 Subject: [PATCH 1676/2102] gpiolib: wait for pending label frees before cleaning up desc_srcu desc_set_label() frees the old label with call_srcu() on gdev->desc_srcu, and gpiodev_release() calls synchronize_srcu() before cleanup_srcu_struct(). synchronize_srcu() waits for a grace period, not for queued callbacks. Once the srcu_struct uses per-CPU callback lists, a label freed by gpiochip_free_hogs() can still be pending, and cleanup_srcu_struct() warns: WARNING: kernel/rcu/srcutree.c:706 at cleanup_srcu_struct+0x239/0x330, CPU#0: init/1 Call Trace: gpiodev_release device_release kobject_put devres_release_all device_release_driver_internal platform_device_unregister gpio_sim_device_deactivate Use srcu_barrier(), which waits for them. Reproduced with a hogged gpio-sim line, setting the chip live and back on a 4-CPU guest with srcutree.convert_to_big=1: it warns within 60 cycles; with this change, 1000 cycles pass. Fixes: a86d27693066 ("gpiolib: fix the speed of descriptor label setting with SRCU") Cc: stable@vger.kernel.org Reviewed-by: Paul E. McKenney Reviewed-by: Andy Shevchenko Tested-by: Yi Lai Signed-off-by: Adrian Ambrozewicz Link: https://patch.msgid.link/20261124-gpiolib-chip-removal-v8-1-aambrozewicz@nvidia.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index 63cc4064bfa4b2..82e0be8864f4dd 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -898,7 +898,7 @@ static void gpiodev_release(struct device *dev) struct gpio_device *gdev = to_gpio_device(dev); /* Call pending kfree()s for descriptor labels. */ - synchronize_srcu(&gdev->desc_srcu); + srcu_barrier(&gdev->desc_srcu); cleanup_srcu_struct(&gdev->desc_srcu); if (gdev->line_state_wq) From 4bc5e234e10866ebaad01ce11ed08f64333dcac0 Mon Sep 17 00:00:00 2001 From: Adrian Ambrozewicz Date: Tue, 24 Nov 2026 11:20:33 +0200 Subject: [PATCH 1677/2102] gpiolib: free the label of lines released after their chip was removed gpiod_free_commit() drops the consumer label only while the chip is still there. A line that user space keeps requested across gpiochip_remove() is released when gdev->chip is already NULL, and its label leaks: unreferenced object (size 32): comm "gpio-hold" backtrace (crc 7ff222d9): desc_set_label gpiod_request_commit gpiod_request linereq_create gpio_ioctl Clear the label before the chip check. The ->free() callback, the flags update and the line state notification need the chip and stay under it. Reproduced with gpio-sim: request a line, set the chip's "live" attribute to 0, then close the request. kmemleak reports up to 30 such objects after 30 cycles; with this change, none after 100. Fixes: 35b545332b80 ("gpio: remove gpio_lock") Cc: stable@vger.kernel.org Reviewed-by: Andy Shevchenko Signed-off-by: Adrian Ambrozewicz Link: https://patch.msgid.link/20261124-gpiolib-chip-removal-v8-2-aambrozewicz@nvidia.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index 82e0be8864f4dd..9832f755312fa0 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -2707,7 +2707,12 @@ void gpiod_free_commit(struct gpio_desc *desc) flags = READ_ONCE(desc->flags); - if (guard.gc && test_bit(GPIOD_FLAG_REQUESTED, &flags)) { + if (guard.gc && !test_bit(GPIOD_FLAG_REQUESTED, &flags)) + return; + + desc_set_label(desc, NULL); + + if (guard.gc) { if (guard.gc->free) guard.gc->free(guard.gc, gpiod_hwgpio(desc)); @@ -2717,7 +2722,6 @@ void gpiod_free_commit(struct gpio_desc *desc) #ifdef CONFIG_OF_DYNAMIC WRITE_ONCE(desc->hog, NULL); #endif - desc_set_label(desc, NULL); set_mask_bits(&desc->flags, BIT(GPIOD_FLAG_ACTIVE_LOW) | BIT(GPIOD_FLAG_REQUESTED) | From dceb3a75ee3300d98ecc6d1bfd1b45ef14fb5a13 Mon Sep 17 00:00:00 2001 From: Adrian Ambrozewicz Date: Tue, 24 Nov 2026 11:20:34 +0200 Subject: [PATCH 1678/2102] gpiolib: cdev: do not free line IRQs again after the chip is removed Since commit ec8b6f55b981 ("gpio: free irqs that are still requested when the chip is being removed"), gpiochip_remove() frees the IRQs still installed on the chip's lines. A line request or v1 line event kept open across the removal frees its IRQ again on release. If the mapping is gone, that can touch freed memory, as reported with virtio-gpio; if the number was reused, free_irq() warns: Trying to free already-free IRQ 28 WARNING: kernel/irq/manage.c:1881 at free_irq+0x193/0x2d0, CPU#2: gpio-hold/111 Call Trace: linereq_free linereq_release __fput Stop edge detection from the device notifier that gpiochip_remove() calls, under config_mutex so that it does not race a reconfiguration. Free the IRQ there only if it still has an action, as gpiochip_remove() frees only those on lines flagged as used for IRQs. The release path then finds nothing left to free. Reproduced with gpio-sim: remove the chip under an open request with edge detection, set it up again and request the same line, then close the first request. Every cycle warns; with this change, 100 cycles pass. Fixes: ec8b6f55b981 ("gpio: free irqs that are still requested when the chip is being removed") Reported-by: Jia Jia Closes: https://lore.kernel.org/all/20260817070429.157993-1-physicalmtea@gmail.com/ Cc: stable@vger.kernel.org Reviewed-by: Kent Gibson Signed-off-by: Adrian Ambrozewicz Link: https://patch.msgid.link/20261124-gpiolib-chip-removal-v8-3-aambrozewicz@nvidia.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib-cdev.c | 57 ++++++++++++++++++++++++++----------- 1 file changed, 40 insertions(+), 17 deletions(-) diff --git a/drivers/gpio/gpiolib-cdev.c b/drivers/gpio/gpiolib-cdev.c index bfe442db7cd383..e6d41a8aba7049 100644 --- a/drivers/gpio/gpiolib-cdev.c +++ b/drivers/gpio/gpiolib-cdev.c @@ -545,17 +545,6 @@ struct linereq { GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE | \ GPIO_V2_LINE_EDGE_FLAGS) -static int linereq_unregistered_notify(struct notifier_block *nb, - unsigned long action, void *data) -{ - struct linereq *lr = container_of(nb, struct linereq, - device_unregistered_nb); - - wake_up_poll(&lr->wait, EPOLLIN | EPOLLERR); - - return NOTIFY_OK; -} - static void linereq_put_event(struct linereq *lr, struct gpio_v2_line_event *le) { @@ -610,6 +599,21 @@ static inline void free_irq_label(const char *label) kfree(label); } +/* + * gpiochip_remove() frees the interrupts still requested on the lines of the + * chip being removed, so once the chip is going away the IRQ may no longer be + * ours to free. + */ +static void free_line_irq(unsigned int irq, void *dev_id) +{ + const char *name = NULL; + + if (irq && irq_has_action(irq)) + name = free_irq(irq, dev_id); + + free_irq_label(name); +} + #ifdef CONFIG_HTE static enum hte_return process_hw_ts_thread(void *p) @@ -977,10 +981,8 @@ static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc, static void edge_detector_stop(struct line *line) { - if (line->irq) { - free_irq_label(free_irq(line->irq, line)); - line->irq = 0; - } + free_line_irq(line->irq, line); + line->irq = 0; #ifdef CONFIG_HTE if (READ_ONCE(line->edflags) & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE) @@ -995,6 +997,25 @@ static void edge_detector_stop(struct line *line) /* do not change line->level - see comment in debounced_value() */ } +static int linereq_unregistered_notify(struct notifier_block *nb, + unsigned long action, void *data) +{ + struct linereq *lr = container_of(nb, struct linereq, device_unregistered_nb); + + /* + * Stop edge detection now rather than when the request is released: + * by then the IRQ numbers of the removed chip may be in use again. + */ + scoped_guard(mutex, &lr->config_mutex) { + for (unsigned int i = 0; i < lr->num_lines; i++) + edge_detector_stop(&lr->lines[i]); + } + + wake_up_poll(&lr->wait, EPOLLIN | EPOLLERR); + + return NOTIFY_OK; +} + static int edge_detector_fifo_init(struct linereq *req) { if (kfifo_initialized(&req->events)) @@ -1788,6 +1809,9 @@ static int lineevent_unregistered_notify(struct notifier_block *nb, struct lineevent_state *le = container_of(nb, struct lineevent_state, device_unregistered_nb); + free_line_irq(le->irq, le); + le->irq = 0; + wake_up_poll(&le->wait, EPOLLIN | EPOLLERR); return NOTIFY_OK; @@ -1867,8 +1891,7 @@ static void lineevent_free(struct lineevent_state *le) if (le->device_unregistered_nb.notifier_call) blocking_notifier_chain_unregister(&le->gdev->device_notifier, &le->device_unregistered_nb); - if (le->irq) - free_irq_label(free_irq(le->irq, le)); + free_line_irq(le->irq, le); if (le->desc) gpiod_free(le->desc); kfree(le->label); From a3a1dbaf7460ad69d3c8d01d42832411531bc4d8 Mon Sep 17 00:00:00 2001 From: Adrian Ambrozewicz Date: Tue, 24 Nov 2026 11:20:35 +0200 Subject: [PATCH 1679/2102] gpiolib: cdev: don't sleep in the SRCU read section in read() linereq_read(), lineevent_read() and lineinfo_watch_read() stay in the gdev->srcu read section while they sleep waiting for an event, so gpiochip_remove() blocks in synchronize_srcu() until an event arrives or the reader is signalled. The device lock is held meanwhile, which also blocks device_shutdown(): task:init state:D stack:0 pid:1 tgid:1 ppid:0 Call Trace: __synchronize_srcu gpiochip_remove devres_release_all device_release_driver_internal platform_device_unregister gpio_sim_device_deactivate Check the chip in a scoped SRCU section only; nothing after the check dereferences it. End the wait once the chip is gone, and return -ENODEV if there is no event to report. Reproduced with gpio-sim: setting "live" to 0 hangs while a reader is blocked in read() on a line request; with this change, the write returns at once and read() fails with -ENODEV. Fixes: bdbbae241a04 ("gpiolib: protect the GPIO device against being dropped while in use by user-space") Cc: stable@vger.kernel.org Reviewed-by: Kent Gibson Signed-off-by: Adrian Ambrozewicz Link: https://patch.msgid.link/20261124-gpiolib-chip-removal-v8-4-aambrozewicz@nvidia.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib-cdev.c | 50 ++++++++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/drivers/gpio/gpiolib-cdev.c b/drivers/gpio/gpiolib-cdev.c index e6d41a8aba7049..f2da4f2646bc5a 100644 --- a/drivers/gpio/gpiolib-cdev.c +++ b/drivers/gpio/gpiolib-cdev.c @@ -1508,6 +1508,20 @@ static __poll_t linereq_poll(struct file *file, return events; } +/* + * For the read() paths, which must not stay in the SRCU read section while + * sleeping: that would stall gpiochip_remove() until an event arrives. + */ +static int gpiodev_check_chip(struct gpio_device *gdev) +{ + guard(srcu)(&gdev->srcu); + + if (!rcu_access_pointer(gdev->chip)) + return -ENODEV; + + return 0; +} + static ssize_t linereq_read(struct file *file, char __user *buf, size_t count, loff_t *f_ps) { @@ -1516,10 +1530,9 @@ static ssize_t linereq_read(struct file *file, char __user *buf, ssize_t bytes_read = 0; int ret; - guard(srcu)(&lr->gdev->srcu); - - if (!rcu_access_pointer(lr->gdev->chip)) - return -ENODEV; + ret = gpiodev_check_chip(lr->gdev); + if (ret) + return ret; if (count < sizeof(le)) return -EINVAL; @@ -1534,9 +1547,12 @@ static ssize_t linereq_read(struct file *file, char __user *buf, return -EAGAIN; ret = wait_event_interruptible_locked(lr->wait, - !kfifo_is_empty(&lr->events)); + !kfifo_is_empty(&lr->events) || + !rcu_access_pointer(lr->gdev->chip)); if (ret) return ret; + if (kfifo_is_empty(&lr->events)) + return -ENODEV; } if (kfifo_out(&lr->events, &le, 1) != 1) { @@ -1831,10 +1847,9 @@ static ssize_t lineevent_read(struct file *file, char __user *buf, ssize_t ge_size; int ret; - guard(srcu)(&le->gdev->srcu); - - if (!rcu_access_pointer(le->gdev->chip)) - return -ENODEV; + ret = gpiodev_check_chip(le->gdev); + if (ret) + return ret; /* * When compatible system call is being used the struct gpioevent_data, @@ -1862,9 +1877,12 @@ static ssize_t lineevent_read(struct file *file, char __user *buf, return -EAGAIN; ret = wait_event_interruptible_locked(le->wait, - !kfifo_is_empty(&le->events)); + !kfifo_is_empty(&le->events) || + !rcu_access_pointer(le->gdev->chip)); if (ret) return ret; + if (kfifo_is_empty(&le->events)) + return -ENODEV; } if (kfifo_out(&le->events, &ge, 1) != 1) { @@ -2608,10 +2626,9 @@ static ssize_t lineinfo_watch_read(struct file *file, char __user *buf, int ret; size_t event_size; - guard(srcu)(&cdev->gdev->srcu); - - if (!rcu_access_pointer(cdev->gdev->chip)) - return -ENODEV; + ret = gpiodev_check_chip(cdev->gdev); + if (ret) + return ret; #ifndef CONFIG_GPIO_CDEV_V1 event_size = sizeof(struct gpio_v2_line_info_changed); @@ -2629,9 +2646,12 @@ static ssize_t lineinfo_watch_read(struct file *file, char __user *buf, return -EAGAIN; ret = wait_event_interruptible_locked(cdev->wait, - !kfifo_is_empty(&cdev->events)); + !kfifo_is_empty(&cdev->events) || + !rcu_access_pointer(cdev->gdev->chip)); if (ret) return ret; + if (kfifo_is_empty(&cdev->events)) + return -ENODEV; } #ifdef CONFIG_GPIO_CDEV_V1 /* must be after kfifo check so watch_abi_version is set */ From f46725141e3db9bfd7531a039e15171f7326135f Mon Sep 17 00:00:00 2001 From: Adrian Ambrozewicz Date: Tue, 24 Nov 2026 11:20:36 +0200 Subject: [PATCH 1680/2102] gpiolib: cdev: don't leak the IRQ name when the chip is removed The character device requests line IRQs with a copy of the consumer label as the name, and frees the name that free_irq() returns. When gpiochip_remove() frees the IRQ first, it drops that name and the copy leaks: unreferenced object (size 8): comm "gpio-hold" backtrace (crc dc8eac94): kstrdup kstrdup_and_replace edge_detector_setup linereq_create gpio_ioctl Keep the name with the line or v1 line event, and free it there, whoever freed the IRQ. Reproduced with gpio-sim: remove the chip under an open request with edge detection and a consumer label. kmemleak reports up to 23 such objects after 30 cycles; with this change, none after 100. Fixes: ec8b6f55b981 ("gpio: free irqs that are still requested when the chip is being removed") Cc: stable@vger.kernel.org Reviewed-by: Kent Gibson Signed-off-by: Adrian Ambrozewicz Link: https://patch.msgid.link/20261124-gpiolib-chip-removal-v8-5-aambrozewicz@nvidia.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib-cdev.c | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/drivers/gpio/gpiolib-cdev.c b/drivers/gpio/gpiolib-cdev.c index f2da4f2646bc5a..fdcd315e776bcc 100644 --- a/drivers/gpio/gpiolib-cdev.c +++ b/drivers/gpio/gpiolib-cdev.c @@ -400,6 +400,7 @@ static int linehandle_create(struct gpio_device *gdev, void __user *ip) * @desc: the GPIO descriptor for this line. * @req: the corresponding line request * @irq: the interrupt triggered in response to events on this GPIO + * @irq_label: the name @irq was requested with * @edflags: the edge flags, GPIO_V2_LINE_FLAG_EDGE_RISING and/or * GPIO_V2_LINE_FLAG_EDGE_FALLING, indicating the edge detection applied * @timestamp_ns: cache for the timestamp storing it between hardirq and @@ -423,6 +424,7 @@ struct line { */ struct linereq *req; unsigned int irq; + char *irq_label; /* * The flags for the active edge detector configuration. * @@ -602,16 +604,18 @@ static inline void free_irq_label(const char *label) /* * gpiochip_remove() frees the interrupts still requested on the lines of the * chip being removed, so once the chip is going away the IRQ may no longer be - * ours to free. + * ours to free. The label is kept by the caller as free_irq() is then not the + * one returning it. */ -static void free_line_irq(unsigned int irq, void *dev_id) +static void free_line_irq(unsigned int irq, void *dev_id, char **label) { - const char *name = NULL; + const char *name = *label; if (irq && irq_has_action(irq)) - name = free_irq(irq, dev_id); + free_irq(irq, dev_id); free_irq_label(name); + *label = NULL; } #ifdef CONFIG_HTE @@ -939,6 +943,7 @@ static int debounce_setup(struct line *line, unsigned int debounce_period_us) return ret; } line->irq = irq; + line->irq_label = label; } else { ret = hte_edge_setup(line, GPIO_V2_LINE_FLAG_EDGE_BOTH); if (ret) @@ -981,7 +986,7 @@ static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc, static void edge_detector_stop(struct line *line) { - free_line_irq(line->irq, line); + free_line_irq(line->irq, line, &line->irq_label); line->irq = 0; #ifdef CONFIG_HTE @@ -1081,6 +1086,7 @@ static int edge_detector_setup(struct line *line, } line->irq = irq; + line->irq_label = label; return 0; } @@ -1777,6 +1783,7 @@ static int linereq_create(struct gpio_device *gdev, void __user *ip) * @desc: the GPIO descriptor held by this event * @eflags: the event flags this line was requested with * @irq: the interrupt that trigger in response to events on this GPIO + * @irq_label: the name @irq was requested with * @wait: wait queue that handles blocking reads of events * @device_unregistered_nb: notifier block for receiving gdev unregister events * @events: KFIFO for the GPIO events @@ -1790,6 +1797,7 @@ struct lineevent_state { struct gpio_desc *desc; u32 eflags; int irq; + char *irq_label; wait_queue_head_t wait; struct notifier_block device_unregistered_nb; DECLARE_KFIFO(events, struct gpioevent_data, 16); @@ -1825,7 +1833,7 @@ static int lineevent_unregistered_notify(struct notifier_block *nb, struct lineevent_state *le = container_of(nb, struct lineevent_state, device_unregistered_nb); - free_line_irq(le->irq, le); + free_line_irq(le->irq, le, &le->irq_label); le->irq = 0; wake_up_poll(&le->wait, EPOLLIN | EPOLLERR); @@ -1909,7 +1917,7 @@ static void lineevent_free(struct lineevent_state *le) if (le->device_unregistered_nb.notifier_call) blocking_notifier_chain_unregister(&le->gdev->device_notifier, &le->device_unregistered_nb); - free_line_irq(le->irq, le); + free_line_irq(le->irq, le, &le->irq_label); if (le->desc) gpiod_free(le->desc); kfree(le->label); @@ -2148,6 +2156,7 @@ static int lineevent_create(struct gpio_device *gdev, void __user *ip) } le->irq = irq; + le->irq_label = label; FD_PREPARE(fdf, O_RDONLY | O_CLOEXEC, anon_inode_getfile("gpio-event", &lineevent_fileops, le, From dcd5d2c2da6ed732b8e7eb415349d043018bc6c8 Mon Sep 17 00:00:00 2001 From: Adrian Ambrozewicz Date: Tue, 24 Nov 2026 11:20:37 +0200 Subject: [PATCH 1681/2102] gpiolib: cdev: don't report a failed line read as an edge With both edges requested, the IRQ threads read the line to tell a rising edge from a falling one, and treat an error as a high level. The read fails when the chip is gone. A driver's ->get() returns an error once its device stops answering: pcf857x when the I2C transfer fails, dln2 when the USB adapter is unplugged. Since gdev->chip became SRCU-protected, the read also returns -ENODEV between gpiochip_remove() and the IRQ being freed. Drop the event when the read fails, as debounce_work_func() does. Tested with gpio-sim removal (test delay in the IRQ threads) and a test chip whose ->get() returns -EIO: both reported a rising edge, none with this change. The HTE path was compile-tested. Fixes: 61f922db7221 ("gpio: userspace ABI for reading GPIO line events") Fixes: d83cee3d2bb1 ("gpio: protect the pointer to gpio_chip in gpio_device with SRCU") Cc: stable@vger.kernel.org Reported-by: Sashiko Closes: https://sashiko.dev/#/patchset/20261020-gpiolib-chip-removal-v3-0-aambrozewicz@nvidia.com?part=6 Reviewed-by: Kent Gibson Signed-off-by: Adrian Ambrozewicz Link: https://patch.msgid.link/20261124-gpiolib-chip-removal-v8-6-aambrozewicz@nvidia.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib-cdev.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/drivers/gpio/gpiolib-cdev.c b/drivers/gpio/gpiolib-cdev.c index fdcd315e776bcc..d829f7d00b5e0d 100644 --- a/drivers/gpio/gpiolib-cdev.c +++ b/drivers/gpio/gpiolib-cdev.c @@ -644,6 +644,8 @@ static enum hte_return process_hw_ts_thread(void *p) level = (line->raw_level >= 0) ? line->raw_level : gpiod_get_raw_value_cansleep(line->desc); + if (level < 0) + return HTE_CB_HANDLED; if (edflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW) level = !level; @@ -746,6 +748,7 @@ static irqreturn_t edge_irq_thread(int irq, void *p) struct line *line = p; struct linereq *lr = line->req; struct gpio_v2_line_event le; + int level; /* Do not leak kernel stack to userspace */ memset(&le, 0, sizeof(le)); @@ -766,7 +769,10 @@ static irqreturn_t edge_irq_thread(int irq, void *p) switch (READ_ONCE(line->edflags) & GPIO_V2_LINE_EDGE_FLAGS) { case GPIO_V2_LINE_FLAG_EDGE_BOTH: - le.id = line_event_id(gpiod_get_value_cansleep(line->desc)); + level = gpiod_get_value_cansleep(line->desc); + if (level < 0) + return IRQ_HANDLED; + le.id = line_event_id(level); break; case GPIO_V2_LINE_FLAG_EDGE_RISING: le.id = GPIO_V2_LINE_EVENT_RISING_EDGE; @@ -2007,6 +2013,8 @@ static irqreturn_t lineevent_irq_thread(int irq, void *p) && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) { int level = gpiod_get_value_cansleep(le->desc); + if (level < 0) + return IRQ_HANDLED; if (level) /* Emit low-to-high event */ ge.id = GPIOEVENT_EVENT_RISING_EDGE; From 93552fdc4a400ed2742f57502c42439a4b7da293 Mon Sep 17 00:00:00 2001 From: Adrian Ambrozewicz Date: Tue, 24 Nov 2026 11:20:38 +0200 Subject: [PATCH 1682/2102] gpiolib: let the character device free its IRQs first on chip removal gpiochip_remove() force-frees the remaining IRQs, removes the irqchip, and only then calls the notifier on which the character device frees its IRQs. It may then free an IRQ it no longer owns, after its mapping was disposed of and the number reused, or from a release racing gpiod_free_irqs() and gpiochip_irqchip_remove(). free_irq() then warns "Trying to free already-free IRQ" or uses a disposed descriptor. Herve Codina first proposed calling the notifier earlier [1]. Call it after the chip pointer is cleared and SRCU synchronized, when no ioctl can request IRQs, then free the rest. The release paths now free their IRQs before unregistering, under the lock the callback takes (config_mutex, or a new mutex for v1 line events). Initialise config_mutex on allocation: linereq_free() takes it, also on linereq_create()'s error returns. IRQs left requested by in-kernel users are now freed after the chip pointer is cleared, when gpiod_*() calls fail. Reproduced with a test chip on the hierarchical irqchip: both races warned in 30 of 30 cycles; with this change, none. Link: https://lore.kernel.org/all/20240227113426.253232-1-herve.codina@bootlin.com/ [1] Fixes: ec8b6f55b981 ("gpio: free irqs that are still requested when the chip is being removed") Cc: stable@vger.kernel.org Signed-off-by: Adrian Ambrozewicz Reviewed-by: Kent Gibson Link: https://patch.msgid.link/20261124-gpiolib-chip-removal-v8-7-aambrozewicz@nvidia.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib-cdev.c | 37 ++++++++++++++++++++++++++----------- drivers/gpio/gpiolib.c | 28 +++++++++++++++++++++++----- 2 files changed, 49 insertions(+), 16 deletions(-) diff --git a/drivers/gpio/gpiolib-cdev.c b/drivers/gpio/gpiolib-cdev.c index d829f7d00b5e0d..ceecce572a520a 100644 --- a/drivers/gpio/gpiolib-cdev.c +++ b/drivers/gpio/gpiolib-cdev.c @@ -1590,19 +1590,25 @@ static void linereq_free(struct linereq *lr) { unsigned int i; + /* + * Stop edge detection while still registered for the notification, so + * that gpiochip_remove() does not get past it until the IRQs are freed. + */ + scoped_guard(mutex, &lr->config_mutex) { + for (i = 0; i < lr->num_lines; i++) + edge_detector_stop(&lr->lines[i]); + } + if (lr->device_unregistered_nb.notifier_call) blocking_notifier_chain_unregister(&lr->gdev->device_notifier, &lr->device_unregistered_nb); - for (i = 0; i < lr->num_lines; i++) { - if (lr->lines[i].desc) { - edge_detector_stop(&lr->lines[i]); - gpiod_free(lr->lines[i].desc); - } - } + for (i = 0; i < lr->num_lines; i++) + gpiod_free(lr->lines[i].desc); kfifo_free(&lr->events); kfree(lr->label); gpio_device_put(lr->gdev); + mutex_destroy(&lr->config_mutex); kvfree(lr); } @@ -1673,6 +1679,7 @@ static int linereq_create(struct gpio_device *gdev, void __user *ip) if (!lr) return -ENOMEM; lr->num_lines = ulr.num_lines; + mutex_init(&lr->config_mutex); lr->gdev = gpio_device_get(gdev); @@ -1690,7 +1697,6 @@ static int linereq_create(struct gpio_device *gdev, void __user *ip) return -ENOMEM; } - mutex_init(&lr->config_mutex); init_waitqueue_head(&lr->wait); INIT_KFIFO(lr->events); lr->event_buffer_size = ulr.event_buffer_size; @@ -1790,6 +1796,7 @@ static int linereq_create(struct gpio_device *gdev, void __user *ip) * @eflags: the event flags this line was requested with * @irq: the interrupt that trigger in response to events on this GPIO * @irq_label: the name @irq was requested with + * @irq_lock: serializes freeing @irq on release and on chip removal * @wait: wait queue that handles blocking reads of events * @device_unregistered_nb: notifier block for receiving gdev unregister events * @events: KFIFO for the GPIO events @@ -1804,6 +1811,8 @@ struct lineevent_state { u32 eflags; int irq; char *irq_label; + /* release vs. chip removal notifier */ + struct mutex irq_lock; wait_queue_head_t wait; struct notifier_block device_unregistered_nb; DECLARE_KFIFO(events, struct gpioevent_data, 16); @@ -1839,8 +1848,10 @@ static int lineevent_unregistered_notify(struct notifier_block *nb, struct lineevent_state *le = container_of(nb, struct lineevent_state, device_unregistered_nb); - free_line_irq(le->irq, le, &le->irq_label); - le->irq = 0; + scoped_guard(mutex, &le->irq_lock) { + free_line_irq(le->irq, le, &le->irq_label); + le->irq = 0; + } wake_up_poll(&le->wait, EPOLLIN | EPOLLERR); @@ -1920,14 +1931,18 @@ static ssize_t lineevent_read(struct file *file, char __user *buf, static void lineevent_free(struct lineevent_state *le) { + scoped_guard(mutex, &le->irq_lock) { + free_line_irq(le->irq, le, &le->irq_label); + le->irq = 0; + } if (le->device_unregistered_nb.notifier_call) blocking_notifier_chain_unregister(&le->gdev->device_notifier, &le->device_unregistered_nb); - free_line_irq(le->irq, le, &le->irq_label); if (le->desc) gpiod_free(le->desc); kfree(le->label); gpio_device_put(le->gdev); + mutex_destroy(&le->irq_lock); kfree(le); } @@ -2101,6 +2116,7 @@ static int lineevent_create(struct gpio_device *gdev, void __user *ip) le = kzalloc_obj(*le); if (!le) return -ENOMEM; + mutex_init(&le->irq_lock); le->gdev = gpio_device_get(gdev); if (eventreq.consumer_label[0] != '\0') { @@ -2836,5 +2852,4 @@ int gpiolib_cdev_register(struct gpio_chip *gc, dev_t devt) void gpiolib_cdev_unregister(struct gpio_device *gdev) { cdev_device_del(&gdev->chrdev, &gdev->dev); - blocking_notifier_call_chain(&gdev->device_notifier, 0, NULL); } diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index 9832f755312fa0..e0ba17a73c4b49 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -854,11 +854,22 @@ bool gpiochip_line_is_valid(const struct gpio_chip *gc, } EXPORT_SYMBOL_GPL(gpiochip_line_is_valid); -static void gpiod_free_irqs(struct gpio_desc *desc) +static void gpiod_free_irqs(struct gpio_chip *gc, struct gpio_desc *desc) { - int irq = gpiod_to_irq(desc); - struct irq_desc *irqd = irq_to_desc(irq); + struct irq_desc *irqd; void *cookie; + int irq; + + /* Called with gdev->chip already NULL, so gpiod_to_irq() can't be used. */ + if (!gc->to_irq) + return; + irq = gc->to_irq(gc, gpiod_hwgpio(desc)); + if (irq <= 0) + return; + + irqd = irq_to_desc(irq); + if (!irqd) + return; for (;;) { /* @@ -890,7 +901,7 @@ static void gpiochip_free_remaining_irqs(struct gpio_chip *gc) struct gpio_desc *desc; for_each_gpio_desc_with_flag(gc, desc, GPIOD_FLAG_USED_AS_IRQ) - gpiod_free_irqs(desc); + gpiod_free_irqs(gc, desc); } static void gpiodev_release(struct device *dev) @@ -1439,7 +1450,6 @@ void gpiochip_remove(struct gpio_chip *gc) /* FIXME: should the legacy sysfs handling be moved to gpio_device? */ gpiochip_sysfs_unregister(gc); gpiochip_free_hogs(gc); - gpiochip_free_remaining_irqs(gc); scoped_guard(mutex, &gpio_devices_lock) list_del_rcu(&gdev->list); @@ -1448,6 +1458,14 @@ void gpiochip_remove(struct gpio_chip *gc) /* Numb the device, cancelling all outstanding operations */ rcu_assign_pointer(gdev->chip, NULL); synchronize_srcu(&gdev->srcu); + + /* + * No new interrupts can be requested through the character device now. + * Have it free the ones it holds before forcibly freeing the rest, and + * both before the irqchip and its mappings go away. + */ + blocking_notifier_call_chain(&gdev->device_notifier, 0, NULL); + gpiochip_free_remaining_irqs(gc); gpio_device_teardown_shared(gdev); gpiochip_irqchip_remove(gc); acpi_gpiochip_remove(gc); From 1f7d535465a5568187cbdfec3beb734bfb5e5015 Mon Sep 17 00:00:00 2001 From: Adrian Ambrozewicz Date: Tue, 24 Nov 2026 11:20:39 +0200 Subject: [PATCH 1683/2102] gpiolib: remove the shared GPIO proxies before freeing the remaining IRQs gpio_shared_proxy_to_irq() returns the parent chip's IRQ, so an edge request on a proxy line holds an IRQ of the parent. When the parent is removed, gpiochip_remove() frees the IRQs still requested on its lines before it removes the proxies in gpio_device_teardown_shared(). The release of a proxy line request is serialized only with the proxy's own removal notifier, so if gpiod_free_irqs() frees the IRQ between the release's irq_has_action() check and its free_irq(), free_irq() warns: Trying to free already-free IRQ 22 Remove the proxies first, so the character device on each proxy frees its IRQs before the rest are forcibly freed. Reproduced on arm64 QEMU with a shared gpio-sim line and a test delay before the release's free_irq(): 3 of 3 runs warned; with this change, none. Fixes: 1e4f6db614a3 ("gpiolib: support shared GPIOs in core subsystem code") Cc: stable@vger.kernel.org Reported-by: Sashiko Closes: https://sashiko.dev/#/patchset/20261103-gpiolib-chip-removal-v5-0-aambrozewicz@nvidia.com?part=7 Signed-off-by: Adrian Ambrozewicz Reviewed-by: Kent Gibson Link: https://patch.msgid.link/20261124-gpiolib-chip-removal-v8-8-aambrozewicz@nvidia.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index e0ba17a73c4b49..57024a1b042b68 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -1461,12 +1461,12 @@ void gpiochip_remove(struct gpio_chip *gc) /* * No new interrupts can be requested through the character device now. - * Have it free the ones it holds before forcibly freeing the rest, and - * both before the irqchip and its mappings go away. + * Have it free the ones it holds, also on the shared proxies, before + * forcibly freeing the rest and removing the irqchip. */ blocking_notifier_call_chain(&gdev->device_notifier, 0, NULL); - gpiochip_free_remaining_irqs(gc); gpio_device_teardown_shared(gdev); + gpiochip_free_remaining_irqs(gc); gpiochip_irqchip_remove(gc); acpi_gpiochip_remove(gc); of_gpiochip_remove(gc); From 3f137feaad8e56597493fc7dd2bc70a6248f9a69 Mon Sep 17 00:00:00 2001 From: Willem de Bruijn Date: Thu, 19 Nov 2026 23:46:39 -0500 Subject: [PATCH 1684/2102] net: gso: cow head on tcp fraglist fallback to skb_segment When tcp4_gso_segment() or tcp6_gso_segment() cannot use skb_segment_list(), they fall back to tcp_gso_segment(), first resetting th->check to the pseudo-header sum. This writes to skb->head without unsharing it. If the skb is cloned, e.g., by a packet socket on a bridge port, the other holders see the rewritten checksum. Call skb_cow_head(), like skb_segment_list() and the UDP fallback already unshare the head with skb_unclone() and __skb_linearize(). skb_header_cloned() is equivalent to skb_cloned() here, as GRO does not set nohdr on the head of fraglist skbs. Discovered by an AI code review agent. Reproduced on an unmodified kernel with bridged veth devices and an AF_PACKET socket, and verified in virtme-ng. Fixes: 17bd3bd82f9f ("net: gso: fix tcp fraglist segmentation after pull from frag_list") Cc: stable@vger.kernel.org Signed-off-by: Willem de Bruijn Link: https://patch.msgid.link/20261120044733.222627-2-willemdebruijn.kernel@gmail.com Signed-off-by: Paolo Abeni --- net/ipv4/tcp_offload.c | 5 +++++ net/ipv6/tcpv6_offload.c | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/net/ipv4/tcp_offload.c b/net/ipv4/tcp_offload.c index b84fcd07c7230f..520778c5ca7f75 100644 --- a/net/ipv4/tcp_offload.c +++ b/net/ipv4/tcp_offload.c @@ -106,11 +106,16 @@ static struct sk_buff *tcp4_gso_segment(struct sk_buff *skb, if (skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST) { struct tcphdr *th = tcp_hdr(skb); + int err; if ((skb_pagelen(skb) - th->doff * 4 == skb_shinfo(skb)->gso_size) && !(skb_shinfo(skb)->gso_type & SKB_GSO_DODGY)) return __tcp4_gso_segment_list(skb, features); + err = skb_cow_head(skb, 0); + if (err < 0) + return ERR_PTR(err); + skb->ip_summed = CHECKSUM_NONE; } diff --git a/net/ipv6/tcpv6_offload.c b/net/ipv6/tcpv6_offload.c index eec3778855eb89..0914f95f100c79 100644 --- a/net/ipv6/tcpv6_offload.c +++ b/net/ipv6/tcpv6_offload.c @@ -178,11 +178,16 @@ static struct sk_buff *tcp6_gso_segment(struct sk_buff *skb, if (skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST) { struct tcphdr *th = tcp_hdr(skb); + int err; if ((skb_pagelen(skb) - th->doff * 4 == skb_shinfo(skb)->gso_size) && !(skb_shinfo(skb)->gso_type & SKB_GSO_DODGY)) return __tcp6_gso_segment_list(skb, features); + err = skb_cow_head(skb, 0); + if (err < 0) + return ERR_PTR(err); + skb->ip_summed = CHECKSUM_NONE; } From ab5b219a7340b0083fca4ea4d55409d126512856 Mon Sep 17 00:00:00 2001 From: Willem de Bruijn Date: Thu, 19 Nov 2026 23:46:40 -0500 Subject: [PATCH 1685/2102] net: gso: fall back to skb_segment when fraglist cannot satisfy checksum skb_segment_list() keeps the original headers and checksum state of the frag_list members. It ignores the checksum features and does not set up the SKB_GSO_CB() checksum state. This breaks: 1. Outer tunnel checksums. __skb_udp_tunnel_segment() and gre_gso_segment() compute these with gso_make_checksum(), which reads stale SKB_GSO_CB() state, and needs an inner payload sum that skb_segment_list() does not compute. 2. CHECKSUM_PARTIAL packets, e.g., from veth or tun, sent to a device without checksum offload. Unlike skb_segment(), skb_segment_list() does not resolve these. Extend the existing fallback to skb_segment() for modified geometry and SKB_GSO_DODGY, from commit 17bd3bd82f9f ("net: gso: fix tcp fraglist segmentation after pull from frag_list"), to when: - skb_tnl_header_len() is non-zero: UDP, GRE and MPLS tunnels (case 1). - the features cannot checksum a CHECKSUM_PARTIAL packet (case 2). - skb->encapsulation is set: encapsulations not seen by skb_tnl_header_len(). For example, ESP with xfrm offload in transport mode, as skb_segment_list() does not copy the ESP header and IV to the frag_list members. IPIP and SIT are excluded too, for simplicity. Share this test between TCP and UDP in skb_gso_fraglist_ok(). This moves some correctly handled tunnel traffic to the slower skb_segment(). Fraglist GRO is off by default. Discovered through analysis by an LLM. Reproduced on an unmodified kernel and verified with LLM-generated reproducers in virtme-ng. Fixes: 9fd1ff5d2ac7 ("udp: Support UDP fraglist GRO/GSO.") Fixes: bee88cd5bd83 ("net: add support for segmenting TCP fraglist GSO packets") Cc: stable@vger.kernel.org Reported-by: Hassan Sultan Signed-off-by: Willem de Bruijn Link: https://patch.msgid.link/20261120044733.222627-3-willemdebruijn.kernel@gmail.com Signed-off-by: Paolo Abeni --- include/net/gso.h | 33 +++++++++++++++++++++++++++++++++ net/ipv4/tcp_offload.c | 5 ++--- net/ipv4/udp_offload.c | 5 +++-- net/ipv6/tcpv6_offload.c | 6 +++--- 4 files changed, 41 insertions(+), 8 deletions(-) diff --git a/include/net/gso.h b/include/net/gso.h index 119fc4c170e164..6cf6a6dee234c3 100644 --- a/include/net/gso.h +++ b/include/net/gso.h @@ -3,6 +3,7 @@ #ifndef _NET_GSO_H #define _NET_GSO_H +#include #include /* Keeps track of mac header offset relative to skb->head. @@ -39,6 +40,38 @@ static inline int skb_tnl_header_len(const struct sk_buff *inner_skb) SKB_GSO_CB(inner_skb)->mac_offset; } +/** + * skb_gso_fraglist_ok - test whether skb_segment_list() can segment an skb + * @skb: SKB_GSO_FRAGLIST skb to segment + * @features: features for the output path + * @hdrlen: transport header length + * @proto: network protocol, for checksum offload + * + * Return: false if the skb must be passed to the more general skb_segment(). + */ +static inline bool skb_gso_fraglist_ok(const struct sk_buff *skb, + netdev_features_t features, + unsigned int hdrlen, __be16 proto) +{ + /* Geometry modified, e.g., by a pull from frag_list */ + if (skb_pagelen(skb) - hdrlen != skb_shinfo(skb)->gso_size) + return false; + + if (skb_shinfo(skb)->gso_type & SKB_GSO_DODGY) + return false; + + /* Tunnel headers and outer checksums are not rebuilt */ + if (skb->encapsulation || skb_tnl_header_len(skb)) + return false; + + /* Checksums are not resolved in software */ + if (skb->ip_summed == CHECKSUM_PARTIAL && + !can_checksum_protocol(features, proto)) + return false; + + return true; +} + static inline int gso_pskb_expand_head(struct sk_buff *skb, int extra) { int new_headroom, headroom; diff --git a/net/ipv4/tcp_offload.c b/net/ipv4/tcp_offload.c index 520778c5ca7f75..7691be01da4d28 100644 --- a/net/ipv4/tcp_offload.c +++ b/net/ipv4/tcp_offload.c @@ -105,11 +105,10 @@ static struct sk_buff *tcp4_gso_segment(struct sk_buff *skb, return ERR_PTR(-EINVAL); if (skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST) { - struct tcphdr *th = tcp_hdr(skb); int err; - if ((skb_pagelen(skb) - th->doff * 4 == skb_shinfo(skb)->gso_size) && - !(skb_shinfo(skb)->gso_type & SKB_GSO_DODGY)) + if (skb_gso_fraglist_ok(skb, features, tcp_hdrlen(skb), + htons(ETH_P_IP))) return __tcp4_gso_segment_list(skb, features); err = skb_cow_head(skb, 0); diff --git a/net/ipv4/udp_offload.c b/net/ipv4/udp_offload.c index b77ae2f00c626c..243bd75302d83b 100644 --- a/net/ipv4/udp_offload.c +++ b/net/ipv4/udp_offload.c @@ -519,8 +519,9 @@ struct sk_buff *__udp_gso_segment(struct sk_buff *gso_skb, * the frag_list skbs still have the IP family we segment for, * as their network headers are not rebuilt. */ - if ((skb_pagelen(gso_skb) - sizeof(*uh) == skb_shinfo(gso_skb)->gso_size) && - !(skb_shinfo(gso_skb)->gso_type & SKB_GSO_DODGY) && + if (skb_gso_fraglist_ok(gso_skb, features, sizeof(*uh), + is_ipv6 ? htons(ETH_P_IPV6) : + htons(ETH_P_IP)) && ip_hdr(skb_shinfo(gso_skb)->frag_list)->version == (is_ipv6 ? 6 : 4)) return __udp_gso_segment_list(gso_skb, features, is_ipv6); diff --git a/net/ipv6/tcpv6_offload.c b/net/ipv6/tcpv6_offload.c index 0914f95f100c79..71feb92aeac28a 100644 --- a/net/ipv6/tcpv6_offload.c +++ b/net/ipv6/tcpv6_offload.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -177,11 +178,10 @@ static struct sk_buff *tcp6_gso_segment(struct sk_buff *skb, return ERR_PTR(-EINVAL); if (skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST) { - struct tcphdr *th = tcp_hdr(skb); int err; - if ((skb_pagelen(skb) - th->doff * 4 == skb_shinfo(skb)->gso_size) && - !(skb_shinfo(skb)->gso_type & SKB_GSO_DODGY)) + if (skb_gso_fraglist_ok(skb, features, tcp_hdrlen(skb), + htons(ETH_P_IPV6))) return __tcp6_gso_segment_list(skb, features); err = skb_cow_head(skb, 0); From e479ed6b6ccf660f5e9c20f2673c98727d2b5679 Mon Sep 17 00:00:00 2001 From: Dmitry Torokhov Date: Mon, 23 Nov 2026 15:00:54 -0800 Subject: [PATCH 1686/2102] ASoC: arizona: convert audio pdata parsing to generic device properties Switch audio platform data parsing in the shared Arizona ASoC helper from OF-only property APIs to generic device property APIs so audio parameters can be provided via software nodes or ACPI in addition to Device Tree. Align the audio configuration array types in struct arizona_pdata with generic property types so properties can be read directly into platform data, using boolean storage for out-mono flags and bounded array reads that preserve unspecified trailing elements. Drop the CONFIG_OF guards and obsolete error checks around the audio property parsing calls in all Arizona codec drivers. Signed-off-by: Dmitry Torokhov Link: https://patch.msgid.link/20261123-arizona-asoc-v2-1-6323d3c0961a@gmail.com Signed-off-by: Mark Brown --- include/linux/mfd/arizona/pdata.h | 15 ++-- sound/soc/codecs/arizona.c | 121 +++++++++++++++--------------- sound/soc/codecs/arizona.h | 2 +- sound/soc/codecs/cs47l24.c | 9 +-- sound/soc/codecs/wm5102.c | 9 +-- sound/soc/codecs/wm5110.c | 9 +-- sound/soc/codecs/wm8997.c | 9 +-- sound/soc/codecs/wm8998.c | 9 +-- 8 files changed, 79 insertions(+), 104 deletions(-) diff --git a/include/linux/mfd/arizona/pdata.h b/include/linux/mfd/arizona/pdata.h index d465dcd8c90aaf..984b2edfec0782 100644 --- a/include/linux/mfd/arizona/pdata.h +++ b/include/linux/mfd/arizona/pdata.h @@ -11,6 +11,7 @@ #include #include #include +#include #define ARIZONA_GPN_DIR_MASK 0x8000 /* GPN_DIR */ #define ARIZONA_GPN_DIR_SHIFT 15 /* GPN_DIR */ @@ -100,7 +101,7 @@ struct arizona_pdata { * useful for systems where and I2S bus with multiple data * lines is mastered. */ - unsigned int max_channels_clocked[ARIZONA_MAX_AIF]; + u32 max_channels_clocked[ARIZONA_MAX_AIF]; /** GPIO5 is used for jack detection */ bool jd_gpio5; @@ -150,7 +151,7 @@ struct arizona_pdata { int num_micd_configs; /** Reference voltage for DMIC inputs */ - int dmic_ref[ARIZONA_MAX_INPUT]; + u32 dmic_ref[ARIZONA_MAX_INPUT]; /** MICBIAS configurations */ struct arizona_micbias micbias[ARIZONA_MAX_MICBIAS]; @@ -161,19 +162,19 @@ struct arizona_pdata { * wm5102/wm5110/wm8280/wm8997: [0]=IN1 [1]=IN2 [2]=IN3 [3]=IN4 * wm8998: [0]=IN1A [1]=IN2A [2]=IN1B [3]=IN2B */ - int inmode[ARIZONA_MAX_INPUT]; + u32 inmode[ARIZONA_MAX_INPUT]; /** Mode for outputs */ - int out_mono[ARIZONA_MAX_OUTPUT]; + bool out_mono[ARIZONA_MAX_OUTPUT]; /** Limit output volumes */ - unsigned int out_vol_limit[2 * ARIZONA_MAX_OUTPUT]; + u32 out_vol_limit[2 * ARIZONA_MAX_OUTPUT]; /** PDM speaker mute setting */ - unsigned int spk_mute[ARIZONA_MAX_PDM_SPK]; + u32 spk_mute[ARIZONA_MAX_PDM_SPK]; /** PDM speaker format */ - unsigned int spk_fmt[ARIZONA_MAX_PDM_SPK]; + u32 spk_fmt[ARIZONA_MAX_PDM_SPK]; /** Haptic actuator type */ unsigned int hap_act; diff --git a/sound/soc/codecs/arizona.c b/sound/soc/codecs/arizona.c index 7c296c5b24f726..46e2ca48e70fa1 100644 --- a/sound/soc/codecs/arizona.c +++ b/sound/soc/codecs/arizona.c @@ -11,8 +11,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -2799,77 +2799,76 @@ int arizona_lhpf_coeff_put(struct snd_kcontrol *kcontrol, } EXPORT_SYMBOL_GPL(arizona_lhpf_coeff_put); -int arizona_of_get_audio_pdata(struct arizona *arizona) +static int arizona_get_variable_u32_array(struct device *dev, + const char *propname, + u32 *dest, size_t n_max) { - struct arizona_pdata *pdata = &arizona->pdata; - struct device_node *np = arizona->dev->of_node; - u32 val; - u32 pdm_val[ARIZONA_MAX_PDM_SPK]; - int ret; - int count = 0; - - count = 0; - of_property_for_each_u32(np, "wlf,inmode", val) { - if (count == ARRAY_SIZE(pdata->inmode)) - break; - - pdata->inmode[count] = val; - count++; - } + int n, ret; - count = 0; - of_property_for_each_u32(np, "wlf,dmic-ref", val) { - if (count == ARRAY_SIZE(pdata->dmic_ref)) - break; - - pdata->dmic_ref[count] = val; - count++; - } + n = device_property_count_u32(dev, propname); + if (n < 0) { + if (n == -EINVAL) + return 0; /* missing, ignore */ - count = 0; - of_property_for_each_u32(np, "wlf,out-mono", val) { - if (count == ARRAY_SIZE(pdata->out_mono)) - break; - - pdata->out_mono[count] = !!val; - count++; + dev_warn(dev, "%s malformed (%d)\n", propname, n); + return n; } - count = 0; - of_property_for_each_u32(np, "wlf,max-channels-clocked", val) { - if (count == ARRAY_SIZE(pdata->max_channels_clocked)) - break; - - pdata->max_channels_clocked[count] = val; - count++; - } + if (!n) + return 0; - count = 0; - of_property_for_each_u32(np, "wlf,out-volume-limit", val) { - if (count == ARRAY_SIZE(pdata->out_vol_limit)) - break; + if (n > n_max) + n = n_max; - pdata->out_vol_limit[count] = val; - count++; + ret = device_property_read_u32_array(dev, propname, dest, n); + if (ret < 0) { + dev_warn(dev, "Failed to read %s (%d)\n", propname, ret); + return ret; } - ret = of_property_read_u32_array(np, "wlf,spk-fmt", - pdm_val, ARRAY_SIZE(pdm_val)); - - if (ret >= 0) - for (count = 0; count < ARRAY_SIZE(pdata->spk_fmt); ++count) - pdata->spk_fmt[count] = pdm_val[count]; - - ret = of_property_read_u32_array(np, "wlf,spk-mute", - pdm_val, ARRAY_SIZE(pdm_val)); - - if (ret >= 0) - for (count = 0; count < ARRAY_SIZE(pdata->spk_mute); ++count) - pdata->spk_mute[count] = pdm_val[count]; + return n; +} - return 0; +void arizona_get_audio_pdata(struct arizona *arizona) +{ + struct arizona_pdata *pdata = &arizona->pdata; + u32 out_mono[ARRAY_SIZE(pdata->out_mono)]; + int i, n, ret; + + arizona_get_variable_u32_array(arizona->dev, "wlf,inmode", + pdata->inmode, + ARRAY_SIZE(pdata->inmode)); + + arizona_get_variable_u32_array(arizona->dev, "wlf,dmic-ref", + pdata->dmic_ref, + ARRAY_SIZE(pdata->dmic_ref)); + + n = arizona_get_variable_u32_array(arizona->dev, "wlf,out-mono", + out_mono, ARRAY_SIZE(out_mono)); + for (i = 0; i < n; i++) + pdata->out_mono[i] = !!out_mono[i]; + + arizona_get_variable_u32_array(arizona->dev, "wlf,max-channels-clocked", + pdata->max_channels_clocked, + ARRAY_SIZE(pdata->max_channels_clocked)); + + arizona_get_variable_u32_array(arizona->dev, "wlf,out-volume-limit", + pdata->out_vol_limit, + ARRAY_SIZE(pdata->out_vol_limit)); + + ret = device_property_read_u32_array(arizona->dev, "wlf,spk-fmt", + pdata->spk_fmt, + ARRAY_SIZE(pdata->spk_fmt)); + if (ret && ret != -EINVAL) + dev_warn(arizona->dev, "Failed to read wlf,spk-fmt (%d)\n", ret); + + ret = device_property_read_u32_array(arizona->dev, "wlf,spk-mute", + pdata->spk_mute, + ARRAY_SIZE(pdata->spk_mute)); + if (ret && ret != -EINVAL) + dev_warn(arizona->dev, "Failed to read wlf,spk-mute (%d)\n", ret); } -EXPORT_SYMBOL_GPL(arizona_of_get_audio_pdata); +EXPORT_SYMBOL_GPL(arizona_get_audio_pdata); MODULE_DESCRIPTION("ASoC Wolfson Arizona class device support"); MODULE_AUTHOR("Mark Brown "); diff --git a/sound/soc/codecs/arizona.h b/sound/soc/codecs/arizona.h index 0703182d87b3e9..499891e62183fb 100644 --- a/sound/soc/codecs/arizona.h +++ b/sound/soc/codecs/arizona.h @@ -388,7 +388,7 @@ static inline int arizona_unregister_notifier(struct snd_soc_component *componen return blocking_notifier_chain_unregister(&arizona->notifier, nb); } -int arizona_of_get_audio_pdata(struct arizona *arizona); +void arizona_get_audio_pdata(struct arizona *arizona); int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev); int arizona_jack_codec_dev_remove(struct arizona_priv *info); diff --git a/sound/soc/codecs/cs47l24.c b/sound/soc/codecs/cs47l24.c index fa2d01ead30bb8..4c09b476b77a56 100644 --- a/sound/soc/codecs/cs47l24.c +++ b/sound/soc/codecs/cs47l24.c @@ -1221,13 +1221,8 @@ static int cs47l24_probe(struct platform_device *pdev) if (!cs47l24) return -ENOMEM; - if (IS_ENABLED(CONFIG_OF)) { - if (!dev_get_platdata(arizona->dev)) { - ret = arizona_of_get_audio_pdata(arizona); - if (ret < 0) - return ret; - } - } + if (!dev_get_platdata(arizona->dev)) + arizona_get_audio_pdata(arizona); platform_set_drvdata(pdev, cs47l24); diff --git a/sound/soc/codecs/wm5102.c b/sound/soc/codecs/wm5102.c index 762e81979cb8d4..35b7c034b51707 100644 --- a/sound/soc/codecs/wm5102.c +++ b/sound/soc/codecs/wm5102.c @@ -2040,13 +2040,8 @@ static int wm5102_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm5102); - if (IS_ENABLED(CONFIG_OF)) { - if (!dev_get_platdata(arizona->dev)) { - ret = arizona_of_get_audio_pdata(arizona); - if (ret < 0) - return ret; - } - } + if (!dev_get_platdata(arizona->dev)) + arizona_get_audio_pdata(arizona); mutex_init(&arizona->dac_comp_lock); diff --git a/sound/soc/codecs/wm5110.c b/sound/soc/codecs/wm5110.c index faa85d88a489bc..312c55ab7cd5d9 100644 --- a/sound/soc/codecs/wm5110.c +++ b/sound/soc/codecs/wm5110.c @@ -2402,13 +2402,8 @@ static int wm5110_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm5110); - if (IS_ENABLED(CONFIG_OF)) { - if (!dev_get_platdata(arizona->dev)) { - ret = arizona_of_get_audio_pdata(arizona); - if (ret < 0) - return ret; - } - } + if (!dev_get_platdata(arizona->dev)) + arizona_get_audio_pdata(arizona); wm5110->core.arizona = arizona; wm5110->core.num_inputs = 8; diff --git a/sound/soc/codecs/wm8997.c b/sound/soc/codecs/wm8997.c index f041dfc905a427..4d0c3a54bd1697 100644 --- a/sound/soc/codecs/wm8997.c +++ b/sound/soc/codecs/wm8997.c @@ -1118,13 +1118,8 @@ static int wm8997_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm8997); - if (IS_ENABLED(CONFIG_OF)) { - if (!dev_get_platdata(arizona->dev)) { - ret = arizona_of_get_audio_pdata(arizona); - if (ret < 0) - return ret; - } - } + if (!dev_get_platdata(arizona->dev)) + arizona_get_audio_pdata(arizona); wm8997->core.arizona = arizona; wm8997->core.num_inputs = 4; diff --git a/sound/soc/codecs/wm8998.c b/sound/soc/codecs/wm8998.c index 1158e9ca40a132..3ae19f03f29a89 100644 --- a/sound/soc/codecs/wm8998.c +++ b/sound/soc/codecs/wm8998.c @@ -1345,13 +1345,8 @@ static int wm8998_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm8998); - if (IS_ENABLED(CONFIG_OF)) { - if (!dev_get_platdata(arizona->dev)) { - ret = arizona_of_get_audio_pdata(arizona); - if (ret < 0) - return ret; - } - } + if (!dev_get_platdata(arizona->dev)) + arizona_get_audio_pdata(arizona); wm8998->core.arizona = arizona; wm8998->core.num_inputs = 3; /* IN1L, IN1R, IN2 */ From 53136aa2d64da6df5aac79f4637babf07eefb57a Mon Sep 17 00:00:00 2001 From: Dmitry Torokhov Date: Mon, 23 Nov 2026 15:00:55 -0800 Subject: [PATCH 1687/2102] ASoC: arizona: always parse device properties regardless of platform data Always parse device properties in the Arizona jack detection driver and codec drivers even when platform data is provided, allowing DT, ACPI, or software node properties to augment platform data configurations. In the jack detection driver, only validate and apply the wlf,hpdet-channel property when it is present, leaving any existing platform data value untouched when the property is absent or invalid, and preserve existing boolean flags using bitwise OR assignments. Default an unset headphone detection channel (0, corresponding to ARIZONA_ACCDET_MODE_MIC and invalid for headphone impedance polling) to ARIZONA_ACCDET_MODE_HPL during jack probe. Commit 9e86b2ad4c11 ("extcon: arizona: Add support for select accessory detect mode when headphone detection") originally placed this default only in the OF property parser, inadvertently leaving platform-data boards that omit the channel setting at 0. Signed-off-by: Dmitry Torokhov Link: https://patch.msgid.link/20261123-arizona-asoc-v2-2-6323d3c0961a@gmail.com Signed-off-by: Mark Brown --- sound/soc/codecs/arizona-jack.c | 50 ++++++++++++++++++--------------- sound/soc/codecs/cs47l24.c | 3 +- sound/soc/codecs/wm5102.c | 3 +- sound/soc/codecs/wm5110.c | 3 +- sound/soc/codecs/wm8997.c | 3 +- sound/soc/codecs/wm8998.c | 3 +- 6 files changed, 33 insertions(+), 32 deletions(-) diff --git a/sound/soc/codecs/arizona-jack.c b/sound/soc/codecs/arizona-jack.c index db60ea1aaec8a6..f36d314a6a5498 100644 --- a/sound/soc/codecs/arizona-jack.c +++ b/sound/soc/codecs/arizona-jack.c @@ -1183,18 +1183,20 @@ static int arizona_extcon_device_get_pdata(struct device *dev, struct arizona *arizona) { struct arizona_pdata *pdata = &arizona->pdata; - unsigned int val = ARIZONA_ACCDET_MODE_HPL; + unsigned int val; int ret; - device_property_read_u32(arizona->dev, "wlf,hpdet-channel", &val); - switch (val) { - case ARIZONA_ACCDET_MODE_HPL: - case ARIZONA_ACCDET_MODE_HPR: - pdata->hpdet_channel = val; - break; - default: - dev_err(arizona->dev, "Wrong wlf,hpdet-channel DT value %d\n", val); - pdata->hpdet_channel = ARIZONA_ACCDET_MODE_HPL; + if (!device_property_read_u32(arizona->dev, "wlf,hpdet-channel", &val)) { + switch (val) { + case ARIZONA_ACCDET_MODE_HPL: + case ARIZONA_ACCDET_MODE_HPR: + pdata->hpdet_channel = val; + break; + default: + dev_err(arizona->dev, + "Wrong wlf,hpdet-channel DT value %d\n", val); + break; + } } device_property_read_u32(arizona->dev, "wlf,micd-detect-debounce", @@ -1212,21 +1214,23 @@ static int arizona_extcon_device_get_pdata(struct device *dev, device_property_read_u32(arizona->dev, "wlf,micd-timeout-ms", &pdata->micd_timeout); - pdata->micd_force_micbias = device_property_read_bool(arizona->dev, - "wlf,micd-force-micbias"); + pdata->micd_force_micbias |= + device_property_read_bool(arizona->dev, + "wlf,micd-force-micbias"); - pdata->micd_software_compare = device_property_read_bool(arizona->dev, - "wlf,micd-software-compare"); + pdata->micd_software_compare |= + device_property_read_bool(arizona->dev, + "wlf,micd-software-compare"); - pdata->jd_invert = device_property_read_bool(arizona->dev, - "wlf,jd-invert"); + pdata->jd_invert |= device_property_read_bool(arizona->dev, + "wlf,jd-invert"); device_property_read_u32(arizona->dev, "wlf,gpsw", &pdata->gpsw); - pdata->jd_gpio5 = device_property_read_bool(arizona->dev, - "wlf,use-jd2"); - pdata->jd_gpio5_nopull = device_property_read_bool(arizona->dev, - "wlf,use-jd2-nopull"); + pdata->jd_gpio5 |= device_property_read_bool(arizona->dev, + "wlf,use-jd2"); + pdata->jd_gpio5_nopull |= + device_property_read_bool(arizona->dev, "wlf,use-jd2-nopull"); ret = arizona_extcon_get_micd_configs(dev, arizona); if (ret < 0) @@ -1241,8 +1245,7 @@ int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev) struct arizona_pdata *pdata = &arizona->pdata; int ret, mode; - if (!dev_get_platdata(arizona->dev)) - arizona_extcon_device_get_pdata(dev, arizona); + arizona_extcon_device_get_pdata(dev, arizona); info->micvdd = devm_regulator_get(dev, "MICVDD"); if (IS_ERR(info->micvdd)) @@ -1286,6 +1289,9 @@ int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev) break; } + if (!pdata->hpdet_channel) + pdata->hpdet_channel = ARIZONA_ACCDET_MODE_HPL; + if (!pdata->micd_timeout) pdata->micd_timeout = DEFAULT_MICD_TIMEOUT; diff --git a/sound/soc/codecs/cs47l24.c b/sound/soc/codecs/cs47l24.c index 4c09b476b77a56..744a610cd1afe3 100644 --- a/sound/soc/codecs/cs47l24.c +++ b/sound/soc/codecs/cs47l24.c @@ -1221,8 +1221,7 @@ static int cs47l24_probe(struct platform_device *pdev) if (!cs47l24) return -ENOMEM; - if (!dev_get_platdata(arizona->dev)) - arizona_get_audio_pdata(arizona); + arizona_get_audio_pdata(arizona); platform_set_drvdata(pdev, cs47l24); diff --git a/sound/soc/codecs/wm5102.c b/sound/soc/codecs/wm5102.c index 35b7c034b51707..b52f1d30c3c05b 100644 --- a/sound/soc/codecs/wm5102.c +++ b/sound/soc/codecs/wm5102.c @@ -2040,8 +2040,7 @@ static int wm5102_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm5102); - if (!dev_get_platdata(arizona->dev)) - arizona_get_audio_pdata(arizona); + arizona_get_audio_pdata(arizona); mutex_init(&arizona->dac_comp_lock); diff --git a/sound/soc/codecs/wm5110.c b/sound/soc/codecs/wm5110.c index 312c55ab7cd5d9..34a6ef55553010 100644 --- a/sound/soc/codecs/wm5110.c +++ b/sound/soc/codecs/wm5110.c @@ -2402,8 +2402,7 @@ static int wm5110_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm5110); - if (!dev_get_platdata(arizona->dev)) - arizona_get_audio_pdata(arizona); + arizona_get_audio_pdata(arizona); wm5110->core.arizona = arizona; wm5110->core.num_inputs = 8; diff --git a/sound/soc/codecs/wm8997.c b/sound/soc/codecs/wm8997.c index 4d0c3a54bd1697..f4608c1f16bb6c 100644 --- a/sound/soc/codecs/wm8997.c +++ b/sound/soc/codecs/wm8997.c @@ -1118,8 +1118,7 @@ static int wm8997_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm8997); - if (!dev_get_platdata(arizona->dev)) - arizona_get_audio_pdata(arizona); + arizona_get_audio_pdata(arizona); wm8997->core.arizona = arizona; wm8997->core.num_inputs = 4; diff --git a/sound/soc/codecs/wm8998.c b/sound/soc/codecs/wm8998.c index 3ae19f03f29a89..9eb82d46346ce7 100644 --- a/sound/soc/codecs/wm8998.c +++ b/sound/soc/codecs/wm8998.c @@ -1345,8 +1345,7 @@ static int wm8998_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm8998); - if (!dev_get_platdata(arizona->dev)) - arizona_get_audio_pdata(arizona); + arizona_get_audio_pdata(arizona); wm8998->core.arizona = arizona; wm8998->core.num_inputs = 3; /* IN1L, IN1R, IN2 */ From a516c1f40ea43db8e16de4a8689068eeb7e730f3 Mon Sep 17 00:00:00 2001 From: Dmitry Torokhov Date: Mon, 23 Nov 2026 15:00:56 -0800 Subject: [PATCH 1688/2102] ASoC: arizona: drop unused HPDET accessory ID support Nothing in the kernel sets hpdet_acc_id or hpdet_acc_id_line in struct arizona_pdata, and neither has any Device Tree or ACPI bindings. Remove both platform data fields and all exclusively connected HPDET accessory identification logic, work items, GPIO lookup, and state from the Arizona jack detection driver. Signed-off-by: Dmitry Torokhov Link: https://patch.msgid.link/20261123-arizona-asoc-v2-3-6323d3c0961a@gmail.com Signed-off-by: Mark Brown --- include/linux/mfd/arizona/pdata.h | 6 - sound/soc/codecs/arizona-jack.c | 181 +----------------------------- sound/soc/codecs/arizona.h | 6 - 3 files changed, 4 insertions(+), 189 deletions(-) diff --git a/include/linux/mfd/arizona/pdata.h b/include/linux/mfd/arizona/pdata.h index 984b2edfec0782..96ef9c97d4cc26 100644 --- a/include/linux/mfd/arizona/pdata.h +++ b/include/linux/mfd/arizona/pdata.h @@ -112,12 +112,6 @@ struct arizona_pdata { /** set to true if jackdet contact opens on insert */ bool jd_invert; - /** Use the headphone detect circuit to identify the accessory */ - bool hpdet_acc_id; - - /** Check for line output with HPDET method */ - bool hpdet_acc_id_line; - /** Channel to use for headphone detection */ unsigned int hpdet_channel; diff --git a/sound/soc/codecs/arizona-jack.c b/sound/soc/codecs/arizona-jack.c index f36d314a6a5498..5650a7f47ede47 100644 --- a/sound/soc/codecs/arizona-jack.c +++ b/sound/soc/codecs/arizona-jack.c @@ -45,7 +45,6 @@ #define ARIZONA_HPDET_MAX 10000 -#define HPDET_DEBOUNCE 500 #define DEFAULT_MICD_TIMEOUT 2000 #define ARIZONA_HPDET_WAIT_COUNT 15 @@ -92,8 +91,6 @@ static const int arizona_micd_levels[] = { 1257, 30000, }; -static void arizona_start_hpdet_acc_id(struct arizona_priv *info); - static void arizona_extcon_hp_clamp(struct arizona_priv *info, bool clamp) { @@ -455,79 +452,11 @@ static int arizona_hpdet_read(struct arizona_priv *info) return val; } -static int arizona_hpdet_do_id(struct arizona_priv *info, int *reading, - bool *mic) -{ - struct arizona *arizona = info->arizona; - - if (!arizona->pdata.hpdet_acc_id) - return 0; - - /* - * If we're using HPDET for accessory identification we need - * to take multiple measurements, step through them in sequence. - */ - info->hpdet_res[info->num_hpdet_res++] = *reading; - - /* Only check the mic directly if we didn't already ID it */ - if (info->hpdet_id_gpio && info->num_hpdet_res == 1) { - dev_dbg(arizona->dev, "Measuring mic\n"); - - regmap_update_bits(arizona->regmap, - ARIZONA_ACCESSORY_DETECT_MODE_1, - ARIZONA_ACCDET_MODE_MASK | - ARIZONA_ACCDET_SRC, - ARIZONA_ACCDET_MODE_HPR | - info->micd_modes[0].src); - - gpiod_set_value_cansleep(info->hpdet_id_gpio, 1); - - regmap_update_bits(arizona->regmap, ARIZONA_HEADPHONE_DETECT_1, - ARIZONA_HP_POLL, ARIZONA_HP_POLL); - return -EAGAIN; - } - - /* OK, got both. Now, compare... */ - dev_dbg(arizona->dev, "HPDET measured %d %d\n", - info->hpdet_res[0], info->hpdet_res[1]); - - /* Take the headphone impedance for the main report */ - *reading = info->hpdet_res[0]; - - /* Sometimes we get false readings due to slow insert */ - if (*reading >= ARIZONA_HPDET_MAX && !info->hpdet_retried) { - dev_dbg(arizona->dev, "Retrying high impedance\n"); - info->num_hpdet_res = 0; - info->hpdet_retried = true; - arizona_start_hpdet_acc_id(info); - pm_runtime_put(arizona->dev); - return -EAGAIN; - } - - /* - * If we measure the mic as high impedance - */ - if (!info->hpdet_id_gpio || info->hpdet_res[1] > 50) { - dev_dbg(arizona->dev, "Detected mic\n"); - *mic = true; - info->detecting = true; - } else { - dev_dbg(arizona->dev, "Detected headphone\n"); - } - - /* Make sure everything is reset back to the real polarity */ - regmap_update_bits(arizona->regmap, ARIZONA_ACCESSORY_DETECT_MODE_1, - ARIZONA_ACCDET_SRC, info->micd_modes[0].src); - - return 0; -} - static irqreturn_t arizona_hpdet_irq(int irq, void *data) { struct arizona_priv *info = data; struct arizona *arizona = info->arizona; int ret, reading, state, report; - bool mic = false; mutex_lock(&info->lock); @@ -552,18 +481,6 @@ static irqreturn_t arizona_hpdet_irq(int irq, void *data) goto done; reading = ret; - /* Reset back to starting range */ - regmap_update_bits(arizona->regmap, - ARIZONA_HEADPHONE_DETECT_1, - ARIZONA_HP_IMPEDANCE_RANGE_MASK | ARIZONA_HP_POLL, - 0); - - ret = arizona_hpdet_do_id(info, &reading, &mic); - if (ret == -EAGAIN) - goto out; - else if (ret < 0) - goto done; - /* Report high impedence cables as line outputs */ if (reading >= 5000) report = SND_JACK_LINEOUT; @@ -581,11 +498,8 @@ static irqreturn_t arizona_hpdet_irq(int irq, void *data) arizona_extcon_hp_clamp(info, false); - if (info->hpdet_id_gpio) - gpiod_set_value_cansleep(info->hpdet_id_gpio, 0); - /* If we have a mic then reenable MICDET */ - if (state && (mic || info->mic)) + if (state && info->mic) arizona_start_mic(info); if (info->hpdet_active) { @@ -654,55 +568,6 @@ static void arizona_identify_headphone(struct arizona_priv *info) info->hpdet_active = false; } -static void arizona_start_hpdet_acc_id(struct arizona_priv *info) -{ - struct arizona *arizona = info->arizona; - int hp_reading = 32; - bool mic; - int ret; - - dev_dbg(arizona->dev, "Starting identification via HPDET\n"); - - /* Make sure we keep the device enabled during the measurement */ - pm_runtime_get_sync(arizona->dev); - - info->hpdet_active = true; - - arizona_extcon_hp_clamp(info, true); - - ret = regmap_update_bits(arizona->regmap, - ARIZONA_ACCESSORY_DETECT_MODE_1, - ARIZONA_ACCDET_SRC | ARIZONA_ACCDET_MODE_MASK, - info->micd_modes[0].src | - arizona->pdata.hpdet_channel); - if (ret != 0) { - dev_err(arizona->dev, "Failed to set HPDET mode: %d\n", ret); - goto err; - } - - if (arizona->pdata.hpdet_acc_id_line) { - ret = regmap_update_bits(arizona->regmap, - ARIZONA_HEADPHONE_DETECT_1, - ARIZONA_HP_POLL, ARIZONA_HP_POLL); - if (ret) { - dev_err(arizona->dev, "Can't start HPDETL measurement: %d\n", ret); - goto err; - } - } else { - arizona_hpdet_do_id(info, &hp_reading, &mic); - } - - return; - -err: - /* Just report headphone */ - snd_soc_jack_report(info->jack, SND_JACK_HEADPHONE, - SND_JACK_LINEOUT | SND_JACK_HEADPHONE); - - pm_runtime_put_autosuspend(arizona->dev); - info->hpdet_active = false; -} - static void arizona_micd_timeout_work(struct work_struct *work) { struct arizona_priv *info = container_of(work, @@ -961,16 +826,6 @@ static irqreturn_t arizona_micdet(int irq, void *data) return IRQ_HANDLED; } -static void arizona_hpdet_work(struct work_struct *work) -{ - struct arizona_priv *info = container_of(work, - struct arizona_priv, - hpdet_work.work); - - guard(mutex)(&info->lock); - arizona_start_hpdet_acc_id(info); -} - static int arizona_hpdet_wait(struct arizona_priv *info) { struct arizona *arizona = info->arizona; @@ -1009,10 +864,9 @@ static irqreturn_t arizona_jackdet(int irq, void *data) struct arizona_priv *info = data; struct arizona *arizona = info->arizona; unsigned int val, present, mask; - bool cancelled_hp, cancelled_mic; - int ret, i; + bool cancelled_mic; + int ret; - cancelled_hp = cancel_delayed_work_sync(&info->hpdet_work); cancelled_mic = cancel_delayed_work_sync(&info->micd_timeout_work); guard(pm_runtime_active_auto)(arizona->dev); @@ -1039,11 +893,6 @@ static irqreturn_t arizona_jackdet(int irq, void *data) val &= mask; if (val == info->last_jackdet) { dev_dbg(arizona->dev, "Suppressing duplicate JACKDET\n"); - if (cancelled_hp) - queue_delayed_work(system_power_efficient_wq, - &info->hpdet_work, - msecs_to_jiffies(HPDET_DEBOUNCE)); - if (cancelled_mic) { int micd_timeout = arizona->pdata.micd_timeout; @@ -1062,13 +911,7 @@ static irqreturn_t arizona_jackdet(int irq, void *data) info->mic = false; info->jack_flips = 0; - if (!arizona->pdata.hpdet_acc_id) { - arizona_start_mic(info); - } else { - queue_delayed_work(system_power_efficient_wq, - &info->hpdet_work, - msecs_to_jiffies(HPDET_DEBOUNCE)); - } + arizona_start_mic(info); if (info->micd_clamp || !arizona->pdata.jd_invert) regmap_update_bits(arizona->regmap, @@ -1080,12 +923,8 @@ static irqreturn_t arizona_jackdet(int irq, void *data) arizona_stop_mic(info); - info->num_hpdet_res = 0; - for (i = 0; i < ARRAY_SIZE(info->hpdet_res); i++) - info->hpdet_res[i] = 0; info->mic = false; info->hpdet_done = false; - info->hpdet_retried = false; snd_soc_jack_report(info->jack, 0, ARIZONA_JACK_MASK | info->micd_button_mask); @@ -1253,7 +1092,6 @@ int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev) mutex_init(&info->lock); info->last_jackdet = ~(ARIZONA_MICD_CLAMP_STS | ARIZONA_JD1_STS); - INIT_DELAYED_WORK(&info->hpdet_work, arizona_hpdet_work); INIT_DELAYED_WORK(&info->micd_detect_work, arizona_micd_detect); INIT_DELAYED_WORK(&info->micd_timeout_work, arizona_micd_timeout_work); @@ -1326,15 +1164,6 @@ int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev) return ret; } - info->hpdet_id_gpio = gpiod_get_optional(arizona->dev, - "wlf,hpdet-id-gpio", - mode); - if (IS_ERR(info->hpdet_id_gpio)) { - ret = PTR_ERR(info->hpdet_id_gpio); - dev_err_probe(arizona->dev, ret, "getting headphone detect ID GPIO\n"); - return ret; - } - return 0; } EXPORT_SYMBOL_GPL(arizona_jack_codec_dev_probe); @@ -1342,7 +1171,6 @@ EXPORT_SYMBOL_GPL(arizona_jack_codec_dev_probe); int arizona_jack_codec_dev_remove(struct arizona_priv *info) { gpiod_put(info->micd_pol_gpio); - gpiod_put(info->hpdet_id_gpio); return 0; } EXPORT_SYMBOL_GPL(arizona_jack_codec_dev_remove); @@ -1588,7 +1416,6 @@ static int arizona_jack_disable_jack_detect(struct arizona_priv *info) arizona_free_irq(arizona, ARIZONA_IRQ_MICDET, info); arizona_free_irq(arizona, jack_irq_rise, info); arizona_free_irq(arizona, jack_irq_fall, info); - cancel_delayed_work_sync(&info->hpdet_work); cancel_delayed_work_sync(&info->micd_detect_work); cancel_delayed_work_sync(&info->micd_timeout_work); diff --git a/sound/soc/codecs/arizona.h b/sound/soc/codecs/arizona.h index 499891e62183fb..766a29a2389357 100644 --- a/sound/soc/codecs/arizona.h +++ b/sound/soc/codecs/arizona.h @@ -94,13 +94,11 @@ struct arizona_priv { /* Variables used by arizona-jack.c code */ struct mutex lock; - struct delayed_work hpdet_work; struct delayed_work micd_detect_work; struct delayed_work micd_timeout_work; struct snd_soc_jack *jack; struct regulator *micvdd; struct gpio_desc *micd_pol_gpio; - struct gpio_desc *hpdet_id_gpio; u16 last_jackdet; @@ -117,14 +115,10 @@ struct arizona_priv { bool hpdet_active; bool hpdet_done; - bool hpdet_retried; bool mic; bool detecting; - int num_hpdet_res; - unsigned int hpdet_res[3]; - int jack_flips; int hpdet_ip_version; }; From ce694590177a0770911187a66daf50781291d8de Mon Sep 17 00:00:00 2001 From: Dmitry Torokhov Date: Mon, 23 Nov 2026 15:00:57 -0800 Subject: [PATCH 1689/2102] ASoC: arizona: clean up coding style and formatting Clean up minor coding style issues in the Arizona jack detection driver, removing redundant parentheses and fixing argument continuation alignment. Signed-off-by: Dmitry Torokhov Link: https://patch.msgid.link/20261123-arizona-asoc-v2-4-6323d3c0961a@gmail.com Signed-off-by: Mark Brown --- sound/soc/codecs/arizona-jack.c | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/sound/soc/codecs/arizona-jack.c b/sound/soc/codecs/arizona-jack.c index 5650a7f47ede47..6f2286eb7cbe1f 100644 --- a/sound/soc/codecs/arizona-jack.c +++ b/sound/soc/codecs/arizona-jack.c @@ -423,7 +423,7 @@ static int arizona_hpdet_read(struct arizona_priv *info) /* Skip up a range, or report? */ if (range < ARRAY_SIZE(arizona_hpdet_c_ranges) - 1 && - (val >= arizona_hpdet_c_ranges[range].max)) { + val >= arizona_hpdet_c_ranges[range].max) { range++; dev_dbg(arizona->dev, "Moving to HPDET range %d-%d\n", arizona_hpdet_c_ranges[range].min, @@ -436,7 +436,7 @@ static int arizona_hpdet_read(struct arizona_priv *info) return -EAGAIN; } - if (range && (val < arizona_hpdet_c_ranges[range].min)) { + if (range && val < arizona_hpdet_c_ranges[range].min) { dev_dbg(arizona->dev, "Reporting range boundary %d\n", arizona_hpdet_c_ranges[range].min); val = arizona_hpdet_c_ranges[range].min; @@ -833,8 +833,7 @@ static int arizona_hpdet_wait(struct arizona_priv *info) int i, ret; for (i = 0; i < ARIZONA_HPDET_WAIT_COUNT; i++) { - ret = regmap_read(arizona->regmap, ARIZONA_HEADPHONE_DETECT_2, - &val); + ret = regmap_read(arizona->regmap, ARIZONA_HEADPHONE_DETECT_2, &val); if (ret) { dev_err(arizona->dev, "Failed to read HPDET state: %d\n", ret); return ret; @@ -1143,7 +1142,7 @@ int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev) if (arizona->pdata.gpsw > 0) regmap_update_bits(arizona->regmap, ARIZONA_GP_SWITCH_1, - ARIZONA_SW1_MODE_MASK, arizona->pdata.gpsw); + ARIZONA_SW1_MODE_MASK, arizona->pdata.gpsw); if (info->micd_modes[0].gpio) mode = GPIOD_OUT_HIGH; @@ -1155,9 +1154,7 @@ int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev) * will reside, but if we devm against that the GPIO * will not be freed if the extcon driver is unloaded. */ - info->micd_pol_gpio = gpiod_get_optional(arizona->dev, - "wlf,micd-pol", - mode); + info->micd_pol_gpio = gpiod_get_optional(arizona->dev, "wlf,micd-pol", mode); if (IS_ERR(info->micd_pol_gpio)) { ret = PTR_ERR(info->micd_pol_gpio); dev_err_probe(arizona->dev, ret, "getting microphone polarity GPIO\n"); @@ -1189,13 +1186,13 @@ static int arizona_jack_enable_jack_detect(struct arizona_priv *info, regmap_update_bits(arizona->regmap, ARIZONA_MIC_DETECT_1, ARIZONA_MICD_BIAS_STARTTIME_MASK, arizona->pdata.micd_bias_start_time - << ARIZONA_MICD_BIAS_STARTTIME_SHIFT); + << ARIZONA_MICD_BIAS_STARTTIME_SHIFT); if (arizona->pdata.micd_rate) regmap_update_bits(arizona->regmap, ARIZONA_MIC_DETECT_1, ARIZONA_MICD_RATE_MASK, arizona->pdata.micd_rate - << ARIZONA_MICD_RATE_SHIFT); + << ARIZONA_MICD_RATE_SHIFT); switch (arizona->pdata.micd_dbtime) { case MICD_DBTIME_FOUR_READINGS: From 3ff394474add264b3aa526106467d0a2e3f2731a Mon Sep 17 00:00:00 2001 From: Dario Binacchi Date: Wed, 28 Oct 2026 11:57:40 +0100 Subject: [PATCH 1690/2102] arm64: dts: st: add firmware reserved memory to Engicam MicroGEA-STM32MP257 The first 64 MiB of the DDR are used by the secure firmware (TF-M, Cortex-M33 firmware, BL31 and OP-TEE) and are protected by the RISAF firewall. Without a reserved-memory node Linux allocates pages there, and the first access triggers an IAC exception and an OP-TEE panic: E/TC:0 stm32_iac_itr:197 IAC exception ID: 137 Faulty address (IADDR0): 0x80000060 E/TC:0 Panic at core/drivers/firewall/stm32_iac.c:212 Reserve the region, as done for the stm32mp257f-ev1 board. Fixes: c5ce8d7bcc78 ("arm64: dts: st: support Engicam MicroGEA-STM32MP257 SoM") Signed-off-by: Dario Binacchi Link: https://lore.kernel.org/r/20261028105807.2567225-1-dario.binacchi@amarulasolutions.com Signed-off-by: Alexandre Torgue --- .../boot/dts/st/stm32mp257-engicam-microgea.dtsi | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/arch/arm64/boot/dts/st/stm32mp257-engicam-microgea.dtsi b/arch/arm64/boot/dts/st/stm32mp257-engicam-microgea.dtsi index 5b4287e86deff9..6cd64587ecdc98 100644 --- a/arch/arm64/boot/dts/st/stm32mp257-engicam-microgea.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp257-engicam-microgea.dtsi @@ -19,6 +19,18 @@ device_type = "memory"; reg = <0x0 0x80000000 0x0 0x80000000>; }; + + reserved-memory { + #address-cells = <2>; + #size-cells = <2>; + ranges; + + fw@80000000 { + compatible = "shared-dma-pool"; + reg = <0x0 0x80000000 0x0 0x4000000>; + no-map; + }; + }; }; &scmi_regu { From ee12947901acfd6ce137cc006f948d139b484ddb Mon Sep 17 00:00:00 2001 From: Marek Vasut Date: Mon, 26 Oct 2026 13:51:38 +0100 Subject: [PATCH 1691/2102] arm64: dts: st: Move Bluetooth to USART2 on STM32MP23xx DHCOS SoM The Bluetooth chip is connected to USART2 on STM32MP23xx DHCOS SoM, adjust the DT to match the schematic. Fixes: 6642d6a47901 ("arm64: dts: st: Add support for DH electronics STM32MP23xx/STM32MP25xx DHCOS SoM and Breakout Board and DHSBC") Signed-off-by: Marek Vasut Link: https://lore.kernel.org/r/20261026125201.76716-1-marex@nabladev.com Signed-off-by: Alexandre Torgue --- .../arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi b/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi index ffdcceb2fa237b..5d4624c3200adc 100644 --- a/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi @@ -24,7 +24,6 @@ interrupts-extended = <&gpiod 10 IRQ_TYPE_EDGE_FALLING>; }; -/* Bluetooth */ &usart1 { pinctrl-names = "default", "sleep", "idle"; pinctrl-0 = <&usart1_pins_a>; @@ -32,15 +31,9 @@ pinctrl-2 = <&usart1_idle_pins_a>; uart-has-rtscts; status = "okay"; - - bluetooth { - compatible = "infineon,cyw55572-bt"; - brcm,requires-autobaud-mode; - max-speed = <3000000>; - shutdown-gpios = <&ioexp 2 GPIO_ACTIVE_HIGH>; - }; }; +/* Bluetooth */ &usart2 { pinctrl-names = "default", "sleep", "idle"; pinctrl-0 = <&usart2_pins_b>; @@ -48,4 +41,11 @@ pinctrl-2 = <&usart2_idle_pins_b>; uart-has-rtscts; status = "okay"; + + bluetooth { + compatible = "infineon,cyw55572-bt"; + brcm,requires-autobaud-mode; + max-speed = <3000000>; + shutdown-gpios = <&ioexp 2 GPIO_ACTIVE_HIGH>; + }; }; From 235ddf44c19acc298c37a4c8148861e50b30cff9 Mon Sep 17 00:00:00 2001 From: Marek Vasut Date: Mon, 26 Oct 2026 13:52:11 +0100 Subject: [PATCH 1692/2102] arm64: dts: st: Update gpio-line-names on STM32MP23xx DHCOS SoM Adjust gpio-line-names to match both STM32MP23xx and STM32MP25xx DHCOS SoM pads respectively in their matching SoM DTs. Fixes: 6642d6a47901 ("arm64: dts: st: Add support for DH electronics STM32MP23xx/STM32MP25xx DHCOS SoM and Breakout Board and DHSBC") Signed-off-by: Marek Vasut Link: https://lore.kernel.org/r/20261026125240.76753-1-marex@nabladev.com Signed-off-by: Alexandre Torgue --- .../boot/dts/st/stm32mp23xx-dhcos-som.dtsi | 54 +++++++++++++++++++ .../boot/dts/st/stm32mp25xx-dhcos-som.dtsi | 47 ++++++++++++++++ .../boot/dts/st/stm32mp2xxx-dhcos-som.dtsi | 45 ---------------- 3 files changed, 101 insertions(+), 45 deletions(-) diff --git a/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi b/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi index 5d4624c3200adc..7a95f56bf857ff 100644 --- a/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi @@ -20,6 +20,60 @@ }; }; +&gpioa { + gpio-line-names = "", "", "", "", + "", "", "", "", + "", "", "", "", + "DHCOS-C", "", "", ""; +}; + +&gpiod { + gpio-line-names = "", "DHCOS-K", "DHCOS-J", "", + "", "", "", "", + "", "", "", "", + "", "", "", ""; +}; + +&gpiof { + gpio-line-names = "", "", "", "", + "", "", "", "", + "", "", "", "DHCOS-E", + "DHCOS-N", "", "", "DHCOS_RAM-CODE_2"; +}; + +&gpiog { + gpio-line-names = "", "", "", "", + "", "", "", "DHCOS-P", + "DHCOS-O", "DHCOS_RAM-CODE_0", "DHCOS_RAM-CODE_1", "", + "", "", "DHCOS-F", "DHCOS_HW-CODE_0"; +}; + +&gpioh { + gpio-line-names = "", "", "DHCOS-I", "", + "", "DHCOS-H", "DHCOS-L", "", + "DHCOS-G", "", "", "", + "", "", "", ""; +}; + +&gpioi { + gpio-line-names = "DHCOS_HW-CODE_1", "DHCOS_HW-CODE_2", "", "", + "", "DHCOS-M", "", "", + "", "", "", "DHCOS-D", + "", "", "", ""; +}; + +&ioexp { + gpio-line-names = + "#ETH1_RST_P0_0", "#ETH0_RST_P0_1", + "BT_REG_ON_P0_2", "WL_REG_ON_P0_3", + "USB1_PWR_EN_P0_4", "USB1_PWR_STAT_P0_5", + "USB0_PWR_EN_P0_6", "USB0_PWR_STAT_P0_7", + "SDIO0_CD_P1_0", "USB0_SS_SEL_P1_1", + "#PCIe_RST_1_2", "#PCIe_Wake_P1_3", + "#QSPI_RST_P1_4", "#CSI0_PWDN_P1_5", + "#CSI0_RST_P1_6", "#PCIE_CLKREQ_GPIO_Q_P1_7"; +}; + &rv3032 { interrupts-extended = <&gpiod 10 IRQ_TYPE_EDGE_FALLING>; }; diff --git a/arch/arm64/boot/dts/st/stm32mp25xx-dhcos-som.dtsi b/arch/arm64/boot/dts/st/stm32mp25xx-dhcos-som.dtsi index 23c25ea086445a..3f3bdef05ce4e9 100644 --- a/arch/arm64/boot/dts/st/stm32mp25xx-dhcos-som.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp25xx-dhcos-som.dtsi @@ -20,6 +20,53 @@ }; }; +&gpioa { + gpio-line-names = "", "DHCOS-M", "DHCOS-K", "DHCOS-L", + "DHCOS-E", "DHCOS-J", "", "", + "DHCOS-D", "", "", "", + "", "", "", ""; +}; + +&gpiof { + gpio-line-names = "", "", "", "", + "", "", "", "", + "", "", "", "", + "", "", "", "DHCOS_RAM-CODE_2"; +}; + +&gpiog { + gpio-line-names = "", "", "", "", + "", "", "", "", + "", "DHCOS_RAM-CODE_0", "DHCOS_RAM-CODE_1", "", + "", "", "DHCOS-F", "DHCOS_HW-CODE_0"; +}; + +&gpioh { + gpio-line-names = "", "", "DHCOS-I", "DHCOS-N", + "", "", "DHCOS-O", "DHCOS-H", + "DHCOS-G", "", "", "", + "", "", "", ""; +}; + +&gpioi { + gpio-line-names = "DHCOS_HW-CODE_1", "DHCOS_HW-CODE_2", "", "", + "", "", "", "", + "", "DHCOS-C", "", "", + "", "", "", ""; +}; + +&ioexp { + gpio-line-names = + "#ETH1_RST_P0_0", "#ETH0_RST_P0_1", + "BT_REG_ON_P0_2", "WL_REG_ON_P0_3", + "USB1_PWR_EN_P0_4", "USB1_PWR_STAT_P0_5", + "USB0_PWR_EN_P0_6", "USB0_PWR_STAT_P0_7", + "SDIO0_CD_P1_0", "USB0_SS_SEL_P1_1", + "#PCIe_RST_1_2", "#PCIe_Wake_P1_3", + "#QSPI_RST_P1_4", "#CSI0_PWDN_P1_5", + "#CSI0_RST_P1_6", "#ETH3_RST_P1_7"; +}; + &rv3032 { interrupts-extended = <&gpioi 10 IRQ_TYPE_EDGE_FALLING>; }; diff --git a/arch/arm64/boot/dts/st/stm32mp2xxx-dhcos-som.dtsi b/arch/arm64/boot/dts/st/stm32mp2xxx-dhcos-som.dtsi index bcf63e2ea98985..6febdbfe83649c 100644 --- a/arch/arm64/boot/dts/st/stm32mp2xxx-dhcos-som.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp2xxx-dhcos-som.dtsi @@ -218,41 +218,6 @@ status = "okay"; }; -&gpioa { - gpio-line-names = "", "DHCOS-M", "DHCOS-K", "DHCOS-L", - "DHCOS-E", "DHCOS-J", "", "", - "DHCOS-D", "", "", "", - "", "", "", ""; -}; - -&gpiof { - gpio-line-names = "", "", "", "", - "", "", "", "", - "", "", "", "", - "", "", "", "DHCOS_RAM-CODE_2"; -}; - -&gpiog { - gpio-line-names = "", "", "", "", - "", "", "", "", - "", "DHCOS_RAM-CODE_0", "DHCOS_RAM-CODE_1", "", - "", "", "DHCOS-F", "DHCOS_HW-CODE_0"; -}; - -&gpioh { - gpio-line-names = "", "", "DHCOS-I", "DHCOS-N", - "", "", "DHCOS-O", "DHCOS-H", - "DHCOS-G", "", "", "", - "", "", "", ""; -}; - -&gpioi { - gpio-line-names = "DHCOS_HW-CODE_1", "DHCOS_HW-CODE_2", "", "", - "", "", "", "", - "", "DHCOS-C", "", "", - "", "", "", ""; -}; - &gpioz { gpio-line-names = "", "", "DHCOS-A", "DHCOS-B", "", "", "", "", @@ -278,16 +243,6 @@ interrupt-controller; #interrupt-cells = <2>; wakeup-source; - - gpio-line-names = - "#ETH1_RST_P0_0", "#ETH0_RST_P0_1", - "BT_REG_ON_P0_2", "WL_REG_ON_P0_3", - "USB1_PWR_EN_P0_4", "USB1_PWR_STAT_P0_5", - "USB0_PWR_EN_P0_6", "USB0_PWR_STAT_P0_7", - "SDIO0_CD_P1_0", "USB0_SS_SEL_P1_1", - "#PCIe_RST_1_2", "#PCIe_Wake_P1_3", - "#QSPI_RST_P1_4", "#CSI0_PWDN_P1_5", - "#CSI0_RST_P1_6", "#ETH3_RST_P1_7"; }; eeprom0: eeprom@50 { From ab4ce1d0630f677032d7e20d27c80ecfbd9960cb Mon Sep 17 00:00:00 2001 From: Patrick Delaunay Date: Thu, 19 Nov 2026 18:55:45 +0100 Subject: [PATCH 1693/2102] arm64: dts: st: add PSCI idle state to STM32MP25 CPU domains Define a PSCI CPU suspend state and reference it from both STM32MP25 CPU power domains. In OSI mode, PSCI power domains are initialized as off. The idle-state allows the CPU power-domain governor to manage them, avoiding probe stalls for devices that depend on the cluster power domain, including SDMMC1. Fixes: 9c8d852dabbd ("arm64: dts: st: add power domain on stm32mp25") Signed-off-by: Patrick Delaunay Tested-by: Amelie Delaunay Reviewed-by: Amelie Delaunay Link: https://lore.kernel.org/r/20261119185544.v2.1.Ia5e0774883d237f5825b7090962b454294922558@changeid Signed-off-by: Alexandre Torgue --- arch/arm64/boot/dts/st/stm32mp251.dtsi | 14 ++++++++++++++ arch/arm64/boot/dts/st/stm32mp253.dtsi | 1 + 2 files changed, 15 insertions(+) diff --git a/arch/arm64/boot/dts/st/stm32mp251.dtsi b/arch/arm64/boot/dts/st/stm32mp251.dtsi index dac3d2d23ff008..bf1542818be257 100644 --- a/arch/arm64/boot/dts/st/stm32mp251.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp251.dtsi @@ -25,6 +25,19 @@ power-domains = <&CPU_PD0>; power-domain-names = "psci"; }; + + idle-states { + entry-method = "psci"; + + cpu_sleep: cpu-sleep { + compatible = "arm,idle-state"; + arm,psci-suspend-param = <0x00000002>; + local-timer-stop; + entry-latency-us = <150>; + exit-latency-us = <200>; + min-residency-us = <1000>; + }; + }; }; arm-pmu { @@ -145,6 +158,7 @@ CPU_PD0: power-domain-cpu0 { #power-domain-cells = <0>; + domain-idle-states = <&cpu_sleep>; power-domains = <&CLUSTER_PD>; }; diff --git a/arch/arm64/boot/dts/st/stm32mp253.dtsi b/arch/arm64/boot/dts/st/stm32mp253.dtsi index 7e82f01fdc10f8..19b3e55a441411 100644 --- a/arch/arm64/boot/dts/st/stm32mp253.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp253.dtsi @@ -26,6 +26,7 @@ psci { CPU_PD1: power-domain-cpu1 { #power-domain-cells = <0>; + domain-idle-states = <&cpu_sleep>; power-domains = <&CLUSTER_PD>; }; }; From 0818ec0de18627ff7d2306e5c2843a0358960874 Mon Sep 17 00:00:00 2001 From: Patrick Delaunay Date: Thu, 19 Nov 2026 18:42:11 +0100 Subject: [PATCH 1694/2102] arm64: dts: st: add PSCI idle state to STM32MP23 CPU domains Define a PSCI CPU suspend state and reference it from both STM32MP23 CPU power domains. In OSI mode, PSCI power domains are initialized as off. The idle-state allows the CPU power-domain governor to manage them, avoiding probe stalls for devices that depend on the cluster power domain, including SDMMC1. Fixes: e9b03ef21386 ("arm64: dts: st: introduce stm32mp23 SoCs family") Signed-off-by: Patrick Delaunay Reviewed-by: Amelie Delaunay Link: https://lore.kernel.org/all/20261030102907.1.I0ef2a7ac525ef18fa683368382d93e98cc36ee25@changeid/ Link: https://lore.kernel.org/r/20261119184209.v2.1.If2b6b99285c1e60ca11b6e7fccf7d9b130ca20dd@changeid Signed-off-by: Alexandre Torgue --- arch/arm64/boot/dts/st/stm32mp231.dtsi | 14 ++++++++++++++ arch/arm64/boot/dts/st/stm32mp233.dtsi | 1 + 2 files changed, 15 insertions(+) diff --git a/arch/arm64/boot/dts/st/stm32mp231.dtsi b/arch/arm64/boot/dts/st/stm32mp231.dtsi index fefbf6f4f15377..27231e140fbb5b 100644 --- a/arch/arm64/boot/dts/st/stm32mp231.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp231.dtsi @@ -24,6 +24,19 @@ power-domains = <&cpu0_pd>; power-domain-names = "psci"; }; + + idle-states { + entry-method = "psci"; + + cpu_sleep: cpu-sleep { + compatible = "arm,idle-state"; + arm,psci-suspend-param = <0x00000002>; + local-timer-stop; + entry-latency-us = <150>; + exit-latency-us = <200>; + min-residency-us = <1000>; + }; + }; }; arm-pmu { @@ -123,6 +136,7 @@ cpu0_pd: power-domain-cpu0 { #power-domain-cells = <0>; + domain-idle-states = <&cpu_sleep>; power-domains = <&cluster_pd>; }; diff --git a/arch/arm64/boot/dts/st/stm32mp233.dtsi b/arch/arm64/boot/dts/st/stm32mp233.dtsi index 78f4059fca5db6..cebefd99906f62 100644 --- a/arch/arm64/boot/dts/st/stm32mp233.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp233.dtsi @@ -26,6 +26,7 @@ psci { cpu1_pd: power-domain-cpu1 { #power-domain-cells = <0>; + domain-idle-states = <&cpu_sleep>; power-domains = <&cluster_pd>; }; }; From 9eb9bea92c7ea2a8886eeab01cdfe4365bee0328 Mon Sep 17 00:00:00 2001 From: Patrick Delaunay Date: Fri, 30 Oct 2026 10:29:08 +0100 Subject: [PATCH 1695/2102] arm64: dts: st: mark STM32MP23 timer as stopping in suspend The generic ARM timer, based on STGEN, stops ticking in low-power states such as Stop1. Replace the always-on property with arm,no-tick-in-suspend in the STM32MP23 timer node, matching the STM32MP25 configuration. Fixes: e9b03ef21386 ("arm64: dts: st: introduce stm32mp23 SoCs family") Signed-off-by: Patrick Delaunay Reviewed-by: Amelie Delaunay Link: https://lore.kernel.org/r/20261030102907.1.I0ef2a7ac525ef18fa683368382d93e98cc36ee25@changeid Signed-off-by: Alexandre Torgue --- arch/arm64/boot/dts/st/stm32mp231.dtsi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/st/stm32mp231.dtsi b/arch/arm64/boot/dts/st/stm32mp231.dtsi index 27231e140fbb5b..deeda0a252ce8e 100644 --- a/arch/arm64/boot/dts/st/stm32mp231.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp231.dtsi @@ -157,7 +157,7 @@ , , ; - always-on; + arm,no-tick-in-suspend; }; soc@0 { From add40017961d3f07b36bad48840aaecf57128150 Mon Sep 17 00:00:00 2001 From: Marek Vasut Date: Mon, 2 Nov 2026 06:22:37 +0100 Subject: [PATCH 1696/2102] ARM: dts: stm32: Fix STM32MP15xx DHCOM SoM PicoITX overlay application Generate the combined STM32MP15xx DHCOM SoM PicoITX and overlay from PicoITX instead of PDK2. Fix the Makefile to use the correct base DT. Fixes: 77a5fde00b9a ("ARM: dts: stm32: Add DT overlays for DH STM32MP13xx/STM32MP15xx DHSOM") Signed-off-by: Marek Vasut Link: https://lore.kernel.org/r/20261102052306.868349-1-marex@nabladev.com Signed-off-by: Alexandre Torgue --- arch/arm/boot/dts/st/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/arch/arm/boot/dts/st/Makefile b/arch/arm/boot/dts/st/Makefile index 10c5d75f6169c9..f699d37254e24b 100644 --- a/arch/arm/boot/dts/st/Makefile +++ b/arch/arm/boot/dts/st/Makefile @@ -94,11 +94,11 @@ stm32mp15xx-dhcom-picoitx-overlay-548-200-x2-mi0700s4t-6-dtbs := \ stm32mp15xx-dhcom-picoitx-overlay-548-200-x2-mi0700s4t-6.dtbo \ stm32mp15xx-dhcom-picoitx-overlay-553-100-x2-tst043015cmhx-dtbs := \ - stm32mp157c-dhcom-pdk2.dtb \ + stm32mp157c-dhcom-picoitx.dtb \ stm32mp15xx-dhcom-picoitx-overlay-553-100-x2-tst043015cmhx.dtbo \ stm32mp15xx-dhcom-picoitx-overlay-626-100-x2-ch101olhlwh-dtbs := \ - stm32mp157c-dhcom-pdk2.dtb \ + stm32mp157c-dhcom-picoitx.dtb \ stm32mp15xx-dhcom-picoitx-overlay-626-100-x2-ch101olhlwh.dtbo \ dtb-$(CONFIG_ARCH_STM32) += \ From cb9809483c7f08c8333833ecac11188e41bcc3c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Grzelak?= Date: Tue, 24 Nov 2026 01:43:12 +0100 Subject: [PATCH 1697/2102] drm/ttm/tests: do not count pages after pool's teardown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently ttm_pool_fini_basic() checks if page count of pool-type's lru list is zero after tearing down its pre-populated pool. After commit 5ffdc8f83613 ("ttm/pool: Don't leak LRU list on shutdown") this check causes NULL dereference because page's lru list is destroyed during pool's teardown which leads to KUnit's crash: [20:08:24] ========== [PASSED] ttm_pool_alloc_basic_dma_addr ========== [20:08:24] [PASSED] ttm_pool_alloc_order_caching_match [20:08:24] [PASSED] ttm_pool_alloc_caching_mismatch [20:08:24] [PASSED] ttm_pool_alloc_order_mismatch [20:08:24] [PASSED] ttm_pool_free_dma_alloc [20:08:24] [PASSED] ttm_pool_free_no_dma_alloc [20:08:25] [ERROR] Test: ttm_pool: missing expected subtest! [20:08:25] [20:08:25] Pid: 80, comm: kunit_try_catch Tainted: G W N 7.4.0-rc4-g401a3e7b64d1 [20:08:25] RIP: 0033:list_lru_count_node+0xe/0x20 [20:08:25] RSP: 00000000a08dbef8 EFLAGS: 00010246 [20:08:25] RAX: 0000000000000001 RBX: 00000000a0803c70 RCX: 0000000000000020 [20:08:25] RDX: 0000000000000001 RSI: 0000000000000000 RDI: 0000000060853030 [20:08:25] RBP: 0000000060853000 R08: 00000000a08dbe98 R09: 00000000601246ac [20:08:25] R10: 000000009f227d00 R11: 0000000000000000 R12: 0000000060124640 [20:08:25] R13: 0000000060853030 R14: 000000006047c950 R15: 00000000604c6488 [20:08:25] Kernel panic - not syncing: Segfault with no mm [20:08:25] [CRASHED] [20:08:25] [ERROR] Test: ttm_pool: missing subtest result line! [20:08:25] # module: ttm_pool_test [20:08:25] ==================== [CRASHED] ttm_pool ==================== [20:08:25] [ERROR] Test: main: missing expected subtest! [20:08:25] [CRASHED] [20:08:25] [ERROR] Test: main: missing expected subtest! [20:08:25] [CRASHED] [20:08:25] [ERROR] Test: main: missing expected subtest! [20:08:25] [CRASHED] [20:08:25] [ERROR] Test: main: missing expected subtest! [20:08:25] [CRASHED] [20:08:25] ============================================================ [20:08:25] Testing complete. Ran 28 tests: passed: 23, crashed: 5, errors: 6 The crash in turn prevents Xe CI from running IGT. Drop the post-teardown assertion. Fixes: 5ffdc8f83613 ("ttm/pool: Don't leak LRU list on shutdown") Cc: Ian Forbes Cc: Christian König Signed-off-by: Michał Grzelak Reviewed-by: Dave Airlie Link: https://patch.msgid.link/20261124004312.3880264-2-michal.grzelak@linux.intel.com Signed-off-by: Rodrigo Vivi --- drivers/gpu/drm/ttm/tests/ttm_pool_test.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/drivers/gpu/drm/ttm/tests/ttm_pool_test.c b/drivers/gpu/drm/ttm/tests/ttm_pool_test.c index be75c8abf38833..dab03dd6c9dd75 100644 --- a/drivers/gpu/drm/ttm/tests/ttm_pool_test.c +++ b/drivers/gpu/drm/ttm/tests/ttm_pool_test.c @@ -401,8 +401,6 @@ static void ttm_pool_fini_basic(struct kunit *test) KUNIT_ASSERT_FALSE(test, !list_lru_count(&pt->pages)); ttm_pool_fini(pool); - - KUNIT_ASSERT_TRUE(test, !list_lru_count(&pt->pages)); } static struct kunit_case ttm_pool_test_cases[] = { From 234b2dc7e7ac867ccc8de7ddf29718b058965c83 Mon Sep 17 00:00:00 2001 From: Vincent Donnefort Date: Fri, 9 Oct 2026 14:28:48 +0100 Subject: [PATCH 1698/2102] tracing/remotes: Align field offset in remote_event_format_show() remote_event_format_show() doesn't take into account each field's alignment leading to an incorrect reporting of the actual field offset. Use the existing field->align. Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261009132848.709379-1-vdonnefort@google.com Fixes: 072529158e60 ("tracing: Add events to trace remotes") Reported-by: Fuad Tabba Signed-off-by: Vincent Donnefort Reviewed-by: Fuad Tabba Tested-by: Fuad Tabba Signed-off-by: Steven Rostedt --- kernel/trace/trace_remote.c | 1 + 1 file changed, 1 insertion(+) diff --git a/kernel/trace/trace_remote.c b/kernel/trace/trace_remote.c index 2d5bc423efca58..7e35f48ae46721 100644 --- a/kernel/trace/trace_remote.c +++ b/kernel/trace/trace_remote.c @@ -1098,6 +1098,7 @@ static int remote_event_format_show(struct seq_file *s, void *unused) field = &evt->fields[0]; while (field->name) { + offset = ALIGN(offset, field->align); seq_printf(s, "\tfield:%s %s;\toffset:%zu;\tsize:%u;\tsigned:%d;\n", field->type, field->name, offset, field->size, field->is_signed); From 7792e21d0a6e2fa819209949e8ba957504bedcd4 Mon Sep 17 00:00:00 2001 From: Andrea Parri Date: Mon, 26 Oct 2026 19:25:52 +0100 Subject: [PATCH 1699/2102] ftrace: Fix lost recursion records in ftrace_record_recursion() cached_function is set to the current ip before the cmpxchg() that claims a slot in recursed_functions[]. When that cmpxchg() loses a race for the same slot, the code bumps index and retries via "goto again", but the retry immediately matches its own cached_function write and returns without ever reaching the bumped-index cmpxchg(). Concretely, for two writers racing on the same index: CPU 0 (ip = A) CPU 1 (ip = B) -------------- -------------- cmpxchg(&recursed_functions[index].ip, 0, B); // succeeds cached_function = A; cmpxchg(&recursed_functions[index].ip, 0, A); // fails, old == B index++; goto again; if (A == cached_function) // true: matches A's own store return; // A is dropped, not retried Once dropped this way, cached_function stays set to A, so every later recursion of A also hits the fast path and returns before reaching the retry, until some unrelated ip overwrites the cache. Set cached_function only after the cmpxchg() has claimed the slot. The retry path then leaves the cache untouched and no longer matches its own store. When the cmpxchg() finds ip already present, the writer that installed it sets the cache. The bug was found with the help of an LLM. Link: https://patch.msgid.link/20261026182553.221141-1-parri.andrea@gmail.com Fixes: 773c16705058e ("ftrace: Add recording of functions that caused recursion") Signed-off-by: Andrea Parri Signed-off-by: Steven Rostedt --- kernel/trace/trace_recursion_record.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/kernel/trace/trace_recursion_record.c b/kernel/trace/trace_recursion_record.c index bac4bc844ccd8b..4f63bec052fca2 100644 --- a/kernel/trace/trace_recursion_record.c +++ b/kernel/trace/trace_recursion_record.c @@ -17,8 +17,8 @@ static struct recursed_functions recursed_functions[CONFIG_FTRACE_RECORD_RECURSI static atomic_t nr_records; /* - * Cache the last found function. Yes, updates to this is racey, but - * so is memory cache ;-) + * Cache the last function found in or added to recursed_functions[]. + * Updates to this are racy, but this is only a best-effort cache. */ static unsigned long cached_function; @@ -67,24 +67,25 @@ void ftrace_record_recursion(unsigned long ip, unsigned long parent_ip) } } - cached_function = ip; - /* * We only want to add a function if it hasn't been added before. - * Add to the current location before incrementing the count. - * If it fails to add, then increment the index (save in i) - * and try again. + * Claim the current slot before incrementing the count. If the slot + * is occupied by another function, advance to the next slot and retry. + * + * Do not update cached_function until ip is known to be present; + * otherwise the retry would match its own cache update. */ old = cmpxchg(&recursed_functions[index].ip, 0, ip); if (old != 0) { /* Did something else already added this for us? */ if (old == ip) return; - /* Try the next location (use i for the next index) */ + /* Try the next location */ index++; goto again; } + cached_function = ip; recursed_functions[index].parent_ip = parent_ip; /* From ac8059e4525091050593f8ec706759268a528441 Mon Sep 17 00:00:00 2001 From: Shenghao Ding Date: Tue, 24 Nov 2026 22:26:34 +0800 Subject: [PATCH 1700/2102] ASoC: tas2781: Refactor TAS2573 calibration status read The TAS2573 calibration status control currently builds the register list inline and hand-rolls the whole payload; it duplicates logic that is already available through tas2573_status_get_common(). No functional change. Signed-off-by: Shenghao Ding Link: https://patch.msgid.link/20261124142634.1383-1-shenghao-ding@ti.com Signed-off-by: Mark Brown --- include/sound/tas2573-reg.h | 22 +++++++++++ sound/soc/codecs/tas2781-i2c.c | 67 +++------------------------------- 2 files changed, 27 insertions(+), 62 deletions(-) diff --git a/include/sound/tas2573-reg.h b/include/sound/tas2573-reg.h index 4fedc8a3329e8f..6f8411c695ebc4 100644 --- a/include/sound/tas2573-reg.h +++ b/include/sound/tas2573-reg.h @@ -59,6 +59,28 @@ struct tasdev_reg_map { /* YM955 */ #define TAS2573_SHORTCKT TASDEVICE_REG(0x00, 0x83, 0x6C) +/* Registers for the speaker calibration */ +static const __maybe_unused unsigned int fct_status_regs[] = { + TAS2573_FCT_INT_LATCH, + TAS2573_FCT_STATUS_CTRL, + TAS2573_FCT_STATUS_BINNING, + TAS2573_SILENCE_DETECTED, + TAS2573_OPEN_CIRCUIT, + TAS2573_SHORTCKT, + TAS2573_FCT_OUTPUT_R0, + TAS2573_FCT_OUTPUT_R0_LOW, + TAS2573_FCT_OUTPUT_INV_R0, + TAS2573_FCT_OUTPUT_POWERTOT, + TAS2573_FCT_OUTPUT_F0, + TAS2573_RE_OUT, +}; + +static const __maybe_unused struct tasdev_reg_map calib_status_map = { + .regs = fct_status_regs, + .nregs = ARRAY_SIZE(fct_status_regs), + .tag = "fct_status_regs", +}; + /* Registers for the realtime (RT) speaker protection data */ static const __maybe_unused unsigned int tas2573_rt_data_regs[] = { TAS2573_TDM_DET_REG, diff --git a/sound/soc/codecs/tas2781-i2c.c b/sound/soc/codecs/tas2781-i2c.c index e44a1d460c703d..2dbbd13f5e8143 100644 --- a/sound/soc/codecs/tas2781-i2c.c +++ b/sound/soc/codecs/tas2781-i2c.c @@ -1605,70 +1605,12 @@ static int tas2573_status_get_common(struct snd_kcontrol *kcontrol, return 0; } +/* Calibration status control */ static int tas2573_calib_status_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { - struct snd_soc_component *comp = snd_kcontrol_chip(kcontrol); - struct tasdevice_priv *priv = snd_soc_component_get_drvdata(comp); - unsigned char *dst = ucontrol->value.bytes.data; - struct soc_bytes_ext *bytes_ext = - (struct soc_bytes_ext *) kcontrol->private_value; - unsigned int fct_status_regs[] = { - TAS2573_FCT_INT_LATCH, - TAS2573_FCT_STATUS_CTRL, - TAS2573_FCT_STATUS_BINNING, - TAS2573_SILENCE_DETECTED, - TAS2573_OPEN_CIRCUIT, - TAS2573_SHORTCKT, - TAS2573_FCT_OUTPUT_R0, - TAS2573_FCT_OUTPUT_R0_LOW, - TAS2573_FCT_OUTPUT_INV_R0, - TAS2573_FCT_OUTPUT_POWERTOT, - TAS2573_FCT_OUTPUT_F0, - TAS2573_RE_OUT, - }; - unsigned int j, k, val; - unsigned int i = 0; - int rc; - - guard(mutex)(&priv->codec_lock); - dst[i++] = bytes_ext->max; - dst[i++] = 'r'; - - for (j = 0; j < ARRAY_SIZE(fct_status_regs); j++) { - dst[i++] = TASDEVICE_BOOK_ID(fct_status_regs[j]); - dst[i++] = TASDEVICE_PAGE_ID(fct_status_regs[j]); - dst[i++] = TASDEVICE_PAGE_REG(fct_status_regs[j]); - } - dst[i++] = 'D'; - - for (j = 0; j < priv->ndev; j++) { - dst[i++] = j; - dst[i++] = 0; - dst[i++] = 0; - dst[i++] = 0; - - rc = tasdevice_dev_read(priv, j, fct_status_regs[0], &val); - if (rc < 0) - dev_err(priv->dev, - "chn %d fct_status_regs[0] rd err = %d\n", - j, rc); - else - dst[i++] = val; - - for (k = 1; k < ARRAY_SIZE(fct_status_regs); k++, i += 4) { - rc = tasdevice_dev_bulk_read(priv, j, - fct_status_regs[k], &dst[i], 4); - if (rc < 0) { - dev_err(priv->dev, - "chn %d regs[%u] bulk_rd err = %d\n", - j, k, rc); - } - } - - } - - return 0; + return tas2573_status_get_common(kcontrol, ucontrol, + &calib_status_map); } static int create_tas2573_cali_status_ktrl(struct tasdevice_priv @@ -1696,7 +1638,8 @@ static int create_tas2573_cali_status_ktrl(struct tasdevice_priv * Sine gain for Device #i (48 bytes) * } */ - ext_cali_start->max = 39 + priv->ndev * 49; + ext_cali_start->max = calib_status_map.nregs * 3 + 3 + + priv->ndev * (calib_status_map.nregs * 4 + 1); cali_ctrl->name = cali_start_name; cali_ctrl->iface = SNDRV_CTL_ELEM_IFACE_MIXER; cali_ctrl->info = snd_soc_bytes_info_ext; From 2f218b200765b9fed1b28551bb9bae6fba398df4 Mon Sep 17 00:00:00 2001 From: Yige Jiang Date: Tue, 24 Nov 2026 17:56:26 +0800 Subject: [PATCH 1701/2102] ASoC: samsung: snow: Fix private data and node cleanup on remove The ASoC core stores the snd_soc_card pointer in the platform device's driver data. snow_remove() treats that pointer as a snow_priv instead, so the accesses to the DAI link and clock use the wrong object. Obtain the private data through snd_soc_card_get_drvdata(), as the other card callbacks do. Also remove the explicit put of link->codecs->of_node. After the modern DAI-link conversion it is the same node that snd_soc_of_put_dai_link_codecs() releases. Keeping both puts would cause an extra reference drop once the private-data lookup is corrected. The helper alone releases the codec references for both supported bindings. Fixes: aff8d2bed9e5 ("ASoC: samsung: Add HDMI audio support for Snow") Fixes: db1623faa432 ("ASoC: samsung: snow: use modern dai_link style") Signed-off-by: Yige Jiang Link: https://patch.msgid.link/confirmed-20261105-21-73b8787ecede@gmail.com Signed-off-by: Mark Brown --- sound/soc/samsung/snow.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sound/soc/samsung/snow.c b/sound/soc/samsung/snow.c index 9b73c2e62296ac..a1a34ec95c8204 100644 --- a/sound/soc/samsung/snow.c +++ b/sound/soc/samsung/snow.c @@ -222,11 +222,11 @@ static int snow_probe(struct platform_device *pdev) static void snow_remove(struct platform_device *pdev) { - struct snow_priv *priv = platform_get_drvdata(pdev); + struct snd_soc_card *card = platform_get_drvdata(pdev); + struct snow_priv *priv = snd_soc_card_get_drvdata(card); struct snd_soc_dai_link *link = &priv->dai_link; of_node_put(link->cpus->of_node); - of_node_put(link->codecs->of_node); snd_soc_of_put_dai_link_codecs(link); clk_put(priv->clk_i2s_bus); From b0d43948d45bef795e4769b88179ba598382bc4f Mon Sep 17 00:00:00 2001 From: Marco Giunta Date: Mon, 23 Nov 2026 18:56:10 +0100 Subject: [PATCH 1702/2102] ASoC: aw88166: fix backup restoring the RE value instead of saving it aw_dev_backup_sec_record() saves the VCALB and RE values so that aw_dev_backup_sec_recovery() can restore them later. However, it passes AW88166_RECOVERY_SEC_DATA for RE, so instead of reading ACR1/ACR2 it writes the stored value back to them. Pass AW88166_RECORD_SEC_DATA instead, as the vendor aw883xx driver does. Fixes: 94e412c28e61 ("ASoC: codecs: Add aw88166 amplifier driver") Signed-off-by: Marco Giunta Link: https://patch.msgid.link/SN6PR19MB230389321D29F0C88582B4F6FC452@SN6PR19MB2303.namprd19.prod.outlook.com Signed-off-by: Mark Brown --- sound/soc/codecs/aw88166.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/codecs/aw88166.c b/sound/soc/codecs/aw88166.c index a520c9089425ca..19436c001a8086 100644 --- a/sound/soc/codecs/aw88166.c +++ b/sound/soc/codecs/aw88166.c @@ -404,7 +404,7 @@ static int aw_dev_init_re_update(struct aw88166 *aw88166, int flag) static void aw_dev_backup_sec_record(struct aw88166 *aw88166) { aw_dev_init_vcalb_update(aw88166, AW88166_RECORD_SEC_DATA); - aw_dev_init_re_update(aw88166, AW88166_RECOVERY_SEC_DATA); + aw_dev_init_re_update(aw88166, AW88166_RECORD_SEC_DATA); } static void aw_dev_backup_sec_recovery(struct aw88166 *aw88166) From 1bbbf65c75064aeaff793b7bc218f12c53cbe1a9 Mon Sep 17 00:00:00 2001 From: Keisuke Tsukuda Date: Tue, 24 Nov 2026 15:53:39 +0000 Subject: [PATCH 1703/2102] KEYS: trusted: caam: propagate protected key option parsing errors get_pkey_options() returns -EINVAL for invalid protected key options, such as "key_enc_algo=GG". trusted_caam_seal() and trusted_caam_unseal() ignore this error and return 0. The trusted key core then instantiates a key without a blob for "new", or with a zero-length key for "load". On an i.MX6Q running a 7.4.0-rc2-based kernel, adding a key with "new 32 pk key_enc_algo=GG" succeeds, but KEYCTL_READ returns zero bytes because no blob was created. The key cannot be saved and reloaded. Return the parsing error from both paths. On the patched kernel, "new" and "load" with "key_enc_algo=GG" both fail with -EINVAL, while valid requests succeed. Fixes: a703a4c2a328 ("KEYS: trusted: caam based protected key") Signed-off-by: Keisuke Tsukuda Reviewed-by: Serge Hallyn Link: https://lore.kernel.org/r/20261124155310.32044-1-tkdkei@outlook.jp Signed-off-by: Jarkko Sakkinen --- security/keys/trusted-keys/trusted_caam.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/security/keys/trusted-keys/trusted_caam.c b/security/keys/trusted-keys/trusted_caam.c index 6a33dbf2a7f55e..33000d7bb1cca4 100644 --- a/security/keys/trusted-keys/trusted_caam.c +++ b/security/keys/trusted-keys/trusted_caam.c @@ -110,7 +110,7 @@ static int trusted_caam_seal(struct trusted_key_payload *p, char *datablob) info.pkey_info.is_pkey = 1; ret = get_pkey_options(datablob, &info.pkey_info); if (ret < 0) - return 0; + return ret; dump_options(&info.pkey_info); } @@ -142,7 +142,7 @@ static int trusted_caam_unseal(struct trusted_key_payload *p, char *datablob) info.pkey_info.is_pkey = 1; ret = get_pkey_options(datablob, &info.pkey_info); if (ret < 0) - return 0; + return ret; dump_options(&info.pkey_info); p->key_len = p->blob_len + sizeof(struct caam_pkey_info); From f779bd424bf27e17cee57c94f068328be29f3662 Mon Sep 17 00:00:00 2001 From: Guicai Ma Date: Tue, 24 Nov 2026 00:28:49 -0500 Subject: [PATCH 1704/2102] KEYS: Use kfree_sensitive() in keyctl_pkey_e_d_s() keyctl_pkey_e_d_s() frees the temporary 'in' and 'out' buffers with kfree(). For encrypt, decrypt and sign operations these buffers hold plaintext or other sensitive data. Free them with kfree_sensitive() instead. Closes: https://sashiko.dev/#/bug/linux-4199b169-0b8d-4055-9a71-6b5b79e38eb3 Fixes: 00d60fd3b932 ("KEYS: Provide keyctls to drive the new key type ops for asymmetric keys [ver #2]") Cc: stable@vger.kernel.org Signed-off-by: Guicai Ma Link: https://lore.kernel.org/r/20261124052849.940005-1-maguicai@kylinos.cn Signed-off-by: Jarkko Sakkinen --- security/keys/keyctl_pkey.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/security/keys/keyctl_pkey.c b/security/keys/keyctl_pkey.c index 662226576954b5..e10d4ad0a3e1b5 100644 --- a/security/keys/keyctl_pkey.c +++ b/security/keys/keyctl_pkey.c @@ -323,9 +323,9 @@ long keyctl_pkey_e_d_s(int op, ret = -EFAULT; error_out: - kfree(out); + kfree_sensitive(out); error_in: - kfree(in); + kfree_sensitive(in); error_params: keyctl_pkey_params_free(¶ms); return ret; From 1bcff832c48d83c5132662bec83bda37f566d8a2 Mon Sep 17 00:00:00 2001 From: Henry Martin Date: Tue, 24 Nov 2026 10:57:59 +0800 Subject: [PATCH 1705/2102] KEYS: Fix crash on big_key read big_key_update() reserves quota with the raw payload length and then destroys the old payload before instantiating the new one. For a payload of N < 16 bytes that reserve releases 16-N bytes, so the reserve of 16 done by generic_key_instantiate() charges them again and can fail with -EDQUOT once the payload is already destroyed. big_key_destroy() keeps payload->length but clears path and data, so the key stays positive with a stale length that KEYCTL_READ and KEYCTL_REVOKE then follow: kernel BUG at fs/open.c:1145! Oops: invalid opcode: 0000 [#1] SMP KASAN NOPTI RIP: 0010:dentry_open+0x7b/0x90 big_key_read+0x141/0x280 Instantiate the new payload first and destroy the old one only on success; a positive key's reservation is already 16 bytes, so it cannot fail. This issue was discovered by Tencent CodeBuddy Security. Cc: stable@vger.kernel.org Fixes: b6f61c314649 ("keys: Implement update for the big_key type") Signed-off-by: Henry Martin Reviewed-by: Jarkko Sakkinen Reviewed-by: Guicai Ma Tested-by: Guicai Ma Link: https://lore.kernel.org/r/20261124025759.39344-1-bsdhenrymartin@gmail.com Signed-off-by: Jarkko Sakkinen --- security/keys/big_key.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/security/keys/big_key.c b/security/keys/big_key.c index 268f702df380e1..aa3e82ac93ee23 100644 --- a/security/keys/big_key.c +++ b/security/keys/big_key.c @@ -193,16 +193,24 @@ void big_key_destroy(struct key *key) */ int big_key_update(struct key *key, struct key_preparsed_payload *prep) { + struct big_key_payload old = { }; + bool positive = key_is_positive(key); int ret; - ret = key_payload_reserve(key, prep->datalen); + if (positive) + old = *to_big_key_payload(key->payload); + + ret = generic_key_instantiate(key, prep); if (ret < 0) return ret; - if (key_is_positive(key)) - big_key_destroy(key); + if (positive) { + if (old.length > BIG_KEY_FILE_THRESHOLD) + path_put(&old.path); + kfree_sensitive(old.data); + } - return generic_key_instantiate(key, prep); + return 0; } /* From a9d5245fbd168eb4bb2ddeb64ee3f74e21a1ee6f Mon Sep 17 00:00:00 2001 From: Christian Marangi Date: Sat, 21 Nov 2026 00:46:38 +0100 Subject: [PATCH 1706/2102] ASoC: dt-bindings: airoha: Add AN7581 PCM controller The Airoha AN7581 SoC provides a PCM interface for VoIP applications, supporting playback and capture at sample rates of 8 kHz and 16 kHz. The driver configures the PCM bit clock to 2.048 MHz and supports 8-bit and 16-bit samples, with up to 32 channels. Document the related compatible and required interrupt/reset and provide an example for it. Signed-off-by: Christian Marangi Reviewed-by: Rob Herring (Arm) Link: https://patch.msgid.link/20261120234640.169279-2-ansuelsmth@gmail.com Signed-off-by: Mark Brown --- .../bindings/sound/airoha,an7581-pcm.yaml | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Documentation/devicetree/bindings/sound/airoha,an7581-pcm.yaml diff --git a/Documentation/devicetree/bindings/sound/airoha,an7581-pcm.yaml b/Documentation/devicetree/bindings/sound/airoha,an7581-pcm.yaml new file mode 100644 index 00000000000000..e73236453b880f --- /dev/null +++ b/Documentation/devicetree/bindings/sound/airoha,an7581-pcm.yaml @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/sound/airoha,an7581-pcm.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Airoha PCM controller for AN7581 SoC + +maintainers: + - Christian Marangi + +properties: + compatible: + const: airoha,an7581-pcm + + reg: + maxItems: 1 + + interrupts: + maxItems: 1 + + resets: + maxItems: 1 + + reset-names: + const: pcm1 + +required: + - compatible + - reg + - interrupts + - resets + - reset-names + +additionalProperties: false + +examples: + - | + #include + #include + #include + + pcm@1fbd0000 { + compatible = "airoha,an7581-pcm"; + reg = <0x1fbd0000 0x10000>; + + interrupts = ; + resets = <&scuclk EN7581_PCM1_RST>; + reset-names = "pcm1"; + }; + +... From a0c2794fd7f77443ac7bacec86b101459336da3c Mon Sep 17 00:00:00 2001 From: Christian Marangi Date: Sat, 21 Nov 2026 00:46:39 +0100 Subject: [PATCH 1707/2102] ASoC: airoha: Add support for AN7581 PCM driver The Airoha AN7581 SoC provides a PCM interface for VoIP applications, supporting playback and capture at sample rates of 8 kHz and 16 kHz. The driver configures the PCM bit clock to 2.048 KHz and supports 8-bit and 16-bit samples, with up to 32 channels. Add an ASoC platform driver for the AN7581 PCM controller configured for ZSI attached voice chip. Signed-off-by: Christian Marangi Link: https://patch.msgid.link/20261120234640.169279-3-ansuelsmth@gmail.com Signed-off-by: Mark Brown --- MAINTAINERS | 7 + sound/soc/Kconfig | 1 + sound/soc/Makefile | 1 + sound/soc/airoha/Kconfig | 11 + sound/soc/airoha/Makefile | 3 + sound/soc/airoha/an7581-pcm.c | 929 ++++++++++++++++++++++++++++++++++ 6 files changed, 952 insertions(+) create mode 100644 sound/soc/airoha/Kconfig create mode 100644 sound/soc/airoha/Makefile create mode 100644 sound/soc/airoha/an7581-pcm.c diff --git a/MAINTAINERS b/MAINTAINERS index ccbcdc0799b9fb..dfeefad6597e62 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -796,6 +796,13 @@ F: Documentation/devicetree/bindings/sound/airoha,an7581-afe.yaml F: Documentation/devicetree/bindings/sound/airoha,an7581-wm8960.yaml F: sound/soc/mediatek/an7581/* +AIROHA PCM CONTROLLER DRIVER +M: Christian Marangi +L: linux-sound@vger.kernel.org +S: Maintained +F: Documentation/devicetree/bindings/sound/airoha,an7581-pcm.yaml +F: sound/soc/airoha/* + AIROHA SPI SNFI DRIVER M: Lorenzo Bianconi M: Ray Liu diff --git a/sound/soc/Kconfig b/sound/soc/Kconfig index edfdcbf734fe69..27fc13e11b77b5 100644 --- a/sound/soc/Kconfig +++ b/sound/soc/Kconfig @@ -103,6 +103,7 @@ config SND_SOC_USB # All the supported SoCs source "sound/soc/adi/Kconfig" +source "sound/soc/airoha/Kconfig" source "sound/soc/amd/Kconfig" source "sound/soc/apple/Kconfig" source "sound/soc/atmel/Kconfig" diff --git a/sound/soc/Makefile b/sound/soc/Makefile index 21d8406767fcbc..ea581930bb3dc9 100644 --- a/sound/soc/Makefile +++ b/sound/soc/Makefile @@ -46,6 +46,7 @@ obj-$(CONFIG_SND_SOC) += codecs/ obj-$(CONFIG_SND_SOC) += generic/ obj-$(CONFIG_SND_SOC) += apple/ obj-$(CONFIG_SND_SOC) += adi/ +obj-$(CONFIG_SND_SOC) += airoha/ obj-$(CONFIG_SND_SOC) += amd/ obj-$(CONFIG_SND_SOC) += atmel/ obj-$(CONFIG_SND_SOC) += au1x/ diff --git a/sound/soc/airoha/Kconfig b/sound/soc/airoha/Kconfig new file mode 100644 index 00000000000000..709ba1ec349fd2 --- /dev/null +++ b/sound/soc/airoha/Kconfig @@ -0,0 +1,11 @@ +# SPDX-License-Identifier: GPL-2.0-only + +config SND_SOC_AN7581_PCM + tristate "PCM support for Airoha AN7581 chip" + depends on ARCH_AIROHA || COMPILE_TEST + select REGMAP_MMIO + help + This adds PCM driver for Airoha AN7581 boards + that can be used with other codecs. + Select Y if you have such device. + If unsure select "N". diff --git a/sound/soc/airoha/Makefile b/sound/soc/airoha/Makefile new file mode 100644 index 00000000000000..2522fe705d9a32 --- /dev/null +++ b/sound/soc/airoha/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-2.0 + +obj-$(CONFIG_SND_SOC_AN7581_PCM) += an7581-pcm.o diff --git a/sound/soc/airoha/an7581-pcm.c b/sound/soc/airoha/an7581-pcm.c new file mode 100644 index 00000000000000..8e06527c741e3d --- /dev/null +++ b/sound/soc/airoha/an7581-pcm.c @@ -0,0 +1,929 @@ +// SPDX-License-Identifier: GPL-2.0 +// +//Airoha ALSA SoC PCM platform driver for AN7581 +// +//Copyright (C) 2026 Christian Marangi +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define AN7581_PCM_PICR 0x0 +#define AN7581_PCM_CFG_VALID BIT(26) +#define AN7581_PCM_LPBK_ENABLE BIT(25) +#define AN7581_PCM_SOFT_RESET BIT(24) +#define AN7581_PCM_FRAME_COUNT GENMASK(22, 18) +#define AN7581_PCM_BIT_ORDER BIT(16) +#define AN7581_PCM_ONE_BIT_DELAY BIT(12) +#define AN7581_PCM_FS_EDGE BIT(10) +#define AN7581_PCM_FS_LEN GENMASK(9, 8) +#define AN7581_PCM_FS_LEN_8 FIELD_PREP_CONST(AN7581_PCM_FS_LEN, 0x2) +#define AN7581_PCM_FS_LEN_16 FIELD_PREP_CONST(AN7581_PCM_FS_LEN, 0x3) +#define AN7581_PCM_SAMPLE_CLK BIT(4) +#define AN7581_PCM_SAMPLE_CLK_8KHZ FIELD_PREP_CONST(AN7581_PCM_SAMPLE_CLK, 0x0) +#define AN7581_PCM_SAMPLE_CLK_16KHZ FIELD_PREP_CONST(AN7581_PCM_SAMPLE_CLK, 0x1) +#define AN7581_PCM_BIT_CLK GENMASK(3, 1) +#define AN7581_PCM_BIT_CLK_256KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x0) +#define AN7581_PCM_BIT_CLK_512KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x1) +#define AN7581_PCM_BIT_CLK_1024KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x2) +#define AN7581_PCM_BIT_CLK_2048KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x3) +#define AN7581_PCM_BIT_CLK_4096KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x4) +#define AN7581_PCM_BIT_CLK_8192KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x5) +#define AN7581_PCM_BIT_MSTSLV_MODE BIT(0) +#define AN7581_PCM_BIT_MSTSLV_MODE_MASTER FIELD_PREP_CONST(AN7581_PCM_BIT_MSTSLV_MODE, 0x0) +#define AN7581_PCM_BIT_MSTSLV_MODE_SLAVE FIELD_PREP_CONST(AN7581_PCM_BIT_MSTSLV_MODE, 0x1) +/* Same bitmap for all TX timeslot reg */ +#define AN7581_PCM_PTTSCR0 0x4 +#define AN7581_PCM_TXTS1_BW BIT(28) +#define AN7581_PCM_TXTS1_BW_8BIT FIELD_PREP_CONST(AN7581_PCM_TXTS1_BW, 0x0) +#define AN7581_PCM_TXTS1_BW_16BIT FIELD_PREP_CONST(AN7581_PCM_TXTS1_BW, 0x1) +#define AN7581_PCM_TXTS1_START GENMASK(25, 16) +#define AN7581_PCM_TXTS0_BW BIT(12) +#define AN7581_PCM_TXTS0_BW_8BIT FIELD_PREP_CONST(AN7581_PCM_TXTS0_BW, 0x0) +#define AN7581_PCM_TXTS0_BW_16BIT FIELD_PREP_CONST(AN7581_PCM_TXTS0_BW, 0x1) +#define AN7581_PCM_TXTS0_START GENMASK(9, 0) +#define AN7581_PCM_PTTSCR1 0x8 +#define AN7581_PCM_PTTSCR2 0xc +#define AN7581_PCM_PTTSCR3 0x10 +/* Same bitmap for all RX timeslot reg */ +#define AN7581_PCM_PRTSCR0 0x14 +#define AN7581_PCM_RXTS1_BW BIT(28) +#define AN7581_PCM_RXTS1_BW_8BIT FIELD_PREP_CONST(AN7581_PCM_RXTS1_BW, 0x0) +#define AN7581_PCM_RXTS1_BW_16BIT FIELD_PREP_CONST(AN7581_PCM_RXTS1_BW, 0x1) +#define AN7581_PCM_RXTS1_START GENMASK(25, 16) +#define AN7581_PCM_RXTS0_BW BIT(12) +#define AN7581_PCM_RXTS0_BW_8BIT FIELD_PREP_CONST(AN7581_PCM_RXTS0_BW, 0x0) +#define AN7581_PCM_RXTS0_BW_16BIT FIELD_PREP_CONST(AN7581_PCM_RXTS0_BW, 0x1) +#define AN7581_PCM_RXTS0_START GENMASK(9, 0) +#define AN7581_PCM_PRTSCR1 0x18 +#define AN7581_PCM_PRTSCR2 0x1c +#define AN7581_PCM_PRTSCR3 0x20 +#define AN7581_PCM_ISR 0x24 +#define AN7581_PCM_IMR 0x28 +#define AN7581_PCM_IMR_ISI2_INT BIT(16) +#define AN7581_PCM_IMR_ZSI2_INT BIT(15) +#define AN7581_PCM_IMR_SLIC_INT BIT(14) +#define AN7581_PCM_IMR_SFC_INT BIT(13) +#define AN7581_PCM_IMR_ISI1_INT BIT(12) +#define AN7581_PCM_IMR_ZSI1_INT BIT(11) +#define AN7581_PCM_IMR_HUNT_OVERTIME_INT BIT(10) +#define AN7581_PCM_IMR_HUNT_ERR_INT BIT(9) +#define AN7581_PCM_IMR_AHB_BUS_ERR_INT BIT(8) +#define AN7581_PCM_IMR_RBUF_OVERRUN_INT BIT(7) +#define AN7581_PCM_IMR_TBUF_UNDERRUN_INT BIT(6) +#define AN7581_PCM_IMR_RDESC_END_INT BIT(5) +#define AN7581_PCM_IMR_TDESC_END_INT BIT(4) +#define AN7581_PCM_IMR_RDESC_UPDATE_INT BIT(3) +#define AN7581_PCM_IMR_TDESC_UPDATE_INT BIT(2) +#define AN7581_PCM_IMR_TXRX_FB_INT BIT(0) +#define AN7581_PCM_TPDR 0x2c +#define AN7581_PCM_TX_POLLING BIT(0) +#define AN7581_PCM_RPDR 0x30 +#define AN7581_PCM_RX_POLLING BIT(0) +#define AN7581_PCM_TDRBAR 0x34 +#define AN7581_TDESC_BASE GENMASK(31, 0) +#define AN7581_PCM_RDRBAR 0x38 +#define AN7581_RDESC_BASE GENMASK(31, 0) +#define AN7581_PCM_TRDRSR 0x3c +#define AN7581_DESC_OFFSET GENMASK(7, 4) +#define AN7581_DESC_SIZE GENMASK(3, 0) +#define AN7581_PCM_TRDCR 0x40 +#define AN7581_PCM_DMA_POLICY GENMASK(3, 2) +#define AN7581_PCM_DMA_POLICY_RR FIELD_PREP_CONST(AN7581_PCM_DMA_POLICY, 0x0) +#define AN7581_PCM_DMA_POLICY_RSVD FIELD_PREP_CONST(AN7581_PCM_DMA_POLICY, 0x1) +#define AN7581_PCM_DMA_POLICY_TX_PRIORITY FIELD_PREP_CONST(AN7581_PCM_DMA_POLICY, 0x2) +#define AN7581_PCM_DMA_POLICY_RX_PRIORITY FIELD_PREP_CONST(AN7581_PCM_DMA_POLICY, 0x3) +#define AN7581_PCM_RXDMA_ENABLE BIT(1) +#define AN7581_PCM_TXDMA_ENABLE BIT(0) +#define AN7581_PCM_PTTSCR4 0x48 +#define AN7581_PCM_PTTSCR5 0x4c +#define AN7581_PCM_PTTSCR6 0x50 +#define AN7581_PCM_PTTSCR7 0x54 +#define AN7581_PCM_PTTSCR8 0x58 +#define AN7581_PCM_PTTSCR9 0x5c +#define AN7581_PCM_PTTSCR10 0x60 +#define AN7581_PCM_PTTSCR11 0x64 +#define AN7581_PCM_PTTSCR12 0x68 +#define AN7581_PCM_PTTSCR13 0x6c +#define AN7581_PCM_PTTSCR14 0x70 +#define AN7581_PCM_PTTSCR15 0x74 +#define AN7581_PCM_PTTSCR(chan) ((chan) < 8 ? \ + (AN7581_PCM_PTTSCR0 + ((chan) / 2) * 4) : \ + (AN7581_PCM_PTTSCR4 + (((chan) - 8) / 2) * 4)) +#define AN7581_PCM_TXTS_BW(chan) ((chan) % 2 ? AN7581_PCM_TXTS1_BW : AN7581_PCM_TXTS0_BW) +#define AN7581_PCM_TXTS_BW_8BIT 0x0 +#define AN7581_PCM_TXTS_BW_16BIT(chan) AN7581_PCM_TXTS_BW(chan) +#define AN7581_PCM_TXTS_START(chan) ((chan) % 2 ? AN7581_PCM_TXTS1_START : AN7581_PCM_TXTS0_START) +#define AN7581_PCM_PRTSCR4 0x78 +#define AN7581_PCM_PRTSCR5 0x7c +#define AN7581_PCM_PRTSCR6 0x80 +#define AN7581_PCM_PRTSCR7 0x84 +#define AN7581_PCM_PRTSCR8 0x88 +#define AN7581_PCM_PRTSCR9 0x8c +#define AN7581_PCM_PRTSCR10 0x90 +#define AN7581_PCM_PRTSCR11 0x94 +#define AN7581_PCM_PRTSCR12 0x98 +#define AN7581_PCM_PRTSCR13 0x9c +#define AN7581_PCM_PRTSCR14 0xa0 +#define AN7581_PCM_PRTSCR15 0xa4 +#define AN7581_PCM_PRTSCR(chan) ((chan) < 8 ? \ + (AN7581_PCM_PRTSCR0 + ((chan) / 2) * 4) : \ + (AN7581_PCM_PRTSCR4 + (((chan) - 8) / 2) * 4)) +#define AN7581_PCM_RXTS_BW(chan) ((chan) % 2 ? AN7581_PCM_RXTS1_BW : AN7581_PCM_RXTS0_BW) +#define AN7581_PCM_RXTS_BW_8BIT 0x0 +#define AN7581_PCM_RXTS_BW_16BIT(chan) AN7581_PCM_RXTS_BW(chan) +#define AN7581_PCM_RXTS_START(chan) ((chan) % 2 ? AN7581_PCM_RXTS1_START : AN7581_PCM_RXTS0_START) +#define AN7581_PCM_CHBFOSR 0xa8 +#define AN7581_PCM_DESC_CHBF_OFFSET GENMASK(15, 0) +#define AN7581_PCM_DCHENR 0xac +/* Each channel correspond to a bit. + * Example: + * BIT(0) -> chan 0 + * BIT(1) -> chan 1 + * ... + * + * Notice that it's expected the channel are sequential + * aka it's not possible to have empty channel in between. + * (example BIT(0) | BIT(2)) + */ +#define AN7581_PCM_CHAN_EN GENMASK(31, 0) + +#define AN7581_PCM_MAX_CHANNELS 32 +#define AN7581_PCM_TX_DESCRIPTORS 15 +#define AN7581_PCM_RX_DESCRIPTORS 15 +#define AN7581_PCM_DESCRIPTORS (AN7581_PCM_TX_DESCRIPTORS + AN7581_PCM_RX_DESCRIPTORS) +#define AN7581_PCM_FRAMES_PER_DESC 80 +#define AN7581_PCM_MIN_PERIOD_BYTES (AN7581_PCM_FRAMES_PER_DESC * sizeof(u8)) +#define AN7581_PCM_MAX_SAMPLE_BYTES 2 +#define AN7581_PCM_MAX_PERIOD_BYTES (AN7581_PCM_FRAMES_PER_DESC * \ + AN7581_PCM_MAX_CHANNELS * \ + AN7581_PCM_MAX_SAMPLE_BYTES) +#define AN7581_PCM_MAX_BUFFER_BYTES (AN7581_PCM_MAX_PERIOD_BYTES * \ + AN7581_PCM_TX_DESCRIPTORS) + +#define AN7581_PCM_DESC_STATUS_OWNERSHIP BIT(31) +#define AN7581_PCM_DESC_STATUS_OWNERSHIP_CPU FIELD_PREP_CONST(AN7581_PCM_DESC_STATUS_OWNERSHIP, 0x0) +#define AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA FIELD_PREP_CONST(AN7581_PCM_DESC_STATUS_OWNERSHIP, 0x1) +#define AN7581_PCM_DESC_STATUS_SAMPLE_SIZE GENMASK(9, 0) + +#define AN7581_PCM_DEFAULT_BCLK 2048 + +struct an7581_pcm_desc { + u32 status; + u32 channel_mask; + u32 dma_addr; +} __packed; + +struct an7581_pcm_priv { + struct regmap *map; + + /* Cached current stream for IRQ */ + struct snd_pcm_substream *stream[SNDRV_PCM_STREAM_LAST + 1]; + + /* Protect descriptor idx */ + spinlock_t desc_lock; + /* Protect configuration shared by playback and capture. */ + struct mutex user_lock; + unsigned int users; + unsigned int current_rate; + unsigned int current_channels; + + struct an7581_pcm_desc *tx_descs; + int tx_desc_idx; + dma_addr_t tx_dma; + + struct an7581_pcm_desc *rx_descs; + int rx_desc_idx; + dma_addr_t rx_dma; + + unsigned int tx_pos; + unsigned int rx_pos; +}; + +static const struct snd_pcm_hardware an7581_pcm_hardware = { + .info = SNDRV_PCM_INFO_MMAP | + SNDRV_PCM_INFO_MMAP_VALID | + SNDRV_PCM_INFO_INTERLEAVED | + SNDRV_PCM_INFO_BATCH, + .formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_U16_LE, + + .period_bytes_min = AN7581_PCM_MIN_PERIOD_BYTES, + .period_bytes_max = AN7581_PCM_MAX_PERIOD_BYTES, + + .buffer_bytes_max = AN7581_PCM_MAX_BUFFER_BYTES, + + .periods_min = AN7581_PCM_TX_DESCRIPTORS, + .periods_max = AN7581_PCM_TX_DESCRIPTORS, +}; + +static int an7581_pcm_setup_time_slot(struct an7581_pcm_priv *priv, + int direction, int bit_width) +{ + int bit_counter = 0; + int chan; + + for (chan = 0; chan < AN7581_PCM_MAX_CHANNELS; chan++) { + u32 mask, val; + u32 reg; + + if (direction == SNDRV_PCM_STREAM_PLAYBACK) { + reg = AN7581_PCM_PTTSCR(chan); + mask = AN7581_PCM_TXTS_BW(chan) | + AN7581_PCM_TXTS_START(chan); + + if (bit_width == 8) + val = AN7581_PCM_TXTS_BW_8BIT; + else + val = AN7581_PCM_TXTS_BW_16BIT(chan); + val |= bit_counter << __bf_shf(AN7581_PCM_TXTS_START(chan)); + } else { + reg = AN7581_PCM_PRTSCR(chan); + mask = AN7581_PCM_RXTS_BW(chan) | + AN7581_PCM_RXTS_START(chan); + + if (bit_width == 8) + val = AN7581_PCM_RXTS_BW_8BIT; + else + val = AN7581_PCM_RXTS_BW_16BIT(chan); + val |= bit_counter << __bf_shf(AN7581_PCM_RXTS_START(chan)); + } + + regmap_update_bits(priv->map, reg, mask, val); + + bit_counter += bit_width; + } + + return 0; +} + +static int an7581_pcm_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); + struct an7581_pcm_priv *priv = snd_soc_card_get_drvdata(rtd->card); + struct snd_pcm_runtime *runtime = substream->runtime; + int ret; + + snd_soc_set_runtime_hwparams(substream, &an7581_pcm_hardware); + + ret = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, + AN7581_PCM_FRAMES_PER_DESC, + AN7581_PCM_FRAMES_PER_DESC); + if (ret < 0) { + dev_err(rtd->card->dev, "failed to constrain period to 80 frames\n"); + return ret; + } + + ret = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); + if (ret < 0) { + dev_err(rtd->card->dev, "snd_pcm_hw_constraint_integer failed\n"); + return ret; + } + + /* Cache stream substream for IRQ handling */ + priv->stream[substream->stream] = substream; + + /* On open mask interrupt and disable DMA */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_TDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_TXDMA_ENABLE); + } else { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_RDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_RXDMA_ENABLE); + } + + usleep_range(10000, 20000); + + mutex_lock(&priv->user_lock); + + if (!priv->users) { + regmap_clear_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_CFG_VALID); + + usleep_range(5000, 10000); + } + + priv->users++; + + mutex_unlock(&priv->user_lock); + + return ret; +} + +static void an7581_pcm_shutdown(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); + struct an7581_pcm_priv *priv = snd_soc_card_get_drvdata(rtd->card); + + /* On close mask interrupt and disable DMA */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_TDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_TXDMA_ENABLE); + } else { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_RDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_RXDMA_ENABLE); + } + + priv->stream[substream->stream] = NULL; + + usleep_range(10000, 20000); + + mutex_lock(&priv->user_lock); + + if (priv->users) + priv->users--; + + if (!priv->users) + regmap_clear_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_CFG_VALID); + + mutex_unlock(&priv->user_lock); +} + +/* + * Hardware position is always reset to the start when a TX/RX polling is + * triggered. This is handled in trigger. + */ +static int an7581_pcm_prepare(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); + struct an7581_pcm_priv *priv = snd_soc_card_get_drvdata(rtd->card); + struct snd_pcm_runtime *runtime = substream->runtime; + struct an7581_pcm_desc *desc; + unsigned int period_bytes; + unsigned long flags; + int num_desc, i; + + spin_lock_irqsave(&priv->desc_lock, flags); + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + priv->tx_pos = 0; + priv->tx_desc_idx = 0; + desc = priv->tx_descs; + num_desc = AN7581_PCM_TX_DESCRIPTORS; + } else { + priv->rx_pos = 0; + priv->rx_desc_idx = 0; + desc = priv->rx_descs; + num_desc = AN7581_PCM_RX_DESCRIPTORS; + } + spin_unlock_irqrestore(&priv->desc_lock, flags); + + period_bytes = frames_to_bytes(runtime, AN7581_PCM_FRAMES_PER_DESC); + for (i = 0; i < num_desc; i++) { + desc->status |= AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA; + desc->dma_addr = runtime->dma_addr + i * period_bytes; + desc++; + } + + return 0; +} + +static int an7581_pcm_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); + struct an7581_pcm_priv *priv = snd_soc_card_get_drvdata(rtd->card); + unsigned int channels = params_channels(params); + unsigned int rate = params_rate(params); + int bit_width = params_width(params); + struct an7581_pcm_desc *desc; + int num_desc, i; + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + desc = priv->tx_descs; + num_desc = AN7581_PCM_TX_DESCRIPTORS; + } else { + desc = priv->rx_descs; + num_desc = AN7581_PCM_RX_DESCRIPTORS; + } + + mutex_lock(&priv->user_lock); + if (priv->users > 1 && + (priv->current_rate != rate || + priv->current_channels != channels)) { + dev_err(rtd->card->dev, "playback/capture rates/channels must match in full-duplex mode\n"); + mutex_unlock(&priv->user_lock); + return -EBUSY; + } + + if ((unsigned long)rate * channels * bit_width > AN7581_PCM_DEFAULT_BCLK * HZ_PER_KHZ) { + dev_err(rtd->card->dev, + "%u channels at %u Hz and %d-bit exceed %u KHz BCLK\n", + channels, rate, bit_width, + AN7581_PCM_DEFAULT_BCLK); + mutex_unlock(&priv->user_lock); + return -EINVAL; + } + + if (priv->users <= 1) { + /* one bit delay for ZSI */ + regmap_set_bits(priv->map, AN7581_PCM_PICR, AN7581_PCM_ONE_BIT_DELAY); + + regmap_update_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_BIT_MSTSLV_MODE, + AN7581_PCM_BIT_MSTSLV_MODE_MASTER); + + regmap_update_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_BIT_CLK, + AN7581_PCM_BIT_CLK_2048KHZ); + + regmap_update_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_SAMPLE_CLK, + (rate == 16000 ? AN7581_PCM_SAMPLE_CLK_16KHZ : + AN7581_PCM_SAMPLE_CLK_8KHZ)); + + regmap_update_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_FS_LEN, + AN7581_PCM_FS_LEN_16); + + regmap_set_bits(priv->map, AN7581_PCM_PICR, AN7581_PCM_BIT_ORDER); + + regmap_clear_bits(priv->map, AN7581_PCM_PICR, AN7581_PCM_FS_EDGE); + } + + /* Setup timeslot */ + an7581_pcm_setup_time_slot(priv, substream->stream, bit_width); + + if (priv->users <= 1) { + /* Setup Descriptor size and number */ + regmap_update_bits(priv->map, AN7581_PCM_TRDRSR, + AN7581_DESC_OFFSET | AN7581_DESC_SIZE, + FIELD_PREP(AN7581_DESC_OFFSET, sizeof(*desc) / sizeof(u32)) | + FIELD_PREP(AN7581_DESC_SIZE, num_desc)); + + /* + * The usage of this register is not entirely clear, it should tell + * DMA the size of the channel buffer. HW Loopback enabled with a + * playback and capture with a 2 channel test audio file, verified + * that channel handling is interleaved and recorded a similar + * audio file compared to the one provided with playback. + */ + regmap_update_bits(priv->map, AN7581_PCM_CHBFOSR, + AN7581_PCM_DESC_CHBF_OFFSET, + FIELD_PREP(AN7581_PCM_DESC_CHBF_OFFSET, + AN7581_PCM_FRAMES_PER_DESC * bit_width / 8)); + } + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + regmap_write(priv->map, AN7581_PCM_TDRBAR, priv->tx_dma); + else + regmap_write(priv->map, AN7581_PCM_RDRBAR, priv->rx_dma); + + /* Configure descriptors for DMA ownership and sample size */ + for (i = 0; i < num_desc; i++) { + /* Assign to each descriptor the dma_addr + offset of period bytes */ + desc[i].status = FIELD_PREP(AN7581_PCM_DESC_STATUS_SAMPLE_SIZE, + AN7581_PCM_FRAMES_PER_DESC); + + desc[i].channel_mask = GENMASK(channels - 1, 0); + } + + if (priv->users <= 1) { + /* Enable channels */ + regmap_update_bits(priv->map, AN7581_PCM_DCHENR, + AN7581_PCM_CHAN_EN, + FIELD_PREP(AN7581_PCM_CHAN_EN, GENMASK(channels - 1, 0))); + + /* Signal PCM configuration is now valid */ + regmap_set_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_CFG_VALID); + } + + priv->current_rate = rate; + priv->current_channels = channels; + + mutex_unlock(&priv->user_lock); + + return 0; +} + +static int an7581_pcm_trigger(struct snd_pcm_substream *substream, int cmd, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); + struct an7581_pcm_priv *priv = snd_soc_card_get_drvdata(rtd->card); + + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + case SNDRV_PCM_TRIGGER_RESUME: + /* Trigger PCM to POLL new descriptor */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + regmap_set_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_TXDMA_ENABLE); + + regmap_set_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_TDESC_UPDATE_INT); + + regmap_write(priv->map, AN7581_PCM_TPDR, + AN7581_PCM_TX_POLLING); + } else { + regmap_set_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_RXDMA_ENABLE); + + regmap_set_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_RDESC_UPDATE_INT); + + regmap_write(priv->map, AN7581_PCM_RPDR, + AN7581_PCM_RX_POLLING); + } + + break; + case SNDRV_PCM_TRIGGER_STOP: + case SNDRV_PCM_TRIGGER_SUSPEND: + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_TDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_TXDMA_ENABLE); + } else { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_RDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_RXDMA_ENABLE); + } + + break; + default: + return -EINVAL; + } + + return 0; +} + +static const struct snd_soc_dai_ops an7581_pcm_ops = { + .startup = an7581_pcm_startup, + .shutdown = an7581_pcm_shutdown, + .hw_params = an7581_pcm_hw_params, + .prepare = an7581_pcm_prepare, + .trigger = an7581_pcm_trigger, +}; + +static struct snd_soc_dai_driver an7581_pcm_dai_driver[] = { + { + .name = "DLPCM", + .id = 0, + .playback = { + .stream_name = "DLPCM", + .channels_min = 1, + .channels_max = 32, + .rates = SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, + .formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_U16_LE, + }, + .ops = &an7581_pcm_ops, + }, + { + .name = "ULPCM", + .id = 1, + .capture = { + .stream_name = "ULPCM", + .channels_min = 1, + .channels_max = 32, + .rates = SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, + .formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_U16_LE, + }, + .ops = &an7581_pcm_ops, + }, +}; + +static const struct snd_soc_component_driver an7581_pcm_dai_component = { + .name = "an7581-pcm-dai", +}; + +static snd_pcm_uframes_t an7581_pcm_pointer(struct snd_soc_component *component, + struct snd_pcm_substream *substream) +{ + struct snd_soc_card *card = component->card; + struct snd_pcm_runtime *runtime = substream->runtime; + struct an7581_pcm_priv *priv; + unsigned long flags; + unsigned int pos; + + priv = snd_soc_card_get_drvdata(card); + + spin_lock_irqsave(&priv->desc_lock, flags); + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + pos = bytes_to_frames(runtime, priv->tx_pos); + else + pos = bytes_to_frames(runtime, priv->rx_pos); + spin_unlock_irqrestore(&priv->desc_lock, flags); + + return pos % runtime->buffer_size; +} + +static int an7581_pcm_new(struct snd_soc_component *component, + struct snd_soc_pcm_runtime *rtd) +{ + struct snd_pcm *pcm = rtd->pcm; + + snd_pcm_set_managed_buffer_all(pcm, SNDRV_DMA_TYPE_DEV, component->dev, + 0, + AN7581_PCM_MAX_BUFFER_BYTES); + + return 0; +} + +static const struct snd_soc_component_driver an7581_pcm_platform = { + .name = "an7581-pcm-audio", + .pointer = an7581_pcm_pointer, + .pcm_new = an7581_pcm_new, +}; + +SND_SOC_DAILINK_DEFS(playback, + DAILINK_COMP_ARRAY(COMP_CPU("DLPCM")), + DAILINK_COMP_ARRAY(COMP_DUMMY()), + DAILINK_COMP_ARRAY(COMP_EMPTY())); + +SND_SOC_DAILINK_DEFS(capture, + DAILINK_COMP_ARRAY(COMP_CPU("ULPCM")), + DAILINK_COMP_ARRAY(COMP_DUMMY()), + DAILINK_COMP_ARRAY(COMP_EMPTY())); + +static struct snd_soc_dai_link an7581_pcm_dai_links[] = { + { + .name = "an7581-playback", + .stream_name = "an7581-playback", + .playback_only = 1, + SND_SOC_DAILINK_REG(playback), + }, + { + .name = "an7581-capture", + .stream_name = "an7581-capture", + .capture_only = 1, + SND_SOC_DAILINK_REG(capture), + }, +}; + +static struct snd_soc_card an7581_pcm_card = { + .name = "an7581-pcm", + .owner = THIS_MODULE, + .dai_link = an7581_pcm_dai_links, + .num_links = ARRAY_SIZE(an7581_pcm_dai_links), +}; + +static irqreturn_t an7581_pcm_irq_handler(int irq, void *data) +{ + struct snd_pcm_substream *substream; + struct an7581_pcm_priv *priv = data; + irqreturn_t ret = IRQ_NONE; + unsigned long flags; + u32 status, isr = 0; + + regmap_read(priv->map, AN7581_PCM_ISR, &isr); + + /* Scan descriptor on receiving RX desc update interrupt */ + if (isr & AN7581_PCM_IMR_RDESC_UPDATE_INT) { + struct snd_pcm_runtime *runtime; + struct an7581_pcm_desc *desc; + unsigned int sample_size; + bool rx_poll = false; + int i; + + substream = priv->stream[SNDRV_PCM_STREAM_CAPTURE]; + if (!substream) + goto handle_tx; + + ret = IRQ_HANDLED; + runtime = substream->runtime; + + for (i = 0; i < AN7581_PCM_RX_DESCRIPTORS; i++) { + spin_lock_irqsave(&priv->desc_lock, flags); + + desc = &priv->rx_descs[priv->rx_desc_idx]; + status = desc->status; + if ((status & AN7581_PCM_DESC_STATUS_OWNERSHIP) == + AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA) { + spin_unlock_irqrestore(&priv->desc_lock, + flags); + break; + } + + sample_size = FIELD_GET(AN7581_PCM_DESC_STATUS_SAMPLE_SIZE, + status); + + priv->rx_pos += frames_to_bytes(runtime, sample_size); + priv->rx_desc_idx++; + if (priv->rx_desc_idx == AN7581_PCM_RX_DESCRIPTORS) + priv->rx_desc_idx = 0; + + spin_unlock_irqrestore(&priv->desc_lock, flags); + + snd_pcm_period_elapsed(substream); + + desc->status |= AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA; + + if (snd_pcm_capture_hw_avail(runtime) < runtime->period_size) + goto handle_tx; + + rx_poll = true; + } + + if (rx_poll) + regmap_write(priv->map, AN7581_PCM_RPDR, AN7581_PCM_RX_POLLING); + } + +handle_tx: + /* Scan descriptor on receiving TX desc update interrupt */ + if (isr & AN7581_PCM_IMR_TDESC_UPDATE_INT) { + struct snd_pcm_runtime *runtime; + struct an7581_pcm_desc *desc; + unsigned int sample_size; + bool tx_poll = false; + int i; + + substream = priv->stream[SNDRV_PCM_STREAM_PLAYBACK]; + if (!substream) + goto exit; + + ret = IRQ_HANDLED; + runtime = substream->runtime; + + for (i = 0; i < AN7581_PCM_TX_DESCRIPTORS; i++) { + spin_lock_irqsave(&priv->desc_lock, flags); + + desc = &priv->tx_descs[priv->tx_desc_idx]; + status = desc->status; + if ((status & AN7581_PCM_DESC_STATUS_OWNERSHIP) == + AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA) { + spin_unlock_irqrestore(&priv->desc_lock, + flags); + break; + } + + sample_size = FIELD_GET(AN7581_PCM_DESC_STATUS_SAMPLE_SIZE, + status); + + priv->tx_pos += frames_to_bytes(runtime, sample_size); + priv->tx_desc_idx++; + if (priv->tx_desc_idx == AN7581_PCM_TX_DESCRIPTORS) + priv->tx_desc_idx = 0; + + spin_unlock_irqrestore(&priv->desc_lock, flags); + + snd_pcm_period_elapsed(substream); + + desc->status |= AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA; + + if (snd_pcm_playback_hw_avail(runtime) < runtime->period_size) + return IRQ_HANDLED; + + tx_poll = true; + } + + if (tx_poll) + regmap_write(priv->map, AN7581_PCM_TPDR, + AN7581_PCM_TX_POLLING); + } + +exit: + return ret; +} + +static const struct regmap_config an7581_pcm_regmap_config = { + .reg_bits = 32, + .val_bits = 32, + .reg_stride = 4, +}; + +static int an7581_pcm_probe(struct platform_device *pdev) +{ + struct snd_soc_card *card = &an7581_pcm_card; + struct snd_soc_dai_link *dai_link; + struct device *dev = &pdev->dev; + struct an7581_pcm_priv *priv; + struct reset_control *reset; + void __iomem *base; + int irq; + int ret; + int i; + + card->dev = dev; + + priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); + if (!priv) + return -ENOMEM; + snd_soc_card_set_drvdata(card, priv); + + base = devm_platform_ioremap_resource(pdev, 0); + if (IS_ERR(base)) + return PTR_ERR(base); + + priv->map = devm_regmap_init_mmio(dev, base, + &an7581_pcm_regmap_config); + if (IS_ERR(priv->map)) + return PTR_ERR(priv->map); + + reset = devm_reset_control_get_exclusive(dev, "pcm1"); + if (IS_ERR(reset)) + return PTR_ERR(reset); + + irq = of_irq_get(dev_of_node(dev), 0); + if (irq < 0) + return irq; + + ret = devm_request_irq(dev, irq, an7581_pcm_irq_handler, + 0, dev_name(dev), priv); + if (ret) + return ret; + + spin_lock_init(&priv->desc_lock); + mutex_init(&priv->user_lock); + + /* Reset the PCM interface */ + reset_control_assert(reset); + usleep_range(5000, 10000); + reset_control_deassert(reset); + usleep_range(5000, 10000); + + ret = dma_set_coherent_mask(dev, DMA_BIT_MASK(32)); + if (ret) + return ret; + + priv->tx_descs = dmam_alloc_coherent(dev, sizeof(struct an7581_pcm_desc) * + AN7581_PCM_TX_DESCRIPTORS, &priv->tx_dma, + GFP_KERNEL); + if (!priv->tx_descs) + return -ENOMEM; + + priv->rx_descs = dmam_alloc_coherent(dev, sizeof(struct an7581_pcm_desc) * + AN7581_PCM_RX_DESCRIPTORS, &priv->rx_dma, + GFP_KERNEL); + if (!priv->rx_descs) + return -ENOMEM; + + for_each_card_prelinks(card, i, dai_link) + dai_link->platforms->of_node = dev->of_node; + + ret = devm_snd_soc_register_component(dev, + &an7581_pcm_platform, + NULL, 0); + if (ret) + return dev_err_probe(dev, ret, "Cannot register PCM component\n"); + + ret = devm_snd_soc_register_component(dev, + &an7581_pcm_dai_component, + an7581_pcm_dai_driver, + ARRAY_SIZE(an7581_pcm_dai_driver)); + if (ret) + return dev_err_probe(dev, ret, "Cannot register PCM DAI component\n"); + + ret = devm_snd_soc_register_card(dev, card); + if (ret) + return dev_err_probe(dev, ret, "%s snd_soc_register_card fail\n", __func__); + + return 0; +} + +static void an7581_pcm_remove(struct platform_device *pdev) +{ + struct snd_soc_card *card = &an7581_pcm_card; + struct an7581_pcm_priv *priv; + + priv = snd_soc_card_get_drvdata(card); + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_TDESC_UPDATE_INT | + AN7581_PCM_IMR_RDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_TXDMA_ENABLE | + AN7581_PCM_RXDMA_ENABLE); +} + +static const struct of_device_id an7581_pcm_dt_match[] = { + { .compatible = "airoha,an7581-pcm" }, + { /* sentinel */ } +}; +MODULE_DEVICE_TABLE(of, an7581_pcm_dt_match); + +static struct platform_driver an7581_pcm_driver = { + .driver = { + .name = "an7581-pcm", + .of_match_table = an7581_pcm_dt_match, + .pm = &snd_soc_pm_ops, + }, + .probe = an7581_pcm_probe, + .remove = an7581_pcm_remove, +}; +module_platform_driver(an7581_pcm_driver); + +MODULE_DESCRIPTION("Airoha SoC PCM platform driver for ALSA AN7581"); +MODULE_AUTHOR("Christian Marangi "); +MODULE_LICENSE("GPL"); From f52668f474f15267e2ce472af9b060748b190382 Mon Sep 17 00:00:00 2001 From: Richard Fitzgerald Date: Fri, 20 Nov 2026 11:04:38 +0000 Subject: [PATCH 1708/2102] ASoC: cs35l56: Remove SDW1 TX source controls and widgets Remove the ALSA controls and mux widgets for the SDW1 capture DAI. Connect this DAI to a dummy siggen source like the OT25 DAI. This is to allow DP3 to be used for its intended purpose as the SDCA companion amp output. The implementation of this DAI was incorrect. It provided a capture DAI for the SoundWire DP3 port. But DP4 (OT25 DAI) is the port for feedback to the host. The DP3 port is used for SDCA companion amp (OT127) and the mixer source registers are owned by the firmware. The driver should not be writing to them. Nothing has ever used these ALSA controls so they can safely be removed. The incorrect use of DP3 as the feedback to the host has already been fixed in these commits: commit 86c8360c97f6 ("ASoC: cs35l56: Add DAI for SDCA OT25 stream") commit 4b7f393a01f8 ("ASoC: sdw_utils: Switch CS35L56/57/62/63 to use OT25 DAI") Signed-off-by: Richard Fitzgerald Link: https://patch.msgid.link/20261120110441.2163567-2-rf@opensource.cirrus.com Signed-off-by: Mark Brown --- sound/soc/codecs/cs35l56-shared.c | 16 ---------- sound/soc/codecs/cs35l56.c | 51 ++----------------------------- 2 files changed, 2 insertions(+), 65 deletions(-) diff --git a/sound/soc/codecs/cs35l56-shared.c b/sound/soc/codecs/cs35l56-shared.c index 4d76f177792723..073f7bdd3b0d4f 100644 --- a/sound/soc/codecs/cs35l56-shared.c +++ b/sound/soc/codecs/cs35l56-shared.c @@ -49,14 +49,6 @@ int cs35l56_set_asp_defaults(struct cs35l56_base *cs35l56_base) EXPORT_SYMBOL_NS_GPL(cs35l56_set_asp_defaults, "SND_SOC_CS35L56_SHARED"); static const struct reg_sequence cs35l56_patch[] = { - /* - * Firmware can change these to non-defaults to satisfy SDCA. - * Ensure that they are at known defaults. - */ - { CS35L56_SWIRE_DP3_CH1_INPUT, 0x00000018 }, - { CS35L56_SWIRE_DP3_CH2_INPUT, 0x00000019 }, - { CS35L56_SWIRE_DP3_CH3_INPUT, 0x00000029 }, - { CS35L56_SWIRE_DP3_CH4_INPUT, 0x00000028 }, { CS35L56_IRQ1_MASK_18, 0x1f7df0ff }, }; @@ -105,10 +97,6 @@ int cs35l56_set_patch(struct cs35l56_base *cs35l56_base) EXPORT_SYMBOL_NS_GPL(cs35l56_set_patch, "SND_SOC_CS35L56_SHARED"); static const struct reg_default cs35l56_reg_defaults[] = { - { CS35L56_SWIRE_DP3_CH1_INPUT, 0x00000018 }, - { CS35L56_SWIRE_DP3_CH2_INPUT, 0x00000019 }, - { CS35L56_SWIRE_DP3_CH3_INPUT, 0x00000029 }, - { CS35L56_SWIRE_DP3_CH4_INPUT, 0x00000028 }, { CS35L56_IRQ1_MASK_1, 0x83ffffff }, { CS35L56_IRQ1_MASK_2, 0xffff7fff }, { CS35L56_IRQ1_MASK_4, 0xe0ffffff }, @@ -121,10 +109,6 @@ static const struct reg_default cs35l56_reg_defaults[] = { }; static const struct reg_default cs35l63_reg_defaults[] = { - { CS35L56_SWIRE_DP3_CH1_INPUT, 0x00000018 }, - { CS35L56_SWIRE_DP3_CH2_INPUT, 0x00000019 }, - { CS35L56_SWIRE_DP3_CH3_INPUT, 0x00000029 }, - { CS35L56_SWIRE_DP3_CH4_INPUT, 0x00000028 }, { CS35L56_IRQ1_MASK_1, 0x8003ffff }, { CS35L56_IRQ1_MASK_2, 0xffff7fff }, { CS35L56_IRQ1_MASK_4, 0xe0ffffff }, diff --git a/sound/soc/codecs/cs35l56.c b/sound/soc/codecs/cs35l56.c index 30835dc5600643..acb202559dff60 100644 --- a/sound/soc/codecs/cs35l56.c +++ b/sound/soc/codecs/cs35l56.c @@ -267,42 +267,6 @@ static const struct snd_kcontrol_new asp1_tx4_mux = SOC_DAPM_ENUM_EXT("ASP1TX4 SRC", cs35l56_asp1tx4_enum, cs35l56_asp_tx_get, cs35l56_asp_tx_put); -static SOC_VALUE_ENUM_SINGLE_DECL(cs35l56_sdw1tx1_enum, - CS35L56_SWIRE_DP3_CH1_INPUT, - 0, CS35L56_SWIRETXn_SRC_MASK, - cs35l56_tx_input_texts, - cs35l56_tx_input_values); - -static const struct snd_kcontrol_new sdw1_tx1_mux = - SOC_DAPM_ENUM("SDW1TX1 SRC", cs35l56_sdw1tx1_enum); - -static SOC_VALUE_ENUM_SINGLE_DECL(cs35l56_sdw1tx2_enum, - CS35L56_SWIRE_DP3_CH2_INPUT, - 0, CS35L56_SWIRETXn_SRC_MASK, - cs35l56_tx_input_texts, - cs35l56_tx_input_values); - -static const struct snd_kcontrol_new sdw1_tx2_mux = - SOC_DAPM_ENUM("SDW1TX2 SRC", cs35l56_sdw1tx2_enum); - -static SOC_VALUE_ENUM_SINGLE_DECL(cs35l56_sdw1tx3_enum, - CS35L56_SWIRE_DP3_CH3_INPUT, - 0, CS35L56_SWIRETXn_SRC_MASK, - cs35l56_tx_input_texts, - cs35l56_tx_input_values); - -static const struct snd_kcontrol_new sdw1_tx3_mux = - SOC_DAPM_ENUM("SDW1TX3 SRC", cs35l56_sdw1tx3_enum); - -static SOC_VALUE_ENUM_SINGLE_DECL(cs35l56_sdw1tx4_enum, - CS35L56_SWIRE_DP3_CH4_INPUT, - 0, CS35L56_SWIRETXn_SRC_MASK, - cs35l56_tx_input_texts, - cs35l56_tx_input_values); - -static const struct snd_kcontrol_new sdw1_tx4_mux = - SOC_DAPM_ENUM("SDW1TX4 SRC", cs35l56_sdw1tx4_enum); - static int cs35l56_play_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { @@ -407,11 +371,6 @@ static const struct snd_soc_dapm_widget cs35l56_dapm_widgets[] = { SND_SOC_DAPM_MUX("ASP1 TX3 Source", SND_SOC_NOPM, 0, 0, &asp1_tx3_mux), SND_SOC_DAPM_MUX("ASP1 TX4 Source", SND_SOC_NOPM, 0, 0, &asp1_tx4_mux), - SND_SOC_DAPM_MUX("SDW1 TX1 Source", SND_SOC_NOPM, 0, 0, &sdw1_tx1_mux), - SND_SOC_DAPM_MUX("SDW1 TX2 Source", SND_SOC_NOPM, 0, 0, &sdw1_tx2_mux), - SND_SOC_DAPM_MUX("SDW1 TX3 Source", SND_SOC_NOPM, 0, 0, &sdw1_tx3_mux), - SND_SOC_DAPM_MUX("SDW1 TX4 Source", SND_SOC_NOPM, 0, 0, &sdw1_tx4_mux), - SND_SOC_DAPM_SIGGEN("VMON ADC"), SND_SOC_DAPM_SIGGEN("IMON ADC"), SND_SOC_DAPM_SIGGEN("ERRVOL ADC"), @@ -420,6 +379,7 @@ static const struct snd_soc_dapm_widget cs35l56_dapm_widgets[] = { SND_SOC_DAPM_SIGGEN("VBSTMON ADC"), SND_SOC_DAPM_SIGGEN("TEMPMON ADC"), SND_SOC_DAPM_SIGGEN("OT25 Reference"), + SND_SOC_DAPM_SIGGEN("OT127 Source"), SND_SOC_DAPM_INPUT("Calibrate"), }; @@ -476,14 +436,7 @@ static const struct snd_soc_dapm_route cs35l56_audio_map[] = { { "ASP1 Capture", NULL, "ASP1TX3" }, { "ASP1 Capture", NULL, "ASP1TX4" }, - CS35L56_SRC_ROUTE("SDW1 TX1") - CS35L56_SRC_ROUTE("SDW1 TX2") - CS35L56_SRC_ROUTE("SDW1 TX3") - CS35L56_SRC_ROUTE("SDW1 TX4") - { "SDW1 Capture", NULL, "SDW1 TX1 Source" }, - { "SDW1 Capture", NULL, "SDW1 TX2 Source" }, - { "SDW1 Capture", NULL, "SDW1 TX3 Source" }, - { "SDW1 Capture", NULL, "SDW1 TX4 Source" }, + { "SDW1 Capture", NULL, "OT127 Source" }, { "OT25", NULL, "OT25 Reference" }, }; From fc7de44504789fb1749847a218258509a2b9aa4c Mon Sep 17 00:00:00 2001 From: Richard Fitzgerald Date: Fri, 20 Nov 2026 11:04:39 +0000 Subject: [PATCH 1709/2102] ASoC: cs35l56: Rename the DP3 DAI to cs35l56-ot127 Rename the DAI for DP3 to cs35l56-ot127 to match its actual function as the SDCA OT127 Companion Amp output (a type of codec-codec link). The previous designation as "SDW1 Capture" was incorrect. It is not for host capture and never has been (this function is on DP4). The use of the old DAI name was already removed in previous commit 4b7f393a01f8 ("ASoC: sdw_utils: Switch CS35L56/57/62/63 to use OT25 DAI"), so there are no users of the old DAI name in the kernel. Signed-off-by: Richard Fitzgerald Link: https://patch.msgid.link/20261120110441.2163567-3-rf@opensource.cirrus.com Signed-off-by: Mark Brown --- sound/soc/codecs/cs35l56.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sound/soc/codecs/cs35l56.c b/sound/soc/codecs/cs35l56.c index acb202559dff60..439063084d4b12 100644 --- a/sound/soc/codecs/cs35l56.c +++ b/sound/soc/codecs/cs35l56.c @@ -436,7 +436,7 @@ static const struct snd_soc_dapm_route cs35l56_audio_map[] = { { "ASP1 Capture", NULL, "ASP1TX3" }, { "ASP1 Capture", NULL, "ASP1TX4" }, - { "SDW1 Capture", NULL, "OT127 Source" }, + { "OT127", NULL, "OT127 Source" }, { "OT25", NULL, "OT25 Reference" }, }; @@ -855,10 +855,10 @@ static struct snd_soc_dai_driver cs35l56_dai[] = { .ops = &cs35l56_sdw_dai_ops, }, { - .name = "cs35l56-sdw1c", + .name = "cs35l56-ot127", .id = 2, .capture = { - .stream_name = "SDW1 Capture", + .stream_name = "OT127", .channels_min = 1, .channels_max = 4, .rates = CS35L56_RATES, From 0c690c80941fcbeef25dd549ccb6f57885266f49 Mon Sep 17 00:00:00 2001 From: Richard Fitzgerald Date: Fri, 20 Nov 2026 11:04:40 +0000 Subject: [PATCH 1710/2102] ASoC: cs35l56: Eliminate trivial regmap patch Previous commits removed most of the registers from the common cs35l56_patch, leaving only one register in this patch. Move that single register patch into the separate cs35l56 and cs35l63 patches and remove the trivial common patch. Signed-off-by: Richard Fitzgerald Link: https://patch.msgid.link/20261120110441.2163567-4-rf@opensource.cirrus.com Signed-off-by: Mark Brown --- sound/soc/codecs/cs35l56-shared.c | 28 +++++++--------------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/sound/soc/codecs/cs35l56-shared.c b/sound/soc/codecs/cs35l56-shared.c index 073f7bdd3b0d4f..34aebf81f4a442 100644 --- a/sound/soc/codecs/cs35l56-shared.c +++ b/sound/soc/codecs/cs35l56-shared.c @@ -50,16 +50,14 @@ EXPORT_SYMBOL_NS_GPL(cs35l56_set_asp_defaults, "SND_SOC_CS35L56_SHARED"); static const struct reg_sequence cs35l56_patch[] = { { CS35L56_IRQ1_MASK_18, 0x1f7df0ff }, -}; - -static const struct reg_sequence cs35l56_patch_fw[] = { /* These are not reset by a soft-reset, so patch to defaults. */ { CS35L56_MAIN_RENDER_USER_MUTE, 0x00000000 }, { CS35L56_MAIN_RENDER_USER_VOLUME, 0x00000000 }, { CS35L56_MAIN_POSTURE_NUMBER, 0x00000000 }, }; -static const struct reg_sequence cs35l63_patch_fw[] = { +static const struct reg_sequence cs35l63_patch[] = { + { CS35L56_IRQ1_MASK_18, 0x1f7df0ff }, /* These are not reset by a soft-reset, so patch to defaults. */ { CS35L63_MAIN_RENDER_USER_MUTE, 0x00000000 }, { CS35L63_MAIN_RENDER_USER_VOLUME, 0x00000000 }, @@ -68,31 +66,19 @@ static const struct reg_sequence cs35l63_patch_fw[] = { int cs35l56_set_patch(struct cs35l56_base *cs35l56_base) { - int ret; - - ret = regmap_register_patch(cs35l56_base->regmap, cs35l56_patch, - ARRAY_SIZE(cs35l56_patch)); - if (ret) - return ret; - - switch (cs35l56_base->type) { case 0x54: case 0x56: case 0x57: - ret = regmap_register_patch(cs35l56_base->regmap, cs35l56_patch_fw, - ARRAY_SIZE(cs35l56_patch_fw)); - break; + return regmap_register_patch(cs35l56_base->regmap, cs35l56_patch, + ARRAY_SIZE(cs35l56_patch)); case 0x63: case 0x62: - ret = regmap_register_patch(cs35l56_base->regmap, cs35l63_patch_fw, - ARRAY_SIZE(cs35l63_patch_fw)); - break; + return regmap_register_patch(cs35l56_base->regmap, cs35l63_patch, + ARRAY_SIZE(cs35l63_patch)); default: - break; + return 0; } - - return ret; } EXPORT_SYMBOL_NS_GPL(cs35l56_set_patch, "SND_SOC_CS35L56_SHARED"); From 406541bbf4eb6f3acc6193a6a74aeb459cddd7f4 Mon Sep 17 00:00:00 2001 From: Richard Fitzgerald Date: Fri, 20 Nov 2026 11:04:41 +0000 Subject: [PATCH 1711/2102] ASoC: cs35l56: Add test that probe() doesn't write SDW mux registers The driver cannot assume that it owns control of the CS35L56_SWIRE_DP3_CH?_INPUT registers so it must not do anything during probe() or component_probe() that could result in a write to these registers. Add a test case for this. Signed-off-by: Richard Fitzgerald Link: https://patch.msgid.link/20261120110441.2163567-5-rf@opensource.cirrus.com Signed-off-by: Mark Brown --- sound/soc/codecs/cs35l56-test.c | 84 +++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/sound/soc/codecs/cs35l56-test.c b/sound/soc/codecs/cs35l56-test.c index b422d19ba0b216..362da30b949e66 100644 --- a/sound/soc/codecs/cs35l56-test.c +++ b/sound/soc/codecs/cs35l56-test.c @@ -63,6 +63,7 @@ struct cs35l56_test_priv { bool asp_config_regs_written; bool asp_mixer_regs_written; + bool sdw_mux_regs_written; }; struct cs35l56_test_param { @@ -124,6 +125,11 @@ static const struct range cs35l56_test_asp_mixer_registers_range = { .end = CS35L56_ASP1TX4_INPUT, }; +static const struct range cs35l56_test_sdw_mux_registers_range = { + .start = CS35L56_SWIRE_DP3_CH1_INPUT, + .end = CS35L56_SWIRE_DP3_CH4_INPUT, +}; + static int cs35l56_test_mock_registers_read(void *context, const void *reg_buf, size_t reg_size, void *val_buf, size_t val_size) @@ -200,6 +206,9 @@ static int cs35l56_test_mock_registers_write(void *context, const void *data, si if (range_overlaps(&addr_range, &cs35l56_test_asp_mixer_registers_range)) priv->asp_mixer_regs_written = true; + if (range_overlaps(&addr_range, &cs35l56_test_sdw_mux_registers_range)) + priv->sdw_mux_regs_written = true; + for (i = 0; i < count; i += sizeof(u32)) { val = get_unaligned_be32(buf + i); ret = regmap_write(priv->registers, reg + i, val); @@ -929,6 +938,79 @@ static void cs35l56_test_component_probe_omits_asp(struct kunit *test) KUNIT_EXPECT_FALSE(test, priv->asp_mixer_regs_written); } +/* + * Probing the component must not write the SoundWire TX mux registers, + * either directly or through a subsequent regcache_sync(). + */ +static void cs35l56_test_component_probe_omits_sdw_mux(struct kunit *test) +{ + struct cs35l56_test_priv *priv = test->priv; + struct cs35l56_private *cs35l56 = priv->cs35l56_priv; + struct snd_soc_card *card = cs35l56->component->card; + struct snd_soc_aux_dev *aux; + struct faux_device *card_dev; + + cs35l56_test_create_mock_supplies(test); + cs35l56_test_create_mock_device_registers(test); + + KUNIT_ASSERT_NOT_NULL(test, priv->regmap_config); + cs35l56->base.regmap = devm_regmap_init(cs35l56->base.dev, + &cs35l56_test_mock_registers_client_regmap_bus, + test, priv->regmap_config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cs35l56->base.regmap); + + KUNIT_ASSERT_EQ(test, 0, cs35l56_common_probe(cs35l56, 0)); + KUNIT_ASSERT_EQ(test, 0, + kunit_add_action_or_reset(test, cs35l56_remove_wrapper, cs35l56)); + + /* Prevent real dsp_work */ + INIT_WORK(&cs35l56->dsp_work, cs35l56_test_dummy_dsp_work); + + /* Simulate first attachment and re-attachment after the soft reset. */ + regcache_cache_only(cs35l56->base.regmap, false); + KUNIT_ASSERT_EQ(test, 0, cs35l56_init(cs35l56)); + KUNIT_ASSERT_EQ(test, 0, cs35l56_init(cs35l56)); + KUNIT_ASSERT_TRUE(test, cs35l56->base.init_done); + flush_work(&cs35l56->component_register_work); + KUNIT_ASSERT_TRUE(test, cs35l56->component_registered); + + card_dev = faux_device_create("cs35l56_test_card", NULL, NULL); + KUNIT_ASSERT_NOT_NULL(test, card_dev); + KUNIT_ASSERT_EQ(test, 0, + kunit_add_action_or_reset(test, faux_device_destroy_wrapper, card_dev)); + + /* Bind as an auxiliary component so the ASP DAI is never probed. */ + aux = kunit_kzalloc(test, sizeof(*aux), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, aux); + aux->dlc.name = dev_name(cs35l56->base.dev); + card->name = "cs35l56-test"; + card->dev = &card_dev->dev; + card->owner = THIS_MODULE; + card->aux_dev = aux; + card->num_aux_devs = 1; + KUNIT_ASSERT_EQ(test, 0, snd_soc_register_card(card)); + KUNIT_ASSERT_EQ(test, 0, + kunit_add_action_or_reset(test, snd_soc_unregister_card_wrapper, card)); + KUNIT_ASSERT_TRUE(test, card->instantiated); + KUNIT_EXPECT_FALSE(test, priv->sdw_mux_regs_written); + + /* + * Flush cache to ensure there aren't cached values for the SoundWire muxes. + * The first case without regcache_mark_dirty() tests flushing when + * hardware registers have not reset, and requires a dummy write to + * the cache to make it dirty. + */ + regcache_cache_only(cs35l56->base.regmap, true); + KUNIT_ASSERT_EQ(test, 0, regmap_write(cs35l56->base.regmap, + CS35L56_DSP_VIRTUAL1_MBOX_1, 0)); + regcache_cache_only(cs35l56->base.regmap, false); + KUNIT_ASSERT_EQ(test, 0, regcache_sync(cs35l56->base.regmap)); + regcache_mark_dirty(cs35l56->base.regmap); + KUNIT_ASSERT_EQ(test, 0, regcache_sync(cs35l56->base.regmap)); + + KUNIT_EXPECT_FALSE(test, priv->sdw_mux_regs_written); +} + static int cs35l56_test_case_init_common(struct kunit *test) { struct cs35l56_test_priv *priv; @@ -1233,6 +1315,8 @@ static struct kunit_case cs35l56_test_cases_soundwire[] = { KUNIT_CASE(cs35l56_test_set_fw_name_preserves_spkid_without_onchip_gpios), KUNIT_CASE_PARAM(cs35l56_test_component_probe_omits_asp, cs35l56_test_type_rev_all_gen_params), + KUNIT_CASE_PARAM(cs35l56_test_component_probe_omits_sdw_mux, + cs35l56_test_type_rev_all_gen_params), { } /* terminator */ }; From 9c57b993ba3ee57198816c3783f222873de75e82 Mon Sep 17 00:00:00 2001 From: "doloers@hotmail.com" Date: Wed, 18 Nov 2026 08:09:32 +0800 Subject: [PATCH 1712/2102] ASoC: codecs: wcd934x: capture needs the codec sysclk MCLK is not just a bit clock: __wcd934x_cdc_mclk_enable() enables the external clock, the analog bias generator (ANA_BIAS) and MCLK_EN in one go, and the ADC/DMIC decimators only run once it is up. In the DAPM graph, however, nothing on the capture side depends on it: the only route into MCLK comes from the board file as "RX_BIAS" -> "MCLK", which is the playback path. Boards whose playback does not go through the codec therefore record digital silence with every mixer in place - polaris (Xiaomi Mi MIX 2S, playback via QUAT_MI2S/TAS2559) is one: peak 0, ANA_BIAS 0x00, MCLK_EN 0, and no error anywhere in the kernel. Make the capture front ends depend on MCLK so the codec is powered when a capture stream starts. Boards keep their existing "RX_BIAS" -> "MCLK" route for playback; this only adds the other half of the graph. Signed-off-by: Shen Xiaopeng Link: https://patch.msgid.link/TYWP301MB008701733619289BE5A87111A37A2@TYWP301MB0087.JPNP301.PROD.OUTLOOK.COM Signed-off-by: Mark Brown --- sound/soc/codecs/wcd934x.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/sound/soc/codecs/wcd934x.c b/sound/soc/codecs/wcd934x.c index f274b24c58a75e..b4bdabd739e06f 100644 --- a/sound/soc/codecs/wcd934x.c +++ b/sound/soc/codecs/wcd934x.c @@ -5625,6 +5625,28 @@ static const struct snd_soc_dapm_widget wcd934x_dapm_widgets[] = { }; static const struct snd_soc_dapm_route wcd934x_audio_map[] = { + /* + * The ADC/DMIC front ends cannot produce a single sample without the + * codec sysclk: MCLK also gates the analog bias generator and the + * decimator clocks (see __wcd934x_cdc_mclk_enable()). Upstream only + * ever wired MCLK into the graph from the board file, as + * "RX_BIAS" -> "MCLK", i.e. from the playback side. A board that can + * only record (or that plays through another amp, like polaris) then + * runs a capture stream with an unclocked codec and reads digital + * silence. Express the dependency where it belongs, on the capture + * front ends, so no board has to remember it. + */ + {"ADC1", NULL, "MCLK"}, + {"ADC2", NULL, "MCLK"}, + {"ADC3", NULL, "MCLK"}, + {"ADC4", NULL, "MCLK"}, + {"DMIC0", NULL, "MCLK"}, + {"DMIC1", NULL, "MCLK"}, + {"DMIC2", NULL, "MCLK"}, + {"DMIC3", NULL, "MCLK"}, + {"DMIC4", NULL, "MCLK"}, + {"DMIC5", NULL, "MCLK"}, + /* RX0-RX7 */ WCD934X_SLIM_RX_AIF_PATH(0), WCD934X_SLIM_RX_AIF_PATH(1), From 519d0ed450c9957899e2bb82ac5f2bd2cfc892e1 Mon Sep 17 00:00:00 2001 From: "doloers@hotmail.com" Date: Wed, 18 Nov 2026 08:09:36 +0800 Subject: [PATCH 1713/2102] ASoC: codecs: wcd934x: do not leak SLIM channel bits across ports wcd934x_slim_set_hw_params() builds one payload from the whole channel list: slim_ch_list: port 0 ch 128, port 3 ch 131 payload = BIT(0) | BIT(3) = 0x09 and then writes that same payload into *every* port's MULTI_CHNL register. So port 3 is programmed with 0x09 instead of 0x08 and enables slot 0 as well, while the SLIMbus channel allocation only gave it one channel - the codec then overruns that port's FIFO and logs wcd934x-codec ...: overflow error on TX port 3, value 5 on every capture stream (measured on polaris after the capture path was made to work). The playback direction has the same leak: every RX port gets the mask of all channels instead of its own. Compute the payload per port instead. Signed-off-by: Shen Xiaopeng Link: https://patch.msgid.link/TYWP301MB0087DFB6BDFBE4A427508BB2A37A2@TYWP301MB0087.JPNP301.PROD.OUTLOOK.COM Signed-off-by: Mark Brown --- sound/soc/codecs/wcd934x.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/sound/soc/codecs/wcd934x.c b/sound/soc/codecs/wcd934x.c index b4bdabd739e06f..99e198761a6c6b 100644 --- a/sound/soc/codecs/wcd934x.c +++ b/sound/soc/codecs/wcd934x.c @@ -1702,7 +1702,6 @@ static int wcd934x_slim_set_hw_params(struct wcd934x_codec *wcd, /* Configure slave interface device */ list_for_each_entry(ch, slim_ch_list, list) { cfg->ch_count++; - payload |= 1 << ch->shift; cfg->port_mask |= BIT(ch->port); } @@ -1712,6 +1711,14 @@ static int wcd934x_slim_set_hw_params(struct wcd934x_codec *wcd, i = 0; list_for_each_entry(ch, slim_ch_list, list) { + /* + * Each port carries its own channel mask. Accumulating the bits + * across the whole list and writing the sum into every port would + * enable the other channels on a port that only gets one of them + * allocated on the bus; the codec then overruns the port's TX FIFO + * ("overflow error on TX port N"). + */ + payload = BIT(ch->shift); cfg->chs[i++] = ch->ch_num; if (direction == SNDRV_PCM_STREAM_PLAYBACK) { /* write to interface device */ From 0262f255ad9e92f97408ffebe6809ac6a418c022 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Tue, 17 Nov 2026 11:21:01 +0700 Subject: [PATCH 1714/2102] ASoC: cirrus: ep93xx-i2s: Simplify platform_get_irq() error check platform_get_irq() is documented to return a non-zero IRQ number on success and a negative error number on failure. Drop the special handling of a zero return value and check only for irq < 0. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261117042102.12442-2-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/cirrus/ep93xx-i2s.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sound/soc/cirrus/ep93xx-i2s.c b/sound/soc/cirrus/ep93xx-i2s.c index 97816fb7536804..8dcfc6717e19f5 100644 --- a/sound/soc/cirrus/ep93xx-i2s.c +++ b/sound/soc/cirrus/ep93xx-i2s.c @@ -462,8 +462,8 @@ static int ep93xx_i2s_probe(struct platform_device *pdev) if (IS_ENABLED(CONFIG_SND_EP93XX_SOC_I2S_WATCHDOG)) { int irq = platform_get_irq(pdev, 0); - if (irq <= 0) - return irq < 0 ? irq : -ENODEV; + if (irq < 0) + return irq; err = devm_request_irq(&pdev->dev, irq, ep93xx_i2s_interrupt, 0, pdev->name, info); From 59852db7b40256f8974d8aebbeb00cc6a4615cf8 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Tue, 17 Nov 2026 11:21:02 +0700 Subject: [PATCH 1715/2102] ASoC: cirrus: ep93xx-i2s: Use devm_clk_get() Use devm_clk_get() to manage clock references automatically, simplifying the error path in probe() and allowing the remove() callback to be dropped. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261117042102.12442-3-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/cirrus/ep93xx-i2s.c | 47 ++++++++--------------------------- 1 file changed, 11 insertions(+), 36 deletions(-) diff --git a/sound/soc/cirrus/ep93xx-i2s.c b/sound/soc/cirrus/ep93xx-i2s.c index 8dcfc6717e19f5..f2d55763a02d36 100644 --- a/sound/soc/cirrus/ep93xx-i2s.c +++ b/sound/soc/cirrus/ep93xx-i2s.c @@ -471,54 +471,30 @@ static int ep93xx_i2s_probe(struct platform_device *pdev) return err; } - info->mclk = clk_get(&pdev->dev, "mclk"); - if (IS_ERR(info->mclk)) { - err = PTR_ERR(info->mclk); - goto fail; - } + info->mclk = devm_clk_get(&pdev->dev, "mclk"); + if (IS_ERR(info->mclk)) + return PTR_ERR(info->mclk); - info->sclk = clk_get(&pdev->dev, "sclk"); - if (IS_ERR(info->sclk)) { - err = PTR_ERR(info->sclk); - goto fail_put_mclk; - } + info->sclk = devm_clk_get(&pdev->dev, "sclk"); + if (IS_ERR(info->sclk)) + return PTR_ERR(info->sclk); - info->lrclk = clk_get(&pdev->dev, "lrclk"); - if (IS_ERR(info->lrclk)) { - err = PTR_ERR(info->lrclk); - goto fail_put_sclk; - } + info->lrclk = devm_clk_get(&pdev->dev, "lrclk"); + if (IS_ERR(info->lrclk)) + return PTR_ERR(info->lrclk); dev_set_drvdata(&pdev->dev, info); err = devm_snd_soc_register_component(&pdev->dev, &ep93xx_i2s_component, &ep93xx_i2s_dai, 1); if (err) - goto fail_put_lrclk; + return err; err = devm_ep93xx_pcm_platform_register(&pdev->dev); if (err) - goto fail_put_lrclk; + return err; return 0; - -fail_put_lrclk: - clk_put(info->lrclk); -fail_put_sclk: - clk_put(info->sclk); -fail_put_mclk: - clk_put(info->mclk); -fail: - return err; -} - -static void ep93xx_i2s_remove(struct platform_device *pdev) -{ - struct ep93xx_i2s_info *info = dev_get_drvdata(&pdev->dev); - - clk_put(info->lrclk); - clk_put(info->sclk); - clk_put(info->mclk); } static const struct of_device_id ep93xx_i2s_of_ids[] = { @@ -529,7 +505,6 @@ MODULE_DEVICE_TABLE(of, ep93xx_i2s_of_ids); static struct platform_driver ep93xx_i2s_driver = { .probe = ep93xx_i2s_probe, - .remove = ep93xx_i2s_remove, .driver = { .name = "ep93xx-i2s", .of_match_table = ep93xx_i2s_of_ids, From 8a2e765cec00e471a38d7700f1cd6ffee380b018 Mon Sep 17 00:00:00 2001 From: Dhanunjanrao Katta Date: Tue, 17 Nov 2026 14:27:37 +0530 Subject: [PATCH 1716/2102] ASoC: dt-bindings: xlnx,spdif: describe AXI4-Stream and audio clocks The SPDIF IP is fed by three clocks: the audio clock used at the SPDIF/AES3 interface, the AXI4-Lite control clock and the AXI4-Stream data clock. So far the binding described only two of them and carried the audio clock frequency in the custom "xlnx,aud_clk_i" property. Describe the AXI4-Stream clock and pick its name from the IP mode, s_axis_aclk for the transmitter and m_axis_aclk for the receiver. The minimum clock count stays at two, so that device trees written against the earlier binding keep validating and the third clock is effectively optional. Mark "xlnx,aud_clk_i" deprecated instead of removing it. The frequency it carries is available from the rate of the audio clock, but the property is part of the published binding and device trees in the field still pass it. As the binding sets "additionalProperties: false", removing the property outright would make those device trees fail validation. Make "xlnx,spdif-mode" required. The conditional that selects the AXI4-Stream clock name keys on that property, and a conditional with no "required" entry of its own also matches when the property is absent. A device tree omitting the mode would therefore have been held to the transmitter clock name by default. Requiring the property turns the omission into a clear validation failure instead. Signed-off-by: Dhanunjanrao Katta Link: https://patch.msgid.link/20261117085739.3807943-2-katta.dhanunjanrao@amd.com Signed-off-by: Mark Brown --- .../devicetree/bindings/sound/xlnx,spdif.yaml | 54 +++++++++++++++---- 1 file changed, 44 insertions(+), 10 deletions(-) diff --git a/Documentation/devicetree/bindings/sound/xlnx,spdif.yaml b/Documentation/devicetree/bindings/sound/xlnx,spdif.yaml index a45d8a0755fe6e..a4abca2027d39f 100644 --- a/Documentation/devicetree/bindings/sound/xlnx,spdif.yaml +++ b/Documentation/devicetree/bindings/sound/xlnx,spdif.yaml @@ -14,6 +14,28 @@ maintainers: allOf: - $ref: dai-common.yaml# + - if: + properties: + xlnx,spdif-mode: + const: 1 + required: + - xlnx,spdif-mode + then: + properties: + clock-names: + minItems: 2 + items: + - const: aud_clk_i + - const: s_axi_aclk + - const: s_axis_aclk + else: + properties: + clock-names: + minItems: 2 + items: + - const: aud_clk_i + - const: s_axi_aclk + - const: m_axis_aclk properties: compatible: @@ -28,15 +50,15 @@ properties: - description: SPDIF audio interrupt clock-names: - items: - - const: aud_clk_i - - const: s_axi_aclk + minItems: 2 + maxItems: 3 clocks: - minItems: 1 + minItems: 2 items: - - description: input audio clock - - description: clock for the AXI data stream + - description: Audio clock input used at the SPDIF/AES3 interface + - description: AXI4-Lite clock + - description: AXI4-Stream clock xlnx,spdif-mode: $ref: /schemas/types.yaml#/definitions/uint32 @@ -49,8 +71,10 @@ properties: xlnx,aud_clk_i: $ref: /schemas/types.yaml#/definitions/uint32 + deprecated: true description: - Input audio clock frequency. It affects the sampling rate. + Frequency of the audio clock input. Superseded by the rate of the + clock named aud_clk_i. required: - compatible @@ -58,6 +82,7 @@ required: - interrupts - clock-names - clocks + - xlnx,spdif-mode additionalProperties: false @@ -66,12 +91,21 @@ examples: spdif@80010000 { compatible = "xlnx,spdif-2.0"; reg = <0x80010000 0x10000>; - clock-names = "aud_clk_i", "s_axi_aclk"; - clocks = <&misc_clk_0>, <&clk 71>; + clock-names = "aud_clk_i", "s_axi_aclk", "s_axis_aclk"; + clocks = <&misc_clk_0>, <&clk 71>, <&misc_clk_0>; interrupt-parent = <&gic>; interrupts = <0 91 4>; xlnx,spdif-mode = <1>; - xlnx,aud_clk_i = <49152913>; + }; + - | + spdif@80090000 { + compatible = "xlnx,spdif-2.0"; + reg = <0x80090000 0x10000>; + clock-names = "aud_clk_i", "s_axi_aclk", "m_axis_aclk"; + clocks = <&misc_clk_0>, <&clk 71>, <&clk 71>; + interrupt-parent = <&gic>; + interrupts = <0 90 4>; + xlnx,spdif-mode = <0>; }; ... From 8090aeadf3a0f24bb9e132caef472399ffc5a6ae Mon Sep 17 00:00:00 2001 From: Dhanunjanrao Katta Date: Tue, 17 Nov 2026 14:27:38 +0530 Subject: [PATCH 1717/2102] ASoC: xlnx: spdif: namespace register macros and use a divider enum The field defines were not named after the registers they belong to and were listed apart from them, three driver constants carried no prefix at all, and the clock-divider configuration values were written as bare numbers at the assignment sites. Name each field define after its register and group the field defines under it, prefix the remaining driver constants with "XSPDIF_", and replace the bare clock-divider values with the "xspdif_clk_div" enum, giving clk_cfg that type. The channel-status interrupt mask is written to both the status and the enable register, so it is named for the field rather than for one of the two registers. Signed-off-by: Dhanunjanrao Katta Link: https://patch.msgid.link/20261117085739.3807943-3-katta.dhanunjanrao@amd.com Signed-off-by: Mark Brown --- sound/soc/xilinx/xlnx_spdif.c | 81 ++++++++++++++++++++--------------- 1 file changed, 46 insertions(+), 35 deletions(-) diff --git a/sound/soc/xilinx/xlnx_spdif.c b/sound/soc/xilinx/xlnx_spdif.c index 9fdafd45c38125..a9d1fe9cc6107c 100644 --- a/sound/soc/xilinx/xlnx_spdif.c +++ b/sound/soc/xilinx/xlnx_spdif.c @@ -22,25 +22,34 @@ #define XLNX_SPDIF_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_LE) +#define XSPDIF_GLOBAL_IRQ_REG 0x1C +#define XSPDIF_GLOBAL_IRQ_ENABLE_MASK BIT(31) #define XSPDIF_IRQ_STS_REG 0x20 +#define XSPDIF_IRQ_CH_STS_MASK BIT(5) #define XSPDIF_IRQ_ENABLE_REG 0x28 #define XSPDIF_SOFT_RESET_REG 0x40 +#define XSPDIF_SOFT_RESET_VAL 0xA #define XSPDIF_CONTROL_REG 0x44 +#define XSPDIF_CONTROL_ENABLE_MASK BIT(0) +#define XSPDIF_CONTROL_FIFO_FLUSH_MASK BIT(1) +#define XSPDIF_CONTROL_CLK_CFG_MASK GENMASK(5, 2) +#define XSPDIF_CONTROL_CLK_CFG_SHIFT 2 #define XSPDIF_CHAN_0_STS_REG 0x4C -#define XSPDIF_GLOBAL_IRQ_ENABLE_REG 0x1C #define XSPDIF_CH_A_USER_DATA_REG_0 0x64 -#define XSPDIF_CORE_ENABLE_MASK BIT(0) -#define XSPDIF_FIFO_FLUSH_MASK BIT(1) -#define XSPDIF_CH_STS_MASK BIT(5) -#define XSPDIF_GLOBAL_IRQ_ENABLE BIT(31) -#define XSPDIF_CLOCK_CONFIG_BITS_MASK GENMASK(5, 2) -#define XSPDIF_CLOCK_CONFIG_BITS_SHIFT 2 -#define XSPDIF_SOFT_RESET_VALUE 0xA - -#define MAX_CHANNELS 2 -#define AES_SAMPLE_WIDTH 32 -#define CH_STATUS_UPDATE_TIMEOUT 40 +#define XSPDIF_MAX_CHANNELS 2 +#define XSPDIF_AES_SAMPLE_WIDTH 32 +#define XSPDIF_CH_STS_UPDATE_TIMEOUT 40 + +enum xspdif_clk_div { + XSPDIF_CLK_DIV_BY_4, + XSPDIF_CLK_DIV_BY_8, + XSPDIF_CLK_DIV_BY_16, + XSPDIF_CLK_DIV_BY_24, + XSPDIF_CLK_DIV_BY_32, + XSPDIF_CLK_DIV_BY_48, + XSPDIF_CLK_DIV_BY_64, +}; struct spdif_dev_data { u32 mode; @@ -57,12 +66,12 @@ static irqreturn_t xlnx_spdifrx_irq_handler(int irq, void *arg) struct spdif_dev_data *ctx = arg; val = readl(ctx->base + XSPDIF_IRQ_STS_REG); - if (val & XSPDIF_CH_STS_MASK) { - writel(val & XSPDIF_CH_STS_MASK, + if (val & XSPDIF_IRQ_CH_STS_MASK) { + writel(val & XSPDIF_IRQ_CH_STS_MASK, ctx->base + XSPDIF_IRQ_STS_REG); val = readl(ctx->base + XSPDIF_IRQ_ENABLE_REG); - writel(val & ~XSPDIF_CH_STS_MASK, + writel(val & ~XSPDIF_IRQ_CH_STS_MASK, ctx->base + XSPDIF_IRQ_ENABLE_REG); ctx->rx_chsts_updated = true; @@ -80,14 +89,14 @@ static int xlnx_spdif_startup(struct snd_pcm_substream *substream, struct spdif_dev_data *ctx = dev_get_drvdata(dai->dev); val = readl(ctx->base + XSPDIF_CONTROL_REG); - val |= XSPDIF_FIFO_FLUSH_MASK; + val |= XSPDIF_CONTROL_FIFO_FLUSH_MASK; writel(val, ctx->base + XSPDIF_CONTROL_REG); if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { - writel(XSPDIF_CH_STS_MASK, + writel(XSPDIF_IRQ_CH_STS_MASK, ctx->base + XSPDIF_IRQ_ENABLE_REG); - writel(XSPDIF_GLOBAL_IRQ_ENABLE, - ctx->base + XSPDIF_GLOBAL_IRQ_ENABLE_REG); + writel(XSPDIF_GLOBAL_IRQ_ENABLE_MASK, + ctx->base + XSPDIF_GLOBAL_IRQ_REG); } return 0; @@ -98,48 +107,50 @@ static void xlnx_spdif_shutdown(struct snd_pcm_substream *substream, { struct spdif_dev_data *ctx = dev_get_drvdata(dai->dev); - writel(XSPDIF_SOFT_RESET_VALUE, ctx->base + XSPDIF_SOFT_RESET_REG); + writel(XSPDIF_SOFT_RESET_VAL, ctx->base + XSPDIF_SOFT_RESET_REG); } static int xlnx_spdif_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { - u32 val, clk_div, clk_cfg; + enum xspdif_clk_div clk_cfg; + u32 val, clk_div; struct spdif_dev_data *ctx = dev_get_drvdata(dai->dev); - clk_div = DIV_ROUND_CLOSEST(ctx->aclk, MAX_CHANNELS * AES_SAMPLE_WIDTH * + clk_div = DIV_ROUND_CLOSEST(ctx->aclk, XSPDIF_MAX_CHANNELS * + XSPDIF_AES_SAMPLE_WIDTH * params_rate(params)); switch (clk_div) { case 4: - clk_cfg = 0; + clk_cfg = XSPDIF_CLK_DIV_BY_4; break; case 8: - clk_cfg = 1; + clk_cfg = XSPDIF_CLK_DIV_BY_8; break; case 16: - clk_cfg = 2; + clk_cfg = XSPDIF_CLK_DIV_BY_16; break; case 24: - clk_cfg = 3; + clk_cfg = XSPDIF_CLK_DIV_BY_24; break; case 32: - clk_cfg = 4; + clk_cfg = XSPDIF_CLK_DIV_BY_32; break; case 48: - clk_cfg = 5; + clk_cfg = XSPDIF_CLK_DIV_BY_48; break; case 64: - clk_cfg = 6; + clk_cfg = XSPDIF_CLK_DIV_BY_64; break; default: return -EINVAL; } val = readl(ctx->base + XSPDIF_CONTROL_REG); - val &= ~XSPDIF_CLOCK_CONFIG_BITS_MASK; - val |= clk_cfg << XSPDIF_CLOCK_CONFIG_BITS_SHIFT; + val &= ~XSPDIF_CONTROL_CLK_CFG_MASK; + val |= clk_cfg << XSPDIF_CONTROL_CLK_CFG_SHIFT; writel(val, ctx->base + XSPDIF_CONTROL_REG); return 0; @@ -149,7 +160,7 @@ static int rx_stream_detect(struct snd_soc_dai *dai) { int err; struct spdif_dev_data *ctx = dev_get_drvdata(dai->dev); - unsigned long jiffies = msecs_to_jiffies(CH_STATUS_UPDATE_TIMEOUT); + unsigned long jiffies = msecs_to_jiffies(XSPDIF_CH_STS_UPDATE_TIMEOUT); /* start capture only if stream is detected within 40ms timeout */ err = wait_event_interruptible_timeout(ctx->chsts_q, @@ -176,7 +187,7 @@ static int xlnx_spdif_trigger(struct snd_pcm_substream *substream, int cmd, case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: - val |= XSPDIF_CORE_ENABLE_MASK; + val |= XSPDIF_CONTROL_ENABLE_MASK; writel(val, ctx->base + XSPDIF_CONTROL_REG); if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) ret = rx_stream_detect(dai); @@ -184,7 +195,7 @@ static int xlnx_spdif_trigger(struct snd_pcm_substream *substream, int cmd, case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: - val &= ~XSPDIF_CORE_ENABLE_MASK; + val &= ~XSPDIF_CONTROL_ENABLE_MASK; writel(val, ctx->base + XSPDIF_CONTROL_REG); break; default: @@ -287,7 +298,7 @@ static int xlnx_spdif_probe(struct platform_device *pdev) if (ret) return ret; - writel(XSPDIF_SOFT_RESET_VALUE, ctx->base + XSPDIF_SOFT_RESET_REG); + writel(XSPDIF_SOFT_RESET_VAL, ctx->base + XSPDIF_SOFT_RESET_REG); dev_info(dev, "%s DAI registered\n", dai_drv->name); return 0; From 91c90b881e551de203365906149171a97f620a6e Mon Sep 17 00:00:00 2001 From: Dhanunjanrao Katta Date: Tue, 17 Nov 2026 14:27:39 +0530 Subject: [PATCH 1718/2102] ASoC: xlnx: spdif: get clocks through the common clock framework The driver requested only the AXI4-Lite clock and relied on the firmware to leave the AXI4-Stream and audio clocks enabled, and it took the audio clock rate from the "xlnx,aud_clk_i" device-tree property. Request and enable the audio clock, and the AXI4-Stream clock matching the IP mode, through the common clock framework. The AXI4-Stream clock is requested with devm_clk_get_optional_enabled() because device trees written against the earlier binding describe only two clocks. Read the audio rate with clk_get_rate() in hw_params so that the SPDIF clock divider follows the rate actually in effect, and reject a zero rate with a diagnostic rather than letting it reach the divider switch and return a bare -EINVAL. "xlnx,aud_clk_i" is no longer read and is marked deprecated in the binding. Signed-off-by: Dhanunjanrao Katta Link: https://patch.msgid.link/20261117085739.3807943-4-katta.dhanunjanrao@amd.com Signed-off-by: Mark Brown --- sound/soc/xilinx/xlnx_spdif.c | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/sound/soc/xilinx/xlnx_spdif.c b/sound/soc/xilinx/xlnx_spdif.c index a9d1fe9cc6107c..b233ab1a92dcea 100644 --- a/sound/soc/xilinx/xlnx_spdif.c +++ b/sound/soc/xilinx/xlnx_spdif.c @@ -53,10 +53,11 @@ enum xspdif_clk_div { struct spdif_dev_data { u32 mode; - u32 aclk; bool rx_chsts_updated; void __iomem *base; struct clk *axi_clk; + struct clk *axis_clk; + struct clk *aud_clk; wait_queue_head_t chsts_q; }; @@ -117,8 +118,15 @@ static int xlnx_spdif_hw_params(struct snd_pcm_substream *substream, enum xspdif_clk_div clk_cfg; u32 val, clk_div; struct spdif_dev_data *ctx = dev_get_drvdata(dai->dev); + unsigned long rate; - clk_div = DIV_ROUND_CLOSEST(ctx->aclk, XSPDIF_MAX_CHANNELS * + rate = clk_get_rate(ctx->aud_clk); + if (!rate) { + dev_err(dai->dev, "aud_clk_i rate is not available\n"); + return -EINVAL; + } + + clk_div = DIV_ROUND_CLOSEST(rate, XSPDIF_MAX_CHANNELS * XSPDIF_AES_SAMPLE_WIDTH * params_rate(params)); @@ -271,8 +279,18 @@ static int xlnx_spdif_probe(struct platform_device *pdev) return dev_err_probe(dev, ret, "cannot get SPDIF mode\n"); if (ctx->mode) { + ctx->axis_clk = devm_clk_get_optional_enabled(dev, "s_axis_aclk"); + if (IS_ERR(ctx->axis_clk)) + return dev_err_probe(dev, PTR_ERR(ctx->axis_clk), + "failed to get s_axis_aclk\n"); + dai_drv = &xlnx_spdif_tx_dai; } else { + ctx->axis_clk = devm_clk_get_optional_enabled(dev, "m_axis_aclk"); + if (IS_ERR(ctx->axis_clk)) + return dev_err_probe(dev, PTR_ERR(ctx->axis_clk), + "failed to get m_axis_aclk\n"); + ret = platform_get_irq(pdev, 0); if (ret < 0) return ret; @@ -287,9 +305,10 @@ static int xlnx_spdif_probe(struct platform_device *pdev) dai_drv = &xlnx_spdif_rx_dai; } - ret = device_property_read_u32(dev, "xlnx,aud_clk_i", &ctx->aclk); - if (ret < 0) - return dev_err_probe(dev, ret, "cannot get aud_clk_i value\n"); + ctx->aud_clk = devm_clk_get_enabled(dev, "aud_clk_i"); + if (IS_ERR(ctx->aud_clk)) + return dev_err_probe(dev, PTR_ERR(ctx->aud_clk), + "failed to get aud_clk_i\n"); dev_set_drvdata(dev, ctx); From caa42517c9d7c63090e8422a0f2849a92025f018 Mon Sep 17 00:00:00 2001 From: Manuel Ebner Date: Sun, 22 Nov 2026 10:06:40 +0100 Subject: [PATCH 1719/2102] ASoC: doc: Fix bracket Add missng '};'. Signed-off-by: Manuel Ebner Acked-by: Randy Dunlap Link: https://patch.msgid.link/20261122090640.1475222-2-manuelebnerli@mailbox.org Signed-off-by: Mark Brown --- Documentation/sound/soc/dpcm.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/sound/soc/dpcm.rst b/Documentation/sound/soc/dpcm.rst index 7b6aeab3c207a9..3b145e8ba15c8b 100644 --- a/Documentation/sound/soc/dpcm.rst +++ b/Documentation/sound/soc/dpcm.rst @@ -370,6 +370,7 @@ The machine driver sets some additional parameters to the DAI link i.e. .num_c2c_params = 1, } < ... more DAI links here ... > + }; These parameters are used to configure the DAI hw_params() when DAPM detects a valid path and then calls the PCM operations to start the link. DAPM will also From ebdd2afe9fb1e293d3625b6fc52d3fc7fe805985 Mon Sep 17 00:00:00 2001 From: Peng Fan Date: Sat, 21 Nov 2026 20:44:19 +0800 Subject: [PATCH 1720/2102] regmap: drop regmap_bus::free_on_exit The SPI and I2C bus helpers kmemdup the static regmap_bus to override max_raw_read and max_raw_write per device and mark the copy with free_on_exit so that the regmap core frees it. This is the only user of free_on_exit, and the per-device limits can instead be applied to the map while it is being initialized. Add an optional regmap_bus::init_limits() callback which is invoked by __regmap_init() after the bus raw I/O limits have been copied and before the cache is initialized. The latter matters for maps with raw register defaults: regcache_hw_init() reads them from the device while the map is still being initialized and uses max_raw_read to chunk the transfer. The callback takes the bus context, the config and pointers to the raw I/O limits. struct regmap is private to drivers/base/regmap, so passing it would make the callback unusable for bus implementations outside the regmap core. Use the callback for the I2C and SPI buses, which allows using the static bus structures directly. This removes the per-device bus allocations and lets us drop free_on_exit along with the associated error and exit paths in the regmap core. No functional changes. Signed-off-by: Peng Fan Link: https://patch.msgid.link/20261121-regmap-improve-2nd-v1-1-6b5fd59451ed@nxp.com Signed-off-by: Mark Brown --- drivers/base/regmap/regmap-i2c.c | 85 +++++++++++++++++--------------- drivers/base/regmap/regmap-spi.c | 66 ++++++++++--------------- drivers/base/regmap/regmap.c | 8 +-- include/linux/regmap.h | 10 +++- 4 files changed, 83 insertions(+), 86 deletions(-) diff --git a/drivers/base/regmap/regmap-i2c.c b/drivers/base/regmap/regmap-i2c.c index a4a259232980d1..7635eca2cbee84 100644 --- a/drivers/base/regmap/regmap-i2c.c +++ b/drivers/base/regmap/regmap-i2c.c @@ -13,6 +13,43 @@ #include "internal.h" +static void regmap_i2c_init_limits(void *context, + const struct regmap_config *config, + size_t *max_raw_read, + size_t *max_raw_write) +{ + struct device *dev = context; + struct i2c_client *i2c = to_i2c_client(dev); + const struct i2c_adapter_quirks *quirks = i2c->adapter->quirks; + size_t val_bytes = BITS_TO_BYTES(config->val_bits); + size_t max_read = *max_raw_read; + size_t max_write = *max_raw_write; + + if (!quirks) + return; + + if (quirks->max_read_len && + quirks->max_read_len >= val_bytes && + (max_read == 0 || max_read > quirks->max_read_len)) + max_read = quirks->max_read_len; + + if (quirks->max_write_len) { + size_t reg_reserve_size, max_payload; + + reg_reserve_size = (config->reg_bits + config->pad_bits) / + BITS_PER_BYTE; + if (quirks->max_write_len > reg_reserve_size) { + max_payload = quirks->max_write_len - reg_reserve_size; + if (max_payload >= val_bytes && + (max_write == 0 || max_write > max_payload)) + max_write = max_payload; + } + } + + *max_raw_read = max_read; + *max_raw_write = max_write; +} + static int regmap_smbus_byte_reg_read(void *context, unsigned int reg, unsigned int *val) { @@ -47,6 +84,7 @@ static int regmap_smbus_byte_reg_write(void *context, unsigned int reg, static const struct regmap_bus regmap_smbus_byte = { .reg_write = regmap_smbus_byte_reg_write, .reg_read = regmap_smbus_byte_reg_read, + .init_limits = regmap_i2c_init_limits, }; static int regmap_smbus_word_reg_read(void *context, unsigned int reg, @@ -83,6 +121,7 @@ static int regmap_smbus_word_reg_write(void *context, unsigned int reg, static const struct regmap_bus regmap_smbus_word = { .reg_write = regmap_smbus_word_reg_write, .reg_read = regmap_smbus_word_reg_read, + .init_limits = regmap_i2c_init_limits, }; static int regmap_smbus_word_read_swapped(void *context, unsigned int reg, @@ -119,6 +158,7 @@ static int regmap_smbus_word_write_swapped(void *context, unsigned int reg, static const struct regmap_bus regmap_smbus_word_swapped = { .reg_write = regmap_smbus_word_write_swapped, .reg_read = regmap_smbus_word_read_swapped, + .init_limits = regmap_i2c_init_limits, }; static int regmap_i2c_write(void *context, const void *data, size_t count) @@ -204,6 +244,7 @@ static const struct regmap_bus regmap_i2c = { .read = regmap_i2c_read, .reg_format_endian_default = REGMAP_ENDIAN_BIG, .val_format_endian_default = REGMAP_ENDIAN_BIG, + .init_limits = regmap_i2c_init_limits, }; static int regmap_i2c_smbus_i2c_write(void *context, const void *data, @@ -245,6 +286,7 @@ static const struct regmap_bus regmap_i2c_smbus_i2c_block = { .read = regmap_i2c_smbus_i2c_read, .max_raw_read = I2C_SMBUS_BLOCK_MAX - 1, .max_raw_write = I2C_SMBUS_BLOCK_MAX - 1, + .init_limits = regmap_i2c_init_limits, }; static int regmap_i2c_smbus_i2c_write_reg16(void *context, const void *data, @@ -302,6 +344,7 @@ static const struct regmap_bus regmap_i2c_smbus_i2c_block_reg16 = { .read = regmap_i2c_smbus_i2c_read_reg16, .max_raw_read = I2C_SMBUS_BLOCK_MAX - 2, .max_raw_write = I2C_SMBUS_BLOCK_MAX - 2, + .init_limits = regmap_i2c_init_limits, }; /* @@ -346,16 +389,13 @@ static const struct regmap_bus regmap_smbus_byte_word_reg16 = { .read = regmap_i2c_smbus_i2c_read_reg16, .max_raw_read = I2C_SMBUS_BLOCK_MAX - 2, .max_raw_write = 1, + .init_limits = regmap_i2c_init_limits, }; static const struct regmap_bus *regmap_get_i2c_bus(struct i2c_client *i2c, const struct regmap_config *config) { - const struct i2c_adapter_quirks *quirks; const struct regmap_bus *bus = NULL; - struct regmap_bus *ret_bus; - size_t val_bytes; - u16 max_read, max_write; if (i2c_check_functionality(i2c->adapter, I2C_FUNC_I2C)) bus = ®map_i2c; @@ -393,43 +433,6 @@ static const struct regmap_bus *regmap_get_i2c_bus(struct i2c_client *i2c, if (!bus) return ERR_PTR(-ENOTSUPP); - max_read = bus->max_raw_read; - max_write = bus->max_raw_write; - val_bytes = BITS_TO_BYTES(config->val_bits); - - quirks = i2c->adapter->quirks; - if (quirks) { - if (quirks->max_read_len && - quirks->max_read_len >= val_bytes && - (max_read == 0 || max_read > quirks->max_read_len)) - max_read = quirks->max_read_len; - - if (quirks->max_write_len) { - size_t reg_reserve_size, max_payload; - - reg_reserve_size = (config->reg_bits + config->pad_bits) / - BITS_PER_BYTE; - if (quirks->max_write_len > reg_reserve_size) { - max_payload = quirks->max_write_len - - reg_reserve_size; - if (max_payload >= val_bytes && - (max_write == 0 || max_write > max_payload)) - max_write = max_payload; - } - } - - if (max_read != bus->max_raw_read || - max_write != bus->max_raw_write) { - ret_bus = kmemdup(bus, sizeof(*bus), GFP_KERNEL); - if (!ret_bus) - return ERR_PTR(-ENOMEM); - ret_bus->free_on_exit = true; - ret_bus->max_raw_read = max_read; - ret_bus->max_raw_write = max_write; - bus = ret_bus; - } - } - return bus; } diff --git a/drivers/base/regmap/regmap-spi.c b/drivers/base/regmap/regmap-spi.c index b9fec387997ebe..e095e0bba10de1 100644 --- a/drivers/base/regmap/regmap-spi.c +++ b/drivers/base/regmap/regmap-spi.c @@ -98,6 +98,28 @@ static int regmap_spi_read(void *context, return spi_write_then_read(spi, reg, reg_size, val, val_size); } +static void regmap_spi_init_limits(void *context, + const struct regmap_config *config, + size_t *max_raw_read, + size_t *max_raw_write) +{ + struct device *dev = context; + struct spi_device *spi = to_spi_device(dev); + size_t max_size = spi_max_transfer_size(spi); + size_t max_msg_size, reg_reserve_size; + + if (max_size == SIZE_MAX) + return; + + max_msg_size = spi_max_message_size(spi); + reg_reserve_size = (config->reg_bits + config->pad_bits) / BITS_PER_BYTE; + if (max_size + reg_reserve_size > max_msg_size) + max_size -= reg_reserve_size; + + *max_raw_read = max_size; + *max_raw_write = max_size; +} + static const struct regmap_bus regmap_spi = { .write = regmap_spi_write, .gather_write = regmap_spi_gather_write, @@ -107,46 +129,16 @@ static const struct regmap_bus regmap_spi = { .read_flag_mask = 0x80, .reg_format_endian_default = REGMAP_ENDIAN_BIG, .val_format_endian_default = REGMAP_ENDIAN_BIG, + .init_limits = regmap_spi_init_limits, }; -static const struct regmap_bus *regmap_get_spi_bus(struct spi_device *spi, - const struct regmap_config *config) -{ - size_t max_size = spi_max_transfer_size(spi); - size_t max_msg_size, reg_reserve_size; - struct regmap_bus *bus; - - if (max_size != SIZE_MAX) { - bus = kmemdup(®map_spi, sizeof(*bus), GFP_KERNEL); - if (!bus) - return ERR_PTR(-ENOMEM); - - max_msg_size = spi_max_message_size(spi); - reg_reserve_size = (config->reg_bits + config->pad_bits) / BITS_PER_BYTE; - if (max_size + reg_reserve_size > max_msg_size) - max_size -= reg_reserve_size; - - bus->free_on_exit = true; - bus->max_raw_read = max_size; - bus->max_raw_write = max_size; - - return bus; - } - - return ®map_spi; -} - struct regmap *__regmap_init_spi(struct spi_device *spi, const struct regmap_config *config, struct lock_class_key *lock_key, const char *lock_name) { - const struct regmap_bus *bus = regmap_get_spi_bus(spi, config); - - if (IS_ERR(bus)) - return ERR_CAST(bus); - - return __regmap_init(&spi->dev, bus, &spi->dev, config, lock_key, lock_name); + return __regmap_init(&spi->dev, ®map_spi, &spi->dev, config, + lock_key, lock_name); } EXPORT_SYMBOL_GPL(__regmap_init_spi); @@ -155,12 +147,8 @@ struct regmap *__devm_regmap_init_spi(struct spi_device *spi, struct lock_class_key *lock_key, const char *lock_name) { - const struct regmap_bus *bus = regmap_get_spi_bus(spi, config); - - if (IS_ERR(bus)) - return ERR_CAST(bus); - - return __devm_regmap_init(&spi->dev, bus, &spi->dev, config, lock_key, lock_name); + return __devm_regmap_init(&spi->dev, ®map_spi, &spi->dev, config, + lock_key, lock_name); } EXPORT_SYMBOL_GPL(__devm_regmap_init_spi); diff --git a/drivers/base/regmap/regmap.c b/drivers/base/regmap/regmap.c index 45b5b4f76b0c1f..66175820704f64 100644 --- a/drivers/base/regmap/regmap.c +++ b/drivers/base/regmap/regmap.c @@ -1180,6 +1180,10 @@ struct regmap *__regmap_init(struct device *dev, if (ret) goto err_range; + if (bus && bus->init_limits) + bus->init_limits(bus_context, config, + &map->max_raw_read, &map->max_raw_write); + ret = regcache_init(map, config); if (ret != 0) goto err_range; @@ -1207,8 +1211,6 @@ struct regmap *__regmap_init(struct device *dev, err_map: kfree(map); err: - if (bus && bus->free_on_exit) - kfree(bus); return ERR_PTR(ret); } EXPORT_SYMBOL_GPL(__regmap_init); @@ -1522,8 +1524,6 @@ void regmap_exit(struct regmap *map) mutex_destroy(&map->mutex); kfree_const(map->name); kfree(map->patch); - if (map->bus && map->bus->free_on_exit) - kfree(map->bus); kfree(map); } EXPORT_SYMBOL_GPL(regmap_exit); diff --git a/include/linux/regmap.h b/include/linux/regmap.h index 5c2c95cac9578d..6194948ff9ed89 100644 --- a/include/linux/regmap.h +++ b/include/linux/regmap.h @@ -581,7 +581,6 @@ typedef void (*regmap_hw_free_context)(void *context); * to perform locking. This field is ignored if custom lock/unlock * functions are used (see fields lock/unlock of * struct regmap_config). - * @free_on_exit: kfree this on exit of regmap * @write: Write operation. * @gather_write: Write operation with split register/value, return -ENOTSUPP * if not implemented on a given device. @@ -612,10 +611,13 @@ typedef void (*regmap_hw_free_context)(void *context); * DEFAULT, BIG is assumed. * @max_raw_read: Max raw read size that can be used on the bus. * @max_raw_write: Max raw write size that can be used on the bus. + * @init_limits: Optional callback to adjust the maximum raw read and write + * sizes for a device. Called with the bus context, the config and + * pointers to the limits during regmap initialization before the cache + * is initialized. */ struct regmap_bus { bool fast_io; - bool free_on_exit; regmap_hw_write write; regmap_hw_gather_write gather_write; regmap_hw_async_write async_write; @@ -632,6 +634,10 @@ struct regmap_bus { enum regmap_endian val_format_endian_default; size_t max_raw_read; size_t max_raw_write; + void (*init_limits)(void *context, + const struct regmap_config *config, + size_t *max_raw_read, + size_t *max_raw_write); }; /* From bc6647f5e8cf1f12006bc4c68c1eb88a45a2da24 Mon Sep 17 00:00:00 2001 From: Peng Fan Date: Sat, 21 Nov 2026 20:44:20 +0800 Subject: [PATCH 1721/2102] regmap: use cleanup API in __regmap_init() Convert the error unwinding in __regmap_init() to the scope-based cleanup API and drop all of the err_* labels. A dedicated regmap_init_release() helper unwinds a partially initialised map in the same order as the old labels. The err label only returned ERR_PTR(ret) after the per-device bus allocation was removed, so the two early failure paths now return directly as well. regcache_exit() requires an initialised cache, so map->cache_type is now set right before regcache_init() instead of during the initial map setup and reset to REGCACHE_NONE if regcache_init() fails. This makes regcache_exit() safe to call from the cleanup path at any point. Nothing between the old and new assignment reads cache_type. No functional change. Signed-off-by: Peng Fan Link: https://patch.msgid.link/20261121-regmap-improve-2nd-v1-2-6b5fd59451ed@nxp.com Signed-off-by: Mark Brown --- drivers/base/regmap/regmap.c | 69 +++++++++++++++++------------------- 1 file changed, 33 insertions(+), 36 deletions(-) diff --git a/drivers/base/regmap/regmap.c b/drivers/base/regmap/regmap.c index 66175820704f64..fc002960018486 100644 --- a/drivers/base/regmap/regmap.c +++ b/drivers/base/regmap/regmap.c @@ -1037,6 +1037,22 @@ static int regmap_init_format(struct regmap *map, return 0; } +static void regmap_init_release(struct regmap *map) +{ + if (!map) + return; + + regcache_exit(map); + regmap_range_exit(map); + kfree(map->work_buf); + if (map->hwlock) + hwspin_lock_free(map->hwlock); + kfree_const(map->name); + kfree(map); +} + +DEFINE_FREE(regmap_init_release, struct regmap *, regmap_init_release(_T)); + struct regmap *__regmap_init(struct device *dev, const struct regmap_bus *bus, void *bus_context, @@ -1044,30 +1060,25 @@ struct regmap *__regmap_init(struct device *dev, struct lock_class_key *lock_key, const char *lock_name) { - struct regmap *map; bool fast_io; int ret; - if (!config) { - ret = -EINVAL; - goto err; - } + if (!config) + return ERR_PTR(-EINVAL); - map = kzalloc_obj(*map); - if (map == NULL) { - ret = -ENOMEM; - goto err; - } + struct regmap *map __free(regmap_init_release) = kzalloc_obj(*map); + if (map == NULL) + return ERR_PTR(-ENOMEM); ret = regmap_set_name(map, config); if (ret) - goto err_map; + return ERR_PTR(ret); fast_io = (bus && bus->fast_io) || config->fast_io; ret = regmap_set_lock(map, config, fast_io, lock_key, lock_name); if (ret) - goto err_name; + return ERR_PTR(ret); /* * When we write in fast-paths with regmap_bulk_write() don't allocate @@ -1119,7 +1130,6 @@ struct regmap *__regmap_init(struct device *dev, map->writeable_noinc_reg = config->writeable_noinc_reg; map->readable_noinc_reg = config->readable_noinc_reg; map->reg_default_cb = config->reg_default_cb; - map->cache_type = config->cache_type; spin_lock_init(&map->async_lock); INIT_LIST_HEAD(&map->async_list); @@ -1148,7 +1158,7 @@ struct regmap *__regmap_init(struct device *dev, REGMAP_ENDIAN_NATIVE, REGMAP_ENDIAN_NATIVE); if (ret) - goto err_hwlock; + return ERR_PTR(ret); } else if (!bus) { map->reg_read = config->reg_read; map->reg_write = config->reg_write; @@ -1172,46 +1182,33 @@ struct regmap *__regmap_init(struct device *dev, regmap_get_reg_endian(bus, config), regmap_get_val_endian(dev, bus, config)); if (ret) - goto err_hwlock; + return ERR_PTR(ret); } - ret = regmap_init_ranges(map, config); if (ret) - goto err_range; + return ERR_PTR(ret); if (bus && bus->init_limits) bus->init_limits(bus_context, config, &map->max_raw_read, &map->max_raw_write); + map->cache_type = config->cache_type; ret = regcache_init(map, config); - if (ret != 0) - goto err_range; + if (ret) { + map->cache_type = REGCACHE_NONE; + return ERR_PTR(ret); + } if (dev) { ret = regmap_attach_dev(dev, map, config); if (ret != 0) - goto err_regcache; + return ERR_PTR(ret); } else { regmap_debugfs_init(map); } - return map; - -err_regcache: - regcache_exit(map); -err_range: - regmap_range_exit(map); - kfree(map->work_buf); -err_hwlock: - if (map->hwlock) - hwspin_lock_free(map->hwlock); -err_name: - kfree_const(map->name); -err_map: - kfree(map); -err: - return ERR_PTR(ret); + return_ptr(map); } EXPORT_SYMBOL_GPL(__regmap_init); From 68bdabf0eed1f79ab61b623f2c135c6ee361ac99 Mon Sep 17 00:00:00 2001 From: Peng Fan Date: Sat, 21 Nov 2026 20:44:21 +0800 Subject: [PATCH 1722/2102] regmap: kunit: add test for regmap_bus::init_limits Add coverage for the optional regmap_bus::init_limits() callback. The test bus lowers the raw I/O limits and relies on raw register defaults so that regcache_hw_init() reads from the device during map initialization. The readback must be split according to the limits set by the callback, which also verifies that __regmap_init() invokes the callback before regcache_init(). Signed-off-by: Peng Fan Link: https://patch.msgid.link/20261121-regmap-improve-2nd-v1-3-6b5fd59451ed@nxp.com Signed-off-by: Mark Brown --- drivers/base/regmap/regmap-kunit.c | 91 ++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/drivers/base/regmap/regmap-kunit.c b/drivers/base/regmap/regmap-kunit.c index c948219f46a39d..75c251132c89c8 100644 --- a/drivers/base/regmap/regmap-kunit.c +++ b/drivers/base/regmap/regmap-kunit.c @@ -2247,6 +2247,96 @@ static void raw_ranges(struct kunit *test) } } +#define TEST_INIT_LIMITS_REGS 16 +#define TEST_INIT_LIMITS_MAX_RAW 4 + +struct test_init_limits_data { + int num_reads; + size_t read_sizes[TEST_INIT_LIMITS_REGS]; +}; + +static void test_init_limits_bus_init_limits(void *context, + const struct regmap_config *config, + size_t *max_raw_read, + size_t *max_raw_write) +{ + *max_raw_read = TEST_INIT_LIMITS_MAX_RAW; + *max_raw_write = TEST_INIT_LIMITS_MAX_RAW; +} + +static int test_init_limits_bus_read(void *context, const void *reg_buf, + size_t reg_size, void *val_buf, + size_t val_size) +{ + struct test_init_limits_data *data = context; + + if (data->num_reads < ARRAY_SIZE(data->read_sizes)) + data->read_sizes[data->num_reads] = val_size; + data->num_reads++; + + memset(val_buf, 0, val_size); + + return 0; +} + +static int test_init_limits_bus_write(void *context, const void *data, + size_t count) +{ + return 0; +} + +static const struct regmap_bus test_init_limits_bus = { + .read = test_init_limits_bus_read, + .write = test_init_limits_bus_write, + .init_limits = test_init_limits_bus_init_limits, +}; + +static const struct regmap_config test_init_limits_config = { + .reg_bits = 8, + .val_bits = 8, + .max_register = TEST_INIT_LIMITS_REGS - 1, + .cache_type = REGCACHE_FLAT, + .num_reg_defaults_raw = TEST_INIT_LIMITS_REGS, +}; + +static void test_init_limits(struct kunit *test) +{ + struct regmap_test_priv *priv = test->priv; + struct test_init_limits_data *data; + struct regmap *map; + int i, ret; + + data = kunit_kzalloc(test, sizeof(*data), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, data); + + map = regmap_init(priv->dev, &test_init_limits_bus, data, + &test_init_limits_config); + KUNIT_ASSERT_FALSE(test, IS_ERR(map)); + if (IS_ERR(map)) + return; + + ret = kunit_add_action_or_reset(test, regmap_exit_action, map); + KUNIT_ASSERT_EQ(test, 0, ret); + if (ret) + return; + + KUNIT_EXPECT_EQ(test, (size_t)TEST_INIT_LIMITS_MAX_RAW, + regmap_get_raw_read_max(map)); + KUNIT_EXPECT_EQ(test, (size_t)TEST_INIT_LIMITS_MAX_RAW, + regmap_get_raw_write_max(map)); + + /* + * regcache_hw_init() reads raw defaults during map initialization, + * so the callback must already have set the limit which chunks the + * readback. + */ + KUNIT_ASSERT_EQ(test, TEST_INIT_LIMITS_REGS / TEST_INIT_LIMITS_MAX_RAW, + data->num_reads); + for (i = 0; i < data->num_reads; i++) + KUNIT_EXPECT_EQ(test, (size_t)TEST_INIT_LIMITS_MAX_RAW, + data->read_sizes[i]); +} + static struct kunit_case regmap_test_cases[] = { KUNIT_CASE_PARAM(basic_read_write, regcache_types_gen_params), KUNIT_CASE_PARAM(read_bypassed, real_cache_types_gen_params), @@ -2290,6 +2380,7 @@ static struct kunit_case regmap_test_cases[] = { KUNIT_CASE_PARAM(raw_noinc_write, raw_test_types_gen_params), KUNIT_CASE_PARAM(raw_sync, raw_test_cache_types_gen_params), KUNIT_CASE_PARAM(raw_ranges, raw_test_cache_types_gen_params), + KUNIT_CASE(test_init_limits), {} }; From e5c608dbb7380f21222988bad5c921d0a8d911c2 Mon Sep 17 00:00:00 2001 From: Ian Rogers Date: Thu, 19 Nov 2026 09:10:59 -0800 Subject: [PATCH 1723/2102] ASoC: codecs: aw88395: Validate 4-byte alignment and init ret in reg update In aw_dev_update_reg_container(), each register entry consists of two 16-bit values (4 bytes). Because 'data_len = len >> 1' shifts off bit 0 before checking 'data_len & 0x1', byte lengths with (len & 0x3) == 1 bypass validation: len == 1 yields data_len == 0, executing zero loop iterations and returning an uninitialized ret, while larger odd lengths silently ignore the trailing byte. Reject any length with (len & 0x3) != 0 and initialize ret to 0. Found via Clang -Wconditional-uninitialized on an x86_64 allyesconfig build. Verified by building sound/soc/codecs/aw88395/aw88395_device.o with LLVM=1 W=1 (-Werror) and -Wconditional-uninitialized, and with a standalone C reproducer; not runtime-tested on AW88395 hardware. Fixes: 06d2fe9cb423 ("ASoC: codecs: Aw88395 function for ALSA Audio Driver") Signed-off-by: Ian Rogers Link: https://patch.msgid.link/20261119171059.1537658-1-irogers@google.com Signed-off-by: Mark Brown --- sound/soc/codecs/aw88395/aw88395_device.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/sound/soc/codecs/aw88395/aw88395_device.c b/sound/soc/codecs/aw88395/aw88395_device.c index 3ae418c8b34e10..2dd0b3b7de0d1c 100644 --- a/sound/soc/codecs/aw88395/aw88395_device.c +++ b/sound/soc/codecs/aw88395/aw88395_device.c @@ -1004,16 +1004,16 @@ static int aw_dev_update_reg_container(struct aw_device *aw_dev, u16 read_vol; u16 reg_val; u8 reg_addr; - int i, ret; - - reg_data = (int16_t *)data; - data_len = len >> 1; + int i, ret = 0; - if (data_len & 0x1) { - dev_err(aw_dev->dev, "data len:%d unsupported", data_len); + if (len & 0x3) { + dev_err(aw_dev->dev, "data len:%u unsupported\n", len); return -EINVAL; } + reg_data = (int16_t *)data; + data_len = len >> 1; + for (i = 0; i < data_len; i += 2) { reg_addr = reg_data[i]; reg_val = reg_data[i + 1]; From 4fec59cdc2f3cdcdbb71d665b53daf384b36d60d Mon Sep 17 00:00:00 2001 From: Kuba Piecuch Date: Mon, 23 Nov 2026 13:55:24 +0000 Subject: [PATCH 1724/2102] sched_ext: Don't allow unlocked kfuncs from ops.dump() and ops.init_cids() scx_kf_allow_flags[] grants SCX_KF_ALLOW_UNLOCKED to ops.dump(). This allows ops.dump() to call scx_bpf_dsq_move*(), scx_bpf_dsq_reenq_task(), and scx_bpf_select_cpu_*(). When no rq is locked, these kfuncs acquire rq, DSQ, and pi locks and may invoke nested SCX ops such as ops.dequeue(). scx_dump_state() runs ops.dump() with IRQs disabled under scx_dump_lock. Callers include the hardirq disable irq_work and SysRq-D. With SCX_KF_ALLOW_UNLOCKED, a debug dump can migrate tasks and run nested scheduler callbacks instead of only inspecting state. ops.dump_cpu() and ops.dump_task() already deny these kfuncs. Remove SCX_KF_ALLOW_UNLOCKED from ops.dump(). ops.init_cids() runs before the cid tables are published and before the arena pool and pshards are set up. Its only job is to finalize the cid layout. SCX_KF_ALLOW_UNLOCKED also gave it scx_bpf_create_dsq(), scx_bpf_dsq_move*(), and scx_bpf_dsq_reenq_task(). Restrict ops.init_cids() to SCX_KF_ALLOW_INIT_CIDS. No in-tree scheduler calls these kfuncs from either op. Fixes: 4c30f5ce4f7a ("sched_ext: Implement scx_bpf_dispatch[_vtime]_from_dsq()") Fixes: 874fdc0e86e4 ("sched_ext: Add ops.init_cids() to finalize the cid layout before init") Cc: stable@vger.kernel.org # v7.3+ Signed-off-by: Kuba Piecuch Signed-off-by: Tejun Heo --- kernel/sched/ext/ext.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c index 7eda101a0e47e2..dfda426c768fcf 100644 --- a/kernel/sched/ext/ext.c +++ b/kernel/sched/ext/ext.c @@ -12291,7 +12291,6 @@ static const u32 scx_kf_allow_flags[] = { [SCX_OP_IDX(dispatch)] = SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH, [SCX_OP_IDX(cpu_release)] = SCX_KF_ALLOW_CPU_RELEASE, [SCX_OP_IDX(init_task)] = SCX_KF_ALLOW_UNLOCKED, - [SCX_OP_IDX(dump)] = SCX_KF_ALLOW_UNLOCKED, #ifdef CONFIG_EXT_GROUP_SCHED [SCX_OP_IDX(cgroup_init)] = SCX_KF_ALLOW_UNLOCKED, [SCX_OP_IDX(cgroup_exit)] = SCX_KF_ALLOW_UNLOCKED, @@ -12307,7 +12306,12 @@ static const u32 scx_kf_allow_flags[] = { [SCX_OP_IDX(sub_child_ecaps_updated)] = SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH, [SCX_OP_IDX(cpu_online)] = SCX_KF_ALLOW_UNLOCKED, [SCX_OP_IDX(cpu_offline)] = SCX_KF_ALLOW_UNLOCKED, - [SCX_OP_IDX(init_cids)] = SCX_KF_ALLOW_UNLOCKED | SCX_KF_ALLOW_INIT_CIDS, + /* + * ops.init_cids() runs before the cid tables are published and before + * the arena pool and pshards are allocated. Limit it to finalizing the + * cid layout; everything else belongs in ops.init(). + */ + [SCX_OP_IDX(init_cids)] = SCX_KF_ALLOW_INIT_CIDS, [SCX_OP_IDX(init)] = SCX_KF_ALLOW_UNLOCKED, [SCX_OP_IDX(exit)] = SCX_KF_ALLOW_UNLOCKED, }; From ed42314d3e76b3142a2bb656e53e5b1d68c4a6ae Mon Sep 17 00:00:00 2001 From: Kuba Piecuch Date: Mon, 23 Nov 2026 13:55:25 +0000 Subject: [PATCH 1725/2102] selftests/sched_ext: Add unlocked_kfunc test Add the unlocked_kfunc test to verify verifier-time restrictions on the SCX_KF_ALLOW_UNLOCKED kfuncs. The valid cpu-form and cid-form schedulers verify that ops.init() and ops.exit() can call scx_bpf_create_dsq(), scx_bpf_dsq_move(), scx_bpf_dsq_reenq_task(), and scx_bpf_select_cpu_dfl(). They also verify that ops.dump() can call scx_bpf_dump() and that ops.init_cids() can call scx_bpf_cid_override(). The two negative schedulers verify that the verifier rejects scx_bpf_dsq_move() from ops.dump() and scx_bpf_create_dsq() from ops.init_cids() with -EACCES. Signed-off-by: Kuba Piecuch Signed-off-by: Tejun Heo --- tools/testing/selftests/sched_ext/Makefile | 1 + .../selftests/sched_ext/unlocked_kfunc.bpf.c | 69 ++++++++++++++++++ .../selftests/sched_ext/unlocked_kfunc.c | 73 +++++++++++++++++++ .../sched_ext/unlocked_kfunc_cid.bpf.c | 67 +++++++++++++++++ .../sched_ext/unlocked_kfunc_fail_dump.bpf.c | 26 +++++++ .../unlocked_kfunc_fail_init_cids.bpf.c | 22 ++++++ 6 files changed, 258 insertions(+) create mode 100644 tools/testing/selftests/sched_ext/unlocked_kfunc.bpf.c create mode 100644 tools/testing/selftests/sched_ext/unlocked_kfunc.c create mode 100644 tools/testing/selftests/sched_ext/unlocked_kfunc_cid.bpf.c create mode 100644 tools/testing/selftests/sched_ext/unlocked_kfunc_fail_dump.bpf.c create mode 100644 tools/testing/selftests/sched_ext/unlocked_kfunc_fail_init_cids.bpf.c diff --git a/tools/testing/selftests/sched_ext/Makefile b/tools/testing/selftests/sched_ext/Makefile index c5d3a2eaea7da2..9a776a8a36ff3f 100644 --- a/tools/testing/selftests/sched_ext/Makefile +++ b/tools/testing/selftests/sched_ext/Makefile @@ -199,6 +199,7 @@ auto-test-targets := \ rt_stall \ test_example \ total_bw \ + unlocked_kfunc \ cyclic_kick_wait \ testcase-targets := $(addsuffix .o,$(addprefix $(SCXOBJ_DIR)/,$(auto-test-targets))) diff --git a/tools/testing/selftests/sched_ext/unlocked_kfunc.bpf.c b/tools/testing/selftests/sched_ext/unlocked_kfunc.bpf.c new file mode 100644 index 00000000000000..194993a0ef0734 --- /dev/null +++ b/tools/testing/selftests/sched_ext/unlocked_kfunc.bpf.c @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * A cpu-form scheduler that calls SCX_KF_ALLOW_UNLOCKED kfuncs from ops.init() + * and ops.exit(). ops.dump() calls scx_bpf_dump(). + * + * Copyright (c) 2026 Google LLC. + */ + +#include + +#define SHARED_DSQ 0 + +char _license[] SEC("license") = "GPL"; + +static void drain_dsq(void) +{ + struct task_struct *p; + + bpf_rcu_read_lock(); + bpf_for_each(scx_dsq, p, SHARED_DSQ, 0) { + if (p->pid & 1) + scx_bpf_dsq_reenq_task(BPF_FOR_EACH_ITER, p); + else + scx_bpf_dsq_move(BPF_FOR_EACH_ITER, p, SCX_DSQ_GLOBAL, 0); + } + bpf_rcu_read_unlock(); +} + +static void select_cpu_for_current(void) +{ + struct task_struct *p = bpf_get_current_task_btf(); + bool is_idle; + + bpf_rcu_read_lock(); + scx_bpf_select_cpu_dfl(p, bpf_get_smp_processor_id(), 0, &is_idle); + bpf_rcu_read_unlock(); +} + +s32 BPF_STRUCT_OPS_SLEEPABLE(unlocked_kfunc_init) +{ + s32 ret; + + ret = scx_bpf_create_dsq(SHARED_DSQ, -1); + if (ret) + return ret; + + drain_dsq(); + select_cpu_for_current(); + return 0; +} + +void BPF_STRUCT_OPS(unlocked_kfunc_exit, struct scx_exit_info *ei) +{ + drain_dsq(); + select_cpu_for_current(); +} + +void BPF_STRUCT_OPS(unlocked_kfunc_dump, struct scx_dump_ctx *dctx) +{ + scx_bpf_dump("nr_cpu_ids=%u\n", scx_bpf_nr_cpu_ids()); +} + +SEC(".struct_ops.link") +struct sched_ext_ops unlocked_kfunc_ops = { + .init = (void *)unlocked_kfunc_init, + .exit = (void *)unlocked_kfunc_exit, + .dump = (void *)unlocked_kfunc_dump, + .name = "unlocked_kfunc", +}; diff --git a/tools/testing/selftests/sched_ext/unlocked_kfunc.c b/tools/testing/selftests/sched_ext/unlocked_kfunc.c new file mode 100644 index 00000000000000..0052c608365db1 --- /dev/null +++ b/tools/testing/selftests/sched_ext/unlocked_kfunc.c @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Verify that the BPF verifier rejects SCX_KF_ALLOW_UNLOCKED kfuncs from + * ops.dump() and ops.init_cids(). Unlocked ops such as ops.init() and + * ops.exit() must still be allowed to call them. + * + * Copyright (c) 2026 Google LLC. + */ +#include +#include +#include +#include "scx_test.h" +#include "unlocked_kfunc.bpf.skel.h" +#include "unlocked_kfunc_cid.bpf.skel.h" +#include "unlocked_kfunc_fail_dump.bpf.skel.h" +#include "unlocked_kfunc_fail_init_cids.bpf.skel.h" + +static enum scx_test_status run(void *ctx) +{ + struct unlocked_kfunc *skel; + struct unlocked_kfunc_cid *cid_skel; + struct unlocked_kfunc_fail_dump *fail_dump; + struct unlocked_kfunc_fail_init_cids *fail_init_cids; + int err; + + if (!__COMPAT_struct_has_field("sched_ext_ops_cid", "init_cids") || + !__COMPAT_has_ksym("scx_bpf_dsq_reenq_task")) + return SCX_TEST_SKIP; + + skel = unlocked_kfunc__open(); + SCX_FAIL_IF(!skel, "Failed to open unlocked_kfunc"); + SCX_ENUM_INIT(skel); + err = unlocked_kfunc__load(skel); + unlocked_kfunc__destroy(skel); + SCX_FAIL_IF(err, "Failed to load unlocked_kfunc (%d)", err); + + cid_skel = unlocked_kfunc_cid__open(); + SCX_FAIL_IF(!cid_skel, "Failed to open unlocked_kfunc_cid"); + SCX_ENUM_INIT(cid_skel); + err = unlocked_kfunc_cid__load(cid_skel); + unlocked_kfunc_cid__destroy(cid_skel); + SCX_FAIL_IF(err, "Failed to load unlocked_kfunc_cid (%d)", err); + + fail_dump = unlocked_kfunc_fail_dump__open(); + SCX_FAIL_IF(!fail_dump, "Failed to open unlocked_kfunc_fail_dump"); + SCX_ENUM_INIT(fail_dump); + err = unlocked_kfunc_fail_dump__load(fail_dump); + unlocked_kfunc_fail_dump__destroy(fail_dump); + SCX_FAIL_IF(!err, + "unlocked_kfunc_fail_dump loaded when it should have been rejected"); + SCX_FAIL_IF(err != -EACCES, + "Expected -EACCES loading unlocked_kfunc_fail_dump, got %d", err); + + fail_init_cids = unlocked_kfunc_fail_init_cids__open(); + SCX_FAIL_IF(!fail_init_cids, "Failed to open unlocked_kfunc_fail_init_cids"); + SCX_ENUM_INIT(fail_init_cids); + err = unlocked_kfunc_fail_init_cids__load(fail_init_cids); + unlocked_kfunc_fail_init_cids__destroy(fail_init_cids); + SCX_FAIL_IF(!err, + "unlocked_kfunc_fail_init_cids loaded when it should have been rejected"); + SCX_FAIL_IF(err != -EACCES, + "Expected -EACCES loading unlocked_kfunc_fail_init_cids, got %d", err); + + return SCX_TEST_PASS; +} + +struct scx_test unlocked_kfunc = { + .name = "unlocked_kfunc", + .description = "Verify verifier kfunc restrictions on ops.dump() and ops.init_cids()", + .run = run, +}; + +REGISTER_SCX_TEST(&unlocked_kfunc) diff --git a/tools/testing/selftests/sched_ext/unlocked_kfunc_cid.bpf.c b/tools/testing/selftests/sched_ext/unlocked_kfunc_cid.bpf.c new file mode 100644 index 00000000000000..ffe2f03c42e373 --- /dev/null +++ b/tools/testing/selftests/sched_ext/unlocked_kfunc_cid.bpf.c @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * A cid-form scheduler that calls scx_bpf_cid_override() from ops.init_cids() + * and SCX_KF_ALLOW_UNLOCKED kfuncs from ops.init(). ops.dump() calls + * scx_bpf_dump(). + * + * Copyright (c) 2026 Google LLC. + */ + +#include + +#define SHARED_DSQ 0 +#define MAX_CPUS 512 + +char _license[] SEC("license") = "GPL"; + +struct { + __uint(type, BPF_MAP_TYPE_ARENA); + __uint(map_flags, BPF_F_MMAPABLE); + __uint(max_entries, 1 << 4); +} arena SEC(".maps"); + +s32 __arena_global cpu_to_cid[MAX_CPUS]; +s32 __arena_global shard_start[MAX_CPUS]; + +s32 BPF_STRUCT_OPS_SLEEPABLE(unlocked_kfunc_cid_init_cids) +{ + u32 nr_cpu_ids = scx_bpf_nr_cpu_ids(); + + if (nr_cpu_ids > MAX_CPUS) + return -E2BIG; + + scx_bpf_cid_override(cpu_to_cid, nr_cpu_ids, shard_start, 1); + return 0; +} + +s32 BPF_STRUCT_OPS_SLEEPABLE(unlocked_kfunc_cid_init) +{ + struct task_struct *p; + s32 ret; + + ret = scx_bpf_create_dsq(SHARED_DSQ, -1); + if (ret) + return ret; + + bpf_rcu_read_lock(); + bpf_for_each(scx_dsq, p, SHARED_DSQ, 0) { + if (p->pid & 1) + scx_bpf_dsq_reenq_task(BPF_FOR_EACH_ITER, p); + else + scx_bpf_dsq_move(BPF_FOR_EACH_ITER, p, SCX_DSQ_GLOBAL, 0); + } + bpf_rcu_read_unlock(); + + return 0; +} + +void BPF_STRUCT_OPS(unlocked_kfunc_cid_dump, struct scx_dump_ctx *dctx) +{ + scx_bpf_dump("nr_cids=%u\n", scx_bpf_nr_cids()); +} + +SCX_OPS_CID_DEFINE(unlocked_kfunc_cid_ops, + .init_cids = (void *)unlocked_kfunc_cid_init_cids, + .init = (void *)unlocked_kfunc_cid_init, + .dump = (void *)unlocked_kfunc_cid_dump, + .name = "unlocked_kfunc_cid"); diff --git a/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_dump.bpf.c b/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_dump.bpf.c new file mode 100644 index 00000000000000..70218f48e93aef --- /dev/null +++ b/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_dump.bpf.c @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Verify that the BPF verifier rejects scx_bpf_dsq_move() from ops.dump(). + * + * Copyright (c) 2026 Google LLC. + */ + +#include + +#define SHARED_DSQ 0 + +char _license[] SEC("license") = "GPL"; + +void BPF_STRUCT_OPS(unlocked_kfunc_fail_dump_cb, struct scx_dump_ctx *dctx) +{ + struct task_struct *p; + + bpf_for_each(scx_dsq, p, SHARED_DSQ, 0) + scx_bpf_dsq_move(BPF_FOR_EACH_ITER, p, SCX_DSQ_GLOBAL, 0); +} + +SEC(".struct_ops.link") +struct sched_ext_ops unlocked_kfunc_fail_dump_ops = { + .dump = (void *)unlocked_kfunc_fail_dump_cb, + .name = "unlocked_kfunc_fail_dump", +}; diff --git a/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_init_cids.bpf.c b/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_init_cids.bpf.c new file mode 100644 index 00000000000000..2f2d277aa54fa8 --- /dev/null +++ b/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_init_cids.bpf.c @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Verify that the BPF verifier rejects scx_bpf_create_dsq() from + * ops.init_cids(). + * + * Copyright (c) 2026 Google LLC. + */ + +#include + +#define SHARED_DSQ 0 + +char _license[] SEC("license") = "GPL"; + +s32 BPF_STRUCT_OPS_SLEEPABLE(unlocked_kfunc_fail_init_cids_cb) +{ + return scx_bpf_create_dsq(SHARED_DSQ, -1); +} + +SCX_OPS_CID_DEFINE(unlocked_kfunc_fail_init_cids_ops, + .init_cids = (void *)unlocked_kfunc_fail_init_cids_cb, + .name = "unlocked_kfunc_fail_init_cids"); From 8b899b15cb3f210f476e044760f0208f3182f9a5 Mon Sep 17 00:00:00 2001 From: Thadeu Lima de Souza Cascardo Date: Wed, 11 Nov 2026 15:28:12 -0300 Subject: [PATCH 1726/2102] drm/amdgpu: clear the entire mapping when partially unmapping MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When we partially clear a BO mapping, we only add the partially unmapped region to the freed list. That will update the page table to clear that mapping and leave the other endpoints mapped. However, we move the endpoints to the invalids list. When later closing that BO, it will simply free the mapping and not clear the GPU page tables. Drop the optimization and clear the entire mapping from the page tables. As the endpoints are already in the invalids list, when that BO mapping needs to be accessed, the page tables will be updated. Though that may clear, then write page table entries and even lead to new page table allocations in certain situations, those would already happen in the clear path. When measuring a given workload, it was noticed an extra allocation in less than 10% of the cases, but no noticeable extra latency. In any case, correctness is more important and this fixes the scenario described. Fixes: 387f49e54672 ("drm/amdgpu: fix clear_all and replace handling in the VM (v2)") Reviewed-by: Christian König Signed-off-by: Thadeu Lima de Souza Cascardo Signed-off-by: Alex Deucher (cherry picked from commit 3940c19c6371c54a2a503431a4ad736c75cc56ac) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c | 6 ------ 1 file changed, 6 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c index 82b9b2d5d0cf5e..298623e14b4d80 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c @@ -2108,12 +2108,6 @@ int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev, list_for_each_entry_safe(tmp, next, &removed, list) { amdgpu_vm_it_remove(tmp, &vm->va); list_del(&tmp->list); - - if (tmp->start < saddr) - tmp->start = saddr; - if (tmp->last > eaddr) - tmp->last = eaddr; - tmp->bo_va = NULL; list_add(&tmp->list, &vm->freed); trace_amdgpu_vm_bo_unmap(NULL, tmp); From def748a82ab48c6d1f0f6eae10a9e8b4b01bdbf1 Mon Sep 17 00:00:00 2001 From: Priya Hosur Date: Wed, 4 Nov 2026 15:52:22 +0530 Subject: [PATCH 1727/2102] drm/amd/pm: restore the forced performance level after a reset After a GPU reset PMFW is reinitialised and comes back on its default curve, while smu_dpm.dpm_level still holds the level the user forced. On an SMU 14.0.1 APU with the level set to high, gfxclk drops from 2.8GHz to 600MHz while sysfs still reports high. Writing the same level again does not help, as amdgpu_dpm_force_performance_level() returns early when the requested level matches the cached one. smu_late_init() does not re-program the level either, as the AMD_PP_TASK_COMPLETE_INIT path compares the cached level against itself. amdgpu_dpm_reapply_umd_profile() replays the retained level after reset and resume, but only for the PROFILE_* levels, and returns early for any other level. Restore every level through this common path and rename it to amdgpu_dpm_reapply_performance_level(). The PROFILE_* levels keep their UMD pstate handling, other levels only replay the level itself. auto is skipped, as PMFW comes back in auto, as it does at probe. If replaying a non-profile level fails, the failure is logged and the level the user asked for is kept. smu_reapply_power_state_dynamic() duplicates smu_adjust_power_state_dynamic() with the display settings skipped and the level forced, so call that instead. v2: restore the forced level instead of reporting the default after the reset (Lijo). v3: use the force_performance_level argument of smu_adjust_power_state_dynamic() instead of switching the cached level to auto first. v4: restore the level through the common reapply path instead of smu_handle_task(), rename amdgpu_dpm_reapply_umd_profile() to amdgpu_dpm_reapply_performance_level(), replay non-profile levels directly and replace the body of smu_reapply_power_state_dynamic() (Lijo). Add the Fixes tag (Kevin). Fixes: 580ad7cbd4b7 ("drm/amdgpu/swsmu: Only force workload setup on init") Reviewed-by: Lijo Lazar Suggested-by: Lijo Lazar Signed-off-by: Priya Hosur Signed-off-by: Alex Deucher (cherry picked from commit 3c3e17be85567d74d3ad0ed0b225afd956c395e9) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_device.c | 4 +-- drivers/gpu/drm/amd/pm/amdgpu_dpm.c | 21 +++++++++--- drivers/gpu/drm/amd/pm/inc/amdgpu_dpm.h | 2 +- drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c | 39 ++++------------------ 4 files changed, 26 insertions(+), 40 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c index b24ccdd958a7fb..6d3aea3b834c1d 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c @@ -2785,9 +2785,9 @@ static int amdgpu_device_ip_late_init(struct amdgpu_device *adev) amdgpu_device_set_cg_state(adev, AMD_CG_STATE_GATE); amdgpu_device_set_pg_state(adev, AMD_PG_STATE_GATE); - r = amdgpu_dpm_reapply_umd_profile(adev); + r = amdgpu_dpm_reapply_performance_level(adev); if (r) { - dev_err(adev->dev, "Failed to restore UMD profile state: %d\n", r); + dev_err(adev->dev, "Failed to restore performance level: %d\n", r); return r; } diff --git a/drivers/gpu/drm/amd/pm/amdgpu_dpm.c b/drivers/gpu/drm/amd/pm/amdgpu_dpm.c index 75d8bb4868e89e..ea698fe48e0782 100644 --- a/drivers/gpu/drm/amd/pm/amdgpu_dpm.c +++ b/drivers/gpu/drm/amd/pm/amdgpu_dpm.c @@ -1083,14 +1083,16 @@ static void amdgpu_dpm_exit_umd_state(struct amdgpu_device *adev) } /** - * amdgpu_dpm_reapply_umd_profile - Restore the active UMD profile + * amdgpu_dpm_reapply_performance_level - Restore the retained DPM level * @adev: amdgpu device * * Resume and reset retain the selected DPM level in software, but the - * underlying GFX and PMFW state is lost. Reapply a retained UMD profile - * after the common resume path has restored its default CG and PG state. + * underlying GFX and PMFW state is lost. Reapply the retained level after + * the common resume path has restored its default CG and PG state. UMD + * profile levels also restore their GFX state, other levels only replay + * the level itself. */ -int amdgpu_dpm_reapply_umd_profile(struct amdgpu_device *adev) +int amdgpu_dpm_reapply_performance_level(struct amdgpu_device *adev) { const struct amd_pm_funcs *pp_funcs = adev->powerplay.pp_funcs; enum amd_dpm_forced_level level; @@ -1120,7 +1122,18 @@ int amdgpu_dpm_reapply_umd_profile(struct amdgpu_device *adev) case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_MCLK: case AMD_DPM_FORCED_LEVEL_PROFILE_PEAK: break; + case AMD_DPM_FORCED_LEVEL_AUTO: + /* PMFW comes back in auto, as it does at probe. */ + ret = 0; + goto unlock; default: + /* No UMD pstate state to restore, only the level itself. */ + ret = pp_funcs->reapply_performance_level(adev->powerplay.pp_handle, + level); + if (ret) + dev_warn(adev->dev, + "Failed to restore performance level %d: %d\n", + level, ret); ret = 0; goto unlock; } diff --git a/drivers/gpu/drm/amd/pm/inc/amdgpu_dpm.h b/drivers/gpu/drm/amd/pm/inc/amdgpu_dpm.h index ba8624d28f28b4..8ae3fcc016f80a 100644 --- a/drivers/gpu/drm/amd/pm/inc/amdgpu_dpm.h +++ b/drivers/gpu/drm/amd/pm/inc/amdgpu_dpm.h @@ -484,7 +484,7 @@ void amdgpu_dpm_set_power_state(struct amdgpu_device *adev, enum amd_dpm_forced_level amdgpu_dpm_get_performance_level(struct amdgpu_device *adev); int amdgpu_dpm_force_performance_level(struct amdgpu_device *adev, enum amd_dpm_forced_level level); -int amdgpu_dpm_reapply_umd_profile(struct amdgpu_device *adev); +int amdgpu_dpm_reapply_performance_level(struct amdgpu_device *adev); int amdgpu_dpm_get_pp_num_states(struct amdgpu_device *adev, struct pp_states_info *states); int amdgpu_dpm_dispatch_task(struct amdgpu_device *adev, diff --git a/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c b/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c index c9fe323fa6244e..76d45549ae2ee5 100644 --- a/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c +++ b/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c @@ -2505,33 +2505,7 @@ static int smu_reapply_power_state_dynamic(struct smu_context *smu, enum amd_dpm_forced_level level) { - struct smu_dpm_context *smu_dpm_ctx = &smu->smu_dpm; - int ret; - - ret = smu_apply_clocks_adjust_rules(smu); - if (ret) { - dev_err(smu->adev->dev, "Failed to apply clocks adjust rules!"); - return ret; - } - - ret = smu_asic_set_performance_level(smu, level); - if (ret) { - if (ret == -EOPNOTSUPP) - dev_info(smu->adev->dev, "set performance level %d not supported", - level); - else - dev_err(smu->adev->dev, "Failed to set performance level %d", - level); - return ret; - } - - smu_dpm_ctx->dpm_level = level; - - if (smu_dpm_ctx->dpm_level == AMD_DPM_FORCED_LEVEL_MANUAL || - smu_dpm_ctx->dpm_level == AMD_DPM_FORCED_LEVEL_PERF_DETERMINISM) - return 0; - - return smu_bump_power_profile_mode(smu, NULL, 0); + return smu_adjust_power_state_dynamic(smu, level, true, true); } static int smu_handle_task(struct smu_context *smu, @@ -2696,21 +2670,20 @@ smu_reapply_performance_level(void *handle, if (!smu->is_apu && !smu_dpm_ctx->dpm_context) return -EINVAL; + if (smu_dpm_ctx->dpm_level != level) + return -EINVAL; + switch (level) { case AMD_DPM_FORCED_LEVEL_PROFILE_STANDARD: case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_SCLK: case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_MCLK: case AMD_DPM_FORCED_LEVEL_PROFILE_PEAK: + smu_enter_umd_pstate(smu); break; default: - return -EINVAL; + break; } - if (smu_dpm_ctx->dpm_level != level) - return -EINVAL; - - smu_enter_umd_pstate(smu); - return smu_reapply_power_state_dynamic(smu, level); } From c6250266746952fc8ee9f8eb109084f415a6b41a Mon Sep 17 00:00:00 2001 From: Alex Deucher Date: Mon, 16 Nov 2026 09:04:14 -0500 Subject: [PATCH 1728/2102] drm/amdkfd: move TBA/TMA back to system memory For non-MI parts, move TBA/TMA back to system memory. Results in GPU resets in some apps after suspend. v2: add additional IP versions Closes: https://gitlab.freedesktop.org/drm/amd/-/work_items/6116 Fixes: fe5966d4fdcb ("drm/amdkfd: move TBA/TMA from system to device memory") Cc: James Zhu Cc: Vladimir Indic Cc: Harish Kasiviswanathan Cc: Philip Yang Reviewed-by: Harish Kasiviswanathan Reviewed-by: James Zhu Signed-off-by: Alex Deucher (cherry picked from commit ec2bd41d3c1f4c132752a99513e6c217044705bf) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_process.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_process.c b/drivers/gpu/drm/amd/amdkfd/kfd_process.c index 6663718fb83ce3..ee1381174b9778 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_process.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_process.c @@ -1536,7 +1536,12 @@ static int kfd_process_device_init_cwsr_dgpu(struct kfd_process_device *pdd) if (!dev->kfd->cwsr_enabled || !iosys_map_is_null(&qpd->cwsr_map) || !qpd->cwsr_base) return 0; - if (KFD_GC_VERSION(dev) >= IP_VERSION(9, 4, 2) && !dev->adev->apu_prefer_gtt) + if ((KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 2) || + KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 3) || + KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 4) || + KFD_GC_VERSION(dev) == IP_VERSION(9, 5, 0) || + KFD_GC_VERSION(dev) == IP_VERSION(12, 1, 0)) && + !dev->adev->apu_prefer_gtt) flags |= KFD_IOC_ALLOC_MEM_FLAGS_VRAM; else flags |= KFD_IOC_ALLOC_MEM_FLAGS_GTT; From f37d2c36832eb335b96c29cf41a1b5ac3e86de0a Mon Sep 17 00:00:00 2001 From: Aveline Noir Date: Sun, 8 Nov 2026 20:15:39 +1100 Subject: [PATCH 1729/2102] drm/amdkfd: preserve the byte address when removing retry faults svm_range_restore_pages() receives a CPU page number, but passes it unchanged to amdgpu_gmc_filter_faults_remove() when recovery is deferred or returns -EAGAIN. The software fault filter uses a byte address and PASID as its key, so this can leave the fault filtered until the entry ages out. Pass the original byte address to svm_range_restore_pages() and derive the CPU page number locally for range operations. Use the original address for both filter removals. This also preserves the GPU subpage offset when CPU pages are larger than the 4 KiB GPU page size. Fixes: b3dc91f97317 ("drm/amdkfd: enable subsequent retry fault") Reported-by: Sashiko Closes: https://lore.kernel.org/r/sashiko-outbox-203586@kernel.org Signed-off-by: Aveline Noir Reviewed-by: Felix Kuehling Signed-off-by: Felix Kuehling Signed-off-by: Alex Deucher (cherry picked from commit 1686421350c18d4943a72e795846d114ea78bf05) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c | 2 +- drivers/gpu/drm/amd/amdkfd/kfd_svm.c | 7 ++++--- drivers/gpu/drm/amd/amdkfd/kfd_svm.h | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c index 298623e14b4d80..9ca861df1f6fc2 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c @@ -3097,7 +3097,7 @@ bool amdgpu_vm_handle_fault(struct amdgpu_device *adev, u32 pasid, drm_exec_fini(&exec); if (!svm_range_restore_pages(adev, pasid, vmid, - node_id, addr >> PAGE_SHIFT, ts, write_fault)) + node_id, addr, ts, write_fault)) return true; /* Re-acquire the VM lock, could be that the VM was freed in between. */ diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c index 2835c1d73d63f6..7bbe4247f4deee 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c @@ -3125,8 +3125,9 @@ svm_fault_allowed(struct vm_area_struct *vma, bool write_fault) int svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid, uint32_t vmid, uint32_t node_id, - uint64_t addr, uint64_t ts, bool write_fault) + uint64_t fault_addr, uint64_t ts, bool write_fault) { + uint64_t addr = fault_addr >> PAGE_SHIFT; unsigned long start, last, size; struct mm_struct *mm = NULL; struct svm_range_list *svms; @@ -3244,7 +3245,7 @@ svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid, mutex_lock(&prange->migrate_mutex); if (svm_range_skip_recover(prange)) { - amdgpu_gmc_filter_faults_remove(node->adev, addr, pasid); + amdgpu_gmc_filter_faults_remove(node->adev, fault_addr, pasid); r = 0; goto out_unlock_range; } @@ -3348,7 +3349,7 @@ svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid, if (r == -EAGAIN) { pr_debug("recover vm fault later\n"); - amdgpu_gmc_filter_faults_remove(node->adev, addr, pasid); + amdgpu_gmc_filter_faults_remove(node->adev, fault_addr, pasid); r = 0; } return r; diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.h b/drivers/gpu/drm/amd/amdkfd/kfd_svm.h index c7d7adae4476bf..38744e716f74da 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.h +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.h @@ -178,7 +178,7 @@ int svm_range_vram_node_new(struct kfd_node *node, struct svm_range *prange, bool clear); void svm_range_vram_node_free(struct svm_range *prange); int svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid, - uint32_t vmid, uint32_t node_id, uint64_t addr, uint64_t ts, + uint32_t vmid, uint32_t node_id, uint64_t fault_addr, uint64_t ts, bool write_fault); int svm_range_evict_svm_bo(struct amdgpu_bo *bo); @@ -230,7 +230,7 @@ static inline void svm_range_list_fini(struct kfd_process *p) static inline int svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid, uint32_t client_id, uint32_t node_id, - uint64_t addr, uint64_t ts, bool write_fault) + uint64_t fault_addr, uint64_t ts, bool write_fault) { return -EFAULT; } From 389ce3e5088d5156921fba809f759dc778d834b4 Mon Sep 17 00:00:00 2001 From: Hongyan Xu Date: Sun, 8 Nov 2026 18:56:17 +0800 Subject: [PATCH 1730/2102] drm/amdkfd: fix use-after-free in create_process() error path create_process() publishes the process in kfd_processes_table before its last failing call (alloc_notifier() must find it there), and its error path frees it with a bare kfree(), ignoring the refcount. find_process() takes its reference inside the sRCU critical section but callers use the process after leaving it, so synchronize_srcu() misses them, and the error path cannot unref once either: it holds two (kref_init() and the one keeping free_notifier() from starting kfd_process_wq_release()). Release the process as soon as it is visible: take the lead thread reference right after lead_thread is assigned, run ida_init() before mmu_notifier_get(), so the release work is safe on a half-built object. The published error paths unlink with hash_del_rcu(), synchronize_srcu() and drop both references, so the last one runs kfd_process_wq_release(). Both labels hold exactly two references, so nothing is freed early and no path falls into the unwind the unpublished labels keep, now with put_task_struct()). Restore pqm_uninit() (kfd_process_queue_manager.c): pqm_init()'s 128 byte queue slot bitmap leaked per failure. Fixes: 3248b6d3cbcd ("drm/amdkfd: Use mmu_notifier_get") Signed-off-by: Hongyan Xu Reviewed-by: Felix Kuehling [Felix: dropped changes in kfd_debugfs.c, fixed by a previous patch] Signed-off-by: Felix Kuehling Signed-off-by: Alex Deucher (cherry picked from commit b5528ff019b07caa7bd1f938a35391528b26dfdb) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_process.c | 46 ++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_process.c b/drivers/gpu/drm/amd/amdkfd/kfd_process.c index ee1381174b9778..46f70ed1d551f5 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_process.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_process.c @@ -1692,6 +1692,11 @@ struct kfd_process *create_process(const struct task_struct *thread, bool primar mutex_init(&process->mutex); process->mm = thread->mm; process->lead_thread = thread->group_leader; + /* + * Take the reference on the lead thread before the process can be + * released through kfd_process_wq_release(), which drops it again. + */ + get_task_struct(process->lead_thread); process->n_pdds = 0; process->queues_paused = false; @@ -1741,13 +1746,17 @@ struct kfd_process *create_process(const struct task_struct *thread, bool primar */ if (primary) { process->context_id = KFD_CONTEXT_ID_PRIMARY; + /* + * Must be initialized before the process can be given to + * kfd_process_wq_release(), which destroys it. + */ + ida_init(&process->id_table); mn = mmu_notifier_get(&kfd_process_mmu_notifier_ops, process->mm); if (IS_ERR(mn)) { err = PTR_ERR(mn); goto err_register_notifier; } BUG_ON(mn != &process->mmu_notifier); - ida_init(&process->id_table); } err = kfd_process_alloc_id(process); @@ -1757,7 +1766,6 @@ struct kfd_process *create_process(const struct task_struct *thread, bool primar } kfd_unref_process(process); - get_task_struct(process->lead_thread); INIT_WORK(&process->debug_event_workarea, debug_event_write_work_handler); @@ -1766,8 +1774,39 @@ struct kfd_process *create_process(const struct task_struct *thread, bool primar err_alloc_id: kfd_process_free_id(process); err_register_notifier: + /* + * The process is already in kfd_processes_table, so find_process() + * may have handed it out with a reference taken on it. Unlink it + * and wait for the readers that are still walking the table before + * dropping the references held here: afterwards no new reference + * can be taken and the ones already taken keep the process alive. + * The memory is then freed by kfd_process_wq_release() when the + * last reference is dropped. + */ hash_del_rcu(&process->kfd_processes); - svm_range_list_fini(process); + synchronize_srcu(&kfd_processes_srcu); + + /* + * kfd_process_wq_release() frees the memory, but it does not + * destroy the queue manager: on the normal path that is done by + * kfd_process_notifier_release_internal(), which neither of these + * two error paths can reach, because no mmu notifier was + * registered for the process. The process is unlinked and no + * reader can reach the pqm any more, so destroy it here, before + * the references are dropped. + */ + pqm_uninit(&process->pqm); + + /* + * Drop the reference that keeps a failing free_notifier() from + * starting kfd_process_wq_release() and the one taken by + * kref_init(). + */ + kfd_unref_process(process); + kfd_unref_process(process); + + return ERR_PTR(err); + err_init_svm_range_list: kfd_process_free_outstanding_kfd_bos(process); kfd_process_destroy_pdds(process); @@ -1777,6 +1816,7 @@ struct kfd_process *create_process(const struct task_struct *thread, bool primar kfd_event_free_process(process); err_event_init: mutex_destroy(&process->mutex); + put_task_struct(process->lead_thread); kfree(process); err_alloc_process: return ERR_PTR(err); From e28daba76453f5e2180f557c7211d25c269a489f Mon Sep 17 00:00:00 2001 From: Prike Liang Date: Tue, 10 Nov 2026 11:42:54 +0800 Subject: [PATCH 1731/2102] drm/amdgpu/mes: keep the RS64 context slot bitmaps across MES re-init mes_v11_0_hw_init() queries the MES context array sizes on every hardware init, including after a GPU reset or a resume, and amdgpu_mes_rs64mem_setup_bitmaps() then allocates new, empty process and gang context slot bitmaps. The old bitmaps leak, and with them the record of which slots live processes and queues still hold, so the next allocation can hand out a slot that is in use, and two processes or queues end up sharing a MES context. Keep the existing bitmaps when MES is re-initialized. The array sizes come from the firmware and don't change. Fixes: 4ae2e536c643 ("drm/amdgpu/mes11: get MES process/gang contex size") Signed-off-by: Prike Liang Acked-by: Shaoyun Liu Signed-off-by: Alex Deucher (cherry picked from commit ef985c229d415b250ffdeed05d15c6e98c07e06f) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c index 384510c343cd13..db70bdd79a80ea 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c @@ -997,6 +997,10 @@ int amdgpu_mes_rs64mem_setup_bitmaps(struct amdgpu_mes *mes) if (!mes->use_rs64mem || !mes->ctx_array_size_cpu_ptr) return 0; + /* Keep the slots live processes and queues hold across MES re-init. */ + if (mes->proc_ctx_bitmap && mes->gang_ctx_bitmap) + return 0; + /* * MES FW wrote the sizes to the GPU buffer: * ctx_array_size_cpu_ptr[0] = proc_ctx_array_size (N) From 458fbc43a2631031219794deaf1e7b67669349b4 Mon Sep 17 00:00:00 2001 From: chong li Date: Tue, 17 Nov 2026 18:16:30 +0800 Subject: [PATCH 1732/2102] drm/amdgpu: post the ASIC after the reset done at init time When the driver is reloaded, amdgpu_device_init() resets the ASIC but does not post it again, because BIOS scratch register 7 still reports ATOM_S7_ASIC_INIT_COMPLETE after the reset. psp_sw_init() can then read the PSP runtime database before the PSP is ready. SCPM is detected as disabled and the PPTable upload fails with "Failed to transfer pptable to SMC!". how to fix: Set has_hw_reset after a successful reset on init, so that amdgpu_device_need_post() returns true and amdgpu_device_asic_init() is called. The ASIC init returns only after the PSP is ready, so the PSP runtime database is valid when it is read. Signed-off-by: chong li Acked-by: Alex Deucher Signed-off-by: Alex Deucher (cherry picked from commit 277773a29c7f24dfae124ec68de1bbcd8531d300) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_device.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c index 6d3aea3b834c1d..8435210e96be30 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c @@ -4076,6 +4076,9 @@ int amdgpu_device_init(struct amdgpu_device *adev, amdgpu_reset_method = AMD_RESET_METHOD_NONE; r = amdgpu_asic_reset(adev); amdgpu_reset_method = tmp; + /* Post again so that the PSP is ready before it is used */ + if (!r) + adev->has_hw_reset = true; } if (r) { From 84fecc06db52138d196ca9a69d8cbaa514aecf8d Mon Sep 17 00:00:00 2001 From: Pierre-Eric Pelloux-Prayer Date: Tue, 17 Nov 2026 08:54:07 +0100 Subject: [PATCH 1733/2102] drm/amdgpu: use a single clear entity on some chips Workaround to fix failing tests until the root cause is understood and fixed. Fixes: 3a6f6eeb3db5 ("drm/amdgpu: give ttm entities access to all the sdma scheds") Signed-off-by: Pierre-Eric Pelloux-Prayer Reviewed-by: Alex Deucher Signed-off-by: Alex Deucher (cherry picked from commit ce9e54fa831ba82a0b084b76d7c4d84e689dbd6c) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c index 0f86777250fc00..dbb1225ff5d2db 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c @@ -2410,6 +2410,13 @@ void amdgpu_ttm_enable_buffer_funcs(struct amdgpu_device *adev) sdma_ip_version = amdgpu_ip_version(adev, SDMA0_HWIP, 0); if (sdma_ip_version == IP_VERSION(7, 0, 0) || sdma_ip_version == IP_VERSION(7, 0, 1)) num_move_entities = 1; + if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 1) || + amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 2) || + amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 3) || + amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 4) || + amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 5, 0) || + amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(12, 1, 0)) + num_clear_entities = 1; adev->mman.clear_entities = kzalloc_objs(struct amdgpu_ttm_buffer_entity, num_clear_entities); From 267f25769532f475e56f9b63a914d66024119137 Mon Sep 17 00:00:00 2001 From: Suresh Guttula Date: Wed, 18 Nov 2026 15:50:46 +0530 Subject: [PATCH 1734/2102] drm/amd/amdgpu: Enable IMU_I/DRAM FW_LOAD CMD For GC 11, Eventhough IMU ucode load from BIOS/IFWI, PSP exepct Load command from GFX to load IMU ucode. v2: Updated fw_load_skip_check specific to GC11 Signed-off-by: Suresh Guttula Reviewed-by: Mario Limonciello (AMD) Tested-by: Mario Limonciello (AMD) Reviewed-by: Lijo Lazar Signed-off-by: Alex Deucher (cherry picked from commit db037de64e38d942fbad28529c15fd5628ed330c) --- drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c | 10 ++++++++++ drivers/gpu/drm/amd/amdgpu/imu_v11_0.c | 14 +++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c index 6d693b5249ddd9..0ce1ff2b775070 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c @@ -3954,6 +3954,16 @@ static int psp_load_smu_fw(struct psp_context *psp) static bool fw_load_skip_check(struct psp_context *psp, struct amdgpu_firmware_info *ucode) { + struct amdgpu_device *adev = psp->adev; + /* Keep IMU firmware loading enabled for APUs with GC IP 11.0.0-11.7.1. */ + if ((adev->flags & AMD_IS_APU) && + (amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(11, 0, 0) + && amdgpu_ip_version(adev, GC_HWIP, 0) <= IP_VERSION(11, 7, 1))) { + if (!ucode->fw && (ucode->ucode_id == AMDGPU_UCODE_ID_IMU_I || + ucode->ucode_id == AMDGPU_UCODE_ID_IMU_D)) + return false; + } + if (!ucode->fw || !ucode->ucode_size) return true; diff --git a/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c b/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c index b6c4ae35ca03a4..3aef68c9891a9b 100644 --- a/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c +++ b/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c @@ -31,6 +31,8 @@ #include "gc/gc_11_0_0_offset.h" #include "gc/gc_11_0_0_sh_mask.h" +#define IMU_DATA_SIZE_BYTES 66304 + MODULE_FIRMWARE("amdgpu/gc_11_0_0_imu.bin"); MODULE_FIRMWARE("amdgpu/gc_11_0_0_imu_kicker.bin"); MODULE_FIRMWARE("amdgpu/gc_11_0_1_imu.bin"); @@ -73,8 +75,18 @@ static int imu_v11_0_init_microcode(struct amdgpu_device *adev) else err = amdgpu_ucode_request(adev, &adev->gfx.imu_fw, required, "amdgpu/%s_imu.bin", ucode_prefix); - if (err == -ENODEV && imu_in_ifwi) + if (err == -ENODEV && imu_in_ifwi) { + info = &adev->firmware.ucode[AMDGPU_UCODE_ID_IMU_I]; + info->ucode_id = AMDGPU_UCODE_ID_IMU_I; + info->fw = adev->gfx.imu_fw; + info->ucode_size = IMU_DATA_SIZE_BYTES; + + info = &adev->firmware.ucode[AMDGPU_UCODE_ID_IMU_D]; + info->ucode_id = AMDGPU_UCODE_ID_IMU_D; + info->fw = adev->gfx.imu_fw; + info->ucode_size = IMU_DATA_SIZE_BYTES; return 0; + } if (err) goto out; From f16f5f0ca1d50895de21ac35bf2244e5ae615642 Mon Sep 17 00:00:00 2001 From: Kent Russell Date: Mon, 9 Nov 2026 11:19:15 -0500 Subject: [PATCH 1735/2102] drm/amdgpu: Disable XNACK retry on GFX12.1 This feature cannot be properly supported, so disable it both on the amdgpu side and the amdkfd side. v2: Remove dead code (thanks Sashiko-bot) v3: Remove unneeded extra check (thanks Mukul/Philip) v4: Remove dead code (thanks Mukul) Signed-off-by: Kent Russell Reviewed-by: Mukul Joshi Signed-off-by: Alex Deucher (cherry picked from commit dd28915031f35d264a79fea9abc7b50f98b84d25) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c | 7 +++++++ drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c | 17 +++++++---------- .../amdkfd/kfd_device_queue_manager_v12_1.c | 18 ++++-------------- 3 files changed, 18 insertions(+), 24 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c index efa0bc1e432abd..2172fe0ea8cf23 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c @@ -1127,6 +1127,13 @@ void amdgpu_gmc_noretry_set(struct amdgpu_device *adev) gmc->noretry = 1; else gmc->noretry = (amdgpu_noretry == -1) ? noretry_default : amdgpu_noretry; + + /* XNACK cannot be enabled on GFX12.1, so keep noretry=1 */ + if (gc_ver == IP_VERSION(12, 1, 0)) { + if (amdgpu_noretry == 0) + dev_warn(adev->dev, "Unable to set noretry = 0 on GFX12.1. Keeping noretry = 1"); + gmc->noretry = 1; + } } void amdgpu_gmc_set_vm_fault_masks(struct amdgpu_device *adev, int hub_type, diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c b/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c index 58f5ff506dc4ec..16518b0abfe91a 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c @@ -1514,9 +1514,8 @@ static u32 gfx_v12_1_get_sh_mem_config(struct amdgpu_device *adev) { u32 sh_mem_config = DEFAULT_SH_MEM_CONFIG; - /* GC 12.1.0 A0 requires RETRY_DISABLE in SH_MEM_CONFIG. */ - if (SOC_V1_0_DIE_REV_XCD(adev->rev_id) == 0) - sh_mem_config |= 1 << SH_MEM_CONFIG__RETRY_DISABLE__SHIFT; + /* XNACK cannot be enabled for GFX12.1 */ + sh_mem_config |= 1 << SH_MEM_CONFIG__RETRY_DISABLE__SHIFT; return sh_mem_config; } @@ -1563,14 +1562,12 @@ static void gfx_v12_1_xcc_init_compute_vmid(struct amdgpu_device *adev, static void gfx_v12_1_xcc_xnack_set_chicken_bits(struct amdgpu_device *adev, int xcc_id) { - /* NOTE: COMPRESSION_ENABLE is used a chicken bit to enable/disable xcc xnack */ + /* NOTE: COMPRESSION_ENABLE is used as a chicken bit to enable/disable xcc xnack + * Since xnack retry is disabled for GFX12.1, set it to 0 unconditionally + */ mutex_lock(&adev->srbm_mutex); - if (!adev->gmc.noretry) { - WREG32_FIELD15_PREREG(GC, GET_INST(GC, xcc_id), - TCP_PERFCOUNTER_FILTER, COMPRESSION_ENABLE, 0x1); - } else - WREG32_FIELD15_PREREG(GC, GET_INST(GC, xcc_id), - TCP_PERFCOUNTER_FILTER, COMPRESSION_ENABLE, 0x0); + WREG32_FIELD15_PREREG(GC, GET_INST(GC, xcc_id), + TCP_PERFCOUNTER_FILTER, COMPRESSION_ENABLE, 0x0); mutex_unlock(&adev->srbm_mutex); } diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager_v12_1.c b/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager_v12_1.c index 52598937137823..63ba13a60b9823 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager_v12_1.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager_v12_1.c @@ -54,7 +54,6 @@ static int update_qpd_v12_1(struct device_queue_manager *dqm, struct kfd_process_device *pdd; struct amdgpu_device *adev = dqm->dev->adev; struct amdgpu_vmhub *hub = &adev->vmhub[AMDGPU_GFXHUB(0)]; - bool xnack_enabled; pdd = qpd_to_pdd(qpd); qpd->vm_cntx_cntl = hub->vm_cntx_cntl; @@ -72,19 +71,10 @@ static int update_qpd_v12_1(struct device_queue_manager *dqm, qpd->sh_mem_ape1_base = 0; } - xnack_enabled = KFD_SUPPORT_XNACK_PER_PROCESS(dqm->dev) ? - pdd->process->xnack_enabled : - !pdd->dev->kfd->noretry; - - if (!xnack_enabled) { - qpd->sh_mem_config |= 1 << SH_MEM_CONFIG__RETRY_DISABLE__SHIFT; - qpd->vm_cntx_cntl &= - ~(1 << GCVM_CONTEXT0_CNTL__RETRY_PERMISSION_OR_INVALID_PAGE_FAULT__SHIFT); - } else { - qpd->sh_mem_config &= ~(1 << SH_MEM_CONFIG__RETRY_DISABLE__SHIFT); - qpd->vm_cntx_cntl |= - (1 << GCVM_CONTEXT0_CNTL__RETRY_PERMISSION_OR_INVALID_PAGE_FAULT__SHIFT); - } + /* XNACK cannot be enabled for gfx12.1 */ + qpd->sh_mem_config |= 1 << SH_MEM_CONFIG__RETRY_DISABLE__SHIFT; + qpd->vm_cntx_cntl &= + ~(1 << GCVM_CONTEXT0_CNTL__RETRY_PERMISSION_OR_INVALID_PAGE_FAULT__SHIFT); qpd->sh_mem_bases = compute_sh_mem_bases_64bit(pdd); From 78d6ce3c0ddd98fb2c96f7319a21ac9cdd82be26 Mon Sep 17 00:00:00 2001 From: Perry Yuan Date: Fri, 6 Nov 2026 11:11:09 +0800 Subject: [PATCH 1736/2102] drm/amdkfd: test copy_from_user() directly in kfd_criu_restore_svm() copy_from_user() returns the number of bytes not copied, not an errno. kfd_criu_restore_svm() stored that count in ret before overwriting it with -EFAULT. Test the return value directly so ret only ever holds an error code. v2: - split the original patch into two, one change per patch (Yifan) Signed-off-by: Perry Yuan Reviewed-by: Yifan Zhang Signed-off-by: Alex Deucher (cherry picked from commit ac886aaae63ef5e57c71ffc0b4177e1b09dd2b43) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_svm.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c index 7bbe4247f4deee..35afc8efca27fd 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c @@ -4284,9 +4284,8 @@ int kfd_criu_restore_svm(struct kfd_process *p, return -ENOMEM; } - ret = copy_from_user(&criu_svm_md->data, user_priv_ptr + *priv_data_offset, - svm_priv_data_size); - if (ret) { + if (copy_from_user(&criu_svm_md->data, user_priv_ptr + *priv_data_offset, + svm_priv_data_size)) { ret = -EFAULT; goto exit; } From 677cb870c2be354109597428f9d8651208465877 Mon Sep 17 00:00:00 2001 From: Pierre-Eric Pelloux-Prayer Date: Thu, 29 Oct 2026 16:19:48 +0100 Subject: [PATCH 1737/2102] drm/amdgpu: fix NULL deref in error path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If we hit the "error_free_root" error path, amdgpu_vm_pt_free_root is called which will clear vm->root.bo so calling amdgpu_bo_unreserve will crash. Since root_bo is a reference to the BO previously installed as vm->root.bo, use it. Fixes: 8473bfdcb5b1 ("drm/amdgpu: fix error handling in amdgpu_vm_init") Signed-off-by: Pierre-Eric Pelloux-Prayer Reviewed-by: Christian König Signed-off-by: Alex Deucher (cherry picked from commit b03a5b1e3cce7733467d198570e79a4fcfa4cf61) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c index 9ca861df1f6fc2..37888b5061ff0d 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c @@ -2689,7 +2689,7 @@ int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm, error_free_root: amdgpu_vm_pt_free_root(adev, vm); - amdgpu_bo_unreserve(vm->root.bo); + amdgpu_bo_unreserve(root_bo); amdgpu_bo_unref(&root_bo); error_free_delayed: From 5ea445d4ac85931fc73a6f65a307a1de3cfd328b Mon Sep 17 00:00:00 2001 From: Alex Deucher Date: Wed, 18 Nov 2026 17:24:17 -0500 Subject: [PATCH 1738/2102] drm/amdgpu: add helper for determining removable devices (USB4, TB) Apparently some Intel TB ports don't set dev_is_removable() on attached devices and thus the current check fails. Add a helper to check both dev_is_removable() and TB attached. Cc: superm1@kernel.org Closes: https://gitlab.freedesktop.org/drm/amd/-/work_items/6163 Fixes: d9b3a066dfcd ("drm/amd: Exclude dGPUs in eGPU enclosures from DPM quirks") Fixes: 7b1c6263eaf4 ("drm/amdgpu: don't use pci_is_thunderbolt_attached()") Fixes: 432e664e7c98 ("drm/amdgpu: don't use ATRM for external devices") Reviewed-by: Mario Limonciello (AMD) Signed-off-by: Alex Deucher (cherry picked from commit b11c2bd60f0bba17c14a91b208ccb3071dc07520) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu.h | 2 ++ drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c | 2 +- drivers/gpu/drm/amd/amdgpu/amdgpu_device.c | 24 ++++++++++++++-------- drivers/gpu/drm/amd/amdgpu/nbio_v2_3.c | 4 ++-- 4 files changed, 21 insertions(+), 11 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu.h b/drivers/gpu/drm/amd/amdgpu/amdgpu.h index c7577b608f3e41..32e4779ea9acbd 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu.h +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu.h @@ -1050,6 +1050,8 @@ int amdgpu_do_asic_reset(struct list_head *device_list_handle, int amdgpu_device_reinit_after_reset(struct amdgpu_reset_context *reset_context); +bool amdgpu_device_is_removable(struct amdgpu_device *adev); + int emu_soc_asic_init(struct amdgpu_device *adev); /* diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c index f9315e0472fe95..ccb91969b7343d 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c @@ -369,7 +369,7 @@ static bool amdgpu_atrm_get_bios(struct amdgpu_device *adev) bool found = false; /* ATRM is for on-platform devices only */ - if (dev_is_removable(&adev->pdev->dev)) + if (amdgpu_device_is_removable(adev)) return false; while ((pdev = pci_get_base_class(PCI_BASE_CLASS_DISPLAY, pdev))) { diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c index 8435210e96be30..ad4b6260bc6aa8 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c @@ -617,8 +617,7 @@ void amdgpu_device_detect_runtime_pm_mode(struct amdgpu_device *adev) int bamaco_support; adev->pm.rpm_mode = AMDGPU_RUNPM_NONE; - if (pci_is_thunderbolt_attached(adev->pdev) || - dev_is_removable(&adev->pdev->dev)) { + if (amdgpu_device_is_removable(adev)) { dev_info(adev->dev, "Runtime PM disabled for externally attached device\n"); return; @@ -1286,6 +1285,16 @@ bool amdgpu_device_seamless_boot_supported(struct amdgpu_device *adev) return amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0); } +bool amdgpu_device_is_removable(struct amdgpu_device *adev) +{ + /* older TB systems don't set dev_is_removable so check both here */ + if (dev_is_removable(adev->dev) || + pci_is_thunderbolt_attached(adev->pdev)) + return true; + + return false; +} + #if IS_ENABLED(CONFIG_X86) static const struct x86_cpu_id amdgpu_pcie_dynamic_switching_quirks[] = { /* @@ -1308,8 +1317,8 @@ static const struct x86_cpu_id amdgpu_pcie_dynamic_switching_quirks[] = { static bool amdgpu_device_pcie_dynamic_switching_supported(struct amdgpu_device *adev) { - /* eGPU change speeds based on USB4 fabric conditions */ - if (dev_is_removable(adev->dev)) + /* eGPU change speeds based on USB4/TB fabric conditions */ + if (amdgpu_device_is_removable(adev)) return true; /* Hosts have problems with dynamic speed switching */ @@ -2075,7 +2084,7 @@ static int amdgpu_device_ip_early_init(struct amdgpu_device *adev) (amdgpu_is_atpx_hybrid() || amdgpu_has_atpx_dgpu_power_cntl()) && ((adev->flags & AMD_IS_APU) == 0) && - !dev_is_removable(&adev->pdev->dev)) + !amdgpu_device_is_removable(adev)) adev->flags |= AMD_IS_PX; if (!(adev->flags & AMD_IS_APU)) { @@ -3768,9 +3777,8 @@ static void amdgpu_device_sys_interface_fini(struct amdgpu_device *adev) static bool amdgpu_device_should_register_switcheroo(struct amdgpu_device *adev, bool px) { - return !pci_is_thunderbolt_attached(adev->pdev) && - (px || (!dev_is_removable(&adev->pdev->dev) && - apple_gmux_detect(NULL, NULL))); + return !amdgpu_device_is_removable(adev) && + (px || apple_gmux_detect(NULL, NULL)); } /** diff --git a/drivers/gpu/drm/amd/amdgpu/nbio_v2_3.c b/drivers/gpu/drm/amd/amdgpu/nbio_v2_3.c index 04041b398781b4..3da92fb09495db 100644 --- a/drivers/gpu/drm/amd/amdgpu/nbio_v2_3.c +++ b/drivers/gpu/drm/amd/amdgpu/nbio_v2_3.c @@ -357,7 +357,7 @@ static void nbio_v2_3_enable_aspm(struct amdgpu_device *adev, data |= NAVI10_PCIE__LC_L0S_INACTIVITY_DEFAULT << PCIE_LC_CNTL__LC_L0S_INACTIVITY__SHIFT; - if (dev_is_removable(&adev->pdev->dev)) + if (amdgpu_device_is_removable(adev)) data |= NAVI10_PCIE__LC_L1_INACTIVITY_TBT_DEFAULT << PCIE_LC_CNTL__LC_L1_INACTIVITY__SHIFT; else data |= NAVI10_PCIE__LC_L1_INACTIVITY_DEFAULT << PCIE_LC_CNTL__LC_L1_INACTIVITY__SHIFT; @@ -476,7 +476,7 @@ static void nbio_v2_3_program_aspm(struct amdgpu_device *adev) def = data = RREG32_PCIE(smnPCIE_LC_CNTL); data |= NAVI10_PCIE__LC_L0S_INACTIVITY_DEFAULT << PCIE_LC_CNTL__LC_L0S_INACTIVITY__SHIFT; - if (dev_is_removable(&adev->pdev->dev)) + if (amdgpu_device_is_removable(adev)) data |= NAVI10_PCIE__LC_L1_INACTIVITY_TBT_DEFAULT << PCIE_LC_CNTL__LC_L1_INACTIVITY__SHIFT; else data |= NAVI10_PCIE__LC_L1_INACTIVITY_DEFAULT << PCIE_LC_CNTL__LC_L1_INACTIVITY__SHIFT; From c5f687cb477cb7c541d2421592470392874c14be Mon Sep 17 00:00:00 2001 From: Mario Limonciello Date: Thu, 19 Nov 2026 13:21:19 -0600 Subject: [PATCH 1739/2102] PCI: Cache bridge firmware secondary bus number Drivers such as amdgpu and radeon need the bus number firmware assigned to a device to match it against firmware tables like VFCT. The PCI core may renumber buses (e.g. with pci=realloc), after which the runtime number no longer reflects what firmware programmed. Record the bridge's secondary bus number in its struct pci_dev when pci_read_bridge_windows() reads the bus number register. This happens once, when the bridge is first enumerated and before any renumbering, so the value is what firmware left at FW/OS handoff. Devices behind the bridge can then retrieve their firmware bus number via their upstream bridge. Fixes: 11c141672045 ("drm/amdgpu: Fix VFCT bus number matching with soft filter") Fixes: 4059e2f02c8a ("drm/radeon: Fix VFCT bus number matching with soft filter") Acked-by: Alex Deucher Acked-by: Bjorn Helgaas Link: https://patch.msgid.link/20261119-vfct-regression-v8-v8-1-12463194e457@amd.com Signed-off-by: Mario Limonciello Signed-off-by: Alex Deucher (cherry picked from commit 03b711fae4ea6071baf96506f56f78c98fbc045d) Cc: stable@vger.kernel.org --- drivers/pci/probe.c | 1 + include/linux/pci.h | 2 ++ 2 files changed, 3 insertions(+) diff --git a/drivers/pci/probe.c b/drivers/pci/probe.c index 9a178e0e5f7f46..89a7c52ac3e5b7 100644 --- a/drivers/pci/probe.c +++ b/drivers/pci/probe.c @@ -513,6 +513,7 @@ static void pci_read_bridge_windows(struct pci_dev *bridge) res.flags = IORESOURCE_BUS; res.start = FIELD_GET(PCI_SECONDARY_BUS_MASK, buses); res.end = FIELD_GET(PCI_SUBORDINATE_BUS_MASK, buses); + bridge->fw_sec_busnr = res.start; pci_info(bridge, "PCI bridge to %pR%s\n", &res, bridge->transparent ? " (subtractive decode)" : ""); diff --git a/include/linux/pci.h b/include/linux/pci.h index aa3765a20a96c1..4c1b1e557a6076 100644 --- a/include/linux/pci.h +++ b/include/linux/pci.h @@ -363,6 +363,8 @@ struct pci_dev { struct pci_slot *slot; /* Physical slot this device is in */ unsigned int devfn; /* Encoded device & function index */ + /* Bridge secondary bus number at FW/OS handoff */ + unsigned char fw_sec_busnr; unsigned short vendor; unsigned short device; unsigned short subsystem_vendor; From 678d0b30f930b4870a2a36eb358fab67f1f1bffc Mon Sep 17 00:00:00 2001 From: Mario Limonciello Date: Thu, 19 Nov 2026 13:21:20 -0600 Subject: [PATCH 1740/2102] drm/amdgpu: Match VFCT using initial PCI bus number VFCT records the PCI bus number from BIOS POST. The current bus number can change after PCI core renumbers the bus, while accepting a mismatch based only on device identity can select the wrong VFCT image when matching devices are present. Compare against the secondary bus number of the upstream bridge at FW/OS handoff, which the PCI core caches before any renumbering. Fall back to the current bus number for devices on a root bus, which is never renumbered. While here, return a bool from amdgpu_acpi_vfct_match() so callers read naturally. Acked-by: Alex Deucher Reported-by: Reza Nikzad Chaleshori Closes: https://lore.kernel.org/amd-gfx/20261014080523.186533-1-rezanikzadch@gmail.com/ Fixes: 11c141672045f ("drm/amdgpu: Fix VFCT bus number matching with soft filter") Link: https://patch.msgid.link/20261119-vfct-regression-v8-v8-2-12463194e457@amd.com Signed-off-by: Mario Limonciello Signed-off-by: Alex Deucher (cherry picked from commit 469fd4495bb721615d4b4c8993f015a9a273ab48) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c | 42 +++++++++--------------- 1 file changed, 15 insertions(+), 27 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c index ccb91969b7343d..2603ca60996ad9 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c @@ -436,35 +436,23 @@ static bool amdgpu_read_disabled_bios(struct amdgpu_device *adev) * VFCT entries contain the PCI bus number as recorded during BIOS POST. * On systems where the kernel renumbers PCI buses (e.g. pci=realloc or * resource conflicts), the runtime bus number may differ from the POST - * value. Match by device identity (vendor + device + function) and use - * the bus number as a preference: exact bus match is preferred, but when - * the bus numbers disagree we accept the entry if the device identity - * matches. + * value. Match against the secondary bus number of the upstream bridge + * at FW/OS handoff, which the PCI core caches before any renumbering. * - * Returns: 0 on match, -ENODEV on no match + * Returns: true if @vhdr describes this device, false otherwise */ -static int amdgpu_acpi_vfct_match(struct amdgpu_device *adev, - VFCT_IMAGE_HEADER *vhdr) +static bool amdgpu_acpi_vfct_match(struct amdgpu_device *adev, + VFCT_IMAGE_HEADER *vhdr) { - /* Vendor and device IDs must always match */ - if (vhdr->VendorID != adev->pdev->vendor || - vhdr->DeviceID != adev->pdev->device) - return -ENODEV; - - if (vhdr->PCIDevice != PCI_SLOT(adev->pdev->devfn) || - vhdr->PCIFunction != PCI_FUNC(adev->pdev->devfn)) - return -ENODEV; - - /* Exact bus number match - preferred */ - if (vhdr->PCIBus == adev->pdev->bus->number) - return 0; - - /* Bus mismatch but device identity matches (PCI renumbering case) */ - dev_notice(adev->dev, - "VFCT bus number mismatch: table %u != runtime %u, matching by device identity (vendor 0x%04x device 0x%04x)\n", - vhdr->PCIBus, adev->pdev->bus->number, - adev->pdev->vendor, adev->pdev->device); - return 0; + struct pci_dev *pdev = adev->pdev; + struct pci_dev *bridge = pci_upstream_bridge(pdev); + u8 bus = bridge ? bridge->fw_sec_busnr : pdev->bus->number; + + return vhdr->VendorID == pdev->vendor && + vhdr->DeviceID == pdev->device && + vhdr->PCIBus == bus && + vhdr->PCIDevice == PCI_SLOT(pdev->devfn) && + vhdr->PCIFunction == PCI_FUNC(pdev->devfn); } static bool amdgpu_acpi_vfct_bios(struct amdgpu_device *adev) @@ -503,7 +491,7 @@ static bool amdgpu_acpi_vfct_bios(struct amdgpu_device *adev) } if (vhdr->ImageLength && - !amdgpu_acpi_vfct_match(adev, vhdr)) { + amdgpu_acpi_vfct_match(adev, vhdr)) { adev->bios = kmemdup(&vbios->VbiosContent, vhdr->ImageLength, GFP_KERNEL); From fb864f73e3453bf877dfadd618fec0c64391effd Mon Sep 17 00:00:00 2001 From: Mario Limonciello Date: Thu, 19 Nov 2026 13:21:21 -0600 Subject: [PATCH 1741/2102] drm/radeon: Match VFCT using initial PCI bus number VFCT records the PCI bus number from BIOS POST. The current bus number can change after PCI core renumbers the bus, while accepting a mismatch based only on device identity can select the wrong VFCT image when matching devices are present. Compare against the secondary bus number of the upstream bridge at FW/OS handoff, which the PCI core caches before any renumbering. Fall back to the current bus number for devices on a root bus, which is never renumbered. While here, return a bool from radeon_acpi_vfct_match() so callers read naturally. Acked-by: Alex Deucher Fixes: 4059e2f02c8a ("drm/radeon: Fix VFCT bus number matching with soft filter") Link: https://patch.msgid.link/20261119-vfct-regression-v8-v8-3-12463194e457@amd.com Signed-off-by: Mario Limonciello Signed-off-by: Alex Deucher (cherry picked from commit 5995dac2a023ecfa7dc6e5e777960037734bf4a2) Cc: stable@vger.kernel.org --- drivers/gpu/drm/radeon/radeon_bios.c | 42 ++++++++++------------------ 1 file changed, 15 insertions(+), 27 deletions(-) diff --git a/drivers/gpu/drm/radeon/radeon_bios.c b/drivers/gpu/drm/radeon/radeon_bios.c index 1da6bf1c17ff34..869240588eb310 100644 --- a/drivers/gpu/drm/radeon/radeon_bios.c +++ b/drivers/gpu/drm/radeon/radeon_bios.c @@ -609,35 +609,23 @@ static bool radeon_read_disabled_bios(struct radeon_device *rdev) * VFCT entries contain the PCI bus number as recorded during BIOS POST. * On systems where the kernel renumbers PCI buses (e.g. pci=realloc or * resource conflicts), the runtime bus number may differ from the POST - * value. Match by device identity (vendor + device + function) and use - * the bus number as a preference: exact bus match is preferred, but when - * the bus numbers disagree we accept the entry if the device identity - * matches. + * value. Match against the secondary bus number of the upstream bridge + * at FW/OS handoff, which the PCI core caches before any renumbering. * - * Returns: 0 on match, -ENODEV on no match + * Returns: true if @vhdr describes this device, false otherwise */ -static int radeon_acpi_vfct_match(struct radeon_device *rdev, - VFCT_IMAGE_HEADER *vhdr) +static bool radeon_acpi_vfct_match(struct radeon_device *rdev, + VFCT_IMAGE_HEADER *vhdr) { - /* Vendor and device IDs must always match */ - if (vhdr->VendorID != rdev->pdev->vendor || - vhdr->DeviceID != rdev->pdev->device) - return -ENODEV; - - if (vhdr->PCIDevice != PCI_SLOT(rdev->pdev->devfn) || - vhdr->PCIFunction != PCI_FUNC(rdev->pdev->devfn)) - return -ENODEV; - - /* Exact bus number match - preferred */ - if (vhdr->PCIBus == rdev->pdev->bus->number) - return 0; - - /* Bus mismatch but device identity matches (PCI renumbering case) */ - dev_notice(&rdev->pdev->dev, - "VFCT bus number mismatch: table %u != runtime %u, matching by device identity (vendor 0x%04x device 0x%04x)\n", - vhdr->PCIBus, rdev->pdev->bus->number, - rdev->pdev->vendor, rdev->pdev->device); - return 0; + struct pci_dev *pdev = rdev->pdev; + struct pci_dev *bridge = pci_upstream_bridge(pdev); + u8 bus = bridge ? bridge->fw_sec_busnr : pdev->bus->number; + + return vhdr->VendorID == pdev->vendor && + vhdr->DeviceID == pdev->device && + vhdr->PCIBus == bus && + vhdr->PCIDevice == PCI_SLOT(pdev->devfn) && + vhdr->PCIFunction == PCI_FUNC(pdev->devfn); } static bool radeon_acpi_vfct_bios(struct radeon_device *rdev) @@ -676,7 +664,7 @@ static bool radeon_acpi_vfct_bios(struct radeon_device *rdev) } if (vhdr->ImageLength && - !radeon_acpi_vfct_match(rdev, vhdr)) { + radeon_acpi_vfct_match(rdev, vhdr)) { rdev->bios = kmemdup(&vbios->VbiosContent, vhdr->ImageLength, GFP_KERNEL); From 4731720b3dbc02990a08326afbb7beb0e1dde9f7 Mon Sep 17 00:00:00 2001 From: Perry Yuan Date: Wed, 28 Oct 2026 17:09:11 +0800 Subject: [PATCH 1742/2102] drm/amdkfd: fix units when unmapping a PROT_NONE VMA from GPUs In svm_range_validate_and_map(), start and end are byte addresses while prange->start and prange->last are page numbers. Mixing them makes e >= s false in practice, so a VMA without VM_READ is never unmapped from the GPUs. The bounds also covered the whole request instead of the current VMA. Use the page numbers of the current VMA, [addr, next). Fixes: 0ed704d058ce ("drm/amdkfd: Handle lack of READ permissions in SVM mapping") Signed-off-by: Perry Yuan Reviewed-by: Yifan Zhang Signed-off-by: Alex Deucher (cherry picked from commit f9886bfab9d623012c962598865a0a7273f3eb85) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_svm.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c index 35afc8efca27fd..4df16176e2c342 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c @@ -1871,8 +1871,8 @@ static int svm_range_validate_and_map(struct mm_struct *mm, svm_range_lock(prange); if (vma->vm_flags & VM_WRITE) pr_debug("VM_WRITE without VM_READ is not supported"); - s = max(start, prange->start); - e = min(end, prange->last); + s = max(addr >> PAGE_SHIFT, prange->start); + e = min((next >> PAGE_SHIFT) - 1, prange->last); if (e >= s) r = svm_range_unmap_from_gpus(prange, s, e, prange->bitmap_mapped, From e821744927c984a9dba75c1d78e959ff8374295c Mon Sep 17 00:00:00 2001 From: Michael Strauss Date: Wed, 4 Nov 2026 12:30:30 -0500 Subject: [PATCH 1743/2102] drm/amd/display: Clear OTG_AUTO_FORCE_VSYNC_MODE on OTG disable [WHY] A frame-lock reset trigger sets OTG_AUTO_FORCE_VSYNC_MODE. If the bit is not cleared when the OTG is released, the OTG keeps forcing vsync on every trigger event. When a display stream later reuses that OTG with DRR enabled, each DRR manual trigger forces an early vsync and cuts the frame short. The display then runs above its programmed refresh rate and underflows, leaving the external monitor with no signal. [HOW] Clear OTG_AUTO_FORCE_VSYNC_MODE in the DCN31/314/35 disable_crtc so a released OTG is left clean. Tested-by: Dan Wheeler Reviewed-by: Wayne Lin Cc: Aric Cyr Cc: Mario Limonciello Cc: Alex Deucher Signed-off-by: Michael Strauss Signed-off-by: James Lin Signed-off-by: Alex Deucher (cherry picked from commit 87bd02dc5b98e57fa305081680382c8c3a8ecaf7) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/display/dc/optc/dcn31/dcn31_optc.c | 4 ++++ drivers/gpu/drm/amd/display/dc/optc/dcn314/dcn314_optc.c | 4 ++++ drivers/gpu/drm/amd/display/dc/optc/dcn35/dcn35_optc.c | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/drivers/gpu/drm/amd/display/dc/optc/dcn31/dcn31_optc.c b/drivers/gpu/drm/amd/display/dc/optc/dcn31/dcn31_optc.c index ce9cd32b807aca..7706f5f16a686b 100644 --- a/drivers/gpu/drm/amd/display/dc/optc/dcn31/dcn31_optc.c +++ b/drivers/gpu/drm/amd/display/dc/optc/dcn31/dcn31_optc.c @@ -143,6 +143,10 @@ static bool optc31_disable_crtc(struct timing_generator *optc) 1, 100000); optc1_clear_optc_underflow(optc); + /* a stale frame-lock force-vsync would cut every DRR-triggered frame short on reuse */ + REG_UPDATE(OTG_VERT_SYNC_CONTROL, + OTG_AUTO_FORCE_VSYNC_MODE, 0); + return true; } /* diff --git a/drivers/gpu/drm/amd/display/dc/optc/dcn314/dcn314_optc.c b/drivers/gpu/drm/amd/display/dc/optc/dcn314/dcn314_optc.c index f5faa49680ef8d..5ec70e849cce89 100644 --- a/drivers/gpu/drm/amd/display/dc/optc/dcn314/dcn314_optc.c +++ b/drivers/gpu/drm/amd/display/dc/optc/dcn314/dcn314_optc.c @@ -142,6 +142,10 @@ static bool optc314_disable_crtc(struct timing_generator *optc) OTG_BUSY, 0, 1, 100000); + /* a stale frame-lock force-vsync would cut every DRR-triggered frame short on reuse */ + REG_UPDATE(OTG_VERT_SYNC_CONTROL, + OTG_AUTO_FORCE_VSYNC_MODE, 0); + return true; } diff --git a/drivers/gpu/drm/amd/display/dc/optc/dcn35/dcn35_optc.c b/drivers/gpu/drm/amd/display/dc/optc/dcn35/dcn35_optc.c index 406446e5eae548..b4b4792167dddf 100644 --- a/drivers/gpu/drm/amd/display/dc/optc/dcn35/dcn35_optc.c +++ b/drivers/gpu/drm/amd/display/dc/optc/dcn35/dcn35_optc.c @@ -162,6 +162,10 @@ static bool optc35_disable_crtc(struct timing_generator *optc) optc1_clear_optc_underflow(optc); + /* a stale frame-lock force-vsync would cut every DRR-triggered frame short on reuse */ + REG_UPDATE(OTG_VERT_SYNC_CONTROL, + OTG_AUTO_FORCE_VSYNC_MODE, 0); + return true; } From 44ccd294f3fa7b216a1399e9700464efedd342ff Mon Sep 17 00:00:00 2001 From: Zhikai Zhai Date: Wed, 21 Oct 2026 17:48:12 +0800 Subject: [PATCH 1744/2102] drm/amd/display: Power up eDP when detect link [WHY] Previously we would start the asynchronous detection timer after resuming from S0i3, the sequence for eDP power up when resume from S0i3 is: 1. eDP power up when link enable 2. Timer trigger async detect for eDP 3. The AUPI could read successfully in display detect Currently 1. eDP detection runs from the display detect path 2. AUPI read fail as HPD low when eDP link detect 3. Link enable to power up eDP [HOW] Power up eDP when detect link for aux read. Tested-by: Dan Wheeler Reviewed-by: Wayne Lin Cc: Wenjing Liu Cc: Mario Limonciello Cc: Alex Deucher Signed-off-by: Zhikai Zhai Signed-off-by: James Lin Signed-off-by: Alex Deucher (cherry picked from commit c492494bcd0c8708ddcab0261fcae341318bd196) Cc: stable@vger.kernel.org --- .../gpu/drm/amd/display/dc/link/link_detection.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/amd/display/dc/link/link_detection.c b/drivers/gpu/drm/amd/display/dc/link/link_detection.c index b4546f93af0cc1..386bdb0f2b5d6f 100644 --- a/drivers/gpu/drm/amd/display/dc/link/link_detection.c +++ b/drivers/gpu/drm/amd/display/dc/link/link_detection.c @@ -1127,11 +1127,16 @@ static bool detect_link_and_local_sink(struct dc_link *link, (!link->dc->config.allow_edp_hotplug_detection)) && link->local_sink) { // need to re-write OUI and brightness in resume case - if (link->connector_signal == SIGNAL_TYPE_EDP && - (link->dpcd_sink_ext_caps.bits.oled == 1)) { - dpcd_set_source_specific_data(link); - msleep(post_oui_delay); - set_default_brightness_aux(link); + if (link->connector_signal == SIGNAL_TYPE_EDP) { + if (!link->dc->config.edp_no_power_sequencing) + link->dc->hwss.edp_power_control(link, true); + link->dc->hwss.edp_wait_for_hpd_ready(link, true); + + if (link->dpcd_sink_ext_caps.bits.oled == 1) { + dpcd_set_source_specific_data(link); + msleep(post_oui_delay); + set_default_brightness_aux(link); + } } return true; From 4da6437456f0ccefba9a2dea98ec25a72372eaea Mon Sep 17 00:00:00 2001 From: Ruijing Dong Date: Thu, 19 Nov 2026 22:14:03 -0500 Subject: [PATCH 1745/2102] drm/amdgpu: keep the commit padding when re-emitting submissions Re-emitted submissions are written back to back without the padding amdgpu_ring_commit() added. Pad each one again, as commit did, since some IPs like VCN require every submission to keep that alignment. Fixes: a17ef941212b ("drm/amdgpu: rework ring reset backup and reemit v9") Reviewed-by: Benjamin Cheng Signed-off-by: Ruijing Dong Signed-off-by: Alex Deucher (cherry picked from commit 4d5b42281bf89f334c640e0d7edbb3313d44bb8c) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_fence.c | 7 ++++++- drivers/gpu/drm/amd/amdgpu/amdgpu_ring.c | 25 +++++++++++++++-------- drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h | 1 + 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_fence.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_fence.c index bff2d38f3571ab..18e333e7ffd321 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_fence.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_fence.c @@ -745,7 +745,8 @@ void amdgpu_ring_set_fence_errors_and_reemit(struct amdgpu_ring *ring, return; } ring->reemit = true; - amdgpu_ring_alloc(ring, ring->ring_backup_entries_to_copy); + amdgpu_ring_alloc(ring, ring->ring_backup_entries_to_copy + + (seq - last_seq) * ring->funcs->align_mask); spin_lock_irqsave(&ring->fence_drv.lock, flags); do { last_seq++; @@ -778,6 +779,10 @@ void amdgpu_ring_set_fence_errors_and_reemit(struct amdgpu_ring *ring, amdgpu_ring_write(ring, ring->ring_backup[fence->backup_idx + i]); } + + /* A job fence ends a submission, pad it like commit did */ + if (fence->skip_ib_dw_end_offset) + amdgpu_ring_pad_to_align(ring); } rcu_read_unlock(); } while (last_seq != seq); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.c index 22773454131650..e64ee4eb11f6d2 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.c @@ -142,6 +142,22 @@ void amdgpu_ring_generic_pad_ib(struct amdgpu_ring *ring, struct amdgpu_ib *ib) } } +/** + * amdgpu_ring_pad_to_align - pad the ring to the fetch alignment + * @ring: amdgpu_ring structure holding ring information + */ +void amdgpu_ring_pad_to_align(struct amdgpu_ring *ring) +{ + u32 count; + + count = ring->funcs->align_mask + 1 - + (ring->wptr & ring->funcs->align_mask); + count &= ring->funcs->align_mask; + + if (count != 0) + ring->funcs->insert_nop(ring, count); +} + /** * amdgpu_ring_commit - tell the GPU to execute the new * commands on the ring buffer @@ -153,18 +169,11 @@ void amdgpu_ring_generic_pad_ib(struct amdgpu_ring *ring, struct amdgpu_ib *ib) */ void amdgpu_ring_commit(struct amdgpu_ring *ring) { - uint32_t count; - if (ring->count_dw < 0) drm_err(adev_to_drm(ring->adev), "writing more dwords to the ring than expected!\n"); /* We pad to match fetch size */ - count = ring->funcs->align_mask + 1 - - (ring->wptr & ring->funcs->align_mask); - count &= ring->funcs->align_mask; - - if (count != 0) - ring->funcs->insert_nop(ring, count); + amdgpu_ring_pad_to_align(ring); mb(); amdgpu_ring_set_wptr(ring); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h b/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h index b2040f80b7f29d..6224a9f94826ae 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h @@ -464,6 +464,7 @@ void amdgpu_ring_ib_on_emit_de(struct amdgpu_ring *ring); void amdgpu_ring_insert_nop(struct amdgpu_ring *ring, uint32_t count); void amdgpu_ring_generic_pad_ib(struct amdgpu_ring *ring, struct amdgpu_ib *ib); +void amdgpu_ring_pad_to_align(struct amdgpu_ring *ring); void amdgpu_ring_commit(struct amdgpu_ring *ring); void amdgpu_ring_undo(struct amdgpu_ring *ring); int amdgpu_ring_init(struct amdgpu_device *adev, struct amdgpu_ring *ring, From bdad2ec8a2cec24dd4c5ece8257c0bfcbb67f8b2 Mon Sep 17 00:00:00 2001 From: Harry VanZyllDeJong Date: Fri, 6 Nov 2026 13:23:21 -0500 Subject: [PATCH 1746/2102] drm/amd/display: Honor the Replay stream regeneration wait event [Why] The shared FreeSync Replay inactive mask omits the stream regeneration wait event. Replay can become eligible before the regeneration wait period expires after stream enable. [How] Include the regeneration wait in the inactive mask. Exercise the public event API to verify nominal coasting while waiting and restoration of static-screen coasting after the event clears. Tested-by: Dan Wheeler Reviewed-by: Wayne Lin Cc: Leon Huang Cc: Mario Limonciello Cc: Alex Deucher Signed-off-by: Harry VanZyllDeJong Signed-off-by: James Lin Signed-off-by: Alex Deucher (cherry picked from commit db4fc9cdb52e678dea1c07676f16e3b6fa8a865a) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/display/modules/power/power_replay.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/gpu/drm/amd/display/modules/power/power_replay.c b/drivers/gpu/drm/amd/display/modules/power/power_replay.c index 666585b7e00c38..8e2fab1db13ca8 100644 --- a/drivers/gpu/drm/amd/display/modules/power/power_replay.c +++ b/drivers/gpu/drm/amd/display/modules/power/power_replay.c @@ -232,6 +232,7 @@ static bool mod_power_update_replay_active_status(unsigned int active_replay_eve replay_event_sleep_resume | replay_event_disable_in_AC | replay_event_disable_replay_while_detect_display | + replay_event_waiting_stream_regen | replay_event_infopacket | replay_event_crc_window_active)) return false; From a6a501d17fe08b20fd13f097577182400c47bac2 Mon Sep 17 00:00:00 2001 From: Nicholas Kazlauskas Date: Mon, 9 Nov 2026 10:33:46 -0500 Subject: [PATCH 1747/2102] drm/amd/display: Skip DSC padding borrow estimate for zero padding [Why] For non-DSC streams the DSC padding is zero. This causes the borrow-mode estimate to always borrow instead of falling back to FRL_BORROW_MODE_NONE. [How] Return early in update_borrow_mode_from_dsc_padding() when both hactive and htotal padding are zero. Tested-by: Dan Wheeler Reviewed-by: Wayne Lin Cc: Aric Cyr Cc: Mario Limonciello Cc: Alex Deucher Signed-off-by: Nicholas Kazlauskas Signed-off-by: James Lin Signed-off-by: Alex Deucher (cherry picked from commit 17d6591c4d844456ead2e3c42778c666cf52d784) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/display/dc/link/protocols/link_hdmi_frl.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/gpu/drm/amd/display/dc/link/protocols/link_hdmi_frl.c b/drivers/gpu/drm/amd/display/dc/link/protocols/link_hdmi_frl.c index 960f18fe275b23..27d413c2bdd6fc 100644 --- a/drivers/gpu/drm/amd/display/dc/link/protocols/link_hdmi_frl.c +++ b/drivers/gpu/drm/amd/display/dc/link/protocols/link_hdmi_frl.c @@ -1159,6 +1159,10 @@ static void update_borrow_mode_from_dsc_padding(struct dsc_padding_params *dsc_p uint32_t h_blank = timing->h_total - h_active; struct frl_borrow_params *borrow_params = &frl_link_settings->borrow_params; + if (dsc_padding_params->dsc_hactive_padding == 0 && + dsc_padding_params->dsc_htotal_padding == 0) + return; + borrow_params->borrow_mode = frl_modify_borrow_mode_for_dsc_padding(timing->pix_clk_100hz, h_active, h_active + dsc_padding_params->dsc_hactive_padding, From 7e3c6322940e13f6630d7cfdc5834f4e69cff4f7 Mon Sep 17 00:00:00 2001 From: Harry Wentland Date: Fri, 13 Nov 2026 10:42:30 -0500 Subject: [PATCH 1748/2102] drm/amd/display: Add RGBA8888 surface pixel format support [why] amdgpu_dm advertises DRM_FORMAT_RGBA8888 for its planes, but DC has no matching surface pixel format, so fill_dc_plane_info_and_addr() rejects the format with -EINVAL. KWin modesets then fail with "Unsupported screen format RA24 little-endian". [how] - Add SURFACE_PIXEL_FORMAT_GRPH_RGBA8888 to the surface_pixel_format enum. - Map DRM_FORMAT_RGBA8888 to the new format in amdgpu_dm. - Program the dedicated RGBA8888 encoding (value 9) in HUBP and DPP for all DCN generations. Unlike ABGR8888, there is no red/blue crossbar swap. - Treat RGBA8888 as a 32bpp graphics format in bandwidth, bytes-per-pixel, DCC, and format-class helpers, the same as ARGB8888. Link: https://gitlab.freedesktop.org/drm/amd/-/issues/5339 Tested-by: Dan Wheeler Reviewed-by: Wayne Lin Cc: Nicholas Kazlauskas Signed-off-by: Harry Wentland Signed-off-by: James Lin Signed-off-by: Alex Deucher (cherry picked from commit e111f3c7258d83c9b5f4851a7006a9afe3462f6e) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c | 3 +++ drivers/gpu/drm/amd/display/dc/basics/dce_calcs.c | 2 ++ drivers/gpu/drm/amd/display/dc/core/dc_resource.c | 4 ++++ drivers/gpu/drm/amd/display/dc/dc_hw_types.h | 2 ++ drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c | 1 + drivers/gpu/drm/amd/display/dc/dce110/dce110_mem_input_v.c | 1 + drivers/gpu/drm/amd/display/dc/dml/calcs/dcn_calcs.c | 1 + drivers/gpu/drm/amd/display/dc/dpp/dcn10/dcn10_dpp.c | 3 +++ drivers/gpu/drm/amd/display/dc/dpp/dcn20/dcn20_dpp.c | 3 +++ drivers/gpu/drm/amd/display/dc/dpp/dcn201/dcn201_dpp.c | 3 +++ drivers/gpu/drm/amd/display/dc/dpp/dcn30/dcn30_dpp.c | 3 +++ drivers/gpu/drm/amd/display/dc/dpp/dcn401/dcn401_dpp.c | 3 +++ drivers/gpu/drm/amd/display/dc/dpp/dcn42/dcn42_dpp.c | 3 +++ drivers/gpu/drm/amd/display/dc/dpp/dcn50/dcn50_dpp.c | 3 +++ drivers/gpu/drm/amd/display/dc/dpp/dcn60/dcn60_dpp.c | 3 +++ drivers/gpu/drm/amd/display/dc/hubbub/dcn10/dcn10_hubbub.c | 1 + drivers/gpu/drm/amd/display/dc/hubbub/dcn20/dcn20_hubbub.c | 1 + drivers/gpu/drm/amd/display/dc/hubbub/dcn401/dcn401_hubbub.c | 1 + drivers/gpu/drm/amd/display/dc/hubp/dcn10/dcn10_hubp.c | 4 ++++ drivers/gpu/drm/amd/display/dc/hubp/dcn20/dcn20_hubp.c | 4 ++++ drivers/gpu/drm/amd/display/dc/hubp/dcn35/dcn35_hubp.c | 4 ++++ drivers/gpu/drm/amd/display/dc/hubp/dcn42/dcn42_hubp.c | 4 ++++ drivers/gpu/drm/amd/display/dc/hubp/dcn50/dcn50_hubp.c | 4 ++++ drivers/gpu/drm/amd/display/dc/hwss/dce/dce_hwseq.c | 1 + drivers/gpu/drm/amd/display/dc/hwss/dce110/dce110_hwseq.c | 1 + 25 files changed, 63 insertions(+) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c index 5d1b010bec9bfb..67bbf95a8c7ab7 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c @@ -3018,6 +3018,9 @@ fill_dc_plane_info_and_addr(struct amdgpu_device *adev, case DRM_FORMAT_ARGB8888: plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888; break; + case DRM_FORMAT_RGBA8888: + plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGBA8888; + break; case DRM_FORMAT_XRGB2101010: case DRM_FORMAT_ARGB2101010: plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010; diff --git a/drivers/gpu/drm/amd/display/dc/basics/dce_calcs.c b/drivers/gpu/drm/amd/display/dc/basics/dce_calcs.c index 1b8e843020d6c5..1ff1a6c23c65c6 100644 --- a/drivers/gpu/drm/amd/display/dc/basics/dce_calcs.c +++ b/drivers/gpu/drm/amd/display/dc/basics/dce_calcs.c @@ -2853,6 +2853,7 @@ static void populate_initial_data( break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: @@ -2957,6 +2958,7 @@ static void populate_initial_data( break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/core/dc_resource.c b/drivers/gpu/drm/amd/display/dc/core/dc_resource.c index 187486d978da65..225dfada44a5a2 100644 --- a/drivers/gpu/drm/amd/display/dc/core/dc_resource.c +++ b/drivers/gpu/drm/amd/display/dc/core/dc_resource.c @@ -808,6 +808,9 @@ static enum dc_pixel_format convert_pixel_format_to_dalsurface( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: dal_pixel_format = PIXEL_FORMAT_ARGB8888; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + dal_pixel_format = PIXEL_FORMAT_ARGB8888; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: dal_pixel_format = PIXEL_FORMAT_ARGB2101010; break; @@ -5831,6 +5834,7 @@ unsigned int resource_pixel_format_to_bpp(enum surface_pixel_format format) return 16; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/dc_hw_types.h b/drivers/gpu/drm/amd/display/dc/dc_hw_types.h index baf6091bb52d05..25e538db02937d 100644 --- a/drivers/gpu/drm/amd/display/dc/dc_hw_types.h +++ b/drivers/gpu/drm/amd/display/dc/dc_hw_types.h @@ -176,6 +176,8 @@ enum surface_pixel_format { SURFACE_PIXEL_FORMAT_GRPH_ARGB8888, /*32 bpp swaped*/ SURFACE_PIXEL_FORMAT_GRPH_ABGR8888, + /*32 bpp, alpha in LSB*/ + SURFACE_PIXEL_FORMAT_GRPH_RGBA8888, SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010, /*swaped*/ diff --git a/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c b/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c index 168c2d0a5eaa75..08cde29a4a7a17 100644 --- a/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c +++ b/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c @@ -593,6 +593,7 @@ static void program_grph_pixel_format( break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: grph_depth = 2; grph_format = 0; break; diff --git a/drivers/gpu/drm/amd/display/dc/dce110/dce110_mem_input_v.c b/drivers/gpu/drm/amd/display/dc/dce110/dce110_mem_input_v.c index 095869912c091f..9d781d12d66959 100644 --- a/drivers/gpu/drm/amd/display/dc/dce110/dce110_mem_input_v.c +++ b/drivers/gpu/drm/amd/display/dc/dce110/dce110_mem_input_v.c @@ -381,6 +381,7 @@ static void program_pixel_format( break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: grph_depth = 2; grph_format = 0; break; diff --git a/drivers/gpu/drm/amd/display/dc/dml/calcs/dcn_calcs.c b/drivers/gpu/drm/amd/display/dc/dml/calcs/dcn_calcs.c index 2ad4a263568326..ec25a76dc3f11d 100644 --- a/drivers/gpu/drm/amd/display/dc/dml/calcs/dcn_calcs.c +++ b/drivers/gpu/drm/amd/display/dc/dml/calcs/dcn_calcs.c @@ -231,6 +231,7 @@ static enum dcn_bw_defs tl_pixel_format_to_bw_defs(enum surface_pixel_format for return dcn_bw_rgb_sub_16; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn10/dcn10_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn10/dcn10_dpp.c index ef605e0a75e389..ef9f0bcdd22b19 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn10/dcn10_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn10/dcn10_dpp.c @@ -342,6 +342,9 @@ void dpp1_cnv_setup ( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn20/dcn20_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn20/dcn20_dpp.c index 8d50007909040b..dde02ea4016ddf 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn20/dcn20_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn20/dcn20_dpp.c @@ -141,6 +141,9 @@ static void dpp2_cnv_setup ( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn201/dcn201_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn201/dcn201_dpp.c index d78ab3ffd95dbc..e120e6f10c85da 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn201/dcn201_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn201/dcn201_dpp.c @@ -85,6 +85,9 @@ static void dpp201_cnv_setup( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn30/dcn30_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn30/dcn30_dpp.c index 2ebc738c37f286..6e8744e7d26059 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn30/dcn30_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn30/dcn30_dpp.c @@ -263,6 +263,9 @@ void dpp3_cnv_setup ( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn401/dcn401_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn401/dcn401_dpp.c index 8e0fa7be34ee73..c24c457f29354c 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn401/dcn401_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn401/dcn401_dpp.c @@ -97,6 +97,9 @@ void dpp401_dpp_setup( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn42/dcn42_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn42/dcn42_dpp.c index eed86f5ae731bf..084b659958f737 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn42/dcn42_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn42/dcn42_dpp.c @@ -157,6 +157,9 @@ static void dpp42_dpp_setup( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn50/dcn50_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn50/dcn50_dpp.c index 38739ed048fae8..865305995ebc71 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn50/dcn50_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn50/dcn50_dpp.c @@ -129,6 +129,9 @@ void dpp50_dpp_setup( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn60/dcn60_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn60/dcn60_dpp.c index be2effb14fc3fe..aa59fe2c6954b5 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn60/dcn60_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn60/dcn60_dpp.c @@ -62,6 +62,9 @@ void dpp60_dpp_setup( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/hubbub/dcn10/dcn10_hubbub.c b/drivers/gpu/drm/amd/display/dc/hubbub/dcn10/dcn10_hubbub.c index 4e33648f74bbef..507b8e8a7077ee 100644 --- a/drivers/gpu/drm/amd/display/dc/hubbub/dcn10/dcn10_hubbub.c +++ b/drivers/gpu/drm/amd/display/dc/hubbub/dcn10/dcn10_hubbub.c @@ -760,6 +760,7 @@ static bool hubbub1_dcc_support_pixel_format( return true; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: *bytes_per_element = 4; diff --git a/drivers/gpu/drm/amd/display/dc/hubbub/dcn20/dcn20_hubbub.c b/drivers/gpu/drm/amd/display/dc/hubbub/dcn20/dcn20_hubbub.c index e5b55fe502ca6b..94c60c6287ce49 100644 --- a/drivers/gpu/drm/amd/display/dc/hubbub/dcn20/dcn20_hubbub.c +++ b/drivers/gpu/drm/amd/display/dc/hubbub/dcn20/dcn20_hubbub.c @@ -147,6 +147,7 @@ bool hubbub2_dcc_support_pixel_format( return true; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_RGB111110_FIX: diff --git a/drivers/gpu/drm/amd/display/dc/hubbub/dcn401/dcn401_hubbub.c b/drivers/gpu/drm/amd/display/dc/hubbub/dcn401/dcn401_hubbub.c index 957e8f5a647532..7fae4df3252a94 100644 --- a/drivers/gpu/drm/amd/display/dc/hubbub/dcn401/dcn401_hubbub.c +++ b/drivers/gpu/drm/amd/display/dc/hubbub/dcn401/dcn401_hubbub.c @@ -671,6 +671,7 @@ bool hubbub401_dcc_support_pixel_format( return true; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hubp/dcn10/dcn10_hubp.c b/drivers/gpu/drm/amd/display/dc/hubp/dcn10/dcn10_hubp.c index 2a4be0c7a724b5..4723a390297ceb 100644 --- a/drivers/gpu/drm/amd/display/dc/hubp/dcn10/dcn10_hubp.c +++ b/drivers/gpu/drm/amd/display/dc/hubp/dcn10/dcn10_hubp.c @@ -272,6 +272,10 @@ void hubp1_program_pixel_format( REG_UPDATE(DCSURF_SURFACE_CONFIG, SURFACE_PIXEL_FORMAT, 8); break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + REG_UPDATE(DCSURF_SURFACE_CONFIG, + SURFACE_PIXEL_FORMAT, 9); + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hubp/dcn20/dcn20_hubp.c b/drivers/gpu/drm/amd/display/dc/hubp/dcn20/dcn20_hubp.c index 79a42981406179..e82bb43be00118 100644 --- a/drivers/gpu/drm/amd/display/dc/hubp/dcn20/dcn20_hubp.c +++ b/drivers/gpu/drm/amd/display/dc/hubp/dcn20/dcn20_hubp.c @@ -473,6 +473,10 @@ void hubp2_program_pixel_format( REG_UPDATE(DCSURF_SURFACE_CONFIG, SURFACE_PIXEL_FORMAT, 8); break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + REG_UPDATE(DCSURF_SURFACE_CONFIG, + SURFACE_PIXEL_FORMAT, 9); + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hubp/dcn35/dcn35_hubp.c b/drivers/gpu/drm/amd/display/dc/hubp/dcn35/dcn35_hubp.c index c879f4901c7df8..69b5d41c959e74 100644 --- a/drivers/gpu/drm/amd/display/dc/hubp/dcn35/dcn35_hubp.c +++ b/drivers/gpu/drm/amd/display/dc/hubp/dcn35/dcn35_hubp.c @@ -94,6 +94,10 @@ void hubp35_program_pixel_format( REG_UPDATE(DCSURF_SURFACE_CONFIG, SURFACE_PIXEL_FORMAT, 8); break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + REG_UPDATE(DCSURF_SURFACE_CONFIG, + SURFACE_PIXEL_FORMAT, 9); + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hubp/dcn42/dcn42_hubp.c b/drivers/gpu/drm/amd/display/dc/hubp/dcn42/dcn42_hubp.c index 0c8a23cef1e0bd..b70fc7c1c80d7d 100644 --- a/drivers/gpu/drm/amd/display/dc/hubp/dcn42/dcn42_hubp.c +++ b/drivers/gpu/drm/amd/display/dc/hubp/dcn42/dcn42_hubp.c @@ -78,6 +78,10 @@ static void hubp42_program_pixel_format( REG_UPDATE(DCSURF_SURFACE_CONFIG, SURFACE_PIXEL_FORMAT, 8); break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + REG_UPDATE(DCSURF_SURFACE_CONFIG, + SURFACE_PIXEL_FORMAT, 9); + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hubp/dcn50/dcn50_hubp.c b/drivers/gpu/drm/amd/display/dc/hubp/dcn50/dcn50_hubp.c index ba86e30b118040..af3ffb31daf221 100644 --- a/drivers/gpu/drm/amd/display/dc/hubp/dcn50/dcn50_hubp.c +++ b/drivers/gpu/drm/amd/display/dc/hubp/dcn50/dcn50_hubp.c @@ -306,6 +306,10 @@ static void hubp50_program_pixel_format( REG_UPDATE(DCSURF_SURFACE_CONFIG, SURFACE_PIXEL_FORMAT, 8); break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + REG_UPDATE(DCSURF_SURFACE_CONFIG, + SURFACE_PIXEL_FORMAT, 9); + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dce/dce_hwseq.c b/drivers/gpu/drm/amd/display/dc/hwss/dce/dce_hwseq.c index 0f44577572fbef..9b8d4d1a2cbe28 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dce/dce_hwseq.c +++ b/drivers/gpu/drm/amd/display/dc/hwss/dce/dce_hwseq.c @@ -228,6 +228,7 @@ bool dce_use_lut(enum surface_pixel_format format) switch (format) { case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: return true; default: return false; diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dce110/dce110_hwseq.c b/drivers/gpu/drm/amd/display/dc/hwss/dce110/dce110_hwseq.c index 7b3aa02dda63b9..8667252fd2b0fb 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dce110/dce110_hwseq.c +++ b/drivers/gpu/drm/amd/display/dc/hwss/dce110/dce110_hwseq.c @@ -265,6 +265,7 @@ static void dce110_prescale_params(struct ipp_prescale_params *prescale_params, break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: prescale_params->scale = 0x2020; break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: From 3024a6cb596a5ee5303d8516af8a13260b4a412a Mon Sep 17 00:00:00 2001 From: Harry Wentland Date: Fri, 13 Nov 2026 10:42:30 -0500 Subject: [PATCH 1749/2102] drm/amd/display: Fix DCE crossbar for RGBA8888 surface format [why] DCE unpacks all 32bpp graphics formats as ARGB and has no native alpha-in-LSB encoding. Channel reordering is done only through the GRPH_SWAP_CNTL crossbar, which programmed just the red and blue selects. RGBA8888 was therefore scanned out with alpha in the MSB. [how] - Program all four GRPH_SWAP_CNTL crossbar selects (red, green, blue, alpha) in program_grph_pixel_format(). - Keep the existing R/B swap for ABGR formats. - Add RGBA8888 with the mapping R<-A, G<-R, B<-G, A<-B. - Add the GRPH_GREEN_CROSSBAR and GRPH_ALPHA_CROSSBAR fields to the DCP register mask and field lists. Closes: https://gitlab.freedesktop.org/drm/amd/-/issues/5339 Tested-by: Dan Wheeler Reviewed-by: Wayne Lin Cc: Nicholas Kazlauskas Signed-off-by: Harry Wentland Signed-off-by: James Lin Signed-off-by: Alex Deucher (cherry picked from commit e7ea5fde5017045794a3c91ccc7514605adb2a4a) Cc: stable@vger.kernel.org --- .../drm/amd/display/dc/dce/dce_mem_input.c | 41 +++++++++++++------ .../drm/amd/display/dc/dce/dce_mem_input.h | 6 +++ 2 files changed, 34 insertions(+), 13 deletions(-) diff --git a/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c b/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c index 08cde29a4a7a17..4f1b8b2750d977 100644 --- a/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c +++ b/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c @@ -558,25 +558,40 @@ static void program_grph_pixel_format( struct dce_mem_input *dce_mi, enum surface_pixel_format format) { - uint32_t red_xbar = 0, blue_xbar = 0; /* no swap */ + /* Crossbar per output channel: 0 R, 1 G, 2 B, 3 A source (see + * DCP_GRPH_*_CROSSBAR in the enum headers). DCE unpacks all 32bpp + * as ARGB, so alpha-in-LSB layouts are reordered via the crossbar. + */ + uint32_t red_xbar = 0, green_xbar = 0, blue_xbar = 0, alpha_xbar = 0; uint32_t grph_depth = 0, grph_format = 0; uint32_t sign = 0, floating = 0; - if (format == SURFACE_PIXEL_FORMAT_GRPH_ABGR8888 || - /*todo: doesn't look like we handle BGRA here, - * should problem swap endian*/ - format == SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010 || - format == SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS || - format == SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616 || - format == SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F) { - /* ABGR formats */ - red_xbar = 2; - blue_xbar = 2; + switch (format) { + case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: + case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: + case SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616: + case SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F: + /* ABGR: swap R and B */ + red_xbar = 2; /* R from B */ + blue_xbar = 2; /* B from R */ + break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + /* rotate ARGB -> RGBA */ + red_xbar = 3; /* R from A */ + green_xbar = 3; /* G from R */ + blue_xbar = 3; /* B from G */ + alpha_xbar = 3; /* A from B */ + break; + default: + break; } - REG_SET_2(GRPH_SWAP_CNTL, 0, + REG_SET_4(GRPH_SWAP_CNTL, 0, GRPH_RED_CROSSBAR, red_xbar, - GRPH_BLUE_CROSSBAR, blue_xbar); + GRPH_GREEN_CROSSBAR, green_xbar, + GRPH_BLUE_CROSSBAR, blue_xbar, + GRPH_ALPHA_CROSSBAR, alpha_xbar); switch (format) { case SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS: diff --git a/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.h b/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.h index e34e445a40132d..a593842ee87960 100644 --- a/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.h +++ b/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.h @@ -189,7 +189,9 @@ struct dce_mem_input_registers { SFB(blk, GRPH_PITCH, GRPH_PITCH, mask_sh),\ SFB(blk, HW_ROTATION, GRPH_ROTATION_ANGLE, mask_sh),\ SFB(blk, GRPH_SWAP_CNTL, GRPH_RED_CROSSBAR, mask_sh),\ + SFB(blk, GRPH_SWAP_CNTL, GRPH_GREEN_CROSSBAR, mask_sh),\ SFB(blk, GRPH_SWAP_CNTL, GRPH_BLUE_CROSSBAR, mask_sh),\ + SFB(blk, GRPH_SWAP_CNTL, GRPH_ALPHA_CROSSBAR, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_SELECT, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_R_SIGN, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_G_SIGN, mask_sh),\ @@ -213,7 +215,9 @@ struct dce_mem_input_registers { SFB(blk, GRPH_Y_END, GRPH_Y_END, mask_sh),\ SFB(blk, GRPH_PITCH, GRPH_PITCH, mask_sh),\ SFB(blk, GRPH_SWAP_CNTL, GRPH_RED_CROSSBAR, mask_sh),\ + SFB(blk, GRPH_SWAP_CNTL, GRPH_GREEN_CROSSBAR, mask_sh),\ SFB(blk, GRPH_SWAP_CNTL, GRPH_BLUE_CROSSBAR, mask_sh),\ + SFB(blk, GRPH_SWAP_CNTL, GRPH_ALPHA_CROSSBAR, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_SELECT, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_R_SIGN, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_G_SIGN, mask_sh),\ @@ -344,7 +348,9 @@ struct dce_mem_input_registers { type GRPH_PITCH; \ type GRPH_ROTATION_ANGLE; \ type GRPH_RED_CROSSBAR; \ + type GRPH_GREEN_CROSSBAR; \ type GRPH_BLUE_CROSSBAR; \ + type GRPH_ALPHA_CROSSBAR; \ type GRPH_PRESCALE_SELECT; \ type GRPH_PRESCALE_R_SIGN; \ type GRPH_PRESCALE_G_SIGN; \ From 85071c568b1630dc1fe78e35a051c587c45eca4d Mon Sep 17 00:00:00 2001 From: Felix Kuehling Date: Tue, 17 Nov 2026 16:21:50 -0500 Subject: [PATCH 1750/2102] drm/amdkfd: Fix context ID cleanup after failures If secondary context ID allocation fails, the context ID remains 0. Make that distinguishable from a valid context ID to avoid double-freeing context IDs. Fixes: fac682a1d1af ("amdkfd: identify a secondary kfd process by its id") Signed-off-by: Felix Kuehling Reviewed-by: Zhu Lingshan Signed-off-by: Alex Deucher (cherry picked from commit 36df098242e1350fd342b9066a78bd70971a3f4d) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_priv.h | 2 +- drivers/gpu/drm/amd/amdkfd/kfd_process.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h index a7b98a8b8e31ee..70d67f9d8cd757 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h +++ b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h @@ -1084,7 +1084,7 @@ struct kfd_process { #define KFD_PROCESS_TABLE_SIZE 8 /* bits: 256 entries */ #define KFD_CONTEXT_ID_PRIMARY 0xFFFF -#define KFD_CONTEXT_ID_MIN 0 +#define KFD_CONTEXT_ID_MIN 1 extern DECLARE_HASHTABLE(kfd_processes_table, KFD_PROCESS_TABLE_SIZE); extern struct srcu_struct kfd_processes_srcu; diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_process.c b/drivers/gpu/drm/amd/amdkfd/kfd_process.c index 46f70ed1d551f5..48f9eab1209d37 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_process.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_process.c @@ -950,7 +950,8 @@ static void kfd_process_free_id(struct kfd_process *process) { struct kfd_process *primary_process; - if (process->context_id == KFD_CONTEXT_ID_PRIMARY) + if (process->context_id == KFD_CONTEXT_ID_PRIMARY || + process->context_id < KFD_CONTEXT_ID_MIN) return; primary_process = kfd_lookup_process_by_mm(process->lead_thread->mm); @@ -1772,7 +1773,6 @@ struct kfd_process *create_process(const struct task_struct *thread, bool primar return process; err_alloc_id: - kfd_process_free_id(process); err_register_notifier: /* * The process is already in kfd_processes_table, so find_process() From d305cb6d999161fd0f8058a48a7b727f9d8b5a58 Mon Sep 17 00:00:00 2001 From: Caden Chien Date: Tue, 17 Nov 2026 10:34:45 +0800 Subject: [PATCH 1751/2102] drm/amdgpu/vpe: align with reg read permission As register VPEC_F32_CNTL could be unreadable, we hardcode the default value instead of reading it. Signed-off-by: Caden Chien Acked-by: Alex Deucher Signed-off-by: Alex Deucher (cherry picked from commit 456b0ec278ff81333cbc5e7b207573df21843b01) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c | 3 ++- drivers/gpu/drm/amd/amdgpu/vpe_v3_0.c | 3 ++- drivers/gpu/drm/amd/amdgpu/vpe_v6_1.c | 4 +++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c b/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c index cefb8d739faf86..9367ffe0c7ad0d 100644 --- a/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c @@ -36,6 +36,7 @@ MODULE_FIRMWARE("amdgpu/vpe_2_0_0_p.bin"); MODULE_FIRMWARE("amdgpu/vpe_2_2_0.bin"); #define VPE_THREAD1_UCODE_OFFSET 0x8000 +#define regVPEC_F32_CNTL_DEFAULT 0x08084001 static uint32_t vpe_v2_0_get_reg_offset(struct amdgpu_vpe *vpe, uint32_t inst, uint32_t offset) { @@ -82,7 +83,7 @@ static int vpe_v2_0_load_microcode(struct amdgpu_vpe *vpe) if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) { f32_offset = vpe_get_reg_offset(vpe, 0, regVPEC_F32_CNTL); - f32_cntl = RREG32(f32_offset); + f32_cntl = regVPEC_F32_CNTL_DEFAULT; f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, HALT, 0); f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, TH1_RESET, 0); diff --git a/drivers/gpu/drm/amd/amdgpu/vpe_v3_0.c b/drivers/gpu/drm/amd/amdgpu/vpe_v3_0.c index 9077ae138d2a36..ca3b27e762517a 100644 --- a/drivers/gpu/drm/amd/amdgpu/vpe_v3_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vpe_v3_0.c @@ -34,6 +34,7 @@ MODULE_FIRMWARE("amdgpu/vpe_3_0_0.bin"); MODULE_FIRMWARE("amdgpu/vpe_3_0_1.bin"); #define VPE_THREAD1_UCODE_OFFSET 0x8000 +#define regVPEC_F32_CNTL_DEFAULT 0x08084001 static uint32_t vpe_v3_0_get_reg_offset(struct amdgpu_vpe *vpe, uint32_t inst, uint32_t offset) { @@ -80,7 +81,7 @@ static int vpe_v3_0_load_microcode(struct amdgpu_vpe *vpe) if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) { f32_offset = vpe_get_reg_offset(vpe, 0, regVPEC_F32_CNTL); - f32_cntl = RREG32(f32_offset); + f32_cntl = regVPEC_F32_CNTL_DEFAULT; f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, HALT, 0); f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, TH1_RESET, 0); diff --git a/drivers/gpu/drm/amd/amdgpu/vpe_v6_1.c b/drivers/gpu/drm/amd/amdgpu/vpe_v6_1.c index 45876883bbf373..c758f7385fac61 100644 --- a/drivers/gpu/drm/amd/amdgpu/vpe_v6_1.c +++ b/drivers/gpu/drm/amd/amdgpu/vpe_v6_1.c @@ -61,6 +61,8 @@ MODULE_FIRMWARE("amdgpu/vpe_6_1_3.bin"); #define regVPEC_PUB_DUMMY2_6_1_1 0x004c #define regVPEC_PUB_DUMMY2_6_1_1_BASE_IDX 0 +#define regVPEC_F32_CNTL_DEFAULT 0x08084001 + static uint32_t vpe_v6_1_get_reg_offset(struct amdgpu_vpe *vpe, uint32_t inst, uint32_t offset) { uint32_t base; @@ -159,7 +161,7 @@ static int vpe_v6_1_load_microcode(struct amdgpu_vpe *vpe) uint32_t f32_offset, f32_cntl; f32_offset = vpe_get_reg_offset(vpe, 0, regVPEC_F32_CNTL); - f32_cntl = RREG32(f32_offset); + f32_cntl = regVPEC_F32_CNTL_DEFAULT; f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, HALT, 0); f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, TH1_RESET, 0); From affd5345aa4fbda5cc51c5be64958a0dafe851c4 Mon Sep 17 00:00:00 2001 From: Xiaogang Chen Date: Wed, 18 Nov 2026 16:42:30 -0600 Subject: [PATCH 1752/2102] drm/amdkfd: Fix a race issue at svm_migrate_copy_to_ram() error path The destination pages were freed while SDMA copies queued earlier could still be writing into them, and while they were still DMA mapped. The mappings were only removed later by the caller's svm_range_dma_unmap_dev(). With swiotlb, the BIDIRECTIONAL unmap copies the bounce buffer back into a page that may already be reused. With an IOMMU, the GPU still has a valid bus address that points at a page now maybe owned by another user. Any SDMA write still in flight, corrupts that page. So, wait on the fence first, then dma unmap before release buffer. Signed-off-by: Xiaogang Chen Reviewed-by: Philip Yang Signed-off-by: Alex Deucher (cherry picked from commit bb85fb52e8a0dba2483dc57d61e6c2789c43f2c0) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_migrate.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c index 1eb92ac6eb058c..d60f486705acb6 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c @@ -726,6 +726,17 @@ svm_migrate_copy_to_ram(struct amdgpu_device *adev, struct svm_range *prange, put_page(dpage); } + /* + * Copies queued before the failure may still be writing into + * the destination pages. Wait for the last SDMA fence (copies + * on the entity complete in order), then remove the device DMA + * mappings, before the pages go back to the allocator. + */ + if (*mfence) { + dma_fence_wait(*mfence, false); + dma_fence_put(*mfence); + } + /* release previous allocated sys pages and unmap dma address */ while (i--) { @@ -834,11 +845,12 @@ svm_migrate_vma_to_ram(struct kfd_node *node, struct svm_range *prange, mpages = svm_migrate_successful_pages(&migrate); pr_debug("migrated/collected/requested 0x%lx/0x%lx/0x%lx\n", mpages, cpages, migrate.npages); - - svm_migrate_copy_done(adev, mfence); + if (!r) + svm_migrate_copy_done(adev, mfence); migrate_vma_finalize(&migrate); - svm_range_dma_unmap_dev(adev->dev, scratch, 0, npages); + if (!r) + svm_range_dma_unmap_dev(adev->dev, scratch, 0, npages); out_free: kvfree(buf); From e88805eec2975dccf772d77c33c12da08b5305cb Mon Sep 17 00:00:00 2001 From: Xiaogang Chen Date: Wed, 18 Nov 2026 16:50:05 -0600 Subject: [PATCH 1753/2102] drm/amdkfd: Swap order of svm_range_dma_unmap_dev and migrate_vma_finalize svm_migrate_vma_to_vram() on success: migrate_vma_finalize() releases the old system-RAM source pages. Only after that they are DMA-unmapped. svm_migrate_vma_to_ram() for slots that failed to migrate: finalize frees the newly allocated dpages, and the unmap comes afterwards. Every mapping uses DMA_BIDIRECTIONAL. With swiotlb, that kind of unmap copies the bounce buffer back into the original page, and by wthen the page may belong to someone else. With an IOMMU, the IOVA stays valid for a short window after the page is freed. During the window GPU may write into the pages that may belong to someone else. So, swap svm_range_dma_unmap_dev and migrate_vma_finalize at both migration direction to make dma unmap happen before sys ram pages got released. Signed-off-by: Xiaogang Chen Reviewed-by: Philip Yang Signed-off-by: Alex Deucher (cherry picked from commit 9129b06b4721b4bc96db3b0fb92bdc24f0360501) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_migrate.c | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c index d60f486705acb6..18652ecc0eb9fa 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c @@ -504,14 +504,13 @@ svm_migrate_vma_to_vram(struct kfd_node *node, struct svm_range *prange, migrate_vma_pages(&migrate); svm_migrate_copy_done(adev, mfence); + svm_range_dma_unmap_dev(adev->dev, scratch, 0, npages); migrate_vma_finalize(&migrate); mpages = svm_migrate_successful_pages(&migrate); pr_debug("migrated/collected/requested 0x%lx/0x%lx/0x%lx\n", mpages, cpages, migrate.npages); - svm_range_dma_unmap_dev(adev->dev, scratch, 0, npages); - out_free: kvfree(buf); kfd_smi_event_migration_end(node, p->lead_thread, @@ -845,12 +844,12 @@ svm_migrate_vma_to_ram(struct kfd_node *node, struct svm_range *prange, mpages = svm_migrate_successful_pages(&migrate); pr_debug("migrated/collected/requested 0x%lx/0x%lx/0x%lx\n", mpages, cpages, migrate.npages); - if (!r) - svm_migrate_copy_done(adev, mfence); - migrate_vma_finalize(&migrate); - if (!r) + if (!r) { + svm_migrate_copy_done(adev, mfence); svm_range_dma_unmap_dev(adev->dev, scratch, 0, npages); + } + migrate_vma_finalize(&migrate); out_free: kvfree(buf); From 42f3979973a766042ae88df368c9b1764d234017 Mon Sep 17 00:00:00 2001 From: Benjamin Cheng Date: Wed, 18 Nov 2026 09:11:23 -0500 Subject: [PATCH 1754/2102] drm/amdkfd: reserve TTM move fences MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Validation of the BO can add up to TTM_NUM_MOVE_FENCES, so we should fix that. Fixes: 897ee11ec020 ("drm/amdgpu: create multiple clear/move ttm entities") Signed-off-by: Benjamin Cheng Reviewed-by: Christian König Signed-off-by: Alex Deucher (cherry picked from commit ee9e47029133bf8931c99106773c207d95093733) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c index 1b79c9f182b1db..b5e96479118271 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c @@ -3009,7 +3009,8 @@ int amdgpu_amdkfd_gpuvm_restore_process_bos(void *info, struct dma_fence __rcu * struct drm_gem_object *gobj; gobj = &mem->bo->tbo.base; - ret = drm_exec_prepare_obj(&exec, gobj, 1); + ret = drm_exec_prepare_obj(&exec, gobj, + TTM_NUM_MOVE_FENCES + 1); drm_exec_retry_on_contention(&exec); if (unlikely(ret)) { pr_err("drm_exec_prepare_obj failed, ret: %d\n", ret); From 1893e8261de741e97e572ebfdb610e08b3953363 Mon Sep 17 00:00:00 2001 From: Benjamin Cheng Date: Wed, 18 Nov 2026 09:11:23 -0500 Subject: [PATCH 1755/2102] drm/amdgpu/gem: reserve fences on the VM root PD MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When creating a BO that shares the VM root PD's resv, TTM eviction fences are added to the resv, and there is another fence added for the BO clear job. Signed-off-by: Benjamin Cheng Reviewed-by: Christian König Signed-off-by: Alex Deucher (cherry picked from commit 6b69c31ef097bf89ce1ba28c58ec30435001d526) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c index c1d715749e0203..5c88544cd12007 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c @@ -504,6 +504,14 @@ int amdgpu_gem_create_ioctl(struct drm_device *dev, void *data, if (r) return r; + /* ttm_bo_init_reserved() + clear fence */ + r = dma_resv_reserve_fences(vm->root.bo->tbo.base.resv, + TTM_NUM_MOVE_FENCES + 1); + if (r) { + amdgpu_bo_unreserve(vm->root.bo); + return r; + } + resv = vm->root.bo->tbo.base.resv; } From 27612b9588d389f51c1e58815ded7ce7a10cbb26 Mon Sep 17 00:00:00 2001 From: Benjamin Cheng Date: Wed, 18 Nov 2026 09:11:47 -0500 Subject: [PATCH 1756/2102] drm/amdgpu/vm: reserve TTM_NUM_MOVE_FENCES in amdgpu_vm_lock_pd MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Page table updates may result in PT/PD allocation, which can add up to TTM_NUM_MOVE_FENCES to the resv. Fixes: 897ee11ec020 ("drm/amdgpu: create multiple clear/move ttm entities") Signed-off-by: Benjamin Cheng Reviewed-by: Christian König Signed-off-by: Alex Deucher (cherry picked from commit d2a44d97c3c68ed764496a71e747b869b75220a3) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c index 37888b5061ff0d..8f6572aab0e874 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c @@ -462,9 +462,13 @@ void amdgpu_vm_bo_base_init(struct amdgpu_vm_bo_base *base, int amdgpu_vm_lock_pd(struct amdgpu_vm *vm, struct drm_exec *exec, unsigned int num_fences) { - /* We need at least two fences for the VM PD/PT updates */ + /* + * One fence slot for clearing newly allocated PDs/PTs and PDE/PTE updates, + * another fence slots for TLB invalidation fences, TTM_NUM_MOVE_FENCES + * for validating PDs/PTs after eviction plus anything the caller requested. + */ return drm_exec_prepare_obj(exec, &vm->root.bo->tbo.base, - 2 + num_fences); + 2 + TTM_NUM_MOVE_FENCES + num_fences); } /** From a66d93ac6e1cc40db3daf2dc5c1d66fb14e08e44 Mon Sep 17 00:00:00 2001 From: Ian Rogers Date: Sat, 21 Nov 2026 20:53:16 -0800 Subject: [PATCH 1757/2102] drm/amdgpu: initialize r in amdgpu_vm_bo_update() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commit bc566781845b ("drm/amdgpu: stop syncing PRT map operations") added an 'else if (!bo)' branch in amdgpu_vm_bo_update() that does not assign 'r'. Because fpriv->prt_va has bo == NULL and is updated on every command submission, userqueue validation, and KFD VM restore, calling amdgpu_vm_bo_update(adev, fpriv->prt_va, false) when bo_va->invalids is empty skips the mapping loop and returns uninitialized stack variable 'r'. Set 'r = 0' in the 'else if (!bo)' branch. Found via an x86_64 LLVM=1 (Clang 21.1.8) allyesconfig audit with -Wconditional-uninitialized enabled; fix and changelog drafted with an AI coding assistant. Build-tested under LLVM=1 W=1 (-Werror) and -Wconditional-uninitialized; not runtime-tested on AMD GPU hardware. Fixes: bc566781845b ("drm/amdgpu: stop syncing PRT map operations") Reviewed-by: Christian König Signed-off-by: Ian Rogers Signed-off-by: Alex Deucher (cherry picked from commit 8c0cb48e0ce27462d84532112cc88c9a5b08b536) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c index 8f6572aab0e874..45f0f6aca754c4 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c @@ -1327,6 +1327,7 @@ int amdgpu_vm_bo_update(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va, } } else if (!bo) { mem = NULL; + r = 0; /* PRT map operations don't need to sync to anything. */ From 89abac69b89bcb7c11c0bb4038e012a8c03d590b Mon Sep 17 00:00:00 2001 From: Ian Rogers Date: Sat, 21 Nov 2026 20:53:17 -0800 Subject: [PATCH 1758/2102] drm/amdgpu: initialize r in amdgpu_ttm_clear_buffer() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In amdgpu_ttm_clear_buffer(), 'r' is declared uninitialized. When consider_clear_status is true (such as AMDGPU_GEM_CREATE_VRAM_CLEARED allocations) and all backing buddy blocks already have DRM_BUDDY_CLEARED set, every iteration of the cursor loop hits 'continue' without assigning 'r', returning uninitialized stack memory to amdgpu_bo_create(). Set 'r = 0' after the cursor loop directly before the 'error:' label. Found via an x86_64 LLVM=1 (Clang 21.1.8) allyesconfig audit with -Wconditional-uninitialized enabled; fix and changelog drafted with an AI coding assistant. Build-tested under LLVM=1 W=1 (-Werror) and -Wconditional-uninitialized; not runtime-tested on AMD GPU hardware. Fixes: 23bd7e67961e ("drm/amdgpu: get rid of amdgpu_ttm_clear_buffer") Reviewed-by: Christian König Signed-off-by: Ian Rogers Signed-off-by: Alex Deucher (cherry picked from commit 6002dd69992103cd006ef8066ae8ef44531bfb42) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c index dbb1225ff5d2db..326abc9b7f6908 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c @@ -2718,6 +2718,8 @@ int amdgpu_ttm_clear_buffer(struct amdgpu_ttm_buffer_entity *entity, amdgpu_res_next(&dst, cur_size); } + r = 0; + error: mutex_unlock(&entity->lock); *out_fence = fence; From 851fb23c38be595f9255a4245a0c3c38869f0d36 Mon Sep 17 00:00:00 2001 From: Christoph Berliner Date: Sat, 21 Nov 2026 07:46:05 +0100 Subject: [PATCH 1759/2102] drm/amdgpu/gfx9: deactivate all compute HQDs before MODE2 on APUs MODE2 does not reset the CP HQD registers on gfx9 APUs. Commit c3988a7ad479 ("drm/amdgpu/gfx9: Fix Ring and IB test fail after mode2") deactivates the HQDs of the kernel compute queues before MODE2, but the HQDs owned by KFD stay active as well: - the HIQ is never destroyed during a GPU reset, because kq_uninitialize() skips destroy_mqd() when it cannot take the reset domain semaphore, which amdgpu_device_gpu_recover() holds for write before calling amdgpu_amdkfd_pre_reset(), and kgd_gfx_v9_hqd_destroy() bails out with -EIO while amdgpu_in_reset() anyway; - user queues mapped by the HWS stay active when the preceding unmap failed (which is the usual reason for the reset). After MODE2 the MEC is unhalted with the stale HIQ. The reset reports success and graphics/KCQs work again, but the HWS no longer answers: the next KFD queue creation runs into amdgpu: qcm fence wait loop timeout expired amdgpu: The cp might be in an unrecoverable state due to an unsuccessful queues preemption amdgpu: process pid ... DQM create queue type 0 failed. ret -62 which triggers another reset, and KFD stays unusable until reboot. Deactivate every active HQD of all MECs before MODE2 instead of only the KCQs, except the KIQ, which gfx_v9_0_kiq_init_register() reprograms on resume. The KIQ is also identified by its MQD address, because at least on Renoir the HQD registers of MEC2 pipes 2/3 read back as those of pipes 0/1 and the KIQ would otherwise get a dequeue request through the alias. amdgpu_gfx_kiq_acquire() already avoids MEC2 pipes 2/3 for the KIQ, so this is likely not Renoir specific. While at it, fix the timeout check of the dequeue loop: it polled for adev->usec_timeout iterations but compared the counter against AMDGPU_MAX_USEC_TIMEOUT. Both are equal by default, but with amdgpu_emu_mode usec_timeout is 10x larger and the manual CP_HQD_ACTIVE=0 fallback was never reached. Tested on Ryzen 5 5600G (Cezanne, gfx90c, GC 9.3.0), MEC firmware 0x1e3, HWS enabled, amdgpu.noretry=1. An instrumented build used the old path for the first MODE2 and the new one afterwards (same boot): with the old path the HIQ was still ACTIVE with its old MQD/PQ after the reset and the next HIP program hung the GPU; with the new path only the KIQ was active at resume and HIP/rocBLAS tests passed. Loaded at boot, a requested reset deactivated 9 HQDs (8 KCQs + HIQ), skipped the KIQ seen through the pipe alias, and HIP/rocBLAS tests passed before and after the reset. Not tested on other gfx9 APUs. Fixes: c3988a7ad479 ("drm/amdgpu/gfx9: Fix Ring and IB test fail after mode2") Closes: https://gitlab.freedesktop.org/drm/amd/-/issues/6177 Assisted-by: Claude Code Reviewed-by: Alex Deucher Signed-off-by: Christoph Berliner Signed-off-by: Alex Deucher (cherry picked from commit af33373b09502de5f736ff91d6fde24a974d9f89) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c | 98 +++++++++++++++++++-------- 1 file changed, 69 insertions(+), 29 deletions(-) diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c b/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c index ae1d94c5f52829..67199f18ee4857 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c @@ -4081,39 +4081,79 @@ static int gfx_v9_0_hw_init(struct amdgpu_ip_block *ip_block) return r; } -static void gfx_v9_0_deactivate_kcq_hqd(struct amdgpu_device *adev) +/* caller must hold srbm_mutex and have selected me/pipe/queue */ +static bool gfx_v9_0_deactivate_hqd(struct amdgpu_device *adev, + u32 me, u32 pipe, u32 queue) { - amdgpu_gfx_rlc_enter_safe_mode(adev, 0); - for (int i = 0; i < adev->gfx.num_compute_rings; i++) { - u32 tmp; - struct amdgpu_ring *ring = &adev->gfx.compute_ring[i]; + int j; - mutex_lock(&adev->srbm_mutex); - soc15_grbm_select(adev, ring->me, ring->pipe, ring->queue, 0, 0); - tmp = RREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE); - /* disable the queue if it's active */ - if (tmp & CP_HQD_ACTIVE__ACTIVE_MASK) { - int j; - - WREG32_SOC15(GC, 0, mmCP_HQD_DEQUEUE_REQUEST, 1); - for (j = 0; j < adev->usec_timeout; j++) { - tmp = RREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE); - if (!(tmp & CP_HQD_ACTIVE__ACTIVE_MASK)) - break; - udelay(1); - } - if (j == AMDGPU_MAX_USEC_TIMEOUT) { - DRM_DEBUG("comp_%u_%u_%u dequeue request failed.\n", - ring->me, ring->pipe, ring->queue); - /* Manual disable if dequeue request times out */ - WREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE, 0); + /* disable the queue if it's active */ + if (!(RREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE) & CP_HQD_ACTIVE__ACTIVE_MASK)) + return false; + + WREG32_SOC15(GC, 0, mmCP_HQD_DEQUEUE_REQUEST, 1); + for (j = 0; j < adev->usec_timeout; j++) { + if (!(RREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE) & + CP_HQD_ACTIVE__ACTIVE_MASK)) + break; + udelay(1); + } + if (j == adev->usec_timeout) { + dev_dbg(adev->dev, "comp_%u_%u_%u dequeue request failed.\n", + me, pipe, queue); + /* Manual disable if dequeue request times out */ + WREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE, 0); + } + WREG32_SOC15(GC, 0, mmCP_HQD_DEQUEUE_REQUEST, 0); + + return true; +} + +/* + * MODE2 does not reset the CP HQD registers on gfx9 APUs. Besides the KCQs, + * the HQDs owned by KFD (HIQ and the user queues mapped by the HWS) also stay + * active, because KFD cannot unmap/destroy them while the reset domain is + * locked. After MODE2 the MEC then resumes with stale HQDs and the HWS no + * longer answers (qcm fence timeout on the next KFD queue). Deactivate every + * active HQD of all MECs except the KIQ, which is reprogrammed on resume. + */ +static void gfx_v9_0_deactivate_all_hqd(struct amdgpu_device *adev) +{ + struct amdgpu_ring *kiq_ring = &adev->gfx.kiq[0].ring; + u64 kiq_mqd_addr = kiq_ring->mqd_gpu_addr & ~0x3ULL; + u32 me, pipe, queue, n = 0; + u64 mqd_addr; + + amdgpu_gfx_rlc_enter_safe_mode(adev, 0); + mutex_lock(&adev->srbm_mutex); + for (me = 1; me <= adev->gfx.mec.num_mec; me++) { + for (pipe = 0; pipe < adev->gfx.mec.num_pipe_per_mec; pipe++) { + for (queue = 0; queue < adev->gfx.mec.num_queue_per_pipe; + queue++) { + if (me == kiq_ring->me && pipe == kiq_ring->pipe && + queue == kiq_ring->queue) + continue; + soc15_grbm_select(adev, me, pipe, queue, 0, 0); + /* + * At least on Renoir the HQD registers of MEC2 + * pipes 2/3 read back as those of pipes 0/1, so + * the KIQ shows up a second time. Skip it by its + * MQD address instead of sending it a dequeue. + */ + mqd_addr = ((u64)RREG32_SOC15(GC, 0, mmCP_MQD_BASE_ADDR_HI) << 32) | + RREG32_SOC15(GC, 0, mmCP_MQD_BASE_ADDR); + if (mqd_addr == kiq_mqd_addr) + continue; + if (gfx_v9_0_deactivate_hqd(adev, me, pipe, queue)) + n++; } - WREG32_SOC15(GC, 0, mmCP_HQD_DEQUEUE_REQUEST, 0); } - soc15_grbm_select(adev, 0, 0, 0, 0, 0); - mutex_unlock(&adev->srbm_mutex); } + soc15_grbm_select(adev, 0, 0, 0, 0, 0); + mutex_unlock(&adev->srbm_mutex); amdgpu_gfx_rlc_exit_safe_mode(adev, 0); + + dev_dbg(adev->dev, "deactivated %u active compute HQDs before MODE2\n", n); } static int gfx_v9_0_hw_fini(struct amdgpu_ip_block *ip_block) @@ -4141,8 +4181,8 @@ static int gfx_v9_0_hw_fini(struct amdgpu_ip_block *ip_block) } if ((adev->flags & AMD_IS_APU) && amdgpu_in_reset(adev) && - amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_MODE2) - gfx_v9_0_deactivate_kcq_hqd(adev); + amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_MODE2) + gfx_v9_0_deactivate_all_hqd(adev); /* Use deinitialize sequence from CAIL when unbinding device from driver, * otherwise KIQ is hanging when binding back From 57737b8f4dd23ead54a09f68c079d8ea0eed79f3 Mon Sep 17 00:00:00 2001 From: Jesse Zhang Date: Sat, 31 Oct 2026 23:45:30 +0800 Subject: [PATCH 1760/2102] drm/amdkfd: return the memory violation data to the debugger kfd_dbg_ev_raise() saves the memory exception data of a GPU VM fault for a debugger subscribed to EC_DEVICE_MEMORY_VIOLATION, but never sets vm_fault_exc_data_size. QUERY_EXCEPTION_INFO copies that many bytes, so the debugger always gets 0 bytes and no fault address. With a process debugging itself and a KFD SDMA queue writing to an unmapped VA: amdgpu 0000:03:00.0: [gfxhub] page fault (src_id:0 ring:40 vmid:8 pasid:63) amdgpu 0000:03:00.0: in page starting at address 0x0000000060200000 from client 10 amdgpu 0000:03:00.0: Faulty UTCL2 client ID: SDMA0 (0xd) memory violation info: 0 bytes, va 0x0 gpu_id 0, fault at 0x60200000 With the size set: memory violation info: 32 bytes, va 0x60200000 gpu_id 51573, fault at 0x60200000 The data is also only freed by a query clearing the exception, free it with the process device as well. Fixes: 2b36de971d25 ("drm/amdkfd: add debug query exception info operation") Reviewed-by: Jonathan Kim Signed-off-by: Jesse Zhang Signed-off-by: Alex Deucher (cherry picked from commit 3b700b69373af4ee79179c4035e22030951e3d13) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_debug.c | 4 +++- drivers/gpu/drm/amd/amdkfd/kfd_process.c | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_debug.c b/drivers/gpu/drm/amd/amdkfd/kfd_debug.c index 0dd1fd448059bb..2296ad1a532ee5 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_debug.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_debug.c @@ -143,7 +143,9 @@ bool kfd_dbg_ev_raise(uint64_t event_mask, exception_data, exception_data_size, GFP_KERNEL); - if (!pdd->vm_fault_exc_data) + if (pdd->vm_fault_exc_data) + pdd->vm_fault_exc_data_size = exception_data_size; + else pr_debug("Failed to allocate exception data memory"); } else { pr_debug("Debugger exception data not saved\n"); diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_process.c b/drivers/gpu/drm/amd/amdkfd/kfd_process.c index 48f9eab1209d37..336c66d9c5a730 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_process.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_process.c @@ -1236,6 +1236,7 @@ static void kfd_process_destroy_pdds(struct kfd_process *p) atomic_dec(&pdd->dev->kfd->kfd_processes_count); mutex_destroy(&pdd->doorbell_mutex); + kfree(pdd->vm_fault_exc_data); kfree(pdd); p->pdds[i] = NULL; } From 94ff2d27fafad99c63c02ab4d7e148c37e4eff80 Mon Sep 17 00:00:00 2001 From: Tejun Heo Date: Mon, 23 Nov 2026 01:38:47 -1000 Subject: [PATCH 1761/2102] workqueue: Fix drain_workqueue() missing work items chained across pwqs drain_workqueue() flushes the workqueue, then checks each pwq under its pool's lock and returns once a pass finds every pwq empty. Only chained queueing is allowed meanwhile, and a chained work item can land on a pwq other than the one the queueing work item is executing on. The pass misses it when: 1. The pass finds pwq A empty. 2. A work item executing on pwq B queues a work item on pwq A. 3. The work item on pwq B finishes. 4. The pass finds pwq B empty. drain_workqueue() returns with the work item on pwq A pending, and destroy_workqueue() can then trip WARN_ON(pwq_busy()) and leak the workqueue. Add pwq->nr_started, which counts the work items a pwq has started executing, and check the pwqs twice after each flush. The drain is complete only if both passes find every pwq empty and no work item started in between. The counter is updated and read under pool->lock, and the queueing path is not touched. Verified with reproducers of both shapes: self-requeueing work items on an unbound workqueue and chained queue_work_on() of another work item on a per-cpu workqueue. Fixes: c8efcc258946 ("workqueue: allow chained queueing during destruction") Cc: stable@vger.kernel.org # v2.6.38+ Link: https://lore.kernel.org/all/CAHk-=wjm3vbiNYsR+aHxmM3KCEgsSWb379ZQbCuZEsN1dhvbKg@mail.gmail.com/ Originally-by: Linus Torvalds Signed-off-by: Tejun Heo --- kernel/workqueue.c | 51 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 11 deletions(-) diff --git a/kernel/workqueue.c b/kernel/workqueue.c index f2e8071a6f4eb0..08046ff0d697d8 100644 --- a/kernel/workqueue.c +++ b/kernel/workqueue.c @@ -281,6 +281,7 @@ struct pool_workqueue { int total_in_flight; /* L: sum of nr_in_flight[] */ int nr_in_flight[WORK_NR_COLORS]; /* L: nr of in_flight works */ + unsigned long nr_started; /* L: see drain_workqueue() */ struct list_head flush_node; /* FN: node on wq_flush_pnode->pwqs */ bool plugged; /* L: execution suspended */ @@ -3455,6 +3456,7 @@ __acquires(&pool->lock) */ set_work_pool_and_clear_pending(work, pool->id, pool_offq_flags(pool)); + pwq->nr_started++; pwq->stats[PWQ_STAT_STARTED]++; rcu_read_lock(); @@ -4449,6 +4451,33 @@ void __flush_workqueue(struct workqueue_struct *wq) } EXPORT_SYMBOL(__flush_workqueue); +/* + * Return 0 if any pwq of @wq is busy. Otherwise, return the sum of nr_started + * of all pwqs encoded as 2 * sum + 1, which is always odd, so that 0 can only + * mean busy. + */ +static unsigned long pwqs_nr_started(struct workqueue_struct *wq) +{ + struct pool_workqueue *pwq; + unsigned long sum = 0; + + lockdep_assert_held(&wq->mutex); + + for_each_pwq(pwq, wq) { + bool empty; + + raw_spin_lock_irq(&pwq->pool->lock); + empty = pwq_is_empty(pwq); + sum += pwq->nr_started; + raw_spin_unlock_irq(&pwq->pool->lock); + + if (!empty) + return 0; + } + + return 2 * sum + 1; +} + /** * drain_workqueue - drain a workqueue * @wq: workqueue to drain @@ -4462,8 +4491,8 @@ EXPORT_SYMBOL(__flush_workqueue); */ void drain_workqueue(struct workqueue_struct *wq) { + unsigned long started; unsigned int flush_cnt = 0; - struct pool_workqueue *pwq; /* * __queue_work() needs to test whether there are drainers, is much @@ -4479,16 +4508,16 @@ void drain_workqueue(struct workqueue_struct *wq) mutex_lock(&wq->mutex); - for_each_pwq(pwq, wq) { - bool drained; - - raw_spin_lock_irq(&pwq->pool->lock); - drained = pwq_is_empty(pwq); - raw_spin_unlock_irq(&pwq->pool->lock); - - if (drained) - continue; - + /* + * A pass isn't atomic across pwqs, so a chained work item can land on + * a pwq it already found empty. Anything slipping past the second pass + * needs a work item that was in flight at its pwq's first check, or + * that started between its pwq's two checks. The first makes the first + * pass fail, the second changes nr_started. wq->mutex keeps the set of + * pwqs stable across both passes. + */ + started = pwqs_nr_started(wq); + if (!started || pwqs_nr_started(wq) != started) { if (++flush_cnt == 10 || (flush_cnt % 100 == 0 && flush_cnt <= 1000)) pr_warn("workqueue %s: %s() isn't complete after %u tries\n", From edf1066ba69c89c42c3007e4230c7b9cb13405a8 Mon Sep 17 00:00:00 2001 From: Saurabh Sengar Date: Tue, 24 Nov 2026 10:00:10 -0800 Subject: [PATCH 1762/2102] workqueue: Skip redundant unbound updates during CPU bringup Before workqueue_init_topology(), all CPUs share the SYSTEM pod, which contains every possible CPU. The effective cpumask and the per-pod cpumask of an unbound workqueue are therefore identical, regardless of which CPUs are online. During this stage, workqueue_online_cpu() walks every possible CPU for every unbound workqueue each time a secondary CPU comes online. The pwq mappings cannot change yet, so this repeats redundant work that scales quadratically with CPU count. On a 640-vCPU Hyper-V VM, each of the 639 secondary CPU-online callbacks walks all 640 possible CPUs for each of the 8 unbound workqueues, giving 3,271,680 unbound_wq_update_pwq() calls that took about 975 ms in total. Skip these updates until workqueue_init_topology(). The pwq mappings already match the effective cpumask, and wq_update_node_max_active() does nothing before topology initialization. workqueue_init_topology() will apply the topology-specific mappings and node limits once ready. Keep worker rebinding and restoration of unbound worker affinity before the guard. CPU hotplug after topology initialization is unchanged. On the same VM running a v7.3 kernel, smp_init() took 1054 ms with this change, compared to 2008 ms without it, a 47.5% reduction. Before After Reduction smp_init() 2008 ms 1054 ms 47.5% Fixes: 84193c07105c ("workqueue: Generalize unbound CPU pods") Signed-off-by: Saurabh Sengar Signed-off-by: Tejun Heo --- kernel/workqueue.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/kernel/workqueue.c b/kernel/workqueue.c index 08046ff0d697d8..b07f60ff39dd9e 100644 --- a/kernel/workqueue.c +++ b/kernel/workqueue.c @@ -7224,6 +7224,14 @@ int workqueue_online_cpu(unsigned int cpu) mutex_unlock(&wq_pool_attach_mutex); } + /* + * Before topology initialization, the SYSTEM pod covers all possible + * CPUs, so CPU onlining does not require updating pwq mappings. + * wq_update_node_max_active() also returns early at this stage. + */ + if (!wq_topo_initialized) + goto out_unlock; + /* update pod affinity of unbound workqueues */ list_for_each_entry(wq, &workqueues, list) { struct workqueue_attrs *attrs = wq->attrs; @@ -7241,6 +7249,7 @@ int workqueue_online_cpu(unsigned int cpu) } } +out_unlock: mutex_unlock(&wq_pool_mutex); return 0; } From a33ffa8462808547aef24ca557451411d4ce2efc Mon Sep 17 00:00:00 2001 From: Zhu Jun Date: Fri, 20 Nov 2026 14:19:12 +0800 Subject: [PATCH 1763/2102] tools/bootconfig: Reject short reads of configuration data load_xbc_fd() places the terminator at the requested size even when read() returns less. Its initrd caller then computes a checksum over bytes that were never read, while the plain file callers can parse a partial configuration. Reject a short read and release the allocated buffer on both read failure paths. Link: https://lore.kernel.org/all/20261120061912.98156-1-zhujun2@cmss.chinamobile.com/ Fixes: 950313ebf79c ("tools: bootconfig: Add bootconfig command") Cc: stable@vger.kernel.org Signed-off-by: Zhu Jun Signed-off-by: Masami Hiramatsu (Google) --- tools/bootconfig/main.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tools/bootconfig/main.c b/tools/bootconfig/main.c index c32fb1e2140cf4..31af794fa4d121 100644 --- a/tools/bootconfig/main.c +++ b/tools/bootconfig/main.c @@ -190,8 +190,12 @@ static int load_xbc_fd(int fd, char **buf, int size) return -ENOMEM; ret = read(fd, *buf, size); - if (ret < 0) - return -errno; + if (ret != size) { + ret = ret < 0 ? -errno : -EIO; + free(*buf); + *buf = NULL; + return ret; + } (*buf)[size] = '\0'; return ret; From 56bb11fe6aacc7666938e8e6765b44aa0cf1fcdd Mon Sep 17 00:00:00 2001 From: Zhu Jun Date: Fri, 20 Nov 2026 14:19:17 +0800 Subject: [PATCH 1764/2102] tools/bootconfig: Report initrd append failures The signed return value of write() is compared against a size_t. A negative return becomes an unsigned value and bypasses the error path, so applying a bootconfig can claim success without appending it. Check for a negative return before comparing the byte count. Link: https://lore.kernel.org/all/20261120061917.98169-1-zhujun2@cmss.chinamobile.com/ Fixes: a995e6bc0524 ("tools/bootconfig: Fix to check the write failure correctly") Cc: stable@vger.kernel.org Signed-off-by: Zhu Jun Signed-off-by: Masami Hiramatsu (Google) --- tools/bootconfig/main.c | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/tools/bootconfig/main.c b/tools/bootconfig/main.c index 31af794fa4d121..c85e58fcb6b0b7 100644 --- a/tools/bootconfig/main.c +++ b/tools/bootconfig/main.c @@ -509,14 +509,16 @@ static int apply_xbc(const char *path, const char *xbc_path) total_size = size + BOOTCONFIG_FOOTER_SIZE; ret = write(fd, data, total_size); - if (ret < total_size) { - if (ret < 0) - ret = -errno; + if (ret < 0) { + ret = -errno; pr_err("Failed to apply a boot config: %d\n", ret); - if (ret >= 0) - goto out_rollback; - } else - ret = 0; + goto out; + } + if ((size_t)ret != total_size) { + pr_err("Failed to apply a boot config: %d\n", ret); + goto out_rollback; + } + ret = 0; out: close(fd); From a6ea69915a230d24e9d9cd8dc0ff0551dab36106 Mon Sep 17 00:00:00 2001 From: Jakub Kicinski Date: Thu, 19 Nov 2026 19:46:44 -0800 Subject: [PATCH 1765/2102] eth: bnxt_en: restore Rx coalescing after re-allocating the completion ring With TPH enabled, queue restart frees and re-allocates the Rx completion ring in the FW, to apply the new Steering Tag. The new FW ring starts with default interrupt coalescing parameters. The driver programs coalescing only at open, from ethtool and from DIM, so after a restart the ring ignores the configured settings, while ethtool keeps reporting them. Re-program Rx coalescing of the ring after allocating it. Use DIM's current profile if adaptive coalescing is enabled, the static settings otherwise. The per-ring DIM values may be stale when DIM is off, ethtool changes to static coalescing don't update them. With rx-usecs 1000, re-allocating the ring on a BCM57508 lowers the latency of a 1 byte ping-pong on that queue by ~250us. Latency goes back up once ethtool re-programs coalescing. Fixes: 6b6bf60fc95f ("bnxt_en: Reallocate RX completion ring for TPH support") Signed-off-by: Jakub Kicinski Reviewed-by: Pavan Chebbi Link: https://patch.msgid.link/20261120034645.364630-1-kuba@kernel.org Signed-off-by: Willem de Bruijn --- drivers/net/ethernet/broadcom/bnxt/bnxt.c | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.c b/drivers/net/ethernet/broadcom/bnxt/bnxt.c index e78cf7ad3cbc8d..25d7c4cc3377f8 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.c @@ -8618,6 +8618,25 @@ int bnxt_hwrm_set_coal(struct bnxt *bp) return rc; } +/* Program Rx coalescing of a single ring, e.g. after its completion ring + * was re-allocated in the FW, which resets the coalescing parameters. + */ +static int bnxt_hwrm_set_rx_ring_coal(struct bnxt *bp, struct bnxt_napi *bnapi) +{ + struct hwrm_ring_cmpl_ring_cfg_aggint_params_input *req; + int rc; + + if (bp->flags & BNXT_FLAG_DIM) + return bnxt_hwrm_set_ring_coal(bp, bnapi); + + rc = hwrm_req_init(bp, req, HWRM_RING_CMPL_RING_CFG_AGGINT_PARAMS); + if (rc) + return rc; + + bnxt_hwrm_set_coal_params(bp, &bp->rx_coal, req); + return bnxt_hwrm_set_rx_coal(bp, bnapi, req); +} + static void bnxt_hwrm_stat_ctx_free(struct bnxt *bp) { struct hwrm_stat_ctx_clr_stats_input *req0 = NULL; @@ -16643,6 +16662,11 @@ static int bnxt_queue_start(struct net_device *dev, rc = bnxt_hwrm_cp_ring_alloc_p5(bp, rxr->rx_cpr); if (rc) goto err_reset; + + rc = bnxt_hwrm_set_rx_ring_coal(bp, bnapi); + if (rc) + netdev_warn(bp->dev, "HWRM set coalescing failure rc: %d\n", + rc); } rc = bnxt_hwrm_rx_agg_ring_alloc(bp, rxr); From 32756b82fde8f6cc98b174fdcd02c2a61033e263 Mon Sep 17 00:00:00 2001 From: Jakub Kicinski Date: Thu, 19 Nov 2026 19:46:45 -0800 Subject: [PATCH 1766/2102] eth: bnxt_en: restore Tx coalescing after re-allocating the completion ring With TPH enabled, queue restart also frees and re-allocates the Tx completion rings which share the NAPI instance with the Rx queue. Same as on the Rx side, the new FW rings start with default interrupt coalescing parameters, and the configured settings are applied again only at the next open or ethtool change. On P5+ chips the Tx completion rings are separate from the Rx ones even in combined channels, and the Tx settings do take effect. On a BCM57508 the completion latency of sparse Tx traffic follows tx-usecs, it's ~20us with tx-usecs 1 and ~220us with tx-usecs 200. Re-program Tx coalescing of each completion ring after allocating it. DIM only manages Rx, the static settings always apply to Tx. Fixes: fe96d717d38e ("bnxt_en: Extend queue stop/start for TX rings") Signed-off-by: Jakub Kicinski Reviewed-by: Pavan Chebbi Link: https://patch.msgid.link/20261120034645.364630-2-kuba@kernel.org Signed-off-by: Willem de Bruijn --- drivers/net/ethernet/broadcom/bnxt/bnxt.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.c b/drivers/net/ethernet/broadcom/bnxt/bnxt.c index 25d7c4cc3377f8..52606db3f7b4a8 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.c @@ -8637,6 +8637,24 @@ static int bnxt_hwrm_set_rx_ring_coal(struct bnxt *bp, struct bnxt_napi *bnapi) return bnxt_hwrm_set_rx_coal(bp, bnapi, req); } +/* Program Tx coalescing of the completion ring of a single Tx ring, e.g. + * after it was re-allocated in the FW. + */ +static int bnxt_hwrm_set_tx_ring_coal(struct bnxt *bp, + struct bnxt_tx_ring_info *txr) +{ + struct hwrm_ring_cmpl_ring_cfg_aggint_params_input *req; + int rc; + + rc = hwrm_req_init(bp, req, HWRM_RING_CMPL_RING_CFG_AGGINT_PARAMS); + if (rc) + return rc; + + bnxt_hwrm_set_coal_params(bp, &bp->tx_coal, req); + req->ring_id = cpu_to_le16(bnxt_cp_ring_for_tx(bp, txr)); + return hwrm_req_send(bp, req); +} + static void bnxt_hwrm_stat_ctx_free(struct bnxt *bp) { struct hwrm_stat_ctx_clr_stats_input *req0 = NULL; @@ -11857,6 +11875,11 @@ static int bnxt_tx_queue_start(struct bnxt *bp, int idx) if (rc) return rc; + rc = bnxt_hwrm_set_tx_ring_coal(bp, txr); + if (rc) + netdev_warn(bp->dev, "HWRM set coalescing failure rc: %d\n", + rc); + rc = bnxt_hwrm_tx_ring_alloc(bp, txr, false); if (rc) return rc; From 5d30a02245c375a9c5e557b1b7476710c4a94a2d Mon Sep 17 00:00:00 2001 From: Florian Fainelli Date: Thu, 19 Nov 2026 11:03:43 -0800 Subject: [PATCH 1767/2102] net: dsa: b53: initialize the jumbo frame size register offset The chip data specifies both the jumbo port mask and frame size register offsets, but b53_switch_init() only copies the former into the device. Since the device is zero-initialized, b53_set_jumbo() writes the frame size to offset zero instead of the chip-specific size register at 0x05 or 0x08. Copy jumbo_size_reg from the chip data along with jumbo_pm_reg so frame size updates reach the intended register. Fixes: 967dd82ffc52 ("net: dsa: b53: Add support for Broadcom RoboSwitch") Reviewed-by: Jonas Gorski Signed-off-by: Florian Fainelli Signed-off-by: Willem de Bruijn --- drivers/net/dsa/b53/b53_common.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/net/dsa/b53/b53_common.c b/drivers/net/dsa/b53/b53_common.c index b7aff5e238e857..1f5776dfaae2e2 100644 --- a/drivers/net/dsa/b53/b53_common.c +++ b/drivers/net/dsa/b53/b53_common.c @@ -3172,6 +3172,7 @@ static int b53_switch_init(struct b53_device *dev) dev->vta_regs[1] = chip->vta_regs[1]; dev->vta_regs[2] = chip->vta_regs[2]; dev->jumbo_pm_reg = chip->jumbo_pm_reg; + dev->jumbo_size_reg = chip->jumbo_size_reg; dev->imp_port = chip->imp_port; dev->num_vlans = chip->vlans; dev->num_arl_bins = chip->arl_bins; From bd7fc60896b3de8ce677142142c96277377e5167 Mon Sep 17 00:00:00 2001 From: Florian Fainelli Date: Thu, 19 Nov 2026 11:03:44 -0800 Subject: [PATCH 1768/2102] net: dsa: b53: fix the SRAB grant timeout check b53_srab_request_grant() polls for a grant up to 20 times, but checks for an iteration count of five to detect a timeout. This rejects a grant received on the sixth poll and reports success when all 20 polls finish without a grant. The latter allows a register access to proceed without ownership of the switch resources. Check for exhaustion of all 20 iterations instead. Fixes: 967dd82ffc52 ("net: dsa: b53: Add support for Broadcom RoboSwitch") Reviewed-by: Jonas Gorski Reviewed-by: Daniel Machon Signed-off-by: Florian Fainelli Signed-off-by: Willem de Bruijn --- drivers/net/dsa/b53/b53_srab.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/dsa/b53/b53_srab.c b/drivers/net/dsa/b53/b53_srab.c index e6d14fdc56fde2..7306535a892a2d 100644 --- a/drivers/net/dsa/b53/b53_srab.c +++ b/drivers/net/dsa/b53/b53_srab.c @@ -105,7 +105,7 @@ static int b53_srab_request_grant(struct b53_device *dev) break; usleep_range(10, 100); } - if (WARN_ON(i == 5)) + if (WARN_ON(i == 20)) return -EIO; return 0; From c6f0992ff6c2c138ffb1b64f406a66d42615770b Mon Sep 17 00:00:00 2001 From: Florian Fainelli Date: Thu, 19 Nov 2026 11:03:45 -0800 Subject: [PATCH 1769/2102] net: dsa: b53: clear stale state when creating an ARL entry When an ARL lookup does not find the requested MAC and VID, b53_arl_read() returns the first free bin index but leaves the entry populated with the last bin examined. The multicast add path then ORs the requested port into that unrelated entry's forwarding bitmap, potentially forwarding packets to ports which are not members of the multicast group. Clear the entry before creating a new one. Also return without writing anything when deleting an entry which is not present, instead of writing back stale bin contents. The return value for that case is unchanged (0). Fixes: 5d65b64a3d97 ("net: dsa: b53: Add support for MDB") Signed-off-by: Florian Fainelli Signed-off-by: Willem de Bruijn --- drivers/net/dsa/b53/b53_common.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/net/dsa/b53/b53_common.c b/drivers/net/dsa/b53/b53_common.c index 1f5776dfaae2e2..dac6013f8fe293 100644 --- a/drivers/net/dsa/b53/b53_common.c +++ b/drivers/net/dsa/b53/b53_common.c @@ -2055,9 +2055,13 @@ static int b53_arl_op(struct b53_device *dev, int op, int port, addr, vid); return is_valid ? ret : 0; case -ENOENT: + if (!is_valid) + return 0; + /* We could not find a matching MAC, so reset to a new entry */ dev_dbg(dev->dev, "{%pM,%.4d} not found, using idx: %d\n", addr, vid, idx); + memset(&ent, 0, sizeof(ent)); break; default: dev_dbg(dev->dev, "{%pM,%.4d} found, using idx: %d\n", From fd2752aac6c2193507af2e96cfc1406b28cade6f Mon Sep 17 00:00:00 2001 From: Florian Fainelli Date: Thu, 19 Nov 2026 11:03:46 -0800 Subject: [PATCH 1770/2102] net: dsa: b53: use the correct override register 2 Gbps bit The IMP and per-port GMII override registers swap the override-enable and 2 Gbps speed bits. Using the IMP speed bit on a GMII port clears its override enable and leaves any previous 2 Gbps selection intact. Select the speed bit alongside the register and enable bit so lower speeds clear the correct bit and 2 Gbps sets it. Fixes: b6a8a5477fe9 ("net: dsa: b53: fix resetting speed and pause on forced link") Fixes: 41af38324341 ("net: dsa: b53: restore the NSP IMP port 2 Gbps mode") Reviewed-by: Jonas Gorski Signed-off-by: Florian Fainelli Signed-off-by: Willem de Bruijn --- drivers/net/dsa/b53/b53_common.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/drivers/net/dsa/b53/b53_common.c b/drivers/net/dsa/b53/b53_common.c index dac6013f8fe293..19e36e51be52b5 100644 --- a/drivers/net/dsa/b53/b53_common.c +++ b/drivers/net/dsa/b53/b53_common.c @@ -1427,17 +1427,19 @@ static void b53_force_port_config(struct b53_device *dev, int port, int speed, int duplex, bool tx_pause, bool rx_pause) { - u8 reg, val, off; + u8 reg, val, off, speed2000; /* Override the port settings */ if (port == dev->imp_port) { off = B53_PORT_OVERRIDE_CTRL; val = PORT_OVERRIDE_EN; + speed2000 = PORT_OVERRIDE_SPEED_2000M; } else if (is5325(dev)) { return; } else { off = B53_GMII_PORT_OVERRIDE_CTRL(port); val = GMII_PO_EN; + speed2000 = GMII_PO_SPEED_2000M; } b53_read8(dev, B53_CTRL_PAGE, off, ®); @@ -1449,11 +1451,12 @@ static void b53_force_port_config(struct b53_device *dev, int port, reg &= ~(0x3 << GMII_PO_SPEED_S); if (is5301x(dev) || is58xx(dev)) - reg &= ~PORT_OVERRIDE_SPEED_2000M; + reg &= ~speed2000; switch (speed) { case 2000: - reg |= PORT_OVERRIDE_SPEED_2000M; + if (is5301x(dev) || is58xx(dev)) + reg |= speed2000; fallthrough; case SPEED_1000: reg |= PORT_OVERRIDE_SPEED_1000M; From 000d468855945953c491810f97fb0bd4166b0b07 Mon Sep 17 00:00:00 2001 From: Florian Fainelli Date: Thu, 19 Nov 2026 11:03:47 -0800 Subject: [PATCH 1771/2102] net: dsa: b53: fix mirror port encoding on BCM5325 and BCM5365 BCM5325 and BCM5365 use an 11-bit bitmap for the mirror capture port, whereas newer switches use a four-bit port ID. Programming the port number directly can select no destination or the wrong destination, and can select multiple destinations. For example, port 2 requires BIT(2), but writing 2 selects port 1 instead. Use the bitmap encoding on BCM5325 and BCM5365, including translating logical CPU port 5 to hardware bit 8. Apply the corresponding field mask when checking for a conflicting destination, replacing the destination, and clearing it after the last mirror source is removed. Keep the port ID encoding for newer switches. The ingress and egress mirror source masks use the same layout on these switches, with the CPU port at bit 8 and bits 5-7 reserved, so apply the same translation when setting and clearing a source port bit. Fixes: ed3af5fd08eb ("net: dsa: b53: Add support for port mirroring") Signed-off-by: Florian Fainelli Signed-off-by: Willem de Bruijn --- drivers/net/dsa/b53/b53_common.c | 35 +++++++++++++++++++++++++++----- drivers/net/dsa/b53/b53_regs.h | 1 + 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/drivers/net/dsa/b53/b53_common.c b/drivers/net/dsa/b53/b53_common.c index 19e36e51be52b5..ffbf5efd8d9517 100644 --- a/drivers/net/dsa/b53/b53_common.c +++ b/drivers/net/dsa/b53/b53_common.c @@ -2604,6 +2604,31 @@ enum dsa_tag_protocol b53_get_tag_protocol(struct dsa_switch *ds, int port, } EXPORT_SYMBOL(b53_get_tag_protocol); +static u16 b53_mirror_capture_port_mask(struct b53_device *dev) +{ + if (is5325(dev) || is5365(dev)) + return CAP_PORT_MASK_25; + + return CAP_PORT_MASK; +} + +static u16 b53_mirror_port_mask(struct b53_device *dev, int port) +{ + /* These switches use a bitmap with the CPU port at bit 8. */ + if ((is5325(dev) || is5365(dev)) && port == B53_CPU_PORT_25) + port = B53_CPU_PORT; + + return BIT(port); +} + +static u16 b53_mirror_capture_port(struct b53_device *dev, int port) +{ + if (is5325(dev) || is5365(dev)) + return b53_mirror_port_mask(dev, port); + + return port; +} + int b53_mirror_add(struct dsa_switch *ds, int port, struct dsa_mall_mirror_tc_entry *mirror, bool ingress, struct netlink_ext_ack *extack) @@ -2617,12 +2642,12 @@ int b53_mirror_add(struct dsa_switch *ds, int port, loc = B53_EG_MIR_CTL; b53_read16(dev, B53_MGMT_PAGE, loc, ®); - reg |= BIT(port); + reg |= b53_mirror_port_mask(dev, port); b53_write16(dev, B53_MGMT_PAGE, loc, reg); b53_read16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, ®); - reg &= ~CAP_PORT_MASK; - reg |= mirror->to_local_port; + reg &= ~b53_mirror_capture_port_mask(dev); + reg |= b53_mirror_capture_port(dev, mirror->to_local_port); reg |= MIRROR_EN; b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, reg); @@ -2644,7 +2669,7 @@ void b53_mirror_del(struct dsa_switch *ds, int port, /* Update the desired ingress/egress register */ b53_read16(dev, B53_MGMT_PAGE, loc, ®); - reg &= ~BIT(port); + reg &= ~b53_mirror_port_mask(dev, port); if (!(reg & MIRROR_MASK)) loc_disable = true; b53_write16(dev, B53_MGMT_PAGE, loc, reg); @@ -2663,7 +2688,7 @@ void b53_mirror_del(struct dsa_switch *ds, int port, /* Both no longer have ports, let's disable mirroring */ if (loc_disable && other_loc_disable) { reg &= ~MIRROR_EN; - reg &= ~mirror->to_local_port; + reg &= ~b53_mirror_capture_port_mask(dev); } b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, reg); } diff --git a/drivers/net/dsa/b53/b53_regs.h b/drivers/net/dsa/b53/b53_regs.h index cfdb5ed3832606..ee049927a63aee 100644 --- a/drivers/net/dsa/b53/b53_regs.h +++ b/drivers/net/dsa/b53/b53_regs.h @@ -239,6 +239,7 @@ /* Mirror capture control register (16 bit) */ #define B53_MIR_CAP_CTL 0x10 #define CAP_PORT_MASK 0xf +#define CAP_PORT_MASK_25 0x7ff #define BLK_NOT_MIR BIT(14) #define MIRROR_EN BIT(15) From 320bc9b8e2bc8a5fc75537082529b534ace633e3 Mon Sep 17 00:00:00 2001 From: Florian Fainelli Date: Thu, 19 Nov 2026 11:03:48 -0800 Subject: [PATCH 1772/2102] net: dsa: b53: fix mirror destination and source state tracking The mirror capture control register selects one destination for all ingress and egress sources. Adding a rule for another destination currently redirects existing rules. Multiple matchall filters can also share one source bit, but deleting any one of them clears that bit and can disable mirroring while other filters still need it. Reject a different destination while either source mask is occupied, and reference count each port's ingress and egress source bit under RTNL. Program a source on its first reference and clear it on its last one. Check every mirror register access and record a first reference only after programming succeeds. Select the destination before enabling the source, and log deletion failures because the callback returns no error. Use the source masks to retain the destination after a failed source deletion and allow a new destination after a failed capture-control clear. Not all supported switches receive a hardware reset during setup, so clear stale capture and source registers before accepting mirror rules. Introduce b53_mirror_init() together with its b53 and bcm_sf2 setup callers. Rebuild active sources and their destination from the reference counts when setup runs again, preserving rules across bcm_sf2 resume. Propagate initialization failures instead of accepting stale state. This depends on "net: dsa: b53: fix mirror port encoding on BCM5325 and BCM5365" for the chip-specific source and capture-port helpers. Fixes: ed3af5fd08eb ("net: dsa: b53: Add support for port mirroring") Signed-off-by: Florian Fainelli Tested-by: Joseph Telaak Signed-off-by: Willem de Bruijn --- drivers/net/dsa/b53/b53_common.c | 168 ++++++++++++++++++++++++------- drivers/net/dsa/b53/b53_priv.h | 4 + drivers/net/dsa/bcm_sf2.c | 4 + 3 files changed, 140 insertions(+), 36 deletions(-) diff --git a/drivers/net/dsa/b53/b53_common.c b/drivers/net/dsa/b53/b53_common.c index ffbf5efd8d9517..ee2d27732c0c8c 100644 --- a/drivers/net/dsa/b53/b53_common.c +++ b/drivers/net/dsa/b53/b53_common.c @@ -1360,6 +1360,10 @@ static int b53_setup(struct dsa_switch *ds) return ret; } + ret = b53_mirror_init(ds); + if (ret) + return ret; + /* setup default vlan for filtering mode */ pvid = b53_default_pvid(dev); vl = &dev->vlans[pvid]; @@ -2629,27 +2633,103 @@ static u16 b53_mirror_capture_port(struct b53_device *dev, int port) return port; } +int b53_mirror_init(struct dsa_switch *ds) +{ + struct b53_device *dev = ds->priv; + u16 ingress = 0, egress = 0, cap_ctl = 0; + unsigned int port; + int ret; + + /* A switch reset may leave the previous mirror configuration intact. */ + ret = b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, 0); + if (ret) + return ret; + + ret = b53_write16(dev, B53_MGMT_PAGE, B53_IG_MIR_CTL, 0); + if (ret) + return ret; + + ret = b53_write16(dev, B53_MGMT_PAGE, B53_EG_MIR_CTL, 0); + if (ret) + return ret; + + /* DSA retains matchall filters across suspend and resume. */ + for (port = 0; port < dev->num_ports; port++) { + if (dev->ports[port].mirror_count[true]) + ingress |= b53_mirror_port_mask(dev, port); + if (dev->ports[port].mirror_count[false]) + egress |= b53_mirror_port_mask(dev, port); + } + + if (!(ingress | egress)) + return 0; + + cap_ctl = MIRROR_EN | b53_mirror_capture_port(dev, dev->mirror_port); + ret = b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, cap_ctl); + if (ret) + return ret; + + ret = b53_write16(dev, B53_MGMT_PAGE, B53_IG_MIR_CTL, ingress); + if (ret) + return ret; + + return b53_write16(dev, B53_MGMT_PAGE, B53_EG_MIR_CTL, egress); +} +EXPORT_SYMBOL(b53_mirror_init); + int b53_mirror_add(struct dsa_switch *ds, int port, struct dsa_mall_mirror_tc_entry *mirror, bool ingress, struct netlink_ext_ack *extack) { struct b53_device *dev = ds->priv; - u16 reg, loc; + unsigned int *mirror_count = &dev->ports[port].mirror_count[ingress]; + u16 reg, other_reg, loc, other_loc, cap_ctl; + u16 cap_mask = b53_mirror_capture_port_mask(dev); + u16 cap_port = b53_mirror_capture_port(dev, mirror->to_local_port); + int ret; - if (ingress) - loc = B53_IG_MIR_CTL; - else - loc = B53_EG_MIR_CTL; + loc = ingress ? B53_IG_MIR_CTL : B53_EG_MIR_CTL; + other_loc = ingress ? B53_EG_MIR_CTL : B53_IG_MIR_CTL; - b53_read16(dev, B53_MGMT_PAGE, loc, ®); - reg |= b53_mirror_port_mask(dev, port); - b53_write16(dev, B53_MGMT_PAGE, loc, reg); + ret = b53_read16(dev, B53_MGMT_PAGE, loc, ®); + if (ret) + return ret; - b53_read16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, ®); - reg &= ~b53_mirror_capture_port_mask(dev); - reg |= b53_mirror_capture_port(dev, mirror->to_local_port); - reg |= MIRROR_EN; - b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, reg); + ret = b53_read16(dev, B53_MGMT_PAGE, other_loc, &other_reg); + if (ret) + return ret; + + ret = b53_read16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, &cap_ctl); + if (ret) + return ret; + + if (((reg | other_reg) & MIRROR_MASK) && + (cap_ctl & cap_mask) != cap_port) { + NL_SET_ERR_MSG_MOD(extack, + "Only one mirroring destination is supported"); + return -EOPNOTSUPP; + } + + if (*mirror_count) { + (*mirror_count)++; + return 0; + } + + /* Select the destination before enabling the new source. */ + cap_ctl &= ~cap_mask; + cap_ctl |= cap_port; + cap_ctl |= MIRROR_EN; + ret = b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, cap_ctl); + if (ret) + return ret; + + ret = b53_write16(dev, B53_MGMT_PAGE, loc, + reg | b53_mirror_port_mask(dev, port)); + if (ret) + return ret; + + (*mirror_count)++; + dev->mirror_port = mirror->to_local_port; return 0; } @@ -2659,38 +2739,54 @@ void b53_mirror_del(struct dsa_switch *ds, int port, struct dsa_mall_mirror_tc_entry *mirror) { struct b53_device *dev = ds->priv; - bool loc_disable = false, other_loc_disable = false; - u16 reg, loc; + unsigned int *mirror_count = + &dev->ports[port].mirror_count[mirror->ingress]; + u16 reg, other_reg, loc, other_loc; + int ret; - if (mirror->ingress) - loc = B53_IG_MIR_CTL; - else - loc = B53_EG_MIR_CTL; + if (!*mirror_count) + return; + + if (--(*mirror_count)) + return; + + loc = mirror->ingress ? B53_IG_MIR_CTL : B53_EG_MIR_CTL; + other_loc = mirror->ingress ? B53_EG_MIR_CTL : B53_IG_MIR_CTL; /* Update the desired ingress/egress register */ - b53_read16(dev, B53_MGMT_PAGE, loc, ®); + ret = b53_read16(dev, B53_MGMT_PAGE, loc, ®); + if (ret) + goto err; + reg &= ~b53_mirror_port_mask(dev, port); - if (!(reg & MIRROR_MASK)) - loc_disable = true; - b53_write16(dev, B53_MGMT_PAGE, loc, reg); + ret = b53_write16(dev, B53_MGMT_PAGE, loc, reg); + if (ret) + goto err; /* Now look at the other one to know if we can disable mirroring * entirely */ - if (mirror->ingress) - b53_read16(dev, B53_MGMT_PAGE, B53_EG_MIR_CTL, ®); - else - b53_read16(dev, B53_MGMT_PAGE, B53_IG_MIR_CTL, ®); - if (!(reg & MIRROR_MASK)) - other_loc_disable = true; + ret = b53_read16(dev, B53_MGMT_PAGE, other_loc, &other_reg); + if (ret) + goto err; - b53_read16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, ®); - /* Both no longer have ports, let's disable mirroring */ - if (loc_disable && other_loc_disable) { - reg &= ~MIRROR_EN; - reg &= ~b53_mirror_capture_port_mask(dev); - } - b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, reg); + if ((reg | other_reg) & MIRROR_MASK) + return; + + ret = b53_read16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, ®); + if (ret) + goto err; + + reg &= ~(MIRROR_EN | b53_mirror_capture_port_mask(dev)); + ret = b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, reg); + if (ret) + goto err; + + return; + +err: + dev_err(dev->dev, "Failed to delete mirror rule for port %d: %d\n", + port, ret); } EXPORT_SYMBOL(b53_mirror_del); diff --git a/drivers/net/dsa/b53/b53_priv.h b/drivers/net/dsa/b53/b53_priv.h index c4d2a41c714f62..df00a5ae46c9d3 100644 --- a/drivers/net/dsa/b53/b53_priv.h +++ b/drivers/net/dsa/b53/b53_priv.h @@ -119,6 +119,8 @@ struct b53_pcs { #define B53_N_PCS 2 struct b53_port { + /* References to each egress/ingress mirror source mask bit. */ + unsigned int mirror_count[2]; u16 vlan_ctl_mask; u16 pvid; struct ethtool_keee eee; @@ -170,6 +172,7 @@ struct b53_device { /* run time configuration */ bool enable_jumbo; + unsigned int mirror_port; unsigned int num_vlans; struct b53_vlan *vlans; @@ -545,6 +548,7 @@ int b53_mdb_add(struct dsa_switch *ds, int port, int b53_mdb_del(struct dsa_switch *ds, int port, const struct switchdev_obj_port_mdb *mdb, struct dsa_db db); +int b53_mirror_init(struct dsa_switch *ds); int b53_mirror_add(struct dsa_switch *ds, int port, struct dsa_mall_mirror_tc_entry *mirror, bool ingress, struct netlink_ext_ack *extack); diff --git a/drivers/net/dsa/bcm_sf2.c b/drivers/net/dsa/bcm_sf2.c index 1747a1f20c78e2..cbaa5de9b1072f 100644 --- a/drivers/net/dsa/bcm_sf2.c +++ b/drivers/net/dsa/bcm_sf2.c @@ -1061,6 +1061,10 @@ static int bcm_sf2_sw_setup(struct dsa_switch *ds) unsigned int port; int ret; + ret = b53_mirror_init(ds); + if (ret) + return ret; + /* Enable all valid ports and disable those unused */ for (port = 0; port < priv->hw_params.num_ports; port++) { /* IMP port receives special treatment */ From 846a6d0982be30aaba5268aac14a0c557d70cc23 Mon Sep 17 00:00:00 2001 From: Wang Haoran Date: Thu, 19 Nov 2026 16:15:02 +0800 Subject: [PATCH 1773/2102] net: bcmasp: avoid refcount drain on probe bcmasp_probe() calls of_find_node_by_name(dev->of_node, "ethernet-ports"), which unconditionally drops the from-node reference the caller never held. Every probe or bind cycle that reaches the port scan, including ones that later fail with "No ports found", drains the asp node refcount by one. Once it hits zero, of_node_release() deadlocks in its error printk (%pOF on the parent while holding devtree_lock with IRQs off), so the machine freezes silently with nothing on the console. Use of_get_child_by_name() which leaves the parent reference alone. Fixes: 490cb412007d ("net: bcmasp: Add support for ASP2.0 Ethernet controller") Signed-off-by: Wang Haoran Link: https://patch.msgid.link/1795076102979-9-385853cc@mail.zgclab.edu.cn Signed-off-by: Willem de Bruijn --- drivers/net/ethernet/broadcom/asp2/bcmasp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/ethernet/broadcom/asp2/bcmasp.c b/drivers/net/ethernet/broadcom/asp2/bcmasp.c index a59a006cea3a73..af9e1421498786 100644 --- a/drivers/net/ethernet/broadcom/asp2/bcmasp.c +++ b/drivers/net/ethernet/broadcom/asp2/bcmasp.c @@ -1342,7 +1342,7 @@ static int bcmasp_probe(struct platform_device *pdev) bcmasp_init_wol(priv); - ports_node = of_find_node_by_name(dev->of_node, "ethernet-ports"); + ports_node = of_get_child_by_name(dev->of_node, "ethernet-ports"); if (!ports_node) { dev_warn(dev, "No ports found\n"); ret = -EINVAL; From ef7bf0628915c18d9391fb0c1fa78b581ab2c4be Mon Sep 17 00:00:00 2001 From: Jason Xing Date: Fri, 20 Nov 2026 15:39:17 +0800 Subject: [PATCH 1774/2102] xsk: set network header on skb at generic transmit When constructing an skb in the XSK generic transmit path, neither xsk_build_skb() nor xsk_build_skb_zerocopy() calls skb_reset_network_header(). After __finalize_skb_around(), the network_header offset defaults to 0 (pointing to skb->head). The subsequent skb_reserve(skb, hr) moves skb->data forward by hr bytes, but leaves network_header still at 0. This makes skb_network_offset() return a negative value (-hr). When such an skb reaches a tunnel driver like ipgre_xmit(), the call chain pskb_inet_may_pull() -> pskb_network_may_pull_reason() computes: pskb_may_pull_reason(skb, skb_network_offset(skb) + nhlen) The negative int from skb_network_offset() is implicitly promoted to unsigned int, wrapping around to a huge value. This triggers the DEBUG_NET_WARN_ON_ONCE(len > INT_MAX) in pskb_may_pull_reason(). Call trace from syzkaller: ipgre_xmit+0x958/0xcd0 net/ipv4/ip_gre.c:658 __netdev_start_xmit include/linux/netdevice.h:5400 netdev_start_xmit include/linux/netdevice.h:5409 __dev_direct_xmit+0x4b6/0x730 net/core/dev.c:4942 __xsk_generic_xmit net/xdp/xsk.c:1079 xsk_generic_xmit+0x277a/0x40a0 net/xdp/xsk.c:1120 Reset the network header so skb_network_offset() is valid (0). For the non-CHECKSUM_PARTIAL case, unlike AF_PACKET, AF_XDP does not need to locate the real L2/L3 boundary: an AF_XDP frame is always a complete, opaque blob from userspace. So resetting the network header is enough to restore the invariant and avoid the crash. Note this is not sufficient for CHECKSUM_PARTIAL skbs, where drivers derive the L2/L3 split from the header offsets for checksum offload; that will be handled separately after this patch. Fixes: 3914d88f7608 ("xsk: Respect device's headroom and tailroom on generic xmit path") Cc: stable@vger.kernel.org Reported-by: James Sawyer Reported-by: syzbot+f16c1b285c9f63994eec@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=f16c1b285c9f63994eec Signed-off-by: Jason Xing Tested-by: James Sawyer Reviewed-by: Maciej Fijalkowski Link: https://patch.msgid.link/20261120073917.63158-1-kerneljasonxing@gmail.com Signed-off-by: Willem de Bruijn --- net/xdp/xsk.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/net/xdp/xsk.c b/net/xdp/xsk.c index ab2e4fa87a4f00..18cbd50047d80b 100644 --- a/net/xdp/xsk.c +++ b/net/xdp/xsk.c @@ -948,6 +948,8 @@ static int xsk_skb_init_misc(struct sk_buff *skb, struct xdp_sock *xs, { int err; + skb_reset_network_header(skb); + err = xsk_skb_destructor_set_addr(skb, addr); if (unlikely(err)) return err; From aa5a537ec43c13e4d2850468b0d88f97cce45dd3 Mon Sep 17 00:00:00 2001 From: Nicolai Buchwitz Date: Fri, 20 Nov 2026 23:42:35 +0100 Subject: [PATCH 1775/2102] net: bcmgenet: keep DIM from getting stuck after close or suspend A close or WoL suspend cancels the pending profile work and can leave DIM in DIM_APPLY_NEW_PROFILE, where net_dim() does nothing. Adaptive coalescing then stays stuck after the next open or resume, and the profile index no longer matches the hardware. The poll also calls net_dim() after napi_complete_done(), so it can queue new work after napi_disable() has returned. Run net_dim() before completing NAPI and flush the work instead of cancelling it, so the pending profile gets applied. Also reset the DIM state on ring init and start from the default profile, which is what bcmgenet_init_rx_coalesce() programs. Fixes: 9f4ca05827a2 ("net: bcmgenet: Add support for adaptive RX coalescing") Signed-off-by: Nicolai Buchwitz Reviewed-by: Florian Fainelli Signed-off-by: Willem de Bruijn --- drivers/net/ethernet/broadcom/genet/bcmgenet.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/drivers/net/ethernet/broadcom/genet/bcmgenet.c b/drivers/net/ethernet/broadcom/genet/bcmgenet.c index 4d2be2a21ed1bc..f702916e7bfaf7 100644 --- a/drivers/net/ethernet/broadcom/genet/bcmgenet.c +++ b/drivers/net/ethernet/broadcom/genet/bcmgenet.c @@ -2502,15 +2502,16 @@ static int bcmgenet_rx_poll(struct napi_struct *napi, int budget) work_done = bcmgenet_desc_rx(ring, budget); - if (work_done < budget && napi_complete_done(napi, work_done)) - bcmgenet_rx_ring_int_enable(ring); - + /* net_dim() can queue work, so run it while NAPI is still owned */ if (ring->dim.use_dim) { dim_update_sample(ring->dim.event_ctr, ring->dim.packets, ring->dim.bytes, &dim_sample); net_dim(&ring->dim.dim, &dim_sample); } + if (work_done < budget && napi_complete_done(napi, work_done)) + bcmgenet_rx_ring_int_enable(ring); + return work_done; } @@ -2702,8 +2703,11 @@ static void bcmgenet_init_dim(struct bcmgenet_rx_ring *ring, { struct bcmgenet_net_dim *dim = &ring->dim; + memset(&dim->dim, 0, sizeof(dim->dim)); INIT_WORK(&dim->dim.work, cb); dim->dim.mode = DIM_CQ_PERIOD_MODE_START_FROM_EQE; + /* Match the profile bcmgenet_init_rx_coalesce() programs */ + dim->dim.profile_ix = NET_DIM_DEF_PROFILE_EQE; dim->event_ctr = 0; dim->packets = 0; dim->bytes = 0; @@ -3014,7 +3018,8 @@ static void bcmgenet_disable_rx_napi(struct bcmgenet_priv *priv) for (i = 0; i <= priv->hw_params->rx_queues; ++i) { ring = &priv->rx_rings[i]; napi_disable(&ring->napi); - cancel_work_sync(&ring->dim.dim.work); + /* Cancelling would leave DIM stuck in DIM_APPLY_NEW_PROFILE */ + flush_work(&ring->dim.dim.work); } } From a15079369636f4324d2985cede7ce7fbefddf4b3 Mon Sep 17 00:00:00 2001 From: Nicolai Buchwitz Date: Fri, 20 Nov 2026 23:42:36 +0100 Subject: [PATCH 1776/2102] net: bcmgenet: accumulate the DIM packet and byte counters net_dim() computes rates from the difference between two samples and needs running totals, but bcmgenet_desc_rx() passes the counts of the last poll. Adaptive coalescing then picks profiles from wrong rates. On a CM4 at a steady 300 Mbit/s UDP, DIM changed profile about 1000 times in 20 s. With the fix it settles, and Rx interrupts drop from about 4500/s to 2240/s. Accumulate the counters instead. Fixes: 9f4ca05827a2 ("net: bcmgenet: Add support for adaptive RX coalescing") Reviewed-by: Florian Fainelli Signed-off-by: Nicolai Buchwitz Signed-off-by: Willem de Bruijn --- drivers/net/ethernet/broadcom/genet/bcmgenet.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/net/ethernet/broadcom/genet/bcmgenet.c b/drivers/net/ethernet/broadcom/genet/bcmgenet.c index f702916e7bfaf7..f9f38445568fcf 100644 --- a/drivers/net/ethernet/broadcom/genet/bcmgenet.c +++ b/drivers/net/ethernet/broadcom/genet/bcmgenet.c @@ -2486,8 +2486,8 @@ static unsigned int bcmgenet_desc_rx(struct bcmgenet_rx_ring *ring, bcmgenet_rdma_ring_writel(priv, ring->index, ring->c_index, RDMA_CONS_INDEX); } - ring->dim.bytes = bytes_processed; - ring->dim.packets = rxpktprocessed; + ring->dim.bytes += bytes_processed; + ring->dim.packets += rxpktprocessed; return rxpktprocessed; } From e99faa3a16209ea5d0b83cc58b64785efd2d9045 Mon Sep 17 00:00:00 2001 From: Nicolai Buchwitz Date: Fri, 20 Nov 2026 23:42:37 +0100 Subject: [PATCH 1777/2102] net: bcmgenet: reset the Rx discard count with the ring Ring init clears the hardware discard counter but not ring->old_discards. Discards after an ifdown and ifup or a resume are then missing from rx_missed. On a CM4, after an ifdown and ifup, 3666 discards showed up as 0 in rx_missed. Reset old_discards together with the ring. Fixes: d26ea6cc48da ("net: bcmgenet: collect Rx discarded packet count") Reviewed-by: Florian Fainelli Signed-off-by: Nicolai Buchwitz Signed-off-by: Willem de Bruijn --- drivers/net/ethernet/broadcom/genet/bcmgenet.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/net/ethernet/broadcom/genet/bcmgenet.c b/drivers/net/ethernet/broadcom/genet/bcmgenet.c index f9f38445568fcf..b81408e6293c3f 100644 --- a/drivers/net/ethernet/broadcom/genet/bcmgenet.c +++ b/drivers/net/ethernet/broadcom/genet/bcmgenet.c @@ -2826,6 +2826,8 @@ static int bcmgenet_init_rx_ring(struct bcmgenet_priv *priv, ring->read_ptr = start_ptr; ring->cb_ptr = start_ptr; ring->end_ptr = end_ptr - 1; + /* Zeroing RDMA_PROD_INDEX below also clears the discard counter */ + ring->old_discards = 0; ret = bcmgenet_rx_ring_create_pool(priv, ring); if (ret) From 8e428e263fa4fd3a752db8d9e1e584307f446aae Mon Sep 17 00:00:00 2001 From: Nicolai Buchwitz Date: Fri, 20 Nov 2026 23:42:38 +0100 Subject: [PATCH 1778/2102] net: systemport: restart DIM from the default profile on start A close or suspend can cancel the pending profile work and leave DIM in DIM_APPLY_NEW_PROFILE, where net_dim() does nothing. Adaptive coalescing then stays stuck after the next open or resume. The poll also calls net_dim() after napi_complete_done(), so it can queue new work after napi_disable() has returned. Run net_dim() before completing NAPI. Reset the DIM state on start and begin from the default profile, which is what bcm_sysport_init_rx_coalesce() programs. Fixes: b6e0e875421e ("net: systemport: Implement adaptive interrupt coalescing") Signed-off-by: Nicolai Buchwitz Signed-off-by: Willem de Bruijn --- drivers/net/ethernet/broadcom/bcmsysport.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/drivers/net/ethernet/broadcom/bcmsysport.c b/drivers/net/ethernet/broadcom/bcmsysport.c index bc88a27da16bee..29e608e7daaf6b 100644 --- a/drivers/net/ethernet/broadcom/bcmsysport.c +++ b/drivers/net/ethernet/broadcom/bcmsysport.c @@ -1012,18 +1012,19 @@ static int bcm_sysport_poll(struct napi_struct *napi, int budget) else rdma_writel(priv, priv->rx_c_index << 16, RDMA_CONS_INDEX); - if (work_done < budget) { - napi_complete_done(napi, work_done); - /* re-enable RX interrupts */ - intrl2_0_mask_clear(priv, INTRL2_0_RDMA_MBDONE); - } - + /* net_dim() can queue work, so run it while NAPI is still owned */ if (priv->dim.use_dim) { dim_update_sample(priv->dim.event_ctr, priv->dim.packets, priv->dim.bytes, &dim_sample); net_dim(&priv->dim.dim, &dim_sample); } + if (work_done < budget) { + napi_complete_done(napi, work_done); + /* re-enable RX interrupts */ + intrl2_0_mask_clear(priv, INTRL2_0_RDMA_MBDONE); + } + return work_done; } @@ -1452,8 +1453,11 @@ static void bcm_sysport_init_dim(struct bcm_sysport_priv *priv, { struct bcm_sysport_net_dim *dim = &priv->dim; + memset(&dim->dim, 0, sizeof(dim->dim)); INIT_WORK(&dim->dim.work, cb); dim->dim.mode = DIM_CQ_PERIOD_MODE_START_FROM_EQE; + /* Match the profile bcm_sysport_init_rx_coalesce() programs */ + dim->dim.profile_ix = NET_DIM_DEF_PROFILE_EQE; dim->event_ctr = 0; dim->packets = 0; dim->bytes = 0; From 3e7e20beef4ec04f7601e92e78608333f2ab3904 Mon Sep 17 00:00:00 2001 From: Nicolai Buchwitz Date: Fri, 20 Nov 2026 23:42:39 +0100 Subject: [PATCH 1779/2102] net: systemport: accumulate the DIM packet and byte counters net_dim() computes rates from the difference between two samples and needs running totals, but bcm_sysport_desc_rx() passes the counts of the last poll. Adaptive coalescing then picks profiles from wrong rates. Accumulate the counters instead. Fixes: b6e0e875421e ("net: systemport: Implement adaptive interrupt coalescing") Reviewed-by: Florian Fainelli Signed-off-by: Nicolai Buchwitz Signed-off-by: Willem de Bruijn --- drivers/net/ethernet/broadcom/bcmsysport.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/net/ethernet/broadcom/bcmsysport.c b/drivers/net/ethernet/broadcom/bcmsysport.c index 29e608e7daaf6b..0902dd0dd94bcb 100644 --- a/drivers/net/ethernet/broadcom/bcmsysport.c +++ b/drivers/net/ethernet/broadcom/bcmsysport.c @@ -844,8 +844,8 @@ static unsigned int bcm_sysport_desc_rx(struct bcm_sysport_priv *priv, priv->rx_read_ptr = 0; } - priv->dim.packets = processed; - priv->dim.bytes = processed_bytes; + priv->dim.packets += processed; + priv->dim.bytes += processed_bytes; return processed; } From 3ab5aae0eb60079d17378af5aab0db84ba946e0e Mon Sep 17 00:00:00 2001 From: Jiayuan Chen Date: Fri, 20 Nov 2026 17:46:59 +0800 Subject: [PATCH 1780/2102] ipv4: fix conntrack defrag forwarding after ip_frag_reinit() q.max_size and max_df_size are used by ip_frag_reasm() to set IPCB(skb)->frag_max_size and the DF bit of the reassembled packet. ip_frag_reinit() reuses the queue for a new datagram but does not reset them, so the new datagram inherits them from the old one. On a router with conntrack defrag, if the largest fragment of the old datagram had DF set and was larger than the egress MTU, a new datagram without DF gets DF set after reassembly and is rejected with ICMP_FRAG_NEEDED, even though all its fragments fit. Reset both fields. Fixes: 5f2d04f1f9b5 ("ipv4: fix path MTU discovery with connection tracking") Fixes: d6b915e29f4a ("ip_fragment: don't forward defragmented DF packet") Reviewed-by: Eric Dumazet Signed-off-by: Jiayuan Chen Link: https://patch.msgid.link/20261120094700.46500-1-jiayuan.chen@linux.dev Signed-off-by: Willem de Bruijn --- net/ipv4/ip_fragment.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/net/ipv4/ip_fragment.c b/net/ipv4/ip_fragment.c index ef7fd61284a3fa..0688be8142c4b3 100644 --- a/net/ipv4/ip_fragment.c +++ b/net/ipv4/ip_fragment.c @@ -250,6 +250,8 @@ static int ip_frag_reinit(struct ipq *qp) qp->q.flags = 0; qp->q.len = 0; qp->q.meat = 0; + qp->q.max_size = 0; + qp->max_df_size = 0; qp->iif = 0; qp->ecn = 0; From cc7fe6e741730fef549e484379281736d32746f0 Mon Sep 17 00:00:00 2001 From: Antonio Quartulli Date: Thu, 19 Nov 2026 16:30:55 +0100 Subject: [PATCH 1781/2102] tun: bound the NAPI receive queue With IFF_NAPI, tun_get_user() queues every written packet for NAPI on an unbounded list. When the poll runs asynchronously (threaded NAPI or ksoftirqd) and is slower than the writer, the queue grows until the system runs out of memory. An unprivileged user can do this from its own user and network namespaces, and the queued skbs are not charged to its memcg: in a test VM, a uid 1000 process limited to 128 MB caused a global OOM in ~6 seconds. The socket send buffer does not help: tun sets it to INT_MAX by default, the build_skb() path is only used while it is INT_MAX, and the XDP batch path never checks it. Drop packets once more than netdev_max_backlog of them are queued, like enqueue_to_backlog() does, and count them as rx_dropped; the write still reports success, as for a full backlog. The check sits where packets are queued for NAPI, in tun_get_user() and in tun_xdp_one() for the batches vhost-net passes, so packets consumed by XDP or delivered through IFF_NAPI_FRAGS are not affected. A dropped zerocopy skb completes its buffer when freed. The check is lockless, so concurrent writers can each still add one packet. The NAPI poll moved the whole queue out, processed up to its budget and put the rest back: while it ran, the queue looked empty to writers, so with the poll on another CPU the backlog could still grow without limit. Take at most budget packets instead: the rest stays on the queue writers check. Dropping also schedules NAPI. vhost-net sends with MSG_MORE while it has more packets, and tun_get_user() schedules NAPI only for a packet without it or once more than NAPI_POLL_WEIGHT are queued. With a netdev_max_backlog below that, the queue fills first and the packet without MSG_MORE is dropped too: nothing would schedule NAPI, and the queued packets, with zerocopy also their buffers, would wait forever. Reproducer, as an unprivileged user in a new user and network namespace, without kernel modifications or fault injection: ip tuntap add t0 mode tun; ip addr add 10.11.0.1/24 dev t0 ip link add d0 type dummy; ip addr add 10.20.0.1/24 dev d0 ip link set t0 up; ip link set d0 up; sysctl net.ipv4.ip_forward=1 install ~500 iptables FORWARD rules, to slow down the poll, and a MASQUERADE rule on d0 open t0 with IFF_TUN | IFF_NO_PI | IFF_NAPI echo 1 > /sys/class/net/t0/threaded write() 1400-byte IPv4 packets for 10.20.0.2 in a loop Found by code inspection while analysing the performance of the tun write path. Tested in an x86-64 VM on net, with 1 and 2 vCPUs: the reproducer causes a global OOM without the patch, while with it memory use stays flat and the forwarding rate is unchanged; the tun kselftest passes; a local vhost-net test of the batch, copy and zerocopy paths with netdev_max_backlog set to 8 passes, and fails without the patch; an XDP program on the device sees every packet while the excess is dropped. Still open: neither the packet size nor the queued memory is bounded, and the skbs are not charged to the writer's memcg. A single write can create an skb of several hundred KB, so even one queue can hold a lot, and IFF_MULTI_QUEUE (allowed in a user namespace) and more devices multiply it. This bounds the queue as enqueue_to_backlog() bounds the per-CPU backlog; charging the skbs to the writer is left to a follow-up. Fixes: 943170998b20 ("tun: enable NAPI for TUN/TAP driver") Signed-off-by: Antonio Quartulli Reviewed-by: Willem de Bruijn Link: https://patch.msgid.link/20261119153056.353156-1-antonio@mandelbit.com Signed-off-by: Willem de Bruijn --- drivers/net/tun.c | 52 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/drivers/net/tun.c b/drivers/net/tun.c index 5178c11ba5b137..ae05b1e58abaa2 100644 --- a/drivers/net/tun.c +++ b/drivers/net/tun.c @@ -58,6 +58,7 @@ #include #include #include +#include #include #include #include @@ -227,6 +228,16 @@ struct veth { static void tun_flow_init(struct tun_struct *tun); static void tun_flow_uninit(struct tun_struct *tun); +/* In IFF_NAPI mode written packets wait in the tfile's sk_write_queue for the + * NAPI poll, which may run later in a kthread or ksoftirqd. Bound that queue + * like the per-CPU backlog. + */ +static bool tun_napi_queue_full(const struct sk_buff_head *queue) +{ + return skb_queue_len_lockless(queue) > + READ_ONCE(net_hotdata.max_backlog); +} + static int tun_napi_receive(struct napi_struct *napi, int budget) { struct tun_file *tfile = container_of(napi, struct tun_file, napi); @@ -237,21 +248,22 @@ static int tun_napi_receive(struct napi_struct *napi, int budget) __skb_queue_head_init(&process_queue); + /* At most budget skbs: the rest stays on the queue writers check */ spin_lock(&queue->lock); - skb_queue_splice_tail_init(queue, &process_queue); + if (skb_queue_len(queue) <= budget) { + skb_queue_splice_tail_init(queue, &process_queue); + } else { + while (skb_queue_len(&process_queue) < budget && + (skb = __skb_dequeue(queue))) + __skb_queue_tail(&process_queue, skb); + } spin_unlock(&queue->lock); - while (received < budget && (skb = __skb_dequeue(&process_queue))) { + while ((skb = __skb_dequeue(&process_queue))) { napi_gro_receive(napi, skb); ++received; } - if (!skb_queue_empty(&process_queue)) { - spin_lock(&queue->lock); - skb_queue_splice(&process_queue, queue); - spin_unlock(&queue->lock); - } - return received; } @@ -2050,6 +2062,19 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, struct sk_buff_head *queue = &tfile->sk.sk_write_queue; int queue_len; + /* Queue full: drop, and schedule NAPI, which a MSG_MORE sender + * may not have done yet. Lockless: concurrent writers can each + * still add one. + */ + if (unlikely(tun_napi_queue_full(queue))) { + local_bh_disable(); + napi_schedule(&tfile->napi); + local_bh_enable(); + rcu_read_unlock(); + drop_reason = SKB_DROP_REASON_FULL_RING; + goto drop; + } + spin_lock_bh(&queue->lock); if (unlikely(tfile->detached)) { @@ -2665,6 +2690,17 @@ static int tun_xdp_one(struct tun_struct *tun, if (tfile->napi_enabled) { queue = &tfile->sk.sk_write_queue; + + /* Queue full: drop, and schedule NAPI so that it drains even if + * nothing in this batch gets queued. + */ + if (unlikely(tun_napi_queue_full(queue))) { + napi_schedule(&tfile->napi); + kfree_skb_reason(skb, SKB_DROP_REASON_FULL_RING); + dev_core_stats_rx_dropped_inc(tun->dev); + return 0; + } + spin_lock(&queue->lock); if (unlikely(tfile->detached)) { From 73f17a98ea707b505b75c45f1ad7535f8d060195 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Tue, 24 Nov 2026 20:54:12 +0100 Subject: [PATCH 1782/2102] bpf: net_sched: Defer bpf_kfree_skb() to irq_work with irqs off bpf_kfree_skb() is also the destructor of an skb kptr. A destructor runs wherever an object or a map value with such a field is freed. That can be with irqs off, for example: - bpf_list_add() drops the new node when @prev is not in the list, while the program holds the bpf_spin_lock of the list, which keeps irqs off. The drop frees a node that has no other reference, with its fields. - bpf_local_storage_map_free() frees the fields of each value under the lock of its bucket, which bpf_selem_unlink_nofail() takes with raw_res_spin_lock_irqsave(). A qdisc program can keep an skb in task storage. The rq lock can be held as well. A program that shares a list with the qdisc program gets there: prog drops the node with ---------------------- ---------------------------------------- sched_ext ops.dispatch bpf_obj_drop() tp_btf/sched_switch bpf_list_add(), @prev is not in the list The check from commit 94c8d1c21be4 ("bpf: Reject bpf_obj_drop() from tracing progs") catches neither. Currently bpf_kfree_skb() calls kfree_skb(), which is not made for that. The destructor of the skb may enable softirqs, take a lock that sleeps on PREEMPT_RT, or wake a task. sock_wfree() wakes the task that waits for the socket to become writable, and under the rq lock that deadlocks: __schedule() holds rq lock, irqs are off bpf_kfree_skb_dtor(skb) kfree_skb(skb) sock_wfree(skb) a task polls the socket for write __wake_up_common_lock() try_to_wake_up() the task belongs on this cpu rq_lock(rq) <- same rq dev_kfree_skb_any() does not solve it. With irqs off it leaves the skb to NET_TX_SOFTIRQ, and raising a softirq outside of an interrupt wakes ksoftirqd: __schedule() holds rq lock, irqs are off bpf_kfree_skb_dtor(skb) dev_kfree_skb_irq_reason(skb) raise_softirq_irqoff() in_interrupt() == 0 wake_up_process(ksoftirqd) ttwu_queue() cpu == this_cpu rq_lock(rq) <- same rq With irqs on it is kfree_skb(), which on PREEMPT_RT must not run with preemption off either, as after bpf_preempt_disable(): bpf_kfree_skb(skb) preempt_count() == 1 sock_wfree(skb) a writer sleeps in sk_wq __wake_up_common_lock() spin_lock_irqsave(&wq_head->lock) Free the skb from an irq_work in these contexts, like bpf_async_refcount_put() does: with irqs off, and on PREEMPT_RT whenever the caller is not preemptible. The skb waits on a lock-less list, linked through skb->ll_node. A shared skb only loses the reference of the caller: as in dev_kfree_skb_irq_reason(), the last reference is the one that may link the skb. The irq_work frees the list with dev_kfree_skb_any(). Without PREEMPT_RT it runs in hard irq context, where dev_kfree_skb_any() leaves the skb to NET_TX_SOFTIRQ and wakes nobody. With PREEMPT_RT it runs in the irq_work thread, where dev_kfree_skb_any() is kfree_skb() and may sleep. Everywhere else bpf_kfree_skb() remains kfree_skb(). Qdisc_ops::enqueue and Qdisc_ops::dequeue run with irqs on, so a qdisc pays for the test of the irq flag and no more. NET_SCH_BPF cannot be a module, so no exit path has to wait for the irq_work. Fixes: 870c28588afa ("bpf: net_sched: Add basic bpf qdisc kfuncs") Signed-off-by: Alexei Starovoitov Signed-off-by: Kumar Kartikeya Dwivedi Link: https://patch.msgid.link/7a28c63f6b3d61442dbee1950f9a76d278a0f5be.1795550039.git.memxor@gmail.com --- net/sched/bpf_qdisc.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/net/sched/bpf_qdisc.c b/net/sched/bpf_qdisc.c index 5691c13781a8b0..de0c3869e403ed 100644 --- a/net/sched/bpf_qdisc.c +++ b/net/sched/bpf_qdisc.c @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -184,6 +185,19 @@ static int bpf_qdisc_gen_epilogue(struct bpf_insn *insn_buf, const struct bpf_pr return insn - insn_buf; } +static LLIST_HEAD(bpf_skb_free_list); + +static void bpf_skb_free_irq_work(struct irq_work *work) +{ + struct llist_node *list = llist_del_all(&bpf_skb_free_list); + struct sk_buff *skb, *next; + + llist_for_each_entry_safe(skb, next, list, ll_node) + dev_kfree_skb_any(skb); +} + +static DEFINE_IRQ_WORK(bpf_skb_free_work, bpf_skb_free_irq_work); + __bpf_kfunc_start_defs(); /* bpf_skb_get_hash - Get the flow hash of an skb. @@ -196,9 +210,22 @@ __bpf_kfunc u32 bpf_skb_get_hash(struct sk_buff *skb) /* bpf_kfree_skb - Release an skb's reference and drop it immediately. * @skb: The skb whose reference to be released and dropped. + * + * Also the destructor of an skb kptr, which runs wherever an object or a map + * value with such a field is freed: under a bpf_spin_lock too, with irqs off. + * rq lock can be held as well, so don't wake up ksoftirqd from here. */ __bpf_kfunc void bpf_kfree_skb(struct sk_buff *skb) { + if (irqs_disabled() || + (IS_ENABLED(CONFIG_PREEMPT_RT) && !preemptible())) { + /* Only the last reference may link the skb. */ + if (refcount_dec_not_one(&skb->users)) + return; + llist_add(&skb->ll_node, &bpf_skb_free_list); + irq_work_queue(&bpf_skb_free_work); + return; + } kfree_skb(skb); } From 81c6c8c608b6075846d3bd5b6f57958300a56eda Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Tue, 24 Nov 2026 20:54:56 +0100 Subject: [PATCH 1783/2102] bpf: Save irq flags on the stack when freeing a list head or rb root bpf_spin_lock() saves the irq flags in the per-cpu variable irqsave_flags, and bpf_spin_unlock() restores them from there. One word per cpu is enough as long as a cpu takes no second bpf_spin_lock before it releases the first. bpf_list_head_free() and bpf_rb_root_free() take a second one. They lock the list or the tree that they free with __bpf_spin_lock_irqsave(), and they can run while a program holds a bpf_spin_lock of its own. bpf_list_add(), bpf_list_push_front(), bpf_list_push_back() and bpf_rbtree_add() drop the node when they fail. The drop frees a node that has no other reference, with its fields, and the node can have a list or a tree itself, like struct foo of the selftests' linked_list.h: bpf_spin_lock(&glock) irqsave_flags = on bpf_list_add(&ghead, foo, prev) prev is not in the list bpf_list_head_free(&foo->head) __bpf_spin_lock_irqsave() irqsave_flags = off bpf_spin_unlock(&glock) restores off The program returns with irqs off. Keep the flags of the two functions in a local variable, and take the lock with __bpf_spin_lock(). Both functions unlock before they drop the nodes, so nothing else runs between the save and the restore. A failed add drops the node since the commit below. Until bpf_list_add() existed, an add failed only for a node that a list or a tree still owned, with a reference of its own, so the drop freed the node only in a race with the release of that reference. bpf_list_add() fails for any node when @prev is not in the list. Fixes: d2dcc67df910 ("bpf: Migrate bpf_rbtree_add and bpf_list_push_{front,back} to possibly fail") Signed-off-by: Alexei Starovoitov Signed-off-by: Kumar Kartikeya Dwivedi Link: https://patch.msgid.link/178849392dfb8ddf82d7ba4259be6113349bdc2e.1795550092.git.memxor@gmail.com --- kernel/bpf/helpers.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index 6788489a2608b3..bc0dd36a2799a0 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -2302,6 +2302,7 @@ void bpf_list_head_free(const struct btf_field *field, void *list_head, struct bpf_spin_lock *spin_lock) { struct list_head *head = list_head, drain, *pos, *n; + unsigned long flags; BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head)); BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head)); @@ -2313,7 +2314,8 @@ void bpf_list_head_free(const struct btf_field *field, void *list_head, * section, and end up doing map ops that call bpf_list_head_free for * the same map value again. */ - __bpf_spin_lock_irqsave(spin_lock); + local_irq_save(flags); + __bpf_spin_lock(spin_lock); if (!head->next || list_empty(head)) goto unlock; list_for_each_safe(pos, n, head) { @@ -2325,7 +2327,8 @@ void bpf_list_head_free(const struct btf_field *field, void *list_head, } unlock: INIT_LIST_HEAD(head); - __bpf_spin_unlock_irqrestore(spin_lock); + __bpf_spin_unlock(spin_lock); + local_irq_restore(flags); while (!list_empty(&drain)) { struct bpf_list_node_kern *node; @@ -2362,19 +2365,22 @@ void bpf_rb_root_free(const struct btf_field *field, void *rb_root, struct rb_root_cached orig_root, *root = rb_root; struct bpf_rb_node_kern *node; struct rb_node *pos, *n; + unsigned long flags; void *obj; BUILD_BUG_ON(sizeof(struct rb_root_cached) > sizeof(struct bpf_rb_root)); BUILD_BUG_ON(__alignof__(struct rb_root_cached) > __alignof__(struct bpf_rb_root)); - __bpf_spin_lock_irqsave(spin_lock); + local_irq_save(flags); + __bpf_spin_lock(spin_lock); orig_root = *root; bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) { node = rb_entry(pos, struct bpf_rb_node_kern, rb_node); WRITE_ONCE(node->owner, BPF_PTR_POISON); } *root = RB_ROOT_CACHED; - __bpf_spin_unlock_irqrestore(spin_lock); + __bpf_spin_unlock(spin_lock); + local_irq_restore(flags); bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) { obj = pos; From 8871f7433d225c24b27c00a0a6130977b8b4c61e Mon Sep 17 00:00:00 2001 From: Dennis Rijsdijk Date: Tue, 24 Nov 2026 22:20:43 +0100 Subject: [PATCH 1784/2102] ALSA: usb-audio: Add generic implicit feedback quirk for Elgato Wave:3 The Elgato Wave:3 (0fd9:0070) records digital silence from its microphone when capture is started while playback to its headphone jack is already running. Starting capture first works. With PipeWire this makes the microphone go silent when an application starts recording while audio is playing. The Elgato XLR Dock had the same problem and was fixed by enforcing the generic implicit feedback mode. The same flag fixes the Wave:3: with it, capture returns audio in both start orders. One case remains at 96 kHz, which the device advertises but Elgato's specifications do not list (only 48 kHz): when playback starts first right after the device ran at 48 kHz, capture is still occasionally silent (2 of 10 tries, against every try without the flag). At a steady rate, and at 48 kHz in all cases tried, it did not happen. Add a quirk entry for the device. The patch and this description were prepared with an AI coding assistant (Claude Code, Claude Opus 5.5); I reproduced the problem and tested the fix on the device. Link: https://lore.kernel.org/all/CAOUQ8cqoTYm-0xeh1jk6bPo7Qd81+rFBz+my-ByMudzZ_6E0wQ@mail.gmail.com/ Signed-off-by: Dennis Rijsdijk Link: https://patch.msgid.link/20261124-b4-implicit-fb-v1-1-99c0526a01f0@dennis.gg Signed-off-by: Takashi Iwai --- sound/usb/quirks.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sound/usb/quirks.c b/sound/usb/quirks.c index bcc93e50b4ef04..bd00db820719d6 100644 --- a/sound/usb/quirks.c +++ b/sound/usb/quirks.c @@ -2684,6 +2684,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { QUIRK_FLAG_FIXED_RATE), DEVICE_FLG(0x0fd9, 0x0008, /* Hauppauge HVR-950Q */ QUIRK_FLAG_SHARE_MEDIA_DEVICE | QUIRK_FLAG_ALIGN_TRANSFER), + DEVICE_FLG(0x0fd9, 0x0070, /* Elgato Wave:3 */ + QUIRK_FLAG_GENERIC_IMPLICIT_FB), DEVICE_FLG(0x0fd9, 0x00a6, /* Elgato XLR Dock */ QUIRK_FLAG_GENERIC_IMPLICIT_FB), DEVICE_FLG(0x1038, 0x1294, /* SteelSeries Arctis Pro Wireless */ From 97e1c7d467d07734f8f5c8c64730e1f7c415bd46 Mon Sep 17 00:00:00 2001 From: Hang Zhengyang Date: Mon, 23 Nov 2026 02:04:54 +0800 Subject: [PATCH 1785/2102] sched_ext: Attach fair_server before tasks fall back to fair on disable In full mode, the enable path detaches fair_server, since no task runs in the fair class. scx_root_disable() attaches it again only at the end, in the dl_server_swap_bw() loop. But tasks fall back to fair well before that. New forks and sched_setscheduler() calls do so once scx_switching_all is cleared, and the switch loop moves all other tasks. Until the swap, fair_server can't start, so an RT task that keeps a CPU starves the fair tasks there. Meanwhile, the disable path waits for RCU grace periods in percpu_down_write() of scx_fork_rwsem and scx_cgroup_ops_rwsem. A grace period can wait for a starved task, so the disable doesn't finish until the RT task stops. The starved task can be a reader preempted under PREEMPT_RCU, or the grace-period kthread itself. While the disable waits in the scx_cgroup_lock() after the switch loop, scx_fork_rwsem and cgroup_mutex are held, so forks wait too. To reproduce, load scx_simple, pin SCHED_NORMAL tasks (/proc walkers, stress-ng --fork) and a SCHED_FIFO spinner to CPU 1, and unload the scheduler 50 ms after the spinner starts. The disable can then get stuck in: synchronize_rcu_normal+0x1da/0x1f0 rcu_sync_enter+0x56/0x140 scx_root_disable+0x230/0x420 kthread_worker_fn+0xf0/0x270 until the spinner stops. Attach fair_server before tasks start to fall back, the same way the enable path attaches ext_server before tasks switch to it. If the root domain can't fit both servers, the swap attaches fair_server as before. Fixes: e7b63427fdb4 ("sched_ext: Auto-register/unregister dl_server reservations") Cc: stable@vger.kernel.org # v7.2+ Signed-off-by: Hang Zhengyang Signed-off-by: Tejun Heo --- kernel/sched/ext/ext.c | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c index dfda426c768fcf..efa1d01d03afa8 100644 --- a/kernel/sched/ext/ext.c +++ b/kernel/sched/ext/ext.c @@ -7576,6 +7576,21 @@ static void scx_root_disable(struct scx_sched *sch) was_switched_all = scx_switched_all(); + /* + * Tasks fall back to fair from here on. Attach fair_server now, or an + * RT task can starve them while we wait for RCU grace periods below. + * If its bandwidth doesn't fit, the swap at the end attaches it. + */ + if (was_switched_all) { + for_each_possible_cpu(cpu) { + struct rq *rq = cpu_rq(cpu); + + guard(rq_lock_irqsave)(rq); + update_rq_clock(rq); + dl_server_attach_bw(&rq->fair_server); + } + } + static_branch_disable(&__scx_switched_all); WRITE_ONCE(scx_switching_all, false); WRITE_ONCE(scx_task_switch_enabled, false); @@ -7626,8 +7641,8 @@ static void scx_root_disable(struct scx_sched *sch) /* * Re-balance the dl_server bandwidth reservations: detach ext_server - * (no more sched_ext tasks) and reinstate fair_server if it was - * previously detached because we were running in full mode. + * (no more sched_ext tasks) and attach fair_server if the attach + * above failed. * * Unlike the enable path, this runs on a recovery path that cannot * fail, so we use dl_server_swap_bw() to atomically free ext_server's From 655a830a248d9e465579d39911fe9aae86508973 Mon Sep 17 00:00:00 2001 From: SungHwan Jung Date: Wed, 25 Nov 2026 17:16:36 +0900 Subject: [PATCH 1786/2102] ALSA: hda/realtek: Fix distorted headphone audio on Acer Predator PHN16-71 On the Acer Predator PHN16-71, booting with headphones already plugged into the 3.5mm jack results in distorted headphone audio until the headphones are unplugged and replugged. Vendor COEF 0x4a reads 0x2010 when the distortion occurs, meaning that the Reset HP JD bit (BIT(15)) is already clear. Clearing the bit alone doesn't fix the issue. Add a dedicated fixup (ALC245_FIXUP_ACER_HP_JD_RESET) that sets and then clears COEF 0x4a BIT(15) during HDA_FIXUP_ACT_INIT while preserving the remaining coefficient bits. Chain ALC245_FIXUP_ACER_MICMUTE_LED to retain mic mute LED and headset microphone support. Testing confirmed that pulsing COEF 0x4a BIT(15) restores clean headphone audio. LLMs were used to assist in analyzing the cause of the headphone audio distortion and refining the commit message. Signed-off-by: SungHwan Jung Link: https://patch.msgid.link/20261125081636.4619-1-onenowy@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 39b2f329dc84d5..3617b6221abfcc 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -1462,6 +1462,17 @@ static void alc245_fixup_minisforum_jack_detect(struct hda_codec *codec, alc_update_coef_idx(codec, 0x4a, BIT(15), 0); } +static void alc245_fixup_acer_hp_jd_reset(struct hda_codec *codec, + const struct hda_fixup *fix, + int action) +{ + if (action == HDA_FIXUP_ACT_INIT) { + /* Pulse Reset HP JD */ + alc_update_coef_idx(codec, 0x4a, BIT(15), BIT(15)); + alc_update_coef_idx(codec, 0x4a, BIT(15), 0); + } +} + /* turn on/off mic-mute LED per capture hook via VREF change */ static int vref_micmute_led_set(struct led_classdev *led_cdev, enum led_brightness brightness) @@ -4554,6 +4565,7 @@ enum { ALC233_FIXUP_LENOVO_GPIO2_MIC_HOTKEY, ALC245_FIXUP_BASS_HP_DAC, ALC245_FIXUP_ACER_MICMUTE_LED, + ALC245_FIXUP_ACER_HP_JD_RESET, ALC245_FIXUP_CS35L41_I2C_2_MUTE_LED, ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED, ALC256_FIXUP_HONOR_MRB_XXX_M1020_AUDIO, @@ -7392,6 +7404,12 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC2XX_FIXUP_HEADSET_MIC, }, + [ALC245_FIXUP_ACER_HP_JD_RESET] = { + .type = HDA_FIXUP_FUNC, + .v.func = alc245_fixup_acer_hp_jd_reset, + .chained = true, + .chain_id = ALC245_FIXUP_ACER_MICMUTE_LED, + }, [ALC245_FIXUP_CS35L41_I2C_2_MUTE_LED] = { .type = HDA_FIXUP_FUNC, .v.func = alc245_fixup_hp_mute_led_coefbit, @@ -7576,7 +7594,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1025, 0x166c, "Acer Predator PH16-71", ALC2XX_FIXUP_HEADSET_MIC), SND_PCI_QUIRK(0x1025, 0x1679, "Acer Nitro 16 AN16-41", ALC2XX_FIXUP_HEADSET_MIC), SND_PCI_QUIRK(0x1025, 0x169a, "Acer Swift SFG16", ALC256_FIXUP_ACER_SFG16_MICMUTE_LED), - SND_PCI_QUIRK(0x1025, 0x170f, "Acer Predator PHN16-71", ALC245_FIXUP_ACER_MICMUTE_LED), + SND_PCI_QUIRK(0x1025, 0x170f, "Acer Predator PHN16-71", ALC245_FIXUP_ACER_HP_JD_RESET), SND_PCI_QUIRK(0x1025, 0x171e, "Acer Nitro ANV15-51", ALC245_FIXUP_ACER_MICMUTE_LED), SND_PCI_QUIRK(0x1025, 0x172c, "Acer Nitro ANV16-41", ALC2XX_FIXUP_HEADSET_MIC), SND_PCI_QUIRK(0x1025, 0x1731, "Acer Predator PHN16-72", ALC245_FIXUP_ACER_MICMUTE_LED), From c8f6ef3d41ea781227869e11a625a6fae574af57 Mon Sep 17 00:00:00 2001 From: Ryan Brue Date: Fri, 20 Nov 2026 12:10:21 -0600 Subject: [PATCH 1787/2102] drm/imagination: Fix the value of ROGUE_COMPUTE_FLAG_PREVENT_ALL_OVERLAP The firmware takes "prevent all overlap" from bit 1 of a compute command's flags; bit 2 is FORCE_TPU_CLK. The kernel has used bit 2 since the FWIF headers were added, so the firmware has never seen DRM_PVR_SUBMIT_JOB_COMPUTE_CMD_PREVENT_ALL_OVERLAP. On a GX6250 (MT8173), a compute job overlapping fragment work from another context hangs both data masters. With every compute job submitted with bit 1 set, a test that hit the hang on every run no longer does; with bit 2 set instead it still hangs. Fixes: a26f067feac1 ("drm/imagination: Add FWIF headers") Cc: stable@vger.kernel.org Reviewed-by: Brajesh Gupta Signed-off-by: Ryan Brue Reviewed-by: Guillaume La Roque Tested-by: Guillaume La Roque Link: https://patch.msgid.link/20261120-rbrue-suez-pvr-compute-overlap-flag-v2-1-ca2b0d3adb4e@gmail.com Signed-off-by: Alessio Belle --- drivers/gpu/drm/imagination/pvr_rogue_fwif_client.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/imagination/pvr_rogue_fwif_client.h b/drivers/gpu/drm/imagination/pvr_rogue_fwif_client.h index 6e224400083a2c..967e903bdca67d 100644 --- a/drivers/gpu/drm/imagination/pvr_rogue_fwif_client.h +++ b/drivers/gpu/drm/imagination/pvr_rogue_fwif_client.h @@ -74,7 +74,7 @@ * Flags supported by the compute DM command i.e. &struct rogue_fwif_cmd_compute. */ -#define ROGUE_COMPUTE_FLAG_PREVENT_ALL_OVERLAP BIT_MASK(2) +#define ROGUE_COMPUTE_FLAG_PREVENT_ALL_OVERLAP BIT_MASK(1) /*!< Use single core in a multi core setup. */ #define ROGUE_COMPUTE_FLAG_SINGLE_CORE BIT_MASK(5) From b2210d8ad09eaad479a91835493cfbc54e5384f3 Mon Sep 17 00:00:00 2001 From: Nicolas Brainez Date: Mon, 28 Sep 2026 09:28:32 +0200 Subject: [PATCH 1788/2102] efistub/x86: Fix the size type of the Apple properties protocol The size argument of the get(), set() and get_all() methods of the Apple device properties protocol is a UINTN, not a u32. The reverse engineered declaration added by commit 58c5475aba67 ("x86/efi: Retrieve and assign Apple device properties") uses u32, and retrieve_apple_device_properties() passes the address of a u32 on the stack to get_all(). 64-bit Apple firmware writes 8 bytes through that pointer, so the upper half of the store lands on whatever the compiler placed next to the variable. OpenCore's Include/Apple/Protocol/DevicePathPropertyDatabase.h declares the same methods with UINTN, and a u32 canary placed right after the u32 size is zeroed by both get_all() calls on a Mac mini 2018 (Macmini8,1). With clang and CONFIG_EFI_MIXED=n, the neighbour is the protocol pointer p: the first get_all() call zeroes its low half, the second call jumps through the corrupted pointer, and the machine powers off before printing anything. A GCC build leaves padding in that slot, and a clang build with CONFIG_EFI_MIXED=y places the setup_data pointer there; neither crashes, so the bug went unnoticed since 2016. Talos Linux, which builds its kernel with clang, reported it on several Mac generations. Declare the size as unsigned long, as the stub does for every other UINTN. No mixed mode argument mapping is needed: 32-bit firmware writes the low 32 bits of the zero-initialised value, and the upper half stays zero across both calls. Tested on a Macmini8,1 with v6.18.51, clang 22.1.8 and LLD, CONFIG_EFI_MIXED=n, booted as EFI/BOOT/BOOTX64.EFI: the machine powers off without the patch and boots with it. Builds with clang and GCC, with and without CONFIG_EFI_MIXED. Mixed mode was not boot tested (no 32-bit EFI Mac at hand). Claude Code assisted with reading the disassembly, writing the debug patches and drafting this changelog; the tests ran on the hardware above. Fixes: 58c5475aba67 ("x86/efi: Retrieve and assign Apple device properties") Cc: stable@vger.kernel.org Cc: Lukas Wunner Link: https://github.com/siderolabs/talos/issues/13231 Link: https://github.com/siderolabs/talos/issues/13579 Signed-off-by: Nicolas Brainez Signed-off-by: Ard Biesheuvel --- drivers/firmware/efi/libstub/efistub.h | 8 +++++--- drivers/firmware/efi/libstub/x86-stub.c | 4 ++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/drivers/firmware/efi/libstub/efistub.h b/drivers/firmware/efi/libstub/efistub.h index f5eec8c12894c0..a3b589c7d81cd6 100644 --- a/drivers/firmware/efi/libstub/efistub.h +++ b/drivers/firmware/efi/libstub/efistub.h @@ -838,15 +838,17 @@ union apple_properties_protocol { unsigned long version; efi_status_t (__efiapi *get)(apple_properties_protocol_t *, struct efi_dev_path *, - efi_char16_t *, void *, u32 *); + efi_char16_t *, void *, + unsigned long *); efi_status_t (__efiapi *set)(apple_properties_protocol_t *, struct efi_dev_path *, - efi_char16_t *, void *, u32); + efi_char16_t *, void *, + unsigned long); efi_status_t (__efiapi *del)(apple_properties_protocol_t *, struct efi_dev_path *, efi_char16_t *); efi_status_t (__efiapi *get_all)(apple_properties_protocol_t *, - void *buffer, u32 *); + void *buffer, unsigned long *); }; struct { u32 version; diff --git a/drivers/firmware/efi/libstub/x86-stub.c b/drivers/firmware/efi/libstub/x86-stub.c index 253dd3ba8fab24..42a0ce40260a9c 100644 --- a/drivers/firmware/efi/libstub/x86-stub.c +++ b/drivers/firmware/efi/libstub/x86-stub.c @@ -158,10 +158,10 @@ static void setup_efi_pci(struct boot_params *params) static void retrieve_apple_device_properties(struct boot_params *boot_params) { static efi_guid_t guid = APPLE_PROPERTIES_PROTOCOL_GUID; + apple_properties_protocol_t *p; struct setup_data *data, *new; + unsigned long size = 0; efi_status_t status; - u32 size = 0; - apple_properties_protocol_t *p; status = efi_bs_call(locate_protocol, &guid, NULL, (void **)&p); if (status != EFI_SUCCESS) From de57f471f664495ebf1f12a47f6c712410fbe702 Mon Sep 17 00:00:00 2001 From: Takashi Iwai Date: Wed, 25 Nov 2026 07:50:32 +0100 Subject: [PATCH 1789/2102] ALSA: pcm: Prevent PCM hw_params & co during mmap on OSS, too In the OSS emulation mode, we allowed the PCM hw_params, hw_refine and hw_free even when the buffer is mmapped as an exception. This is supposed to be a workaround for some old applications, but this exception is rather harmful as the mmapped pages can be invalidated by the concurrent hw_free and hw_params. As the need of OSS emulation with mmap must be very very low (almost negligible) now, let's remove the exception and prohibits the PCM parameter changes during the mmap just like the normal ALSA applications, too. Link: https://lore.kernel.org/20261118131945.27592-1-Dmitry.Chumachenko@cyberprotect.ru Cc: Dmitriy Chumachenko Link: https://patch.msgid.link/20261125065034.1470697-3-tiwai@suse.de Signed-off-by: Takashi Iwai --- sound/core/pcm_native.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c index da2b789962c213..764a61fcdf8de1 100644 --- a/sound/core/pcm_native.c +++ b/sound/core/pcm_native.c @@ -778,7 +778,7 @@ static int hw_params_state_check(struct snd_pcm_substream *substream, case SNDRV_PCM_STATE_OPEN: case SNDRV_PCM_STATE_SETUP: case SNDRV_PCM_STATE_PREPARED: - if (check_mmap && !is_oss_stream(substream) && + if (check_mmap && atomic_read(&substream->mmap_count)) return -EBADFD; return 0; From e6474ead54b8acecb8b0462dde2d77f46d2b7dc1 Mon Sep 17 00:00:00 2001 From: Chad Aldreda Date: Thu, 19 Nov 2026 06:15:26 +0000 Subject: [PATCH 1790/2102] ptp: vmclock: keep the device state until the last file is closed vmclock_probe() allocates struct vmclock_state with devm_kzalloc_obj() and maps the shared page with devm_memremap(), so both are released when the driver is unbound, but an open /dev/vmclockN keeps using them through its file state. After an unbind, read() runs on the freed struct and reads through the released mapping, and a poll() in progress sleeps on a wait queue in the freed struct. KASAN reports a slab-use-after-free in vmclock_miscdev_read(). In testing, the same read() faulted on the unmapped page once the device had been bound again. Allocate the state with kzalloc_obj() and map the page with memremap(), and release both on the last reference: open() takes a reference and release() drops it, and a devm action drops the device's own reference after vmclock_remove() has called misc_deregister(). misc_open() calls open() with misc_mtx held, and misc_deregister() takes misc_mtx, so open() always runs while the device's reference is held. vmclock_remove() now marks the device as removed and wakes every waiter on the wait queue. A read() or mmap() on a file that is still open fails with -ENODEV once it sees the mark. On a device that supports notifications, poll() returns EPOLLHUP | EPOLLERR, including a poll() that was already waiting; it tests the mark after poll_wait(), so it cannot miss the wake-up. The wake-up uses wake_up_interruptible_all(), because no later notification will reach a waiter that the remove-time wake-up skips, such as a second epoll instance that registered the file with EPOLLEXCLUSIVE. Without notifications poll() already returns POLLHUP. Separately from the report below, the bug was also found by a Coccinelle script that reports device nodes in devm-allocated memory, posted at https://lore.kernel.org/r/20261106193517.3267013-2-ca@modelmiser.com, and reproduced in QEMU 10.2.4 with -device vmclock. There is no access to EC2 hardware with this device, so the fix has only been tested in QEMU. QEMU's device has no notifications, so the poll() path was tested with a local change that lets poll() wait without them. Fixes: 205032724226 ("ptp: Add support for the AMZNC10C 'vmclock' device") Reported-by: Shuangpeng Bai Closes: https://lore.kernel.org/all/178144969601.60470.14493569608271069160@gmail.com/ Cc: stable@vger.kernel.org # 7.0+ Signed-off-by: Chad Aldreda Reviewed-by: David Woodhouse Link: https://patch.msgid.link/20261119061517.1142436-2-ca@modelmiser.com Signed-off-by: Paolo Abeni --- drivers/ptp/ptp_vmclock.c | 63 ++++++++++++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 8 deletions(-) diff --git a/drivers/ptp/ptp_vmclock.c b/drivers/ptp/ptp_vmclock.c index 7f25fe6c2ce2a8..3e32a90306616c 100644 --- a/drivers/ptp/ptp_vmclock.c +++ b/drivers/ptp/ptp_vmclock.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -51,6 +52,8 @@ struct vmclock_state { enum clocksource_ids cs_id, sys_cs_id; int index; char *name; + struct kref kref; + bool removed; }; #define VMCLOCK_MAX_WAIT ms_to_ktime(100) @@ -369,6 +372,9 @@ static int vmclock_miscdev_mmap(struct file *fp, struct vm_area_struct *vma) struct vmclock_file_state *fst = fp->private_data; struct vmclock_state *st = fst->st; + if (READ_ONCE(st->removed)) + return -ENODEV; + if ((vma->vm_flags & (VM_READ|VM_WRITE)) != VM_READ) return -EROFS; @@ -398,6 +404,9 @@ static ssize_t vmclock_miscdev_read(struct file *fp, char __user *buf, uint32_t seq, old_seq; size_t max_count; + if (READ_ONCE(st->removed)) + return -ENODEV; + if (*ppos >= PAGE_SIZE) return 0; @@ -450,6 +459,10 @@ static __poll_t vmclock_miscdev_poll(struct file *fp, poll_table *wait) poll_wait(fp, &st->disrupt_wait, wait); + /* After poll_wait(), so vmclock_remove()'s wake-up is not missed */ + if (READ_ONCE(st->removed)) + return EPOLLHUP | EPOLLERR; + seq = le32_to_cpu(st->clk->seq_count); if (atomic_read(&fst->seq) != seq) return POLLIN | POLLRDNORM; @@ -466,6 +479,12 @@ static int vmclock_miscdev_open(struct inode *inode, struct file *fp) if (!fst) return -ENOMEM; + /* + * misc_open() calls this with misc_mtx held, and vmclock_remove() + * calls misc_deregister(), which takes misc_mtx, before the device's + * own reference is dropped. + */ + kref_get(&st->kref); fst->st = st; atomic_set(&fst->seq, 0); @@ -474,9 +493,22 @@ static int vmclock_miscdev_open(struct inode *inode, struct file *fp) return 0; } +static void vmclock_free(struct kref *kref) +{ + struct vmclock_state *st = + container_of(kref, struct vmclock_state, kref); + + if (st->clk) + memunmap(st->clk); + kfree(st); +} + static int vmclock_miscdev_release(struct inode *inode, struct file *fp) { - kfree(fp->private_data); + struct vmclock_file_state *fst = fp->private_data; + + kref_put(&fst->st->kref, vmclock_free); + kfree(fst); return 0; } @@ -649,9 +681,20 @@ static void vmclock_remove(void *data) if (st->miscdev.minor != MISC_DYNAMIC_MINOR) misc_deregister(&st->miscdev); + /* Files still open now fail, and a poll() in progress returns */ + WRITE_ONCE(st->removed, true); + wake_up_interruptible_all(&st->disrupt_wait); + dev->driver_data = NULL; } +static void vmclock_put(void *data) +{ + struct vmclock_state *st = data; + + kref_put(&st->kref, vmclock_free); +} + static void vmclock_put_idx(void *data) { struct vmclock_state *st = data; @@ -665,9 +708,15 @@ static int vmclock_probe(struct platform_device *pdev) struct vmclock_state *st; int ret; - st = devm_kzalloc_obj(dev, *st); + /* Open files can outlive the device, so st is not devm memory */ + st = kzalloc_obj(*st); if (!st) return -ENOMEM; + kref_init(&st->kref); + + ret = devm_add_action_or_reset(dev, vmclock_put, st); + if (ret) + return ret; #if IS_ENABLED(CONFIG_ACPI) if (has_acpi_companion(dev)) @@ -686,13 +735,11 @@ static int vmclock_probe(struct platform_device *pdev) resource_size(&st->res)); return -EINVAL; } - st->clk = devm_memremap(dev, st->res.start, resource_size(&st->res), - MEMREMAP_WB | MEMREMAP_DEC); - if (IS_ERR(st->clk)) { - ret = PTR_ERR(st->clk); + st->clk = memremap(st->res.start, resource_size(&st->res), + MEMREMAP_WB | MEMREMAP_DEC); + if (!st->clk) { dev_info(dev, "failed to map shared memory\n"); - st->clk = NULL; - return ret; + return -ENXIO; } if (le32_to_cpu(st->clk->magic) != VMCLOCK_MAGIC || From a7e632493acf33b7c17f922678377bc26b877d50 Mon Sep 17 00:00:00 2001 From: Rui Qi Date: Tue, 17 Nov 2026 19:35:35 +0800 Subject: [PATCH 1791/2102] arm64: module: Use text-poke for late PLT/veneer emission module_emit_plt_entry() and module_emit_veneer_for_adrp() write PLT entries into the .plt section by direct assignment. Once a module is fully formed its .plt is read-only/executable, so a late (livepatch) relocation that falls back to PLT emission -- an out-of-range R_AARCH64_CALL26/JUMP26, or an ADRP under CONFIG_ARM64_ERRATUM_843419 -- triggers a synchronous Data Abort and panics. This is the same ROX premise that commit 91b89a634487 ("arm64/module: Use text-poke API for late relocations.") handled for the relocation writes through WRITE_PLACE(); the PLT/veneer emitters were left using direct assignment. The late path is reachable without remapping: klp_write_section_relocs() applies .klp.rela.* sections through apply_relocate_add() with the patch module already MODULE_STATE_LIVE, so .plt is ROX. Route the emitters through the same text-poke write path the relocation code already uses. Replace WRITE_PLACE() with an out-of-line module_write_place() helper in module.c and declare it in asm/module.h so both relocation code and the PLT and veneer emitters can use it. Once late writes go through text-poke they no longer fault on the ROX mapping, so PLT slot exhaustion -- e.g. when livepatch relocations are reapplied without resetting plt_num_entries -- would silently overwrite memory beyond .plt instead of faulting. Add a bounds check before each write so exhaustion fails cleanly with -ENOEXEC instead of corrupting memory. Fixes: 91b89a634487 ("arm64/module: Use text-poke API for late relocations.") Cc: stable@vger.kernel.org Signed-off-by: Rui Qi [catalin.marinas@arm.com: keep the spare .plt slot for the duplicate check] [catalin.marinas@arm.com: declare module_write_place() in asm/module.h] Signed-off-by: Catalin Marinas --- arch/arm64/include/asm/module.h | 3 ++ arch/arm64/kernel/module-plts.c | 23 +++++++++---- arch/arm64/kernel/module.c | 59 +++++++++++++++++++++++---------- 3 files changed, 62 insertions(+), 23 deletions(-) diff --git a/arch/arm64/include/asm/module.h b/arch/arm64/include/asm/module.h index fb9b88eebeb15a..aff1d4ff3245f4 100644 --- a/arch/arm64/include/asm/module.h +++ b/arch/arm64/include/asm/module.h @@ -29,6 +29,9 @@ u64 module_emit_plt_entry(struct module *mod, Elf64_Shdr *sechdrs, u64 module_emit_veneer_for_adrp(struct module *mod, Elf64_Shdr *sechdrs, void *loc, u64 val); +void module_write_place(void *place, void *val, size_t len, + struct module *mod); + struct plt_entry { /* * A program that conforms to the AArch64 Procedure Call Standard diff --git a/arch/arm64/kernel/module-plts.c b/arch/arm64/kernel/module-plts.c index 7afd370da9f48f..758b2ec0ebc305 100644 --- a/arch/arm64/kernel/module-plts.c +++ b/arch/arm64/kernel/module-plts.c @@ -76,11 +76,20 @@ u64 module_emit_plt_entry(struct module *mod, Elf64_Shdr *sechdrs, int i = pltsec->plt_num_entries; int j = i - 1; u64 val = sym->st_value + rela->r_addend; + struct plt_entry entry; if (is_forbidden_offset_for_adrp(&plt[i].adrp)) i++; - plt[i] = get_plt_entry(val, &plt[i]); + /* + * The section has plt_max_entries + 1 slots; the last one is where a + * duplicate of the final entry is built before being discarded. + */ + if (WARN_ON_ONCE(i > pltsec->plt_max_entries)) + return 0; + + entry = get_plt_entry(val, &plt[i]); + module_write_place(&plt[i], &entry, sizeof(entry), mod); /* * Check if the entry we just created is a duplicate. Given that the @@ -107,13 +116,14 @@ u64 module_emit_veneer_for_adrp(struct module *mod, Elf64_Shdr *sechdrs, int i = pltsec->plt_num_entries++; u32 br; int rd; - - if (WARN_ON(pltsec->plt_num_entries > pltsec->plt_max_entries)) - return 0; + struct plt_entry entry; if (is_forbidden_offset_for_adrp(&plt[i].adrp)) i = pltsec->plt_num_entries++; + if (WARN_ON_ONCE(pltsec->plt_num_entries > pltsec->plt_max_entries)) + return 0; + /* get the destination register of the ADRP instruction */ rd = aarch64_insn_decode_register(AARCH64_INSN_REGTYPE_RD, le32_to_cpup((__le32 *)loc)); @@ -121,8 +131,9 @@ u64 module_emit_veneer_for_adrp(struct module *mod, Elf64_Shdr *sechdrs, br = aarch64_insn_gen_branch_imm((u64)&plt[i].br, (u64)loc + 4, AARCH64_INSN_BRANCH_NOLINK); - plt[i] = __get_adrp_add_pair(val, (u64)&plt[i], rd); - plt[i].br = cpu_to_le32(br); + entry = __get_adrp_add_pair(val, (u64)&plt[i], rd); + entry.br = cpu_to_le32(br); + module_write_place(&plt[i], &entry, sizeof(entry), mod); return (u64)&plt[i]; } diff --git a/arch/arm64/kernel/module.c b/arch/arm64/kernel/module.c index 24adb581af0eb2..9ecefc55fb48d6 100644 --- a/arch/arm64/kernel/module.c +++ b/arch/arm64/kernel/module.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -49,14 +50,20 @@ static u64 do_reloc(enum aarch64_reloc_op reloc_op, __le32 *place, u64 val) return 0; } -#define WRITE_PLACE(place, val, mod) do { \ - __typeof__(val) __val = (val); \ - \ - if (mod->state == MODULE_STATE_UNFORMED) \ - *(place) = __val; \ - else \ - aarch64_insn_copy(place, &(__val), sizeof(*place)); \ -} while (0) +/* + * Write @len bytes from @val to @place within a module. While the module is + * MODULE_STATE_UNFORMED the destination is writable and a plain copy is used; + * once the module is fully formed the region is read-only and executable, so + * the write is routed through the text-poke API. + */ +void module_write_place(void *place, void *val, size_t len, + struct module *mod) +{ + if (mod->state == MODULE_STATE_UNFORMED) + memcpy(place, val, len); + else + aarch64_insn_copy(place, val, len); +} static int reloc_data(enum aarch64_reloc_op op, void *place, u64 val, int len, struct module *me) @@ -76,8 +83,10 @@ static int reloc_data(enum aarch64_reloc_op op, void *place, u64 val, int len, */ switch (len) { - case 16: - WRITE_PLACE((s16 *)place, sval, me); + case 16: { + s16 v = sval; + + module_write_place(place, &v, sizeof(v), me); switch (op) { case RELOC_OP_ABS: if (sval < 0 || sval > U16_MAX) @@ -92,8 +101,11 @@ static int reloc_data(enum aarch64_reloc_op op, void *place, u64 val, int len, return 0; } break; - case 32: - WRITE_PLACE((s32 *)place, sval, me); + } + case 32: { + s32 v = sval; + + module_write_place(place, &v, sizeof(v), me); switch (op) { case RELOC_OP_ABS: if (sval < 0 || sval > U32_MAX) @@ -108,9 +120,13 @@ static int reloc_data(enum aarch64_reloc_op op, void *place, u64 val, int len, return 0; } break; - case 64: - WRITE_PLACE((s64 *)place, sval, me); + } + case 64: { + s64 v = sval; + + module_write_place(place, &v, sizeof(v), me); break; + } default: pr_err("Invalid length (%d) for data relocation\n", len); return 0; @@ -130,6 +146,7 @@ static int reloc_insn_movw(enum aarch64_reloc_op op, __le32 *place, u64 val, u64 imm; s64 sval; u32 insn = le32_to_cpu(*place); + __le32 v; sval = do_reloc(op, place, val); imm = sval >> lsb; @@ -157,7 +174,9 @@ static int reloc_insn_movw(enum aarch64_reloc_op op, __le32 *place, u64 val, /* Update the instruction with the new encoding. */ insn = aarch64_insn_encode_immediate(AARCH64_INSN_IMM_16, insn, imm); - WRITE_PLACE(place, cpu_to_le32(insn), me); + v = cpu_to_le32(insn); + + module_write_place(place, &v, sizeof(v), me); if (imm > U16_MAX) return -ERANGE; @@ -172,6 +191,7 @@ static int reloc_insn_imm(enum aarch64_reloc_op op, __le32 *place, u64 val, u64 imm, imm_mask; s64 sval; u32 insn = le32_to_cpu(*place); + __le32 v; /* Calculate the relocation value. */ sval = do_reloc(op, place, val); @@ -183,7 +203,9 @@ static int reloc_insn_imm(enum aarch64_reloc_op op, __le32 *place, u64 val, /* Update the instruction's immediate field. */ insn = aarch64_insn_encode_immediate(imm_type, insn, imm); - WRITE_PLACE(place, cpu_to_le32(insn), me); + v = cpu_to_le32(insn); + + module_write_place(place, &v, sizeof(v), me); /* * Extract the upper value bits (including the sign bit) and @@ -205,6 +227,7 @@ static int reloc_insn_adrp(struct module *mod, Elf64_Shdr *sechdrs, __le32 *place, u64 val, struct module *me) { u32 insn; + __le32 v; if (!is_forbidden_offset_for_adrp(place)) return reloc_insn_imm(RELOC_OP_PAGE, place, val, 12, 21, @@ -224,7 +247,9 @@ static int reloc_insn_adrp(struct module *mod, Elf64_Shdr *sechdrs, AARCH64_INSN_BRANCH_NOLINK); } - WRITE_PLACE(place, cpu_to_le32(insn), me); + v = cpu_to_le32(insn); + + module_write_place(place, &v, sizeof(v), me); return 0; } From 601acadb79b62ee52edbd29ec69d8f677dc32dcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Sch=C3=A4r?= Date: Fri, 20 Nov 2026 14:02:08 +0100 Subject: [PATCH 1792/2102] gpiolib: fix inverted trace values in gpiod_get_array_value() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Almost all trace_gpio_value() calls report the raw value. gpiod_get_array_value_complex() is the only exception; it reports the logical value in traces unless the caller requests raw values. This inconsistency makes GPIO traces confusing. Move the trace call earlier, where the value is still raw. Now, all GPIO traces consistently report raw values. Fixes: eec1d566cdf9 ("gpio: Introduce ->get_multiple callback") Signed-off-by: Jan Schär Link: https://patch.msgid.link/20261120130208.89621-1-jan@jschaer.ch Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index 57024a1b042b68..06574f4c50d013 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -3669,10 +3669,10 @@ int gpiod_get_array_value_complex(bool raw, bool can_sleep, int hwgpio = gpiod_hwgpio(desc); int value = test_bit(hwgpio, bits); + trace_gpio_value(desc_to_gpio(desc), 1, value); if (!raw && test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags)) value = !value; __assign_bit(j, value_bitmap, value); - trace_gpio_value(desc_to_gpio(desc), 1, value); j++; if (array_info) From cdc466fd769b9f29887f5921d2db5b7205120973 Mon Sep 17 00:00:00 2001 From: Rob Clark Date: Mon, 23 Nov 2026 10:13:05 -0800 Subject: [PATCH 1793/2102] drm/msm/a8xx: Add missing preempt_record_size Somehow this got overlooked, and Glymur/Mahua were falling back to the default 4MB. Which is way too small for the amount of GMEM on these devices, causing faults in cases where preemption needs to save GMEM contents. Reported-by: Connor Abbott Fixes: 7fad33097e67 ("drm/msm/a6xx: Enable Preemption on X2-85") Signed-off-by: Rob Clark Reviewed-by: Konrad Dybcio Reviewed-by: Akhil P Oommen Patchwork: https://patchwork.freedesktop.org/patch/772210/ Message-ID: <20261123181306.420017-1-robin.clark@oss.qualcomm.com> --- drivers/gpu/drm/msm/adreno/a8xx_catalog.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/gpu/drm/msm/adreno/a8xx_catalog.c b/drivers/gpu/drm/msm/adreno/a8xx_catalog.c index 529b9b53a72315..eb805168e2d649 100644 --- a/drivers/gpu/drm/msm/adreno/a8xx_catalog.c +++ b/drivers/gpu/drm/msm/adreno/a8xx_catalog.c @@ -1614,6 +1614,7 @@ static const struct adreno_info a8xx_gpus[] = { .clx_tbl = &x285_clx_tbl, .limits_tbl = &x285_limits, }, + .preempt_record_size = 23088 * SZ_1K, .speedbins = ADRENO_SPEEDBINS( { 0, 0 }, { 388, 1 }, @@ -1743,6 +1744,7 @@ static const struct adreno_info a8xx_gpus[] = { { /* sentinel */ }, }, }, + .preempt_record_size = 17712 * SZ_1K, .speedbins = ADRENO_SPEEDBINS( { 0, 0 }, { 388, 1 }, From fe27fb7f1204b90081eeb6e69153c99ea889614d Mon Sep 17 00:00:00 2001 From: Takashi Iwai Date: Wed, 25 Nov 2026 11:10:30 +0100 Subject: [PATCH 1794/2102] ALSA: pcm: Cover buffer access gate in all read/write ioctls We haven't applied the buffer access gate in interleaved read/write because it doesn't involve with the runtime attribute access before the actual snd_pcm_lib_read/write calls. However, there can be a slight race during those ioctls between the PCM state check and read/write calls, which may trigger a kernel WARNING() for the NULL runtime->dma_area check in pcm_sanity_check(). For addressing it, in this patch, all callers of __snd_pcm_lib_xfer() are changed to take the buffer access get via SND_PCM_BUFFER_ACQUIRE() call for avoiding the unexpected PCM state change during the whole operation. Some inline helpers imply the runtime->buffer_access gating, so the definitions of SND_PCM_BUFFER_ACQUIRE() & co are moved to the standard pcm.h now (so that the usage outside sound/* can work e.g. for USB gadget audio driver). Meanwhile, this change makes the snd_pcm_buffer_access_get() and _put() calls in __snd_pcm_lib_xfer() superfluous, so those are dropped, too. Link: https://patch.msgid.link/20261125101035.1754568-1-tiwai@suse.de Signed-off-by: Takashi Iwai --- include/sound/pcm.h | 45 ++++++++++++++++++++++++++++++++++++---- sound/core/oss/pcm_oss.c | 9 ++++---- sound/core/pcm_compat.c | 3 +++ sound/core/pcm_lib.c | 5 +---- sound/core/pcm_local.h | 26 ----------------------- sound/core/pcm_native.c | 3 +++ 6 files changed, 53 insertions(+), 38 deletions(-) diff --git a/include/sound/pcm.h b/include/sound/pcm.h index 04f58c2ec5c623..92ff263e747934 100644 --- a/include/sound/pcm.h +++ b/include/sound/pcm.h @@ -702,6 +702,32 @@ DEFINE_LOCK_GUARD_1(pcm_stream_lock_irqsave, struct snd_pcm_substream, stream <= SNDRV_PCM_STREAM_LAST; \ stream++) +/* + * helpers for restricting hw_params / hw_refine changes + */ +static inline int snd_pcm_buffer_access_get(struct snd_pcm_runtime *runtime) +{ + if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + return -EBUSY; + return 0; +} + +static inline void snd_pcm_buffer_access_put(struct snd_pcm_runtime *runtime) +{ + atomic_dec(&runtime->buffer_accessing); +} + +/* auto-cleanup macros */ +DEFINE_GUARD(snd_pcm_buffer_access, struct snd_pcm_runtime *, + snd_pcm_buffer_access_get(_T), snd_pcm_buffer_access_put(_T)); +DEFINE_GUARD_COND(snd_pcm_buffer_access, _try, + snd_pcm_buffer_access_get(_T), _RET == 0); + +#define SND_PCM_BUFFER_ACQUIRE(runtime, var) \ + ACQUIRE(snd_pcm_buffer_access_try, var)(runtime) +#define SND_PCM_BUFFER_ACQUIRE_ERR(var) \ + ACQUIRE_ERR(snd_pcm_buffer_access_try, &(var)) + /** * snd_pcm_running - Check whether the substream is in a running state * @substream: substream to check @@ -1188,6 +1214,17 @@ snd_pcm_sframes_t __snd_pcm_lib_xfer(struct snd_pcm_substream *substream, void *buf, bool interleaved, snd_pcm_uframes_t frames, bool in_kernel); +static inline snd_pcm_sframes_t +snd_pcm_lib_get_and_xfer(struct snd_pcm_substream *substream, + void *buf, bool interleaved, + snd_pcm_uframes_t frames, bool in_kernel) +{ + SND_PCM_BUFFER_ACQUIRE(substream->runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; + return __snd_pcm_lib_xfer(substream, buf, interleaved, frames, in_kernel); +} + static inline snd_pcm_sframes_t snd_pcm_lib_write(struct snd_pcm_substream *substream, const void __user *buf, snd_pcm_uframes_t frames) @@ -1220,28 +1257,28 @@ static inline snd_pcm_sframes_t snd_pcm_kernel_write(struct snd_pcm_substream *substream, const void *buf, snd_pcm_uframes_t frames) { - return __snd_pcm_lib_xfer(substream, (void *)buf, true, frames, true); + return snd_pcm_lib_get_and_xfer(substream, (void *)buf, true, frames, true); } static inline snd_pcm_sframes_t snd_pcm_kernel_read(struct snd_pcm_substream *substream, void *buf, snd_pcm_uframes_t frames) { - return __snd_pcm_lib_xfer(substream, buf, true, frames, true); + return snd_pcm_lib_get_and_xfer(substream, buf, true, frames, true); } static inline snd_pcm_sframes_t snd_pcm_kernel_writev(struct snd_pcm_substream *substream, void **bufs, snd_pcm_uframes_t frames) { - return __snd_pcm_lib_xfer(substream, bufs, false, frames, true); + return snd_pcm_lib_get_and_xfer(substream, bufs, false, frames, true); } static inline snd_pcm_sframes_t snd_pcm_kernel_readv(struct snd_pcm_substream *substream, void **bufs, snd_pcm_uframes_t frames) { - return __snd_pcm_lib_xfer(substream, bufs, false, frames, true); + return snd_pcm_lib_get_and_xfer(substream, bufs, false, frames, true); } int snd_pcm_hw_limit_rates(struct snd_pcm_hardware *hw); diff --git a/sound/core/oss/pcm_oss.c b/sound/core/oss/pcm_oss.c index 2fc52fe2cb52ee..fc1f7e1c0a564b 100644 --- a/sound/core/oss/pcm_oss.c +++ b/sound/core/oss/pcm_oss.c @@ -1246,8 +1246,8 @@ snd_pcm_sframes_t snd_pcm_oss_write3(struct snd_pcm_substream *substream, const break; } mutex_unlock(&runtime->oss.params_lock); - ret = __snd_pcm_lib_xfer(substream, (void *)ptr, true, - frames, in_kernel); + ret = snd_pcm_lib_get_and_xfer(substream, (void *)ptr, true, + frames, in_kernel); mutex_lock(&runtime->oss.params_lock); if (ret != -EPIPE && ret != -ESTRPIPE) break; @@ -1287,9 +1287,10 @@ snd_pcm_sframes_t snd_pcm_oss_read3(struct snd_pcm_substream *substream, char *p if (ret < 0) break; mutex_unlock(&runtime->oss.params_lock); - ret = __snd_pcm_lib_xfer(substream, (void *)ptr, true, - frames, in_kernel); + ret = snd_pcm_lib_get_and_xfer(substream, ptr, true, + frames, in_kernel); mutex_lock(&runtime->oss.params_lock); + if (ret == -EPIPE) { if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_DRAINING) { ret = snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_DROP, NULL); diff --git a/sound/core/pcm_compat.c b/sound/core/pcm_compat.c index c5931fdfe1f54d..924fd269dace61 100644 --- a/sound/core/pcm_compat.c +++ b/sound/core/pcm_compat.c @@ -293,6 +293,9 @@ static int snd_pcm_ioctl_xferi_compat(struct snd_pcm_substream *substream, return -ENOTTY; if (substream->stream != dir) return -EINVAL; + SND_PCM_BUFFER_ACQUIRE(substream->runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_OPEN) return -EBADFD; diff --git a/sound/core/pcm_lib.c b/sound/core/pcm_lib.c index e13286b51858e9..3d2db8a575a37f 100644 --- a/sound/core/pcm_lib.c +++ b/sound/core/pcm_lib.c @@ -2275,6 +2275,7 @@ int pcm_lib_apply_appl_ptr(struct snd_pcm_substream *substream, } /* the common loop for read/write data */ +/* the caller should reserve the buffer via runtime->buffer_access beforehand */ snd_pcm_sframes_t __snd_pcm_lib_xfer(struct snd_pcm_substream *substream, void *data, bool interleaved, snd_pcm_uframes_t size, bool in_kernel) @@ -2377,9 +2378,6 @@ snd_pcm_sframes_t __snd_pcm_lib_xfer(struct snd_pcm_substream *substream, err = -EINVAL; goto _end_unlock; } - err = snd_pcm_buffer_access_get(runtime); - if (err < 0) - goto _end_unlock; snd_pcm_stream_unlock_irq(substream); if (!is_playback) snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_CPU); @@ -2388,7 +2386,6 @@ snd_pcm_sframes_t __snd_pcm_lib_xfer(struct snd_pcm_substream *substream, if (is_playback) snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_DEVICE); snd_pcm_stream_lock_irq(substream); - snd_pcm_buffer_access_put(runtime); if (err < 0) goto _end_unlock; err = pcm_accessible_state(substream); diff --git a/sound/core/pcm_local.h b/sound/core/pcm_local.h index 7762c89e0f9ffd..4b134d435c24f3 100644 --- a/sound/core/pcm_local.h +++ b/sound/core/pcm_local.h @@ -86,30 +86,4 @@ static inline void snd_pcm_dma_buffer_sync(struct snd_pcm_substream *substream, #define is_oss_stream(substream) false #endif -/* - * helpers for restricting hw_params / hw_refine changes - */ -static inline int snd_pcm_buffer_access_get(struct snd_pcm_runtime *runtime) -{ - if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) - return -EBUSY; - return 0; -} - -static inline void snd_pcm_buffer_access_put(struct snd_pcm_runtime *runtime) -{ - atomic_dec(&runtime->buffer_accessing); -} - -/* auto-cleanup macros */ -DEFINE_GUARD(snd_pcm_buffer_access, struct snd_pcm_runtime *, - snd_pcm_buffer_access_get(_T), snd_pcm_buffer_access_put(_T)); -DEFINE_GUARD_COND(snd_pcm_buffer_access, _try, - snd_pcm_buffer_access_get(_T), _RET == 0); - -#define SND_PCM_BUFFER_ACQUIRE(runtime, var) \ - ACQUIRE(snd_pcm_buffer_access_try, var)(runtime) -#define SND_PCM_BUFFER_ACQUIRE_ERR(var) \ - ACQUIRE_ERR(snd_pcm_buffer_access_try, &(var)) - #endif /* __SOUND_CORE_PCM_LOCAL_H */ diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c index 4cc40990f2ef6c..c7768793422aed 100644 --- a/sound/core/pcm_native.c +++ b/sound/core/pcm_native.c @@ -3411,6 +3411,9 @@ static int snd_pcm_xferi_frames_ioctl(struct snd_pcm_substream *substream, struct snd_xferi xferi; snd_pcm_sframes_t result; + SND_PCM_BUFFER_ACQUIRE(substream->runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_OPEN) return -EBADFD; if (put_user(0, &_xferi->result)) From 4dc6b4cd17c2040e86aceb26200cc359e8d60b6d Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Wed, 25 Nov 2026 09:35:37 +0000 Subject: [PATCH 1795/2102] ALSA: core: Reject zero major number Reject a zero major number before calling register_chrdev(), as ALSA expects a fixed major number. Remove the redundant major variable and use snd_major directly with module_param_named(). Keep a separate configured card limit for automatic module loading, as snd_ecards_limit may increase at runtime when cards are registered at higher indices. Update device number creation and character device registration and unregistration to use snd_major. Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261125093538.4974-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/core/sound.c | 43 +++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/sound/core/sound.c b/sound/core/sound.c index ba226aa7affd3c..536720bc148824 100644 --- a/sound/core/sound.c +++ b/sound/core/sound.c @@ -18,28 +18,28 @@ #include #include -static int major = CONFIG_SND_MAJOR; -int snd_major; +int snd_major = CONFIG_SND_MAJOR; EXPORT_SYMBOL(snd_major); -static int cards_limit = 1; +/* maximum number of cards allowed for automatic module loading */ +static int snd_cards_limit = 1; + +/* this holds the actual maximum card number currently available. + * it is initialized from snd_cards_limit and increases when + * cards are registered manually at higher indices. + */ +int snd_ecards_limit = 1; +EXPORT_SYMBOL(snd_ecards_limit); MODULE_AUTHOR("Jaroslav Kysela "); MODULE_DESCRIPTION("Advanced Linux Sound Architecture driver for soundcards."); MODULE_LICENSE("GPL"); -module_param(major, int, 0444); +module_param_named(major, snd_major, int, 0444); MODULE_PARM_DESC(major, "Major # for sound driver."); -module_param(cards_limit, int, 0444); +module_param_named(cards_limit, snd_cards_limit, int, 0444); MODULE_PARM_DESC(cards_limit, "Count of auto-loadable soundcards."); MODULE_ALIAS_CHARDEV_MAJOR(CONFIG_SND_MAJOR); -/* this one holds the actual max. card number currently available. - * as default, it's identical with cards_limit option. when more - * modules are loaded manually, this limit number increases, too. - */ -int snd_ecards_limit; -EXPORT_SYMBOL(snd_ecards_limit); - #ifdef CONFIG_SND_DEBUG struct dentry *sound_debugfs_root; EXPORT_SYMBOL_GPL(sound_debugfs_root); @@ -61,7 +61,7 @@ void snd_request_card(int card) { if (snd_card_locked(card)) return; - if (card < 0 || card >= cards_limit) + if (card < 0 || card >= snd_cards_limit) return; request_module("snd-card-%i", card); } @@ -326,7 +326,7 @@ int snd_register_device(int type, struct snd_card *card, int dev, } preg->dev = device; - device->devt = MKDEV(major, minor); + device->devt = MKDEV(snd_major, minor); err = device_add(device); if (err < 0) goto error; @@ -442,18 +442,21 @@ static int __init alsa_sound_init(void) { int err; - snd_major = major; - snd_ecards_limit = cards_limit; + if (!snd_major) + return -EINVAL; + + snd_ecards_limit = snd_cards_limit; - err = register_chrdev(major, "alsa", &snd_fops); + err = register_chrdev(snd_major, "alsa", &snd_fops); if (err < 0) { - pr_err("ALSA core: unable to register native major device number %d\n", major); + pr_err("ALSA core: unable to register native major device number %d\n", + snd_major); return err; } err = snd_info_init(); if (err < 0) { - unregister_chrdev(major, "alsa"); + unregister_chrdev(snd_major, "alsa"); return err; } @@ -472,7 +475,7 @@ static void __exit alsa_sound_exit(void) debugfs_remove(sound_debugfs_root); #endif snd_info_done(); - unregister_chrdev(major, "alsa"); + unregister_chrdev(snd_major, "alsa"); } subsys_initcall(alsa_sound_init); From d6972801342f4098d03c260a0c992bac6d28601a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amadeusz=20S=C5=82awi=C5=84ski?= Date: Tue, 24 Nov 2026 20:57:00 +0100 Subject: [PATCH 1796/2102] ALSA: hda: Remove orphaned function prototypes from hda_local.h MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit snd_hda_schedule_power_save() was never implemented, and snd_print_channel_allocation() was renamed to snd_hdac_print_channel_allocation() in commit bb63f726f98b ("ALSA: hda - Use snd_hdac namespace prefix for chmap exported APIs"). Remove both orphaned prototypes from hda_local.h. Signed-off-by: Amadeusz Sławiński Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261124195704.41649-2-amade@asmblr.net --- sound/hda/common/hda_local.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/sound/hda/common/hda_local.h b/sound/hda/common/hda_local.h index 8bd4497a6b0909..61998cc35a449d 100644 --- a/sound/hda/common/hda_local.h +++ b/sound/hda/common/hda_local.h @@ -616,8 +616,6 @@ int snd_hda_get_int_hint(struct hda_codec *codec, const char *key, int *valp) * power-management */ -void snd_hda_schedule_power_save(struct hda_codec *codec); - struct hda_amp_list { hda_nid_t nid; unsigned char dir; @@ -708,7 +706,6 @@ void snd_hdmi_write_eld_info(struct hdmi_eld *eld, #endif #define SND_PRINT_CHANNEL_ALLOCATION_ADVISED_BUFSIZE 80 -void snd_print_channel_allocation(int spk_alloc, char *buf, int buflen); void snd_hda_codec_display_power(struct hda_codec *codec, bool enable); From a9db9d646a25fdde394b27eebc2d26079ed04008 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amadeusz=20S=C5=82awi=C5=84ski?= Date: Tue, 24 Nov 2026 20:57:01 +0100 Subject: [PATCH 1797/2102] ALSA: hda: Remove orphaned snd_hda_get_codec_name() prototype MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit snd_hda_get_codec_name() was replaced by static get_codec_name() in commit f44ac8378d3d ("ALSA: hda - Allocate name string of each codec"), leaving behind an unused prototype in hda_codec.h. Remove it. Signed-off-by: Amadeusz Sławiński Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261124195704.41649-3-amade@asmblr.net --- include/sound/hda_codec.h | 1 - 1 file changed, 1 deletion(-) diff --git a/include/sound/hda_codec.h b/include/sound/hda_codec.h index 084f06488a95f6..c68a0076d42ce9 100644 --- a/include/sound/hda_codec.h +++ b/include/sound/hda_codec.h @@ -479,7 +479,6 @@ int snd_hda_attach_pcm_stream(struct hda_bus *_bus, struct hda_codec *codec, /* * Misc */ -void snd_hda_get_codec_name(struct hda_codec *codec, char *name, int namelen); void snd_hda_codec_set_power_to_all(struct hda_codec *codec, hda_nid_t fg, unsigned int power_state); From c5f04f2681769d34c4146b4051ec6eaa35ac8cef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amadeusz=20S=C5=82awi=C5=84ski?= Date: Tue, 24 Nov 2026 20:57:02 +0100 Subject: [PATCH 1798/2102] ALSA: gus: Remove orphaned snd_gf1_mem_free_owner() prototype MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit snd_gf1_mem_free_owner() has no implementation in the tree. Remove its orphaned function prototype from include/sound/gus.h. Signed-off-by: Amadeusz Sławiński Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261124195704.41649-4-amade@asmblr.net --- include/sound/gus.h | 1 - 1 file changed, 1 deletion(-) diff --git a/include/sound/gus.h b/include/sound/gus.h index 3feb42627de1eb..f00ab15f6cd467 100644 --- a/include/sound/gus.h +++ b/include/sound/gus.h @@ -520,7 +520,6 @@ struct snd_gf1_mem_block *snd_gf1_mem_alloc(struct snd_gf1_mem * alloc, int owne char *name, int size, int w_16, int align, unsigned int *share_id); int snd_gf1_mem_free(struct snd_gf1_mem * alloc, unsigned int address); -int snd_gf1_mem_free_owner(struct snd_gf1_mem * alloc, int owner); int snd_gf1_mem_init(struct snd_gus_card * gus); int snd_gf1_mem_done(struct snd_gus_card * gus); From 4d6fbb250a96ecdfc0135e32c4d737531ae86fcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amadeusz=20S=C5=82awi=C5=84ski?= Date: Tue, 24 Nov 2026 20:57:03 +0100 Subject: [PATCH 1799/2102] ALSA: sb8: Remove orphaned PCM open/close function prototypes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sb8_main.c uses static snd_sb8_open() and snd_sb8_close() callbacks for both playback and capture, while snd_sb8_playback_open(), snd_sb8_capture_open(), snd_sb8_playback_close() and snd_sb8_capture_close() are not defined anywhere. Remove their orphaned prototypes from include/sound/sb.h. Signed-off-by: Amadeusz Sławiński Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261124195704.41649-5-amade@asmblr.net --- include/sound/sb.h | 4 ---- 1 file changed, 4 deletions(-) diff --git a/include/sound/sb.h b/include/sound/sb.h index 24970f36c38ae9..f133cfee378841 100644 --- a/include/sound/sb.h +++ b/include/sound/sb.h @@ -299,10 +299,6 @@ static inline void snd_sbmixer_resume(struct snd_sb *chip) {} int snd_sb8dsp_pcm(struct snd_sb *chip, int device); /* sb8.c */ irqreturn_t snd_sb8dsp_interrupt(struct snd_sb *chip); -int snd_sb8_playback_open(struct snd_pcm_substream *substream); -int snd_sb8_capture_open(struct snd_pcm_substream *substream); -int snd_sb8_playback_close(struct snd_pcm_substream *substream); -int snd_sb8_capture_close(struct snd_pcm_substream *substream); /* midi8.c */ irqreturn_t snd_sb8dsp_midi_interrupt(struct snd_sb *chip); int snd_sb8dsp_midi(struct snd_sb *chip, int device); From fcb973efe971850692b5b3c997967499a10c5538 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amadeusz=20S=C5=82awi=C5=84ski?= Date: Tue, 24 Nov 2026 20:57:04 +0100 Subject: [PATCH 1800/2102] ALSA: emu10k1: Remove orphaned snd_emu10k1_memhdr_init() prototype MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit snd_emu10k1_memhdr_init() has no implementation in the tree. Remove its orphaned function prototype from emu10k1_synth_local.h. Signed-off-by: Amadeusz Sławiński Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261124195704.41649-6-amade@asmblr.net --- sound/pci/emu10k1/emu10k1_synth_local.h | 1 - 1 file changed, 1 deletion(-) diff --git a/sound/pci/emu10k1/emu10k1_synth_local.h b/sound/pci/emu10k1/emu10k1_synth_local.h index 11373695344b15..36b37e7c1a5caa 100644 --- a/sound/pci/emu10k1/emu10k1_synth_local.h +++ b/sound/pci/emu10k1/emu10k1_synth_local.h @@ -19,7 +19,6 @@ int snd_emu10k1_sample_new(struct snd_emux *private_data, int snd_emu10k1_sample_free(struct snd_emux *private_data, struct snd_sf_sample *sp, struct snd_util_memhdr *hdr); -int snd_emu10k1_memhdr_init(struct snd_emux *emu); /* emu10k1_callback.c */ void snd_emu10k1_ops_setup(struct snd_emux *emu); From 4e3cca6e4c445a4a3fac73100386754a58e67543 Mon Sep 17 00:00:00 2001 From: sandrees2007-ctrl Date: Tue, 24 Nov 2026 23:26:41 +1000 Subject: [PATCH 1801/2102] ALSA: hda/realtek: Add quirk for Infinix BL51A7H The Infinix BL51A7H (Realtek ALC233, SSID 2782:a24a) has its internal speakers wired to pin 0x1b, but the BIOS pin configuration reports the speaker on 0x14 and leaves 0x1b disabled. As a result the analog output is silent. Apply the existing ALC233_FIXUP_MEDION_MTL_SPK quirk, which maps pin 0x1b as an internal speaker. The same quirk is already used for the related Colorful L1 Plus (2782:a248) and Medion E15443 (2782:4900). Tested on the Infinix BL51A7H: the internal speakers work after the quirk. Signed-off-by: sandrees2007-ctrl Link: https://patch.msgid.link/20261124132641.79890-1-sandrees2007@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/codecs/realtek/alc269.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 3617b6221abfcc..5c3b383bb61822 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -8838,6 +8838,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x2782, 0xa128, "Positivo N15RPE-S", ALC269_FIXUP_LIMIT_INT_MIC_BOOST), SND_PCI_QUIRK(0x2782, 0xa212, "Lunnen Ground 14", ALC269VC_FIXUP_LUNNEN_GROUND_14), SND_PCI_QUIRK(0x2782, 0xa248, "COLORFUL L1 Plus", ALC233_FIXUP_MEDION_MTL_SPK), + SND_PCI_QUIRK(0x2782, 0xa24a, "Infinix BL51A7H", ALC233_FIXUP_MEDION_MTL_SPK), SND_PCI_QUIRK(0x7017, 0x2014, "Star Labs StarFighter", ALC233_FIXUP_STARLABS_STARFIGHTER), SND_PCI_QUIRK(0x8086, 0x2073, "Intel NUC 8 Hades Canyon", ALC700_FIXUP_INTEL_HADES_CANYON), From dddfd76900d20927f509e74fc94c8d82fc235501 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yannick=20M=C3=BCller?= Date: Tue, 24 Nov 2026 14:25:50 +0100 Subject: [PATCH 1802/2102] ALSA: usb-audio: Limit the depth of the clock topology walk MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit __uac_clock_find_source() recurses through clock selectors and multipliers using entity IDs from the device's descriptors. The visited bitmap stops loops, but a device can still chain up to 255 distinct clock entities. At about 96 bytes of stack per nested call (x86-64, gcc 14) that is roughly 24 KB on a 16 KB kernel stack, so a device with crafted descriptors can overflow it. Pass the nesting depth down and fail with -EINVAL beyond 16 levels. Signed-off-by: Yannick Müller Fixes: 79f920fbff56 ("ALSA: usb-audio: parse clock topology of UAC2 devices") Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261124132551.137134-2-mail@ynnk.dev --- sound/usb/clock.c | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/sound/usb/clock.c b/sound/usb/clock.c index cc77eace7b592d..74f9923e501584 100644 --- a/sound/usb/clock.c +++ b/sound/usb/clock.c @@ -292,9 +292,12 @@ static bool uac_clock_source_is_valid(struct snd_usb_audio *chip, return uac_clock_source_is_valid_quirk(chip, fmt, source_id); } +#define MAX_CLOCK_DEPTH 16 + static int __uac_clock_find_source(struct snd_usb_audio *chip, const struct audioformat *fmt, int entity_id, - unsigned long *visited, bool validate) + unsigned long *visited, bool validate, + int depth) { union uac23_clock_source_desc *source; union uac23_clock_selector_desc *selector; @@ -307,6 +310,13 @@ static int __uac_clock_find_source(struct snd_usb_audio *chip, entity_id &= 0xff; + if (depth >= MAX_CLOCK_DEPTH) { + usb_audio_warn(chip, + "%s(): clock topology is too deep, id %d.\n", + __func__, entity_id); + return -EINVAL; + } + if (test_and_set_bit(entity_id, visited)) { usb_audio_warn(chip, "%s(): recursive clock topology detected, id %d.\n", @@ -381,7 +391,7 @@ static int __uac_clock_find_source(struct snd_usb_audio *chip, cur = ret; ret = __uac_clock_find_source(chip, fmt, sources[ret - 1], - visited, validate); + visited, validate, depth + 1); if (ret > 0) { /* Skip setting clock selector again for some devices */ if (chip->quirk_flags & QUIRK_FLAG_SKIP_CLOCK_SELECTOR || @@ -414,7 +424,7 @@ static int __uac_clock_find_source(struct snd_usb_audio *chip, ret = __uac_clock_find_source(chip, fmt, sources[i - 1], - visited, true); + visited, true, depth + 1); if (ret < 0) continue; @@ -436,7 +446,7 @@ static int __uac_clock_find_source(struct snd_usb_audio *chip, if (multiplier) return __uac_clock_find_source(chip, fmt, GET_VAL(multiplier, proto, bCSourceID), - visited, validate); + visited, validate, depth + 1); return -EINVAL; } @@ -462,7 +472,7 @@ int snd_usb_clock_find_source(struct snd_usb_audio *chip, case UAC_VERSION_2: case UAC_VERSION_3: return __uac_clock_find_source(chip, fmt, fmt->clock, visited, - validate); + validate, 0); default: return -EINVAL; } From 486060b97284c95384744f030706f89e1980a46e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yannick=20M=C3=BCller?= Date: Tue, 24 Nov 2026 14:25:51 +0100 Subject: [PATCH 1803/2102] ALSA: usb-audio: Limit the unit nesting depth in the mixer parser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit parse_audio_unit() and __check_input_term() recurse along the source IDs found in the device's descriptors. The unit and terminal bitmaps only ensure that no ID is visited twice, so a device can still chain all 255 unit IDs. At 176 to 304 bytes of stack per nested unit (x86-64, gcc 14) that takes 44 to 76 KB and overflows the 16 KB kernel stack while the device is probed. Stop after 16 nested units and return -EINVAL, which the callers already treat as a broken topology: that chain gets no controls and the rest of the mixer is still created. The deepest topology documented in mixer_maps.c (SB Extigy) nests 12 units. __check_input_term() nests at most once per call, so counting its calls since check_input_term() gives the depth. Signed-off-by: Yannick Müller Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261124132551.137134-3-mail@ynnk.dev --- sound/usb/mixer.c | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/sound/usb/mixer.c b/sound/usb/mixer.c index 95209ec006b3c6..37850f34caaea8 100644 --- a/sound/usb/mixer.c +++ b/sound/usb/mixer.c @@ -51,6 +51,7 @@ #include "power.h" #define MAX_ID_ELEMS 256 +#define MAX_UNIT_DEPTH 16 struct usb_audio_term { int id; @@ -69,6 +70,8 @@ struct mixer_build { unsigned int buflen; DECLARE_BITMAP(unitbitmap, MAX_ID_ELEMS); DECLARE_BITMAP(termbitmap, MAX_ID_ELEMS); + unsigned int unit_depth; + unsigned int term_depth; struct usb_audio_term oterm; const struct usbmix_name_map *map; const struct usbmix_selector_map *selector_map; @@ -1023,6 +1026,9 @@ static int __check_input_term(struct mixer_build *state, int id, void *p1; unsigned char *hdr; + if (++state->term_depth > MAX_UNIT_DEPTH) + return -EINVAL; + for (;;) { /* a loop in the terminal chain? */ if (test_and_set_bit(id, state->termbitmap)) @@ -1093,6 +1099,7 @@ static int check_input_term(struct mixer_build *state, int id, { memset(term, 0, sizeof(*term)); memset(state->termbitmap, 0, sizeof(state->termbitmap)); + state->term_depth = 0; return __check_input_term(state, id, term); } @@ -3180,7 +3187,7 @@ static int parse_audio_selector_unit(struct mixer_build *state, int unitid, * parse an audio unit recursively */ -static int parse_audio_unit(struct mixer_build *state, int unitid) +static int __parse_audio_unit(struct mixer_build *state, int unitid) { unsigned char *p1; int protocol = state->mixer->protocol; @@ -3240,6 +3247,22 @@ static int parse_audio_unit(struct mixer_build *state, int unitid) } } +static int parse_audio_unit(struct mixer_build *state, int unitid) +{ + int err; + + if (state->unit_depth >= MAX_UNIT_DEPTH) { + usb_audio_err(state->chip, + "unit %d: unit chain is too deep\n", unitid); + return -EINVAL; + } + + state->unit_depth++; + err = __parse_audio_unit(state, unitid); + state->unit_depth--; + return err; +} + static void snd_usb_mixer_free(struct usb_mixer_interface *mixer) { struct usb_mixer_elem_list *list, *next; From 23c8af89aac3feb3867c5eb47aca5b3a2dccb70e Mon Sep 17 00:00:00 2001 From: Steven Rostedt Date: Tue, 24 Nov 2026 09:24:47 -0500 Subject: [PATCH 1804/2102] tracing/probes: Zero out faulted dereferenced fields While looking at tasks global descriptor tables, I discovered the following anomaly: ~# echo 't:sched sched_switch prev=prev mm=(task_struct)prev->mm ppgd=(task_struct)prev->mm->pgd' > /sys/kernel/tracing/dynamic_events The above creates a tprobe on the sched_switch tracepoint and records the previous task_struct pointer, it's mm_struct and the pgd the mm_struct points to. ~# trace-cmd start -e tracepoints:sched bash-1050 [000] d..3. 90.829478: sched: (__probestub_sched_switch+0x0/0x10) prev=0xffff88d30b623600 mm=0xffff88d30108c600 ppgd=0xffff88d33352b000 -0 [002] d..3. 90.836024: sched: (__probestub_sched_switch+0x0/0x10) prev=0xffff88d301870000 mm=0x0 ppgd=0x0 rcu_preempt-15 [002] d..3. 90.836031: sched: (__probestub_sched_switch+0x0/0x10) prev=0xffff88d3013ad100 mm=0x0 ppgd=0xffff88d33352b000 The first event has is a user task that has both a valid mm_struct and a pgd. The second event is a kernel task where the mm_struct is NULL and so is the dereferenced pgd pointer. The third event is where things looked strange. The mm_struct is NULL but the dereferenced pgd has a value! That is: NULL->pgd produced something other than zero. The reason for this is that the probe_mem_read() and probe_mem_read_user() do not write to the destination on failure. The process_fetch_insn_bottom() loop does not check the return value of the dereference (as it is the last one), and does not update the event. That leaves the value for that failed field to be whatever was in the ring buffer at that time. Have both probe_mem_read() and probe_mem_read_user() set the destination to zero on failure to read the address. Now all pgd are zero when mm is zero. Also update the stage 2 of process_fetch_insn_bottom() to not return on fault but to just set the value to zero and also do not even bother dereferencing the address if the value is already zero. This allows the code to continue and fill in the zero into the memory location on the ring buffer. Link: https://lore.kernel.org/all/20261124092447.4dbf5233@gandalf.local.home/ Cc: stable@vger.kernel.org Fixes: 533059281ee59 ("tracing: probeevent: Introduce new argument fetching code") Signed-off-by: Steven Rostedt Signed-off-by: Masami Hiramatsu (Google) --- kernel/trace/trace_probe_tmpl.h | 103 +++++++++++++++++++++++++------- 1 file changed, 83 insertions(+), 20 deletions(-) diff --git a/kernel/trace/trace_probe_tmpl.h b/kernel/trace/trace_probe_tmpl.h index 8acc0f0ebd7a6b..b9fd2f61a0ca73 100644 --- a/kernel/trace/trace_probe_tmpl.h +++ b/kernel/trace/trace_probe_tmpl.h @@ -96,7 +96,8 @@ fetch_store_symstring(unsigned long addr, void *dest, void *base) return -ENOMEM; __dest = get_loc_data(dest, base); - len = sprint_symbol(namebuf, addr); + /* Do not dereference NULL pointers */ + len = addr ? sprint_symbol(namebuf, addr) : -1; if (len < 0) { *(u32 *)dest = make_data_loc(0, __dest - base); return 0; @@ -133,13 +134,65 @@ process_common_fetch_insn(struct fetch_insn *code, unsigned long *val) return 0; } +/* On failure, zero out the destination */ +static nokprobe_inline int +do_probe_mem_read_user(void *dest, void *src, size_t size) +{ + int ret; + + /* Do not dereference NULL pointers */ + ret = src ? probe_mem_read_user(dest, src, size) : -1; + if (ret < 0) + memset(dest, 0, size); + return ret; +} + +/* On failure, zero out the destination */ +static nokprobe_inline int +do_probe_mem_read(void *dest, void *src, size_t size) +{ + int ret; + + /* Do not dereference NULL pointers */ + ret = src ? probe_mem_read(dest, src, size) : -1; + if (ret < 0) + memset(dest, 0, size); + return ret; +} + +static nokprobe_inline int +do_fetch_store_string(unsigned long addr, void *dest, void *base) +{ + /* NULL addr gets zero size string */ + if (!addr) { + void *__dest = get_loc_data(dest, base); + + *(u32 *)dest = make_data_loc(0, __dest - base); + return 0; + } + return fetch_store_string(addr, dest, base); +} + +static nokprobe_inline int +do_fetch_store_string_user(unsigned long addr, void *dest, void *base) +{ + /* NULL addr gets zero size string */ + if (!addr) { + void *__dest = get_loc_data(dest, base); + + *(u32 *)dest = make_data_loc(0, __dest - base); + return 0; + } + return fetch_store_string_user(addr, dest, base); +} + /* From the 2nd stage, routine is same */ static nokprobe_inline int process_fetch_insn_bottom(struct fetch_insn *code, unsigned long val, void *dest, void *base) { struct fetch_insn *s3 = NULL; - int total = 0, ret = 0, i = 0; + int total = 0, ret = 0, i = 0, offset; u32 loc = 0; unsigned long lval, llval = val; @@ -147,25 +200,26 @@ process_fetch_insn_bottom(struct fetch_insn *code, unsigned long val, /* 2nd stage: dereference memory if needed */ do { lval = val; + /* Prevent dereferencing NULL val pointer */ + offset = val ? code->offset : 0; switch (code->op) { case FETCH_OP_DEREF: - ret = probe_mem_read(&val, (void *)val + code->offset, - sizeof(val)); + do_probe_mem_read(&val, (void *)val + offset, + sizeof(val)); break; case FETCH_OP_UDEREF: - ret = probe_mem_read_user(&val, - (void *)val + code->offset, sizeof(val)); + do_probe_mem_read_user(&val, (void *)val + offset, + sizeof(val)); break; case FETCH_OP_CPU_PTR: - val = (unsigned long)this_cpu_ptr((void __percpu *)val); - ret = 0; + /* Do not dereference NULL pointers */ + if (val) + val = (unsigned long)this_cpu_ptr((void __percpu *)val); break; default: lval = llval; goto out; } - if (ret) - return ret; llval = lval; code++; } while (1); @@ -175,17 +229,18 @@ process_fetch_insn_bottom(struct fetch_insn *code, unsigned long val, stage3: /* 3rd stage: store value to buffer */ if (unlikely(!dest)) { + offset = code->offset; switch (code->op) { case FETCH_OP_ST_STRING: - ret = fetch_store_strlen(val + code->offset); + ret = val ? fetch_store_strlen(val + offset) : 0; code++; goto array; case FETCH_OP_ST_USTRING: - ret = fetch_store_strlen_user(val + code->offset); + ret = val ? fetch_store_strlen_user(val + offset) : 0; code++; goto array; case FETCH_OP_ST_SYMSTR: - ret = fetch_store_symstrlen(val + code->offset); + ret = val ? fetch_store_symstrlen(val + offset) : 0; code++; goto array; default: @@ -193,27 +248,33 @@ process_fetch_insn_bottom(struct fetch_insn *code, unsigned long val, } } + /* + * Once val is zero, it is pointing to NULL. Any new dereference is + * also treated as a NULL pointer. + */ + offset = val ? code->offset : 0; + switch (code->op) { case FETCH_OP_ST_RAW: fetch_store_raw(val, code, dest); break; case FETCH_OP_ST_MEM: - probe_mem_read(dest, (void *)val + code->offset, code->size); + do_probe_mem_read(dest, (void *)val + offset, code->size); break; case FETCH_OP_ST_UMEM: - probe_mem_read_user(dest, (void *)val + code->offset, code->size); + do_probe_mem_read_user(dest, (void *)val + offset, code->size); break; case FETCH_OP_ST_STRING: loc = *(u32 *)dest; - ret = fetch_store_string(val + code->offset, dest, base); + ret = do_fetch_store_string(val + offset, dest, base); break; case FETCH_OP_ST_USTRING: loc = *(u32 *)dest; - ret = fetch_store_string_user(val + code->offset, dest, base); + ret = do_fetch_store_string_user(val + offset, dest, base); break; case FETCH_OP_ST_SYMSTR: loc = *(u32 *)dest; - ret = fetch_store_symstring(val + code->offset, dest, base); + ret = fetch_store_symstring(val + offset, dest, base); break; default: return -EILSEQ; @@ -237,11 +298,13 @@ process_fetch_insn_bottom(struct fetch_insn *code, unsigned long val, if (s3->op != FETCH_OP_ST_STRING && s3->op != FETCH_OP_ST_USTRING) { dest += s3->size; - val += s3->size; + /* Only update a non NULL val */ + if (val) + val += s3->size; goto stage3; } code--; - val = lval + sizeof(char *); + val = lval ? lval + sizeof(char *) : 0; if (dest) { dest += sizeof(u32); *(u32 *)dest = update_data_loc(loc, ret); From 041d89bf5b0135e17fcadf8048c8b7c965c587c0 Mon Sep 17 00:00:00 2001 From: Yifan Feng Date: Thu, 19 Nov 2026 11:12:05 -0800 Subject: [PATCH 1805/2102] ftrace: Reject "!!" in front of a set_ftrace_filter command A command written to set_ftrace_filter with two '!' in front of the function glob triggers the WARN_ON() in unregister_ftrace_function_probe_func(): # echo '!!vfs_read:traceoff' >> set_ftrace_filter WARNING: kernel/trace/ftrace.c:5675 at unregister_ftrace_function_probe_func+0x662/0x870 The command callbacks strip the first '!' and pass the rest as the glob of the probe to remove. filter_parse_regex() then reports the second '!' as a negated glob, which function probes do not support. Return -EINVAL for such input in ftrace_process_regex(), before a command callback is called. Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261119191205.32892-1-evanfengff@gmail.com Fixes: 23b4ff3aa479 ("ftrace: add traceon traceoff commands to enable/disable the buffers") Suggested-by: Steven Rostedt Signed-off-by: Yifan Feng Reviewed-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- kernel/trace/ftrace.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/kernel/trace/ftrace.c b/kernel/trace/ftrace.c index 6654da9d1bbf96..5b161959e7019c 100644 --- a/kernel/trace/ftrace.c +++ b/kernel/trace/ftrace.c @@ -5847,6 +5847,13 @@ static int ftrace_process_regex(struct ftrace_iterator *iter, /* command found */ + /* + * A double "!!" confuses the parser. This isn't a boolean operation, + * simply reject it. + */ + if (func[0] == '!' && func[1] == '!') + return -EINVAL; + command = strsep(&next, ":"); guard(mutex)(&ftrace_cmd_mutex); From 86020484c0cf36a72ab998274d051f9a14ff4f40 Mon Sep 17 00:00:00 2001 From: "Masami Hiramatsu (Google)" Date: Sun, 22 Nov 2026 16:17:26 +0900 Subject: [PATCH 1806/2102] tracing/filters: Use atomic bitops and READ_ONCE() for trace_event_file::flags syzbot reported a KCSAN data race on struct trace_event_file::flags between filter_disable() and __trace_trigger_soft_disabled(): BUG: KCSAN: data-race in __trace_trigger_soft_disabled / apply_subsystem_event_filter write to 0xffff888100172888 of 8 bytes by task 5433 on cpu 0: filter_disable [inline] process_system_preds [inline] create_system_filter [inline] apply_subsystem_event_filter+0x28f/0xcd0 subsystem_filter_write+0x79/0xd0 read to 0xffff888100172888 of 8 bytes by task 5440 on cpu 1: __trace_trigger_soft_disabled+0x20/0x1a0 trace_trigger_soft_disabled [inline] filter_disable() and event_set_filtered_flag() update EVENT_FILE_FL_FILTERED using non-atomic read-modify-write operations on file->flags and compare old_flags != file->flags to decide whether to call trace_buffered_event_disable() / trace_buffered_event_enable(). Because other bits in file->flags (such as EVENT_FILE_FL_SOFT_DISABLED_BIT from event enable/disable triggers) can be modified concurrently without event_mutex using atomic bitops, the non-atomic RMW can lose concurrent bit updates or misdetect a flag transition and unbalance the buffered event refcount. Use test_and_clear_bit() / test_and_set_bit() on EVENT_FILE_FL_FILTERED_BIT in filter_disable() and event_set_filtered_flag(), and use READ_ONCE() / test_bit() for lockless readers of file->flags in the trace event fast paths. CC: stable@vger.kernel.org Link: https://patch.msgid.link/179533184612.139632.4029978219979965754.stgit@devnote2 Reported-by: syzbot+1faa12be48036b80e416@syzkaller.appspotmail.com Closes: https://lore.kernel.org/all/6b0234dc.44b41460.34b83f.0019.GAE@google.com Fixes: 0fc1b09ff1ff ("tracing: Use temp buffer when filtering events") Signed-off-by: Masami Hiramatsu (Google) Signed-off-by: Steven Rostedt --- include/linux/trace_events.h | 2 +- kernel/trace/trace.c | 7 ++++--- kernel/trace/trace.h | 18 ++++++++++-------- kernel/trace/trace_events.c | 2 +- kernel/trace/trace_events_filter.c | 12 ++---------- kernel/trace/trace_events_trigger.c | 5 +++-- 6 files changed, 21 insertions(+), 25 deletions(-) diff --git a/include/linux/trace_events.h b/include/linux/trace_events.h index 321f2f3a6c8e8f..7a0aa23825de45 100644 --- a/include/linux/trace_events.h +++ b/include/linux/trace_events.h @@ -764,7 +764,7 @@ bool __trace_trigger_soft_disabled(struct trace_event_file *file); static __always_inline bool trace_trigger_soft_disabled(struct trace_event_file *file) { - unsigned long eflags = file->flags; + unsigned long eflags = READ_ONCE(file->flags); if (likely(!(eflags & (EVENT_FILE_FL_TRIGGER_MODE | EVENT_FILE_FL_SOFT_DISABLED | diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c index 65b9d67647e578..fa65ef8d7fbea3 100644 --- a/kernel/trace/trace.c +++ b/kernel/trace/trace.c @@ -1886,7 +1886,8 @@ trace_event_buffer_lock_reserve(struct trace_buffer **current_rb, *current_rb = tr->array_buffer.buffer; if (!tr->no_filter_buffering_ref && - (trace_file->flags & (EVENT_FILE_FL_SOFT_DISABLED | EVENT_FILE_FL_FILTERED))) { + (READ_ONCE(trace_file->flags) & + (EVENT_FILE_FL_SOFT_DISABLED | EVENT_FILE_FL_FILTERED))) { preempt_disable_notrace(); /* * Filtering is on, so try to use the per cpu buffer first. @@ -1947,7 +1948,7 @@ trace_event_buffer_lock_reserve(struct trace_buffer **current_rb, * to store the trace event for the trigger to use. It's recursive * safe and will not be recorded anywhere. */ - if (!entry && trace_file->flags & EVENT_FILE_FL_TRIGGER_COND) { + if (!entry && (READ_ONCE(trace_file->flags) & EVENT_FILE_FL_TRIGGER_COND)) { *current_rb = temp_buffer; entry = __trace_buffer_lock_reserve(*current_rb, type, len, trace_ctx); @@ -1978,7 +1979,7 @@ static void output_printk(struct trace_event_buffer *fbuffer) file = fbuffer->trace_file; if (test_bit(EVENT_FILE_FL_SOFT_DISABLED_BIT, &file->flags) || - (unlikely(file->flags & EVENT_FILE_FL_FILTERED) && + (unlikely(test_bit(EVENT_FILE_FL_FILTERED_BIT, &file->flags)) && !filter_match_preds(file->filter, fbuffer->entry))) return; diff --git a/kernel/trace/trace.h b/kernel/trace/trace.h index 1fec567e789ea2..32997b58a8a0a4 100644 --- a/kernel/trace/trace.h +++ b/kernel/trace/trace.h @@ -1729,24 +1729,26 @@ __event_trigger_test_discard(struct trace_event_file *file, void *entry, enum event_trigger_type *tt) { - unsigned long eflags = file->flags; + unsigned long eflags = READ_ONCE(file->flags); - if (eflags & EVENT_FILE_FL_TRIGGER_COND) + if (eflags & EVENT_FILE_FL_TRIGGER_COND) { *tt = event_triggers_call(file, buffer, entry, event); + eflags = READ_ONCE(file->flags); + } - if (likely(!(file->flags & (EVENT_FILE_FL_SOFT_DISABLED | - EVENT_FILE_FL_FILTERED | - EVENT_FILE_FL_PID_FILTER)))) + if (likely(!(eflags & (EVENT_FILE_FL_SOFT_DISABLED | + EVENT_FILE_FL_FILTERED | + EVENT_FILE_FL_PID_FILTER)))) return false; - if (file->flags & EVENT_FILE_FL_SOFT_DISABLED) + if (eflags & EVENT_FILE_FL_SOFT_DISABLED) goto discard; - if (file->flags & EVENT_FILE_FL_FILTERED && + if (eflags & EVENT_FILE_FL_FILTERED && !filter_match_preds(file->filter, entry)) goto discard; - if ((file->flags & EVENT_FILE_FL_PID_FILTER) && + if ((eflags & EVENT_FILE_FL_PID_FILTER) && trace_event_ignore_this_pid(file)) goto discard; diff --git a/kernel/trace/trace_events.c b/kernel/trace/trace_events.c index 7f89160aeff3af..394d7cde1a7031 100644 --- a/kernel/trace/trace_events.c +++ b/kernel/trace/trace_events.c @@ -707,7 +707,7 @@ void *trace_event_buffer_reserve(struct trace_event_buffer *fbuffer, { struct trace_event_call *event_call = trace_file->event_call; - if ((trace_file->flags & EVENT_FILE_FL_PID_FILTER) && + if (test_bit(EVENT_FILE_FL_PID_FILTER_BIT, &trace_file->flags) && trace_event_ignore_this_pid(trace_file)) return NULL; diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c index a9d77df3e19a9e..b3ac2519a62d16 100644 --- a/kernel/trace/trace_events_filter.c +++ b/kernel/trace/trace_events_filter.c @@ -1349,11 +1349,7 @@ static void free_prog(struct event_filter *filter) static void filter_disable(struct trace_event_file *file) { - unsigned long old_flags = file->flags; - - file->flags &= ~EVENT_FILE_FL_FILTERED; - - if (old_flags != file->flags) + if (test_and_clear_bit(EVENT_FILE_FL_FILTERED_BIT, &file->flags)) trace_buffered_event_disable(); } @@ -2331,11 +2327,7 @@ static int process_preds(struct trace_event_call *call, static inline void event_set_filtered_flag(struct trace_event_file *file) { - unsigned long old_flags = file->flags; - - file->flags |= EVENT_FILE_FL_FILTERED; - - if (old_flags != file->flags) + if (!test_and_set_bit(EVENT_FILE_FL_FILTERED_BIT, &file->flags)) trace_buffered_event_enable(); } diff --git a/kernel/trace/trace_events_trigger.c b/kernel/trace/trace_events_trigger.c index a2487ad7fef85a..96203ba72ab976 100644 --- a/kernel/trace/trace_events_trigger.c +++ b/kernel/trace/trace_events_trigger.c @@ -214,7 +214,7 @@ EXPORT_SYMBOL_GPL(event_triggers_call); bool __trace_trigger_soft_disabled(struct trace_event_file *file) { - unsigned long eflags = file->flags; + unsigned long eflags = READ_ONCE(file->flags); if (eflags & EVENT_FILE_FL_TRIGGER_MODE) event_triggers_call(file, NULL, NULL, NULL); @@ -1692,7 +1692,8 @@ event_enable_count_func(struct event_trigger_data *data, return false; /* Skip if the event is in a state we want to switch to */ - if (enable_data->enable == !(enable_data->file->flags & EVENT_FILE_FL_SOFT_DISABLED)) + if (enable_data->enable == !test_bit(EVENT_FILE_FL_SOFT_DISABLED_BIT, + &enable_data->file->flags)) return false; if (data->count != -1) From 94df5595e31bf4502fe5195748ca55164ac763f0 Mon Sep 17 00:00:00 2001 From: Leonard Lausen Date: Tue, 17 Nov 2026 11:08:11 +0000 Subject: [PATCH 1807/2102] ipv6: Honor suppress_prefixlength in fib6_lookup() When custom FIB rules are configured, fib6_lookup() performs the lookup via fib6_rule_action_alt() which calls fib6_table_lookup() and only populates the f6i, nh, fib6_flags and fib6_type fields of the FIB result. However, fib6_rule_suppress() only examines the rt6 field, which is only populated when the lookup is performed via one of the callers of fib6_rule_lookup() such as ip6_route_output(). As a result, fib6_lookup() ignores suppress_prefixlength. This was not a problem for nftables until commit 1c32b24c234b ("netfilter: nft_fib_ipv6: switch to fib6_lookup") switched the FIB expression from ip6_route_lookup() / nf_ip6_route() to fib6_lookup(). Since then, with a rule that suppresses the default route in the main table before looking up a VPN table (as commonly configured for WireGuard), the FIB expression returns the suppressed default route instead of the VPN route. Strict reverse path filtering then drops replies received over the VPN. Fix by evaluating suppress_prefixlength against the prefix length of the FIB entry when the lookup is performed via fib6_lookup(). fib_rules_lookup() only invokes the suppress callback when the rule action returns 0. Unlike __fib6_rule_action(), fib6_rule_action_alt() returns 0 for reject routes and instead sets RTF_REJECT in the result. Do not suppress such routes so that they continue to terminate the lookup, as with ip6_route_output() and IPv4. Check the flags in the result rather than in the FIB entry so that blackhole nexthop objects are also covered. suppress_ifgroup is not handled since fib6_table_lookup() does not perform multipath selection and the nexthop it returns might not be the one that is eventually used. Observed during WireGuard use and reproduced on unmodified v7.4-rc2, without instrumentation or error injection. Verified with namespace probes and nft_fib.sh on the rebuilt v7.4-rc2-based kernel. Fixes: 1c32b24c234b ("netfilter: nft_fib_ipv6: switch to fib6_lookup") Link: https://github.com/firewalld/firewalld/issues/1600 Signed-off-by: Leonard Lausen Reviewed-by: Ido Schimmel Link: https://patch.msgid.link/20261117110813.9894-3-leonard@lausen.nl Signed-off-by: Paolo Abeni --- net/ipv6/fib6_rules.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/net/ipv6/fib6_rules.c b/net/ipv6/fib6_rules.c index 0ffd7b47a0460d..7efb0515b5c8bc 100644 --- a/net/ipv6/fib6_rules.c +++ b/net/ipv6/fib6_rules.c @@ -286,6 +286,12 @@ INDIRECT_CALLABLE_SCOPE bool fib6_rule_suppress(struct fib_rule *rule, struct rt6_info *rt = res->rt6; struct net_device *dev = NULL; + if (arg->lookup_ptr == fib6_table_lookup) { + /* fib6_table_lookup() returns 0 for reject routes. */ + return !(res->fib6_flags & RTF_REJECT) && + res->f6i->fib6_dst.plen <= rule->suppress_prefixlen; + } + if (!rt) return false; From a0bf14e17fb2438f1f460747966e767b348f0bba Mon Sep 17 00:00:00 2001 From: Leonard Lausen Date: Tue, 17 Nov 2026 11:08:12 +0000 Subject: [PATCH 1808/2102] selftests: netfilter: cover IPv6 FIB prefix suppression Extend nft_fib.sh using its existing namespaces and counter helper to check that suppress_prefixlength 0 suppresses a default route while retaining a more-specific route. Check that blackhole, unreachable and prohibit routes remain terminal despite a usable route in a later table. Include a blackhole nexthop object to distinguish result reject flags from flags on the FIB entry. Require a positive counter for the expected nftables FIB result. Compare it with the output device or rejection error from an ordinary lookup. Label ruleset-load failures and skip the affected checks when IPv6 prefix suppression or nexthop objects are unavailable. Run these checks after the existing default-table tests so that adding policy rules does not remove coverage of the path without custom IPv6 rules. The router's logging RPF rules have already been removed by then, allowing neighbour discovery during intentionally different reverse-route states. Signed-off-by: Leonard Lausen Link: https://patch.msgid.link/20261117110813.9894-4-leonard@lausen.nl Signed-off-by: Paolo Abeni --- .../selftests/net/netfilter/nft_fib.sh | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/tools/testing/selftests/net/netfilter/nft_fib.sh b/tools/testing/selftests/net/netfilter/nft_fib.sh index 04544905c2164d..25e13197f05780 100755 --- a/tools/testing/selftests/net/netfilter/nft_fib.sh +++ b/tools/testing/selftests/net/netfilter/nft_fib.sh @@ -202,6 +202,50 @@ check_fib_counter() { return 0 } +# Count probes matching the expected FIB result, then drop them. +test_fib_suppress() { + local label="$1" expected="$2" + local result="${3:-oifname}" error err=0 + + if ! ip netns exec "$nsrouter" nft -f /dev/stdin < /dev/null 2>&1 + if [ "$result" = type ]; then + case "$expected" in + blackhole) error="Invalid argument" ;; + unreachable) error="No route to host" ;; + prohibit) error="Permission denied" ;; + esac + LC_ALL=C ip -net "$nsrouter" -6 route get dead:1::99 \ + from dead:1::1 2>&1 | + grep -Fxq "RTNETLINK answers: $error" || err=1 + else + ip -net "$nsrouter" -6 route get dead:1::99 from dead:1::1 | + grep -q "dev $expected " || err=1 + fi + if check_fib_type_counter_family ip6 1 "$nsrouter" prerouting \ + "$result" "$label" && + [ "$err" -eq 0 ]; then + echo "PASS: $label" + else + echo "FAIL: $label" + ret=1 + return 1 + fi +} + load_ruleset "$nsrouter" load_ruleset "$ns1" load_ruleset "$ns2" @@ -845,6 +889,52 @@ test_fib_type "default table" ip netns exec "$nsrouter" nft delete table ip filter ip netns exec "$nsrouter" nft delete table ip6 filter +# Keep the earlier IPv6 checks on the path without custom rules. +# The router's logging RPF rules have already been removed here. +if ip -net "$nsrouter" -6 rule add pref 100 to dead:1::99 table 128 \ + suppress_prefixlength 0; then + ip -net "$nsrouter" -6 route add table 128 default dev veth1 || exit 1 + ip -net "$nsrouter" -6 route add table 129 dead:1::/64 \ + dev veth0 || exit 1 + ip -net "$nsrouter" -6 rule add pref 101 to dead:1::99 \ + table 129 || exit 1 + ip netns exec "$nsrouter" nft add table ip6 filter || exit 1 + + test_fib_suppress "suppress default route" veth0 || ret=1 + ip -net "$nsrouter" -6 route add table 128 dead:1::/64 \ + dev veth1 || exit 1 + test_fib_suppress "retain non-default route" veth1 || ret=1 + ip -net "$nsrouter" -6 route del table 128 dead:1::/64 \ + dev veth1 || exit 1 + + for type in blackhole unreachable prohibit; do + ip -net "$nsrouter" -6 route replace "$type" default \ + table 128 || exit 1 + test_fib_suppress "retain $type" "$type" type || ret=1 + done + + if ip -net "$nsrouter" -6 nexthop add id 1 blackhole; then + ip -net "$nsrouter" -6 route replace default nhid 1 \ + table 128 || exit 1 + test_fib_suppress "retain blackhole nexthop" \ + blackhole type || ret=1 + ip -net "$nsrouter" -6 route del table 128 default + ip -net "$nsrouter" -6 nexthop del id 1 + else + echo "SKIP: blackhole nexthop objects unavailable" + [ "$ret" -eq 0 ] && ret=$ksft_skip + ip -net "$nsrouter" -6 route del table 128 default + fi + + ip -net "$nsrouter" -6 rule del pref 100 + ip -net "$nsrouter" -6 rule del pref 101 + ip -net "$nsrouter" -6 route flush table 129 + ip netns exec "$nsrouter" nft delete table ip6 filter +else + echo "SKIP: IPv6 prefix suppression unavailable" + [ "$ret" -eq 0 ] && ret=$ksft_skip +fi + test_fib_vrf exit $ret From 8a37614bcd382da36337a271b8945d0dc0cdb111 Mon Sep 17 00:00:00 2001 From: David Francis Date: Mon, 23 Nov 2026 14:18:20 -0500 Subject: [PATCH 1809/2102] drm/amdkfd: Correctly handle multi-xcc mqd size in CRIU restore kfd_criu_restore_queue validates that a CRIU restore has the correct mqd size, but doesn't correctly handle that the mqd will be scaled but the number of xccs. Change the check to handle multiple xccs correctly. Fixes: f19d8086f664 ("drm/amdkfd: Check bounds on CRIU restore queue type and mqd size") Signed-off-by: David Francis Reviewed-by: David Yat Sin Signed-off-by: Alex Deucher (cherry picked from commit a69db917063c539fa09325ea22f3ff7b0626b478) Cc: stable@vger.kernel.org --- drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c b/drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c index b68e884b1c37a0..2b86d359c40653 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c @@ -1041,7 +1041,8 @@ int kfd_criu_restore_queue(struct kfd_process *p, goto exit; } - if (q_data->mqd_size != mqd_size_from_queue_type(pdd->dev->dqm, q_data->type)) { + if (q_data->mqd_size != mqd_size_from_queue_type(pdd->dev->dqm, q_data->type) * + NUM_XCC(pdd->dev->xcc_mask)) { ret = -EINVAL; goto exit; } From dda2d9cd1fcd9ea1e4a93657e7386fde37d7e2ba Mon Sep 17 00:00:00 2001 From: Takashi Iwai Date: Wed, 25 Nov 2026 14:54:52 +0100 Subject: [PATCH 1810/2102] ALSA: oss: Fix deadlock at unregistering (again) The recent code refactoring using guard() re-introduced a potential deadlock at unregistering OSS device that had been fixed onceby the commit 97d917879d7f ("ALSA: oss: Fix potential deadlock at unregistration"). The unregister_sound_special() call must be done outside the sound_oss_mutex. Fix the regression by changing guard() with scoped_guard() to limit the range. Fixes: 742ecf3ce1ac ("ALSA: core: Use guard() for locking") Cc: Link: https://patch.msgid.link/20261125135453.2088984-1-tiwai@suse.de Signed-off-by: Takashi Iwai --- sound/core/sound_oss.c | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/sound/core/sound_oss.c b/sound/core/sound_oss.c index 7eb49f2cada5d0..f36c413bbf5663 100644 --- a/sound/core/sound_oss.c +++ b/sound/core/sound_oss.c @@ -153,24 +153,25 @@ int snd_unregister_oss_device(int type, struct snd_card *card, int dev) return 0; if (minor < 0) return minor; - guard(mutex)(&sound_oss_mutex); - mptr = snd_oss_minors[minor]; - if (mptr == NULL) - return -ENOENT; - switch (SNDRV_MINOR_OSS_DEVICE(minor)) { - case SNDRV_MINOR_OSS_PCM: - track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_AUDIO); - break; - case SNDRV_MINOR_OSS_MIDI: - track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_DMMIDI); - break; - case SNDRV_MINOR_OSS_MIDI1: - track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_DMMIDI1); - break; + scoped_guard(mutex, &sound_oss_mutex) { + mptr = snd_oss_minors[minor]; + if (mptr == NULL) + return -ENOENT; + switch (SNDRV_MINOR_OSS_DEVICE(minor)) { + case SNDRV_MINOR_OSS_PCM: + track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_AUDIO); + break; + case SNDRV_MINOR_OSS_MIDI: + track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_DMMIDI); + break; + case SNDRV_MINOR_OSS_MIDI1: + track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_DMMIDI1); + break; + } + if (track2 >= 0) + snd_oss_minors[track2] = NULL; + snd_oss_minors[minor] = NULL; } - if (track2 >= 0) - snd_oss_minors[track2] = NULL; - snd_oss_minors[minor] = NULL; /* call unregister_sound_special() outside sound_oss_mutex; * otherwise may deadlock, as it can trigger the release of a card From 5a6fcabe156e91c6ef2435a74f2d16e6dd39f7c7 Mon Sep 17 00:00:00 2001 From: Takashi Iwai Date: Wed, 25 Nov 2026 15:10:56 +0100 Subject: [PATCH 1811/2102] ALSA: usb-audio: Don't queue playback URBs after stop Although we've tried to address the corrupted ready_list for the playback URBs due to the concurrent start/stop of streams, there seems still a slight race: namely, in snd_complete_urb(), the driver checks the EP check via ep_state_running() and process push_back_to_ready_list() only when the EP isn't stopped. But since the EP state change can still happen between the EP state check and push_back_to_ready_list(), push_back_to_ready_list() may queue the URBs unexpectedly even after the EP gets stopped. This may result in a list corruption when the stream is restarted. The addition to the list itself is properly protected by a lock, so as a stop-gap, just add the EP state check again before actually adding to the list. In a long-term, we should reorganize the code to cover the EP state changes more consistently, but this should suffice for the particular race, at least. Reported-by: Miloslav Brada Closes: https://lore.kernel.org/awZs88beIhMcOchv@genesis.transkript.cz Cc: Link: https://patch.msgid.link/20261125141057.2094719-1-tiwai@suse.de Signed-off-by: Takashi Iwai --- sound/usb/endpoint.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sound/usb/endpoint.c b/sound/usb/endpoint.c index 8dd0b3525e4b07..02f0049cacf32a 100644 --- a/sound/usb/endpoint.c +++ b/sound/usb/endpoint.c @@ -449,6 +449,9 @@ static void push_back_to_ready_list(struct snd_usb_endpoint *ep, struct snd_urb_ctx *ctx) { guard(spinlock_irqsave)(&ep->lock); + /* don't re-queue after stop_urbs() flushed the list */ + if (!ep_state_running(ep)) + return; /* ctx may still be linked: a stale completion racing a stop/restart. */ if (list_empty(&ctx->ready_list)) list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs); From 469b61e4be88bc671dabe802e11f706b1ea7aa15 Mon Sep 17 00:00:00 2001 From: Aristo Chen Date: Thu, 19 Nov 2026 10:07:10 +0000 Subject: [PATCH 1812/2102] net: dsa: felix: fix NULL pointer dereference in felix_port_enable() DSA registers the user ports in dsa_tree_setup_ports() before it sets conduit->dsa_ptr in dsa_tree_setup_conduit(). On teardown, it clears conduit->dsa_ptr in dsa_tree_teardown_conduit() before dsa_tree_teardown_ports() removes the user ports. RTNL is not held across either pair of steps, so user space can open a user port while conduit->dsa_ptr is NULL. In NPI mode, felix_port_enable() calls felix_cpu_port_for_conduit(). For a physical conduit, that function reads the CPU port index through conduit->dsa_ptr without checking for NULL. This caused an oops on an LS1028A RDB when systemd-networkd tried to open a user port while the switch was being probed again at runtime: [ 166.722423] Unable to handle kernel access to user memory outside uaccess routines at virtual address 0000000000000028 [ 166.816908] Internal error: Oops: 0000000096000004 [#1] SMP [ 166.961766] pc : felix_cpu_port_for_conduit.isra.0+0x90/0xb8 [mscc_felix_dsa_lib] [ 166.969289] lr : felix_port_enable+0x120/0x1a0 [mscc_felix_dsa_lib] The oops left RTNL locked. Later operations that waited for RTNL hung, and the board had to be power cycled. NPI mode uses one CPU port for the whole switch. Changing the conduit of a user port can move the NPI port to another CPU port, and the check in felix_port_enable() keeps user ports that still use the old CPU port down. For a physical conduit, compare dp->cpu_dp->index with the NPI port instead. DSA sets dp->cpu_dp before it registers the user port and clears it only after it removes the user port, so the check keeps working while conduit->dsa_ptr is NULL. As long as the physical conduit is set up, conduit->dsa_ptr and dp->cpu_dp point to the same CPU port, so the check gives the same result as before. LAG conduits keep using felix_cpu_port_for_conduit(), which does not read dsa_ptr for them. Fixes: eca70102cfb1 ("net: dsa: felix: add support for changing DSA master") Signed-off-by: Aristo Chen Reviewed-by: Vladimir Oltean Tested-by: Vladimir Oltean Link: https://patch.msgid.link/20261119100710.129379-1-aristo.chen@canonical.com Signed-off-by: Paolo Abeni --- drivers/net/dsa/ocelot/felix.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/drivers/net/dsa/ocelot/felix.c b/drivers/net/dsa/ocelot/felix.c index c99fd3d23bb3f1..76aabb8e288787 100644 --- a/drivers/net/dsa/ocelot/felix.c +++ b/drivers/net/dsa/ocelot/felix.c @@ -1239,8 +1239,19 @@ static int felix_port_enable(struct dsa_switch *ds, int port, if (ocelot->npi >= 0) { struct net_device *conduit = dsa_port_to_conduit(dp); + int cpu; - if (felix_cpu_port_for_conduit(ds, conduit) != ocelot->npi) { + /* Do not use conduit->dsa_ptr for a physical conduit. It is + * NULL before DSA sets up the conduit and after it tears it + * down, and opening a user port can reach this check in both + * cases. + */ + if (netif_is_lag_master(conduit)) + cpu = felix_cpu_port_for_conduit(ds, conduit); + else + cpu = dp->cpu_dp->index; + + if (cpu != ocelot->npi) { dev_err(ds->dev, "Multiple conduits are not allowed\n"); return -EINVAL; } From 7ed616970b652ae76d99a01b468588e491021648 Mon Sep 17 00:00:00 2001 From: Dominik Maier Date: Thu, 19 Nov 2026 20:21:59 +0100 Subject: [PATCH 1813/2102] mptcp: gate diag sequence counters on CAP_NET_ADMIN In net/mptcp/diag.c, subflow_get_info() restricts MPTCP sequence-related subflow attributes (rel_write_seq, map_seq, map_subflow_seq, ssn_offset) to callers holding CAP_NET_ADMIN in the network namespace. However, mptcp_diag_get_info() unconditionally exports mptcpi_write_seq, mptcpi_snd_una, and mptcpi_rcv_nxt via INET_DIAG_INFO because .idiag_get_info does not receive the caller's net_admin status. Any unprivileged local user can therefore dump or query cross-UID MPTCP sockets by token via SOCK_DIAG_BY_FAMILY and read live 64-bit MPTCP Data Sequence Numbers. Emit INET_DIAG_INFO from an .idiag_get_aux callback in mptcp_diag (which already receives net_admin from inet_sk_diag_fill(), while msk never sets icsk_ca_ops so netlink attribute ordering is unchanged) and zero mptcpi_write_seq, mptcpi_snd_una, and mptcpi_rcv_nxt when !net_admin. getsockopt(SOL_MPTCP, MPTCP_INFO) for the socket owner and token-based lookup in mptcp_diag_dump_one() remain unchanged. This issue was discovered with an AI-assisted code review tool (ARTIST) and reproduced in QEMU/KVM on an unmodified v7.4-rc3 kernel without kernel modifications or error injection. Fixes: ac3b45f60954 ("mptcp: add MPTCP socket diag interface") Cc: stable@vger.kernel.org Signed-off-by: Dominik Maier Tested-by: Kalpan Jani Reviewed-by: Matthieu Baerts (NGI0) Link: https://patch.msgid.link/20261119192159.2646113-1-dmnk@google.com Signed-off-by: Paolo Abeni --- net/mptcp/mptcp_diag.c | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/net/mptcp/mptcp_diag.c b/net/mptcp/mptcp_diag.c index 136c2d05c0eeb8..62d8f1fa7a4088 100644 --- a/net/mptcp/mptcp_diag.c +++ b/net/mptcp/mptcp_diag.c @@ -193,10 +193,9 @@ static void mptcp_diag_get_info(struct sock *sk, struct inet_diag_msg *r, void *_info) { struct mptcp_sock *msk = mptcp_sk(sk); - struct mptcp_info *info = _info; r->idiag_rqueue = sk_rmem_alloc_get(sk) + - READ_ONCE(mptcp_sk(sk)->backlog_len); + READ_ONCE(msk->backlog_len); r->idiag_wqueue = sk_wmem_alloc_get(sk); if (inet_sk_state_load(sk) == TCP_LISTEN) { @@ -210,11 +209,29 @@ static void mptcp_diag_get_info(struct sock *sk, struct inet_diag_msg *r, r->idiag_wqueue = READ_ONCE(lsk->sk_max_ack_backlog); } } +} - if (!info) - return; +static int mptcp_diag_get_aux(struct sock *sk, bool net_admin, + struct sk_buff *skb) +{ + struct mptcp_sock *msk = mptcp_sk(sk); + struct mptcp_info *info; + struct nlattr *attr; + attr = nla_reserve_64bit(skb, INET_DIAG_INFO, + sizeof(struct mptcp_info), INET_DIAG_PAD); + if (!attr) + return -EMSGSIZE; + + info = nla_data(attr); mptcp_diag_fill_info(msk, info); + /* Only export seq related counters to user with CAP_NET_ADMIN */ + if (!net_admin) { + info->mptcpi_write_seq = 0; + info->mptcpi_snd_una = 0; + info->mptcpi_rcv_nxt = 0; + } + return 0; } static const struct inet_diag_handler mptcp_diag_handler = { @@ -222,8 +239,9 @@ static const struct inet_diag_handler mptcp_diag_handler = { .dump = mptcp_diag_dump, .dump_one = mptcp_diag_dump_one, .idiag_get_info = mptcp_diag_get_info, + .idiag_get_aux = mptcp_diag_get_aux, .idiag_type = IPPROTO_MPTCP, - .idiag_info_size = sizeof(struct mptcp_info), + .idiag_info_size = 0, }; static int __init mptcp_diag_init(void) From 83e20d3e0d1197cbc9b18eb50efab0cf561ee95a Mon Sep 17 00:00:00 2001 From: Ian Rogers Date: Thu, 19 Nov 2026 09:11:11 -0800 Subject: [PATCH 1814/2102] ASoC: sti: Return irqreturn_t instead of -EPERM in uni_player_irq_handler() When UNIPERIF_ITM_UNDERFLOW_REC_DONE_MASK fires while player->underflow_enabled is false, uni_player_irq_handler() sets ret = -EPERM and returns it as irqreturn_t. Returning a negative errno from a hardirq handler triggers report_bad_irq() in note_interrupt() and bypasses unhandled-IRQ storm accounting (while also clobbering IRQ_HANDLED if an earlier status bit was handled in the same call). Leave ret unchanged (IRQ_NONE by default, or IRQ_HANDLED if an earlier error bit was handled) instead of overwriting it with -EPERM. Found via Clang -Wassign-enum on an x86_64 allyesconfig build. Verified by building sound/soc/sti/uniperif_player.o with LLVM=1 W=1 (-Werror) and -Wassign-enum; not runtime-tested on STi hardware. Fixes: 76c2145ded6b ("ASoC: sti: Add CPU DAI driver for playback") Signed-off-by: Ian Rogers Link: https://patch.msgid.link/20261119171111.1538575-1-irogers@google.com Signed-off-by: Mark Brown --- sound/soc/sti/uniperif_player.c | 1 - 1 file changed, 1 deletion(-) diff --git a/sound/soc/sti/uniperif_player.c b/sound/soc/sti/uniperif_player.c index 23c6f9e513c121..f5abbfd91b114f 100644 --- a/sound/soc/sti/uniperif_player.c +++ b/sound/soc/sti/uniperif_player.c @@ -117,7 +117,6 @@ static irqreturn_t uni_player_irq_handler(int irq, void *dev_id) if (!player->underflow_enabled) { dev_err(player->dev, "unexpected Underflow recovering\n"); - ret = -EPERM; snd_pcm_stream_unlock(player->substream); return ret; } From 1c986bc5918cbbb438eb57211c9d0b3de2878cd0 Mon Sep 17 00:00:00 2001 From: Xiaolei Wang Date: Tue, 24 Nov 2026 11:37:23 +0000 Subject: [PATCH 1815/2102] drm/v3d: Fix double free of query arrays on parse failure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a parse error the timestamp and performance parsers free the query array, and the job release path then frees it again: query_info->count had not been set yet, so no syncobj was put twice, but the stale array was handed to kvfree() a second time. Make the job the only owner: the parsers just fill the array and record how far they got. count is set before the parse loop, the arrays are zero allocated, and the free helpers stop at the first entry that was never set up, which keeps put-count equal to find-count. That also removes the inline kvfree() of kperfmon_ids and the count arguments of the free helpers. Tested on Raspberry Pi 5 (v3d). Cc: stable@vger.kernel.org # v6.8+ Fixes: 9ba0ff3e083f ("drm/v3d: Create a CPU job extension for the timestamp query job") Fixes: bae7cb5d6800 ("drm/v3d: Create a CPU job extension for the reset performance query job") Signed-off-by: Xiaolei Wang Link: https://patch.msgid.link/20261124113723.3055530-1-wangxiaolei01@kaihong.com Reviewed-by: Maíra Canal Signed-off-by: Maíra Canal --- drivers/gpu/drm/v3d/v3d_drv.h | 6 +- drivers/gpu/drm/v3d/v3d_sched.c | 40 +++++---- drivers/gpu/drm/v3d/v3d_submit.c | 142 ++++++++++--------------------- 3 files changed, 73 insertions(+), 115 deletions(-) diff --git a/drivers/gpu/drm/v3d/v3d_drv.h b/drivers/gpu/drm/v3d/v3d_drv.h index 7c7bdf6e51a51e..e5c9ad86449a15 100644 --- a/drivers/gpu/drm/v3d/v3d_drv.h +++ b/drivers/gpu/drm/v3d/v3d_drv.h @@ -669,10 +669,8 @@ static __always_inline int v3d_pm_runtime_put(struct v3d_dev *v3d) } /* v3d_sched.c */ -void v3d_timestamp_query_info_free(struct v3d_timestamp_query_info *query_info, - unsigned int count); -void v3d_performance_query_info_free(struct v3d_performance_query_info *query_info, - unsigned int count); +void v3d_timestamp_query_info_free(struct v3d_timestamp_query_info *query_info); +void v3d_performance_query_info_free(struct v3d_performance_query_info *query_info); struct v3d_stats *v3d_stats_alloc(void); void v3d_stats_release(struct kref *refcount); void v3d_job_update_stats(struct v3d_job *job); diff --git a/drivers/gpu/drm/v3d/v3d_sched.c b/drivers/gpu/drm/v3d/v3d_sched.c index 1be2cd5bbf673b..cc4e6d0dddabc5 100644 --- a/drivers/gpu/drm/v3d/v3d_sched.c +++ b/drivers/gpu/drm/v3d/v3d_sched.c @@ -96,33 +96,41 @@ v3d_sched_job_free(struct drm_sched_job *sched_job) } void -v3d_timestamp_query_info_free(struct v3d_timestamp_query_info *query_info, - unsigned int count) +v3d_timestamp_query_info_free(struct v3d_timestamp_query_info *query_info) { - if (query_info->queries) { - unsigned int i; + unsigned int i; - for (i = 0; i < count; i++) - drm_syncobj_put(query_info->queries[i].syncobj); + if (!query_info->queries) + return; - kvfree(query_info->queries); + for (i = 0; i < query_info->count; i++) { + if (!query_info->queries[i].syncobj) + break; + + drm_syncobj_put(query_info->queries[i].syncobj); } + + kvfree(query_info->queries); } void -v3d_performance_query_info_free(struct v3d_performance_query_info *query_info, - unsigned int count) +v3d_performance_query_info_free(struct v3d_performance_query_info *query_info) { - if (query_info->queries) { - unsigned int i; + unsigned int i; - for (i = 0; i < count; i++) { - drm_syncobj_put(query_info->queries[i].syncobj); - kvfree(query_info->queries[i].kperfmon_ids); - } + if (!query_info->queries) + return; - kvfree(query_info->queries); + for (i = 0; i < query_info->count; i++) { + kvfree(query_info->queries[i].kperfmon_ids); + + if (!query_info->queries[i].syncobj) + break; + + drm_syncobj_put(query_info->queries[i].syncobj); } + + kvfree(query_info->queries); } static void diff --git a/drivers/gpu/drm/v3d/v3d_submit.c b/drivers/gpu/drm/v3d/v3d_submit.c index 7548faab67baad..fc85ad4defb75f 100644 --- a/drivers/gpu/drm/v3d/v3d_submit.c +++ b/drivers/gpu/drm/v3d/v3d_submit.c @@ -174,11 +174,9 @@ v3d_cpu_job_free(struct kref *ref) struct v3d_cpu_job *job = container_of(ref, struct v3d_cpu_job, base.refcount); - v3d_timestamp_query_info_free(&job->timestamp_query, - job->timestamp_query.count); + v3d_timestamp_query_info_free(&job->timestamp_query); - v3d_performance_query_info_free(&job->performance_query, - job->performance_query.count); + v3d_performance_query_info_free(&job->performance_query); if (job->indirect_csd.indirect) drm_gem_object_put(job->indirect_csd.indirect); @@ -734,7 +732,6 @@ v3d_get_cpu_timestamp_query_params(struct drm_file *file_priv, struct drm_v3d_timestamp_query timestamp; struct v3d_timestamp_query_info *query_info = &job->timestamp_query; unsigned int i; - int err; if (!v3d_validate_cpu_job(file_priv, job)) return -EINVAL; @@ -747,43 +744,34 @@ v3d_get_cpu_timestamp_query_params(struct drm_file *file_priv, job->job_type = V3D_CPU_JOB_TYPE_TIMESTAMP_QUERY; - query_info->queries = kvmalloc_objs(struct v3d_timestamp_query, + query_info->queries = kvzalloc_objs(struct v3d_timestamp_query, timestamp.count); if (!query_info->queries) return -ENOMEM; + query_info->count = timestamp.count; + offsets = u64_to_user_ptr(timestamp.offsets); syncs = u64_to_user_ptr(timestamp.syncs); - for (i = 0; i < timestamp.count; i++) { + for (i = 0; i < query_info->count; i++) { u32 offset, sync; - if (get_user(offset, offsets++)) { - err = -EFAULT; - goto error; - } + if (get_user(offset, offsets++)) + return -EFAULT; query_info->queries[i].offset = offset; - if (get_user(sync, syncs++)) { - err = -EFAULT; - goto error; - } + if (get_user(sync, syncs++)) + return -EFAULT; query_info->queries[i].syncobj = drm_syncobj_find(file_priv, sync); - if (!query_info->queries[i].syncobj) { - err = -ENOENT; - goto error; - } + if (!query_info->queries[i].syncobj) + return -ENOENT; } - query_info->count = timestamp.count; return 0; - -error: - v3d_timestamp_query_info_free(&job->timestamp_query, i); - return err; } static int @@ -795,7 +783,6 @@ v3d_get_cpu_reset_timestamp_params(struct drm_file *file_priv, struct drm_v3d_reset_timestamp_query reset; struct v3d_timestamp_query_info *query_info = &job->timestamp_query; unsigned int i; - int err; if (!v3d_validate_cpu_job(file_priv, job)) return -EINVAL; @@ -805,37 +792,30 @@ v3d_get_cpu_reset_timestamp_params(struct drm_file *file_priv, job->job_type = V3D_CPU_JOB_TYPE_RESET_TIMESTAMP_QUERY; - query_info->queries = kvmalloc_objs(struct v3d_timestamp_query, + query_info->queries = kvzalloc_objs(struct v3d_timestamp_query, reset.count); if (!query_info->queries) return -ENOMEM; + query_info->count = reset.count; + syncs = u64_to_user_ptr(reset.syncs); - for (i = 0; i < reset.count; i++) { + for (i = 0; i < query_info->count; i++) { u32 sync; query_info->queries[i].offset = reset.offset + 8 * i; - if (get_user(sync, syncs++)) { - err = -EFAULT; - goto error; - } + if (get_user(sync, syncs++)) + return -EFAULT; query_info->queries[i].syncobj = drm_syncobj_find(file_priv, sync); - if (!query_info->queries[i].syncobj) { - err = -ENOENT; - goto error; - } + if (!query_info->queries[i].syncobj) + return -ENOENT; } - query_info->count = reset.count; return 0; - -error: - v3d_timestamp_query_info_free(&job->timestamp_query, i); - return err; } /* Get data for the copy timestamp query results job submission. */ @@ -848,7 +828,6 @@ v3d_get_cpu_copy_query_results_params(struct drm_file *file_priv, struct drm_v3d_copy_timestamp_query copy; struct v3d_timestamp_query_info *query_info = &job->timestamp_query; unsigned int i; - int err; if (!v3d_validate_cpu_job(file_priv, job)) return -EINVAL; @@ -861,37 +840,32 @@ v3d_get_cpu_copy_query_results_params(struct drm_file *file_priv, job->job_type = V3D_CPU_JOB_TYPE_COPY_TIMESTAMP_QUERY; - query_info->queries = kvmalloc_objs(struct v3d_timestamp_query, + query_info->queries = kvzalloc_objs(struct v3d_timestamp_query, copy.count); if (!query_info->queries) return -ENOMEM; + query_info->count = copy.count; + offsets = u64_to_user_ptr(copy.offsets); syncs = u64_to_user_ptr(copy.syncs); - for (i = 0; i < copy.count; i++) { + for (i = 0; i < query_info->count; i++) { u32 offset, sync; - if (get_user(offset, offsets++)) { - err = -EFAULT; - goto error; - } + if (get_user(offset, offsets++)) + return -EFAULT; query_info->queries[i].offset = offset; - if (get_user(sync, syncs++)) { - err = -EFAULT; - goto error; - } + if (get_user(sync, syncs++)) + return -EFAULT; query_info->queries[i].syncobj = drm_syncobj_find(file_priv, sync); - if (!query_info->queries[i].syncobj) { - err = -ENOENT; - goto error; - } + if (!query_info->queries[i].syncobj) + return -ENOENT; } - query_info->count = copy.count; job->copy.do_64bit = copy.do_64bit; job->copy.do_partial = copy.do_partial; @@ -900,73 +874,51 @@ v3d_get_cpu_copy_query_results_params(struct drm_file *file_priv, job->copy.stride = copy.stride; return 0; - -error: - v3d_timestamp_query_info_free(&job->timestamp_query, i); - return err; } static int v3d_copy_query_info(struct v3d_performance_query_info *query_info, - unsigned int count, unsigned int nperfmons, u32 __user *syncs, u64 __user *kperfmon_ids, struct drm_file *file_priv) { unsigned int i, j; - int err; - for (i = 0; i < count; i++) { + for (i = 0; i < query_info->count; i++) { struct v3d_performance_query *query = &query_info->queries[i]; u32 __user *ids_pointer; u32 sync, id; u64 ids; - if (get_user(sync, syncs++)) { - err = -EFAULT; - goto error; - } + if (get_user(sync, syncs++)) + return -EFAULT; - if (get_user(ids, kperfmon_ids++)) { - err = -EFAULT; - goto error; - } + if (get_user(ids, kperfmon_ids++)) + return -EFAULT; query->kperfmon_ids = kvmalloc_array(nperfmons, sizeof(struct v3d_performance_query *), GFP_KERNEL); - if (!query->kperfmon_ids) { - err = -ENOMEM; - goto error; - } + if (!query->kperfmon_ids) + return -ENOMEM; ids_pointer = u64_to_user_ptr(ids); for (j = 0; j < nperfmons; j++) { - if (get_user(id, ids_pointer++)) { - kvfree(query->kperfmon_ids); - err = -EFAULT; - goto error; - } + if (get_user(id, ids_pointer++)) + return -EFAULT; query->kperfmon_ids[j] = id; } query->syncobj = drm_syncobj_find(file_priv, sync); - if (!query->syncobj) { - kvfree(query->kperfmon_ids); - err = -ENOENT; - goto error; - } + if (!query->syncobj) + return -ENOENT; } return 0; - -error: - v3d_performance_query_info_free(query_info, i); - return err; } static int @@ -987,12 +939,13 @@ v3d_get_cpu_reset_performance_params(struct drm_file *file_priv, job->job_type = V3D_CPU_JOB_TYPE_RESET_PERFORMANCE_QUERY; query_info->queries = - kvmalloc_objs(struct v3d_performance_query, reset.count); + kvzalloc_objs(struct v3d_performance_query, reset.count); if (!query_info->queries) return -ENOMEM; + query_info->count = reset.count; + err = v3d_copy_query_info(query_info, - reset.count, reset.nperfmons, u64_to_user_ptr(reset.syncs), u64_to_user_ptr(reset.kperfmon_ids), @@ -1000,7 +953,6 @@ v3d_get_cpu_reset_performance_params(struct drm_file *file_priv, if (err) return err; - query_info->count = reset.count; query_info->nperfmons = reset.nperfmons; return 0; @@ -1027,12 +979,13 @@ v3d_get_cpu_copy_performance_query_params(struct drm_file *file_priv, job->job_type = V3D_CPU_JOB_TYPE_COPY_PERFORMANCE_QUERY; query_info->queries = - kvmalloc_objs(struct v3d_performance_query, copy.count); + kvzalloc_objs(struct v3d_performance_query, copy.count); if (!query_info->queries) return -ENOMEM; + query_info->count = copy.count; + err = v3d_copy_query_info(query_info, - copy.count, copy.nperfmons, u64_to_user_ptr(copy.syncs), u64_to_user_ptr(copy.kperfmon_ids), @@ -1040,7 +993,6 @@ v3d_get_cpu_copy_performance_query_params(struct drm_file *file_priv, if (err) return err; - query_info->count = copy.count; query_info->nperfmons = copy.nperfmons; query_info->ncounters = copy.ncounters; From bbdf19889585f036692a0c77a1402a37cf07c417 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Wed, 11 Nov 2026 09:35:14 +0000 Subject: [PATCH 1816/2102] io_uring/net: don't copy msg_name on a recvmsg retry IORING_OP_RECVMSG with MSG_WAITALL can write past the end of the user's msg_name buffer, if a partial receive is retried and the source address is longer than the buffer. msg_namelen is an in/out field: move_addr_to_user() reads the size of the buffer from it, and then stores the untruncated length of the address there. So the size is valid for one call to ____sys_recvmsg() only. But io_recvmsg() passes the same umsg and uaddr again when it retries a partial receive, and nothing restores msg_namelen in between: msg_namelen = 16, AF_UNIX source address of 110 bytes size read bytes copied msg_namelen stored receive 1 16 16 110 receive 2 110 110 110 If the copy in the retry faults, the result of the request lacks the data that the retry took off the socket. A retry that hits EOF has no address, so it stores a msg_namelen of 0 while the buffer holds the address. And an address that is longer than the one before it is truncated to the length of the one before. The fix used here is to copy the address out with the first part of the data only, and to leave msg_name and msg_namelen alone in the retries. The address is now that of the first part of the data and no longer that of the last part. The two differ only if the source address changes within one request: on an unconnected SOCK_SEQPACKET socket that receives from several peers, or if an AF_UNIX peer binds between two parts. A program that passes a msg_namelen smaller than its buffer got the whole address from the second receive on, and now gets the truncated address, as from recvmsg(2). The retries also no longer reach audit_sockaddr(), so with an audit rule for IORING_OP_RECVMSG the event of the retry that completes the request can lack its SOCKADDR record. The event that keeps the record is that of the first partial receive, which audit logs as failed with -EAGAIN. Fixes: 7ba89d2af17a ("io_uring: ensure recv and recvmsg handle MSG_WAITALL correctly") Signed-off-by: Chris Mason Signed-off-by: Jens Axboe --- io_uring/net.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/io_uring/net.c b/io_uring/net.c index 8afad1b2ddc010..f8d547c5e7d671 100644 --- a/io_uring/net.c +++ b/io_uring/net.c @@ -1116,6 +1116,8 @@ int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags) if (ret > 0 && io_net_retry(sock, flags) && io_net_kbuf_can_retry(req, sel.buf_list, kmsg)) { sr->done_io += ret; + /* msg_name and msg_namelen are filled in, leave them */ + kmsg->uaddr = NULL; return io_net_kbuf_recyle(req, sel.buf_list, kmsg, ret); } if (ret == -ERESTARTSYS) From 2f70f2cf62e87b908f301fd78b2d01308cbf2ea4 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Wed, 11 Nov 2026 16:39:08 +0000 Subject: [PATCH 1817/2102] io_uring/kbuf: clear REQ_F_BL_NO_RECYCLE on buffer put A bundle receive with MSG_WAITALL can hit a NULL pointer dereference in io_net_kbuf_can_retry(), or share ring provided buffers with another request of the buffer group, if another reader of the socket takes the data that the receive is about to append. The buffer list is only known within the issue that selected from it, so io_recv() has to commit or recycle ring provided buffers before it returns IOU_RETRY. On -EAGAIN it calls io_kbuf_recycle(), which does nothing if REQ_F_BL_NO_RECYCLE is set. A partial transfer sets that flag for the buffer that holds the data, and nothing ever clears it. That was fine while only a multishot receive selected more than once, as multishot excludes MSG_WAITALL. But since commit 7c71a0af81ba ("io_uring/net: improve recv bundles") any bundle receive can put its buffers and select new ones, and the stale flag covers these too: io_recv() partial transfer io_net_kbuf_recyle() sets the flag, commits the buffer return IOU_RETRY io_recv() fills the buffer, msg_inq > 1 io_recv_finish() io_put_kbufs() leaves the flag set io_buffers_peek() sets REQ_F_BUFFERS_COMMIT sock_recvmsg() -EAGAIN, the data is gone io_kbuf_recycle() does nothing return IOU_RETRY buffers mapped, but not committed io_recv() sel.buf_list is NULL, no selection sock_recvmsg() partial transfer io_net_kbuf_can_retry() reads bl->flags The fix used here is to clear the flag when the request puts the buffers that the flag was set for. Fixes: 7c71a0af81ba ("io_uring/net: improve recv bundles") Signed-off-by: Chris Mason Signed-off-by: Jens Axboe --- io_uring/kbuf.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/io_uring/kbuf.c b/io_uring/kbuf.c index 873d66a06b3605..78d29008919aae 100644 --- a/io_uring/kbuf.c +++ b/io_uring/kbuf.c @@ -428,6 +428,9 @@ unsigned int __io_put_kbufs(struct io_kiocb *req, struct io_buffer_list *bl, ret = IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT); + /* only covers the buffer(s) being put, not a later selection */ + req->flags &= ~REQ_F_BL_NO_RECYCLE; + if (unlikely(!(req->flags & REQ_F_BUFFER_RING))) { io_kbuf_drop_legacy(req); return ret; From 0e433c705aff3846356f402e8b054d6e4ebbdbe0 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Thu, 12 Nov 2026 08:32:48 +0000 Subject: [PATCH 1818/2102] io_uring: free the ring after a grace period On !PREEMPT_RT, a task that removes its tctx node on exit or exec can race with the exit work of a closed ring and cause a use-after-free of the io_ring_ctx. A mutex has to stay allocated until mutex_unlock() has returned. But io_uring_del_tctx_node() holds no reference on the ring, only its node on ->tctx_list keeps it, and io_ring_exit_work() frees the ring once it has tctx_lock and finds the list empty. If the exit work has queued as a waiter, it can get there while the unlock still needs the mutex: io_uring_del_tctx_node() io_ring_exit_work() ======================== =================== mutex_lock(tctx_lock) list_del() mutex_lock(tctx_lock) lock wait_lock set MUTEX_FLAG_WAITERS mutex_unlock(tctx_lock) clear the owner __mutex_trylock() succeeds unlock wait_lock list_empty() is true mutex_unlock(tctx_lock) io_ring_ctx_free() kfree(ctx) lock wait_lock waiter = lock->first_waiter Each node used to hold a file reference that was dropped after the unlock. Commit eebd2e37e662 ("io_uring: don't take task ring-file notes") removed it, and relies on the exit work to wait for the nodes. The fix used here is to do the unlock inside an RCU read section, and to free the io_ring_ctx only after a grace period. Fixes: eebd2e37e662 ("io_uring: don't take task ring-file notes") Signed-off-by: Chris Mason Signed-off-by: Jens Axboe --- include/linux/io_uring_types.h | 2 ++ io_uring/io_uring.c | 2 +- io_uring/tctx.c | 3 +++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/include/linux/io_uring_types.h b/include/linux/io_uring_types.h index 1468bcb028930b..1b85872bb7ea83 100644 --- a/include/linux/io_uring_types.h +++ b/include/linux/io_uring_types.h @@ -517,6 +517,8 @@ struct io_ring_ctx { /* ctx exit and cancelation */ struct work_struct exit_work; + /* the ctx is freed after a grace period, see io_uring_del_tctx_node() */ + struct rcu_head rcu; struct completion ref_comp; /* io-wq management, e.g. thread count */ diff --git a/io_uring/io_uring.c b/io_uring/io_uring.c index be5a4f9505e09d..06ff9992187112 100644 --- a/io_uring/io_uring.c +++ b/io_uring/io_uring.c @@ -2368,7 +2368,7 @@ static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx) xa_destroy(&ctx->io_bl_xa); xa_destroy(&ctx->hpage_acct); xa_destroy(&ctx->personalities); - kfree(ctx); + kfree_rcu(ctx, rcu); } static __cold void io_activate_pollwq_cb(struct callback_head *cb) diff --git a/io_uring/tctx.c b/io_uring/tctx.c index b4fecea3ea4797..c6b7f5647f7906 100644 --- a/io_uring/tctx.c +++ b/io_uring/tctx.c @@ -231,7 +231,10 @@ __cold void io_uring_del_tctx_node(unsigned long index) mutex_lock(&node->ctx->tctx_lock); list_del(&node->ctx_node); + /* keeps the ctx until the unlock is done, see io_ring_ctx_free() */ + rcu_read_lock(); mutex_unlock(&node->ctx->tctx_lock); + rcu_read_unlock(); if (tctx->last == node->ctx) tctx->last = NULL; From a905ff43362e80590e54f6ea9ddb2d1a998aa01c Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 25 Nov 2026 10:32:32 -0700 Subject: [PATCH 1819/2102] io_uring: free the ring from an RCU work The ring is currently freed in two steps: a synchronize_rcu() in io_ring_exit_work() for DEFER_TASKRUN and SQPOLL rings, which pairs with the RCU read sections in the task_work add paths, and a kfree_rcu() of the ctx itself, which pairs with the one in io_uring_del_tctx_node(). The kfree_rcu() alone can't replace the synchronize_rcu(). The task_work add paths also look at the ring memory (->rings and ->rings_rcu, for the SQ flags) and at ->submitter_task, and io_ring_ctx_free() releases both before it gets to the free of the ctx. Instead of waiting for a grace period in the exit work, queue the whole io_ring_ctx_free() as an RCU work, and make its final free a plain kfree(). That is process context, as io_ring_ctx_free() needs, and everything it tears down now happens after a grace period. This covers the readers in the task_work add paths for all rings, and the unlock in io_uring_del_tctx_node(), and removes both the synchronize_rcu() and the rcu_head in the ctx. Signed-off-by: Jens Axboe --- include/linux/io_uring_types.h | 4 ++-- io_uring/io_uring.c | 23 +++++++++++++++++------ io_uring/tctx.c | 2 +- io_uring/tw.c | 2 +- 4 files changed, 21 insertions(+), 10 deletions(-) diff --git a/include/linux/io_uring_types.h b/include/linux/io_uring_types.h index 1b85872bb7ea83..7a835113eac3f7 100644 --- a/include/linux/io_uring_types.h +++ b/include/linux/io_uring_types.h @@ -517,8 +517,8 @@ struct io_ring_ctx { /* ctx exit and cancelation */ struct work_struct exit_work; - /* the ctx is freed after a grace period, see io_uring_del_tctx_node() */ - struct rcu_head rcu; + /* the ctx is freed after a grace period, see io_ring_exit_work() */ + struct rcu_work free_rwork; struct completion ref_comp; /* io-wq management, e.g. thread count */ diff --git a/io_uring/io_uring.c b/io_uring/io_uring.c index 06ff9992187112..6808229edf07ce 100644 --- a/io_uring/io_uring.c +++ b/io_uring/io_uring.c @@ -2368,7 +2368,15 @@ static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx) xa_destroy(&ctx->io_bl_xa); xa_destroy(&ctx->hpage_acct); xa_destroy(&ctx->personalities); - kfree_rcu(ctx, rcu); + kfree(ctx); +} + +static __cold void io_ring_ctx_free_work(struct work_struct *work) +{ + struct io_ring_ctx *ctx = container_of(to_rcu_work(work), + struct io_ring_ctx, free_rwork); + + io_ring_ctx_free(ctx); } static __cold void io_activate_pollwq_cb(struct callback_head *cb) @@ -2660,11 +2668,14 @@ static __cold void io_ring_exit_work(struct work_struct *work) spin_lock(&ctx->completion_lock); spin_unlock(&ctx->completion_lock); - /* pairs with the RCU read sections in the task_work add paths */ - if (ctx->flags & (IORING_SETUP_DEFER_TASKRUN | IORING_SETUP_SQPOLL)) - synchronize_rcu(); - - io_ring_ctx_free(ctx); + /* + * Free the ring after a grace period. This pairs with the RCU read + * sections in the task_work add paths, which look at the rings and + * the submitter task, and with the one in io_uring_del_tctx_node(), + * which may still be unlocking ->tctx_lock. + */ + INIT_RCU_WORK(&ctx->free_rwork, io_ring_ctx_free_work); + queue_rcu_work(iou_wq, &ctx->free_rwork); } static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx) diff --git a/io_uring/tctx.c b/io_uring/tctx.c index c6b7f5647f7906..508a72fdfc1b59 100644 --- a/io_uring/tctx.c +++ b/io_uring/tctx.c @@ -231,7 +231,7 @@ __cold void io_uring_del_tctx_node(unsigned long index) mutex_lock(&node->ctx->tctx_lock); list_del(&node->ctx_node); - /* keeps the ctx until the unlock is done, see io_ring_ctx_free() */ + /* keeps the ctx until the unlock is done, see io_ring_exit_work() */ rcu_read_lock(); mutex_unlock(&node->ctx->tctx_lock); rcu_read_unlock(); diff --git a/io_uring/tw.c b/io_uring/tw.c index b4a9e28ce7794c..41b3b9422d41fb 100644 --- a/io_uring/tw.c +++ b/io_uring/tw.c @@ -184,7 +184,7 @@ void io_req_local_work_add(struct io_kiocb *req, unsigned flags) struct io_ring_ctx *ctx = req->ctx; int nr_wait; - /* pairs with synchronize_rcu() in io_ring_exit_work() */ + /* pairs with the grace period before the free in io_ring_exit_work() */ guard(rcu)(); /* From 37149fc6e1504c35490cdb5752ba4bc20acd8c98 Mon Sep 17 00:00:00 2001 From: Bard Liao Date: Sun, 22 Nov 2026 17:39:43 +0800 Subject: [PATCH 1820/2102] ASoC: Intel: skl_hda_dsp_generic: add HDMI IN DAI link support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add HDMI_IN to SOF_LINK_ORDER so that the HDMI IN dai links will be createrd if SSP_MASK_HDMI_CAPTURE is set to board_quirk. Signed-off-by: Bard Liao Reviewed-by: Péter Ujfalusi Link: https://patch.msgid.link/20261122093945.2138118-2-yung-chuan.liao@linux.intel.com Signed-off-by: Mark Brown --- sound/soc/intel/boards/skl_hda_dsp_generic.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sound/soc/intel/boards/skl_hda_dsp_generic.c b/sound/soc/intel/boards/skl_hda_dsp_generic.c index 34c8b7fec3aeea..e7f5869ff12ec5 100644 --- a/sound/soc/intel/boards/skl_hda_dsp_generic.c +++ b/sound/soc/intel/boards/skl_hda_dsp_generic.c @@ -53,13 +53,14 @@ static void skl_set_hda_codec_autosuspend_delay(struct snd_soc_card *card) #define DMIC01_BE_ID 6 #define DMIC16K_BE_ID 7 #define BT_OFFLOAD_BE_ID 8 +#define HDMI_IN_BE_ID 13 #define HDA_LINK_ORDER SOF_LINK_ORDER(SOF_LINK_IDISP_HDMI, \ SOF_LINK_HDA, \ SOF_LINK_DMIC01, \ SOF_LINK_DMIC16K, \ SOF_LINK_BT_OFFLOAD, \ - SOF_LINK_NONE, \ + SOF_LINK_HDMI_IN, \ SOF_LINK_NONE) #define HDA_LINK_IDS SOF_LINK_ORDER(IDISP_HDMI_BE_ID, \ @@ -67,7 +68,7 @@ static void skl_set_hda_codec_autosuspend_delay(struct snd_soc_card *card) DMIC01_BE_ID, \ DMIC16K_BE_ID, \ BT_OFFLOAD_BE_ID, \ - 0, \ + HDMI_IN_BE_ID, \ 0) static unsigned long From d6e074890461e8cfdc7deb8dc3c39eb701038840 Mon Sep 17 00:00:00 2001 From: Bard Liao Date: Sun, 22 Nov 2026 17:39:44 +0800 Subject: [PATCH 1821/2102] ASoC: Intel: skl_hda_dsp_generic: Limit HDMI ignore to playback FE MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When iDisp is absent, limit the HDMI ignore check to playback FE links. HDMI-In links use names such as SSP%d-HDMI, and their stream_name may contain HDMI as well. Excluding BE and capture-only links prevents the HDMI-In capture link from being ignored. Signed-off-by: Bard Liao Reviewed-by: Péter Ujfalusi Link: https://patch.msgid.link/20261122093945.2138118-3-yung-chuan.liao@linux.intel.com Signed-off-by: Mark Brown --- sound/soc/intel/boards/skl_hda_dsp_generic.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sound/soc/intel/boards/skl_hda_dsp_generic.c b/sound/soc/intel/boards/skl_hda_dsp_generic.c index e7f5869ff12ec5..3c86bb6546dca6 100644 --- a/sound/soc/intel/boards/skl_hda_dsp_generic.c +++ b/sound/soc/intel/boards/skl_hda_dsp_generic.c @@ -92,7 +92,8 @@ static int skl_hda_add_dai_link(struct snd_soc_card *card, struct sof_card_private *ctx = snd_soc_card_get_drvdata(card); /* Ignore the HDMI PCM link if iDisp is not present */ - if (strstr(link->stream_name, "HDMI") && !ctx->hdmi.idisp_codec) + if (strstr(link->stream_name, "HDMI") && !link->no_pcm && + !link->capture_only && !ctx->hdmi.idisp_codec) link->ignore = true; return 0; From 7f3bfbf471d7335688d47aef3a87ed46233be6d9 Mon Sep 17 00:00:00 2001 From: Bard Liao Date: Sun, 22 Nov 2026 17:39:45 +0800 Subject: [PATCH 1822/2102] ASoC: Intel: sof_sdw: Limit HDMI ignore to playback FE MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When iDisp is absent, limit the HDMI ignore check to playback FE links. HDMI-In links use names such as SSP%d-HDMI, and their stream_name may contain HDMI as well. Excluding BE and capture-only links prevents the HDMI-In capture link from being ignored. Signed-off-by: Bard Liao Reviewed-by: Péter Ujfalusi Link: https://patch.msgid.link/20261122093945.2138118-4-yung-chuan.liao@linux.intel.com Signed-off-by: Mark Brown --- sound/soc/intel/boards/sof_sdw.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sound/soc/intel/boards/sof_sdw.c b/sound/soc/intel/boards/sof_sdw.c index 1e5de71c0f21eb..b3e88dce0c252c 100644 --- a/sound/soc/intel/boards/sof_sdw.c +++ b/sound/soc/intel/boards/sof_sdw.c @@ -1447,7 +1447,8 @@ static int sof_sdw_add_dai_link(struct snd_soc_card *card, struct intel_mc_ctx *intel_ctx = (struct intel_mc_ctx *)ctx->private; /* Ignore the HDMI PCM link if iDisp is not present */ - if (strstr(link->stream_name, "HDMI") && !intel_ctx->hdmi.idisp_codec) + if (strstr(link->stream_name, "HDMI") && !link->no_pcm && + !link->capture_only && !intel_ctx->hdmi.idisp_codec) link->ignore = true; return 0; From d680ba51f7f8732053d3a083ca229f493a703953 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:41:52 +0000 Subject: [PATCH 1823/2102] ASoC: soc-generic-dmaengine-pcm: move devm_snd_dmaengine_pcm_register() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We don't need to have dmaengine related function in soc-devres.c. Let's move it. Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/878q2hg00v.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- sound/soc/soc-devres.c | 40 --------------------------- sound/soc/soc-generic-dmaengine-pcm.c | 36 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 40 deletions(-) diff --git a/sound/soc/soc-devres.c b/sound/soc/soc-devres.c index 718165ba84ac87..ca6c29b54f6abe 100644 --- a/sound/soc/soc-devres.c +++ b/sound/soc/soc-devres.c @@ -63,43 +63,3 @@ int devm_snd_soc_register_card(struct device *dev, struct snd_soc_card *card) return snd_soc_register_card(card); } EXPORT_SYMBOL_GPL(devm_snd_soc_register_card); - -#ifdef CONFIG_SND_SOC_GENERIC_DMAENGINE_PCM - -static void devm_dmaengine_pcm_release(struct device *dev, void *res) -{ - snd_dmaengine_pcm_unregister(*(struct device **)res); -} - -/** - * devm_snd_dmaengine_pcm_register - resource managed dmaengine PCM registration - * @dev: The parent device for the PCM device - * @config: Platform specific PCM configuration - * @flags: Platform specific quirks - * - * Register a dmaengine based PCM device with automatic unregistration when the - * device is unregistered. - */ -int devm_snd_dmaengine_pcm_register(struct device *dev, - const struct snd_dmaengine_pcm_config *config, unsigned int flags) -{ - struct device **ptr; - int ret; - - ptr = devres_alloc(devm_dmaengine_pcm_release, sizeof(*ptr), GFP_KERNEL); - if (!ptr) - return -ENOMEM; - - ret = snd_dmaengine_pcm_register(dev, config, flags); - if (ret == 0) { - *ptr = dev; - devres_add(dev, ptr); - } else { - devres_free(ptr); - } - - return ret; -} -EXPORT_SYMBOL_GPL(devm_snd_dmaengine_pcm_register); - -#endif diff --git a/sound/soc/soc-generic-dmaengine-pcm.c b/sound/soc/soc-generic-dmaengine-pcm.c index c7523bae45af76..1ecf3feb2bed0f 100644 --- a/sound/soc/soc-generic-dmaengine-pcm.c +++ b/sound/soc/soc-generic-dmaengine-pcm.c @@ -520,5 +520,41 @@ void snd_dmaengine_pcm_unregister(struct device *dev) } EXPORT_SYMBOL_GPL(snd_dmaengine_pcm_unregister); +static void devm_dmaengine_pcm_release(struct device *dev, void *res) +{ + snd_dmaengine_pcm_unregister(*(struct device **)res); +} + +/** + * devm_snd_dmaengine_pcm_register - resource managed dmaengine PCM registration + * @dev: The parent device for the PCM device + * @config: Platform specific PCM configuration + * @flags: Platform specific quirks + * + * Register a dmaengine based PCM device with automatic unregistration when the + * device is unregistered. + */ +int devm_snd_dmaengine_pcm_register(struct device *dev, + const struct snd_dmaengine_pcm_config *config, unsigned int flags) +{ + struct device **ptr; + int ret; + + ptr = devres_alloc(devm_dmaengine_pcm_release, sizeof(*ptr), GFP_KERNEL); + if (!ptr) + return -ENOMEM; + + ret = snd_dmaengine_pcm_register(dev, config, flags); + if (ret == 0) { + *ptr = dev; + devres_add(dev, ptr); + } else { + devres_free(ptr); + } + + return ret; +} +EXPORT_SYMBOL_GPL(devm_snd_dmaengine_pcm_register); + MODULE_DESCRIPTION("ASoC helpers for generic PCM dmaengine API"); MODULE_LICENSE("GPL"); From be3f338873c6a94923c890006a9e7b27da29f6c6 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:41:58 +0000 Subject: [PATCH 1824/2102] ASoC: soc-component: rename snd_soc_component_{init/exit}_regmap() to snd_soc_component_regmap_{init/exit}() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. We already have snd_soc_component_regmap_xxx() functions. Let's standardize the function names. - snd_soc_component_{init/exit}_regmap() + snd_soc_component_regmap_{init/exit}() Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/877bi1g00q.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 6 ++++-- sound/soc/soc-component.c | 14 +++++++------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 73d66c97669440..4e30a22a767e2f 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -337,9 +337,9 @@ int snd_soc_component_regmap_val_bytes(struct snd_soc_component *component); int snd_soc_component_regmap_cache_sync(struct snd_soc_component *component); void snd_soc_component_regmap_async_complete(struct snd_soc_component *component); #ifdef CONFIG_REGMAP -void snd_soc_component_init_regmap(struct snd_soc_component *component, +void snd_soc_component_regmap_init(struct snd_soc_component *component, struct regmap *regmap); -void snd_soc_component_exit_regmap(struct snd_soc_component *component); +void snd_soc_component_regmap_exit(struct snd_soc_component *component); #endif int snd_soc_component_fixup_controls(struct snd_soc_component *component); @@ -445,6 +445,8 @@ void snd_soc_pcm_component_delay(struct snd_pcm_substream *substream, snd_pcm_sframes_t *cpu_delay, snd_pcm_sframes_t *codec_delay); /* REMOVE ME */ +#define snd_soc_component_init_regmap snd_soc_component_regmap_init +#define snd_soc_component_exit_regmap snd_soc_component_regmap_exit #define snd_soc_component_cache_sync snd_soc_component_regmap_cache_sync #define snd_soc_component_async_complete snd_soc_component_regmap_async_complete #define snd_soc_lookup_component_nolocked snd_soc_component_lookup_nolock diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index a6e280c798f3dd..1f40caefee8f17 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -435,7 +435,7 @@ EXPORT_SYMBOL_GPL(snd_soc_component_regmap_async_complete); #ifdef CONFIG_REGMAP /** - * snd_soc_component_init_regmap() - Initialize regmap instance for the + * snd_soc_component_regmap_init() - Initialize regmap instance for the * component * @component: The component for which to initialize the regmap instance * @regmap: The regmap instance that should be used by the component @@ -445,30 +445,30 @@ EXPORT_SYMBOL_GPL(snd_soc_component_regmap_async_complete); * yet ready when the component is registered. The function must also be called * before the first IO attempt of the component. */ -void snd_soc_component_init_regmap(struct snd_soc_component *component, +void snd_soc_component_regmap_init(struct snd_soc_component *component, struct regmap *regmap) { component->regmap = regmap; } -EXPORT_SYMBOL_GPL(snd_soc_component_init_regmap); +EXPORT_SYMBOL_GPL(snd_soc_component_regmap_init); /** - * snd_soc_component_exit_regmap() - De-initialize regmap instance for the + * snd_soc_component_regmap_exit() - De-initialize regmap instance for the * component * @component: The component for which to de-initialize the regmap instance * * Calls regmap_exit() on the regmap instance associated to the component and * removes the regmap instance from the component. * - * This function should only be used if snd_soc_component_init_regmap() was used + * This function should only be used if snd_soc_component_regmap_init() was used * to initialize the regmap instance. */ -void snd_soc_component_exit_regmap(struct snd_soc_component *component) +void snd_soc_component_regmap_exit(struct snd_soc_component *component) { regmap_exit(component->regmap); component->regmap = NULL; } -EXPORT_SYMBOL_GPL(snd_soc_component_exit_regmap); +EXPORT_SYMBOL_GPL(snd_soc_component_regmap_exit); #endif From 9c5d61abec9e90fbb45078154965ab529a06a72a Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:42:04 +0000 Subject: [PATCH 1825/2102] ASoC: soc-component: rename snd_soc_component_regmap_val_bytes() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit snd_soc_component_regmap_val_bytes() (A) calls regmap_get_val_bytes() (B) (A) snd_soc_component_regmap_ val_bytes() (B) regmap_get_val_bytes() ^^^^ Let's align the function name to original function. Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/875wxlg00k.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 3 ++- sound/soc/soc-component.c | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 4e30a22a767e2f..fd2db8992b248f 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -333,7 +333,7 @@ int snd_soc_component_stream_event(struct snd_soc_component *component, int snd_soc_component_set_bias_level(struct snd_soc_component *component, enum snd_soc_bias_level level); -int snd_soc_component_regmap_val_bytes(struct snd_soc_component *component); +int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component); int snd_soc_component_regmap_cache_sync(struct snd_soc_component *component); void snd_soc_component_regmap_async_complete(struct snd_soc_component *component); #ifdef CONFIG_REGMAP @@ -448,6 +448,7 @@ void snd_soc_pcm_component_delay(struct snd_pcm_substream *substream, #define snd_soc_component_init_regmap snd_soc_component_regmap_init #define snd_soc_component_exit_regmap snd_soc_component_regmap_exit #define snd_soc_component_cache_sync snd_soc_component_regmap_cache_sync +#define snd_soc_component_regmap_val_bytes snd_soc_component_regmap_get_val_bytes #define snd_soc_component_async_complete snd_soc_component_regmap_async_complete #define snd_soc_lookup_component_nolocked snd_soc_component_lookup_nolock #define snd_soc_lookup_component snd_soc_component_lookup diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 1f40caefee8f17..41fa459d954be5 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -386,7 +386,7 @@ int snd_soc_component_of_xlate_dai_name(struct snd_soc_component *component, return -ENOTSUPP; } -int snd_soc_component_regmap_val_bytes(struct snd_soc_component *component) +int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component) { int val_bytes; @@ -401,7 +401,7 @@ int snd_soc_component_regmap_val_bytes(struct snd_soc_component *component) return val_bytes; } -EXPORT_SYMBOL_GPL(snd_soc_component_regmap_val_bytes); +EXPORT_SYMBOL_GPL(snd_soc_component_regmap_get_val_bytes); /** * snd_soc_component_regmap_cache_sync() - Sync the register cache with the hardware From 55a3e787200a2acc17bda524220d2f7b7cc20e7c Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:42:09 +0000 Subject: [PATCH 1826/2102] ASoC: soc-component: rename snd_soc_component_regmap_cache_sync() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit snd_soc_component_regmap_cache_sync() (A) calls regcache_sync() (B) (A) snd_soc_component_regmap_cache_sync() (B) reg cache_sync() Let's align the function name to original function. There is no snd_soc_component_regmap_cache_sync() user yet (function name change will be happen later when all new functions were ready to use). Don't need to care re-rename the function name in macro. Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/874id5g00e.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 4 ++-- sound/soc/soc-component.c | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index fd2db8992b248f..d4fe3e02347eb5 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -334,8 +334,8 @@ int snd_soc_component_set_bias_level(struct snd_soc_component *component, enum snd_soc_bias_level level); int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component); -int snd_soc_component_regmap_cache_sync(struct snd_soc_component *component); void snd_soc_component_regmap_async_complete(struct snd_soc_component *component); +int snd_soc_component_regcache_sync(struct snd_soc_component *component); #ifdef CONFIG_REGMAP void snd_soc_component_regmap_init(struct snd_soc_component *component, struct regmap *regmap); @@ -447,7 +447,7 @@ void snd_soc_pcm_component_delay(struct snd_pcm_substream *substream, /* REMOVE ME */ #define snd_soc_component_init_regmap snd_soc_component_regmap_init #define snd_soc_component_exit_regmap snd_soc_component_regmap_exit -#define snd_soc_component_cache_sync snd_soc_component_regmap_cache_sync +#define snd_soc_component_cache_sync snd_soc_component_regcache_sync #define snd_soc_component_regmap_val_bytes snd_soc_component_regmap_get_val_bytes #define snd_soc_component_async_complete snd_soc_component_regmap_async_complete #define snd_soc_lookup_component_nolocked snd_soc_component_lookup_nolock diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 41fa459d954be5..2979d2b79ed135 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -404,19 +404,19 @@ int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component) EXPORT_SYMBOL_GPL(snd_soc_component_regmap_get_val_bytes); /** - * snd_soc_component_regmap_cache_sync() - Sync the register cache with the hardware + * snd_soc_component_regcache_sync() - Sync the register cache with the hardware * @component: COMPONENT to sync * * Note: This function will call regcache_sync() */ -int snd_soc_component_regmap_cache_sync(struct snd_soc_component *component) +int snd_soc_component_regcache_sync(struct snd_soc_component *component) { if (!component->regmap) return 0; return regcache_sync(component->regmap); } -EXPORT_SYMBOL_GPL(snd_soc_component_regmap_cache_sync); +EXPORT_SYMBOL_GPL(snd_soc_component_regcache_sync); /** * snd_soc_component_regmap_async_complete() - Ensure asynchronous I/O has completed From a8eb1d812d0ef6669ce954fe0c95729d0111d34b Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:42:14 +0000 Subject: [PATCH 1827/2102] ASoC: soc-component: align snd_soc_component_{regmap/regcache}_xxx() functions Current soc-component.c has snd_soc_component_{regmap/regcache}_xxx(), but are located randumly. Let's align them. No functional changes. Signed-off-by: Kuninori Morimoto Link: https://patch.msgid.link/8733spg009.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 6 +-- sound/soc/soc-component.c | 92 +++++++++++++++++------------------ 2 files changed, 49 insertions(+), 49 deletions(-) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index d4fe3e02347eb5..7476923c60d0dd 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -333,14 +333,14 @@ int snd_soc_component_stream_event(struct snd_soc_component *component, int snd_soc_component_set_bias_level(struct snd_soc_component *component, enum snd_soc_bias_level level); -int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component); -void snd_soc_component_regmap_async_complete(struct snd_soc_component *component); -int snd_soc_component_regcache_sync(struct snd_soc_component *component); #ifdef CONFIG_REGMAP void snd_soc_component_regmap_init(struct snd_soc_component *component, struct regmap *regmap); void snd_soc_component_regmap_exit(struct snd_soc_component *component); #endif +int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component); +void snd_soc_component_regmap_async_complete(struct snd_soc_component *component); +int snd_soc_component_regcache_sync(struct snd_soc_component *component); int snd_soc_component_fixup_controls(struct snd_soc_component *component); int snd_soc_component_add_controls(struct snd_soc_component *component, diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 2979d2b79ed135..7e565da045b602 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -386,52 +386,6 @@ int snd_soc_component_of_xlate_dai_name(struct snd_soc_component *component, return -ENOTSUPP; } -int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component) -{ - int val_bytes; - - /* Errors are legitimate for non-integer byte multiples */ - - if (!component->regmap) - return 0; - - val_bytes = regmap_get_val_bytes(component->regmap); - if (val_bytes < 0) - return 0; - - return val_bytes; -} -EXPORT_SYMBOL_GPL(snd_soc_component_regmap_get_val_bytes); - -/** - * snd_soc_component_regcache_sync() - Sync the register cache with the hardware - * @component: COMPONENT to sync - * - * Note: This function will call regcache_sync() - */ -int snd_soc_component_regcache_sync(struct snd_soc_component *component) -{ - if (!component->regmap) - return 0; - - return regcache_sync(component->regmap); -} -EXPORT_SYMBOL_GPL(snd_soc_component_regcache_sync); - -/** - * snd_soc_component_regmap_async_complete() - Ensure asynchronous I/O has completed - * @component: Component for which to wait - * - * This function blocks until all asynchronous I/O which has previously been - * scheduled using snd_soc_component_update_bits_async() has completed. - */ -void snd_soc_component_regmap_async_complete(struct snd_soc_component *component) -{ - if (component->regmap) - regmap_async_complete(component->regmap); -} -EXPORT_SYMBOL_GPL(snd_soc_component_regmap_async_complete); - #ifdef CONFIG_REGMAP /** @@ -472,6 +426,52 @@ EXPORT_SYMBOL_GPL(snd_soc_component_regmap_exit); #endif +int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component) +{ + int val_bytes; + + /* Errors are legitimate for non-integer byte multiples */ + + if (!component->regmap) + return 0; + + val_bytes = regmap_get_val_bytes(component->regmap); + if (val_bytes < 0) + return 0; + + return val_bytes; +} +EXPORT_SYMBOL_GPL(snd_soc_component_regmap_get_val_bytes); + +/** + * snd_soc_component_regmap_async_complete() - Ensure asynchronous I/O has completed + * @component: Component for which to wait + * + * This function blocks until all asynchronous I/O which has previously been + * scheduled using snd_soc_component_update_bits_async() has completed. + */ +void snd_soc_component_regmap_async_complete(struct snd_soc_component *component) +{ + if (component->regmap) + regmap_async_complete(component->regmap); +} +EXPORT_SYMBOL_GPL(snd_soc_component_regmap_async_complete); + +/** + * snd_soc_component_regcache_sync() - Sync the register cache with the hardware + * @component: COMPONENT to sync + * + * Note: This function will call regcache_sync() + */ +int snd_soc_component_regcache_sync(struct snd_soc_component *component) +{ + if (!component->regmap) + return 0; + + return regcache_sync(component->regmap); +} +EXPORT_SYMBOL_GPL(snd_soc_component_regcache_sync); + int snd_soc_component_compr_open(struct snd_soc_component *component, struct snd_compr_stream *cstream) { From 1ca1caef5b1e4fe1c7925fac9409544d6a6e3fbf Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:42:20 +0000 Subject: [PATCH 1828/2102] ASoC: soc-core: move snd_soc_del_component_unlocked() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit No functional change, just for preparation for cleanup. Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/871p89g003.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- sound/soc/soc-core.c | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/sound/soc/soc-core.c b/sound/soc/soc-core.c index 7dfd79b4ca3e56..15d466b5ac15c7 100644 --- a/sound/soc/soc-core.c +++ b/sound/soc/soc-core.c @@ -1457,18 +1457,6 @@ static void convert_endianness_formats(struct snd_soc_pcm_stream *stream) stream->formats |= endianness_format_map[i]; } -static void snd_soc_del_component_unlocked(struct snd_soc_component *component) -{ - struct snd_soc_card *card = component->card; - - snd_soc_unregister_dais(component); - - if (card) - snd_soc_card_unbind(card, true); - - list_del(&component->list); -} - struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, const struct snd_soc_component_driver *driver) { @@ -1505,6 +1493,18 @@ struct snd_soc_component *snd_soc_component_new(struct device *dev, const char * } EXPORT_SYMBOL_GPL(snd_soc_component_new); +static void snd_soc_del_component_unlocked(struct snd_soc_component *component) +{ + struct snd_soc_card *card = component->card; + + snd_soc_unregister_dais(component); + + if (card) + snd_soc_card_unbind(card, true); + + list_del(&component->list); +} + int snd_soc_component_register(struct snd_soc_component *component, struct snd_soc_dai_driver *dai_drv, int num_dai) From 880393bc2bfdf919a9ea620f41b14f14e48f83e8 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:42:26 +0000 Subject: [PATCH 1829/2102] ASoC: soc-core: add missing snd_soc_component_unregister() Current soc-component has snd_soc_component_register() (A), but not have snd_soc_component_unregister() (B) (A) snd_soc_component_register() (B) snd_soc_component_unregister() We can use snd_soc_del_component_unlocked() for (B). Let's add snd_soc_component_unregister(). Signed-off-by: Kuninori Morimoto Link: https://patch.msgid.link/87zeuxelfi.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 1 + sound/soc/soc-core.c | 14 +++++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 7476923c60d0dd..d6685812cad761 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -275,6 +275,7 @@ struct snd_soc_component { struct snd_soc_dapm_context *snd_soc_component_to_dapm(struct snd_soc_component *component); struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, const struct snd_soc_component_driver *driver); +void snd_soc_component_unregister(struct snd_soc_component *component); int snd_soc_component_register(struct snd_soc_component *component, struct snd_soc_dai_driver *dai_drv, int num_dai); diff --git a/sound/soc/soc-core.c b/sound/soc/soc-core.c index 15d466b5ac15c7..a7313419dc5f93 100644 --- a/sound/soc/soc-core.c +++ b/sound/soc/soc-core.c @@ -1493,7 +1493,7 @@ struct snd_soc_component *snd_soc_component_new(struct device *dev, const char * } EXPORT_SYMBOL_GPL(snd_soc_component_new); -static void snd_soc_del_component_unlocked(struct snd_soc_component *component) +static void snd_soc_component_unregister_unlocked(struct snd_soc_component *component) { struct snd_soc_card *card = component->card; @@ -1505,6 +1505,14 @@ static void snd_soc_del_component_unlocked(struct snd_soc_component *component) list_del(&component->list); } +void snd_soc_component_unregister(struct snd_soc_component *component) +{ + guard(mutex)(&client_mutex); + + snd_soc_component_unregister_unlocked(component); +} +EXPORT_SYMBOL_GPL(snd_soc_component_unregister); + int snd_soc_component_register(struct snd_soc_component *component, struct snd_soc_dai_driver *dai_drv, int num_dai) @@ -1540,7 +1548,7 @@ int snd_soc_component_register(struct snd_soc_component *component, err_cleanup: if (ret < 0) - snd_soc_del_component_unlocked(component); + snd_soc_component_unregister_unlocked(component); return ret; } @@ -1584,7 +1592,7 @@ void snd_soc_unregister_component_by_driver(struct device *dev, if (!component) break; - snd_soc_del_component_unlocked(component); + snd_soc_component_unregister_unlocked(component); } } EXPORT_SYMBOL_GPL(snd_soc_unregister_component_by_driver); From 7c3533508433c1a951faf41fae28de15216fbd3b Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:42:36 +0000 Subject: [PATCH 1830/2102] ASoC: soc-generic-dmaengine-pcm: use snd_soc_component_unregister() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Current snd_dmaengine_pcm_unregister() (X) is using snd_soc_unregister_component_by_driver() (Y) to unregister component. (X) void snd_dmaengine_pcm_unregister(...) { (Z) component = snd_soc_lookup_component(...); ... (p) pcm = snd_soc_component_to_priv(component); (Y) snd_soc_unregister_component_by_driver(...); (p) dmaengine_pcm_release_chan(pcm); (p) kfree(pcm); } But it try to unregister all components from dev (a). (Y) void snd_soc_unregister_component(...) { ... while (1) { (Z) component = snd_soc_lookup_component_nolocked(...); ... (a) snd_soc_component_unregister(component); } } snd_dmaengine_pcm_unregister() (X) need to care/free pcm which is connected to component (= p). Both (X) and (Y) are using lookup_component (Z). So (X) can handle first component/pcm (p), but can't handle 2nd or more component/pcm eventhough (X) was called multiple times, because (Y) unregister all components. Let's call snd_soc_component_unregister() (a) instead of snd_soc_unregister_component_by_driver() (Y) in (X), and unregister target component only, not all. Signed-off-by: Kuninori Morimoto Reported-by: Sashiko Closes: https://lore.kernel.org/r/sashiko-outbox-206296@kernel.org Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87y0ahelf8.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- sound/soc/soc-generic-dmaengine-pcm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/soc-generic-dmaengine-pcm.c b/sound/soc/soc-generic-dmaengine-pcm.c index 1ecf3feb2bed0f..62f86d97668ef4 100644 --- a/sound/soc/soc-generic-dmaengine-pcm.c +++ b/sound/soc/soc-generic-dmaengine-pcm.c @@ -514,7 +514,7 @@ void snd_dmaengine_pcm_unregister(struct device *dev) pcm = snd_soc_component_to_priv(component); - snd_soc_unregister_component_by_driver(dev, component->driver); + snd_soc_component_unregister(component); dmaengine_pcm_release_chan(pcm); kfree(pcm); } From 2408a5eed7ec70866158f96dedce56380fe92aba Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:42:45 +0000 Subject: [PATCH 1831/2102] ASoC: soc-devres: use snd_soc_component_unregister() for devm_snd_soc_register_component() Current devm_snd_soc_register_component() (X) is using snd_soc_unregister_component() (Y) to unregiser component. (X) static void devm_component_release(...) { ... (Y) snd_soc_unregister_component(...); } int devm_snd_soc_register_component(...) { ... ptr = devres_alloc(devm_component_release, ...); ... } But now, (Y) will removes all components if multiple component were connected to dev. We can use snd_soc_component_unregister() (Z) which unregiser only target component, not all. Let's use (Y) snd_soc_unregister_component() // unregister all components (Z) snd_soc_component_unregister() // unregister only target component Signed-off-by: Kuninori Morimoto Link: https://patch.msgid.link/87wlq1eley.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- sound/soc/soc-devres.c | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/sound/soc/soc-devres.c b/sound/soc/soc-devres.c index ca6c29b54f6abe..0323897c664dcb 100644 --- a/sound/soc/soc-devres.c +++ b/sound/soc/soc-devres.c @@ -11,9 +11,9 @@ static void devm_component_release(struct device *dev, void *res) { - const struct snd_soc_component_driver **cmpnt_drv = res; + struct snd_soc_component **component = res; - snd_soc_unregister_component_by_driver(dev, *cmpnt_drv); + snd_soc_component_unregister(*component); } /** @@ -30,21 +30,32 @@ int devm_snd_soc_register_component(struct device *dev, const struct snd_soc_component_driver *cmpnt_drv, struct snd_soc_dai_driver *dai_drv, int num_dai) { - const struct snd_soc_component_driver **ptr; - int ret; + const struct snd_soc_component **ptr; + struct snd_soc_component *component; + int ret = -ENOMEM; + + component = snd_soc_component_new(dev, NULL, cmpnt_drv); + if (IS_ERR(component)) + goto err; ptr = devres_alloc(devm_component_release, sizeof(*ptr), GFP_KERNEL); if (!ptr) - return -ENOMEM; + goto free_component; + + ret = snd_soc_component_register(component, dai_drv, num_dai); + if (ret < 0) + goto free_devres; - ret = snd_soc_register_component(dev, cmpnt_drv, dai_drv, num_dai); - if (ret == 0) { - *ptr = cmpnt_drv; - devres_add(dev, ptr); - } else { - devres_free(ptr); - } + *ptr = component; + devres_add(dev, ptr); + + return ret; +free_devres: + devres_free(ptr); +free_component: + devm_kfree(dev, component); +err: return ret; } EXPORT_SYMBOL_GPL(devm_snd_soc_register_component); From bd3b466bd188c8d1c61f746da8b7217cf747fb58 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:43:07 +0000 Subject: [PATCH 1832/2102] ASoC: soc-core: remove snd_soc_unregister_component_by_driver() No one is using snd_soc_unregister_component_by_driver(). Let's remove it. Signed-off-by: Kuninori Morimoto Link: https://patch.msgid.link/87v75lelec.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc.h | 4 +--- sound/soc/soc-core.c | 15 ++++----------- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/include/sound/soc.h b/include/sound/soc.h index 338662645b42fa..0f8e46c131c91b 100644 --- a/include/sound/soc.h +++ b/include/sound/soc.h @@ -454,9 +454,7 @@ int snd_soc_register_component(struct device *dev, int devm_snd_soc_register_component(struct device *dev, const struct snd_soc_component_driver *component_driver, struct snd_soc_dai_driver *dai_drv, int num_dai); -#define snd_soc_unregister_component(dev) snd_soc_unregister_component_by_driver(dev, NULL) -void snd_soc_unregister_component_by_driver(struct device *dev, - const struct snd_soc_component_driver *component_driver); +void snd_soc_unregister_component(struct device *dev); int soc_new_pcm(struct snd_soc_pcm_runtime *rtd); #ifdef CONFIG_SND_SOC_COMPRESS diff --git a/sound/soc/soc-core.c b/sound/soc/soc-core.c index a7313419dc5f93..406ab3620ac1d1 100644 --- a/sound/soc/soc-core.c +++ b/sound/soc/soc-core.c @@ -1570,24 +1570,17 @@ int snd_soc_register_component(struct device *dev, EXPORT_SYMBOL_GPL(snd_soc_register_component); /** - * snd_soc_unregister_component_by_driver - Unregister component using a given driver + * snd_soc_unregister_component - Unregister component using a given driver * from the ASoC core * * @dev: The device to unregister - * @component_driver: The component driver to unregister */ -void snd_soc_unregister_component_by_driver(struct device *dev, - const struct snd_soc_component_driver *component_driver) +void snd_soc_unregister_component(struct device *dev) { - const char *driver_name = NULL; - - if (component_driver) - driver_name = component_driver->name; - guard(mutex)(&client_mutex); while (1) { - struct snd_soc_component *component = snd_soc_lookup_component_nolocked(dev, driver_name); + struct snd_soc_component *component = snd_soc_lookup_component_nolocked(dev, NULL); if (!component) break; @@ -1595,7 +1588,7 @@ void snd_soc_unregister_component_by_driver(struct device *dev, snd_soc_component_unregister_unlocked(component); } } -EXPORT_SYMBOL_GPL(snd_soc_unregister_component_by_driver); +EXPORT_SYMBOL_GPL(snd_soc_unregister_component); /* Retrieve a card's name from device tree */ int snd_soc_of_parse_card_name(struct snd_soc_card *card, From 5459e6d238e535535bdda305648d7674666aca50 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:43:12 +0000 Subject: [PATCH 1833/2102] ASoC: soc-component: move snd_soc_register_[un]component() to soc-component.c MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. move snd_soc_register_[un]component() to soc-component.c Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87tsl5ele8.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 8 ++ include/sound/soc.h | 9 -- sound/soc/soc-component.c | 213 ++++++++++++++++++++++++++++++++++ sound/soc/soc-core.c | 213 ---------------------------------- 4 files changed, 221 insertions(+), 222 deletions(-) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index d6685812cad761..965c2555010c7d 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -279,6 +279,14 @@ void snd_soc_component_unregister(struct snd_soc_component *component); int snd_soc_component_register(struct snd_soc_component *component, struct snd_soc_dai_driver *dai_drv, int num_dai); +int snd_soc_register_component(struct device *dev, + const struct snd_soc_component_driver *component_driver, + struct snd_soc_dai_driver *dai_drv, int num_dai); + +int devm_snd_soc_register_component(struct device *dev, + const struct snd_soc_component_driver *component_driver, + struct snd_soc_dai_driver *dai_drv, int num_dai); +void snd_soc_unregister_component(struct device *dev); const char *snd_soc_component_name(struct snd_soc_component *component); diff --git a/include/sound/soc.h b/include/sound/soc.h index 0f8e46c131c91b..338ba5cf85fb30 100644 --- a/include/sound/soc.h +++ b/include/sound/soc.h @@ -447,15 +447,6 @@ static inline int snd_soc_resume(struct device *dev) } #endif int snd_soc_poweroff(struct device *dev); -int snd_soc_register_component(struct device *dev, - const struct snd_soc_component_driver *component_driver, - struct snd_soc_dai_driver *dai_drv, int num_dai); - -int devm_snd_soc_register_component(struct device *dev, - const struct snd_soc_component_driver *component_driver, - struct snd_soc_dai_driver *dai_drv, int num_dai); -void snd_soc_unregister_component(struct device *dev); - int soc_new_pcm(struct snd_soc_pcm_runtime *rtd); #ifdef CONFIG_SND_SOC_COMPRESS int snd_soc_new_compress(struct snd_soc_pcm_runtime *rtd); diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 7e565da045b602..ca51f976ec4092 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -1553,3 +1553,216 @@ struct snd_soc_component *snd_soc_component_lookup_by_name(const char *component return NULL; } EXPORT_SYMBOL_GPL(snd_soc_component_lookup_by_name); + +/** + * snd_soc_unregister_dais - Unregister DAIs from the ASoC core + * + * @component: The component for which the DAIs should be unregistered + */ +static void snd_soc_unregister_dais(struct snd_soc_component *component) +{ + struct snd_soc_dai *dai, *_dai; + + for_each_component_dais_safe(component, dai, _dai) + snd_soc_unregister_dai(dai); +} + +/** + * snd_soc_register_dais - Register a DAI with the ASoC core + * + * @component: The component the DAIs are registered for + * @dai_drv: DAI driver to use for the DAIs + * @count: Number of DAIs + */ +static int snd_soc_register_dais(struct snd_soc_component *component, + struct snd_soc_dai_driver *dai_drv, + size_t count) +{ + struct snd_soc_dai *dai; + unsigned int i; + int ret; + + for (i = 0; i < count; i++) { + dai = snd_soc_register_dai(component, dai_drv + i, count == 1 && + component->driver->legacy_dai_naming); + if (dai == NULL) { + ret = -ENOMEM; + goto err; + } + } + + return 0; + +err: + snd_soc_unregister_dais(component); + + return ret; +} + +#define ENDIANNESS_MAP(name) \ + (SNDRV_PCM_FMTBIT_##name##LE | SNDRV_PCM_FMTBIT_##name##BE) +static u64 endianness_format_map[] = { + ENDIANNESS_MAP(S16_), + ENDIANNESS_MAP(U16_), + ENDIANNESS_MAP(S24_), + ENDIANNESS_MAP(U24_), + ENDIANNESS_MAP(S32_), + ENDIANNESS_MAP(U32_), + ENDIANNESS_MAP(S24_3), + ENDIANNESS_MAP(U24_3), + ENDIANNESS_MAP(S20_3), + ENDIANNESS_MAP(U20_3), + ENDIANNESS_MAP(S18_3), + ENDIANNESS_MAP(U18_3), + ENDIANNESS_MAP(FLOAT_), + ENDIANNESS_MAP(FLOAT64_), + ENDIANNESS_MAP(IEC958_SUBFRAME_), +}; + +/* + * Fix up the DAI formats for endianness: codecs don't actually see + * the endianness of the data but we're using the CPU format + * definitions which do need to include endianness so we ensure that + * codec DAIs always have both big and little endian variants set. + */ +static void convert_endianness_formats(struct snd_soc_pcm_stream *stream) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(endianness_format_map); i++) + if (stream->formats & endianness_format_map[i]) + stream->formats |= endianness_format_map[i]; +} + +struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, + const struct snd_soc_component_driver *driver) +{ + struct snd_soc_component *component; + + component = devm_kzalloc_obj(dev, *component); + if (!component) + return ERR_PTR(-ENOMEM); + + component->dapm = snd_soc_dapm_alloc(dev); + if (!component->dapm) + return ERR_PTR(-ENOMEM); + + if (!name) { + name = snd_soc_fmt_single_name(dev, NULL); + if (!name) { + dev_err(dev, "ASoC: Failed to allocate name\n"); + return ERR_PTR(-ENOMEM); + } + } + + component->dev = dev; + component->name = name; + component->driver = driver; + + INIT_LIST_HEAD(&component->dai_list); + INIT_LIST_HEAD(&component->dobj_list); + INIT_LIST_HEAD(&component->card_list); + INIT_LIST_HEAD(&component->list); + INIT_LIST_HEAD(&component->card_aux_list); + mutex_init(&component->io_mutex); + + return component; +} +EXPORT_SYMBOL_GPL(snd_soc_component_new); + +static void snd_soc_component_unregister_unlocked(struct snd_soc_component *component) +{ + struct snd_soc_card *card = component->card; + + snd_soc_unregister_dais(component); + + if (card) + snd_soc_card_unbind(card, true); + + list_del(&component->list); +} + +void snd_soc_component_unregister(struct snd_soc_component *component) +{ + guard(mutex)(&client_mutex); + + snd_soc_component_unregister_unlocked(component); +} +EXPORT_SYMBOL_GPL(snd_soc_component_unregister); + +int snd_soc_component_register(struct snd_soc_component *component, + struct snd_soc_dai_driver *dai_drv, + int num_dai) +{ + int ret; + int i; + guard(mutex)(&client_mutex); + + if (component->driver->endianness) { + for (i = 0; i < num_dai; i++) { + convert_endianness_formats(&dai_drv[i].playback); + convert_endianness_formats(&dai_drv[i].capture); + } + } + + ret = snd_soc_register_dais(component, dai_drv, num_dai); + if (ret < 0) { + dev_err(component->dev, "ASoC: Failed to register DAIs: %d\n", + ret); + goto err_cleanup; + } + + if (!component->driver->write && !component->driver->read) { + if (!component->regmap) + component->regmap = dev_get_regmap(component->dev, + NULL); + } + + /* see for_each_component */ + list_add(&component->list, snd_soc_component_get_list_head()); + + snd_soc_card_rebind(); + +err_cleanup: + if (ret < 0) + snd_soc_component_unregister_unlocked(component); + + return ret; +} +EXPORT_SYMBOL_GPL(snd_soc_component_register); + +int snd_soc_register_component(struct device *dev, + const struct snd_soc_component_driver *component_driver, + struct snd_soc_dai_driver *dai_drv, + int num_dai) +{ + struct snd_soc_component *component; + + component = snd_soc_component_new(dev, NULL, component_driver); + if (IS_ERR(component)) + return PTR_ERR(component); + + return snd_soc_component_register(component, dai_drv, num_dai); +} +EXPORT_SYMBOL_GPL(snd_soc_register_component); + +/** + * snd_soc_unregister_component - Unregister component using a given driver + * from the ASoC core + * + * @dev: The device to unregister + */ +void snd_soc_unregister_component(struct device *dev) +{ + guard(mutex)(&client_mutex); + + while (1) { + struct snd_soc_component *component = snd_soc_lookup_component_nolocked(dev, NULL); + + if (!component) + break; + + snd_soc_component_unregister_unlocked(component); + } +} +EXPORT_SYMBOL_GPL(snd_soc_unregister_component); diff --git a/sound/soc/soc-core.c b/sound/soc/soc-core.c index 406ab3620ac1d1..3663227adda683 100644 --- a/sound/soc/soc-core.c +++ b/sound/soc/soc-core.c @@ -1377,219 +1377,6 @@ char *snd_soc_fmt_multiple_name(struct device *dev, struct snd_soc_dai_driver *d return devm_kstrdup(dev, dai_drv->name, GFP_KERNEL); } -/** - * snd_soc_unregister_dais - Unregister DAIs from the ASoC core - * - * @component: The component for which the DAIs should be unregistered - */ -static void snd_soc_unregister_dais(struct snd_soc_component *component) -{ - struct snd_soc_dai *dai, *_dai; - - for_each_component_dais_safe(component, dai, _dai) - snd_soc_unregister_dai(dai); -} - -/** - * snd_soc_register_dais - Register a DAI with the ASoC core - * - * @component: The component the DAIs are registered for - * @dai_drv: DAI driver to use for the DAIs - * @count: Number of DAIs - */ -static int snd_soc_register_dais(struct snd_soc_component *component, - struct snd_soc_dai_driver *dai_drv, - size_t count) -{ - struct snd_soc_dai *dai; - unsigned int i; - int ret; - - for (i = 0; i < count; i++) { - dai = snd_soc_register_dai(component, dai_drv + i, count == 1 && - component->driver->legacy_dai_naming); - if (dai == NULL) { - ret = -ENOMEM; - goto err; - } - } - - return 0; - -err: - snd_soc_unregister_dais(component); - - return ret; -} - -#define ENDIANNESS_MAP(name) \ - (SNDRV_PCM_FMTBIT_##name##LE | SNDRV_PCM_FMTBIT_##name##BE) -static u64 endianness_format_map[] = { - ENDIANNESS_MAP(S16_), - ENDIANNESS_MAP(U16_), - ENDIANNESS_MAP(S24_), - ENDIANNESS_MAP(U24_), - ENDIANNESS_MAP(S32_), - ENDIANNESS_MAP(U32_), - ENDIANNESS_MAP(S24_3), - ENDIANNESS_MAP(U24_3), - ENDIANNESS_MAP(S20_3), - ENDIANNESS_MAP(U20_3), - ENDIANNESS_MAP(S18_3), - ENDIANNESS_MAP(U18_3), - ENDIANNESS_MAP(FLOAT_), - ENDIANNESS_MAP(FLOAT64_), - ENDIANNESS_MAP(IEC958_SUBFRAME_), -}; - -/* - * Fix up the DAI formats for endianness: codecs don't actually see - * the endianness of the data but we're using the CPU format - * definitions which do need to include endianness so we ensure that - * codec DAIs always have both big and little endian variants set. - */ -static void convert_endianness_formats(struct snd_soc_pcm_stream *stream) -{ - int i; - - for (i = 0; i < ARRAY_SIZE(endianness_format_map); i++) - if (stream->formats & endianness_format_map[i]) - stream->formats |= endianness_format_map[i]; -} - -struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, - const struct snd_soc_component_driver *driver) -{ - struct snd_soc_component *component; - - component = devm_kzalloc_obj(dev, *component); - if (!component) - return ERR_PTR(-ENOMEM); - - component->dapm = snd_soc_dapm_alloc(dev); - if (!component->dapm) - return ERR_PTR(-ENOMEM); - - if (!name) { - name = snd_soc_fmt_single_name(dev, NULL); - if (!name) { - dev_err(dev, "ASoC: Failed to allocate name\n"); - return ERR_PTR(-ENOMEM); - } - } - - component->dev = dev; - component->name = name; - component->driver = driver; - - INIT_LIST_HEAD(&component->dai_list); - INIT_LIST_HEAD(&component->dobj_list); - INIT_LIST_HEAD(&component->card_list); - INIT_LIST_HEAD(&component->list); - INIT_LIST_HEAD(&component->card_aux_list); - mutex_init(&component->io_mutex); - - return component; -} -EXPORT_SYMBOL_GPL(snd_soc_component_new); - -static void snd_soc_component_unregister_unlocked(struct snd_soc_component *component) -{ - struct snd_soc_card *card = component->card; - - snd_soc_unregister_dais(component); - - if (card) - snd_soc_card_unbind(card, true); - - list_del(&component->list); -} - -void snd_soc_component_unregister(struct snd_soc_component *component) -{ - guard(mutex)(&client_mutex); - - snd_soc_component_unregister_unlocked(component); -} -EXPORT_SYMBOL_GPL(snd_soc_component_unregister); - -int snd_soc_component_register(struct snd_soc_component *component, - struct snd_soc_dai_driver *dai_drv, - int num_dai) -{ - int ret; - int i; - guard(mutex)(&client_mutex); - - if (component->driver->endianness) { - for (i = 0; i < num_dai; i++) { - convert_endianness_formats(&dai_drv[i].playback); - convert_endianness_formats(&dai_drv[i].capture); - } - } - - ret = snd_soc_register_dais(component, dai_drv, num_dai); - if (ret < 0) { - dev_err(component->dev, "ASoC: Failed to register DAIs: %d\n", - ret); - goto err_cleanup; - } - - if (!component->driver->write && !component->driver->read) { - if (!component->regmap) - component->regmap = dev_get_regmap(component->dev, - NULL); - } - - /* see for_each_component */ - list_add(&component->list, snd_soc_component_get_list_head()); - - snd_soc_card_rebind(); - -err_cleanup: - if (ret < 0) - snd_soc_component_unregister_unlocked(component); - - return ret; -} -EXPORT_SYMBOL_GPL(snd_soc_component_register); - -int snd_soc_register_component(struct device *dev, - const struct snd_soc_component_driver *component_driver, - struct snd_soc_dai_driver *dai_drv, - int num_dai) -{ - struct snd_soc_component *component; - - component = snd_soc_component_new(dev, NULL, component_driver); - if (IS_ERR(component)) - return PTR_ERR(component); - - return snd_soc_component_register(component, dai_drv, num_dai); -} -EXPORT_SYMBOL_GPL(snd_soc_register_component); - -/** - * snd_soc_unregister_component - Unregister component using a given driver - * from the ASoC core - * - * @dev: The device to unregister - */ -void snd_soc_unregister_component(struct device *dev) -{ - guard(mutex)(&client_mutex); - - while (1) { - struct snd_soc_component *component = snd_soc_lookup_component_nolocked(dev, NULL); - - if (!component) - break; - - snd_soc_component_unregister_unlocked(component); - } -} -EXPORT_SYMBOL_GPL(snd_soc_unregister_component); - /* Retrieve a card's name from device tree */ int snd_soc_of_parse_card_name(struct snd_soc_card *card, const char *propname) From 8a21879a0a3f9bdbe444096de412f166cae6e13c Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:43:16 +0000 Subject: [PATCH 1834/2102] ASoC: soc-component: move devm_snd_soc_component_register() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We don't need to have component related function in soc-devres.c. Let's move it. Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87se0pele4.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- sound/soc/soc-component.c | 51 +++++++++++++++++++++++++++++++++++++++ sound/soc/soc-devres.c | 51 --------------------------------------- 2 files changed, 51 insertions(+), 51 deletions(-) diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index ca51f976ec4092..ea8ed0a662dc60 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -1766,3 +1766,54 @@ void snd_soc_unregister_component(struct device *dev) } } EXPORT_SYMBOL_GPL(snd_soc_unregister_component); + +static void devm_component_release(struct device *dev, void *res) +{ + struct snd_soc_component **component = res; + + snd_soc_component_unregister(*component); +} + +/** + * devm_snd_soc_register_component - resource managed component registration + * @dev: Device used to manage component + * @cmpnt_drv: Component driver + * @dai_drv: DAI driver + * @num_dai: Number of DAIs to register + * + * Register a component with automatic unregistration when the device is + * unregistered. + */ +int devm_snd_soc_register_component(struct device *dev, + const struct snd_soc_component_driver *cmpnt_drv, + struct snd_soc_dai_driver *dai_drv, int num_dai) +{ + const struct snd_soc_component **ptr; + struct snd_soc_component *component; + int ret = -ENOMEM; + + component = snd_soc_component_new(dev, NULL, cmpnt_drv); + if (IS_ERR(component)) + goto err; + + ptr = devres_alloc(devm_component_release, sizeof(*ptr), GFP_KERNEL); + if (!ptr) + goto free_component; + + ret = snd_soc_component_register(component, dai_drv, num_dai); + if (ret < 0) + goto free_devres; + + *ptr = component; + devres_add(dev, ptr); + + return ret; + +free_devres: + devres_free(ptr); +free_component: + devm_kfree(dev, component); +err: + return ret; +} +EXPORT_SYMBOL_GPL(devm_snd_soc_register_component); diff --git a/sound/soc/soc-devres.c b/sound/soc/soc-devres.c index 0323897c664dcb..431bb366468ac9 100644 --- a/sound/soc/soc-devres.c +++ b/sound/soc/soc-devres.c @@ -9,57 +9,6 @@ #include #include -static void devm_component_release(struct device *dev, void *res) -{ - struct snd_soc_component **component = res; - - snd_soc_component_unregister(*component); -} - -/** - * devm_snd_soc_register_component - resource managed component registration - * @dev: Device used to manage component - * @cmpnt_drv: Component driver - * @dai_drv: DAI driver - * @num_dai: Number of DAIs to register - * - * Register a component with automatic unregistration when the device is - * unregistered. - */ -int devm_snd_soc_register_component(struct device *dev, - const struct snd_soc_component_driver *cmpnt_drv, - struct snd_soc_dai_driver *dai_drv, int num_dai) -{ - const struct snd_soc_component **ptr; - struct snd_soc_component *component; - int ret = -ENOMEM; - - component = snd_soc_component_new(dev, NULL, cmpnt_drv); - if (IS_ERR(component)) - goto err; - - ptr = devres_alloc(devm_component_release, sizeof(*ptr), GFP_KERNEL); - if (!ptr) - goto free_component; - - ret = snd_soc_component_register(component, dai_drv, num_dai); - if (ret < 0) - goto free_devres; - - *ptr = component; - devres_add(dev, ptr); - - return ret; - -free_devres: - devres_free(ptr); -free_component: - devm_kfree(dev, component); -err: - return ret; -} -EXPORT_SYMBOL_GPL(devm_snd_soc_register_component); - /** * devm_snd_soc_register_card - resource managed card registration * @dev: Device used to manage card From e19d8ca4bc8f8093ad195e1e9d15eb2edc264a6a Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:43:20 +0000 Subject: [PATCH 1835/2102] ASoC: soc-component: move snd_soc_of_xlate_dai_name() to soc-component.c MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. move snd_soc_of_xlate_dai_name() to soc-component.c This renames function name - snd_soc_of_xlate_dai_name() + snd_soc_component_of_simple_xlate_dai_name(). Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87qzg9ele0.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 4 ++++ include/sound/soc.h | 3 --- sound/soc/soc-component.c | 33 +++++++++++++++++++++++++++++++++ sound/soc/soc-core.c | 33 --------------------------------- 4 files changed, 37 insertions(+), 36 deletions(-) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 965c2555010c7d..caed32327daca4 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -401,6 +401,9 @@ int snd_soc_component_of_xlate_dai_id(struct snd_soc_component *component, int snd_soc_component_of_xlate_dai_name(struct snd_soc_component *component, const struct of_phandle_args *args, const char **dai_name); +int snd_soc_component_of_simple_xlate_dai_name(struct snd_soc_component *component, + const struct of_phandle_args *args, + const char **dai_name); int snd_soc_component_compr_open(struct snd_soc_component *component, struct snd_compr_stream *cstream); void snd_soc_component_compr_free(struct snd_soc_component *component, @@ -462,5 +465,6 @@ void snd_soc_pcm_component_delay(struct snd_pcm_substream *substream, #define snd_soc_lookup_component_nolocked snd_soc_component_lookup_nolock #define snd_soc_lookup_component snd_soc_component_lookup #define snd_soc_lookup_component_by_name snd_soc_component_lookup_by_name +#define snd_soc_of_xlate_dai_name snd_soc_component_of_simple_xlate_dai_name #endif /* __SOC_COMPONENT_H */ diff --git a/include/sound/soc.h b/include/sound/soc.h index 338ba5cf85fb30..5abebfa329b522 100644 --- a/include/sound/soc.h +++ b/include/sound/soc.h @@ -1303,9 +1303,6 @@ int snd_soc_of_parse_tdm_slot(struct device_node *np, unsigned int *rx_mask, unsigned int *slots, unsigned int *slot_width); -int snd_soc_of_xlate_dai_name(struct snd_soc_component *component, - const struct of_phandle_args *args, - const char **dai_name); void snd_soc_of_parse_node_prefix(struct device_node *np, struct snd_soc_codec_conf *codec_conf, struct device_node *of_node, diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index ea8ed0a662dc60..c1f90a47e182bb 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -1817,3 +1817,36 @@ int devm_snd_soc_register_component(struct device *dev, return ret; } EXPORT_SYMBOL_GPL(devm_snd_soc_register_component); + +/** + * snd_soc_component_of_simple_xlate_dai_name - Resolve a sound-dai phandle argument to a + * DAI name by searching the component DAI list. + * @component: ASoC component to search. + * @args: Phandle arguments from the sound-dai property; args[0] is the + * DAI ID. + * @dai_name: Output pointer set to the matched DAI name on success. + * + * Return: 0 on success, -EINVAL if args_count != 1 or no match is found. + */ +int snd_soc_component_of_simple_xlate_dai_name(struct snd_soc_component *component, + const struct of_phandle_args *args, + const char **dai_name) +{ + struct snd_soc_dai *dai; + int id; + + if (args->args_count != 1) + return -EINVAL; + + id = args->args[0]; + + for_each_component_dais(component, dai) { + if (dai->driver->id == id) { + *dai_name = snd_soc_dai_name(dai); + return 0; + } + } + + return -EINVAL; +} +EXPORT_SYMBOL_GPL(snd_soc_component_of_simple_xlate_dai_name); diff --git a/sound/soc/soc-core.c b/sound/soc/soc-core.c index 3663227adda683..894a81b2d98365 100644 --- a/sound/soc/soc-core.c +++ b/sound/soc/soc-core.c @@ -1591,39 +1591,6 @@ int snd_soc_of_parse_tdm_slot(struct device_node *np, } EXPORT_SYMBOL_GPL(snd_soc_of_parse_tdm_slot); -/** - * snd_soc_of_xlate_dai_name - Resolve a sound-dai phandle argument to a - * DAI name by searching the component DAI list. - * @component: ASoC component to search. - * @args: Phandle arguments from the sound-dai property; args[0] is the - * DAI ID. - * @dai_name: Output pointer set to the matched DAI name on success. - * - * Return: 0 on success, -EINVAL if args_count != 1 or no match is found. - */ -int snd_soc_of_xlate_dai_name(struct snd_soc_component *component, - const struct of_phandle_args *args, - const char **dai_name) -{ - struct snd_soc_dai *dai; - int id; - - if (args->args_count != 1) - return -EINVAL; - - id = args->args[0]; - - for_each_component_dais(component, dai) { - if (dai->driver->id == id) { - *dai_name = snd_soc_dai_name(dai); - return 0; - } - } - - return -EINVAL; -} -EXPORT_SYMBOL_GPL(snd_soc_of_xlate_dai_name); - void snd_soc_dlc_use_cpu_as_platform(struct snd_soc_dai_link_component *platforms, struct snd_soc_dai_link_component *cpus) { From 31518c1a6e8f4f814de9b00d5a95a712c854e032 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:43:23 +0000 Subject: [PATCH 1836/2102] ASoC: soc-component: add snd_soc_component_name_prefix() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. Add snd_soc_component_name_prefix() to soc-component.c Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87pkvteldw.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 1 + sound/soc/soc-component.c | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index caed32327daca4..e78e0c9cc9d0d3 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -289,6 +289,7 @@ int devm_snd_soc_register_component(struct device *dev, void snd_soc_unregister_component(struct device *dev); const char *snd_soc_component_name(struct snd_soc_component *component); +const char *snd_soc_component_name_prefix(struct snd_soc_component *component); void snd_soc_component_set_priv(struct snd_soc_component *component, void *priv); void *snd_soc_component_to_priv(struct snd_soc_component *component); diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index c1f90a47e182bb..e6c0a66c7314ec 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -43,6 +43,12 @@ const char *snd_soc_component_name(struct snd_soc_component *component) } EXPORT_SYMBOL_GPL(snd_soc_component_name); +const char *snd_soc_component_name_prefix(struct snd_soc_component *component) +{ + return component->name_prefix; +} +EXPORT_SYMBOL_GPL(snd_soc_component_name_prefix); + void snd_soc_component_set_priv(struct snd_soc_component *component, void *priv) { component->priv = priv; From dbb15d439bba072d12c02a111a35987aca8984c8 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:43:29 +0000 Subject: [PATCH 1837/2102] ASoC: soc-component: add snd_soc_component_to_dev() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. Add snd_soc_component_to_dev() to soc-component.c Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87o6bdeldr.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 1 + sound/soc/soc-component.c | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index e78e0c9cc9d0d3..8a03730a2e54ae 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -272,6 +272,7 @@ struct snd_soc_component { snd_soc_dai_to_list(dai) != &(component)->dai_list; \ dai = _dai, _dai = snd_soc_dai_from_list(snd_soc_dai_to_list(_dai)->next)) +struct device *snd_soc_component_to_dev(struct snd_soc_component *component); struct snd_soc_dapm_context *snd_soc_component_to_dapm(struct snd_soc_component *component); struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, const struct snd_soc_component_driver *driver); diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index e6c0a66c7314ec..cb0a75901ea5b4 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -61,6 +61,12 @@ void *snd_soc_component_to_priv(struct snd_soc_component *component) } EXPORT_SYMBOL_GPL(snd_soc_component_to_priv); +struct device *snd_soc_component_to_dev(struct snd_soc_component *component) +{ + return component->dev; +} +EXPORT_SYMBOL_GPL(snd_soc_component_to_dev); + struct snd_soc_dapm_context *snd_soc_component_to_dapm(struct snd_soc_component *component) { return component->dapm; From 8c8dd756b3b4e74652b155b0f190c66fd95700df Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:43:41 +0000 Subject: [PATCH 1838/2102] ASoC: soc-component: add snd_soc_component_to_driver() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. Add snd_soc_component_to_driver() to soc-component.c Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87mrqxelde.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 2 ++ sound/soc/soc-component.c | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 8a03730a2e54ae..d0b82374f2801a 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -274,6 +274,8 @@ struct snd_soc_component { struct device *snd_soc_component_to_dev(struct snd_soc_component *component); struct snd_soc_dapm_context *snd_soc_component_to_dapm(struct snd_soc_component *component); +const struct snd_soc_component_driver +*snd_soc_component_to_driver(struct snd_soc_component *component); struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, const struct snd_soc_component_driver *driver); void snd_soc_component_unregister(struct snd_soc_component *component); diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index cb0a75901ea5b4..3bf1b8691bdc72 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -73,6 +73,13 @@ struct snd_soc_dapm_context *snd_soc_component_to_dapm(struct snd_soc_component } EXPORT_SYMBOL_GPL(snd_soc_component_to_dapm); +const struct snd_soc_component_driver * +snd_soc_component_to_driver(struct snd_soc_component *component) +{ + return component->driver; +} +EXPORT_SYMBOL_GPL(snd_soc_component_to_driver); + unsigned int snd_soc_component_active(struct snd_soc_component *component) { return component->active; From 5a6f9f229329262a6fa30ffdb0f6dc15c4db3d57 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:43:45 +0000 Subject: [PATCH 1839/2102] ASoC: soc-component: add snd_soc_component_to_card() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. Add snd_soc_component_to_card() to soc-component.c Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87ld6heldb.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 1 + sound/soc/soc-component.c | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index d0b82374f2801a..ec0e3d7264cc31 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -276,6 +276,7 @@ struct device *snd_soc_component_to_dev(struct snd_soc_component *component); struct snd_soc_dapm_context *snd_soc_component_to_dapm(struct snd_soc_component *component); const struct snd_soc_component_driver *snd_soc_component_to_driver(struct snd_soc_component *component); +struct snd_soc_card *snd_soc_component_to_card(struct snd_soc_component *component); struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, const struct snd_soc_component_driver *driver); void snd_soc_component_unregister(struct snd_soc_component *component); diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 3bf1b8691bdc72..2d666bb241223c 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -80,6 +80,12 @@ snd_soc_component_to_driver(struct snd_soc_component *component) } EXPORT_SYMBOL_GPL(snd_soc_component_to_driver); +struct snd_soc_card *snd_soc_component_to_card(struct snd_soc_component *component) +{ + return component->card; +} +EXPORT_SYMBOL_GPL(snd_soc_component_to_card); + unsigned int snd_soc_component_active(struct snd_soc_component *component) { return component->active; From b461f4daf684d5b7dfef782b5b03d7c0cea75282 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:43:49 +0000 Subject: [PATCH 1840/2102] ASoC: soc-component: add snd_soc_component_to_debugfs_root() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. This patch adds snd_soc_component_debugfs_root() to get component->debugfs_root. Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87jym1eld7.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 1 + sound/soc/soc-component.c | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index ec0e3d7264cc31..0bc84c9c0e7e1e 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -277,6 +277,7 @@ struct snd_soc_dapm_context *snd_soc_component_to_dapm(struct snd_soc_component const struct snd_soc_component_driver *snd_soc_component_to_driver(struct snd_soc_component *component); struct snd_soc_card *snd_soc_component_to_card(struct snd_soc_component *component); +struct dentry *snd_soc_component_to_debugfs_root(struct snd_soc_component *component); struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, const struct snd_soc_component_driver *driver); void snd_soc_component_unregister(struct snd_soc_component *component); diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 2d666bb241223c..110f4d60d4a4d1 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -86,6 +86,12 @@ struct snd_soc_card *snd_soc_component_to_card(struct snd_soc_component *compone } EXPORT_SYMBOL_GPL(snd_soc_component_to_card); +struct dentry *snd_soc_component_to_debugfs_root(struct snd_soc_component *component) +{ + return component->debugfs_root; +} +EXPORT_SYMBOL_GPL(snd_soc_component_to_debugfs_root); + unsigned int snd_soc_component_active(struct snd_soc_component *component) { return component->active; From 2349773f2addf62aac5a30afad7c485c7a4a17b6 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:43:52 +0000 Subject: [PATCH 1841/2102] ASoC: soc-component: add snd_soc_component_to_regmap() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. Add snd_soc_component_to_regmap() to soc-component.c Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87ik1leld3.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 1 + sound/soc/soc-component.c | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 0bc84c9c0e7e1e..0caea23da4fc05 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -278,6 +278,7 @@ const struct snd_soc_component_driver *snd_soc_component_to_driver(struct snd_soc_component *component); struct snd_soc_card *snd_soc_component_to_card(struct snd_soc_component *component); struct dentry *snd_soc_component_to_debugfs_root(struct snd_soc_component *component); +struct regmap *snd_soc_component_to_regmap(struct snd_soc_component *component); struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, const struct snd_soc_component_driver *driver); void snd_soc_component_unregister(struct snd_soc_component *component); diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 110f4d60d4a4d1..f1ff81412420e6 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -92,6 +92,12 @@ struct dentry *snd_soc_component_to_debugfs_root(struct snd_soc_component *compo } EXPORT_SYMBOL_GPL(snd_soc_component_to_debugfs_root); +struct regmap *snd_soc_component_to_regmap(struct snd_soc_component *component) +{ + return component->regmap; +} +EXPORT_SYMBOL_GPL(snd_soc_component_to_regmap); + unsigned int snd_soc_component_active(struct snd_soc_component *component) { return component->active; From 17adf820d64cb68802a728f4d573a89f551dc71a Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:43:56 +0000 Subject: [PATCH 1842/2102] ASoC: soc-component: add snd_soc_component_regcache_mark_dirty() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. Adds snd_soc_component_regcache_mark_dirty(). Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87h5h5elcz.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 1 + sound/soc/soc-component.c | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 0caea23da4fc05..9b799cc300f48b 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -357,6 +357,7 @@ void snd_soc_component_regmap_exit(struct snd_soc_component *component); int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component); void snd_soc_component_regmap_async_complete(struct snd_soc_component *component); int snd_soc_component_regcache_sync(struct snd_soc_component *component); +void snd_soc_component_regcache_mark_dirty(struct snd_soc_component *component); int snd_soc_component_fixup_controls(struct snd_soc_component *component); int snd_soc_component_add_controls(struct snd_soc_component *component, diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index f1ff81412420e6..8c1da7dbcbc733 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -509,6 +509,15 @@ int snd_soc_component_regcache_sync(struct snd_soc_component *component) } EXPORT_SYMBOL_GPL(snd_soc_component_regcache_sync); +void snd_soc_component_regcache_mark_dirty(struct snd_soc_component *component) +{ + struct regmap *regmap = component->regmap; + + if (regmap) + regcache_mark_dirty(regmap); +} +EXPORT_SYMBOL_GPL(snd_soc_component_regcache_mark_dirty); + int snd_soc_component_compr_open(struct snd_soc_component *component, struct snd_compr_stream *cstream) { From b3d85c7a63dc56760e08d7862ec144eaaca5074b Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:44:00 +0000 Subject: [PATCH 1843/2102] ASoC: soc-component: add snd_soc_component_regcache_cache_only() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. Adds snd_soc_component_regcache_cache_only(). Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87fqwpelcw.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 1 + sound/soc/soc-component.c | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 9b799cc300f48b..3427f2f0949569 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -358,6 +358,7 @@ int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component); void snd_soc_component_regmap_async_complete(struct snd_soc_component *component); int snd_soc_component_regcache_sync(struct snd_soc_component *component); void snd_soc_component_regcache_mark_dirty(struct snd_soc_component *component); +void snd_soc_component_regcache_cache_only(struct snd_soc_component *component, bool enable); int snd_soc_component_fixup_controls(struct snd_soc_component *component); int snd_soc_component_add_controls(struct snd_soc_component *component, diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 8c1da7dbcbc733..3c9c22e8c282a2 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -518,6 +518,15 @@ void snd_soc_component_regcache_mark_dirty(struct snd_soc_component *component) } EXPORT_SYMBOL_GPL(snd_soc_component_regcache_mark_dirty); +void snd_soc_component_regcache_cache_only(struct snd_soc_component *component, bool enable) +{ + struct regmap *regmap = component->regmap; + + if (regmap) + regcache_cache_only(regmap, enable); +} +EXPORT_SYMBOL_GPL(snd_soc_component_regcache_cache_only); + int snd_soc_component_compr_open(struct snd_soc_component *component, struct snd_compr_stream *cstream) { From da50009144e29926388f543e0f13fccd0bc5bce3 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:44:03 +0000 Subject: [PATCH 1844/2102] ASoC: soc-component: add snd_soc_component_regcache_cache_bypass() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. Adds snd_soc_component_regcache_cache_bypass(). Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87ecc9elcs.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 1 + sound/soc/soc-component.c | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 3427f2f0949569..7b1d9775422c95 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -359,6 +359,7 @@ void snd_soc_component_regmap_async_complete(struct snd_soc_component *component int snd_soc_component_regcache_sync(struct snd_soc_component *component); void snd_soc_component_regcache_mark_dirty(struct snd_soc_component *component); void snd_soc_component_regcache_cache_only(struct snd_soc_component *component, bool enable); +void snd_soc_component_regcache_cache_bypass(struct snd_soc_component *component, bool enable); int snd_soc_component_fixup_controls(struct snd_soc_component *component); int snd_soc_component_add_controls(struct snd_soc_component *component, diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 3c9c22e8c282a2..996b66188cec12 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -527,6 +527,15 @@ void snd_soc_component_regcache_cache_only(struct snd_soc_component *component, } EXPORT_SYMBOL_GPL(snd_soc_component_regcache_cache_only); +void snd_soc_component_regcache_cache_bypass(struct snd_soc_component *component, bool enable) +{ + struct regmap *regmap = component->regmap; + + if (regmap) + regcache_cache_bypass(regmap, enable); +} +EXPORT_SYMBOL_GPL(snd_soc_component_regcache_cache_bypass); + int snd_soc_component_compr_open(struct snd_soc_component *component, struct snd_compr_stream *cstream) { From ae261152c4d5a8855b29aa77152828419037e6cb Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:44:07 +0000 Subject: [PATCH 1845/2102] ASoC: soc-component: add snd_soc_component_regmap_multi_reg_write_bypassed() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. Adds snd_soc_component_regmap_multi_reg_write_bypassed(). Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87cxrtelco.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 3 +++ sound/soc/soc-component.c | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 7b1d9775422c95..458fe11a10da3f 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -353,6 +353,9 @@ int snd_soc_component_set_bias_level(struct snd_soc_component *component, void snd_soc_component_regmap_init(struct snd_soc_component *component, struct regmap *regmap); void snd_soc_component_regmap_exit(struct snd_soc_component *component); +int snd_soc_component_regmap_multi_reg_write_bypassed(struct snd_soc_component *component, + const struct reg_sequence *regs, + int num_regs); #endif int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component); void snd_soc_component_regmap_async_complete(struct snd_soc_component *component); diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 996b66188cec12..2a82d19b126d2e 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -461,6 +461,19 @@ void snd_soc_component_regmap_exit(struct snd_soc_component *component) } EXPORT_SYMBOL_GPL(snd_soc_component_regmap_exit); +int snd_soc_component_regmap_multi_reg_write_bypassed(struct snd_soc_component *component, + const struct reg_sequence *regs, + int num_regs) +{ + struct regmap *regmap = component->regmap; + + if (!regmap) + return 0; + + return regmap_multi_reg_write_bypassed(regmap, regs, num_regs); +} +EXPORT_SYMBOL_GPL(snd_soc_component_regmap_multi_reg_write_bypassed); + #endif int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component) From 3e30b0232bd4c382429da6266e95eb364c1040bd Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:44:10 +0000 Subject: [PATCH 1846/2102] ASoC: soc-component: add snd_soc_component_num_dai() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. This patch adds snd_soc_component_num_dai() to get component->num_dai. Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87bj7delcl.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- include/sound/soc-component.h | 1 + sound/soc/soc-component.c | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 458fe11a10da3f..8314a2e8df55fa 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -393,6 +393,7 @@ static inline void *snd_soc_component_get_drvdata(struct snd_soc_component *c) } unsigned int snd_soc_component_active(struct snd_soc_component *component); +int snd_soc_component_num_dai(struct snd_soc_component *component); /* component controls */ struct snd_kcontrol *snd_soc_component_get_kcontrol(struct snd_soc_component *component, diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 2a82d19b126d2e..a0e1a7648b8188 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -104,6 +104,12 @@ unsigned int snd_soc_component_active(struct snd_soc_component *component) } EXPORT_SYMBOL_GPL(snd_soc_component_active); +int snd_soc_component_num_dai(struct snd_soc_component *component) +{ + return component->num_dai; +} +EXPORT_SYMBOL_GPL(snd_soc_component_num_dai); + /* * We might want to check substream by using list. * In such case, we can update these macros. From cd7f386dc8de071fb160ed80f2f54c274b183b27 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:44:15 +0000 Subject: [PATCH 1847/2102] ASoC: soc-component: add snd_soc_component_connect_dai() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. This patch adds snd_soc_component_connect_dai() to connect DAI to Component. Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/87a4mxelch.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- sound/soc/soc-component.c | 7 +++++++ sound/soc/soc-dai.c | 3 +-- sound/soc/soc-internal.h | 1 + 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index a0e1a7648b8188..806aa8ab66092f 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -110,6 +110,13 @@ int snd_soc_component_num_dai(struct snd_soc_component *component) } EXPORT_SYMBOL_GPL(snd_soc_component_num_dai); +void snd_soc_component_connect_dai(struct snd_soc_component *component, struct snd_soc_dai *dai) +{ + /* dai->list <-> component->dai_list */ + list_add_tail(snd_soc_dai_to_list(dai), &component->dai_list); + component->num_dai++; +} + /* * We might want to check substream by using list. * In such case, we can update these macros. diff --git a/sound/soc/soc-dai.c b/sound/soc/soc-dai.c index 9e34f34eac3d8a..596180367d9a08 100644 --- a/sound/soc/soc-dai.c +++ b/sound/soc/soc-dai.c @@ -1265,8 +1265,7 @@ struct snd_soc_dai *snd_soc_dai_register(struct snd_soc_component *component, dai->driver = dai_drv; /* see for_each_component_dais */ - list_add_tail(&dai->list, &component->dai_list); - component->num_dai++; + snd_soc_component_connect_dai(component, dai); dev_dbg(dev, "ASoC: Registered DAI '%s'\n", dai->name); return dai; diff --git a/sound/soc/soc-internal.h b/sound/soc/soc-internal.h index e09d283d443a84..98ff0e2fc2e1da 100644 --- a/sound/soc/soc-internal.h +++ b/sound/soc/soc-internal.h @@ -69,6 +69,7 @@ bool snd_soc_component_matches_dlc(struct snd_soc_component *component, void snd_soc_component_remove(struct snd_soc_component *component, int probed); int snd_soc_component_probe(struct snd_soc_component *component, struct snd_soc_card *card); struct list_head *snd_soc_component_get_list_head(void); +void snd_soc_component_connect_dai(struct snd_soc_component *component, struct snd_soc_dai *dai); #define for_each_component(component) \ list_for_each_entry(component, snd_soc_component_get_list_head(), list) From 09cae9addf155c1003c3d645815daf7430927461 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:44:18 +0000 Subject: [PATCH 1848/2102] ASoC: soc-component: add snd_soc_component_active_update() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. This patch adds snd_soc_component_active_update() to handle Component acitive count. Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/878q2helcd.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- sound/soc/soc-component.c | 5 +++++ sound/soc/soc-dai.c | 2 +- sound/soc/soc-internal.h | 1 + sound/soc/soc-pcm.c | 2 +- 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 806aa8ab66092f..5475938f80738b 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -104,6 +104,11 @@ unsigned int snd_soc_component_active(struct snd_soc_component *component) } EXPORT_SYMBOL_GPL(snd_soc_component_active); +void snd_soc_component_active_update(struct snd_soc_component *component, int action) +{ + component->active += action; +} + int snd_soc_component_num_dai(struct snd_soc_component *component) { return component->num_dai; diff --git a/sound/soc/soc-dai.c b/sound/soc/soc-dai.c index 596180367d9a08..73aea7291fa73e 100644 --- a/sound/soc/soc-dai.c +++ b/sound/soc/soc-dai.c @@ -713,7 +713,7 @@ void snd_soc_dai_active_update(struct snd_soc_dai *dai, int stream, int action) dai->stream[stream].active += action; /* see snd_soc_component_active() */ - dai->component->active += action; + snd_soc_component_active_update(dai->component, action); } int snd_soc_dai_active(const struct snd_soc_dai *dai) diff --git a/sound/soc/soc-internal.h b/sound/soc/soc-internal.h index 98ff0e2fc2e1da..1190be669eae3e 100644 --- a/sound/soc/soc-internal.h +++ b/sound/soc/soc-internal.h @@ -70,6 +70,7 @@ void snd_soc_component_remove(struct snd_soc_component *component, int probed); int snd_soc_component_probe(struct snd_soc_component *component, struct snd_soc_card *card); struct list_head *snd_soc_component_get_list_head(void); void snd_soc_component_connect_dai(struct snd_soc_component *component, struct snd_soc_dai *dai); +void snd_soc_component_active_update(struct snd_soc_component *component, int action); #define for_each_component(component) \ list_for_each_entry(component, snd_soc_component_get_list_head(), list) diff --git a/sound/soc/soc-pcm.c b/sound/soc/soc-pcm.c index ef8ccf52798eb6..dac353fec4bcfd 100644 --- a/sound/soc/soc-pcm.c +++ b/sound/soc/soc-pcm.c @@ -374,7 +374,7 @@ void snd_soc_runtime_action(struct snd_soc_pcm_runtime *rtd, for_each_rtd_components(rtd, i, component) { if (component->num_dai) continue; - component->active += action; + snd_soc_component_active_update(component, action); } } EXPORT_SYMBOL_GPL(snd_soc_runtime_action); From e14a9bcd22a7ae07e5dd01428dd82664271210b3 Mon Sep 17 00:00:00 2001 From: Kuninori Morimoto Date: Wed, 25 Nov 2026 01:44:24 +0000 Subject: [PATCH 1849/2102] ASoC: soc-component: add snd_soc_component_device_link_{add/del}() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit struct snd_soc_component will be capsuled soon, its member will not be able to access from non soc-component.c. This patch adds snd_soc_component_device_link_{add/del}() to handle Component device_link. Signed-off-by: Kuninori Morimoto Reviewed-by: Alvin Šipraga Link: https://patch.msgid.link/877bi1elc8.wl-kuninori.morimoto.gx@renesas.com Signed-off-by: Mark Brown --- sound/soc/soc-card.c | 22 ++++------------------ sound/soc/soc-component.c | 28 ++++++++++++++++++++++++++++ sound/soc/soc-internal.h | 2 ++ 3 files changed, 34 insertions(+), 18 deletions(-) diff --git a/sound/soc/soc-card.c b/sound/soc/soc-card.c index 6544dbf2ee2607..079312216a3b2d 100644 --- a/sound/soc/soc-card.c +++ b/sound/soc/soc-card.c @@ -884,12 +884,8 @@ static void snd_soc_remove_device_links(struct snd_soc_card *card) { struct snd_soc_component *component; - for_each_card_components(card, component) { - if (component->card_device_link) { - device_link_del(component->card_device_link); - component->card_device_link = NULL; - } - } + for_each_card_components(card, component) + snd_soc_component_device_link_del(component); } void snd_soc_card_unbind(struct snd_soc_card *card, bool reuse) @@ -1043,18 +1039,8 @@ static int snd_soc_card_bind(struct snd_soc_card *card) * If a driver pair already have a link in the opposite direction * they must manage their own suspend order. */ - for_each_card_components(card, component) { - if (card->dev == component->dev) - continue; - - component->card_device_link = device_link_add(card->dev, - component->dev, - DL_FLAG_STATELESS); - if (!component->card_device_link) { - dev_warn(card->dev, "Could not create device link to %s\n", - dev_name(component->dev)); - } - } + for_each_card_components(card, component) + snd_soc_component_device_link_add(component); ret = snd_soc_card_late_probe(card); if (ret < 0) diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index 5475938f80738b..de3218bb2b2a8d 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -122,6 +122,34 @@ void snd_soc_component_connect_dai(struct snd_soc_component *component, struct s component->num_dai++; } +void snd_soc_component_device_link_del(struct snd_soc_component *component) +{ + if (component->card_device_link) { + device_link_del(component->card_device_link); + component->card_device_link = NULL; + } +} + +int snd_soc_component_device_link_add(struct snd_soc_component *component) +{ + struct snd_soc_card *card = snd_soc_component_to_card(component); + struct device *card_dev = card->dev; + struct device *component_dev = snd_soc_component_to_dev(component); + + if (card_dev == component_dev) + return 0; + + component->card_device_link = device_link_add(card_dev, component_dev, + DL_FLAG_STATELESS); + if (!component->card_device_link) { + dev_warn(card_dev, "Could not create device link to %s\n", + dev_name(component_dev)); + return -EINVAL; + } + + return 0; +} + /* * We might want to check substream by using list. * In such case, we can update these macros. diff --git a/sound/soc/soc-internal.h b/sound/soc/soc-internal.h index 1190be669eae3e..e713d13543b2d7 100644 --- a/sound/soc/soc-internal.h +++ b/sound/soc/soc-internal.h @@ -71,6 +71,8 @@ int snd_soc_component_probe(struct snd_soc_component *component, struct snd_soc_ struct list_head *snd_soc_component_get_list_head(void); void snd_soc_component_connect_dai(struct snd_soc_component *component, struct snd_soc_dai *dai); void snd_soc_component_active_update(struct snd_soc_component *component, int action); +void snd_soc_component_device_link_del(struct snd_soc_component *component); +int snd_soc_component_device_link_add(struct snd_soc_component *component); #define for_each_component(component) \ list_for_each_entry(component, snd_soc_component_get_list_head(), list) From 4c30a6661e5304dea4b1f7216cd552f1b798970e Mon Sep 17 00:00:00 2001 From: Chen Yuxi Date: Thu, 19 Nov 2026 08:25:06 +0000 Subject: [PATCH 1850/2102] ASoC: SOF: Intel: hda: Fix NULL deref in hw_params and hw_free When the topology and the machine driver DAI links do not match, the DAI widget may be missing and hda_dai_get_ops() returns NULL. However, in hda_dai_hw_params_data() and hda_dai_hw_free(), the sdev pointer is obtained by dereferencing the DAI widget at declaration time, before the ops check, so a NULL widget is dereferenced before the intended error path can run. Move both sdev assignments after the ops check. Also use dai->dev instead of sdev->dev for the error message in hda_dai_hw_params_data(), since sdev cannot be obtained when the DAI widget is missing. Fixes: de8e2d5d8024 ("ASoC: SOF: Intel: hda-dai: remove use of cpu_dai->component drvdata") Cc: stable@vger.kernel.org Signed-off-by: Chen Yuxi Link: https://patch.msgid.link/20261119082506.2485543-1-chenyuxi19@huawei.com Signed-off-by: Mark Brown --- sound/soc/sof/intel/hda-dai.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/sound/soc/sof/intel/hda-dai.c b/sound/soc/sof/intel/hda-dai.c index 7d920d43ef2a39..987a4deeee289d 100644 --- a/sound/soc/sof/intel/hda-dai.c +++ b/sound/soc/sof/intel/hda-dai.c @@ -223,13 +223,15 @@ static int __maybe_unused hda_dai_hw_free(struct snd_pcm_substream *substream, { const struct hda_dai_widget_dma_ops *ops = hda_dai_get_ops(substream, cpu_dai); struct hdac_ext_stream *hext_stream; - struct snd_sof_dev *sdev = dai_to_sdev(substream, cpu_dai); + struct snd_sof_dev *sdev; if (!ops) { dev_err(cpu_dai->dev, "DAI widget ops not set\n"); return -EINVAL; } + sdev = dai_to_sdev(substream, cpu_dai); + hext_stream = ops->get_hext_stream(sdev, cpu_dai, substream); if (!hext_stream) return 0; @@ -246,14 +248,16 @@ static int __maybe_unused hda_dai_hw_params_data(struct snd_pcm_substream *subst struct snd_soc_dapm_widget *w = snd_soc_dai_get_widget(dai, substream->stream); const struct hda_dai_widget_dma_ops *ops = hda_dai_get_ops(substream, dai); struct hdac_ext_stream *hext_stream; - struct snd_sof_dev *sdev = widget_to_sdev(w); + struct snd_sof_dev *sdev; int ret; if (!ops) { - dev_err(sdev->dev, "DAI widget ops not set\n"); + dev_err(dai->dev, "DAI widget ops not set\n"); return -EINVAL; } + sdev = widget_to_sdev(w); + hext_stream = ops->get_hext_stream(sdev, dai, substream); if (hext_stream && hext_stream->link_prepared) return 0; From e49d115878796b7b7f77f821d67b7b2f7ccaf400 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Wed, 11 Nov 2026 16:41:26 +0000 Subject: [PATCH 1851/2102] io_uring/filetable: don't install O_PATH files IORING_OP_FADVISE with POSIX_FADV_WILLNEED on a fixed file that was opened with O_PATH can dereference a NULL pointer in the readahead code of the filesystem. The opcode handlers are written like the system calls that they mirror, which get their file from fdget() and so never see an O_PATH file. io_uring has to keep that true for req->file. io_file_get_normal() does, with fget(). io_file_get_fixed() checks nothing, so a fixed file table must never hold an O_PATH file. The register and update paths take their files from fget(). But a direct open, IORING_OP_OPENAT or IORING_OP_OPENAT2 with sqe->file_index set, installs the file that do_file_open() returns, and io_install_fixed_file() refuses nothing but io_uring files. With O_PATH, do_dentry_open() returns before it calls ->open(), so file->private_data stays NULL. generic_fadvise() has no check of its own and starts readahead with that file, and fuse_send_readpages(), for one, dereferences file->private_data. The fix used here is to refuse O_PATH files in io_install_fixed_file() as well, so that a direct open gives what an open followed by a register gives. A direct open with O_PATH now fails with -EBADF. Until now the slot could be turned into a descriptor with IORING_OP_FIXED_FD_INSTALL, passed to another ring with IORING_MSG_SEND_FD, and used with IORING_OP_FGETXATTR and IORING_OP_FSETXATTR. No program that does so is known, and a fixed file can't serve as the directory of a lookup. Fixes: b9445598d8c6 ("io_uring: openat directly into fixed fd table") Signed-off-by: Chris Mason Signed-off-by: Jens Axboe --- io_uring/filetable.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/io_uring/filetable.c b/io_uring/filetable.c index cb1838c9fc3776..f547ab1193b103 100644 --- a/io_uring/filetable.c +++ b/io_uring/filetable.c @@ -67,6 +67,9 @@ static int io_install_fixed_file(struct io_ring_ctx *ctx, struct file *file, if (io_is_uring_fops(file)) return -EBADF; + /* Registered files come from fget(), which refuses these too */ + if (file->f_mode & FMODE_PATH) + return -EBADF; if (!ctx->file_table.data.nr) return -ENXIO; if (slot_index >= ctx->file_table.data.nr) From 40162f8314a98948e0791b580024bbc899d2ee81 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Wed, 11 Nov 2026 16:46:12 +0000 Subject: [PATCH 1852/2102] io_uring/timeout: hold timeout_lock for the link splice The exit of a single thread that races with the close of its IORING_SETUP_DEFER_TASKRUN ring can cause a use-after-free of a linked timeout that has fired. io-wq calls its match function under raw spinlocks, so there io_match_task_safe() walks the link chain without ->uring_lock. It holds ->timeout_lock, which is enough only if a linked timeout leaves the chain under that lock. But io_req_task_link_timeout() does the splice under ->uring_lock alone. Once the ring is closed, the closing task runs that task_work, and with a drain active the flush frees the request: io_match_task_safe() io_cancel_local_task_work() ==================== =========================== lock ->timeout_lock io_match_linked() req = head->link lock ->uring_lock io_req_task_link_timeout() prev->link = req->link io_req_task_complete() io_submit_flush_completions() io_free_batch_list() io_queue_deferred() __io_req_caches_free() req = req->link The fix used here is to hold ->timeout_lock as well for the splice, which stays in task_work and under ->uring_lock. Fixes: 49ae66eb8c27 ("io_uring: defer linked-timeout chain splice out of hrtimer context") Signed-off-by: Chris Mason Signed-off-by: Jens Axboe --- io_uring/timeout.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/io_uring/timeout.c b/io_uring/timeout.c index db78059cfeab12..46c01704b58fba 100644 --- a/io_uring/timeout.c +++ b/io_uring/timeout.c @@ -392,11 +392,14 @@ static void io_req_task_link_timeout(struct io_tw_req tw_req, io_tw_token_t tw) if (prev) { /* * splice the linked timeout out of prev's chain if the regular - * completion path didn't already do it. + * completion path didn't already do it. io-wq cancellation + * walks the chain with only ->timeout_lock held. */ + raw_spin_lock_irq(&req->ctx->timeout_lock); if (prev->link == req) prev->link = req->link; req->link = NULL; + raw_spin_unlock_irq(&req->ctx->timeout_lock); if (!tw.cancel) { struct io_cancel_data cd = { From a6b53de207d3472f209e71fd4990be3dd3133d1f Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Wed, 11 Nov 2026 16:46:13 +0000 Subject: [PATCH 1853/2102] io_uring/cancel: always walk links under timeout_lock The exit of a single thread that races with the close of its IORING_SETUP_DEFER_TASKRUN ring can cause a use-after-free of a linked timeout, if io-wq is the first to issue the request that the timeout is linked to. When io-wq calls io_match_task_safe(), ->timeout_lock alone protects the walk of the link chain against the removal of a linked timeout. The function takes the lock only if the head has REQ_F_LINK_TIMEOUT. But the first issue sets that flag. If that happens in an io-wq worker, cancellation can find the request as the current work of the worker before the flag is set: io_match_task_safe() io-wq worker, timer, task_work ==================== ============================== REQ_F_LINK_TIMEOUT is clear io_match_linked() req = head->link __io_issue_sqe() __io_prep_linked_timeout() io_queue_linked_timeout() io_link_timeout_fn() io_req_task_link_timeout() __io_req_caches_free() req = req->link The fix used here is to take ->timeout_lock for every walk, whatever the flags of the head say. Signed-off-by: Chris Mason Signed-off-by: Jens Axboe --- io_uring/cancel.c | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/io_uring/cancel.c b/io_uring/cancel.c index e3d9fe8fc982c6..5b57d27225acd8 100644 --- a/io_uring/cancel.c +++ b/io_uring/cancel.c @@ -438,6 +438,7 @@ static bool io_match_linked(struct io_kiocb *head) bool io_match_task_safe(struct io_kiocb *head, struct io_uring_task *tctx, bool cancel_all) { + struct io_ring_ctx *ctx = head->ctx; bool matched; if (tctx && head->tctx != tctx) @@ -445,16 +446,13 @@ bool io_match_task_safe(struct io_kiocb *head, struct io_uring_task *tctx, if (cancel_all) return true; - if (head->flags & REQ_F_LINK_TIMEOUT) { - struct io_ring_ctx *ctx = head->ctx; - - /* protect against races with linked timeouts */ - raw_spin_lock_irq(&ctx->timeout_lock); - matched = io_match_linked(head); - raw_spin_unlock_irq(&ctx->timeout_lock); - } else { - matched = io_match_linked(head); - } + /* + * Protect against races with linked timeouts. REQ_F_LINK_TIMEOUT can't + * tell if there is one: an io-wq worker may set it during the walk. + */ + raw_spin_lock_irq(&ctx->timeout_lock); + matched = io_match_linked(head); + raw_spin_unlock_irq(&ctx->timeout_lock); return matched; } From 449c7dc8502404b3a95ffa75cf5b54be5350fc49 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Wed, 11 Nov 2026 23:45:44 +0000 Subject: [PATCH 1854/2102] io_uring/net: don't count the buffers of a send bundle A bundle send on a packet socket with a TX ring can cause a slab-out-of-bounds read, if the frames in the ring hold more bytes than the iovecs of the send. io_send_finish() hands the result of the send to io_bundle_nbufs(), which walks the iovec array and subtracts each iov_len from the result. The walk only stops at zero, so the iovecs have to cover the result. But io_send() only tests if the result is below the count of the iter, and tpacket_snd() ignores msg_iter and returns the length of the frames that it took from the TX ring: iovecs = 2, of 1 byte each frames in the TX ring = 1, of 64 bytes sock_sendmsg() = 64 64 - iov[0].iov_len = 63 63 - iov[1].iov_len = 62 62 - iov[2].iov_len is out of bounds The send side doesn't use the number of buffers: io_buffers_select() commits them at selection, so at completion io_kbuf_commit() returns before it reads the number. The fix used here is to put the buffers of a send bundle without counting them, so that nothing walks the iovecs with the result of the send. Fixes: a05d1f625c7a ("io_uring/net: support bundles for send") Signed-off-by: Chris Mason Signed-off-by: Jens Axboe --- io_uring/net.c | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/io_uring/net.c b/io_uring/net.c index f8d547c5e7d671..9c69f37cb8aa57 100644 --- a/io_uring/net.c +++ b/io_uring/net.c @@ -515,12 +515,10 @@ static inline bool io_send_finish(struct io_kiocb *req, bool bundle_finished = sel->val <= 0; unsigned int cflags; - if (!(sr->flags & IORING_RECVSEND_BUNDLE)) { - cflags = io_put_kbuf(req, sel->val, sel->buf_list); + /* Committed at selection time, so a bundle needs no buffer count */ + cflags = io_put_kbuf(req, sel->val, sel->buf_list); + if (!(sr->flags & IORING_RECVSEND_BUNDLE)) goto finish; - } - - cflags = io_put_kbufs(req, sel->val, sel->buf_list, io_bundle_nbufs(kmsg, sel->val)); /* * Don't start new bundles if the buffer list is empty, or if the From 6f3159575d53eed2d54557aef2dd8373da7c0208 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Thu, 12 Nov 2026 07:04:13 +0000 Subject: [PATCH 1855/2102] io_uring: drop cached task refs on ring release An exiting task can leak its own task_struct, if its exit releases a ring that still has a request of that task in flight. If a task frees its own request, io_put_task() doesn't put the task reference but keeps it in tctx->cached_refs. An exiting task empties that cache for the last time in io_uring_cancel_generic(). So whatever frees requests in that task later on has to call io_uring_drop_tctx_refs() afterwards, as tctx_task_work_run() does. The cancel pass in io_ring_ctx_wait_and_kill() doesn't. With a timeout armed on a DEFER_TASKRUN ring: do_exit() io_uring_files_cancel() io_uring_cancel_generic() io_uring_drop_tctx_refs() io_tctx_cancel_done() is true, the timeout stays armed exit_files() io_uring_release() io_ring_ctx_wait_and_kill() io_ring_ctx_cancel() io_kill_timeouts() io_cancel_local_task_work() io_put_task() tctx->cached_refs++ Commit e775f93f2ab9 ("io_uring: ensure that cached task references are always put on exit") added that call to io_ring_ctx_wait_and_kill(). Commit 02bac94bd8ef ("io_uring: don't iopoll from io_ring_ctx_wait_and_kill()") removed it together with the completions at release, and commit 89baa3154a72 ("io_uring: run cancelations synchronously on ring release") brought only the completions back. The fix used here is to restore that call, after the task that releases the ring has run its cancelations. Fixes: 89baa3154a72 ("io_uring: run cancelations synchronously on ring release") Signed-off-by: Chris Mason Signed-off-by: Jens Axboe --- io_uring/io_uring.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/io_uring/io_uring.c b/io_uring/io_uring.c index 6808229edf07ce..d8491f86e48082 100644 --- a/io_uring/io_uring.c +++ b/io_uring/io_uring.c @@ -2702,6 +2702,9 @@ static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx) if (!(current->flags & PF_IO_WORKER)) { io_ring_ctx_cancel(ctx); io_ring_ctx_wait_inflight(ctx); + /* exit is past the drop in io_uring_cancel_generic() */ + if (current->io_uring) + io_uring_drop_tctx_refs(current); } INIT_WORK(&ctx->exit_work, io_ring_exit_work); From 437e79d6a2a7aba81d56c11198576a72574e6d52 Mon Sep 17 00:00:00 2001 From: Chris Mason Date: Fri, 13 Nov 2026 03:29:20 +0000 Subject: [PATCH 1856/2102] io_uring/net: restore the cmsg buffer on recvmsg retry A single-shot IORING_OP_RECVMSG that is retried after -EAGAIN can report the control messages of the failed attempt, and hide those that came with the data. On an AF_UNIX stream socket with SO_PASSCRED, the caller gets SCM_CREDENTIALS with pid, uid and gid 0, and never sees the descriptors that an SCM_RIGHTS message installed. io_recvmsg() passes the msghdr that was set up at prep to each attempt, so a failed ->recvmsg() has to leave msg_control and msg_controllen as they were. recvmsg(2) doesn't depend on that, since it copies the user's msghdr for each call. unix_stream_read_generic() calls scm_recv_unix() whatever its result is, with a zeroed scm_cookie if the queue was empty, and put_cmsg() advances the control buffer. ____sys_recvmsg() then counts the reported length from where its call started, but the caller reads from the head of its buffer: msg_control = C, msg_controllen = 64 first attempt, the queue is empty put_cmsg(SCM_CREDENTIALS {0, 0, 0}) at C msg_control = C + 32, msg_controllen = 32 return -EAGAIN second attempt cmsg_ptr = C + 32 put_cmsg(SCM_CREDENTIALS of the sender) at C + 32 msg_control = C + 64, msg_controllen = 0 put_user(msg_control - cmsg_ptr = 32, &umsg->msg_controllen) The fix used here is to save the control buffer before each attempt, and to restore it if the attempt fails with -EAGAIN and will be retried. The tradeoff: with MSG_WAITALL, a retry whose control buffer the failed attempts had used up went on after a short receive until the data buffer was full. It now completes short, as every recvmsg with a control buffer does since commit 78d0d2063bab ("io_uring/net: disable partial retries for recvmsg with cmsg"). Fixes: e54937963fa2 ("net: remove cmsg restriction from io_uring based send/recvmsg calls") Signed-off-by: Chris Mason Signed-off-by: Jens Axboe --- io_uring/net.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/io_uring/net.c b/io_uring/net.c index 9c69f37cb8aa57..b0d508b772ceea 100644 --- a/io_uring/net.c +++ b/io_uring/net.c @@ -1047,6 +1047,8 @@ int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags) int ret, min_ret = 0; bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK; bool mshot_finished = true; + void __user *control; + size_t controllen; int consumed = 0; size_t len; @@ -1084,6 +1086,8 @@ int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags) kmsg->msg.msg_get_inq = 1; kmsg->msg.msg_inq = -1; + control = kmsg->msg.msg_control_user; + controllen = kmsg->msg.msg_controllen; if (req->flags & REQ_F_APOLL_MULTISHOT) { ret = io_recvmsg_multishot(sock, sr, kmsg, flags, &mshot_finished); @@ -1108,6 +1112,12 @@ int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags) if (ret < min_ret) { if (ret == -EAGAIN && force_nonblock) { + /* + * Don't depend on the control buffer being untouched, a + * protocol may post a cmsg before it finds no data. + */ + kmsg->msg.msg_control_user = control; + kmsg->msg.msg_controllen = controllen; io_kbuf_recycle(req, sel.buf_list, issue_flags); return IOU_RETRY; } From ce25f661d1df14cd9bf677871bcf33aeb6b251b4 Mon Sep 17 00:00:00 2001 From: HyeongJun An Date: Wed, 18 Nov 2026 18:38:39 +0900 Subject: [PATCH 1857/2102] ASoC: SOF: control: Report the volume range as ASoC does SOF controls with more than two channels use snd_sof_volume_info() instead of snd_soc_info_volsw(). The snd_sof_volume_info() reports platform_max - min as the maximum, while snd_soc_info_volsw() reports max - min, limited by platform_max. With min 10, max 100 and platform_max 80, a control reports 70 with more than two channels and 80 with up to two. To fix this, compute the maximum the way snd_soc_info_volsw() does. The helper is reused by the next patch to check the values written to the controls. It also no longer stores max in platform_max as a side effect. No SOF topology sets min or platform_max today, so the reported ranges do not change. Suggested-by: Peter Ujfalusi Signed-off-by: HyeongJun An Link: https://patch.msgid.link/20261118093840.3514408-2-sammiee5311@gmail.com Signed-off-by: Mark Brown --- sound/soc/sof/control.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/sound/soc/sof/control.c b/sound/soc/sof/control.c index 74d997a4f6203c..136e2ce15201fd 100644 --- a/sound/soc/sof/control.c +++ b/sound/soc/sof/control.c @@ -15,6 +15,17 @@ #include "sof-priv.h" #include "sof-audio.h" +/* the maximum value as snd_soc_info_volsw() reports it */ +static int sof_mixer_max(const struct soc_mixer_control *sm) +{ + int max = sm->max - sm->min; + + if (sm->platform_max && sm->platform_max < max) + max = sm->platform_max; + + return max; +} + int snd_sof_volume_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { @@ -50,20 +61,16 @@ int snd_sof_volume_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info struct soc_mixer_control *sm = (struct soc_mixer_control *)kcontrol->private_value; struct snd_sof_control *scontrol = sm->dobj.private; unsigned int channels = scontrol->num_channels; - int platform_max; - - if (!sm->platform_max) - sm->platform_max = sm->max; - platform_max = sm->platform_max; + int max = sof_mixer_max(sm); - if (platform_max == 1 && !strstr(kcontrol->id.name, " Volume")) + if (max == 1 && !strstr(kcontrol->id.name, " Volume")) uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN; else uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = channels; uinfo->value.integer.min = 0; - uinfo->value.integer.max = platform_max - sm->min; + uinfo->value.integer.max = max; return 0; } From 4f64e9b7c63bffb64efe62b95702c6d8a830451b Mon Sep 17 00:00:00 2001 From: HyeongJun An Date: Wed, 18 Nov 2026 18:38:40 +0900 Subject: [PATCH 1858/2102] ASoC: SOF: control: Reject out of range volume and switch values The snd_sof_volume_put() and snd_sof_switch_put() pass the user values to the IPC put handlers without a range check. The switch handlers store any value and send it to the firmware, so on IPC3 writing 2 or -1 to a switch reads back as 2 or 4294967295. The volume handlers convert the value to u32 and clamp it to the end of the volume table. Writing -1 sets the maximum volume, and on 64-bit writing LONG_MIN sets the minimum, both without an error. Return -EINVAL for values outside the range the info callbacks report, as snd_soc_put_volsw() does. This fixes the write_invalid failures in mixer-test, and the event_spurious failures caused by the events those writes generated. Fixes: c3078f539704 ("ASoC: SOF: Add Sound Open Firmware KControl support") Signed-off-by: HyeongJun An Link: https://patch.msgid.link/20261118093840.3514408-3-sammiee5311@gmail.com Signed-off-by: Mark Brown --- sound/soc/sof/control.c | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/sound/soc/sof/control.c b/sound/soc/sof/control.c index 136e2ce15201fd..dcf101f7e1d5f0 100644 --- a/sound/soc/sof/control.c +++ b/sound/soc/sof/control.c @@ -26,6 +26,24 @@ static int sof_mixer_max(const struct soc_mixer_control *sm) return max; } +/* the IPC put handlers do not check the range */ +static int sof_mixer_check_values(const struct soc_mixer_control *sm, + const struct snd_sof_control *scontrol, + const struct snd_ctl_elem_value *ucontrol) +{ + int max = sof_mixer_max(sm); + unsigned int i; + + for (i = 0; i < scontrol->num_channels; i++) { + long val = ucontrol->value.integer.value[i]; + + if (val < 0 || val > max) + return -EINVAL; + } + + return 0; +} + int snd_sof_volume_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { @@ -49,6 +67,11 @@ int snd_sof_volume_put(struct snd_kcontrol *kcontrol, struct snd_soc_component *scomp = scontrol->scomp; struct snd_sof_dev *sdev = snd_soc_component_get_drvdata(scomp); const struct sof_ipc_tplg_ops *tplg_ops = sof_ipc_get_ops(sdev, tplg); + int ret; + + ret = sof_mixer_check_values(sm, scontrol, ucontrol); + if (ret) + return ret; if (tplg_ops && tplg_ops->control && tplg_ops->control->volume_put) return tplg_ops->control->volume_put(scontrol, ucontrol); @@ -97,6 +120,11 @@ int snd_sof_switch_put(struct snd_kcontrol *kcontrol, struct snd_soc_component *scomp = scontrol->scomp; struct snd_sof_dev *sdev = snd_soc_component_get_drvdata(scomp); const struct sof_ipc_tplg_ops *tplg_ops = sof_ipc_get_ops(sdev, tplg); + int ret; + + ret = sof_mixer_check_values(sm, scontrol, ucontrol); + if (ret) + return ret; if (tplg_ops && tplg_ops->control && tplg_ops->control->switch_put) return tplg_ops->control->switch_put(scontrol, ucontrol); From 7a9e767b1db628dd667bb96003c264e068ea669b Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 25 Nov 2026 11:54:40 -0500 Subject: [PATCH 1859/2102] ext4: stub ext4_sb_find_get_block_nonatomic() in the inode KUnit tests The merge of the ext4 KUnit tests with commit d25c14b2d79e ("ext4: use sb_find_get_block_nonatomic() in ext4_get_inode_loc_noio()") added a stubbable ext4_sb_find_get_block_nonatomic() wrapper and switched ext4_get_inode_loc_noio() to it. However, inode_test_setup() still only stubs ext4_sb_find_get_block(), breaking some KUnit tests. Fix this by adding the missing stub. Fixes: 4dce97c6c265 ("Merge tag 'ext4_for_linus-7.4-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/tytso/ext4") Signed-off-by: Theodore Ts'o --- fs/ext4/inode-test.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/fs/ext4/inode-test.c b/fs/ext4/inode-test.c index ab1ca59826aaf5..529cab24db48f3 100644 --- a/fs/ext4/inode-test.c +++ b/fs/ext4/inode-test.c @@ -1149,6 +1149,8 @@ static struct inode_test_ctx *inode_test_setup(struct kunit *test) inode_test_sb_getblk_stub); kunit_activate_static_stub(test, ext4_sb_find_get_block, inode_test_sb_find_get_block_stub); + kunit_activate_static_stub(test, ext4_sb_find_get_block_nonatomic, + inode_test_sb_find_get_block_stub); kunit_activate_static_stub(test, ext4_sb_getblk_unmovable, inode_test_sb_getblk_unmovable_stub); kunit_activate_static_stub(test, ext4_ext_getblk, From 43d2e9d3f4ba3eaaec7356a7537164865266dff5 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 25 Nov 2026 12:01:50 -0500 Subject: [PATCH 1860/2102] ext4: set s_user_ns in the KUnit tests' fake superblocks xattr_test_init() builds a fake super_block but never sets s_user_ns. ext4_xattr_inode_create() calls i_uid_read() and i_gid_read() on the parent inode, which map the ids through inode->i_sb->s_user_ns. With CONFIG_USER_NS=y this dereferences a NULL user namespace. Fix this by pointing s_user_ns at init_user_ns, as alloc_super() does for a normal mount. The dir, hash, inline and namei tests build their fake superblocks the same way. None of them reads an inode owner today, but do the same there so that new test cases don't run into this. Fixes: 5df08dcafa99 ("ext4: add KUnit tests for fs/ext4/xattr.c") Signed-off-by: Theodore Ts'o --- fs/ext4/dir-test.c | 2 ++ fs/ext4/hash-test.c | 3 +++ fs/ext4/inline-test.c | 2 ++ fs/ext4/namei-test.c | 2 ++ fs/ext4/xattr-test.c | 3 +++ 5 files changed, 12 insertions(+) diff --git a/fs/ext4/dir-test.c b/fs/ext4/dir-test.c index 7ec661919760da..5939fbfd85b5b5 100644 --- a/fs/ext4/dir-test.c +++ b/fs/ext4/dir-test.c @@ -15,6 +15,7 @@ #include #include #include +#include #include "ext4.h" #include "ext4_jbd2.h" @@ -364,6 +365,7 @@ static int dir_test_init(struct kunit *test) ctx->sb.s_maxbytes = 64ULL * DIR_TEST_BLK_SIZE; ctx->sb.s_op = &dir_test_sops; ctx->sb.s_fs_info = &ctx->sbi; + ctx->sb.s_user_ns = &init_user_ns; ctx->sb.s_bdev = &ctx->bdev; ctx->bdev.bd_mapping = &ctx->bd_mapping; bdev_set_flag(&ctx->bdev, BD_READ_ONLY); diff --git a/fs/ext4/hash-test.c b/fs/ext4/hash-test.c index 49b0d874c833a5..2898f112a43790 100644 --- a/fs/ext4/hash-test.c +++ b/fs/ext4/hash-test.c @@ -9,6 +9,7 @@ #include #include #include +#include #include "ext4.h" static void ext4_hash_init_fake_dir(struct inode *dir, struct super_block *sb) @@ -16,6 +17,7 @@ static void ext4_hash_init_fake_dir(struct inode *dir, struct super_block *sb) memset(sb, 0, sizeof(*sb)); memset(dir, 0, sizeof(*dir)); dir->i_sb = sb; + sb->s_user_ns = &init_user_ns; strscpy(sb->s_id, "kunit-ext4", sizeof(sb->s_id)); } @@ -48,6 +50,7 @@ static void ext4_hash_init_fake_ext4_dir(struct ext4_inode_info *ei, memset(sbi, 0, sizeof(*sbi)); strscpy(sb->s_id, "kunit-ext4", sizeof(sb->s_id)); + sb->s_user_ns = &init_user_ns; sb->s_fs_info = sbi; sbi->s_sb = sb; diff --git a/fs/ext4/inline-test.c b/fs/ext4/inline-test.c index 0198ce8311c73e..b3d7c51ad216be 100644 --- a/fs/ext4/inline-test.c +++ b/fs/ext4/inline-test.c @@ -13,6 +13,7 @@ #include #include #include +#include #include "ext4.h" #include "ext4_jbd2.h" @@ -275,6 +276,7 @@ static int inline_test_init(struct kunit *test) ctx->sb.s_time_gran = 1; ctx->sb.s_bdi = &noop_backing_dev_info; ctx->sb.s_fs_info = &ctx->sbi; + ctx->sb.s_user_ns = &init_user_ns; ctx->sb.s_op = &inline_test_sops; #ifdef CONFIG_FS_ENCRYPTION ctx->sb.s_cop = &ext4_cryptops; diff --git a/fs/ext4/namei-test.c b/fs/ext4/namei-test.c index cce3f8d5b36da7..f0192135fcf223 100644 --- a/fs/ext4/namei-test.c +++ b/fs/ext4/namei-test.c @@ -16,6 +16,7 @@ #include #include #include +#include #include #include "ext4.h" @@ -447,6 +448,7 @@ static int namei_test_init(struct kunit *test) ctx->sb.s_time_gran = 1; ctx->sb.s_op = &namei_test_sops; ctx->sb.s_fs_info = &ctx->sbi; + ctx->sb.s_user_ns = &init_user_ns; ctx->sb.s_bdev = &ctx->bdev; #ifdef CONFIG_FS_ENCRYPTION ctx->sb.s_cop = &ext4_cryptops; diff --git a/fs/ext4/xattr-test.c b/fs/ext4/xattr-test.c index 981bf145585121..480bb4ac19ad3c 100644 --- a/fs/ext4/xattr-test.c +++ b/fs/ext4/xattr-test.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include "ext4.h" @@ -495,6 +496,8 @@ static int xattr_test_init(struct kunit *test) sb->s_maxbytes = MAX_LFS_FILESIZE; sb->s_time_gran = 1; sb->s_xattr = ext4_xattr_handlers; + /* i_uid_read()/i_gid_read() map through sb->s_user_ns */ + sb->s_user_ns = &init_user_ns; strscpy(sb->s_id, "ext4_xattr_kunit", sizeof(sb->s_id)); init_rwsem(&sb->s_umount); From eaf10afc0cb3103bf0601e7e227dceea526363eb Mon Sep 17 00:00:00 2001 From: Fredric Cover Date: Sat, 21 Nov 2026 03:09:51 +0000 Subject: [PATCH 1861/2102] smb: client: convert DFS prefix from cache charset on reconnect The DFS referral cache stores paths and target strings in UTF-8 (cache_cp), whereas cifs_sb->prepath must be encoded in the mount's local charset (cifs_sb->local_nls). When reconnecting a DFS link in tree_connect_dfs_target(), dfs_cache_get_tgt_share() returns @prefix in cache_cp, which was passed directly to cifs_update_super_prepath(). On mounts using a non-UTF-8 iocharset such as iso8859-1, this overwrites cifs_sb->prepath with UTF-8 bytes. Subsequent operations then re-encode cifs_sb->prepath to UTF-16LE using cifs_sb->local_nls, corrupting non-ASCII characters on the wire and causing lookups to fail with -ENOENT. Add dfs_cache_local_path() to convert a path from cache_cp to a caller-specified codepage via UTF-16, and use it in a new set_super_prepath_from_cache() helper called by tree_connect_dfs_target() so cifs_sb->prepath stays in cifs_sb->local_nls across reconnects. Tested against Samba with iocharset=utf8 and iocharset=iso8859-1 across multiple smbd restarts. Fixes: c870a8e70e68 ("cifs: handle different charsets in dfs cache") Cc: stable@vger.kernel.org Signed-off-by: Fredric Cover Signed-off-by: Paulo Alcantara --- fs/smb/client/dfs.c | 22 +++++++++++++++++++++- fs/smb/client/dfs_cache.c | 31 +++++++++++++++++++++++++++++++ fs/smb/client/dfs_cache.h | 1 + 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/fs/smb/client/dfs.c b/fs/smb/client/dfs.c index 788cdda9a573ee..ee1503d0217d1c 100644 --- a/fs/smb/client/dfs.c +++ b/fs/smb/client/dfs.c @@ -404,6 +404,26 @@ static int target_share_matches_server(struct TCP_Server_Info *server, char *sha return rc; } + +/* + * @prefix is in the DFS cache charset, the superblock prefix in the mount + * charset. + */ +static int set_super_prepath(struct cifs_sb_info *cifs_sb, const char *prefix) +{ + char *lprefix = NULL; + int rc; + + if (prefix && *prefix) { + lprefix = dfs_cache_local_path(prefix, cifs_sb->local_nls); + if (IS_ERR(lprefix)) + return PTR_ERR(lprefix); + } + rc = cifs_update_super_prepath(cifs_sb, lprefix); + kfree(lprefix); + return rc; +} + static int tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon, struct cifs_sb_info *cifs_sb, @@ -444,7 +464,7 @@ static int tree_connect_dfs_target(const unsigned int xid, rc = ops->tree_connect(xid, tcon->ses, tree, tcon); if (islink && !rc && cifs_sb) - rc = cifs_update_super_prepath(cifs_sb, prefix); + rc = set_super_prepath(cifs_sb, prefix); break; } diff --git a/fs/smb/client/dfs_cache.c b/fs/smb/client/dfs_cache.c index 02864f7acefc25..168f563d5ef64c 100644 --- a/fs/smb/client/dfs_cache.c +++ b/fs/smb/client/dfs_cache.c @@ -105,6 +105,37 @@ char *dfs_cache_canonical_path(const char *path, const struct nls_table *cp, int return npath; } +/** + * dfs_cache_local_path - convert a path from the DFS cache charset + * + * @path: path in the DFS cache charset + * @cp: codepage to convert to + * + * Return the converted path, which the caller must free, or an error pointer. + */ +char *dfs_cache_local_path(const char *path, const struct nls_table *cp) +{ + char *tmp, *npath; + int plen = 0; + + if (!path || !cp || unlikely(!cache_cp)) + return ERR_PTR(-EINVAL); + + if (!strcmp(cp->charset, cache_cp->charset)) { + npath = kstrdup(path, GFP_KERNEL); + return npath ?: ERR_PTR(-ENOMEM); + } + + tmp = (char *)cifs_strndup_to_utf16(path, strlen(path), &plen, + cache_cp, NO_MAP_UNI_RSVD); + if (!tmp) + return ERR_PTR(-ENOMEM); + + npath = cifs_strndup_from_utf16(tmp, plen, true, cp); + kfree(tmp); + return npath ?: ERR_PTR(-ENOMEM); +} + static inline bool cache_entry_expired(const struct cache_entry *ce) { struct timespec64 ts; diff --git a/fs/smb/client/dfs_cache.h b/fs/smb/client/dfs_cache.h index c99dc3546c700f..636eb15543114c 100644 --- a/fs/smb/client/dfs_cache.h +++ b/fs/smb/client/dfs_cache.h @@ -53,6 +53,7 @@ int dfs_cache_get_tgt_share(char *path, char **share, char **prefix); char *dfs_cache_canonical_path(const char *path, const struct nls_table *cp, int remap); +char *dfs_cache_local_path(const char *path, const struct nls_table *cp); int dfs_cache_remount_fs(struct cifs_sb_info *cifs_sb); void dfs_cache_refresh(struct work_struct *work); From fa72921a0c9b1ec3d1bcf07a7003cb239a39705c Mon Sep 17 00:00:00 2001 From: Fredric Cover Date: Sun, 22 Nov 2026 04:58:40 +0000 Subject: [PATCH 1862/2102] smb: client: convert DFS target node name from cache charset on mount parse_dfs_target() converts @path_consumed to the mount charset using dfs_consumed_to_local(), but @ref->node_name from the DFS referral cache is still encoded in UTF-8 (cache_cp). In dfs_parse_target_referral(), passing @ref->node_name directly to cifs_build_devname() and smb3_parse_devname() copies UTF-8 bytes into ctx->UNC and ctx->prepath (and mixes encodings when @prepath from @full_path is also non-empty). On mounts using a non-UTF-8 iocharset such as iso8859-1, subsequent path checks re-encode these strings to UTF-16LE using local_nls, corrupting non-ASCII characters on the wire and causing initial mount to fail with -ENOENT. Convert @ref->node_name from cache_cp to ctx->local_nls with dfs_cache_local_path() before building the device name so ctx->UNC and ctx->prepath stay in the mount charset. Tested against Samba with iocharset=iso8859-1 and iocharset=utf8 for both DFS link referrals with a non-ASCII target subpath and mounts with an additional non-ASCII prepath, including reconnects. Fixes: c870a8e70e68 ("cifs: handle different charsets in dfs cache") Cc: stable@vger.kernel.org Signed-off-by: Fredric Cover Signed-off-by: Paulo Alcantara --- fs/smb/client/dfs.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/fs/smb/client/dfs.c b/fs/smb/client/dfs.c index ee1503d0217d1c..f5d867ab623a17 100644 --- a/fs/smb/client/dfs.c +++ b/fs/smb/client/dfs.c @@ -23,9 +23,10 @@ int dfs_parse_target_referral(const char *full_path, const struct dfs_info3_param *ref, struct smb3_fs_context *ctx) { - int rc; const char *prepath = NULL; + char *node_name = NULL; char *path; + int rc; if (!full_path || !*full_path || !ref || !ctx) return -EINVAL; @@ -40,7 +41,12 @@ int dfs_parse_target_referral(const char *full_path, const struct dfs_info3_para prepath++; } - path = cifs_build_devname(ref->node_name, prepath); + node_name = dfs_cache_local_path(ref->node_name, ctx->local_nls); + if (IS_ERR(node_name)) + return PTR_ERR(node_name); + + path = cifs_build_devname(node_name, prepath); + kfree(node_name); if (IS_ERR(path)) return PTR_ERR(path); From 48c30659359328e95ef83c8afe6c3b0a5f597788 Mon Sep 17 00:00:00 2001 From: ZhangGuoDong Date: Tue, 24 Nov 2026 15:59:26 +0800 Subject: [PATCH 1863/2102] smb: client: fix little-endian values in diagnostic messages Convert to CPU byte order to avoid incorrect debug log on big-endian architectures. Signed-off-by: ZhangGuoDong Reviewed-by: ChenXiaoSong Cc: stable@vger.kernel.org Signed-off-by: Paulo Alcantara --- fs/smb/client/cifsacl.c | 3 ++- fs/smb/client/sess.c | 2 +- fs/smb/client/smb1debug.c | 5 +++-- fs/smb/client/smb1misc.c | 5 +++-- fs/smb/client/smb2ops.c | 5 +++-- fs/smb/client/smb2pdu.c | 5 +++-- fs/smb/client/smb2transport.c | 7 ++++--- fs/smb/client/transport.c | 2 +- 8 files changed, 20 insertions(+), 14 deletions(-) diff --git a/fs/smb/client/cifsacl.c b/fs/smb/client/cifsacl.c index d8f30c35cbe5b4..b23cb226c4d3d6 100644 --- a/fs/smb/client/cifsacl.c +++ b/fs/smb/client/cifsacl.c @@ -1375,7 +1375,8 @@ static int parse_sec_desc(struct cifs_sb_info *cifs_sb, gsidoffset = le32_to_cpu(pntsd->gsidoffset); dacloffset = le32_to_cpu(pntsd->dacloffset); cifs_dbg(NOISY, "revision %d type 0x%x ooffset 0x%x goffset 0x%x sacloffset 0x%x dacloffset 0x%x\n", - pntsd->revision, pntsd->type, osidoffset, gsidoffset, + le16_to_cpu(pntsd->revision), le16_to_cpu(pntsd->type), + osidoffset, gsidoffset, le32_to_cpu(pntsd->sacloffset), dacloffset); fattr->cf_uid = cifs_sb->ctx->linux_uid; fattr->cf_gid = cifs_sb->ctx->linux_gid; diff --git a/fs/smb/client/sess.c b/fs/smb/client/sess.c index fe006e9f2e1025..468bdeae2de61a 100644 --- a/fs/smb/client/sess.c +++ b/fs/smb/client/sess.c @@ -672,7 +672,7 @@ int decode_ntlmssp_challenge(char *bcc_ptr, int blob_len, } if (pblob->MessageType != NtLmChallenge) { cifs_dbg(VFS, "Incorrect message type %d\n", - pblob->MessageType); + le32_to_cpu(pblob->MessageType)); return -EINVAL; } diff --git a/fs/smb/client/smb1debug.c b/fs/smb/client/smb1debug.c index e2d013e751e54b..91b52243d67ad3 100644 --- a/fs/smb/client/smb1debug.c +++ b/fs/smb/client/smb1debug.c @@ -15,8 +15,9 @@ void cifs_dump_detail(void *buf, size_t buf_len, struct TCP_Server_Info *server) struct smb_hdr *smb = buf; cifs_dbg(VFS, "Cmd: %d Err: 0x%x Flags: 0x%x Flgs2: 0x%x Mid: %d Pid: %d Wct: %d\n", - smb->Command, smb->Status.CifsError, smb->Flags, - smb->Flags2, smb->Mid, smb->Pid, smb->WordCount); + smb->Command, le32_to_cpu(smb->Status.CifsError), + smb->Flags, le16_to_cpu(smb->Flags2), le16_to_cpu(smb->Mid), + le16_to_cpu(smb->Pid), smb->WordCount); if (!server->ops->check_message(buf, buf_len, server->total_read, server)) { cifs_dbg(VFS, "smb buf %p len %u\n", smb, server->ops->calc_smb_size(smb)); diff --git a/fs/smb/client/smb1misc.c b/fs/smb/client/smb1misc.c index cdfbbff24b72ad..ef6186b1c62f8d 100644 --- a/fs/smb/client/smb1misc.c +++ b/fs/smb/client/smb1misc.c @@ -95,14 +95,15 @@ is_valid_oplock_break(char *buffer, struct TCP_Server_Info *srv) pnotify = (struct file_notify_information *) ((char *)&pSMBr->hdr.Protocol + data_offset); cifs_dbg(FYI, "dnotify on %s Action: 0x%x\n", - pnotify->FileName, pnotify->Action); + pnotify->FileName, + le32_to_cpu(pnotify->Action)); /* cifs_dump_mem("Rcvd notify Data: ",buf, sizeof(struct smb_hdr)+60); */ return true; } if (pSMBr->hdr.Status.CifsError) { cifs_dbg(FYI, "notify err 0x%x\n", - pSMBr->hdr.Status.CifsError); + le32_to_cpu(pSMBr->hdr.Status.CifsError)); return true; } return false; diff --git a/fs/smb/client/smb2ops.c b/fs/smb/client/smb2ops.c index 298f549bd7ed37..9c16839576e907 100644 --- a/fs/smb/client/smb2ops.c +++ b/fs/smb/client/smb2ops.c @@ -454,8 +454,9 @@ smb2_dump_detail(void *buf, size_t buf_len, struct TCP_Server_Info *server) struct smb2_hdr *shdr = (struct smb2_hdr *)buf; cifs_server_dbg(VFS, "Cmd: %d Err: 0x%x Flags: 0x%x Mid: %llu Pid: %d\n", - shdr->Command, shdr->Status, shdr->Flags, shdr->MessageId, - shdr->Id.SyncId.ProcessId); + le16_to_cpu(shdr->Command), le32_to_cpu(shdr->Status), + le32_to_cpu(shdr->Flags), le64_to_cpu(shdr->MessageId), + le32_to_cpu(shdr->Id.SyncId.ProcessId)); if (!server->ops->check_message(buf, buf_len, server->total_read, server)) { cifs_server_dbg(VFS, "smb buf %p len %u\n", buf, server->ops->calc_smb_size(buf)); diff --git a/fs/smb/client/smb2pdu.c b/fs/smb/client/smb2pdu.c index 7b7d25364e2072..2b2b4dff107b70 100644 --- a/fs/smb/client/smb2pdu.c +++ b/fs/smb/client/smb2pdu.c @@ -278,7 +278,7 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon, if (smb2_command != SMB2_TREE_DISCONNECT) { spin_unlock(&tcon->tc_lock); cifs_tcon_dbg(FYI, "can not send cmd %d while umounting\n", - smb2_command); + le16_to_cpu(smb2_command)); return -ENODEV; } } @@ -1294,7 +1294,8 @@ SMB2_negotiate(const unsigned int xid, goto neg_exit; } - cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode); + cifs_dbg(FYI, "%s: security mode 0x%x\n", __func__, + le16_to_cpu(rsp->SecurityMode)); switch (dialect) { case SMB20_PROT_ID: diff --git a/fs/smb/client/smb2transport.c b/fs/smb/client/smb2transport.c index c63d66b01bda2d..7c4b5faf9de65d 100644 --- a/fs/smb/client/smb2transport.c +++ b/fs/smb/client/smb2transport.c @@ -380,7 +380,7 @@ generate_smb3signingkey(struct cifs_ses *ses, */ cifs_dbg(VFS, "Session Id %*ph\n", (int)sizeof(ses->Suid), &ses->Suid); - cifs_dbg(VFS, "Cipher type %d\n", server->cipher_type); + cifs_dbg(VFS, "Cipher type %d\n", le16_to_cpu(server->cipher_type)); cifs_dbg(VFS, "Session Key %*ph\n", (int)ses->auth_key.len, ses->auth_key.response); cifs_dbg(VFS, "Signing Key %*ph\n", @@ -570,7 +570,7 @@ smb2_verify_signature(struct smb_rqst *rqst, struct TCP_Server_Info *server) /* Do not need to verify session setups with signature "BSRSPYL " */ if (memcmp(shdr->Signature, "BSRSPYL ", 8) == 0) cifs_dbg(FYI, "dummy signature received for smb command 0x%x\n", - shdr->Command); + le16_to_cpu(shdr->Command)); /* * Save off the original signature so we can modify the smb and check @@ -588,7 +588,8 @@ smb2_verify_signature(struct smb_rqst *rqst, struct TCP_Server_Info *server) if (crypto_memneq(server_response_sig, shdr->Signature, SMB2_SIGNATURE_SIZE)) { cifs_dbg(VFS, "sign fail cmd 0x%x message id 0x%llx\n", - shdr->Command, shdr->MessageId); + le16_to_cpu(shdr->Command), + le64_to_cpu(shdr->MessageId)); return -EACCES; } else return 0; diff --git a/fs/smb/client/transport.c b/fs/smb/client/transport.c index 375b821ab3eacd..ea1f4fe42ee5e0 100644 --- a/fs/smb/client/transport.c +++ b/fs/smb/client/transport.c @@ -101,7 +101,7 @@ void __release_mid(struct TCP_Server_Info *server, struct mid_q_entry *midEntry) midEntry->when_sent, midEntry->when_received); if (cifsFYI & CIFS_TIMER) { pr_debug("slow rsp: cmd %d mid %llu A: 0x%lx S: 0x%lx R: 0x%lx\n", - midEntry->command, midEntry->mid, + smb_cmd, midEntry->mid, now - midEntry->when_alloc, now - midEntry->when_sent, now - midEntry->when_received); From 3b709e8700c7c3253fcfe7f94f1e967614d8a354 Mon Sep 17 00:00:00 2001 From: ZhangGuoDong Date: Tue, 24 Nov 2026 15:59:27 +0800 Subject: [PATCH 1864/2102] smb: client: fix file name conversion on big-endian systems Use CPU byte order for temporary UTF-16 buffers to avoid incorrect file name conversion on big-endian architectures. Fixes: b29103076bec ("Fix to convert SURROGATE PAIR") Cc: stable@vger.kernel.org Signed-off-by: ZhangGuoDong Reviewed-by: ChenXiaoSong Signed-off-by: Paulo Alcantara --- fs/smb/client/cifs_unicode.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/fs/smb/client/cifs_unicode.c b/fs/smb/client/cifs_unicode.c index 4a8a591f4bcac7..264595633b1e28 100644 --- a/fs/smb/client/cifs_unicode.c +++ b/fs/smb/client/cifs_unicode.c @@ -92,7 +92,7 @@ convert_sfm_char(const __u16 src_char, char *target) /* * cifs_mapchar - convert a host-endian char to proper char in codepage * @target - where converted character should be copied - * @src_char - 2 byte host-endian source character + * @from - 2 byte host-endian source character * @cp - codepage to which character should be converted * @map_type - How should the 7 NTFS/SMB reserved characters be mapped to UCS2? * @@ -126,7 +126,7 @@ cifs_mapchar(char *target, const __u16 *from, const struct nls_table *cp, /* convert SURROGATE_PAIR and IVS */ if (strcmp(cp->charset, "utf8")) goto unknown; - len = utf16s_to_utf8s(from, 3, UTF16_LITTLE_ENDIAN, target, 6); + len = utf16s_to_utf8s(from, 3, UTF16_HOST_ENDIAN, target, 6); if (len <= 0) goto unknown; return len; @@ -518,7 +518,7 @@ cifsConvertToUTF16(__le16 *target, const char *source, int srclen, } else goto unknown; ret = utf8s_to_utf16s(source + i, charlen, - UTF16_LITTLE_ENDIAN, + UTF16_HOST_ENDIAN, wchar_to, 6); if (ret < 0) goto unknown; From 61c581ea62ee3dcf348b5ba30448b993cf1c1c74 Mon Sep 17 00:00:00 2001 From: Elkin Cruz Date: Wed, 25 Nov 2026 21:00:25 +0000 Subject: [PATCH 1865/2102] smb: client: unlock reconnect_mutex before putting session on terminate In smb2_reconnect_server(), when server->terminate is set, the early exit path calls cifs_put_tcp_session(server, true) while still holding pserver->reconnect_mutex and unlocks pserver->reconnect_mutex afterwards. Dropping the last session reference can free server (which equals pserver for primary channels), causing mutex_unlock() to touch freed memory; the normal done: label at the end of the same function explicitly unlocks reconnect_mutex before calling cifs_put_tcp_session(). Unlock pserver->reconnect_mutex before calling cifs_put_tcp_session() in the server->terminate branch as well. Fixes: ee1d21794e55 ("cifs: handle when server stops supporting multichannel") Cc: stable@vger.kernel.org Signed-off-by: Elkin Cruz Signed-off-by: Paulo Alcantara --- fs/smb/client/smb2pdu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/smb/client/smb2pdu.c b/fs/smb/client/smb2pdu.c index 2b2b4dff107b70..fd7499c7966490 100644 --- a/fs/smb/client/smb2pdu.c +++ b/fs/smb/client/smb2pdu.c @@ -4391,8 +4391,8 @@ void smb2_reconnect_server(struct work_struct *work) /* if the server is marked for termination, drop the ref count here */ if (server->terminate) { - cifs_put_tcp_session(server, true); mutex_unlock(&pserver->reconnect_mutex); + cifs_put_tcp_session(server, true); return; } From 39738c813c716c64a55767bfbe30da13f17e6dc3 Mon Sep 17 00:00:00 2001 From: Suyuan Wang Date: Thu, 19 Nov 2026 21:39:02 +0000 Subject: [PATCH 1866/2102] tipc: restore write readiness when a socket's group goes away tipc_group_create() sets tsk->group_is_open to false, and tipc_poll() only reports EPOLLOUT for a socket in TIPC_OPEN state when that flag is true. Commit 1b22bcad7e39 ("tipc: correct initial value for group congestion flag") made sure the flag is true for sockets that never join a group, since otherwise "SOCK_RDM/DGRAM sockets sending datagrams never receive POLLOUT". The flag is not set back when the group goes away again, though: - tipc_group_create() clears the flag and then fails when the topology subscription cannot be created, for example when TIPC_MAX_SUBSCR subscriptions exist already; - tipc_sk_join() deletes the new group when tipc_sk_publish() fails, for example when the node's publication limit is reached; - tipc_sk_leave() deletes the group while the flag may still be false, e.g. because of group congestion, or because the group has no other members yet. In all three cases the socket is back to an ordinary RDM/DGRAM socket, but poll() never reports EPOLLOUT for it again. Before commit 60c253069632 ("tipc: fix race between poll() and setsockopt()"), tipc_poll() also reported EPOLLOUT when tsk->group was NULL, so deleting the group was enough; since then the flag has to be reset. Set tsk->group_is_open to true in these three places, as it is for a socket that never had a group, and call sk_write_space() so that a task already waiting for EPOLLOUT is woken up, as tipc_sk_filter_rcv() does when a group becomes open again. Found with a static analysis tool and checked by hand. Fixes: 60c253069632 ("tipc: fix race between poll() and setsockopt()") Cc: stable@vger.kernel.org Co-developed-by: Kaixuan Li Signed-off-by: Kaixuan Li Signed-off-by: Suyuan Wang Reviewed-by: Tung Nguyen Link: https://patch.msgid.link/20261119-tipc-group-open-v1-1-cb725145da51@gmail.com Signed-off-by: Willem de Bruijn --- net/tipc/socket.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/net/tipc/socket.c b/net/tipc/socket.c index 65cc0c4964b31f..26771a98dc7a6f 100644 --- a/net/tipc/socket.c +++ b/net/tipc/socket.c @@ -3096,8 +3096,12 @@ static int tipc_sk_join(struct tipc_sock *tsk, struct tipc_group_req *mreq) if (grp) return -EACCES; grp = tipc_group_create(net, tsk->portid, mreq, &tsk->group_is_open); - if (!grp) + if (!grp) { + /* tipc_group_create() may have cleared it before failing */ + tsk->group_is_open = true; + tsk->sk.sk_write_space(&tsk->sk); return -ENOMEM; + } tsk->group = grp; msg_set_lookup_scope(hdr, mreq->scope); msg_set_nametype(hdr, mreq->type); @@ -3109,6 +3113,8 @@ static int tipc_sk_join(struct tipc_sock *tsk, struct tipc_group_req *mreq) if (rc) { tipc_group_delete(net, grp); tsk->group = NULL; + tsk->group_is_open = true; + tsk->sk.sk_write_space(&tsk->sk); return rc; } /* Eliminate any risk that a broadcast overtakes sent JOINs */ @@ -3132,7 +3138,9 @@ static int tipc_sk_leave(struct tipc_sock *tsk) ua.scope = scope; tipc_group_delete(net, grp); tsk->group = NULL; + tsk->group_is_open = true; tipc_sk_withdraw(tsk, &ua); + tsk->sk.sk_write_space(&tsk->sk); return 0; } From 58f419bfa4c3a6797246a7c4e53a535ee34372ae Mon Sep 17 00:00:00 2001 From: Eric Dumazet Date: Mon, 23 Nov 2026 13:44:58 +0100 Subject: [PATCH 1867/2102] ipv6: mcast: do not pass uninitialized bytes to dev_mc_add() igmp6_group_added() and igmp6_group_dropped() build a link-layer multicast address in an on-stack buffer with ndisc_mc_map(), which fills a number of bytes depending on dev->type. dev_mc_add() and dev_mc_del() then use dev->addr_len bytes of it. Since IPv6 multicast joins and leaves no longer hold RTNL, dev->type and dev->addr_len can change between the two steps, for instance with TUNSETLINK, or when bonding or team change their type. If addr_len grows (eg ARPHRD_ETHER -> ARPHRD_IP6GRE), dev_mc_add() copies uninitialized stack bytes into a netdev_hw_addr, which can later be dumped to user space by /proc/net/dev_mcast and RTM_GETMULTICAST. Zero the buffers. Found by Sashiko AI review of a tun patch, by code inspection only. Kernels built with CONFIG_INIT_STACK_ALL_ZERO=y are not affected. Fixes: 1767bb2d47b7 ("ipv6: mcast: Don't hold RTNL for IPV6_ADD_MEMBERSHIP and MCAST_JOIN_GROUP.") Link: https://lore.kernel.org/netdev/179512665919.3136.5931555157250030152@kernel.org/ Cc: Kuniyuki Iwashima Signed-off-by: Eric Dumazet Reviewed-by: Hangbin Liu Reviewed-by: Ido Schimmel Link: https://patch.msgid.link/20261123124458.205233-1-edumazet@kernel.org Signed-off-by: Willem de Bruijn --- net/ipv6/mcast.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/net/ipv6/mcast.c b/net/ipv6/mcast.c index ecef55f261890c..bce7287ae709f1 100644 --- a/net/ipv6/mcast.c +++ b/net/ipv6/mcast.c @@ -684,7 +684,10 @@ bool inet6_mc_check(const struct sock *sk, const struct in6_addr *mc_addr, static void igmp6_group_added(struct ifmcaddr6 *mc) { struct net_device *dev = mc->idev->dev; - char buf[MAX_ADDR_LEN]; + /* RTNL might not be held: dev->type and dev->addr_len can change. + * Make sure dev_mc_{add|del}() do not use uninitialized bytes. + */ + char buf[MAX_ADDR_LEN] = {}; mc_assert_locked(mc->idev); @@ -720,7 +723,10 @@ static void igmp6_group_added(struct ifmcaddr6 *mc) static void igmp6_group_dropped(struct ifmcaddr6 *mc) { struct net_device *dev = mc->idev->dev; - char buf[MAX_ADDR_LEN]; + /* RTNL might not be held: dev->type and dev->addr_len can change. + * Make sure dev_mc_{add|del}() do not use uninitialized bytes. + */ + char buf[MAX_ADDR_LEN] = {}; mc_assert_locked(mc->idev); From bf57105b00e32d37b666c029c8c6b8708391da20 Mon Sep 17 00:00:00 2001 From: Dave Airlie Date: Mon, 23 Nov 2026 10:25:26 +1000 Subject: [PATCH 1868/2102] drm/nouveau/devinit/gf100-: fix double vbios init checks The initial fix from 2017 wasn't updated for modern nouveau devinit disable paths. Fix that and just check if display exists instead. (two other people reproduced this patch, so let's commit it). Fixes: 2139cb633d48 ("drm/nouveau/devinit/gf100-: try to avoid double-running vbios scripts") Tested-by: Francis Laniel Reviewed-by: Francesco Magazzu Signed-off-by: Dave Airlie Link: https://patch.msgid.link/20261123-nouveau-fix-disp-v1-1-ebdc525287ce@redhat.com --- drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c b/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c index 186e09ea0cb10a..b256404c2454ff 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c @@ -107,12 +107,12 @@ gf100_devinit_preinit(struct nvkm_devinit *base) * VBIOS multiple times may have detrimental effects. */ if (base->post) { - u64 disable = nvkm_devinit_disable(base); + nvkm_devinit_disable(base); /* magic to detect whether or not x86 vbios code has * executed the devinit scripts to initialise the * board. only works if there's a display engine. */ - if (!(disable & (1ULL << NVKM_ENGINE_DISP))) { + if (device->disp) { if (nvkm_rdvgac(device, 0, 0x00) || nvkm_rdvgac(device, 0, 0x1a)) { base->post = false; From cdf84b850584574fc81bd80990d3bf1cf81b6a00 Mon Sep 17 00:00:00 2001 From: Xu Rao Date: Fri, 20 Nov 2026 11:38:24 +0800 Subject: [PATCH 1869/2102] vhost/net: Fix receive queue test in busy poll MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sock_has_rx_data() returns a positive value when receive data is available. For sockets without a peek_len() callback, however, its fallback returns skb_queue_empty(), which has the opposite meaning. An AF_PACKET SOCK_RAW socket is accepted by get_raw_socket() as a vhost-net backend, and its socket operations do not provide peek_len(). With busy polling enabled for this backend, an empty receive queue is treated as ready and a nonempty queue as not ready. This can make vhost_net_busy_poll() stop polling prematurely or fail to stop for queued receive data, and invert its receive-side scheduling decision. TUN and TAP backends provide peek_len() and are unaffected. Negate skb_queue_empty() so the fallback matches the callback and the readiness checks in vhost_net_busy_poll(). The issue was found during AI-assisted code review. The helper's incorrect result was confirmed on x86_64 running 6.6.0-amd64-desktop using a temporary diagnostic module containing the original and fixed helpers. An AF_PACKET SOCK_RAW socket, without PACKET_RX_RING, was bound to loopback in a private network namespace. Across three cycles of sending and receiving a 60-byte frame, the original helper returned 1 for an empty queue and 0 for a queued frame. The fixed helper returned 0 and 1 respectively, matching socket readability in all nine checks. This tests helper copies on real sockets, not the running vhost-net busy-poll path; the vhost-net module was not replaced. The patched drivers/vhost/net.o was also build-tested on the net tree with x86_64 GCC 12.3 and W=1 under allmodconfig and allyesconfig. No end-to-end vhost tests or kernel selftests were run. Fixes: 1576d9860599 ("tun: switch to use skb array for tx") Cc: stable@vger.kernel.org Signed-off-by: Xu Rao Acked-by: Eugenio Pérez Link: https://patch.msgid.link/1B3A1B72438119BC+20261120033824.681219-1-raoxu@uniontech.com Signed-off-by: Willem de Bruijn --- drivers/vhost/net.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/vhost/net.c b/drivers/vhost/net.c index 4570a4ffbab2c5..10ed2d55ff0723 100644 --- a/drivers/vhost/net.c +++ b/drivers/vhost/net.c @@ -538,7 +538,7 @@ static int sock_has_rx_data(struct socket *sock) if (sock->ops->peek_len) return sock->ops->peek_len(sock); - return skb_queue_empty(&sock->sk->sk_receive_queue); + return !skb_queue_empty(&sock->sk->sk_receive_queue); } static void vhost_net_busy_poll_try_queue(struct vhost_net *net, From 1ab3fb564f20b78615a6d88b8c90da292f29e227 Mon Sep 17 00:00:00 2001 From: Kuniyuki Iwashima Date: Sat, 21 Nov 2026 20:35:27 +0000 Subject: [PATCH 1870/2102] tcp: Don't clear saddr before ->put_port(). When CGROUP_INET4_POST_BIND or CGROUP_INET6_POST_BIND prog fails, __inet_bind() / __inet6_bind() calls sk->sk_prot->put_port(). For TCP, __inet_put_port() calls inet_bhashfn_portaddr() to get the corresponding bhash2 bucket. inet_bhashfn_portaddr() requires saddr, but it is cleared before __inet_put_port(), leading to bhash2 lock mismatch. This triggers list corruption or use-after-free by a conccurent thread touching the same bhash2 bucket, e.g. tcp_diag_dump() with TCPF_BOUND_INACTIVE. [0] Let's clear saddr after calling sk->sk_prot->put_port(). [0]: BUG: KASAN: slab-use-after-free in tcp_diag_dump (net/ipv4/tcp_diag.c:415) Read of size 8 at addr ffff88810ae0e7a0 by task a/1007 CPU: 10 UID: 0 PID: 1007 Comm: a Not tainted 7.4.0-rc3-00456-gd5b89d55a322 #295 PREEMPT(lazy) Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-debian-1.17.0-1 04/01/2014 Call Trace: dump_stack_lvl (lib/dump_stack.c:120) print_address_description (mm/kasan/report.c:378) print_report (mm/kasan/report.c:482) kasan_report (mm/kasan/report.c:595) sock_recvmsg (net/socket.c:1154) __sys_recvfrom (net/socket.c:2333) __x64_sys_recvfrom (net/socket.c:2348 net/socket.c:2344 net/socket.c:2344) do_syscall_64 (arch/x86/entry/syscall_64.c:61 arch/x86/entry/syscall_64.c:89) entry_SYSCALL_64_after_hwframe (arch/x86/entry/entry_64.S:121) RIP: 0033:0x7f2f268f8e92 Code: 08 0f 85 91 41 ff ff 49 89 fb 48 89 f0 48 89 d7 48 89 ce 4c 89 c2 4d 89 ca 4c 8b 44 24 08 4c 8b 4c 24 10 4c 89 5c 24 08 0f 05 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 00 f3 0f 1e fa 55 bf 01 00 RSP: 002b:00007f2f26874d28 EFLAGS: 00000246 ORIG_RAX: 000000000000002d RAX: ffffffffffffffda RBX: 00007f2f26879ce4 RCX: 00007f2f268f8e92 RDX: 0000000000004000 RSI: 00007f2f26874db0 RDI: 00000000000007d7 RBP: 00007f2f26874d50 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000021 R13: 00007ffcbb216e70 R14: 0000000000000000 R15: 00007ffcbb216f77 Allocated by task 1009: kasan_save_track (mm/kasan/common.c:57 mm/kasan/common.c:79) __kasan_slab_alloc (mm/kasan/common.c:354 mm/kasan/common.c:380) kmem_cache_alloc_noprof (./include/linux/kasan.h:257 mm/slub.c:4720 mm/slub.c:5033 mm/slub.c:5047) inet_bind2_bucket_create (net/ipv4/inet_hashtables.c:162) inet_csk_get_port (net/ipv4/inet_connection_sock.c:573) __inet_bind (net/ipv4/af_inet.c:544) inet_bind_sk (net/ipv4/af_inet.c:470) __sys_bind (net/socket.c:1947 net/socket.c:1978) __x64_sys_bind (net/socket.c:1983 net/socket.c:1981 net/socket.c:1981) do_syscall_64 (arch/x86/entry/syscall_64.c:61 arch/x86/entry/syscall_64.c:89) entry_SYSCALL_64_after_hwframe (arch/x86/entry/entry_64.S:121) Freed by task 1009: kasan_save_track (mm/kasan/common.c:57 mm/kasan/common.c:79) kasan_save_free_info (mm/kasan/generic.c:599) __kasan_slab_free (mm/kasan/common.c:267 mm/kasan/common.c:299) kmem_cache_free (./include/linux/kasan.h:239 mm/slub.c:2780 mm/slub.c:6637 mm/slub.c:6764) inet_put_port (net/ipv4/inet_hashtables.c:178) __inet_bind (net/ipv4/af_inet.c:554) inet_bind_sk (net/ipv4/af_inet.c:470) __sys_bind (net/socket.c:1947 net/socket.c:1978) __x64_sys_bind (net/socket.c:1983 net/socket.c:1981 net/socket.c:1981) do_syscall_64 (arch/x86/entry/syscall_64.c:61 arch/x86/entry/syscall_64.c:89) entry_SYSCALL_64_after_hwframe (arch/x86/entry/entry_64.S:121) The buggy address belongs to the object at ffff88810ae0e780 which belongs to the cache tcp_bind2_bucket of size 80 Fixes: 28044fc1d495 ("net: Add a bhash2 table hashed by port and address") Signed-off-by: Kuniyuki Iwashima Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261121203537.341320-1-kuniyu@google.com Signed-off-by: Willem de Bruijn --- net/ipv4/af_inet.c | 2 +- net/ipv6/af_inet6.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/net/ipv4/af_inet.c b/net/ipv4/af_inet.c index 8822bae439f88d..5d03a9149b40f9 100644 --- a/net/ipv4/af_inet.c +++ b/net/ipv4/af_inet.c @@ -549,9 +549,9 @@ int __inet_bind(struct sock *sk, struct sockaddr_unsized *uaddr, int addr_len, if (!(flags & BIND_FROM_BPF)) { err = BPF_CGROUP_RUN_PROG_INET4_POST_BIND(sk); if (err) { - inet->inet_saddr = inet->inet_rcv_saddr = 0; if (sk->sk_prot->put_port) sk->sk_prot->put_port(sk); + inet->inet_saddr = inet->inet_rcv_saddr = 0; goto out_release_sock; } } diff --git a/net/ipv6/af_inet6.c b/net/ipv6/af_inet6.c index a9b8b4b42a1af7..b85125c3f14bdf 100644 --- a/net/ipv6/af_inet6.c +++ b/net/ipv6/af_inet6.c @@ -398,10 +398,10 @@ int __inet6_bind(struct sock *sk, struct sockaddr_unsized *uaddr, int addr_len, if (!(flags & BIND_FROM_BPF)) { err = BPF_CGROUP_RUN_PROG_INET6_POST_BIND(sk); if (err) { - sk->sk_ipv6only = saved_ipv6only; - inet_reset_saddr(sk); if (sk->sk_prot->put_port) sk->sk_prot->put_port(sk); + sk->sk_ipv6only = saved_ipv6only; + inet_reset_saddr(sk); goto out; } } From 2acad73b68ca1f5acc24ef1e20c3f6e303438204 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:28:52 +0000 Subject: [PATCH 1871/2102] bpf: Do not trust pointers in flexible arrays The verifier does not know how many elements a flexible array of a kernel object has. Mark pointers that are loaded from one as untrusted. Ignore the __rcu tag of such pointers. Fixes: 9c5f8a1008a1 ("bpf: Support variable length array in tracing programs") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-2-alexei.starovoitov@gmail.com --- kernel/bpf/btf.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c index 49fcd32d418a9c..f5ecac4abff4b5 100644 --- a/kernel/bpf/btf.c +++ b/kernel/bpf/btf.c @@ -8127,6 +8127,10 @@ int btf_struct_access(struct bpf_verifier_log *log, */ *next_btf_id = id; *flag = tmp_flag; + /* nothing tells where a flexible array ends */ + t = btf_type_skip_modifiers(btf, reg->btf_id, NULL); + if (min_off + size > t->size) + *flag = (tmp_flag & ~MEM_RCU) | PTR_UNTRUSTED; ret = PTR_TO_BTF_ID; goto check_variable_offset; case WALK_PTR_UNTRUSTED: From e74ff9b13b44c4e87fd01cd87adfcc76a0fdb157 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:28:53 +0000 Subject: [PATCH 1872/2102] bpf: Look at the type of a program next to expected_attach_type expected_attach_type of a struct_ops program is the index of the member. sock_ops, cgroup_device and cgroup_sysctl programs load with almost any value. The kernel compares it with attach types of other programs: - Members 25, 26, 27, 43 and 58 can read ctx[nr_args], as fexit does. The slot has stale stack. - The trampoline of members 58 and 61 clears that slot, as for fsession. It is the last argument when the member returns void. - Pointer arguments of member 23 get the rules of raw tracepoints. - Members 59, 60 and 61 cannot be loaded. - The release of a cgroup looks for the LSM shim of a program that says BPF_LSM_CGROUP and has no attach_btf. Look at the type of the program too. Fixes: 27ae7997a661 ("bpf: Introduce BPF_PROG_TYPE_STRUCT_OPS") Fixes: 69fd337a975c ("bpf: per-cgroup lsm flavor") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-3-alexei.starovoitov@gmail.com --- include/linux/bpf.h | 3 +++ kernel/bpf/btf.c | 5 +++-- kernel/bpf/cgroup.c | 4 ++-- kernel/bpf/syscall.c | 3 ++- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/include/linux/bpf.h b/include/linux/bpf.h index 1dd9db16f32403..a1c96ca14afdcb 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -2517,6 +2517,9 @@ static inline int bpf_fsession_cnt(struct bpf_tramp_nodes *nodes) struct bpf_tramp_nodes fentries = nodes[BPF_TRAMP_FENTRY]; int cnt = 0; + if (is_struct_ops_tramp(&fentries)) + return 0; + for (int i = 0; i < nodes[BPF_TRAMP_FENTRY].nr_nodes; i++) { if (fentries.nodes[i]->link->prog->expected_attach_type == BPF_TRACE_FSESSION) cnt++; diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c index f5ecac4abff4b5..7c83f3bdfcf1f1 100644 --- a/kernel/bpf/btf.c +++ b/kernel/bpf/btf.c @@ -7485,7 +7485,8 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type, nr_args--; } - if (arg > nr_args) { + /* expected_attach_type of struct_ops is the index of the member */ + if (arg > nr_args || (arg == nr_args && prog->type == BPF_PROG_TYPE_STRUCT_OPS)) { bpf_log(log, "func '%s' doesn't have %d-th argument\n", tname, arg + 1); return false; @@ -7622,7 +7623,7 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type, if (btf_param_match_suffix(btf, &args[arg], "__nullable")) info->reg_type |= PTR_MAYBE_NULL; - if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { + if (prog->aux->attach_btf_trace) { struct btf *btf = prog->aux->attach_btf; const struct btf_type *t; const char *tname; diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index f195d5fcae6c6c..88b49238931af3 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -399,7 +399,7 @@ static void bpf_cgroup_link_auto_detach(struct bpf_cgroup_link *link) return; } - if (link->link.prog->expected_attach_type == BPF_LSM_CGROUP) + if (link->link.prog->type == BPF_PROG_TYPE_LSM) bpf_trampoline_unlink_cgroup_shim(link->link.prog); cgroup_put(link->cgroup); link->cgroup = NULL; @@ -509,7 +509,7 @@ static void cgroup_bpf_release(struct work_struct *work) hlist_for_each_entry_safe(pl, pltmp, progs, node) { hlist_del(&pl->node); if (pl->prog) { - if (pl->prog->expected_attach_type == BPF_LSM_CGROUP) + if (pl->prog->type == BPF_PROG_TYPE_LSM) bpf_trampoline_unlink_cgroup_shim(pl->prog); bpf_prog_put(pl->prog); } diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c index 60c4d84b9aba6f..48ed0944f31d52 100644 --- a/kernel/bpf/syscall.c +++ b/kernel/bpf/syscall.c @@ -3025,7 +3025,8 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at if (is_perfmon_prog_type(type) && !bpf_token_capable(token, CAP_PERFMON)) goto put_token; - multi_func = is_tracing_multi(attr->expected_attach_type); + multi_func = type != BPF_PROG_TYPE_STRUCT_OPS && + is_tracing_multi(attr->expected_attach_type); /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog * or btf, we need to check which one it is From 7ee82af6e463207683b478167379c3d39a597fa3 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:28:54 +0000 Subject: [PATCH 1873/2102] bpf: Do not take bpf_get_retval() of struct bpf_tcp_ops for an errno The verifier gives the result of bpf_get_retval() the range [-4095, 0]. In timeout_init and rwnd_init of struct bpf_tcp_ops it is what the previous program returned, any int. Do not refine the range for struct_ops programs. Fixes: 5ac77ae32940 ("bpf: tcp: Support selected sock_ops callbacks as struct_ops") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-4-alexei.starovoitov@gmail.com --- kernel/bpf/verifier.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 01a74e166e89ff..311c9f19b781fe 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -12305,6 +12305,10 @@ static int do_refine_retval_range(struct bpf_verifier_env *env, env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) break; + /* It is what the previous struct bpf_tcp_ops returned, any int */ + if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) + break; + if (prog_type == BPF_PROG_TYPE_LSM && env->prog->expected_attach_type == BPF_LSM_CGROUP) { if (!env->prog->aux->attach_func_proto->type) From 1139c7d8ffcd941d4860a75ef37eb1ffd15b4f87 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:28:55 +0000 Subject: [PATCH 1874/2102] bpf: Do not allow bpf_d_path() by an id of another BTF For a program that is attached to a program attach_btf_id is an id in the BTF of the target. bpf_d_path_allowed() looks for it in a list of kernel functions, it can match by chance. Do not look at the list when there is a target program. Fixes: 6e22ab9da793 ("bpf: Add d_path helper") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-5-alexei.starovoitov@gmail.com --- kernel/trace/bpf_trace.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c index 1f35a18ef39961..bb79669d1cf408 100644 --- a/kernel/trace/bpf_trace.c +++ b/kernel/trace/bpf_trace.c @@ -980,6 +980,10 @@ BTF_SET_END(btf_allowlist_d_path_fentry) static bool bpf_d_path_allowed(const struct bpf_prog *prog) { + /* attach_btf_id is a function of the target program */ + if (prog->aux->dst_prog) + return false; + if (prog->type == BPF_PROG_TYPE_TRACING && prog->expected_attach_type == BPF_TRACE_ITER) return true; From f44d0e6a1d684167d4fc58d313077ba21ad6f301 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:28:56 +0000 Subject: [PATCH 1875/2102] bpf: Check that an extension fits the hook of its target An extension runs in the hook of its target, and the checks for the hook do not see it. Tracing, LSM and struct_ops programs are checked against the BTF of their hook. An extension takes the type of its target, but it has no attach_btf and no st_ops, and attach_btf_id and the prototype are those of the function that it replaces: - tp_btf: it can read more arguments than the tracepoint has. - LSM: the range of bpf_get_retval() and bpf_set_retval(), and the helpers that only some hooks have, are looked up by a wrong id. - tp_btf and struct_ops: the load can oops. fentry, fexit, fsession and iterators cannot be extended already. Refuse the rest. freplace of global functions of tp_btf, fmod_ret and LSM programs goes away. Targets of other types load with any expected_attach_type. Do not take their extension for tp_btf or for an iterator. Some properties of a program are looked at when it is attached or run. Nobody looks at those of an extension: - bpf_get_local_storage() returns the storage of the attached program, the extension is verified against its own map. - bpf_override_return() needs a function that allows error injection. - skb->cb is saved, cleared and restored only for programs that access it. Ask for the storage map of the target, at load and at attach. Refuse the attach when the target does not call bpf_override_return() itself, or does not access skb->cb. A tail call counts as an access to skb->cb. Fixes: be8704ff07d2 ("bpf: Introduce dynamic program extensions") Signed-off-by: Alexei Starovoitov Acked-by: Anton Protopopov Link: https://patch.msgid.link/20261125032938.670542-6-alexei.starovoitov@gmail.com --- kernel/bpf/syscall.c | 18 ++++++++++++++++++ kernel/bpf/verifier.c | 38 +++++++++++++++++++++++++------------- 2 files changed, 43 insertions(+), 13 deletions(-) diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c index 48ed0944f31d52..3f2bc772e297ed 100644 --- a/kernel/bpf/syscall.c +++ b/kernel/bpf/syscall.c @@ -3847,6 +3847,24 @@ static int bpf_tracing_prog_attach(struct bpf_prog *prog, err = -EINVAL; goto out_unlock; } + /* Where the return can be overridden is checked for the target only */ + if (prog->type == BPF_PROG_TYPE_EXT && + prog->kprobe_override && !tgt_prog->kprobe_override) { + err = -EINVAL; + goto out_unlock; + } + /* bpf_prog_run_save_cb() and bpf_prog_run_clear_cb() look at the target only */ + if (prog->type == BPF_PROG_TYPE_EXT && + (tgt_prog->type == BPF_PROG_TYPE_SOCKET_FILTER || + tgt_prog->type == BPF_PROG_TYPE_CGROUP_SKB || + tgt_prog->type == BPF_PROG_TYPE_LWT_IN || + tgt_prog->type == BPF_PROG_TYPE_LWT_OUT || + tgt_prog->type == BPF_PROG_TYPE_LWT_XMIT || + tgt_prog->type == BPF_PROG_TYPE_LWT_SEG6LOCAL) && + prog->cb_access && !tgt_prog->cb_access) { + err = -EINVAL; + goto out_unlock; + } /* * The size of these contexts depends on what the program is attached * to, or run with. That is compared with max_ctx_offset of the program, diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 311c9f19b781fe..4cc9a210cb256a 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -22675,6 +22675,7 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, } if (tgt_prog) { struct bpf_prog_aux *aux = tgt_prog->aux; + enum bpf_cgroup_storage_type stype; bool tgt_changes_pkt_data; bool tgt_might_sleep; bool tgt_can_unwind; @@ -22729,6 +22730,16 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, "Extension programs should be JITed\n"); return -EINVAL; } + /* bpf_get_local_storage() returns the storage of the target */ + for_each_cgroup_storage_type(stype) { + struct bpf_map *storage = prog->aux->cgroup_storage[stype]; + + if (storage && storage != aux->cgroup_storage[stype]) { + bpf_log(log, + "Extension program has another cgroup storage than original\n"); + return -EINVAL; + } + } /* * How much of the buffer of the tracepoint is used * is checked for the program that is attached to it. @@ -22793,16 +22804,14 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, bpf_log(log, "Cannot recursively attach\n"); return -EINVAL; } - if (tgt_prog->type == BPF_PROG_TYPE_TRACING && - prog_extension && - (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || - tgt_prog->expected_attach_type == BPF_TRACE_FEXIT || - tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI || - tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || - tgt_prog->expected_attach_type == BPF_TRACE_FSESSION || - tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { - /* Program extensions can extend all program types - * except fentry/fexit. The reason is the following. + if (prog_extension && + (tgt_prog->type == BPF_PROG_TYPE_TRACING || + tgt_prog->type == BPF_PROG_TYPE_LSM || + tgt_prog->type == BPF_PROG_TYPE_STRUCT_OPS)) { + /* + * These types are checked against the BTF of their hook, + * and an extension has the BTF of its target instead. + * There is one more reason for fentry/fexit. * The fentry/fexit programs are used for performance * analysis, stats and can be attached to any program * type. When extension program is replacing XDP function @@ -22815,7 +22824,7 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, * beyond reasonable stack size. Hence extending fentry * is not allowed. */ - bpf_log(log, "Cannot extend fentry/fexit/fsession\n"); + bpf_log(log, "Cannot extend tracing, LSM and struct_ops programs\n"); return -EINVAL; } } else { @@ -23163,10 +23172,13 @@ static int check_attach_btf_id(struct bpf_verifier_env *env) prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; } - if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { + /* An extension has expected_attach_type of its target, it can be any value */ + if (prog->type != BPF_PROG_TYPE_EXT && + prog->expected_attach_type == BPF_TRACE_RAW_TP) { prog->aux->attach_btf_trace = true; return 0; - } else if (prog->expected_attach_type == BPF_TRACE_ITER) { + } else if (prog->type != BPF_PROG_TYPE_EXT && + prog->expected_attach_type == BPF_TRACE_ITER) { return bpf_iter_prog_supported(prog); } From 3d6d222bb9794a054188e9304b5c5f0c30a83063 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:28:57 +0000 Subject: [PATCH 1876/2102] bpf: Take the attach type of the target for tail calls of an extension A prog array compares expected_attach_type. It is 0 for an extension at the time of the check, so the extension can call programs that were checked for another attach type, and cannot share an array with its target. Take the attach type of the target. Fixes: 4540aed51b12 ("bpf: Enforce expected_attach_type for tailcall compatibility") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-7-alexei.starovoitov@gmail.com --- kernel/bpf/core.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index 0bfd23a41401d2..14b8ee05e50639 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -2518,6 +2518,7 @@ static unsigned int __bpf_prog_ret0_warn(const void *ctx, static bool __bpf_prog_map_compatible(struct bpf_map *map, const struct bpf_prog *fp) { + enum bpf_attach_type attach_type = fp->expected_attach_type; enum bpf_prog_type prog_type = resolve_prog_type(fp); struct bpf_prog_aux *aux = fp->aux; enum bpf_cgroup_storage_type i; @@ -2527,6 +2528,9 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, if (fp->kprobe_override) return ret; + if (fp->type == BPF_PROG_TYPE_EXT) + attach_type = aux->saved_dst_attach_type; + spin_lock(&map->owner_lock); /* There's no owner yet where we could check for compatibility. */ if (!map->owner) { @@ -2537,7 +2541,7 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, map->owner->jited = fp->jited; map->owner->xdp_has_frags = aux->xdp_has_frags; map->owner->sleepable = fp->sleepable; - map->owner->expected_attach_type = fp->expected_attach_type; + map->owner->expected_attach_type = attach_type; map->owner->attach_func_proto = aux->attach_func_proto; for_each_cgroup_storage_type(i) { map->owner->storage_cookie[i] = @@ -2552,7 +2556,7 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, map->owner->sleepable == fp->sleepable; if (ret && map->map_type == BPF_MAP_TYPE_PROG_ARRAY && - map->owner->expected_attach_type != fp->expected_attach_type) + map->owner->expected_attach_type != attach_type) ret = false; for_each_cgroup_storage_type(i) { if (!ret) From 98ff9cff0b94050d0404e1c5bee717ab3423a2d4 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:28:58 +0000 Subject: [PATCH 1877/2102] bpf: Compare what a hook tells next to its prototype at tail calls Hooks of one prototype differ in what the verifier assumes: - struct_ops: two structs can have the same index and prototype of a member. Nullable and referenced arguments, filters of kfuncs and the prologue belong to the struct. - tp_btf: which arguments can be NULL. - LSM and iterators: what is trusted, helpers, kfuncs, return values. - A tracer of a program: the context of the target. Compare that. Tracepoints that agree, and tracers of kernel functions, share a prog array as before. Two LSM hooks cannot. Fixes: 28ead3eaabc1 ("bpf: Prevent tail call between progs attached to different hooks") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-8-alexei.starovoitov@gmail.com --- include/linux/bpf.h | 3 +++ include/linux/btf.h | 1 + kernel/bpf/btf.c | 10 ++++++++++ kernel/bpf/core.c | 20 ++++++++++++++++++-- kernel/bpf/syscall.c | 1 + 5 files changed, 33 insertions(+), 2 deletions(-) diff --git a/include/linux/bpf.h b/include/linux/bpf.h index a1c96ca14afdcb..5f2e386dc118a4 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -300,7 +300,9 @@ struct bpf_map_owner { bool sleepable; u64 storage_cookie[MAX_BPF_CGROUP_STORAGE_TYPE]; const struct btf_type *attach_func_proto; + const struct bpf_struct_ops *st_ops; enum bpf_attach_type expected_attach_type; + u64 hook_key; }; struct bpf_map { @@ -1889,6 +1891,7 @@ struct bpf_prog_aux { struct mutex dst_mutex; /* protects dst_* pointers below, *after* prog becomes visible */ struct bpf_prog *dst_prog; struct bpf_trampoline *dst_trampoline; + enum bpf_prog_type saved_dst_ctx_type; enum bpf_prog_type saved_dst_prog_type; enum bpf_attach_type saved_dst_attach_type; bool verifier_zext; /* Zero extensions has been inserted by verifier. */ diff --git a/include/linux/btf.h b/include/linux/btf.h index 87fad4076f0e9d..7bb3cc973c1f25 100644 --- a/include/linux/btf.h +++ b/include/linux/btf.h @@ -159,6 +159,7 @@ struct btf_struct_metas { extern const struct file_operations btf_fops; const char *btf_get_name(const struct btf *btf); +u64 btf_raw_tp_null_mask(const struct bpf_prog *prog); void btf_get(struct btf *btf); void btf_put(struct btf *btf); const struct btf_header *btf_header(const struct btf *btf); diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c index 7c83f3bdfcf1f1..d5e126dc5d3e19 100644 --- a/kernel/bpf/btf.c +++ b/kernel/bpf/btf.c @@ -7449,6 +7449,16 @@ static const struct bpf_raw_tp_null_args raw_tp_null_args[] = { { "amdtp_packet", 0x100 }, }; +u64 btf_raw_tp_null_mask(const struct bpf_prog *prog) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(raw_tp_null_args); i++) + if (!strcmp(prog->aux->attach_func_name, raw_tp_null_args[i].func)) + return raw_tp_null_args[i].mask; + return btf_is_module(prog->aux->attach_btf) ? U64_MAX : 0; +} + bool btf_ctx_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index 14b8ee05e50639..06a0413da48970 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -2515,6 +2515,18 @@ static unsigned int __bpf_prog_ret0_warn(const void *ctx, return 0; } +/* What the verifier took from the hook, next to its prototype */ +static u64 bpf_prog_hook_key(const struct bpf_prog *fp) +{ + if (IS_ENABLED(CONFIG_BPF_SYSCALL) && fp->aux->attach_btf_trace) + return btf_raw_tp_null_mask(fp); + if (fp->type == BPF_PROG_TYPE_TRACING && fp->expected_attach_type != BPF_TRACE_ITER) + return fp->aux->saved_dst_ctx_type; + if (fp->type == BPF_PROG_TYPE_TRACING || fp->type == BPF_PROG_TYPE_LSM) + return fp->aux->attach_btf_id; + return 0; +} + static bool __bpf_prog_map_compatible(struct bpf_map *map, const struct bpf_prog *fp) { @@ -2522,8 +2534,8 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, enum bpf_prog_type prog_type = resolve_prog_type(fp); struct bpf_prog_aux *aux = fp->aux; enum bpf_cgroup_storage_type i; + u64 cookie, hook_key = bpf_prog_hook_key(fp); bool ret = false; - u64 cookie; if (fp->kprobe_override) return ret; @@ -2543,6 +2555,8 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, map->owner->sleepable = fp->sleepable; map->owner->expected_attach_type = attach_type; map->owner->attach_func_proto = aux->attach_func_proto; + map->owner->st_ops = aux->st_ops; + map->owner->hook_key = hook_key; for_each_cgroup_storage_type(i) { map->owner->storage_cookie[i] = aux->cgroup_storage[i] ? @@ -2553,7 +2567,9 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, ret = map->owner->type == prog_type && map->owner->jited == fp->jited && map->owner->xdp_has_frags == aux->xdp_has_frags && - map->owner->sleepable == fp->sleepable; + map->owner->sleepable == fp->sleepable && + map->owner->st_ops == aux->st_ops && + map->owner->hook_key == hook_key; if (ret && map->map_type == BPF_MAP_TYPE_PROG_ARRAY && map->owner->expected_attach_type != attach_type) diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c index 3f2bc772e297ed..571eec4f0cf526 100644 --- a/kernel/bpf/syscall.c +++ b/kernel/bpf/syscall.c @@ -3091,6 +3091,7 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at prog->aux->attach_btf_id = multi_func ? bpf_multi_func_btf_id[0] : attr->attach_btf_id; prog->aux->dst_prog = dst_prog; if (dst_prog) { + prog->aux->saved_dst_ctx_type = resolve_prog_type(dst_prog); prog->aux->saved_dst_prog_type = dst_prog->type; prog->aux->saved_dst_attach_type = dst_prog->expected_attach_type; } From bf675c92165500367509fc126338ef3dea4611ed Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:28:59 +0000 Subject: [PATCH 1878/2102] bpf: Reserve cookie and ip in the trampoline for tail calls The trampoline has a session cookie and the address of the function only when the program that is attached asks for them. After a tail call bpf_get_func_ip() returns what is on the stack, and bpf_session_cookie() points to the first argument, which the trampoline passes to the function: KASAN: maybe wild-memory-access in range [0x4141414141414148-0x414141414141414f] RIP: 0010:vfs_truncate+0x32/0x450 Ask for both when the program has a tail call. Fixes: 9b99edcae5c8 ("bpf: Add bpf_get_func_ip helper for tracing programs") Fixes: eeee4239dbb1 ("bpf: support fsession for bpf_session_cookie") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-9-alexei.starovoitov@gmail.com --- kernel/bpf/fixups.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c index a656634fa9e468..59dcd91ed5517c 100644 --- a/kernel/bpf/fixups.c +++ b/kernel/bpf/fixups.c @@ -2254,6 +2254,10 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) * the program array. */ prog->cb_access = 1; + prog->call_get_func_ip = 1; + if (prog_type == BPF_PROG_TYPE_TRACING && + (eatype == BPF_TRACE_FSESSION || eatype == BPF_TRACE_FSESSION_MULTI)) + prog->call_session_cookie = 1; if (!bpf_allow_tail_call_in_subprogs(env)) prog->aux->stack_depth = MAX_BPF_STACK; prog->aux->max_pkt_offset = MAX_PACKET_OFF; From 80184a7381c11eae0103f0c432e2adf6a5fd476f Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:00 +0000 Subject: [PATCH 1879/2102] bpf: Check that a program and a struct_ops map are for the same struct A map takes a program when the id of the struct and the index of the member are the same. Ids of types are not unique among modules. Compare BTF too. BPF_PROG_ASSOC_STRUCT_OPS takes any struct_ops map, and the callers of bpf_prog_get_assoc_struct_ops() take the result for their own struct. Pass the struct_ops that the caller wants, return NULL for another one. The callers are scx_prog_sched() of sched_ext and bpf_testmod, they change with the prototype. Fixes: f6be98d19985 ("bpf, net: switch to dynamic registration") Fixes: b5709f6d26d6 ("bpf: Support associating BPF program with struct_ops") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-10-alexei.starovoitov@gmail.com --- include/linux/bpf.h | 6 ++++-- kernel/bpf/bpf_struct_ops.c | 8 ++++++-- kernel/sched/ext/internal.h | 5 ++++- tools/testing/selftests/bpf/test_kmods/bpf_testmod.c | 6 ++++-- 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/include/linux/bpf.h b/include/linux/bpf.h index 5f2e386dc118a4..e98d26cf6cedf4 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -2411,7 +2411,8 @@ static inline void bpf_module_put(const void *data, struct module *owner) int bpf_struct_ops_link_create(union bpf_attr *attr); int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_map *map); void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog); -void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux); +void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux, + const struct bpf_struct_ops *st_ops); u32 bpf_struct_ops_id(const void *kdata); int bpf_struct_ops_for_each_prog(const void *kdata, int (*cb)(struct bpf_prog *prog, void *data), @@ -2475,7 +2476,8 @@ static inline int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_ma static inline void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog) { } -static inline void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux) +static inline void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux, + const struct bpf_struct_ops *st_ops) { return NULL; } diff --git a/kernel/bpf/bpf_struct_ops.c b/kernel/bpf/bpf_struct_ops.c index 7c5cd6086e2735..71235df99cc978 100644 --- a/kernel/bpf/bpf_struct_ops.c +++ b/kernel/bpf/bpf_struct_ops.c @@ -845,6 +845,7 @@ static long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key, } if (prog->type != BPF_PROG_TYPE_STRUCT_OPS || + prog->aux->attach_btf != st_map->btf || prog->aux->attach_btf_id != st_ops_desc->type_id || prog->expected_attach_type != i) { bpf_prog_put(prog); @@ -1591,13 +1592,14 @@ void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog) * Get a reference to the struct_ops struct (i.e., kdata) associated with a * program. Should only be called in BPF program context (e.g., in a kfunc). * - * If the returned pointer is not NULL, it must points to a valid struct_ops. + * If the returned pointer is not NULL, it must points to a valid @st_ops. * The struct_ops map is not guaranteed to be initialized nor attached. * Kernel struct_ops implementers are responsible for tracking and checking * the state of the struct_ops if the use case requires an initialized or * attached struct_ops. */ -void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux) +void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux, + const struct bpf_struct_ops *st_ops) { struct bpf_struct_ops_map *st_map; struct bpf_map *st_ops_assoc; @@ -1607,6 +1609,8 @@ void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux) return NULL; st_map = (struct bpf_struct_ops_map *)st_ops_assoc; + if (st_map->st_ops_desc->st_ops != st_ops) + return NULL; return &st_map->kvalue.data; } diff --git a/kernel/sched/ext/internal.h b/kernel/sched/ext/internal.h index 58652370da5ad2..c0109ac9834705 100644 --- a/kernel/sched/ext/internal.h +++ b/kernel/sched/ext/internal.h @@ -2674,6 +2674,8 @@ static inline bool scx_task_on_sched(struct scx_sched *sch, return rcu_access_pointer(p->scx.sched) == sch; } +static struct bpf_struct_ops bpf_sched_ext_ops, bpf_sched_ext_ops_cid; + /** * scx_prog_sched - Find scx_sched associated with a BPF prog * @aux: aux passed in from BPF to a kfunc @@ -2687,7 +2689,8 @@ static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux) struct sched_ext_ops *ops; struct scx_sched *sch, *root; - ops = bpf_prog_get_assoc_struct_ops(aux); + ops = bpf_prog_get_assoc_struct_ops(aux, &bpf_sched_ext_ops) ?: + bpf_prog_get_assoc_struct_ops(aux, &bpf_sched_ext_ops_cid); if (likely(ops)) { sch = rcu_dereference_all(ops->priv); if (sch && unlikely(READ_ONCE(sch->dead))) diff --git a/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c b/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c index 76fbe64755ef95..7c5255ac49a340 100644 --- a/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c +++ b/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c @@ -2500,13 +2500,15 @@ int bpf_kfunc_multi_st_ops_test_1(struct st_ops_args *args, u32 id) return ret; } +static struct bpf_struct_ops testmod_multi_st_ops; + /* Call test_1() of the associated struct_ops map */ int bpf_kfunc_multi_st_ops_test_1_assoc(struct st_ops_args *args, struct bpf_prog_aux *aux) { struct bpf_testmod_multi_st_ops *st_ops; int ret = -1; - st_ops = (struct bpf_testmod_multi_st_ops *)bpf_prog_get_assoc_struct_ops(aux); + st_ops = bpf_prog_get_assoc_struct_ops(aux, &testmod_multi_st_ops); if (st_ops) ret = st_ops->test_1(args); @@ -2584,7 +2586,7 @@ static struct bpf_testmod_multi_st_ops multi_st_ops_cfi_stubs = { .test_1 = bpf_testmod_multi_st_ops__test_1, }; -struct bpf_struct_ops testmod_multi_st_ops = { +static struct bpf_struct_ops testmod_multi_st_ops = { .verifier_ops = &bpf_testmod_verifier_ops, .init = multi_st_ops_init, .init_member = multi_st_ops_init_member, From 4151f3558d6e65d4ae6cf1a431537ed52ad48239 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:01 +0000 Subject: [PATCH 1880/2102] bpf: Keep the names in front of a number in delegate options The delegate_* mount options of bpffs take names and numbers. A number overwrites the mask, the names in front of it are lost. That is the order in which /proc/mounts shows them. Fixes: 6c1752e0b6ca ("bpf: Support symbolic BPF FS delegation mount options") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-11-alexei.starovoitov@gmail.com --- kernel/bpf/inode.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/kernel/bpf/inode.c b/kernel/bpf/inode.c index c6f328e4752e1d..50dad8a3936af0 100644 --- a/kernel/bpf/inode.c +++ b/kernel/bpf/inode.c @@ -1055,7 +1055,7 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param) struct bpffs_btf_enums info; const struct btf_type *enum_t; const char *enum_pfx; - u64 *delegate_msk, msk = 0; + u64 *delegate_msk, msk = 0, num; char *p, *str; int val; @@ -1094,9 +1094,10 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param) } else if (find_btf_enum_const(info.btf, enum_t, enum_pfx, p, &val)) { msk |= 1ULL << val; } else { - err = kstrtou64(p, 0, &msk); + err = kstrtou64(p, 0, &num); if (err) return err; + msk |= num; } } From 2c517088d2ef5f9b17fcb2e44a296e36c5a91843 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:02 +0000 Subject: [PATCH 1881/2102] bpf: Do not trust the neighbour of tp_btf/neigh_create ___neigh_create() calls the tracepoint before it tests the result of neigh_alloc(). It is NULL when the table is full. The verifier takes it for a trusted pointer, and a load through it oopses: BUG: kernel NULL pointer dereference, address: 000000000000013c RIP: 0010:bpf_prog_56e3384dcafb1b5b_on_create+0x61/0xc4 Mark it untrusted, loads through it are probed then. PTR_MAYBE_NULL would refuse programs like bpftune, which pass &n->parms to bpf_probe_read_kernel() without a check. The pointer cannot be passed as memory or as a trusted argument any more. Fixes: 838a10bd2ebf ("bpf: Augment raw_tp arguments with PTR_MAYBE_NULL") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-12-alexei.starovoitov@gmail.com --- kernel/bpf/btf.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c index d5e126dc5d3e19..8c934aa8ad609a 100644 --- a/kernel/bpf/btf.c +++ b/kernel/bpf/btf.c @@ -7444,6 +7444,7 @@ static const struct bpf_raw_tp_null_args raw_tp_null_args[] = { /* iptfs */ { "iptfs_ingress_postq_event", 0x1000 }, /* neigh */ + { "neigh_create", 0x4000 }, { "neigh_update", 0x10 }, /* snd_firewire_lib */ { "amdtp_packet", 0x100 }, @@ -7656,6 +7657,9 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type, /* Is the current arg IS_ERR? */ if (raw_tp_null_args[i].mask & (0x2ULL << (arg * 4))) ptr_err_raw_tp = true; + /* It can be NULL, and programs that do not check it have to load */ + if (raw_tp_null_args[i].mask & (0x4ULL << (arg * 4))) + info->reg_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; break; } /* If we don't know NULL-ness specification and the tracepoint From a6de3c4be04d235901f71a6d23ca50a0e797ae89 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:03 +0000 Subject: [PATCH 1882/2102] bpf: Check for NULL in helpers that take a kernel pointer Helpers take a plain PTR_TO_BTF_ID, which can be NULL: an argument of a traced function, or a member of a struct. Some do not check it: KASAN: null-ptr-deref in range [0x0000000000000048-0x000000000000004f] RIP: 0010:sock_from_file+0x22/0x70 bpf_task_pt_regs(), bpf_get_task_stack(), bpf_copy_from_user_task(), bpf_xdp_get_buff_len(), bpf_getsockopt() and bpf_setsockopt() oops the same way. So does bpf_d_path() on the path of a unix socket that is not bound, it has no dentry. Check for NULL, as bpf_find_vma() and bpf_skc_to_*() do. Fixes: fa28dcb82a38 ("bpf: Introduce helper bpf_get_task_stack()") Fixes: 6e22ab9da793 ("bpf: Add d_path helper") Fixes: 4f19cab76136 ("bpf: Add a bpf_sock_from_file helper") Fixes: 3cee6fb8e69e ("bpf: tcp: Support bpf_(get|set)sockopt in bpf tcp iter") Fixes: dd6e10fbd9fb ("bpf: Add bpf_task_pt_regs() helper") Fixes: d99173027d68 ("bpf: add frags support to xdp copy helpers") Fixes: 376040e47334 ("bpf: Add bpf_copy_from_user_task() helper") Fixes: 9113d7e48e91 ("bpf: expose bpf_{g,s}etsockopt to lsm cgroup") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-13-alexei.starovoitov@gmail.com --- kernel/bpf/helpers.c | 2 +- kernel/bpf/stackmap.c | 2 +- kernel/trace/bpf_trace.c | 4 +++- net/core/filter.c | 17 +++++++++++------ 4 files changed, 16 insertions(+), 9 deletions(-) diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index bc0dd36a2799a0..749169a0b157bc 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -726,7 +726,7 @@ BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size, if (unlikely(!size)) return 0; - mm = get_task_mm(tsk); + mm = tsk ? get_task_mm(tsk) : NULL; if (!mm) { memset(dst, 0, size); return -EFAULT; diff --git a/kernel/bpf/stackmap.c b/kernel/bpf/stackmap.c index a19126f5db0292..f25f5585e578c1 100644 --- a/kernel/bpf/stackmap.c +++ b/kernel/bpf/stackmap.c @@ -897,7 +897,7 @@ static long __bpf_get_task_stack(struct task_struct *task, void *buf, u32 size, struct pt_regs *regs; long res = -EINVAL; - if (!try_get_task_stack(task)) { + if (!task || !try_get_task_stack(task)) { memset(buf, 0, size); return -EFAULT; } diff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c index bb79669d1cf408..19e6b51bb2f000 100644 --- a/kernel/trace/bpf_trace.c +++ b/kernel/trace/bpf_trace.c @@ -807,7 +807,7 @@ const struct bpf_func_proto bpf_get_current_task_btf_proto = { BPF_CALL_1(bpf_task_pt_regs, struct task_struct *, task) { - return (unsigned long) task_pt_regs(task); + return task ? (unsigned long)task_pt_regs(task) : 0; } BTF_ID_LIST_SINGLE(bpf_task_pt_regs_ids, struct, pt_regs) @@ -946,6 +946,8 @@ BPF_CALL_3(bpf_d_path, const struct path *, path, char *, buf, u32, sz) len = copy_from_kernel_nofault(©, path, sizeof(*path)); if (len < 0) return len; + if (!copy.mnt || !copy.dentry) + return -EFAULT; p = d_path(©, buf, sz); if (IS_ERR(p)) { diff --git a/net/core/filter.c b/net/core/filter.c index 53c042b267ab68..49eb26d016a1e7 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -4215,10 +4215,15 @@ static const struct bpf_func_proto bpf_xdp_get_buff_len_proto = { .arg1_type = ARG_PTR_TO_CTX, }; +BPF_CALL_1(bpf_xdp_get_buff_len_trace, struct xdp_buff *, xdp) +{ + return xdp ? xdp_get_buff_len(xdp) : 0; +} + BTF_ID_LIST_SINGLE(bpf_xdp_get_buff_len_bpf_ids, struct, xdp_buff) const struct bpf_func_proto bpf_xdp_get_buff_len_trace_proto = { - .func = bpf_xdp_get_buff_len, + .func = bpf_xdp_get_buff_len_trace, .gpl_only = false, .arg1_type = ARG_PTR_TO_BTF_ID, .arg1_btf_id = &bpf_xdp_get_buff_len_bpf_ids[0], @@ -5856,7 +5861,7 @@ static int sol_ipv6_sockopt(struct sock *sk, int optname, static int __bpf_setsockopt(struct sock *sk, int level, int optname, char *optval, int optlen) { - if (!sk_fullsock(sk)) + if (!sk || !sk_fullsock(sk)) return -EINVAL; if (level == SOL_SOCKET) @@ -5879,7 +5884,7 @@ static bool is_locked_tcp_sock_ops(struct bpf_sock_ops_kern *bpf_sock) static int _bpf_setsockopt(struct sock *sk, int level, int optname, char *optval, int optlen) { - if (sk_fullsock(sk)) + if (sk && sk_fullsock(sk)) sock_owned_by_me(sk); return __bpf_setsockopt(sk, level, optname, optval, optlen); } @@ -5889,7 +5894,7 @@ static int __bpf_getsockopt(struct sock *sk, int level, int optname, { int err, saved_optlen = optlen; - if (!sk_fullsock(sk)) { + if (!sk || !sk_fullsock(sk)) { err = -EINVAL; goto done; } @@ -5916,7 +5921,7 @@ static int __bpf_getsockopt(struct sock *sk, int level, int optname, static int _bpf_getsockopt(struct sock *sk, int level, int optname, char *optval, int optlen) { - if (sk_fullsock(sk)) + if (sk && sk_fullsock(sk)) sock_owned_by_me(sk); return __bpf_getsockopt(sk, level, optname, optval, optlen); } @@ -12469,7 +12474,7 @@ const struct bpf_func_proto bpf_skc_to_mptcp_sock_proto = { BPF_CALL_1(bpf_sock_from_file, struct file *, file) { - return (unsigned long)sock_from_file(file); + return file ? (unsigned long)sock_from_file(file) : 0; } BTF_ID_LIST(bpf_sock_from_file_btf_ids) From 86cedb416c4651dde27cfb8142541de8dd2801d9 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:04 +0000 Subject: [PATCH 1883/2102] bpf: Leave nothing behind in the frame of bpf_throw() bpf_throw() does not return. What is kept for the return stays behind. With fexit on bpf_throw() the trampoline is never freed. With kretprobes and function_graph the next traced function up the stack takes the return address of bpf_throw() for its own. Mark it notrace and NOKPROBE_SYMBOL. kasan_unpoison_task_stack_below() takes the stack for aligned to THREAD_SIZE. The stack for interrupts of x86-64 is aligned to a page. A program that throws in softirq can leave the redzones of bpf_throw() there: BUG: KASAN: stack-out-of-bounds in stack_trace_consume_entry+0x14e/0x170 It is the only frame with redzones that is skipped. Do not instrument it. Fixes: f18b03fabaa9 ("bpf: Implement BPF exceptions") Fixes: ec5290a178b7 ("bpf: Prevent KASAN false positive with bpf_throw") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-14-alexei.starovoitov@gmail.com --- kernel/bpf/helpers.c | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index 749169a0b157bc..70330a7088db18 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include @@ -3463,7 +3463,8 @@ static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp) return false; } -__bpf_kfunc void bpf_throw(u64 cookie) +/* It does not return. What a tracer keeps for the return would stay behind, redzones too. */ +__bpf_kfunc notrace __no_sanitize_address void bpf_throw(u64 cookie) { struct bpf_throw_ctx ctx = {}; @@ -3473,16 +3474,10 @@ __bpf_kfunc void bpf_throw(u64 cookie) WARN_ON_ONCE(!ctx.aux->exception_boundary); WARN_ON_ONCE(!ctx.bp); WARN_ON_ONCE(!ctx.cnt); - /* - * Prevent KASAN false positives for CONFIG_KASAN_STACK by unpoisoning - * deeper stack depths than ctx.sp as we do not return from bpf_throw, - * which skips compiler generated instrumentation to do the same. Some - * architectures cannot recover sp while unwinding, so fall back to bp. - */ - kasan_unpoison_task_stack_below((void *)(long)(ctx.sp ?: ctx.bp)); ctx.aux->bpf_exception_cb(cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust, ctx.bp, 0, 0); WARN(1, "A call to BPF exception callback should never return\n"); } +NOKPROBE_SYMBOL(bpf_throw); __bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__const_map, unsigned int flags) { From f7a40c2de8d4abdea6d1e21122b447b593e28bd9 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:05 +0000 Subject: [PATCH 1884/2102] bpf: Add the symbol of a prog before its id A prog can be taken by its id and run before bpf_prog_kallsyms_add(). bpf_throw() does not find the main prog and oopses: KASAN: null-ptr-deref in range [0x0000000000000568-0x000000000000056f] RIP: 0010:bpf_throw+0x129/0x220 The exception table is found by the same symbol. Add the symbol first. bpf_prog_free() removes it when there is no id. Fixes: 3dec541b2e63 ("bpf: Add support for BTF pointers to x86 JIT") Fixes: f18b03fabaa9 ("bpf: Implement BPF exceptions") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-15-alexei.starovoitov@gmail.com --- kernel/bpf/syscall.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c index 571eec4f0cf526..03cb9f769398b9 100644 --- a/kernel/bpf/syscall.c +++ b/kernel/bpf/syscall.c @@ -3179,6 +3179,9 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at if (err < 0) goto free_used_maps; + /* bpf_throw() and faults look for the symbol. The prog can run once it has the id. */ + bpf_prog_kallsyms_add(prog); + err = bpf_prog_alloc_id(prog); if (err) goto free_used_maps; @@ -3197,7 +3200,6 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at * Also, any failure handling from this point onwards must * be using bpf_prog_put() given the program is exposed. */ - bpf_prog_kallsyms_add(prog); perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0); bpf_audit_prog(prog, BPF_AUDIT_LOAD); From 2f2b119ea30dfba27563c1c939eb42b5298a391a Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:06 +0000 Subject: [PATCH 1885/2102] bpf: Do not fill jited line info for a hidden subprog func_idx of the default exception callback is func_cnt, and the test for hidden subprogs is off by one. The address of the callback goes to jited_linfo[0]. libbpf and bpftool refuse the jited line info of the prog. Fixes: 335d1c5b5452 ("bpf: Implement support for adding hidden subprogs") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-16-alexei.starovoitov@gmail.com --- kernel/bpf/core.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index 06a0413da48970..2f6392ccef7300 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -233,7 +233,8 @@ void bpf_prog_fill_jited_linfo(struct bpf_prog *prog, const struct bpf_line_info *linfo; void **jited_linfo; - if (!prog->aux->jited_linfo || prog->aux->func_idx > prog->aux->func_cnt) + if (!prog->aux->jited_linfo || + (prog->aux->func_idx && prog->aux->func_idx >= prog->aux->func_cnt)) /* Userspace did not provide linfo */ return; From f28ed533106bc01aedba6ba47c0e1a1098c92092 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:07 +0000 Subject: [PATCH 1886/2102] bpf: Fix NULL dereference in XDP redirect from async callbacks bpf_redirect() and bpf_redirect_map() do not take the context, so the timer callback of an XDP program can call them. There is no current->bpf_net_context then: KASAN: null-ptr-deref in range [0x0000000000000038-0x000000000000003f] RIP: 0010:bpf_xdp_redirect+0x5b/0x170 Return XDP_ABORTED, like the tc helpers return TC_ACT_SHOT. It is one more test and branch on a value that is loaded anyway. Fixes: 401cb7dae813 ("net: Reference bpf_redirect_info via task_struct on PREEMPT_RT.") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-17-alexei.starovoitov@gmail.com --- include/linux/filter.h | 5 +++-- net/core/filter.c | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/include/linux/filter.h b/include/linux/filter.h index 4f0cd67caccb80..5a664d706ee99a 100644 --- a/include/linux/filter.h +++ b/include/linux/filter.h @@ -1948,13 +1948,14 @@ static __always_inline long __bpf_xdp_redirect_map(struct bpf_map *map, u64 inde u64 flags, const u64 flag_mask, void *lookup_elem(struct bpf_map *map, u32 key)) { - struct bpf_redirect_info *ri = bpf_net_ctx_get_ri(); const u64 action_mask = XDP_ABORTED | XDP_DROP | XDP_PASS | XDP_TX; + struct bpf_redirect_info *ri; /* Lower bits of the flags are used as return code on lookup failure */ - if (unlikely(flags & ~(action_mask | flag_mask))) + if (unlikely(!bpf_net_ctx_get() || flags & ~(action_mask | flag_mask))) return XDP_ABORTED; + ri = bpf_net_ctx_get_ri(); ri->tgt_value = lookup_elem(map, index); if (unlikely(!ri->tgt_value) && !(flags & BPF_F_BROADCAST)) { /* If the lookup fails we want to clear out the state in the diff --git a/net/core/filter.c b/net/core/filter.c index 49eb26d016a1e7..b9dbdd276b0246 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -4889,11 +4889,12 @@ int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb, BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags) { - struct bpf_redirect_info *ri = bpf_net_ctx_get_ri(); + struct bpf_redirect_info *ri; - if (unlikely(flags)) + if (unlikely(!bpf_net_ctx_get() || flags)) return XDP_ABORTED; + ri = bpf_net_ctx_get_ri(); /* NB! Map type UNSPEC and map_id == INT_MAX (never generated * by map_idr) is used for ifindex based XDP redirect. */ From a5e757f6cb34e1be0700359a02567722bcbbf6e3 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:08 +0000 Subject: [PATCH 1887/2102] bpf: Check the attach type when a cgroup link gets another program BPF_LINK_UPDATE compares only the type of the program. A program that is verified for one hook runs in another one. In setsockopt the result of bpf_get_retval() is an errno, in getsockopt it is any int. Check expected_attach_type, as the attach does. Fixes: 0c991ebc8c69 ("bpf: Implement bpf_prog replacement for an active bpf_cgroup_link") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-18-alexei.starovoitov@gmail.com --- kernel/bpf/cgroup.c | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index 88b49238931af3..4e388d994d8073 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -1248,6 +1248,24 @@ static bool cgroup_bpf_storages_compatible(struct bpf_prog *old_prog, return true; } +/* See bpf_prog_attach_check_attach_type() */ +static bool prog_is_for_attach_type(const struct bpf_prog *prog, enum bpf_attach_type type) +{ + switch (prog->type) { + case BPF_PROG_TYPE_CGROUP_SKB: + if (!prog->enforce_expected_attach_type) + return true; + fallthrough; + case BPF_PROG_TYPE_CGROUP_SOCK: + case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: + case BPF_PROG_TYPE_CGROUP_SOCKOPT: + case BPF_PROG_TYPE_LSM: + return prog->expected_attach_type == type; + default: + return true; + } +} + /** * __cgroup_bpf_replace() - Replace link's program and propagate the change * to descendants @@ -1274,7 +1292,8 @@ static int __cgroup_bpf_replace(struct cgroup *cgrp, progs = &cgrp->bpf.progs[atype]; - if (link->link.prog->type != new_prog->type) + if (link->link.prog->type != new_prog->type || + !prog_is_for_attach_type(new_prog, link->link.attach_type)) return -EINVAL; hlist_for_each_entry(pl, progs, node) { From c66c8adf3226e02b74a33728d1fa1e911c3f0d21 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:09 +0000 Subject: [PATCH 1888/2102] bpf: Refuse metadata maps of signed programs that can be mapped writable The signature of a program covers the value of its metadata maps. It holds because they are frozen and exclusive. The freeze is not final for an array that user space was allowed to map for writing, which is why bpf_map_mmap() refuses that for read-only maps. A loader writes to its map, so it's not one of those. Refuse a map that has BPF_F_MMAPABLE without BPF_F_RDONLY_PROG. Light skeletons do not set it. Fixes: b707068e0ed9 ("bpf: Verify signed loader metadata at load time") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-19-alexei.starovoitov@gmail.com --- Documentation/bpf/signing.rst | 3 ++- kernel/bpf/verifier.c | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Documentation/bpf/signing.rst b/Documentation/bpf/signing.rst index 27fdad3df96f1f..db48965cea642b 100644 --- a/Documentation/bpf/signing.rst +++ b/Documentation/bpf/signing.rst @@ -141,7 +141,8 @@ reuses the existing ``fd_array``: ``excl_prog_sha``) and a plain array map (``BPF_MAP_TYPE_ARRAY``); only an array map exposes its value buffer through ``map_direct_value_addr()`` as a kernel address spanning ``value_size`` bytes. A map that is not exclusive, not - frozen, or not a plain array is rejected, with a verifier log message naming + frozen, not a plain array, or that user space could map for writing + (``BPF_F_MMAPABLE``) is rejected, with a verifier log message naming the offending map. The kernel appends each map's frozen contents to the instruction buffer and verifies the PKCS#7 signature over the concatenation ``insns || metadata_0 || metadata_1 || ...`` in ``used_maps`` diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 4cc9a210cb256a..76a50cc2138b4b 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -23850,6 +23850,13 @@ static int bpf_prog_verify_signature(struct bpf_verifier_env *env, err = -EPERM; goto out; } + /* The freeze is not final for it, see bpf_map_mmap() */ + if ((map->map_flags & BPF_F_MMAPABLE) && !(map->map_flags & BPF_F_RDONLY_PROG)) { + verbose(env, "signed program metadata map '%s' must not be mmapable\n", + map->name); + err = -EPERM; + goto out; + } data_sz += map->value_size; } if (bpf_dynptr_check_size(data_sz)) { From 2c00b6b35af0122f1b1fc0ea029bcb567fd4f1b8 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:10 +0000 Subject: [PATCH 1889/2102] bpf: Take bpf_lock with interrupts disabled A program can disable interrupts with bpf_local_irq_save(). bpf_setsockopt(TCP_CONGESTION) can put the last reference of a struct_ops map there, which removes the symbols of the trampolines with spin_lock_bh(). Use the irqsave lock, as bpf_map_free_id() does. PREEMPT_RT is as before, both locks sleep there. Fixes: 5db69b0fbdc8 ("bpf: Make struct_ops tasks_rcu grace period optional") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-20-alexei.starovoitov@gmail.com --- kernel/bpf/core.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index 2f6392ccef7300..47c43e8099dc25 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -648,11 +648,10 @@ static struct latch_tree_root bpf_tree __cacheline_aligned; void bpf_ksym_add(struct bpf_ksym *ksym) { - spin_lock_bh(&bpf_lock); + guard(spinlock_irqsave)(&bpf_lock); WARN_ON_ONCE(!list_empty(&ksym->lnode)); list_add_tail_rcu(&ksym->lnode, &bpf_kallsyms); latch_tree_insert(&ksym->tnode, &bpf_tree, &bpf_tree_ops); - spin_unlock_bh(&bpf_lock); } static void __bpf_ksym_del(struct bpf_ksym *ksym) @@ -666,9 +665,8 @@ static void __bpf_ksym_del(struct bpf_ksym *ksym) void bpf_ksym_del(struct bpf_ksym *ksym) { - spin_lock_bh(&bpf_lock); + guard(spinlock_irqsave)(&bpf_lock); __bpf_ksym_del(ksym); - spin_unlock_bh(&bpf_lock); } static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp) From a70da21f98e0b7b7dd41f637f0c160bdb43e5dd6 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:11 +0000 Subject: [PATCH 1890/2102] bpf: Bound the time that dumps of the stack take may_goto looks at the time once in BPF_MAX_TIMED_LOOPS trips. A dump of the stack takes long, and it is staged before the stream is asked for room. A may_goto loop over bpf_stream_print_stack(), or one that faults in an arena on each trip, holds up RCU tasks and can end in a soft lockup. Let the next may_goto of the program look at the time after a dump. Remember the length of a report that did not fit, and skip the next ones until a reader has made room for it. Fixes: d7c431cafcb4 ("bpf: Add dump_stack() analogue to print to BPF stderr") Fixes: 63328bb23f26 ("bpf: Add bpf_stream_print_stack stack dumping kfunc") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-21-alexei.starovoitov@gmail.com --- include/linux/bpf.h | 5 ++++- include/linux/filter.h | 1 + kernel/bpf/core.c | 9 +++++++++ kernel/bpf/stream.c | 21 +++++++++++++++++++-- 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/include/linux/bpf.h b/include/linux/bpf.h index e98d26cf6cedf4..448431c4cd2d2d 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -1841,6 +1841,7 @@ struct bpf_stream { struct llist_node *backlog_tail; /* tail of the list above */ wait_queue_head_t waitq; struct irq_work notify_work; + int refused; /* length of the last stage that did not fit */ bool notify_used; /* notify_work was queued at least once */ bool dead; }; @@ -4339,6 +4340,7 @@ int bpf_prog_stream_init(struct bpf_prog *prog, gfp_t gfp_extra_flags); void bpf_prog_stream_free(struct bpf_prog *prog); int bpf_prog_stream_read(struct bpf_prog *prog, enum bpf_stream_id stream_id, void __user *buf, u32 len); int bpf_prog_stream_new_fd(struct bpf_prog *prog, enum bpf_stream_id stream_id, u32 flags); +bool bpf_stream_has_room(struct bpf_prog *prog, enum bpf_stream_id stream_id); void bpf_stream_stage_init(struct bpf_stream_stage *ss); void bpf_stream_stage_free(struct bpf_stream_stage *ss); __printf(2, 3) @@ -4353,7 +4355,8 @@ int bpf_stream_stage_dump_stack(struct bpf_stream_stage *ss); #define bpf_stream_stage(ss, prog, stream_id, expr) \ ({ \ bpf_stream_stage_init(&ss); \ - (expr); \ + if (bpf_stream_has_room(prog, stream_id)) \ + (expr); \ bpf_stream_stage_commit(&ss, prog, stream_id); \ bpf_stream_stage_free(&ss); \ }) diff --git a/include/linux/filter.h b/include/linux/filter.h index 5a664d706ee99a..5cf3582823f579 100644 --- a/include/linux/filter.h +++ b/include/linux/filter.h @@ -1334,6 +1334,7 @@ u64 bpf_arch_uaddress_limit(void); void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie); u64 arch_bpf_timed_may_goto(void); u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *); +void bpf_timed_may_goto_check_time(const struct bpf_prog *prog); void bpf_timed_may_goto_save(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved); void bpf_timed_may_goto_restore(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved); bool bpf_helper_changes_pkt_data(enum bpf_func_id func_id); diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index 47c43e8099dc25..50d175fcef6960 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -3713,6 +3713,15 @@ void bpf_timed_may_goto_restore(const struct bpf_prog *prog, struct bpf_timed_ma *cur = *saved; } +/* A walk of the stack is too long for BPF_MAX_TIMED_LOOPS trips. The next one looks at the time. */ +void bpf_timed_may_goto_check_time(const struct bpf_prog *prog) +{ + struct bpf_timed_may_goto __percpu *tmg = prog->aux->main_prog_aux->timed_may_goto; + + if (tmg && this_cpu_read(tmg->count)) + this_cpu_write(tmg->count, 1); +} + /* for configs without MMU or 32-bit */ __weak const struct bpf_map_ops arena_map_ops; __weak u64 bpf_arena_get_user_vm_start(struct bpf_arena *arena) diff --git a/kernel/bpf/stream.c b/kernel/bpf/stream.c index 83e803ea54ef24..65f65876afdb84 100644 --- a/kernel/bpf/stream.c +++ b/kernel/bpf/stream.c @@ -74,7 +74,9 @@ static int bpf_stream_consume_capacity(struct bpf_stream *stream, int len) static void bpf_stream_release_capacity(struct bpf_stream *stream, int len) { - atomic_sub(len, &stream->capacity); + if (atomic_sub_return(len, &stream->capacity) + READ_ONCE(stream->refused) < + BPF_STREAM_MAX_CAPACITY) + WRITE_ONCE(stream->refused, 0); } static void bpf_stream_notify(struct irq_work *work) @@ -490,6 +492,15 @@ void bpf_prog_stream_free(struct bpf_prog *prog) } } +/* A dump of the stack is expensive, and a loop can ask for one on each trip */ +bool bpf_stream_has_room(struct bpf_prog *prog, enum bpf_stream_id stream_id) +{ + struct bpf_stream *stream = bpf_stream_get(stream_id, prog->aux); + + return stream && atomic_read(&stream->capacity) + READ_ONCE(stream->refused) < + BPF_STREAM_MAX_CAPACITY; +} + void bpf_stream_stage_init(struct bpf_stream_stage *ss) { init_llist_head(&ss->log); @@ -531,13 +542,19 @@ int bpf_stream_stage_commit(struct bpf_stream_stage *ss, struct bpf_prog *prog, struct bpf_stream *stream; int ret; + bpf_timed_may_goto_check_time(prog); + stream = bpf_stream_get(stream_id, prog->aux); if (!stream) return -EINVAL; + if (!ss->len) + return 0; ret = bpf_stream_consume_capacity(stream, ss->len); - if (ret) + if (ret) { + WRITE_ONCE(stream->refused, min(ss->len, BPF_STREAM_MAX_CAPACITY / 2)); return ret; + } list = llist_del_all(&ss->log); head = tail = list; From 0cd1f2029b1b9fd7ceb52e3dfec181452cf20be0 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:12 +0000 Subject: [PATCH 1891/2102] bpf: Refuse mmap() of a part of an arena The first mmap() sets the addresses of an arena that has no map_extra. It can be shorter than max_entries, but all pages stay in the range tree. An allocation without an address gets pages behind the end of the mapping. They can be mapped behind the vmalloc area of the arena. Require the length of the whole arena, as for an arena with map_extra. libbpf and cilium/ebpf map all pages. Fixes: b795379757eb ("bpf: Introduce range_tree data structure and use it in bpf arena") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-22-alexei.starovoitov@gmail.com --- kernel/bpf/arena.c | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c index ec2bda1a6ebf60..2c6ddec747def3 100644 --- a/kernel/bpf/arena.c +++ b/kernel/bpf/arena.c @@ -637,16 +637,13 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad return -EINVAL; if (len > (u64)map->max_entries * PAGE_SIZE) return -E2BIG; + /* each page in the range tree needs an address */ + if (len < (u64)map->max_entries * PAGE_SIZE) + return -EINVAL; /* if user_vm_start was specified at arena creation time */ - if (arena->user_vm_start) { - if (len > arena->user_vm_end - arena->user_vm_start) - return -E2BIG; - if (len != arena->user_vm_end - arena->user_vm_start) - return -EINVAL; - if (addr != arena->user_vm_start) - return -EINVAL; - } + if (arena->user_vm_start && addr != arena->user_vm_start) + return -EINVAL; /* * Without MAP_FIXED the mm finds a free range. Ask for twice the From 16829046f0a0df75fe0a0b937771ffa301b650f7 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:13 +0000 Subject: [PATCH 1892/2102] bpf: Flush TLB when a page of arena replaces the scratch page A fault of a kfunc maps the scratch page. An allocation at that address puts a new page in its place. flush_tlb_before_set() is empty on x86, so all cpus that have touched the address keep the scratch page in TLB. The program reads junk from the page that it has got, and its writes are lost. The flush takes an IPI. Do it after the lock is dropped when the caller can sleep. Otherwise fail and free the range: the work unmaps the scratch page and flushes TLB. The range is taken until then. As with any deferred free, it stays taken when kmalloc_nolock() of the span fails. Fixes: f64c723741c9 ("bpf: Replace scratch PTE atomically when allocating arena pages") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-23-alexei.starovoitov@gmail.com --- kernel/bpf/arena.c | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c index 2c6ddec747def3..56bd02b783f989 100644 --- a/kernel/bpf/arena.c +++ b/kernel/bpf/arena.c @@ -149,6 +149,8 @@ struct apply_range_data { struct bpf_arena *arena; struct llist_head *pages; int i; + bool can_flush; /* the caller can flush TLB of all cpus after it drops the lock */ + bool flush; }; struct clear_range_data { @@ -189,6 +191,12 @@ static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data) continue; if (WARN_ON_ONCE(pte_page(old) != d->arena->scratch_page)) return -EBUSY; +#ifndef flush_tlb_before_set + /* The scratch page is in TLB, and it takes an IPI to flush it */ + if (!d->can_flush) + return -EBUSY; + d->flush = true; +#endif ptep_get_and_clear(&init_mm, addr, pte); flush_tlb_before_set(addr); } @@ -571,6 +579,7 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf) } llist_add(&new_page->pcp_llist, &pages); data.arena = arena; + data.can_flush = false; data.pages = &pages; data.i = 0; @@ -803,6 +812,8 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt goto out_memcg; data.arena = arena; + data.can_flush = sleepable; + data.flush = false; data.pages = &pages; data.i = 0; @@ -833,17 +844,18 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt flush_vmap_cache(kern_vm_start + uaddr32, mapped << PAGE_SHIFT); raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); + if (data.flush) + flush_tlb_kernel_range(kern_vm_start + uaddr32, + kern_vm_start + uaddr32 + (mapped << PAGE_SHIFT)); addr = clear_lo32(arena->user_vm_start) + uaddr32; goto out_memcg; out_unmap: - /* Error handling: Undo partial mappings. */ + /* Error handling: Undo partial mappings, unmap the scratch page. */ flush_vmap_cache(kern_vm_start + uaddr32, mapped << PAGE_SHIFT); - range_tree_set(&arena->rt, pgoff + mapped, page_cnt - mapped); raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); - if (mapped) - arena_free_pages(arena, uaddr32, mapped, sleepable); + arena_free_pages(arena, uaddr32, page_cnt, sleepable); out_free_pages: /* Error handling: Free back any unmapped pages. */ From 6c8d5a113c2341a9fc12a6550c0645d5cda0d56d Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:14 +0000 Subject: [PATCH 1893/2102] bpf: Fix reads past an enum in prints of BTF data An enum has 1, 2, 4 or 8 bytes. It's read as int, enum64 as u64, whatever the size is. The file of a map in bpffs shows what is behind a key or a value that ends with a short enum. Read as many bytes as the type has. The check of a member of a struct with bitfields takes any enum for 4 bytes, so an enum of 8 bytes can stick out of it. Use the size there too. Short enums are printed by their names. BTF with an enum that sticks out of its struct is refused, compilers don't make it. Fixes: 9eea98497951 ("bpf: fix BTF verification of enums") Fixes: 6089fb325cf7 ("bpf: Add btf enum64 support") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-24-alexei.starovoitov@gmail.com --- kernel/bpf/btf.c | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c index 8c934aa8ad609a..7b3291556e6ee7 100644 --- a/kernel/bpf/btf.c +++ b/kernel/bpf/btf.c @@ -4579,7 +4579,7 @@ static int btf_enum_check_kflag_member(struct btf_verifier_env *env, return -EINVAL; } - nr_bits = int_bitsize; + nr_bits = member_type->size * BITS_PER_BYTE; } else if (nr_bits > int_bitsize) { btf_verifier_log_member(env, struct_type, member, "Invalid member bitfield_size"); @@ -4662,12 +4662,30 @@ static void btf_enum_log(struct btf_verifier_env *env, btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t)); } +static s64 btf_enum_read(const struct btf_type *t, const void *data) +{ + bool sign = btf_type_kflag(t); + + switch (t->size) { + case 1: + return sign ? *(s8 *)data : *(u8 *)data; + case 2: + return sign ? *(s16 *)data : *(u16 *)data; + case 4: + return sign ? (s64)*(s32 *)data : *(u32 *)data; + default: + return *(s64 *)data; + } +} + static void btf_enum_show(const struct btf *btf, const struct btf_type *t, u32 type_id, void *data, u8 bits_offset, struct btf_show *show) { const struct btf_enum *enums = btf_type_enum(t); u32 i, nr_enums = btf_type_vlen(t); + /* Old compilers don't set the flag for negative values */ + u32 mask = t->size < 4 ? BIT(t->size * BITS_PER_BYTE) - 1 : U32_MAX; void *safe_data; int v; @@ -4675,10 +4693,10 @@ static void btf_enum_show(const struct btf *btf, const struct btf_type *t, if (!safe_data) return; - v = *(int *)safe_data; + v = btf_enum_read(t, safe_data); for (i = 0; i < nr_enums; i++) { - if (v != enums[i].val) + if ((v ^ enums[i].val) & mask) continue; btf_show_type_value(show, "%s", @@ -4778,7 +4796,7 @@ static void btf_enum64_show(const struct btf *btf, const struct btf_type *t, if (!safe_data) return; - v = *(u64 *)safe_data; + v = btf_enum_read(t, safe_data); for (i = 0; i < nr_enums; i++) { if (v != btf_enum64_value(enums + i)) From 703826e497ffaed83e9f93f1694250ba1e81eacf Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:15 +0000 Subject: [PATCH 1894/2102] bpf: Give the error of bpf_res_spin_lock() a 32-bit range The verifier gives r0 the range [-4095, -1] in 64 bits when bpf_res_spin_lock() fails. The kfunc returns int, x86-64 and arm64 leave the upper half zero. Give the range to the lower half only. GCC extends the result with r0 = (s32)r0. Keep the range of the lower half there, so that a test of the sign still tells the error. Fixes: 0de2046137f9 ("bpf: Implement verifier support for rqspinlock") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-25-alexei.starovoitov@gmail.com --- kernel/bpf/verifier.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 76a50cc2138b4b..d29d0725ec01c5 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -6217,6 +6217,7 @@ static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) u64 top_smax_value, top_smin_value; u64 num_bits = size * 8; s64 limit = 1LL << (num_bits - 1); + struct cnum32 r32; /* If every value fits the signed N-bit range sign extension is a noop. */ if (reg_smin(reg) >= -limit && reg_smax(reg) < limit) @@ -6271,7 +6272,13 @@ static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) } out: + r32 = reg->r32; set_sext64_default_val(reg, size); + /* the low 32 bits fit, they do not change */ + if (cnum32_smin(r32) >= -limit && cnum32_smax(r32) < limit) { + reg->r32 = r32; + reg->r64 = cnum64_from_srange(cnum32_smin(r32), cnum32_smax(r32)); + } } static void set_sext32_default_val(struct bpf_reg_state *reg, int size) @@ -15538,12 +15545,10 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, for (i = 0; i < CALLER_SAVED_REGS; i++) bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); + /* The kfunc returns int, the upper half of r0 is not known */ mark_reg_unknown(env, regs, BPF_REG_0); - err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); - if (err) { - verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); - return err; - } + reg_set_srange32(®s[BPF_REG_0], -MAX_ERRNO, -1); + reg_bounds_sync(®s[BPF_REG_0]); } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); return -EFAULT; From 2ff55b023f637d61a56a893b0a3eb534acfb2ffd Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:16 +0000 Subject: [PATCH 1895/2102] bpf: Give syscall programs without CAP_PERFMON the base helpers only A syscall program needs CAP_BPF only, and it gets all helpers of tracing programs. These don't ask for CAP_PERFMON, the load of a tracing program does. The helpers for loader programs take current for the loader. It's another task in a callback. bpf_kallsyms_lookup_name() answers in a callback of bpf_wq, as a kworker has all capabilities. bpf_sys_close() in a task work closes a file of any process. Give the program the base helpers. It loses bpf_perf_event_output() too. Loader programs are not affected, bpf_sys_bpf() needs CAP_PERFMON already. Fixes: 79a7f8bdb159 ("bpf: Introduce bpf_sys_bpf() helper and program type.") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-26-alexei.starovoitov@gmail.com --- kernel/bpf/syscall.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c index 03cb9f769398b9..e82ae48c0bc075 100644 --- a/kernel/bpf/syscall.c +++ b/kernel/bpf/syscall.c @@ -6747,10 +6747,12 @@ static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = { static const struct bpf_func_proto * syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { + if (!bpf_token_capable(prog->aux->token, CAP_PERFMON)) + return bpf_base_func_proto(func_id, prog); + switch (func_id) { case BPF_FUNC_sys_bpf: - return !bpf_token_capable(prog->aux->token, CAP_PERFMON) - ? NULL : &bpf_sys_bpf_proto; + return &bpf_sys_bpf_proto; case BPF_FUNC_btf_find_by_name_kind: return &bpf_btf_find_by_name_kind_proto; case BPF_FUNC_sys_close: From 3e03955a6518de7675cb05d263dd4d3a7f0b85ba Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:17 +0000 Subject: [PATCH 1896/2102] bpf: Require CAP_PERFMON for kfuncs that leak pointers or touch tasks Syscall, tc, XDP and cgroup programs load without CAP_PERFMON and can call kfuncs that give more than CAP_BPF stands for: - kfuncs of arena take any pointer for the address and can leak it. The check for an arena misses one from a map of maps. - void * of a kfunc is a number for the verifier. - bpf_send_signal_task() and the kfuncs of task work act on any task. Ask for CAP_PERFMON, as the helpers of the same kind do. struct_ops and tracing programs have it. Fixes: 317460317a02 ("bpf: Introduce bpf_arena.") Fixes: 88d1d4a7eebe ("bpf: Allow kfuncs return 'void *'") Fixes: 6280cf718db0 ("bpf: Implement bpf_send_signal_task() kfunc") Fixes: 38aa7003e369 ("bpf: task work scheduling kfuncs") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-27-alexei.starovoitov@gmail.com --- Documentation/bpf/kfuncs.rst | 3 ++- kernel/bpf/arena.c | 7 ++++--- kernel/bpf/helpers.c | 6 +++--- kernel/bpf/verifier.c | 6 ++++++ 4 files changed, 15 insertions(+), 7 deletions(-) diff --git a/Documentation/bpf/kfuncs.rst b/Documentation/bpf/kfuncs.rst index 901c3750421776..31389dd5c9f6dd 100644 --- a/Documentation/bpf/kfuncs.rst +++ b/Documentation/bpf/kfuncs.rst @@ -537,7 +537,8 @@ addresses to the BPF program, for example by reading through a pointer that the verifier does not check. Calling such a kfunc requires CAP_PERFMON, or CAP_SYS_ADMIN, in the same way that the equivalent BPF helpers are gated in bpf_base_func_proto(). A program loaded with CAP_BPF alone is rejected at load -time. +time. The flag is implied when the program gets a returned ``void *`` as a +number. 2.6 Registering the kfuncs -------------------------- diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c index 56bd02b783f989..70a49b1200a9b5 100644 --- a/kernel/bpf/arena.c +++ b/kernel/bpf/arena.c @@ -1187,9 +1187,10 @@ __bpf_kfunc int bpf_arena_reserve_pages(void *p__map, void *ptr__ign, u32 page_c __bpf_kfunc_end_defs(); BTF_KFUNCS_START(arena_kfuncs) -BTF_ID_FLAGS(func, bpf_arena_alloc_pages, KF_ARENA_RET | KF_ARENA_ARG2 | KF_SPINLOCK_SAFE) -BTF_ID_FLAGS(func, bpf_arena_free_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE) -BTF_ID_FLAGS(func, bpf_arena_reserve_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE) +BTF_ID_FLAGS(func, bpf_arena_alloc_pages, + KF_ARENA_RET | KF_ARENA_ARG2 | KF_SPINLOCK_SAFE | KF_PERFMON) +BTF_ID_FLAGS(func, bpf_arena_free_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE | KF_PERFMON) +BTF_ID_FLAGS(func, bpf_arena_reserve_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE | KF_PERFMON) BTF_KFUNCS_END(arena_kfuncs) static const struct btf_kfunc_id_set common_kfunc_set = { diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index 70330a7088db18..61ddc45b033051 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -5156,7 +5156,7 @@ BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL) BTF_ID_FLAGS(func, bpf_task_from_vpid, KF_ACQUIRE | KF_RET_NULL) BTF_ID_FLAGS(func, bpf_throw) #ifdef CONFIG_BPF_EVENTS -BTF_ID_FLAGS(func, bpf_send_signal_task) +BTF_ID_FLAGS(func, bpf_send_signal_task, KF_PERFMON) #endif #ifdef CONFIG_KEYS BTF_ID_FLAGS(func, bpf_lookup_user_key, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE) @@ -5272,8 +5272,8 @@ BTF_ID_FLAGS(func, bpf_cgroup_read_xattr, KF_RCU) #endif BTF_ID_FLAGS(func, bpf_stream_vprintk, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE | KF_PERFMON) BTF_ID_FLAGS(func, bpf_stream_print_stack, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE | KF_PERFMON) -BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_IMPLICIT_ARGS) -BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_IMPLICIT_ARGS) +BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_IMPLICIT_ARGS | KF_PERFMON) +BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_IMPLICIT_ARGS | KF_PERFMON) BTF_ID_FLAGS(func, bpf_call_rcu, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, bpf_call_rcu_tasks_trace, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, bpf_dynptr_from_file) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index d29d0725ec01c5..410804e8039292 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -15851,6 +15851,12 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, return err; } else if (btf_type_is_void(ptr_type)) { /* kfunc returning 'void *' is equivalent to returning scalar */ + if (!env->allow_ptr_leaks) { + verbose(env, + "%s is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", + func_name); + return -EPERM; + } mark_reg_unknown(env, regs, BPF_REG_0); } else if (!__btf_type_is_struct(ptr_type)) { if (!meta.ret_mem.found) { From 54b59a467bc7aad34c511817492467d16dc46f1a Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:18 +0000 Subject: [PATCH 1897/2102] bpf: Require CAP_PERFMON to read streams A loader that has CAP_BPF only can read the streams of its program. Reports of the kernel have addresses in them: those of locks after a deadlock, and of code that has no symbol in call traces. Require CAP_PERFMON for BPF_PROG_STREAM_READ_BY_FD and BPF_PROG_STREAM_OPEN, through the token of the program if it has one. Fixes: ecec5b5743bf ("bpf: Report rqspinlock deadlocks/timeout to BPF stderr") Fixes: d7c431cafcb4 ("bpf: Add dump_stack() analogue to print to BPF stderr") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-28-alexei.starovoitov@gmail.com --- include/uapi/linux/bpf.h | 3 ++- kernel/bpf/stream.c | 4 ++++ tools/include/uapi/linux/bpf.h | 3 ++- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/include/uapi/linux/bpf.h b/include/uapi/linux/bpf.h index 8d72288343054b..6840ca5b923bf1 100644 --- a/include/uapi/linux/bpf.h +++ b/include/uapi/linux/bpf.h @@ -934,6 +934,7 @@ union bpf_iter_link_info { * by *prog_fd*, and the stream is identified by the *stream_id*. * The data is copied to a buffer pointed to by *stream_buf*, and * filled less than or equal to *stream_buf_len* bytes. + * The caller needs **CAP_PERFMON**. * * Return * Number of bytes read from the stream on success, or -1 if an @@ -953,7 +954,7 @@ union bpf_iter_link_info { * Description * Open a file descriptor for one of the BPF streams associated * with the program identified by *prog_fd*. The stream is selected - * by *stream_id*. + * by *stream_id*. The caller needs **CAP_PERFMON**. * * The returned file descriptor supports **read**\ (2) and * **poll**\ (2). Reads block while the stream is empty unless diff --git a/kernel/bpf/stream.c b/kernel/bpf/stream.c index 65f65876afdb84..53519a17bf261d 100644 --- a/kernel/bpf/stream.c +++ b/kernel/bpf/stream.c @@ -268,6 +268,8 @@ int bpf_prog_stream_read(struct bpf_prog *prog, enum bpf_stream_id stream_id, vo { struct bpf_stream *stream; + if (!bpf_token_capable(prog->aux->token, CAP_PERFMON)) + return -EPERM; stream = bpf_stream_get(stream_id, prog->aux); if (!stream) return -ENOENT; @@ -368,6 +370,8 @@ int bpf_prog_stream_new_fd(struct bpf_prog *prog, enum bpf_stream_id stream_id, int fd_flags = O_RDONLY | O_CLOEXEC; int fd; + if (!bpf_token_capable(prog->aux->token, CAP_PERFMON)) + return -EPERM; stream = bpf_stream_get(stream_id, prog->aux); if (!stream) return -ENOENT; diff --git a/tools/include/uapi/linux/bpf.h b/tools/include/uapi/linux/bpf.h index 8d72288343054b..6840ca5b923bf1 100644 --- a/tools/include/uapi/linux/bpf.h +++ b/tools/include/uapi/linux/bpf.h @@ -934,6 +934,7 @@ union bpf_iter_link_info { * by *prog_fd*, and the stream is identified by the *stream_id*. * The data is copied to a buffer pointed to by *stream_buf*, and * filled less than or equal to *stream_buf_len* bytes. + * The caller needs **CAP_PERFMON**. * * Return * Number of bytes read from the stream on success, or -1 if an @@ -953,7 +954,7 @@ union bpf_iter_link_info { * Description * Open a file descriptor for one of the BPF streams associated * with the program identified by *prog_fd*. The stream is selected - * by *stream_id*. + * by *stream_id*. The caller needs **CAP_PERFMON**. * * The returned file descriptor supports **read**\ (2) and * **poll**\ (2). Reads block while the stream is empty unless From 419c69483a62c9b91654e9fa32e3782efea5dc7c Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:19 +0000 Subject: [PATCH 1898/2102] bpf: Limit reads of variables of the kernel ld_imm64 of a variable that is not a struct gives readable memory, so do bpf_per_cpu_ptr() and bpf_this_cpu_ptr(). Many variables hold addresses, and CAP_BPF is enough to read them. The size comes from BTF, and that can be BTF of the program. Loads from such memory are not probed. Ask for CAP_PERFMON, as for the access to a struct. Addresses of functions and of per-cpu variables can be loaded as before. Take BTF of the kernel and of modules only, libbpf passes no other. Fixes: eaa6bcb71ef6 ("bpf: Introduce bpf_per_cpu_ptr()") Fixes: 541c3bad8dc5 ("bpf: Support BPF ksym variables in kernel modules") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-29-alexei.starovoitov@gmail.com --- kernel/bpf/helpers.c | 8 ++++---- kernel/bpf/verifier.c | 11 +++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index 61ddc45b033051..b570b7314ab492 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -2185,10 +2185,6 @@ bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) return &bpf_spin_unlock_proto; case BPF_FUNC_jiffies64: return &bpf_jiffies64_proto; - case BPF_FUNC_per_cpu_ptr: - return &bpf_per_cpu_ptr_proto; - case BPF_FUNC_this_cpu_ptr: - return &bpf_this_cpu_ptr_proto; case BPF_FUNC_timer_init: return &bpf_timer_init_proto; case BPF_FUNC_timer_set_callback: @@ -2292,6 +2288,10 @@ bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) return &bpf_get_branch_snapshot_proto; case BPF_FUNC_find_vma: return &bpf_find_vma_proto; + case BPF_FUNC_per_cpu_ptr: + return &bpf_per_cpu_ptr_proto; + case BPF_FUNC_this_cpu_ptr: + return &bpf_this_cpu_ptr_proto; default: return NULL; } diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 410804e8039292..3cfc64e2f9e107 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -20989,6 +20989,12 @@ static int __check_pseudo_btf_id(struct bpf_verifier_env *env, } } + if (!percpu && !env->allow_ptr_leaks) { + verbose(env, "access to '%s' is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", + sym_name); + return -EPERM; + } + type = t->type; t = btf_type_skip_modifiers(btf, type, NULL); if (percpu) { @@ -21034,6 +21040,11 @@ static int check_pseudo_btf_id(struct bpf_verifier_env *env, verbose(env, "invalid module BTF object FD specified.\n"); return -EINVAL; } + if (!btf_is_kernel(btf)) { + verbose(env, "BTF fd for ksym is not a kernel BTF\n"); + btf_put(btf); + return -EINVAL; + } } else { if (!btf_vmlinux) { verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); From b8aa487429d46a72881933c026a6ca2a8e72d6d2 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:20 +0000 Subject: [PATCH 1899/2102] bpf: Require CAP_PERFMON for dumps of xlated insns The verifier puts addresses of the kernel to insns: for ksyms, inlined helpers and hidden arguments. The dump of xlated insns hides the ones of maps and calls only, the others look like constants by then. Give no dump, as for a blinded program, to who has no CAP_PERFMON and can't read kallsyms. Fixes: 2c78ee898d8f ("bpf: Implement CAP_BPF") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-30-alexei.starovoitov@gmail.com --- kernel/bpf/syscall.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c index e82ae48c0bc075..7e1085d6a67e86 100644 --- a/kernel/bpf/syscall.c +++ b/kernel/bpf/syscall.c @@ -5261,7 +5261,8 @@ static int bpf_prog_get_info_by_fd(struct file *file, struct bpf_insn *insns_sanitized; bool fault; - if (!prog->blinded || bpf_dump_raw_ok(file->f_cred)) { + /* The verifier puts addresses to ld_imm64 and mov insns */ + if (bpf_dump_raw_ok(file->f_cred) || (!prog->blinded && perfmon_capable())) { insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred); if (!insns_sanitized) return -ENOMEM; From 8252c3517f95f02a8569480563a773e0462dce52 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:21 +0000 Subject: [PATCH 1900/2102] bpf: Zero bpf_list_head in copies of map values Lookups from user space copy the value to a buffer and init special fields there. An empty list_head points to itself. The caller gets the address of the buffer. Fill the fields with zeros. It's what a new element of a map has. bpf_refcount in a value reads as 0. Fixes: 3e81740a9062 ("bpf: Centralize btf_field-specific initialization logic") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-31-alexei.starovoitov@gmail.com --- include/linux/bpf.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/include/linux/bpf.h b/include/linux/bpf.h index 448431c4cd2d2d..5d4b0e5d56dceb 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -566,7 +566,14 @@ static inline void bpf_obj_init(const struct btf_record *rec, void *obj) */ static inline void check_and_init_map_value(struct bpf_map *map, void *dst) { - bpf_obj_init(map->record, dst); + const struct btf_record *rec = map->record; + int i; + + if (IS_ERR_OR_NULL(rec)) + return; + /* Not bpf_obj_init(): an empty list_head has the address of 'dst' */ + for (i = 0; i < rec->cnt; i++) + memset(dst + rec->fields[i].offset, 0, rec->fields[i].size); } /* memcpy that is used with 8-byte aligned pointers, power-of-8 size and From 398557b30b9cd673a762d284c714b5c6b2769fbe Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:22 +0000 Subject: [PATCH 1901/2102] bpf: Require CAP_PERFMON to read pinned maps with special fields A read of a pinned map prints values as they are in memory. bpf_timer, bpf_wq, bpf_list_head and bpf_rb_root are arrays of u64 for BTF and have addresses. Refuse open() of the file. BPF_OBJ_GET works as before. Fixes: b00628b1c7d5 ("bpf: Introduce bpf timers.") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-32-alexei.starovoitov@gmail.com --- kernel/bpf/inode.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/kernel/bpf/inode.c b/kernel/bpf/inode.c index 50dad8a3936af0..eefd1da179c524 100644 --- a/kernel/bpf/inode.c +++ b/kernel/bpf/inode.c @@ -310,6 +310,11 @@ static int bpffs_map_open(struct inode *inode, struct file *file) struct seq_file *m; int err; + /* Special fields are printed as they are. Most have addresses. */ + if (btf_record_has_field(map->record, ~(BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) && + !perfmon_capable()) + return -EPERM; + iter = map_iter_alloc(map); if (!iter) return -ENOMEM; From 5fec973f49daeb6f21993d9ea94f1231c975191b Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:23 +0000 Subject: [PATCH 1902/2102] bpf: Require CAP_PERFMON to pass values of insn_array as memory The value of an insn_array has addresses in the JIT image. Helpers take it for plain memory. Refuse to pass it without CAP_PERFMON. gotox works as before. Fixes: 493d9e0d6083 ("bpf, x86: add support for indirect jumps") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-33-alexei.starovoitov@gmail.com --- kernel/bpf/verifier.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 3cfc64e2f9e107..554d99c1c9430a 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -7970,6 +7970,10 @@ static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_ return check_mem_region_access(env, reg, argno, 0, access_size, reg->map_ptr->key_size, false); case PTR_TO_MAP_VALUE: + if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY && !env->allow_ptr_leaks) { + verbose(env, "%s leaks addr from insn_array\n", reg_arg_name(env, argno)); + return -EACCES; + } if (check_map_access_type(env, reg, 0, access_size, access_type)) return -EACCES; return check_map_access(env, reg, argno, 0, access_size, From f9e4fda5eb350f4a310eb266cad83d55c14b3e1c Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:24 +0000 Subject: [PATCH 1903/2102] bpf: Require CAP_PERFMON for the dump of all storages of sockets inet_diag dumps values of all sk_storage maps when the request names no map. It takes CAP_BPF and no fd. These are data of other programs, and tracing programs keep addresses and memory of the kernel there. Ask for CAP_PERFMON. "ss --bpf-maps" needs it then. A request with fds of maps works as before. Fixes: 2c78ee898d8f ("bpf: Implement CAP_BPF") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-34-alexei.starovoitov@gmail.com --- net/core/bpf_sk_storage.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/net/core/bpf_sk_storage.c b/net/core/bpf_sk_storage.c index 1c59300af05c7e..67288177492ac1 100644 --- a/net/core/bpf_sk_storage.c +++ b/net/core/bpf_sk_storage.c @@ -502,6 +502,10 @@ bpf_sk_storage_diag_alloc(const struct nlattr *nla_stgs) nr_maps++; } + /* It's a dump of all maps, see bpf_sk_storage_diag_put() */ + if (!nr_maps && !perfmon_capable()) + return ERR_PTR(-EPERM); + diag = kzalloc_flex(*diag, maps, nr_maps); if (!diag) return ERR_PTR(-ENOMEM); From 9bc9dab411133a7d14536351793c8ed3c5f3faba Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:25 +0000 Subject: [PATCH 1904/2102] bpf, x86: Do not use the paranoid ITS thunk The paranoid thunk completes the check of a hash, it traps when ZF is clear. The JIT emits no such check. With paranoid FineIBT, the default with IBT and no FRED, on a cpu that has ITS the kernel oopses at an indirect tail call, at gotox, and when an XDP program is not in the dispatcher: CFI failure at __x86_indirect_its_thunk_array+0x3d/0x3e Take the plain thunk. its_static_thunk() has no user after this. The miss of the dispatcher is an indirect jump to bpf_func. FineIBT has no ENDBR there, with or without ITS. Jump to bpf_dispatcher_nop_func(), it goes through the preamble. Fixes: 4f9087f16651 ("x86/cfi,bpf: Fix BPF JIT call") Fixes: e52c1dc7455d ("x86/its: FineIBT-paranoid vs ITS") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-35-alexei.starovoitov@gmail.com --- arch/x86/net/bpf_jit_comp.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c index 4c3e09d98131d2..4411fa667027cd 100644 --- a/arch/x86/net/bpf_jit_comp.c +++ b/arch/x86/net/bpf_jit_comp.c @@ -683,6 +683,12 @@ static void __emit_indirect_jump(u8 **pprog, int reg, bool ereg) *pprog = prog; } +/* its_static_thunk() can give the one that completes the check of a hash */ +static u8 *its_thunk(int reg) +{ + return IS_ENABLED(CONFIG_MITIGATION_ITS) ? __x86_indirect_its_thunk_array[reg] : NULL; +} + static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip) { u8 *prog = *pprog; @@ -691,7 +697,7 @@ static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip) if (cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS)) { OPTIMIZER_HIDE_VAR(reg); - emit_jump(&prog, its_static_thunk(reg + 8*ereg), ip); + emit_jump(&prog, its_thunk(reg + 8*ereg), ip); } else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) { EMIT_LFENCE(); __emit_indirect_jump(&prog, reg, ereg); @@ -732,7 +738,7 @@ static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip) if (cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS)) { OPTIMIZER_HIDE_VAR(reg); - err = emit_call(&prog, its_static_thunk(reg + 8*ereg), ip); + err = emit_call(&prog, its_thunk(reg + 8*ereg), ip); } else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) { EMIT_LFENCE(); __emit_indirect_call(&prog, reg, ereg); @@ -4675,6 +4681,7 @@ int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags, static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image, u8 *buf) { + void *nop_func = bpf_dispatcher_nop_func; u8 *jg_reloc, *prog = *pprog; int pivot, err, jg_bytes = 1; s64 jg_offset; @@ -4694,7 +4701,11 @@ static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image, if (err) return err; - emit_indirect_jump(&prog, BPF_REG_3 /* R3 -> rdx */, image + (prog - buf)); + /* With FineIBT there is no ENDBR at bpf_func, go through the preamble */ + OPTIMIZER_HIDE_VAR(nop_func); + err = emit_jump(&prog, nop_func, image + (prog - buf)); + if (err) + return err; *pprog = prog; return 0; From 62a99ab25c915c15d2cbd422d62e45834d45898e Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:26 +0000 Subject: [PATCH 1905/2102] bpf, x86: Enforce alignment of atomics in arenas A program chooses the address of an atomic insn in an arena at run time, the verifier does not check it. A locked insn that crosses a cache line locks the bus, and with split_lock_detect it is fatal in the kernel. Copy the low bits of the address to its top bits. A misaligned address is not canonical then, and the access goes the way of a fault in the arena: the insn is skipped, a fetch gives 0, the report is in the stream of the program. That is what arm64 does after an alignment fault. Fixes: d503a04f8bc0 ("bpf: Add support for certain atomics in bpf_arena to x86 JIT") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-36-alexei.starovoitov@gmail.com --- arch/x86/net/bpf_jit_comp.c | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c index 4411fa667027cd..0624290633cce5 100644 --- a/arch/x86/net/bpf_jit_comp.c +++ b/arch/x86/net/bpf_jit_comp.c @@ -1687,6 +1687,23 @@ static int emit_atomic_rmw_index(u8 **pprog, u32 atomic_op, u32 size, return 0; } +/* + * AUX_REG = dst_reg, with the low bits of dst_reg + off in the top bits. r12 + AUX_REG + off + * is not canonical when it's not aligned: the access faults, no split lock is taken. + */ +static void emit_arena_align_check(u8 **pprog, const struct bpf_insn *insn, u32 dst_reg) +{ + int size = BPF_LDST_BYTES(insn); + u8 *prog = *pprog; + + /* lea r11, [dst_reg + off % size] */ + EMIT2(add_2mod(0x48, dst_reg, AUX_REG), 0x8D); + emit_insn_suffix(&prog, dst_reg, AUX_REG, insn->off & (size - 1)); + emit_shift_imm(&prog, BPF_LSH, AUX_REG, 64 - ilog2(size), true); + emit_alu_reg(&prog, BPF_OR, AUX_REG, dst_reg, true); + *pprog = prog; +} + static int emit_atomic_ld_st(struct bpf_verifier_env *env, u8 **pprog, struct bpf_insn *insn, u8 *ip, u32 dst_reg, u32 src_reg, bool accesses_stack_only) @@ -1771,12 +1788,14 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg, branch_target = prog; /* Load old value */ + if (index_reg >= 0) + emit_arena_align_check(&prog, insn, dst_reg); if (fault) fault[0] = prog; if (index_reg < 0) emit_ldx(&prog, BPF_SIZE(insn->code), BPF_REG_0, dst_reg, insn->off); else - emit_ldx_index(&prog, BPF_SIZE(insn->code), BPF_REG_0, dst_reg, + emit_ldx_index(&prog, BPF_SIZE(insn->code), BPF_REG_0, AUX_REG, index_reg, insn->off); /* @@ -3409,6 +3428,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * } break; } + if (!bpf_atomic_is_load_store(insn)) + emit_arena_align_check(&prog, insn, dst_reg); start_of_ldx = prog; if (bpf_atomic_is_load_store(insn)) @@ -3417,7 +3438,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * src_reg, X86_REG_R12, insn->off); else err = emit_atomic_rmw_index(&prog, insn->imm, BPF_SIZE(insn->code), - dst_reg, src_reg, X86_REG_R12, + AUX_REG, src_reg, X86_REG_R12, insn->off); if (err) return err; From 1c34522e8b78b3d91b75fd7bd2318c8e7e293a76 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:27 +0000 Subject: [PATCH 1906/2102] bpf, x86: Fix the range of BPF code that has a frame pointer The ORC unwinder trusts rbp between ksym.fp_start and ksym.fp_end. The JIT sets fp_end to an offset in the code of the exit insn, and fp_start counts the CFI preamble, which is in front of the symbol. The main program of a program with subprogs and trampolines of struct_ops get neither. The range ends at the epilogue, compilers put blocks behind it. So stack traces with BPF code in them are not reliable, and livepatch waits for tasks that sleep there. Behind the prologue of a program only the return has no frame. Record its offset in fp_ret and take all the rest. Count from the start of the symbol, copy the offsets from func[0], and from a struct bpf_tramp_image that struct_ops passes for the time of the call. Fixes: ca45c84afb8c ("bpf: Add bpf_has_frame_pointer()") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-37-alexei.starovoitov@gmail.com --- arch/x86/net/bpf_jit_comp.c | 11 +++++------ include/linux/bpf.h | 5 +++-- kernel/bpf/bpf_struct_ops.c | 12 +++++++++--- kernel/bpf/core.c | 2 +- kernel/bpf/fixups.c | 3 +++ net/bpf/bpf_dummy_struct_ops.c | 2 +- 6 files changed, 22 insertions(+), 13 deletions(-) diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c index 0624290633cce5..a45668e971a44a 100644 --- a/arch/x86/net/bpf_jit_comp.c +++ b/arch/x86/net/bpf_jit_comp.c @@ -2600,7 +2600,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * bpf_prog_was_classic(bpf_prog), tail_call_reachable, bpf_is_subprog(bpf_prog), bpf_prog->aux->exception_cb); - bpf_prog->aux->ksym.fp_start = prog - temp; + bpf_prog->aux->ksym.fp_start = prog - temp - cfi_get_offset(); + bpf_prog->aux->ksym.fp_end = U32_MAX; /* Exception callback will clobber callee regs for its own use, and * restore the original callee regs from main prog's stack frame. @@ -3828,7 +3829,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * pop_r12(&prog); } EMIT1(0xC9); /* leave */ - bpf_prog->aux->ksym.fp_end = prog - temp; + bpf_prog->aux->ksym.fp_ret = proglen + (prog - temp) - cfi_get_offset(); emit_return(&prog, image + addrs[i - 1] + (prog - temp)); break; @@ -4480,8 +4481,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im } EMIT1(0x55); /* push rbp */ EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */ - if (im) - im->ksym.fp_start = prog - (u8 *)rw_image; + im->ksym.fp_start = prog - (u8 *)rw_image; /* sub rsp, stack_size */ emit_sub_rsp(&prog, stack_size); @@ -4622,8 +4622,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, -rbx_off); EMIT1(0xC9); /* leave */ - if (im) - im->ksym.fp_end = prog - (u8 *)rw_image; + im->ksym.fp_end = prog - (u8 *)rw_image; if (flags & BPF_TRAMP_F_SKIP_FRAME) { /* skip our return address and return to parent */ diff --git a/include/linux/bpf.h b/include/linux/bpf.h index 5d4b0e5d56dceb..3a5a0380304dc5 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -1426,6 +1426,7 @@ struct bpf_ksym { bool prog; u32 fp_start; u32 fp_end; + u32 fp_ret; /* a return in between, it has no frame */ }; enum bpf_tramp_prog_type { @@ -1470,7 +1471,7 @@ static inline void bpf_tramp_image_add_skip(struct bpf_tramp_image *im, struct b { struct bpf_tramp_skip *skip; - /* struct_ops trampolines and arch_bpf_trampoline_size() have no image */ + /* struct_ops trampolines and arch_bpf_trampoline_size() have none */ if (!im || !im->skips) return; skip = &im->skips[im->nr_skips++]; @@ -2400,7 +2401,7 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes, const struct btf_func_model *model, void *stub_func, void **image, u32 *image_off, - bool allow_alloc); + bool allow_alloc, struct bpf_ksym *ksym); void bpf_struct_ops_image_free(void *image); static inline bool bpf_try_module_get(const void *data, struct module *owner) { diff --git a/kernel/bpf/bpf_struct_ops.c b/kernel/bpf/bpf_struct_ops.c index 71235df99cc978..5461e0ebab2b63 100644 --- a/kernel/bpf/bpf_struct_ops.c +++ b/kernel/bpf/bpf_struct_ops.c @@ -640,9 +640,10 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes, const struct btf_func_model *model, void *stub_func, void **_image, u32 *_image_off, - bool allow_alloc) + bool allow_alloc, struct bpf_ksym *ksym) { u32 image_off = *_image_off, flags = BPF_TRAMP_F_INDIRECT; + struct bpf_tramp_image im = {}; void *image = *_image; int size; @@ -667,7 +668,7 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes, image_off = 0; } - size = arch_prepare_bpf_trampoline(NULL, image + image_off, + size = arch_prepare_bpf_trampoline(&im, image + image_off, image + image_off + size, model, flags, tnodes, stub_func); if (size <= 0) { @@ -676,6 +677,10 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes, return size ? : -EFAULT; } + if (ksym) { + ksym->fp_start = im.ksym.fp_start; + ksym->fp_end = im.ksym.fp_end; + } *_image = image; *_image_off = image_off + size; return 0; @@ -879,7 +884,8 @@ static long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key, &st_ops->func_models[i], *(void **)(st_ops->cfi_stubs + moff), &image, &image_off, - st_map->image_pages_cnt < MAX_TRAMP_IMAGE_PAGES); + st_map->image_pages_cnt < MAX_TRAMP_IMAGE_PAGES, + ksym); if (err) goto reset_unlock; diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index 50d175fcef6960..b34d9bdaf67e59 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -785,7 +785,7 @@ bool bpf_has_frame_pointer(unsigned long ip) offset = ip - ksym->start; - return offset >= ksym->fp_start && offset < ksym->fp_end; + return offset >= ksym->fp_start && offset < ksym->fp_end && offset != ksym->fp_ret; } const struct exception_table_entry *search_bpf_extables(unsigned long addr) diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c index 59dcd91ed5517c..9d5f2774bf8f83 100644 --- a/kernel/bpf/fixups.c +++ b/kernel/bpf/fixups.c @@ -1572,6 +1572,9 @@ static int jit_subprogs(struct bpf_verifier_env *env) prog->jited_len = func[0]->jited_len; prog->aux->extable = func[0]->aux->extable; prog->aux->num_exentries = func[0]->aux->num_exentries; + prog->aux->ksym.fp_start = func[0]->aux->ksym.fp_start; + prog->aux->ksym.fp_end = func[0]->aux->ksym.fp_end; + prog->aux->ksym.fp_ret = func[0]->aux->ksym.fp_ret; prog->aux->func = func; prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; prog->aux->real_func_cnt = env->subprog_cnt; diff --git a/net/bpf/bpf_dummy_struct_ops.c b/net/bpf/bpf_dummy_struct_ops.c index 191a6b3ee25415..c724a6bc7b807b 100644 --- a/net/bpf/bpf_dummy_struct_ops.c +++ b/net/bpf/bpf_dummy_struct_ops.c @@ -179,7 +179,7 @@ int bpf_struct_ops_test_run(struct bpf_prog *prog, const union bpf_attr *kattr, &st_ops->func_models[op_idx], &dummy_ops_test_ret_function, &image, &image_off, - true); + true, NULL); if (err < 0) goto out; From 918bea2c6b682405b20cde0f44e76b0161dde912 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:28 +0000 Subject: [PATCH 1907/2102] bpf, arm64: Restore the shadow call stack pointer after an exception bpf_throw() does not return, its return address stays on the shadow call stack. The caller of the program takes it for its own. test_progs -t exceptions crashes the kernel with CONFIG_SHADOW_CALL_STACK: Internal error: Oops - FPAC: 0000000072000000 [#1] SMP pc : bpf_test_run+0x410/0x968 JITed code puts nothing on the shadow call stack, and bpf_throw() skips only frames of JITed code. So that address is the only entry that is left behind. Pop it in the prologue of the exception callback. Fixes: 22fc0e80aeb5 ("bpf, arm64: support exceptions") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-38-alexei.starovoitov@gmail.com --- arch/arm64/net/bpf_jit_comp.c | 7 +++++++ kernel/bpf/helpers.c | 1 + 2 files changed, 8 insertions(+) diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c index 33632fb20997b7..bee2d3f6b868f6 100644 --- a/arch/arm64/net/bpf_jit_comp.c +++ b/arch/arm64/net/bpf_jit_comp.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -600,6 +601,12 @@ static int build_prologue(struct jit_ctx *ctx, bool ebpf_from_cbpf) * 12 registers are on the stack */ emit(A64_SUB_I(1, A64_SP, A64_FP, 96), ctx); + /* + * Pop the return address of bpf_throw() from the shadow call + * stack. The frames of the JIT put nothing there. + */ + if (scs_is_enabled()) + emit(A64_SUB_I(1, A64_R(18), A64_R(18), 8), ctx); /* The callback may use its own BPF stack, set up fp for it. */ ctx->fp_used = true; } diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index b570b7314ab492..a0fd6bdb3278e0 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -3474,6 +3474,7 @@ __bpf_kfunc notrace __no_sanitize_address void bpf_throw(u64 cookie) WARN_ON_ONCE(!ctx.aux->exception_boundary); WARN_ON_ONCE(!ctx.bp); WARN_ON_ONCE(!ctx.cnt); + /* arm64 drops one entry of the shadow call stack, don't move the call to a callee */ ctx.aux->bpf_exception_cb(cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust, ctx.bp, 0, 0); WARN(1, "A call to BPF exception callback should never return\n"); } From 401fce9f48b1d684b92dbc08389d7c20bd036280 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:29 +0000 Subject: [PATCH 1908/2102] bpf: Clear the data that bpf_msg_push_data() adds The helper puts a new page into the message as the allocator gave it. Bytes that the program does not write can be read by it, and are sent to the peer. Allocate zeroed memory. Fixes: 6fff607e2f14 ("bpf: sk_msg program helper bpf_msg_push_data") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-39-alexei.starovoitov@gmail.com --- net/core/filter.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/core/filter.c b/net/core/filter.c index b9dbdd276b0246..b4057a6cdd7c1d 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -2902,7 +2902,7 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, if (unlikely(copy + len < copy)) return -EINVAL; - page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP, + page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP | __GFP_ZERO, get_order(copy + len)); if (unlikely(!page)) return -ENOMEM; From 766907cdaeefb57faddc5d09a49bdd4ce20a6272 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:30 +0000 Subject: [PATCH 1909/2102] bpf: Fail loads from a network header that was not set skb->network_header is 0 until something sets it. Loads at SKF_NET_OFF and bpf_skb_load_bytes_relative() start at skb->head then, and read headroom that nobody has written. qrtr and AF_XDP in copy mode make such skbs. Fail the load, like for the MAC header. A network header at skb->head counts as set when skb->data or the MAC header is there too. CAN and 6LoWPAN make such skbs. Fixes: 2e07fa9cd3ba ("[SK_BUFF]: Use offsets for skb->{mac,network,transport}_header on 64bit architectures") Fixes: 0f5d82f187e1 ("net/filter: Permit reading NET in load_bytes_relative when MAC not set") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-40-alexei.starovoitov@gmail.com --- include/linux/filter.h | 9 +++++++++ kernel/bpf/core.c | 2 ++ net/core/filter.c | 5 ++++- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/include/linux/filter.h b/include/linux/filter.h index 5cf3582823f579..84d770aea722b5 100644 --- a/include/linux/filter.h +++ b/include/linux/filter.h @@ -1055,6 +1055,15 @@ static inline void bpf_restore_data_end( cb->data_end = saved_data_end; } +/* + * If nothing has set the header, it points to headroom that was not written. + * The packet starts at skb->head when skb->data or the MAC header is there. + */ +static inline bool bpf_skb_has_network_header(const struct sk_buff *skb) +{ + return skb->network_header || !skb->mac_header || !skb_headroom(skb); +} + static inline u8 *bpf_skb_cb(const struct sk_buff *skb) { /* eBPF programs may read/write skb->cb[] area to transfer meta diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index b34d9bdaf67e59..6742f5be865860 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -83,6 +83,8 @@ void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, uns u8 *ptr = NULL; if (k >= SKF_NET_OFF) { + if (unlikely(!bpf_skb_has_network_header(skb))) + return NULL; ptr = skb_network_header(skb) + k - SKF_NET_OFF; } else if (k >= SKF_LL_OFF) { if (unlikely(!skb_mac_header_was_set(skb))) diff --git a/net/core/filter.c b/net/core/filter.c index b4057a6cdd7c1d..2415cd90ab5d62 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -232,7 +232,8 @@ static int bpf_skb_load_helper_convert_offset(const struct sk_buff *skb, int off return offset; if (offset >= SKF_NET_OFF) - return offset - SKF_NET_OFF + skb_network_offset(skb); + return bpf_skb_has_network_header(skb) ? + offset - SKF_NET_OFF + skb_network_offset(skb) : INT_MIN; if (offset >= SKF_LL_OFF && skb_mac_header_was_set(skb)) return offset - SKF_LL_OFF + skb_mac_offset(skb); @@ -1862,6 +1863,8 @@ BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb, start = skb_mac_header(skb); break; case BPF_HDR_START_NET: + if (unlikely(!bpf_skb_has_network_header(skb))) + goto err_clear; start = skb_network_header(skb); break; default: From 2fc7a1733992e28d4c89f57e2c237b85b236d83c Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:31 +0000 Subject: [PATCH 1910/2102] bpf: Fix slices behind the end of an XDP packet A dynptr keeps the size that the packet had at bpf_dynptr_from_xdp(). When the packet has shrunk since, bpf_dynptr_slice() takes the error of bpf_xdp_pointer() for "not linear" and copies from the frags. A linear packet has none, its skb_shared_info is what the buffer held before. Return NULL. Don't look at the frags of a linear packet for a length of 0 at its end either. Fixes: 66e3a13e7c2c ("bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-41-alexei.starovoitov@gmail.com --- kernel/bpf/helpers.c | 4 +++- net/core/filter.c | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index a0fd6bdb3278e0..1b95fe795b4d9f 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -3144,7 +3145,8 @@ __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr *p, u64 offset, if (!IS_ERR_OR_NULL(xdp_ptr)) return xdp_ptr; - if (!buffer__nullable) + /* the packet may be shorter than it was for bpf_dynptr_from_xdp() */ + if (!buffer__nullable || ptr->offset + offset + len > xdp_get_buff_len(ptr->data)) return NULL; bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer__nullable, len, false); return buffer__nullable; diff --git a/net/core/filter.c b/net/core/filter.c index 2415cd90ab5d62..97f5d60ec81742 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -4326,7 +4326,7 @@ void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len) if (unlikely(offset + len > xdp_get_buff_len(xdp))) return ERR_PTR(-EINVAL); - if (likely(offset < size)) /* linear area */ + if (likely(offset < size || !xdp_buff_has_frags(xdp))) /* linear area */ goto out; sinfo = xdp_get_shared_info_from_buff(xdp); From 2abc088aae543fa97350df8b2dd5eedf622e380d Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:32 +0000 Subject: [PATCH 1911/2102] bpf: Clear family and port of a short address for cgroup sockaddr hooks recvmsg() from a unix socket that has no name leaves the buffer of the address as it is, and that is on the stack of the kernel. The program reads user_family and user_port whatever the length is. bpf_sock_addr_set_sun_path() sends the family to user space. Clear the bytes from the length up to 4. Write AF_UNIX next to the path in the kfunc. Fixes: 859051dd165e ("bpf: Implement cgroup sockaddr hooks for unix sockets") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-42-alexei.starovoitov@gmail.com --- kernel/bpf/cgroup.c | 4 ++++ net/core/filter.c | 1 + 2 files changed, 5 insertions(+) diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index 4e388d994d8073..1ff030f4314fb2 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -2010,6 +2010,10 @@ int __cgroup_bpf_run_filter_sock_addr(struct sock *sk, ctx.uaddrlen = 0; } else { ctx.uaddrlen = *uaddrlen; + /* Programs read the family and the port also of a short address. */ + if (ctx.uaddrlen < offsetofend(struct sockaddr_in, sin_port)) + memset((void *)uaddr + ctx.uaddrlen, 0, + offsetofend(struct sockaddr_in, sin_port) - ctx.uaddrlen); } cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data); diff --git a/net/core/filter.c b/net/core/filter.c index 97f5d60ec81742..eb6aeabb410e42 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -12633,6 +12633,7 @@ __bpf_kfunc int bpf_sock_addr_set_sun_path(struct bpf_sock_addr_kern *sa_kern, return -EINVAL; un = (struct sockaddr_un *)sa_kern->uaddr; + un->sun_family = AF_UNIX; memcpy(un->sun_path, sun_path, sun_path__sz); sa_kern->uaddrlen = offsetof(struct sockaddr_un, sun_path) + sun_path__sz; From c1b5decc73149f69db0b8d28ebcea204249e3b0b Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:33 +0000 Subject: [PATCH 1912/2102] bpf: Take a neighbour of the L3 master in bpf_redirect_neigh() bpf_redirect_neigh() takes the neighbour from the route, the skb gets the device that the program has named. They are not always the same for IPv4, and the queue of a neighbour is purged with its own device only. When a L3 master was named take a neighbour of that device, as IPv6 does. Its driver drops the header and routes the packet, one entry does for all. Fixes: ba452c9e996d ("bpf: Fix bpf_redirect_neigh helper api to support supplying nexthop") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-43-alexei.starovoitov@gmail.com --- net/core/filter.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/net/core/filter.c b/net/core/filter.c index eb6aeabb410e42..8d331802a7db6f 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -2367,7 +2367,11 @@ static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb, } rcu_read_lock(); - if (!nh) { + if (!nh && netif_is_l3_master(dev)) { + /* The route leads to another device, this one looks it up again */ + skb_dst_drop(skb); + neigh = ip_neigh_gw4(dev, htonl(INADDR_ANY)); + } else if (!nh) { struct rtable *rt = skb_rtable(skb); neigh = ip_neigh_for_gw(rt, skb, &is_v6gw); From 28ffeb9cb9722f39854f11e5f0511a4a8c12d9fb Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:34 +0000 Subject: [PATCH 1913/2102] bpf: Keep the MAC header in bpf_skb_change_tail() The least length of the skb is the offset of the transport header when it's set, also when that is below the offset of the network header. Callers of tc programs count on a skb that is not shorter than mac_len. Take the bigger one of the two offsets. Fixes: 5293efe62df8 ("bpf: add bpf_skb_change_tail helper") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-44-alexei.starovoitov@gmail.com --- net/core/filter.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/core/filter.c b/net/core/filter.c index 8d331802a7db6f..fb403e18a5d754 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -4044,7 +4044,7 @@ static u32 __bpf_skb_min_len(const struct sk_buff *skb) if (skb_transport_header_was_set(skb)) { offset = skb_transport_offset(skb); if (offset > 0) - min_len = offset; + min_len = max_t(u32, min_len, offset); } return min_len; } From b3a433f20f0a247cb2c4664b6e1400253287da63 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:35 +0000 Subject: [PATCH 1914/2102] bpf, sockmap: Keep the parser and sk_data_ready in sync sk_psock_strp_data_ready() takes the psock that the socket has at the call. An update from a program does not wait for the owner of the socket, so that is not always the psock that has set the callback, and it may have no parser. strp_data_ready() dereferences a NULL strp->sk then. Look at SK_PSOCK_RX_STRP_ENABLED, it is set under sk_callback_lock. The event is dropped, as it is when the socket has no psock. A socket can be in a map with a verdict program and not have it, the program was attached after the update. Another map can start the parser then. The delete from the first map restores sk_data_ready and nobody stops the parser: WARNING: net/strparser/strparser.c:451 at strp_done+0xef/0x130 Stop the parser when its callback goes away. The psock can outlive the stop, and a later update must not run strp_init() on works that are still pending. Start the stopped parser again instead. Fixes: 0126240f448d ("bpf: sockmap: Allow update from BPF") Fixes: ef5659280eb1 ("bpf, sockmap: Allow skipping sk_skb parser program") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-45-alexei.starovoitov@gmail.com --- net/core/skmsg.c | 12 +++++++++--- net/core/sock_map.c | 3 ++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/net/core/skmsg.c b/net/core/skmsg.c index 8a3b8536c0c218..1a0029f276e2f2 100644 --- a/net/core/skmsg.c +++ b/net/core/skmsg.c @@ -1149,7 +1149,9 @@ static void sk_psock_strp_data_ready(struct sock *sk) psock = sk_psock(sk); if (likely(psock)) { read_lock_bh(&sk->sk_callback_lock); - strp_data_ready(&psock->strp); + /* This psock may be not the one that has set the callback */ + if (likely(sk_psock_test_state(psock, SK_PSOCK_RX_STRP_ENABLED))) + strp_data_ready(&psock->strp); read_unlock_bh(&sk->sk_callback_lock); } rcu_read_unlock(); @@ -1157,7 +1159,7 @@ static void sk_psock_strp_data_ready(struct sock *sk) int sk_psock_init_strp(struct sock *sk, struct sk_psock *psock) { - int ret; + int ret = 0; static const struct strp_callbacks cb = { .rcv_msg = sk_psock_strp_read, @@ -1165,7 +1167,11 @@ int sk_psock_init_strp(struct sock *sk, struct sk_psock *psock) .parse_msg = sk_psock_strp_parse, }; - ret = strp_init(&psock->strp, sk, &cb); + /* A stopped parser keeps its works and its skb until strp_done() */ + if (sk_psock_test_state(psock, SK_PSOCK_RX_STRP_ENABLED)) + psock->strp.stopped = 0; + else + ret = strp_init(&psock->strp, sk, &cb); if (!ret) sk_psock_set_state(psock, SK_PSOCK_RX_STRP_ENABLED); diff --git a/net/core/sock_map.c b/net/core/sock_map.c index 0d7a8d9405d196..ac62174e8e01e6 100644 --- a/net/core/sock_map.c +++ b/net/core/sock_map.c @@ -169,7 +169,8 @@ static void sock_map_del_link(struct sock *sk, write_lock_bh(&sk->sk_callback_lock); if (psock->saved_data_ready) { - if (strp_stop) + /* The parser can be from another map, it loses sk_data_ready too */ + if (strp_stop || psock->progs.stream_parser) sk_psock_stop_strp(sk, psock); if (verdict_stop) sk_psock_stop_verdict(sk, psock); From 9abfa0ad4f7606619586187152a0479efd306b13 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:36 +0000 Subject: [PATCH 1915/2102] bpf, sockmap: Hold the psock of the work in sk_psock_backlog() The socket can leave its map and come back after the test of SK_PSOCK_TX_ENABLED. sk_psock_get() takes a reference to the new psock then, and the work puts the old one that has none left. The new one and its socket are never freed. Take the reference that is put. Fixes: 8259eb0e06d8 ("bpf, sockmap: Avoid using sk_socket after free when sending") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-46-alexei.starovoitov@gmail.com --- net/core/skmsg.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/core/skmsg.c b/net/core/skmsg.c index 1a0029f276e2f2..005e09121f00ab 100644 --- a/net/core/skmsg.c +++ b/net/core/skmsg.c @@ -694,7 +694,7 @@ static void sk_psock_backlog(struct work_struct *work) * before sk_socket freed. If refcnt increment fails, it indicates * sock_map_close() completed with sk_socket potentially already freed. */ - if (!sk_psock_get(psock->sk)) + if (!refcount_inc_not_zero(&psock->refcnt)) return; mutex_lock(&psock->work_mutex); while ((skb = skb_peek(&psock->ingress_skb))) { From 434ea9c5125a8c3ad16e241687e1983309f99d1c Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:37 +0000 Subject: [PATCH 1916/2102] libbpf: Fix struct_ops members 59-61 and optional struct_ops maps expected_attach_type of a struct_ops program is the index of the member. For members 59, 60 and 61 it is equal to an attach type of tracing multi, and attach_btf_obj_fd is overwritten. The load fails when the struct is in a module. Look at the type of the program too. Only the first map of SEC("?.struct_ops") or SEC("?.struct_ops.link") is not created by default. The '?' is skipped in the loop over the variables, so the next ones do not see it. They are created, and their programs are loaded. Look at it once. Fixes: f2aa370dfe57 ("libbpf: Add support to create tracing multi link") Fixes: 5ad0ecbe056a ("libbpf: Struct_ops in SEC("?.struct_ops") / SEC("?.struct_ops.link")") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-47-alexei.starovoitov@gmail.com --- tools/lib/bpf/libbpf.c | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c index fb8a1f07c5b655..5f54a8e6f46fa0 100644 --- a/tools/lib/bpf/libbpf.c +++ b/tools/lib/bpf/libbpf.c @@ -1454,6 +1454,7 @@ static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name, __s32 type_id, datasec_id; const struct btf *btf; struct bpf_map *map; + bool optional; __u32 i; if (shndx == -1) @@ -1468,6 +1469,14 @@ static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name, return -EINVAL; } + /* + * Follow same convention as for programs autoload: + * SEC("?.struct_ops") means map is not created by default. + */ + optional = sec_name[0] == '?'; + /* from now on forget there was ? in section name */ + sec_name += optional; + datasec = btf__type_by_id(btf, datasec_id); vsi = btf_var_secinfos(datasec); for (i = 0; i < btf_vlen(datasec); i++, vsi++) { @@ -1503,14 +1512,8 @@ static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name, return -ENOMEM; map->btf_value_type_id = type_id; - /* Follow same convention as for programs autoload: - * SEC("?.struct_ops") means map is not created by default. - */ - if (sec_name[0] == '?') { + if (optional) map->autocreate = false; - /* from now on forget there was ? in section name */ - sec_name++; - } map->def.type = BPF_MAP_TYPE_STRUCT_OPS; map->def.key_size = sizeof(int); @@ -8407,7 +8410,7 @@ static int libbpf_prepare_prog_load(struct bpf_program *prog, opts->attach_btf_id = btf_type_id; } - if (is_tracing_multi(prog->expected_attach_type)) { + if (prog->type == BPF_PROG_TYPE_TRACING && is_tracing_multi(prog->expected_attach_type)) { int err, btf_obj_fd = 0; err = tracing_multi_mod_fd(prog, &btf_obj_fd); From 65e362827a6edf078ef8f5d34fbaea2ccb6b7879 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Wed, 25 Nov 2026 03:29:38 +0000 Subject: [PATCH 1917/2102] bpf: Check the type of R0 at the exit of a struct_ops program check_return_code() takes reg->btf for valid when it is not NULL. The field is in a union, so for other types of registers it holds something else, and the verifier follows that as a struct btf. Look at it only when the register is PTR_TO_BTF_ID. Fixes: 8d9f547f74c7 ("bpf: Allow struct_ops prog to return referenced kptr") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261125032938.670542-48-alexei.starovoitov@gmail.com --- kernel/bpf/verifier.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 554d99c1c9430a..d4b31990fcb9c6 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -19608,7 +19608,8 @@ static int check_return_code(struct bpf_verifier_env *env, int regno, const char * matches the operator's return type and is in its unmodified * form. A scalar zero (i.e., a null pointer) is also allowed. */ - reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; + reg_type = base_type(reg->type) == PTR_TO_BTF_ID ? + btf_type_by_id(reg->btf, reg->btf_id) : NULL; ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, prog->aux->attach_func_proto->type, NULL); From 080434cbb0e9bf03e83f35ebc1cb339546ff6e1a Mon Sep 17 00:00:00 2001 From: Hengyu Liang Date: Wed, 25 Nov 2026 13:08:17 -0500 Subject: [PATCH 1918/2102] io_uring/openclose: allow an empty path with O_EMPTYPATH Commit 31cf44efa6df ("vfs: add O_EMPTYPATH to openat(2)/openat2(2)") made build_open_flags() accept O_EMPTYPATH and turn it into LOOKUP_EMPTY, so that openat(fd, "", O_EMPTYPATH) reopens the file behind fd. However, io_uring also uses build_open_flags(), but __io_openat_prep() still copies the name with delayed_getname(), which rejects an empty name with -ENOENT. As of now, IORING_OP_OPENAT and IORING_OP_OPENAT2 accept O_EMPTYPATH, but fail on the empty path this flag is meant for. Before 31cf44efa6df, both calls fail: it prints "openat: -1" and "IORING_OP_OPENAT: -2". After that commit (v7.2), the result is: openat: 4 IORING_OP_OPENAT: -2 Copy the name with delayed_getname_uflags() and AT_EMPTY_PATH when O_EMPTYPATH is set, as io_uring's statx already does for AT_EMPTY_PATH. Fixes: 31cf44efa6df ("vfs: add O_EMPTYPATH to openat(2)/openat2(2)") Signed-off-by: Hengyu Liang Link: https://patch.msgid.link/20261125180817.3682397-1-hengyul@cs.unc.edu Reviewed-by: Jori Koolstra (CIQ) Signed-off-by: Jens Axboe --- io_uring/openclose.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/io_uring/openclose.c b/io_uring/openclose.c index 24cf3ce2e2bc3a..29fe31f16a2b21 100644 --- a/io_uring/openclose.c +++ b/io_uring/openclose.c @@ -54,6 +54,7 @@ static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe { struct io_open *open = io_kiocb_to_cmd(req, struct io_open); const char __user *fname; + int uflags = 0; int ret; if (unlikely(sqe->buf_index)) @@ -67,7 +68,9 @@ static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe open->dfd = READ_ONCE(sqe->fd); fname = u64_to_user_ptr(READ_ONCE(sqe->addr)); - ret = delayed_getname(&open->filename, fname); + if (open->how.flags & O_EMPTYPATH) + uflags = AT_EMPTY_PATH; + ret = delayed_getname_uflags(&open->filename, fname, uflags); if (unlikely(ret)) return ret; req->flags |= REQ_F_NEED_CLEANUP; From e50436deae925d1b95b01936e2499428c4782a6a Mon Sep 17 00:00:00 2001 From: Jiayuan Chen Date: Mon, 23 Nov 2026 20:24:31 +0800 Subject: [PATCH 1919/2102] tcp: fix negative sk_forward_alloc after MSG_ZEROCOPY append Our local syzbot reported the following warning: WARNING: ./include/linux/ucopysize.h:57 at tcp_sendmsg_locked+0x1e13/0x1f20 Modules linked in: CPU: 3 UID: 0 PID: 377 Comm: syz.2.2248 Not tainted 7.4.0-rc2+ #398 PREEMPT RIP: 0010:tcp_sendmsg_locked+0x1e13/0x1f20 Call Trace: tcp_sendmsg+0x2c/0x50 inet_sendmsg+0x62/0xb0 __sys_sendto+0x2fe/0x350 __x64_sys_sendto+0x7f/0xb0 x64_sys_call+0x1375/0x27e0 do_syscall_64+0xe4/0x470 entry_SYSCALL_64_after_hwframe+0x76/0x7e The problem is here: if (!skb_zcopy_pure(skb)) { copy = tcp_wmem_schedule(sk, copy); if (!copy) goto wait_for_space; } When MSG_ZEROCOPY data is appended to a skb that already holds copied data, only the user length is scheduled, but the pinned pages are then charged by their truesize: skb_zerocopy_iter_stream __zerocopy_sg_from_iter zerocopy_fill_skb_from_iter //truesize += PAGE_ALIGN(copied + start) sk_mem_charge(sk, truesize) //sk_forward_alloc goes negative For example, sending 8 iovecs of 1 byte each schedules 8 bytes and charges 32768 with 4K pages. On a later sendmsg() without MSG_ZEROCOPY, if sk_wmem_schedule() fails (e.g. tcp_mem hard limit is reached), tcp_wmem_schedule() returns min(copy, sk->sk_forward_alloc), which is negative. The negative copy is passed to skb_copy_to_page_nocache() and triggers the warning, and sendmsg() fails with -EFAULT. A few options were considered: 1) Schedule the truesize up front. It is not known before the pages are pinned, it depends on the iovec layout. 2) Do not append zerocopy data to a non pure skb. This splits a small header and its zerocopy payload into two skbs. 3) Schedule the missing part right after the pages are charged. They are already in the skb at this point, so this can not fail. Go with 3). Fixes: 849b425cd091 ("tcp: fix possible freeze in tx path under memory pressure") Signed-off-by: Jiayuan Chen Reviewed-by: Eric Dumazet Link: https://patch.msgid.link/20261123122432.297135-1-jiayuan.chen@linux.dev Signed-off-by: Willem de Bruijn --- net/ipv4/tcp.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/net/ipv4/tcp.c b/net/ipv4/tcp.c index 418842a2dfd98c..80de376a9d2ef9 100644 --- a/net/ipv4/tcp.c +++ b/net/ipv4/tcp.c @@ -1352,6 +1352,8 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size) err = skb_zerocopy_iter_stream(sk, skb, msg, copy, uarg, binding); + if (!skb_zcopy_pure(skb)) + sk_forced_mem_schedule(sk, 0); if (err == -EMSGSIZE || err == -EEXIST) { tcp_mark_push(tp, skb); goto new_segment; From ef3e21c61baa74e39a49b75318bd4541562ec43f Mon Sep 17 00:00:00 2001 From: Hungyu Lin Date: Mon, 23 Nov 2026 03:40:47 +0000 Subject: [PATCH 1920/2102] net/tcp-ao: fix reset key lookup for IPv4 segments on IPv6 listeners tcp_ao_prepare_reset() looks up the key for a reset that is sent on behalf of a listener by the address of the peer. It takes that address from the IPv6 header whenever the listener is an AF_INET6 socket, also when the segment is an IPv4 one that arrived on a dual-stack listener. The address is then read from the middle of the IPv4 header, the key of the peer is not found and the reset is not sent. The v4-mapped check that follows does not help: it looks at sk->sk_v6_daddr, which is the unspecified address for a listener, and it runs after the address has been picked. Take the family and the address from the protocol of the segment instead of the family of the socket. Fixes: 06b22ef29591 ("net/tcp: Wire TCP-AO to request sockets") Cc: stable@vger.kernel.org Signed-off-by: Hungyu Lin Reviewed-by: Eric Dumazet Acked-by: Dmitry Safonov <0x7f454c46@gmail.com> Link: https://patch.msgid.link/20261123034047.56745-1-dennylin0707@gmail.com Signed-off-by: Willem de Bruijn --- net/ipv4/tcp_ao.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/net/ipv4/tcp_ao.c b/net/ipv4/tcp_ao.c index bb7bbc20ba3fad..857b8684e01d93 100644 --- a/net/ipv4/tcp_ao.c +++ b/net/ipv4/tcp_ao.c @@ -799,8 +799,8 @@ int tcp_ao_prepare_reset(const struct sock *sk, struct sk_buff *skb, return -ENOTCONN; if ((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_NEW_SYN_RECV)) { - unsigned int family = READ_ONCE(sk->sk_family); union tcp_ao_addr *addr; + unsigned int family; __be32 disn, sisn; if (sk->sk_state == TCP_NEW_SYN_RECV) { @@ -813,14 +813,14 @@ int tcp_ao_prepare_reset(const struct sock *sk, struct sk_buff *skb, sisn = th->seq; disn = 0; } - if (IS_ENABLED(CONFIG_IPV6) && family == AF_INET6) + if (IS_ENABLED(CONFIG_IPV6) && + skb->protocol == htons(ETH_P_IPV6)) { + family = AF_INET6; addr = (union tcp_md5_addr *)&ipv6_hdr(skb)->saddr; - else - addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr; -#if IS_ENABLED(CONFIG_IPV6) - if (family == AF_INET6 && ipv6_addr_v4mapped(&sk->sk_v6_daddr)) + } else { family = AF_INET; -#endif + addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr; + } sk = sk_const_to_full_sk(sk); ao_info = rcu_dereference(tcp_sk(sk)->ao_info); From aceadbccd428fb8e6593b27a3091d961f80225d1 Mon Sep 17 00:00:00 2001 From: Theodore Ts'o Date: Wed, 25 Nov 2026 20:13:01 -0500 Subject: [PATCH 1921/2102] ext4: don't track metadata buffers on an inode during fast commit replay Fast commit replay runs without a journal handle and before EXT4_SB(sb)->s_journal is set, so it effectively runs in nojournal mode. __ext4_handle_dirty_metadata() then hands every extent tree block and directory block it dirties to mmb_mark_buffer_dirty(). Commit d4fdde3257a5 ("fs: set I_METADATA_WRITEBACK in mmb_mark_buffer_dirty()") sets this flag on the inode, which can trigger a NULL pointer dereference on a per-cpu pointer during the fast commit replay. This is because the iput at the end of each fast commit update triggers write_inode_now(), and with I_METADATA_WRITEBACK set, writeback_single_inode() will end up calling ext4_writepages(), before ext4_percpu_param_init() has initialized s_writepages_rwsem. A similar crash was fixed in commit 0ecd56573c1f ("ext4: Avoid entering writeback paths during fastcommit replay") by not setting this flag in ext4_mark_iloc_dirty(). This commit applies the same fix to __ext4_handle_dirty_metadata(). Once the fast commit replay is complete, jbd2_journal_recover() syncs and flushes the whole block device, o the buffer is still written out before the mount proceeds. Reproduced with generic/311 using "-O inline_data,fast_commit" (the ext4/adv test configuration). Fixes: d4fdde3257a5 ("fs: set I_METADATA_WRITEBACK in mmb_mark_buffer_dirty()") Cc: stable@vger.kernel.org Signed-off-by: Theodore Ts'o --- fs/ext4/ext4_jbd2.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/fs/ext4/ext4_jbd2.c b/fs/ext4/ext4_jbd2.c index 23e53c9cc0ceda..a52998c709da9b 100644 --- a/fs/ext4/ext4_jbd2.c +++ b/fs/ext4/ext4_jbd2.c @@ -432,7 +432,19 @@ int __ext4_handle_dirty_metadata(const char *where, unsigned int line, err); } } else { - if (inode) { + /* + * Fast commit replay runs without a handle, before the + * writeback paths are set up. Don't track the buffer in the + * inode's metadata list then: mmb_mark_buffer_dirty() sets + * I_METADATA_WRITEBACK, and since the superblock isn't active + * yet the iput() ending the replay step writes the inode out + * and enters ext4_writepages() before s_writepages_rwsem is + * initialized. Journal recovery flushes the whole block + * device once replay is done, so the buffer still gets + * written. + */ + if (inode && !(EXT4_SB(inode->i_sb)->s_mount_state & + EXT4_FC_REPLAY)) { if (!ext4_i_metadata_bhs(inode)) ext4_inode_attach_mmb(inode); mmb_mark_buffer_dirty(bh, ext4_i_metadata_bhs(inode)); From 25faec9ce61c01fb45abf812a222c5b43c3cd5c5 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Wed, 25 Nov 2026 21:57:38 -0800 Subject: [PATCH 1922/2102] net: dpaa2-eth: fix objtool warning and logic bug This commit came about because I locally had a build with COMPILE_TEST and various runtime hardening features (that don't make sense for a pure build test anyway) disabled - and objtool complained about some of the code as a result: drivers/net/ethernet/freescale/dpaa2/fsl-dpaa2-eth.o: warning: objtool: dpaa2_eth_add_bufs+0x3f8: stack state mismatch: reg1[15]=-1+0 reg2[15]=-2-208 The reason seems to be that without the hardening features, objtool notices that gcc is doing really odd things with the 'page' variable, which is uninitialized in the path where 'ch->xsk_zc' is true. Now, this seems to be just objtool becoming confused about some ugly code, but that code is _also_ actively buggy in a different way, so let's just fix this all. What confuses objtool seems to be the stack slot for the uninitialized 'page' variable - for the case where that variable isn't actually used. There is some shared error handling code that frees the previously allocated page or xsk buffers depending on previous state. That code is ugly and worth fixing: just free the page or buffers in the context where they are actually allocated, not at some common point where you have to wonder "which one is it I'm supposed to free again?". That gets rid of the objtool warning, because now gcc doesn't take messy and incomprehensible source code and turn it into messy and even more incomprehensible object code any more. No more questionable stack frames with CFI information that blows objtool's little mind. But fixing that then makes a real bug more obvious: the freeing of the xsk buffers is buggy. It frees the buffers that never got mapped: for (; i < batch; i++) xsk_buff_free(xdp_buffs[i]); and that looks sane enough: iterate over the unused part of the batch. But it's horrendously wrong, because it updates 'i'. And 'i' isn't some harmless little local loop counter. It's the variable that is supposed to contain how many buffers have been successfully mapped. So now that 'free the buffers we didn't map' loop ends up updating that counter, and after the loop 'i' will be the whole batch we allocated. So that loop first freed the buffers that failed to map, and then as a side effect said "all these buffers I just freed were successfully mapped" and they would be released to hardware. So objtool didn't actually find a real bug. It just found code that was so ugly that it triggered a false positive. And as is often the case with ugly code: people hadn't understood it either, and it was buggy. It's worth noting that the code is still ugly. A variable name like 'i' is perfectly fine for some random anonymous loop iterator that is just that. But when it has serious meaning outside the loop, you should give it a serious name that makes sense non-locally. This does not fix that kind of ugliness. This is just the minimal fix for the objtool warning and the entirely incidental bug it then uncovered. They had nothing in common except for the obfuscated C code contest entry. Fixes: 48276c08cf5d ("net: dpaa2-eth: AF_XDP RX zero copy support") Cc: Robert-Ionut Alexa Cc: Ioana Ciornei Cc: David S. Miller Cc: Andrew Lunn Cc: Jakub Kicinski Cc: Paolo Abeni Signed-off-by: Linus Torvalds --- .../net/ethernet/freescale/dpaa2/dpaa2-eth.c | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/drivers/net/ethernet/freescale/dpaa2/dpaa2-eth.c b/drivers/net/ethernet/freescale/dpaa2/dpaa2-eth.c index 9003cff88024c4..bb3c55d84d89ea 100644 --- a/drivers/net/ethernet/freescale/dpaa2/dpaa2-eth.c +++ b/drivers/net/ethernet/freescale/dpaa2/dpaa2-eth.c @@ -1681,11 +1681,9 @@ static int dpaa2_eth_add_bufs(struct dpaa2_eth_priv *priv, struct device *dev = priv->net_dev->dev.parent; u64 buf_array[DPAA2_ETH_BUFS_PER_CMD]; struct dpaa2_eth_swa *swa; - struct page *page; dma_addr_t addr; int retries = 0; int i = 0, err; - u32 batch; /* Allocate buffers visible to WRIOP */ if (!ch->xsk_zc) { @@ -1695,14 +1693,16 @@ static int dpaa2_eth_add_bufs(struct dpaa2_eth_priv *priv, * the entire page except for a tailroom reserved for * skb shared info */ - page = dev_alloc_pages(0); + struct page *page = dev_alloc_pages(0); if (!page) goto err_alloc; addr = dma_map_page(dev, page, 0, priv->rx_buf_size, DMA_BIDIRECTIONAL); - if (unlikely(dma_mapping_error(dev, addr))) - goto err_map; + if (unlikely(dma_mapping_error(dev, addr))) { + __free_pages(page, 0); + goto err_alloc; + } buf_array[i] = addr; @@ -1718,8 +1718,8 @@ static int dpaa2_eth_add_bufs(struct dpaa2_eth_priv *priv, * of DPAA2_ETH_BUFS_PER_CMD. Bail out if the UMEM cannot * provide enough buffers at the moment */ - batch = xsk_buff_alloc_batch(ch->xsk_pool, xdp_buffs, - DPAA2_ETH_BUFS_PER_CMD); + u32 batch = xsk_buff_alloc_batch(ch->xsk_pool, xdp_buffs, + DPAA2_ETH_BUFS_PER_CMD); if (!batch) goto err_alloc; @@ -1729,8 +1729,11 @@ static int dpaa2_eth_add_bufs(struct dpaa2_eth_priv *priv, swa->xsk.xdp_buff = xdp_buffs[i]; addr = xsk_buff_xdp_get_frame_dma(xdp_buffs[i]); - if (unlikely(dma_mapping_error(dev, addr))) - goto err_map; + if (unlikely(dma_mapping_error(dev, addr))) { + for (int j = i; j < batch; j++) + xsk_buff_free(xdp_buffs[j]); + goto err_alloc; + } buf_array[i] = addr; @@ -1761,13 +1764,6 @@ static int dpaa2_eth_add_bufs(struct dpaa2_eth_priv *priv, return i; -err_map: - if (!ch->xsk_zc) { - __free_pages(page, 0); - } else { - for (; i < batch; i++) - xsk_buff_free(xdp_buffs[i]); - } err_alloc: /* If we managed to allocate at least some buffers, * release them to hardware From e509726660dd06ce107437aecf7c106c9d3fc1e7 Mon Sep 17 00:00:00 2001 From: Shuai Liu <847807867@qq.com> Date: Thu, 19 Nov 2026 13:08:14 +0800 Subject: [PATCH 1923/2102] xfrm: interface: drop non-IP packets before pskb_inet_may_pull() AF_XDP sockets bound to an xfrm interface submit skbs with skb->protocol unset (0) and skb->network_header still 0 from the __alloc_skb() zero-initialization; skb_reserve() only moves data NET_SKB_PAD bytes into the headroom. Since commit 86de3a1118a16 ("xfrm: interface: validate the IP header on xmit"), xfrmi_xmit() calls pskb_inet_may_pull() unconditionally. For such a skb, pskb_inet_may_pull_reason() selects nhlen = 0 for the unknown protocol and pskb_may_pull_reason() receives len = skb_network_offset(skb) = network_header - data = -64, which as unsigned int exceeds INT_MAX and trips the DEBUG_NET_WARN_ON_ONCE(len > INT_MAX) in pskb_may_pull_reason(): WARNING: ./include/linux/skbuff.h:2856 at pskb_may_pull_reason [inline] WARNING: ./include/linux/skbuff.h:3286 at pskb_network_may_pull_reason [inline] WARNING: ./include/net/ip_tunnels.h:483 at pskb_inet_may_pull_reason [inline] WARNING: ./include/net/ip_tunnels.h:488 at pskb_inet_may_pull [inline] WARNING: ./include/net/ip_tunnels.h:488 at xfrmi_xmit+0x1844/0x1eb0 net/xfrm/xfrm_interface_core.c:534 RIP: 0010:pskb_may_pull_reason include/linux/skbuff.h:2856 [inline] Call Trace: __dev_direct_xmit+0x4b6/0x730 net/core/dev.c:5164 __xsk_generic_xmit net/xdp/xsk.c:1288 [inline] xsk_generic_xmit+0x27d8/0x47a0 net/xdp/xsk.c:1344 xsk_poll+0x326/0x670 net/xdp/xsk.c:1472 The packet is dropped by the pull returning PKT_TOO_SMALL and hitting the default case afterwards anyway, so the only visible effect is the warning; reject unknown protocols before the pull to restore the pre-86de3a1118a16 behavior of dropping them silently via the switch default. Reported-by: syzbot+d29af9ef5c96a3f5e96c@syzkaller.appspotmail.com Closes: https://syzbot.org/bug?extid=d29af9ef5c96a3f5e96c Fixes: 86de3a1118a16 ("xfrm: interface: validate the IP header on xmit") Cc: stable@vger.kernel.org Signed-off-by: Shuai Liu <847807867@qq.com> Acked-by: Steffen Klassert Link: https://patch.msgid.link/tencent_46F20906773869221623F9FA26275C133107@qq.com Signed-off-by: Paolo Abeni --- net/xfrm/xfrm_interface_core.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/net/xfrm/xfrm_interface_core.c b/net/xfrm/xfrm_interface_core.c index 9835fbe63ccb83..aa6e42c3e0e2e8 100644 --- a/net/xfrm/xfrm_interface_core.c +++ b/net/xfrm/xfrm_interface_core.c @@ -531,6 +531,14 @@ static netdev_tx_t xfrmi_xmit(struct sk_buff *skb, struct net_device *dev) memset(&fl, 0, sizeof(fl)); + switch (skb->protocol) { + case htons(ETH_P_IPV6): + case htons(ETH_P_IP): + break; + default: + goto tx_err; + } + if (!pskb_inet_may_pull(skb)) goto tx_err; From 8e324d767bdc5ab38b0e1e921e786ff9ea514188 Mon Sep 17 00:00:00 2001 From: Rongen Wang Date: Thu, 26 Nov 2026 18:18:33 +0900 Subject: [PATCH 1924/2102] ALSA: timer: Protect the slave instance flags with the timer lock snd_timer_start_slave() and snd_timer_stop_slave() set and clear SNDRV_TIMER_IFLG_RUNNING in timeri->flags while holding only timeri_lock. For a slave that is linked to a master, the interrupt path updates the same word under timer->lock: snd_timer_process_callbacks() sets SNDRV_TIMER_IFLG_CALLBACK before it calls the instance callback and clears it afterwards. Both sides do a plain read-modify-write, so when they overlap one of the two updates is lost. If the set of SNDRV_TIMER_IFLG_CALLBACK is lost, snd_timer_close_locked() does not wait for the callback that is still running, the owner frees the instance, and the interrupt path clears the flag in the freed object: BUG: KASAN: slab-use-after-free in snd_timer_process_callbacks+0x269/0x2b0 Read of size 4 at addr ffff888007e5cc10 by task poc/90 snd_timer_process_callbacks+0x269/0x2b0 snd_timer_interrupt+0x7b8/0x1100 snd_utimer_ioctl+0x7c/0xb0 Freed by task 91: kfree+0x127/0x3b0 __snd_timer_user_ioctl.isra.0+0xe93/0x28f0 If the clear is lost instead, the flag stays set: the instance gets no further callbacks, and closing it spins in the drain loop of snd_timer_close_locked() with register_mutex held, which blocks every other open and close of an ALSA timer. Take timer->lock around the whole flag update of a linked slave, as snd_timer_start1() and snd_timer_stop1() do for master instances. The callers hold timeri_lock, so timeri->timer is stable, and the lock order is the one these functions already use. A slave that is not linked to a master cannot be reached from any timer and needs no additional protection. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable@vger.kernel.org Signed-off-by: Rongen Wang Link: https://patch.msgid.link/20261126-alsa-timer-slave-flags-v2-1-8e07a536fea3@nitrohex.com Signed-off-by: Takashi Iwai --- sound/core/timer.c | 50 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/sound/core/timer.c b/sound/core/timer.c index 905176bf6948d7..50e31827d9ffdd 100644 --- a/sound/core/timer.c +++ b/sound/core/timer.c @@ -657,9 +657,12 @@ static int snd_timer_start1(struct snd_timer_instance *timeri, return result; } -/* start/continue a slave timer */ -static int snd_timer_start_slave(struct snd_timer_instance *timeri, - bool start) +/* + * start/continue a slave timer; + * called with timer->lock held when the slave is linked to a master + */ +static int __snd_timer_start_slave(struct snd_timer_instance *timeri, + bool start) { if (timeri->flags & SNDRV_TIMER_IFLG_DEAD) return -EINVAL; @@ -667,7 +670,6 @@ static int snd_timer_start_slave(struct snd_timer_instance *timeri, return -EBUSY; timeri->flags |= SNDRV_TIMER_IFLG_RUNNING; if (timeri->master && timeri->timer) { - guard(spinlock)(&timeri->timer->lock); list_add_tail(&timeri->active_list, &timeri->master->slave_active_head); snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START : @@ -676,6 +678,27 @@ static int snd_timer_start_slave(struct snd_timer_instance *timeri, return 1; /* delayed start */ } +/* + * start/continue a slave timer + * + * The flags of a slave linked to a master are updated also from the timer + * interrupt (SNDRV_TIMER_IFLG_CALLBACK in snd_timer_process_callbacks()) + * under timer->lock. Change them only under the same lock, otherwise one + * of the two read-modify-write updates may get lost. The caller holds + * timeri_lock, hence timeri->timer can't change here; an unlinked slave is + * not reachable from any timer and needs no further protection. + */ +static int snd_timer_start_slave(struct snd_timer_instance *timeri, + bool start) +{ + struct snd_timer *timer = timeri->timer; + + if (!timer) + return __snd_timer_start_slave(timeri, start); + guard(spinlock)(&timer->lock); + return __snd_timer_start_slave(timeri, start); +} + /* stop/pause a master timer */ static int snd_timer_stop1(struct snd_timer_instance *timeri, bool stop) { @@ -718,15 +741,17 @@ static int snd_timer_stop1(struct snd_timer_instance *timeri, bool stop) return 0; } -/* stop/pause a slave timer */ -static int snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop) +/* + * stop/pause a slave timer; + * called with timer->lock held when the slave is linked to a master + */ +static int __snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop) { bool running; running = timeri->flags & SNDRV_TIMER_IFLG_RUNNING; timeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING; if (timeri->timer) { - guard(spinlock)(&timeri->timer->lock); list_del_init(&timeri->ack_list); list_del_init(&timeri->active_list); if (running) @@ -736,6 +761,17 @@ static int snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop) return running ? 0 : -EBUSY; } +/* stop/pause a slave timer; see snd_timer_start_slave() for the locking */ +static int snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop) +{ + struct snd_timer *timer = timeri->timer; + + if (!timer) + return __snd_timer_stop_slave(timeri, stop); + guard(spinlock)(&timer->lock); + return __snd_timer_stop_slave(timeri, stop); +} + /* * start the timer instance */ From ddea524e437eae0d5581482a90565b4c1e6d4b24 Mon Sep 17 00:00:00 2001 From: Hengyu Liang Date: Wed, 25 Nov 2026 13:10:05 -0500 Subject: [PATCH 1925/2102] ALSA: pcm: oss: Refine slave hw_params after setting format Commit 93d7d38fa61d ("ALSA: aloop: add DSD formats") added DSD_U8 to the formats of snd-aloop. Before that, its narrowest format had 16 bits. However, snd_pcm_oss_change_params_locked() sets the slave format with _snd_pcm_hw_param_set(), which does not refine the parameters, while the access, rate and channels before it are set with refining helpers. snd_pcm_oss_period_size() then reads a buffer size maximum that is still computed for the narrowest format, now DSD_U8, so the OSS period doubles. With the default U8 client format, the doubled period no longer fits in the format plugin, and snd_pcm_plugin_alloc() returns -ENOMEM. As of now, an OSS program that asks snd-aloop for 8 channels at 192 kHz gets ENOMEM from SNDCTL_DSP_SPEED and from every later ioctl on the same file. The issue can be reproduced with this program, where card 1 is snd-aloop: #include #include #include #include int main(void) { int fd = open("/dev/dsp1", O_WRONLY | O_NONBLOCK); int ch = 8, rate = 192000, blk = 0; ioctl(fd, SNDCTL_DSP_CHANNELS, &ch); if (ioctl(fd, SNDCTL_DSP_SPEED, &rate) < 0) perror("SNDCTL_DSP_SPEED"); if (ioctl(fd, SNDCTL_DSP_GETBLKSIZE, &blk) < 0) perror("SNDCTL_DSP_GETBLKSIZE"); printf("block size %d\n", blk); return 0; } Before that commit, it prints "block size 65536". After that commit, the result is: SNDCTL_DSP_SPEED: Cannot allocate memory SNDCTL_DSP_GETBLKSIZE: Cannot allocate memory block size 0 This patch will set the format with snd_pcm_hw_param_set(), which refines the parameters, as is done for the channels just before. Fixes: 93d7d38fa61d ("ALSA: aloop: add DSD formats") Cc: Signed-off-by: Hengyu Liang Link: https://patch.msgid.link/20261125181005.3683575-1-hengyul@cs.unc.edu Signed-off-by: Takashi Iwai --- sound/core/oss/pcm_oss.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sound/core/oss/pcm_oss.c b/sound/core/oss/pcm_oss.c index 66162caa45d4ac..3c2ac8966d5e3e 100644 --- a/sound/core/oss/pcm_oss.c +++ b/sound/core/oss/pcm_oss.c @@ -921,7 +921,8 @@ static int snd_pcm_oss_change_params_locked(struct snd_pcm_substream *substream) goto failure; } format_found: - err = _snd_pcm_hw_param_set(sparams, SNDRV_PCM_HW_PARAM_FORMAT, sformat, 0); + err = snd_pcm_hw_param_set(substream, sparams, + SNDRV_PCM_HW_PARAM_FORMAT, sformat, 0); if (err < 0) goto failure; From 285ca329ad4bfc32d0f383340c40a40c8157ac7c Mon Sep 17 00:00:00 2001 From: Felipe Pereira Stival Date: Wed, 18 Nov 2026 17:35:48 -0300 Subject: [PATCH 1926/2102] tls: don't hide a queued KeyUpdate from poll() When application data and a KeyUpdate are both queued, the recv() for the data can also decrypt the KeyUpdate. That makes a rekey pending, and the KeyUpdate is left on rx_list because its record type differs. tls_sk_poll() reports no read events while a rekey is pending, so the socket doesn't poll readable although a recvmsg() would return the KeyUpdate. A reader that waits for a read event before each recv() never reads it, never provides the new key and receives nothing more. Report read events for records on rx_list while a rekey is pending, since they are already decrypted. Keep ignoring the records still in the strparser, so once the KeyUpdate has been read there are no read events until the new key is provided, as before. Update the documentation to say so. Found with a level-triggered epoll reader that does one recv() per read event. Without this patch it gets the data and then no read event for the KeyUpdate; with it, the KeyUpdate is reported and the rekey completes. Fixes: 47069594e67e ("tls: implement rekey for TLS1.3") Signed-off-by: Felipe Pereira Stival Reviewed-by: Simon Horman Reviewed-by: Sabrina Dubroca Link: https://patch.msgid.link/20261118-v0idpwn-tls-poll-parked-keyupdate-v1-1-8e25101e7be6@gmail.com Signed-off-by: Paolo Abeni --- Documentation/networking/tls.rst | 7 ++++--- net/tls/tls_main.c | 6 +++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/Documentation/networking/tls.rst b/Documentation/networking/tls.rst index 980c442d7161ae..e07c1a001b2177 100644 --- a/Documentation/networking/tls.rst +++ b/Documentation/networking/tls.rst @@ -215,9 +215,10 @@ To prevent attempting to decrypt incoming records using the wrong key, decryption will be paused when a KeyUpdate message is received by the kernel, until the new key has been provided using the TLS_RX socket option. Any read occurring after the KeyUpdate has been read and -before the new key is provided will fail with EKEYEXPIRED. poll() will -not report any read events from the socket until the new key is -provided. There is no pausing on the transmit side. +before the new key is provided will fail with EKEYEXPIRED. Once the +KeyUpdate has been read, poll() will not report any read events from +the socket until the new key is provided. There is no pausing on the +transmit side. Userspace should make sure that the crypto_info provided has been set properly. In particular, the kernel will not check for key/nonce diff --git a/net/tls/tls_main.c b/net/tls/tls_main.c index fa71c75c28611d..d24e86e7f42d9c 100644 --- a/net/tls/tls_main.c +++ b/net/tls/tls_main.c @@ -414,9 +414,9 @@ static __poll_t tls_sk_poll(struct file *file, struct socket *sock, tls_ctx = tls_get_ctx(sk); ctx = tls_sw_ctx_rx(tls_ctx); - if ((skb_queue_empty_lockless(&ctx->rx_list) && - !tls_strp_msg_ready(ctx)) || - READ_ONCE(ctx->key_update_pending)) + if (skb_queue_empty_lockless(&ctx->rx_list) && + (!tls_strp_msg_ready(ctx) || + READ_ONCE(ctx->key_update_pending))) mask &= ~(EPOLLIN | EPOLLRDNORM); return mask; From d26b244cdec331b987ae2202ef23c92ab43a8afe Mon Sep 17 00:00:00 2001 From: Felipe Pereira Stival Date: Wed, 18 Nov 2026 17:35:49 -0300 Subject: [PATCH 1927/2102] selftests: tls: add a poll test for a queued KeyUpdate Check that poll() reports a read event when a recv() for data has decrypted and queued a KeyUpdate. Once the KeyUpdate has been read, check that poll() doesn't report a record sent with the new key. Signed-off-by: Felipe Pereira Stival Reviewed-by: Simon Horman Reviewed-by: Sabrina Dubroca Link: https://patch.msgid.link/20261118-v0idpwn-tls-poll-parked-keyupdate-v1-2-8e25101e7be6@gmail.com Signed-off-by: Paolo Abeni --- tools/testing/selftests/net/tls.c | 40 +++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/tools/testing/selftests/net/tls.c b/tools/testing/selftests/net/tls.c index bd2797f9f619df..59e403b5f12cf3 100644 --- a/tools/testing/selftests/net/tls.c +++ b/tools/testing/selftests/net/tls.c @@ -2421,6 +2421,46 @@ TEST_F(tls, rekey_poll_delay) } } +TEST_F(tls, rekey_poll_queued) +{ + char const *test_str = "test_message"; + struct tls_crypto_info_keys tls12; + struct pollfd pfd = { }; + char buf[100]; + int send_len; + + if (self->notls) + SKIP(return, "no TLS support"); + + if (variant->tls_version != TLS_1_3_VERSION) + return; + + /* data followed by a KeyUpdate */ + send_len = strlen(test_str) + 1; + EXPECT_EQ(send(self->fd, test_str, send_len, 0), send_len); + tls_send_keyupdate(_metadata, self->fd); + + /* reading the data decrypts the KeyUpdate and leaves it queued */ + EXPECT_EQ(recv(self->cfd, buf, sizeof(buf), MSG_WAITALL), send_len); + EXPECT_EQ(memcmp(buf, test_str, send_len), 0); + + /* KeyUpdate hasn't been read, expect cfd to be readable */ + pfd.fd = self->cfd; + pfd.events = POLLIN; + EXPECT_EQ(poll(&pfd, 1, 0), 1); + + /* get KeyUpdate */ + tls_recv_keyupdate(_metadata, self->cfd, 0); + + /* update TX key and send with it */ + tls_crypto_info_init(variant->tls_version, variant->cipher_type, &tls12, 1); + EXPECT_EQ(setsockopt(self->fd, SOL_TLS, TLS_TX, &tls12, tls12.len), 0); + EXPECT_EQ(send(self->fd, test_str, send_len, 0), send_len); + + /* key hasn't been updated, expect cfd to be non-readable */ + EXPECT_EQ(poll(&pfd, 1, 0), 0); +} + struct raw_rec { unsigned int plain_len; unsigned char plain_data[100]; From 686b8dbcedf8773dc505f9f315a0551c0bca70a3 Mon Sep 17 00:00:00 2001 From: Pavan Chebbi Date: Wed, 18 Nov 2026 16:24:06 +0530 Subject: [PATCH 1928/2102] tg3: Don't fail probe if 31-bit coherent DMA mask is unsupported Commit 614f4d166eee ("tg3: Set coherent DMA mask bits to 31 for BCM57766 chipsets") lowered the coherent DMA mask to 31 bits as a workaround for a spurious address overflow error in the hardware. The result of dma_set_coherent_mask() is fatal to probe, so on platforms that cannot satisfy such a mask the device fails to probe: tg3 0000:01:00.0: Unable to obtain 64 bit DMA for consistent allocations tg3 0000:01:00.0: probe with driver tg3 failed with error -5 This was reported on a Mac mini (Macmini6,2, BCM57766) running a kernel built without CONFIG_ZONE_DMA and with IOMMU passthrough as the default. Without CONFIG_ZONE_DMA, dma_direct_supported() only accepts a mask narrower than 32 bits if it covers the highest physical memory address, so with direct mapping a 31-bit coherent mask is rejected whenever memory extends above 2GB. Treat the 31-bit mask as best effort. If it is refused, warn and fall back to the mask used before 614f4d166eee, so that the device still probes. Platforms that accept the mask are unaffected. Where it is refused, 614f4d166eee never protected the device, it only stopped it from probing, so this restores the behaviour of kernels before that commit. Warn when a status block lands at an address matching the pattern described in 614f4d166eee, so that a resulting TX timeout can be identified. Fixes: 614f4d166eee ("tg3: Set coherent DMA mask bits to 31 for BCM57766 chipsets") Reported-by: Rui Salvaterra Link: https://lore.kernel.org/netdev/CALjTZvYKHWrD5m+RXimjxODvpFPw7Cq_EOEuzRi1PZT9_JxF+g@mail.gmail.com/ Signed-off-by: Pavan Chebbi Reviewed-by: Simon Horman Link: https://patch.msgid.link/20261118105408.1076095-2-pavan.chebbi@broadcom.com Signed-off-by: Paolo Abeni --- drivers/net/ethernet/broadcom/tg3.c | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/drivers/net/ethernet/broadcom/tg3.c b/drivers/net/ethernet/broadcom/tg3.c index 95827df4cf6a1b..2cf9d2ea069b5e 100644 --- a/drivers/net/ethernet/broadcom/tg3.c +++ b/drivers/net/ethernet/broadcom/tg3.c @@ -8867,6 +8867,13 @@ static int tg3_alloc_consistent(struct tg3 *tp) if (!tnapi->hw_status) goto err_out; + if (tg3_asic_rev(tp) == ASIC_REV_57766 && + (lower_32_bits(tnapi->status_mapping) & 0xffff0000) == + 0xffff0000) + dev_warn(&tp->pdev->dev, + "Status block at DMA address %pad may cause TX timeouts on this device\n", + &tnapi->status_mapping); + sblk = tnapi->hw_status; if (tg3_flag(tp, ENABLE_RSS)) { @@ -17756,6 +17763,7 @@ static int tg3_init_one(struct pci_dev *pdev, u64 dma_mask, persist_dma_mask; netdev_features_t features = 0; u8 addr[ETH_ALEN] __aligned(2); + u64 test_dma_mask = 0; err = pci_enable_device(pdev); if (err) { @@ -17895,15 +17903,22 @@ static int tg3_init_one(struct pci_dev *pdev, persist_dma_mask = dma_mask = DMA_BIT_MASK(64); if (tg3_asic_rev(tp) == ASIC_REV_57766) - persist_dma_mask = DMA_BIT_MASK(31); + test_dma_mask = DMA_BIT_MASK(31); /* Configure DMA attributes. */ if (dma_mask > DMA_BIT_MASK(32)) { err = dma_set_mask(&pdev->dev, dma_mask); if (!err) { features |= NETIF_F_HIGHDMA; - err = dma_set_coherent_mask(&pdev->dev, - persist_dma_mask); + if (!test_dma_mask || + dma_set_coherent_mask(&pdev->dev, + test_dma_mask)) { + if (test_dma_mask) + dev_warn(&pdev->dev, + "Unable to set 31 bit coherent DMA mask, workaround not applied\n"); + err = dma_set_coherent_mask(&pdev->dev, + persist_dma_mask); + } if (err < 0) { dev_err(&pdev->dev, "Unable to obtain 64 bit " "DMA for consistent allocations\n"); From 70e57e1255e06fd7a22d45dd2bf854200fcbd575 Mon Sep 17 00:00:00 2001 From: Pavan Chebbi Date: Wed, 18 Nov 2026 16:24:07 +0530 Subject: [PATCH 1929/2102] tg3: Skip management FW version when APE firmware is not ready When the APE firmware is not present or not ready, for example when the NCSI component is missing in the NVRAM, tg3_read_fw_ver() still calls tg3_read_dash_ver() after tg3_probe_ncsi(). The signature and ready checks that tg3_read_dash_ver() used to make were moved into tg3_probe_ncsi(), which only sets the NCSI flag and does not stop the caller. The driver then reads the APE firmware version register, which holds no valid data in this state, and ethtool -i shows an invalid "DASH" string with a garbage version. Make tg3_probe_ncsi() return whether valid, ready APE firmware was found, and read the version only in that case. Otherwise just report the bootcode version. This was seen by a user on BCM5719/BCM5720 with no NCSI component in the NVRAM. With this change, ethtool -i displays only the bootcode version. Fixes: 165f4d1cb3d7 ("tg3: Fix the setting of the APE_HAS_NCSI flag") Signed-off-by: Pavan Chebbi Reviewed-by: Simon Horman Link: https://patch.msgid.link/20261118105408.1076095-3-pavan.chebbi@broadcom.com Signed-off-by: Paolo Abeni --- drivers/net/ethernet/broadcom/tg3.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/drivers/net/ethernet/broadcom/tg3.c b/drivers/net/ethernet/broadcom/tg3.c index 2cf9d2ea069b5e..5a0e247a4c4634 100644 --- a/drivers/net/ethernet/broadcom/tg3.c +++ b/drivers/net/ethernet/broadcom/tg3.c @@ -15997,20 +15997,26 @@ static void tg3_read_mgmtfw_ver(struct tg3 *tp) } } -static void tg3_probe_ncsi(struct tg3 *tp) +/* Returns true if valid, ready APE firmware is present, regardless of + * whether it advertises NCSI (it may be DASH or SMASH). Sets APE_HAS_NCSI + * if the NCSI feature is advertised. + */ +static bool tg3_probe_ncsi(struct tg3 *tp) { u32 apedata; apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG); if (apedata != APE_SEG_SIG_MAGIC) - return; + return false; apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS); if (!(apedata & APE_FW_STATUS_READY)) - return; + return false; if (tg3_ape_read32(tp, TG3_APE_FW_FEATURES) & TG3_APE_FW_FEATURE_NCSI) tg3_flag_set(tp, APE_HAS_NCSI); + + return true; } static void tg3_read_dash_ver(struct tg3 *tp) @@ -16089,8 +16095,7 @@ static void tg3_read_fw_ver(struct tg3 *tp) if (tg3_flag(tp, ENABLE_ASF)) { if (tg3_flag(tp, ENABLE_APE)) { - tg3_probe_ncsi(tp); - if (!vpd_vers) + if (tg3_probe_ncsi(tp) && !vpd_vers) tg3_read_dash_ver(tp); } else if (!vpd_vers) { tg3_read_mgmtfw_ver(tp); From 0323a427052447e2c41c650fc98a6c04bf417e5d Mon Sep 17 00:00:00 2001 From: Shravya KN Date: Wed, 18 Nov 2026 16:24:08 +0530 Subject: [PATCH 1930/2102] tg3: Fix heap overflow in unbuffered NVRAM write path tg3_nvram_write_block_unbuffered() reads a whole NVRAM page into a buffer of pagesize bytes, copies the caller's data into it at page_off, and writes the page back. The copy size was clamped to pagesize rather than to the room left in the page, pagesize - page_off, so a write at an offset that is not page aligned, as ETHTOOL_SEEPROM allows, copies past the end of the buffer and corrupts the kernel heap. Clamp size to pagesize - page_off. Also advance buf by size on each iteration. Without this, a write that spans more than one page programmed every page after the first with the data of the first page, and a write that did not start on a page boundary lost the tail of the data without reporting an error. Reject an nvram_pagesize that is smaller than 4 or not a power of two. The page mask is pagesize - 1, which is only a valid mask for a power of two. A page size of 0, which tg3_get_nvram_info() leaves unset for an unhandled flash vendor, also made the loop issue erase commands at address 0 forever with the rtnl and NVRAM locks held. ethtool -E now fails with -EINVAL in these cases. This was found by an AI code review scan. It has not been observed on hardware, but it can be reached with ethtool -E on devices with unbuffered flash. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Signed-off-by: Shravya KN Signed-off-by: Pavan Chebbi Reviewed-by: Simon Horman Link: https://patch.msgid.link/20261118105408.1076095-4-pavan.chebbi@broadcom.com Signed-off-by: Paolo Abeni --- drivers/net/ethernet/broadcom/tg3.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/net/ethernet/broadcom/tg3.c b/drivers/net/ethernet/broadcom/tg3.c index 5a0e247a4c4634..12f199355984b1 100644 --- a/drivers/net/ethernet/broadcom/tg3.c +++ b/drivers/net/ethernet/broadcom/tg3.c @@ -56,6 +56,7 @@ #include #include #include +#include #include #include @@ -3379,6 +3380,9 @@ static int tg3_nvram_write_block_unbuffered(struct tg3 *tp, u32 offset, u32 len, u32 nvram_cmd; u8 *tmp; + if (pagesize < 4 || !is_power_of_2(pagesize)) + return -EINVAL; + tmp = kmalloc(pagesize, GFP_KERNEL); if (tmp == NULL) return -ENOMEM; @@ -3399,13 +3403,14 @@ static int tg3_nvram_write_block_unbuffered(struct tg3 *tp, u32 offset, u32 len, break; page_off = offset & pagemask; - size = pagesize; + size = pagesize - page_off; if (len < size) size = len; len -= size; memcpy(tmp + page_off, buf, size); + buf += size; offset = offset + (pagesize - page_off); From 18817028301de963a3a25f6d7d652d1d3b79f570 Mon Sep 17 00:00:00 2001 From: Yadong Qi Date: Thu, 26 Nov 2026 10:22:27 +0800 Subject: [PATCH 1931/2102] arm64: fixmap: fix missing break-before-make in __set_fixmap() __set_fixmap() installs a new PTE with __set_pte() but never invalidates the TLB; only the clear path calls flush_tlb_kernel_range(). The dsb(ishst)/isb that __set_pte() emits makes the new PTE visible to the table walker but does not invalidate stale TLB entries. Overwriting a still-valid slot therefore leaves the old translation cached and violates break-before-make: accesses may keep hitting the old output address, and changing the attributes of a cached entry can trigger TLB conflict aborts or CONSTRAINED UNPREDICTABLE behaviour. Two in-tree callers overwrite a valid FIX_EARLYCON_MEM_BASE slot: - earlycon: earlycon_map() maps the UART before match->setup() runs. If setup fails, con->write is unset, or the DT reg-io-width is unsupported, the slot stays valid but no console is registered. The console_is_registered() guard only blocks successful registrations, so a later attempt (e.g. a failed DT earlycon followed by earlycon= on the command line) remaps the slot to a different UART. - samsung_tty: apple_s5l_early_console_setup() overrides the just-installed entry from PROT_DEVICE_nGnRE (FIXMAP_PAGE_IO) to PROT_DEVICE_nGnRnE on the normal successful boot path. Both are valid-to-valid changes (different output address or memory type), which arm64 requires to be break-before-make. Fix this in __set_fixmap() by invalidating any existing valid mapping up front: clear the old PTE and flush the TLB, then install the new PTE only when setting. The old translation is gone before the new one is created, so the two can never coexist in the TLB. A first-time mapping (old entry invalid) skips the invalidation and pays no extra cost, and clearing a slot is handled by the same step. A clear (!flags) always clears and flushes, even when the PTE is already invalid. An invalid PTE does not imply an invalid TLB: another CPU may have cleared the PTE but not yet completed its TLB flush, leaving a stale entry cached locally. Take KVM arm64 VNCR unmap path as example: in this_cpu_reset_vncr_fixmap(), a CPU that loses the atomic_xchg_relaxed() ownership race in unmap_l1_vncr() still calls clear_fixmap() on its own slot. Gating that flush on pte_valid() would let vcpu_put() return while the winner's TLB flush is still in flight, so a vCPU from another VM could remap the slot with the old translation still cached. The unconditional flush preserves clear_fixmap()'s TLB shootdown guarantee. This belongs in the callee, as on x86: __set_fixmap() there calls set_pte_vaddr(), which flushes the TLB unconditionally after writing the PTE. x86 can flush after the write because it has no break-before-make requirement; arm64 must invalidate and flush before installing the new valid entry to avoid TLB conflict aborts. Fixes: bf4b558eba92 ("arm64: add early_ioremap support") Cc: stable@vger.kernel.org Reported-by: Huang Ying Signed-off-by: Yadong Qi Reviewed-by: Catalin Marinas Signed-off-by: Catalin Marinas --- arch/arm64/mm/fixmap.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/arch/arm64/mm/fixmap.c b/arch/arm64/mm/fixmap.c index 951004ad700c39..c8a0d008cf2aa1 100644 --- a/arch/arm64/mm/fixmap.c +++ b/arch/arm64/mm/fixmap.c @@ -126,13 +126,20 @@ void __set_fixmap(enum fixed_addresses idx, ptep = fixmap_pte(addr); + /* + * Break-before-make if the slot holds a valid mapping. Always + * flush on clear since another CPU may have cleared the pte + * without completing its TLBI yet. + */ + if (pte_valid(__ptep_get(ptep)) || !pgprot_val(flags)) { + __pte_clear(&init_mm, addr, ptep); + flush_tlb_kernel_range(addr, addr + PAGE_SIZE); + } + if (pgprot_val(flags)) { /* The slot must be usable on return, even in lazy MMU mode. */ __set_pte_nosync(ptep, pfn_pte(phys >> PAGE_SHIFT, flags)); emit_pte_barriers(); - } else { - __pte_clear(&init_mm, addr, ptep); - flush_tlb_kernel_range(addr, addr+PAGE_SIZE); } } From ae8e5ef9fa9eeaf4ee0a9a9bde0fc63023d9b154 Mon Sep 17 00:00:00 2001 From: Florian Fainelli Date: Wed, 18 Nov 2026 10:40:04 -0800 Subject: [PATCH 1932/2102] net: dsa: tag_brcm: fix link-local detection with a prepended tag brcm_tag_rcv_ll() checks eth_hdr(skb)->h_dest to avoid marking link-local frames as forwarded by the switch. With a prepended tag, eth_type_trans() sets the MAC header at the start of the tag, so the address checked is the tag plus the first two bytes of the real destination address. Link-local frames such as BPDUs, LLDP or EAPOL are then not recognized and get skb->offload_fwd_mark set, which keeps the bridge from forwarding them in software to the other ports of the switch when it is configured to do so. Read the destination address after the tag instead when the tag is prepended. Tags embedded after the source address are not affected. Fixes: 762e7e174da9 ("net: dsa: tag_brcm: do not mark link local traffic as offloaded") Signed-off-by: Florian Fainelli Link: https://patch.msgid.link/20261118184004.1916105-1-florian.fainelli@broadcom.com Signed-off-by: Paolo Abeni --- net/dsa/tag_brcm.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/net/dsa/tag_brcm.c b/net/dsa/tag_brcm.c index b7c49822ca8880..b58669c9214742 100644 --- a/net/dsa/tag_brcm.c +++ b/net/dsa/tag_brcm.c @@ -149,6 +149,7 @@ static struct sk_buff *brcm_tag_rcv_ll(struct sk_buff *skb, unsigned int offset) { int source_port; + const u8 *dest; u8 *brcm_tag; if (unlikely(!pskb_may_pull(skb, BRCM_TAG_LEN))) { @@ -184,7 +185,11 @@ static struct sk_buff *brcm_tag_rcv_ll(struct sk_buff *skb, /* Remove Broadcom tag and update checksum */ skb_pull_rcsum(skb, BRCM_TAG_LEN); - if (likely(!is_link_local_ether_addr(eth_hdr(skb)->h_dest))) + /* With a prepended tag, the MAC header set by eth_type_trans() starts + * at the tag, and the destination address follows it. + */ + dest = offset == ETH_HLEN ? brcm_tag + BRCM_TAG_LEN : eth_hdr(skb)->h_dest; + if (likely(!is_link_local_ether_addr(dest))) dsa_default_offload_fwd_mark(skb); return skb; From e4c5112f01816b0ac6d74724545eca1195788c38 Mon Sep 17 00:00:00 2001 From: Tengda Wu Date: Thu, 19 Nov 2026 09:51:00 +0000 Subject: [PATCH 1933/2102] perf: Prevent duplicate sigtrap task work enqueue The sigtrap handling in __perf_event_overflow() checks event->pending_work before calling task_work_add(), but only sets pending_work after the task work has been queued. This leaves a window where an NMI can interrupt task_work_add() and re-enter __perf_event_overflow() for the same (software/tracepoint) event. Since pending_work is still zero, the nested invocation can enqueue the same pending_task again. The re-entrant call path looks like this: __perf_event_overflow() task_work_add() __perf_event_overflow() task_work_add() The nested invocation may enqueue pending_task before the outer invocation does. When the outer invocation resumes, it inserts the same task work entry again, potentially creating a cycle in the task work list. As a result, perf_pending_task() may be executed repeatedly, leading to unbalanced event reference counting. Fix this by atomically claiming pending_work with cmpxchg_local() before calling task_work_add(). This ensures that only one invocation can enqueue the task work, even when another overflow occurs re-entrantly from an NMI. Notably: sigtrap events must be per-task, meaning that the there is no concurrency, only re-entrancy. [peterz: clarify and rewrite] Fixes: c5d93d23a260 ("perf: Enqueue SIGTRAP always via task_work.") Signed-off-by: Tengda Wu Signed-off-by: Peter Zijlstra (Intel) Link: https://patch.msgid.link/45bd71c976aea1a0e8bf5762dd6b6552e6009439.1795053619.git.wutengda@huaweicloud.com --- kernel/events/core.c | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/kernel/events/core.c b/kernel/events/core.c index ee51134510578f..5925752687d814 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -7776,9 +7776,15 @@ static void perf_pending_task(struct callback_head *head) rctx = perf_swevent_get_recursion_context(); if (event->pending_work) { - event->pending_work = 0; perf_sigtrap(event); local_dec(&event->ctx->nr_no_switch_fast); + /* + * event->pending_work also acts as a 'lock' for + * event->{pending_addr, orig_type, attr.sig_data}. As such we + * must clear after perf_sigtrap is complete. + */ + barrier(); + event->pending_work = 0; } put_event(event); @@ -10953,16 +10959,22 @@ static int __perf_event_overflow(struct perf_event *event, notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME; - if (!event->pending_work && - !task_work_add(current, &event->pending_task, notify_mode)) { - event->pending_work = pending_id; - local_inc(&event->ctx->nr_no_switch_fast); - WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount)); - - event->pending_addr = 0; - if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR)) - event->pending_addr = data->addr; - + /* + * Software events can nest and attempt this recursively; + * claim the pending_work before task_work_add() recurses. + */ + if (cmpxchg_local(&event->pending_work, 0, 1) == 0) { + if (!task_work_add(current, &event->pending_task, notify_mode)) { + event->pending_work = pending_id; + local_inc(&event->ctx->nr_no_switch_fast); + WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount)); + + event->pending_addr = 0; + if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR)) + event->pending_addr = data->addr; + } else { + event->pending_work = 0; + } } else if (event->attr.exclude_kernel && valid_sample) { /* * Should not be able to return to user space without From 38606d2911f7f2fe80388315da0c4a7fc98af0f8 Mon Sep 17 00:00:00 2001 From: Peter Zijlstra Date: Thu, 19 Nov 2026 09:51:01 +0000 Subject: [PATCH 1934/2102] perf: Fix sigtrap for software events perf_sigtrap() contains: WARN_ON_ONCE(event->ctx->task != current) The warning assumes that an event's ctx->task always matches the task that ends up running the pending task_work. That assumption can be broken by the context fast-swap path. The failure sequence is: 1. A -> B switch, perf_event_context_sched_out() takes the fast path and does WRITE_ONCE(ctx->task, next) / WRITE_ONCE(next_ctx->task, task). An NMI then hits while the context is swapped, and __perf_event_overflow() queues pending task_work on the *current* task (A), even though the event now belongs to B's swapped-in context view. 2. B -> A switch. Because A now has pending task_work, nr_no_switch_fast is non-zero, so the slow path is taken and ctx->task is *not* swapped back. 3. A returns to user mode, task_work runs perf_pending_task() -> perf_sigtrap(), and event->ctx->task no longer equals current, tripping the WARN_ON_ONCE(). The nr_no_switch_fast bits hard rely on perf_pmu_disable() actually working. It turns out the software events do not implement the pmu::pmu_{dis,en}able() methods and generally ignore the state, making the above scenario worse in that an overflow can happen in the middle of swapping task contexts, making it impossible to reconstruct state. Ensure software and tracepoint events respect the disable state. Fixes: ca6c21327c6a ("perf: Fix missing SIGTRAPs") Fixes: c5d93d23a260 ("perf: Enqueue SIGTRAP always via task_work.") Reported-by: Tengda Wu Signed-off-by: Peter Zijlstra (Intel) Tested-by: Tengda Wu Link: https://patch.msgid.link/20261125161342.GP2669272%40noisy.programming.kicks-ass.net --- include/linux/perf_event.h | 1 + kernel/events/core.c | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/include/linux/perf_event.h b/include/linux/perf_event.h index e1e11500df097a..b52348eca6ef10 100644 --- a/include/linux/perf_event.h +++ b/include/linux/perf_event.h @@ -1236,6 +1236,7 @@ extern const struct perf_event_attr *perf_event_attrs(struct perf_event *event); extern void perf_event_print_debug(void); extern void perf_pmu_disable(struct pmu *pmu); extern void perf_pmu_enable(struct pmu *pmu); +extern bool perf_pmu_enabled(struct pmu *pmu); extern void perf_sched_cb_dec(struct pmu *pmu); extern void perf_sched_cb_inc(struct pmu *pmu); extern int perf_event_task_disable(void); diff --git a/kernel/events/core.c b/kernel/events/core.c index 5925752687d814..10dc3d0cd81a26 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -1366,6 +1366,12 @@ void perf_pmu_enable(struct pmu *pmu) pmu->pmu_enable(pmu); } +bool perf_pmu_enabled(struct pmu *pmu) +{ + int *count = &this_cpc(pmu)->pmu_disable_count; + return *count == 0; +} + static void perf_assert_pmu_disabled(struct pmu *pmu) { int *count = &this_cpc(pmu)->pmu_disable_count; @@ -11159,6 +11165,9 @@ static int perf_swevent_match(struct perf_event *event, u32 event_id, struct pt_regs *regs) { + if (!perf_pmu_enabled(event->pmu)) + return 0; + if (event->attr.type != type) return 0; @@ -11537,6 +11546,9 @@ static int perf_tp_event_match(struct perf_event *event, struct perf_raw_record *raw, struct pt_regs *regs) { + if (!perf_pmu_enabled(event->pmu)) + return 0; + if (event->hw.state & PERF_HES_STOPPED) return 0; /* From 34dc983cc1628dea5054baa8687477cbb8683e28 Mon Sep 17 00:00:00 2001 From: Peter Zijlstra Date: Thu, 19 Nov 2026 09:51:01 +0000 Subject: [PATCH 1935/2102] perf: Fix sigtrap vs fast-switch perf_sigtrap() contains: WARN_ON_ONCE(event->ctx->task != current) The warning assumes that an event's ctx->task always matches the task that ends up running the pending task_work. That assumption can be broken by the context fast-swap path. The failure sequence is: 1. A -> B switch, perf_event_context_sched_out() takes the fast path and does WRITE_ONCE(ctx->task, next) / WRITE_ONCE(next_ctx->task, task). An NMI then hits while the context is swapped, and __perf_event_overflow() queues pending task_work on the *current* task (A), even though the event now belongs to B's swapped-in context view. 2. B -> A switch. Because A now has pending task_work, nr_no_switch_fast is non-zero, so the slow path is taken and ctx->task is *not* swapped back. 3. A returns to user mode, task_work runs perf_pending_task() -> perf_sigtrap(), and event->ctx->task no longer equals current, tripping the WARN_ON_ONCE(). Therefore; the task_work_add() should in fact use event->ctx->task, rather than current. They are always the same, except in this narrow window between perf_event_task_sched_out() and switch_to(). Fixes: c5d93d23a260 ("perf: Enqueue SIGTRAP always via task_work.") Reported-by: Tengda Wu Tested-by: Tengda Wu Signed-off-by: Peter Zijlstra (Intel) Link: https://patch.msgid.link/20261125161342.GP2669272%40noisy.programming.kicks-ass.net --- kernel/events/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kernel/events/core.c b/kernel/events/core.c index 10dc3d0cd81a26..08f0e0ffe50148 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -10970,7 +10970,7 @@ static int __perf_event_overflow(struct perf_event *event, * claim the pending_work before task_work_add() recurses. */ if (cmpxchg_local(&event->pending_work, 0, 1) == 0) { - if (!task_work_add(current, &event->pending_task, notify_mode)) { + if (!task_work_add(event->ctx->task, &event->pending_task, notify_mode)) { event->pending_work = pending_id; local_inc(&event->ctx->nr_no_switch_fast); WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount)); From 8f8dc0d419fba286722611dae31119c48280c319 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 24 Nov 2026 17:51:06 +0100 Subject: [PATCH 1936/2102] efi: efivars: Don't dereference NULL __efivars in efivar_lock() efivar_lock() and efivar_trylock() check __efivars->ops after taking efivars_lock, but __efivars itself is NULL whenever no efivars implementation is registered. That happens at runtime, not only before efivars is set up. For example, tee_stmm_efi_probe() unregisters the generic efivars ops before registering its own, and qcom_uefisecapp_remove() and gsmi_exit() unregister efivars outright. A concurrent or subsequent efivarfs access, or a write from a pstore backend that is still registered, then dereferences a NULL pointer instead of failing with -ENODEV. Check __efivars itself as well as __efivars->ops. Fixes: 472831d4c4b2 ("efi: vars: Add thin wrapper around EFI get/set variable interface") Cc: stable@vger.kernel.org Signed-off-by: Ard Biesheuvel --- drivers/firmware/efi/vars.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/firmware/efi/vars.c b/drivers/firmware/efi/vars.c index 3700e98697676d..f9c28fbdb26dfb 100644 --- a/drivers/firmware/efi/vars.c +++ b/drivers/firmware/efi/vars.c @@ -143,7 +143,7 @@ int efivar_lock(void) { if (down_interruptible(&efivars_lock)) return -EINTR; - if (!__efivars->ops) { + if (!__efivars || !__efivars->ops) { up(&efivars_lock); return -ENODEV; } @@ -159,7 +159,7 @@ int efivar_trylock(void) { if (down_trylock(&efivars_lock)) return -EBUSY; - if (!__efivars->ops) { + if (!__efivars || !__efivars->ops) { up(&efivars_lock); return -ENODEV; } From e70f587f09e4a9de1827aea0401ab61baad16183 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 24 Nov 2026 17:51:16 +0100 Subject: [PATCH 1937/2102] efi: Statically initialize efivar_ops_nh efisubsys_init() initializes the efivar_ops_nh notifier head at runtime, but only after generic_ops_register() has already called efivars_register(), which invokes blocking_notifier_call_chain() on it. This is currently harmless: the head is zero-initialized, and blocking_notifier_call_chain() returns early on an empty chain before touching the rwsem. Still, it is fragile, and there is no reason to set up the notifier head at runtime at all. Use BLOCKING_NOTIFIER_HEAD() so it is valid from the start, and drop the runtime initialization. Signed-off-by: Ard Biesheuvel --- drivers/firmware/efi/efi.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/drivers/firmware/efi/efi.c b/drivers/firmware/efi/efi.c index c5cebd4a75c06f..355d4cb0404e69 100644 --- a/drivers/firmware/efi/efi.c +++ b/drivers/firmware/efi/efi.c @@ -186,7 +186,7 @@ static const struct attribute_group efi_subsys_attr_group = { .is_visible_const = efi_attr_is_visible, }; -struct blocking_notifier_head efivar_ops_nh; +BLOCKING_NOTIFIER_HEAD(efivar_ops_nh); EXPORT_SYMBOL_GPL(efivar_ops_nh); static struct efivars generic_efivars; @@ -487,8 +487,6 @@ static int __init efisubsys_init(void) platform_device_register_simple("efivars", 0, NULL, 0); } - BLOCKING_INIT_NOTIFIER_HEAD(&efivar_ops_nh); - error = sysfs_create_group(efi_kobj, &efi_subsys_attr_group); if (error) { pr_err("efi: Sysfs attribute export failed with error %d.\n", From 3c762dbdc06d3792b5796de3c0d59ee7f02e5ac6 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Thu, 19 Nov 2026 17:34:10 +0700 Subject: [PATCH 1938/2102] ASoC: atmel: mchp-spdifrx: Improve probe error handling Use dev_err_probe() when retrieving clocks to avoid logging errors for deferred probes. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261119103413.31729-2-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-spdifrx.c | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/sound/soc/atmel/mchp-spdifrx.c b/sound/soc/atmel/mchp-spdifrx.c index 63089ac3ebdc97..7d80f35576cd20 100644 --- a/sound/soc/atmel/mchp-spdifrx.c +++ b/sound/soc/atmel/mchp-spdifrx.c @@ -1116,21 +1116,15 @@ static int mchp_spdifrx_probe(struct platform_device *pdev) /* Get the peripheral clock */ dev->pclk = devm_clk_get(&pdev->dev, "pclk"); - if (IS_ERR(dev->pclk)) { - err = PTR_ERR(dev->pclk); - dev_err(&pdev->dev, "failed to get the peripheral clock: %d\n", - err); - return err; - } + if (IS_ERR(dev->pclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->pclk), + "failed to get the peripheral clock\n"); /* Get the generated clock */ dev->gclk = devm_clk_get(&pdev->dev, "gclk"); - if (IS_ERR(dev->gclk)) { - err = PTR_ERR(dev->gclk); - dev_err(&pdev->dev, - "failed to get the PMC generated clock: %d\n", err); - return err; - } + if (IS_ERR(dev->gclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->gclk), + "failed to get the PMC generated clock\n"); /* * Signal control need a valid rate on gclk. hw_params() configures From 0918434ce54001f4d31bfa607b2c9b0d5e8540a8 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Thu, 19 Nov 2026 17:34:11 +0700 Subject: [PATCH 1939/2102] ASoC: atmel: mchp-spdifrx: Use devm helpers for runtime PM Use devm_pm_runtime_enable() and a devm action to handle runtime PM cleanup automatically. This removes the manual runtime PM cleanup from the probe error paths and the remove callback. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261119103413.31729-3-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-spdifrx.c | 47 ++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/sound/soc/atmel/mchp-spdifrx.c b/sound/soc/atmel/mchp-spdifrx.c index 7d80f35576cd20..25122f6ef3c9ba 100644 --- a/sound/soc/atmel/mchp-spdifrx.c +++ b/sound/soc/atmel/mchp-spdifrx.c @@ -1079,6 +1079,15 @@ static const struct dev_pm_ops mchp_spdifrx_pm_ops = { NULL) }; +/* Runtime suspend the device on cleanup if necessary */ +static void mchp_spdifrx_runtime_suspend_action(void *data) +{ + struct device *dev = data; + + if (!pm_runtime_status_suspended(dev)) + mchp_spdifrx_runtime_suspend(dev); +} + static int mchp_spdifrx_probe(struct platform_device *pdev) { struct mchp_spdifrx_dev *dev; @@ -1141,11 +1150,22 @@ static int mchp_spdifrx_probe(struct platform_device *pdev) dev->regmap = regmap; platform_set_drvdata(pdev, dev); - pm_runtime_enable(dev->dev); + err = devm_add_action(dev->dev, mchp_spdifrx_runtime_suspend_action, + dev->dev); + if (err) + return err; + + err = devm_pm_runtime_enable(dev->dev); + if (err) + return err; if (!pm_runtime_enabled(dev->dev)) { err = mchp_spdifrx_runtime_resume(dev->dev); - if (err) - goto pm_runtime_disable; + if (err) { + devm_remove_action(dev->dev, + mchp_spdifrx_runtime_suspend_action, + dev->dev); + return err; + } } dev->capture.addr = (dma_addr_t)mem->start + SPDIFRX_RHR; @@ -1154,7 +1174,7 @@ static int mchp_spdifrx_probe(struct platform_device *pdev) err = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (err) { dev_err(&pdev->dev, "failed to register PCM: %d\n", err); - goto pm_runtime_suspend; + return err; } err = devm_snd_soc_register_component(&pdev->dev, @@ -1162,34 +1182,17 @@ static int mchp_spdifrx_probe(struct platform_device *pdev) &mchp_spdifrx_dai, 1); if (err) { dev_err(&pdev->dev, "fail to register dai\n"); - goto pm_runtime_suspend; + return err; } regmap_read(regmap, SPDIFRX_VERSION, &vers); dev_info(&pdev->dev, "hw version: %#lx\n", vers & SPDIFRX_VERSION_MASK); return 0; - -pm_runtime_suspend: - if (!pm_runtime_status_suspended(dev->dev)) - mchp_spdifrx_runtime_suspend(dev->dev); -pm_runtime_disable: - pm_runtime_disable(dev->dev); - return err; -} - -static void mchp_spdifrx_remove(struct platform_device *pdev) -{ - struct mchp_spdifrx_dev *dev = platform_get_drvdata(pdev); - - pm_runtime_disable(dev->dev); - if (!pm_runtime_status_suspended(dev->dev)) - mchp_spdifrx_runtime_suspend(dev->dev); } static struct platform_driver mchp_spdifrx_driver = { .probe = mchp_spdifrx_probe, - .remove = mchp_spdifrx_remove, .driver = { .name = "mchp_spdifrx", .of_match_table = mchp_spdifrx_dt_ids, From e3414e02d7fed7f869ab203ba6f6fc6dd2ce418d Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Thu, 19 Nov 2026 17:34:12 +0700 Subject: [PATCH 1940/2102] ASoC: atmel: mchp-spdifrx: Move IRQ request after runtime PM setup Move devm_request_irq() after runtime PM setup to ensure the IRQ is released before the runtime suspend action runs during cleanup. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261119103413.31729-4-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-spdifrx.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/sound/soc/atmel/mchp-spdifrx.c b/sound/soc/atmel/mchp-spdifrx.c index 25122f6ef3c9ba..41c65e83576525 100644 --- a/sound/soc/atmel/mchp-spdifrx.c +++ b/sound/soc/atmel/mchp-spdifrx.c @@ -1113,16 +1113,11 @@ static int mchp_spdifrx_probe(struct platform_device *pdev) if (IS_ERR(regmap)) return PTR_ERR(regmap); - /* Request IRQ. */ + /* Get IRQ. */ irq = platform_get_irq(pdev, 0); if (irq < 0) return irq; - err = devm_request_irq(&pdev->dev, irq, mchp_spdif_interrupt, 0, - dev_name(&pdev->dev), dev); - if (err) - return err; - /* Get the peripheral clock */ dev->pclk = devm_clk_get(&pdev->dev, "pclk"); if (IS_ERR(dev->pclk)) @@ -1168,6 +1163,12 @@ static int mchp_spdifrx_probe(struct platform_device *pdev) } } + /* Request IRQ. */ + err = devm_request_irq(&pdev->dev, irq, mchp_spdif_interrupt, 0, + dev_name(&pdev->dev), dev); + if (err) + return err; + dev->capture.addr = (dma_addr_t)mem->start + SPDIFRX_RHR; dev->capture.maxburst = 1; From 648e08bdb51ca5bbd48ac5e9522b019145a74bf5 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Thu, 19 Nov 2026 17:34:13 +0700 Subject: [PATCH 1941/2102] ASoC: atmel: mchp-spdifrx: Propagate runtime PM errors in ulock get Return the result of pm_runtime_resume_and_get() instead of comparing the old and current ulock values. This ensures runtime PM errors are propagated to the caller. Fixes: c7db2a594389 ("ASoC: mchp-spdifrx: add runtime pm support") Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261119103413.31729-5-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-spdifrx.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sound/soc/atmel/mchp-spdifrx.c b/sound/soc/atmel/mchp-spdifrx.c index 41c65e83576525..632da8d7bc8159 100644 --- a/sound/soc/atmel/mchp-spdifrx.c +++ b/sound/soc/atmel/mchp-spdifrx.c @@ -709,7 +709,6 @@ static int mchp_spdifrx_ulock_get(struct snd_kcontrol *kcontrol, struct mchp_spdifrx_mixer_control *ctrl = &dev->control; u32 val; int ret; - bool ulock_old = ctrl->ulock; mutex_lock(&dev->mlock); @@ -735,7 +734,7 @@ static int mchp_spdifrx_ulock_get(struct snd_kcontrol *kcontrol, unlock: mutex_unlock(&dev->mlock); - return ulock_old != ctrl->ulock; + return ret; } static int mchp_spdifrx_badf_get(struct snd_kcontrol *kcontrol, From a142f1c5de4b9c03910cc304a26fbbdef69ca422 Mon Sep 17 00:00:00 2001 From: Sahaj Chaudhari Date: Tue, 24 Nov 2026 19:06:53 +0530 Subject: [PATCH 1942/2102] gpio: davinci: use controller-specific MMIO for BINTEN The file-global gpio_base can be overwritten when probes for multiple DaVinci GPIO controllers overlap. The later IRQ setup can then write the BINTEN register of a different controller. Derive the BINTEN address from the current controller's mapped bank instead of shared global state. Fixes: 118150f22d6b ("gpio: davinci: move to platform device") Reviewed-by: Linus Walleij Signed-off-by: Sahaj Chaudhari Link: https://patch.msgid.link/20261124121500.2cd5cbf30f89-2-sahaj123.sc@gmail.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-davinci.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpio/gpio-davinci.c b/drivers/gpio/gpio-davinci.c index 303b5409e2844b..5f536761ee71fe 100644 --- a/drivers/gpio/gpio-davinci.c +++ b/drivers/gpio/gpio-davinci.c @@ -43,7 +43,6 @@ typedef struct irq_chip *(*gpio_get_irq_chip_cb_t)(unsigned int irq); #define BINTEN 0x8 /* GPIO Interrupt Per-Bank Enable Register */ -static void __iomem *gpio_base; static unsigned int offset_array[5] = {0x10, 0x38, 0x60, 0x88, 0xb0}; struct davinci_gpio_irq_data { @@ -168,6 +167,7 @@ static int davinci_gpio_probe(struct platform_device *pdev) unsigned int ngpio, nbank, nirq, gpio_unbanked; struct davinci_gpio_controller *chips; struct device *dev = &pdev->dev; + void __iomem *gpio_base; /* * The gpio banks conceptually expose a segmented bitmap, @@ -586,7 +586,7 @@ static int davinci_gpio_irq_setup(struct platform_device *pdev) * BINTEN -- per-bank interrupt enable. genirq would also let these * bits be set/cleared dynamically. */ - writel_relaxed(binten, gpio_base + BINTEN); + writel_relaxed(binten, chips->regs[0] - offset_array[0] + BINTEN); return 0; } From 9c5f350322837c83882e350f11f10cb29ed7f9eb Mon Sep 17 00:00:00 2001 From: Sahaj Chaudhari Date: Tue, 24 Nov 2026 19:06:54 +0530 Subject: [PATCH 1943/2102] gpio: davinci: allocate bank IRQ data before installing handlers If allocation fails partway through bank setup, previously installed chained handlers still point at devm-managed data that is released when probe fails. Allocate the complete bank-data array before installing the first chained handler so an allocation failure leaves no handlers behind. This fixes the probe-failure path; it does not change ordinary device removal. Fixes: b5cf3fd827d2 ("gpio: davinci: Redesign driver to accommodate ngpios in one gpio chip") Reviewed-by: Linus Walleij Signed-off-by: Sahaj Chaudhari Link: https://patch.msgid.link/20261124121500.2cd5cbf30f89-3-sahaj123.sc@gmail.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-davinci.c | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/drivers/gpio/gpio-davinci.c b/drivers/gpio/gpio-davinci.c index 5f536761ee71fe..5f24367ad9af8a 100644 --- a/drivers/gpio/gpio-davinci.c +++ b/drivers/gpio/gpio-davinci.c @@ -550,6 +550,13 @@ static int davinci_gpio_irq_setup(struct platform_device *pdev) * Or, AINTC can handle IRQs for banks of 16 GPIO IRQs, which we * then chain through our own handler. */ + irqdata = devm_kzalloc_objs(dev, *irqdata, + DIV_ROUND_UP(ngpio, 16)); + if (!irqdata) { + irq_domain_remove(chips->irq_domain); + return -ENOMEM; + } + for (gpio = 0, bank = 0; gpio < ngpio; bank++, gpio += 16) { /* disabled by default, enabled only as needed * There are register sets for 32 GPIOs. 2 banks of 16 @@ -564,19 +571,12 @@ static int davinci_gpio_irq_setup(struct platform_device *pdev) * gpio irqs. Pass the irq bank's corresponding controller to * the chained irq handler. */ - irqdata = devm_kzalloc_obj(&pdev->dev, - struct davinci_gpio_irq_data); - if (!irqdata) { - irq_domain_remove(chips->irq_domain); - return -ENOMEM; - } - - irqdata->regs = g; - irqdata->bank_num = bank; - irqdata->chip = chips; + irqdata[bank].regs = g; + irqdata[bank].bank_num = bank; + irqdata[bank].chip = chips; irq_set_chained_handler_and_data(chips->irqs[bank], - gpio_irq_handler, irqdata); + gpio_irq_handler, &irqdata[bank]); binten |= BIT(bank); } From f18a4698b0124f77549c23600fa5105bac2951f2 Mon Sep 17 00:00:00 2001 From: Guangshuo Li Date: Tue, 24 Nov 2026 21:58:32 +0800 Subject: [PATCH 1944/2102] gpio: aspeed: Fix potential coprocessor bank map leak The coprocessor bank map is allocated lazily but is never freed when the GPIO controller is removed. Its only owner is the device-managed GPIO private data. Allocate the map with the controller's managed resources before registering the GPIO chip, so chip removal finishes before the map is freed. Round up the bank count to cover a partial last bank. This issue was found by our static analysis tool under development. Fixes: a7ca13826e47 ("gpio: aspeed: Add interfaces for co-processor to grab GPIOs") Cc: stable@vger.kernel.org Signed-off-by: Guangshuo Li Link: https://patch.msgid.link/20261124135833.2275409-1-liguangshuo@mail.sdu.edu.cn Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-aspeed.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/drivers/gpio/gpio-aspeed.c b/drivers/gpio/gpio-aspeed.c index 45e90ebaf07840..8f66be7ff9b5bc 100644 --- a/drivers/gpio/gpio-aspeed.c +++ b/drivers/gpio/gpio-aspeed.c @@ -944,10 +944,6 @@ int aspeed_gpio_copro_grab_gpio(struct gpio_desc *desc, if (!aspeed_gpio_support_copro(gpio)) return -EOPNOTSUPP; - if (!gpio->cf_copro_bankmap) - gpio->cf_copro_bankmap = kzalloc(gpio->chip.ngpio >> 3, GFP_KERNEL); - if (!gpio->cf_copro_bankmap) - return -ENOMEM; if (offset < 0 || offset > gpio->chip.ngpio) return -EINVAL; bindex = offset >> 3; @@ -1381,6 +1377,14 @@ static int aspeed_gpio_probe(struct platform_device *pdev) gpio->config->llops->reg_bank_get(gpio, (i << 5), reg_rdata); } + if (aspeed_gpio_support_copro(gpio)) { + gpio->cf_copro_bankmap = devm_kzalloc_objs(gpio->dev, + *gpio->cf_copro_bankmap, + DIV_ROUND_UP(gpio->chip.ngpio, 8)); + if (!gpio->cf_copro_bankmap) + return -ENOMEM; + } + if (gpio->config->llops->privilege_init) gpio->config->llops->privilege_init(gpio); From 64b7a47c24cd1fa01fd7e70bdfd72ea95c8c8e60 Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Wed, 25 Nov 2026 16:03:41 +0100 Subject: [PATCH 1945/2102] gpiolib: use the of_xlate() result when hogging lines Since commit d1d564ec4992 ("gpio: move hogs into GPIO core"), gpiochip_add_hog() takes the hogged line from the first cell of the "gpios" property. The of_xlate() callback is still called for OF nodes but only to get the flags so on controllers that compute the offset in of_xlate() (sunxi, Qualcomm PMIC GPIOs, tegra186, ...) the wrong line is hogged. Use the descriptor returned by of_xlate() for OF nodes. Cc: stable@vger.kernel.org Fixes: d1d564ec4992 ("gpio: move hogs into GPIO core") Reported-by: Norman Herms Closes: https://lore.kernel.org/all/qh4LV99kGaQYdQuGbsPX4b9Fm6Cip_Ow7ImY4icfwI8IsbMQy_09FovZY82b-_HVkDmR2ELMlKe8bzCuBB5NpaZizoO-s4tc11zAX30FDhw=@proton.me/ Reviewed-by: Mika Westerberg Reviewed-by: Linus Walleij Tested-by: Norman Herms Link: https://patch.msgid.link/20261125-gpio-three-cell-hog-v1-1-724b15c4f0d8@oss.qualcomm.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib-of.c | 10 +++++----- drivers/gpio/gpiolib-of.h | 15 ++++++++------- drivers/gpio/gpiolib.c | 14 +++++++------- 3 files changed, 20 insertions(+), 19 deletions(-) diff --git a/drivers/gpio/gpiolib-of.c b/drivers/gpio/gpiolib-of.c index 8f8454d5960469..ea1dfc3a313112 100644 --- a/drivers/gpio/gpiolib-of.c +++ b/drivers/gpio/gpiolib-of.c @@ -721,9 +721,9 @@ struct gpio_desc *of_find_gpio(struct device_node *np, const char *con_id, return desc; } -int of_gpiochip_get_lflags(struct gpio_chip *chip, - struct fwnode_reference_args *gpiospec, - unsigned long *lflags) +struct gpio_desc *of_gpiochip_get_hog_desc(struct gpio_chip *chip, + struct fwnode_reference_args *gpiospec, + unsigned long *lflags) { enum of_gpio_flags xlate_flags = 0; struct of_phandle_args args; @@ -737,11 +737,11 @@ int of_gpiochip_get_lflags(struct gpio_chip *chip, desc = of_xlate_and_get_gpiod_flags(chip, &args, &xlate_flags); if (IS_ERR(desc)) - return PTR_ERR(desc); + return desc; *lflags = of_convert_gpio_flags(xlate_flags); - return 0; + return desc; } #ifdef CONFIG_OF_DYNAMIC diff --git a/drivers/gpio/gpiolib-of.h b/drivers/gpio/gpiolib-of.h index 9ca540d93f93be..347b82f9e3ff4d 100644 --- a/drivers/gpio/gpiolib-of.h +++ b/drivers/gpio/gpiolib-of.h @@ -25,9 +25,9 @@ int of_gpiochip_add(struct gpio_chip *gc); void of_gpiochip_remove(struct gpio_chip *gc); bool of_gpiochip_instance_match(struct gpio_chip *gc, unsigned int index); int of_gpio_count(const struct fwnode_handle *fwnode, const char *con_id); -int of_gpiochip_get_lflags(struct gpio_chip *chip, - struct fwnode_reference_args *gpiospec, - unsigned long *lflags); +struct gpio_desc *of_gpiochip_get_hog_desc(struct gpio_chip *chip, + struct fwnode_reference_args *gpiospec, + unsigned long *lflags); #else static inline struct gpio_desc *of_find_gpio(struct device_node *np, const char *con_id, @@ -48,11 +48,12 @@ static inline int of_gpio_count(const struct fwnode_handle *fwnode, { return -ENOENT; } -static inline int of_gpiochip_get_lflags(struct gpio_chip *chip, - struct fwnode_reference_args *gpiospec, - unsigned long *lflags) +static inline struct gpio_desc * +of_gpiochip_get_hog_desc(struct gpio_chip *chip, + struct fwnode_reference_args *gpiospec, + unsigned long *lflags) { - return -ENOENT; + return ERR_PTR(-ENOENT); } #endif /* CONFIG_OF_GPIO */ diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index 06574f4c50d013..46a68a6b739f70 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -1047,9 +1047,9 @@ int gpiochip_add_hog(struct gpio_chip *gc, struct fwnode_handle *fwnode) for (unsigned int j = 0; j < cells; j++) gpiospec.args[j] = gpios[i * cells + j]; - ret = of_gpiochip_get_lflags(gc, &gpiospec, &lflags); - if (ret) - return ret; + desc = of_gpiochip_get_hog_desc(gc, &gpiospec, &lflags); + if (IS_ERR(desc)) + return PTR_ERR(desc); /* * If no line-name property is present, fall back to the OF @@ -1065,11 +1065,11 @@ int gpiochip_add_hog(struct gpio_chip *gc, struct fwnode_handle *fwnode) */ if (cells > 1 && gpios[i * cells + 1]) lflags |= GPIO_ACTIVE_LOW; - } - desc = gpiochip_get_desc(gc, gpios[i * cells]); - if (IS_ERR(desc)) - return PTR_ERR(desc); + desc = gpiochip_get_desc(gc, gpios[i * cells]); + if (IS_ERR(desc)) + return PTR_ERR(desc); + } ret = gpiod_hog(desc, name, lflags, dflags); if (ret) From 62a41997c1553b723a7a333c0246d0646ebd2c95 Mon Sep 17 00:00:00 2001 From: Rosen Penev Date: Wed, 25 Nov 2026 16:26:50 -0800 Subject: [PATCH 1946/2102] gpio: mvebu: validate ngpios before use If ngpios is read as 0 from device tree, it is passed via irq_alloc_domain_generic_chips() as irqs_per_chip, which leads to a division by zero in DIV_ROUND_UP(d->revmap_size, irqs_per_chip). Reject ngpios == 0 early. Also reject higher than 32, which is the limit. Fixes: fefe7b0923459 ("gpio: introduce gpio-mvebu driver for Marvell SoCs") Signed-off-by: Rosen Penev Link: https://patch.msgid.link/20261126002650.603321-1-rosenp@gmail.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-mvebu.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/gpio/gpio-mvebu.c b/drivers/gpio/gpio-mvebu.c index 2591239b1956bb..1e30f23a5317ee 100644 --- a/drivers/gpio/gpio-mvebu.c +++ b/drivers/gpio/gpio-mvebu.c @@ -1213,6 +1213,9 @@ static int mvebu_gpio_probe(struct platform_device *pdev) return -ENODEV; } + if (ngpios == 0 || ngpios > MVEBU_MAX_GPIO_PER_BANK) + return dev_err_probe(&pdev->dev, -EINVAL, "ngpios must be between 1 and 32\n"); + id = of_alias_get_id(pdev->dev.of_node, "gpio"); if (id < 0) { dev_err(&pdev->dev, "Couldn't get OF id\n"); From 1e5a677a5c53b96abf8004cc4d7ba0387f4e8505 Mon Sep 17 00:00:00 2001 From: Marco Giunta Date: Sat, 21 Nov 2026 08:05:10 +0100 Subject: [PATCH 1947/2102] ASoC: aw88399: fix register used to disable I2S TX aw_dev_i2s_tx_enable() uses I2SCTRL3 when enabling the I2S transmitter but I2SCFG1 when disabling it. Per the datasheet, the I2STXEN bit lives in I2SCTRL3. As a result, the I2S transmitter is never disabled when the device is stopped. Use I2SCTRL3 in both cases, as the vendor Android driver (aw883xx) and aw88166 (which is also derived from aw883xx) do. Fixes: 8ade6cc7e261 ("ASoC: codecs: Add aw88399 amplifier driver") Signed-off-by: Marco Giunta Link: https://patch.msgid.link/SN6PR19MB23038B66A212CA32A4B6B3CCFC472@SN6PR19MB2303.namprd19.prod.outlook.com Signed-off-by: Mark Brown --- sound/soc/codecs/aw88399-lib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/codecs/aw88399-lib.c b/sound/soc/codecs/aw88399-lib.c index f2e2c88f5ec0a7..a6303f32e2cfb9 100644 --- a/sound/soc/codecs/aw88399-lib.c +++ b/sound/soc/codecs/aw88399-lib.c @@ -552,7 +552,7 @@ static void aw_dev_i2s_tx_enable(struct aw_device *aw_dev, bool flag) ret = regmap_update_bits(aw_dev->regmap, AW88399_I2SCTRL3_REG, ~AW88399_I2STXEN_MASK, AW88399_I2STXEN_ENABLE_VALUE); else - ret = regmap_update_bits(aw_dev->regmap, AW88399_I2SCFG1_REG, + ret = regmap_update_bits(aw_dev->regmap, AW88399_I2SCTRL3_REG, ~AW88399_I2STXEN_MASK, AW88399_I2STXEN_DISABLE_VALUE); if (ret) From b824fb3c0844f6fcfded73bfb72813205f3ad40d Mon Sep 17 00:00:00 2001 From: Marco Giunta Date: Thu, 19 Nov 2026 17:30:12 +0100 Subject: [PATCH 1948/2102] ASoC: aw88261: fix sign bit check in aw88261_dev_get_vcalk() AW88261_EF_ISN_GESLP_SIGN_MASK and AW88261_EF_VSN_GESLP_SIGN_MASK are defined with the usual Awinic inverted-mask convention, i.e. they both equal ~BIT(9); therefore, their negations have to be used to test the sign bit. aw88261_dev_get_icalk() does this correctly: if (reg_icalk & (~AW88261_EF_ISN_GESLP_SIGN_MASK)) while aw88261_dev_get_vcalk() does not: if (reg_vcalk & AW88261_EF_VSN_GESLP_SIGN_MASK) Add the missing negation to fix this. This ensures that the aw88261 driver behaves like the vendor Android driver it was ported from (aw882xx), and that it's consistent with the other upstream Awinic drivers that have analogous functions, i.e. aw88166 and aw88395 (aw88399 has the same bug, which is fixed in the next patch). Fixes: 028a2ae25691 ("ASoC: codecs: Add aw88261 amplifier driver") Signed-off-by: Marco Giunta Reviewed-by: Vladyslav Tymoshchuk Tested-by: Vladyslav Tymoshchuk Link: https://patch.msgid.link/SN6PR19MB2303E8188DC58BDC07645705FC792@SN6PR19MB2303.namprd19.prod.outlook.com Signed-off-by: Mark Brown --- sound/soc/codecs/aw88261.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/codecs/aw88261.c b/sound/soc/codecs/aw88261.c index e14df93e67f7ad..d4db919d8a2df6 100644 --- a/sound/soc/codecs/aw88261.c +++ b/sound/soc/codecs/aw88261.c @@ -306,7 +306,7 @@ static int aw88261_dev_get_vcalk(struct aw_device *aw_dev, int16_t *vcalk) reg_vcalk = (reg_vcalk >> AW88261_VCALK_SHIFT) & (reg_vcalkl >> AW88261_VCALKL_SHIFT); - if (reg_vcalk & AW88261_EF_VSN_GESLP_SIGN_MASK) + if (reg_vcalk & (~AW88261_EF_VSN_GESLP_SIGN_MASK)) reg_vcalk = reg_vcalk | (~AW88261_EF_VSN_GESLP_NEG); *vcalk = (int16_t)reg_vcalk; From e18570e9cee374d3bdd5784eb2ed608d92567d05 Mon Sep 17 00:00:00 2001 From: Marco Giunta Date: Thu, 19 Nov 2026 17:30:13 +0100 Subject: [PATCH 1949/2102] ASoC: aw88399: fix sign bit check in aw88399_dev_get_vcalk() AW88399_EF_ISN_GESLP_SIGN_MASK and AW88399_EF_VSN_GESLP_SIGN_MASK are defined with the usual Awinic inverted-mask convention, i.e. they both equal ~BIT(9); therefore, their negations have to be used to test the sign bit. aw88399_dev_get_icalk() does this correctly: if (icalk_val & (~AW88399_EF_ISN_GESLP_SIGN_MASK)) while aw88399_dev_get_vcalk() does not: if (vcalk_val & AW88399_EF_VSN_GESLP_SIGN_MASK) Add the missing negation to fix this. This ensures that the aw88399 driver behaves like the vendor Android driver it was ported from (aw883xx), and that it's consistent with the other upstream Awinic drivers that have analogous functions, i.e. aw88166, aw88261, and aw88395. Fixes: 8ade6cc7e261 ("ASoC: codecs: Add aw88399 amplifier driver") Signed-off-by: Marco Giunta Link: https://patch.msgid.link/SN6PR19MB23035CADF2988E49E618ADE4FC792@SN6PR19MB2303.namprd19.prod.outlook.com Signed-off-by: Mark Brown --- sound/soc/codecs/aw88399-lib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/codecs/aw88399-lib.c b/sound/soc/codecs/aw88399-lib.c index f2e2c88f5ec0a7..39a752171aa1ca 100644 --- a/sound/soc/codecs/aw88399-lib.c +++ b/sound/soc/codecs/aw88399-lib.c @@ -296,7 +296,7 @@ static int aw88399_dev_get_vcalk(struct aw88399 *aw88399, int16_t *vcalk) else vcalk_val = vcalkh_val | vcalkl_val; - if (vcalk_val & AW88399_EF_VSN_GESLP_SIGN_MASK) + if (vcalk_val & (~AW88399_EF_VSN_GESLP_SIGN_MASK)) vcalk_val = vcalk_val | AW88399_EF_VSN_GESLP_SIGN_NEG; *vcalk = (int16_t)vcalk_val; From da290cad79b6e11bc6fb995ad2087f3eb54ecff8 Mon Sep 17 00:00:00 2001 From: Marco Giunta Date: Thu, 19 Nov 2026 17:30:14 +0100 Subject: [PATCH 1950/2102] ASoC: aw88166: fix clearing of SYSCTRL bits When applying the SYSCTRL value from the firmware, aw_dev_update_reg_container() means to overwrite the HMUTE, PWDN and DSPBY bits with fixed values, by clearing them and then taking the OR with the intended values. This is the same behavior as the Android driver aw88166 was ported from (aw883xx), which does so field by field, and as the upstream aw88081 and aw88261 drivers, which manually compute a collective mask and perform a single VAL &= MASK. Currently, the aw88166 driver takes the latter approach, by computing MASK as AW88166_HMUTE_MASK | AW88166_PWDN_MASK | AW88166_DSPBY_MASK. As per the usual Awinic inverted-mask convention, these macros equal ~BIT(8), ~BIT(0) and ~BIT(2) respectively, so using OR on them yields all ones and clears nothing. Use AND instead, as commit b82fa9b0c26e ("ASoC: codecs: aw88261: Fix erroneous bitmask logic in Awinic init") did for aw88261. In practice this makes no difference, since the values ORed in right afterwards equal BIT(8), BIT(0) and BIT(2): these bits end up set regardless of whether or not they were previously cleared. The fix here simply keeps the code correct regardless of the values used. Fixes: 94e412c28e61 ("ASoC: codecs: Add aw88166 amplifier driver") Signed-off-by: Marco Giunta Link: https://patch.msgid.link/SN6PR19MB2303CBDAF11DF2405D138159FC792@SN6PR19MB2303.namprd19.prod.outlook.com Signed-off-by: Mark Brown --- sound/soc/codecs/aw88166.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/codecs/aw88166.c b/sound/soc/codecs/aw88166.c index a520c9089425ca..226a36f041d9e3 100644 --- a/sound/soc/codecs/aw88166.c +++ b/sound/soc/codecs/aw88166.c @@ -961,7 +961,7 @@ static int aw_dev_update_reg_container(struct aw88166 *aw88166, else aw_dev->dsp_cfg = AW88166_DEV_DSP_WORK; - reg_val &= (AW88166_HMUTE_MASK | AW88166_PWDN_MASK | + reg_val &= (AW88166_HMUTE_MASK & AW88166_PWDN_MASK & AW88166_DSPBY_MASK); reg_val |= (AW88166_HMUTE_ENABLE_VALUE | AW88166_PWDN_POWER_DOWN_VALUE | AW88166_DSPBY_BYPASS_VALUE); From 9deb0f9e70281f9187d007f975ced8d400a61763 Mon Sep 17 00:00:00 2001 From: Marco Giunta Date: Thu, 19 Nov 2026 17:30:15 +0100 Subject: [PATCH 1951/2102] ASoC: aw88399: fix clearing of SYSCTRL bits When applying the SYSCTRL value from the firmware, aw_dev_update_reg_container() means to overwrite the HMUTE, PWDN and DSPBY bits with fixed values, by clearing them and then taking the OR with the intended values. This is the same behavior as the Android driver aw88399 was ported from (aw883xx), which does so field by field, and as the upstream aw88081, aw88166, and aw88261 drivers, which manually compute a collective mask and perform a single VAL &= MASK. Currently, the aw88399 driver takes the latter approach, by computing MASK as AW88399_HMUTE_MASK | AW88399_PWDN_MASK | AW88399_DSPBY_MASK. As per the usual Awinic inverted-mask convention, these macros equal ~BIT(8), ~BIT(0) and ~BIT(2) respectively, so using OR on them yields all ones and clears nothing. Use AND instead, as commit b82fa9b0c26e ("ASoC: codecs: aw88261: Fix erroneous bitmask logic in Awinic init") did for aw88261. In practice this makes no difference, since the values ORed in right afterwards equal BIT(8), BIT(0) and BIT(2): these bits end up set regardless of whether or not they were previously cleared. The fix here simply keeps the code correct regardless of the values used. Fixes: 8ade6cc7e261 ("ASoC: codecs: Add aw88399 amplifier driver") Signed-off-by: Marco Giunta Link: https://patch.msgid.link/SN6PR19MB2303EE6C412E5102D89F7FC0FC792@SN6PR19MB2303.namprd19.prod.outlook.com Signed-off-by: Mark Brown --- sound/soc/codecs/aw88399-lib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/codecs/aw88399-lib.c b/sound/soc/codecs/aw88399-lib.c index 39a752171aa1ca..447ac5fb01a16a 100644 --- a/sound/soc/codecs/aw88399-lib.c +++ b/sound/soc/codecs/aw88399-lib.c @@ -957,7 +957,7 @@ static int aw_dev_update_reg_container(struct aw88399 *aw88399, else aw_dev->dsp_cfg = AW88399_DEV_DSP_WORK; - reg_val &= (AW88399_HMUTE_MASK | AW88399_PWDN_MASK | + reg_val &= (AW88399_HMUTE_MASK & AW88399_PWDN_MASK & AW88399_DSPBY_MASK); reg_val |= (AW88399_HMUTE_ENABLE_VALUE | AW88399_PWDN_POWER_DOWN_VALUE | AW88399_DSPBY_BYPASS_VALUE); From a860c9588b94518bb904d2294a2999bcaa765c4b Mon Sep 17 00:00:00 2001 From: Marco Giunta Date: Thu, 19 Nov 2026 17:30:16 +0100 Subject: [PATCH 1952/2102] ASoC: aw88399: rename AW883XX_* macros to AW88399_* The aw88399 library header at include/sound/aw88399.h defines all its macros as AW88399_*, apart from a few AW883XX_* ones. These are likely an oversight from when the generic Android vendor driver, aw883xx, was originally ported upstream in an aw88399-specialized version. Rename these macros to AW88399_* to make them consistent with the rest of the header. Signed-off-by: Marco Giunta Link: https://patch.msgid.link/SN6PR19MB23031C99F1C5700B1D89003EFC792@SN6PR19MB2303.namprd19.prod.outlook.com Signed-off-by: Mark Brown --- include/sound/aw88399.h | 14 +++++++------- sound/soc/codecs/aw88399.c | 6 +++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/include/sound/aw88399.h b/include/sound/aw88399.h index d72c491ee86636..fa43e8068093ac 100644 --- a/include/sound/aw88399.h +++ b/include/sound/aw88399.h @@ -469,13 +469,13 @@ #define AW88399_DSP_VOL_MASK \ (~(((1<regmap, AW88399_DBGCTRL_REG, - ~AW883XX_DSP_NG_EN_MASK, AW883XX_DSP_NG_EN_DISABLE_VALUE); + ~AW88399_DSP_NG_EN_MASK, AW88399_DSP_NG_EN_DISABLE_VALUE); aw_dev_dsp_write(aw_dev, AW88399_DSP_LOW_POWER_SWITCH_CFG_ADDR, AW88399_DSP_LOW_POWER_SWITCH_DISABLE, AW_DSP_16_DATA); @@ -166,7 +166,7 @@ static void aw_cali_svc_backup_info(struct aw_device *aw_dev) unsigned int reg_val, dsp_val; regmap_read(aw_dev->regmap, AW88399_DBGCTRL_REG, ®_val); - backup_desc->dsp_ng_cfg = reg_val & (~AW883XX_DSP_NG_EN_MASK); + backup_desc->dsp_ng_cfg = reg_val & (~AW88399_DSP_NG_EN_MASK); aw_dev_dsp_read(aw_dev, AW88399_DSP_LOW_POWER_SWITCH_CFG_ADDR, &dsp_val, AW_DSP_16_DATA); @@ -178,7 +178,7 @@ static void aw_cali_svc_recover_info(struct aw_device *aw_dev) struct aw_cali_backup_desc *backup_desc = &aw_dev->cali_desc.backup_info; regmap_update_bits(aw_dev->regmap, AW88399_DBGCTRL_REG, - ~AW883XX_DSP_NG_EN_MASK, backup_desc->dsp_ng_cfg); + ~AW88399_DSP_NG_EN_MASK, backup_desc->dsp_ng_cfg); aw_dev_dsp_write(aw_dev, AW88399_DSP_LOW_POWER_SWITCH_CFG_ADDR, backup_desc->dsp_lp_cfg, AW_DSP_16_DATA); From d77700039d09479f81f0bc8b73002af8ec95d3f7 Mon Sep 17 00:00:00 2001 From: Dominik Maier Date: Thu, 19 Nov 2026 20:21:42 +0100 Subject: [PATCH 1953/2102] udp: only quit inuse scan early on identical SO_REUSEPORT sockets Commit df560056d960 ("udp: inuse checks can quit early for reuseport") optimized udp_lib_lport_inuse() and udp_lib_lport_inuse2() to return 0 immediately upon encountering the first same-UID SO_REUSEPORT socket that matches under wildcard conflict rules. However, a socket that matches under wildcard rules (or shares only a relaxed subset of bind attributes) does not guarantee that the remaining sockets in hslot->head or hslot2->head are conflict-free for the new socket. Because IPv4 UDP sockets prepend to the head of the hash chain, an unprivileged local user can bind a non-conflicting SO_REUSEPORT socket (e.g., 127.0.0.2:PORT) ahead of another user's exclusive 127.0.0.1:PORT UDP listener, then bind 0.0.0.0:PORT (returning early on 127.0.0.2:PORT without reaching the exclusive listener), and finally bind 127.0.0.1:PORT at the head of hslot2->head to intercept cross-UID UDP datagrams. Only take the O(1) early exit when sk and sk2 share the exact same conflict domain (sk_family, ipv6_only_sock(), sk_bound_dev_if, sk_reuse, and exact receive address via inet_rcv_saddr_equal() with match_wildcard=false), and continue scanning the hash chain otherwise. This preserves O(1) bind scaling for identical SO_REUSEPORT groups while preventing cross-UID conflict checks from being skipped. This issue was discovered with an AI-assisted code review tool (ARTIST) and reproduced in QEMU/KVM on an unmodified v7.4-rc3 kernel without kernel modifications or error injection; a standalone reproducer is available on request. This revised exact-match fastpath patch was compile-tested with -Werror and checked with checkpatch.pl --strict; it has not yet been runtime-tested against the reproducer or kernel selftests. Fixes: df560056d960 ("udp: inuse checks can quit early for reuseport") Cc: stable@vger.kernel.org Signed-off-by: Dominik Maier Link: https://patch.msgid.link/20261119192142.2637952-1-dmnk@google.com Signed-off-by: Paolo Abeni --- net/ipv4/udp.c | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/net/ipv4/udp.c b/net/ipv4/udp.c index 2e5562f353f85d..d784faf939c3b8 100644 --- a/net/ipv4/udp.c +++ b/net/ipv4/udp.c @@ -131,6 +131,15 @@ EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc); #define MAX_UDP_PORTS 65536 #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN_PERNET) +static bool udp_sk_reuseport_match(struct sock *sk, struct sock *sk2) +{ + return sk2->sk_family == sk->sk_family && + ipv6_only_sock(sk2) == ipv6_only_sock(sk) && + sk2->sk_bound_dev_if == sk->sk_bound_dev_if && + sk2->sk_reuse == sk->sk_reuse && + inet_rcv_saddr_equal(sk, sk2, false); +} + static int udp_lib_lport_inuse(struct net *net, __u16 num, const struct udp_hslot *hslot, unsigned long *bitmap, @@ -154,8 +163,11 @@ static int udp_lib_lport_inuse(struct net *net, __u16 num, if (!bitmap) { if (sk2->sk_reuseport && sk->sk_reuseport && !rcu_access_pointer(sk->sk_reuseport_cb) && - uid_eq(uid, sk_uid(sk2))) - return 0; + uid_eq(uid, sk_uid(sk2))) { + if (udp_sk_reuseport_match(sk, sk2)) + return 0; + continue; + } return 1; } __set_bit(udp_sk(sk2)->udp_port_hash >> log, bitmap); @@ -188,10 +200,13 @@ static int udp_lib_lport_inuse2(struct net *net, __u16 num, if (sk2->sk_reuseport && sk->sk_reuseport && !rcu_access_pointer(sk->sk_reuseport_cb) && uid_eq(uid, sk_uid(sk2))) { - res = 0; - } else { - res = 1; + if (udp_sk_reuseport_match(sk, sk2)) { + res = 0; + break; + } + continue; } + res = 1; break; } } From 145707a7d371113748d912e074c8e54514d3fc6b Mon Sep 17 00:00:00 2001 From: Jiebing Chen Date: Tue, 10 Nov 2026 10:28:25 +0800 Subject: [PATCH 1954/2102] dt-bindings: Asoc: axg-audio: Add S4 audio tocodec Add S4 SoC tocodec compatibility support. Acked-by: Rob Herring (Arm) Signed-off-by: Jiebing Chen Link: https://patch.msgid.link/20261110-audio_drvier-v8-2-1489241e4c83@amlogic.com Signed-off-by: Mark Brown --- .../devicetree/bindings/sound/amlogic,g12a-toacodec.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/sound/amlogic,g12a-toacodec.yaml b/Documentation/devicetree/bindings/sound/amlogic,g12a-toacodec.yaml index 23f82bb8975089..7e053aaa0f59a7 100644 --- a/Documentation/devicetree/bindings/sound/amlogic,g12a-toacodec.yaml +++ b/Documentation/devicetree/bindings/sound/amlogic,g12a-toacodec.yaml @@ -25,6 +25,7 @@ properties: - const: amlogic,g12a-toacodec - items: - enum: + - amlogic,s4-toacodec - amlogic,sm1-toacodec - const: amlogic,g12a-toacodec From 61802135f7437ab1ae41a24fa4c5a52b4f24f6d3 Mon Sep 17 00:00:00 2001 From: Jiebing Chen Date: Tue, 10 Nov 2026 10:28:26 +0800 Subject: [PATCH 1955/2102] ASoC: meson: g12a-toacodec: Add S4 tocodec driver The S4 requires additional clock control bits to be turn on while enabled. The S4 has 8 TDM lanes, instead of 4 on previous SoC. Update the widget accordingly. Signed-off-by: Jiebing Chen Link: https://patch.msgid.link/20261110-audio_drvier-v8-3-1489241e4c83@amlogic.com Signed-off-by: Mark Brown --- sound/soc/meson/g12a-toacodec.c | 64 +++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/sound/soc/meson/g12a-toacodec.c b/sound/soc/meson/g12a-toacodec.c index b3d74419e56ecb..ecee099ac8bf18 100644 --- a/sound/soc/meson/g12a-toacodec.c +++ b/sound/soc/meson/g12a-toacodec.c @@ -40,6 +40,10 @@ #define CTRL0_BCLK_SEL_MSB 5 #define CTRL0_BCLK_SEL_LSB 4 #define CTRL0_MCLK_SEL GENMASK(2, 0) +#define CTRL0_BCLK_ENABLE_SHIFT_S4 30 +#define CTRL0_MCLK_ENABLE_SHIFT_S4 29 +#define CTRL0_DAT_SEL_S4_MSB 20 +#define CTRL0_DAT_SEL_S4_LSB 19 #define TOACODEC_OUT_CHMAX 2 @@ -123,6 +127,19 @@ static const struct snd_kcontrol_new sm1_toacodec_mux = snd_soc_dapm_get_enum_double, g12a_toacodec_mux_put_enum); +/* + * The S4 lane selector is one bit wider than the SM1 one, which pushes the + * data selector up by one bit as well. + */ +static SOC_ENUM_SINGLE_DECL(s4_toacodec_mux_enum, TOACODEC_CTRL0, + CTRL0_DAT_SEL_S4_LSB, + g12a_toacodec_mux_texts); + +static const struct snd_kcontrol_new s4_toacodec_mux = + SOC_DAPM_ENUM_EXT("Source", s4_toacodec_mux_enum, + snd_soc_dapm_get_enum_double, + g12a_toacodec_mux_put_enum); + static const struct snd_kcontrol_new g12a_toacodec_out_enable = SOC_DAPM_SINGLE_AUTODISABLE("Switch", TOACODEC_CTRL0, CTRL0_ENABLE_SHIFT, 1, 0); @@ -141,6 +158,17 @@ static const struct snd_soc_dapm_widget sm1_toacodec_widgets[] = { &g12a_toacodec_out_enable), }; +static const struct snd_soc_dapm_widget s4_toacodec_widgets[] = { + SND_SOC_DAPM_MUX("SRC", SND_SOC_NOPM, 0, 0, + &s4_toacodec_mux), + SND_SOC_DAPM_SWITCH("OUT EN", SND_SOC_NOPM, 0, 0, + &g12a_toacodec_out_enable), + SND_SOC_DAPM_SUPPLY("I2S BCLK EN", TOACODEC_CTRL0, + CTRL0_BCLK_ENABLE_SHIFT_S4, 0, NULL, 0), + SND_SOC_DAPM_SUPPLY("I2S MCLK EN", TOACODEC_CTRL0, + CTRL0_MCLK_ENABLE_SHIFT_S4, 0, NULL, 0), +}; + static int g12a_toacodec_input_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) @@ -226,6 +254,16 @@ static const struct snd_soc_dapm_route g12a_toacodec_routes[] = { { "OUT Capture", NULL, "OUT EN" }, }; +static const struct snd_soc_dapm_route s4_toacodec_routes[] = { + { "SRC", "I2S A", "IN A Playback" }, + { "SRC", "I2S B", "IN B Playback" }, + { "SRC", "I2S C", "IN C Playback" }, + { "OUT EN", "Switch", "SRC" }, + { "OUT Capture", NULL, "OUT EN" }, + { "OUT EN", NULL, "I2S BCLK EN" }, + { "OUT EN", NULL, "I2S MCLK EN" }, +}; + static const struct snd_kcontrol_new g12a_toacodec_controls[] = { SOC_SINGLE("Lane Select", TOACODEC_CTRL0, CTRL0_LANE_SEL, 3, 0), }; @@ -234,6 +272,10 @@ static const struct snd_kcontrol_new sm1_toacodec_controls[] = { SOC_SINGLE("Lane Select", TOACODEC_CTRL0, CTRL0_LANE_SEL_SM1, 3, 0), }; +static const struct snd_kcontrol_new s4_toacodec_controls[] = { + SOC_SINGLE("Lane Select", TOACODEC_CTRL0, CTRL0_LANE_SEL_SM1, 7, 0), +}; + static const struct snd_soc_component_driver g12a_toacodec_component_drv = { .probe = g12a_toacodec_component_probe, .controls = g12a_toacodec_controls, @@ -256,6 +298,17 @@ static const struct snd_soc_component_driver sm1_toacodec_component_drv = { .endianness = 1, }; +static const struct snd_soc_component_driver s4_toacodec_component_drv = { + .probe = sm1_toacodec_component_probe, + .controls = s4_toacodec_controls, + .num_controls = ARRAY_SIZE(s4_toacodec_controls), + .dapm_widgets = s4_toacodec_widgets, + .num_dapm_widgets = ARRAY_SIZE(s4_toacodec_widgets), + .dapm_routes = s4_toacodec_routes, + .num_dapm_routes = ARRAY_SIZE(s4_toacodec_routes), + .endianness = 1, +}; + static const struct regmap_config g12a_toacodec_regmap_cfg = { .reg_bits = 32, .val_bits = 32, @@ -276,6 +329,13 @@ static const struct g12a_toacodec_match_data sm1_toacodec_match_data = { .field_bclk_sel = REG_FIELD(TOACODEC_CTRL0, 4, 6), }; +static const struct g12a_toacodec_match_data s4_toacodec_match_data = { + .component_drv = &s4_toacodec_component_drv, + .field_dat_sel = REG_FIELD(TOACODEC_CTRL0, 19, 20), + .field_lrclk_sel = REG_FIELD(TOACODEC_CTRL0, 12, 14), + .field_bclk_sel = REG_FIELD(TOACODEC_CTRL0, 4, 6), +}; + static const struct of_device_id g12a_toacodec_of_match[] = { { .compatible = "amlogic,g12a-toacodec", @@ -285,6 +345,10 @@ static const struct of_device_id g12a_toacodec_of_match[] = { .compatible = "amlogic,sm1-toacodec", .data = &sm1_toacodec_match_data, }, + { + .compatible = "amlogic,s4-toacodec", + .data = &s4_toacodec_match_data, + }, {} }; MODULE_DEVICE_TABLE(of, g12a_toacodec_of_match); From d8e27d04274746093f8d5a4e909efd9885262166 Mon Sep 17 00:00:00 2001 From: Rosen Penev Date: Wed, 25 Nov 2026 16:13:23 -0800 Subject: [PATCH 1956/2102] gpio: mvebu: fix Armada XP per-CPU mask register save/restore The Armada XP variant keeps the per-CPU edge/level mask registers in a second I/O window (percpu_regs) rather than in the main GPIO window. The suspend and resume paths however read and wrote them through mvchip->regs with the per-CPU offsets, which hits unrelated registers in the main window (including the global GPIO_EDGE_MASK / GPIO_LEVEL_MASK registers) instead. The per-CPU mask state was therefore never saved or restored, so interrupts the kernel had unmasked could stay masked after resume, while the main window was written with per-CPU mask values. Use mvchip->percpu_regs for the Armada XP per-CPU mask registers in both the suspend save and the resume restore paths, matching the mask/unmask handlers and the probe-time masking. Fixes: b5b7b487431b ("gpio: mvebu: add suspend/resume support") Cc: stable@vger.kernel.org Signed-off-by: Rosen Penev Reviewed-by: Linus Walleij Link: https://patch.msgid.link/20261126001323.583722-1-rosenp@gmail.com Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpio-mvebu.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/gpio/gpio-mvebu.c b/drivers/gpio/gpio-mvebu.c index 1e30f23a5317ee..6c2bcc5d749cc7 100644 --- a/drivers/gpio/gpio-mvebu.c +++ b/drivers/gpio/gpio-mvebu.c @@ -1030,10 +1030,10 @@ static int mvebu_gpio_suspend(struct platform_device *pdev, pm_message_t state) break; case MVEBU_GPIO_SOC_VARIANT_ARMADAXP: for (i = 0; i < 4; i++) { - regmap_read(mvchip->regs, + regmap_read(mvchip->percpu_regs, GPIO_EDGE_MASK_ARMADAXP_OFF(i), &mvchip->edge_mask_regs[i]); - regmap_read(mvchip->regs, + regmap_read(mvchip->percpu_regs, GPIO_LEVEL_MASK_ARMADAXP_OFF(i), &mvchip->level_mask_regs[i]); } @@ -1103,10 +1103,10 @@ static int mvebu_gpio_resume(struct platform_device *pdev) break; case MVEBU_GPIO_SOC_VARIANT_ARMADAXP: for (i = 0; i < 4; i++) { - regmap_write(mvchip->regs, + regmap_write(mvchip->percpu_regs, GPIO_EDGE_MASK_ARMADAXP_OFF(i), mvchip->edge_mask_regs[i] & edge_cache); - regmap_write(mvchip->regs, + regmap_write(mvchip->percpu_regs, GPIO_LEVEL_MASK_ARMADAXP_OFF(i), mvchip->level_mask_regs[i] & level_cache); } From b4378764a58960a016a42506992eac86d4d4eaf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alen=20Ti=C5=A1ljar?= Date: Tue, 24 Nov 2026 19:23:29 +0100 Subject: [PATCH 1957/2102] ASoC: amd: yc: Add DMI quirk for HP 255R G10 (board 8D22) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The HP 255R 15.6 inch G10 Notebook PC (board 8D22, Ryzen 7 7735U) has an internal DMIC connected to the ACP6x. Without a quirk entry the acp6x machine driver doesn't register a card and the internal microphone doesn't work. Add a DMI entry for the board to enable it. Signed-off-by: Alen Tišljar Reviewed-by: Vijendar Mukunda Link: https://patch.msgid.link/20261124182329.20428-1-alen.tisljar@gmail.com Signed-off-by: Mark Brown --- sound/soc/amd/yc/acp6x-mach.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/sound/soc/amd/yc/acp6x-mach.c b/sound/soc/amd/yc/acp6x-mach.c index 3e4626b968fa5f..e7ca9d6f85bea4 100644 --- a/sound/soc/amd/yc/acp6x-mach.c +++ b/sound/soc/amd/yc/acp6x-mach.c @@ -739,6 +739,13 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { DMI_MATCH(DMI_BOARD_NAME, "8A22"), } }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "HP"), + DMI_MATCH(DMI_BOARD_NAME, "8D22"), + } + }, { .driver_data = &acp6x_card, .matches = { From f29b683543cca614be3c9d5d02a0034c7617f60a Mon Sep 17 00:00:00 2001 From: Srinivas Kandagatla Date: Thu, 26 Nov 2026 11:57:37 +0000 Subject: [PATCH 1958/2102] ASoC: qcom: q6asm: fix 24-bit PCM level via media format V4/V5 q6asm uses ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2 for every LINEAR_PCM stream. V2 has no sample_word_size, so the DSP defaults to word_size = 32 and expects the 24-bit sample MSB-justified, while ALSA S24_LE is LSB-justified. The 8-bit shift costs ~48 dB. Switch to V4 or V5. Pick V5 when ac->q6asm->ainfo.api_version >= 2, V4 otherwise. Both carry sample_word_size; mode stays 0 so the DSP picks the default Q factor. Apply on playback (q6asm_media_format_block_multi_ch_pcm, q6asm_open_write) and capture (q6asm_enc_cfg_blk_pcm_format_support, __q6asm_open_read). Drop S24_LE from the MultiMedia FE PCM. Advertise S24_3LE on capture, S24_3LE and S32_LE on playback. S24_LE can't be made to work zero-copy: the firmware ignores the Q-factor override. plughw converts S24_LE to S24_3LE transparently. Signed-off-by: Srinivas Kandagatla Fixes: 68fd8480bb7b ("ASoC: qdsp6: q6asm: Add support to audio stream apis") Fixes: 2a9e92d371db ("ASoC: qdsp6: q6asm: Add q6asm dai driver") Link: https://patch.msgid.link/20261126115738.1765949-2-srinivas.kandagatla@oss.qualcomm.com Signed-off-by: Mark Brown --- sound/soc/qcom/qdsp6/q6asm-dai.c | 26 +++-- sound/soc/qcom/qdsp6/q6asm.c | 184 ++++++++++++++++++++++++++----- sound/soc/qcom/qdsp6/q6asm.h | 6 +- 3 files changed, 178 insertions(+), 38 deletions(-) diff --git a/sound/soc/qcom/qdsp6/q6asm-dai.c b/sound/soc/qcom/qdsp6/q6asm-dai.c index 3840669867351a..57cbce2bb0cb71 100644 --- a/sound/soc/qcom/qdsp6/q6asm-dai.c +++ b/sound/soc/qcom/qdsp6/q6asm-dai.c @@ -63,6 +63,7 @@ struct q6asm_dai_rtd { uint64_t bytes_received; uint64_t copied_total; uint16_t bits_per_sample; + uint16_t sample_word_size; snd_pcm_uframes_t queue_ptr; uint16_t source; /* Encoding source bit mask */ struct audio_client *audio_client; @@ -90,7 +91,7 @@ static const struct snd_pcm_hardware q6asm_dai_hardware_capture = { SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME), .formats = (SNDRV_PCM_FMTBIT_S16_LE | - SNDRV_PCM_FMTBIT_S24_LE), + SNDRV_PCM_FMTBIT_S24_3LE), .rates = SNDRV_PCM_RATE_8000_48000, .rate_min = 8000, .rate_max = 48000, @@ -113,7 +114,8 @@ static const struct snd_pcm_hardware q6asm_dai_hardware_playback = { SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME), .formats = (SNDRV_PCM_FMTBIT_S16_LE | - SNDRV_PCM_FMTBIT_S24_LE), + SNDRV_PCM_FMTBIT_S24_3LE | + SNDRV_PCM_FMTBIT_S32_LE), .rates = SNDRV_PCM_RATE_8000_192000, .rate_min = 8000, .rate_max = 192000, @@ -139,7 +141,8 @@ static const struct snd_pcm_hardware q6asm_dai_hardware_playback = { SNDRV_PCM_RATE_176400 | \ SNDRV_PCM_RATE_192000), \ .formats = (SNDRV_PCM_FMTBIT_S16_LE | \ - SNDRV_PCM_FMTBIT_S24_LE), \ + SNDRV_PCM_FMTBIT_S24_3LE | \ + SNDRV_PCM_FMTBIT_S32_LE), \ .channels_min = 1, \ .channels_max = 8, \ .rate_min = 8000, \ @@ -151,7 +154,7 @@ static const struct snd_pcm_hardware q6asm_dai_hardware_playback = { SNDRV_PCM_RATE_12000 | \ SNDRV_PCM_RATE_24000), \ .formats = (SNDRV_PCM_FMTBIT_S16_LE | \ - SNDRV_PCM_FMTBIT_S24_LE), \ + SNDRV_PCM_FMTBIT_S24_3LE), \ .channels_min = 1, \ .channels_max = 4, \ .rate_min = 8000, \ @@ -284,13 +287,15 @@ static int q6asm_dai_prepare(struct snd_soc_component *component, ret = q6asm_media_format_block_multi_ch_pcm( prtd->audio_client, prtd->stream_id, runtime->rate, runtime->channels, NULL, - prtd->bits_per_sample); + prtd->bits_per_sample, + prtd->sample_word_size); } else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { ret = q6asm_enc_cfg_blk_pcm_format_support(prtd->audio_client, prtd->stream_id, runtime->rate, runtime->channels, - prtd->bits_per_sample); + prtd->bits_per_sample, + prtd->sample_word_size); /* Queue the buffers */ for (i = 0; i < runtime->periods; i++) @@ -507,9 +512,16 @@ static int q6asm_dai_hw_params(struct snd_soc_component *component, switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: prtd->bits_per_sample = 16; + prtd->sample_word_size = 16; break; - case SNDRV_PCM_FORMAT_S24_LE: + case SNDRV_PCM_FORMAT_S24_3LE: + /* 24-bit samples packed in three bytes, no padding */ prtd->bits_per_sample = 24; + prtd->sample_word_size = 24; + break; + case SNDRV_PCM_FORMAT_S32_LE: + prtd->bits_per_sample = 32; + prtd->sample_word_size = 32; break; } diff --git a/sound/soc/qcom/qdsp6/q6asm.c b/sound/soc/qcom/qdsp6/q6asm.c index d042132caf0343..ee1930e41d4b63 100644 --- a/sound/soc/qcom/qdsp6/q6asm.c +++ b/sound/soc/qcom/qdsp6/q6asm.c @@ -40,6 +40,10 @@ #define ASM_PARAM_ID_ENCDEC_ENC_CFG_BLK_V2 0x00010DA3 #define ASM_SESSION_CMD_RUN_V2 0x00010DAA #define ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2 0x00010DA5 +#define ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V4 0x0001320C +#define ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V5 0x00013222 +/* ADSP ASM service API version at which the V5 PCM media format is supported */ +#define ADSP_ASM_API_VERSION_V2 2 #define ASM_MEDIA_FMT_MP3 0x00010BE9 #define ASM_MEDIA_FMT_FLAC 0x00010C16 #define ASM_MEDIA_FMT_WMA_V9 0x00010DA8 @@ -99,6 +103,31 @@ struct asm_multi_channel_pcm_fmt_blk_v2 { u8 channel_mapping[PCM_MAX_NUM_CHANNEL]; } __packed; +/* Note: in V4 the channel map precedes endianness/mode (unlike V5) */ +struct asm_multi_channel_pcm_fmt_blk_v4 { + struct asm_data_cmd_media_fmt_update_v2 fmt_blk; + u16 num_channels; + u16 bits_per_sample; + u32 sample_rate; + u16 is_signed; + u16 sample_word_size; + u8 channel_mapping[PCM_MAX_NUM_CHANNEL]; + u16 endianness; /* 0: little endian */ + u16 mode; /* 0: default Q factors */ +} __packed; + +struct asm_multi_channel_pcm_fmt_blk_v5 { + struct asm_data_cmd_media_fmt_update_v2 fmt_blk; + u16 num_channels; + u16 bits_per_sample; + u32 sample_rate; + u16 is_signed; + u16 sample_word_size; + u16 endianness; /* 0: little endian */ + u16 mode; /* 0: default Q factors */ + u8 channel_mapping[PCM_MAX_NUM_CHANNEL]; +} __packed; + struct asm_flac_fmt_blk_v2 { struct asm_data_cmd_media_fmt_update_v2 fmt_blk; u16 is_stream_info_present; @@ -191,6 +220,33 @@ struct asm_multi_channel_pcm_enc_cfg_v2 { uint8_t channel_mapping[8]; } __packed; +/* Note: in V4 the channel map precedes endianness/mode (unlike V5) */ +struct asm_multi_channel_pcm_enc_cfg_v4 { + struct asm_stream_cmd_set_encdec_param encdec; + struct asm_enc_cfg_blk_param_v2 encblk; + u16 num_channels; + u16 bits_per_sample; + u32 sample_rate; + u16 is_signed; + u16 sample_word_size; + u8 channel_mapping[PCM_MAX_NUM_CHANNEL]; + u16 endianness; /* 0: little endian */ + u16 mode; /* 0: default Q factors */ +} __packed; + +struct asm_multi_channel_pcm_enc_cfg_v5 { + struct asm_stream_cmd_set_encdec_param encdec; + struct asm_enc_cfg_blk_param_v2 encblk; + u16 num_channels; + u16 bits_per_sample; + u32 sample_rate; + u16 is_signed; + u16 sample_word_size; + u16 endianness; /* 0: little endian */ + u16 mode; /* 0: default Q factors */ + u8 channel_mapping[PCM_MAX_NUM_CHANNEL]; +} __packed; + struct asm_data_cmd_read_v2 { u32 buf_addr_lsw; u32 buf_addr_msw; @@ -912,6 +968,19 @@ static int q6asm_ac_send_cmd_sync(struct audio_client *ac, struct apr_pkt *pkt) return rc; } +/* + * Both the V4 and V5 multichannel PCM media formats carry the sample word size + * needed to describe e.g. 24-bit samples held in a 32-bit word. V5 is only + * understood by newer ADSP firmware (ASM API version >= 2); everything else - + * including when the version query is unsupported and ainfo is left zeroed - + * uses V4, which the QDSP6 firmware has supported since its introduction. (The + * old V2 format, which lacks the word size, is no longer used for playback.) + */ +static bool q6asm_pcm_fmt_v5_supported(struct audio_client *ac) +{ + return ac->q6asm->ainfo.api_version >= ADSP_ASM_API_VERSION_V2; +} + /** * q6asm_open_write() - Open audio client for writing * @ac: audio client pointer @@ -955,7 +1024,9 @@ int q6asm_open_write(struct audio_client *ac, uint32_t stream_id, open->dec_fmt_id = ASM_MEDIA_FMT_MP3; break; case FORMAT_LINEAR_PCM: - open->dec_fmt_id = ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2; + open->dec_fmt_id = q6asm_pcm_fmt_v5_supported(ac) ? + ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V5 : + ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V4; break; case SND_AUDIOCODEC_FLAC: open->dec_fmt_id = ASM_MEDIA_FMT_FLAC; @@ -1078,6 +1149,7 @@ EXPORT_SYMBOL_GPL(q6asm_run_nowait); * @channels: number of audio channels. * @channel_map: channel map pointer * @bits_per_sample: bits per sample + * @sample_word_size: size in bits of the word that holds a sample of a channel * * Return: Will be an negative value on error or zero on success */ @@ -1085,30 +1157,60 @@ int q6asm_media_format_block_multi_ch_pcm(struct audio_client *ac, uint32_t stream_id, uint32_t rate, uint32_t channels, u8 channel_map[PCM_MAX_NUM_CHANNEL], - uint16_t bits_per_sample) + uint16_t bits_per_sample, + uint16_t sample_word_size) { - struct asm_multi_channel_pcm_fmt_blk_v2 *fmt; + bool use_v5 = q6asm_pcm_fmt_v5_supported(ac); + struct asm_multi_channel_pcm_fmt_blk_v5 *fmt_v5; + struct asm_multi_channel_pcm_fmt_blk_v4 *fmt_v4; struct apr_pkt *pkt; u8 *channel_mapping; - int pkt_size = APR_HDR_SIZE + sizeof(*fmt); + int pkt_size = APR_HDR_SIZE + + (use_v5 ? sizeof(*fmt_v5) : sizeof(*fmt_v4)); void *p __free(kfree) = kzalloc(pkt_size, GFP_KERNEL); if (!p) return -ENOMEM; pkt = p; - fmt = p + APR_HDR_SIZE; q6asm_add_hdr(ac, &pkt->hdr, pkt_size, true, stream_id); - pkt->hdr.opcode = ASM_DATA_CMD_MEDIA_FMT_UPDATE_V2; - fmt->fmt_blk.fmt_blk_size = sizeof(*fmt) - sizeof(fmt->fmt_blk); - fmt->num_channels = channels; - fmt->bits_per_sample = bits_per_sample; - fmt->sample_rate = rate; - fmt->is_signed = 1; - channel_mapping = fmt->channel_mapping; + dev_dbg(ac->dev, "%s: fmt=%s rate=%u ch=%u bps=%u word=%u (asm api %u)\n", + __func__, use_v5 ? "V5" : "V4", rate, channels, + bits_per_sample, sample_word_size, ac->q6asm->ainfo.api_version); + + /* + * Leave mode=0 (default Q factors). Per the ADSP ABI the defaults + * are Q15 for 16-bit, Q23 for 24-bit packed (word_size=24), and Q31 + * for 32-bit, which match every format we advertise to userspace. + * The explicit override values (15/23/31) are not honoured by every + * firmware; the default path is the safe choice. + */ + if (use_v5) { + fmt_v5 = p + APR_HDR_SIZE; + fmt_v5->fmt_blk.fmt_blk_size = sizeof(*fmt_v5) - + sizeof(fmt_v5->fmt_blk); + fmt_v5->num_channels = channels; + fmt_v5->bits_per_sample = bits_per_sample; + fmt_v5->sample_rate = rate; + fmt_v5->is_signed = 1; + fmt_v5->sample_word_size = sample_word_size; + fmt_v5->mode = 0; /* default Q-factor per bps/word_size */ + channel_mapping = fmt_v5->channel_mapping; + } else { + fmt_v4 = p + APR_HDR_SIZE; + fmt_v4->fmt_blk.fmt_blk_size = sizeof(*fmt_v4) - + sizeof(fmt_v4->fmt_blk); + fmt_v4->num_channels = channels; + fmt_v4->bits_per_sample = bits_per_sample; + fmt_v4->sample_rate = rate; + fmt_v4->is_signed = 1; + fmt_v4->sample_word_size = sample_word_size; + fmt_v4->mode = 0; /* default Q-factor per bps/word_size */ + channel_mapping = fmt_v4->channel_mapping; + } if (channel_map) { memcpy(channel_mapping, channel_map, PCM_MAX_NUM_CHANNEL); @@ -1347,40 +1449,62 @@ EXPORT_SYMBOL_GPL(q6asm_stream_remove_trailing_silence); * @rate: audio sample rate * @channels: number of audio channels. * @bits_per_sample: bits per sample + * @sample_word_size: size in bits of the word that holds a sample of a channel * * Return: Will be an negative value on error or zero on success */ int q6asm_enc_cfg_blk_pcm_format_support(struct audio_client *ac, uint32_t stream_id, uint32_t rate, uint32_t channels, - uint16_t bits_per_sample) + uint16_t bits_per_sample, + uint16_t sample_word_size) { - struct asm_multi_channel_pcm_enc_cfg_v2 *enc_cfg; + bool use_v5 = q6asm_pcm_fmt_v5_supported(ac); + struct asm_multi_channel_pcm_enc_cfg_v5 *enc_v5; + struct asm_multi_channel_pcm_enc_cfg_v4 *enc_v4; struct apr_pkt *pkt; u8 *channel_mapping; u32 frames_per_buf = 0; - int pkt_size = APR_HDR_SIZE + sizeof(*enc_cfg); + int pkt_size = APR_HDR_SIZE + + (use_v5 ? sizeof(*enc_v5) : sizeof(*enc_v4)); void *p __free(kfree) = kzalloc(pkt_size, GFP_KERNEL); if (!p) return -ENOMEM; pkt = p; - enc_cfg = p + APR_HDR_SIZE; q6asm_add_hdr(ac, &pkt->hdr, pkt_size, true, stream_id); - pkt->hdr.opcode = ASM_STREAM_CMD_SET_ENCDEC_PARAM; - enc_cfg->encdec.param_id = ASM_PARAM_ID_ENCDEC_ENC_CFG_BLK_V2; - enc_cfg->encdec.param_size = sizeof(*enc_cfg) - sizeof(enc_cfg->encdec); - enc_cfg->encblk.frames_per_buf = frames_per_buf; - enc_cfg->encblk.enc_cfg_blk_size = enc_cfg->encdec.param_size - - sizeof(struct asm_enc_cfg_blk_param_v2); - - enc_cfg->num_channels = channels; - enc_cfg->bits_per_sample = bits_per_sample; - enc_cfg->sample_rate = rate; - enc_cfg->is_signed = 1; - channel_mapping = enc_cfg->channel_mapping; + + if (use_v5) { + enc_v5 = p + APR_HDR_SIZE; + enc_v5->encdec.param_id = ASM_PARAM_ID_ENCDEC_ENC_CFG_BLK_V2; + enc_v5->encdec.param_size = sizeof(*enc_v5) - + sizeof(enc_v5->encdec); + enc_v5->encblk.frames_per_buf = frames_per_buf; + enc_v5->encblk.enc_cfg_blk_size = enc_v5->encdec.param_size - + sizeof(struct asm_enc_cfg_blk_param_v2); + enc_v5->num_channels = channels; + enc_v5->bits_per_sample = bits_per_sample; + enc_v5->sample_rate = rate; + enc_v5->is_signed = 1; + enc_v5->sample_word_size = sample_word_size; + channel_mapping = enc_v5->channel_mapping; + } else { + enc_v4 = p + APR_HDR_SIZE; + enc_v4->encdec.param_id = ASM_PARAM_ID_ENCDEC_ENC_CFG_BLK_V2; + enc_v4->encdec.param_size = sizeof(*enc_v4) - + sizeof(enc_v4->encdec); + enc_v4->encblk.frames_per_buf = frames_per_buf; + enc_v4->encblk.enc_cfg_blk_size = enc_v4->encdec.param_size - + sizeof(struct asm_enc_cfg_blk_param_v2); + enc_v4->num_channels = channels; + enc_v4->bits_per_sample = bits_per_sample; + enc_v4->sample_rate = rate; + enc_v4->is_signed = 1; + enc_v4->sample_word_size = sample_word_size; + channel_mapping = enc_v4->channel_mapping; + } if (q6dsp_map_channels(channel_mapping, channels)) return -EINVAL; @@ -1473,7 +1597,9 @@ static int __q6asm_open_read(struct audio_client *ac, uint32_t stream_id, switch (format) { case FORMAT_LINEAR_PCM: open->mode_flags |= 0x00; - open->enc_cfg_id = ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2; + open->enc_cfg_id = q6asm_pcm_fmt_v5_supported(ac) ? + ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V5 : + ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V4; break; default: pr_err("Invalid format[%d]\n", format); diff --git a/sound/soc/qcom/qdsp6/q6asm.h b/sound/soc/qcom/qdsp6/q6asm.h index 6fafda5bd8498e..2d969dbffcffce 100644 --- a/sound/soc/qcom/qdsp6/q6asm.h +++ b/sound/soc/qcom/qdsp6/q6asm.h @@ -106,7 +106,8 @@ int q6asm_open_read(struct audio_client *ac, uint32_t stream_id, int q6asm_enc_cfg_blk_pcm_format_support(struct audio_client *ac, uint32_t stream_id, uint32_t rate, uint32_t channels, - uint16_t bits_per_sample); + uint16_t bits_per_sample, + uint16_t sample_word_size); int q6asm_read(struct audio_client *ac, uint32_t stream_id); @@ -114,7 +115,8 @@ int q6asm_media_format_block_multi_ch_pcm(struct audio_client *ac, uint32_t stream_id, uint32_t rate, uint32_t channels, u8 channel_map[PCM_MAX_NUM_CHANNEL], - uint16_t bits_per_sample); + uint16_t bits_per_sample, + uint16_t sample_word_size); int q6asm_stream_media_format_block_flac(struct audio_client *ac, uint32_t stream_id, struct q6asm_flac_cfg *cfg); From e03e85ff75004587a5cf516b155f5b9cb2275e90 Mon Sep 17 00:00:00 2001 From: Srinivas Kandagatla Date: Thu, 26 Nov 2026 11:57:38 +0000 Subject: [PATCH 1959/2102] ASoC: qcom: q6dsp: add S24_LE and S32_LE to MI2S playback DAIs The DSP supports 24 and 32-bit samples on the MI2S ports. However, the Primary through Quinary MI2S playback DAIs only list S16_LE, except Primary, which also lists S24_LE. This stops the machine driver from running these backends with 32-bit slots, which some I2S sinks need, like the ANX7625 DP bridge. Add S24_LE and S32_LE to these DAIs. That matches the Senary and LPI MI2S DAIs. Also have q6routing pass 32 bits per sample to the ADM for S32_LE. Without that, the session would keep the default 16 bits. [riccardo: rebase onto the reworked lpass-ports, fix indentation, add commit description] Signed-off-by: Srinivas Kandagatla Signed-off-by: Riccardo Mereu Fixes: 68fd8480bb7b ("ASoC: qdsp6: q6asm: Add support to audio stream apis") Fixes: 2a9e92d371db ("ASoC: qdsp6: q6asm: Add q6asm dai driver") Link: https://patch.msgid.link/20261126115738.1765949-3-srinivas.kandagatla@oss.qualcomm.com Signed-off-by: Mark Brown --- sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c | 19 ++++++++++++++----- sound/soc/qcom/qdsp6/q6routing.c | 3 +++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c index f422346a50c694..49902abf8d2d1c 100644 --- a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c +++ b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c @@ -389,7 +389,8 @@ static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = { .rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, .formats = SNDRV_PCM_FMTBIT_S16_LE | - SNDRV_PCM_FMTBIT_S24_LE, + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE, .channels_min = 1, .channels_max = 8, .rate_min = 8000, @@ -416,7 +417,9 @@ static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = { .stream_name = "Secondary MI2S Playback", .rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, - .formats = SNDRV_PCM_FMTBIT_S16_LE, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE, .channels_min = 1, .channels_max = 8, .rate_min = 8000, @@ -443,7 +446,9 @@ static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = { .stream_name = "Tertiary MI2S Playback", .rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, - .formats = SNDRV_PCM_FMTBIT_S16_LE, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE, .channels_min = 1, .channels_max = 8, .rate_min = 8000, @@ -470,7 +475,9 @@ static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = { .stream_name = "Quaternary MI2S Playback", .rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, - .formats = SNDRV_PCM_FMTBIT_S16_LE, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE, .channels_min = 1, .channels_max = 8, .rate_min = 8000, @@ -498,7 +505,9 @@ static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = { .rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_192000, - .formats = SNDRV_PCM_FMTBIT_S16_LE, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE, .channels_min = 1, .channels_max = 8, .rate_min = 8000, diff --git a/sound/soc/qcom/qdsp6/q6routing.c b/sound/soc/qcom/qdsp6/q6routing.c index 0a55d1f384d4d8..5e532b8336dfe7 100644 --- a/sound/soc/qcom/qdsp6/q6routing.c +++ b/sound/soc/qcom/qdsp6/q6routing.c @@ -1170,6 +1170,9 @@ static int routing_hw_params(struct snd_soc_component *component, case SNDRV_PCM_FORMAT_S24_LE: session->bits_per_sample = 24; break; + case SNDRV_PCM_FORMAT_S32_LE: + session->bits_per_sample = 32; + break; default: break; } From 40fddc398878c2cf661b7f16d783bfc5b0000642 Mon Sep 17 00:00:00 2001 From: Breno Leitao Date: Mon, 10 Aug 2026 04:46:45 -0700 Subject: [PATCH 1960/2102] sched/topology: Don't claim sched_domain_shared twice on the same domain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit build_sched_domains() lets the asymmetric capacity path claim a sched_domain_shared object on the lowest SD_ASYM_CPUCAPACITY_FULL ancestor, and then unconditionally claims one for the topmost SD_SHARE_LLC domain. When those are the same sched_domain - a system whose single LLC spans CPUs of differing capacity, for example an arm64 machine with one MC domain covering every CPU - init_sched_domain_shared() runs twice on that domain. The second call overwrites sd->shared without dropping the reference the first call took, so the asym blob ends up with a refcount equal to the CPU count and nothing pointing at it. claim_allocations() sees the non-zero refcount and clears the per-CPU slot, so __sds_free() does not reclaim it either, and the object leaks. kmemleak reports one 32-byte object per build_sched_domains() call: unreferenced object 0xffff0000c02432a0 (size 32): comm "swapper/0", pid 1, jiffies 4294667436 hex dump (first 32 bytes): 08 00 00 00 08 00 00 00 00 00 00 00 20 00 00 00 ............ ... 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ backtrace (crc f4478cb7): kmemleak_alloc+0x44/0xd8 __kmalloc_cache_node_noprof+0x344/0x5d0 build_sched_domains+0x2f8/0x2110 sched_init_domains+0xec/0x160 sched_init_smp+0x48/0x108 kernel_init_freeable+0x1cc/0x2b8 ref and nr_busy_cpus are both the online CPU count and alloc_flags is 0x20, SD_ASYM_CPUCAPACITY, identifying it as the blob the asym path claimed. Only claim a shared object for the LLC domain when the domain does not already have one. sd_init() zero initialises sd->shared for every domain it builds, so a non-NULL sd->shared here means the asym path already claimed this very domain. Cache aware scheduling still finds a shared object on sd_llc, the same one, covering the same span. Reproduced under QEMU/virtme-ng on arm64 with two capacity tiers (capacity-dmips-mhz 0x400 on cpu0-3 and 0x200 on cpu4-7), where the MC domain spans all CPUs and carries both SD_SHARE_LLC and SD_ASYM_CPUCAPACITY_FULL. Leaked sched_domain_shared objects reported by kmemleak, with a kmemleak-test module loaded as a positive control: before after after boot 1 0 after 12 rebuilds via CPU hotplug 13 0 That is exactly one leak per build_sched_domains(), and none once the domain is only claimed once. Fixes: 9e005ed21152 ("sched/topology: Allow multiple domains to claim sched_domain_shared") Signed-off-by: Breno Leitao Signed-off-by: Peter Zijlstra (Intel) Tested-by: André Draszik Link: https://patch.msgid.link/20260810-b4-sched_shared_leak-v1-1-3eacd249d0a3@debian.org --- kernel/sched/topology.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/kernel/sched/topology.c b/kernel/sched/topology.c index 9d3a1b8dd39349..2e355a658dfc63 100644 --- a/kernel/sched/topology.c +++ b/kernel/sched/topology.c @@ -3187,7 +3187,13 @@ build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *att sd = sd->parent; if (sd->flags & SD_SHARE_LLC) { - init_sched_domain_shared(&d, sd, SD_SHARE_LLC); + /* + * The asym path above may have claimed a shared object + * on this very domain; claiming it again overwrites + * sd->shared and leaks the first reference. + */ + if (!sd->shared) + init_sched_domain_shared(&d, sd, SD_SHARE_LLC); /* * In presence of higher domains, adjust the From 50529c05b08bd1aa726474c2f55301a48138d425 Mon Sep 17 00:00:00 2001 From: Shengjiu Wang Date: Thu, 26 Nov 2026 18:25:27 +0800 Subject: [PATCH 1961/2102] ASoC: SOF: imx8: Switch imx8ulp DSP control to reset framework Replace direct syscon regmap accesses for i.MX8ULP DSP reset control with the standard kernel reset controller framework. Use named reset controls: runstall to stall and unstall the DSP core, softreset to reset the DSP core, and dbgreset to control the DSP debug logic. Remove the direct DSP clock-gate writes; the corresponding SIM_LPAV clocks are managed through the common SOF clock handling. Signed-off-by: Shengjiu Wang Reviewed-by: Daniel Baluta Link: https://patch.msgid.link/20261126102528.1531824-1-shengjiu.wang@oss.nxp.com Signed-off-by: Mark Brown --- sound/soc/sof/imx/imx8.c | 72 +++++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 35 deletions(-) diff --git a/sound/soc/sof/imx/imx8.c b/sound/soc/sof/imx/imx8.c index 5cd3f44c90d2bb..80326d2eb1fc04 100644 --- a/sound/soc/sof/imx/imx8.c +++ b/sound/soc/sof/imx/imx8.c @@ -26,19 +26,18 @@ /* imx8ulp macros */ #define FSL_SIP_HIFI_XRDC 0xc200000e -#define SYSCTRL0 0x8 -#define EXECUTE_BIT BIT(13) -#define RESET_BIT BIT(16) -#define HIFI4_CLK_BIT BIT(17) -#define PB_CLK_BIT BIT(18) -#define PLAT_CLK_BIT BIT(19) -#define DEBUG_LOGIC_BIT BIT(25) struct imx8m_chip_data { void __iomem *dap; struct reset_control *run_stall; }; +struct imx8ulp_chip_data { + struct reset_control *run_stall; + struct reset_control *soft_rst; + struct reset_control *dbg_rst; +}; + static int imx8_shutdown(struct snd_sof_dev *sdev) { int ret; @@ -202,42 +201,31 @@ static int imx8m_probe(struct snd_sof_dev *sdev) static int imx8ulp_run(struct snd_sof_dev *sdev) { - struct regmap *regmap = get_chip_pdata(sdev); + struct imx8ulp_chip_data *chip = get_chip_pdata(sdev); - /* Controls the HiFi4 DSP Reset: 1 in reset, 0 out of reset */ - regmap_update_bits(regmap, SYSCTRL0, RESET_BIT, 0); + reset_control_deassert(chip->soft_rst); - /* Reset HiFi4 DSP Debug logic: 1 debug reset, 0 out of reset*/ - regmap_update_bits(regmap, SYSCTRL0, DEBUG_LOGIC_BIT, 0); + /* Release HiFi4 DSP Debug logic */ + reset_control_deassert(chip->dbg_rst); - /* Stall HIFI4 DSP Execution: 1 stall, 0 run */ - regmap_update_bits(regmap, SYSCTRL0, EXECUTE_BIT, 0); + /* Run HIFI4 DSP Execution */ + reset_control_deassert(chip->run_stall); return 0; } static int imx8ulp_reset(struct snd_sof_dev *sdev) { + struct imx8ulp_chip_data *chip = get_chip_pdata(sdev); struct arm_smccc_res smc_res; - struct regmap *regmap; - - regmap = get_chip_pdata(sdev); - - /* HiFi4 Platform Clock Enable: 1 enabled, 0 disabled */ - regmap_update_bits(regmap, SYSCTRL0, PLAT_CLK_BIT, PLAT_CLK_BIT); - /* HiFi4 PBCLK clock enable: 1 enabled, 0 disabled */ - regmap_update_bits(regmap, SYSCTRL0, PB_CLK_BIT, PB_CLK_BIT); - - /* HiFi4 Clock Enable: 1 enabled, 0 disabled */ - regmap_update_bits(regmap, SYSCTRL0, HIFI4_CLK_BIT, HIFI4_CLK_BIT); - - regmap_update_bits(regmap, SYSCTRL0, RESET_BIT, RESET_BIT); + reset_control_assert(chip->soft_rst); usleep_range(1, 2); - /* Stall HIFI4 DSP Execution: 1 stall, 0 not stall */ - regmap_update_bits(regmap, SYSCTRL0, EXECUTE_BIT, EXECUTE_BIT); + /* Stall HIFI4 DSP Execution: */ + reset_control_assert(chip->run_stall); + usleep_range(1, 2); arm_smccc_smc(FSL_SIP_HIFI_XRDC, 0, 0, 0, 0, 0, 0, 0, &smc_res); @@ -248,16 +236,30 @@ static int imx8ulp_reset(struct snd_sof_dev *sdev) static int imx8ulp_probe(struct snd_sof_dev *sdev) { struct imx_common_data *common; - struct regmap *regmap; + struct imx8ulp_chip_data *chip; + + chip = devm_kzalloc(sdev->dev, sizeof(*chip), GFP_KERNEL); + if (!chip) + return -ENOMEM; common = sdev->pdata->hw_pdata; - regmap = syscon_regmap_lookup_by_phandle(sdev->dev->of_node, "fsl,dsp-ctrl"); - if (IS_ERR(regmap)) - return dev_err_probe(sdev->dev, PTR_ERR(regmap), - "failed to fetch dsp ctrl regmap\n"); + chip->run_stall = devm_reset_control_get_exclusive(sdev->dev, "runstall"); + if (IS_ERR(chip->run_stall)) + return dev_err_probe(sdev->dev, PTR_ERR(chip->run_stall), + "failed to get dsp runstall reset control\n"); + + chip->soft_rst = devm_reset_control_get_optional_exclusive(sdev->dev, "softreset"); + if (IS_ERR(chip->soft_rst)) + return dev_err_probe(sdev->dev, PTR_ERR(chip->soft_rst), + "failed to get dsp softreset reset control\n"); - common->chip_pdata = regmap; + chip->dbg_rst = devm_reset_control_get_optional_exclusive(sdev->dev, "dbgreset"); + if (IS_ERR(chip->dbg_rst)) + return dev_err_probe(sdev->dev, PTR_ERR(chip->dbg_rst), + "failed to get dsp dbgreset reset control\n"); + + common->chip_pdata = chip; return 0; } From fe57062e09bc162be9133695d5f1459c1c0e46c0 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 26 Nov 2026 15:55:24 +0100 Subject: [PATCH 1962/2102] efi/libstub: loongarch: Provide 64-bit integer shift helpers for 32-bit The EFI stub's copy of lib/cmdline.c performs 64-bit shifts in memparse() [which is never actually called from the stub], and so it needs library routines when running on 32-bit CPUs that lack native instructions for this. The LoongArch 32-bit EFI stub build already pulls in the library helpers that are needed for this, but only when CONFIG_EFI_ZBOOT=y, which is not sufficient, given that the same helpers will be needed in the vmlinux build for the builtin copy of the EFI stub. On other architectures, the builtin copy will call vmlinux's versions of those routines, which are exposed to the stub via aliases in the linker script. However, on LoongArch, those are C implementations that may be instrumented and therefore unsuitable for use in the EFI stub. Reported-by: Dmitry Antipov Reported-by: kernel test robot Closes: https://lore.kernel.org/oe-kbuild-all/20261122125352.gAcg5yLx-lkp@intel.com/ Fixes: 3d9aba6618d1 ("LoongArch: Adjust build infrastructure for 32BIT/64BIT") Signed-off-by: Ard Biesheuvel --- drivers/firmware/efi/libstub/Makefile | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/drivers/firmware/efi/libstub/Makefile b/drivers/firmware/efi/libstub/Makefile index bbab12b8eb4b23..ba6c9e7638622a 100644 --- a/drivers/firmware/efi/libstub/Makefile +++ b/drivers/firmware/efi/libstub/Makefile @@ -88,7 +88,9 @@ lib-$(CONFIG_ARM64) += kaslr.o arm64.o arm64-stub.o smbios.o lib-$(CONFIG_X86) += x86-stub.o smbios.o lib-$(CONFIG_X86_64) += x86-5lvl.o lib-$(CONFIG_RISCV) += kaslr.o riscv.o riscv-stub.o -lib-$(CONFIG_LOONGARCH) += loongarch.o loongarch-stub.o +lib-loongarch-$(CONFIG_32BIT) += lib-ashldi3.o lib-lshrdi3.o +lib-$(CONFIG_LOONGARCH) += loongarch.o loongarch-stub.o \ + $(lib-loongarch-y) CFLAGS_arm32-stub.o := -DTEXT_OFFSET=$(TEXT_OFFSET) @@ -99,8 +101,7 @@ CFLAGS_zboot-decompress-zstd.o += -I$(srctree)/lib/zstd zboot-riscv-obj-$(CONFIG_32BIT) := lib-ashldi3.o lib-lshrdi3.o zboot-obj-$(CONFIG_RISCV) += lib-clz_ctz.o $(zboot-riscv-obj-y) -zboot-loongarch-obj-$(CONFIG_32BIT) := lib-ashldi3.o lib-lshrdi3.o -zboot-obj-$(CONFIG_LOONGARCH) += lib-clz_ctz.o $(zboot-loongarch-obj-y) +zboot-obj-$(CONFIG_LOONGARCH) += lib-clz_ctz.o lib-$(CONFIG_EFI_ZBOOT) += zboot.o $(zboot-obj-y) lib-$(CONFIG_UNACCEPTED_MEMORY) += unaccepted_memory.o bitmap.o find.o From ba0084f1402bdf2946282290a3fb0af8f3544759 Mon Sep 17 00:00:00 2001 From: Sechang Lim Date: Thu, 19 Nov 2026 11:59:29 +0000 Subject: [PATCH 1963/2102] io_uring/bpf-ops: validate loop_step before registration A struct_ops map with only ring_fd set leaves loop_step NULL. The struct_ops update path skips a zero program fd, and bpf_ring_ops does not validate the completed value. Without BPF_F_LINK, the update then calls bpf_io_reg(), where io_install_bpf() triggers a kernel warning before returning -EINVAL. With BPF_F_LINK, the warning occurs when the link is created. Validate loop_step before either registration path. Reject an incomplete value with -EINVAL so malformed userspace input cannot trigger the warning. Fixes: 98f37634b12b ("io_uring/bpf-ops: implement bpf ops registration") Signed-off-by: Sechang Lim Reviewed-by: Pavel Begunkov Link: https://patch.msgid.link/20261119115942.3613868-1-rhkrqnwk98@gmail.com Signed-off-by: Jens Axboe --- io_uring/bpf-ops.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/io_uring/bpf-ops.c b/io_uring/bpf-ops.c index 6c2a587fb1bf65..dfa93144b090df 100644 --- a/io_uring/bpf-ops.c +++ b/io_uring/bpf-ops.c @@ -157,6 +157,13 @@ static int bpf_io_check_member(const struct btf_type *t, return 0; } +static int bpf_io_validate(void *kdata) +{ + const struct io_uring_bpf_ops *ops = kdata; + + return ops->loop_step ? 0 : -EINVAL; +} + static int bpf_io_init_member(const struct btf_type *t, const struct btf_member *member, void *kdata, const void *udata) @@ -269,6 +276,7 @@ static struct bpf_struct_ops bpf_ring_ops = { .check_member = bpf_io_check_member, .init_member = bpf_io_init_member, .init = bpf_io_init, + .validate = bpf_io_validate, .cfi_stubs = &io_bpf_ops_stubs, .name = "io_uring_bpf_ops", .owner = THIS_MODULE, From 964d54793da74d0fe3d8f3b5742590f954a21c97 Mon Sep 17 00:00:00 2001 From: Oleg Nesterov Date: Thu, 12 Nov 2026 15:53:53 +0100 Subject: [PATCH 1964/2102] sched/wait: kill leftover bookmark logic in __wake_up_common() The manual list head check and list_for_each_entry_safe_from() in __wake_up_common() are leftovers from commit 2554db916586 ("sched/wait: Break up long wake list walk"). This logic was later removed by commit 37acade0ce89 ("sched: remove wait bookmarks") but the now-unnecessary list hacks were left behind. Signed-off-by: Oleg Nesterov Signed-off-by: Linus Torvalds --- kernel/sched/wait.c | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/kernel/sched/wait.c b/kernel/sched/wait.c index f8d6d8b9d03e66..d0521b54eeb3d2 100644 --- a/kernel/sched/wait.c +++ b/kernel/sched/wait.c @@ -96,12 +96,7 @@ static int __wake_up_common(struct wait_queue_head *wq_head, unsigned int mode, lockdep_assert_held(&wq_head->lock); - curr = list_first_entry(&wq_head->head, wait_queue_entry_t, entry); - - if (&curr->entry == &wq_head->head) - return nr_exclusive; - - list_for_each_entry_safe_from(curr, next, &wq_head->head, entry) { + list_for_each_entry_safe(curr, next, &wq_head->head, entry) { unsigned flags = curr->flags; int ret; From de59f08259545ba089fe7d33ac95f6b4b479abe0 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Mon, 23 Nov 2026 17:33:14 -0800 Subject: [PATCH 1965/2102] sctp: don't let a blocked reader take write-space wakeups sctp_wait_for_packet() waits exclusively on sk_sleep() with the default autoremove wake function, so it accepts any wakeup and consumes it. Then __sctp_write_space() sends EPOLLOUT with a wake-one wakeup: sctp_wait_for_packet() wakes up, finds no data, goes back to sleep, and the walk stops. End result: anybody else queued behind it that was waiting for EPOLLOUT will never see it. Filter on EPOLLIN | EPOLLERR like receiver_wake_function() in net/core/datagram.c. State changes (using sock_def_wakeup()) use an unkeyed wake-all and still get through and will ignore the exclusive nature of sctp_wait_for_packet(). Cc: Oleg Nesterov Cc: Marcelo Ricardo Leitner Cc: Xin Long Cc: Eric Dumazet Cc: Jakub Kicinski Acked-by: Paolo Abeni Signed-off-by: Linus Torvalds --- net/sctp/socket.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/net/sctp/socket.c b/net/sctp/socket.c index bc68af88e27104..85ac4952e9cb68 100644 --- a/net/sctp/socket.c +++ b/net/sctp/socket.c @@ -9070,6 +9070,15 @@ static int sctp_msghdr_parse(const struct msghdr *msg, struct sctp_cmsgs *cmsgs) return 0; } +/* Don't take wakeups for other events, e.g. EPOLLOUT from write space. */ +static int sctp_receiver_wake_function(wait_queue_entry_t *wait, + unsigned int mode, int sync, void *key) +{ + if (key && !(key_to_poll(key) & (EPOLLIN | EPOLLERR))) + return 0; + return autoremove_wake_function(wait, mode, sync, key); +} + /* * Wait for a packet.. * Note: This function is the same function as in core/datagram.c @@ -9078,7 +9087,7 @@ static int sctp_msghdr_parse(const struct msghdr *msg, struct sctp_cmsgs *cmsgs) static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p) { int error; - DEFINE_WAIT(wait); + DEFINE_WAIT_FUNC(wait, sctp_receiver_wake_function); prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); From d8764bc050af2bb6ab4ecd611db15ceb6cdbcc04 Mon Sep 17 00:00:00 2001 From: Srinivas Kandagatla Date: Wed, 25 Nov 2026 17:18:30 +0000 Subject: [PATCH 1966/2102] ASoC: codecs: lpass-rx-macro: handle LPASS_CODEC_VERSION_2_9 LPASS_CODEC_VERSION_2_9 is reported by va-macro on Glymur-class SoCs, but the rx-macro probe path, component probe and read-write register check still fall through to the "Unsupported Codec version" default arm. Version 2.9 is register-layout compatible with 2.8 (and the rest of the 2.5 family), so add it to the same switch arms. Signed-off-by: Srinivas Kandagatla Link: https://patch.msgid.link/20261125171831.1458954-2-srinivas.kandagatla@oss.qualcomm.com Signed-off-by: Mark Brown --- sound/soc/codecs/lpass-rx-macro.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sound/soc/codecs/lpass-rx-macro.c b/sound/soc/codecs/lpass-rx-macro.c index ab8a1c2b0489b8..74ff281293bf93 100644 --- a/sound/soc/codecs/lpass-rx-macro.c +++ b/sound/soc/codecs/lpass-rx-macro.c @@ -1613,6 +1613,7 @@ static bool rx_is_rw_register(struct device *dev, unsigned int reg) case LPASS_CODEC_VERSION_2_6: case LPASS_CODEC_VERSION_2_7: case LPASS_CODEC_VERSION_2_8: + case LPASS_CODEC_VERSION_2_9: return rx_2_5_is_rw_register(dev, reg); default: break; @@ -3652,6 +3653,7 @@ static int rx_macro_component_probe(struct snd_soc_component *component) case LPASS_CODEC_VERSION_2_6: case LPASS_CODEC_VERSION_2_7: case LPASS_CODEC_VERSION_2_8: + case LPASS_CODEC_VERSION_2_9: controls = rx_macro_2_5_snd_controls; num_controls = ARRAY_SIZE(rx_macro_2_5_snd_controls); widgets = rx_macro_2_5_dapm_widgets; @@ -3837,6 +3839,7 @@ static int rx_macro_probe(struct platform_device *pdev) case LPASS_CODEC_VERSION_2_6: case LPASS_CODEC_VERSION_2_7: case LPASS_CODEC_VERSION_2_8: + case LPASS_CODEC_VERSION_2_9: rx->rxn_reg_stride = 0xc0; rx->rxn_reg_stride2 = 0x0; def_count = ARRAY_SIZE(rx_defaults) + ARRAY_SIZE(rx_2_5_defaults); From 9efa4eac7819825dbd28004d0c5b158ec00c93ae Mon Sep 17 00:00:00 2001 From: Srinivas Kandagatla Date: Wed, 25 Nov 2026 17:18:31 +0000 Subject: [PATCH 1967/2102] ASoC: dt-bindings: qcom: Add Glymur LPASS macro codecs Add qcom,glymur-lpass-rx-macro and qcom,glymur-lpass-tx-macro to the compatible enums for lpass-rx-macro and lpass-tx-macro bindings. Signed-off-by: Srinivas Kandagatla Link: https://patch.msgid.link/20261125171831.1458954-3-srinivas.kandagatla@oss.qualcomm.com Signed-off-by: Mark Brown --- Documentation/devicetree/bindings/sound/qcom,lpass-rx-macro.yaml | 1 + Documentation/devicetree/bindings/sound/qcom,lpass-tx-macro.yaml | 1 + 2 files changed, 2 insertions(+) diff --git a/Documentation/devicetree/bindings/sound/qcom,lpass-rx-macro.yaml b/Documentation/devicetree/bindings/sound/qcom,lpass-rx-macro.yaml index 4988e7ed6e34b0..be3e77ab28e2de 100644 --- a/Documentation/devicetree/bindings/sound/qcom,lpass-rx-macro.yaml +++ b/Documentation/devicetree/bindings/sound/qcom,lpass-rx-macro.yaml @@ -22,6 +22,7 @@ properties: - items: - enum: - qcom,eliza-lpass-rx-macro + - qcom,glymur-lpass-rx-macro - qcom,kaanapali-lpass-rx-macro - qcom,sm8650-lpass-rx-macro - qcom,sm8750-lpass-rx-macro diff --git a/Documentation/devicetree/bindings/sound/qcom,lpass-tx-macro.yaml b/Documentation/devicetree/bindings/sound/qcom,lpass-tx-macro.yaml index d8682ff2e82c59..0f35d10c988a38 100644 --- a/Documentation/devicetree/bindings/sound/qcom,lpass-tx-macro.yaml +++ b/Documentation/devicetree/bindings/sound/qcom,lpass-tx-macro.yaml @@ -22,6 +22,7 @@ properties: - items: - enum: - qcom,eliza-lpass-tx-macro + - qcom,glymur-lpass-tx-macro - qcom,kaanapali-lpass-tx-macro - qcom,sm8650-lpass-tx-macro - qcom,sm8750-lpass-tx-macro From 1298a779a3ad921445266e8eb666b7c0d0f7aadf Mon Sep 17 00:00:00 2001 From: Richard Fitzgerald Date: Thu, 26 Nov 2026 15:44:08 +0000 Subject: [PATCH 1968/2102] ASoC: cs35l56: Make SoundWire DP3 mixer registers volatile Mark the CS35L56_SWIRE_DP3_CH*_INPUT registers as volatile so that reading them won't populate the regmap cache with a value that overwrites the register value during a regcache_sync(). These registers are owned by the firmware so the driver must not write to them. Previous commit f52668f474f1 ("ASoC: cs35l56: Remove SDW1 TX source controls and widgets") removed the DAPM widgets so that the driver does not read or write these registers. But it left the possibility that reading the regmap through debugfs would populate the cache value and so unintentionally overwrite them on the next regcache_sync(). Marking them volatile prevents this. Fixes: f52668f474f1 ("ASoC: cs35l56: Remove SDW1 TX source controls and widgets") Signed-off-by: Richard Fitzgerald Link: https://patch.msgid.link/20261126154409.1665214-2-rf@opensource.cirrus.com Signed-off-by: Mark Brown --- sound/soc/codecs/cs35l56-shared.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sound/soc/codecs/cs35l56-shared.c b/sound/soc/codecs/cs35l56-shared.c index 34aebf81f4a442..329351de32b167 100644 --- a/sound/soc/codecs/cs35l56-shared.c +++ b/sound/soc/codecs/cs35l56-shared.c @@ -232,6 +232,10 @@ static bool cs35l56_common_volatile_reg(unsigned int reg) case CS35L56_DACPCM2_INPUT: /* owned by firmware */ case CS35L56_DSP1RX1_INPUT: /* owned by firmware */ case CS35L56_DSP1RX2_INPUT: /* owned by firmware */ + case CS35L56_SWIRE_DP3_CH1_INPUT: /* owned by firmware */ + case CS35L56_SWIRE_DP3_CH2_INPUT: /* owned by firmware */ + case CS35L56_SWIRE_DP3_CH3_INPUT: /* owned by firmware */ + case CS35L56_SWIRE_DP3_CH4_INPUT: /* owned by firmware */ case CS35L56_IRQ1_STATUS: case CS35L56_IRQ1_EINT_1 ... CS35L56_IRQ1_EINT_8: case CS35L56_IRQ1_EINT_18: From 4c17de5c7713778251c253114d1ffb5ac29cd9ff Mon Sep 17 00:00:00 2001 From: Richard Fitzgerald Date: Thu, 26 Nov 2026 15:44:09 +0000 Subject: [PATCH 1969/2102] ASoC: cs35l56-test: Initialize DP3 mixer registers in mock regmap In cs35l56_test_create_mock_device_registers() put dummy values in the simulated CS35L56_SWIRE_DP3_CH*_INPUT registers so that they can be read. This fixes a problem with the cs35l56_test_component_probe_omits_sdw_mux() test. The test aims to prove that component_probe() does not put a value in the regmap cache that will be written out to the registers during a regcache_sync(). But the registers did not have a value in the simulated regmap, so an attempt to read the register would fail instead of populating the cache. Fixes: 406541bbf4eb ("ASoC: cs35l56: Add test that probe() doesn't write SDW mux registers") Signed-off-by: Richard Fitzgerald Link: https://patch.msgid.link/20261126154409.1665214-3-rf@opensource.cirrus.com Signed-off-by: Mark Brown --- sound/soc/codecs/cs35l56-test.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/soc/codecs/cs35l56-test.c b/sound/soc/codecs/cs35l56-test.c index 362da30b949e66..2285076b9d0eba 100644 --- a/sound/soc/codecs/cs35l56-test.c +++ b/sound/soc/codecs/cs35l56-test.c @@ -280,6 +280,7 @@ static void cs35l56_test_create_mock_device_registers(struct kunit *test) cs35l56_test_fill_register_range(test, &cs35l56_test_asp_config_registers_range, 0); cs35l56_test_fill_register_range(test, &cs35l56_test_asp_mixer_registers_range, 0); + cs35l56_test_fill_register_range(test, &cs35l56_test_sdw_mux_registers_range, 0); } /* From 029fd68a263364583b6f9b34d22761acf0a3940c Mon Sep 17 00:00:00 2001 From: Lad Prabhakar Date: Mon, 23 Nov 2026 00:12:13 +0000 Subject: [PATCH 1970/2102] sched/fair: Fix h_nr_runnable leak in dequeue_hierarchy() Commit 486c3d06b902 ("sched/fair: Avoid transient double accounting for delayed tasks") changed the h_nr_runnable logic in dequeue_hierarchy() from "set to 1 unless delayed" to "set to 0 if delayed", but left the initialiser at 0: int h_nr_runnable = 0; ... if (se->sched_delayed) h_nr_runnable = 0; h_nr_runnable is therefore always 0, so dequeuing a task that is not delayed no longer decrements cfs_rq->h_nr_runnable. The count only grows, which inflates se->runnable_weight and skews PELT runnable_avg and load balancing. Initialise h_nr_runnable to 1 so that only delayed tasks, which set_delayed() has already accounted for, skip the decrement. Fixes: 486c3d06b902 ("sched/fair: Avoid transient double accounting for delayed tasks") Closes: https://lore.kernel.org/oe-lkp/202611230853.e2e6401-lkp@intel.com Signed-off-by: Lad Prabhakar Signed-off-by: Peter Zijlstra (Intel) Reviewed-by: K Prateek Nayak Tested-by: Chen Yu Tested-by: Christian Loehle Tested-by: Alexey Charkov Tested-by: Vlad Poenaru Link: https://patch.msgid.link/20261123001213.7609-1-prabhakar.mahadev-lad.rj@bp.renesas.com --- kernel/sched/fair.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index da0d9e19c45772..8a55571b9719dc 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -8242,7 +8242,7 @@ static void dequeue_hierarchy(struct task_struct *p, int flags) { struct sched_entity *se = &p->se; bool task_throttled = flags & DEQUEUE_THROTTLE; - int h_nr_runnable = 0; + int h_nr_runnable = 1; int h_nr_idle = task_has_idle_policy(p); bool dequeue = true; From 61914cb2002ac3d745853d1064350764bd3d6c9b Mon Sep 17 00:00:00 2001 From: Christian Marangi Date: Wed, 25 Nov 2026 00:12:43 +0100 Subject: [PATCH 1971/2102] ASoC: airoha: fix objtool warning with memif probe loop Objtool produce a warning when clang is used as compiler. This was caused by the memif probe loop when assigning the irq to the memif. The warning is: >> sound/soc/mediatek/an7581/snd-soc-an7581-afe.o: warning: objtool: an7581_afe_pcm_dev_probe(): unexpected end of section .text.an7581_afe_pcm_dev_probe Fix this by giving a fixed upper bound for the loop for the memif as it seems there are some problem with detecting the runtime value is hardcoded. Fixes: 4974ffa0d6c2 ("ASoC: airoha: Add AFE driver for Airoha AN7581") Reported-by: kernel test robot Closes: https://lore.kernel.org/oe-kbuild-all/202611201414.1NBNxorL-lkp@intel.com/ Signed-off-by: Christian Marangi Link: https://patch.msgid.link/20261124231245.271869-1-ansuelsmth@gmail.com Signed-off-by: Mark Brown --- sound/soc/mediatek/an7581/an7581-afe-pcm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/mediatek/an7581/an7581-afe-pcm.c b/sound/soc/mediatek/an7581/an7581-afe-pcm.c index 1b12655ab42aa9..21655b0fe29b87 100644 --- a/sound/soc/mediatek/an7581/an7581-afe-pcm.c +++ b/sound/soc/mediatek/an7581/an7581-afe-pcm.c @@ -444,7 +444,7 @@ static int an7581_afe_pcm_dev_probe(struct platform_device *pdev) return irq_id; /* init memif */ - for (i = 0; i < afe->memif_size; i++) { + for (i = 0; i < AN7581_MEMIF_NUM; i++) { int sel_irq = an7581_memif_irq_descs[i].irq; afe->memif[i].data = &memif_data[i]; From 4d5ed6cd0a14fc04c9d852bd0baec4fb3f00ee61 Mon Sep 17 00:00:00 2001 From: Elkin Cruz Date: Fri, 20 Nov 2026 19:22:36 +0000 Subject: [PATCH 1972/2102] ASoC: mediatek: mt8196: clear afe->regmap on devm_regmap_init_mmio() error When devm_regmap_init_mmio() fails in mt8196_afe_pcm_dev_probe(), afe->regmap holds an ERR_PTR() while unwinding through err_pm_put -> pm_runtime_put_sync(), which invokes mt8196_afe_runtime_suspend(). Because mt8196_afe_runtime_suspend() only guards if (!afe->regmap), it passes the error pointer into regcache_cache_only() and crashes. Clear afe->regmap to NULL before jumping to err_pm_put. Fixes: e38353138a09 ("ASoC: mediatek: mt8196: Fix probe resource cleanup") Signed-off-by: Elkin Cruz Link: https://patch.msgid.link/20261120192237.2870582-2-elkin@google.com Signed-off-by: Mark Brown --- sound/soc/mediatek/mt8196/mt8196-afe-pcm.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c b/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c index 638b3672212b05..e12a3cdf0e86bb 100644 --- a/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c +++ b/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c @@ -2442,6 +2442,7 @@ static int mt8196_afe_pcm_dev_probe(struct platform_device *pdev) &mt8196_afe_regmap_config); if (IS_ERR(afe->regmap)) { ret = PTR_ERR(afe->regmap); + afe->regmap = NULL; goto err_pm_put; } From 18246650ab69ed6b275bc963d6ab2d73411ea75d Mon Sep 17 00:00:00 2001 From: Elkin Cruz Date: Fri, 20 Nov 2026 19:22:37 +0000 Subject: [PATCH 1973/2102] ASoC: mediatek: mt8189: clear afe->regmap on devm_regmap_init_mmio() error When devm_regmap_init_mmio() fails in mt8189_afe_pcm_dev_probe(), afe->regmap holds an ERR_PTR() while unwinding through err_pm_put -> pm_runtime_put_sync(), which invokes mt8189_afe_runtime_suspend(). Because mt8189_afe_runtime_suspend() only checks if (!afe->regmap), the ERR_PTR() value is passed to regmap_write() and regcache_cache_only(). Clear afe->regmap to NULL before jumping to err_pm_put. Fixes: 5404599c3292 ("ASoC: mediatek: mt8189: Fix probe resource cleanup") Signed-off-by: Elkin Cruz Link: https://patch.msgid.link/20261120192237.2870582-3-elkin@google.com Signed-off-by: Mark Brown --- sound/soc/mediatek/mt8189/mt8189-afe-pcm.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c b/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c index f39b01590f7145..85b5be6d45ec6e 100644 --- a/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c +++ b/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c @@ -2563,6 +2563,7 @@ static int mt8189_afe_pcm_dev_probe(struct platform_device *pdev) &mt8189_afe_regmap_config); if (IS_ERR(afe->regmap)) { ret = PTR_ERR(afe->regmap); + afe->regmap = NULL; goto err_pm_put; } From da96c8b9ebb256578bee364060bcabb8eb9ee9ab Mon Sep 17 00:00:00 2001 From: Suyuan Wang Date: Sat, 21 Nov 2026 15:26:27 +0000 Subject: [PATCH 1974/2102] ASoC: SOF: ipc4-mtrace: fix the wrapped read when the user buffer is short When the log data wraps around the end of the slot, sof_ipc4_mtrace_dfs_read() copies it in two parts: sof_mailbox_read(..., log_buffer, avail - write_ptr); sof_mailbox_read(..., log_buffer + avail - write_ptr, write_ptr); This assumes that avail is still the full distance from read_ptr to write_ptr. But avail has just been cut down to count - sizeof(avail) if the user asked for less. If it ends up smaller than write_ptr, avail - write_ptr wraps around, and the first sof_mailbox_read() gets a length of about 4 GiB for the 4 KiB log_buffer. For example, with read_ptr = 4080 and write_ptr = 16, a read of 12 bytes gives avail = 8 and a copy of 0xfffffff8 bytes. If avail is cut but still larger than write_ptr, the two parts don't line up with read_ptr and the user gets the wrong bytes. Copy from read_ptr up to the end of the slot, but no more than avail, and take the rest from the start of the slot. Found with a static analysis tool and checked by hand. Fixes: f4ea22f7aa75 ("ASoC: SOF: ipc4: Add support for mtrace log extraction") Cc: stable@vger.kernel.org Co-developed-by: Kaixuan Li Signed-off-by: Kaixuan Li Signed-off-by: Suyuan Wang Link: https://patch.msgid.link/20261121-sof-mtrace-wrap-v1-1-9798707c3439@gmail.com Signed-off-by: Mark Brown --- sound/soc/sof/ipc4-mtrace.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/sound/soc/sof/ipc4-mtrace.c b/sound/soc/sof/ipc4-mtrace.c index 064291e26974be..0d5135d256c3ea 100644 --- a/sound/soc/sof/ipc4-mtrace.c +++ b/sound/soc/sof/ipc4-mtrace.c @@ -230,14 +230,17 @@ static ssize_t sof_ipc4_mtrace_dfs_read(struct file *file, char __user *buffer, /* Read data between read pointer and write pointer */ sof_mailbox_read(sdev, log_buffer_offset + read_ptr, log_buffer, avail); } else { + /* avail may have been cut to the user's count above */ + u32 tail = min(avail, log_buffer_size - read_ptr); + /* read from read pointer to end of the slot */ sof_mailbox_read(sdev, log_buffer_offset + read_ptr, log_buffer, - avail - write_ptr); - /* read from slot start to write pointer */ - if (write_ptr) + tail); + /* read the rest from slot start */ + if (avail > tail) sof_mailbox_read(sdev, log_buffer_offset, - (u8 *)(log_buffer) + avail - write_ptr, - write_ptr); + (u8 *)(log_buffer) + tail, + avail - tail); } /* first write the number of bytes we have gathered */ From f3ea554859ba836326e0918764c962623c70ed28 Mon Sep 17 00:00:00 2001 From: Gerard Marull-Paretas Date: Sun, 22 Nov 2026 10:34:19 +0100 Subject: [PATCH 1975/2102] ASoC: dt-bindings: awinic,aw8738: Add AW8155 The AW8155 is a class-D/AB mono amplifier whose mode is selected by the number of pulses on its CTRL pin, holding it low shutting it down, as on the AW8738. The waveform the aw8738 driver generates (2 us pulses, 40 ms start-up wait, 1-2 ms low for shutdown) is within the AW8155 datasheet timings (0.75-10 us pulses, 40 ms start-up, 150-800 us turn-off), so the AW8738 compatible can serve as a fallback. Only modes 1, 2 and 4 are valid on the AW8155, mode 3 being a test mode, so restrict awinic,mode to those. Signed-off-by: Gerard Marull-Paretas Link: https://patch.msgid.link/20261122093419.72135-1-gerard@teslabs.com Signed-off-by: Mark Brown --- .../bindings/sound/awinic,aw8738.yaml | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Documentation/devicetree/bindings/sound/awinic,aw8738.yaml b/Documentation/devicetree/bindings/sound/awinic,aw8738.yaml index bc6c6b17223809..5ef7b800226a37 100644 --- a/Documentation/devicetree/bindings/sound/awinic,aw8738.yaml +++ b/Documentation/devicetree/bindings/sound/awinic,aw8738.yaml @@ -14,12 +14,28 @@ description: (set using one-wire pulse control). The mode configures the speaker-guard function (primarily the power limit for the amplifier). + The Awinic AW8155 also has its mode set by one-wire pulses on its control + pin. Its modes select the amplifier class, its gain and its power limit. + allOf: - $ref: dai-common.yaml# + - if: + properties: + compatible: + contains: + const: awinic,aw8155 + then: + properties: + awinic,mode: + enum: [1, 2, 4] properties: compatible: - const: awinic,aw8738 + oneOf: + - const: awinic,aw8738 + - items: + - const: awinic,aw8155 + - const: awinic,aw8738 mode-gpios: description: From fa84f87e42af9ffa3f777d4ea3b8c4f82a5a7436 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Thu, 26 Nov 2026 03:38:13 +0000 Subject: [PATCH 1976/2102] bpf: Undo insn aux changes of a failed speculative path If a check fails on a speculative path, do_check() adds a nospec before the insn and ends the path. The check can have written nospec_result and ctx_field_size of the insn already. The other paths can use the insn with another type of pointer, so these values do not apply to them. Save both fields before the check and restore them. Fixes: d6f1c85f2253 ("bpf: Fall back to nospec for Spectre v1") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261126033816.4124847-2-alexei.starovoitov@gmail.com --- kernel/bpf/verifier.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index d4b31990fcb9c6..c553e1533acec8 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -20649,7 +20649,8 @@ static int do_check(struct bpf_verifier_env *env) for (;;) { struct bpf_insn *insn; struct bpf_insn_aux_data *insn_aux; - int err; + int err, ctx_field_size; + bool nospec_result; if (signal_pending(current)) return -EAGAIN; @@ -20802,6 +20803,8 @@ static int do_check(struct bpf_verifier_env *env) if (state->speculative && insn_aux->nospec) goto process_bpf_exit; + nospec_result = insn_aux->nospec_result; + ctx_field_size = insn_aux->ctx_field_size; err = do_check_insn(env, &do_print_state); if (error_recoverable_with_nospec(err) && state->speculative) { /* Prevent this speculative path from ever reaching the @@ -20812,6 +20815,8 @@ static int do_check(struct bpf_verifier_env *env) * markings for alu sanitization. */ insn_aux->alu_state = 0; + insn_aux->nospec_result = nospec_result; + insn_aux->ctx_field_size = ctx_field_size; goto process_bpf_exit; } else if (err < 0) { return err; From bbe2012ece4a72d4917dcc9b3461f7573a66c418 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Thu, 26 Nov 2026 03:38:14 +0000 Subject: [PATCH 1977/2102] bpf: Treat NOT_INIT as a pointer in __is_pointer_value() The blamed commit made __is_pointer_value() use is_pointer_regtype(), which is false for NOT_INIT. mark_reg_invalid() can set a spilled register to NOT_INIT, and check_stack_read_fixed_off() must not handle such a spill like a spilled scalar. Go back to the check for SCALAR_VALUE. Fixes: 1f737e46ca6a ("bpf: Remove artificial limitations on pointer types eligible for spilling") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261126033816.4124847-3-alexei.starovoitov@gmail.com --- kernel/bpf/verifier.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index c553e1533acec8..5929478787d35c 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -3825,7 +3825,7 @@ static bool __is_pointer_value(bool allow_ptr_leaks, if (allow_ptr_leaks) return false; - return is_pointer_regtype(reg->type); + return reg->type != SCALAR_VALUE; } static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, From 599e0ce412d5f9587aab689113c762c19caf4429 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Thu, 26 Nov 2026 03:38:15 +0000 Subject: [PATCH 1978/2102] bpf: Use get_unaligned() in bpf_map_direct_read() const_reg_xfer() calls bpf_map_direct_read() before the main pass checks the alignment of the load. So the offset is not always a multiple of the size. Fixes: f1606dd0ac49 ("bpf: Add bpf_compute_const_regs() and bpf_prune_dead_branches() passes") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261126033816.4124847-4-alexei.starovoitov@gmail.com --- kernel/bpf/verifier.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 5929478787d35c..36441ed9f0eacb 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -6386,13 +6387,13 @@ int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; break; case sizeof(u16): - *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; + *val = is_ldsx ? (s64)get_unaligned((s16 *)ptr) : (u64)get_unaligned((u16 *)ptr); break; case sizeof(u32): - *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; + *val = is_ldsx ? (s64)get_unaligned((s32 *)ptr) : (u64)get_unaligned((u32 *)ptr); break; case sizeof(u64): - *val = *(u64 *)ptr; + *val = get_unaligned((u64 *)ptr); break; default: return -EINVAL; From 1879b5e505de97e250bb2d7e6914fbdf4032e15b Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Thu, 26 Nov 2026 03:38:16 +0000 Subject: [PATCH 1979/2102] bpf: Emit nospec after calls and atomics that write to the stack check_stack_write_fixed_off() sets nospec_result for BPF_ATOMIC insns and for calls of helpers and kfuncs too. do_check() ends a speculative path there, but bpf_convert_ctx_accesses() emits the nospec only after BPF_MEM stores. Later passes rewrite a call and need its aux data. Put the nospec in front of the next insn. Fixes: d6f1c85f2253 ("bpf: Fall back to nospec for Spectre v1") Fixes: 880442305a39 ("bpf: Introduce load-acquire and store-release instructions") Suggested-by: Luis Gerhorst Signed-off-by: Alexei Starovoitov Acked-by: Luis Gerhorst Link: https://patch.msgid.link/20261126033816.4124847-5-alexei.starovoitov@gmail.com --- kernel/bpf/fixups.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c index 9d5f2774bf8f83..8c3a17a05a4e19 100644 --- a/kernel/bpf/fixups.c +++ b/kernel/bpf/fixups.c @@ -911,6 +911,7 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env) const int insn_cnt = env->prog->len; struct bpf_insn *epilogue_buf = env->epilogue_buf; struct bpf_insn *insn_buf = env->insn_buf; + bool nospec, nospec_next = false; struct bpf_insn *insn; u32 target_size, size_default, off; struct bpf_prog *new_prog; @@ -994,8 +995,13 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env) enum bpf_reg_type ptr_type; u8 mode; - if (env->insn_aux_data[i + delta].nospec) { - WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state); + /* A call or an atomic gets its nospec in front of the next insn */ + nospec = env->insn_aux_data[i + delta].nospec; + WARN_ON_ONCE(nospec && env->insn_aux_data[i + delta].alu_state); + nospec |= nospec_next; + nospec_next = env->insn_aux_data[i + delta].nospec_result; + + if (nospec) { struct bpf_insn *patch = insn_buf; *patch++ = BPF_ST_NOSPEC(); @@ -1102,6 +1108,7 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env) delta += cnt - 1; env->prog = new_prog; insn = new_prog->insnsi + i + delta; + nospec_next = false; continue; } From a81d29df131fa3f8b3777f3b8118d6c964af731f Mon Sep 17 00:00:00 2001 From: Perry Dale Date: Fri, 20 Nov 2026 11:47:24 -0800 Subject: [PATCH 1980/2102] ASoC: qcom: q6apm-dai: queue playback buffers only while the graph runs Commit cab45ab95ce7 ("ASoC: qcom: q6apm-dai: reset queue ptr on trigger stop") resets queue_ptr to 0 on SNDRV_PCM_TRIGGER_STOP, but ALSA leaves appl_ptr unchanged until the next prepare. ALSA calls .ack when a write, a forward or SNDRV_PCM_IOCTL_SYNC_PTR moves appl_ptr, and SYNC_PTR can do so in the SETUP and XRUN states after a stop. q6apm_dai_ack() then computes avail_periods from the full appl_ptr and issues one q6apm_write_async() per period. After 530 seconds of playback at 48 kHz with 480-frame periods that is about 53000 writes in one call. The glink channel runs out of remote intents, the write fails with -EBUSY, and the DSP stops answering GPR commands. Every later prepare times out with -ETIMEDOUT until a reboot: q6apm-dai ...: Error queuing playback buffer -16 qcom-apm gprsvc:service:2:1: CMD timeout for [1001003] opcode q6apm-lpass-dais ...: Failed to set media format -110 On the AYN Odin 2 Portal (SM8550) PipeWire triggers this when a game pauses its stream. A test program reproduces it by playing one second on the PCM, calling snd_pcm_drop() and moving appl_ptr forward one period with SNDRV_PCM_IOCTL_SYNC_PTR. Queue only while the graph is running, which prepare sets once the graph is started and trigger stop clears, and only in the PREPARED, RUNNING, PAUSED and DRAINING states. A drop before start does not reach the trigger callback, so the driver state alone does not cover it. Reset queue_ptr in prepare, where ALSA resets appl_ptr. Prepare runs without the stream lock and a second prepare finds the stream running, so mark it stopped under the stream lock before the graph and its buffers are replaced. The same unsigned difference is wrong in two more cases. SNDRV_PCM_IOCTL_RESET moves appl_ptr back to hw_ptr without a call to .ack and leaves queue_ptr ahead of it, and appl_ptr wraps at the boundary while queue_ptr did not. Both can queue a burst of writes. Wrap queue_ptr at the boundary, take the difference modulo the boundary, and queue nothing when it is more than ALSA holds for playback. That also covers an appl_ptr moved more than a ring past hw_ptr. After a reset on a running stream whose hw_ptr has reached the end of the first ring, or on a paused or suspended stream that far along, the stream no longer advances until its next prepare, and the DSP keeps answering. The next patch carries the stream across a reset. It is not needed for stable. An .ack between the end of the driver's prepare and the point where ALSA resets appl_ptr can still queue stale data, as before, now at most one ring in total. Tool use: drafted with Claude Opus 5.5 and revised with Claude Fable 5.2 (Anthropic), run in Claude Code, from a prompt asking for the cause of the audio DSP failures during games on the Portal. The tools analysed the kernel logs and wrote the test program, the change and this changelog. Built as a module for 7.4-rc1 and run on the Portal with the test program: plain playback, drop followed by appl_ptr updates before and after start, resets while running and before start, underrun recovery, 30 drained streams, and 40 resets and prepares while a second thread moves appl_ptr with SYNC_PTR. The DSP kept answering through every run. The resets on a running stream stopped it as described above. The unpatched driver fails the first drop round of the same program with the messages above. The boundary wrap was not exercised. Fixes: cab45ab95ce7 ("ASoC: qcom: q6apm-dai: reset queue ptr on trigger stop") Fixes: 3d4a4411aa8b ("ASoC: q6apm-dai: schedule all available frames to avoid dsp under-runs") Cc: stable@vger.kernel.org Cc: Srinivas Kandagatla Signed-off-by: Perry Dale Link: https://patch.msgid.link/LV5PR84MB40260AD8BB8842BA97269B9DA7782@LV5PR84MB4026.NAMPRD84.PROD.OUTLOOK.COM Signed-off-by: Mark Brown --- sound/soc/qcom/qdsp6/q6apm-dai.c | 52 +++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/sound/soc/qcom/qdsp6/q6apm-dai.c b/sound/soc/qcom/qdsp6/q6apm-dai.c index 3dcbaa64f2c0b9..9c5c89507326db 100644 --- a/sound/soc/qcom/qdsp6/q6apm-dai.c +++ b/sound/soc/qcom/qdsp6/q6apm-dai.c @@ -345,6 +345,17 @@ static int q6apm_dai_prepare(struct snd_soc_component *component, cfg.bit_width = prtd->bits_per_sample; cfg.fmt = SND_AUDIOCODEC_PCM; audioreach_set_default_channel_mapping(cfg.channel_map, runtime->channels); + /* + * A second prepare finds the stream running. Stop .ack from queueing + * while the graph and its buffers are replaced. + */ + snd_pcm_stream_lock_irq(substream); + if (prtd->state == Q6APM_STREAM_RUNNING) + prtd->state = Q6APM_STREAM_STOPPED; + /* ALSA sets appl_ptr to 0 after a successful prepare */ + prtd->queue_ptr = 0; + snd_pcm_stream_unlock_irq(substream); + if (prtd->state) { /* clear the previous setup if any */ q6apm_graph_stop(prtd->graph); @@ -415,7 +426,9 @@ static int q6apm_dai_prepare(struct snd_soc_component *component, } /* Now that graph as been prepared and started update the internal state accordingly */ + snd_pcm_stream_lock_irq(substream); prtd->state = Q6APM_STREAM_RUNNING; + snd_pcm_stream_unlock_irq(substream); return 0; } @@ -429,8 +442,43 @@ static int q6apm_dai_ack(struct snd_soc_component *component, struct snd_pcm_sub if (q6apm_is_graph_in_push_pull_mode(prtd->graph)) return 0; + /* + * ALSA calls .ack whenever appl_ptr moves, also after a stop and + * before the next prepare. The graph has no queue to fill then, and + * queue_ptr is out of step with appl_ptr until prepare resets both. + */ + if (prtd->state != Q6APM_STREAM_RUNNING) + return 0; + + /* A drop before start does not reach the trigger callback. */ + switch (runtime->state) { + case SNDRV_PCM_STATE_PREPARED: + case SNDRV_PCM_STATE_RUNNING: + case SNDRV_PCM_STATE_PAUSED: + case SNDRV_PCM_STATE_DRAINING: + break; + default: + return 0; + } + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { - avail_periods = (runtime->control->appl_ptr - prtd->queue_ptr)/runtime->period_size; + snd_pcm_sframes_t pending = runtime->control->appl_ptr - prtd->queue_ptr; + + /* appl_ptr wraps at the boundary before queue_ptr does. */ + if (pending < 0) + pending += runtime->boundary; + + /* + * What is left to queue is part of what ALSA holds for + * playback. It is more when queue_ptr is ahead of appl_ptr, + * as after SNDRV_PCM_IOCTL_RESET, or when appl_ptr was moved + * more than a ring past hw_ptr. + */ + if (pending > snd_pcm_playback_hw_avail(runtime)) + return 0; + + avail_periods = min_t(snd_pcm_sframes_t, pending / runtime->period_size, + runtime->periods); for (i = 0; i < avail_periods; i++) { ret = q6apm_write_async(prtd->graph, prtd->pcm_count, 0, 0, NO_TIMESTAMP); if (ret < 0) { @@ -438,6 +486,8 @@ static int q6apm_dai_ack(struct snd_soc_component *component, struct snd_pcm_sub return ret; } prtd->queue_ptr += runtime->period_size; + if (prtd->queue_ptr >= runtime->boundary) + prtd->queue_ptr -= runtime->boundary; } } From 164041af6ce0572931efacef8de7d2f07d0dbb43 Mon Sep 17 00:00:00 2001 From: Perry Dale Date: Fri, 20 Nov 2026 11:47:25 -0800 Subject: [PATCH 1981/2102] ASoC: qcom: q6apm-dai: keep a playback stream running across a PCM reset SNDRV_PCM_IOCTL_RESET sets appl_ptr to hw_ptr. On a running stream it first reduces hw_ptr modulo the buffer size, otherwise it sets hw_ptr to 0. The period buffers already given to the DSP stay with it, and queue_ptr keeps its value from before the reset. Once that value is at least a ring away from the new hw_ptr, q6apm_dai_ack() queues nothing, the application fills the ring and the stream stops advancing until its next prepare. Count the buffers the DSP holds. A buffer is added when it is queued and taken off by the write-done event, under the stream lock and in the same section that reports the elapsed period. Prepare clears the count when it replaces the buffers. Handle SNDRV_PCM_IOCTL1_RESET in an ioctl callback. After snd_pcm_lib_ioctl() has moved hw_ptr, give queue_ptr the ring offset it had, relative to the new hw_ptr. The next buffer handed to the DSP is then still the one after the buffers it holds. That offset is 0 both for an empty and for a full queue. A running stream with every buffer queued continues with those buffers, and what the application writes over them is not queued a second time. In every other case with offset 0 the queue is taken as empty, and what is written from there on is queued as buffers come back. Move the queueing into a helper that both .ack and the write-done event call. One call queues at most the buffers the DSP does not hold. The limit of one ring per call did not account for buffers already queued. With that limit a write can find no free buffer, so the event queues what is waiting when a buffer comes back. Without it the data waited for the next write, which never comes at the end of a stream. The helper measures queue_ptr against hw_ptr and aligns it in the same way when it is not within one ring ahead. hw_ptr passes queue_ptr after a reset before start with every buffer queued, and a reset on a paused or suspended stream can leave the two apart as well. A send that fails now stops the stream with an xrun. The core has advanced its buffer index by then, and only a prepare brings it back in step with queue_ptr. Before, the error went to the writer and the two stayed out of step. Not changed here: the graph keeps playing while the stream is paused, so a reset on a paused stream can skip the first period written after it, and a write-done event that the core drops leaves the count one too high until the next prepare. Tool use: written with Claude Fable 5.2 (Anthropic), run in Claude Code, from a prompt asking to carry a running stream across a reset. The tool wrote the change, the test program and this changelog, and revised them after reviews by Claude Opus 5.5 and GPT (Codex). Built as a module for 7.4-rc1 and run on the AYN Odin 2 Portal (SM8550) with the test program of the previous patch. Five resets in a row on a running stream, a reset with the queue played out in the second lap, a reset before start with two periods written, and a reset and rewrite with a full ring queued before start all continued. The cases of the previous patch passed, and the DSP kept answering through every run. A debug build that failed two sends during PipeWire playback stopped the stream each time, and PipeWire restarted it. The test checks that the stream advances. It does not check which samples the DSP plays for the buffers it held at a reset, and it does not exercise the boundary wrap or a paused stream. Cc: Srinivas Kandagatla Signed-off-by: Perry Dale Link: https://patch.msgid.link/LV5PR84MB4026E23CD27421FEF1D8B373A7782@LV5PR84MB4026.NAMPRD84.PROD.OUTLOOK.COM Signed-off-by: Mark Brown --- sound/soc/qcom/qdsp6/q6apm-dai.c | 154 ++++++++++++++++++++++++------- 1 file changed, 121 insertions(+), 33 deletions(-) diff --git a/sound/soc/qcom/qdsp6/q6apm-dai.c b/sound/soc/qcom/qdsp6/q6apm-dai.c index 9c5c89507326db..a8b9c1bfb5675b 100644 --- a/sound/soc/qcom/qdsp6/q6apm-dai.c +++ b/sound/soc/qcom/qdsp6/q6apm-dai.c @@ -91,6 +91,8 @@ struct q6apm_dai_rtd { uint64_t copied_total; uint16_t bits_per_sample; snd_pcm_uframes_t queue_ptr; + unsigned int in_flight; + struct device *dev; bool next_track; enum stream_state state; struct q6apm_graph *graph; @@ -236,6 +238,8 @@ static const struct snd_pcm_hardware q6apm_dai_hardware_playback = { .fifo_size = 0, }; +static int q6apm_dai_queue_playback(struct snd_pcm_substream *substream); + static void event_handler(uint32_t opcode, uint32_t token, void *payload, void *priv) { struct q6apm_dai_rtd *prtd = priv; @@ -249,7 +253,13 @@ static void event_handler(uint32_t opcode, uint32_t token, void *payload, void * prtd->state = Q6APM_STREAM_STOPPED; break; case APM_CLIENT_EVENT_DATA_WRITE_DONE: - snd_pcm_period_elapsed(substream); + scoped_guard(pcm_stream_lock_irqsave, substream) { + if (prtd->in_flight) + prtd->in_flight--; + snd_pcm_period_elapsed_under_stream_lock(substream); + /* The returned buffer may be needed for data already written. */ + q6apm_dai_queue_playback(substream); + } break; case APM_CLIENT_EVENT_DATA_READ_DONE: @@ -363,6 +373,10 @@ static int q6apm_dai_prepare(struct snd_soc_component *component, } prtd->last_pos_index = 0; + /* The graph gets a new set of buffers and starts with none queued. */ + snd_pcm_stream_lock_irq(substream); + prtd->in_flight = 0; + snd_pcm_stream_unlock_irq(substream); prtd->pcm_count = snd_pcm_lib_period_bytes(substream); if (q6apm_is_graph_in_push_pull_mode(prtd->graph)) { if (prtd->pcm_size != prtd->push_pull_size) { @@ -433,14 +447,39 @@ static int q6apm_dai_prepare(struct snd_soc_component *component, return 0; } -static int q6apm_dai_ack(struct snd_soc_component *component, struct snd_pcm_substream *substream) +/* + * Give queue_ptr its ring offset back relative to hw_ptr. Called with the + * stream lock held after hw_ptr moved without it. + */ +static void q6apm_dai_align_queue(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; struct q6apm_dai_rtd *prtd = runtime->private_data; - int i, ret = 0, avail_periods; + snd_pcm_uframes_t hw_ptr = runtime->status->hw_ptr; + snd_pcm_uframes_t ahead; - if (q6apm_is_graph_in_push_pull_mode(prtd->graph)) - return 0; + ahead = (prtd->queue_ptr % runtime->buffer_size + runtime->buffer_size - + hw_ptr % runtime->buffer_size) % runtime->buffer_size; + /* + * The offset is 0 both for an empty and for a full queue. A running + * stream with every buffer queued continues with the buffers the DSP + * holds. A paused stream can have them played before its hw_ptr moves + * again, so a stream that is not running queues what is written from + * here on. + */ + if (!ahead && snd_pcm_running(substream) && prtd->in_flight == runtime->periods) + ahead = runtime->buffer_size; + + prtd->queue_ptr = (hw_ptr + ahead) % runtime->boundary; +} + +/* Queue the periods written and not yet queued. Called with the stream lock held. */ +static int q6apm_dai_queue_playback(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct q6apm_dai_rtd *prtd = runtime->private_data; + snd_pcm_sframes_t ahead, pending; + int i, ret, avail_periods; /* * ALSA calls .ack whenever appl_ptr moves, also after a stop and @@ -461,37 +500,84 @@ static int q6apm_dai_ack(struct snd_soc_component *component, struct snd_pcm_sub return 0; } - if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { - snd_pcm_sframes_t pending = runtime->control->appl_ptr - prtd->queue_ptr; - - /* appl_ptr wraps at the boundary before queue_ptr does. */ - if (pending < 0) - pending += runtime->boundary; - - /* - * What is left to queue is part of what ALSA holds for - * playback. It is more when queue_ptr is ahead of appl_ptr, - * as after SNDRV_PCM_IOCTL_RESET, or when appl_ptr was moved - * more than a ring past hw_ptr. - */ - if (pending > snd_pcm_playback_hw_avail(runtime)) - return 0; - - avail_periods = min_t(snd_pcm_sframes_t, pending / runtime->period_size, - runtime->periods); - for (i = 0; i < avail_periods; i++) { - ret = q6apm_write_async(prtd->graph, prtd->pcm_count, 0, 0, NO_TIMESTAMP); - if (ret < 0) { - dev_err(component->dev, "Error queuing playback buffer %d\n", ret); - return ret; - } - prtd->queue_ptr += runtime->period_size; - if (prtd->queue_ptr >= runtime->boundary) - prtd->queue_ptr -= runtime->boundary; + /* Frames queued that hw_ptr has not passed yet, at most one ring. */ + ahead = prtd->queue_ptr - runtime->status->hw_ptr; + if (ahead < 0) + ahead += runtime->boundary; + if (ahead > runtime->buffer_size) { + q6apm_dai_align_queue(substream); + ahead = prtd->queue_ptr - runtime->status->hw_ptr; + if (ahead < 0) + ahead += runtime->boundary; + } + + /* Nothing to queue until appl_ptr has passed queue_ptr. */ + pending = snd_pcm_playback_hw_avail(runtime) - ahead; + if (pending <= 0) + return 0; + + /* Leave the buffers the DSP still holds alone. */ + avail_periods = min_t(snd_pcm_sframes_t, pending / runtime->period_size, + (snd_pcm_sframes_t)runtime->periods - + (snd_pcm_sframes_t)prtd->in_flight); + for (i = 0; i < avail_periods; i++) { + ret = q6apm_write_async(prtd->graph, prtd->pcm_count, 0, 0, NO_TIMESTAMP); + if (ret < 0) { + dev_err(prtd->dev, "Error queuing playback buffer %d\n", ret); + /* + * The core has moved on to its next buffer. Only a + * prepare brings queue_ptr back in step with it. + */ + snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN); + return ret; } + prtd->in_flight++; + prtd->queue_ptr += runtime->period_size; + if (prtd->queue_ptr >= runtime->boundary) + prtd->queue_ptr -= runtime->boundary; } - return ret; + return 0; +} + +static int q6apm_dai_ack(struct snd_soc_component *component, struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct q6apm_dai_rtd *prtd = runtime->private_data; + + if (q6apm_is_graph_in_push_pull_mode(prtd->graph)) + return 0; + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + return q6apm_dai_queue_playback(substream); + + return 0; +} + +/* + * A PCM reset, which ALSA also runs at the end of every prepare, moves + * hw_ptr: modulo the buffer size on a running stream, to 0 otherwise. + * appl_ptr follows it without a call to .ack. The buffers the DSP holds + * stay with it, so keep queue_ptr in step with the ring. + */ +static int q6apm_dai_ioctl(struct snd_soc_component *component, + struct snd_pcm_substream *substream, + unsigned int cmd, void *arg) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct q6apm_dai_rtd *prtd = runtime->private_data; + int ret; + + ret = snd_pcm_lib_ioctl(substream, cmd, arg); + if (ret < 0 || cmd != SNDRV_PCM_IOCTL1_RESET || + substream->stream != SNDRV_PCM_STREAM_PLAYBACK || + q6apm_is_graph_in_push_pull_mode(prtd->graph)) + return ret; + + guard(pcm_stream_lock_irq)(substream); + q6apm_dai_align_queue(substream); + + return 0; } static int q6apm_dai_trigger(struct snd_soc_component *component, @@ -547,6 +633,7 @@ static int q6apm_dai_open(struct snd_soc_component *component, return -ENOMEM; spin_lock_init(&prtd->lock); + prtd->dev = dev; prtd->substream = substream; prtd->graph = q6apm_graph_open(dev, event_handler, prtd, graph_id, substream->stream); if (IS_ERR(prtd->graph)) { @@ -1232,6 +1319,7 @@ static const struct snd_soc_component_driver q6apm_fe_dai_component = { .pointer = q6apm_dai_pointer, .trigger = q6apm_dai_trigger, .ack = q6apm_dai_ack, + .ioctl = q6apm_dai_ioctl, .compress_ops = &q6apm_dai_compress_ops, .use_dai_pcm_id = true, .remove_order = SND_SOC_COMP_ORDER_EARLY, From 3c625090b46b0d683112465a07d95bf5ff71174f Mon Sep 17 00:00:00 2001 From: Sechang Lim Date: Thu, 26 Nov 2026 05:30:06 +0000 Subject: [PATCH 1982/2102] bpf: Reject kernel threads in bpf_task_work_schedule() bpf_task_work_schedule_signal() on a kernel thread sets TIF_NOTIFY_SIGNAL, but the thread never returns to user space, so nothing clears it and signal_pending() stays true. Interruptible sleeps in the thread return immediately. For kthreadd this means spinning at 100% CPU. io_ring_exit_work() waits on ctx->ref_comp interruptibly, assuming a kworker gets no signals. If a prog running in that kworker schedules task work on current, the wait returns -ERESTARTSYS and the ctx is freed while ctx->refs is still switching to atomic: WARNING: lib/percpu-refcount.c:114 at __percpu_ref_exit+0x77/0x110 Workqueue: iou_exit io_ring_exit_work ... BUG: KASAN: slab-use-after-free in rcu_cblist_dequeue+0xd3/0x120 The callback can't run before the thread exits anyway. Reject kernel threads with -EPERM, as bpf_send_signal() does. Fixes: 38aa7003e369 ("bpf: task work scheduling kfuncs") Signed-off-by: Sechang Lim Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261126053016.1145482-1-rhkrqnwk98@gmail.com --- kernel/bpf/helpers.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index 1b95fe795b4d9f..784674c5fddf9e 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -4804,6 +4804,9 @@ static int bpf_task_work_schedule(struct task_struct *task, struct bpf_task_work BTF_TYPE_EMIT(struct bpf_task_work); + if (task->flags & PF_KTHREAD) + return -EPERM; + prog = bpf_prog_inc_not_zero(aux->prog); if (IS_ERR(prog)) return -EBADF; From 14f6b10422d640695803c621687f790f6f3d2401 Mon Sep 17 00:00:00 2001 From: Sechang Lim Date: Thu, 26 Nov 2026 10:19:41 +0000 Subject: [PATCH 1983/2102] bpf, sockmap: Clear the redirect target after the stream parser runs A stream parser can call bpf_sk_redirect_{map,hash}(), which store the target socket in skb->_sk_redir. sk_psock_strp_parse() never clears it, and it shares storage with skb->_skb_refdst, so skb_dst_drop() later passes the socket to dst_release(): KASAN: null-ptr-deref in range [0x0000000000000128-0x000000000000012f] RIP: 0010:percpu_counter_add_batch+0x24/0x220 Call Trace: dst_release.part.0+0xc9/0x180 skb_release_head_state+0x1cc/0x2f0 sk_skb_reason_drop+0xbc/0x420 strp_done+0xcf/0x150 sk_psock_destroy+0x85e/0xb10 Drop the dst before the parser runs, as the verdict paths do, and clear the redirect after it. The parser's redirect was never used. Fixes: e3526bb92a20 ("skmsg: Move sk_redir from TCP_SKB_CB to skb") Signed-off-by: Sechang Lim Signed-off-by: Alexei Starovoitov Reviewed-by: Jiayuan Chen Link: https://patch.msgid.link/20261126101950.1682160-1-rhkrqnwk98@gmail.com --- net/core/skmsg.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/net/core/skmsg.c b/net/core/skmsg.c index 005e09121f00ab..4089901a95812a 100644 --- a/net/core/skmsg.c +++ b/net/core/skmsg.c @@ -1131,7 +1131,9 @@ static int sk_psock_strp_parse(struct strparser *strp, struct sk_buff *skb) prog = READ_ONCE(psock->progs.stream_parser); if (likely(prog)) { skb->sk = psock->sk; + skb_dst_drop(skb); ret = bpf_prog_run_pin_on_cpu(prog, skb); + skb_bpf_redirect_clear(skb); skb->sk = NULL; } rcu_read_unlock(); From 2b978906a8785f8ecd8c1691efe88dee0b224025 Mon Sep 17 00:00:00 2001 From: Manuel Ebner Date: Thu, 26 Nov 2026 21:21:07 +0100 Subject: [PATCH 1984/2102] ASoC: rt5514-spi: fix comment notation Turn kernel-doc into multi-line comment, fixing: $ ./scripts/kernel-doc --none sound/soc/codecs/rt5514-spi.h Warning: sound/soc/codecs/rt5514-spi.h:12 This comment starts with '/**', but isn't a kernel-doc comment. Refer to Documentation/doc-guide/kernel-doc.rst * RT5514_SPI_BUF_LEN is the buffer size of SPI master controller. Signed-off-by: Manuel Ebner Link: https://patch.msgid.link/20261126202107.1776233-2-manuelebnerli@mailbox.org Signed-off-by: Mark Brown --- sound/soc/codecs/rt5514-spi.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sound/soc/codecs/rt5514-spi.h b/sound/soc/codecs/rt5514-spi.h index cedb19709c9aca..fce9fba1fc9c88 100644 --- a/sound/soc/codecs/rt5514-spi.h +++ b/sound/soc/codecs/rt5514-spi.h @@ -9,9 +9,9 @@ #ifndef __RT5514_SPI_H__ #define __RT5514_SPI_H__ -/** +/* * RT5514_SPI_BUF_LEN is the buffer size of SPI master controller. -*/ + */ #define RT5514_SPI_BUF_LEN 240 #define RT5514_BUFFER_VOICE_BASE 0x18000200 From 2d69cae40cf6b02014928f71a46a66a6eb50773b Mon Sep 17 00:00:00 2001 From: Manuel Ebner Date: Thu, 26 Nov 2026 21:30:39 +0100 Subject: [PATCH 1985/2102] ASoC: imx-pcm-rpmsg: fix kernel-doc Correct typo in kernel-doc, fixing: $ ./scripts/kernel-doc --none sound/soc/fsl/imx-pcm-rpmsg.h Warning: sound/soc/fsl/imx-pcm-rpmsg.h:419 expecting prototype for struct param_s. Prototype was for struct param_r instead Signed-off-by: Manuel Ebner Link: https://patch.msgid.link/20261126203039.1777085-2-manuelebnerli@mailbox.org Signed-off-by: Mark Brown --- sound/soc/fsl/imx-pcm-rpmsg.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/fsl/imx-pcm-rpmsg.h b/sound/soc/fsl/imx-pcm-rpmsg.h index 8286b55f00ae95..52f2529724f62b 100644 --- a/sound/soc/fsl/imx-pcm-rpmsg.h +++ b/sound/soc/fsl/imx-pcm-rpmsg.h @@ -397,7 +397,7 @@ struct param_s { } __packed; /** - * struct param_s: send rpmsg parameter + * struct param_r: send rpmsg parameter * * @audioindex: audio instance index * @resp: response value From d430c96a291a9c2e7f9a279e8bf9ec252d18c4a9 Mon Sep 17 00:00:00 2001 From: Tina Zhang Date: Fri, 27 Nov 2026 08:38:17 +0800 Subject: [PATCH 1986/2102] x86/cpu/hygon: Work around XSAVES Erratum 1386 The XSAVES malfunction described in AMD Erratum 1386 also affects certain Hygon Family 18h processors. Under specific conditions, XSAVES may fail to save XMM register state, allowing stale register values to reappear after the state is restored. The failure mode is documented as Erratum 1386 in "Revision Guide for AMD Family 19h Models 00h-0Fh Processors", Publication #56683. None of the affected processors enumerate supervisor XSAVE state components. XSAVEC is therefore equivalent for their enabled state components and is not affected by the erratum. Family 18h models 00h through 06h and model 10h are affected. Other Family 18h models contain the fix in hardware. For the following model and stepping combinations, the minimum microcode revisions containing the fix are: Model Stepping Microcode 04h 0 0x9040000f 04h 1 0x9041000f 06h 0 0x9060000f 06h 1 0x9061000f 10h 0 0x91000004 These are the only known steppings for those models. Disable XSAVES on affected processors unless a matching model and stepping entry identifies a sufficiently recent microcode revision containing the fix. This allows the x86 FPU code to use XSAVEC instead. Signed-off-by: Tina Zhang Signed-off-by: Borislav Petkov (AMD) Reviewed-by: Zhen Yang Tested-by: Qiming Deng Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261127003818.1208038-1-zhang_wei@open-hieco.net --- arch/x86/kernel/cpu/hygon.c | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/arch/x86/kernel/cpu/hygon.c b/arch/x86/kernel/cpu/hygon.c index 0bccb934fbf855..ea37c48de26e40 100644 --- a/arch/x86/kernel/cpu/hygon.c +++ b/arch/x86/kernel/cpu/hygon.c @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -170,11 +171,39 @@ static void early_init_hygon(struct cpuinfo_x86 *c) set_cpu_cap(c, X86_FEATURE_VMMCALL); } +#define X86_MATCH_HYGON_MODEL_STEP_UCODE(model, step, ucode) \ + X86_MATCH_VFM_STEPS(VFM_MAKE(X86_VENDOR_HYGON, 0x18, model), \ + step, step, ucode) + +static const struct x86_cpu_id erratum_1386_microcode[] = { + X86_MATCH_HYGON_MODEL_STEP_UCODE(0x04, 0x00, 0x9040000f), + X86_MATCH_HYGON_MODEL_STEP_UCODE(0x04, 0x01, 0x9041000f), + X86_MATCH_HYGON_MODEL_STEP_UCODE(0x06, 0x00, 0x9060000f), + X86_MATCH_HYGON_MODEL_STEP_UCODE(0x06, 0x01, 0x9061000f), + X86_MATCH_HYGON_MODEL_STEP_UCODE(0x10, 0x00, 0x91000004), + {} +}; + +static void fix_erratum_1386(struct cpuinfo_x86 *c) +{ + /* + * Work around Erratum 1386. The XSAVES instruction malfunctions in + * certain circumstances on affected Hygon processors. Clear the feature + * flag only on microcode revisions without the fix. + */ + if (x86_match_min_microcode_rev(erratum_1386_microcode)) + return; + + clear_cpu_cap(c, X86_FEATURE_XSAVES); +} + static void init_hygon(struct cpuinfo_x86 *c) { u64 vm_cr; early_init_hygon(c); + if (c->x86 == 0x18 && (c->x86_model <= 0x06 || c->x86_model == 0x10)) + fix_erratum_1386(c); set_cpu_cap(c, X86_FEATURE_REP_GOOD); From f8c89079cd90aa40c9ea9353221058a72c8100e2 Mon Sep 17 00:00:00 2001 From: Romain TISSERAND Date: Fri, 27 Nov 2026 03:00:29 +0100 Subject: [PATCH 1987/2102] ASoC: sun8i-codec-analog: Add the headphone inversion switches Bits 1 and 0 of PAEN_HP_CTRL (analog register 0x07; LTRNMUTE, RTLNMUTE) are "Left HPOUT Negative To Right HPOUT Mute" and "Right HPOUT Negative To Left HPOUT Mute" in the A23 and A33 user manuals and the V3s datasheet (0 = mute, the reset value). The driver defines them, but nothing can set them. The PocketGo S30 (A33) has a mono speaker amplifier bridged across HPL and HPR. With the same signal on both outputs it gets very little; setting bit 1 makes it clearly louder, which is what the board needs. Expose each bit as its own switch, "Headphone L to R Inversion Playback Switch" and "Headphone R to L Inversion Playback Switch". Both default to off (the reset value), so nothing changes for existing boards. Signed-off-by: Romain TISSERAND Link: https://patch.msgid.link/20261127020029.1618525-1-romain.tisserand@gmail.com Signed-off-by: Mark Brown --- sound/soc/sunxi/sun8i-codec-analog.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/sound/soc/sunxi/sun8i-codec-analog.c b/sound/soc/sunxi/sun8i-codec-analog.c index 3335855c6311e3..e24fd7bd0613f3 100644 --- a/sound/soc/sunxi/sun8i-codec-analog.c +++ b/sound/soc/sunxi/sun8i-codec-analog.c @@ -323,6 +323,13 @@ static const struct snd_kcontrol_new sun8i_codec_headphone_controls[] = { SUN8I_ADDA_DAC_PA_SRC, SUN8I_ADDA_DAC_PA_SRC_LHPPAMUTE, SUN8I_ADDA_DAC_PA_SRC_RHPPAMUTE, 1, 0), + /* inverted left to the right output, and the reverse */ + SOC_SINGLE("Headphone L to R Inversion Playback Switch", + SUN8I_ADDA_PAEN_HP_CTRL, + SUN8I_ADDA_PAEN_HP_CTRL_LTRNMUTE, 1, 0), + SOC_SINGLE("Headphone R to L Inversion Playback Switch", + SUN8I_ADDA_PAEN_HP_CTRL, + SUN8I_ADDA_PAEN_HP_CTRL_RTLNMUTE, 1, 0), }; static const char * const sun8i_codec_hp_src_enum_text[] = { From 02d3452bdd80cf645694110128db2ed67da96490 Mon Sep 17 00:00:00 2001 From: Alexei Starovoitov Date: Thu, 26 Nov 2026 03:31:14 +0000 Subject: [PATCH 1988/2102] bpf: Set the run context for async callbacks bpf_get_retval(), bpf_set_retval() and bpf_get_local_storage() use current->bpf_ctx, which the hook sets. bpf_getsockopt() and bpf_setsockopt() count on the hook to hold the socket lock. bpf_sys_bpf(), bpf_sys_close(), bpf_btf_find_by_name_kind() and bpf_kallsyms_lookup_name() use the credentials and the files of current. An async callback runs in a timer, in a kworker, in an RCU callback or in a task that the program has picked. Give async callbacks a run context of their own, and make these helpers fail in it. bpf_get_retval() returns 0. bpf_get_local_storage() cannot fail. Refuse async callbacks in a program with cgroup storage. Fixes: b00628b1c7d5 ("bpf: Introduce bpf timers.") Signed-off-by: Alexei Starovoitov Link: https://patch.msgid.link/20261126033114.4111944-1-alexei.starovoitov@gmail.com --- include/linux/bpf.h | 13 +++++++++++++ kernel/bpf/btf.c | 3 +++ kernel/bpf/cgroup.c | 4 +++- kernel/bpf/helpers.c | 35 ++++++++++++++++++----------------- kernel/bpf/syscall.c | 7 +++++-- kernel/bpf/verifier.c | 6 ++++++ net/core/filter.c | 14 ++++++++++---- net/ipv4/bpf_tcp_ops.c | 2 +- 8 files changed, 59 insertions(+), 25 deletions(-) diff --git a/include/linux/bpf.h b/include/linux/bpf.h index 3a5a0380304dc5..a6976776e90b6a 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -3440,6 +3440,14 @@ static inline bool has_current_bpf_ctx(void) return !!current->bpf_ctx; } +/* An async callback runs in no hook, and current is not the task that has armed it */ +extern struct bpf_run_ctx bpf_async_run_ctx; + +static inline bool bpf_in_async_cb(void) +{ + return current->bpf_ctx == &bpf_async_run_ctx; +} + void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog); void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data, @@ -3765,6 +3773,11 @@ static inline bool has_current_bpf_ctx(void) return false; } +static inline bool bpf_in_async_cb(void) +{ + return false; +} + static inline void bpf_prog_inc_misses_counter(struct bpf_prog *prog) { } diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c index 7b3291556e6ee7..23e8977164e79d 100644 --- a/kernel/bpf/btf.c +++ b/kernel/bpf/btf.c @@ -9703,6 +9703,9 @@ BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int if (name_sz <= 1 || name[name_sz - 1]) return -EINVAL; + if (bpf_in_async_cb()) + return -EPERM; + ret = bpf_find_btf_id(name, kind, &btf); if (ret > 0 && btf_is_module(btf)) { btf_obj_fd = __btf_new_fd(btf); diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index 1ff030f4314fb2..3bf3081bfa276b 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -2110,7 +2110,7 @@ BPF_CALL_0(bpf_get_retval) struct bpf_cg_run_ctx *ctx = container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx); - return ctx->retval; + return bpf_in_async_cb() ? 0 : ctx->retval; } const struct bpf_func_proto bpf_get_retval_proto = { @@ -2124,6 +2124,8 @@ BPF_CALL_1(bpf_set_retval, int, retval) struct bpf_cg_run_ctx *ctx = container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx); + if (bpf_in_async_cb()) + return -EOPNOTSUPP; ctx->retval = retval; return 0; } diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index 784674c5fddf9e..cebf9d8dfe36db 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -1219,12 +1219,25 @@ static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running); static void bpf_async_refcount_put(struct bpf_async_cb *cb); +struct bpf_run_ctx bpf_async_run_ctx; + +static void bpf_run_async_cb(struct bpf_prog *prog, bpf_callback_t callback_fn, + struct bpf_map *map, void *key, void *value) +{ + struct bpf_run_ctx *old_ctx = bpf_set_run_ctx(&bpf_async_run_ctx); + struct bpf_timed_may_goto saved; + + bpf_timed_may_goto_save(prog, &saved); + callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); + bpf_timed_may_goto_restore(prog, &saved); + bpf_reset_run_ctx(old_ctx); +} + static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer) { struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer); struct bpf_map *map = READ_ONCE(t->cb.map); struct bpf_prog *prog = READ_ONCE(t->cb.prog); - struct bpf_timed_may_goto saved; void *value = t->cb.value; bpf_callback_t callback_fn; void *key; @@ -1245,10 +1258,8 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer) key = map_key_from_value(map, value, &idx); - bpf_timed_may_goto_save(prog, &saved); - callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); /* The verifier checked that return value is zero. */ - bpf_timed_may_goto_restore(prog, &saved); + bpf_run_async_cb(prog, callback_fn, map, key, value); this_cpu_write(hrtimer_running, NULL); out: @@ -1259,7 +1270,6 @@ static void bpf_wq_work(struct work_struct *work) { struct bpf_work *w = container_of(work, struct bpf_work, work); struct bpf_async_cb *cb = &w->cb; - struct bpf_timed_may_goto saved; struct bpf_prog *prog; struct bpf_map *map; bpf_callback_t callback_fn; @@ -1282,9 +1292,7 @@ static void bpf_wq_work(struct work_struct *work) migrate_disable(); - bpf_timed_may_goto_save(prog, &saved); - callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); - bpf_timed_may_goto_restore(prog, &saved); + bpf_run_async_cb(prog, callback_fn, map, key, value); migrate_enable(); out: @@ -4624,7 +4632,6 @@ static void bpf_task_work_cancel(struct bpf_task_work_ctx *ctx, static void bpf_task_work_callback(struct callback_head *cb) { struct bpf_task_work_ctx *ctx = container_of(cb, struct bpf_task_work_ctx, work); - struct bpf_timed_may_goto saved; enum bpf_task_work_state state; u32 idx; void *key; @@ -4646,10 +4653,7 @@ static void bpf_task_work_callback(struct callback_head *cb) key = (void *)map_key_from_value(ctx->map, ctx->map_val, &idx); migrate_disable(); - bpf_timed_may_goto_save(ctx->prog, &saved); - ctx->callback_fn((u64)(long)ctx->map, (u64)(long)key, - (u64)(long)ctx->map_val, 0, 0); - bpf_timed_may_goto_restore(ctx->prog, &saved); + bpf_run_async_cb(ctx->prog, ctx->callback_fn, ctx->map, key, ctx->map_val); migrate_enable(); bpf_task_work_ctx_reset(ctx); @@ -4892,7 +4896,6 @@ static void bpf_rcu_run_callback(struct rcu_head *rcu) struct bpf_rcu_head_kern *rh = container_of(rcu, struct bpf_rcu_head_kern, rcu); bpf_callback_t callback_fn = rh->callback_fn; struct bpf_prog *prog = rh->prog; - struct bpf_timed_may_goto saved; struct bpf_map *map = rh->map; void *value, *key; u32 idx; @@ -4904,9 +4907,7 @@ static void bpf_rcu_run_callback(struct rcu_head *rcu) smp_store_release(&rh->armed, 0); rcu_read_lock_dont_migrate(); - bpf_timed_may_goto_save(prog, &saved); - callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); - bpf_timed_may_goto_restore(prog, &saved); + bpf_run_async_cb(prog, callback_fn, map, key, value); rcu_read_unlock_migrate(); bpf_prog_put(prog); diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c index 7e1085d6a67e86..91d078bb13d2d8 100644 --- a/kernel/bpf/syscall.c +++ b/kernel/bpf/syscall.c @@ -6618,6 +6618,9 @@ static bool syscall_prog_is_valid_access(int off, int size, BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size) { + if (bpf_in_async_cb()) + return -EPERM; + switch (cmd) { case BPF_MAP_CREATE: case BPF_MAP_DELETE_ELEM: @@ -6707,7 +6710,7 @@ BPF_CALL_1(bpf_sys_close, u32, fd) * This helper is allowed in the following callchain only: * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close */ - return close_fd(fd); + return bpf_in_async_cb() ? -EPERM : close_fd(fd); } static const struct bpf_func_proto bpf_sys_close_proto = { @@ -6727,7 +6730,7 @@ BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flag if (name_sz <= 1 || name[name_sz - 1]) return -EINVAL; - if (!bpf_dump_raw_ok(current_cred())) + if (bpf_in_async_cb() || !bpf_dump_raw_ok(current_cred())) return -EPERM; *res = kallsyms_lookup_name(name); diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 36441ed9f0eacb..85fec1f389277c 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -11494,6 +11494,12 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins struct bpf_verifier_state *async_cb; /* there is no real recursion here. timer and workqueue callbacks are async */ + /* there is no cgroup to take the storage from */ + if (env->prog->aux->cgroup_storage[BPF_CGROUP_STORAGE_SHARED] || + env->prog->aux->cgroup_storage[BPF_CGROUP_STORAGE_PERCPU]) { + verbose(env, "async callback in a program with cgroup storage\n"); + return -EINVAL; + } env->subprog_info[subprog].is_async_cb = true; async_cb = push_async_cb(env, env->subprog_info[subprog].start, insn_idx, subprog, diff --git a/net/core/filter.c b/net/core/filter.c index fb403e18a5d754..ea20fd2be65c01 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -5866,10 +5866,16 @@ static int sol_ipv6_sockopt(struct sock *sk, int optname, KERNEL_SOCKPTR(optval), *optlen); } +/* No hook has locked the socket for an async callback */ +static bool bpf_sockopt_allowed(const struct sock *sk) +{ + return sk && sk_fullsock(sk) && !bpf_in_async_cb(); +} + static int __bpf_setsockopt(struct sock *sk, int level, int optname, char *optval, int optlen) { - if (!sk || !sk_fullsock(sk)) + if (!bpf_sockopt_allowed(sk)) return -EINVAL; if (level == SOL_SOCKET) @@ -5892,7 +5898,7 @@ static bool is_locked_tcp_sock_ops(struct bpf_sock_ops_kern *bpf_sock) static int _bpf_setsockopt(struct sock *sk, int level, int optname, char *optval, int optlen) { - if (sk && sk_fullsock(sk)) + if (bpf_sockopt_allowed(sk)) sock_owned_by_me(sk); return __bpf_setsockopt(sk, level, optname, optval, optlen); } @@ -5902,7 +5908,7 @@ static int __bpf_getsockopt(struct sock *sk, int level, int optname, { int err, saved_optlen = optlen; - if (!sk || !sk_fullsock(sk)) { + if (!bpf_sockopt_allowed(sk)) { err = -EINVAL; goto done; } @@ -5929,7 +5935,7 @@ static int __bpf_getsockopt(struct sock *sk, int level, int optname, static int _bpf_getsockopt(struct sock *sk, int level, int optname, char *optval, int optlen) { - if (sk && sk_fullsock(sk)) + if (bpf_sockopt_allowed(sk)) sock_owned_by_me(sk); return __bpf_getsockopt(sk, level, optname, optval, optlen); } diff --git a/net/ipv4/bpf_tcp_ops.c b/net/ipv4/bpf_tcp_ops.c index 2ba73dd6c52cce..432ca078377105 100644 --- a/net/ipv4/bpf_tcp_ops.c +++ b/net/ipv4/bpf_tcp_ops.c @@ -207,7 +207,7 @@ BPF_CALL_0(bpf_tcp_ops_get_retval) * return value chained across the bpf_tcp_ops attached to the cgroup * and is this program's saved_run_ctx. */ - if (WARN_ON_ONCE(!ctx->saved_run_ctx)) + if (bpf_in_async_cb() || WARN_ON_ONCE(!ctx->saved_run_ctx)) return 0; return container_of(ctx->saved_run_ctx, struct bpf_tramp_run_ctx, From eca06bf5923526338291ef62501b359596d2ac9d Mon Sep 17 00:00:00 2001 From: Niklas Cassel Date: Thu, 26 Nov 2026 15:24:07 +0100 Subject: [PATCH 1989/2102] ata: libata-core: Disable LPM on ADATA SU650 with firmware XD0R3C0F ADATA SU650 SSDs with firmware XD0R3C0F drop off the bus with NCQ command timeouts when LPM is enabled. Disable LPM for this firmware only, as the SU650 has shipped with several different controllers. Reported-by: Mohammad Harsij Sani Closes: https://lore.kernel.org/linux-ide/CACeOiPg=3_wY40upkFVkWQvJouomoTF6Ro+eL_DimkunYVSUFQ@mail.gmail.com/ Cc: stable@vger.kernel.org Tested-by: Mohammad Harsij Sani Link: https://lore.kernel.org/r/20261126142406.2753290-2-cassel@kernel.org Signed-off-by: Niklas Cassel --- drivers/ata/libata-core.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/ata/libata-core.c b/drivers/ata/libata-core.c index 2a5ca1b9ee5c03..d234c83e046374 100644 --- a/drivers/ata/libata-core.c +++ b/drivers/ata/libata-core.c @@ -4305,6 +4305,7 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = { ATA_QUIRK_FIRMWARE_WARN }, /* ADATA devices with LPM issues. */ + { "ADATA SU650", "XD0R3C0F", ATA_QUIRK_NOLPM }, { "ADATA SU680", NULL, ATA_QUIRK_NOLPM }, /* Seagate disks with LPM issues */ From d630454310b39d33be6757d7784418cf44ab0601 Mon Sep 17 00:00:00 2001 From: Jiwoo Kim Date: Sat, 14 Nov 2026 15:22:49 +0900 Subject: [PATCH 1990/2102] perf/x86/intel: Don't allow extended register sampling for BTS events x86_pmu_hw_config() accepts extended (XMM) register sampling in REGS_USER for events without precise_ip, and the same goes for the SIMD register fields. The BTS event is such an event, and intel_pmu_bts_config() does not reject it. For a sample taken in the PMI handler, x86_pmu_update_perf_regs() copies the user registers into the per-CPU x86_user_regs, which is a struct x86_perf_regs. That is what perf_reg_value() and perf_simd_reg_value() expect: they use container_of() on the sampled struct pt_regs to reach the fields that follow it. intel_pmu_drain_bts_buffer() does not call x86_pmu_update_perf_regs(). It passes zeroed on-stack registers to perf_prepare_sample(), so the generic perf_sample_regs_user() takes the user registers from perf_get_regs_user(). That returns task_pt_regs(current), or on x86_64, when the buffer is drained from the PMI handler, a copy in the per-CPU nmi_user_regs, and neither is embedded in a struct x86_perf_regs. For a BTS event that requests these registers in REGS_USER, perf_reg_value() and perf_simd_reg_value() therefore read past the end of the struct pt_regs they are given, and use the words found there as pointers. REGS_INTR is not affected: BTS events must set exclude_kernel, and perf_sample_regs_intr() then reports no registers, as the zeroed ones are not user mode. BTS samples are built from the BTS buffer when it is drained, not from the registers of an interrupted context, so there is nothing meaningful to report in these registers for them. Reject extended and SIMD register sampling for BTS events in intel_pmu_bts_config(), as was the case before these registers could be sampled for events without precise_ip. This was found with an AI coding assistant, which also drafted this patch and its changelog. It has not been reproduced, and the change has only been compile-tested. Fixes: edd9aec51213 ("perf/x86: Enable XMM register sampling for REGS_USER case") Signed-off-by: Jiwoo Kim Signed-off-by: Peter Zijlstra (Intel) Reviewed-by: Dapeng Mi Link: https://patch.msgid.link/20261114062249.1301-1-arpe1618@gmail.com --- arch/x86/events/intel/core.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/arch/x86/events/intel/core.c b/arch/x86/events/intel/core.c index 0a34d674df590c..88a60d3e4eeb41 100644 --- a/arch/x86/events/intel/core.c +++ b/arch/x86/events/intel/core.c @@ -4778,6 +4778,16 @@ static int intel_pmu_bts_config(struct perf_event *event) if (attr->precise_ip) return -EOPNOTSUPP; + /* + * BTS samples are built from the BTS buffer when it is drained, + * not from the registers of an interrupted context, and + * intel_pmu_drain_bts_buffer() does not provide the registers in + * the struct x86_perf_regs layout that extended register sampling + * relies on. + */ + if (event_has_extended_regs(event) || event_has_simd_regs(event)) + return -EOPNOTSUPP; + /* disallow bts if conflicting events are present */ if (x86_add_exclusive(x86_lbr_exclusive_lbr)) return -EBUSY; From 67b34211a9eb103aba474bc179fab3dd2912f07e Mon Sep 17 00:00:00 2001 From: Jay Hilton Date: Tue, 17 Nov 2026 15:23:51 -0500 Subject: [PATCH 1991/2102] perf/core: Use the elapsed period for frequency-mode period adjustment In frequency mode, __perf_event_account_interrupt() estimates the event rate from hwc->last_period and the time since the previous overflow, and passes it to perf_adjust_period(). The PMU drivers re-arm the counter before they call perf_event_overflow(), and re-arming sets hwc->last_period to the period of the next interval. The estimator therefore divides the next period by the time the previous one took. While the period ramps up from its initial value, each period is much larger than the previous one, so the rate is overestimated by that ratio and the period overshoots its target. On an AMD EPYC 9655P running v7.3, sampling user-mode cycles at 11 Hz, the period jumped from 21.9M to 2.3G cycles, 5.6x the target, and the next sample arrived after 544 ms instead of 91 ms. When the overshoot exceeds 8x, the next tick's perf_adjust_period() resets period_left, and the cycles counted before the reset are not attributed to any sample (145M in that run). Intel and AMD IBS show the same overshoot. On Intel, intel_pmu_freq_start_period() hides it for the default hardware events, but not for raw events. Since commit 1734d98fbcce ("perf/arch: Record sample last_period before updating on the x86 and PowerPC platforms"), the PMU drivers record the elapsed period in data->period before re-arming. Pass that to the estimator instead of hwc->last_period. perf_event_account_interrupt(), which has no sample data, keeps using hwc->last_period. This fixes the overshoot reported in the Closes: thread. Tested on v7.3 with and without this patch, using the reproducer from the report and repeated runs (user mode, 11 Hz unless noted). Runs with the bug, i.e. a period over 2x the target or a sample whose period doesn't match the cycles counted: AMD EPYC 9655P (Zen5), bare metal v7.3 v7.3 + patch cycles 50/50 0/50 instructions 50/50 0/50 raw cycles 50/50 0/50 cycles, 4000 Hz 10/10 0/10 IBS (ibs_op, incl. kernel) 20/20 0/20 max period / target up to 7.0x 1.00x Intel Xeon Platinum 8468, bare metal v7.3 v7.3 + patch raw cycles (0x3c) 49/50 0/50 cycles 0/50 0/50 instructions 0/50 0/50 max period / target up to 6.8x 1.02x (On Intel, intel_pmu_freq_start_period() already keeps the default events close to the target, so only the raw event shows the bug.) With the patch, the period approaches the target from below, as the low-pass filter intends (9655P, target ~411M cycles): period counted dt(ms) 2371 1791 0.001 11854 11880 0.004 28341794 28341765 6.284 251213029 251213027 55.579 411087485 411087548 90.895 All perf_event_overflow() callers under arch/ and drivers/ in v7.3 initialize the sample data with the period recorded before re-arming, so data->period is the elapsed period on every path we checked. perf_event_account_interrupt() still passes hwc->last_period, and this patch doesn't change its callers. Two of them run after the counter has been re-armed, so they still feed the estimator the next period: perf_ibs_handle_irq() when it discards a sample (user/kernel mode filtering, the load-latency and fetch-latency filters, and the zero-RIP erratum workaround), and powerpc's record_and_restart() for an invalid SIAR. The Intel PEBS error path runs before re-arming and is fine. We haven't measured the IBS discard case; if it's worth fixing, those callers could pass the elapsed period too, in a follow-up. On kernels without 1734d98fbcce, x86_pmu_handle_irq() and handle_pmi_common() still put the next period in data->period, so a backport there also needs 1734d98fbcce. The original change was written by an AI coding assistant in Jay's session. This version, the changelog and these notes were prepared with an AI coding assistant; Jay and I reviewed them, and I ran the tests above. Fixes: abd50713944c ("perf: Reimplement frequency driven sampling") Signed-off-by: Jay Hilton Signed-off-by: Gregg Leventhal Signed-off-by: Ingo Molnar Acked-by: Peter Zijlstra Cc: Cc: James Clark Cc: Leo Yan Link: https://patch.msgid.link/20261117152351.1294050-1-gleventhal@janestreet.com Closes: https://lore.kernel.org/all/CAFN_u7G94CC_RGL1La66jX+jRKHSJdAB5PKkTRSWrUvqhM48oQ@mail.gmail.com/ Assisted-by: LLM --- kernel/events/core.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/kernel/events/core.c b/kernel/events/core.c index 08f0e0ffe50148..4ab3919ac78e90 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -10759,8 +10759,15 @@ void perf_report_aux_output_id(struct perf_event *event, u64 hw_id) } EXPORT_SYMBOL_GPL(perf_report_aux_output_id); +/* + * @period is the period of the interval that just ended. PMU drivers + * re-arm the counter before calling perf_event_overflow(), which sets + * hwc->last_period to the period of the next interval, so the overflow + * path passes the sample's period instead. + */ static int -__perf_event_account_interrupt(struct perf_event *event, int throttle) +__perf_event_account_interrupt(struct perf_event *event, int throttle, + u64 period) { struct hw_perf_event *hwc = &event->hw; int ret = 0; @@ -10788,7 +10795,7 @@ __perf_event_account_interrupt(struct perf_event *event, int throttle) hwc->freq_time_stamp = now; if (delta > 0 && delta < 2*TICK_NSEC) - perf_adjust_period(event, delta, hwc->last_period, true); + perf_adjust_period(event, delta, period, true); } return ret; @@ -10796,7 +10803,7 @@ __perf_event_account_interrupt(struct perf_event *event, int throttle) int perf_event_account_interrupt(struct perf_event *event) { - return __perf_event_account_interrupt(event, 1); + return __perf_event_account_interrupt(event, 1, event->hw.last_period); } static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs) @@ -10927,7 +10934,7 @@ static int __perf_event_overflow(struct perf_event *event, if (unlikely(!is_sampling_event(event))) return 0; - ret = __perf_event_account_interrupt(event, throttle); + ret = __perf_event_account_interrupt(event, throttle, data->period); if (event->attr.aux_pause) perf_event_aux_pause(event->aux_event, true); From cded8664815454cd923665318fda434ac7284fe7 Mon Sep 17 00:00:00 2001 From: Yuho Choi Date: Mon, 23 Nov 2026 06:01:55 +0000 Subject: [PATCH 1992/2102] iommu/hyperv: Don't free a paging domain the hypervisor did not delete hv_iommu_paging_domain_free() frees all page-table pages with pt_iommu_deinit() and only then asks the hypervisor to delete the device domain that points at them. If HVCALL_DELETE_DEVICE_DOMAIN fails, hv_delete_device_domain() only logs the error, returns the domain ID to the IDA, and the domain is freed anyway. The hypervisor then keeps a device domain whose page tables have been freed and can be reused for anything. The ID is also handed out again by the next paging domain allocation, while the hypervisor still has a domain with that ID. Delete the domain before freeing its page tables, and keep the ID, the page tables and the domain if the hypervisor fails to delete it. WARN when the delete fails, as the domain is then leaked. Fixes: 2690d4156b51 ("iommu/hyperv: Add para-virtualized IOMMU support for Hyper-V guest") Reviewed-by: Easwar Hariharan Reviewed-by: Jason Gunthorpe Reviewed-by: Yu Zhang Signed-off-by: Yuho Choi Signed-off-by: Joerg Roedel --- drivers/iommu/hyperv/hv-iommu-guest.c | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/drivers/iommu/hyperv/hv-iommu-guest.c b/drivers/iommu/hyperv/hv-iommu-guest.c index 9f4fa431509168..aa1db9db1e9733 100644 --- a/drivers/iommu/hyperv/hv-iommu-guest.c +++ b/drivers/iommu/hyperv/hv-iommu-guest.c @@ -107,7 +107,7 @@ static int hv_create_device_domain(struct hv_iommu_domain *hv_domain) return hv_result_to_errno(status); } -static void hv_delete_device_domain(struct hv_iommu_domain *hv_domain) +static int hv_delete_device_domain(struct hv_iommu_domain *hv_domain) { u64 status; unsigned long flags; @@ -122,11 +122,15 @@ static void hv_delete_device_domain(struct hv_iommu_domain *hv_domain) local_irq_restore(flags); - if (!hv_result_success(status)) - hv_status_err(status, "HVCALL_DELETE_DEVICE_DOMAIN failed\n"); + /* If the domain still exists, its ID cannot be reused */ + if (WARN(!hv_result_success(status), + "HVCALL_DELETE_DEVICE_DOMAIN failed: %#llx (%s)\n", + status, hv_result_to_string(status))) + return hv_result_to_errno(status); ida_free(&hv_domain->hv_iommu->domain_ids, hv_domain->device_domain.domain_id.id); + return 0; } static int @@ -466,11 +470,16 @@ static void hv_iommu_paging_domain_free(struct iommu_domain *domain) { struct hv_iommu_domain *hv_domain = to_hv_iommu_domain(domain); + /* + * If the hypervisor still has the domain, it may still use its page + * tables, so leak them. + */ + if (hv_delete_device_domain(hv_domain)) + return; + /* Free all remaining mappings */ pt_iommu_deinit(&hv_domain->pt_iommu); - hv_delete_device_domain(hv_domain); - kfree(hv_domain); } From ea82a3d0bbd5008fb36a483e1a4ab9d673725877 Mon Sep 17 00:00:00 2001 From: Yuho Choi Date: Mon, 23 Nov 2026 06:01:56 +0000 Subject: [PATCH 1993/2102] iommu/hyperv: Keep a new domain's page tables if it cannot be deleted When hv_iommu_domain_alloc_paging() fails to configure a new device domain, hv_create_configure_device_domain() deletes the domain again, and the caller then frees the page tables with pt_iommu_deinit(). The page tables are freed even if the delete fails and the hypervisor still has the domain. The current Hyper-V implementation does not adopt the page table root when HVCALL_CONFIGURE_DEVICE_DOMAIN fails, so the page tables are not referenced in this case today. This change is defensive: it avoids relying on that while the hypervisor still has the domain. Create and configure the domain in hv_iommu_domain_alloc_paging() itself, and leak the page tables and the domain when the delete fails, as hv_iommu_paging_domain_free() does. Reported-by: Jacob Pan Closes: https://lore.kernel.org/all/20261105141427.00005946@linux.microsoft.com/ Reviewed-by: Jason Gunthorpe Reviewed-by: Easwar Hariharan Signed-off-by: Yuho Choi Reviewed-by: Yu Zhang Signed-off-by: Joerg Roedel --- drivers/iommu/hyperv/hv-iommu-guest.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/drivers/iommu/hyperv/hv-iommu-guest.c b/drivers/iommu/hyperv/hv-iommu-guest.c index aa1db9db1e9733..0110a1529a2361 100644 --- a/drivers/iommu/hyperv/hv-iommu-guest.c +++ b/drivers/iommu/hyperv/hv-iommu-guest.c @@ -540,10 +540,23 @@ static struct iommu_domain *hv_iommu_domain_alloc_paging(struct device *dev) settings.page_table_root = pt_info.gcr3_pt; settings.flags.first_stage_paging_mode = pt_info.levels == 5; - ret = hv_create_configure_device_domain(hv_domain, &settings); + ret = hv_create_device_domain(hv_domain); if (ret) goto err_pt_deinit; + ret = hv_configure_device_domain(hv_domain, &settings); + if (ret) { + /* + * The current hypervisor does not adopt the page table root + * when the configure call fails. Still, keep the page tables + * while it has the domain, as hv_iommu_paging_domain_free() + * does. + */ + if (hv_delete_device_domain(hv_domain)) + return ERR_PTR(ret); + goto err_pt_deinit; + } + return &hv_domain->domain; err_pt_deinit: From 0008c5d5030c4bddad186be9c5c3959f21012a66 Mon Sep 17 00:00:00 2001 From: Daniel Golle Date: Sun, 25 Oct 2026 13:27:08 +0000 Subject: [PATCH 1994/2102] iommu/vsi: keep the runtime PM callbacks without PM_SLEEP The runtime PM operations are handed to the driver core through pm_sleep_ptr(), which is NULL unless CONFIG_PM_SLEEP is set. Without system sleep support the IOMMU has no runtime PM callbacks at all: its clocks are never enabled by the driver, the page table is not restored when the power domain comes back, and iommu->enable stays set while genpd powers the domain off. The TLB flush issued from vsi_iommu_map() then writes to the unpowered IOMMU, and the first buffer allocation of the RK3588 AV1 decoder ends in an asynchronous SError. Use pm_ptr(), which keeps the operations whenever CONFIG_PM is set. Fixes: 917ace84b770 ("iommu: Add verisilicon IOMMU driver") Signed-off-by: Daniel Golle Reviewed-by: Benjamin Gaignard Signed-off-by: Joerg Roedel --- drivers/iommu/vsi-iommu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/iommu/vsi-iommu.c b/drivers/iommu/vsi-iommu.c index 0633fe82d44366..4a25dc65c8e79c 100644 --- a/drivers/iommu/vsi-iommu.c +++ b/drivers/iommu/vsi-iommu.c @@ -780,7 +780,7 @@ static struct platform_driver rockchip_vsi_iommu_driver = { .driver = { .name = "vsi_iommu", .of_match_table = vsi_iommu_dt_ids, - .pm = pm_sleep_ptr(&vsi_iommu_pm_ops), + .pm = pm_ptr(&vsi_iommu_pm_ops), .suppress_bind_attrs = true, }, }; From 4ec193a567bf7f09a7a4b3eae4087ab1571f304e Mon Sep 17 00:00:00 2001 From: Arun Iyengar Date: Fri, 13 Nov 2026 20:04:36 +0000 Subject: [PATCH 1995/2102] iommu/vsi: Don't leak a runtime PM reference in the TLB flush pm_runtime_get() takes a usage reference even when it fails, e.g. with -EINPROGRESS while a resume runs, and vsi_iommu_flush_tlb() then skips the put. The IOMMU then never suspends again. Flush only an active IOMMU and flush the TLB when the IOMMU is enabled, which covers resume. Fixes: 917ace84b770 ("iommu: Add verisilicon IOMMU driver") Signed-off-by: Arun Iyengar Reviewed-by: Benjamin Gaignard Signed-off-by: Joerg Roedel --- drivers/iommu/vsi-iommu.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/drivers/iommu/vsi-iommu.c b/drivers/iommu/vsi-iommu.c index 4a25dc65c8e79c..81f51ccf9fc88a 100644 --- a/drivers/iommu/vsi-iommu.c +++ b/drivers/iommu/vsi-iommu.c @@ -369,7 +369,8 @@ static void vsi_iommu_flush_tlb(struct iommu_domain *domain) struct vsi_iommu *iommu; list_for_each_entry(iommu, &vsi_domain->iommus, node) { - if (pm_runtime_get(iommu->dev) < 0) + /* A suspended IOMMU is flushed when it resumes */ + if (pm_runtime_get_if_active(iommu->dev) <= 0) continue; spin_lock(&iommu->lock); @@ -545,6 +546,8 @@ static void vsi_iommu_enable(struct vsi_iommu *iommu, struct iommu_domain *domai writel(VSI_MMU_OUT_OF_BOUND, iommu->regs + VSI_MMU_CONFIG1_BASE); writel(VSI_MMU_BIT_ENABLE, iommu->regs + VSI_MMU_AHB_EXCEPTION_BASE); writel(VSI_MMU_BIT_ENABLE, iommu->regs + VSI_MMU_AHB_CONTROL_BASE); + writel(VSI_MMU_BIT_FLUSH, iommu->regs + VSI_MMU_FLUSH_BASE); + writel(0, iommu->regs + VSI_MMU_FLUSH_BASE); iommu->enable = true; } @@ -564,8 +567,6 @@ static int vsi_iommu_attach_device(struct iommu_domain *domain, spin_lock(&iommu->lock); vsi_iommu_enable(iommu, domain); - writel(VSI_MMU_BIT_FLUSH, iommu->regs + VSI_MMU_FLUSH_BASE); - writel(0, iommu->regs + VSI_MMU_FLUSH_BASE); list_del_init(&iommu->node); list_add_tail(&iommu->node, &vsi_domain->iommus); From 923278dea97476c58ace9f5b7d8429a185ce439a Mon Sep 17 00:00:00 2001 From: Arun Iyengar Date: Fri, 13 Nov 2026 20:04:37 +0000 Subject: [PATCH 1996/2102] iommu/vsi: Don't resume the IOMMU in its interrupt handler The interrupt handler calls pm_runtime_resume_and_get(), which can sleep, in hard IRQ context. Handle the interrupt only if the IOMMU is active. Fixes: 917ace84b770 ("iommu: Add verisilicon IOMMU driver") Signed-off-by: Arun Iyengar Reviewed-by: Benjamin Gaignard Signed-off-by: Joerg Roedel --- drivers/iommu/vsi-iommu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/iommu/vsi-iommu.c b/drivers/iommu/vsi-iommu.c index 81f51ccf9fc88a..694c421cfdaa62 100644 --- a/drivers/iommu/vsi-iommu.c +++ b/drivers/iommu/vsi-iommu.c @@ -196,7 +196,7 @@ static irqreturn_t vsi_iommu_irq(int irq, void *dev_id) dma_addr_t iova; u32 status; - if (pm_runtime_resume_and_get(iommu->dev) < 0) + if (pm_runtime_get_if_active(iommu->dev) <= 0) return IRQ_NONE; spin_lock_irqsave(&iommu->lock, flags); From 2f2e6b0890b772e02418491556baa91ef8bde547 Mon Sep 17 00:00:00 2001 From: Arun Iyengar Date: Fri, 13 Nov 2026 20:06:43 +0000 Subject: [PATCH 1997/2102] iommu/vsi: Don't write the enable register on suspend Benjamin Gaignard pointed out that, per the IOMMU documentation, the IOMMU can't be disabled once enabled. Drop the write on suspend: resume reprograms the IOMMU anyway. Suggested-by: Benjamin Gaignard Signed-off-by: Arun Iyengar Reviewed-by: Benjamin Gaignard Signed-off-by: Joerg Roedel --- drivers/iommu/vsi-iommu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/iommu/vsi-iommu.c b/drivers/iommu/vsi-iommu.c index 694c421cfdaa62..1a9f41d4d17dd3 100644 --- a/drivers/iommu/vsi-iommu.c +++ b/drivers/iommu/vsi-iommu.c @@ -741,7 +741,7 @@ static int __maybe_unused vsi_iommu_suspend(struct device *dev) { struct vsi_iommu *iommu = dev_get_drvdata(dev); - vsi_iommu_disable(iommu); + iommu->enable = false; clk_bulk_disable(iommu->num_clocks, iommu->clocks); From 9cd3aa3d2bff8e797866ebbc3e9ac86b66fbe294 Mon Sep 17 00:00:00 2001 From: Arun Iyengar Date: Sat, 14 Nov 2026 00:14:25 +0000 Subject: [PATCH 1998/2102] iommu/vsi: Don't use the identity domain as a paging domain vsi_identity_domain is a bare struct iommu_domain, but identity attach and resume pass it to to_vsi_domain() and take the lock of that vsi_iommu_domain, which is memory past the static domain. Identity attach also unlinks the IOMMU from its old domain's list without that domain's lock. Take the old paging domain's lock to unlink the IOMMU, and only the IOMMU lock otherwise. Resume touches neither the page tables nor the domain's list, so it needs only the IOMMU lock. Fixes: 917ace84b770 ("iommu: Add verisilicon IOMMU driver") Reported-by: Sashiko Closes: https://sashiko.dev/#/patchset/20261113-vsi-iommu-pm-ref-v1-0-fd917eebdf18@gmail.com?part=1 Cc: stable@vger.kernel.org Signed-off-by: Arun Iyengar Reviewed-by: Benjamin Gaignard Signed-off-by: Joerg Roedel --- drivers/iommu/vsi-iommu.c | 45 ++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/drivers/iommu/vsi-iommu.c b/drivers/iommu/vsi-iommu.c index 1a9f41d4d17dd3..2e1413b8f3b784 100644 --- a/drivers/iommu/vsi-iommu.c +++ b/drivers/iommu/vsi-iommu.c @@ -497,31 +497,42 @@ static void vsi_iommu_disable(struct vsi_iommu *iommu) iommu->enable = false; } +/* Take the IOMMU off the list of its paging domain, if it has one. */ +static void vsi_iommu_list_del(struct vsi_iommu *iommu) +{ + struct vsi_iommu_domain *vsi_domain; + unsigned long flags; + + if (!iommu->domain || iommu->domain == &vsi_identity_domain) + return; + + vsi_domain = to_vsi_domain(iommu->domain); + spin_lock_irqsave(&vsi_domain->lock, flags); + list_del_init(&iommu->node); + spin_unlock_irqrestore(&vsi_domain->lock, flags); +} + static int vsi_iommu_identity_attach(struct iommu_domain *domain, struct device *dev, struct iommu_domain *old) { struct vsi_iommu *iommu = dev_iommu_priv_get(dev); - struct vsi_iommu_domain *vsi_domain = to_vsi_domain(domain); unsigned long flags; int ret; + if (iommu->domain == domain) + return 0; + ret = pm_runtime_resume_and_get(iommu->dev); if (ret < 0) return ret; - spin_lock_irqsave(&vsi_domain->lock, flags); - spin_lock(&iommu->lock); - if (iommu->domain == domain) - goto unlock; + vsi_iommu_list_del(iommu); + spin_lock_irqsave(&iommu->lock, flags); vsi_iommu_disable(iommu); - list_del_init(&iommu->node); - iommu->domain = domain; + spin_unlock_irqrestore(&iommu->lock, flags); -unlock: - spin_unlock(&iommu->lock); - spin_unlock_irqrestore(&vsi_domain->lock, flags); pm_runtime_put_autosuspend(iommu->dev); return 0; } @@ -537,11 +548,12 @@ static struct iommu_domain vsi_identity_domain = { static void vsi_iommu_enable(struct vsi_iommu *iommu, struct iommu_domain *domain) { - struct vsi_iommu_domain *vsi_domain = to_vsi_domain(domain); + struct vsi_iommu_domain *vsi_domain; if (domain == &vsi_identity_domain) return; + vsi_domain = to_vsi_domain(domain); writel(vsi_domain->pta_dma, iommu->regs + VSI_MMU_AHB_TLB_ARRAY_BASE_L_BASE); writel(VSI_MMU_OUT_OF_BOUND, iommu->regs + VSI_MMU_CONFIG1_BASE); writel(VSI_MMU_BIT_ENABLE, iommu->regs + VSI_MMU_AHB_EXCEPTION_BASE); @@ -758,15 +770,10 @@ static int __maybe_unused vsi_iommu_resume(struct device *dev) if (ret) return ret; - if (iommu->domain) { - struct vsi_iommu_domain *vsi_domain = to_vsi_domain(iommu->domain); - - spin_lock_irqsave(&vsi_domain->lock, flags); - spin_lock(&iommu->lock); + spin_lock_irqsave(&iommu->lock, flags); + if (iommu->domain) vsi_iommu_enable(iommu, iommu->domain); - spin_unlock(&iommu->lock); - spin_unlock_irqrestore(&vsi_domain->lock, flags); - } + spin_unlock_irqrestore(&iommu->lock, flags); return 0; } From ecceb7dba63cb63ca920f87bb43afaaf3a56c618 Mon Sep 17 00:00:00 2001 From: Arun Iyengar Date: Sat, 14 Nov 2026 00:14:26 +0000 Subject: [PATCH 1999/2102] iommu/vsi: Unlink the IOMMU from its old domain under that domain's lock Attaching a paging domain moves iommu->node to the new domain's list holding only the new domain's lock. A concurrent map or unmap on the old domain walks the old list in vsi_iommu_flush_tlb() and can follow the moved node into the new list. Unlink the IOMMU under the old domain's lock first. Fixes: 917ace84b770 ("iommu: Add verisilicon IOMMU driver") Reported-by: Sashiko Closes: https://lore.kernel.org/all/sashiko-outbox-206639@kernel.org/ Cc: stable@vger.kernel.org Signed-off-by: Arun Iyengar Reviewed-by: Benjamin Gaignard Signed-off-by: Joerg Roedel --- drivers/iommu/vsi-iommu.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/iommu/vsi-iommu.c b/drivers/iommu/vsi-iommu.c index 2e1413b8f3b784..734b867e192cb3 100644 --- a/drivers/iommu/vsi-iommu.c +++ b/drivers/iommu/vsi-iommu.c @@ -575,12 +575,13 @@ static int vsi_iommu_attach_device(struct iommu_domain *domain, if (ret < 0) return ret; + vsi_iommu_list_del(iommu); + spin_lock_irqsave(&vsi_domain->lock, flags); spin_lock(&iommu->lock); vsi_iommu_enable(iommu, domain); - list_del_init(&iommu->node); list_add_tail(&iommu->node, &vsi_domain->iommus); iommu->domain = domain; From 807bf13083be85673963f57cb9375626e0b06f13 Mon Sep 17 00:00:00 2001 From: Arun Iyengar Date: Sat, 14 Nov 2026 00:14:27 +0000 Subject: [PATCH 2000/2102] iommu/vsi: Unprepare the clocks when getting the IRQ fails vsi_iommu_probe() returns without clk_bulk_unprepare() when platform_get_irq() fails. Fixes: 917ace84b770 ("iommu: Add verisilicon IOMMU driver") Signed-off-by: Arun Iyengar Reviewed-by: Benjamin Gaignard Signed-off-by: Joerg Roedel --- drivers/iommu/vsi-iommu.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/iommu/vsi-iommu.c b/drivers/iommu/vsi-iommu.c index 734b867e192cb3..f0963e0406c7e2 100644 --- a/drivers/iommu/vsi-iommu.c +++ b/drivers/iommu/vsi-iommu.c @@ -707,8 +707,10 @@ static int vsi_iommu_probe(struct platform_device *pdev) return err; iommu->irq = platform_get_irq(pdev, 0); - if (iommu->irq < 0) - return iommu->irq; + if (iommu->irq < 0) { + err = iommu->irq; + goto err_unprepare_clocks; + } err = devm_request_irq(iommu->dev, iommu->irq, vsi_iommu_irq, IRQF_SHARED, dev_name(dev), iommu); From 10bcc637f7a657725dd8bbcc2b30d027acee6f2d Mon Sep 17 00:00:00 2001 From: Vasant Hegde Date: Fri, 20 Nov 2026 15:23:08 +0000 Subject: [PATCH 2001/2102] iommu/amd: Mark v2 page tables incoherent on Cezanne DMA fails on Cezanne (family 19h, model 50h) when a device is placed in an IOMMU v2 paging domain due to missing coherency setting in IOMMU HW. The IOMMU walks v2 page tables without observing CPU writes still held in the cache. v1 PTEs have a Force Coherent bit, which the driver sets on every entry, but the v2 format has no equivalent bit, so v2 walks are not kept coherent. Set PT_FEAT_DMA_INCOHERENT for v2 domains on this CPU so the generic page-table code clflushes table memory before the IOMMU reads it. Link: https://lore.kernel.org/linux-iommu/CACOV87VBwH+R3eSBEOuz8hk7OaT63+A9m6ipPSW5wt1VhHMFPg@mail.gmail.com/ Cc: Mario Limonciello (AMD) Cc: Alex Deucher Tested-by: Akshata V Unkal Co-developed-by: Nathan Blomquist Signed-off-by: Nathan Blomquist Signed-off-by: Vasant Hegde Reviewed-by: Jason Gunthorpe Tested-by: Nathan Blomquist Closes: https://gitlab.freedesktop.org/drm/amd/-/work_items/6081 Reviewed-by: Mario Limonciello (AMD) Signed-off-by: Joerg Roedel --- drivers/iommu/amd/iommu.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/drivers/iommu/amd/iommu.c b/drivers/iommu/amd/iommu.c index 41ee4ad1dcf826..0f04013f590d44 100644 --- a/drivers/iommu/amd/iommu.c +++ b/drivers/iommu/amd/iommu.c @@ -2792,6 +2792,15 @@ static const struct iommu_domain_ops amdv2_ops = { .enforce_cache_coherency = amd_iommu_enforce_cache_coherency, }; +/* + * Force a clflush on Cezanne (family 19h, model 50h) when the v2 + * page-table is enabled. + */ +static bool amd_iommu_force_incoherent(void) +{ + return boot_cpu_data.x86 == 0x19 && boot_cpu_data.x86_model == 0x50; +} + static struct iommu_domain *amd_iommu_domain_alloc_paging_v2(struct device *dev, u32 flags) { @@ -2810,6 +2819,13 @@ static struct iommu_domain *amd_iommu_domain_alloc_paging_v2(struct device *dev, domain->iommu.nid = dev_to_node(dev); cfg.common.features = BIT(PT_FEAT_X86_64_AMD_ENCRYPT_TABLES); + + if (amd_iommu_force_incoherent()) { + cfg.common.features |= BIT(PT_FEAT_DMA_INCOHERENT); + /* pt_iommu_init() rejects DMA_INCOHERENT without a device */ + domain->iommu.iommu_device = dev; + } + if (amd_iommu_np_cache) cfg.common.features |= BIT(PT_FEAT_FLUSH_RANGE_NO_GAPS); else From fbf1f115ba411a5b60629bb8ba6ed6f8306e5d78 Mon Sep 17 00:00:00 2001 From: Richard Fitzgerald Date: Fri, 27 Nov 2026 09:46:17 +0000 Subject: [PATCH 2002/2102] ASoC: cs35l56: Volume/Mute/Posture controls don't need to wait for dsp_work Remove the special get/put handlers for the Volume/Mute/Posture controls. These are not necessary now. The original reason for the special get/put handlers was that the downloaded firmware can patch the registers to non-default values. To avoid the regmap cache getting out-of-sync with the actual register value the regmap content was fixed-up at the end of cs35l56_dsp_work(). This meant that control get/put had to wait for cs35l56_dsp_work() to complete. This is now unnecessary since commit df4167d658d4 ("ASoC: cs35l56: Patch soft registers to defaults") removed this fix-up code, and instead used the regmap patch to set volume/mute/posture registers to a default of zero. When the amp is rebooted after a firmware download, cs35l56_system_reset() puts regmap in cache-only and this is only released in cs35l56_init() after the amp has rebooted. The regcache_sync() in cs35l56_init() will overwrite the volume/mute/posture registers with the values from the regmap patch and then write out the content of the cache. That means it is safe for the Volume/Mute/Posture controls to read/write regmap any time. Signed-off-by: Richard Fitzgerald Link: https://patch.msgid.link/20261127094617.1932934-1-rf@opensource.cirrus.com Signed-off-by: Mark Brown --- sound/soc/codecs/cs35l56.c | 72 +++++++++++--------------------------- 1 file changed, 20 insertions(+), 52 deletions(-) diff --git a/sound/soc/codecs/cs35l56.c b/sound/soc/codecs/cs35l56.c index 439063084d4b12..0ea8c69d93fc11 100644 --- a/sound/soc/codecs/cs35l56.c +++ b/sound/soc/codecs/cs35l56.c @@ -103,26 +103,6 @@ static void cs35l56_wait_dsp_ready(struct cs35l56_private *cs35l56) flush_work(&cs35l56->dsp_work); } -static int cs35l56_dspwait_get_volsw(struct snd_kcontrol *kcontrol, - struct snd_ctl_elem_value *ucontrol) -{ - struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); - struct cs35l56_private *cs35l56 = snd_soc_component_get_drvdata(component); - - cs35l56_wait_dsp_ready(cs35l56); - return snd_soc_get_volsw(kcontrol, ucontrol); -} - -static int cs35l56_dspwait_put_volsw(struct snd_kcontrol *kcontrol, - struct snd_ctl_elem_value *ucontrol) -{ - struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); - struct cs35l56_private *cs35l56 = snd_soc_component_get_drvdata(component); - - cs35l56_wait_dsp_ready(cs35l56); - return snd_soc_put_volsw(kcontrol, ucontrol); -} - static DECLARE_TLV_DB_SCALE(vol_tlv, -10000, 25, 0); static SOC_ENUM_SINGLE_DECL(cs35l56_cal_set_status_enum, SND_SOC_NOPM, 0, @@ -138,44 +118,32 @@ static int cs35l56_cal_set_status_ctl_get(struct snd_kcontrol *kcontrol, } static const struct snd_kcontrol_new cs35l56_controls[] = { - SOC_SINGLE_EXT("Speaker Switch", - CS35L56_MAIN_RENDER_USER_MUTE, 0, 1, 1, - cs35l56_dspwait_get_volsw, cs35l56_dspwait_put_volsw), - SOC_SINGLE_S_EXT_TLV("Speaker Volume", - CS35L56_MAIN_RENDER_USER_VOLUME, - CS35L56_MAIN_RENDER_USER_VOLUME_SHIFT, - CS35L56_MAIN_RENDER_USER_VOLUME_MIN, - CS35L56_MAIN_RENDER_USER_VOLUME_MAX, - CS35L56_MAIN_RENDER_USER_VOLUME_SIGNBIT, - 0, - cs35l56_dspwait_get_volsw, - cs35l56_dspwait_put_volsw, - vol_tlv), - SOC_SINGLE_EXT("Posture Number", CS35L56_MAIN_POSTURE_NUMBER, - 0, 255, 0, - cs35l56_dspwait_get_volsw, cs35l56_dspwait_put_volsw), + SOC_SINGLE("Speaker Switch", CS35L56_MAIN_RENDER_USER_MUTE, 0, 1, 1), + SOC_SINGLE_S_TLV("Speaker Volume", + CS35L56_MAIN_RENDER_USER_VOLUME, + CS35L56_MAIN_RENDER_USER_VOLUME_SHIFT, + CS35L56_MAIN_RENDER_USER_VOLUME_MIN, + CS35L56_MAIN_RENDER_USER_VOLUME_MAX, + CS35L56_MAIN_RENDER_USER_VOLUME_SIGNBIT, + 0, + vol_tlv), + SOC_SINGLE("Posture Number", CS35L56_MAIN_POSTURE_NUMBER, 0, 255, 0), SOC_ENUM_EXT_ACC("CAL_SET_STATUS", cs35l56_cal_set_status_enum, cs35l56_cal_set_status_ctl_get, NULL, SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE), }; static const struct snd_kcontrol_new cs35l63_controls[] = { - SOC_SINGLE_EXT("Speaker Switch", - CS35L63_MAIN_RENDER_USER_MUTE, 0, 1, 1, - cs35l56_dspwait_get_volsw, cs35l56_dspwait_put_volsw), - SOC_SINGLE_S_EXT_TLV("Speaker Volume", - CS35L63_MAIN_RENDER_USER_VOLUME, - CS35L56_MAIN_RENDER_USER_VOLUME_SHIFT, - CS35L56_MAIN_RENDER_USER_VOLUME_MIN, - CS35L56_MAIN_RENDER_USER_VOLUME_MAX, - CS35L56_MAIN_RENDER_USER_VOLUME_SIGNBIT, - 0, - cs35l56_dspwait_get_volsw, - cs35l56_dspwait_put_volsw, - vol_tlv), - SOC_SINGLE_EXT("Posture Number", CS35L63_MAIN_POSTURE_NUMBER, - 0, 255, 0, - cs35l56_dspwait_get_volsw, cs35l56_dspwait_put_volsw), + SOC_SINGLE("Speaker Switch", CS35L63_MAIN_RENDER_USER_MUTE, 0, 1, 1), + SOC_SINGLE_S_TLV("Speaker Volume", + CS35L63_MAIN_RENDER_USER_VOLUME, + CS35L56_MAIN_RENDER_USER_VOLUME_SHIFT, + CS35L56_MAIN_RENDER_USER_VOLUME_MIN, + CS35L56_MAIN_RENDER_USER_VOLUME_MAX, + CS35L56_MAIN_RENDER_USER_VOLUME_SIGNBIT, + 0, + vol_tlv), + SOC_SINGLE("Posture Number", CS35L63_MAIN_POSTURE_NUMBER, 0, 255, 0), SOC_ENUM_EXT_ACC("CAL_SET_STATUS", cs35l56_cal_set_status_enum, cs35l56_cal_set_status_ctl_get, NULL, SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE), From 6534c2bedf46fd2e8bf05c2de9af91fafc5f0de0 Mon Sep 17 00:00:00 2001 From: Richard Fitzgerald Date: Fri, 27 Nov 2026 11:40:36 +0000 Subject: [PATCH 2003/2102] firmware: cs_dsp: Resize members of cs_dsp_coeff_ctl to save bytes Reduce the size of some members in struct cs_dsp_coeff_ctl to the size of the data they are storing. On an x86_64 build this saves 8 bytes per control. - The subname_len string can never be more than 16-bits. In V0 and V1 firmwares it is a 256-character array, and in later firmwares it is an 8-bit field. (In any case it is impractical to have a control name >65535 characters long.) - Control type and flags are 16-bit values in the firmware. - Type is relocated adjacent to subname_len to avoid introducing alignment padding bytes after subname_len The ctl_type and flags fields in struct cs_dsp_coeff_parsed_coeff have been changed to match these widths. The arguments to cs_dsp_create_control() have been changed to the same types so that consistent widths are used. Signed-off-by: Richard Fitzgerald Link: https://patch.msgid.link/20261127114037.2010271-2-rf@opensource.cirrus.com Signed-off-by: Mark Brown --- drivers/firmware/cirrus/cs_dsp.c | 15 +++++++++------ include/linux/firmware/cirrus/cs_dsp.h | 8 ++++---- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/drivers/firmware/cirrus/cs_dsp.c b/drivers/firmware/cirrus/cs_dsp.c index abf9196db883c2..b9e4b9283df103 100644 --- a/drivers/firmware/cirrus/cs_dsp.c +++ b/drivers/firmware/cirrus/cs_dsp.c @@ -1044,8 +1044,8 @@ static void cs_dsp_free_ctl_blk(struct cs_dsp_coeff_ctl *ctl) static int cs_dsp_create_control(struct cs_dsp *dsp, const struct cs_dsp_alg_region *alg_region, unsigned int offset, unsigned int len, - const char *subname, unsigned int subname_len, - unsigned int flags, unsigned int type) + const char *subname, u16 subname_len, + u16 flags, u16 type) { struct cs_dsp_coeff_ctl *ctl; int ret; @@ -1162,9 +1162,9 @@ struct cs_dsp_coeff_parsed_coeff { int offset; int mem_type; const u8 *name; - int name_len; - unsigned int ctl_type; - int flags; + u16 name_len; + u16 ctl_type; + u16 flags; int len; }; @@ -1312,6 +1312,9 @@ static int cs_dsp_coeff_parse_coeff(struct cs_dsp *dsp, blk->offset = le16_to_cpu(raw->hdr.offset); blk->mem_type = le16_to_cpu(raw->hdr.type); + static_assert(sizeof(blk->ctl_type) >= sizeof(raw->ctl_type)); + static_assert(sizeof(blk->flags) >= sizeof(raw->flags)); + switch (dsp->wmfw_ver) { case 0: case 1: @@ -1319,7 +1322,7 @@ static int cs_dsp_coeff_parse_coeff(struct cs_dsp *dsp, return -EOVERFLOW; blk->name = raw->name; - blk->name_len = strnlen(raw->name, ARRAY_SIZE(raw->name)); + blk->name_len = (u16)strnlen(raw->name, ARRAY_SIZE(raw->name)); blk->ctl_type = le16_to_cpu(raw->ctl_type); blk->flags = le16_to_cpu(raw->flags); blk->len = le32_to_cpu(raw->len); diff --git a/include/linux/firmware/cirrus/cs_dsp.h b/include/linux/firmware/cirrus/cs_dsp.h index 6aa1e1b2b4a57f..16542bdce5c45d 100644 --- a/include/linux/firmware/cirrus/cs_dsp.h +++ b/include/linux/firmware/cirrus/cs_dsp.h @@ -84,9 +84,9 @@ struct cs_dsp_alg_region { * @fw_name: Name of the firmware * @subname: Name of the control parsed from the WMFW * @subname_len: Length of subname + * @type: One of the WMFW_CTL_TYPE_ control types defined in wmfw.h * @offset: Offset of control within alg_region in words * @len: Length of the cached value in bytes - * @type: One of the WMFW_CTL_TYPE_ control types defined in wmfw.h * @flags: Bitfield of WMFW_CTL_FLAG_ control flags defined in wmfw.h * @set: Flag indicating the value has been written by the user * @enabled: Flag indicating whether control is enabled @@ -100,11 +100,11 @@ struct cs_dsp_coeff_ctl { const char *fw_name; /* Subname is needed to match with firmware */ const char *subname; - unsigned int subname_len; + u16 subname_len; + u16 type; unsigned int offset; unsigned int len; - unsigned int type; - unsigned int flags; + u16 flags; unsigned int set:1; unsigned int enabled:1; struct cs_dsp_alg_region alg_region; From 3bbfb78a99fc1a9ffc6ef62116fbc22fdf3dc83d Mon Sep 17 00:00:00 2001 From: Richard Fitzgerald Date: Fri, 27 Nov 2026 11:40:37 +0000 Subject: [PATCH 2004/2102] firmware: cs_dsp: Store control cache data in struct cs_dsp_coeff_ctl Make the 'cache' member of struct cs_dsp_coeff_ctl a variable-length array instead of a pointer to another block of memory. This needs a small update to one KUnit test case to correctly check the expected length of the allocated memory block. The code originally allocated a block of memory for the data cache and stored a pointer to that cache in struct cs_dsp_coeff_ctl. But most controls are only 4 bytes, so this was wasteful on memory. On 64-bit machines at least 12 bytes were used to store 4 bytes of data, and there were extra wasted bytes from alignment and kmalloc block sizes. The data can be stored directly in the struct cs_dsp_coeff_ctl in a variable-length array. On an x86_64 build: Before: total total sizeof(*ctl) ksize(ctl) ctl->len ksize(ctl->cache) requested allocated 88 96 4 8 92 104 After: 80 96 4 84 96 Signed-off-by: Richard Fitzgerald Link: https://patch.msgid.link/20261127114037.2010271-3-rf@opensource.cirrus.com Signed-off-by: Mark Brown --- drivers/firmware/cirrus/cs_dsp.c | 19 ++++++------------- .../cirrus/test/cs_dsp_test_control_cache.c | 5 +++-- include/linux/firmware/cirrus/cs_dsp.h | 5 +++-- 3 files changed, 12 insertions(+), 17 deletions(-) diff --git a/drivers/firmware/cirrus/cs_dsp.c b/drivers/firmware/cirrus/cs_dsp.c index b9e4b9283df103..bb8e7c70ea4968 100644 --- a/drivers/firmware/cirrus/cs_dsp.c +++ b/drivers/firmware/cirrus/cs_dsp.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -824,7 +825,7 @@ int cs_dsp_coeff_write_ctrl(struct cs_dsp_coeff_ctl *ctl, if (ctl->flags & WMFW_CTL_FLAG_VOLATILE) { ret = -EPERM; - } else if (buf != ctl->cache) { + } else if (buf != &ctl->cache[0]) { if (memcmp(ctl->cache + off * sizeof(u32), buf, len)) memcpy(ctl->cache + off * sizeof(u32), buf, len); else @@ -933,7 +934,7 @@ int cs_dsp_coeff_read_ctrl(struct cs_dsp_coeff_ctl *ctl, if (!ctl->flags && ctl->enabled && ctl->dsp->running && !ctl->dsp->hibernating) ret = cs_dsp_coeff_read_ctrl_raw(ctl, 0, ctl->cache, ctl->len); - if (buf != ctl->cache) + if (buf != &ctl->cache[0]) memcpy(buf, ctl->cache + off * sizeof(u32), len); } @@ -1036,9 +1037,8 @@ static void cs_dsp_signal_event_controls(struct cs_dsp *dsp, static void cs_dsp_free_ctl_blk(struct cs_dsp_coeff_ctl *ctl) { - kvfree(ctl->cache); kfree(ctl->subname); - kfree(ctl); + kvfree(ctl); } static int cs_dsp_create_control(struct cs_dsp *dsp, @@ -1064,7 +1064,7 @@ static int cs_dsp_create_control(struct cs_dsp *dsp, } } - ctl = kzalloc_obj(*ctl); + ctl = kvzalloc_flex(*ctl, cache, len); if (!ctl) return -ENOMEM; @@ -1086,11 +1086,6 @@ static int cs_dsp_create_control(struct cs_dsp *dsp, ctl->type = type; ctl->offset = offset; ctl->len = len; - ctl->cache = kvzalloc(ctl->len, GFP_KERNEL); - if (!ctl->cache) { - ret = -ENOMEM; - goto err_ctl_subname; - } list_add(&ctl->list, &dsp->ctl_list); @@ -1104,11 +1099,9 @@ static int cs_dsp_create_control(struct cs_dsp *dsp, err_list_del: list_del(&ctl->list); - kvfree(ctl->cache); -err_ctl_subname: kfree(ctl->subname); err_ctl: - kfree(ctl); + kvfree(ctl); return ret; } diff --git a/drivers/firmware/cirrus/test/cs_dsp_test_control_cache.c b/drivers/firmware/cirrus/test/cs_dsp_test_control_cache.c index b03cd7c37f6e40..7a9f939fcf6f56 100644 --- a/drivers/firmware/cirrus/test/cs_dsp_test_control_cache.c +++ b/drivers/firmware/cirrus/test/cs_dsp_test_control_cache.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -186,9 +187,9 @@ static void cs_dsp_ctl_v2_cache_alloc(struct kunit *test) KUNIT_EXPECT_EQ(test, list_count_nodes(&dsp->ctl_list), num_ctls); - /* Check that the block allocated for the cache is large enough */ + /* Check that the allocation holds the control and its cache */ list_for_each_entry(ctl, &dsp->ctl_list, list) - KUNIT_EXPECT_GE(test, ksize(ctl->cache), ctl->len); + KUNIT_EXPECT_GE(test, ksize(ctl), struct_size(ctl, cache, ctl->len)); } /* diff --git a/include/linux/firmware/cirrus/cs_dsp.h b/include/linux/firmware/cirrus/cs_dsp.h index 16542bdce5c45d..b2492c55660cfa 100644 --- a/include/linux/firmware/cirrus/cs_dsp.h +++ b/include/linux/firmware/cirrus/cs_dsp.h @@ -80,7 +80,6 @@ struct cs_dsp_alg_region { * struct cs_dsp_coeff_ctl - Describes a coefficient control * @list: List node for internal use * @dsp: DSP instance associated with this control - * @cache: Cached value of the control * @fw_name: Name of the firmware * @subname: Name of the control parsed from the WMFW * @subname_len: Length of subname @@ -92,11 +91,11 @@ struct cs_dsp_alg_region { * @enabled: Flag indicating whether control is enabled * @alg_region: Logical region associated with this control * @priv: For use by the client + * @cache: Cached value of the control */ struct cs_dsp_coeff_ctl { struct list_head list; struct cs_dsp *dsp; - void *cache __counted_by_ptr(len); const char *fw_name; /* Subname is needed to match with firmware */ const char *subname; @@ -110,6 +109,8 @@ struct cs_dsp_coeff_ctl { struct cs_dsp_alg_region alg_region; void *priv; + + u8 cache[] __counted_by(len); }; struct cs_dsp_ops; From 016f2e469760a9a7bb44d70c7a0c0bb732efb1fb Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Thu, 26 Nov 2026 06:32:25 +0000 Subject: [PATCH 2005/2102] ALSA: vmaster: Restore follower values on put failure Restore the cached follower values when the underlying put callback fails. Otherwise, a retry with the same value may be skipped because the cache already contains the requested value. Fixes: 3b0a5f22d464 ("[ALSA] Add virtual master control helpers") Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261126063225.3166-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/core/vmaster.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/sound/core/vmaster.c b/sound/core/vmaster.c index f43144ba279788..f5cc11eba25de0 100644 --- a/sound/core/vmaster.c +++ b/sound/core/vmaster.c @@ -193,7 +193,7 @@ static int follower_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct link_follower *follower = snd_kcontrol_chip(kcontrol); - int err, ch, changed = 0; + int err, ch, changed = 0, old_vals[2]; err = follower_init(follower); if (err < 0) @@ -204,6 +204,10 @@ static int follower_put(struct snd_kcontrol *kcontrol, return -EINVAL; } + /* save the original cached values */ + for (ch = 0; ch < follower->info.count; ch++) + old_vals[ch] = follower->vals[ch]; + for (ch = 0; ch < follower->info.count; ch++) { if (follower->vals[ch] != ucontrol->value.integer.value[ch]) { changed = 1; @@ -213,8 +217,13 @@ static int follower_put(struct snd_kcontrol *kcontrol, if (!changed) return 0; err = follower_put_val(follower, ucontrol); - if (err < 0) + if (err < 0) { + /* restore cached values on failure */ + for (ch = 0; ch < follower->info.count; ch++) + follower->vals[ch] = old_vals[ch]; return err; + } + return 1; } From 97f08ceaf5bf34653a30e2270b2a9265e4e5257c Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Thu, 26 Nov 2026 06:53:10 +0000 Subject: [PATCH 2006/2102] ALSA: vmaster: Check follower callback errors Check the return values of follower_get_val() and follower_put_val() in sync_followers(). Stop synchronization and return the error when either callback fails. Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261126065310.3451-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/core/vmaster.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/sound/core/vmaster.c b/sound/core/vmaster.c index f5cc11eba25de0..de4f1c14c53099 100644 --- a/sound/core/vmaster.c +++ b/sound/core/vmaster.c @@ -354,17 +354,27 @@ static int sync_followers(struct link_master *master, int old_val, int new_val) struct link_follower *follower; struct snd_ctl_elem_value *uval __free(kfree) = kmalloc_obj(*uval); + int err; if (!uval) return -ENOMEM; list_for_each_entry(follower, &master->followers, list) { master->val = old_val; uval->id = follower->follower.id; - follower_get_val(follower, uval); + err = follower_get_val(follower, uval); + if (err < 0) + goto error; + master->val = new_val; - follower_put_val(follower, uval); + err = follower_put_val(follower, uval); + if (err < 0) + goto error; } return 0; + +error: + master->val = old_val; + return err; } static int master_put(struct snd_kcontrol *kcontrol, From 3f94e237af0949c8daf6c175bf8b94a0ff6f92ee Mon Sep 17 00:00:00 2001 From: Haoxiang Li Date: Fri, 27 Nov 2026 12:55:09 +0800 Subject: [PATCH 2007/2102] sound/oss/dmasound: unregister OSS devices on init failure dmasound_init() registers dsp, special sound and mixer device but never unregisters if something fails. Unregister the devices in the error handling path so a failed initialization leaves no stale OSS registrations. Also fix some code styles. Signed-off-by: Haoxiang Li Link: https://patch.msgid.link/20261127045509.333969-1-haoxiang_li2024@163.com Signed-off-by: Takashi Iwai --- sound/oss/dmasound/dmasound_core.c | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/sound/oss/dmasound/dmasound_core.c b/sound/oss/dmasound/dmasound_core.c index e80f730d08038f..15e4682e6cf89e 100644 --- a/sound/oss/dmasound/dmasound_core.c +++ b/sound/oss/dmasound/dmasound_core.c @@ -1377,18 +1377,29 @@ int dmasound_init(void) /* Set up sound queue, /dev/audio and /dev/dsp. */ /* Set default settings. */ - if ((res = sq_init()) < 0) - return res ; + res = sq_init(); + if (res < 0) + return res; /* Set up /dev/sndstat. */ - if ((res = state_init()) < 0) - return res ; + res = state_init(); + if (res < 0) { + if (sq_unit >= 0) + unregister_sound_dsp(sq_unit); + return res; + } /* Set up /dev/mixer. */ mixer_init(); if (!dmasound.mach.irqinit()) { printk(KERN_ERR "DMA sound driver: Interrupt initialization failed\n"); + if (mixer_unit >= 0) + unregister_sound_mixer(mixer_unit); + if (state_unit >= 0) + unregister_sound_special(state_unit); + if (sq_unit >= 0) + unregister_sound_dsp(sq_unit); return -ENODEV; } irq_installed = 1; From 872a2dc476c335bf9c6da7632a2ed4aa73753001 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:01 +0100 Subject: [PATCH 2008/2102] docs: security-bugs: reorganize the document without changing its contents The document has grown incrementally over time and new rules were added where they fit at the moment, each time trying to minimize the affected context in order to ease reviews, resulting in information being spread over several sections (e.g. the rules about when to Cc the security team appear in three different places), which makes it hard to follow for reporters and hard to update. Moreover it probably encourages reporters to stop reading once they think they found the information they were looking for. This patch attempts to reorganize the document to make it both easier to discover, and to ease future updates. It only moves existing paragraphs, without changing the wording: - we now start with what qualifies as a security bug (important to permit the user to stop reading if sufficient); - report preparation is now more natural, with responsible use of AI just after "preparing your report". - "identifying contacts" was split into 1) finding the maintainers, and 2) when to Cc the security team, with a part of what was earlier in "sending the report" about the Cc rules. - the "one message per issue" paragraph was moved to "Sending the report"; - a new section "after sending the report" covers the parapgraph about a reporter's expected availability in a more visible way, and could later receive parts related to coordinated disclosure if relevant. Using "git show --color-moved=dimmed-zebra" helps here, and shows that aside section titles, nothing was added nor removed. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-2-w@1wt.eu> --- Documentation/process/security-bugs.rst | 241 ++++++++++++------------ 1 file changed, 125 insertions(+), 116 deletions(-) diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index c7dfecc87764c0..3575af5274f04b 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -7,6 +7,42 @@ Linux kernel developers take security very seriously. As such, we'd like to know when a security bug is found so that it can be fixed and disclosed as quickly as possible. +What qualifies as a security bug +-------------------------------- + +It is important that most bugs are handled publicly so as to involve the widest +possible audience and find the best solution. By nature, bugs that are handled +in closed discussions between a small set of participants are less likely to +produce the best possible fix (e.g., risk of missing valid use cases, limited +testing abilities). + +It turns out that the majority of the bugs reported via the security team are +just regular bugs that have been improperly qualified as security bugs due to +a lack of awareness of the Linux kernel's threat model, as described in +Documentation/process/threat-model.rst, and ought to have been sent through +the normal channels described in Documentation/admin-guide/reporting-issues.rst +instead. + +The security list exists for urgent bugs that grant an attacker a capability +they are not supposed to have on a correctly configured production system, and +can be easily exploited, representing an imminent threat to many users. Before +reporting, consider whether the issue actually crosses a trust boundary on such +a system. + +**If you resorted to AI assistance to identify a bug, you must treat it as +public**. While you may have valid reasons to believe it is not, the security +team's experience shows that bugs discovered this way systematically surface +simultaneously across multiple researchers, often on the same day. In this +case, do not publicly share a reproducer, as this could cause unintended harm; +just mention that one is available and maintainers might ask for it privately +if they need it. + +If you are unsure whether an issue qualifies, err on the side of reporting +privately: the security team would rather triage a borderline report than miss +a real vulnerability. Reporting ordinary bugs to the security list, however, +does not make them move faster and consumes triage capacity that other reports +need. + Preparing your report --------------------- @@ -70,107 +106,6 @@ In addition, the following information are highly desirable: the issue appear. It is useful to share them, as they can be helpful to keep end users protected during the time it takes them to apply the fix. -What qualifies as a security bug --------------------------------- - -It is important that most bugs are handled publicly so as to involve the widest -possible audience and find the best solution. By nature, bugs that are handled -in closed discussions between a small set of participants are less likely to -produce the best possible fix (e.g., risk of missing valid use cases, limited -testing abilities). - -It turns out that the majority of the bugs reported via the security team are -just regular bugs that have been improperly qualified as security bugs due to -a lack of awareness of the Linux kernel's threat model, as described in -Documentation/process/threat-model.rst, and ought to have been sent through -the normal channels described in Documentation/admin-guide/reporting-issues.rst -instead. - -The security list exists for urgent bugs that grant an attacker a capability -they are not supposed to have on a correctly configured production system, and -can be easily exploited, representing an imminent threat to many users. Before -reporting, consider whether the issue actually crosses a trust boundary on such -a system. - -**If you resorted to AI assistance to identify a bug, you must treat it as -public**. While you may have valid reasons to believe it is not, the security -team's experience shows that bugs discovered this way systematically surface -simultaneously across multiple researchers, often on the same day. In this -case, do not publicly share a reproducer, as this could cause unintended harm; -just mention that one is available and maintainers might ask for it privately -if they need it. - -If you are unsure whether an issue qualifies, err on the side of reporting -privately: the security team would rather triage a borderline report than miss -a real vulnerability. Reporting ordinary bugs to the security list, however, -does not make them move faster and consumes triage capacity that other reports -need. - -Identifying contacts --------------------- - -The most effective way to report a security bug is to send it directly to the -affected subsystem's maintainers and Cc: the Linux kernel security team. Do -not send it to a public list at this stage, unless you have good reasons to -consider the issue as being public or trivial to discover (e.g. result of a -widely available automated vulnerability scanning tool that can be repeated by -anyone, or use of AI-based tools). - -If you're sending a report for issues affecting multiple parts in the kernel, -even if they're fairly similar issues, please send individual messages (think -that maintainers will not all work on the issues at the same time). The only -exception is when an issue concerns closely related parts maintained by the -exact same subset of maintainers, and these parts are expected to be fixed all -at once by the same commit, then it may be acceptable to report them at once. - -One difficulty for most first-time reporters is to figure the right list of -recipients to send a report to. In the Linux kernel, all official maintainers -are trusted, so the consequences of accidentally including the wrong maintainer -are essentially a bit more noise for that person, i.e. nothing dramatic. As -such, a suitable method to figure the list of maintainers (which kernel -security officers use) is to rely on the get_maintainer.pl script, tuned to -only report maintainers. This script, when passed a file name, will look for -its path in the MAINTAINERS file to figure a hierarchical list of relevant -maintainers. Calling it a first time with the finest level of filtering will -most of the time return a short list of this specific file's maintainers:: - - $ ./scripts/get_maintainer.pl --no-l --no-r --pattern-depth 1 \ - drivers/example.c - Developer One (maintainer:example driver) - Developer Two (maintainer:example driver) - -These two maintainers should then receive the message. If the command does not -return anything, it means the affected file is part of a wider subsystem, so we -should be less specific:: - - $ ./scripts/get_maintainer.pl --no-l --no-r drivers/example.c - Developer One (maintainer:example subsystem) - Developer Two (maintainer:example subsystem) - Developer Three (maintainer:example subsystem [GENERAL]) - Developer Four (maintainer:example subsystem [GENERAL]) - -Here, picking the first, most specific ones, is sufficient. When the list is -long, it is possible to produce a comma-delimited e-mail address list on a -single line suitable for use in the To: field of a mailer like this:: - - $ ./scripts/get_maintainer.pl --no-tree --no-l --no-r --no-n --m \ - --no-git-fallback --no-substatus --no-rolestats --no-multiline \ - --pattern-depth 1 drivers/example.c - dev1@example.com, dev2@example.org - -or this for the wider list:: - - $ ./scripts/get_maintainer.pl --no-tree --no-l --no-r --no-n --m \ - --no-git-fallback --no-substatus --no-rolestats --no-multiline \ - drivers/example.c - dev1@example.com, dev2@example.org, dev3@example.com, dev4@example.org - -If at this point you're still facing difficulties spotting the right -maintainers, **and only in this case**, it's possible to send your report to -the Linux kernel security team only. Your message will be triaged, and you -will receive instructions about whom to contact, if needed. Your message may -equally be forwarded as-is to the relevant maintainers. - Responsible use of AI to find bugs ---------------------------------- @@ -239,7 +174,7 @@ identify the maintainers with get_maintainer.pl. On top of that procedure, the AI assistant **MUST**: 1. Prepare a plain-text report explaining the problem. It must contain the - four items listed at the top of this file as absolutely necessary: the + four items listed above as absolutely necessary: the affected version or commit ID noted while following the procedure above, the description of the problem, the reproducer or its status, and the triggering conditions. @@ -251,22 +186,69 @@ On top of that procedure, the AI assistant **MUST**: A more detailed process is covered at https://github.com/masoncl/kres.git. -Sending the report ------------------- +Identifying contacts +-------------------- -Reports are to be sent over e-mail exclusively. Please use a working e-mail -address, preferably the same that you want to appear in ``Reported-by`` tags -if any. If unsure, send your report to yourself first. +The most effective way to report a security bug is to send it directly to the +affected subsystem's maintainers and Cc: the Linux kernel security team. Do +not send it to a public list at this stage, unless you have good reasons to +consider the issue as being public or trivial to discover (e.g. result of a +widely available automated vulnerability scanning tool that can be repeated by +anyone, or use of AI-based tools). -The security team and maintainers almost always require additional -information beyond what was initially provided in a report and rely on -active and efficient collaboration with the reporter to perform further -testing (e.g., verifying versions, configuration options, mitigations, or -patches). Before contacting the security team, the reporter must ensure -they are available to explain their findings, engage in discussions, and -run additional tests. Reports where the reporter does not respond promptly -or cannot effectively discuss their findings may be abandoned if the -communication does not quickly improve. +Finding the maintainers +~~~~~~~~~~~~~~~~~~~~~~~ + +One difficulty for most first-time reporters is to figure the right list of +recipients to send a report to. In the Linux kernel, all official maintainers +are trusted, so the consequences of accidentally including the wrong maintainer +are essentially a bit more noise for that person, i.e. nothing dramatic. As +such, a suitable method to figure the list of maintainers (which kernel +security officers use) is to rely on the get_maintainer.pl script, tuned to +only report maintainers. This script, when passed a file name, will look for +its path in the MAINTAINERS file to figure a hierarchical list of relevant +maintainers. Calling it a first time with the finest level of filtering will +most of the time return a short list of this specific file's maintainers:: + + $ ./scripts/get_maintainer.pl --no-l --no-r --pattern-depth 1 \ + drivers/example.c + Developer One (maintainer:example driver) + Developer Two (maintainer:example driver) + +These two maintainers should then receive the message. If the command does not +return anything, it means the affected file is part of a wider subsystem, so we +should be less specific:: + + $ ./scripts/get_maintainer.pl --no-l --no-r drivers/example.c + Developer One (maintainer:example subsystem) + Developer Two (maintainer:example subsystem) + Developer Three (maintainer:example subsystem [GENERAL]) + Developer Four (maintainer:example subsystem [GENERAL]) + +Here, picking the first, most specific ones, is sufficient. When the list is +long, it is possible to produce a comma-delimited e-mail address list on a +single line suitable for use in the To: field of a mailer like this:: + + $ ./scripts/get_maintainer.pl --no-tree --no-l --no-r --no-n --m \ + --no-git-fallback --no-substatus --no-rolestats --no-multiline \ + --pattern-depth 1 drivers/example.c + dev1@example.com, dev2@example.org + +or this for the wider list:: + + $ ./scripts/get_maintainer.pl --no-tree --no-l --no-r --no-n --m \ + --no-git-fallback --no-substatus --no-rolestats --no-multiline \ + drivers/example.c + dev1@example.com, dev2@example.org, dev3@example.com, dev4@example.org + +If at this point you're still facing difficulties spotting the right +maintainers, **and only in this case**, it's possible to send your report to +the Linux kernel security team only. Your message will be triaged, and you +will receive instructions about whom to contact, if needed. Your message may +equally be forwarded as-is to the relevant maintainers. + +Copying the security team +~~~~~~~~~~~~~~~~~~~~~~~~~ The report must be sent to maintainers. If there are two or fewer recipients in your message, you must also always Cc: the Linux kernel @@ -283,6 +265,20 @@ who will help verify the bug report and assist developers working on a fix. It is possible that the security team will bring in extra help from area maintainers to understand and fix the security vulnerability. +Sending the report +------------------ + +Reports are to be sent over e-mail exclusively. Please use a working e-mail +address, preferably the same that you want to appear in ``Reported-by`` tags +if any. If unsure, send your report to yourself first. + +If you're sending a report for issues affecting multiple parts in the kernel, +even if they're fairly similar issues, please send individual messages (think +that maintainers will not all work on the issues at the same time). The only +exception is when an issue concerns closely related parts maintained by the +exact same subset of maintainers, and these parts are expected to be fixed all +at once by the same commit, then it may be acceptable to report them at once. + Please send **plain text** emails without attachments where possible. It is much harder to have a context-quoted discussion about a complex issue if all the details are hidden away in attachments. Think of it like a @@ -296,6 +292,19 @@ security report. Note that some mailers tend to mangle formatting of plain text by default, please consult Documentation/process/email-clients.rst for more info. +After sending the report +------------------------ + +The security team and maintainers almost always require additional +information beyond what was initially provided in a report and rely on +active and efficient collaboration with the reporter to perform further +testing (e.g., verifying versions, configuration options, mitigations, or +patches). Before contacting the security team, the reporter must ensure +they are available to explain their findings, engage in discussions, and +run additional tests. Reports where the reporter does not respond promptly +or cannot effectively discuss their findings may be abandoned if the +communication does not quickly improve. + Disclosure and embargoed information ------------------------------------ From cfedbbbf1315a2a2a57d3e824e838d80e7807deb Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:02 +0100 Subject: [PATCH 2009/2102] docs: security-bugs: clarify when to Cc the security team The rules indicating when to Cc the security team were a bit confusing, because "Identifying contacts" said to always Cc it, while the details said it was only needed for small teams or for the first few reports, and nothing said what to do when the impact is unclear or when posting to a public list. Let's try to clarify this a little bit now that the rules have evolved a few times, while not changing what already works fine nor from what is being properly practiced. It also clarifies the "within a week" by insisting not to ask before that delay. This patch changes the unconditional Cc at the top to "when needed, see below", and groups all cases in a single list that's easier to verify for the reporter. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-3-w@1wt.eu> --- Documentation/process/security-bugs.rst | 48 +++++++++++++++++-------- 1 file changed, 34 insertions(+), 14 deletions(-) diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index 3575af5274f04b..157e84c0d12a5a 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -190,11 +190,11 @@ Identifying contacts -------------------- The most effective way to report a security bug is to send it directly to the -affected subsystem's maintainers and Cc: the Linux kernel security team. Do -not send it to a public list at this stage, unless you have good reasons to -consider the issue as being public or trivial to discover (e.g. result of a -widely available automated vulnerability scanning tool that can be repeated by -anyone, or use of AI-based tools). +affected subsystem's maintainers, and to Cc: the Linux kernel security team +when needed (see below). Do not send it to a public list at this stage, +unless you have good reasons to consider the issue as being public or trivial +to discover (e.g. result of a widely available automated vulnerability +scanning tool that can be repeated by anyone, or use of AI-based tools). Finding the maintainers ~~~~~~~~~~~~~~~~~~~~~~~ @@ -250,15 +250,35 @@ equally be forwarded as-is to the relevant maintainers. Copying the security team ~~~~~~~~~~~~~~~~~~~~~~~~~ -The report must be sent to maintainers. If there are two or fewer -recipients in your message, you must also always Cc: the Linux kernel -security team who will ensure the message is delivered to the proper -people, and will be able to assist small maintainer teams with processes -they may not be familiar with. For larger teams, Cc: the Linux kernel -security team for your first few reports or when seeking specific help, -such as when resending a message which got no response within a week. -Once you have become comfortable with the process for a few reports, it is -no longer necessary to Cc: the security list when sending to large teams. +The report must be sent to maintainers. You must also Cc: the Linux kernel +security team in any of the following cases: + + * it is your first report: many first reports are incomplete, too long, too + strong, difficult to handle, and put a lot of pressure on maintainers. The + security team will help with the process and with the qualification of the + issue. Note that this rule also applies if you were asked to fix or adjust + a previous submission; + + * there are two or fewer maintainers among the recipients: the security + team will ensure the message is delivered to the proper people, and + will be able to assist small maintainer teams with processes they may + not be familiar with; + + * the maintainers could not be clearly identified (see above); + + * the impact of the issue is uncertain and needs to be qualified. In this + case, your must clearly state upfront that you are seeking help to qualify + this impact, and you will need to share any information you have; + + * you are seeking specific help, such as when resending a message which got + no response within a week (and please do not ask for feedback before such + a delay, some subsystems have a long report queue, and some maintainers can + only read them in their spare time). + +Otherwise, when a report of clear impact is sent to a larger team of clearly +identified maintainers, it is not necessary to Cc: the security list. Never +Cc: the security list on a message sent to a public list. + The Linux kernel security team can be contacted by email at . This is a private list of security officers who will help verify the bug report and assist developers working on a fix. From 0ae4224d9c1afb2c0b1486cb6e26f40ddf5b0ef9 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:03 +0100 Subject: [PATCH 2010/2102] docs: security-bugs: never publish reproducers of bugs with a security impact Some bugs are outside the threat model because their exploitation requires very specific conditions (dedicated network link, crafted device, crafted file system image only root may mount), but they may still have a security impact for a few users, and a CVE may be assigned later. These are handled publicly as regular bugs, but their reproducers and exploits must never be shared on public lists since that could put the few exposed users at risk. The documentation was never very clear about this and a few reporters were put in embarrassing situations while trying to follow the process, because threat-model says to check reporting-issues which asks for public repros. There shouldn't be any ambiguity because reporters reading these files already come with the idea of reporting a security issue. Let's clarify this point in threat-model.rst and point to this from security-bugs.rst. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-4-w@1wt.eu> --- Documentation/process/security-bugs.rst | 14 +++++++++----- Documentation/process/threat-model.rst | 16 +++++++++++++++- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index 157e84c0d12a5a..27442592671703 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -21,7 +21,9 @@ just regular bugs that have been improperly qualified as security bugs due to a lack of awareness of the Linux kernel's threat model, as described in Documentation/process/threat-model.rst, and ought to have been sent through the normal channels described in Documentation/admin-guide/reporting-issues.rst -instead. +instead. Note that when such a bug may still have a security impact for some +users, its reproducer and any exploit must never be posted publicly; only the +fix is (see Documentation/process/threat-model.rst). The security list exists for urgent bugs that grant an attacker a capability they are not supposed to have on a correctly configured production system, and @@ -142,8 +144,8 @@ handle: Please always ensure your tool provides one and **test it thoroughly**. If the reproducer does not work, or if the tool cannot produce one, the validity of the report should be seriously questioned. Note that since the - report will be posted to a public list, the reproducer should only be - shared upon maintainers' request. + report will be posted to a public list, the reproducer must only be + shared privately with the maintainers. * **Propose a Fix**: Many AI tools are actually better at writing code than evaluating it. Please ask your tool to propose a fix and **test it** before @@ -162,7 +164,7 @@ likely that usage has declined and exposed users are virtually non-existent (e.g., drivers for very old hardware, obsolete filesystems). In such cases, there is no need to consume a maintainer's time with an unimportant report. If the issue is clearly trivial and publicly discoverable, you should report it -directly to the public mailing lists. +directly to the public mailing lists, without the reproducer. At the very least, when using an AI assistant to find and report bugs, make the assistant read this file and threat-model.rst before proceeding, and have it @@ -194,7 +196,9 @@ affected subsystem's maintainers, and to Cc: the Linux kernel security team when needed (see below). Do not send it to a public list at this stage, unless you have good reasons to consider the issue as being public or trivial to discover (e.g. result of a widely available automated vulnerability -scanning tool that can be repeated by anyone, or use of AI-based tools). +scanning tool that can be repeated by anyone, or use of AI-based tools). Even +in this case, never post a reproducer or an exploit to a public list; only +maintainers need it, and publishing it could put some users in trouble. Finding the maintainers ~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/Documentation/process/threat-model.rst b/Documentation/process/threat-model.rst index 04e5df6a6f78b8..4c61f196fa84d1 100644 --- a/Documentation/process/threat-model.rst +++ b/Documentation/process/threat-model.rst @@ -105,7 +105,21 @@ In the Linux kernel's threat model, the following classes of problems are **NOT** considered Linux Kernel vulnerabilities. However, when it is believed that the kernel could do better, they should be reported, so that they can be reviewed and fixed where reasonably possible, but they will be handled as any -regular bug: +regular bug. + +Some of these bugs may still have a security impact for a few users, for +example when their exploitation requires a dedicated network link, a crafted +device, or a crafted file system image that only root may mount. For the vast +majority of users the impact is null, and such isolated bugs do not represent a +target worth writing an exploit for, which is why they are handled publicly +(a CVE may still be assigned later by the :doc:`CVE team `). However, +publishing a reproducer or an exploit could put the few exposed users at risk. +For such bugs, the fix is sent publicly like any regular fix, with a commit +message that does not detail how to exploit the bug, while the reproducer and +any exploit are only shared privately with the maintainers and are never posted +to public lists. + +The following classes of problems are not considered vulnerabilities: * **Configuration**: From 8a61aa662b23a86935f6c6e5ba45d0d4d6f77831 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:04 +0100 Subject: [PATCH 2011/2102] docs: threat-model: clarify the case of automatically mounted file systems Bugs triggered by crafted file system images are among the most frequently reported non-security issues, often with the argument that some desktop environments automatically mount removable media without checking them. Let's state that automatic mounting of unchecked file systems does not change the analysis: an automounter is expected to check a file system before mounting it, otherwise it is at fault, and if the check does not detect the issue, the file system checker is at fault (this doesn't void the need to handle the kernel side of the report). Fixes should then be directed to these tools. The only exception remains drivers specifically documented as being hardened against hostile inputs, as already stated for non-conforming devices and media. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-5-w@1wt.eu> --- Documentation/process/threat-model.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Documentation/process/threat-model.rst b/Documentation/process/threat-model.rst index 4c61f196fa84d1..a55e7c1c119680 100644 --- a/Documentation/process/threat-model.rst +++ b/Documentation/process/threat-model.rst @@ -234,7 +234,12 @@ The following classes of problems are not considered vulnerabilities: image: mounting a block device is a privileged operation (see above), and the administrator is responsible for the media they mount. This includes issues that are resolved, mitigated, or detected by running a filesystem - consistency check (fsck) on the image prior to mounting. + consistency check (fsck) on the image prior to mounting. Automatic + mounting of unchecked file systems (e.g. removable media mounted by a + desktop environment) does not change this: an automounter is expected to + check a file system before mounting it, otherwise it is at fault, and if + the check does not detect the issue, the file system checker is at fault. + In such cases, fixes should be directed to these tools. * bugs whose reproduction requires hardware modification or emulation, including fake USB devices that pretend to be another one, or devices From 9c0b499f3770d30ae8c474326853358f1ef1166b Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:05 +0100 Subject: [PATCH 2012/2102] docs: security-bugs: explain how to send a fix that can be applied Most fixes accompanying security reports cannot be applied with git am, either because they were damaged by the mailer, or because they just lack a commit message, and the vast majority of our responses to reporters are about the patch format. The doc only said to format the fix "in a way that can be immediately merged", but by now it has become clear that for many reporters it doesn't have the same meaning as for maintainers. Let's give concrete methods: preferably the report as the cover letter of the series produced by git format-patch, then the fix sent as a reply to the report, and as a last resort the patch attached, with a warning that some maintainers won't look at it. Let's also explain how to deal with public patches and private reports. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-6-w@1wt.eu> --- Documentation/process/security-bugs.rst | 46 +++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index 27442592671703..42b7926f3021c7 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -307,8 +307,9 @@ Please send **plain text** emails without attachments where possible. It is much harder to have a context-quoted discussion about a complex issue if all the details are hidden away in attachments. Think of it like a :doc:`regular patch submission <../process/submitting-patches>` -(even if you don't have a patch yet): describe the problem and impact, list -reproduction steps, and follow it with a proposed fix, all in plain text. +(even if you don't have a patch yet): describe the problem and impact, and +list reproduction steps, all in plain text, then provide a proposed fix as +described below. Markdown, HTML and RST formatted reports are particularly frowned upon since they're quite hard to read for humans and encourage to use dedicated viewers, sometimes online, which by definition is not acceptable for a confidential @@ -316,6 +317,47 @@ security report. Note that some mailers tend to mangle formatting of plain text by default, please consult Documentation/process/email-clients.rst for more info. +Sending a fix +~~~~~~~~~~~~~ + +Most fixes sent along with reports cannot be applied as-is because they were +damaged by the mailer or lacking a commit message, forcing maintainers to ask +for a resend. A fix must be applicable using ``git am``, which is most easily +achieved by letting git produce and send the messages (see +Documentation/process/submitting-patches.rst). + +When the fix is meant to only be sent privately, the preferred method is to +send the report as a cover letter of a series, followed by the fix:: + + $ git format-patch --cover-letter -1 + (edit 0000-cover-letter.patch and replace the subject and text with the + report's subject and text) + $ git send-email --suppress-cc=all --to= 000*.patch + +The recipients are those determined above (add ``--cc=`` for the security team +when needed). The ``--suppress-cc=all`` option is important: without it, +``git send-email`` also sends the messages to addresses found in the patch's +tags (e.g. ``Cc: stable@vger.kernel.org``), which would leak the report to a +public list. + +If the report was already sent, the fix may be sent as a reply to it, to the +same recipients, for example using ``git send-email --suppress-cc=all +--in-reply-to=``. As a last resort, when none of these +methods is possible, the file produced by ``git format-patch`` may be attached +as-is to the report, but be aware that some maintainers will not look at +attachments. However, never attach more than one patch per message without +being explicitly invited to so, as this would significantly complicate reviews. + +When the fix is meant to be public (e.g. for bugs found using AI-based tools, +see above), send it using ``git send-email`` to the maintainers and lists +reported by get_maintainer.pl (i.e. without the ``--no-l`` option), with a +commit message that does not detail how to exploit the bug. Then send the +report and the reproducer privately to the maintainers (and to the security +team when needed), mentioning the patch's Message-ID or its link on +https://lore.kernel.org/ so that they can be matched. The report may also be +sent as a reply to the public message, after carefully removing all public +addresses from the To: and Cc: fields. + After sending the report ------------------------ From 67afc96560bb2626b9fe269bee7b620702045913 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:06 +0100 Subject: [PATCH 2013/2102] docs: security-bugs: do not send archives or binary attachments Many reports still come with zip files or other archives attached, which are a pain to deal with, may be blocked by filtering on some maintainers' end, and that also encourage recipients to adopt risky practices of opening binary files. The doc only used to say to avoid attachments "where possible". Let's clarify that archives, binary files and documents are never acceptable, that large reproducers should be attached as plain text source files, and that scripts generating the required files (e.g. file system images) are a better solution. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-7-w@1wt.eu> --- Documentation/process/security-bugs.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index 42b7926f3021c7..38bdb2354353e4 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -305,7 +305,11 @@ at once by the same commit, then it may be acceptable to report them at once. Please send **plain text** emails without attachments where possible. It is much harder to have a context-quoted discussion about a complex -issue if all the details are hidden away in attachments. Think of it like a +issue if all the details are hidden away in attachments. Archives (zip, tar, +etc.), binary files and documents (PDF, etc.) are never acceptable: when a +reproducer is too large to be placed in the message, attach its source files +as plain text, and provide scripts that generate the required files (e.g. file +system images) instead of the files themselves. Think of it like a :doc:`regular patch submission <../process/submitting-patches>` (even if you don't have a patch yet): describe the problem and impact, and list reproduction steps, all in plain text, then provide a proposed fix as From 87f25898fe00822b6525d0d21dd668084fd4832e Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:07 +0100 Subject: [PATCH 2014/2102] docs: security-bugs: first-time reporters must send a single report first The security team regularly receives series of reports from first-time reporters, all of them suffering from the same issues (missing fix, wrong format, missing information), which need to be addressed one at a time and put unneeded pressure on maintainers. Worse, the security team ends up having to respond to each one of these messages so that CCed maintainers know about the problem. Let's ask first-time reporters to send only one report, and to wait for confirmation that it is in the expected form before sending the other ones. Also make it clear that violating this rule shows that the reporter did not read the doc, and that such reporters should be prepared not to receive any response. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-8-w@1wt.eu> --- Documentation/process/security-bugs.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index 38bdb2354353e4..437f3cb29e80a5 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -303,6 +303,15 @@ exception is when an issue concerns closely related parts maintained by the exact same subset of maintainers, and these parts are expected to be fixed all at once by the same commit, then it may be acceptable to report them at once. +If this is your first report, send only one, and wait for confirmation that it +is in the expected form before sending the other ones as individual messages. +The vast majority of first reports need to be adjusted, and otherwise the same +mistakes are repeated in all of them, putting needless pressure on the +maintainers and on the security team. Violating this rule is a clear +indication that the reporter did not read this document, and such reporters +should be prepared not to receive any response at all, as maintainers and the +security team have better things to do than to repeat what is written here. + Please send **plain text** emails without attachments where possible. It is much harder to have a context-quoted discussion about a complex issue if all the details are hidden away in attachments. Archives (zip, tar, From 6f06a15a2858a9b47bdeb47505dac30f39a5b428 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:08 +0100 Subject: [PATCH 2015/2102] docs: security-bugs: explain what to do when a report gets no response Some reports get lost, especially those with attachments or HTML, and reporters sometimes wait for weeks for a response that will never come. Since reports are private, the reporter has no other way to know if the report was delivered than asking. The doc only mentioned resending a message with no response within a week, in the middle of the rules about copying the security team. Let's explain it in "After sending the report": wait for a week, since some maintainers are overloaded or only work in their spare time, then resend the report with the security team in Cc. Also suggest to drop any attachment and double-check the output format. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-9-w@1wt.eu> --- Documentation/process/security-bugs.rst | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index 437f3cb29e80a5..82ece82ecfb758 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -275,9 +275,7 @@ security team in any of the following cases: this impact, and you will need to share any information you have; * you are seeking specific help, such as when resending a message which got - no response within a week (and please do not ask for feedback before such - a delay, some subsystems have a long report queue, and some maintainers can - only read them in their spare time). + no response within a week (see "After sending the report"). Otherwise, when a report of clear impact is sent to a larger team of clearly identified maintainers, it is not necessary to Cc: the security list. Never @@ -384,6 +382,19 @@ run additional tests. Reports where the reporter does not respond promptly or cannot effectively discuss their findings may be abandoned if the communication does not quickly improve. +Messages sometimes get lost, especially those containing attachments or HTML. +Since the report is private, you have no other way to know whether it was +delivered than to ask. However, some subsystems have a long report queue, some +maintainers are overloaded or only work in their spare time, so please wait for +a week without any response before resending your report with the security team +in Cc: (see above). In this case, be clear about the fact that it is a resend, +and if possible, provide a reference to the original message. Better double +check that the message is sent in plain text, and drop any attachment when +resending, to increase the chances of successful delivery. In any case, please +do not ask for proper receipt before this delay. This will not make your report +be processed faster, will add extra load on maintainers and all you risk is +your future messages being ignored. + Disclosure and embargoed information ------------------------------------ From 045cbca41342f42bef7f9e81a2430f9d4fb5af53 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:09 +0100 Subject: [PATCH 2016/2102] docs: security-bugs: reports left unanswered for 7 days will be dropped Between 5 and 10% of the questions or requests sent by the security team or maintainers to reporters never receive any response. The doc only said that such reports "may be abandoned", without any indication of time, and team members keep collection of unresponded threads in their boxes just due to this. Let's say that reports for which requests remain unanswered for 7 days will most likely be dropped. This matches the maximum embargo duration, which is how long the security team considers it reasonable to keep an issue private. Also remind that concurrent reports may cause the same bug to be addressed by someone else who will then receive the credit in this case. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-10-w@1wt.eu> --- Documentation/process/security-bugs.rst | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index 82ece82ecfb758..992c8d8d9b1c1d 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -382,6 +382,14 @@ run additional tests. Reports where the reporter does not respond promptly or cannot effectively discuss their findings may be abandoned if the communication does not quickly improve. +In practice, a report for which questions or requests from the security team +or the maintainers remain unanswered for 7 days will most likely be dropped. +This matches the maximum embargo duration described below, which is how long +the security team considers it reasonable to keep an issue private. Given the +number of reports handled in parallel, the same bug may also end up being fixed +later after being reported by someone else, in which case credit can no longer +be guaranteed. + Messages sometimes get lost, especially those containing attachments or HTML. Since the report is private, you have no other way to know whether it was delivered than to ask. However, some subsystems have a long report queue, some From c543e2c33325db09cae3a109eeedaebaea5297ff Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:10 +0100 Subject: [PATCH 2017/2102] docs: security-bugs: add a section for maintainers receiving reports Now that reports are expected to be more commonly sent directly to maintainers, some of them will receive security reports for the first time and may not know what to do with them, or worry about having to deal with them alone. Let's add a short section reminding them that they are not alone, and that they are welcome to ask the security team for help at any time. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-11-w@1wt.eu> --- Documentation/process/security-bugs.rst | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index 992c8d8d9b1c1d..791a78964a9d3c 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -5,7 +5,8 @@ Security bugs Linux kernel developers take security very seriously. As such, we'd like to know when a security bug is found so that it can be fixed and -disclosed as quickly as possible. +disclosed as quickly as possible. If you are a maintainer and received +a report, there is a section dedicated to you below. What qualifies as a security bug -------------------------------- @@ -403,6 +404,24 @@ do not ask for proper receipt before this delay. This will not make your report be processed faster, will add extra load on maintainers and all you risk is your future messages being ignored. +For maintainers receiving a report +---------------------------------- + +If you maintain some code in the kernel and received a security report, don't +panic, you're not alone! The wording of AI-generated reports these days tends +to sound scary, but just stick to technical facts and proceed like you would +with any other bug report. Feel free to share the report with other maintainers +who you think can help you, telling them upfront that the report is private. +Many other reports are being handled by other maintainers at any instant, do +not start to worry that the security of the whole kernel suddenly depends on +your ability to provide a quick fix. Do not let reporters dictate conditions +that are not compatible with what this document describes. If you have any +question or doubt, be it about the validity of the report, its impact, the +process to follow, difficult interactions with a reporter, or even if you've +mistakenly leaked part of the report to a public list (yes, this happens), just +ask the security team for help, for example by replying to the report with the +security team in Cc:, or by forwarding it to them if you're seeking advice. + Disclosure and embargoed information ------------------------------------ From be3051f2c54600d44ebc8194f7343bca54e2d138 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:11 +0100 Subject: [PATCH 2018/2102] docs: security-bugs: explain why directly sent reports add extra work Many reporters imagine that contacting a maintainer directly will bring their report a special attention but it's exactly the opposite because it breaks the normal workflow, and deprives the maintainer from their usual tools (CI, reviews etc), and even requires extra care (e.g. use separate branches, avoid CCing stable etc). Let's just explain this upfront so that reporters understand that there is a reason for everyone insisting on public posts. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-12-w@1wt.eu> --- Documentation/process/security-bugs.rst | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index 791a78964a9d3c..11a4ee55589473 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -15,7 +15,14 @@ It is important that most bugs are handled publicly so as to involve the widest possible audience and find the best solution. By nature, bugs that are handled in closed discussions between a small set of participants are less likely to produce the best possible fix (e.g., risk of missing valid use cases, limited -testing abilities). +testing abilities). In addition, dealing with private discussions on patches +adds much more burden to maintainers who cannot follow their usual process nor +benefit from their usual tools. For example, many subsystems have CI jobs +running on publicly posted patches and will not merge a fix before it has been +validated, and automated review tools such as Sashiko review patches posted to +the lists. Since the fix will have to be posted publicly anyway, sending it +privately first only delays it by the time needed to ask for it to be reposted +publicly, adds extra work, and loses the benefit of early reviews. It turns out that the majority of the bugs reported via the security team are just regular bugs that have been improperly qualified as security bugs due to From 7223b970e1c7e9cdabb1e3156fe35c6f89a89a8a Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:12 +0100 Subject: [PATCH 2019/2102] docs: security-bugs: explain why AI-found bugs are handled publicly Many reporters of bugs found using AI do not follow the instructions to treat them as public, likely because they're worried to be blamed for disclosing it. The security team constantly receives duplicate reports within a very short time, which makes it clear that when an LLM finds a bug, others find it at the same time, and some may already be working on exploiting it. Keeping it private then protects nobody, while handling it publicly lets everyone fix it quickly without a needless embargo. Let's clarify these points and also reword a sentence about AI reports that could be read as "do not send them to us". Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-13-w@1wt.eu> --- Documentation/process/security-bugs.rst | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index 11a4ee55589473..b37d9ed94f6e7c 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -42,10 +42,16 @@ a system. **If you resorted to AI assistance to identify a bug, you must treat it as public**. While you may have valid reasons to believe it is not, the security team's experience shows that bugs discovered this way systematically surface -simultaneously across multiple researchers, often on the same day. In this -case, do not publicly share a reproducer, as this could cause unintended harm; -just mention that one is available and maintainers might ask for it privately -if they need it. +simultaneously across multiple researchers, often on the same day. Others are +then likely to be already working on exploiting the same bug, so keeping it +private would protect nobody, while handling it publicly lets everyone fix it +quickly without wasting time in a needless embargo. This applies even when the +bug falls within the threat model: only the fix and its description are made +public, and reporters following this procedure will never be blamed for it. In +any case, do not publicly share a reproducer, as this could cause unintended +harm; just mention that one is available and maintainers might ask for it +privately if they need it, or better, send it upfront in a separate message to +maintainers only. If you are unsure whether an issue qualifies, err on the side of reporting privately: the security team would rather triage a borderline report than miss @@ -169,10 +175,10 @@ ignored. Use common sense when evaluating the report. If the affected file has not been touched for more than one year and is maintained by a single individual, it is likely that usage has declined and exposed users are virtually non-existent -(e.g., drivers for very old hardware, obsolete filesystems). In such cases, -there is no need to consume a maintainer's time with an unimportant report. If -the issue is clearly trivial and publicly discoverable, you should report it -directly to the public mailing lists, without the reproducer. +(e.g., drivers for very old hardware, obsolete filesystems). In such cases, as +well as when the issue is clearly trivial and publicly discoverable, there is +no need to consume a maintainer's time with a private security report: just +send the fix publicly like any regular bug fix, without the reproducer. At the very least, when using an AI assistant to find and report bugs, make the assistant read this file and threat-model.rst before proceeding, and have it From dd655d40262631f7b7ae138fc760b6d568aa1859 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:13 +0100 Subject: [PATCH 2020/2102] docs: submitting-patches: defer to security-bugs.rst for security fixes Despite recent improvements, the security team continues to receive non-compliant reports clearly indicating that the author had not read the documentation. It turns out that submitting-patches.rst asks to send such reports to list's address in a short paragraph, so it's very likely that some reports only find this one and do not read the rest! Let's replace this with an invitation to read the security doc instead. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Signed-off-by: Willy Tarreau Acked-by: Bagas Sanjaya Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-14-w@1wt.eu> --- Documentation/process/submitting-patches.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Documentation/process/submitting-patches.rst b/Documentation/process/submitting-patches.rst index f271d7413f72cf..ac7d0d8f5be562 100644 --- a/Documentation/process/submitting-patches.rst +++ b/Documentation/process/submitting-patches.rst @@ -253,11 +253,11 @@ He gets a lot of e-mail, and, at this point, very few patches go through Linus directly, so typically you should do your best to -avoid- sending him e-mail. -If you have a patch that fixes an exploitable security bug, send that patch -to security@kernel.org. For severe bugs, a short embargo may be considered -to allow distributors to get the patch out to users; in such cases, -obviously, the patch should not be sent to any public lists. See also -Documentation/process/security-bugs.rst. +If you have a patch that fixes a bug with possible security implications, you +need to read Documentation/process/security-bugs.rst first: it explains which +bugs need to be handled privately, and whom to send them to. Most such fixes +are posted publicly like any other fix, but their reproducers and exploits must +never be posted publicly. Patches that fix a severe bug in a released kernel should be directed toward the stable maintainers by putting a line like this:: From 9fb6d9a19e51b413ef88f257e09f331febd0ee75 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sat, 14 Nov 2026 20:00:14 +0100 Subject: [PATCH 2021/2102] docs: netdev: drop references to the securit list in the doc The netdev maintainer profile asks reporters of bugs with possible security implications to use the public lists, which is consistent with the way most of these bugs are handled, but it says nothing about reproducers, and its suggested alternatives contradict security-bugs.rst: it points to the security team's address, and to the linux-distros list which must not be contacted before a fix is accepted. This text has been left unchanged since 2013 when security reports were not yet a problem, just because it remained unnoticed during the security doc refactoring. Instead of making a special case of security fixes, let's just drop this outdated section entirely, so that readers refer to the usual docs. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Johan Hovold Cc: Jakub Kicinski Signed-off-by: Willy Tarreau Acked-by: Jakub Kicinski Signed-off-by: Jonathan Corbet Message-ID: <20261114190014.17826-15-w@1wt.eu> --- Documentation/process/maintainer-netdev.rst | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/Documentation/process/maintainer-netdev.rst b/Documentation/process/maintainer-netdev.rst index df220a9654387a..276dae2969a61a 100644 --- a/Documentation/process/maintainer-netdev.rst +++ b/Documentation/process/maintainer-netdev.rst @@ -324,18 +324,6 @@ the case today. Please follow the standard stable rules in :ref:`Documentation/process/stable-kernel-rules.rst `, and make sure you include appropriate Fixes tags! -Security fixes -~~~~~~~~~~~~~~ - -Do not email netdev maintainers directly if you think you discovered -a bug that might have possible security implications. -The current netdev maintainer has consistently requested that -people use the mailing lists and not reach out directly. If you aren't -OK with that, then perhaps consider mailing security@kernel.org or -reading about http://oss-security.openwall.org/wiki/mailing-lists/distros -as possible alternative mechanisms. - - Co-posting changes to user space components ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From e1aff4d4241057636394751508e633a92f1cbbab Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Fri, 27 Nov 2026 10:06:45 +0000 Subject: [PATCH 2022/2102] ALSA: atmel: ac97c: fix reset GPIO error handling The driver currently ignores errors returned by devm_gpiod_get_index() and continues probing. This can cause problems when the GPIO provider is not ready and the function returns -EPROBE_DEFER. Use devm_gpiod_get_index_optional() to handle the reset GPIO as optional. If the GPIO is not available, the driver can continue using the internal reset mechanism. If GPIO acquisition fails for another reason, return the error using dev_err_probe(). Also, check the GPIO descriptor for NULL in atmel_ac97c_reset(), because the optional GPIO API returns NULL when no GPIO is assigned. Fixes: 5f10e84934e4 ("ALSA: atmel: convert AC97c driver to GPIO descriptor API") Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261127100645.3564-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/atmel/ac97c.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/sound/atmel/ac97c.c b/sound/atmel/ac97c.c index 234549e17351c9..3ab6ddb3259fce 100644 --- a/sound/atmel/ac97c.c +++ b/sound/atmel/ac97c.c @@ -670,7 +670,7 @@ static void atmel_ac97c_reset(struct atmel_ac97c *chip) ac97c_writel(chip, CAMR, 0); ac97c_writel(chip, COMR, 0); - if (!IS_ERR(chip->reset_pin)) { + if (chip->reset_pin) { gpiod_set_value(chip->reset_pin, 0); /* AC97 v2.2 specifications says minimum 1 us. */ udelay(2); @@ -743,9 +743,13 @@ static int atmel_ac97c_probe(struct platform_device *pdev) chip->pdev = pdev; chip->regs = regs; - chip->reset_pin = devm_gpiod_get_index(dev, "ac97", 2, GPIOD_OUT_HIGH); + chip->reset_pin = devm_gpiod_get_index_optional(dev, + "ac97", 2, + GPIOD_OUT_HIGH); if (IS_ERR(chip->reset_pin)) - dev_dbg(dev, "reset pin not available\n"); + return dev_err_probe(dev, + PTR_ERR(chip->reset_pin), + "failed to get reset GPIO\n"); atmel_ac97c_reset(chip); From 03699c24d1ca308e117c5500dc4360b884719412 Mon Sep 17 00:00:00 2001 From: Navon John Lukose Date: Mon, 14 Sep 2026 03:17:13 +0530 Subject: [PATCH 2023/2102] hwmon: (yogafan) Fix fan paths for Yoga Pro 7 14IAH10 The Yoga Pro 7 14IAH10 entry names \_SB.PC00.LPCB.EC0.FANS, which this machine's DSDT does not have, so probe matches on DMI, fails to resolve the path and returns -ENODEV. The EC exposes its two fan tachometers as FA1S and FA2S, and loq_15iax9_8bit_dual_cfg already describes that layout. Point the entry at it, and update the reference table row to match. Fixes: 9c110a467686 ("hwmon: (yogafan) Add support for new Lenovo models") Cc: stable@vger.kernel.org Signed-off-by: Navon John Lukose Link: https://patch.msgid.link/20260913214713.205208-1-navonjohnlukose@gmail.com Acked-by: Sergio Melas Signed-off-by: Guenter Roeck --- Documentation/hwmon/yogafan.rst | 3 ++- drivers/hwmon/yogafan.c | 8 +------- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/Documentation/hwmon/yogafan.rst b/Documentation/hwmon/yogafan.rst index 239c7b5761caf6..57d528cdd6f461 100644 --- a/Documentation/hwmon/yogafan.rst +++ b/Documentation/hwmon/yogafan.rst @@ -105,7 +105,8 @@ immediately to ensure the user knows the fan has stopped. 83KF | XiaoXinPro 13ARE | 0x06/0xFE | \_SB.PCI0.LPC0.EC0.FANS/FA2S | 8-bit | 100 82KU | IdeaPad 3 15ALC6 | 0x06 | \_SB.PCI0.LPC0.EC0.FAN0 | 8-bit | 100 83RU | Legion Pro 7 16 | 0x03/0x06 | \_SB.PCI0.LPC0.EC0.FANS/FA2S | 8-bit | 100 - 83KF | Yoga Pro 7 14IAH | 0x06 | \_SB.PC00.LPCB.EC0.FANS | 8-bit | 100 + 83KF | Yoga Pro 7 14IAH | 0x104 | \_SB.PC00.LPCB.EC0.FA1S (Fan1) | 8-bit | 100 + 83KF | Yoga Pro 7 14IAH | 0x137 | \_SB.PC00.LPCB.EC0.FA2S (Fan2) | 8-bit | 100 83BS | Yoga 7 16ARP8 | 0x03/0x06 | \_SB.PCI0.LPC0.EC0.FANS/FA2S | 8-bit | 100 *Legacy* | Pre-2020 Models | 0x06 | \_SB.PCI0.LPC.EC.FAN0 | 8-bit | 100 ------------------------------------------------------------------------------------------------------- diff --git a/drivers/hwmon/yogafan.c b/drivers/hwmon/yogafan.c index 6d1284c090487d..285bc71843525b 100644 --- a/drivers/hwmon/yogafan.c +++ b/drivers/hwmon/yogafan.c @@ -89,12 +89,6 @@ static const struct yogafan_config xiaoxin_8bit_dual_cfg = { .paths = { "\\_SB.PCI0.LPC0.EC0.FANS", "\\_SB.PCI0.LPC0.EC0.FA2S" } }; -static const struct yogafan_config yoga_pro_7_14iah10_cfg = { - .multiplier = 100, - .fan_count = 1, - .paths = { "\\_SB.PC00.LPCB.EC0.FANS", NULL } -}; - /* * Lenovo Yoga Pro 9 16IMH9 (83DN) uses the PC00 namespace and has two * 8-bit fan tachometer fields. @@ -267,7 +261,7 @@ static const struct dmi_system_id yogafan_quirks[] = { DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), DMI_MATCH(DMI_PRODUCT_FAMILY, "Yoga Pro 7 14IAH10"), }, - .driver_data = (void *)&yoga_pro_7_14iah10_cfg, + .driver_data = (void *)&loq_15iax9_8bit_dual_cfg, }, { .ident = "Lenovo Yoga 7 16ARP8", From 9c0710316e503275ca4ceb67d1cbfe2d1924f1e8 Mon Sep 17 00:00:00 2001 From: Markus Haberlander Date: Mon, 23 Nov 2026 08:27:01 +0100 Subject: [PATCH 2024/2102] hwmon: (cgbc-hwmon) Add module alias The board controller's core driver adds the hwmon cell as platform device "cgbc-hwmon", but the driver declares no matching module alias. Built as a module, it is therefore not loaded automatically, unlike the GPIO, I2C and backlight drivers, and the sensors stay missing until it is loaded by hand. Tested on a conga-PA7: with the alias, the driver loads at boot. The patch and this changelog were drafted with the help of Claude Opus 5.5 and reviewed and tested by me. Fixes: 08ebc9def79f ("hwmon: Add Congatec Board Controller monitoring driver") Cc: stable@vger.kernel.org Signed-off-by: Markus Haberlander Link: https://patch.msgid.link/20261123-cgbc-hwmon-alias-v1-1-3054681f984a@rosenberger.com Signed-off-by: Guenter Roeck --- drivers/hwmon/cgbc-hwmon.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/hwmon/cgbc-hwmon.c b/drivers/hwmon/cgbc-hwmon.c index ba21ed8f0ceaf3..d1f20db4b28924 100644 --- a/drivers/hwmon/cgbc-hwmon.c +++ b/drivers/hwmon/cgbc-hwmon.c @@ -336,3 +336,4 @@ module_platform_driver(cgbc_hwmon_driver); MODULE_AUTHOR("Thomas Richard "); MODULE_DESCRIPTION("Congatec Board Controller Hardware Monitoring Driver"); MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:cgbc-hwmon"); From ab8ea038584868fbcc91878a6caccf6404582fce Mon Sep 17 00:00:00 2001 From: Christopher de Guzman Date: Mon, 23 Nov 2026 14:52:02 +0800 Subject: [PATCH 2025/2102] hwmon: (pmbus/ltc2978) Fix peak comparison for IEEE-754 chips The LT7170, LT7171, LT7175 and LT7176P report their sensor values in IEEE-754 half-precision format, but ltc_get_max() and ltc_get_min() compare peak values with lin11_to_val(), which decodes LINEAR11. Bit 10 is the lowest exponent bit in binary16, while LINEAR11 treats it as the mantissa sign bit. Positive values with an odd biased exponent, such as temperatures from 16 to 31 C or input voltages from 4 to 8 V, are therefore decoded as negative, and the reported peak stops following the real one. The peak start values have the same problem: 0x7c00 is the lowest LINEAR11 value, but it is +infinity in binary16. Add a FEAT_IEEE754 flag for these chips. Compare binary16 values as sign-magnitude integers, and start peak maximums at -infinity (0xfc00) and peak minimums at +infinity (0x7c00). The min attributes are not exposed for these chips, but the min path is fixed as well for consistency. Tested on an LT7171-1: after stepping VIN from 3.3 V to 5 V and back, in1_highest now reports 4992 mV instead of staying at 3294 mV. Fixes: c1d6afdbb8ed ("hwmon: (pmbus/ltc2978) add support for lt717x") Reported-by: sashiko-bot Closes: https://lore.kernel.org/all/sashiko-outbox-206843@kernel.org/ Signed-off-by: Christopher de Guzman Link: https://patch.msgid.link/20261123-ltc2978-ieee754-peak-fix-v1-1-96cbe686ab67@analog.com [groeck: Adjust patch order; lt7175 and lt7176p are only introduced later] Signed-off-by: Guenter Roeck --- drivers/hwmon/pmbus/ltc2978.c | 66 +++++++++++++++++++++++++++-------- 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/drivers/hwmon/pmbus/ltc2978.c b/drivers/hwmon/pmbus/ltc2978.c index 58c83d4f398daf..bd58f786693bf6 100644 --- a/drivers/hwmon/pmbus/ltc2978.c +++ b/drivers/hwmon/pmbus/ltc2978.c @@ -136,9 +136,11 @@ struct ltc2978_data { #define FEAT_CLEAR_PEAKS BIT(0) #define FEAT_NEEDS_POLLING BIT(1) +#define FEAT_IEEE754 BIT(2) #define has_clear_peaks(d) ((d)->features & FEAT_CLEAR_PEAKS) #define needs_polling(d) ((d)->features & FEAT_NEEDS_POLLING) +#define has_ieee754(d) ((d)->features & FEAT_IEEE754) static int ltc_wait_ready(struct i2c_client *client) { @@ -236,6 +238,30 @@ static inline int lin11_to_val(int data) return (e < 0 ? m >> -e : m << e); } +static inline int ieee754_sort_key(u16 h) +{ + int mag = h & 0x7fff; + + return (h & 0x8000) ? -mag : mag; +} + +static bool ltc_peak_gt(struct ltc2978_data *data, u16 a, u16 b) +{ + if (has_ieee754(data)) + return ieee754_sort_key(a) > ieee754_sort_key(b); + return lin11_to_val(a) > lin11_to_val(b); +} + +static u16 ltc_peak_max_init(struct ltc2978_data *data) +{ + return has_ieee754(data) ? 0xfc00 : 0x7c00; +} + +static u16 ltc_peak_min_init(struct ltc2978_data *data) +{ + return has_ieee754(data) ? 0x7c00 : 0x7bff; +} + static int ltc_get_max(struct ltc2978_data *data, struct i2c_client *client, int page, int reg, u16 *pmax) { @@ -243,7 +269,7 @@ static int ltc_get_max(struct ltc2978_data *data, struct i2c_client *client, ret = ltc_read_word_data(client, page, 0xff, reg); if (ret >= 0) { - if (lin11_to_val(ret) > lin11_to_val(*pmax)) + if (ltc_peak_gt(data, ret, *pmax)) *pmax = ret; ret = *pmax; } @@ -257,7 +283,7 @@ static int ltc_get_min(struct ltc2978_data *data, struct i2c_client *client, ret = ltc_read_word_data(client, page, 0xff, reg); if (ret >= 0) { - if (lin11_to_val(ret) < lin11_to_val(*pmin)) + if (ltc_peak_gt(data, *pmin, ret)) *pmin = ret; ret = *pmin; } @@ -494,22 +520,22 @@ static int ltc2978_write_word_data(struct i2c_client *client, int page, switch (reg) { case PMBUS_VIRT_RESET_IIN_HISTORY: - data->iin_max = 0x7c00; - data->iin_min = 0x7bff; + data->iin_max = ltc_peak_max_init(data); + data->iin_min = ltc_peak_min_init(data); ret = ltc2978_clear_peaks(data, client, 0); break; case PMBUS_VIRT_RESET_PIN_HISTORY: - data->pin_max = 0x7c00; - data->pin_min = 0x7bff; + data->pin_max = ltc_peak_max_init(data); + data->pin_min = ltc_peak_min_init(data); ret = ltc2978_clear_peaks(data, client, 0); break; case PMBUS_VIRT_RESET_IOUT_HISTORY: - data->iout_max[page] = 0x7c00; - data->iout_min[page] = 0xfbff; + data->iout_max[page] = ltc_peak_max_init(data); + data->iout_min[page] = has_ieee754(data) ? 0x7c00 : 0xfbff; ret = ltc2978_clear_peaks(data, client, page); break; case PMBUS_VIRT_RESET_TEMP2_HISTORY: - data->temp2_max = 0x7c00; + data->temp2_max = ltc_peak_max_init(data); ret = ltc2978_clear_peaks(data, client, page); break; case PMBUS_VIRT_RESET_VOUT_HISTORY: @@ -518,13 +544,13 @@ static int ltc2978_write_word_data(struct i2c_client *client, int page, ret = ltc2978_clear_peaks(data, client, page); break; case PMBUS_VIRT_RESET_VIN_HISTORY: - data->vin_min = 0x7bff; - data->vin_max = 0x7c00; + data->vin_min = ltc_peak_min_init(data); + data->vin_max = ltc_peak_max_init(data); ret = ltc2978_clear_peaks(data, client, page); break; case PMBUS_VIRT_RESET_TEMP_HISTORY: - data->temp_min[page] = 0x7bff; - data->temp_max[page] = 0x7c00; + data->temp_min[page] = ltc_peak_min_init(data); + data->temp_max[page] = ltc_peak_max_init(data); ret = ltc2978_clear_peaks(data, client, page); break; default: @@ -761,7 +787,19 @@ static int ltc2978_probe(struct i2c_client *client) switch (data->id) { case lt7170: case lt7171: - data->features |= FEAT_CLEAR_PEAKS | FEAT_NEEDS_POLLING; + data->features |= FEAT_CLEAR_PEAKS | FEAT_NEEDS_POLLING | + FEAT_IEEE754; + data->vin_max = ltc_peak_max_init(data); + for (i = 0; i < ARRAY_SIZE(data->iout_max); i++) + data->iout_max[i] = ltc_peak_max_init(data); + for (i = 0; i < ARRAY_SIZE(data->temp_max); i++) + data->temp_max[i] = ltc_peak_max_init(data); + data->temp2_max = ltc_peak_max_init(data); + data->vin_min = ltc_peak_min_init(data); + for (i = 0; i < ARRAY_SIZE(data->iout_min); i++) + data->iout_min[i] = 0x7c00; + for (i = 0; i < ARRAY_SIZE(data->temp_min); i++) + data->temp_min[i] = ltc_peak_min_init(data); info->read_word_data = ltc3883_read_word_data; info->pages = LTC3883_NUM_PAGES; info->format[PSC_VOLTAGE_IN] = ieee754; From 76a0a6d58318fff8b14530ed9b99c7065995db29 Mon Sep 17 00:00:00 2001 From: Vincent Donnefort Date: Tue, 17 Nov 2026 15:15:20 +0000 Subject: [PATCH 2026/2102] ring-buffer: Add missing cnt increment for remote ring buffers The ring_buffer_per_cpu::cnt member tracks modifications to the ring buffer links. It was introduced for rb_check_pages() to avoid locking the ring buffer for the entire duration of the check. The reader page swap function for remote ring buffers does not update it. If a concurrent rb_check_pages() recorded a page as head before dropping the reader lock, it misses the list update and loops indefinitely. Add the missing increment. Cc: stable@vger.kernel.org Fixes: fbd1743ecba1 ("ring-buffer: Add non-consuming read for ring-buffer remotes") Reported-by: Sashiko Link: https://patch.msgid.link/20261117151520.3972146-1-vdonnefort@google.com Signed-off-by: Vincent Donnefort [ rebased to v7.4-rc4 as there were conflicts ] Signed-off-by: Steven Rostedt --- kernel/trace/ring_buffer.c | 1 + 1 file changed, 1 insertion(+) diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c index a5a0adc934faa6..65dddfac5e047b 100644 --- a/kernel/trace/ring_buffer.c +++ b/kernel/trace/ring_buffer.c @@ -5891,6 +5891,7 @@ __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer) cpu_buffer->pages = &new_head->list; cpu_buffer->lost_events = cpu_buffer->meta_page->reader.lost_events; local_inc(&cpu_buffer->pages_read); + cpu_buffer->cnt++; if (!rb_page_size(cpu_buffer->reader_page)) return NULL; From 3285c9db0ff45b86ef80297627450402bc30f614 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 24 Nov 2026 18:28:11 +0100 Subject: [PATCH 2027/2102] efi: pstore: Make pstore_disable parameter read-only again Commit a28655c330ab ("efi: pstore: Allow dynamic initialization based on module parameter") wired up a kernel_param_ops::set callback for pstore_disable that invokes efivars_pstore_init() directly. Because parse_args() runs before module initialization (and before mm_core_init() during early boot when built-in), calling efivars_pstore_init() from the parameter setter is fundamentally broken: - Loading efi-pstore as a module with pstore_disable=N initializes and registers efi_pstore_info during parse_args(), and then runs efivars_pstore_init() a second time from do_init_module(), leaking the first buffer, failing pstore_register() with -EBUSY, and zeroing efi_pstore_info.buf/bufsize while leaving efi_pstore_info registered with pstore. - If load_module() fails after parse_args() (e.g., due to a subsequent unknown parameter), the module is freed without calling module_exit, leaving pstore with a dangling backend pointer. - Passing pstore_disable=N before record_size= initializes the buffer using the default record_size before record_size is parsed. Module parameters are meant for boot/load-time configuration rather than runtime driver state control via sysfs. Revert the dynamic parameter callback changes and tighten the sysfs permissions of pstore_disable from 0644 to 0444 (matching record_size) so it is no longer misleadingly writable at runtime. Fixes: a28655c330ab ("efi: pstore: Allow dynamic initialization based on module parameter") Cc: stable@vger.kernel.org Tested-by: Guilherme G. Piccoli Signed-off-by: Ard Biesheuvel --- drivers/firmware/efi/efi-pstore.c | 39 +++++-------------------------- 1 file changed, 6 insertions(+), 33 deletions(-) diff --git a/drivers/firmware/efi/efi-pstore.c b/drivers/firmware/efi/efi-pstore.c index a5db3534f0a632..19a7e4fe5b5248 100644 --- a/drivers/firmware/efi/efi-pstore.c +++ b/drivers/firmware/efi/efi-pstore.c @@ -19,37 +19,10 @@ MODULE_PARM_DESC(record_size, "size of each pstore UEFI var (in bytes, min/defau EFI_VARIABLE_BOOTSERVICE_ACCESS | \ EFI_VARIABLE_RUNTIME_ACCESS) -static bool pstore_disable = IS_ENABLED(CONFIG_EFI_VARS_PSTORE_DEFAULT_DISABLE); +static bool efivars_pstore_disable = + IS_ENABLED(CONFIG_EFI_VARS_PSTORE_DEFAULT_DISABLE); -static int efivars_pstore_init(void); -static void efivars_pstore_exit(void); - -static int efi_pstore_disable_set(const char *val, const struct kernel_param *kp) -{ - int err; - bool old_pstore_disable = pstore_disable; - - err = param_set_bool(val, kp); - if (err) - return err; - - if (old_pstore_disable != pstore_disable) { - if (pstore_disable) - efivars_pstore_exit(); - else - efivars_pstore_init(); - } - - return 0; -} - -static const struct kernel_param_ops pstore_disable_ops = { - .set = efi_pstore_disable_set, - .get = param_get_bool, -}; - -module_param_cb(pstore_disable, &pstore_disable_ops, &pstore_disable, 0644); -__MODULE_PARM_TYPE(pstore_disable, "bool"); +module_param_named(pstore_disable, efivars_pstore_disable, bool, 0444); static int efi_pstore_open(struct pstore_info *psi) { @@ -255,12 +228,12 @@ static struct pstore_info efi_pstore_info = { .erase = efi_pstore_erase, }; -static int efivars_pstore_init(void) +static __init int efivars_pstore_init(void) { if (!efivar_supports_writes()) return 0; - if (pstore_disable) + if (efivars_pstore_disable) return 0; /* @@ -287,7 +260,7 @@ static int efivars_pstore_init(void) return 0; } -static void efivars_pstore_exit(void) +static __exit void efivars_pstore_exit(void) { if (!efi_pstore_info.bufsize) return; From f6ce3d09d6480b56e357336ac080952f9525eab0 Mon Sep 17 00:00:00 2001 From: Hungyu Lin Date: Fri, 20 Nov 2026 10:17:58 +0000 Subject: [PATCH 2028/2102] block: fix discard alignment for non-power-of-two granularities bio_discard_limit() uses round_up() and round_down(), which require a power-of-two alignment. However, discard_granularity need not be a power of two. For example, dm-thin supports data block sizes that are arbitrary multiples of 64 KiB and advertises the block size as its granularity. With a 192 KiB granularity, discarding one complete block at offset 384 KiB is split into 128 KiB and 64 KiB bios. Neither covers a complete thin block, so dm-thin ignores both and the mapping remains allocated. Use div_u64_rem() to find the starting sector's remainder without modifying the sector. Round the maximum bio size down with rounddown() and subtract the remainder so that the next bio starts on a granularity boundary. This handles non-power-of-two granularities and avoids a small initial bio when a large discard starts at an unaligned sector. When discard is unsupported or disabled, discard_granularity can be zero. Return BIO_MAX_SECTORS in that case so the existing bio submission checks can handle unsupported discard requests without dividing by zero. Fixes: 9b15d109a6b2 ("block: improve discard bio alignment in __blkdev_issue_discard()") Reported-by: Ming-Hung Tsai Link: https://lore.kernel.org/r/CALjSBEvjbiGDVewuapWKhGDtaxZwcn4=22raUiBEOyj22rY7-g@mail.gmail.com Suggested-by: Christoph Hellwig Reviewed-by: Christoph Hellwig Cc: stable@vger.kernel.org Signed-off-by: Hungyu Lin Tested-by: Usama Arif Link: https://patch.msgid.link/20261120101758.45513-1-dennylin0707@gmail.com Signed-off-by: Jens Axboe --- block/blk-lib.c | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/block/blk-lib.c b/block/blk-lib.c index 688bc67cbf733d..e98aa4837079c0 100644 --- a/block/blk-lib.c +++ b/block/blk-lib.c @@ -3,6 +3,7 @@ * Functions related to generic helpers functions */ #include +#include #include #include #include @@ -13,26 +14,25 @@ static sector_t bio_discard_limit(struct block_device *bdev, sector_t sector) { unsigned int discard_granularity = bdev_discard_granularity(bdev); - sector_t granularity_aligned_sector; + u32 unaligned_sectors; + + if (!discard_granularity) + return BIO_MAX_SECTORS; if (bdev_is_partition(bdev)) sector += bdev->bd_start_sect; - granularity_aligned_sector = - round_up(sector, discard_granularity >> SECTOR_SHIFT); - - /* - * Make sure subsequent bios start aligned to the discard granularity if - * it needs to be split. - */ - if (granularity_aligned_sector != sector) - return granularity_aligned_sector - sector; - /* - * Align the bio size to the discard granularity to make splitting the bio - * at discard granularity boundaries easier in the driver if needed. + * Align the bio size to the discard granularity to make splitting the + * bio at discard granularity boundaries easier in the driver if needed. + * + * If the current sector is not aligned, shorten the range so that the + * next one is aligned. */ - return round_down(BIO_MAX_SIZE, discard_granularity) >> SECTOR_SHIFT; + div_u64_rem(sector, discard_granularity >> SECTOR_SHIFT, + &unaligned_sectors); + return (rounddown(BIO_MAX_SIZE, discard_granularity) >> SECTOR_SHIFT) - + unaligned_sectors; } struct bio *blk_alloc_discard_bio(struct block_device *bdev, From d9667b1a6a3387ef934667b9a2e6c099eee0e4f1 Mon Sep 17 00:00:00 2001 From: Sasha Levin Date: Thu, 26 Nov 2026 18:17:06 -0500 Subject: [PATCH 2029/2102] selftests/ublk: use the configured kernel UAPI headers With generated headers in an output directory, the hardcoded source-tree include path falls through to distribution headers. New ublk flags and structure members, including UBLK_F_IO_DESC_SIZE, are then missing. Use KHDR_INCLUDES to consume the headers from the kernel under test, and add the headers target as an order-only prerequisite of the ublk programs, as nolibc-test does, so that a standalone build installs them first. Baseline builds fail on the missing definitions; GCC 14 and Clang 21 builds succeed with the output-directory headers and target liburing development files available. Fixes: e371b9d3368c ("selftests: ublk: kublk: fix include path") Signed-off-by: Sasha Levin Reviewed-by: Ming Lei Link: https://patch.msgid.link/20261126231706.1303486-1-sashal@kernel.org Signed-off-by: Jens Axboe --- tools/testing/selftests/ublk/Makefile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/ublk/Makefile b/tools/testing/selftests/ublk/Makefile index 1a50d4695c9fa3..8fc3291eaed947 100644 --- a/tools/testing/selftests/ublk/Makefile +++ b/tools/testing/selftests/ublk/Makefile @@ -1,6 +1,6 @@ # SPDX-License-Identifier: GPL-2.0 -CFLAGS += -O3 -Wl,-no-as-needed -Wall -I $(top_srcdir)/usr/include +CFLAGS += -O3 -Wl,-no-as-needed -Wall $(KHDR_INCLUDES) CFLAGS += -D_FILE_OFFSET_BITS=64 ifneq ($(WERROR),0) CFLAGS += -Werror @@ -86,6 +86,7 @@ include ../lib.mk $(OUTPUT)/kublk: $(filter-out $(STANDALONE_UTILS),$(wildcard *.c)) $(OUTPUT)/ublk_cancel_ready: ublk_cancel_ready.c ctrl.c +$(TEST_GEN_PROGS_EXTENDED): | headers check: shellcheck -x -f gcc *.sh From aea1c2ec03b399434ff1bafbb2f0d5076f74ce03 Mon Sep 17 00:00:00 2001 From: Zizhi Wo Date: Mon, 2 Nov 2026 16:04:20 +0800 Subject: [PATCH 2030/2102] block: fix BLKSECDISCARD zero-length range causing page cache invalidation Commit 697ba0b6ec4a ("block: fix integer overflow in BLKSECDISCARD") fixed the start+len overflow via check_add_overflow() but did not handle the start=0, len=0 case. There, start + len = 0, so end = 0 passes all checks, and truncate_bdev_range()->truncate_inode_pages_range() is then called with lend=UINT64_MAX, whitch is the "truncate to the end of file" sentinel, so the entire page cache is invalidated. Fix this by replacing the validation with blk_validate_byte_range(), which already rejects a zero-length range and is what BLKDISCARD uses. This also switches the alignment check from a hardcoded 512 to bdev_logical_block_size(). Fixes: 0bd1ed4860d0 ("block: pass inclusive 'lend' parameter to truncate_inode_pages_range") Signed-off-by: Zizhi Wo Reviewed-by: Yu Kuai Reviewed-by: Christoph Hellwig Reviewed-by: Bart Van Assche Link: https://patch.msgid.link/20261102080420.3774409-1-wozizhi@huaweicloud.com Signed-off-by: Jens Axboe --- block/ioctl.c | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/block/ioctl.c b/block/ioctl.c index fb2f4b4d2505ed..96da0c87802be1 100644 --- a/block/ioctl.c +++ b/block/ioctl.c @@ -177,8 +177,7 @@ static int blk_ioctl_discard(struct block_device *bdev, blk_mode_t mode, static int blk_ioctl_secure_erase(struct block_device *bdev, blk_mode_t mode, void __user *argp) { - uint64_t start, len, end; - uint64_t range[2]; + uint64_t range[2], start, len; int err; if (!(mode & BLK_OPEN_WRITE)) @@ -190,15 +189,13 @@ static int blk_ioctl_secure_erase(struct block_device *bdev, blk_mode_t mode, start = range[0]; len = range[1]; - if ((start & 511) || (len & 511)) - return -EINVAL; - if (check_add_overflow(start, len, &end) || - end > bdev_nr_bytes(bdev)) - return -EINVAL; + err = blk_validate_byte_range(bdev, start, len); + if (err) + return err; inode_lock(bdev->bd_mapping->host); filemap_invalidate_lock(bdev->bd_mapping); - err = truncate_bdev_range(bdev, mode, start, end - 1); + err = truncate_bdev_range(bdev, mode, start, start + len - 1); if (!err) err = blkdev_issue_secure_erase(bdev, start >> 9, len >> 9, GFP_KERNEL); From 348d25516523c3edfec477d56abde2b2491dbf9d Mon Sep 17 00:00:00 2001 From: Zakaria Belkadi Date: Fri, 20 Nov 2026 20:56:44 +0100 Subject: [PATCH 2031/2102] block: bounce user PI when writes may remap reference tags On an io_uring O_DIRECT write, bio_integrity_map_user() can attach the caller's protection information (PI) buffer directly to the bio. The block layer pins the pages for reading, but reference-tag remapping can write to those same pages. A caller with write access to a block device whose integrity profile enables reference-tag remapping can therefore modify a page it can only map for reading. In testing, remapping changed a tag in the page cache of a read-only file. With a PI buffer backed by the shared zero page, the kernel faulted during remapping. Use the existing bounce-buffer path for REQ_OP_WRITE when the queue's integrity profile has BLK_INTEGRITY_REF_TAG set. This copies the PI buffer into kernel memory before remapping, so the caller's buffer retains its original reference tags. I found this issue during a source review assisted by an LLM. Fixes: 3d8b5a22d404 ("block: add support to pass user meta buffer") Cc: stable@vger.kernel.org Suggested-by: Christoph Hellwig Signed-off-by: Zakaria Belkadi Reviewed-by: Martin K. Petersen Reviewed-by: Christoph Hellwig Reviewed-by: Caleb Sander Mateos Link: https://patch.msgid.link/20261120195644.19511-1-zakaria.belkadi@inria.fr Signed-off-by: Jens Axboe --- block/bio-integrity.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/block/bio-integrity.c b/block/bio-integrity.c index d3df726e0f0881..aaea5802ecd5d3 100644 --- a/block/bio-integrity.c +++ b/block/bio-integrity.c @@ -394,6 +394,11 @@ int bio_integrity_map_user(struct bio *bio, struct iov_iter *iter) copy = iov_iter_alignment(iter) & blk_lim_dma_alignment_and_pad(&q->limits); + /* Reference-tag remapping must operate on a private copy of user PI. */ + if (bio_op(bio) == REQ_OP_WRITE && + (q->limits.integrity.flags & BLK_INTEGRITY_REF_TAG)) + copy = true; + if (blk_queue_pci_p2pdma(q)) extraction_flags |= ITER_ALLOW_P2PDMA; From 4aa6ef16095644ecd8ece085384ea65543867dca Mon Sep 17 00:00:00 2001 From: David Yang Date: Sun, 15 Nov 2026 02:42:33 +0800 Subject: [PATCH 2032/2102] dt-bindings: watchdog: arm,sp805: reference the PrimeCell binding Unlike the other PrimeCell bindings, the binding ends in unevaluatedProperties: false without referencing /schemas/arm/primecell.yaml#, so arm,primecell-periphid is not an evaluated property on an arm,sp805 node. Two nodes in the tree carry that property regardless -- watchdog@a2c000 in hisi-x5hd2.dtsi and watchdog@8000 in mps2.dtsi. `make CHECK_DTBS=y`: watchdog@a2c000 (arm,sp805): Unevaluated properties are not allowed ('arm,primecell-periphid' was unexpected) Add the reference so the property becomes evaluable; both nodes then validate. Fixes: 73d3e43f9813 ("dt-bindings: watchdog: sp-805: Convert to Json-schema") Cc: stable@vger.kernel.org Signed-off-by: David Yang Acked-by: Viresh Kumar Reviewed-by: Krzysztof Kozlowski Link: https://patch.msgid.link/20261114184257.535546-1-mmyangfl@gmail.com Signed-off-by: Guenter Roeck --- Documentation/devicetree/bindings/watchdog/arm,sp805.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/watchdog/arm,sp805.yaml b/Documentation/devicetree/bindings/watchdog/arm,sp805.yaml index bd7c09ed193855..690456839fccab 100644 --- a/Documentation/devicetree/bindings/watchdog/arm,sp805.yaml +++ b/Documentation/devicetree/bindings/watchdog/arm,sp805.yaml @@ -16,6 +16,7 @@ description: |+ allOf: - $ref: /schemas/watchdog/watchdog.yaml# + - $ref: /schemas/arm/primecell.yaml# # Need a custom select here or 'arm,primecell' will match on lots of nodes select: From edf8ee40167473828c1ae20ab9c6442f2e66dded Mon Sep 17 00:00:00 2001 From: Fernand Sieber Date: Thu, 12 Nov 2026 18:15:46 +0200 Subject: [PATCH 2033/2102] sched/core: Rank DL server picks as deadline in the core-wide pick Commit 4b26cfdd3956 ("sched/core: Fix priority checking for DL server picks") made the core-wide selection rank a task picked through a DL server as deadline, so that a fair task competing with RT tasks under core scheduling still gets its server's bandwidth. It keys on p->dl_server, which pick_task() used to set. Since commit bd9bbc96e835 ("sched: Rework dl_server"), pick_task() records the server in rq->dl_server and p->dl_server is only set once the task is switched in. The core-wide selection still ranks each sibling's pick with prio_less(), so a task the sibling's server has just picked ranks as a plain fair or ext task and loses to an RT task on another sibling. The server's CPU then runs a task with the RT task's cookie or is forced idle, and the fair task gets none of the server's bandwidth for as long as the RT task runs. Rank each sibling's pick by the server it came through, rq_i->dl_server. prio_less() keeps using p->dl_server for the core tree, whose tasks are not being picked. Fixes: bd9bbc96e835 ("sched: Rework dl_server") Signed-off-by: Fernand Sieber Signed-off-by: Peter Zijlstra (Intel) Signed-off-by: Ingo Molnar Link: https://patch.msgid.link/20261112161548.78189-4-sieberf@amazon.com --- kernel/sched/core.c | 51 +++++++++++++++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 16 deletions(-) diff --git a/kernel/sched/core.c b/kernel/sched/core.c index c9890ed35df7c8..07ec834d54fde6 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -196,12 +196,13 @@ __read_mostly int scheduler_running; DEFINE_STATIC_KEY_FALSE(__sched_core_enabled); /* kernel prio, less is more */ -static inline int __task_prio(const struct task_struct *p) +static inline int __task_prio(const struct task_struct *p, + const struct sched_dl_entity *dl_server) { if (p->sched_class == &stop_sched_class) /* trumps deadline */ return -2; - if (p->dl_server) + if (dl_server) return -1; /* deadline */ if (rt_or_dl_prio(p->prio)) @@ -223,12 +224,19 @@ static inline int __task_prio(const struct task_struct *p) * ge(a,b) := !l(a,b) */ -/* real prio, less is less */ -static inline bool prio_less(const struct task_struct *a, - const struct task_struct *b, bool in_fi) +/* + * real prio, less is less + * + * @a_dl_server and @b_dl_server are the DL servers @a and @b run on + * behalf of, if any. + */ +static inline bool __prio_less(const struct task_struct *a, + const struct sched_dl_entity *a_dl_server, + const struct task_struct *b, + const struct sched_dl_entity *b_dl_server, + bool in_fi) { - - int pa = __task_prio(a), pb = __task_prio(b); + int pa = __task_prio(a, a_dl_server), pb = __task_prio(b, b_dl_server); if (-pa < -pb) return true; @@ -239,18 +247,13 @@ static inline bool prio_less(const struct task_struct *a, if (pa == -1) { /* dl_prio() doesn't work because of stop_class above */ const struct sched_dl_entity *a_dl, *b_dl; - a_dl = &a->dl; /* - * Since,'a' and 'b' can be CFS tasks served by DL server, + * Since 'a' and 'b' can be tasks served by a DL server, * __task_prio() can return -1 (for DL) even for those. In that * case, get to the dl_server's DL entity. */ - if (a->dl_server) - a_dl = a->dl_server; - - b_dl = &b->dl; - if (b->dl_server) - b_dl = b->dl_server; + a_dl = a_dl_server ?: &a->dl; + b_dl = b_dl_server ?: &b->dl; return !dl_time_before(a_dl->deadline, b_dl->deadline); } @@ -266,6 +269,12 @@ static inline bool prio_less(const struct task_struct *a, return false; } +static inline bool prio_less(const struct task_struct *a, + const struct task_struct *b, bool in_fi) +{ + return __prio_less(a, a->dl_server, b, b->dl_server, in_fi); +} + static inline bool __sched_core_less(const struct task_struct *a, const struct task_struct *b) { @@ -6316,6 +6325,7 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) __must_hold(__rq_lockp(rq)) { struct task_struct *next, *p, *max; + struct sched_dl_entity *max_dl_server; bool fi_before = false; bool core_clock_updated = (rq == rq->core); unsigned long cookie; @@ -6429,6 +6439,7 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) * Tie-break prio towards the current CPU */ max = NULL; + max_dl_server = NULL; for_each_core_cpu_wrap(i, rq) { rq_i = cpu_rq(i); @@ -6452,8 +6463,16 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) rq_i->core_pick = p; rq_i->core_dl_server = rq_i->dl_server; - if (!max || prio_less(max, p, fi_before)) + /* + * p->dl_server is only set once @p runs; rank a pick that + * came through a DL server by that server. + */ + if (!max || __prio_less(max, max_dl_server, + p, rq_i->dl_server, + fi_before)) { max = p; + max_dl_server = rq_i->dl_server; + } } cookie = rq->core->core_cookie = max->core_cookie; From 0694c8f58a541d56e3c71a9cacd24155f9463702 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Mon, 23 Nov 2026 16:47:33 -0800 Subject: [PATCH 2034/2102] sched/wait: add WQ_FLAG_POLL_EXCLUSIVE for user space waiters An exclusive waiter whose wake function returns a positive return value to indicate that it has successfully been woken up stops the wakeup walk, on the understanding that it will handle the event. However, user space consumers - like eventpoll or io_uring - want to be woken up, and want to avoid the thundering herd issue. So they used an exclusive wait - but without any actual guarantee that they will then meaningfully handle the event. So the wakeup could be lost, and real waiters would be left pending. Add a separate flag for these kind of "exclusive poll" cases, which is effectively what these user space waiters are. Only the first such entry that accepts a wakeup is woken, as now, but they don't count against nr_exclusive and it doesn't stop the walk. Wake-all (nr_exclusive == 0, including POLLFREE) still calls every entry. Reported-by: Mani Tofigh Reviewed-by: Oleg Nesterov Cc: Jens Axboe Cc: Ingo Molnar Cc: Peter Zijlstra Cc: Juri Lelli Cc: Vincent Guittot Signed-off-by: Linus Torvalds --- include/linux/wait.h | 1 + kernel/sched/wait.c | 14 +++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/include/linux/wait.h b/include/linux/wait.h index b3e94c71cd3e66..09518f8ff10cd4 100644 --- a/include/linux/wait.h +++ b/include/linux/wait.h @@ -21,6 +21,7 @@ int default_wake_function(struct wait_queue_entry *wq_entry, unsigned mode, int #define WQ_FLAG_CUSTOM 0x04 #define WQ_FLAG_DONE 0x08 #define WQ_FLAG_PRIORITY 0x10 +#define WQ_FLAG_POLL_EXCLUSIVE 0x20 /* * A single wait-queue entry structure: diff --git a/kernel/sched/wait.c b/kernel/sched/wait.c index d0521b54eeb3d2..020cf3f77611de 100644 --- a/kernel/sched/wait.c +++ b/kernel/sched/wait.c @@ -85,6 +85,11 @@ EXPORT_SYMBOL(remove_wait_queue); * may be at the head of the list, and can consume the event without any other * tasks being woken if it's also an exclusive task. * + * An exclusive waiter that returns >0 promises to handle the event. Pollers + * (EPOLLEXCLUSIVE) can't promise that, since userspace may never consume it. + * They use WQ_FLAG_POLL_EXCLUSIVE instead: only one of them is woken, but they + * never count against nr_exclusive or stop the walk. + * * There are circumstances in which we can try to wake a task which has already * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns * zero in this (rare) case, and we handle it by continuing to scan the queue. @@ -93,6 +98,7 @@ static int __wake_up_common(struct wait_queue_head *wq_head, unsigned int mode, int nr_exclusive, int wake_flags, void *key) { wait_queue_entry_t *curr, *next; + bool poll_woken = false; lockdep_assert_held(&wq_head->lock); @@ -100,10 +106,16 @@ static int __wake_up_common(struct wait_queue_head *wq_head, unsigned int mode, unsigned flags = curr->flags; int ret; + if ((flags & WQ_FLAG_POLL_EXCLUSIVE) && poll_woken) + continue; ret = curr->func(curr, mode, wake_flags, key); if (ret < 0) break; - if (ret && (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive) + if (!ret) + continue; + if (flags & WQ_FLAG_POLL_EXCLUSIVE) + poll_woken = nr_exclusive > 0; + else if ((flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive) break; } From ad692c9e3ea3a72659ae8e695bfb52cc104c5631 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Mon, 23 Nov 2026 16:47:42 -0800 Subject: [PATCH 2035/2102] eventpoll: don't claim real exclusivity for EPOLLEXCLUSIVE An EPOLLEXCLUSIVE entry that wakes an epoll_wait()er returns 1, and because it was queued as an exclusive waiter that stops the wakeup walk. But nothing makes the epoll user consume the event: it may be killed, time out, pick another ready fd, or just not read. Anything queued behind the entry - a blocked pipe reader, an accept()er, a recv()er - then sleeps with the event pending. Queue it with WQ_FLAG_POLL_EXCLUSIVE instead: still only one epoll instance is woken per wakeup, but real waiters are not skipped. Reported-by: Mani Tofigh Reviewed-by: Oleg Nesterov Cc: Christian Brauner Cc: Ingo Molnar Cc: Peter Zijlstra Cc: Juri Lelli Cc: Vincent Guittot Signed-off-by: Linus Torvalds --- fs/eventpoll.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/fs/eventpoll.c b/fs/eventpoll.c index b959af04772c87..58c0cb845dc722 100644 --- a/fs/eventpoll.c +++ b/fs/eventpoll.c @@ -1626,9 +1626,8 @@ static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead, pwq->whead = whead; pwq->base = epi; if (epi->event.events & EPOLLEXCLUSIVE) - add_wait_queue_exclusive(whead, &pwq->wait); - else - add_wait_queue(whead, &pwq->wait); + pwq->wait.flags |= WQ_FLAG_POLL_EXCLUSIVE; + add_wait_queue(whead, &pwq->wait); pwq->next = epi->pwqlist; epi->pwqlist = pwq; } From c653b1a50661d1e936952c64f2825dc79486bdad Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Mon, 23 Nov 2026 16:47:49 -0800 Subject: [PATCH 2036/2102] io_uring/poll: don't claim real exclusivity for EPOLLEXCLUSIVE Same problem as epoll: an EPOLLEXCLUSIVE poll request returns 1 from io_poll_wake() (even when it lost the ownership race and does nothing), which stops the wakeup walk, but posting a CQE doesn't consume the event. Waiters queued behind it can sleep with the event pending. Use WQ_FLAG_POLL_EXCLUSIVE, so only one io_uring entry is woken but real waiters are not skipped. Reported-by: Mani Tofigh Cc: Jens Axboe Cc: Oleg Nesterov Cc: Ingo Molnar Cc: Peter Zijlstra Cc: Juri Lelli Cc: Vincent Guittot Signed-off-by: Linus Torvalds --- io_uring/poll.c | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/io_uring/poll.c b/io_uring/poll.c index fc1800c7097b53..67bf39575238b6 100644 --- a/io_uring/poll.c +++ b/io_uring/poll.c @@ -533,11 +533,9 @@ static void __io_queue_proc(struct io_poll *poll, struct io_poll_table *pt, poll->head = head; poll->wait.private = (void *) wqe_private; - if (poll->events & EPOLLEXCLUSIVE) { - add_wait_queue_exclusive(head, &poll->wait); - } else { - add_wait_queue(head, &poll->wait); - } + if (poll->events & EPOLLEXCLUSIVE) + poll->wait.flags |= WQ_FLAG_POLL_EXCLUSIVE; + add_wait_queue(head, &poll->wait); } static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head, From fe6ff8d5d675c01793b9f051d16055dd4aa75244 Mon Sep 17 00:00:00 2001 From: Linus Torvalds Date: Sun, 29 Nov 2026 14:20:14 -0800 Subject: [PATCH 2037/2102] Linux 7.4-rc5 --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 9d5bfe5e0b43cc..3bd24ea8ff8937 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ VERSION = 7 PATCHLEVEL = 4 SUBLEVEL = 0 -EXTRAVERSION = -rc4 +EXTRAVERSION = -rc5 NAME = Baby Opossum Posse # *DOCUMENTATION* From 507609718a06fb439944ccd7e621048f3eb01315 Mon Sep 17 00:00:00 2001 From: Arina Kharlamova Date: Sun, 29 Nov 2026 11:27:30 +0400 Subject: [PATCH 2038/2102] ASoC: Intel: atom: Fix double unlock in sst_register_dsp() Commit 71c0f725d35d ("ASoC: Intel: atom: Use guard() for locking") replaced the mutex_lock()/mutex_unlock() pair in sst_register_dsp() with guard(mutex), but left the explicit mutex_unlock() on the -EEXIST path. When a DSP is already registered, sst_lock is now released twice: once by hand and once when the guard goes out of scope. Drop the explicit unlock and let the guard release the mutex. Fixes: 71c0f725d35d ("ASoC: Intel: atom: Use guard() for locking") Cc: stable@vger.kernel.org Signed-off-by: Arina Kharlamova Acked-by: Cezary Rojewski Link: https://patch.msgid.link/20261129-s2p-c01-v1-1-12c1ed41896f@mbzuai.ac.ae Signed-off-by: Mark Brown --- sound/soc/intel/atom/sst-mfld-platform-pcm.c | 1 - 1 file changed, 1 deletion(-) diff --git a/sound/soc/intel/atom/sst-mfld-platform-pcm.c b/sound/soc/intel/atom/sst-mfld-platform-pcm.c index 8c0e4c1d0c0c13..bbd43d1b5bfa32 100644 --- a/sound/soc/intel/atom/sst-mfld-platform-pcm.c +++ b/sound/soc/intel/atom/sst-mfld-platform-pcm.c @@ -37,7 +37,6 @@ int sst_register_dsp(struct sst_device *dev) if (sst) { dev_err(dev->dev, "we already have a device %s\n", sst->name); module_put(dev->dev->driver->owner); - mutex_unlock(&sst_lock); return -EEXIST; } dev_dbg(dev->dev, "registering device %s\n", dev->name); From 9711cbb13f92d25bf67e5ab507923948ad4bfb4d Mon Sep 17 00:00:00 2001 From: Arina Kharlamova Date: Sun, 29 Nov 2026 11:29:05 +0400 Subject: [PATCH 2039/2102] ASoC: Intel: KMB: Unregister the dmaengine PCM on unbind In DMA mode kmb_plat_dai_probe() registers the generic dmaengine PCM with snd_dmaengine_pcm_register(), but nothing unregisters it: the driver has no remove callback, and the probe error path that follows a failed devm_snd_soc_register_component() returns without undoing it. The PCM component, its allocation and the requested DMA channels stay behind after the device is unbound, and the next bind registers a second one on top. Use devm_snd_dmaengine_pcm_register() so that devres releases it on unbind and on probe failure, after the DAI component registered later. Fixes: 11b943c06a1c ("ASoC: Intel: KMB: Enable DMA transfer mode") Signed-off-by: Arina Kharlamova Reviewed-by: Cezary Rojewski Link: https://patch.msgid.link/20261129-s2p-v01-v1-1-a9ca22014892@mbzuai.ac.ae Signed-off-by: Mark Brown --- sound/soc/intel/keembay/kmb_platform.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sound/soc/intel/keembay/kmb_platform.c b/sound/soc/intel/keembay/kmb_platform.c index 1ca8ef95d41e71..2a8cc47ae3b310 100644 --- a/sound/soc/intel/keembay/kmb_platform.c +++ b/sound/soc/intel/keembay/kmb_platform.c @@ -888,8 +888,8 @@ static int kmb_plat_dai_probe(struct platform_device *pdev) } else { kmb_i2s->play_dma_data.addr = res->start + I2S_TXDMA; kmb_i2s->capture_dma_data.addr = res->start + I2S_RXDMA; - ret = snd_dmaengine_pcm_register(&pdev->dev, - NULL, 0); + ret = devm_snd_dmaengine_pcm_register(&pdev->dev, + NULL, 0); if (ret) { dev_err(&pdev->dev, "could not register dmaengine: %d\n", ret); From 8d1e5a7a1b58730654edd6f67a709318feade3c0 Mon Sep 17 00:00:00 2001 From: Siva Subramanian Ravi Saravanan Date: Mon, 30 Nov 2026 14:32:22 +0530 Subject: [PATCH 2040/2102] ASoC: SOF: amd: acp7x: enable ACPI target power states The ACP7.x PM handlers need to distinguish S4 from S3, since the ASP firmware carveout in DDR is lost across S4 but preserved across S3. snd_sof_prepare() derives sdev->system_suspend_target from acpi_target_system_state() only when use_acpi_target_states is set; otherwise it defaults to SOF_SUSPEND_S3, and S4 is never detected. Set use_acpi_target_states for ACP7.B and ACP7.F. Signed-off-by: Siva Subramanian Ravi Saravanan Reviewed-by: Vijendar Mukunda Link: https://patch.msgid.link/20261130090246.3653208-2-sravisar@amd.com Signed-off-by: Mark Brown --- sound/soc/sof/amd/pci-acp7x.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sound/soc/sof/amd/pci-acp7x.c b/sound/soc/sof/amd/pci-acp7x.c index 5a21ab8ebb4b9b..b27798f2007bcf 100644 --- a/sound/soc/sof/amd/pci-acp7x.c +++ b/sound/soc/sof/amd/pci-acp7x.c @@ -66,6 +66,7 @@ static const struct sof_dev_desc acp7b_desc = { .nocodec_tplg_filename = "sof-acp.tplg", .ops = &sof_acp7x_ops, .ops_init = sof_acp7x_ops_init, + .use_acpi_target_states = true, }; static const struct sof_amd_acp_desc acp7f_chip_info = { @@ -108,6 +109,7 @@ static const struct sof_dev_desc acp7f_desc = { .nocodec_tplg_filename = "sof-acp.tplg", .ops = &sof_acp7x_ops, .ops_init = sof_acp7x_ops_init, + .use_acpi_target_states = true, }; static const struct pci_device_id acp7b_pci_id = { From f256500eae71f0a37bf25d67cf4e6b972167c0c1 Mon Sep 17 00:00:00 2001 From: Siva Subramanian Ravi Saravanan Date: Mon, 30 Nov 2026 14:32:23 +0530 Subject: [PATCH 2041/2102] ASoC: SOF: amd: acp7x: reload firmware from disk on S4 resume On S4 (hibernate) the ASP carveout in DDR loses power, so the raw firmware image previously deposited there by VALIDATE_IMAGE is gone. acp7x_load_firmware_carveout() skips VALIDATE_IMAGE whenever fw_code_carveout_addr is already set and SHA-DMAs directly from the carveout, which on S4 resume would read an empty carveout and fail to boot the DSP. Clear fw_code_carveout_addr at the start of amd_sof_acp7x_resume() when the system suspend target is deeper than S3, so the loader takes the full request_firmware() + VALIDATE_IMAGE path and re-deposits the image into the carveout. Doing this before the SoundWire clock-stop and acp_init()/acp_memory_init() early returns ensures it is never skipped. Resume is used rather than suspend because the platform suspend callback is not invoked when the DSP is already runtime suspended. snd_sof_prepare() leaves the target at S3 without querying ACPI when the firmware has crashed or failed to boot, so S4 cannot be detected in that case. Also clear fw_code_carveout_addr in amd_sof_acp7x_suspend() for those firmware states. S0ix/s2idle resume is unaffected and keeps the fast SHA-DMA path, as the carveout contents are preserved. Fixes: cec3598305a6 ("ASoC: SOF: amd: add ASP carveout firmware loading for ACP7.B/7.F") Signed-off-by: Siva Subramanian Ravi Saravanan Reviewed-by: Vijendar Mukunda Link: https://patch.msgid.link/20261130090246.3653208-3-sravisar@amd.com Signed-off-by: Mark Brown --- sound/soc/sof/amd/acp.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/sound/soc/sof/amd/acp.c b/sound/soc/sof/amd/acp.c index 8039b2450cf3ef..2846d9042207f5 100644 --- a/sound/soc/sof/amd/acp.c +++ b/sound/soc/sof/amd/acp.c @@ -1586,6 +1586,12 @@ int amd_sof_acp7x_suspend(struct snd_sof_dev *sdev, u32 target_state) acp_data = sdev->pdata->hw_pdata; + /* snd_sof_prepare() can't detect S4 if FW crashed; reload from disk */ + if (acp_data->asp_carveout_base && + (sdev->fw_state == SOF_FW_CRASHED || + sdev->fw_state == SOF_FW_BOOT_FAILED)) + acp_data->fw_code_carveout_addr = 0; + if (acp_data->is_sdw_dev && check_acp_sdw_enable_status(sdev)) { snd_sof_dsp_write(sdev, ACP_DSP_BAR, ACP7X_ZSC_DSP_CTRL, 1); return acp_dsp_reset(sdev); @@ -1656,6 +1662,11 @@ int amd_sof_acp7x_resume(struct snd_sof_dev *sdev) acp_data = sdev->pdata->hw_pdata; + /* Carveout is unpowered in S4/S5; force a full firmware reload */ + if (acp_data->asp_carveout_base && + sdev->system_suspend_target > SOF_SUSPEND_S3) + acp_data->fw_code_carveout_addr = 0; + if (acp_data->sdw_en_stat) { snd_sof_dsp_write(sdev, ACP_DSP_BAR, ACP7X_ZSC_DSP_CTRL, 0); snd_sof_dsp_write(sdev, ACP_DSP_BAR, ACP7X_PME_EN, 1); From bc34e9913b7e78ec0d5310102b1048943008a6e0 Mon Sep 17 00:00:00 2001 From: Rafael Diniz Date: Sat, 28 Nov 2026 09:23:05 +0000 Subject: [PATCH 2042/2102] ASoC: wm8731: use one sample width for both directions Playback and capture share one interface format register (IFACE), whose IWL field sets the word length for both directions, as SRATE sets one sample rate for both. symmetric_rate already makes a second stream use the rate of the running one, but a second stream at a different width rewrites IWL under the running stream, which then carries samples of the wrong length. Set symmetric_sample_bits, so the second stream gets the width of the running one. Its hw_params then writes back the values already there; rewriting SRATE and IFACE with their values under an active interface stayed healthy in 12 of 12 trials on the hardware below. Tested on a Raspberry Pi 4 with the AudioInjector stereo card, 6.18.60 (Raspberry Pi kernel, where the driver is the same as here): with a 32-bit capture stream running, a 16-bit playback stream is refused as a format not available, and the register trace shows no write to IFACE. Built with W=1 on mainline. This patch and its changelog were written with Claude Code (Claude Opus 5.5) following the review of v2. Signed-off-by: Rafael Diniz Reviewed-by: Charles Keepax Link: https://patch.msgid.link/20261128092306.1566199-3-rafael@riseup.net Signed-off-by: Mark Brown --- sound/soc/codecs/wm8731.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/soc/codecs/wm8731.c b/sound/soc/codecs/wm8731.c index f25b50919a9a58..f22f57b05ff27d 100644 --- a/sound/soc/codecs/wm8731.c +++ b/sound/soc/codecs/wm8731.c @@ -557,6 +557,7 @@ static struct snd_soc_dai_driver wm8731_dai = { .formats = WM8731_FORMATS,}, .ops = &wm8731_dai_ops, .symmetric_rate = 1, + .symmetric_sample_bits = 1, }; static const struct snd_soc_component_driver soc_component_dev_wm8731 = { From e6c245ad55241411e6237eeba7b92c7d99acc374 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Wed, 25 Nov 2026 17:48:33 +0700 Subject: [PATCH 2043/2102] ASoC: stm32: i2s: Use devm helpers and drop remove callback Commit caff4ce8cc58 ("ASoC: stm32: i2s: manage rebind issue") switched to explicit registration and unregistration to address a sound card rebind issue. Commit 58f30150ffd6 ("ASoC: core: Remove only the registered component in devm functions") fixed the underlying issue in the ASoC core, so devm helpers can now be used again. Also use devm_pm_runtime_enable(), which fixes the unbalanced pm_runtime_disable() in the probe error path. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261125104833.514491-1-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/stm/stm32_i2s.c | 42 +++++++++++++-------------------------- 1 file changed, 14 insertions(+), 28 deletions(-) diff --git a/sound/soc/stm/stm32_i2s.c b/sound/soc/stm/stm32_i2s.c index 79465be82cb8b4..e6e861a957dc70 100644 --- a/sound/soc/stm/stm32_i2s.c +++ b/sound/soc/stm/stm32_i2s.c @@ -1255,13 +1255,6 @@ static int stm32_i2s_parse_dt(struct platform_device *pdev, return 0; } -static void stm32_i2s_remove(struct platform_device *pdev) -{ - snd_dmaengine_pcm_unregister(&pdev->dev); - snd_soc_unregister_component(&pdev->dev); - pm_runtime_disable(&pdev->dev); -} - static int stm32_i2s_probe(struct platform_device *pdev) { struct stm32_i2s_data *i2s; @@ -1301,56 +1294,50 @@ static int stm32_i2s_probe(struct platform_device *pdev) if (ret) return ret; - ret = snd_dmaengine_pcm_register(&pdev->dev, &stm32_i2s_pcm_config, 0); + ret = devm_pm_runtime_enable(&pdev->dev); if (ret) return ret; - ret = snd_soc_register_component(&pdev->dev, &stm32_i2s_component, - i2s->dai_drv, 1); - if (ret) { - snd_dmaengine_pcm_unregister(&pdev->dev); + ret = devm_snd_dmaengine_pcm_register(&pdev->dev, &stm32_i2s_pcm_config, 0); + if (ret) + return ret; + + ret = devm_snd_soc_register_component(&pdev->dev, &stm32_i2s_component, + i2s->dai_drv, 1); + if (ret) return ret; - } /* Set SPI/I2S in i2s mode */ ret = regmap_update_bits(i2s->regmap, STM32_I2S_CGFR_REG, I2S_CGFR_I2SMOD, I2S_CGFR_I2SMOD); if (ret) - goto error; + return ret; ret = regmap_read(i2s->regmap, STM32_I2S_IPIDR_REG, &val); if (ret) - goto error; + return ret; if (val == I2S_IPIDR_NUMBER) { ret = regmap_read(i2s->regmap, STM32_I2S_HWCFGR_REG, &val); if (ret) - goto error; + return ret; if (!FIELD_GET(I2S_HWCFGR_I2S_SUPPORT_MASK, val)) { dev_err(&pdev->dev, "Device does not support i2s mode\n"); - ret = -EPERM; - goto error; + return -EPERM; } ret = regmap_read(i2s->regmap, STM32_I2S_VERR_REG, &val); if (ret) - goto error; + return ret; dev_dbg(&pdev->dev, "I2S version: %lu.%lu registered\n", FIELD_GET(I2S_VERR_MAJ_MASK, val), FIELD_GET(I2S_VERR_MIN_MASK, val)); } - pm_runtime_enable(&pdev->dev); - - return ret; - -error: - stm32_i2s_remove(pdev); - - return ret; + return 0; } MODULE_DEVICE_TABLE(of, stm32_i2s_ids); @@ -1384,7 +1371,6 @@ static struct platform_driver stm32_i2s_driver = { .pm = pm_ptr(&stm32_i2s_pm_ops), }, .probe = stm32_i2s_probe, - .remove = stm32_i2s_remove, }; module_platform_driver(stm32_i2s_driver); From ecbaa9735c69558c3369ba1574c9103150d38730 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Fri, 20 Nov 2026 17:46:29 +0700 Subject: [PATCH 2044/2102] ASoC: atmel: mchp-pdmc: Mark IMR as volatile The interrupt handler reads ISR and IMR to determine which interrupts are pending. While ISR is marked as volatile, IMR is not, causing regmap to return its cached value instead of reading the hardware. Add IMR to the volatile registers. Fixes: c5682e2ba132 ("ASoC: mchp-pdmc: fix poc noise at capture startup") Fixes: e8c8e9de4ee3 ("ASoC: mchp-pdmc: use runtime pm for clock power saving") Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261120104630.10240-2-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-pdmc.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/soc/atmel/mchp-pdmc.c b/sound/soc/atmel/mchp-pdmc.c index 039b2eba0d9de5..cc98f3b59d76a1 100644 --- a/sound/soc/atmel/mchp-pdmc.c +++ b/sound/soc/atmel/mchp-pdmc.c @@ -832,6 +832,7 @@ static bool mchp_pdmc_volatile_reg(struct device *dev, unsigned int reg) { switch (reg) { case MCHP_PDMC_ISR: + case MCHP_PDMC_IMR: case MCHP_PDMC_RHR: return true; default: From fe9d304ebb68a8fa159eb58ee01068382ae29cd1 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Fri, 20 Nov 2026 17:46:30 +0700 Subject: [PATCH 2045/2102] ASoC: atmel: mchp-spdiftx: Mark interrupt registers as volatile The interrupt handler reads ISR and IMR to determine which interrupts are pending. Neither register is marked as volatile, causing regmap to return cached values instead of reading the hardware. Add a volatile_reg callback marking IMR and ISR as volatile. Fixes: 4bf54ca60f99 ("ASoC: mchp-spdiftx: add runtime pm support") Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261120104630.10240-3-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-spdiftx.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/sound/soc/atmel/mchp-spdiftx.c b/sound/soc/atmel/mchp-spdiftx.c index fc635ed6856e15..6a493b4b0d7a25 100644 --- a/sound/soc/atmel/mchp-spdiftx.c +++ b/sound/soc/atmel/mchp-spdiftx.c @@ -165,6 +165,17 @@ static bool mchp_spdiftx_precious_reg(struct device *dev, unsigned int reg) } } +static bool mchp_spdiftx_volatile_reg(struct device *dev, unsigned int reg) +{ + switch (reg) { + case SPDIFTX_IMR: + case SPDIFTX_ISR: + return true; + default: + return false; + } +} + static const struct regmap_config mchp_spdiftx_regmap_config = { .reg_bits = 32, .reg_stride = 4, @@ -173,6 +184,7 @@ static const struct regmap_config mchp_spdiftx_regmap_config = { .readable_reg = mchp_spdiftx_readable_reg, .writeable_reg = mchp_spdiftx_writeable_reg, .precious_reg = mchp_spdiftx_precious_reg, + .volatile_reg = mchp_spdiftx_volatile_reg, .cache_type = REGCACHE_FLAT, }; From b1ff4cf03d7e023fd79b1088216806a5cf591bcd Mon Sep 17 00:00:00 2001 From: Ian Rogers Date: Thu, 19 Nov 2026 09:07:58 -0800 Subject: [PATCH 2046/2102] ASoC: codecs: lpass-rx-macro: Return early for non-HPH interpolators in HD2 control rx_macro_enable_interp() invokes rx_macro_hd2_control() whenever rx->hph_hd2_mode is enabled, including for INTERP_AUX. However, rx_macro_hd2_control() only assigns hd2_scale_reg and hd2_enable_reg for INTERP_HPHL and INTERP_HPHR, leaving both u16 register offsets uninitialized on the stack for INTERP_AUX before testing 'if (hd2_enable_reg && ...)' and writing to random codec register addresses. Return immediately in the default branch of switch (interp_idx). Found via an x86_64 LLVM=1 (Clang 21.1.8) allyesconfig audit with -Wconditional-uninitialized enabled; fix and changelog drafted with an AI coding assistant. Build-tested under LLVM=1 W=1 (-Werror) and -Wconditional-uninitialized; not tested on Qualcomm LPASS audio hardware. Fixes: 4f692926f562 ("ASoC: codecs: lpass-rx-macro: add dapm widgets and route") Signed-off-by: Ian Rogers Link: https://patch.msgid.link/8af31a87f52c4cebc5ac7db6696a91545adb6ac4.1795106962.git.irogers@google.com Signed-off-by: Mark Brown --- sound/soc/codecs/lpass-rx-macro.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sound/soc/codecs/lpass-rx-macro.c b/sound/soc/codecs/lpass-rx-macro.c index ab8a1c2b0489b8..84a3a47cf9327c 100644 --- a/sound/soc/codecs/lpass-rx-macro.c +++ b/sound/soc/codecs/lpass-rx-macro.c @@ -2414,6 +2414,8 @@ static void rx_macro_hd2_control(struct snd_soc_component *component, hd2_scale_reg = CDC_RX_RXn_RX_PATH_SEC3(rx, 1); hd2_enable_reg = CDC_RX_RXn_RX_PATH_CFG0(rx, 1); break; + default: + return; } if (hd2_enable_reg && SND_SOC_DAPM_EVENT_ON(event)) { From 25ea3210cb653ecc2c6d97bdee092532be55aa20 Mon Sep 17 00:00:00 2001 From: Ian Rogers Date: Thu, 19 Nov 2026 09:07:59 -0800 Subject: [PATCH 2047/2102] ASoC: qcom: lpass-platform: Return IRQ_NONE on invalid DAI ID in DMA ISR In lpass_dma_interrupt_handler(), the default switch branch returns -EINVAL from an irqreturn_t handler, which triggers report_bad_irq() in note_interrupt() instead of reporting an unhandled interrupt. Return IRQ_NONE, matching the other error paths in lpass_dma_interrupt_handler(). Found via Clang -Wassign-enum on an x86_64 allyesconfig build. Verified by building sound/soc/qcom/lpass-platform.o with LLVM=1 W=1 (-Werror) and -Wassign-enum; not runtime-tested on Qualcomm LPASS hardware. Fixes: 7cb37b7bd0d3 ("ASoC: qcom: Add support for lpass hdmi driver") Signed-off-by: Ian Rogers Link: https://patch.msgid.link/1de898fc85710c85f6f90bb685d3be109f44c2ba.1795106962.git.irogers@google.com Signed-off-by: Mark Brown --- sound/soc/qcom/lpass-platform.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sound/soc/qcom/lpass-platform.c b/sound/soc/qcom/lpass-platform.c index dad4becf7579e0..45379604b68963 100644 --- a/sound/soc/qcom/lpass-platform.c +++ b/sound/soc/qcom/lpass-platform.c @@ -963,8 +963,9 @@ static irqreturn_t lpass_dma_interrupt_handler( val = 0; break; default: - dev_err(soc_runtime->dev, "%s: invalid %d interface\n", __func__, dai_id); - return -EINVAL; + dev_err(soc_runtime->dev, "%s: invalid %d interface\n", + __func__, dai_id); + return IRQ_NONE; } if (interrupts & LPAIF_IRQ_PER(chan)) { rv = regmap_write_bits(map, reg, mask, (LPAIF_IRQ_PER(chan) | val)); From 376530c27556efca1e6ab7bea495b9bf2d6ac351 Mon Sep 17 00:00:00 2001 From: Demeter Barna Date: Fri, 27 Nov 2026 00:49:41 +0000 Subject: [PATCH 2048/2102] ASoC: qcom: sm8250: Add SM8350 sound card Give the SM8350 sound card its own driver name, so UCM files can tell it from SM8250. Signed-off-by: Demeter Barna Reviewed-by: Srinivas Kandagatla Link: https://patch.msgid.link/20261127-sm8350-sndcard-v1-1-50cbf3db3cb0@fromdisposition.org Signed-off-by: Mark Brown --- sound/soc/qcom/sm8250.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/soc/qcom/sm8250.c b/sound/soc/qcom/sm8250.c index d0015e5f525761..ba0aaf4282ad27 100644 --- a/sound/soc/qcom/sm8250.c +++ b/sound/soc/qcom/sm8250.c @@ -231,6 +231,7 @@ static const struct of_device_id snd_sm8250_dt_match[] = { { .compatible = "qcom,qrb5165-rb5-sndcard", .data = "sm8250" }, { .compatible = "qcom,sdm660-sndcard", .data = "sdm660" }, { .compatible = "qcom,sm8250-sndcard", .data = "sm8250" }, + { .compatible = "qcom,sm8350-sndcard", .data = "sm8350" }, {} }; From 314917853456f7ce6ea0d73c782b5c8113c3f8c2 Mon Sep 17 00:00:00 2001 From: Hyunuk Son Date: Fri, 27 Nov 2026 18:07:06 +0900 Subject: [PATCH 2049/2102] ASoC: dt-bindings: Add Iron Device MA5311 The Iron Device MA5311 is an audio codec integrating digital speaker amplification, analog-to-digital conversion, and audio DSP functionality. The device uses two I2C slave addresses for separate control and ADC register banks. It also provides an active-low reset input and an interrupt output for fault and thermal warning notification. Add the Device Tree binding to describe these hardware interfaces. Reviewed-by: Krzysztof Kozlowski Signed-off-by: Hyunuk Son Link: https://patch.msgid.link/20261127090707.389362-2-hyunuk.son@irondevice.com Signed-off-by: Mark Brown --- .../bindings/sound/irondevice,ma5311.yaml | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Documentation/devicetree/bindings/sound/irondevice,ma5311.yaml diff --git a/Documentation/devicetree/bindings/sound/irondevice,ma5311.yaml b/Documentation/devicetree/bindings/sound/irondevice,ma5311.yaml new file mode 100644 index 00000000000000..d013d539e0ef53 --- /dev/null +++ b/Documentation/devicetree/bindings/sound/irondevice,ma5311.yaml @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/sound/irondevice,ma5311.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Iron Device MA5311 Audio Codec + +maintainers: + - Hyunuk Son + +description: + The Iron Device MA5311 integrates digital speaker amplification, + analog-to-digital conversion, and audio DSP functionality. + + The device uses two I2C slave addresses. The first address + provides access to the control register bank, while the second + provides access to the ADC register bank. + + The device provides an active-low reset input and an active-low + interrupt output for fault and thermal warning notification. + +allOf: + - $ref: dai-common.yaml# + +properties: + compatible: + enum: + - irondevice,ma5311 + + reg: + items: + - description: I2C address for control registers + - description: I2C address for ADC registers + + reg-names: + items: + - const: control + - const: adc + + reset-gpios: + maxItems: 1 + description: + GPIO connected to the active-low RSTN pin. + + interrupts: + maxItems: 1 + description: + Falling-edge interrupt from the active-low INTN output. + INTN is deasserted when the fault condition clears. + + '#sound-dai-cells': + const: 1 + +required: + - compatible + - reg + - reg-names + - '#sound-dai-cells' + +unevaluatedProperties: false + +examples: + - | + #include + #include + + i2c { + #address-cells = <1>; + #size-cells = <0>; + + audio-codec@3e { + compatible = "irondevice,ma5311"; + + reg = <0x3e>, <0x3f>; + reg-names = "control", "adc"; + + reset-gpios = <&gpio 2 GPIO_ACTIVE_LOW>; + interrupt-parent = <&gpio>; + interrupts = <3 IRQ_TYPE_EDGE_FALLING>; + + #sound-dai-cells = <1>; + }; + }; From 3fcfb6c8a602a58d8fc9443a9bb560c7b12fdcee Mon Sep 17 00:00:00 2001 From: Hyunuk Son Date: Fri, 27 Nov 2026 18:07:07 +0900 Subject: [PATCH 2050/2102] ASoC: codecs: Add driver for Iron Device MA5311 Add an ASoC codec driver for the Iron Device MA5311. The driver supports audio playback and capture through I2S and TDM interfaces. It provides ALSA mixer controls for audio configuration and uses regmap for register access. Signed-off-by: Hyunuk Son Link: https://patch.msgid.link/20261127090707.389362-3-hyunuk.son@irondevice.com Signed-off-by: Mark Brown --- MAINTAINERS | 2 + sound/soc/codecs/Kconfig | 12 + sound/soc/codecs/Makefile | 2 + sound/soc/codecs/ma5311.c | 2300 +++++++++++++++++++++++++++++++++++++ sound/soc/codecs/ma5311.h | 558 +++++++++ 5 files changed, 2874 insertions(+) create mode 100644 sound/soc/codecs/ma5311.c create mode 100644 sound/soc/codecs/ma5311.h diff --git a/MAINTAINERS b/MAINTAINERS index ccbcdc0799b9fb..4b1896f9cbd810 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -14121,9 +14121,11 @@ F: net/netfilter/ipvs/ IRON DEVICE AUDIO CODEC DRIVERS M: Kiseok Jo +M: Hyunuk Son L: linux-sound@vger.kernel.org S: Maintained F: Documentation/devicetree/bindings/sound/irondevice,* +F: sound/soc/codecs/ma5311.* F: sound/soc/codecs/sma* IRQ DOMAINS (IRQ NUMBER MAPPING LIBRARY) diff --git a/sound/soc/codecs/Kconfig b/sound/soc/codecs/Kconfig index ba59dabeeccde5..7f9d554e657b58 100644 --- a/sound/soc/codecs/Kconfig +++ b/sound/soc/codecs/Kconfig @@ -143,6 +143,7 @@ config SND_SOC_ALL_CODECS imply SND_SOC_LM4857 imply SND_SOC_LM49453 imply SND_SOC_LOCHNAGAR_SC + imply SND_SOC_MA5311 imply SND_SOC_MAX98088 imply SND_SOC_MAX98090 imply SND_SOC_MAX98095 @@ -1423,6 +1424,17 @@ config SND_SOC_LOCHNAGAR_SC This driver support the sound card functionality of the Cirrus Logic Lochnagar audio development board. +config SND_SOC_MA5311 + tristate "Iron Device MA5311 Audio Codec" + depends on I2C && GPIOLIB + select REGMAP_I2C + help + Enable support for the Iron Device MA5311 audio codec with + playback and capture over an I2S/TDM interface. + + To compile this driver as a module, choose M here: the module + will be called snd-soc-ma5311. + config SND_SOC_MADERA tristate select SND_SOC_WM_ADSP diff --git a/sound/soc/codecs/Makefile b/sound/soc/codecs/Makefile index 3826f9e4fce8a2..0b774afbe32714 100644 --- a/sound/soc/codecs/Makefile +++ b/sound/soc/codecs/Makefile @@ -165,6 +165,7 @@ snd-soc-lpass-rx-macro-y := lpass-rx-macro.o snd-soc-lpass-tx-macro-y := lpass-tx-macro.o snd-soc-lpass-wsa-macro-y := lpass-wsa-macro.o snd-soc-lpass-va-macro-y := lpass-va-macro.o +snd-soc-ma5311-y := ma5311.o snd-soc-madera-y := madera.o snd-soc-max9759-y := max9759.o snd-soc-max9768-y := max9768.o @@ -608,6 +609,7 @@ obj-$(CONFIG_SND_SOC_JZ4770_CODEC) += snd-soc-jz4770-codec.o obj-$(CONFIG_SND_SOC_LM4857) += snd-soc-lm4857.o obj-$(CONFIG_SND_SOC_LM49453) += snd-soc-lm49453.o obj-$(CONFIG_SND_SOC_LOCHNAGAR_SC) += snd-soc-lochnagar-sc.o +obj-$(CONFIG_SND_SOC_MA5311) += snd-soc-ma5311.o obj-$(CONFIG_SND_SOC_MADERA) += snd-soc-madera.o obj-$(CONFIG_SND_SOC_MAX9759) += snd-soc-max9759.o obj-$(CONFIG_SND_SOC_MAX9768) += snd-soc-max9768.o diff --git a/sound/soc/codecs/ma5311.c b/sound/soc/codecs/ma5311.c new file mode 100644 index 00000000000000..d548fcd0267b48 --- /dev/null +++ b/sound/soc/codecs/ma5311.c @@ -0,0 +1,2300 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// ma5311.c -- ma5311 ALSA SoC Audio driver +// +// Copyright 2026 Iron Device Corporation +// +// Author: Gyuhwa Park +// Author: Hyunuk Son + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ma5311.h" + +/* Board-selected delays; RSTN timing has not been hardware-validated. */ +#define MA5311_RESET_ASSERT_MS 50 +#define MA5311_RESET_RECOVERY_MS 50 + +#define MA5311_PLL_MATCH(_input_clk, _post_n, _n, _f1, _f2, _f3_p_cp) \ + { \ + .input_clk = (_input_clk), \ + .post_n = (_post_n), \ + .n = (_n), \ + .f1 = (_f1), \ + .f2 = (_f2), \ + .f3_p_cp = (_f3_p_cp), \ + } + +struct ma5311_pll_match { + unsigned int input_clk; + unsigned int post_n; + unsigned int n; + unsigned int f1; + unsigned int f2; + unsigned int f3_p_cp; +}; + +struct ma5311_priv { + bool amp_power_status; + bool adc_power_status; + enum ma5311_mode amp_mode; + unsigned int num_of_pll_matches; + struct device *dev; + struct regmap *ctrl_regmap; + struct i2c_client *adc_client; + struct regmap *adc_regmap; + struct gpio_desc *reset_gpio; + const struct ma5311_pll_match *pll_matches; + unsigned int format; + unsigned int frame_size; + unsigned int last_bclk; + unsigned int sys_clk_id; + + /* For dai configuration backup */ + unsigned int dai_sys_clk; /* 0x00: MA5311_DAC_CLKSYSTEM_MASK */ + unsigned int dai_clk_mode; + unsigned int dai_leftpol; + unsigned int dai_sck_edge; + unsigned int dai_spk_mute; + unsigned int dai_tdm1_rx_pos; + unsigned int dai_tdm2_data_len; + unsigned int dai_tdm2_capture_cfg; + unsigned int dai_data_path; + unsigned int dai_tdm_slot_enable; + unsigned int dai_pll_input; /* 0xa2: PLL input and reference clock selection */ + unsigned int dai_pll_post_n; + unsigned int dai_pll_n; + unsigned int dai_pll_f1; + unsigned int dai_pll_f2; + unsigned int dai_pll_f3_p_cp; + unsigned int dai_sdo_len; + unsigned int dai_sck_rate; + unsigned int dai_o_format; + unsigned int dai_adc_mix_ch; + unsigned int dai_mas_clk_sel; /* 0xb8: MA5311_LRCK_SCK_MAS_CLK_SEL_MASK */ + unsigned int dai_adc_clk; /* 0xb8: MA5311_DAC_ADC_CLK_ON_MASK */ + + unsigned int dai_adc1_word_len; + unsigned int dai_adc1_sck_rate; + unsigned int dai_adc2_word_len; + unsigned int dai_adc2_sck_rate; + unsigned int dai_adc3_word_len; + unsigned int dai_adc3_sck_rate; + unsigned int dai_adc4_word_len; + unsigned int dai_adc4_sck_rate; + + bool flag_ext_rst; + bool flag_dai_tdm; +}; + +static const struct ma5311_pll_match ma5311_pll_matches[] = { + /* Input clock in Hz; register values produce a 24.576 MHz PLL clock. */ + MA5311_PLL_MATCH(1536000, 0x07, 0xE0, 0x00, 0x00, 0x03), + MA5311_PLL_MATCH(3072000, 0x07, 0x70, 0x00, 0x00, 0x03), + MA5311_PLL_MATCH(6144000, 0x07, 0x70, 0x00, 0x00, 0x07), + MA5311_PLL_MATCH(12288000, 0x07, 0x70, 0x00, 0x00, 0x0B), +}; + +static const struct reg_default ma5311_ctrl_reg_def[] = { + { 0x00, 0x08 }, + { 0x01, 0x00 }, + { 0x02, 0x00 }, + { 0x03, 0x01 }, + { 0x04, 0x17 }, + { 0x05, 0x01 }, + { 0x09, 0x00 }, + { 0x0A, 0x58 }, + { 0x0B, 0x58 }, + { 0x0E, 0xAF }, + { 0x0F, 0x0F }, + { 0x10, 0x00 }, + { 0x11, 0x00 }, + { 0x12, 0x01 }, + { 0x14, 0x5B }, + { 0x15, 0x01 }, + { 0x16, 0x0F }, + { 0x17, 0x0F }, + { 0x18, 0x0F }, + { 0x19, 0x00 }, + { 0x1A, 0x00 }, + { 0x1B, 0x00 }, + { 0x23, 0x19 }, + { 0x24, 0x00 }, + { 0x25, 0x00 }, + { 0x26, 0x04 }, + { 0x2B, 0x00 }, + { 0x2C, 0x0C }, + { 0x2D, 0x0C }, + { 0x2E, 0x0C }, + { 0x2F, 0x0C }, + { 0x30, 0x0C }, + { 0x33, 0x2C }, + { 0x34, 0x00 }, + { 0x35, 0x00 }, + { 0x36, 0x92 }, + { 0x37, 0x01 }, + { 0x38, 0x41 }, + { 0x39, 0x00 }, + { 0x3A, 0x00 }, + { 0x3B, 0x00 }, + { 0x3C, 0x00 }, + { 0x3D, 0x00 }, + { 0x40, 0x00 }, + { 0x41, 0x00 }, + { 0x42, 0x00 }, + { 0x43, 0x00 }, + { 0x44, 0x00 }, + { 0x45, 0x00 }, + { 0x46, 0x20 }, + { 0x47, 0x00 }, + { 0x48, 0x00 }, + { 0x49, 0x00 }, + { 0x4A, 0x00 }, + { 0x4B, 0x00 }, + { 0x4C, 0x00 }, + { 0x4D, 0x00 }, + { 0x4E, 0x00 }, + { 0x4F, 0x00 }, + { 0x50, 0x00 }, + { 0x51, 0x00 }, + { 0x52, 0x00 }, + { 0x53, 0x00 }, + { 0x54, 0x00 }, + { 0x55, 0x20 }, + { 0x56, 0x00 }, + { 0x57, 0x00 }, + { 0x58, 0x00 }, + { 0x59, 0x00 }, + { 0x5A, 0x00 }, + { 0x5B, 0x00 }, + { 0x5C, 0x00 }, + { 0x5D, 0x00 }, + { 0x5E, 0x00 }, + { 0x5F, 0x00 }, + { 0x60, 0x00 }, + { 0x61, 0x00 }, + { 0x62, 0x00 }, + { 0x63, 0x00 }, + { 0x64, 0x20 }, + { 0x65, 0x00 }, + { 0x66, 0x00 }, + { 0x67, 0x00 }, + { 0x68, 0x00 }, + { 0x69, 0x00 }, + { 0x6A, 0x00 }, + { 0x6B, 0x00 }, + { 0x6C, 0x00 }, + { 0x6D, 0x00 }, + { 0x6E, 0x00 }, + { 0x6F, 0x00 }, + { 0x70, 0x00 }, + { 0x71, 0x00 }, + { 0x72, 0x00 }, + { 0x73, 0x20 }, + { 0x74, 0x00 }, + { 0x75, 0x00 }, + { 0x76, 0x00 }, + { 0x77, 0x00 }, + { 0x78, 0x00 }, + { 0x79, 0x00 }, + { 0x7A, 0x00 }, + { 0x7B, 0x00 }, + { 0x7C, 0x00 }, + { 0x7D, 0x00 }, + { 0x7E, 0x00 }, + { 0x7F, 0x00 }, + { 0x80, 0x00 }, + { 0x81, 0x00 }, + { 0x82, 0x20 }, + { 0x83, 0x00 }, + { 0x84, 0x00 }, + { 0x85, 0x00 }, + { 0x86, 0x00 }, + { 0x87, 0x00 }, + { 0x88, 0x00 }, + { 0x89, 0x00 }, + { 0x8A, 0x00 }, + { 0x8B, 0x08 }, + { 0x8C, 0x20 }, + { 0x8D, 0x00 }, + { 0x8E, 0x00 }, + { 0x8F, 0x02 }, + { 0x91, 0x00 }, + { 0xA1, 0x40 }, + { 0xA2, 0x48 }, + { 0xA3, 0x20 }, + { 0xA4, 0x00 }, + { 0xA5, 0x1A }, + { 0xA6, 0x52 }, + { 0xA7, 0x00 }, + { 0xA8, 0x28 }, + { 0xA9, 0x25 }, + { 0xAA, 0x44 }, + { 0xAB, 0x62 }, + { 0xAC, 0x04 }, + { 0xAD, 0x00 }, + { 0xAE, 0x00 }, + { 0xAF, 0x00 }, + { 0xB0, 0x00 }, + { 0xB1, 0x00 }, + { 0xB2, 0x00 }, + { 0xB3, 0x04 }, + { 0xB4, 0x00 }, + { 0xB5, 0x00 }, + { 0xB7, 0x20 }, + { 0xB8, 0x44 }, + { 0xB9, 0x0B }, + { 0xBB, 0x42 }, + { 0xBC, 0x82 }, + { 0xBD, 0x61 }, + { 0xBE, 0x67 }, + { 0xBF, 0x67 }, +}; + +static const struct reg_default ma5311_adc_reg_def[] = { + { 0x00, 0x89 }, + { 0x01, 0x6C }, + { 0x02, 0x07 }, + { 0x03, 0x00 }, + { 0x04, 0xFF }, + { 0x05, 0xFF }, + { 0x06, 0x00 }, + { 0x07, 0xC0 }, + { 0x08, 0xC0 }, + { 0x09, 0x10 }, + { 0x0A, 0x10 }, + { 0x0B, 0xFF }, + { 0x0C, 0x6C }, + { 0x0D, 0x6C }, + { 0x0E, 0x00 }, + { 0x0F, 0x82 }, + { 0x10, 0x89 }, + { 0x11, 0x6C }, + { 0x12, 0x07 }, + { 0x13, 0x00 }, + { 0x14, 0xFF }, + { 0x15, 0xFF }, + { 0x16, 0x00 }, + { 0x17, 0xC0 }, + { 0x18, 0xC0 }, + { 0x19, 0x10 }, + { 0x1A, 0x10 }, + { 0x1B, 0xFF }, + { 0x1C, 0x6C }, + { 0x1D, 0x6C }, + { 0x1E, 0x00 }, + { 0x1F, 0x82 }, + { 0x20, 0x89 }, + { 0x21, 0x6C }, + { 0x22, 0x07 }, + { 0x23, 0x00 }, + { 0x24, 0xFF }, + { 0x25, 0xFF }, + { 0x26, 0x00 }, + { 0x27, 0xC0 }, + { 0x28, 0xC0 }, + { 0x29, 0x10 }, + { 0x2A, 0x10 }, + { 0x2B, 0xFF }, + { 0x2C, 0x6C }, + { 0x2D, 0x6C }, + { 0x2E, 0x00 }, + { 0x2F, 0x82 }, + { 0x30, 0x89 }, + { 0x31, 0x6C }, + { 0x32, 0x07 }, + { 0x33, 0x00 }, + { 0x34, 0xFF }, + { 0x35, 0xFF }, + { 0x36, 0x00 }, + { 0x37, 0xC0 }, + { 0x38, 0xC0 }, + { 0x39, 0x10 }, + { 0x3A, 0x10 }, + { 0x3B, 0xFF }, + { 0x3C, 0x6C }, + { 0x3D, 0x6C }, + { 0x3E, 0x00 }, + { 0x3F, 0x82 }, +}; + +static bool ma5311_ctrl_readable_register(struct device *dev, unsigned int reg) +{ + if (reg > MA5311_DAC_FF_VERSION) + return false; + + switch (reg) { + case MA5311_DAC_00_SYSTEM_CTRL1 ... MA5311_DAC_05_ADC_DAC_MIX2: + case MA5311_DAC_09_OUTPUT_CTRL ... MA5311_DAC_0B_SPK_VOL_R: + case MA5311_DAC_0E_MUTE_VOL_CTRL ... MA5311_DAC_12_SYSTEM_CTRL5: + case MA5311_DAC_14_MODULATOR2 ... MA5311_DAC_1B_BASS_SPK7: + case MA5311_DAC_23_COMP_LIM1 ... MA5311_DAC_26_COMP_LIM4: + case MA5311_DAC_2B_EQ_MODE ... MA5311_DAC_30_EQ_GRAPHIC5: + case MA5311_DAC_33_FLL_CTRL3 ... MA5311_DAC_3D_TEST3: + case MA5311_DAC_40_EQ_CTRL1 ... MA5311_DAC_8F_PLL_F3_P_CP: + case MA5311_DAC_91_ADC_DAC_MIX: + case MA5311_DAC_A1_TOP_MAN1_FOR_SDO ... MA5311_DAC_B5_MCLKO_TEST: + case MA5311_DAC_B7_TOP_MAN4 ... MA5311_DAC_B9_PLL_A_SETTING: + case MA5311_DAC_BB_CLASS_G_LEVEL1 ... MA5311_DAC_BF_POWER_METER: + case MA5311_DAC_EA_DAC_STATUS ... MA5311_DAC_EC_DAC_SCP_STATUS: + case MA5311_DAC_FB_STATUS2 ... MA5311_DAC_FD_POWER_METER_DISPLAY: + case MA5311_DAC_FF_VERSION: + break; + default: + return false; + } + + return true; +} + +static bool ma5311_ctrl_writeable_register(struct device *dev, unsigned int reg) +{ + if (reg > MA5311_DAC_FF_VERSION) + return false; + + switch (reg) { + case MA5311_DAC_00_SYSTEM_CTRL1 ... MA5311_DAC_05_ADC_DAC_MIX2: + case MA5311_DAC_09_OUTPUT_CTRL ... MA5311_DAC_0B_SPK_VOL_R: + case MA5311_DAC_0E_MUTE_VOL_CTRL ... MA5311_DAC_12_SYSTEM_CTRL5: + case MA5311_DAC_14_MODULATOR2 ... MA5311_DAC_1B_BASS_SPK7: + case MA5311_DAC_23_COMP_LIM1 ... MA5311_DAC_26_COMP_LIM4: + case MA5311_DAC_2B_EQ_MODE ... MA5311_DAC_30_EQ_GRAPHIC5: + case MA5311_DAC_33_FLL_CTRL3 ... MA5311_DAC_3D_TEST3: + case MA5311_DAC_40_EQ_CTRL1 ... MA5311_DAC_8F_PLL_F3_P_CP: + case MA5311_DAC_91_ADC_DAC_MIX: + case MA5311_DAC_A1_TOP_MAN1_FOR_SDO ... MA5311_DAC_B5_MCLKO_TEST: + case MA5311_DAC_B7_TOP_MAN4 ... MA5311_DAC_B9_PLL_A_SETTING: + case MA5311_DAC_BB_CLASS_G_LEVEL1 ... MA5311_DAC_BF_POWER_METER: + break; + default: + return false; + } + + return true; +} + +static bool ma5311_ctrl_volatile_register(struct device *dev, unsigned int reg) +{ + if (reg > MA5311_DAC_FF_VERSION) + return false; + + switch (reg) { + case MA5311_DAC_EA_DAC_STATUS ... MA5311_DAC_EC_DAC_SCP_STATUS: + case MA5311_DAC_FB_STATUS2 ... MA5311_DAC_FD_POWER_METER_DISPLAY: + case MA5311_DAC_FF_VERSION: + break; + default: + return false; + } + + return true; +} + +static bool ma5311_adc_readable_register(struct device *dev, unsigned int reg) +{ + if (reg > MA5311_ADC_CH4_3F_OUTPUT_FORMAT) + return false; + + switch (reg) { + case MA5311_ADC_CH1_00_GENERAL_SETTING ... MA5311_ADC_CH4_3F_OUTPUT_FORMAT: + break; + default: + return false; + } + + return true; +} + +static bool ma5311_adc_writeable_register(struct device *dev, unsigned int reg) +{ + if (reg > MA5311_ADC_CH4_3F_OUTPUT_FORMAT) + return false; + + switch (reg) { + case MA5311_ADC_CH1_00_GENERAL_SETTING ... MA5311_ADC_CH4_3F_OUTPUT_FORMAT: + break; + default: + return false; + } + + return true; +} + +static const DECLARE_TLV_DB_RANGE(ma5311_adc_vol_tlv, + 0x00, 0xef, TLV_DB_MINMAX_ITEM(-7200, 1763), + 0xf0, 0xff, TLV_DB_SCALE_ITEM(1763, 0, 0)); + +static const DECLARE_TLV_DB_RANGE(ma5311_adc_pga_tlv, + 0x00, 0x3b, TLV_DB_MINMAX_ITEM(-1200, 3225), + 0x3c, 0x3f, TLV_DB_SCALE_ITEM(3225, 0, 0)); + +static const DECLARE_TLV_DB_RANGE(ma5311_spk_tlv, + 0x00, 0xa8, TLV_DB_MINMAX_ITEM(-6000, 2400), + 0xa9, 0xff, TLV_DB_SCALE_ITEM(-6000, 0, 0)); + +static const char *const ma5311_aif_in_source_text[] = { + "Mono Both", "Stereo", +}; + +static const char *const ma5311_rx_slot_text[] = { + "None", "Slot01", "Slot23", "Slot45", "Slot67", +}; + +static const char *const ma5311_reset_text[] = { + "idle", "reset", +}; + +static const unsigned int ma5311_tdm_rx_slot_values[] = { + MA5311_DISABLE_TDM_SLOT, + MA5311_TDM_SLOT0_RX_POS_0 | MA5311_TDM_SLOT1_RX_POS_1, + MA5311_TDM_SLOT0_RX_POS_2 | MA5311_TDM_SLOT1_RX_POS_3, + MA5311_TDM_SLOT0_RX_POS_4 | MA5311_TDM_SLOT1_RX_POS_5, + MA5311_TDM_SLOT0_RX_POS_6 | MA5311_TDM_SLOT1_RX_POS_7, +}; + +static const struct soc_enum ma5311_reset_enum = + SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(ma5311_reset_text), ma5311_reset_text); + +static SOC_ENUM_SINGLE_VIRT_DECL(ma5311_aif_in_source_enum, + ma5311_aif_in_source_text); + +static const struct soc_enum ma5311_rx_slot_enum = + SOC_VALUE_ENUM_SINGLE(MA5311_DAC_37_TDM1, 0, + MA5311_TDM_SLOT0_RX_POS_MASK | + MA5311_TDM_SLOT1_RX_POS_MASK, + ARRAY_SIZE(ma5311_rx_slot_text), + ma5311_rx_slot_text, + ma5311_tdm_rx_slot_values); + +static void ma5311_restore_dai_config(struct ma5311_priv *ma5311) +{ + /* Restore clock settings without powering up the chip or PLL. */ + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_DAC_CLKSYSTEM_MASK, + ma5311->dai_sys_clk); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_LEFTPOL_MASK | + MA5311_SCK_RISING_MASK | + MA5311_CONTROLLER_DEVICE_MASK, + ma5311->dai_leftpol | + ma5311->dai_sck_edge | + ma5311->dai_clk_mode); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_0E_MUTE_VOL_CTRL, + MA5311_DAC_MUTE_VOL_MASK, + ma5311->dai_spk_mute); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_TDM_SLOT0_RX_POS_MASK | + MA5311_TDM_SLOT1_RX_POS_MASK, + ma5311->dai_tdm1_rx_pos); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_DAC_38_DATA_LEN_MASK | + MA5311_ADC_TDM2_SETTING_MASK, + ma5311->dai_tdm2_data_len | + ma5311->dai_tdm2_capture_cfg); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_39_DATA_PATH, + ma5311->dai_data_path); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_3A_TDM_SLOT_ENABLE, + ma5311->dai_tdm_slot_enable); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_8B_PLL_POST_N, + ma5311->dai_pll_post_n); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_8C_PLL_N, + ma5311->dai_pll_n); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_8D_PLL_F1, + ma5311->dai_pll_f1); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_8E_PLL_F2, + ma5311->dai_pll_f2); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_8F_PLL_F3_P_CP, + ma5311->dai_pll_f3_p_cp); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_91_ADC_DAC_MIX, + MA5311_DAC_ADC_DAC_MIX_CH_MASK, + ma5311->dai_adc_mix_ch); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_SOO_LENGTH_MASK | + MA5311_DAC_A1_SCK_RATE_MASK | + MA5311_TOP_MAN1_O_FORMAT_MASK, + ma5311->dai_sdo_len | + ma5311->dai_sck_rate | + ma5311->dai_o_format); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLLIN_CLK_MASK | + MA5311_DAC_PLL_REF_CLK1_MASK | + MA5311_DAC_PLL_REF_CLK2_MASK, + ma5311->dai_pll_input); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK | + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + ma5311->dai_adc1_word_len | + ma5311->dai_adc1_sck_rate); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK | + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + ma5311->dai_adc2_word_len | + ma5311->dai_adc2_sck_rate); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK | + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + ma5311->dai_adc3_word_len | + ma5311->dai_adc3_sck_rate); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK | + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + ma5311->dai_adc4_word_len | + ma5311->dai_adc4_sck_rate); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_B8_TOP_MAN5, + MA5311_LRCK_SCK_MAS_CLK_SEL_MASK | + MA5311_DAC_ADC_CLK_ON_MASK, + ma5311->dai_mas_clk_sel | ma5311->dai_adc_clk); +} + +static int ma5311_reset(struct snd_soc_component *component) +{ + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int status, revision, i; + int ret; + + ret = regmap_read(ma5311->ctrl_regmap, MA5311_DAC_FF_VERSION, &status); + if (ret) { + dev_err(component->dev, "Register read operation failed\n"); + return ret; + } + + revision = status & MA5311_REV_NUM_STATUS; + dev_dbg(component->dev, "MA5311 revision: %u\n", revision); + + /* + * Critical register settings including speaker, ADC, PGA gains are + * following factory defaults, while rest of settings are fixed + * in practical settings including data format and path settings. + */ + + for (i = 0; i < ARRAY_SIZE(ma5311_ctrl_reg_def); i++) { + regmap_write(ma5311->ctrl_regmap, + ma5311_ctrl_reg_def[i].reg, + ma5311_ctrl_reg_def[i].def); + } + + for (i = 0; i < ARRAY_SIZE(ma5311_adc_reg_def); i++) { + regmap_write(ma5311->adc_regmap, + ma5311_adc_reg_def[i].reg, + ma5311_adc_reg_def[i].def); + } + + if (ma5311->flag_ext_rst) + ma5311_restore_dai_config(ma5311); + + return 0; +} + +static int ma5311_adc_volume_control_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + const struct soc_mixer_control *mc = + (const struct soc_mixer_control *)kcontrol->private_value; + unsigned int val; + int ret; + + ret = regmap_read(ma5311->adc_regmap, mc->reg, &val); + if (ret) + return ret; + + ucontrol->value.integer.value[0] = val & MA5311_ADC_VOL_CTRL_MASK; + + return 0; +} + +static int ma5311_adc_volume_control_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + const struct soc_mixer_control *mc = + (const struct soc_mixer_control *)kcontrol->private_value; + long input = ucontrol->value.integer.value[0]; + unsigned int val; + bool changed; + int ret; + + if (input < 0 || input > MA5311_ADC_VOL_CTRL_MASK) + return -EINVAL; + + val = input; + + ret = regmap_update_bits_check(ma5311->adc_regmap, mc->reg, + MA5311_ADC_VOL_CTRL_MASK, val, &changed); + if (ret) + return ret; + + return changed; +} + +static int ma5311_adc_pga_control_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + const struct soc_mixer_control *mc = + (const struct soc_mixer_control *)kcontrol->private_value; + unsigned int val; + int ret; + + ret = regmap_read(ma5311->adc_regmap, mc->reg, &val); + if (ret) + return ret; + + ucontrol->value.integer.value[0] = val & MA5311_ADC_PGA_CTRL_MASK; + + return 0; +} + +static int ma5311_adc_pga_control_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + const struct soc_mixer_control *mc = + (const struct soc_mixer_control *)kcontrol->private_value; + long input = ucontrol->value.integer.value[0]; + unsigned int val; + int ret; + bool changed; + + if (input < 0 || input > MA5311_ADC_PGA_CTRL_MASK) + return -EINVAL; + + val = input; + + ret = regmap_update_bits_check(ma5311->adc_regmap, mc->reg, + MA5311_ADC_PGA_CTRL_MASK, val, &changed); + if (ret) + return ret; + + return changed; +} + +static int ma5311_startup(struct snd_soc_component *component) +{ + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_PLL_MASK, MA5311_PLL_ON); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_POWER_MASK, MA5311_POWER_ON); + + if (ma5311->amp_mode == MA5311_MONO_BOTH_MODE) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_10_SYSTEM_CTRL3, + MA5311_SPK_MODE_MASK, + MA5311_SPK_MONO_BOTH); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_DAC_TDM_STEREO_MASK, + MA5311_DAC_TDM_MONO); + } else { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_10_SYSTEM_CTRL3, + MA5311_SPK_MODE_MASK, + MA5311_SPK_STEREO); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_DAC_TDM_STEREO_MASK, + MA5311_DAC_TDM_STEREO); + } + + ma5311->amp_power_status = true; + msleep(55); + + return 0; +} + +static int ma5311_shutdown(struct snd_soc_component *component) +{ + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + + regmap_update_bits(ma5311->ctrl_regmap, MA5311_DAC_0E_MUTE_VOL_CTRL, + MA5311_DAC_MUTE_VOL_MASK, MA5311_SPK_MUTE); + + msleep(55); + + regmap_update_bits(ma5311->ctrl_regmap, MA5311_DAC_10_SYSTEM_CTRL3, + MA5311_SPK_MODE_MASK, MA5311_SPK_OFF); + + ma5311->amp_power_status = false; + + /* Capture shares the PLL and global power with playback. */ + if (!ma5311->adc_power_status) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_PLL_MASK, MA5311_PLL_OFF); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_POWER_MASK, MA5311_POWER_OFF); + } + + return 0; +} + +static int ma5311_reset_control_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + + if (!ma5311->reset_gpio) + return -ENODEV; + + ucontrol->value.enumerated.item[0] = 0; + + return 0; +} + +static int ma5311_reset_control_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + struct snd_soc_dapm_context *dapm = + snd_soc_component_to_dapm(component); + struct snd_kcontrol *slot_control; + unsigned int val = ucontrol->value.enumerated.item[0]; + unsigned int rx_slot; + int ret = 0; + + if (!val) + return 0; + + if (!ma5311->reset_gpio) + return -ENODEV; + + if (val >= ARRAY_SIZE(ma5311_reset_text)) + return -EINVAL; + + slot_control = snd_soc_card_get_kcontrol(component->card, + "RX Slot Configuration"); + if (!slot_control) + return -ENOENT; + + snd_soc_dpcm_mutex_lock(component->card); + snd_soc_dapm_mutex_lock(dapm); + + if (ma5311->amp_power_status || ma5311->adc_power_status) { + dev_warn(component->dev, + "Reset denied: playback or capture path is powered\n"); + ret = -EBUSY; + goto unlock; + } + + if (snd_soc_component_active(component)) { + dev_warn(component->dev, + "Reset denied: pcm stream is in active state\n"); + ret = -EBUSY; + goto unlock; + } + + gpiod_set_value_cansleep(ma5311->reset_gpio, 1); + msleep(MA5311_RESET_ASSERT_MS); + + gpiod_set_value_cansleep(ma5311->reset_gpio, 0); + msleep(MA5311_RESET_RECOVERY_MS); + + rx_slot = snd_soc_dapm_kcontrol_get_value(slot_control); + rx_slot &= MA5311_TDM_SLOT0_RX_POS_MASK | + MA5311_TDM_SLOT1_RX_POS_MASK; + ma5311->dai_tdm1_rx_pos = rx_slot; + + ma5311->flag_ext_rst = true; + ret = ma5311_reset(component); + ma5311->flag_ext_rst = false; + +unlock: + snd_soc_dapm_mutex_unlock(dapm); + snd_soc_dpcm_mutex_unlock(component->card); + + return ret; +} + +static const struct snd_kcontrol_new ma5311_reset_controls[] = { + SOC_ENUM_EXT(MA5311_RESET_CTRL_NAME, ma5311_reset_enum, + ma5311_reset_control_get, ma5311_reset_control_put), +}; + +static const struct snd_kcontrol_new ma5311_snd_controls[] = { + SOC_SINGLE_TLV(MA5311_LEFT_VOL_CTRL_NAME, MA5311_DAC_0A_SPK_VOL_L, 0, + 168, 1, ma5311_spk_tlv), + SOC_SINGLE_TLV(MA5311_RIGHT_VOL_CTRL_NAME, MA5311_DAC_0B_SPK_VOL_R, 0, + 168, 1, ma5311_spk_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC1_LEFT_VOL_CTRL_NAME, + MA5311_ADC_CH1_07_VOLUME_LEFT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC1_RIGHT_VOL_CTRL_NAME, + MA5311_ADC_CH1_08_VOLUME_RIGHT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC2_LEFT_VOL_CTRL_NAME, + MA5311_ADC_CH2_17_VOLUME_LEFT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC2_RIGHT_VOL_CTRL_NAME, + MA5311_ADC_CH2_18_VOLUME_RIGHT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC3_LEFT_VOL_CTRL_NAME, + MA5311_ADC_CH3_27_VOLUME_LEFT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC3_RIGHT_VOL_CTRL_NAME, + MA5311_ADC_CH3_28_VOLUME_RIGHT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC4_LEFT_VOL_CTRL_NAME, + MA5311_ADC_CH4_37_VOLUME_LEFT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC4_RIGHT_VOL_CTRL_NAME, + MA5311_ADC_CH4_38_VOLUME_RIGHT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC1_LEFT_PGA_CTRL_NAME, + MA5311_ADC_CH1_09_PGA_LEFT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC1_RIGHT_PGA_CTRL_NAME, + MA5311_ADC_CH1_0A_PGA_RIGHT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC2_LEFT_PGA_CTRL_NAME, + MA5311_ADC_CH2_19_PGA_LEFT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC2_RIGHT_PGA_CTRL_NAME, + MA5311_ADC_CH2_1A_PGA_RIGHT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC3_LEFT_PGA_CTRL_NAME, + MA5311_ADC_CH3_29_PGA_LEFT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC3_RIGHT_PGA_CTRL_NAME, + MA5311_ADC_CH3_2A_PGA_RIGHT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC4_LEFT_PGA_CTRL_NAME, + MA5311_ADC_CH4_39_PGA_LEFT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC4_RIGHT_PGA_CTRL_NAME, + MA5311_ADC_CH4_3A_PGA_RIGHT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), +}; + +static int ma5311_dapm_aif_in_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_dapm_context *dapm = + snd_soc_dapm_kcontrol_to_dapm(kcontrol); + struct snd_soc_component *component = snd_soc_dapm_to_component(dapm); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int val = ucontrol->value.enumerated.item[0]; + unsigned int old_val = snd_soc_dapm_kcontrol_get_value(kcontrol); + + if (val >= ARRAY_SIZE(ma5311_aif_in_source_text)) { + dev_err(ma5311->dev, "%s: Out of range\n", __func__); + return -EINVAL; + } + + if (old_val == val) + return 0; + + if (ma5311->amp_power_status) { + dev_warn(ma5311->dev, + "Cannot change AIF IN Source during playback\n"); + return -EBUSY; + } + + return snd_soc_dapm_put_enum_double(kcontrol, ucontrol); +} + +static const struct snd_kcontrol_new ma5311_aif_in_source_control = { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = MA5311_AIF_IN_NAME, + .info = snd_soc_info_enum_double, + .get = snd_soc_dapm_get_enum_double, + .put = ma5311_dapm_aif_in_put, + .private_value = (unsigned long)&ma5311_aif_in_source_enum, +}; + +static const struct snd_kcontrol_new ma5311_rx_slot_control = + SOC_DAPM_ENUM("Route", ma5311_rx_slot_enum); + +static int ma5311_aif_in_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + struct snd_soc_component *component = snd_soc_dapm_to_component(w->dapm); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int mux = snd_soc_dapm_kcontrol_get_value(w->kcontrols[0]); + + switch (event) { + case SND_SOC_DAPM_PRE_PMU: + switch (mux) { + case MA5311_MONO_BOTH_MODE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_10_SYSTEM_CTRL3, + MA5311_SPK_MODE_MASK, + MA5311_SPK_MONO_BOTH); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_DAC_TDM_STEREO_MASK, + MA5311_DAC_TDM_MONO); + break; + case MA5311_STEREO_MODE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_10_SYSTEM_CTRL3, + MA5311_SPK_MODE_MASK, + MA5311_SPK_STEREO); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_DAC_TDM_STEREO_MASK, + MA5311_DAC_TDM_STEREO); + break; + default: + dev_err(ma5311->dev, "%s: Invalid value (%u)\n", + __func__, mux); + return -EINVAL; + } + + ma5311->amp_mode = mux; + break; + } + + return 0; +} + +static int ma5311_power_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + struct snd_soc_component *component = snd_soc_dapm_to_component(w->dapm); + + switch (event) { + case SND_SOC_DAPM_POST_PMU: + return ma5311_startup(component); + case SND_SOC_DAPM_PRE_PMD: + return ma5311_shutdown(component); + } + + return 0; +} + +static int ma5311_adc_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + struct snd_soc_component *component = snd_soc_dapm_to_component(w->dapm); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int format = ma5311->format; + + switch (event) { + case SND_SOC_DAPM_PRE_PMU: + regmap_update_bits(ma5311->ctrl_regmap, MA5311_DAC_A2_TOP_MAN2, + MA5311_PLL_MASK, MA5311_PLL_ON); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_POWER_MASK, MA5311_POWER_ON); + + switch (format) { + case SND_SOC_DAIFMT_I2S: + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_00_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_ON); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_DEMUTE); + break; + case SND_SOC_DAIFMT_DSP_A: + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_00_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_ON); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_DEMUTE); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_10_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_ON); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_DEMUTE); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_20_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_ON); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_DEMUTE); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_30_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_ON); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_DEMUTE); + break; + default: + dev_err(ma5311->dev, "%s: Invalid value (%u)\n", + __func__, format); + return -EINVAL; + } + + ma5311->adc_power_status = true; + break; + + case SND_SOC_DAPM_POST_PMD: + switch (format) { + case SND_SOC_DAIFMT_I2S: + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_MUTE); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_00_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_DOWN); + break; + case SND_SOC_DAIFMT_DSP_A: + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_MUTE); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_00_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_DOWN); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_MUTE); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_10_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_DOWN); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_MUTE); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_20_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_DOWN); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_MUTE); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_30_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_DOWN); + break; + default: + dev_err(ma5311->dev, "%s: Invalid value (%u)\n", + __func__, format); + return -EINVAL; + } + + ma5311->adc_power_status = false; + + if (!ma5311->amp_power_status) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_PLL_MASK, MA5311_PLL_OFF); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_POWER_MASK, MA5311_POWER_OFF); + } + } + + return 0; +} + +static const struct snd_soc_dapm_widget ma5311_dapm_widgets[] = { + /* Playback */ + SND_SOC_DAPM_AIF_IN("AIF IN", "Playback", 0, SND_SOC_NOPM, 0, 0), + SND_SOC_DAPM_MUX_E("AIF IN Source", SND_SOC_NOPM, 0, 0, + &ma5311_aif_in_source_control, ma5311_aif_in_event, + SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU), + SND_SOC_DAPM_MUX("RX Slot Configuration", SND_SOC_NOPM, 0, 0, + &ma5311_rx_slot_control), + SND_SOC_DAPM_OUT_DRV_E("AMP Power", SND_SOC_NOPM, 0, 0, NULL, 0, + ma5311_power_event, + SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD), + SND_SOC_DAPM_OUTPUT("AOUT1L"), + SND_SOC_DAPM_OUTPUT("AOUT1R"), + + /* Capture */ + SND_SOC_DAPM_INPUT("ADC IN"), + SND_SOC_DAPM_ADC_E("ADC", NULL, SND_SOC_NOPM, 0, 0, ma5311_adc_event, + SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), + SND_SOC_DAPM_AIF_OUT("AIF OUT", "Capture", 0, SND_SOC_NOPM, 0, 0), +}; + +static const struct snd_soc_dapm_route ma5311_dapm_routes[] = { + /* Playback */ + { "AIF IN Source", "Mono Both", "AIF IN" }, + { "AIF IN Source", "Stereo", "AIF IN" }, + + { "RX Slot Configuration", "None", "AIF IN Source" }, + { "RX Slot Configuration", "Slot01", "AIF IN Source" }, + { "RX Slot Configuration", "Slot23", "AIF IN Source" }, + { "RX Slot Configuration", "Slot45", "AIF IN Source" }, + { "RX Slot Configuration", "Slot67", "AIF IN Source" }, + + { "AMP Power", NULL, "RX Slot Configuration" }, + + { "AOUT1L", NULL, "AMP Power" }, + { "AOUT1R", NULL, "AMP Power" }, + + /* Capture */ + { "ADC", NULL, "ADC IN" }, + { "AIF OUT", NULL, "ADC" }, +}; + +static int ma5311_probe(struct snd_soc_component *component) +{ + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + int ret; + + if (ma5311->reset_gpio) { + ret = snd_soc_add_component_controls(component, + ma5311_reset_controls, + ARRAY_SIZE(ma5311_reset_controls)); + if (ret) + return ret; + } + + return ma5311_reset(component); +} + +static const struct snd_soc_component_driver ma5311_component = { + .probe = ma5311_probe, + .controls = ma5311_snd_controls, + .num_controls = ARRAY_SIZE(ma5311_snd_controls), + .dapm_widgets = ma5311_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(ma5311_dapm_widgets), + .dapm_routes = ma5311_dapm_routes, + .num_dapm_routes = ARRAY_SIZE(ma5311_dapm_routes), +}; + +static const struct regmap_config ma5311_ctrl_regmap_config = { + .reg_bits = 8, + .val_bits = 8, + + .max_register = MA5311_DAC_FF_VERSION, + .readable_reg = ma5311_ctrl_readable_register, + .writeable_reg = ma5311_ctrl_writeable_register, + .volatile_reg = ma5311_ctrl_volatile_register, + + .cache_type = REGCACHE_FLAT, + .reg_defaults = ma5311_ctrl_reg_def, + .num_reg_defaults = ARRAY_SIZE(ma5311_ctrl_reg_def), +}; + +static const struct regmap_config ma5311_adc_regmap_config = { + .reg_bits = 8, + .val_bits = 8, + + .max_register = MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + .readable_reg = ma5311_adc_readable_register, + .writeable_reg = ma5311_adc_writeable_register, + + .cache_type = REGCACHE_FLAT, + .reg_defaults = ma5311_adc_reg_def, + .num_reg_defaults = ARRAY_SIZE(ma5311_adc_reg_def), +}; + +static int ma5311_setup_pll(struct snd_soc_component *component, + unsigned int bclk) +{ + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int i = 0; + unsigned int pll_post_n; + unsigned int pll_n; + unsigned int pll_f1; + unsigned int pll_f2; + unsigned int pll_f3_p_cp; + + dev_dbg(component->dev, "PLL input BCLK: %u Hz\n", bclk); + + if (ma5311->sys_clk_id == MA5311_PLL_CLKIN_BCLK) { + for (i = 0; i < ma5311->num_of_pll_matches; i++) { + if (ma5311->pll_matches[i].input_clk == bclk) + break; + } + + if (i == ma5311->num_of_pll_matches) { + dev_warn(component->dev, + "%s: No matching value between pll table and SCK\n", + __func__); + return -EINVAL; + } + + pll_post_n = ma5311->pll_matches[i].post_n; + pll_n = ma5311->pll_matches[i].n; + pll_f1 = ma5311->pll_matches[i].f1; + pll_f2 = ma5311->pll_matches[i].f2; + pll_f3_p_cp = ma5311->pll_matches[i].f3_p_cp; + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLLIN_CLK_MASK, + MA5311_DAC_PLLIN_EXT_OSC); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLL_REF_CLK1_MASK, + MA5311_DAC_PLL_REF_EXT_CLK); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLL_REF_CLK2_MASK, + MA5311_DAC_PLL_REF_CLK2_SCK); + + ma5311->dai_pll_input = MA5311_DAC_PLLIN_EXT_OSC | + MA5311_DAC_PLL_REF_EXT_CLK | + MA5311_DAC_PLL_REF_CLK2_SCK; + } else if (ma5311->sys_clk_id == MA5311_INTERNAL_OSC) { + pll_post_n = MA5311_INT_OSC_POST_N; + pll_n = MA5311_INT_OSC_N; + pll_f1 = MA5311_INT_OSC_F1; + pll_f2 = MA5311_INT_OSC_F2; + pll_f3_p_cp = MA5311_INT_OSC_F3_P_CP; + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLLIN_CLK_MASK, + MA5311_DAC_PLLIN_INT_OSC); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLL_REF_CLK1_MASK, + MA5311_DAC_PLL_REF_INT_OSC); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLL_REF_CLK2_MASK, + MA5311_DAC_PLL_REF_CLK2_REF1); + + ma5311->dai_pll_input = MA5311_DAC_PLLIN_INT_OSC | + MA5311_DAC_PLL_REF_INT_OSC | + MA5311_DAC_PLL_REF_CLK2_REF1; + } else { + return 0; + } + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_PLL_MASK, MA5311_PLL_ON); + + regmap_write(ma5311->ctrl_regmap, MA5311_DAC_8B_PLL_POST_N, + pll_post_n); + ma5311->dai_pll_post_n = pll_post_n; + + regmap_write(ma5311->ctrl_regmap, MA5311_DAC_8C_PLL_N, + pll_n); + ma5311->dai_pll_n = pll_n; + + regmap_write(ma5311->ctrl_regmap, MA5311_DAC_8D_PLL_F1, + pll_f1); + ma5311->dai_pll_f1 = pll_f1; + + regmap_write(ma5311->ctrl_regmap, MA5311_DAC_8E_PLL_F2, + pll_f2); + ma5311->dai_pll_f2 = pll_f2; + + regmap_write(ma5311->ctrl_regmap, MA5311_DAC_8F_PLL_F3_P_CP, + pll_f3_p_cp); + ma5311->dai_pll_f3_p_cp = pll_f3_p_cp; + + return 0; +} + +static int ma5311_dai_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + struct snd_soc_component *component = dai->component; + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int bclk = 0; + unsigned int frame_size; + int ret; + + switch (params_rate(params)) { + case 48000: + break; + + default: + dev_err(component->dev, "%s: unsupported sample rate: %u\n", + __func__, params_rate(params)); + + return -EINVAL; + } + + if (params_channels(params) > 8) { + dev_err(component->dev, "%s: unsupported channel count: %u\n", + __func__, params_channels(params)); + + return -EINVAL; + } + + if (ma5311->format == SND_SOC_DAIFMT_DSP_A) { + if (ma5311->frame_size) + frame_size = ma5311->frame_size; + else + frame_size = params_channels(params) * + params_physical_width(params); + + bclk = params_rate(params) * frame_size; + dev_dbg(component->dev, "Estimated TDM BCLK: %u Hz\n", bclk); + } else if (ma5311->format == SND_SOC_DAIFMT_I2S) { + bclk = params_rate(params) * params_physical_width(params) * 2; + dev_dbg(component->dev, "Estimated I2S BCLK: %u Hz\n", bclk); + } else { + return -EINVAL; + } + + if (ma5311->sys_clk_id == MA5311_PLL_CLKIN_BCLK) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_DAC_CLKSYSTEM_MASK, + MA5311_DAC_EXT_CLK_24_576); + ma5311->dai_sys_clk = MA5311_DAC_EXT_CLK_24_576; + } else { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_DAC_CLKSYSTEM_MASK, + MA5311_DAC_INT_OSCILLATOR); + ma5311->dai_sys_clk = MA5311_DAC_INT_OSCILLATOR; + } + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + if (ma5311->sys_clk_id == MA5311_PLL_CLKIN_BCLK && + ma5311->last_bclk != bclk) { + dev_dbg(component->dev, "Playback BCLK: %u Hz\n", bclk); + ret = ma5311_setup_pll(component, bclk); + + if (ret) { + ma5311->last_bclk = 0; + dev_err(component->dev, + "Failed to configure PLL: %d\n", ret); + return ret; + } + + ma5311->last_bclk = bclk; + } else if (ma5311->sys_clk_id == MA5311_INTERNAL_OSC) { + ret = ma5311_setup_pll(component, MA5311_DUMMY_BCLK); + + if (ret) { + ma5311->last_bclk = 0; + dev_err(component->dev, + "Failed to configure PLL: %d\n", ret); + return ret; + } + + ma5311->last_bclk = 0; + } + + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_SOO_LENGTH_MASK, + MA5311_TOP_MAN1_SDO_16B); + ma5311->dai_sdo_len = MA5311_TOP_MAN1_SDO_16B; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_DAC_A1_SCK_RATE_MASK, + MA5311_DAC_A1_SCK_RATE_32FS); + ma5311->dai_sck_rate = MA5311_DAC_A1_SCK_RATE_32FS; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_DAC_38_DATA_LEN_MASK, + MA5311_DAC_38_DATA_LEN_16); + ma5311->dai_tdm2_data_len = MA5311_DAC_38_DATA_LEN_16; + break; + + case SNDRV_PCM_FORMAT_S32_LE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_SOO_LENGTH_MASK, + MA5311_TOP_MAN1_SDO_24B); + ma5311->dai_sdo_len = MA5311_TOP_MAN1_SDO_24B; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_DAC_A1_SCK_RATE_MASK, + MA5311_DAC_A1_SCK_RATE_64FS); + ma5311->dai_sck_rate = MA5311_DAC_A1_SCK_RATE_64FS; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_DAC_38_DATA_LEN_MASK, + MA5311_DAC_38_DATA_LEN_32); + ma5311->dai_tdm2_data_len = MA5311_DAC_38_DATA_LEN_32; + break; + + default: + dev_err(component->dev, + "%s: unsupported PCM format: %d\n", __func__, + params_format(params)); + return -EINVAL; + } + + switch (ma5311->format) { + case SND_SOC_DAIFMT_I2S: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_TDM_SLOT0_RX_POS_MASK | + MA5311_TDM_SLOT1_RX_POS_MASK, + MA5311_DISABLE_TDM_SLOT); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_O_FORMAT_MASK, + MA5311_TOP_MAN1_O_FORMAT_I2S); + ma5311->dai_tdm1_rx_pos = MA5311_DISABLE_TDM_SLOT; + ma5311->dai_o_format = MA5311_TOP_MAN1_O_FORMAT_I2S; + break; + + case SND_SOC_DAIFMT_DSP_A: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_O_FORMAT_MASK, + MA5311_TOP_MAN1_O_FORMAT_TDM); + ma5311->dai_o_format = MA5311_TOP_MAN1_O_FORMAT_TDM; + break; + + default: + return -EINVAL; + } + } + + if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_B8_TOP_MAN5, + MA5311_DAC_ADC_CLK_ON_MASK, + MA5311_DAC_ADC_CLK_ON); + ma5311->dai_adc_clk = MA5311_DAC_ADC_CLK_ON; + + if (ma5311->sys_clk_id == MA5311_PLL_CLKIN_BCLK && + ma5311->last_bclk != bclk) { + dev_dbg(component->dev, "Capture BCLK: %u Hz\n", bclk); + ret = ma5311_setup_pll(component, bclk); + if (ret) { + ma5311->last_bclk = 0; + dev_err(component->dev, + "Failed to configure PLL: %d\n", ret); + return ret; + } + + ma5311->last_bclk = bclk; + } else if (ma5311->sys_clk_id == MA5311_INTERNAL_OSC) { + ret = ma5311_setup_pll(component, MA5311_DUMMY_BCLK); + + if (ret) { + ma5311->last_bclk = 0; + dev_err(component->dev, + "Failed to configure PLL: %d\n", ret); + return ret; + } + + ma5311->last_bclk = 0; + } + + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_DAC_38_DATA_LEN_MASK, + MA5311_DAC_38_DATA_LEN_16); + ma5311->dai_tdm2_data_len = MA5311_DAC_38_DATA_LEN_16; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_SOO_LENGTH_MASK, + MA5311_TOP_MAN1_SDO_16B); + ma5311->dai_sdo_len = MA5311_TOP_MAN1_SDO_16B; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_DAC_A1_SCK_RATE_MASK, + MA5311_DAC_A1_SCK_RATE_32FS); + ma5311->dai_sck_rate = MA5311_DAC_A1_SCK_RATE_32FS; + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_16); + ma5311->dai_adc1_word_len = MA5311_ADC_WORD_LENGTH_16; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_16); + ma5311->dai_adc2_word_len = MA5311_ADC_WORD_LENGTH_16; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_16); + ma5311->dai_adc3_word_len = MA5311_ADC_WORD_LENGTH_16; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_16); + ma5311->dai_adc4_word_len = MA5311_ADC_WORD_LENGTH_16; + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_16BIT_CFG); + ma5311->dai_adc1_sck_rate = MA5311_ADC_SCK_RATE_16BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_16BIT_CFG); + ma5311->dai_adc2_sck_rate = MA5311_ADC_SCK_RATE_16BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_16BIT_CFG); + ma5311->dai_adc3_sck_rate = MA5311_ADC_SCK_RATE_16BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_16BIT_CFG); + ma5311->dai_adc4_sck_rate = MA5311_ADC_SCK_RATE_16BIT_CFG; + break; + + case SNDRV_PCM_FORMAT_S32_LE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_DAC_38_DATA_LEN_MASK, + MA5311_DAC_38_DATA_LEN_32); + ma5311->dai_tdm2_data_len = MA5311_DAC_38_DATA_LEN_32; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_SOO_LENGTH_MASK, + MA5311_TOP_MAN1_SDO_24B); + ma5311->dai_sdo_len = MA5311_TOP_MAN1_SDO_24B; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_DAC_A1_SCK_RATE_MASK, + MA5311_DAC_A1_SCK_RATE_64FS); + ma5311->dai_sck_rate = MA5311_DAC_A1_SCK_RATE_64FS; + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_24); + ma5311->dai_adc1_word_len = MA5311_ADC_WORD_LENGTH_24; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_24); + ma5311->dai_adc2_word_len = MA5311_ADC_WORD_LENGTH_24; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_24); + ma5311->dai_adc3_word_len = MA5311_ADC_WORD_LENGTH_24; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_24); + ma5311->dai_adc4_word_len = MA5311_ADC_WORD_LENGTH_24; + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_24BIT_CFG); + ma5311->dai_adc1_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_24BIT_CFG); + ma5311->dai_adc2_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_24BIT_CFG); + ma5311->dai_adc3_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_24BIT_CFG); + ma5311->dai_adc4_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + break; + default: + dev_err(component->dev, + "%s: unsupported PCM format: %d\n", __func__, + params_format(params)); + return -EINVAL; + } + + switch (ma5311->format) { + case SND_SOC_DAIFMT_I2S: + dev_info(component->dev, "Working in I2S TX Mode\n"); + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_39_DATA_PATH, + MA5311_ADC_DATA_PATH_I2S); + ma5311->dai_data_path = MA5311_ADC_DATA_PATH_I2S; + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_3A_TDM_SLOT_ENABLE, + MA5311_TDM_SLOT_DISABLE_ALL); + ma5311->dai_tdm_slot_enable = MA5311_TDM_SLOT_DISABLE_ALL; + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_91_ADC_DAC_MIX, + MA5311_DAC_ADC_DAC_MIX_CH_MASK, + MA5311_ADC_MIX_CH0); + ma5311->dai_adc_mix_ch = MA5311_ADC_MIX_CH0; + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_O_FORMAT_MASK, + MA5311_TOP_MAN1_O_FORMAT_I2S); + ma5311->dai_o_format = MA5311_TOP_MAN1_O_FORMAT_I2S; + + break; + + case SND_SOC_DAIFMT_DSP_A: + dev_info(component->dev, "Working in TDM TX Mode\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_O_FORMAT_MASK, + MA5311_TOP_MAN1_O_FORMAT_TDM); + ma5311->dai_o_format = MA5311_TOP_MAN1_O_FORMAT_TDM; + + if (!ma5311->flag_dai_tdm) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_ADC_TDM2_SETTING_MASK, + MA5311_DAC_38_CAPTURE_8CH_CFG); + ma5311->dai_tdm2_capture_cfg = MA5311_DAC_38_CAPTURE_8CH_CFG; + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_39_DATA_PATH, MA5311_ADC_DATA_PATH_TDM_8CH); + ma5311->dai_data_path = MA5311_ADC_DATA_PATH_TDM_8CH; + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_3A_TDM_SLOT_ENABLE, + MA5311_TDM_SLOT_ENABLE_ALL); + ma5311->dai_tdm_slot_enable = MA5311_TDM_SLOT_ENABLE_ALL; + } + + break; + } + } + + return 0; +} + +static int ma5311_dai_set_fmt(struct snd_soc_dai *dai, unsigned int fmt) +{ + struct snd_soc_component *component = dai->component; + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_I2S: + case SND_SOC_DAIFMT_DSP_A: + break; + default: + return -EINVAL; + } + + switch (fmt & SND_SOC_DAIFMT_INV_MASK) { + case SND_SOC_DAIFMT_NB_NF: + case SND_SOC_DAIFMT_NB_IF: + case SND_SOC_DAIFMT_IB_NF: + case SND_SOC_DAIFMT_IB_IF: + break; + default: + return -EINVAL; + } + + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_I2S: + case SND_SOC_DAIFMT_DSP_A: + break; + + default: + return -EINVAL; + } + + switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { + case SND_SOC_DAIFMT_CBC_CFC: + dev_dbg(component->dev, "BCLK and frame clock consumer\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_CONTROLLER_DEVICE_MASK, + MA5311_DEVICE_MODE); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_B8_TOP_MAN5, + MA5311_LRCK_SCK_MAS_CLK_SEL_MASK, + MA5311_LRCK_SCK_CLK_SLAVE_MODE); + ma5311->dai_clk_mode = MA5311_DEVICE_MODE; + ma5311->dai_mas_clk_sel = MA5311_LRCK_SCK_CLK_SLAVE_MODE; + break; + + case SND_SOC_DAIFMT_CBP_CFP: + dev_dbg(component->dev, "BCLK and frame clock provider\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_CONTROLLER_DEVICE_MASK, + MA5311_CONTROLLER_MODE); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_B8_TOP_MAN5, + MA5311_LRCK_SCK_MAS_CLK_SEL_MASK, + MA5311_LRCK_SCK_CLK_MASTER_MODE); + + ma5311->dai_clk_mode = MA5311_CONTROLLER_MODE; + ma5311->dai_mas_clk_sel = MA5311_LRCK_SCK_CLK_MASTER_MODE; + break; + + default: + dev_err(component->dev, + "%s: Unsupported Controller/Device : 0x%x\n", __func__, + fmt); + return -EINVAL; + } + + switch (fmt & SND_SOC_DAIFMT_INV_MASK) { + case SND_SOC_DAIFMT_NB_NF: + dev_dbg(component->dev, "Normal BCLK, normal frame clock\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_LEFTPOL_MASK | + MA5311_SCK_RISING_MASK, + MA5311_LOW_FIRST_CH | + MA5311_SCK_FALLING_EDGE); + ma5311->dai_leftpol = MA5311_LOW_FIRST_CH; + ma5311->dai_sck_edge = MA5311_SCK_FALLING_EDGE; + break; + + case SND_SOC_DAIFMT_NB_IF: + dev_dbg(component->dev, "Normal BCLK, inverted frame clock\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_LEFTPOL_MASK | + MA5311_SCK_RISING_MASK, + MA5311_HIGH_FIRST_CH | + MA5311_SCK_FALLING_EDGE); + ma5311->dai_leftpol = MA5311_HIGH_FIRST_CH; + ma5311->dai_sck_edge = MA5311_SCK_FALLING_EDGE; + break; + + case SND_SOC_DAIFMT_IB_NF: + dev_dbg(component->dev, "Inverted BCLK, normal frame clock\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_LEFTPOL_MASK | + MA5311_SCK_RISING_MASK, + MA5311_LOW_FIRST_CH | + MA5311_SCK_RISING_EDGE); + ma5311->dai_leftpol = MA5311_LOW_FIRST_CH; + ma5311->dai_sck_edge = MA5311_SCK_RISING_EDGE; + break; + + case SND_SOC_DAIFMT_IB_IF: + dev_dbg(component->dev, + "Inverted BCLK, inverted frame clock\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_LEFTPOL_MASK | MA5311_SCK_RISING_MASK, + MA5311_HIGH_FIRST_CH | + MA5311_SCK_RISING_EDGE); + ma5311->dai_leftpol = MA5311_HIGH_FIRST_CH; + ma5311->dai_sck_edge = MA5311_SCK_RISING_EDGE; + break; + + default: + dev_err(component->dev, + "%s: Unsupported Bit & Frameclock : 0x%x\n", __func__, + fmt); + return -EINVAL; + } + + ma5311->format = fmt & SND_SOC_DAIFMT_FORMAT_MASK; + + return 0; +} + +static int ma5311_dai_set_sysclk(struct snd_soc_dai *dai, int clk_id, + unsigned int freq, int dir) +{ + struct snd_soc_component *component = dai->component; + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + + switch (clk_id) { + case MA5311_PLL_CLKIN_BCLK: + case MA5311_INTERNAL_OSC: + if (clk_id == MA5311_PLL_CLKIN_BCLK) + dev_dbg(component->dev, "PLL input: BCLK\n"); + break; + + default: + dev_err(component->dev, "%s: Invalid clk id: %d\n", __func__, + clk_id); + return -EINVAL; + } + + ma5311->sys_clk_id = clk_id; + + return 0; +} + +static int ma5311_dai_set_tdm_slot(struct snd_soc_dai *dai, + unsigned int tx_mask, unsigned int rx_mask, + int slots, int slot_width) +{ + struct snd_soc_component *component = dai->component; + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int rx_val = MA5311_TDM_SLOT0_RX_POS_0 | + MA5311_TDM_SLOT1_RX_POS_1; + int ret; + + /* Reject invalid frame geometry before changing the hardware. */ + switch (slot_width) { + case 16: + case 32: + break; + default: + dev_err(component->dev, "%s: unsupported TDM slot width: %d\n", + __func__, slot_width); + return -EINVAL; + } + + switch (slots) { + case 8: + break; + default: + dev_err(component->dev, "%s: unsupported TDM slot count: %d\n", + __func__, slots); + return -EINVAL; + } + + if (rx_mask & ~GENMASK(7, 0)) { + dev_err(component->dev, + "RX mask %#x exceeds %d slots\n", rx_mask, slots); + return -EINVAL; + } + + if (tx_mask != 0 && tx_mask != GENMASK(7, 0)) + return -EINVAL; + + switch (rx_mask) { + case 0: + break; + + case BIT(0) | BIT(1): + rx_val = MA5311_TDM_SLOT0_RX_POS_0 | + MA5311_TDM_SLOT1_RX_POS_1; + break; + + case BIT(2) | BIT(3): + rx_val = MA5311_TDM_SLOT0_RX_POS_2 | + MA5311_TDM_SLOT1_RX_POS_3; + break; + + case BIT(4) | BIT(5): + rx_val = MA5311_TDM_SLOT0_RX_POS_4 | + MA5311_TDM_SLOT1_RX_POS_5; + break; + + case BIT(6) | BIT(7): + rx_val = MA5311_TDM_SLOT0_RX_POS_6 | + MA5311_TDM_SLOT1_RX_POS_7; + break; + + default: + dev_err(component->dev, "Unsupported RX mask: %#x\n", + rx_mask); + return -EINVAL; + } + + ret = regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_TDM_SLOT0_RX_POS_MASK | + MA5311_TDM_SLOT1_RX_POS_MASK, + rx_val); + if (ret) + return ret; + + ma5311->dai_tdm1_rx_pos = rx_val; + + switch (tx_mask) { + case 0: + break; + + case GENMASK(7, 0): + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_ADC_TDM2_SETTING_MASK, + MA5311_DAC_38_CAPTURE_8CH_CFG); + ma5311->dai_tdm2_capture_cfg = MA5311_DAC_38_CAPTURE_8CH_CFG; + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_39_DATA_PATH, MA5311_ADC_DATA_PATH_TDM_8CH); + ma5311->dai_data_path = MA5311_ADC_DATA_PATH_TDM_8CH; + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_3A_TDM_SLOT_ENABLE, + MA5311_TDM_SLOT_ENABLE_ALL); + ma5311->dai_tdm_slot_enable = MA5311_TDM_SLOT_ENABLE_ALL; + break; + + default: + dev_err(component->dev, "Unsupported TX mask: %#x\n", + tx_mask); + return -EINVAL; + } + + ma5311->frame_size = slots * slot_width; + + dev_dbg(component->dev, "TDM slots=%d width=%d\n", slots, slot_width); + + if (!ma5311->flag_dai_tdm) + ma5311->flag_dai_tdm = true; + + return 0; +} + +static int ma5311_dai_mute_stream(struct snd_soc_dai *dai, int mute, int stream) +{ + struct snd_soc_component *component = dai->component; + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int val = MA5311_SPK_UNMUTE; + int ret; + + if (stream == SNDRV_PCM_STREAM_CAPTURE) + return 0; + + if (mute) + val = MA5311_SPK_MUTE; + + ret = regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_0E_MUTE_VOL_CTRL, + MA5311_DAC_MUTE_VOL_MASK, val); + if (ret) + return ret; + + ma5311->dai_spk_mute = val; + + return 0; +} + +static const struct snd_soc_dai_ops ma5311_dai_ops_amp = { + .hw_params = ma5311_dai_hw_params, + .set_fmt = ma5311_dai_set_fmt, + .set_sysclk = ma5311_dai_set_sysclk, + .set_tdm_slot = ma5311_dai_set_tdm_slot, + .mute_stream = ma5311_dai_mute_stream, +}; + +#define MA5311_RATES_PLAYBACK SNDRV_PCM_RATE_48000 +#define MA5311_RATES_CAPTURE SNDRV_PCM_RATE_48000 +#define MA5311_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S32_LE) + +static struct snd_soc_dai_driver ma5311_dai[] = { + { + .name = "ma5311-amplifier", + .id = 0, + .playback = { + .stream_name = "Playback", + .channels_min = 1, + .channels_max = 8, + .rates = MA5311_RATES_PLAYBACK, + .formats = MA5311_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 1, + .channels_max = 8, + .rates = MA5311_RATES_CAPTURE, + .formats = MA5311_FORMATS, + }, + .ops = &ma5311_dai_ops_amp, + .symmetric_rate = 1, + .symmetric_sample_bits = 1, + }, +}; + +static void ma5311_unregister_ancillary_client(void *data) +{ + struct i2c_client *client = data; + + i2c_unregister_device(client); +} + +static irqreturn_t ma5311_irq_thread(int irq, void *data) +{ + struct ma5311_priv *ma5311 = data; + unsigned int dac_status; + int ret = 0; + + ret = regmap_read(ma5311->ctrl_regmap, + MA5311_DAC_EA_DAC_STATUS, &dac_status); + if (ret) { + dev_err_ratelimited(ma5311->dev, + "I2C Read Failed During Interrupt Handling\n"); + return IRQ_NONE; + } + + if (!(dac_status & MA5311_DAC_EA_FAULT_MASK)) + return IRQ_NONE; + + dev_err_ratelimited(ma5311->dev, "FAULT Asserted\n"); + + return IRQ_HANDLED; +} + +static int ma5311_i2c_probe(struct i2c_client *client) +{ + struct ma5311_priv *ma5311; + int ret; + unsigned int irq_type; + + ma5311 = devm_kzalloc(&client->dev, sizeof(*ma5311), GFP_KERNEL); + if (!ma5311) + return -ENOMEM; + + ma5311->ctrl_regmap = devm_regmap_init_i2c(client, + &ma5311_ctrl_regmap_config); + if (IS_ERR(ma5311->ctrl_regmap)) + return dev_err_probe(&client->dev, PTR_ERR(ma5311->ctrl_regmap), + "%s: Failed to allocate control regmap\n", + __func__); + + ma5311->adc_client = i2c_new_ancillary_device(client, "adc", 0x3f); + if (IS_ERR(ma5311->adc_client)) + return dev_err_probe(&client->dev, PTR_ERR(ma5311->adc_client), + "Failed to create ADC ancillary client\n"); + + ret = devm_add_action_or_reset(&client->dev, + ma5311_unregister_ancillary_client, + ma5311->adc_client); + if (ret) + return ret; + + ma5311->adc_regmap = devm_regmap_init_i2c(ma5311->adc_client, + &ma5311_adc_regmap_config); + if (IS_ERR(ma5311->adc_regmap)) + return dev_err_probe(&client->dev, PTR_ERR(ma5311->adc_regmap), + "Failed to allocate ADC regmap\n"); + + ma5311->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", + GPIOD_OUT_LOW); + if (IS_ERR(ma5311->reset_gpio)) + return dev_err_probe(&client->dev, PTR_ERR(ma5311->reset_gpio), + "Failed to acquire reset GPIO\n"); + + if (ma5311->reset_gpio) + msleep(MA5311_RESET_RECOVERY_MS); + + ma5311->amp_mode = MA5311_MONO_BOTH_MODE; + ma5311->num_of_pll_matches = ARRAY_SIZE(ma5311_pll_matches); + ma5311->pll_matches = ma5311_pll_matches; + ma5311->format = SND_SOC_DAIFMT_I2S; + ma5311->sys_clk_id = MA5311_PLL_CLKIN_BCLK; + ma5311->dev = &client->dev; + ma5311->frame_size = 0; + ma5311->dai_sys_clk = 0; + ma5311->dai_mas_clk_sel = MA5311_LRCK_SCK_CLK_SLAVE_MODE; + ma5311->dai_adc_clk = 0; + ma5311->dai_adc_mix_ch = MA5311_ADC_MIX_CH0; + ma5311->dai_clk_mode = MA5311_DEVICE_MODE; + ma5311->dai_leftpol = MA5311_LOW_FIRST_CH; + ma5311->dai_sck_edge = MA5311_SCK_FALLING_EDGE; + ma5311->dai_spk_mute = MA5311_SPK_MUTE; + ma5311->dai_tdm1_rx_pos = MA5311_TDM_SLOT0_RX_POS_0 | + MA5311_TDM_SLOT1_RX_POS_1; + ma5311->dai_tdm2_data_len = MA5311_DAC_38_DATA_LEN_16; + ma5311->dai_tdm2_capture_cfg = MA5311_DAC_38_CAPTURE_8CH_CFG; + ma5311->dai_data_path = MA5311_ADC_DATA_PATH_CH0; + ma5311->dai_tdm_slot_enable = MA5311_TDM_SLOT_DISABLE_ALL; + ma5311->dai_pll_input = MA5311_DAC_PLLIN_EXT_OSC | + MA5311_DAC_PLL_REF_EXT_CLK | + MA5311_DAC_PLL_REF_CLK2_SCK; + ma5311->dai_pll_post_n = MA5311_PLL_POST_N_DEFAULT; + ma5311->dai_pll_n = MA5311_PLL_N_DEFAULT; + ma5311->dai_pll_f1 = MA5311_PLL_F1_DEFAULT; + ma5311->dai_pll_f2 = MA5311_PLL_F2_DEFAULT; + ma5311->dai_pll_f3_p_cp = MA5311_PLL_F3_P_CP_DEFAULT; + ma5311->dai_sdo_len = MA5311_TOP_MAN1_SDO_16B; + ma5311->dai_sck_rate = MA5311_DAC_A1_SCK_RATE_32FS; + ma5311->dai_o_format = MA5311_TOP_MAN1_O_FORMAT_I2S; + ma5311->dai_adc1_word_len = MA5311_ADC_WORD_LENGTH_24; + ma5311->dai_adc1_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + ma5311->dai_adc2_word_len = MA5311_ADC_WORD_LENGTH_24; + ma5311->dai_adc2_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + ma5311->dai_adc3_word_len = MA5311_ADC_WORD_LENGTH_24; + ma5311->dai_adc3_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + ma5311->dai_adc4_word_len = MA5311_ADC_WORD_LENGTH_24; + ma5311->dai_adc4_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + ma5311->flag_ext_rst = false; + ma5311->flag_dai_tdm = false; + i2c_set_clientdata(client, ma5311); + + ret = devm_snd_soc_register_component(&client->dev, &ma5311_component, + ma5311_dai, 1); + if (ret) { + dev_err(&client->dev, "Failed to register component: %d\n", + ret); + return ret; + } + + if (client->irq > 0) { + irq_type = irq_get_trigger_type(client->irq); + if (irq_type != IRQ_TYPE_EDGE_FALLING) + return dev_err_probe(&client->dev, -EINVAL, + "Falling-edge IRQ required\n"); + + ret = devm_request_threaded_irq(&client->dev, client->irq, NULL, + ma5311_irq_thread, IRQF_ONESHOT, + "ma5311", ma5311); + if (ret) + return dev_err_probe(&client->dev, ret, + "Failed to request IRQ %d\n", + client->irq); + } else { + dev_warn(&client->dev, "No IRQ configured\n"); + } + + return ret; +} + +static const struct i2c_device_id ma5311_i2c_id[] = { + { .name = "ma5311", .driver_data = 0 }, + { } +}; + +MODULE_DEVICE_TABLE(i2c, ma5311_i2c_id); + +static const struct of_device_id ma5311_of_match[] = { + { .compatible = "irondevice,ma5311" }, + { } +}; + +MODULE_DEVICE_TABLE(of, ma5311_of_match); + +static struct i2c_driver ma5311_i2c_driver = { + .driver = { + .name = "ma5311", + .of_match_table = ma5311_of_match, + }, + .probe = ma5311_i2c_probe, + .id_table = ma5311_i2c_id, +}; + +module_i2c_driver(ma5311_i2c_driver); + +MODULE_DESCRIPTION("ALSA SoC MA5311 driver"); +MODULE_AUTHOR("Hyunuk Son, "); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/ma5311.h b/sound/soc/codecs/ma5311.h new file mode 100644 index 00000000000000..2470124e4290dc --- /dev/null +++ b/sound/soc/codecs/ma5311.h @@ -0,0 +1,558 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * ma5311.h -- MA5311 ALSA SoC codec register definitions + */ + +#ifndef _MA5311_H +#define _MA5311_H + +#include + +/* DAC/control and ADC registers use separate I2C banks. */ + +/* I2C addresses */ +#define MA5311_ADC_I2C_ADDR_00 0x3f +#define MA5311_ADC_I2C_ADDR_01 0x4f +#define MA5311_ADC_I2C_ADDR_10 0x5f +#define MA5311_ADC_I2C_ADDR_11 0x6f + +#define MA5311_I2C_RETRY_COUNT 3 + +/* DAC and control register addresses */ +#define MA5311_DAC_00_SYSTEM_CTRL1 0x00 +#define MA5311_DAC_01_INPUT1_CTRL1 0x01 +#define MA5311_DAC_02_INPUT1_CTRL2 0x02 +#define MA5311_DAC_03_INPUT1_CTRL3 0x03 +#define MA5311_DAC_04_INPUT1_CTRL4 0x04 +#define MA5311_DAC_05_ADC_DAC_MIX2 0x05 +#define MA5311_DAC_09_OUTPUT_CTRL 0x09 +#define MA5311_DAC_0A_SPK_VOL_L 0x0a +#define MA5311_DAC_0B_SPK_VOL_R 0x0b +#define MA5311_DAC_0E_MUTE_VOL_CTRL 0x0e +#define MA5311_DAC_0F_SYSTEM_CTRL2 0x0f +#define MA5311_DAC_10_SYSTEM_CTRL3 0x10 +#define MA5311_DAC_11_SYSTEM_CTRL4 0x11 +#define MA5311_DAC_12_SYSTEM_CTRL5 0x12 +#define MA5311_DAC_14_MODULATOR2 0x14 +#define MA5311_DAC_15_BASS_SPK1 0x15 +#define MA5311_DAC_16_BASS_SPK2 0x16 +#define MA5311_DAC_17_BASS_SPK3 0x17 +#define MA5311_DAC_18_BASS_SPK4 0x18 +#define MA5311_DAC_19_BASS_SPK5 0x19 +#define MA5311_DAC_1A_BASS_SPK6 0x1a +#define MA5311_DAC_1B_BASS_SPK7 0x1b +#define MA5311_DAC_23_COMP_LIM1 0x23 +#define MA5311_DAC_24_COMP_LIM2 0x24 +#define MA5311_DAC_25_COMP_LIM3 0x25 +#define MA5311_DAC_26_COMP_LIM4 0x26 +#define MA5311_DAC_2B_EQ_MODE 0x2b +#define MA5311_DAC_2C_EQ_GRAPHIC1 0x2c +#define MA5311_DAC_2D_EQ_GRAPHIC2 0x2d +#define MA5311_DAC_2E_EQ_GRAPHIC3 0x2e +#define MA5311_DAC_2F_EQ_GRAPHIC4 0x2f +#define MA5311_DAC_30_EQ_GRAPHIC5 0x30 +#define MA5311_DAC_33_FLL_CTRL3 0x33 +#define MA5311_DAC_34_EQ_CTRL 0x34 +#define MA5311_DAC_35_POST_DRC_CTRL 0x35 +#define MA5311_DAC_36_PROTECTION 0x36 +#define MA5311_DAC_37_TDM1 0x37 +#define MA5311_DAC_38_TDM2 0x38 +#define MA5311_DAC_39_DATA_PATH 0x39 +#define MA5311_DAC_3A_TDM_SLOT_ENABLE 0x3a +#define MA5311_DAC_3B_TEST1 0x3b +#define MA5311_DAC_3C_TEST2 0x3c +#define MA5311_DAC_3D_TEST3 0x3d +#define MA5311_DAC_40_EQ_CTRL1 0x40 +#define MA5311_DAC_41_EQ_CTRL2 0x41 +#define MA5311_DAC_42_EQ_CTRL3 0x42 +#define MA5311_DAC_43_EQ_CTRL4 0x43 +#define MA5311_DAC_44_EQ_CTRL5 0x44 +#define MA5311_DAC_45_EQ_CTRL6 0x45 +#define MA5311_DAC_46_EQ_CTRL7 0x46 +#define MA5311_DAC_47_EQ_CTRL8 0x47 +#define MA5311_DAC_48_EQ_CTRL9 0x48 +#define MA5311_DAC_49_EQ_CTRL10 0x49 +#define MA5311_DAC_4A_EQ_CTRL11 0x4a +#define MA5311_DAC_4B_EQ_CTRL12 0x4b +#define MA5311_DAC_4C_EQ_CTRL13 0x4c +#define MA5311_DAC_4D_EQ_CTRL14 0x4d +#define MA5311_DAC_4E_EQ_CTRL15 0x4e +#define MA5311_DAC_4F_EQ_CTRL16 0x4f +#define MA5311_DAC_50_EQ_CTRL17 0x50 +#define MA5311_DAC_51_EQ_CTRL18 0x51 +#define MA5311_DAC_52_EQ_CTRL19 0x52 +#define MA5311_DAC_53_EQ_CTRL20 0x53 +#define MA5311_DAC_54_EQ_CTRL21 0x54 +#define MA5311_DAC_55_EQ_CTRL22 0x55 +#define MA5311_DAC_56_EQ_CTRL23 0x56 +#define MA5311_DAC_57_EQ_CTRL24 0x57 +#define MA5311_DAC_58_EQ_CTRL25 0x58 +#define MA5311_DAC_59_EQ_CTRL26 0x59 +#define MA5311_DAC_5A_EQ_CTRL27 0x5a +#define MA5311_DAC_5B_EQ_CTRL28 0x5b +#define MA5311_DAC_5C_EQ_CTRL29 0x5c +#define MA5311_DAC_5D_EQ_CTRL30 0x5d +#define MA5311_DAC_5E_EQ_CTRL31 0x5e +#define MA5311_DAC_5F_EQ_CTRL32 0x5f +#define MA5311_DAC_60_EQ_CTRL33 0x60 +#define MA5311_DAC_61_EQ_CTRL34 0x61 +#define MA5311_DAC_62_EQ_CTRL35 0x62 +#define MA5311_DAC_63_EQ_CTRL36 0x63 +#define MA5311_DAC_64_EQ_CTRL37 0x64 +#define MA5311_DAC_65_EQ_CTRL38 0x65 +#define MA5311_DAC_66_EQ_CTRL39 0x66 +#define MA5311_DAC_67_EQ_CTRL40 0x67 +#define MA5311_DAC_68_EQ_CTRL41 0x68 +#define MA5311_DAC_69_EQ_CTRL42 0x69 +#define MA5311_DAC_6A_EQ_CTRL43 0x6a +#define MA5311_DAC_6B_EQ_CTRL44 0x6b +#define MA5311_DAC_6C_EQ_CTRL45 0x6c +#define MA5311_DAC_6D_EQ_CTRL46 0x6d +#define MA5311_DAC_6E_EQ_CTRL47 0x6e +#define MA5311_DAC_6F_EQ_CTRL48 0x6f +#define MA5311_DAC_70_EQ_CTRL49 0x70 +#define MA5311_DAC_71_EQ_CTRL50 0x71 +#define MA5311_DAC_72_EQ_CTRL51 0x72 +#define MA5311_DAC_73_EQ_CTRL52 0x73 +#define MA5311_DAC_74_EQ_CTRL53 0x74 +#define MA5311_DAC_75_EQ_CTRL54 0x75 +#define MA5311_DAC_76_EQ_CTRL55 0x76 +#define MA5311_DAC_77_EQ_CTRL56 0x77 +#define MA5311_DAC_78_EQ_CTRL57 0x78 +#define MA5311_DAC_79_EQ_CTRL58 0x79 +#define MA5311_DAC_7A_EQ_CTRL59 0x7a +#define MA5311_DAC_7B_EQ_CTRL60 0x7b +#define MA5311_DAC_7C_EQ_CTRL61 0x7c +#define MA5311_DAC_7D_EQ_CTRL62 0x7d +#define MA5311_DAC_7E_EQ_CTRL63 0x7e +#define MA5311_DAC_7F_EQ_CTRL64 0x7f +#define MA5311_DAC_80_EQ_CTRL65 0x80 +#define MA5311_DAC_81_EQ_CTRL66 0x81 +#define MA5311_DAC_82_EQ_CTRL67 0x82 +#define MA5311_DAC_83_EQ_CTRL68 0x83 +#define MA5311_DAC_84_EQ_CTRL69 0x84 +#define MA5311_DAC_85_EQ_CTRL70 0x85 +#define MA5311_DAC_86_EQ_CTRL71 0x86 +#define MA5311_DAC_87_EQ_CTRL72 0x87 +#define MA5311_DAC_88_EQ_CTRL73 0x88 +#define MA5311_DAC_89_EQ_CTRL74 0x89 +#define MA5311_DAC_8A_EQ_CTRL75 0x8a +#define MA5311_DAC_8B_PLL_POST_N 0x8b +#define MA5311_DAC_8C_PLL_N 0x8c +#define MA5311_DAC_8D_PLL_F1 0x8d +#define MA5311_DAC_8E_PLL_F2 0x8e +#define MA5311_DAC_8F_PLL_F3_P_CP 0x8f +#define MA5311_DAC_91_ADC_DAC_MIX 0x91 +#define MA5311_DAC_A1_TOP_MAN1_FOR_SDO 0xa1 +#define MA5311_DAC_A2_TOP_MAN2 0xa2 +#define MA5311_DAC_A3_TOP_MAN3 0xa3 +#define MA5311_DAC_A4_BLOCK_CONTROL 0xa4 +#define MA5311_DAC_A5_VALUE_CONTROL 0xa5 +#define MA5311_DAC_A6_VALUE_CONTROL2 0xa6 +#define MA5311_DAC_A7_DT_CONTROL 0xa7 +#define MA5311_DAC_A8_SLOPE_CONTROL 0xa8 +#define MA5311_DAC_A9_FDPEC_CONTROL 0xa9 +#define MA5311_DAC_AA_LDO_CONTROL 0xaa +#define MA5311_DAC_AB_PRESCALER 0xab +#define MA5311_DAC_AC_MBD_COMP_LIM1 0xac +#define MA5311_DAC_AD_MBD_COMP_LIM2 0xad +#define MA5311_DAC_AE_MBD_COMP_LIM3 0xae +#define MA5311_DAC_AF_MBD_COMP_LIM4 0xaf +#define MA5311_DAC_B0_BPD_COMP_LIM1 0xb0 +#define MA5311_DAC_B1_BPD_COMP_LIM2 0xb1 +#define MA5311_DAC_B2_BPD_COMP_LIM3 0xb2 +#define MA5311_DAC_B3_BPD_COMP_LIM4 0xb3 +#define MA5311_DAC_B4_DSP_SPK_CTRL 0xb4 +#define MA5311_DAC_B5_MCLKO_TEST 0xb5 +#define MA5311_DAC_B7_TOP_MAN4 0xb7 +#define MA5311_DAC_B8_TOP_MAN5 0xb8 +#define MA5311_DAC_B9_PLL_A_SETTING 0xb9 +#define MA5311_DAC_BB_CLASS_G_LEVEL1 0xbb +#define MA5311_DAC_BC_CLASS_G_LEVEL2 0xbc +#define MA5311_DAC_BD_TONE_GENERATOR 0xbd +#define MA5311_DAC_BE_TONE_FINE_VOLUME 0xbe +#define MA5311_DAC_BF_POWER_METER 0xbf +#define MA5311_DAC_EA_DAC_STATUS 0xea +#define MA5311_DAC_EB_DAC_OCP_STATUS 0xeb +#define MA5311_DAC_EC_DAC_SCP_STATUS 0xec +#define MA5311_DAC_FB_STATUS2 0xfb +#define MA5311_DAC_FC_STATUS3 0xfc +#define MA5311_DAC_FD_POWER_METER_DISPLAY 0xfd +#define MA5311_DAC_FF_VERSION 0xff + +/* DAC/control register masks and values */ + +#define MA5311_POWER_MASK BIT(0) +#define MA5311_POWER_OFF 0 +#define MA5311_POWER_ON BIT(0) + +#define MA5311_DAC_MUTE_VOL_MASK GENMASK(1, 0) +#define MA5311_SPK_MUTE 0x03 +#define MA5311_SPK_UNMUTE 0x00 + +/* 0x10: Speaker mode */ +#define MA5311_SPK_MODE_MASK GENMASK(4, 2) +#define MA5311_SPK_MONO_LEFT 0x02 +#define MA5311_SPK_MONO_RIGHT 0x04 +#define MA5311_SPK_MONO_BOTH 0x0c +#define MA5311_SPK_STEREO 0x10 +#define MA5311_SPK_OFF 0x00 + +/* 0x37: TDM receive slot positions */ +#define MA5311_TDM_SLOT0_RX_POS_MASK GENMASK(5, 3) +#define MA5311_TDM_SLOT0_RX_POS_0 0x00 +#define MA5311_TDM_SLOT0_RX_POS_1 0x08 +#define MA5311_TDM_SLOT0_RX_POS_2 0x10 +#define MA5311_TDM_SLOT0_RX_POS_3 0x18 +#define MA5311_TDM_SLOT0_RX_POS_4 0x20 +#define MA5311_TDM_SLOT0_RX_POS_5 0x28 +#define MA5311_TDM_SLOT0_RX_POS_6 0x30 +#define MA5311_TDM_SLOT0_RX_POS_7 0x38 + +#define MA5311_TDM_SLOT1_RX_POS_MASK GENMASK(2, 0) +#define MA5311_TDM_SLOT1_RX_POS_0 0x00 +#define MA5311_TDM_SLOT1_RX_POS_1 0x01 +#define MA5311_TDM_SLOT1_RX_POS_2 0x02 +#define MA5311_TDM_SLOT1_RX_POS_3 0x03 +#define MA5311_TDM_SLOT1_RX_POS_4 0x04 +#define MA5311_TDM_SLOT1_RX_POS_5 0x05 +#define MA5311_TDM_SLOT1_RX_POS_6 0x06 +#define MA5311_TDM_SLOT1_RX_POS_7 0x07 + +#define MA5311_TDM_N_SLOT_MASK BIT(6) +#define MA5311_TDM_N_SLOT_4 0 +#define MA5311_TDM_N_SLOT_8 BIT(6) + +#define MA5311_TDM_SLOT0_TX_POS_MASK GENMASK(5, 3) +#define MA5311_TDM_SLOT0_TX_POS_0 0x00 +#define MA5311_TDM_SLOT0_TX_POS_1 0x08 +#define MA5311_TDM_SLOT0_TX_POS_2 0x10 +#define MA5311_TDM_SLOT0_TX_POS_3 0x18 +#define MA5311_TDM_SLOT0_TX_POS_4 0x20 +#define MA5311_TDM_SLOT0_TX_POS_5 0x28 +#define MA5311_TDM_SLOT0_TX_POS_6 0x30 +#define MA5311_TDM_SLOT0_TX_POS_7 0x38 + +#define MA5311_TDM_SLOT1_TX_POS_MASK GENMASK(2, 0) +#define MA5311_TDM_SLOT1_TX_POS_0 0x00 +#define MA5311_TDM_SLOT1_TX_POS_1 0x01 +#define MA5311_TDM_SLOT1_TX_POS_2 0x02 +#define MA5311_TDM_SLOT1_TX_POS_3 0x03 +#define MA5311_TDM_SLOT1_TX_POS_4 0x04 +#define MA5311_TDM_SLOT1_TX_POS_5 0x05 +#define MA5311_TDM_SLOT1_TX_POS_6 0x06 +#define MA5311_TDM_SLOT1_TX_POS_7 0x07 + +#define MA5311_ADC_TDM2_SETTING_MASK GENMASK(6, 0) + +/* 0x39: SDO data path */ +#define MA5311_DAC_SDO_DATA_PATH_MASK GENMASK(3, 2) + +/* 0x91: ADC-to-DAC mix */ +#define MA5311_DAC_ADC_DAC_MIX_CH_MASK GENMASK(1, 0) + +/* 0xA1: SDO output format and word length */ +#define MA5311_TOP_MAN1_O_FORMAT_MASK GENMASK(7, 5) +#define MA5311_TOP_MAN1_O_FORMAT_I2S 0x40 +#define MA5311_TOP_MAN1_O_FORMAT_TDM 0x80 +#define MA5311_TOP_MAN1_SOO_LENGTH_MASK GENMASK(2, 1) +#define MA5311_TOP_MAN1_SDO_16B 0x04 +#define MA5311_TOP_MAN1_SDO_24B 0x00 + +/* 0xA2: PLL power */ +#define MA5311_PLL_MASK BIT(6) +#define MA5311_PLL_ON 0 +#define MA5311_PLL_OFF BIT(6) + +/* 0xFF: Device identification and revision */ +#define MA5311_DAC_VERSION_MASK GENMASK(7, 0) +#define MA5311_DEVICE_ID 0x0bU +#define MA5311_REV_NUM_STATUS GENMASK(7, 0) + +/* ADC register addresses */ +/* ADC CH1(L/R) */ +/* General Settings */ +#define MA5311_ADC_CH1_00_GENERAL_SETTING 0x00 +#define MA5311_ADC_CH1_01_DMIC_ALC1 0x01 +#define MA5311_ADC_CH1_02_ALC2 0x02 +#define MA5311_ADC_CH1_03_ALC3 0x03 +#define MA5311_ADC_CH1_04_ALC4 0x04 +#define MA5311_ADC_CH1_05_ALC5 0x05 +#define MA5311_ADC_CH1_06_ALC6 0x06 +#define MA5311_ADC_CH1_07_VOLUME_LEFT 0x07 +#define MA5311_ADC_CH1_08_VOLUME_RIGHT 0x08 +#define MA5311_ADC_CH1_09_PGA_LEFT 0x09 +#define MA5311_ADC_CH1_0A_PGA_RIGHT 0x0a +#define MA5311_ADC_CH1_0B_AFE 0x0b +#define MA5311_ADC_CH1_0C_VOLUME_BOOST_LINE1 0x0c +#define MA5311_ADC_CH1_0D_VOLUME_BOOST_LINE2 0x0d +#define MA5311_ADC_CH1_0E_MUTE_DATA_FLOW 0x0e +#define MA5311_ADC_CH1_0F_OUTPUT_FORMAT 0x0f + +/* ADC CH2(L/R) */ +#define MA5311_ADC_CH2_10_GENERAL_SETTING 0x10 +#define MA5311_ADC_CH2_11_DMIC_ALC1 0x11 +#define MA5311_ADC_CH2_12_ALC2 0x12 +#define MA5311_ADC_CH2_13_ALC3 0x13 +#define MA5311_ADC_CH2_14_ALC4 0x14 +#define MA5311_ADC_CH2_15_ALC5 0x15 +#define MA5311_ADC_CH2_16_ALC6 0x16 +#define MA5311_ADC_CH2_17_VOLUME_LEFT 0x17 +#define MA5311_ADC_CH2_18_VOLUME_RIGHT 0x18 +#define MA5311_ADC_CH2_19_PGA_LEFT 0x19 +#define MA5311_ADC_CH2_1A_PGA_RIGHT 0x1a +#define MA5311_ADC_CH2_1B_AFE 0x1b +#define MA5311_ADC_CH2_1C_VOLUME_BOOST_LINE1 0x1c +#define MA5311_ADC_CH2_1D_VOLUME_BOOST_LINE2 0x1d +#define MA5311_ADC_CH2_1E_MUTE_DATA_FLOW 0x1e +#define MA5311_ADC_CH2_1F_OUTPUT_FORMAT 0x1f + +/* ADC CH3(L/R) */ +#define MA5311_ADC_CH3_20_GENERAL_SETTING 0x20 +#define MA5311_ADC_CH3_21_DMIC_ALC1 0x21 +#define MA5311_ADC_CH3_22_ALC2 0x22 +#define MA5311_ADC_CH3_23_ALC3 0x23 +#define MA5311_ADC_CH3_24_ALC4 0x24 +#define MA5311_ADC_CH3_25_ALC5 0x25 +#define MA5311_ADC_CH3_26_ALC6 0x26 +#define MA5311_ADC_CH3_27_VOLUME_LEFT 0x27 +#define MA5311_ADC_CH3_28_VOLUME_RIGHT 0x28 +#define MA5311_ADC_CH3_29_PGA_LEFT 0x29 +#define MA5311_ADC_CH3_2A_PGA_RIGHT 0x2a +#define MA5311_ADC_CH3_2B_AFE 0x2b +#define MA5311_ADC_CH3_2C_VOLUME_BOOST_LINE1 0x2c +#define MA5311_ADC_CH3_2D_VOLUME_BOOST_LINE2 0x2d +#define MA5311_ADC_CH3_2E_MUTE_DATA_FLOW 0x2e +#define MA5311_ADC_CH3_2F_OUTPUT_FORMAT 0x2f + +/* ADC CH4(L/R) */ +#define MA5311_ADC_CH4_30_GENERAL_SETTING 0x30 +#define MA5311_ADC_CH4_31_DMIC_ALC1 0x31 +#define MA5311_ADC_CH4_32_ALC2 0x32 +#define MA5311_ADC_CH4_33_ALC3 0x33 +#define MA5311_ADC_CH4_34_ALC4 0x34 +#define MA5311_ADC_CH4_35_ALC5 0x35 +#define MA5311_ADC_CH4_36_ALC6 0x36 +#define MA5311_ADC_CH4_37_VOLUME_LEFT 0x37 +#define MA5311_ADC_CH4_38_VOLUME_RIGHT 0x38 +#define MA5311_ADC_CH4_39_PGA_LEFT 0x39 +#define MA5311_ADC_CH4_3A_PGA_RIGHT 0x3a +#define MA5311_ADC_CH4_3B_AFE 0x3b +#define MA5311_ADC_CH4_3C_VOLUME_BOOST_LINE1 0x3c +#define MA5311_ADC_CH4_3D_VOLUME_BOOST_LINE2 0x3d +#define MA5311_ADC_CH4_3E_MUTE_DATA_FLOW 0x3e +#define MA5311_ADC_CH4_3F_OUTPUT_FORMAT 0x3f + +/* ADC register masks and values */ +#define MA5311_ADC_HPF_ENABLE_MASK BIT(7) +#define MA5311_ADC_OSR_SDM_MASK BIT(6) +#define MA5311_ADC_SAMPLE_RATE_MASK GENMASK(4, 2) +#define MA5311_ADC_SAMPLE_RATE_192K 0x00U +#define MA5311_ADC_SAMPLE_RATE_96K 0x04U +#define MA5311_ADC_SAMPLE_RATE_48K 0x08U +#define MA5311_ADC_SAMPLE_RATE_24K 0x10U +#define MA5311_ADC_SAMPLE_RATE_12K 0x18U +#define MA5311_ADC_OSR_DEC_MASK BIT(1) +#define MA5311_ADC_POWER_MASK BIT(0) +#define MA5311_ADC_POWER_ON 0U +#define MA5311_ADC_POWER_DOWN BIT(0) + +#define MA5311_ADC_SYSCLK_MASK GENMASK(7, 6) +#define MA5311_ADC_DMIC_CLOCK_MASK BIT(5) +#define MA5311_ADC_DMIC_MODE_MASK BIT(4) +#define MA5311_ADC_ALC_SELECT_MASK GENMASK(1, 0) + +#define MA5311_ADC_VOL_CTRL_MASK GENMASK(7, 0) +#define MA5311_ADC_PGA_CTRL_MASK GENMASK(5, 0) + +#define MA5311_ADC_LRCK_POL_MASK BIT(7) +#define MA5311_ADC_SCK_POL_MASK BIT(6) +#define MA5311_ADC_SWAP_LR_MASK BIT(5) +#define MA5311_ADC_MUTE_SLOPE_MASK GENMASK(4, 3) +#define MA5311_ADC_MUTE_RIGHT_MASK BIT(2) +#define MA5311_ADC_MUTE_LEFT_MASK BIT(1) + +#define MA5311_ADC_LEFT_MUTE BIT(1) +#define MA5311_ADC_LEFT_DEMUTE 0 +#define MA5311_ADC_RIGHT_MUTE BIT(2) +#define MA5311_ADC_RIGHT_DEMUTE 0 + +#define MA5311_ADC_MUTE_BOTH_MASK GENMASK(2, 1) +#define MA5311_ADC_BOTH_MUTE 0x06 +#define MA5311_ADC_BOTH_DEMUTE 0x00 + +#define MA5311_ADC_OUTPUT_MASTER_MASK BIT(7) +#define MA5311_ADC_OUTPUT_SCK_RATE_MASK GENMASK(6, 5) +#define MA5311_ADC_OUTPUT_WORD_LENGTH_MASK GENMASK(4, 3) +#define MA5311_ADC_OUTPUT_FORMAT_MASK GENMASK(2, 0) +#define MA5311_ADC_OUTPUT_FORMAT_RJ 0x00U +#define MA5311_ADC_OUTPUT_FORMAT_LJ 0x01U +#define MA5311_ADC_OUTPUT_FORMAT_I2S 0x02U +#define MA5311_ADC_OUTPUT_FORMAT_SPI 0x03U +#define MA5311_ADC_OUTPUT_FORMAT_PCM_SHORT 0x04U + +#define MA5311_ADC_WORD_LENGTH_24 0x00 +#define MA5311_ADC_WORD_LENGTH_16 0x18 + +#define MA5311_PLL_CLKIN_BCLK 0x00 +#define MA5311_INTERNAL_OSC 0x01 +#define MA5311_DUMMY_BCLK 0 +#define MA5311_INT_OSC_POST_N 0x07 +#define MA5311_INT_OSC_N 0x70 +#define MA5311_INT_OSC_F1 0x00 +#define MA5311_INT_OSC_F2 0x00 +#define MA5311_INT_OSC_F3_P_CP 0x0b + +#define MA5311_RESET_CTRL_NAME "Reset Command" +#define MA5311_LEFT_VOL_CTRL_NAME "Left Speaker Volume" +#define MA5311_RIGHT_VOL_CTRL_NAME "Right Speaker Volume" + +#define MA5311_ADC1_LEFT_VOL_CTRL_NAME "ADC1 Left Volume" +#define MA5311_ADC1_RIGHT_VOL_CTRL_NAME "ADC1 Right Volume" +#define MA5311_ADC1_LEFT_PGA_CTRL_NAME "ADC1 Left PGA" +#define MA5311_ADC1_RIGHT_PGA_CTRL_NAME "ADC1 Right PGA" + +#define MA5311_ADC2_LEFT_VOL_CTRL_NAME "ADC2 Left Volume" +#define MA5311_ADC2_RIGHT_VOL_CTRL_NAME "ADC2 Right Volume" +#define MA5311_ADC2_LEFT_PGA_CTRL_NAME "ADC2 Left PGA" +#define MA5311_ADC2_RIGHT_PGA_CTRL_NAME "ADC2 Right PGA" + +#define MA5311_ADC3_LEFT_VOL_CTRL_NAME "ADC3 Left Volume" +#define MA5311_ADC3_RIGHT_VOL_CTRL_NAME "ADC3 Right Volume" +#define MA5311_ADC3_LEFT_PGA_CTRL_NAME "ADC3 Left PGA" +#define MA5311_ADC3_RIGHT_PGA_CTRL_NAME "ADC3 Right PGA" + +#define MA5311_ADC4_LEFT_VOL_CTRL_NAME "ADC4 Left Volume" +#define MA5311_ADC4_RIGHT_VOL_CTRL_NAME "ADC4 Right Volume" +#define MA5311_ADC4_LEFT_PGA_CTRL_NAME "ADC4 Left PGA" +#define MA5311_ADC4_RIGHT_PGA_CTRL_NAME "ADC4 Right PGA" + +#define MA5311_CAPTURE_NAME "Capture Mode" +#define MA5311_TDM_RX_SLOT "TDM RX Slot" + +#define MA5311_AIF_IN_NAME "AIF IN Source" +#define MA5311_AIF_OUT0_NAME "AIF OUT0 Source" +#define MA5311_AIF_OUT1_NAME "AIF OUT1 Source" + +#define MA5311_CONTROLLER_DEVICE_MASK BIT(7) +#define MA5311_DEVICE_MODE 0 +#define MA5311_CONTROLLER_MODE BIT(7) + +#define MA5311_SCK_RISING_MASK BIT(2) +#define MA5311_SCK_RISING_EDGE BIT(2) +#define MA5311_SCK_FALLING_EDGE 0 + +#define MA5311_LEFTPOL_MASK BIT(3) +#define MA5311_LOW_FIRST_CH 0 +#define MA5311_HIGH_FIRST_CH BIT(3) + +enum ma5311_mode { + MA5311_MONO_BOTH_MODE, + MA5311_STEREO_MODE, + MA5311_MONO_LEFT_MODE, + MA5311_MONO_RIGHT_MODE, +}; + +enum ma5311_setting { + MA5311_SPEAKER_MODE, + MA5311_RECEIVER_MODE, +}; + +enum ma5311_adc_mode { + MA5311_I2S_MODE_ADC1, + MA5311_I2S_MODE_ADC2, + MA5311_I2S_MODE_ADC3, + MA5311_I2S_MODE_ADC4, + MA5311_TDM_MODE, +}; + +#define MA5311_TSD_FAULT_STATUS BIT(2) + +/* Field encodings used by the existing serial audio configuration. */ +#define MA5311_DAC_A1_SCK_RATE_MASK GENMASK(4, 3) +#define MA5311_DAC_A1_SCK_RATE_32FS 0x18 +#define MA5311_DAC_A1_SCK_RATE_64FS 0x00 + +/* MA5311_DAC_38_TDM2 data length field. */ +#define MA5311_DAC_38_DATA_LEN_MASK BIT(7) +#define MA5311_DAC_38_DATA_LEN_16 0 +#define MA5311_DAC_38_DATA_LEN_32 BIT(7) +#define MA5311_DAC_38_CAPTURE_8CH_CFG 0x41 +#define MA5311_DAC_38_CAPTURE_4CH_CFG 0x01 + +/* Full-register values: keep the other DATA_PATH bits cleared. */ +#define MA5311_ADC_DATA_PATH_I2S 0x00 +#define MA5311_ADC_DATA_PATH_TDM_8CH 0x01 +#define MA5311_TDM_SLOT_ENABLE_ALL 0xff +#define MA5311_TDM_SLOT_DISABLE_ALL 0x00 + +/* Preserve the SCK_RATE encoding used for 16-bit ADC capture. */ +#define MA5311_ADC_SCK_RATE_16BIT_CFG 0x40 +#define MA5311_ADC_SCK_RATE_24BIT_CFG 0x00 + +/* 0xEA: DAC fault status */ +#define MA5311_DAC_EA_FAULT_MASK BIT(7) +#define MA5311_DAC_EA_UVLON_CH1_MASK BIT(6) +#define MA5311_DAC_EA_UVLON_CH2_MASK BIT(5) +#define MA5311_DAC_EA_TSDW_MASK BIT(3) +#define MA5311_DAC_EA_TSD_MASK BIT(2) + +/* 0xEB: DAC OCP status */ +#define MA5311_DAC_EB_IPSC_2U_MASK BIT(7) +#define MA5311_DAC_EB_IPSC_2L_MASK BIT(6) +#define MA5311_DAC_EB_IPSC_1U_MASK BIT(5) +#define MA5311_DAC_EB_IPSC_1L_MASK BIT(4) +#define MA5311_DAC_EB_OCP_2B_MASK BIT(3) +#define MA5311_DAC_EB_OCP_2A_MASK BIT(2) +#define MA5311_DAC_EB_OCP_1B_MASK BIT(1) +#define MA5311_DAC_EB_OCP_1A_MASK BIT(0) + +/* 0xEC: DAC SCP status */ +#define MA5311_DAC_EC_SCP_2B_MASK BIT(3) +#define MA5311_DAC_EC_SCP_2A_MASK BIT(2) +#define MA5311_DAC_EC_SCP_1B_MASK BIT(1) +#define MA5311_DAC_EC_SCP_1A_MASK BIT(0) + +/* 0xFB: Clock fault status */ +#define MA5311_DAC_FB_CLOCK_MON_MASK BIT(0) + +/* Factory Default */ +#define MA5311_PLL_POST_N_DEFAULT BIT(3) +#define MA5311_PLL_N_DEFAULT BIT(5) +#define MA5311_PLL_F1_DEFAULT 0 +#define MA5311_PLL_F2_DEFAULT 0 +#define MA5311_PLL_F3_P_CP_DEFAULT BIT(1) + +#define MA5311_LRCK_SCK_MAS_CLK_SEL_MASK BIT(0) +#define MA5311_LRCK_SCK_CLK_MASTER_MODE 1 +#define MA5311_LRCK_SCK_CLK_SLAVE_MODE 0 + +#define MA5311_DAC_CLKSYSTEM_MASK GENMASK(7, 5) +#define MA5311_DAC_EXT_CLK_24_576 BIT(7) +#define MA5311_DAC_INT_OSCILLATOR 0 + +#define MA5311_DAC_TDM_STEREO_MASK BIT(6) +#define MA5311_DAC_TDM_MONO 0 +#define MA5311_DAC_TDM_STEREO BIT(6) + +#define MA5311_DAC_ADC_CLK_ON_MASK BIT(4) +#define MA5311_DAC_ADC_CLK_ON BIT(4) +#define MA5311_DAC_ADC_CLK_OFF 0 + +#define MA5311_DISABLE_TDM_SLOT 0X00 +#define MA5311_ADC_MIX_CH0 0 +#define MA5311_ADC_DATA_PATH_CH0 0 + +#define MA5311_DAC_PLLIN_CLK_MASK BIT(7) +#define MA5311_DAC_PLLIN_EXT_OSC 0 +#define MA5311_DAC_PLLIN_INT_OSC BIT(7) + +#define MA5311_DAC_PLL_REF_CLK1_MASK BIT(4) +#define MA5311_DAC_PLL_REF_EXT_CLK 0 +#define MA5311_DAC_PLL_REF_INT_OSC BIT(4) + +#define MA5311_DAC_PLL_REF_CLK2_MASK BIT(3) +#define MA5311_DAC_PLL_REF_CLK2_REF1 0 +#define MA5311_DAC_PLL_REF_CLK2_SCK BIT(3) + +#endif /* _MA5311_H */ From 1e611c5e2343ea01968671b6dd5215184c3e67e5 Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Fri, 20 Nov 2026 01:43:23 +0100 Subject: [PATCH 2051/2102] ASoC: dt-bindings: add Texas Instruments TAS2557 Document the TAS2557 mono Class-D smart amplifier with an integrated DSP for speaker protection. The device is controlled over I2C and receives audio over I2S/TDM (ASI). One node describes either a single device or, with a two-entry reg, a stereo pair sharing one bus. The device at each reg index applies one half of a stereo-tuned firmware image: index 0 is DEV_A and index 1 is DEV_B. No channel selection property is needed, as for ti,tas2781.yaml. reg is limited to two entries because the firmware format only defines mono or DEV_A/DEV_B devices. reset-gpios and interrupts are per device: the item at array index N configures the device at the Nth reg entry, and a single entry is shared by every device in the group. A pair wired to independent RESET and INT pins uses two entries each. ti,asi-port selects which of the two audio serial interfaces, ASI1 or ASI2, is wired to the host. The DSP boots from a firmware image generated per speaker design with the TI PurePath Console tuning tools. The optional firmware-name property selects a board specific image shared by the whole group. The default names are the mono images, so a pair must set it. Signed-off-by: Gianluca Boiano Link: https://patch.msgid.link/20261120004414.1686884-2-morf3089@gmail.com Signed-off-by: Mark Brown --- .../devicetree/bindings/sound/ti,tas2557.yaml | 158 ++++++++++++++++++ MAINTAINERS | 1 + 2 files changed, 159 insertions(+) create mode 100644 Documentation/devicetree/bindings/sound/ti,tas2557.yaml diff --git a/Documentation/devicetree/bindings/sound/ti,tas2557.yaml b/Documentation/devicetree/bindings/sound/ti,tas2557.yaml new file mode 100644 index 00000000000000..4a7f9065980a03 --- /dev/null +++ b/Documentation/devicetree/bindings/sound/ti,tas2557.yaml @@ -0,0 +1,158 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +# Copyright (C) 2026 Gianluca Boiano +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/sound/ti,tas2557.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Texas Instruments TAS2557 Mono Smart Amplifier + +maintainers: + - Gianluca Boiano + +description: | + The TAS2557 is a mono, digital-input Class-D amplifier with an + integrated DSP for speaker protection, controlled over I2C, with + audio over I2S/TDM (ASI). The DSP runs a firmware image generated for + the speaker with the TI PurePath Console tuning tools. + + One node describes one device or a pair sharing one ASI bus, using + the reg-array convention of ti,tas2781.yaml. The device at reg index 0 + is DEV_A and the one at index 1 is DEV_B; they select the two halves + of a stereo-tuned firmware image. The firmware format defines no + other device types, so a node has at most two devices. + + Datasheet: https://www.ti.com/lit/gpn/tas2557 + +allOf: + - $ref: dai-common.yaml# + +properties: + compatible: + const: ti,tas2557 + + reg: + minItems: 1 + maxItems: 2 + description: + I2C address of each physical device sharing this node. One + entry configures a single mono TAS2557. Two entries configure a + device pair; the device at index 0 is DEV_A and the device at + index 1 is DEV_B. + + '#sound-dai-cells': + const: 0 + + reset-gpios: + minItems: 1 + maxItems: 2 + description: + GPIO connected to the active-low RESET pin of each physical + device sharing this node, one entry per reg entry. A single + entry is shared by every device in the group. + + interrupts: + minItems: 1 + maxItems: 2 + description: + Fault interrupt output (INT) of each physical device sharing + this node, one entry per reg entry. A single entry is shared + by every device in the group. + + vbat-supply: + description: Battery/boost input supply (VBAT), 2.9 V to 5.5 V. + + iovdd-supply: + description: Digital I/O supply, 1.62 V to 3.6 V. + + avdd-supply: + description: Analog supply, 1.65 V to 1.95 V. + + dvdd-supply: + description: Digital core supply, 1.65 V to 1.95 V. + + firmware-name: + maxItems: 1 + description: + Name of the DSP firmware image to load. Defaults to a name + derived from the silicon revision, which is the mono image, so a + device pair must set this property. A device pair shares one + image; each device's half of it is selected by its reg index, + not by this property. + + ti,asi-port: + $ref: /schemas/types.yaml#/definitions/uint32 + enum: [1, 2] + default: 2 + description: + Which audio serial interface (ASI1 or ASI2) of the chip is + wired to the host. Only the selected interface is configured. + +required: + - compatible + - reg + - '#sound-dai-cells' + - vbat-supply + - iovdd-supply + - avdd-supply + - dvdd-supply + +if: + properties: + reg: + minItems: 2 +then: + required: + - firmware-name + +unevaluatedProperties: false + +examples: + - | + #include + #include + + i2c { + #address-cells = <1>; + #size-cells = <0>; + + audio-codec@4c { + compatible = "ti,tas2557"; + reg = <0x4c>; + #sound-dai-cells = <0>; + reset-gpios = <&tlmm 77 GPIO_ACTIVE_LOW>; + interrupt-parent = <&tlmm>; + interrupts = <73 IRQ_TYPE_LEVEL_HIGH>; + + vbat-supply = <&vph_pwr>; + iovdd-supply = <&vreg_l6b_1p8>; + avdd-supply = <&vreg_l6b_1p8>; + dvdd-supply = <&vreg_l6b_1p8>; + }; + }; + - | + #include + #include + + i2c { + #address-cells = <1>; + #size-cells = <0>; + + audio-codec@4c { + compatible = "ti,tas2557"; + reg = <0x4c>, <0x4e>; + #sound-dai-cells = <0>; + reset-gpios = <&tlmm 77 GPIO_ACTIVE_LOW>, + <&tlmm 78 GPIO_ACTIVE_LOW>; + interrupt-parent = <&tlmm>; + interrupts = <73 IRQ_TYPE_LEVEL_HIGH>, <74 IRQ_TYPE_LEVEL_HIGH>; + + vbat-supply = <&vph_pwr>; + iovdd-supply = <&vreg_l6b_1p8>; + avdd-supply = <&vreg_l6b_1p8>; + dvdd-supply = <&vreg_l6b_1p8>; + + firmware-name = "tas2557-stereo.bin"; + }; + }; +... diff --git a/MAINTAINERS b/MAINTAINERS index ccbcdc0799b9fb..eca7cdcb48bc60 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -27717,6 +27717,7 @@ M: Sen Wang L: linux-sound@vger.kernel.org S: Maintained F: Documentation/devicetree/bindings/sound/ti,tas2552.yaml +F: Documentation/devicetree/bindings/sound/ti,tas2557.yaml F: Documentation/devicetree/bindings/sound/ti,tas2562.yaml F: Documentation/devicetree/bindings/sound/ti,tas2770.yaml F: Documentation/devicetree/bindings/sound/ti,tas27xx.yaml From 0d15b67a16523e4c0ffc6ac44a9813d5ae0fc007 Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Fri, 20 Nov 2026 01:43:24 +0100 Subject: [PATCH 2052/2102] ASoC: codecs: add TAS2557 mono smart amplifier driver Add a driver for the Texas Instruments TAS2557 mono Class-D smart amplifier with an integrated DSP. One DT node drives a group of up to two chips that share one firmware image, DAI and mute/power state, like the grouped tas2781 devices. Register access, the paged regmap and the i2c_client address swap used to reach each chip come from tas2781-comlib and tas2781-comlib-i2c. The driver keeps what comlib has no field for: firmware parsing and loading, DSP program and config bookkeeping, ASI slot offsets and the per chip reset and IRQ lines. Secondary I2C addresses are reserved with dummy clients. The firmware file header is the one tas2781-fmwlib parses, but the PLL and config records are not handled there, so the file is parsed in this driver. The header device field uses the TASDEVICE_DSP_TAS_2557_* values. reset-gpios and interrupts take one or two entries, a single entry applying to every chip. All configured reset lines are toggled together and every IRQ line shares one threaded handler that recovers the whole group. An interrupt that is not available yet defers the probe. ti,asi-port (1 or 2, default 2) selects the wired ASI. Only its pin mux, clock dividers and format and offset registers are programmed, and DAPM has a single ASI widget. The ASI1 table also sets GPIO3 to ASI1_DOUT. In a stereo group only chip 0 drives DOUT, the others have the pin disabled. INT1 can be routed to any GPIO; the driver uses GPIO4, the reset default and the ball labelled IRQ. The chip's DSP format at OFFSET1 = 0 is DSP_B, so DSP_A adds one BCLK to OFFSET1. With set_tdm_slot(), an rx_mask with at least two slots and at least as many as chips gives chip n the n-th slot; otherwise all chips use the first slot. Without TDM the offset is 0, plus one BCLK for DSP_A. Only the I2S, DSP and justified formats with the chip as clock consumer and no clock inversion are accepted. The default firmware names are the mono images, so a pair requires firmware-name. The firmware's mono/stereo device type is checked against the number of configured chips before the image is installed; on a mismatch the image is dropped. The PLL index of each config is checked when the image is parsed and an out of range index rejects the image. Firmware configs have fixed sample rates. The DAI startup callback waits for the firmware load, bounded, and restricts the stream to the rates of the current program's configs. hw_params rejects a rate without a config before changing any state. The firmware program, PLL and config are loaded when the firmware arrives and again only after a reset, fault recovery or resume, or when the sample rate needs another config, instead of on every DAPM power-up. Power-up then only runs the startup sequence and restores the cached runtime and mute state. The shutdown sequence mutes and powers down the blocks; it does not reset the chips or make program, coefficient or PLL writes. A rate or word length change while powered is applied immediately. As in the TI driver, I and V sense are powered at startup and muted and unmuted together with the amplifier, since the DSP needs the feedback while it plays; the capture stream is not muted separately. Fault recovery resets the chips once and reuses the common mute restore code. The comlib lock is destroyed by a devm action registered after tasdevice_init(), so it outlives the component, the IRQs and the firmware teardown. SND_SOC_TAS2781_COMLIB is selected together with the I2C helper, which does not pull it in. Signed-off-by: Gianluca Boiano Link: https://patch.msgid.link/20261120004414.1686884-3-morf3089@gmail.com Signed-off-by: Mark Brown --- sound/soc/codecs/Kconfig | 13 + sound/soc/codecs/Makefile | 2 + sound/soc/codecs/tas2557.c | 2973 ++++++++++++++++++++++++++++++++++++ sound/soc/codecs/tas2557.h | 207 +++ 4 files changed, 3195 insertions(+) create mode 100644 sound/soc/codecs/tas2557.c create mode 100644 sound/soc/codecs/tas2557.h diff --git a/sound/soc/codecs/Kconfig b/sound/soc/codecs/Kconfig index ba59dabeeccde5..aa2c7150c18863 100644 --- a/sound/soc/codecs/Kconfig +++ b/sound/soc/codecs/Kconfig @@ -272,6 +272,7 @@ config SND_SOC_ALL_CODECS imply SND_SOC_STI_SAS imply SND_SOC_TAC5XX2_SDW imply SND_SOC_TAS2552 + imply SND_SOC_TAS2557 imply SND_SOC_TAS2562 imply SND_SOC_TAS2764 imply SND_SOC_TAS2770 @@ -2211,6 +2212,18 @@ config SND_SOC_TAS2552 tristate "Texas Instruments TAS2552 Mono Audio amplifier" depends on I2C +config SND_SOC_TAS2557 + tristate "Texas Instruments TAS2557 Mono Smart Amplifier" + depends on I2C + select SND_SOC_TAS2781_COMLIB + select SND_SOC_TAS2781_COMLIB_I2C + help + Enable support for the Texas Instruments TAS2557 mono smart + amplifier with integrated DSP. The on-chip DSP requires firmware + (tas2557_uCDSP.bin) to be present in the firmware search path; + audio cannot pass through the device without it. Uses the + tas2781-comlib(-i2c) helpers for paged register access. + config SND_SOC_TAS2562 tristate "Texas Instruments TAS2562 Mono Audio amplifier" depends on I2C diff --git a/sound/soc/codecs/Makefile b/sound/soc/codecs/Makefile index 3826f9e4fce8a2..304c18c0480a03 100644 --- a/sound/soc/codecs/Makefile +++ b/sound/soc/codecs/Makefile @@ -440,6 +440,7 @@ snd-soc-max98504-y := max98504.o snd-soc-simple-amplifier-y := simple-amplifier.o snd-soc-tpa6130a2-y := tpa6130a2.o snd-soc-tas2552-y := tas2552.o +snd-soc-tas2557-y := tas2557.o snd-soc-tas2562-y := tas2562.o snd-soc-tas2764-y := tas2764.o snd-soc-tas2780-y := tas2780.o @@ -766,6 +767,7 @@ obj-$(CONFIG_SND_SOC_STAC9766) += snd-soc-stac9766.o obj-$(CONFIG_SND_SOC_STI_SAS) += snd-soc-sti-sas.o obj-$(CONFIG_SND_SOC_TAC5XX2_SDW) += snd-soc-tac5xx2-sdw.o obj-$(CONFIG_SND_SOC_TAS2552) += snd-soc-tas2552.o +obj-$(CONFIG_SND_SOC_TAS2557) += snd-soc-tas2557.o obj-$(CONFIG_SND_SOC_TAS2562) += snd-soc-tas2562.o obj-$(CONFIG_SND_SOC_TAS2764) += snd-soc-tas2764.o obj-$(CONFIG_SND_SOC_TAS2780) += snd-soc-tas2780.o diff --git a/sound/soc/codecs/tas2557.c b/sound/soc/codecs/tas2557.c new file mode 100644 index 00000000000000..c49917149c863d --- /dev/null +++ b/sound/soc/codecs/tas2557.c @@ -0,0 +1,2973 @@ +// SPDX-License-Identifier: GPL-2.0-only +// +// ALSA SoC Texas Instruments TAS2557 Smart Amplifier +// +// Copyright (C) 2016 Texas Instruments Inc. +// Copyright (C) 2026 Gianluca Boiano +// +// The TAS2557 requires DSP firmware (tas2557_uCDSP.bin for PG2.x, +// tas2557_pg1p0_uCDSP.bin for PG1.0) to route audio through its internal +// DSP and DAC. Without loaded firmware the device produces no audio. +// +// Probe reads REV_PGID to detect the PG version, then requests firmware +// asynchronously. The firmware program, PLL and config blocks are loaded +// once the firmware arrives and again only when the chips lost them or a +// different config is needed (sample rate change, fault recovery, resume). +// +// Register access, the paged regmap and the i2c_client address swap needed +// to reach several chips through one i2c_client are provided by +// tas2781-comlib(-i2c). One DT node drives up to TAS2557_MAX_DEV chips, +// addressed by channel index into tas_priv->tasdevice[] and +// struct tas2557_priv::devs[]. Firmware, DAI, power and mute state are +// shared by the group; DSP program bookkeeping, ASI slot offsets and the +// reset/IRQ lines are per chip. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tas2557.h" + +/* Special delay markers embedded in register sequence tables */ +#define TAS2557_UDELAY 0xFFFFFFFE +#define TAS2557_MDELAY 0xFFFFFFFD + +/* Supported PCM formats exposed to the ASoC core */ +#define TAS2557_FORMATS \ + (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \ + SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S32_LE) + +/* struct tas2557_block - one block of register-write commands from firmware */ +struct tas2557_block { + u32 type; + u32 num_commands; + u8 *data; /* num_commands * 4 bytes: [book][page][reg][val] */ +}; + +/* struct tas2557_data - named container of firmware blocks */ +struct tas2557_data { + char name[64]; + u32 num_blocks; + struct tas2557_block *blocks; +}; + +/* struct tas2557_pll - one PLL configuration */ +struct tas2557_pll { + char name[64]; + struct tas2557_block block; +}; + +/* struct tas2557_program - one DSP program */ +struct tas2557_program { + char name[64]; + struct tas2557_data data; +}; + +/* struct tas2557_config - one audio configuration (tied to a sample rate) */ +struct tas2557_config { + char name[64]; + u32 program; /* which program this config is for */ + u32 pll; /* which PLL config to use */ + u32 sample_rate; + struct tas2557_data data; +}; + +/* struct tas2557_firmware - top-level parsed firmware container */ +struct tas2557_firmware { + u32 ppc_version; + u32 fw_version; + u32 driver_version; + u32 device; + u32 num_plls; + struct tas2557_pll *plls; + u32 num_programs; + struct tas2557_program *programs; + u32 num_configs; + struct tas2557_config *configs; +}; + +/* + * struct tas2557_dev - per-chip state that comlib's struct tasdevice has + * no field for. One instance per entry in tas_priv->tasdevice[]. + */ +struct tas2557_dev { + /* Hardware revision of this chip */ + int pg_id; + + /* + * DSP program/config currently loaded and recovery-attempt count. + * tas2557_set_program() drives every chip to the same program and + * config, so these stay in lock-step; devs[0] is read back as the + * group's value. + */ + unsigned int current_program; + unsigned int current_config; + unsigned int restart_count; + + /* + * Cached ASI RX (playback) data-slot offset in BCLK cycles for this + * chip, set by set_tdm_slot() and re-applied by + * tas2557_apply_runtime_state(). + */ + unsigned int asi_offset; +}; + +/* + * struct tas2557_priv - group driver state (one node, up to TAS2557_MAX_DEV + * chips), wrapping the shared tas2781-comlib device. + */ +struct tas2557_priv { + struct tasdevice_priv *tas_priv; + + /* Per-device reset lines and fault IRQs (reset-gpios/interrupts) */ + struct gpio_desc *reset[TAS2557_MAX_DEV]; + int irq[TAS2557_MAX_DEV]; + bool irq_enabled; + + /* Which ASI (1 or 2) this board wires up (ti,asi-port, default 2) */ + unsigned int asi_port; + + /* Chip-specific state, one entry per tas_priv->tasdevice[] slot */ + struct tas2557_dev devs[TAS2557_MAX_DEV]; + + /* Power state */ + bool powered; + bool dac_muted; /* mute state for SNDRV_PCM_STREAM_PLAYBACK */ + + /* Firmware state, one image shared by the group */ + struct tas2557_firmware *fw; /* NULL until tas2557_fw_ready() parses it */ + char fw_name[64]; /* filename requested at probe */ + bool fw_requested; /* request_firmware_nowait() was issued */ + struct completion fw_done; /* signalled when tas2557_fw_ready() returns */ + + /* + * devs[].current_program/current_config are still loaded on the + * chips. Cleared by every reset, resume, fw (re)load and failed + * program load; set when tas2557_set_program() completes. + */ + bool prog_valid; + + /* Sample rates of the current program's configs, for DAI startup */ + unsigned int *rates; + struct snd_pcm_hw_constraint_list rate_list; + + /* Runtime audio configuration */ + unsigned int sample_rate; + int dai_fmt; /* ASI format from set_dai_fmt(), -1 = never set */ + unsigned int asi_delay; /* 1 BCLK for DSP_A, 0 otherwise */ + unsigned int wordlength; /* ASI WORDLENGTH_* bits from hw_params */ + + bool tdm_configured; /* true once set_tdm_slot() set an RX slot */ + + /* Volume control */ + unsigned int dac_gain; +}; + +/* + * tas2557_asi_reg() - pick the DAC format or RX offset register of + * whichever ASI (ti,asi-port) this board wires up. The other ASI's + * registers are never written by this driver. + */ +static unsigned int tas2557_asi_reg(struct tas2557_priv *tas2557, + unsigned int asi1_reg, unsigned int asi2_reg) +{ + return tas2557->asi_port == TAS2557_ASI_PORT1 ? asi1_reg : asi2_reg; +} + +/* Forward declarations */ +static void tas2557_hw_reset(struct tas2557_priv *tas2557); +static int tas2557_failsafe_recovery(struct tas2557_priv *tas2557); +static int tas2557_apply_runtime_state(struct tas2557_priv *tas2557); +static int tas2557_power_up_locked(struct tas2557_priv *tas2557, + unsigned int prog_idx); + +/* + * Default device initialization sequence - identical to the TI Android + * driver (p_tas2557_default_data). Written once after every + * hardware/software reset. + */ +static const unsigned int tas2557_default_data[] = { + TAS2557_SAR_ADC2_REG, 0x05, /* enable SAR ADC */ + TAS2557_CLK_ERR_CTRL2, 0x21, /* clk1: hysteresis 0.34 ms */ + TAS2557_CLK_ERR_CTRL3, 0x21, /* clk2: rampDown 15 dB/us */ + TAS2557_SAFE_GUARD_REG, TAS2557_SAFE_GUARD_PATTERN, + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* + * Interrupt output configuration - identical to the TI reference + * (p_tas2557_irq_config). Reloaded after every reset. GPIO4=INT1 + * output is wired the same way regardless of which ASI carries audio, + * so it stays common to both ASI selections. + */ +static const unsigned int tas2557_irq_config[] = { + TAS2557_CLK_HALT_REG, 0x71, /* enable clk-halt detect2 interrupt */ + TAS2557_INT_GEN1_REG, 0x11, /* enable SPK OC and OV */ + TAS2557_INT_GEN2_REG, 0x11, /* enable clk-err1 and die OT */ + TAS2557_INT_GEN3_REG, 0x11, /* enable clk-err2 and brownout */ + TAS2557_INT_GEN4_REG, 0x01, /* disable SAR, enable clk-halt */ + TAS2557_GPIO4_PIN_REG, 0x07, /* GPIO4 = INT1 output */ + TAS2557_INT_MODE_REG, 0x80, /* active-high, held until cleared */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* + * Startup sequence - power up Class-D, Boost, DSP/PLL clocks. Split into + * a common part and one part per ASI: only the ASI selected by + * ti,asi-port is programmed, the other ASI's GPIOx_PIN registers stay at + * reset defaults. The PLL is not configured here; it comes from the + * firmware PLL block loaded by tas2557_set_program(). + */ +static const unsigned int tas2557_startup_common_data[] = { + TAS2557_GPI_PIN_REG, 0x15, /* enable DIN, MCLK, CCI */ + /* Power sequencing: Class-D + Boost first, then DSP/PLL */ + TAS2557_POWER_CTRL2_REG, 0xA0, /* Class-D, Boost power up */ + TAS2557_POWER_CTRL2_REG, 0xA3, /* Class-D, Boost, IV-sense power up */ + TAS2557_POWER_CTRL1_REG, 0xF8, /* PLL, DSP, clock dividers power up */ + TAS2557_UDELAY, 2000, /* 2 ms stabilisation */ + /* CE1_IC = ASI1; TI's ASI2 build writes the same value */ + TAS2557_CLK_ERR_CTRL, 0x2b, /* enable clock error detection */ + TAS2557_DBOOST_CFG_REG, 0x0b, /* reduce full-band noise */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* ASI1 pin wiring: BCLK/WCLK/DOUT on GPIO1/GPIO2/GPIO3 */ +static const unsigned int tas2557_startup_asi1_data[] = { + TAS2557_GPIO1_PIN_REG, 0x01, /* enable BCLK (ASI1) */ + TAS2557_GPIO2_PIN_REG, 0x01, /* enable WCLK (ASI1) */ + TAS2557_GPIO3_PIN_REG, 0x10, /* GPIO3 = ASI1 DOUT */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* + * ASI2 pin wiring (GPIO5-8) and BDIV/WDIV clock dividers; arm the BCLK + * source (GPIO5) before its dividers. + */ +static const unsigned int tas2557_startup_asi2_data[] = { + TAS2557_GPIO6_PIN_REG, 0x01, /* GPIO6 = ASI2 WCLK input */ + TAS2557_GPIO8_PIN_REG, 0x02, /* GPIO8 = ASI2 DIN */ + TAS2557_GPIO5_PIN_REG, 0x01, /* GPIO5 = ASI2 BCLK input */ + TAS2557_ASI2_BDIV_CLK_SEL_REG, 0x01, + TAS2557_ASI2_BDIV_CLK_RATIO_REG, 0x01, + TAS2557_ASI2_BDIV_CLK_RATIO_REG, 0x81, /* power up BDIV */ + TAS2557_ASI2_WDIV_CLK_RATIO_REG, 0x40, + TAS2557_ASI2_WDIV_CLK_RATIO_REG, 0xc0, /* power up WDIV */ + TAS2557_GPIO7_PIN_REG, 0x15, /* GPIO7 = ASI2 DOUT */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* Unmute sequence */ +static const unsigned int tas2557_unmute_data[] = { + TAS2557_MUTE_REG, 0x00, /* unmute I and V sense */ + TAS2557_SOFT_MUTE_REG, 0x00, /* clear soft-mute in DSP */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* Shutdown sequence: device-independent part, run before the ASI part */ +static const unsigned int tas2557_shutdown_common_data[] = { + TAS2557_CLK_ERR_CTRL, 0x00, /* disable clock error detection */ + TAS2557_SOFT_MUTE_REG, 0x01, /* soft mute */ + TAS2557_UDELAY, 10000, /* 10 ms */ + TAS2557_MUTE_REG, 0x03, /* mute I and V sense */ + TAS2557_POWER_CTRL1_REG, 0x60, /* DSP power down */ + TAS2557_UDELAY, 2000, /* 2 ms */ + TAS2557_POWER_CTRL2_REG, 0x00, /* Class-D, Boost power down */ + TAS2557_POWER_CTRL1_REG, 0x00, /* all power down */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* Disable ASI1 GPIOs */ +static const unsigned int tas2557_shutdown_asi1_data[] = { + TAS2557_GPIO1_PIN_REG, 0x00, + TAS2557_GPIO2_PIN_REG, 0x00, + TAS2557_GPIO3_PIN_REG, 0x00, + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* Disable ASI2 GPIOs */ +static const unsigned int tas2557_shutdown_asi2_data[] = { + TAS2557_GPIO5_PIN_REG, 0x00, + TAS2557_GPIO6_PIN_REG, 0x00, + TAS2557_GPIO7_PIN_REG, 0x00, + TAS2557_GPIO8_PIN_REG, 0x00, + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* Disable the shared DIN/MCLK/CCI enable, run after the ASI-specific part */ +static const unsigned int tas2557_shutdown_tail_data[] = { + TAS2557_GPI_PIN_REG, 0x00, + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* + * Book/page/register access + * + * All register I/O goes through tas2781-comlib's tasdevice_dev_*() + * helpers, which drive a paged regmap and swap the i2c_client address to + * reach each chip in the group. Comlib does not lock: every caller holds + * tas_priv->codec_lock, which also protects all driver state. @chn + * indexes tas_priv->tasdevice[]/tas2557->devs[]; @reg is built with + * TASDEVICE_REG(book, page, reg). + */ + +static int tas2557_dev_read(struct tas2557_priv *tas2557, unsigned int chn, + unsigned int reg, unsigned int *value) +{ + return tasdevice_dev_read(tas2557->tas_priv, chn, reg, value); +} + +static int tas2557_dev_write(struct tas2557_priv *tas2557, unsigned int chn, + unsigned int reg, unsigned int value) +{ + return tasdevice_dev_write(tas2557->tas_priv, chn, reg, value); +} + +static int tas2557_dev_update_bits(struct tas2557_priv *tas2557, unsigned int chn, + unsigned int reg, unsigned int mask, + unsigned int value) +{ + return tasdevice_dev_update_bits(tas2557->tas_priv, chn, reg, mask, value); +} + +static int tas2557_dev_bulk_write(struct tas2557_priv *tas2557, unsigned int chn, + unsigned int reg, const u8 *data, size_t len) +{ + /* The chip auto-increments past reg 0x7f into the page register */ + if (TASDEVICE_PAGE_REG(reg) + len > 128) + return -EINVAL; + + return tasdevice_dev_bulk_write(tas2557->tas_priv, chn, reg, + (unsigned char *)data, len); +} + +static int tas2557_load_data(struct tas2557_priv *tas2557, unsigned int chn, + const unsigned int *data) +{ + unsigned int reg, val; + int i = 0, ret = 0; + + while (1) { + reg = data[i * 2]; + val = data[i * 2 + 1]; + + if (reg == 0xFFFFFFFF) + break; + + if (reg == TAS2557_UDELAY) { + usleep_range(val, val + 100); + } else if (reg == TAS2557_MDELAY) { + msleep(val); + } else { + ret = tas2557_dev_write(tas2557, chn, reg, val); + if (ret < 0) + break; + } + i++; + } + + return ret; +} + +/* tas2557_load_data_all - apply a {reg,val} sequence table to every chip */ +static int tas2557_load_data_all(struct tas2557_priv *tas2557, + const unsigned int *data) +{ + unsigned int chn; + int ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_load_data(tas2557, chn, data); + if (ret < 0) + return ret; + } + + return 0; +} + +/* tas2557_write_all - write the same register/value to every chip */ +static int tas2557_write_all(struct tas2557_priv *tas2557, + unsigned int reg, unsigned int value) +{ + unsigned int chn; + int ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_dev_write(tas2557, chn, reg, value); + if (ret < 0) + return ret; + } + + return 0; +} + +/* tas2557_update_bits_all - update_bits the same register/mask/value on every chip */ +static int tas2557_update_bits_all(struct tas2557_priv *tas2557, + unsigned int reg, unsigned int mask, + unsigned int value) +{ + unsigned int chn; + int ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_dev_update_bits(tas2557, chn, reg, mask, value); + if (ret < 0) + return ret; + } + + return 0; +} + +/* + * tas2557_asi_fmt_update_all - update_bits @mask/@value in the DAC (playback) + * format register of the selected ASI on every chip. + */ +static int tas2557_asi_fmt_update_all(struct tas2557_priv *tas2557, + unsigned int mask, unsigned int value) +{ + unsigned int dac = tas2557_asi_reg(tas2557, TAS2557_ASI1_DAC_FORMAT_REG, + TAS2557_ASI2_DAC_FORMAT_REG); + + return tas2557_update_bits_all(tas2557, dac, mask, value); +} + +/* + * tas2557_write_rx_offset - program OFFSET1 of the selected ASI on one chip: + * its TDM slot offset plus the 1 BCLK delay of DSP_A. The chip's DSP + * format at offset 0 is DSP_B. + */ +static int tas2557_write_rx_offset(struct tas2557_priv *tas2557, + unsigned int chn) +{ + unsigned int reg = tas2557_asi_reg(tas2557, TAS2557_ASI1_OFFSET1_REG, + TAS2557_ASI2_OFFSET1_REG); + + return tas2557_dev_write(tas2557, chn, reg, + tas2557->asi_delay + tas2557->devs[chn].asi_offset); +} + +/* + * tas2557_startup_sequence / tas2557_shutdown_sequence - run the common + * part of the power up/down sequence together with the part of the ASI + * selected by ti,asi-port. + * + * The shutdown tables only mute, stop clock error detection, power down + * the DSP/PLL/Class-D blocks and clear the GPIO pin muxes. They do not + * reset the chip or write the DSP program, coefficient or PLL registers, + * so the firmware loaded by tas2557_set_program() survives a shutdown and + * the next power-up only has to re-run the startup sequence. + */ +static int tas2557_startup_sequence(struct tas2557_priv *tas2557) +{ + const unsigned int *asi = tas2557->asi_port == TAS2557_ASI_PORT1 ? + tas2557_startup_asi1_data : + tas2557_startup_asi2_data; + unsigned int dout_reg = tas2557_asi_reg(tas2557, TAS2557_GPIO3_PIN_REG, + TAS2557_GPIO7_PIN_REG); + unsigned int chn; + int ret; + + ret = tas2557_load_data_all(tas2557, tas2557_startup_common_data); + if (ret < 0) + return ret; + + ret = tas2557_load_data_all(tas2557, asi); + if (ret < 0) + return ret; + + /* Only chip 0 drives DOUT of the shared ASI */ + for (chn = 1; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_dev_write(tas2557, chn, dout_reg, 0x00); + if (ret < 0) + return ret; + } + + return 0; +} + +static int tas2557_shutdown_sequence(struct tas2557_priv *tas2557) +{ + const unsigned int *asi = tas2557->asi_port == TAS2557_ASI_PORT1 ? + tas2557_shutdown_asi1_data : + tas2557_shutdown_asi2_data; + int ret; + + ret = tas2557_load_data_all(tas2557, tas2557_shutdown_common_data); + if (ret < 0) + return ret; + + ret = tas2557_load_data_all(tas2557, asi); + if (ret < 0) + return ret; + + return tas2557_load_data_all(tas2557, tas2557_shutdown_tail_data); +} + +/* ========================================================================= + * Firmware parsing + * + * Format (all multi-byte fields are big-endian): + * 4 bytes magic 0x35 0x35 0x35 0x32 ("5552") + * 4 bytes size + * 4 bytes checksum + * 4 bytes ppc_version + * 4 bytes fw_version + * 4 bytes driver_version + * 4 bytes timestamp + * 64 bytes ddc_name (null-padded) + * N bytes description (null-terminated string) + * 4 bytes device_family (must be 0) + * 4 bytes device (2 = mono, 3 = stereo) + * then PLLs, programs, configs + * + * Fields the driver does not use (size, checksum, timestamp, description, + * per-block checksums, ...) are skipped, not stored. + * ========================================================================= + */ + +static void tas2557_fw_free(struct tas2557_firmware *fw) +{ + unsigned int i, j; + + if (!fw) + return; + + if (fw->plls) { + for (i = 0; i < fw->num_plls; i++) + kfree(fw->plls[i].block.data); + kfree(fw->plls); + } + + if (fw->programs) { + for (i = 0; i < fw->num_programs; i++) { + if (fw->programs[i].data.blocks) { + for (j = 0; j < fw->programs[i].data.num_blocks; j++) + kfree(fw->programs[i].data.blocks[j].data); + kfree(fw->programs[i].data.blocks); + } + } + kfree(fw->programs); + } + + if (fw->configs) { + for (i = 0; i < fw->num_configs; i++) { + if (fw->configs[i].data.blocks) { + for (j = 0; j < fw->configs[i].data.num_blocks; j++) + kfree(fw->configs[i].data.blocks[j].data); + kfree(fw->configs[i].data.blocks); + } + } + kfree(fw->configs); + } + + kfree(fw); +} + +static int fw_parse_header(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + const u8 *data, size_t size) +{ + const u8 *start = data; + size_t desc_len; + u32 device_family; + char ddc_name[64]; + + if (size < 104) { + dev_err(tas2557->tas_priv->dev, "firmware header too short (%zu bytes)\n", + size); + return -EINVAL; + } + + /* Magic: four bytes "5552" (0x35 0x35 0x35 0x32) */ + if (data[0] != 0x35 || data[1] != 0x35 || + data[2] != 0x35 || data[3] != 0x32) { + dev_err(tas2557->tas_priv->dev, + "firmware magic mismatch: %02x%02x%02x%02x (expected 35353532)\n", + data[0], data[1], data[2], data[3]); + return -EINVAL; + } + data += 4; + + /* size, checksum: not needed at runtime, skip */ + data += 8; + + fw->ppc_version = get_unaligned_be32(data); data += 4; + fw->fw_version = get_unaligned_be32(data); data += 4; + fw->driver_version = get_unaligned_be32(data); data += 4; + + /* timestamp: not needed at runtime, skip */ + data += 4; + + memcpy(ddc_name, data, 64); + ddc_name[63] = '\0'; + data += 64; + + desc_len = strnlen(data, size - (size_t)(data - start)); + if (desc_len >= size - (size_t)(data - start)) { + dev_err(tas2557->tas_priv->dev, "firmware header: description not NUL-terminated\n"); + return -EINVAL; + } + /* description string: informational only, not stored */ + data += desc_len + 1; + + if ((data - start) + 8 > (ptrdiff_t)size) { + dev_err(tas2557->tas_priv->dev, "firmware header truncated\n"); + return -EINVAL; + } + + device_family = get_unaligned_be32(data); data += 4; + if (device_family != 0) { + dev_err(tas2557->tas_priv->dev, "unsupported device family: %u\n", + device_family); + return -EINVAL; + } + + fw->device = get_unaligned_be32(data); data += 4; + if (fw->device != TASDEVICE_DSP_TAS_2557_MONO && + fw->device != TASDEVICE_DSP_TAS_2557_DUAL_MONO) { + dev_err(tas2557->tas_priv->dev, + "unsupported device %u in firmware (expected 2=mono or 3=stereo)\n", + fw->device); + return -EINVAL; + } + + dev_dbg(tas2557->tas_priv->dev, + "firmware header: DDC=%s fw_ver=0x%x ppc=0x%x drv=0x%x\n", + ddc_name, fw->fw_version, fw->ppc_version, fw->driver_version); + + return data - start; +} + +static int fw_parse_block(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + struct tas2557_block *block, + const u8 *data, size_t remaining) +{ + const u8 *start = data; + size_t data_len; + + if (remaining < 4) + return -EINVAL; + + block->type = get_unaligned_be32(data); + data += 4; + remaining -= 4; + + if (fw->driver_version >= PPC_DRIVER_CRCCHK) { + /* Per-block checksum bytes (pchksum/ychksum): not used, skip */ + if (remaining < 4) + return -EINVAL; + data += 4; + remaining -= 4; + } + + if (remaining < 4) + return -EINVAL; + + block->num_commands = get_unaligned_be32(data); + data += 4; + remaining -= 4; + + /* + * num_commands comes straight from the firmware file; bound it + * against the bytes left before multiplying so the size cannot wrap. + */ + if (block->num_commands > remaining / 4) { + dev_err(tas2557->tas_priv->dev, + "block type 0x%x truncated: %u cmds, %zu bytes left\n", + block->type, block->num_commands, remaining); + return -EINVAL; + } + data_len = (size_t)block->num_commands * 4; + + if (data_len > 0) { + block->data = kmemdup(data, data_len, GFP_KERNEL); + if (!block->data) + return -ENOMEM; + } + data += data_len; + + return data - start; +} + +static int fw_parse_data(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + struct tas2557_data *img_data, + const u8 *data, size_t remaining) +{ + const u8 *start = data; + size_t desc_len; + unsigned int i; + int ret; + + if (remaining < 64) + return -EINVAL; + + memcpy(img_data->name, data, 64); + img_data->name[63] = '\0'; + data += 64; + remaining -= 64; + + desc_len = strnlen(data, remaining); + if (desc_len >= remaining) + return -EINVAL; + /* description string: informational only, not stored */ + data += desc_len + 1; + remaining -= desc_len + 1; + + if (remaining < 2) + return -EINVAL; + + img_data->num_blocks = get_unaligned_be16(data); + data += 2; + remaining -= 2; + + if (img_data->num_blocks == 0) + return data - start; + + img_data->blocks = kcalloc(img_data->num_blocks, + sizeof(struct tas2557_block), GFP_KERNEL); + if (!img_data->blocks) + return -ENOMEM; + + for (i = 0; i < img_data->num_blocks; i++) { + ret = fw_parse_block(tas2557, fw, &img_data->blocks[i], + data, remaining); + if (ret < 0) + return ret; + data += ret; + remaining -= ret; + } + + return data - start; +} + +static int fw_parse_plls(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + const u8 *data, size_t remaining) +{ + const u8 *start = data; + size_t desc_len; + unsigned int i; + int ret; + + if (remaining < 2) + return -EINVAL; + + fw->num_plls = get_unaligned_be16(data); + data += 2; + remaining -= 2; + + if (fw->num_plls == 0) + return data - start; + + fw->plls = kcalloc(fw->num_plls, sizeof(struct tas2557_pll), + GFP_KERNEL); + if (!fw->plls) + return -ENOMEM; + + for (i = 0; i < fw->num_plls; i++) { + if (remaining < 64) + return -EINVAL; + + memcpy(fw->plls[i].name, data, 64); + fw->plls[i].name[63] = '\0'; + data += 64; + remaining -= 64; + + desc_len = strnlen(data, remaining); + if (desc_len >= remaining) + return -EINVAL; + data += desc_len + 1; + remaining -= desc_len + 1; + + ret = fw_parse_block(tas2557, fw, &fw->plls[i].block, + data, remaining); + if (ret < 0) + return ret; + data += ret; + remaining -= ret; + } + + return data - start; +} + +static int fw_parse_programs(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + const u8 *data, size_t remaining) +{ + const u8 *start = data; + size_t desc_len; + unsigned int i; + int ret; + + if (remaining < 2) + return -EINVAL; + + fw->num_programs = get_unaligned_be16(data); + data += 2; + remaining -= 2; + + if (fw->num_programs == 0) { + dev_err(tas2557->tas_priv->dev, "firmware contains no programs\n"); + return -EINVAL; + } + + fw->programs = kcalloc(fw->num_programs, sizeof(struct tas2557_program), + GFP_KERNEL); + if (!fw->programs) + return -ENOMEM; + + for (i = 0; i < fw->num_programs; i++) { + if (remaining < 64) + return -EINVAL; + + memcpy(fw->programs[i].name, data, 64); + fw->programs[i].name[63] = '\0'; + data += 64; + remaining -= 64; + + desc_len = strnlen(data, remaining); + if (desc_len >= remaining) + return -EINVAL; + data += desc_len + 1; + remaining -= desc_len + 1; + + /* app_mode (1 byte) + boost (2 bytes): not used, skip */ + if (remaining < 3) + return -EINVAL; + data += 3; + remaining -= 3; + + ret = fw_parse_data(tas2557, fw, &fw->programs[i].data, + data, remaining); + if (ret < 0) + return ret; + data += ret; + remaining -= ret; + } + + return data - start; +} + +static int fw_parse_configs(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + const u8 *data, size_t remaining) +{ + const u8 *start = data; + size_t desc_len; + unsigned int i; + int ret; + + if (remaining < 2) + return -EINVAL; + + fw->num_configs = get_unaligned_be16(data); + data += 2; + remaining -= 2; + + if (fw->num_configs == 0) { + dev_err(tas2557->tas_priv->dev, "firmware contains no configurations\n"); + return -EINVAL; + } + + fw->configs = kcalloc(fw->num_configs, sizeof(struct tas2557_config), + GFP_KERNEL); + if (!fw->configs) + return -ENOMEM; + + for (i = 0; i < fw->num_configs; i++) { + if (remaining < 64) + return -EINVAL; + + memcpy(fw->configs[i].name, data, 64); + fw->configs[i].name[63] = '\0'; + data += 64; + remaining -= 64; + + desc_len = strnlen(data, remaining); + if (desc_len >= remaining) + return -EINVAL; + data += desc_len + 1; + remaining -= desc_len + 1; + + /* + * Device-count field present from driver_version 0x101. + * Consume it (unused here) across the [0x101, 0x1ff] band + * and for >= 0x300, matching the TI fw_parse_configuration. + */ + if (fw->driver_version >= PPC_DRIVER_CONFDEV || + (fw->driver_version >= PPC_DRIVER_CFGDEV_NONCRC && + fw->driver_version < PPC_DRIVER_CRCCHK)) { + if (remaining < 2) + return -EINVAL; + data += 2; remaining -= 2; + } + + if (remaining < 6) + return -EINVAL; + + fw->configs[i].program = data[0]; data++; remaining--; + fw->configs[i].pll = data[0]; data++; remaining--; + if (fw->configs[i].pll >= fw->num_plls) { + dev_err(tas2557->tas_priv->dev, + "config %u: PLL index %u out of range (%u total)\n", + i, fw->configs[i].pll, fw->num_plls); + return -EINVAL; + } + fw->configs[i].sample_rate = get_unaligned_be32(data); + data += 4; remaining -= 4; + + /* PLL source fields present when driver >= MTPLLSRC: skip */ + if (fw->driver_version >= PPC_DRIVER_MTPLLSRC) { + if (remaining < 5) + return -EINVAL; + data += 5; remaining -= 5; + } + + ret = fw_parse_data(tas2557, fw, &fw->configs[i].data, + data, remaining); + if (ret < 0) + return ret; + data += ret; + remaining -= ret; + } + + return data - start; +} + +static struct tas2557_firmware *fw_parse(struct tas2557_priv *tas2557, + const u8 *data, size_t size) +{ + struct tas2557_firmware *fw; + size_t remaining = size; + int ret; + + fw = kzalloc_obj(*fw, GFP_KERNEL); + if (!fw) + return ERR_PTR(-ENOMEM); + + ret = fw_parse_header(tas2557, fw, data, remaining); + if (ret < 0) + goto err; + data += ret; remaining -= ret; + + ret = fw_parse_plls(tas2557, fw, data, remaining); + if (ret < 0) + goto err; + data += ret; remaining -= ret; + + ret = fw_parse_programs(tas2557, fw, data, remaining); + if (ret < 0) + goto err; + data += ret; remaining -= ret; + + ret = fw_parse_configs(tas2557, fw, data, remaining); + if (ret < 0) + goto err; + + return fw; + +err: + tas2557_fw_free(fw); + return ERR_PTR(ret); +} + +/* ========================================================================= + * Firmware application + * + * Each firmware block contains a sequence of 4-byte commands: + * [book][page][reg][val] - single register write + * [hi][lo][0x81][--] - msleep((hi<<8)|lo) + * [hi][lo][0x85][first] - bulk write: length=(hi<<8)|lo, data follows + * ========================================================================= + */ + +static int tas2557_load_block(struct tas2557_priv *tas2557, + struct tas2557_block *block, unsigned int chn) +{ + const u8 *data = block->data; + unsigned int i; + u8 book, page, offset, value; + u16 sleep_time, bulk_len; + int ret; + + dev_dbg(tas2557->tas_priv->dev, "chn %u: load block type=0x%x cmds=%u\n", + chn, block->type, block->num_commands); + + for (i = 0; i < block->num_commands; ) { + book = data[i * 4]; + page = data[i * 4 + 1]; + offset = data[i * 4 + 2]; + value = data[i * 4 + 3]; + i++; + + if (offset <= 0x7f) { + ret = tas2557_dev_write(tas2557, chn, + TAS2557_REG(book, page, offset), + value); + if (ret < 0) + return ret; + } else if (offset == 0x81) { + sleep_time = ((u16)book << 8) | page; + msleep(sleep_time); + } else if (offset == 0x85) { + bulk_len = ((u16)book << 8) | page; + + if (bulk_len == 0) + return -EINVAL; + + if (i >= block->num_commands) + return -EINVAL; + /* Verify bulk payload stays within block->data */ + if ((size_t)i * 4 + 3 + bulk_len > + (size_t)block->num_commands * 4) + return -EINVAL; + + book = data[i * 4]; + page = data[i * 4 + 1]; + offset = data[i * 4 + 2]; + + if (bulk_len > 1) + ret = tas2557_dev_bulk_write(tas2557, chn, + TAS2557_REG(book, page, offset), + &data[i * 4 + 3], bulk_len); + else + ret = tas2557_dev_write(tas2557, chn, + TAS2557_REG(book, page, offset), + data[i * 4 + 3]); + if (ret < 0) + return ret; + + i++; + if (bulk_len >= 2) + i += (bulk_len - 2) / 4 + 1; + } + } + + return 0; +} + +/* + * tas2557_block_chn_range - which devs[] a firmware block type targets + * + * Mirrors tasdevice_load_block()'s dispatch in tas2781-fmwlib.c: DEV_A/ + * DEV_B blocks target exactly one physical chip (selected by its index in + * the DT `reg` array, see the ti,tas2557.yaml binding), device-independent + * blocks (PGM_ALL, CFG_POST, CFG_POST_POWER) and the PLL block target every + * chip in the group. @chnend is clamped to tas2557->tas_priv->ndev, so a DEV_B block + * becomes an empty range on a single-chip group instead of touching a + * devs[] slot that was never populated. Returns false for a block type + * this driver does not recognise, so the caller does not apply it blindly. + */ +static bool tas2557_block_chn_range(struct tas2557_priv *tas2557, + unsigned int type, + unsigned int *chn, unsigned int *chnend) +{ + switch (type) { + case TAS2557_BLOCK_PGM_DEV_A: + case TAS2557_BLOCK_CFG_COEFF_DEV_A: + case TAS2557_BLOCK_CFG_PRE_DEV_A: + *chn = 0; + *chnend = 1; + break; + case TAS2557_BLOCK_PGM_DEV_B: + case TAS2557_BLOCK_CFG_COEFF_DEV_B: + case TAS2557_BLOCK_CFG_PRE_DEV_B: + *chn = 1; + *chnend = 2; + break; + case TAS2557_BLOCK_PLL: + case TAS2557_BLOCK_PGM_ALL: + case TAS2557_BLOCK_CFG_POST: + case TAS2557_BLOCK_CFG_POST_POWER: + *chn = 0; + *chnend = tas2557->tas_priv->ndev; + break; + default: + return false; + } + + if (*chnend > tas2557->tas_priv->ndev) + *chnend = tas2557->tas_priv->ndev; + + return true; +} + +/* + * tas2557_load_fw_data - apply every block of a data set in storage order, + * each to whichever devs[] its type targets. Used for program->data, + * which only ever contains PGM_ALL/PGM_DEV_A/PGM_DEV_B blocks with no + * ordering constraint between them. + */ +static int tas2557_load_fw_data(struct tas2557_priv *tas2557, + struct tas2557_data *img_data) +{ + unsigned int i, chn, chnend, c; + int ret; + + for (i = 0; i < img_data->num_blocks; i++) { + if (!tas2557_block_chn_range(tas2557, img_data->blocks[i].type, + &chn, &chnend)) + continue; + + for (c = chn; c < chnend; c++) { + ret = tas2557_load_block(tas2557, &img_data->blocks[i], c); + if (ret < 0) + return ret; + } + } + + return 0; +} + +/* + * tas2557_load_fw_data_type - apply only the blocks of a single type, + * in storage order, each to whichever devs[] that type targets. + */ +static int tas2557_load_fw_data_type(struct tas2557_priv *tas2557, + struct tas2557_data *img_data, + unsigned int type) +{ + unsigned int i, chn, chnend, c; + int ret; + + if (!tas2557_block_chn_range(tas2557, type, &chn, &chnend)) + return 0; + + for (i = 0; i < img_data->num_blocks; i++) { + if (img_data->blocks[i].type != type) + continue; + + for (c = chn; c < chnend; c++) { + ret = tas2557_load_block(tas2557, &img_data->blocks[i], c); + if (ret < 0) + return ret; + } + } + + return 0; +} + +/* + * tas2557_load_config_data - apply a configuration's pre-power blocks in the + * order the hardware expects: each chip's pre-coefficient block, then its + * coefficient block (DEV_A before DEV_B), then the device-independent + * CFG_POST block. The CFG_POST_POWER block is NOT applied here; it needs + * active clocks and is loaded by tas2557_load_config_post_power() after the + * device is powered up. Blocks are applied by type, not storage order (per + * TI); tas2557_block_chn_range() decides which chip(s) each type reaches. + */ +static int tas2557_load_config_data(struct tas2557_priv *tas2557, + struct tas2557_data *img_data) +{ + static const unsigned int order[] = { + TAS2557_BLOCK_CFG_PRE_DEV_A, + TAS2557_BLOCK_CFG_COEFF_DEV_A, + TAS2557_BLOCK_CFG_PRE_DEV_B, + TAS2557_BLOCK_CFG_COEFF_DEV_B, + TAS2557_BLOCK_CFG_POST, + }; + unsigned int i; + int ret; + + for (i = 0; i < ARRAY_SIZE(order); i++) { + ret = tas2557_load_fw_data_type(tas2557, img_data, order[i]); + if (ret < 0) + return ret; + } + + return 0; +} + +/* + * tas2557_load_config_post_power - apply the CFG_POST_POWER block of the + * current configuration. These register writes target DSP/clock state that + * only latches once the Class-D/DSP power-up sequence has run, so this is + * called from the power-up path after tas2557_startup_sequence(), not during the + * (powered-down) configuration load. current_config is kept in lock-step + * across every devs[] entry by tas2557_set_program(), so devs[0] is read + * back as the group's representative value. + */ +static int tas2557_load_config_post_power(struct tas2557_priv *tas2557) +{ + struct tas2557_config *config; + + if (!tas2557->fw || tas2557->devs[0].current_config >= tas2557->fw->num_configs) + return 0; + + config = &tas2557->fw->configs[tas2557->devs[0].current_config]; + + return tas2557_load_fw_data_type(tas2557, &config->data, + TAS2557_BLOCK_CFG_POST_POWER); +} + +/* + * tas2557_load_pll - apply a firmware PLL block to every chip in the group. + * PLL configuration is device-independent (each chip clocks itself off the + * same shared reference), so this is loaded on every devs[] entry. + */ +static int tas2557_load_pll(struct tas2557_priv *tas2557, unsigned int pll_idx) +{ + unsigned int chn; + int ret; + + if (!tas2557->fw || pll_idx >= tas2557->fw->num_plls) + return -EINVAL; + + dev_dbg(tas2557->tas_priv->dev, "loading PLL[%u]: %s\n", + pll_idx, tas2557->fw->plls[pll_idx].name); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_load_block(tas2557, + &tas2557->fw->plls[pll_idx].block, chn); + if (ret < 0) + return ret; + } + + return 0; +} + +/* + * tas2557_find_config - first config of @prog_idx for @rate (0 = any rate), + * or -EINVAL if the firmware has none. + */ +static int tas2557_find_config(const struct tas2557_firmware *fw, + unsigned int prog_idx, unsigned int rate) +{ + unsigned int i; + + for (i = 0; i < fw->num_configs; i++) { + if (fw->configs[i].program != prog_idx) + continue; + if (rate == 0 || rate == fw->configs[i].sample_rate) + return i; + } + + return -EINVAL; +} + +/* + * tas2557_set_program - reset the device group and load a firmware program + * and config + * + * Hardware reset, software reset, default registers and IRQ config on every + * chip, then the program blocks, the config's PLL block and the config + * blocks. The PLL is configured only by the firmware PLL block. The group + * is not powered up: callers run the startup sequence afterwards. A + * powered group must be shut down by the caller first. + * + * Caller must hold tas_priv->codec_lock. + * + * @config_idx: -1 to select the config for the current sample_rate; while + * that is still 0, the first config of the program + */ +static int tas2557_set_program(struct tas2557_priv *tas2557, + unsigned int prog_idx, int config_idx) +{ + struct tas2557_firmware *fw = tas2557->fw; + struct tas2557_program *program; + struct tas2557_config *config; + unsigned int chn; + int ret; + + lockdep_assert_held(&tas2557->tas_priv->codec_lock); + + if (!fw || !fw->programs || !fw->configs) { + dev_err(tas2557->tas_priv->dev, "firmware not loaded, cannot set program\n"); + return -EINVAL; + } + + if (prog_idx >= fw->num_programs) { + dev_err(tas2557->tas_priv->dev, "program %u out of range (%u total)\n", + prog_idx, fw->num_programs); + return -EINVAL; + } + + if (config_idx < 0) { + config_idx = tas2557_find_config(fw, prog_idx, tas2557->sample_rate); + if (config_idx < 0) { + dev_err(tas2557->tas_priv->dev, + "no config for program %u at %u Hz\n", + prog_idx, tas2557->sample_rate); + return -EINVAL; + } + } + + if ((unsigned int)config_idx >= fw->num_configs) { + dev_err(tas2557->tas_priv->dev, "config %d out of range (%u total)\n", + config_idx, fw->num_configs); + return -EINVAL; + } + + config = &fw->configs[config_idx]; + if (config->program != prog_idx) { + dev_err(tas2557->tas_priv->dev, + "config %u belongs to program %u, not %u\n", + config_idx, config->program, prog_idx); + return -EINVAL; + } + + program = &fw->programs[prog_idx]; + + /* Hard + soft reset (every chip), then baseline register setup */ + tas2557_hw_reset(tas2557); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_dev_write(tas2557, chn, TAS2557_SW_RESET_REG, 0x01); + if (ret < 0) + return ret; + } + usleep_range(1000, 2000); + + ret = tas2557_load_data_all(tas2557, tas2557_default_data); + if (ret < 0) + return ret; + + /* Restore IRQ configuration lost by the reset */ + ret = tas2557_load_data_all(tas2557, tas2557_irq_config); + if (ret < 0) + dev_warn(tas2557->tas_priv->dev, "IRQ config reload failed: %d\n", ret); + + /* + * Load DSP program blocks. Which chip(s) each block targets is + * decided purely by the block's own type (PGM_ALL/PGM_DEV_A/ + * PGM_DEV_B) via tas2557_block_chn_range(); DEV_A/DEV_B tuning maps + * onto devs[0]/devs[1], i.e. onto the chip order of the DT `reg` + * array, not any runtime TDM slot selection. + */ + dev_dbg(tas2557->tas_priv->dev, "loading program %u (%s)\n", + prog_idx, program->name); + ret = tas2557_load_fw_data(tas2557, &program->data); + if (ret < 0) + return ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->devs[chn].current_program = prog_idx; + + /* Load the PLL configuration of this config (index checked at parse) */ + ret = tas2557_load_pll(tas2557, config->pll); + if (ret < 0) + return ret; + + /* Load config blocks (coefficients, sample-rate-specific settings) */ + dev_dbg(tas2557->tas_priv->dev, + "loading config %u (%s) rate=%u Hz PLL[%u]\n", + config_idx, config->name, config->sample_rate, config->pll); + ret = tas2557_load_config_data(tas2557, &config->data); + if (ret < 0) + return ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->devs[chn].current_config = config_idx; + + tas2557->prog_valid = true; + + return 0; +} + +static const char *tas2557_pg_name(int pg_id) +{ + switch (pg_id) { + case TAS2557_PG_VERSION_1P0: + return "PG1.0"; + case TAS2557_PG_VERSION_2P0: + return "PG2.0"; + case TAS2557_PG_VERSION_2P1: + return "PG2.1"; + default: + return "PG?"; + } +} + +/* + * tas2557_build_rate_list - collect the distinct sample rates of the + * current program's configs for the DAI rate constraint. Caller holds + * tas_priv->codec_lock. + */ +static int tas2557_build_rate_list(struct tas2557_priv *tas2557) +{ + const struct tas2557_firmware *fw = tas2557->fw; + unsigned int prog_idx = tas2557->devs[0].current_program; + unsigned int *rates, num = 0, i, j; + + rates = kmalloc_array(fw->num_configs, sizeof(*rates), GFP_KERNEL); + if (!rates) + return -ENOMEM; + + for (i = 0; i < fw->num_configs; i++) { + unsigned int rate = fw->configs[i].sample_rate; + + if (fw->configs[i].program != prog_idx || !rate) + continue; + + for (j = 0; j < num; j++) + if (rates[j] == rate) + break; + if (j == num) + rates[num++] = rate; + } + + kfree(tas2557->rates); + tas2557->rates = rates; + tas2557->rate_list.list = rates; + tas2557->rate_list.count = num; + + return 0; +} + +/* + * tas2557_fw_ready - firmware load callback + * + * Called from request_firmware_nowait(). Parses the firmware and, if it + * matches the configured chip count, installs it, builds the rate list and + * loads program 0 so the DSP is ready for the first power-up. Every path + * reaches the completion at the end, so tas2557_fw_teardown() and DAPM can + * always wait for this callback to finish. + */ +static void tas2557_fw_ready(const struct firmware *fw_entry, void *context) +{ + struct tas2557_priv *tas2557 = context; + struct tas2557_firmware *fw = NULL; + int ret; + + if (!fw_entry || !fw_entry->data || fw_entry->size == 0) { + /* + * Firmware is required: without it the DSP cannot route + * audio and the Class-D stage stays muted. + */ + dev_err(tas2557->tas_priv->dev, + "firmware '%s' not found, the amplifier cannot work without it\n", + tas2557->fw_name); + release_firmware(fw_entry); + goto done; + } + + dev_dbg(tas2557->tas_priv->dev, "firmware received, size=%zu\n", fw_entry->size); + + fw = fw_parse(tas2557, fw_entry->data, fw_entry->size); + release_firmware(fw_entry); + + if (IS_ERR(fw)) { + dev_err(tas2557->tas_priv->dev, + "firmware '%s' parse error %ld, it may be corrupt\n", + tas2557->fw_name, PTR_ERR(fw)); + fw = NULL; + goto done; + } + + /* + * The firmware's device field is the number of chips it was built + * for; a mismatch with the DT group size means the wrong file. + */ + if ((fw->device == TASDEVICE_DSP_TAS_2557_MONO && + tas2557->tas_priv->ndev != 1) || + (fw->device == TASDEVICE_DSP_TAS_2557_DUAL_MONO && + tas2557->tas_priv->ndev != 2)) { + dev_err(tas2557->tas_priv->dev, + "firmware '%s' is for %s but %u chip(s) are configured\n", + tas2557->fw_name, + fw->device == TASDEVICE_DSP_TAS_2557_MONO ? "mono" : "stereo", + tas2557->tas_priv->ndev); + tas2557_fw_free(fw); + goto done; + } + + mutex_lock(&tas2557->tas_priv->codec_lock); + + tas2557_fw_free(tas2557->fw); + tas2557->fw = fw; + tas2557->prog_valid = false; + + if (tas2557_build_rate_list(tas2557) < 0) + dev_warn(tas2557->tas_priv->dev, + "no memory for the rate list, rates are not constrained\n"); + + ret = tas2557_set_program(tas2557, 0, -1); + if (ret < 0) + dev_err(tas2557->tas_priv->dev, "initial program load failed: %d\n", ret); + else + dev_info(tas2557->tas_priv->dev, + "%s ready: fw '%s' ver=0x%x drv=0x%x (%u prog, %u cfg)\n", + tas2557_pg_name(tas2557->devs[0].pg_id), tas2557->fw_name, + fw->fw_version, fw->driver_version, + fw->num_programs, fw->num_configs); + + mutex_unlock(&tas2557->tas_priv->codec_lock); + +done: + complete_all(&tas2557->fw_done); +} + +/* + * tas2557_fw_teardown - release firmware resources on driver teardown + * + * Waits for a pending tas2557_fw_ready() callback (if a request is still + * in flight) before freeing the parsed firmware, closing the + * use-after-free window where the firmware core could still be about to + * invoke tas2557_fw_ready() while the device is being unbound. See the + * comment above its devm_add_action_or_reset() registration in + * tas2557_i2c_probe() for why this ordering is safe. + */ +static void tas2557_fw_teardown(void *data) +{ + struct tas2557_priv *tas2557 = data; + + if (tas2557->fw_requested) + wait_for_completion(&tas2557->fw_done); + + mutex_lock(&tas2557->tas_priv->codec_lock); + tas2557_fw_free(tas2557->fw); + tas2557->fw = NULL; + kfree(tas2557->rates); + tas2557->rates = NULL; + mutex_unlock(&tas2557->tas_priv->codec_lock); +} + +/* + * tas2557_hw_reset - assert and release every configured reset line + * together. A lone reset-gpios entry is replicated into every slot by + * tas2557_parse_dt(). Invalidates the loaded program and comlib's cached + * book numbers; without a reset GPIO only that bookkeeping is done. + */ +static void tas2557_hw_reset(struct tas2557_priv *tas2557) +{ + unsigned int chn; + bool have_reset = false; + + tas2557->prog_valid = false; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + if (tas2557->reset[chn]) { + have_reset = true; + /* Assert reset (active-low: logical 1 = reset asserted) */ + gpiod_set_value_cansleep(tas2557->reset[chn], 1); + } + } + + if (have_reset) { + usleep_range(5000, 6000); + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + if (tas2557->reset[chn]) + gpiod_set_value_cansleep(tas2557->reset[chn], 0); + usleep_range(10000, 11000); + } + + /* The reset clears the selected book; force comlib to reselect it */ + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->tas_priv->tasdevice[chn].cur_book = -1; +} + +/* + * tas2557_irq_arm()/tas2557_irq_disarm() - enable/disable every configured + * fault IRQ from the power path (interrupts, minItems 1 maxItems 2, + * one entry may apply to every chip; every distinct line is armed and + * disarmed once, together, since the whole group is powered up/down together). + * Called with tas_priv->codec_lock NOT held: enable_irq()/disable_irq() must not + * run while the threaded handler could be blocked waiting for + * tas_priv->codec_lock, or a self-deadlock results (disable_irq() waits for the + * handler thread to finish, which is waiting on the lock the caller is + * holding). + */ +static void tas2557_irq_arm(struct tas2557_priv *tas2557) +{ + unsigned int chn; + + if (tas2557->irq_enabled) + return; + tas2557->irq_enabled = true; + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + if (chn > 0 && tas2557->irq[chn] == tas2557->irq[chn - 1]) + continue; + if (tas2557->irq[chn] > 0) + enable_irq(tas2557->irq[chn]); + } +} + +static void tas2557_irq_disarm(struct tas2557_priv *tas2557) +{ + unsigned int chn; + + if (!tas2557->irq_enabled) + return; + tas2557->irq_enabled = false; + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + if (chn > 0 && tas2557->irq[chn] == tas2557->irq[chn - 1]) + continue; + if (tas2557->irq[chn] > 0) + disable_irq(tas2557->irq[chn]); + } +} + +/* + * tas2557_irq_handler - threaded fault IRQ handler + * + * GPIO4 is programmed as the INT1 output (see tas2557_irq_config) on every + * chip; every configured host IRQ line shares this same handler with + * dev_id = tas2557, so a fault on any chip's INT line diagnoses and + * recovers the whole group the same way. FLAGS_1/FLAGS_2/POWER_UP_FLAG + * are read back from each chip in turn: any single chip reporting a fault + * triggers failsafe recovery for the whole group. + */ +static irqreturn_t tas2557_irq_handler(int irq, void *data) +{ + struct tas2557_priv *tas2557 = data; + unsigned int chn; + bool fault = false; + int ret = 0; + + mutex_lock(&tas2557->tas_priv->codec_lock); + + if (!tas2557->fw || !tas2557->powered) { + mutex_unlock(&tas2557->tas_priv->codec_lock); + return IRQ_NONE; + } + + /* Gate the chips' INT output while diagnosing the fault */ + tas2557_write_all(tas2557, TAS2557_GPIO4_PIN_REG, 0x00); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + unsigned int int1 = 0, int2 = 0, pwr_flag = 0; + + ret = tas2557_dev_read(tas2557, chn, TAS2557_FLAGS_1, &int1); + if (ret >= 0) + ret = tas2557_dev_read(tas2557, chn, TAS2557_FLAGS_2, &int2); + + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "IRQ: chn %u failed to read FLAGS\n", chn); + fault = true; + break; + } + + if ((int1 & 0xfc) || (int2 & 0x0c)) { + /* + * Clock faults while muted are expected: the host is + * allowed to stop the I2S clocks around stream stop + * while the amplifier is still powered. Nothing to + * recover from. + */ + if (tas2557->dac_muted && !(int1 & 0xd8)) { + dev_dbg(tas2557->tas_priv->dev, + "IRQ: chn %u clock stop while muted (FLAGS_1=0x%02x FLAGS_2=0x%02x)\n", + chn, int1, int2); + continue; + } + dev_err(tas2557->tas_priv->dev, "IRQ: chn %u FLAGS_1=0x%02x FLAGS_2=0x%02x\n", + chn, int1, int2); + fault = true; + break; + } + + if (!tas2557->dac_muted) { + ret = tas2557_dev_read(tas2557, chn, TAS2557_POWER_UP_FLAG_REG, + &pwr_flag); + if (ret < 0) { + fault = true; + break; + } + + if ((pwr_flag & 0xc0) != 0xc0) { + dev_err(tas2557->tas_priv->dev, "IRQ: chn %u power-up flag=0x%02x\n", + chn, pwr_flag); + fault = true; + break; + } + } + } + + if (!fault) { + /* No fault (or expected clock stop): re-enable the INT output */ + tas2557_write_all(tas2557, TAS2557_GPIO4_PIN_REG, 0x07); + mutex_unlock(&tas2557->tas_priv->codec_lock); + return IRQ_HANDLED; + } + + if (tas2557_failsafe_recovery(tas2557) == 0) + tas2557_write_all(tas2557, TAS2557_GPIO4_PIN_REG, 0x07); + + mutex_unlock(&tas2557->tas_priv->codec_lock); + return IRQ_HANDLED; +} + +/* + * tas2557_clk_err_detect - gate the chips' clock error/halt detection + * + * The host is allowed to stop the I2S clocks whenever no audio is + * playing (amplifier muted), so detection is armed only between unmute + * and mute; otherwise a normal stream stop looks like a clock-halt + * fault. This matches the TI reference sequences, which disable + * detection as the first step of the shutdown sequence. + */ +static int tas2557_clk_err_detect(struct tas2557_priv *tas2557, bool enable) +{ + return tas2557_write_all(tas2557, TAS2557_CLK_ERR_CTRL, + enable ? 0x2b : 0x00); +} + +/* + * tas2557_apply_mute_state - program the cached mute state into a freshly + * powered group. + * + * With the DAC unmuted, unmute (I/V sense are unmuted with it, as the DSP + * needs the IV feedback while the amplifier plays) and arm clock error + * detection. With the DAC muted the host may not be clocking the bus, so + * keep detection off. tas2557_mute_stream() arms detection when the DAC + * is unmuted later. + */ +static int tas2557_apply_mute_state(struct tas2557_priv *tas2557) +{ + int ret; + + if (!tas2557->dac_muted) { + ret = tas2557_load_data_all(tas2557, tas2557_unmute_data); + if (ret >= 0) + ret = tas2557_clk_err_detect(tas2557, true); + } else { + ret = tas2557_clk_err_detect(tas2557, false); + } + + return ret; +} + +/* + * tas2557_failsafe_recovery - re-initialise the device group after a fault IRQ + * + * Caller must hold tas_priv->codec_lock (called from tas2557_irq_handler()). + * Capped at 5 attempts so a permanently faulty amplifier does not spin + * the IRQ thread forever; the group is recovered together, so restart_count + * is incremented on every chip and devs[0] is read back. + */ +static int tas2557_failsafe_recovery(struct tas2557_priv *tas2557) +{ + unsigned int chn; + int ret; + + lockdep_assert_held(&tas2557->tas_priv->codec_lock); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->devs[chn].restart_count++; + + dev_info(tas2557->tas_priv->dev, "failsafe recovery attempt %u\n", + tas2557->devs[0].restart_count); + + if (tas2557->devs[0].restart_count > 5) { + dev_err(tas2557->tas_priv->dev, "too many recovery attempts, giving up\n"); + /* The handler zeroed INT1 routing; force a reload at next power-up */ + tas2557->prog_valid = false; + return -EIO; + } + + /* + * tas2557_set_program() does the hardware reset, the software + * reset and the defaults/IRQ config reload. The faulted chips are + * reset directly, without a graceful shutdown. + */ + ret = tas2557_set_program(tas2557, tas2557->devs[0].current_program, + (int)tas2557->devs[0].current_config); + if (ret < 0) + return ret; + + if (tas2557->powered) { + ret = tas2557_startup_sequence(tas2557); + if (ret < 0) + return ret; + + ret = tas2557_apply_runtime_state(tas2557); + if (ret < 0) + return ret; + + ret = tas2557_load_config_post_power(tas2557); + if (ret < 0) + return ret; + + ret = tas2557_apply_mute_state(tas2557); + if (ret < 0) + return ret; + } + + dev_info(tas2557->tas_priv->dev, "failsafe recovery succeeded\n"); + return 0; +} + +static void tas2557_check_pll_lock(struct tas2557_priv *tas2557) +{ + unsigned int chn; + + /* + * The PLL needs a few ms to lock after the I2S bit clock starts + * flowing. Poll POWER_UP_FLAG rather than sampling it once, so we + * don't emit a spurious "not locked" warning during clock ramp-up. + */ + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + unsigned int flag = 0, f1 = 0, f2 = 0; + int i; + + for (i = 0; i < 20; i++) { + tas2557_dev_read(tas2557, chn, TAS2557_POWER_UP_FLAG_REG, &flag); + if ((flag & 0xc0) == 0xc0) + break; + usleep_range(2000, 2500); + } + + tas2557_dev_read(tas2557, chn, TAS2557_FLAGS_1, &f1); + tas2557_dev_read(tas2557, chn, TAS2557_FLAGS_2, &f2); + + if ((flag & 0xc0) == 0xc0) + dev_dbg(tas2557->tas_priv->dev, + "chn %u: PLL locked, power-up OK (FLAG=0x%02x F1=0x%02x F2=0x%02x)\n", + chn, flag, f1, f2); + else + dev_warn(tas2557->tas_priv->dev, + "chn %u: PLL or clock may not have locked (FLAG=0x%02x F1=0x%02x F2=0x%02x)\n", + chn, flag, f1, f2); + + if (f1 & 0x04) + dev_warn(tas2557->tas_priv->dev, "chn %u: clock error detected (FLAGS_1=0x%02x)\n", + chn, f1); + } +} + +/* + * Power-up sequence, see tas2557_power_up_locked(): + * 1. tas2557_set_program() - only if the chips no longer hold the needed + * program/config: reset, defaults, IRQ config, firmware program, PLL + * and config blocks + * 2. tas2557_startup_sequence() - GPIO clocks, Class-D, Boost, DSP + * 3. DAC gain, ASI word length/format and slot offset + * 4. CFG_POST_POWER firmware block + * 5. Cached mute state + * 6. POWER_UP_FLAG/FLAGS check for PLL lock and clock errors + * + * tas2557_hw_params() runs it again while powered for a live sample rate + * change, which always reloads the program and config. + */ + +/* + * tas2557_apply_runtime_state - program the cached ALSA/DAI state: DAC + * gain, ASI word length/format and the RX data-slot offset of the ASI + * selected by ti,asi-port. Run after every startup sequence and after a + * reset. Caller holds tas_priv->codec_lock. + */ +static int tas2557_apply_runtime_state(struct tas2557_priv *tas2557) +{ + unsigned int chn; + int ret; + + lockdep_assert_held(&tas2557->tas_priv->codec_lock); + + ret = tas2557_update_bits_all(tas2557, TAS2557_SPK_CTRL_REG, + TAS2557_DAC_GAIN_MASK, + tas2557->dac_gain << TAS2557_DAC_GAIN_SHIFT); + if (ret < 0) + return ret; + + /* Word length is always valid (seeded at probe); format only if set */ + ret = tas2557_asi_fmt_update_all(tas2557, TAS2557_WORDLENGTH_MASK, + tas2557->wordlength); + if (ret < 0) + return ret; + + if (tas2557->dai_fmt >= 0) { + ret = tas2557_asi_fmt_update_all(tas2557, TAS2557_FORMAT_MASK, + tas2557->dai_fmt); + if (ret < 0) + return ret; + } + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_write_rx_offset(tas2557, chn); + if (ret < 0) + return ret; + } + + return 0; +} + +/* + * tas2557_power_up_locked - power up the amplifier group with @prog_idx at + * the current tas2557->sample_rate, loading the program and config first + * when the chips do not hold them. + * + * The program is reloaded if the loaded state was invalidated, a different + * config is needed for the rate, or the group is already powered (live rate + * change from hw_params(); it is shut down first). + * + * Caller must hold tas_priv->codec_lock and must have already verified that + * firmware is loaded. + */ +static int tas2557_power_up_locked(struct tas2557_priv *tas2557, + unsigned int prog_idx) +{ + int cfg_idx, ret; + + lockdep_assert_held(&tas2557->tas_priv->codec_lock); + + cfg_idx = tas2557_find_config(tas2557->fw, prog_idx, tas2557->sample_rate); + if (cfg_idx < 0) { + dev_err(tas2557->tas_priv->dev, "no config for program %u at %u Hz\n", + prog_idx, tas2557->sample_rate); + return cfg_idx; + } + + if (tas2557->powered || !tas2557->prog_valid || + tas2557->devs[0].current_program != prog_idx || + tas2557->devs[0].current_config != cfg_idx) { + if (tas2557->powered) { + ret = tas2557_shutdown_sequence(tas2557); + if (ret < 0) + return ret; + /* Callers set powered again on success */ + tas2557->powered = false; + tas2557->dac_muted = true; + } + + ret = tas2557_set_program(tas2557, prog_idx, cfg_idx); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, + "firmware program load failed on power-up: %d\n", + ret); + return ret; + } + } + + /* Power up Class-D + Boost + selected-ASI clocks on every chip */ + ret = tas2557_startup_sequence(tas2557); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "startup sequence failed: %d\n", + ret); + goto err_shutdown; + } + + ret = tas2557_apply_runtime_state(tas2557); + if (ret < 0) + goto err_shutdown; + + /* DSP post-power coefficients need active clocks to latch */ + ret = tas2557_load_config_post_power(tas2557); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, + "post-power config load failed: %d\n", ret); + goto err_shutdown; + } + + /* + * On DPCM systems mute_stream(0) for a back-end DAI can run before + * the DAPM widgets power up, so the unmute may already be recorded + * while the device is still off. + */ + ret = tas2557_apply_mute_state(tas2557); + if (ret < 0) + goto err_shutdown; + + /* Verify PLL lock and clock health on every chip */ + tas2557_check_pll_lock(tas2557); + + return 0; + +err_shutdown: + /* Do not leave the chips powered while powered == false */ + tas2557_shutdown_sequence(tas2557); + tas2557->powered = false; + tas2557->dac_muted = true; + return ret; +} + +/* + * tas2557_enable - power the amplifier group up or down + * + * Caller must hold tas_priv->codec_lock. Does not touch the fault IRQ or the + * mute state; see tas2557_classd_event() and tas2557_mute_stream(). + */ +static int tas2557_enable(struct tas2557_priv *tas2557, bool enable) +{ + unsigned int chn; + int ret = 0; + + lockdep_assert_held(&tas2557->tas_priv->codec_lock); + + if (enable && !tas2557->powered) { + if (!tas2557->fw) { + dev_warn(tas2557->tas_priv->dev, + "firmware not loaded, cannot produce audio; install %s\n", + tas2557->fw_name[0] ? tas2557->fw_name + : TAS2557_FW_NAME); + return -ENODEV; + } + + ret = tas2557_power_up_locked(tas2557, tas2557->devs[0].current_program); + if (ret < 0) + return ret; + + tas2557->powered = true; + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->devs[chn].restart_count = 0; + + dev_dbg(tas2557->tas_priv->dev, "amplifier group powered on (prog=%u cfg=%u)\n", + tas2557->devs[0].current_program, tas2557->devs[0].current_config); + + } else if (!enable && tas2557->powered) { + ret = tas2557_shutdown_sequence(tas2557); + if (ret < 0) + dev_err(tas2557->tas_priv->dev, "shutdown failed: %d\n", ret); + + tas2557->powered = false; + tas2557->dac_muted = true; + + dev_dbg(tas2557->tas_priv->dev, "amplifier group powered off\n"); + } + + return ret; +} + +/* ========================================================================= + * ASoC DAI operations + * ========================================================================= + */ + +/* + * tas2557_wait_fw - wait, bounded, for the asynchronous firmware load to + * finish. Must be called without tas_priv->codec_lock held: + * tas2557_fw_ready() takes it before it completes fw_done. + */ +static void tas2557_wait_fw(struct tas2557_priv *tas2557) +{ + if (tas2557->fw_requested && + !wait_for_completion_timeout(&tas2557->fw_done, + msecs_to_jiffies(5000))) + dev_warn(tas2557->tas_priv->dev, "firmware load timed out\n"); +} + +/* + * The firmware configs have fixed sample rates, so once the firmware is + * loaded restrict the stream to the rates of the current program. Without + * firmware the stream opens unconstrained and power-up reports the error. + */ +static int tas2557_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(dai->component); + + tas2557_wait_fw(tas2557); + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + if (!tas2557->fw || !tas2557->rate_list.count) + return 0; + + return snd_pcm_hw_constraint_list(substream->runtime, 0, + SNDRV_PCM_HW_PARAM_RATE, + &tas2557->rate_list); +} + +static int tas2557_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + struct snd_soc_component *component = dai->component; + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + unsigned int rate = params_rate(params); + unsigned int chn, wordlength; + bool rate_changed, fmt_changed, live, remute; + int ret; + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + dev_dbg(tas2557->tas_priv->dev, "hw_params: rate=%u width=%d\n", + rate, params_physical_width(params)); + + /* + * Firmware configs have fixed sample rates. Reject a rate the + * program has no config for before changing any state; without + * firmware the check is left to power-up. + */ + if (tas2557->fw && + tas2557_find_config(tas2557->fw, tas2557->devs[0].current_program, + rate) < 0) { + dev_err(tas2557->tas_priv->dev, + "no firmware config for program %u at %u Hz\n", + tas2557->devs[0].current_program, rate); + return -EINVAL; + } + + /* Validate the ASI word length before committing any cached state */ + switch (params_width(params)) { + case 16: + wordlength = TAS2557_WORDLENGTH_16BIT; + break; + case 20: + wordlength = TAS2557_WORDLENGTH_20BIT; + break; + case 24: + wordlength = TAS2557_WORDLENGTH_24BIT; + break; + case 32: + wordlength = TAS2557_WORDLENGTH_32BIT; + break; + default: + dev_err(tas2557->tas_priv->dev, "unsupported sample width %d\n", + params_width(params)); + return -EINVAL; + } + + /* + * Without set_tdm_slot() the slot offset is 0 for every chip (the + * DSP_A BCLK is added when it is written); an explicit + * set_tdm_slot() takes precedence and leaves asi_offset alone. + */ + if (!tas2557->tdm_configured) { + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->devs[chn].asi_offset = 0; + } + + /* A lost program (failed reload, recovery give-up) forces a reload too */ + rate_changed = tas2557->powered && + (rate != tas2557->sample_rate || !tas2557->prog_valid); + fmt_changed = tas2557->powered && wordlength != tas2557->wordlength; + live = rate_changed || fmt_changed; + + /* + * If the group is powered and the rate or word length changed, apply + * it now instead of at the next power-up. A rate change needs the + * new config's PLL block and goes through tas2557_power_up_locked(); + * a word-length change is written to the format registers under + * mute. + */ + remute = live && fmt_changed && !rate_changed && !tas2557->dac_muted; + if (remute) { + ret = tas2557_update_bits_all(tas2557, TAS2557_SOFT_MUTE_REG, + TAS2557_PDM_SOFT_MUTE, + TAS2557_PDM_SOFT_MUTE); + if (ret >= 0) { + usleep_range(10000, 11000); + ret = tas2557_write_all(tas2557, TAS2557_MUTE_REG, + TAS2557_MUTE_ISNS | + TAS2557_MUTE_VSNS); + } + if (ret < 0) + return ret; + } + + /* Program the selected ASI's data-slot offset on every chip */ + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_write_rx_offset(tas2557, chn); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "chn %u: ASI offset write failed: %d\n", + chn, ret); + return ret; + } + } + + if (live && fmt_changed && !rate_changed) { + ret = tas2557_asi_fmt_update_all(tas2557, TAS2557_WORDLENGTH_MASK, + wordlength); + if (ret < 0) + return ret; + } + + /* Commit cached stream state now the hardware writes have succeeded */ + tas2557->sample_rate = rate; + tas2557->wordlength = wordlength; + + if (rate_changed) { + ret = tas2557_power_up_locked(tas2557, tas2557->devs[0].current_program); + if (ret < 0) { + /* + * The chips are down but ClassD is still on: keep + * powered so that a retry reloads the program and + * PRE_PMD still runs the shutdown. + */ + tas2557->powered = true; + tas2557->dac_muted = true; + tas2557->prog_valid = false; + return ret; + } + tas2557->powered = true; + } else if (remute) { + ret = tas2557_write_all(tas2557, TAS2557_MUTE_REG, 0); + if (ret >= 0) + ret = tas2557_update_bits_all(tas2557, + TAS2557_SOFT_MUTE_REG, + TAS2557_PDM_SOFT_MUTE, 0); + if (ret < 0) + return ret; + } + + return 0; +} + +static int tas2557_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt) +{ + struct snd_soc_component *component = dai->component; + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + unsigned int asi_fmt = 0, asi_delay = 0, chn; + int ret; + + /* The chip is always the clock consumer and has no inversion support */ + if ((fmt & SND_SOC_DAIFMT_CLOCK_PROVIDER_MASK) != SND_SOC_DAIFMT_CBC_CFC || + (fmt & SND_SOC_DAIFMT_INV_MASK) != SND_SOC_DAIFMT_NB_NF) { + dev_err(tas2557->tas_priv->dev, "unsupported DAI format 0x%x\n", fmt); + return -EINVAL; + } + + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_I2S: + asi_fmt = TAS2557_FORMAT_I2S; + break; + case SND_SOC_DAIFMT_DSP_A: + /* The DSP format at OFFSET1 = 0 is DSP_B; DSP_A is 1 BCLK later */ + asi_delay = 1; + fallthrough; + case SND_SOC_DAIFMT_DSP_B: + asi_fmt = TAS2557_FORMAT_DSP; + break; + case SND_SOC_DAIFMT_RIGHT_J: + asi_fmt = TAS2557_FORMAT_RIGHT_J; + break; + case SND_SOC_DAIFMT_LEFT_J: + asi_fmt = TAS2557_FORMAT_LEFT_J; + break; + default: + dev_err(tas2557->tas_priv->dev, "unsupported DAI format 0x%x\n", fmt); + return -EINVAL; + } + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + tas2557->dai_fmt = asi_fmt; + tas2557->asi_delay = asi_delay; + + ret = tas2557_asi_fmt_update_all(tas2557, TAS2557_FORMAT_MASK, asi_fmt); + if (ret < 0) + return ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_write_rx_offset(tas2557, chn); + if (ret < 0) + return ret; + } + + return 0; +} + +static int tas2557_set_tdm_slot(struct snd_soc_dai *dai, + unsigned int tx_mask, unsigned int rx_mask, + int slots, int slot_width) +{ + struct snd_soc_component *component = dai->component; + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + unsigned int ndev = tas2557->tas_priv->ndev; + unsigned int offsets[TAS2557_MAX_DEV] = { }; + bool per_chip_slots = false; + unsigned int mask = rx_mask; + unsigned int chn; + int ret = 0; + + switch (slot_width) { + case 0: + case 16: + case 24: + case 32: + break; + default: + dev_err(tas2557->tas_priv->dev, "unsupported TDM slot width %d\n", + slot_width); + return -EINVAL; + } + + /* + * With at least two slots in the mask and at least as many as + * chips, chip n takes the n-th slot; otherwise every chip takes the + * first one. Only the slots actually used are checked. + */ + if (rx_mask) { + per_chip_slots = hweight32(rx_mask) >= 2 && + hweight32(rx_mask) >= ndev; + + for (chn = 0; chn < ndev; chn++) { + unsigned int slot = __ffs(mask); + + if (slot && !slot_width) { + dev_err(tas2557->tas_priv->dev, + "TDM slot %u needs a slot width\n", slot); + return -EINVAL; + } + if (per_chip_slots) + mask &= mask - 1; + offsets[chn] = slot * slot_width; + } + } + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + /* The offset plus the DSP_A BCLK must fit the 8-bit OFFSET1 register */ + for (chn = 0; chn < ndev; chn++) + if (offsets[chn] + tas2557->asi_delay > U8_MAX) { + dev_err(tas2557->tas_priv->dev, + "TDM slot offset %u out of range\n", offsets[chn]); + return -EINVAL; + } + + /* + * tx_mask is accepted but not programmed: DOUT slot placement is not + * handled by this driver. Clearing both masks leaves TDM mode and + * restores the default offset. + */ + if (!rx_mask && tx_mask) + return 0; + + tas2557->tdm_configured = !!rx_mask; + + for (chn = 0; chn < ndev; chn++) { + tas2557->devs[chn].asi_offset = offsets[chn]; + + ret = tas2557_write_rx_offset(tas2557, chn); + if (ret < 0) + return ret; + } + + dev_dbg(tas2557->tas_priv->dev, "TDM: rx_mask=0x%x width=%d\n", + rx_mask, slot_width); + + return 0; +} + +static int tas2557_mute_stream(struct snd_soc_dai *dai, int mute, int direction) +{ + struct snd_soc_component *component = dai->component; + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + int ret = 0; + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + if (!tas2557->powered) { + tas2557->dac_muted = mute; + return 0; + } + + if (mute) { + /* Detection off first: the host is about to stop the clocks */ + ret = tas2557_clk_err_detect(tas2557, false); + if (ret >= 0) + ret = tas2557_update_bits_all(tas2557, + TAS2557_SOFT_MUTE_REG, + TAS2557_PDM_SOFT_MUTE, + TAS2557_PDM_SOFT_MUTE); + if (ret >= 0) { + usleep_range(10000, 11000); + ret = tas2557_write_all(tas2557, TAS2557_MUTE_REG, + TAS2557_MUTE_ISNS | + TAS2557_MUTE_VSNS); + } + tas2557->dac_muted = mute; + } else { + /* Clocks are running now: unmute and arm error detection */ + tas2557->dac_muted = false; + ret = tas2557_apply_mute_state(tas2557); + } + + return ret; +} + +static const struct snd_soc_dai_ops tas2557_dai_ops = { + .startup = tas2557_startup, + .hw_params = tas2557_hw_params, + .set_fmt = tas2557_set_dai_fmt, + .set_tdm_slot = tas2557_set_tdm_slot, + .mute_stream = tas2557_mute_stream, + /* + * The DSP needs the IV sense feedback while the amplifier plays, so + * only the playback stream is muted. + */ + .no_capture_mute = 1, +}; + +static struct snd_soc_dai_driver tas2557_dai = { + .name = "tas2557-amplifier", + .playback = { + .stream_name = "Playback", + .channels_min = 1, + .channels_max = 2, + .rates = SNDRV_PCM_RATE_8000_192000, + .formats = TAS2557_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 1, + .channels_max = 2, + .rates = SNDRV_PCM_RATE_8000_192000, + .formats = TAS2557_FORMATS, + }, + .ops = &tas2557_dai_ops, + /* + * One firmware config (hence one rate) is active at a time, and + * playback and capture share the single ASI word length, so both + * substreams must agree on rate and sample width. + */ + .symmetric_rate = 1, + .symmetric_sample_bits = 1, +}; + +/* ========================================================================= + * ALSA mixer controls + * ========================================================================= + */ +static DECLARE_TLV_DB_SCALE(tas2557_dac_tlv, 0, 100, 0); + +static int tas2557_volume_get(struct snd_kcontrol *kc, + struct snd_ctl_elem_value *ucontrol) +{ + struct tas2557_priv *tas2557 = + snd_soc_component_get_drvdata(snd_kcontrol_chip(kc)); + + ucontrol->value.integer.value[0] = tas2557->dac_gain; + return 0; +} + +static int tas2557_volume_put(struct snd_kcontrol *kc, + struct snd_ctl_elem_value *ucontrol) +{ + struct tas2557_priv *tas2557 = + snd_soc_component_get_drvdata(snd_kcontrol_chip(kc)); + unsigned int gain = ucontrol->value.integer.value[0]; + int ret = 0; + + if (gain > TAS2557_DAC_GAIN_MAX) + return -EINVAL; + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + if (gain == tas2557->dac_gain) + return 0; + + if (tas2557->powered) { + ret = tas2557_update_bits_all(tas2557, TAS2557_SPK_CTRL_REG, + TAS2557_DAC_GAIN_MASK, + gain << TAS2557_DAC_GAIN_SHIFT); + if (ret < 0) + return ret; + } + + /* Only commit the cached gain once the hardware write has succeeded */ + tas2557->dac_gain = gain; + + return 1; +} + +static const struct snd_kcontrol_new tas2557_controls[] = { + SOC_SINGLE_EXT_TLV("Speaker Playback Volume", SND_SOC_NOPM, 0, + TAS2557_DAC_GAIN_MAX, 0, + tas2557_volume_get, tas2557_volume_put, + tas2557_dac_tlv), +}; + +/* ========================================================================= + * DAPM topology + * + * Playback path: ASI (AIF_IN, stream "Playback") -> DAC -> ClassD -> OUT + * Capture path: ClassD -> ISENSE/VSENSE -> SENSE (AIF_OUT, "Capture") + * + * One AIF widget serves whichever ASI ti,asi-port selects; the pin and + * format programming is done by the startup sequence, not by DAPM. + * ========================================================================= + */ +static int tas2557_classd_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + struct snd_soc_component *component = + snd_soc_dapm_to_component(w->dapm); + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + int ret; + + switch (event) { + case SND_SOC_DAPM_POST_PMU: + /* Not under codec_lock, see tas2557_wait_fw() */ + tas2557_wait_fw(tas2557); + + mutex_lock(&tas2557->tas_priv->codec_lock); + ret = tas2557_enable(tas2557, true); + mutex_unlock(&tas2557->tas_priv->codec_lock); + if (ret < 0) + return ret; + tas2557_irq_arm(tas2557); + return 0; + case SND_SOC_DAPM_PRE_PMD: + tas2557_irq_disarm(tas2557); + mutex_lock(&tas2557->tas_priv->codec_lock); + ret = tas2557_enable(tas2557, false); + mutex_unlock(&tas2557->tas_priv->codec_lock); + return ret; + default: + return 0; + } +} + +static const struct snd_soc_dapm_widget tas2557_dapm_widgets[] = { + SND_SOC_DAPM_AIF_IN("ASI", "Playback", 0, SND_SOC_NOPM, 0, 0), + + SND_SOC_DAPM_DAC("DAC", NULL, SND_SOC_NOPM, 0, 0), + + SND_SOC_DAPM_OUT_DRV_E("ClassD", SND_SOC_NOPM, 0, 0, NULL, 0, + tas2557_classd_event, + SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD), + + /* IV sense is powered by the startup sequence, not by DAPM writes */ + SND_SOC_DAPM_ADC("ISENSE", NULL, SND_SOC_NOPM, 0, 0), + SND_SOC_DAPM_ADC("VSENSE", NULL, SND_SOC_NOPM, 0, 0), + + SND_SOC_DAPM_OUTPUT("OUT"), + SND_SOC_DAPM_AIF_OUT("SENSE", "Capture", 0, SND_SOC_NOPM, 0, 0), +}; + +static const struct snd_soc_dapm_route tas2557_dapm_routes[] = { + { "ASI", NULL, "Playback" }, + { "DAC", NULL, "ASI" }, + { "ClassD", NULL, "DAC" }, + { "OUT", NULL, "ClassD" }, + + { "ISENSE", NULL, "ClassD" }, + { "VSENSE", NULL, "ClassD" }, + { "SENSE", NULL, "ISENSE" }, + { "SENSE", NULL, "VSENSE" }, + { "Capture", NULL, "SENSE" }, +}; + +/* ========================================================================= + * ASoC component probe / suspend / resume + * ========================================================================= + */ +static int tas2557_codec_probe(struct snd_soc_component *component) +{ + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + const char *default_fw; + unsigned int chn; + int ret; + + /* Serialise against a pending tas2557_fw_ready() on a card re-bind */ + guard(mutex)(&tas2557->tas_priv->codec_lock); + + tas2557_hw_reset(tas2557); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_dev_write(tas2557, chn, TAS2557_SW_RESET_REG, 0x01); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "chn %u: software reset failed: %d\n", + chn, ret); + return ret; + } + } + usleep_range(1000, 2000); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + unsigned int pg_id; + + ret = tas2557_dev_read(tas2557, chn, TAS2557_REV_PGID_REG, &pg_id); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "chn %u: failed to read REV_PGID: %d\n", + chn, ret); + return ret; + } + tas2557->devs[chn].pg_id = pg_id; + } + + /* + * Firmware selection is group-wide (one shared image); the PG + * version of devs[0] is used as the representative silicon + * revision, matching how current_program/current_config/pg_id are + * otherwise read back from devs[0] elsewhere in this driver. + */ + switch (tas2557->devs[0].pg_id) { + case TAS2557_PG_VERSION_1P0: + dev_dbg(tas2557->tas_priv->dev, "silicon: PG1.0 (0x%02x)\n", + tas2557->devs[0].pg_id); + default_fw = TAS2557_PG1P0_FW_NAME; + break; + case TAS2557_PG_VERSION_2P0: + dev_dbg(tas2557->tas_priv->dev, "silicon: PG2.0 (0x%02x)\n", + tas2557->devs[0].pg_id); + default_fw = TAS2557_FW_NAME; + break; + case TAS2557_PG_VERSION_2P1: + dev_dbg(tas2557->tas_priv->dev, "silicon: PG2.1 (0x%02x)\n", + tas2557->devs[0].pg_id); + default_fw = TAS2557_FW_NAME; + break; + default: + dev_warn(tas2557->tas_priv->dev, + "unknown silicon version 0x%02x, assuming PG2.x fw\n", + tas2557->devs[0].pg_id); + default_fw = TAS2557_FW_NAME; + break; + } + + /* + * A "firmware-name" DT property (read at i2c probe) overrides the + * PG-based default; dual-amp stereo boards load a different DSP + * blob (e.g. tas2557s_uCDSP.bin). + */ + if (!tas2557->fw_name[0]) + strscpy(tas2557->fw_name, default_fw, sizeof(tas2557->fw_name)); + + ret = tas2557_load_data_all(tas2557, tas2557_default_data); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "default data load failed: %d\n", ret); + return ret; + } + + ret = tas2557_load_data_all(tas2557, tas2557_irq_config); + if (ret < 0) + dev_warn(tas2557->tas_priv->dev, "IRQ config failed: %d\n", ret); + + /* + * Component rebind (e.g. after an unbind/bind cycle): firmware is + * already parsed and stored, so do not request it again. + */ + if (!tas2557->fw_requested) { + reinit_completion(&tas2557->fw_done); + ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT, + tas2557->fw_name, tas2557->tas_priv->dev, + GFP_KERNEL, tas2557, + tas2557_fw_ready); + if (ret) { + return dev_err_probe(tas2557->tas_priv->dev, ret, + "failed to request fw '%s'\n", + tas2557->fw_name); + } + tas2557->fw_requested = true; + } + + dev_dbg(tas2557->tas_priv->dev, "codec probed (%u chip(s)), requesting firmware '%s'\n", + tas2557->tas_priv->ndev, tas2557->fw_name); + return 0; +} + +static int tas2557_suspend(struct snd_soc_component *component) +{ + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + + tas2557_irq_disarm(tas2557); + + guard(mutex)(&tas2557->tas_priv->codec_lock); + if (!tas2557->powered) + return 0; + + return tas2557_enable(tas2557, false); +} + +static int tas2557_resume(struct snd_soc_component *component) +{ + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + int ret; + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + /* Also invalidates the loaded program, even without a reset GPIO */ + tas2557_hw_reset(tas2557); + + ret = tas2557_load_data_all(tas2557, tas2557_default_data); + if (ret < 0) + dev_err(tas2557->tas_priv->dev, "defaults reload on resume failed: %d\n", + ret); + else if (tas2557_load_data_all(tas2557, tas2557_irq_config) < 0) + dev_warn(tas2557->tas_priv->dev, "IRQ config reload on resume failed\n"); + + /* + * The group stays powered down until the next DAPM power-up, which + * reloads the program and applies both mute states. + */ + + return ret; +} + +static const struct snd_soc_component_driver soc_component_tas2557 = { + .probe = tas2557_codec_probe, + .suspend = tas2557_suspend, + .resume = tas2557_resume, + .controls = tas2557_controls, + .num_controls = ARRAY_SIZE(tas2557_controls), + .dapm_widgets = tas2557_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(tas2557_dapm_widgets), + .dapm_routes = tas2557_dapm_routes, + .num_dapm_routes = ARRAY_SIZE(tas2557_dapm_routes), + .idle_bias_on = 1, + .use_pmdown_time = 1, + .endianness = 1, +}; + +/* ========================================================================= + * I2C driver + * ========================================================================= + */ + +/* + * tas2557_parse_dt - populate tas_priv->tasdevice[]/ndev, the per-chip + * reset/IRQ lines and ti,asi-port + * + * `reg` holds one I2C address per chip (up to TAS2557_MAX_DEV), read with + * of_property_read_reg() as tasdevice_parse_dt() does, since + * i2c_client::addr only reflects the first entry. Without an OF node a + * single chip at the i2c_client's address is used. + * + * A single reset-gpios/interrupts entry applies to every chip. + */ +static int tas2557_parse_dt(struct tas2557_priv *tas2557, struct i2c_client *client) +{ + struct tasdevice_priv *tas_priv = tas2557->tas_priv; + struct device *dev = tas_priv->dev; + struct device_node *np = dev->of_node; + unsigned int i; + int ndev = 0; + int ret; + + if (np) { + u64 addr; + + for (i = 0; i < TAS2557_MAX_DEV; i++) { + if (of_property_read_reg(np, i, &addr, NULL)) + break; + tas_priv->tasdevice[ndev++].dev_addr = addr; + } + } + + if (ndev == 0) { + ndev = 1; + tas_priv->tasdevice[0].dev_addr = client->addr; + } + + tas_priv->ndev = ndev; + + /* + * Reserve every secondary address on the bus so no other + * driver can claim it; tasdevice_change_chn_book() keeps swapping + * client->addr to reach each chip, these dummies only reserve the + * i2c_client namespace. + */ + for (i = 1; i < tas_priv->ndev; i++) { + struct i2c_client *dummy = devm_i2c_new_dummy_device(dev, + client->adapter, tas_priv->tasdevice[i].dev_addr); + if (IS_ERR(dummy)) + return dev_err_probe(dev, PTR_ERR(dummy), + "failed to reserve i2c addr 0x%02x\n", + tas_priv->tasdevice[i].dev_addr); + } + + /* + * reset-gpios / interrupts, minItems 1 maxItems 2; a single + * entry applies to every chip. Reset GPIOs are modeled active-low + * in DT: the logical value 0 (GPIOD_OUT_LOW) deasserts reset, + * releasing the device group. + */ + for (i = 0; i < tas_priv->ndev; i++) { + tas2557->reset[i] = devm_gpiod_get_index_optional(dev, "reset", i, + GPIOD_OUT_LOW); + if (IS_ERR(tas2557->reset[i])) + return dev_err_probe(dev, PTR_ERR(tas2557->reset[i]), + "failed to get reset GPIO %u\n", i); + if (!tas2557->reset[i] && i > 0) + tas2557->reset[i] = tas2557->reset[0]; + + tas2557->irq[i] = of_irq_get(np, i); + if (tas2557->irq[i] == -EPROBE_DEFER) + return dev_err_probe(dev, tas2557->irq[i], + "interrupt %u not ready\n", i); + if (tas2557->irq[i] <= 0 && i > 0) + tas2557->irq[i] = tas2557->irq[0]; + /* Index 0 falls back to the primary i2c_client IRQ */ + if (i == 0 && tas2557->irq[i] <= 0) + tas2557->irq[i] = client->irq; + } + + /* Which ASI's pins/dividers/format registers to program */ + tas2557->asi_port = TAS2557_ASI_PORT_DEFAULT; + ret = of_property_read_u32(np, "ti,asi-port", &tas2557->asi_port); + if (ret && ret != -EINVAL) + return dev_err_probe(dev, ret, "failed to read ti,asi-port\n"); + if (tas2557->asi_port != TAS2557_ASI_PORT1 && + tas2557->asi_port != TAS2557_ASI_PORT2) + return dev_err_probe(dev, -EINVAL, + "ti,asi-port must be 1 or 2, got %u\n", + tas2557->asi_port); + + for (i = 0; i < tas_priv->ndev; i++) { + tas2557->devs[i].pg_id = 0; + tas2557->devs[i].current_program = 0; + tas2557->devs[i].current_config = 0; + tas2557->devs[i].restart_count = 0; + tas2557->devs[i].asi_offset = 0; + } + + return 0; +} + +/* + * Destroys codec_lock; must run after everything that can take it. + * comlib leaves client->addr on the last chip it accessed; put the primary + * address back so a later probe can reserve it again. + */ +static void tas2557_comlib_remove(void *data) +{ + struct tasdevice_priv *tas_priv = data; + struct i2c_client *client = tas_priv->client; + + client->addr = tas_priv->tasdevice[0].dev_addr; + tasdevice_remove(tas_priv); +} + +static int tas2557_i2c_probe(struct i2c_client *client) +{ + static const char * const tas2557_supplies[] = { + "vbat", "iovdd", "avdd", "dvdd" + }; + struct device *dev = &client->dev; + struct tas2557_priv *tas2557; + struct tasdevice_priv *tas_priv; + const char *fw_name; + unsigned int i, j; + int irq, ret; + + tas2557 = devm_kzalloc(dev, sizeof(*tas2557), GFP_KERNEL); + if (!tas2557) + return -ENOMEM; + + /* tas2781-comlib owns the paged regmap and per-chip register I/O */ + tas_priv = tasdevice_kzalloc(client); + if (!tas_priv) + return -ENOMEM; + tas2557->tas_priv = tas_priv; + + i2c_set_clientdata(client, tas2557); + + init_completion(&tas2557->fw_done); + tas2557->fw_requested = false; + + ret = tas2557_parse_dt(tas2557, client); + if (ret) + return ret; + + /* Default gain: +15 dB, as the firmware programs write */ + tas2557->dac_gain = TAS2557_DAC_GAIN_MAX; + + /* The device group comes out of reset muted */ + tas2557->dac_muted = true; + + /* -1 means "never set"; see tas2557_apply_runtime_state() */ + tas2557->dai_fmt = -1; + + /* Seed a valid ASI word length before the first hw_params() */ + tas2557->wordlength = TAS2557_WORDLENGTH_32BIT; + + /* Explicit firmware name; overrides the PG-based mono default */ + if (!of_property_read_string(dev->of_node, "firmware-name", &fw_name)) + strscpy(tas2557->fw_name, fw_name, sizeof(tas2557->fw_name)); + else if (tas_priv->ndev > 1) + return dev_err_probe(dev, -EINVAL, + "firmware-name is required for two chips\n"); + + ret = devm_regulator_bulk_get_enable(dev, ARRAY_SIZE(tas2557_supplies), + tas2557_supplies); + if (ret) + return dev_err_probe(dev, ret, + "failed to get/enable supplies\n"); + usleep_range(5000, 10000); + + ret = tasdevice_init(tas_priv); + if (ret) + return dev_err_probe(dev, ret, "comlib init failed\n"); + + /* + * Both actions are registered right after tasdevice_init(). devm + * actions run in LIFO order: the component registered below goes + * first, then the IRQs, then tas2557_fw_teardown() (nothing can + * still run tas2557_irq_handler() or the DAI ops at that point, and + * it waits for tas2557_fw_ready()), and only then is codec_lock + * destroyed, before the comlib regmap, reset GPIOs and regulators + * are released. + */ + ret = devm_add_action_or_reset(dev, tas2557_comlib_remove, tas_priv); + if (ret) + return ret; + + ret = devm_add_action_or_reset(dev, tas2557_fw_teardown, tas2557); + if (ret) + return ret; + + /* One threaded handler per configured IRQ, same dev_id */ + for (i = 0; i < tas_priv->ndev; i++) { + if (i > 0 && tas2557->irq[i] == tas2557->irq[i - 1]) + continue; + if (tas2557->irq[i] <= 0) + continue; + + irq = tas2557->irq[i]; + ret = devm_request_threaded_irq(dev, irq, NULL, + tas2557_irq_handler, + IRQF_ONESHOT | IRQF_NO_AUTOEN, + "tas2557", tas2557); + if (ret) { + dev_warn(dev, "IRQ %d request failed: %d\n", irq, ret); + /* Every chip sharing the line loses it */ + for (j = i; j < tas_priv->ndev; j++) + if (tas2557->irq[j] == irq) + tas2557->irq[j] = 0; + } else { + dev_dbg(dev, "IRQ %d registered\n", irq); + } + } + + ret = devm_snd_soc_register_component(dev, &soc_component_tas2557, + &tas2557_dai, 1); + if (ret) + return dev_err_probe(dev, ret, + "component registration failed\n"); + + dev_dbg(dev, "TAS2557 probed (%u chip(s), primary I2C addr 0x%02x, ASI%u)\n", + tas_priv->ndev, client->addr, tas2557->asi_port); + return 0; +} + +static const struct i2c_device_id tas2557_i2c_id[] = { + { .name = "tas2557" }, + { } +}; +MODULE_DEVICE_TABLE(i2c, tas2557_i2c_id); + +static const struct of_device_id tas2557_of_match[] = { + { .compatible = "ti,tas2557" }, + { } +}; +MODULE_DEVICE_TABLE(of, tas2557_of_match); + +static struct i2c_driver tas2557_i2c_driver = { + .driver = { + .name = "tas2557", + .of_match_table = tas2557_of_match, + }, + .probe = tas2557_i2c_probe, + .id_table = tas2557_i2c_id, +}; +module_i2c_driver(tas2557_i2c_driver); + +MODULE_AUTHOR("Texas Instruments Inc."); +MODULE_AUTHOR("Gianluca Boiano "); +MODULE_DESCRIPTION("ASoC TAS2557 Smart Amplifier Driver"); +MODULE_FIRMWARE(TAS2557_FW_NAME); +MODULE_FIRMWARE(TAS2557_PG1P0_FW_NAME); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/tas2557.h b/sound/soc/codecs/tas2557.h new file mode 100644 index 00000000000000..0b01496d944a30 --- /dev/null +++ b/sound/soc/codecs/tas2557.h @@ -0,0 +1,207 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * ALSA SoC Texas Instruments TAS2557 Smart Amplifier + * + * Copyright (C) 2016 Texas Instruments Inc. + * Copyright (C) 2026 Gianluca Boiano + */ + +#ifndef __TAS2557_H__ +#define __TAS2557_H__ + +#include +#include + +/* + * TAS2557 uses a book/page/register addressing scheme, same layout as + * tas2781-comlib's TASDEVICE_REG(): 8-bit registers, page selected via + * register 0, book selected via register 0x7f in page 0. Register + * access, book/page switching and the paged-window regmap are all + * provided by tas2781-comlib(-i2c); this header only keeps the TAS2557_* + * register names for readability, defined in terms of TASDEVICE_REG(). + */ + +/* Build a register address from firmware-block book/page/offset bytes */ +#define TAS2557_REG(book, page, reg) TASDEVICE_REG(book, page, reg) + +/* Book 0, Page 0 registers */ +#define TAS2557_SW_RESET_REG TASDEVICE_REG(0, 0, 1) +#define TAS2557_REV_PGID_REG TASDEVICE_REG(0, 0, 3) +#define TAS2557_POWER_CTRL1_REG TASDEVICE_REG(0, 0, 4) +#define TAS2557_POWER_CTRL2_REG TASDEVICE_REG(0, 0, 5) +#define TAS2557_SPK_CTRL_REG TASDEVICE_REG(0, 0, 6) +#define TAS2557_MUTE_REG TASDEVICE_REG(0, 0, 7) +#define TAS2557_ADC_INPUT_SEL_REG TASDEVICE_REG(0, 0, 9) +#define TAS2557_DBOOST_CTL_REG TASDEVICE_REG(0, 0, 10) +#define TAS2557_SAR_SAMPLING_TIME_REG TASDEVICE_REG(0, 0, 19) +#define TAS2557_SAR_ADC1_REG TASDEVICE_REG(0, 0, 20) +#define TAS2557_SAR_ADC2_REG TASDEVICE_REG(0, 0, 21) +#define TAS2557_CRC_CHECKSUM_REG TASDEVICE_REG(0, 0, 32) +#define TAS2557_CRC_RESET_REG TASDEVICE_REG(0, 0, 33) +#define TAS2557_DSP_MODE_SELECT_REG TASDEVICE_REG(0, 0, 34) +#define TAS2557_SAFE_GUARD_REG TASDEVICE_REG(0, 0, 37) +#define TAS2557_ASI_CTL1_REG TASDEVICE_REG(0, 0, 42) +#define TAS2557_CLK_ERR_CTRL TASDEVICE_REG(0, 0, 44) +#define TAS2557_CLK_ERR_CTRL2 TASDEVICE_REG(0, 0, 45) +#define TAS2557_CLK_ERR_CTRL3 TASDEVICE_REG(0, 0, 46) +#define TAS2557_DBOOST_CFG_REG TASDEVICE_REG(0, 0, 52) +#define TAS2557_POWER_UP_FLAG_REG TASDEVICE_REG(0, 0, 100) +#define TAS2557_FLAGS_1 TASDEVICE_REG(0, 0, 104) +#define TAS2557_FLAGS_2 TASDEVICE_REG(0, 0, 108) + +/* Book 0, Page 1 registers - ASI1 configuration */ +#define TAS2557_ASI1_DAC_FORMAT_REG TASDEVICE_REG(0, 1, 1) +#define TAS2557_ASI1_OFFSET1_REG TASDEVICE_REG(0, 1, 3) +#define TAS2557_ASI1_ADC_PATH_REG TASDEVICE_REG(0, 1, 7) +#define TAS2557_ASI1_DAC_BCLK_REG TASDEVICE_REG(0, 1, 8) +#define TAS2557_ASI1_DAC_WCLK_REG TASDEVICE_REG(0, 1, 9) +#define TAS2557_ASI1_ADC_BCLK_REG TASDEVICE_REG(0, 1, 10) +#define TAS2557_ASI1_ADC_WCLK_REG TASDEVICE_REG(0, 1, 11) +#define TAS2557_ASI1_DIN_DOUT_MUX_REG TASDEVICE_REG(0, 1, 12) + +/* Book 0, Page 1 - ASI2 configuration */ +#define TAS2557_ASI2_DAC_FORMAT_REG TASDEVICE_REG(0, 1, 21) +#define TAS2557_ASI2_OFFSET1_REG TASDEVICE_REG(0, 1, 23) +#define TAS2557_ASI2_ADC_PATH_REG TASDEVICE_REG(0, 1, 27) +#define TAS2557_ASI2_DAC_BCLK_REG TASDEVICE_REG(0, 1, 28) +#define TAS2557_ASI2_DAC_WCLK_REG TASDEVICE_REG(0, 1, 29) +#define TAS2557_ASI2_ADC_BCLK_REG TASDEVICE_REG(0, 1, 30) +#define TAS2557_ASI2_ADC_WCLK_REG TASDEVICE_REG(0, 1, 31) +#define TAS2557_ASI2_DIN_DOUT_MUX_REG TASDEVICE_REG(0, 1, 32) +#define TAS2557_ASI2_BDIV_CLK_SEL_REG TASDEVICE_REG(0, 1, 33) +#define TAS2557_ASI2_BDIV_CLK_RATIO_REG TASDEVICE_REG(0, 1, 34) +#define TAS2557_ASI2_WDIV_CLK_RATIO_REG TASDEVICE_REG(0, 1, 35) +#define TAS2557_ASI2_DAC_CLKOUT_REG TASDEVICE_REG(0, 1, 36) +#define TAS2557_ASI2_ADC_CLKOUT_REG TASDEVICE_REG(0, 1, 37) + +/* Book 0, Page 1 - GPIO pin configuration */ +#define TAS2557_GPIO1_PIN_REG TASDEVICE_REG(0, 1, 61) +#define TAS2557_GPIO2_PIN_REG TASDEVICE_REG(0, 1, 62) +#define TAS2557_GPIO3_PIN_REG TASDEVICE_REG(0, 1, 63) +#define TAS2557_GPIO4_PIN_REG TASDEVICE_REG(0, 1, 64) +#define TAS2557_GPIO5_PIN_REG TASDEVICE_REG(0, 1, 65) +#define TAS2557_GPIO6_PIN_REG TASDEVICE_REG(0, 1, 66) +#define TAS2557_GPIO7_PIN_REG TASDEVICE_REG(0, 1, 67) +#define TAS2557_GPIO8_PIN_REG TASDEVICE_REG(0, 1, 68) +#define TAS2557_GPI_PIN_REG TASDEVICE_REG(0, 1, 77) + +/* Book 0, Page 1 - interrupt configuration */ +#define TAS2557_CLK_HALT_REG TASDEVICE_REG(0, 1, 106) +#define TAS2557_INT_GEN1_REG TASDEVICE_REG(0, 1, 108) +#define TAS2557_INT_GEN2_REG TASDEVICE_REG(0, 1, 109) +#define TAS2557_INT_GEN3_REG TASDEVICE_REG(0, 1, 110) +#define TAS2557_INT_GEN4_REG TASDEVICE_REG(0, 1, 111) +#define TAS2557_INT_MODE_REG TASDEVICE_REG(0, 1, 114) +#define TAS2557_MAIN_CLKIN_REG TASDEVICE_REG(0, 1, 115) +#define TAS2557_PLL_CLKIN_REG TASDEVICE_REG(0, 1, 116) + +/* Book 0, Page 2 */ +#define TAS2557_SLEEPMODE_CTL_REG TASDEVICE_REG(0, 2, 7) + +/* Book 100, Page 0 - DSP / PLL registers */ +#define TAS2557_DAC_INTERPOL_REG TASDEVICE_REG(100, 0, 1) +#define TAS2557_SOFT_MUTE_REG TASDEVICE_REG(100, 0, 7) +#define TAS2557_PLL_P_VAL_REG TASDEVICE_REG(100, 0, 27) +#define TAS2557_PLL_J_VAL_REG TASDEVICE_REG(100, 0, 28) +#define TAS2557_PLL_D_VAL_MSB_REG TASDEVICE_REG(100, 0, 29) +#define TAS2557_PLL_D_VAL_LSB_REG TASDEVICE_REG(100, 0, 30) +#define TAS2557_CLK_MISC_REG TASDEVICE_REG(100, 0, 31) +#define TAS2557_PLL_N_VAL_REG TASDEVICE_REG(100, 0, 32) +#define TAS2557_DAC_MADC_VAL_REG TASDEVICE_REG(100, 0, 33) +#define TAS2557_VBOOST_CTL_REG TASDEVICE_REG(100, 0, 64) + +/* Book 130, Page 2 - Die temperature */ +#define TAS2557_DIE_TEMP_REG TASDEVICE_REG(130, 2, 124) + +/* DSP coefficient swap register (skipped by the firmware CRC checker) */ +#define TAS2557_SA_COEFF_SWAP_REG TASDEVICE_REG(0, 53, 44) + +/* PG (Process Generation) version identifiers from REV_PGID_REG */ +#define TAS2557_PG_VERSION_1P0 0x80 +#define TAS2557_PG_VERSION_2P0 0x90 +#define TAS2557_PG_VERSION_2P1 0xa0 + +/* B0P0R4 - TAS2557_POWER_CTRL1_REG */ +#define TAS2557_SW_SHUTDOWN BIT(0) +#define TAS2557_MADC_POWER_UP BIT(3) +#define TAS2557_MDAC_POWER_UP BIT(4) +#define TAS2557_NDIV_POWER_UP BIT(5) +#define TAS2557_PLL_POWER_UP BIT(6) +#define TAS2557_DSP_POWER_UP BIT(7) + +/* B0P0R5 - TAS2557_POWER_CTRL2_REG */ +#define TAS2557_BOOST_ENABLE BIT(5) +#define TAS2557_CLASSD_ENABLE BIT(7) + +/* B0P0R6 - TAS2557_SPK_CTRL_REG */ +#define TAS2557_DAC_GAIN_MASK (0xf << 3) +#define TAS2557_DAC_GAIN_SHIFT 3 +#define TAS2557_DAC_GAIN_MAX 0x0f + +/* B0P0R7 - TAS2557_MUTE_REG */ +#define TAS2557_MUTE_VSNS BIT(0) +#define TAS2557_MUTE_ISNS BIT(1) + +/* B100P0R7 - TAS2557_SOFT_MUTE_REG */ +#define TAS2557_PDM_SOFT_MUTE BIT(0) + +/* ASI format field in ASIx_DAC_FORMAT_REG bits [7:5] */ +#define TAS2557_FORMAT_I2S (0x0 << 5) +#define TAS2557_FORMAT_DSP (0x1 << 5) +#define TAS2557_FORMAT_RIGHT_J (0x2 << 5) +#define TAS2557_FORMAT_LEFT_J (0x3 << 5) +#define TAS2557_FORMAT_MONO_PCM (0x4 << 5) +#define TAS2557_FORMAT_MASK (0x7 << 5) + +/* ASI word length field in ASIx_DAC_FORMAT_REG bits [4:3] */ +#define TAS2557_WORDLENGTH_16BIT (0x0 << 3) +#define TAS2557_WORDLENGTH_20BIT (0x1 << 3) +#define TAS2557_WORDLENGTH_24BIT (0x2 << 3) +#define TAS2557_WORDLENGTH_32BIT (0x3 << 3) +#define TAS2557_WORDLENGTH_MASK (0x3 << 3) + +/* Safe guard pattern written to TAS2557_SAFE_GUARD_REG */ +#define TAS2557_SAFE_GUARD_PATTERN 0x5a + +/* Firmware filenames - PG version determines which file is loaded */ +#define TAS2557_FW_NAME "tas2557_uCDSP.bin" +#define TAS2557_PG1P0_FW_NAME "tas2557_pg1p0_uCDSP.bin" + +/* Firmware block type codes */ +#define TAS2557_BLOCK_PLL 0x00 +#define TAS2557_BLOCK_PGM_ALL 0x0d +#define TAS2557_BLOCK_PGM_DEV_A 0x01 +#define TAS2557_BLOCK_PGM_DEV_B 0x08 +#define TAS2557_BLOCK_CFG_COEFF_DEV_A 0x03 +#define TAS2557_BLOCK_CFG_COEFF_DEV_B 0x0a +#define TAS2557_BLOCK_CFG_PRE_DEV_A 0x04 +#define TAS2557_BLOCK_CFG_PRE_DEV_B 0x0b +#define TAS2557_BLOCK_CFG_POST 0x05 +#define TAS2557_BLOCK_CFG_POST_POWER 0x06 + +/* + * ti,asi-port selects which ASI's pin mux/clock dividers/format registers + * this driver programs; the other ASI's registers are left untouched at + * reset defaults. + */ +#define TAS2557_ASI_PORT1 1 +#define TAS2557_ASI_PORT2 2 +#define TAS2557_ASI_PORT_DEFAULT TAS2557_ASI_PORT2 + +/* + * One DT node manages an array of up to TAS2557_MAX_DEV physical chips + * (one entry per `reg` address), all sharing one firmware image, DAI and + * mute/power state via tas2781-comlib's per-channel register access + * (tasdevice_dev_*(tas_priv, chn, ...)). reset-gpios/interrupts follow + * the same per-index convention (a single entry applies to every chip). + */ +#define TAS2557_MAX_DEV 2 + +/* Firmware driver version flags (driver_version field) */ +#define PPC_DRIVER_CRCCHK 0x00000200 +#define PPC_DRIVER_CONFDEV 0x00000300 +#define PPC_DRIVER_MTPLLSRC 0x00000400 +/* Present from driver_version 0x101; carries a 2-byte device field */ +#define PPC_DRIVER_CFGDEV_NONCRC 0x00000101 + +#endif /* __TAS2557_H__ */ From 9d4bfe077aeac5c1c617751c06d3f0d09590a7ed Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Fri, 20 Nov 2026 16:43:52 +0700 Subject: [PATCH 2053/2102] ASoC: atmel: mchp-spdiftx: Improve probe error handling Use dev_err_probe() when retrieving clocks to avoid logging errors for deferred probes. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261120094354.6814-2-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-spdiftx.c | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/sound/soc/atmel/mchp-spdiftx.c b/sound/soc/atmel/mchp-spdiftx.c index fc635ed6856e15..6ab32f0b8b8ede 100644 --- a/sound/soc/atmel/mchp-spdiftx.c +++ b/sound/soc/atmel/mchp-spdiftx.c @@ -815,21 +815,15 @@ static int mchp_spdiftx_probe(struct platform_device *pdev) /* Get the peripheral clock */ dev->pclk = devm_clk_get(&pdev->dev, "pclk"); - if (IS_ERR(dev->pclk)) { - err = PTR_ERR(dev->pclk); - dev_err(&pdev->dev, - "failed to get the peripheral clock: %d\n", err); - return err; - } + if (IS_ERR(dev->pclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->pclk), + "failed to get the peripheral clock\n"); /* Get the generic clock */ dev->gclk = devm_clk_get(&pdev->dev, "gclk"); - if (IS_ERR(dev->gclk)) { - err = PTR_ERR(dev->gclk); - dev_err(&pdev->dev, - "failed to get the PMC generic clock: %d\n", err); - return err; - } + if (IS_ERR(dev->gclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->gclk), + "failed to get the PMC generic clock\n"); ctrl = &dev->control; spin_lock_init(&ctrl->lock); From 582d2686d230973f05cdd6ccf5c738594aba8723 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Fri, 20 Nov 2026 16:43:53 +0700 Subject: [PATCH 2054/2102] ASoC: atmel: mchp-spdiftx: Use devm helpers for runtime PM Use devm_pm_runtime_enable() and a devm action to handle runtime PM cleanup automatically. This removes the manual runtime PM cleanup from the probe error paths and the remove callback. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261120094354.6814-3-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-spdiftx.c | 46 ++++++++++++++++++---------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/sound/soc/atmel/mchp-spdiftx.c b/sound/soc/atmel/mchp-spdiftx.c index 6ab32f0b8b8ede..b034bd46cd5af6 100644 --- a/sound/soc/atmel/mchp-spdiftx.c +++ b/sound/soc/atmel/mchp-spdiftx.c @@ -778,6 +778,15 @@ static const struct dev_pm_ops mchp_spdiftx_pm_ops = { NULL) }; +/* Runtime suspend the device on cleanup if necessary */ +static void mchp_spdiftx_runtime_suspend_action(void *data) +{ + struct device *dev = data; + + if (!pm_runtime_status_suspended(dev)) + mchp_spdiftx_runtime_suspend(dev); +} + static int mchp_spdiftx_probe(struct platform_device *pdev) { struct mchp_spdiftx_dev *dev; @@ -836,11 +845,22 @@ static int mchp_spdiftx_probe(struct platform_device *pdev) dev->regmap = regmap; platform_set_drvdata(pdev, dev); - pm_runtime_enable(dev->dev); + err = devm_add_action(dev->dev, mchp_spdiftx_runtime_suspend_action, + dev->dev); + if (err) + return err; + + err = devm_pm_runtime_enable(dev->dev); + if (err) + return err; if (!pm_runtime_enabled(dev->dev)) { err = mchp_spdiftx_runtime_resume(dev->dev); - if (err) + if (err) { + devm_remove_action(dev->dev, + mchp_spdiftx_runtime_suspend_action, + dev->dev); return err; + } } dev->playback.addr = (dma_addr_t)mem->start + SPDIFTX_CDR; @@ -849,7 +869,7 @@ static int mchp_spdiftx_probe(struct platform_device *pdev) err = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (err) { dev_err(&pdev->dev, "failed to register PMC: %d\n", err); - goto pm_runtime_suspend; + return err; } err = devm_snd_soc_register_component(&pdev->dev, @@ -857,32 +877,14 @@ static int mchp_spdiftx_probe(struct platform_device *pdev) &mchp_spdiftx_dai, 1); if (err) { dev_err(&pdev->dev, "failed to register component: %d\n", err); - goto pm_runtime_suspend; + return err; } return 0; - -pm_runtime_suspend: - if (!pm_runtime_status_suspended(dev->dev)) - mchp_spdiftx_runtime_suspend(dev->dev); - pm_runtime_disable(dev->dev); - - return err; -} - -static void mchp_spdiftx_remove(struct platform_device *pdev) -{ - struct mchp_spdiftx_dev *dev = platform_get_drvdata(pdev); - - if (!pm_runtime_status_suspended(dev->dev)) - mchp_spdiftx_runtime_suspend(dev->dev); - - pm_runtime_disable(dev->dev); } static struct platform_driver mchp_spdiftx_driver = { .probe = mchp_spdiftx_probe, - .remove = mchp_spdiftx_remove, .driver = { .name = "mchp_spdiftx", .of_match_table = mchp_spdiftx_dt_ids, From fdec9546b1d33a9b8e8ac3180abd7612883a6c72 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Fri, 20 Nov 2026 16:43:54 +0700 Subject: [PATCH 2055/2102] ASoC: atmel: mchp-spdiftx: Move IRQ request after runtime PM setup Move devm_request_irq() after runtime PM setup to ensure the IRQ is released before the runtime suspend action runs during cleanup. Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261120094354.6814-4-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-spdiftx.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/sound/soc/atmel/mchp-spdiftx.c b/sound/soc/atmel/mchp-spdiftx.c index b034bd46cd5af6..658ff667439cee 100644 --- a/sound/soc/atmel/mchp-spdiftx.c +++ b/sound/soc/atmel/mchp-spdiftx.c @@ -812,16 +812,11 @@ static int mchp_spdiftx_probe(struct platform_device *pdev) if (IS_ERR(regmap)) return PTR_ERR(regmap); - /* Request IRQ */ + /* Get IRQ */ irq = platform_get_irq(pdev, 0); if (irq < 0) return irq; - err = devm_request_irq(&pdev->dev, irq, mchp_spdiftx_interrupt, 0, - dev_name(&pdev->dev), dev); - if (err) - return err; - /* Get the peripheral clock */ dev->pclk = devm_clk_get(&pdev->dev, "pclk"); if (IS_ERR(dev->pclk)) @@ -863,6 +858,12 @@ static int mchp_spdiftx_probe(struct platform_device *pdev) } } + /* Request IRQ */ + err = devm_request_irq(&pdev->dev, irq, mchp_spdiftx_interrupt, 0, + dev_name(&pdev->dev), dev); + if (err) + return err; + dev->playback.addr = (dma_addr_t)mem->start + SPDIFTX_CDR; dev->playback.addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; From 874d50f9be871d1ded0452d3807b04484e7745a6 Mon Sep 17 00:00:00 2001 From: Zhang Heng Date: Tue, 10 Nov 2026 10:52:36 +0800 Subject: [PATCH 2056/2102] ASoC: amd: yc: Add DMI quirk for Acer Nitro AN515-46 Add a DMI match entry so the ACP6x sound card is selected on the Acer Nitro AN515-46. Closes: https://bugzilla.kernel.org/show_bug.cgi?id=222239 Signed-off-by: Zhang Heng Link: https://patch.msgid.link/20261110025236.206625-1-zhangheng@kylinos.cn Signed-off-by: Mark Brown --- sound/soc/amd/yc/acp6x-mach.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/sound/soc/amd/yc/acp6x-mach.c b/sound/soc/amd/yc/acp6x-mach.c index e7ca9d6f85bea4..88234f351f5376 100644 --- a/sound/soc/amd/yc/acp6x-mach.c +++ b/sound/soc/amd/yc/acp6x-mach.c @@ -676,6 +676,13 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { DMI_MATCH(DMI_PRODUCT_NAME, "Swift SFA16-41"), } }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "RB"), + DMI_MATCH(DMI_PRODUCT_NAME, "Nitro AN515-46"), + } + }, { .driver_data = &acp6x_card, .matches = { From eedf01508d860d41c19f4b658d7bb5ecff15286d Mon Sep 17 00:00:00 2001 From: Jizhou Tong Date: Sun, 22 Nov 2026 06:25:04 +0000 Subject: [PATCH 2057/2102] ASoC: codecs: wcd-common: bound interrupt status retries wcd_interrupt_callback() reads three status registers after dispatching the codec interrupt. It ignores read errors, so the loop condition can use an uninitialized value or a value from the previous pass. A status bit that stays set can also keep the callback looping while SoundWire holds sdw_dev_lock. Return on the first failed read. Allow up to ten dispatches for status to clear, matching the SoundWire alert handler's retry budget. If a bit remains set, log a rate-limited error and return -ETIMEDOUT. Signed-off-by: Jizhou Tong Fixes: 59aebbbb0b47 ("ASoC: codecs: wcd-common: move status_update callback to common") Link: https://patch.msgid.link/010601a201ee018c-30715d0f-712e-4181-9dea-d1b82b234831-000000@ap-northeast-1.amazonses.com Signed-off-by: Mark Brown --- sound/soc/codecs/wcd-common.c | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/sound/soc/codecs/wcd-common.c b/sound/soc/codecs/wcd-common.c index 9016e974582f55..7c2d96ace030fe 100644 --- a/sound/soc/codecs/wcd-common.c +++ b/sound/soc/codecs/wcd-common.c @@ -15,6 +15,8 @@ #include "wcd-common.h" +#define WCD_IRQ_MAX_RETRIES 10 + #define WCD_MIN_MICBIAS_MV 1000 #define WCD_DEF_MICBIAS_MV 1800 #define WCD_MAX_MICBIAS_MV 2850 @@ -127,16 +129,27 @@ int wcd_interrupt_callback(struct sdw_slave *slave, struct irq_domain *slave_irq { struct regmap *regmap = dev_get_regmap(&slave->dev, NULL); u32 sts1, sts2, sts3; + int ret, i; - do { + /* A failed read or a stuck status must not hold sdw_dev_lock forever. */ + for (i = 0; i < WCD_IRQ_MAX_RETRIES; i++) { handle_nested_irq(irq_find_mapping(slave_irq, 0)); - regmap_read(regmap, wcd_intr_status0, &sts1); - regmap_read(regmap, wcd_intr_status1, &sts2); - regmap_read(regmap, wcd_intr_status2, &sts3); + ret = regmap_read(regmap, wcd_intr_status0, &sts1); + if (ret) + return ret; + ret = regmap_read(regmap, wcd_intr_status1, &sts2); + if (ret) + return ret; + ret = regmap_read(regmap, wcd_intr_status2, &sts3); + if (ret) + return ret; - } while (sts1 || sts2 || sts3); + if (!(sts1 || sts2 || sts3)) + return IRQ_HANDLED; + } - return IRQ_HANDLED; + dev_err_ratelimited(&slave->dev, "interrupt status did not clear\n"); + return -ETIMEDOUT; } EXPORT_SYMBOL_GPL(wcd_interrupt_callback); From 6d80a2e2b5cdc56a455699a3b64fabe06a9814b6 Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Fri, 20 Nov 2026 10:59:38 +0700 Subject: [PATCH 2058/2102] ASoC: atmel: mchp-spdifrx: Fix 16-bit big-endian format check MCHP_SPDIF_FORMATS advertises SNDRV_PCM_FMTBIT_U16_BE as a supported format, but mchp_spdifrx_hw_params() checks for SNDRV_PCM_FORMAT_S16_BE instead. Replace SNDRV_PCM_FORMAT_S16_BE with SNDRV_PCM_FORMAT_U16_BE to make the format check consistent with the advertised supported formats. Fixes: ef265c55c1ac ("ASoC: mchp-spdifrx: add driver for SPDIF RX") Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261120035939.12774-2-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-spdifrx.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/atmel/mchp-spdifrx.c b/sound/soc/atmel/mchp-spdifrx.c index 63089ac3ebdc97..80a64af0878b5a 100644 --- a/sound/soc/atmel/mchp-spdifrx.c +++ b/sound/soc/atmel/mchp-spdifrx.c @@ -455,7 +455,7 @@ static int mchp_spdifrx_hw_params(struct snd_pcm_substream *substream, } switch (params_format(params)) { - case SNDRV_PCM_FORMAT_S16_BE: + case SNDRV_PCM_FORMAT_U16_BE: case SNDRV_PCM_FORMAT_S20_3BE: case SNDRV_PCM_FORMAT_S24_3BE: case SNDRV_PCM_FORMAT_S24_BE: From bfa5f3714c0e2e4937f9c6cd7bea3e3b2ae76d4e Mon Sep 17 00:00:00 2001 From: bui duc phuc Date: Fri, 20 Nov 2026 10:59:39 +0700 Subject: [PATCH 2059/2102] ASoC: atmel: mchp-spdifrx: Preserve MR defaults in hw_params hw_params() overwrites the entire MR register, clearing the VBMODE and SBMODE bits configured in dai_probe(). Use regmap_update_bits() to update only the ENDIAN and DATAWIDTH fields, preserving the other MR bits. Fixes: fa09fa60385a ("ASoC: mchp-spdifrx: fix controls which rely on rsr register") Signed-off-by: bui duc phuc Link: https://patch.msgid.link/20261120035939.12774-3-phucduc.bui@gmail.com Signed-off-by: Mark Brown --- sound/soc/atmel/mchp-spdifrx.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sound/soc/atmel/mchp-spdifrx.c b/sound/soc/atmel/mchp-spdifrx.c index 80a64af0878b5a..19be9311136178 100644 --- a/sound/soc/atmel/mchp-spdifrx.c +++ b/sound/soc/atmel/mchp-spdifrx.c @@ -502,7 +502,9 @@ static int mchp_spdifrx_hw_params(struct snd_pcm_substream *substream, dev_dbg(dev->dev, "GCLK range min set to %d\n", params_rate(params) * SPDIFRX_GCLK_RATIO_MIN + 1); - ret = regmap_write(dev->regmap, SPDIFRX_MR, mr); + ret = regmap_update_bits(dev->regmap, SPDIFRX_MR, + SPDIFRX_MR_ENDIAN_MASK | SPDIFRX_MR_DATAWIDTH_MASK, + mr); unlock: mutex_unlock(&dev->mlock); From c292fb07f795c191f240e7faed8144f81f880d40 Mon Sep 17 00:00:00 2001 From: Poojitha N Date: Mon, 30 Nov 2026 20:49:42 +0530 Subject: [PATCH 2060/2102] ASoC: amd: acp: add RT766 SoundWire machine entries for ACP7.F Add RT766 SDCA codec support to the ACP7.F SoundWire machine table. The codec sits on link 0 and exposes jack, amp and DMIC endpoints. Add adr_device and link_adr descriptors for the two supported RT766 revisions, which differ only in the version field of the SoundWire device address: rt766_VA0_l0 -> 0x000030025d076601 (version 3) rt766_VA1_l0 -> 0x000040025d076601 (version 4) Select SND_SOC_RT766_SDCA_SDW from the AMD SOF SoundWire machine driver option when SND_SOC_SDCA_CLASS is enabled, since the codec driver depends on it and a plain select would not satisfy that. Signed-off-by: Poojitha N Link: https://patch.msgid.link/20261130152104.3803413-1-npoojith@amd.com Signed-off-by: Mark Brown --- sound/soc/amd/acp/Kconfig | 1 + sound/soc/amd/acp/amd-acp7x-acpi-match.c | 52 ++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/sound/soc/amd/acp/Kconfig b/sound/soc/amd/acp/Kconfig index 1b492a9ab58237..23ce610eabce3a 100644 --- a/sound/soc/amd/acp/Kconfig +++ b/sound/soc/amd/acp/Kconfig @@ -158,6 +158,7 @@ config SND_SOC_AMD_SOF_SDW_MACH select SND_SOC_RT715_SDW select SND_SOC_RT715_SDCA_SDW select SND_SOC_RT722_SDCA_SDW + select SND_SOC_RT766_SDCA_SDW if SND_SOC_SDCA_CLASS help This option enables SOF sound card support for SoundWire enabled AMD platforms along with ACP PDM controller. diff --git a/sound/soc/amd/acp/amd-acp7x-acpi-match.c b/sound/soc/amd/acp/amd-acp7x-acpi-match.c index b71060c9ecb016..a71f8a7929962e 100644 --- a/sound/soc/amd/acp/amd-acp7x-acpi-match.c +++ b/sound/soc/amd/acp/amd-acp7x-acpi-match.c @@ -131,6 +131,42 @@ static const struct snd_soc_acpi_link_adr acp7x_rt722_only[] = { {} }; +static const struct snd_soc_acpi_adr_device rt766_VA0_l0[] = { + { + .adr = 0x000030025d076601ull, + .num_endpoints = ARRAY_SIZE(jack_amp_dmic_endpoints), + .endpoints = jack_amp_dmic_endpoints, + .name_prefix = "rt766" + } +}; + +static const struct snd_soc_acpi_link_adr acp7x_rt766_VA0_l0[] = { + { + .mask = BIT(0), + .num_adr = ARRAY_SIZE(rt766_VA0_l0), + .adr_d = rt766_VA0_l0, + }, + {} +}; + +static const struct snd_soc_acpi_adr_device rt766_VA1_l0[] = { + { + .adr = 0x000040025d076601ull, + .num_endpoints = ARRAY_SIZE(jack_amp_dmic_endpoints), + .endpoints = jack_amp_dmic_endpoints, + .name_prefix = "rt766" + } +}; + +static const struct snd_soc_acpi_link_adr acp7x_rt766_VA1_l0[] = { + { + .mask = BIT(0), + .num_adr = ARRAY_SIZE(rt766_VA1_l0), + .adr_d = rt766_VA1_l0, + }, + {} +}; + static const struct snd_soc_acpi_adr_device rt1320_l1_single_adr[] = { { .adr = 0x000130025d132001ull, @@ -553,6 +589,22 @@ struct snd_soc_acpi_mach snd_soc_acpi_amd_acp7f_sof_sdw_machines[] = { .fw_filename = "sof-acp7f.ri", .get_function_tplg_files = amd_sof_sdw_get_tplg_files, }, + { + .link_mask = BIT(0), + .links = acp7x_rt766_VA0_l0, + .drv_name = "amd_sof_sdw", + .sof_tplg_filename = "sof-acp7f-rt766-l0.tplg", + .fw_filename = "sof-acp7f.ri", + .get_function_tplg_files = amd_sof_sdw_get_tplg_files, + }, + { + .link_mask = BIT(0), + .links = acp7x_rt766_VA1_l0, + .drv_name = "amd_sof_sdw", + .sof_tplg_filename = "sof-acp7f-rt766-l0.tplg", + .fw_filename = "sof-acp7f.ri", + .get_function_tplg_files = amd_sof_sdw_get_tplg_files, + }, { .link_mask = BIT(0) | BIT(1), .links = acp7x_cs42l43_l0u0_cs35l56x4_l1u3210, From c3409cbf70ac824510c011f1874fe13ef11c71d2 Mon Sep 17 00:00:00 2001 From: Zhangfei Gao Date: Mon, 30 Nov 2026 18:02:28 +0800 Subject: [PATCH 2061/2102] ASoC: qcom: audioreach: support multichannel PCM formats AudioReach currently rejects PCM streams with more than four channels in the PCM and shared-memory media format paths. This prevents TDM links that expose more channels, such as the 6-channel playback path used on SA8797P Ride, from being configured. Reuse q6dsp_map_channels() to support multichannel PCM formats and use the common PCM channel limit definition. Reviewed-by: Prasad Kumpatla Reviewed-by: Srinivas Kandagatla Tested-by: Shawn Guo Signed-off-by: Zhangfei Gao Link: https://patch.msgid.link/20261130100228.3121617-1-zhangfei.gao@oss.qualcomm.com Signed-off-by: Mark Brown --- sound/soc/qcom/qdsp6/audioreach.c | 36 ++++--------------------- sound/soc/qcom/qdsp6/audioreach.h | 5 ++-- sound/soc/qcom/qdsp6/q6apm-dai.c | 12 ++++++--- sound/soc/qcom/qdsp6/q6apm-lpass-dais.c | 16 +++++------ 4 files changed, 24 insertions(+), 45 deletions(-) diff --git a/sound/soc/qcom/qdsp6/audioreach.c b/sound/soc/qcom/qdsp6/audioreach.c index aa1f4e29676474..5b5289bf6d1393 100644 --- a/sound/soc/qcom/qdsp6/audioreach.c +++ b/sound/soc/qcom/qdsp6/audioreach.c @@ -306,22 +306,6 @@ void *audioreach_alloc_apm_cmd_pkt(int pkt_size, uint32_t opcode, uint32_t token } EXPORT_SYMBOL_GPL(audioreach_alloc_apm_cmd_pkt); -void audioreach_set_default_channel_mapping(u8 *ch_map, int num_channels) -{ - if (num_channels == 1) { - ch_map[0] = PCM_CHANNEL_FL; - } else if (num_channels == 2) { - ch_map[0] = PCM_CHANNEL_FL; - ch_map[1] = PCM_CHANNEL_FR; - } else if (num_channels == 4) { - ch_map[0] = PCM_CHANNEL_FL; - ch_map[1] = PCM_CHANNEL_FR; - ch_map[2] = PCM_CHANNEL_LS; - ch_map[3] = PCM_CHANNEL_RS; - } -} -EXPORT_SYMBOL_GPL(audioreach_set_default_channel_mapping); - static void apm_populate_container_config(struct apm_container_obj *cfg, const struct audioreach_container *cont) { @@ -760,7 +744,7 @@ static int audioreach_codec_dma_set_media_format(struct q6apm_graph *graph, intf_cfg->cfg.intf_index = module->hw_interface_idx; intf_cfg->cfg.active_channels_mask = 0; /* Convert the physical channel mapping into a bit field */ - for (i = 0; i < AR_PCM_MAX_NUM_CHANNEL; i++) + for (i = 0; i < PCM_MAX_NUM_CHANNEL; i++) if (cfg->channel_map[i]) intf_cfg->cfg.active_channels_mask |= BIT(i); @@ -883,7 +867,7 @@ static int audioreach_mfc_set_media_format(struct q6apm_graph *graph, media_format->bit_width = cfg->bit_width; media_format->num_channels = cfg->num_channels; /* Convert the physical mapping to a logical mapping of the channels */ - for (i = 0, j = 0; i < AR_PCM_MAX_NUM_CHANNEL && j < cfg->num_channels; i++) { + for (i = 0, j = 0; i < PCM_MAX_NUM_CHANNEL && j < cfg->num_channels; i++) { if (!cfg->channel_map[i]) continue; media_format->channel_mapping[j++] = cfg->channel_map[i]; @@ -1185,11 +1169,6 @@ static int audioreach_pcm_set_media_format(struct q6apm_graph *graph, int payload_size; int i, j; - if (num_channels > 4) { - dev_err(graph->dev, "Error: Invalid channels (%d)!\n", num_channels); - return -EINVAL; - } - payload_size = APM_PCM_MODULE_FMT_CMD_PSIZE(num_channels); struct gpr_pkt *pkt __free(kfree) = @@ -1223,7 +1202,7 @@ static int audioreach_pcm_set_media_format(struct q6apm_graph *graph, */ media_cfg->bits_per_sample = mcfg->bit_width == 24 ? 32 : mcfg->bit_width; /* Convert the physical mapping to a logical mapping of the channels */ - for (i = 0, j = 0; i < AR_PCM_MAX_NUM_CHANNEL && j < mcfg->num_channels; i++) { + for (i = 0, j = 0; i < PCM_MAX_NUM_CHANNEL && j < mcfg->num_channels; i++) { if (!mcfg->channel_map[i]) continue; media_cfg->channel_mapping[j++] = mcfg->channel_map[i]; @@ -1280,11 +1259,6 @@ static int audioreach_shmem_set_media_format(struct q6apm_graph *graph, int i, j; void *p; - if (num_channels > 4) { - dev_err(graph->dev, "Error: Invalid channels (%d)!\n", num_channels); - return -EINVAL; - } - payload_size = APM_SHMEM_FMT_CFG_PSIZE(num_channels) + APM_MODULE_PARAM_DATA_SIZE; struct gpr_pkt *pkt __free(kfree) = @@ -1319,7 +1293,7 @@ static int audioreach_shmem_set_media_format(struct q6apm_graph *graph, cfg->endianness = PCM_LITTLE_ENDIAN; cfg->num_channels = mcfg->num_channels; /* Convert the physical mapping to a logical mapping of the channels */ - for (i = 0, j = 0; i < AR_PCM_MAX_NUM_CHANNEL && j < cfg->num_channels; i++) { + for (i = 0, j = 0; i < PCM_MAX_NUM_CHANNEL && j < cfg->num_channels; i++) { if (!mcfg->channel_map[i]) continue; cfg->channel_mapping[j++] = mcfg->channel_map[i]; @@ -1442,7 +1416,7 @@ static int audioreach_speaker_protection_vi(struct q6apm_graph *graph, cm_cfg->cfg.num_channels = num_channels * 2; /* Convert the physical mapping to a logical mapping of the channels */ - for (i = 0, j = 0; i < AR_PCM_MAX_NUM_CHANNEL && j < num_channels; i++) { + for (i = 0, j = 0; i < PCM_MAX_NUM_CHANNEL && j < num_channels; i++) { if (!mcfg->channel_map[i]) continue; /* diff --git a/sound/soc/qcom/qdsp6/audioreach.h b/sound/soc/qcom/qdsp6/audioreach.h index 0a50b933773826..542775f493f108 100644 --- a/sound/soc/qcom/qdsp6/audioreach.h +++ b/sound/soc/qcom/qdsp6/audioreach.h @@ -6,6 +6,7 @@ #include #include #include +#include "q6dsp-common.h" struct q6apm; struct q6apm_graph; @@ -805,7 +806,6 @@ struct param_id_hw_ep_power_mode_cfg { #define PARAM_ID_HW_EP_DMA_DATA_ALIGN 0x08001233 #define AR_HW_EP_DMA_DATA_ALIGN_MSB 0 #define AR_HW_EP_DMA_DATA_ALIGN_LSB 1 -#define AR_PCM_MAX_NUM_CHANNEL 8 struct param_id_hw_ep_dma_data_align { uint32_t dma_data_align; @@ -998,7 +998,7 @@ struct audioreach_module_config { u16 nslots_per_frame; u16 slot_width; struct snd_codec codec; - u8 channel_map[AR_PCM_MAX_NUM_CHANNEL]; + u8 channel_map[PCM_MAX_NUM_CHANNEL]; }; /* Packet Allocation routines */ @@ -1009,7 +1009,6 @@ static inline u16 audioreach_gpr_dest_domain(gpr_device_t *gdev) void *audioreach_alloc_apm_cmd_pkt(int pkt_size, uint32_t opcode, uint32_t token); -void audioreach_set_default_channel_mapping(u8 *ch_map, int num_channels); void *audioreach_alloc_cmd_pkt(int payload_size, uint32_t opcode, uint32_t token, uint32_t src_port, uint32_t dest_port); diff --git a/sound/soc/qcom/qdsp6/q6apm-dai.c b/sound/soc/qcom/qdsp6/q6apm-dai.c index 362f306790200e..3d667d7c612e26 100644 --- a/sound/soc/qcom/qdsp6/q6apm-dai.c +++ b/sound/soc/qcom/qdsp6/q6apm-dai.c @@ -21,6 +21,7 @@ #include #include #include "q6apm.h" +#include "q6dsp-common.h" #define DRV_NAME "q6apm-dai" #define POS_BUFFER_BYTES 4096 @@ -354,7 +355,10 @@ static int q6apm_dai_prepare(struct snd_soc_component *component, cfg.num_channels = runtime->channels; cfg.bit_width = prtd->bits_per_sample; cfg.fmt = SND_AUDIOCODEC_PCM; - audioreach_set_default_channel_mapping(cfg.channel_map, runtime->channels); + ret = q6dsp_map_channels(cfg.channel_map, runtime->channels); + if (ret) + return ret; + /* * A second prepare finds the stream running. Stop .ack from queueing * while the graph and its buffers are replaced. @@ -1156,8 +1160,10 @@ static int q6apm_dai_compr_set_params(struct snd_soc_component *component, cfg.num_channels = 2; cfg.bit_width = prtd->bits_per_sample; cfg.fmt = codec->id; - audioreach_set_default_channel_mapping(cfg.channel_map, - cfg.num_channels); + ret = q6dsp_map_channels(cfg.channel_map, cfg.num_channels); + if (ret) + return ret; + memcpy(&cfg.codec, codec, sizeof(*codec)); ret = q6apm_graph_media_format_shmem(prtd->graph, &cfg); diff --git a/sound/soc/qcom/qdsp6/q6apm-lpass-dais.c b/sound/soc/qcom/qdsp6/q6apm-lpass-dais.c index c63622629f1515..d43d97d1384101 100644 --- a/sound/soc/qcom/qdsp6/q6apm-lpass-dais.c +++ b/sound/soc/qcom/qdsp6/q6apm-lpass-dais.c @@ -94,7 +94,7 @@ static int q6dma_set_channel_map(struct snd_soc_dai *dai, return -EINVAL; } - if (tx_num > AR_PCM_MAX_NUM_CHANNEL) { + if (tx_num > PCM_MAX_NUM_CHANNEL) { dev_err(dai->dev, "invalid tx num %d\n", tx_num); return -EINVAL; @@ -147,7 +147,9 @@ static int q6hdmi_hw_params(struct snd_pcm_substream *substream, cfg->bit_width = params_width(params); cfg->sample_rate = params_rate(params); cfg->num_channels = channels; - audioreach_set_default_channel_mapping(cfg->channel_map, channels); + ret = q6dsp_map_channels(cfg->channel_map, channels); + if (ret) + return ret; switch (dai->id) { case DISPLAY_PORT_RX_0: @@ -173,16 +175,14 @@ static int q6dma_hw_params(struct snd_pcm_substream *substream, struct q6apm_lpass_dai_data *dai_data = dev_get_drvdata(dai->dev); struct audioreach_module_config *cfg = &dai_data->module_config[dai->id]; int channels = hw_param_interval_c(params, SNDRV_PCM_HW_PARAM_CHANNELS)->max; - int i; + int ret; cfg->bit_width = params_width(params); cfg->sample_rate = params_rate(params); cfg->num_channels = channels; - memset(cfg->channel_map, 0, sizeof(cfg->channel_map)); - audioreach_set_default_channel_mapping(cfg->channel_map, channels); - for (i = 0; i < channels && i < AR_PCM_MAX_NUM_CHANNEL; i++) - if (!cfg->channel_map[i]) - cfg->channel_map[i] = i + 1; + ret = q6dsp_map_channels(cfg->channel_map, channels); + if (ret) + return ret; return 0; } From b56386b4c09affecce17d8b5a3a14ee656bddec3 Mon Sep 17 00:00:00 2001 From: Nathan Chancellor Date: Sat, 28 Nov 2026 15:21:48 -0700 Subject: [PATCH 2062/2102] regmap: Make reg_field's definition always visible When building without CONFIG_REGMAP, there are a few warnings/errors from stubs because 'struct reg_field' is only defined in a CONFIG_REGMAP=y block. In file included from drivers/regulator/helpers.c:13: include/linux/regmap.h:2108:53: warning: 'struct reg_field' declared inside parameter list will not be visible outside of this definition or declaration 2108 | regmap_reg_field_read(struct regmap *regmap, struct reg_field field, | ^~~~~~~~~ include/linux/regmap.h:2108:63: error: parameter 2 ('field') has incomplete type 2108 | regmap_reg_field_read(struct regmap *regmap, struct reg_field field, | ~~~~~~~~~~~~~~~~~^~~~~ include/linux/regmap.h:2108:1: error: function declaration isn't a prototype [-Werror=strict-prototypes] 2108 | regmap_reg_field_read(struct regmap *regmap, struct reg_field field, | ^~~~~~~~~~~~~~~~~~~~~ include/linux/regmap.h:2116:54: warning: 'struct reg_field' declared inside parameter list will not be visible outside of this definition or declaration 2116 | regmap_reg_field_write(struct regmap *regmap, struct reg_field field, | ^~~~~~~~~ include/linux/regmap.h:2116:64: error: parameter 2 ('field') has incomplete type 2116 | regmap_reg_field_write(struct regmap *regmap, struct reg_field field, | ~~~~~~~~~~~~~~~~~^~~~~ include/linux/regmap.h:2116:1: error: function declaration isn't a prototype [-Werror=strict-prototypes] 2116 | regmap_reg_field_write(struct regmap *regmap, struct reg_field field, | ^~~~~~~~~~~~~~~~~~~~~~ cc1: some warnings being treated as errors Move the definition of 'struct reg_field' out of the CONFIG_REGMAP block so that it is always defined, clearing up the errors. Fixes: 39e628387d32 ("regmap: add regmap_reg_field_* APIs") Signed-off-by: Nathan Chancellor Link: https://patch.msgid.link/20261128-regmap-fix-wvisibility-v1-1-9b53e2e85e47@kernel.org Signed-off-by: Mark Brown --- include/linux/regmap.h | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/include/linux/regmap.h b/include/linux/regmap.h index 6194948ff9ed89..ab43fb603c8070 100644 --- a/include/linux/regmap.h +++ b/include/linux/regmap.h @@ -212,6 +212,23 @@ struct reg_sequence { __ret ?: __tmp; \ }) +/** + * struct reg_field - Description of an register field + * + * @reg: Offset of the register within the regmap bank + * @lsb: lsb of the register field. + * @msb: msb of the register field. + * @id_size: port size if it has some ports + * @id_offset: address offset for each ports + */ +struct reg_field { + unsigned int reg; + unsigned int lsb; + unsigned int msb; + unsigned int id_size; + unsigned int id_offset; +}; + #ifdef CONFIG_REGMAP enum regmap_endian { @@ -1454,23 +1471,6 @@ static inline int regmap_assign_bits(struct regmap *map, unsigned int reg, int regmap_test_bits(struct regmap *map, unsigned int reg, unsigned int bits); -/** - * struct reg_field - Description of an register field - * - * @reg: Offset of the register within the regmap bank - * @lsb: lsb of the register field. - * @msb: msb of the register field. - * @id_size: port size if it has some ports - * @id_offset: address offset for each ports - */ -struct reg_field { - unsigned int reg; - unsigned int lsb; - unsigned int msb; - unsigned int id_size; - unsigned int id_offset; -}; - #define REG_FIELD(_reg, _lsb, _msb) ((struct reg_field){ \ .reg = _reg, \ .lsb = _lsb, \ From dccd5c63dd3715163dc9c94b6a53b6d1ba9689e3 Mon Sep 17 00:00:00 2001 From: Manuel Ebner Date: Mon, 30 Nov 2026 10:29:32 +0100 Subject: [PATCH 2063/2102] ASoC: SOF: fix kernel-doc Remove 'of' for correct kernel-doc notation, fixing: $ ./scripts/kernel-doc --none sound/soc/sof/ipc4-fw-reg.h Warning: sound/soc/sof/ipc4-fw-reg.h:68 expecting prototype for struct of. Prototype was for struct sof_ipc4_llp_reading_extended instead Signed-off-by: Manuel Ebner Link: https://patch.msgid.link/20261130092932.1812155-2-manuelebnerli@mailbox.org Signed-off-by: Mark Brown --- sound/soc/sof/ipc4-fw-reg.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/sof/ipc4-fw-reg.h b/sound/soc/sof/ipc4-fw-reg.h index 7b85a364a6a6c4..b8d1588169c028 100644 --- a/sound/soc/sof/ipc4-fw-reg.h +++ b/sound/soc/sof/ipc4-fw-reg.h @@ -57,7 +57,7 @@ struct sof_ipc4_llp_reading { } __packed __aligned(4); /** - * struct of sof_ipc4_llp_reading_extended - Extended llp info + * struct sof_ipc4_llp_reading_extended - Extended llp info * @llp_reading: Llp information in memory window * @tpd_low: Total processed data (low part) * @tpd_high: Total processed data (high part) From edf7d974a5ce36dc50d240d66c16ef3ec504574b Mon Sep 17 00:00:00 2001 From: Yuwei Chen <2522445001@qq.com> Date: Mon, 30 Nov 2026 14:28:24 +0800 Subject: [PATCH 2064/2102] ASoC: kirkwood: armada-370-db: fix device node leak in probe a370db_probe() takes four of_parse_phandle() references and never calls of_node_put(). The marvell,audio-controller node is parsed once and stored in every link's CPU and platform fields, so it is one reference. Each marvell,audio-codec index is its own reference. Register one devres action after each successful parse. A missing phandle still stores NULL and probe continues. These actions are added before devm_snd_soc_register_card(), so on unbind snd_soc_unregister_card() runs before of_node_put(). Fixes: 74d04c3efbc4 ("sound: ASoC: add ASoC board driver for Armada 370 DB") Fixes: cece5656901f ("ASoC: add S/PDIF support to Armada 370 DB ASoC driver") Cc: stable@vger.kernel.org Signed-off-by: Yuwei Chen <2522445001@qq.com> Link: https://patch.msgid.link/tencent_86B07AD72DAA64FF2CB4325A9765543C0506@qq.com Signed-off-by: Mark Brown --- sound/soc/kirkwood/armada-370-db.c | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/sound/soc/kirkwood/armada-370-db.c b/sound/soc/kirkwood/armada-370-db.c index 77a5f440364e43..a60aa78d316e0b 100644 --- a/sound/soc/kirkwood/armada-370-db.c +++ b/sound/soc/kirkwood/armada-370-db.c @@ -102,9 +102,15 @@ static struct snd_soc_card a370db = { .num_dapm_routes = ARRAY_SIZE(a370db_route), }; +static void a370db_of_node_put(void *np) +{ + of_node_put(np); +} + static int a370db_probe(struct platform_device *pdev) { struct snd_soc_card *card = &a370db; + int ret; card->dev = &pdev->dev; @@ -112,10 +118,22 @@ static int a370db_probe(struct platform_device *pdev) of_parse_phandle(pdev->dev.of_node, "marvell,audio-controller", 0); a370db_dai[0].platforms->of_node = a370db_dai[0].cpus->of_node; + if (a370db_dai[0].cpus->of_node) { + ret = devm_add_action_or_reset(&pdev->dev, a370db_of_node_put, + a370db_dai[0].cpus->of_node); + if (ret) + return ret; + } a370db_dai[0].codecs->of_node = of_parse_phandle(pdev->dev.of_node, "marvell,audio-codec", 0); + if (a370db_dai[0].codecs->of_node) { + ret = devm_add_action_or_reset(&pdev->dev, a370db_of_node_put, + a370db_dai[0].codecs->of_node); + if (ret) + return ret; + } a370db_dai[1].cpus->of_node = a370db_dai[0].cpus->of_node; a370db_dai[1].platforms->of_node = a370db_dai[0].cpus->of_node; @@ -123,6 +141,12 @@ static int a370db_probe(struct platform_device *pdev) a370db_dai[1].codecs->of_node = of_parse_phandle(pdev->dev.of_node, "marvell,audio-codec", 1); + if (a370db_dai[1].codecs->of_node) { + ret = devm_add_action_or_reset(&pdev->dev, a370db_of_node_put, + a370db_dai[1].codecs->of_node); + if (ret) + return ret; + } a370db_dai[2].cpus->of_node = a370db_dai[0].cpus->of_node; a370db_dai[2].platforms->of_node = a370db_dai[0].cpus->of_node; @@ -130,6 +154,12 @@ static int a370db_probe(struct platform_device *pdev) a370db_dai[2].codecs->of_node = of_parse_phandle(pdev->dev.of_node, "marvell,audio-codec", 2); + if (a370db_dai[2].codecs->of_node) { + ret = devm_add_action_or_reset(&pdev->dev, a370db_of_node_put, + a370db_dai[2].codecs->of_node); + if (ret) + return ret; + } return devm_snd_soc_register_card(card->dev, card); } From 1306d7b3c9e57d1587b70e32a5817c53941650e2 Mon Sep 17 00:00:00 2001 From: Li Jun Date: Mon, 30 Nov 2026 16:00:38 +0800 Subject: [PATCH 2065/2102] ASoC: loongson: Check sysclk in hw_params loongson_i2s_hw_params() uses i2s->sysclk as a divisor when computing the bclk and mclk ratios, so a zero sysclk would cause a division by zero. Return -EINVAL before the revision switch when sysclk is zero. Fixes: d84881e06836 ("ASoC: Add support for Loongson I2S controller") Signed-off-by: Li Jun Link: https://patch.msgid.link/20261130080038.789541-1-lijun01@kylinos.cn Signed-off-by: Mark Brown --- sound/soc/loongson/loongson_i2s.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sound/soc/loongson/loongson_i2s.c b/sound/soc/loongson/loongson_i2s.c index 438bbae0888f81..76741ec139fe76 100644 --- a/sound/soc/loongson/loongson_i2s.c +++ b/sound/soc/loongson/loongson_i2s.c @@ -73,6 +73,11 @@ static int loongson_i2s_hw_params(struct snd_pcm_substream *substream, u32 mask; u32 val = 0; + if (!sysclk) { + dev_err(i2s->dev, "invalid sysclk\n"); + return -EINVAL; + } + switch (i2s->rev_id) { case 0: bclk_ratio = DIV_ROUND_CLOSEST(clk_rate, From 16ff7b03696f0a5a5fc26e6b2d557b864eec9f17 Mon Sep 17 00:00:00 2001 From: Chancel Liu Date: Mon, 30 Nov 2026 10:54:44 +0900 Subject: [PATCH 2066/2102] ASoC: fsl_mqs: Remove unnecessary semicolons Remove unnecessary semicolons after the fsl_mqs_sm_read() and fsl_mqs_sm_write() function definitions. Signed-off-by: Chancel Liu Link: https://patch.msgid.link/20261130-for-next-v1-1-378732659693@nxp.com Signed-off-by: Mark Brown --- sound/soc/fsl/fsl_mqs.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sound/soc/fsl/fsl_mqs.c b/sound/soc/fsl/fsl_mqs.c index fd4a5f4a56bed8..ce12cc79b9c49c 100644 --- a/sound/soc/fsl/fsl_mqs.c +++ b/sound/soc/fsl/fsl_mqs.c @@ -87,7 +87,7 @@ static int fsl_mqs_sm_read(void *context, unsigned int reg, unsigned int *val) return scmi_imx_misc_ctrl_get(mqs_priv->soc->sm_index, &num, val); return -EINVAL; -}; +} static int fsl_mqs_sm_write(void *context, unsigned int reg, unsigned int val) { @@ -98,7 +98,7 @@ static int fsl_mqs_sm_write(void *context, unsigned int reg, unsigned int val) return scmi_imx_misc_ctrl_set(mqs_priv->soc->sm_index, val); return -EINVAL; -}; +} static int fsl_mqs_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, From 4c09bd928bfadbb68e0ab621c17f9add2573f400 Mon Sep 17 00:00:00 2001 From: Chancel Liu Date: Mon, 30 Nov 2026 10:54:45 +0900 Subject: [PATCH 2067/2102] ASoC: fsl_mqs: Disable runtime PM on probe failure Disable runtime PM if the ASoC component registration fails to keep the probe error path balanced. Signed-off-by: Chancel Liu Fixes: 9e28f6532c61 ("ASoC: fsl_mqs: Add MQS component driver") Link: https://patch.msgid.link/20261130-for-next-v1-2-378732659693@nxp.com Signed-off-by: Mark Brown --- sound/soc/fsl/fsl_mqs.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/sound/soc/fsl/fsl_mqs.c b/sound/soc/fsl/fsl_mqs.c index ce12cc79b9c49c..b171120952aad0 100644 --- a/sound/soc/fsl/fsl_mqs.c +++ b/sound/soc/fsl/fsl_mqs.c @@ -312,9 +312,14 @@ static int fsl_mqs_probe(struct platform_device *pdev) ret = devm_snd_soc_register_component(&pdev->dev, &soc_codec_fsl_mqs, &fsl_mqs_dai, 1); if (ret) - return ret; + goto err_pm_disable; return 0; + +err_pm_disable: + pm_runtime_disable(&pdev->dev); + + return ret; } static void fsl_mqs_remove(struct platform_device *pdev) From bace70c91d6c6015036c574841bc569a13861fcc Mon Sep 17 00:00:00 2001 From: Gianfranco Mariotti Date: Mon, 30 Nov 2026 02:20:12 +0100 Subject: [PATCH 2068/2102] ASoC: dt-bindings: qcom,sm8250: add arduino,monza-sndcard compatible Arduino VENTUNO Q (Monza) uses a board-specific MAX98091 analog audio topology that should not be tied to the generic "qcom,qcs8275-sndcard" compatible shared by other QCS8275 boards such as Monaco EVK. Add "arduino,monza-sndcard" with "qcom,qcs8275-sndcard" as fallback so the Monza sound card can match its own board configuration while keeping forward and backward Device Tree compatibility. Fixes: 4ba2678ad03e ("ASoC: qcom: sc8280xp: add monaco/monza controls for qcs8275") Signed-off-by: Gianfranco Mariotti Link: https://patch.msgid.link/20261130012014.181326-2-gianfranco.mariotti94@gmail.com Signed-off-by: Mark Brown --- Documentation/devicetree/bindings/sound/qcom,sm8250.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml b/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml index e2e3fc99e6d9a0..dadefd41ae8be5 100644 --- a/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml +++ b/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml @@ -16,6 +16,9 @@ description: properties: compatible: oneOf: + - items: + - const: arduino,monza-sndcard + - const: qcom,qcs8275-sndcard - items: - enum: - lenovo,yoga-c630-sndcard From 9ad29504a610161bc226382e88cc89792bba7627 Mon Sep 17 00:00:00 2001 From: Gianfranco Mariotti Date: Mon, 30 Nov 2026 02:20:13 +0100 Subject: [PATCH 2069/2102] ASoC: qcom: sc8280xp: move Arduino Monza config out of qcs8275_priv_data Commit 4ba2678ad03e ("ASoC: qcom: sc8280xp: add monaco/monza controls for qcs8275") attached Arduino VENTUNO Q (Monza) MAX98090 widgets, pin switches, DAI format, and 256*fs codec sysclk setup directly to qcs8275_priv_data, which backs the generic "qcom,qcs8275-sndcard" compatible already used by Monaco EVK, Monaco AC EVK, and other QCS8275 carrier boards. On non-Monza QCS8275 boards this causes multiple regressions: - Replaces sc8280xp_dapm_widgets with max98090_dapm_widgets and adds max98090_controls, exposing six nonexistent MAX98090 pin switches on Monaco EVK / Monaco AC EVK, colliding with max98357a's "Speaker" DAPM widget, and dropping the "DP0 Jack".."DP7 Jack" widgets. - Forces codec_sysclk_set (256 * rate on MI2S, bitclock rate on TDM) and codec_dai_fmt (I2S | NB_NF | BC_FC) onto every QCS8275 board's codecs, breaking codecs clocked from a different MCLK rate or DAI format. Move the MAX98090 configuration to a dedicated monza_priv_data entry bound to "arduino,monza-sndcard" and restore qcs8275_priv_data to the generic QCS8275 defaults while keeping LPI_MI2S DAI ID handling in sc8280xp_snd_hw_params(). Fall back to monza_priv_data when matching "qcom,qcs8275-sndcard" on an "arduino,monza" machine so existing DTBs continue to work. Fixes: 4ba2678ad03e ("ASoC: qcom: sc8280xp: add monaco/monza controls for qcs8275") Signed-off-by: Gianfranco Mariotti Link: https://patch.msgid.link/20261130012014.181326-3-gianfranco.mariotti94@gmail.com Signed-off-by: Mark Brown --- sound/soc/qcom/sc8280xp.c | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/sound/soc/qcom/sc8280xp.c b/sound/soc/qcom/sc8280xp.c index e136407c56bfdd..874b4a19c78ac3 100644 --- a/sound/soc/qcom/sc8280xp.c +++ b/sound/soc/qcom/sc8280xp.c @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -522,6 +523,9 @@ static void sc8280xp_add_be_ops(struct snd_soc_card *card) } } +static const struct qcom_snd_soc_common monza_priv_data; +static const struct qcom_snd_soc_common qcs8275_priv_data; + static int sc8280xp_platform_probe(struct platform_device *pdev) { struct snd_soc_card *card; @@ -542,6 +546,15 @@ static int sc8280xp_platform_probe(struct platform_device *pdev) if (!data->priv) return -ENODEV; + /* + * Legacy monaco-arduino-monza DTBs used the generic + * "qcom,qcs8275-sndcard" compatible before "arduino,monza-sndcard" + * was introduced. + */ + if (data->priv == &qcs8275_priv_data && + of_machine_is_compatible("arduino,monza")) + data->priv = &monza_priv_data; + card->owner = THIS_MODULE; card->dev = dev; dev_set_drvdata(dev, card); @@ -602,6 +615,18 @@ static const struct qcom_snd_soc_common maili_priv_data = { .wcd_jack = true, }; +static const struct qcom_snd_soc_common monza_priv_data = { + .driver_name = "qcs8300", + .dapm_widgets = max98090_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(max98090_dapm_widgets), + .controls = max98090_controls, + .num_controls = ARRAY_SIZE(max98090_controls), + .codec_sysclk_set = true, + .codec_dai_fmt = SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_I2S | + SND_SOC_DAIFMT_BC_FC, +}; + static const struct qcom_snd_soc_common nord_priv_data = { .driver_name = "nord", .mi2s_bclk_enable = true, @@ -662,12 +687,8 @@ static const struct qcom_snd_soc_common rubikpi3_priv_data = { static const struct qcom_snd_soc_common qcs8275_priv_data = { .driver_name = "qcs8300", - .dapm_widgets = max98090_dapm_widgets, - .num_dapm_widgets = ARRAY_SIZE(max98090_dapm_widgets), - .controls = max98090_controls, - .num_controls = ARRAY_SIZE(max98090_controls), - .codec_sysclk_set = true, - .codec_dai_fmt = SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_BC_FC, + .dapm_widgets = sc8280xp_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(sc8280xp_dapm_widgets), }; static const struct qcom_snd_soc_common sc8280xp_priv_data = { @@ -731,6 +752,7 @@ static const struct qcom_snd_soc_common sm8750_priv_data = { }; static const struct of_device_id snd_sc8280xp_dt_match[] = { + { .compatible = "arduino,monza-sndcard", .data = &monza_priv_data }, { .compatible = "ayaneo,pocket-s2-sndcard", .data = &ayaneo_ps2_priv_data }, { .compatible = "qcom,eliza-sndcard", .data = &eliza_priv_data }, { .compatible = "qcom,hawi-sndcard", .data = &hawi_priv_data }, From 6112677a4669683646ec0a73d8e4919573490e86 Mon Sep 17 00:00:00 2001 From: Juan Raul Rodriguez Gil Date: Sat, 28 Nov 2026 21:58:32 +0100 Subject: [PATCH 2070/2102] ASoC: amd: yc: Add DMI quirk for MSI Crosshair A16 HX D8WGKG Add DMI quirk entry for MSI Crosshair A16 HX D8WGKG (MS-15PL) to enable the internal digital microphone (DMIC) on the AMD Audio Coprocessor. Cc: stable@vger.kernel.org Signed-off-by: Juan Raul Rodriguez Gil Link: https://patch.msgid.link/20261128205832.18165-1-jrodriiguezgmaker@gmail.com Signed-off-by: Mark Brown --- sound/soc/amd/yc/acp6x-mach.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/sound/soc/amd/yc/acp6x-mach.c b/sound/soc/amd/yc/acp6x-mach.c index 88234f351f5376..505d481173ce8c 100644 --- a/sound/soc/amd/yc/acp6x-mach.c +++ b/sound/soc/amd/yc/acp6x-mach.c @@ -584,6 +584,13 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { DMI_MATCH(DMI_PRODUCT_NAME, "Crosshair A16 HX D7WFKG"), } }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International Co., Ltd."), + DMI_MATCH(DMI_PRODUCT_NAME, "Crosshair A16 HX D8WGKG"), + } + }, { .driver_data = &acp6x_card, .matches = { From dda6e32e2d13751fc482b23be233386ff71c154b Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Mon, 30 Nov 2026 12:34:45 +0000 Subject: [PATCH 2071/2102] ALSA: aoa: Return ENODEV when no sound card is available aoa_snd_device_new() returns -ENOMEM when aoa_get_card() returns NULL. This is misleading because the failure indicates that no ALSA card is available, not that memory allocation failed. Return -ENODEV instead to report the missing device correctly. Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261130123445.3060-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/aoa/core/alsa.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sound/aoa/core/alsa.c b/sound/aoa/core/alsa.c index aad7dfe089c7d8..bc7e576ab2794d 100644 --- a/sound/aoa/core/alsa.c +++ b/sound/aoa/core/alsa.c @@ -64,7 +64,8 @@ int aoa_snd_device_new(enum snd_device_type type, struct snd_card *card = aoa_get_card(); int err; - if (!card) return -ENOMEM; + if (!card) + return -ENODEV; err = snd_device_new(card, type, device_data, ops); if (err) { From 845129518de69bddff23a01d83ff3a9fcb8a25d2 Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Mon, 30 Nov 2026 13:13:10 +0000 Subject: [PATCH 2072/2102] ALSA: aoa: Fix GPIO notification IRQ cleanup The feature GPIO implementation checks gpio_private when cleaning up the line-in and line-out notification IRQs. However, ftr_set_notify() registers these IRQs using request_irq() and tracks the registered callbacks through the notify field. Check notify consistently for all notification IRQs so that registered line-in and line-out IRQs are released during teardown. Fixes: f3d9478b2ce4 ("[ALSA] snd-aoa: add snd-aoa") Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261130131310.3114-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/aoa/core/gpio-feature.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sound/aoa/core/gpio-feature.c b/sound/aoa/core/gpio-feature.c index 19ed0e6907da3f..2549b660caa450 100644 --- a/sound/aoa/core/gpio-feature.c +++ b/sound/aoa/core/gpio-feature.c @@ -285,9 +285,9 @@ static void ftr_gpio_exit(struct gpio_runtime *rt) rt->implementation_private = 0; if (rt->headphone_notify.notify) free_irq(headphone_detect_irq, &rt->headphone_notify); - if (rt->line_in_notify.gpio_private) + if (rt->line_in_notify.notify) free_irq(linein_detect_irq, &rt->line_in_notify); - if (rt->line_out_notify.gpio_private) + if (rt->line_out_notify.notify) free_irq(lineout_detect_irq, &rt->line_out_notify); cancel_delayed_work_sync(&rt->headphone_notify.work); cancel_delayed_work_sync(&rt->line_in_notify.work); From 190551e5be955d336466e840d3d8c5b6e49e475c Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Sat, 28 Nov 2026 08:52:35 +0000 Subject: [PATCH 2073/2102] ALSA: aoa: Fix codec unregister handling Fix aoa_codec_unregister() to use the codec's own fabric pointer when removing a codec. Previously, the function checked the global fabric pointer instead of codec->fabric. This could call the fabric's remove_codec() callback for a codec that was never attached to the fabric. The function also called module_put() unconditionally, even when attach_codec_to_fabric() had not acquired a module reference. This could cause an incorrect module reference count. Use aoa_fabric_unlink_codec() to detach an attached codec. This helper calls exit(), remove_codec(), and module_put() and clears codec->fabric. These operations are now performed only when the codec is actually attached to a fabric. This also prevents releasing the module reference a second time when codec initialization fails and the attach path has already cleaned up. Fixes: f3d9478b2ce4 ("[ALSA] snd-aoa: add snd-aoa") Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261128085235.2984-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/aoa/core/core.c | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/sound/aoa/core/core.c b/sound/aoa/core/core.c index 99b032a4081fd2..09eeadba4277f2 100644 --- a/sound/aoa/core/core.c +++ b/sound/aoa/core/core.c @@ -72,12 +72,9 @@ EXPORT_SYMBOL_GPL(aoa_codec_register); void aoa_codec_unregister(struct aoa_codec *codec) { list_del(&codec->list); - if (codec->fabric && codec->exit) - codec->exit(codec); - if (fabric && fabric->remove_codec) - fabric->remove_codec(codec); - codec->fabric = NULL; - module_put(codec->owner); + + if (codec->fabric) + aoa_fabric_unlink_codec(codec); } EXPORT_SYMBOL_GPL(aoa_codec_unregister); From d6ebd8296ae2cc6dc244ecf72e6086a3e1041067 Mon Sep 17 00:00:00 2001 From: Silvio Unkovic Date: Sat, 28 Nov 2026 02:22:30 +0100 Subject: [PATCH 2074/2102] ALSA: usb-audio: Add quirks for Sony PlayStation Eye The Sony PlayStation Eye camera (1415:2000) has a UAC1 four-microphone array capture interface with a single 16 kHz rate. Reading back the sampling frequency from its endpoint returns garbage (e.g. 33186, 17004 or 2199316 instead of 16000), producing a "current rate ... is different from the runtime rate" warning on every stream start. This was already reported in 2012 [1]. Set QUIRK_FLAG_GET_SAMPLE_RATE to skip the read. Its feature unit 3 advertises a per-channel volume control, but the device answers GET_MIN, GET_MAX, GET_RES and GET_CUR with a single zero byte instead of two bytes, so the driver logs "cannot get min/max values" and creates a "Mic Capture Volume" control with a fallback 0..1 range that returns -EINVAL on read. SET_CUR is accepted for any value, but the capture level does not change: with a fixed range forced in the driver, recordings stayed at the same level for every setting from -80 dB to +60 dB. Skip the control via a mixer map. [1] "Usb audio - unsuported sampling rates", alsa-devel, 2012-07-10 Assisted-by: Claude:claude-fable-5-2 Signed-off-by: Silvio Unkovic Link: https://patch.msgid.link/20261128-pseye-audio-v1-1-b751d7911847@pm.me Signed-off-by: Takashi Iwai --- sound/usb/mixer_maps.c | 16 ++++++++++++++++ sound/usb/quirks.c | 2 ++ 2 files changed, 18 insertions(+) diff --git a/sound/usb/mixer_maps.c b/sound/usb/mixer_maps.c index 9218ca6314ad79..26319ed0a1f76a 100644 --- a/sound/usb/mixer_maps.c +++ b/sound/usb/mixer_maps.c @@ -562,6 +562,17 @@ static const struct usbmix_name_map avermedia_gc553pro_map[] = { {} }; +/* + * Sony PlayStation Eye: FU 3 advertises per-channel volume for the four + * microphones, but the device answers GET_MIN, GET_MAX and GET_CUR with a + * single zero byte, and SET_CUR is accepted without changing the capture + * level. Skip the control. + */ +static const struct usbmix_name_map sony_ps_eye_map[] = { + { 3, NULL, UAC_FU_VOLUME }, + {} +}; + /* * Control map entries */ @@ -640,6 +651,11 @@ static const struct usbmix_ctl_map usbmix_ctl_maps[] = { .id = USB_ID(0x13e5, 0x0001), .map = scratch_live_map, }, + { + /* Sony PlayStation Eye */ + .id = USB_ID(0x1415, 0x2000), + .map = sony_ps_eye_map, + }, { .id = USB_ID(0x200c, 0x1018), .map = ebox44_map, diff --git a/sound/usb/quirks.c b/sound/usb/quirks.c index bd00db820719d6..ff2bfe8504f23b 100644 --- a/sound/usb/quirks.c +++ b/sound/usb/quirks.c @@ -2713,6 +2713,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { QUIRK_FLAG_PLAYBACK_FIRST | QUIRK_FLAG_GENERIC_IMPLICIT_FB), DEVICE_FLG(0x13e5, 0x0001, /* Serato Phono */ QUIRK_FLAG_IGNORE_CTL_ERROR), + DEVICE_FLG(0x1415, 0x2000, /* Sony PlayStation Eye */ + QUIRK_FLAG_GET_SAMPLE_RATE), DEVICE_FLG(0x152a, 0x85dd, /* SMSL USB DAC */ QUIRK_FLAG_DSD_RAW | QUIRK_FLAG_DISABLE_AUTOSUSPEND | QUIRK_FLAG_SKIP_IFACE_SETUP), From 0dadd356778dc05c46d20cc92723330fe6f5eeda Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Thu, 26 Nov 2026 07:22:20 +0000 Subject: [PATCH 2075/2102] ALSA: vmaster: Retry follower initialization on failure Reset the follower count when the initial follower update fails. This allows follower initialization to be retried on the next access. Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261126072220.4496-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/core/vmaster.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/sound/core/vmaster.c b/sound/core/vmaster.c index de4f1c14c53099..be4e64a5b2675f 100644 --- a/sound/core/vmaster.c +++ b/sound/core/vmaster.c @@ -102,7 +102,14 @@ static int follower_init(struct link_follower *follower) follower->info.min_val = uinfo->value.integer.min; follower->info.max_val = uinfo->value.integer.max; - return follower_update(follower); + err = follower_update(follower); + if (err < 0) { + /* allow initialization to be retried */ + follower->info.count = 0; + return err; + } + + return 0; } /* initialize master volume */ From c8af212af73c5fb9989de54747b2cb2b563ad663 Mon Sep 17 00:00:00 2001 From: Brian Harring Date: Thu, 19 Nov 2026 17:08:18 +0100 Subject: [PATCH 2076/2102] ALSA: usb-audio: Use ALC4080 mixer map for ASRock X870E Taichi The ASRock X870E Taichi / Taichi Lite onboard audio (26ce:0a0b, Realtek ALC4082) has the same problem as the MSI ALC4080 boards already using this map: all its playback feature units are named "PCM", so the UCM profile pairs the headphone volume with the rear output's mute. Its unit IDs match, so use the same map, renamed to alc408x_map now that it's no longer MSI-only. Signed-off-by: Brian Harring Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261119-alc4082-taichi-v2-1-03ad1352f807@gmail.com --- sound/usb/mixer_maps.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/sound/usb/mixer_maps.c b/sound/usb/mixer_maps.c index 26319ed0a1f76a..173bc218366f58 100644 --- a/sound/usb/mixer_maps.c +++ b/sound/usb/mixer_maps.c @@ -486,8 +486,8 @@ static const struct usbmix_name_map aorus_master_alc1220vb_map[] = { {} }; -/* MSI MPG X570S Carbon Max Wifi with ALC4080 */ -static const struct usbmix_name_map msi_mpg_x570s_carbon_max_wifi_alc4080_map[] = { +/* ALC4080/ALC4082 boards with this playback feature unit layout */ +static const struct usbmix_name_map alc408x_map[] = { { 29, "Speaker Playback" }, { 30, "Front Headphone Playback" }, { 32, "IEC958 Playback" }, @@ -786,15 +786,19 @@ static const struct usbmix_ctl_map usbmix_ctl_maps[] = { }, { /* MSI MPG X570S Carbon Max Wifi */ .id = USB_ID(0x0db0, 0x419c), - .map = msi_mpg_x570s_carbon_max_wifi_alc4080_map, + .map = alc408x_map, }, { /* MSI MAG X570S Torpedo Max */ .id = USB_ID(0x0db0, 0xa073), - .map = msi_mpg_x570s_carbon_max_wifi_alc4080_map, + .map = alc408x_map, }, { /* MSI MAG B850M MORTAR WIFI */ .id = USB_ID(0x0db0, 0xcc78), - .map = msi_mpg_x570s_carbon_max_wifi_alc4080_map, + .map = alc408x_map, + }, + { /* ASRock X870E Taichi (Lite) (ALC4082) */ + .id = USB_ID(0x26ce, 0x0a0b), + .map = alc408x_map, }, { /* MSI TRX40 */ .id = USB_ID(0x0db0, 0x543d), From 250eb16dcd515b1f03601828c316bda9e1dd5f8e Mon Sep 17 00:00:00 2001 From: Brian Harring Date: Thu, 19 Nov 2026 17:08:19 +0100 Subject: [PATCH 2077/2102] ALSA: usb-audio: Add ES9219 speaker volume for ASRock X870E Taichi The rear output of the ASRock X870E Taichi / Taichi Lite onboard audio (26ce:0a0b, Realtek ALC4082) has a feature unit with only a mute, but an ESS ES9219 DAC sits behind it which can be used for volume control. The DAC is reachable through the codec's I2C bridge, using the vendor requests found in Realtek's Windows 10 driver (version 6.4.0.2449). That driver doesn't enable this for any ASRock device; at a guess, ASRock simply overlooked it. Assisted-by: Claude Opus 5.5 Signed-off-by: Brian Harring Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261119-alc4082-taichi-v2-2-03ad1352f807@gmail.com --- sound/usb/mixer_quirks.c | 177 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 177 insertions(+) diff --git a/sound/usb/mixer_quirks.c b/sound/usb/mixer_quirks.c index 4c7d68311f2048..60ac92a1ca4f9e 100644 --- a/sound/usb/mixer_quirks.c +++ b/sound/usb/mixer_quirks.c @@ -4656,6 +4656,179 @@ static int snd_xiisound_init_fu_pins(struct usb_mixer_interface *mixer) return 0; } +/* + * ASRock X870E Taichi (ALC4082): the rear line (feature unit 29) has only mute, + * however there is an ESS ES9219 DAC behind it that is usable for volume + * control. + */ +#define TAICHI_I2C_READ 0x3d +#define TAICHI_I2C_WRITE 0x3e +#define TAICHI_I2C_INDEX 0x0100 +#define TAICHI_ES9219_I2C_ADDR 0x48 +#define TAICHI_ES9219_REG_VOL_L 0x0f +#define TAICHI_ES9219_REG_VOL_R 0x10 +#define TAICHI_ES9219_PRIV_VOL_L GENMASK(7, 0) +#define TAICHI_ES9219_PRIV_VOL_R GENMASK(15, 8) +#define TAICHI_ES9219_VOL_MAX 0xff + +static int taichi_es9219_read(struct snd_usb_audio *chip, u8 reg, u8 *val) +{ + struct usb_device *dev = chip->dev; + u8 buf[2] = { reg, 0 }; + int err; + + err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), TAICHI_I2C_READ, + USB_RECIP_DEVICE | USB_TYPE_VENDOR | USB_DIR_OUT, + TAICHI_ES9219_I2C_ADDR, TAICHI_I2C_INDEX, + buf, sizeof(buf)); + if (err < 0) + return err; + err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), TAICHI_I2C_READ, + USB_RECIP_DEVICE | USB_TYPE_VENDOR | USB_DIR_IN, + TAICHI_ES9219_I2C_ADDR, TAICHI_I2C_INDEX, + buf, sizeof(buf)); + if (err < 0) + return err; + if (err < 1) + return -EIO; + *val = buf[0]; + return 0; +} + +static int taichi_es9219_write(struct snd_usb_audio *chip, u8 reg, u8 val) +{ + struct usb_device *dev = chip->dev; + u8 buf[2] = { reg, val }; + int err; + + err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), TAICHI_I2C_WRITE, + USB_RECIP_DEVICE | USB_TYPE_VENDOR | USB_DIR_OUT, + TAICHI_ES9219_I2C_ADDR, TAICHI_I2C_INDEX, + buf, sizeof(buf)); + return err < 0 ? err : 0; +} + +/* The return value follows the kcontrol put contract */ +static int taichi_es9219_vol_update(struct usb_mixer_elem_list *list, + u8 left, u8 right, bool force) +{ + struct snd_usb_audio *chip = list->mixer->chip; + unsigned long *pv = &list->kctl->private_value; + bool update_l = force || left != FIELD_GET(TAICHI_ES9219_PRIV_VOL_L, *pv); + bool update_r = force || right != FIELD_GET(TAICHI_ES9219_PRIV_VOL_R, *pv); + int err; + + if (!update_l && !update_r) + return 0; + + CLASS(snd_usb_lock, pm)(chip); + if (pm.err < 0) + return pm.err; + + if (update_l) { + err = taichi_es9219_write(chip, TAICHI_ES9219_REG_VOL_L, + TAICHI_ES9219_VOL_MAX - left); + if (err < 0) + return err; + FIELD_MODIFY(TAICHI_ES9219_PRIV_VOL_L, pv, left); + } + + if (update_r) { + err = taichi_es9219_write(chip, TAICHI_ES9219_REG_VOL_R, + TAICHI_ES9219_VOL_MAX - right); + if (err < 0) + return err; + FIELD_MODIFY(TAICHI_ES9219_PRIV_VOL_R, pv, right); + } + return 1; +} + +static int taichi_es9219_vol_info(struct snd_kcontrol *kctl, + struct snd_ctl_elem_info *uinfo) +{ + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 2; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = TAICHI_ES9219_VOL_MAX; + return 0; +} + +static int taichi_es9219_vol_get(struct snd_kcontrol *kctl, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.integer.value[0] = FIELD_GET(TAICHI_ES9219_PRIV_VOL_L, + kctl->private_value); + ucontrol->value.integer.value[1] = FIELD_GET(TAICHI_ES9219_PRIV_VOL_R, + kctl->private_value); + return 0; +} + +static int taichi_es9219_vol_put(struct snd_kcontrol *kctl, + struct snd_ctl_elem_value *ucontrol) +{ + struct usb_mixer_elem_list *list = snd_kcontrol_chip(kctl); + long l = ucontrol->value.integer.value[0]; + long r = ucontrol->value.integer.value[1]; + + if (l < 0 || l > TAICHI_ES9219_VOL_MAX || + r < 0 || r > TAICHI_ES9219_VOL_MAX) + return -EINVAL; + + return taichi_es9219_vol_update(list, l, r, false); +} + +static int taichi_es9219_vol_resume(struct usb_mixer_elem_list *list) +{ + unsigned long l = FIELD_GET(TAICHI_ES9219_PRIV_VOL_L, + list->kctl->private_value); + unsigned long r = FIELD_GET(TAICHI_ES9219_PRIV_VOL_R, + list->kctl->private_value); + + return taichi_es9219_vol_update(list, l, r, true); +} + +static const DECLARE_TLV_DB_SCALE(taichi_es9219_db_scale, -12750, 50, 0); + +static const struct snd_kcontrol_new taichi_es9219_vol = { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = "Speaker Playback Volume", + .access = SNDRV_CTL_ELEM_ACCESS_READWRITE | + SNDRV_CTL_ELEM_ACCESS_TLV_READ, + .info = taichi_es9219_vol_info, + .get = taichi_es9219_vol_get, + .put = taichi_es9219_vol_put, + .tlv = { .p = taichi_es9219_db_scale }, +}; + +static int taichi_es9219_controls_create(struct usb_mixer_interface *mixer) +{ + struct snd_usb_audio *chip = mixer->chip; + struct usb_mixer_elem_list *list; + u8 l, r; + int err; + + err = taichi_es9219_read(chip, TAICHI_ES9219_REG_VOL_L, &l); + if (err < 0) { + usb_audio_dbg(chip, "ES9219 VOL_L read failed: %d\n", err); + return 0; + } + err = taichi_es9219_read(chip, TAICHI_ES9219_REG_VOL_R, &r); + if (err < 0) { + usb_audio_dbg(chip, "ES9219 VOL_R read failed: %d\n", err); + return 0; + } + + err = add_single_ctl_with_resume(mixer, 0, taichi_es9219_vol_resume, + &taichi_es9219_vol, &list); + if (err < 0) + return err; + + list->kctl->private_value = + FIELD_PREP(TAICHI_ES9219_PRIV_VOL_L, TAICHI_ES9219_VOL_MAX - l) | + FIELD_PREP(TAICHI_ES9219_PRIV_VOL_R, TAICHI_ES9219_VOL_MAX - r); + return 0; +} + int snd_usb_mixer_apply_create_quirk(struct usb_mixer_interface *mixer) { int err = 0; @@ -4797,6 +4970,10 @@ int snd_usb_mixer_apply_create_quirk(struct usb_mixer_interface *mixer) err = dell_dock_mixer_create(mixer); break; + case USB_ID(0x26ce, 0x0a0b): /* ASRock X870E Taichi (Lite) */ + err = taichi_es9219_controls_create(mixer); + break; + case USB_ID(0x2a39, 0x3fd2): /* RME ADI-2 Pro */ case USB_ID(0x2a39, 0x3fd3): /* RME ADI-2 DAC */ case USB_ID(0x2a39, 0x3fd4): /* RME */ From 1bed11068213e4f40351d827fe8e28d91f85539a Mon Sep 17 00:00:00 2001 From: Ajay Kumar Nandam Date: Tue, 1 Dec 2026 03:00:34 +0530 Subject: [PATCH 2078/2102] ASoC: dt-bindings: qcom,sm8250: add Shikra sound card compatibles Add Shikra sound-card compatible strings to the Qualcomm sound card binding so DT can describe board-specific audio topologies: - qcom,shikra-cqm-sndcard - qcom,shikra-cqs-sndcard - qcom,shikra-iqs-sndcard Shikra EVK variants use different codec/interface combinations and DSP processing paths. Describing these variants explicitly in DT allows the machine driver to select the correct DAPM routes, controls, and clocking behavior for each board. Reviewed-by: Krzysztof Kozlowski Reviewed-by: Prasad Kumpatla Signed-off-by: Ajay Kumar Nandam Signed-off-by: Mohammad Rafi Shaik Reviewed-by: Ravi Hothi Tested-by: Ravi Hothi Link: https://patch.msgid.link/20261201-shikra-machine-v4-1-5c7261806dae@oss.qualcomm.com Signed-off-by: Mark Brown --- Documentation/devicetree/bindings/sound/qcom,sm8250.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml b/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml index a890fa288a76b3..1dc164e2c73cfc 100644 --- a/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml +++ b/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml @@ -57,6 +57,9 @@ properties: - qcom,sc8280xp-sndcard - qcom,sdm660-sndcard - qcom,sdm845-sndcard + - qcom,shikra-cqm-sndcard + - qcom,shikra-cqs-sndcard + - qcom,shikra-iqs-sndcard - qcom,sm8250-sndcard - qcom,sm8450-sndcard - qcom,x1e80100-sndcard From 6d2524f0d360b68dacfd0f137b3ed0caa3a563fa Mon Sep 17 00:00:00 2001 From: Ajay Kumar Nandam Date: Tue, 1 Dec 2026 03:00:35 +0530 Subject: [PATCH 2079/2102] ASoC: qcom: sc8280xp: add backend handling for Shikra sound cards The Shikra sound cards reuse the sc8280xp machine driver, but their audio links still need three pieces of backend handling that the driver does not provide. Add them now that the generic QAIF DAI ID support is upstream. Shikra routes its VA macro capture path through VA_CODEC_DMA_TX_1, so handle that DAI like the other codec DMA DAIs: treat it as a SoundWire-style DAI, lower the backend channel minimum to one channel, and allow a WCD jack to be registered on it. Shikra CQM drives its QAIF TDM speaker backend with DSP_A framing, while the other links on this driver use the default I2S framing. Add a cpu_dai_fmt field to the per-DAI board data and, when it is set, program it instead of the hardcoded SND_SOC_DAIFMT_BP_FP. This lets a board override the CPU DAI format for a single DAI without changing the default for every other DAI or board. Boards that do not route audio through the DSP describe plain CPU <-> codec links with no platform node. Such links are neither dynamic nor no_pcm, so they were skipped by sc8280xp_add_be_ops() and were left without the ops that configure the codec DAI. Attach the ops to non-dynamic links as well. link->dynamic has to be the test here because qcom_snd_parse_of() attaches snd_soc_dummy_dlc to DPCM frontends, which leaves num_codecs non-zero for them too, so the codec count cannot distinguish a frontend from a plain codec link. Signed-off-by: Ajay Kumar Nandam Signed-off-by: Mohammad Rafi Shaik Reviewed-by: Ravi Hothi Tested-by: Ravi Hothi Link: https://patch.msgid.link/20261201-shikra-machine-v4-2-5c7261806dae@oss.qualcomm.com Signed-off-by: Mark Brown --- sound/soc/qcom/common.c | 1 + sound/soc/qcom/sc8280xp.c | 24 +++++++++++++++++++++--- sound/soc/qcom/sdw.c | 1 + 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/sound/soc/qcom/common.c b/sound/soc/qcom/common.c index af5cacddf67dff..77845d43c21943 100644 --- a/sound/soc/qcom/common.c +++ b/sound/soc/qcom/common.c @@ -426,6 +426,7 @@ int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, case TX_CODEC_DMA_TX_1: case TX_CODEC_DMA_TX_2: case TX_CODEC_DMA_TX_3: + case VA_CODEC_DMA_TX_1: for_each_rtd_codec_dais(rtd, i, codec_dai) { rval = snd_soc_component_set_jack(codec_dai->component, jack, NULL); diff --git a/sound/soc/qcom/sc8280xp.c b/sound/soc/qcom/sc8280xp.c index ac4dfb2c2182ca..889543daadf36a 100644 --- a/sound/soc/qcom/sc8280xp.c +++ b/sound/soc/qcom/sc8280xp.c @@ -71,6 +71,7 @@ enum sc8280xp_jack_setup { struct sc8280xp_dai_data { unsigned int id; unsigned int mclk_rate; + unsigned int cpu_dai_fmt; bool codec_sysclk_set; bool mi2s_mclk_enable; bool mi2s_bclk_enable; @@ -159,6 +160,7 @@ static int sc8280xp_tdm_hw_params(struct snd_pcm_substream *substream, struct qcom_snd_tdm_slot_cfg codec_cfg; bool codec_sysclk_set = data->priv->codec_sysclk_set; bool mi2s_bclk_enable = data->priv->mi2s_bclk_enable; + unsigned int cpu_dai_fmt = SND_SOC_DAIFMT_BP_FP; int bclk_freq; int ret; int i; @@ -167,6 +169,8 @@ static int sc8280xp_tdm_hw_params(struct snd_pcm_substream *substream, if (dai_data) { codec_sysclk_set = dai_data->codec_sysclk_set; mi2s_bclk_enable = dai_data->mi2s_bclk_enable; + if (dai_data->cpu_dai_fmt) + cpu_dai_fmt = dai_data->cpu_dai_fmt; } ret = qcom_snd_get_dai_tdm_slots(rtd, &cpu_cfg, &codec_cfg); @@ -176,7 +180,7 @@ static int sc8280xp_tdm_hw_params(struct snd_pcm_substream *substream, if (!cpu_cfg.slots) return 0; - ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_BP_FP); + ret = snd_soc_dai_set_fmt(cpu_dai, cpu_dai_fmt); if (ret && ret != -ENOTSUPP) return ret; @@ -329,6 +333,7 @@ static int sc8280xp_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, case TX_CODEC_DMA_TX_1: case TX_CODEC_DMA_TX_2: case TX_CODEC_DMA_TX_3: + case VA_CODEC_DMA_TX_1: channels->min = 1; break; case PRIMARY_MI2S_RX ... QUATERNARY_MI2S_TX: @@ -388,6 +393,7 @@ static int sc8280xp_snd_hw_params(struct snd_pcm_substream *substream, bool codec_sysclk_set = data->priv->codec_sysclk_set; bool mi2s_mclk_enable = data->priv->mi2s_mclk_enable; bool mi2s_bclk_enable = data->priv->mi2s_bclk_enable; + unsigned int cpu_dai_fmt = SND_SOC_DAIFMT_BP_FP; int mclk_freq; int bclk_freq = sc8280xp_get_bclk_freq(params); int ret; @@ -398,6 +404,8 @@ static int sc8280xp_snd_hw_params(struct snd_pcm_substream *substream, codec_sysclk_set = dai_data->codec_sysclk_set; mi2s_mclk_enable = dai_data->mi2s_mclk_enable; mi2s_bclk_enable = dai_data->mi2s_bclk_enable; + if (dai_data->cpu_dai_fmt) + cpu_dai_fmt = dai_data->cpu_dai_fmt; if (dai_data->mclk_rate) mclk_freq = dai_data->mclk_rate; } @@ -408,7 +416,7 @@ static int sc8280xp_snd_hw_params(struct snd_pcm_substream *substream, case SENARY_MI2S_RX ... SENARY_MI2S_TX: case LPI_MI2S_RX_0 ... LPI_MI2S_TX_4: case AIF_MI2S_RX_0 ... AIF_MI2S_TX_12: - ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_BP_FP); + ret = snd_soc_dai_set_fmt(cpu_dai, cpu_dai_fmt); if (ret && ret != -ENOTSUPP) return ret; @@ -544,7 +552,17 @@ static void sc8280xp_add_be_ops(struct snd_soc_card *card) int i; for_each_card_prelinks(card, i, link) { - if (link->no_pcm == 1) { + /* + * Attach the ops to DPCM backends and to plain CPU <-> codec + * links, which boards that do not route audio through the DSP + * describe without a platform node. Both have a real codec DAI + * to configure. + * + * DPCM frontends must be skipped: qcom_snd_parse_of() marks + * them dynamic and attaches snd_soc_dummy_dlc to them, so + * num_codecs is never zero and cannot tell them apart. + */ + if (link->no_pcm == 1 || !link->dynamic) { link->init = sc8280xp_snd_init; link->exit = sc8280xp_snd_exit; link->be_hw_params_fixup = sc8280xp_be_hw_params_fixup; diff --git a/sound/soc/qcom/sdw.c b/sound/soc/qcom/sdw.c index 6576b47a4c8c35..e19adb7c750b0d 100644 --- a/sound/soc/qcom/sdw.c +++ b/sound/soc/qcom/sdw.c @@ -30,6 +30,7 @@ static bool qcom_snd_is_sdw_dai(int id) case TX_CODEC_DMA_TX_5: case RX_CODEC_DMA_RX_6: case RX_CODEC_DMA_RX_7: + case VA_CODEC_DMA_TX_1: case SLIMBUS_0_RX...SLIMBUS_6_TX: return true; default: From 37b79af6e915f3885bad504d4ee1c1ee4aceddd6 Mon Sep 17 00:00:00 2001 From: Ajay Kumar Nandam Date: Tue, 1 Dec 2026 03:00:36 +0530 Subject: [PATCH 2080/2102] ASoC: qcom: sc8280xp: Add shikra-cqm-evk compatible support Add machine driver support for the Qualcomm Shikra CQM EVK board. The Shikra CQM platform uses an I2S-based audio path with WSA885x amplifiers and PM4125/Rouleur codec components. Configure the CQM QAIF TDM speaker backend with DSP_A framing using per-DAI board data. Reviewed-by: Prasad Kumpatla Signed-off-by: Ajay Kumar Nandam Signed-off-by: Mohammad Rafi Shaik Reviewed-by: Ravi Hothi Tested-by: Ravi Hothi Link: https://patch.msgid.link/20261201-shikra-machine-v4-3-5c7261806dae@oss.qualcomm.com Signed-off-by: Mark Brown --- sound/soc/qcom/sc8280xp.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/sound/soc/qcom/sc8280xp.c b/sound/soc/qcom/sc8280xp.c index 889543daadf36a..4beab1b0e6e811 100644 --- a/sound/soc/qcom/sc8280xp.c +++ b/sound/soc/qcom/sc8280xp.c @@ -734,6 +734,20 @@ static const struct qcom_snd_soc_common sc8280xp_priv_data = { .wcd_jack = true, }; +static const struct qcom_snd_soc_common shikra_cqm_priv_data = { + .driver_name = "shikra", + .dapm_widgets = sc8280xp_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(sc8280xp_dapm_widgets), + .wcd_jack = true, + SC8280XP_DAI_DATA({ + .id = AIF_TDM_RX_2, + .cpu_dai_fmt = SND_SOC_DAIFMT_DSP_A | SND_SOC_DAIFMT_BP_FP, + .codec_sysclk_set = true, + .mi2s_bclk_enable = true, + } + ), +}; + static const struct qcom_snd_soc_common sm8450_priv_data = { .driver_name = "sm8450", .dapm_widgets = sc8280xp_dapm_widgets, @@ -803,6 +817,7 @@ static const struct of_device_id snd_sc8280xp_dt_match[] = { { .compatible = "qcom,qcs9075-sndcard", .data = &qcs9100_priv_data }, { .compatible = "qcom,qcs9100-sndcard", .data = &qcs9100_priv_data }, { .compatible = "qcom,sc8280xp-sndcard", .data = &sc8280xp_priv_data }, + { .compatible = "qcom,shikra-cqm-sndcard", .data = &shikra_cqm_priv_data }, { .compatible = "qcom,sm8450-sndcard", .data = &sm8450_priv_data }, { .compatible = "qcom,sm8475-sndcard", .data = &sm8475_priv_data }, { .compatible = "qcom,sm8550-sndcard", .data = &sm8550_priv_data }, From 16d980fa3d849172deb2155d0efa70ade54eddc9 Mon Sep 17 00:00:00 2001 From: Ajay Kumar Nandam Date: Tue, 1 Dec 2026 03:00:37 +0530 Subject: [PATCH 2081/2102] ASoC: qcom: sc8280xp: Add shikra-cqs-evk compatible support Add machine driver support for the Qualcomm Shikra CQS EVK board. The Shikra CQS platform uses an I2S-based audio path with WSA885x amplifiers and PM4125/Rouleur codec components with modem-DSP based audio processing. Reviewed-by: Prasad Kumpatla Signed-off-by: Ajay Kumar Nandam Signed-off-by: Mohammad Rafi Shaik Reviewed-by: Ravi Hothi Tested-by: Ravi Hothi Link: https://patch.msgid.link/20261201-shikra-machine-v4-4-5c7261806dae@oss.qualcomm.com Signed-off-by: Mark Brown --- sound/soc/qcom/sc8280xp.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/sound/soc/qcom/sc8280xp.c b/sound/soc/qcom/sc8280xp.c index 4beab1b0e6e811..43e6c3e882aac2 100644 --- a/sound/soc/qcom/sc8280xp.c +++ b/sound/soc/qcom/sc8280xp.c @@ -748,6 +748,19 @@ static const struct qcom_snd_soc_common shikra_cqm_priv_data = { ), }; +static const struct qcom_snd_soc_common shikra_cqs_priv_data = { + .driver_name = "shikra", + .dapm_widgets = sc8280xp_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(sc8280xp_dapm_widgets), + .wcd_jack = true, + SC8280XP_DAI_DATA({ + .id = AIF_TDM_RX_2, + .codec_sysclk_set = true, + .mi2s_bclk_enable = true, + } + ), +}; + static const struct qcom_snd_soc_common sm8450_priv_data = { .driver_name = "sm8450", .dapm_widgets = sc8280xp_dapm_widgets, @@ -818,6 +831,7 @@ static const struct of_device_id snd_sc8280xp_dt_match[] = { { .compatible = "qcom,qcs9100-sndcard", .data = &qcs9100_priv_data }, { .compatible = "qcom,sc8280xp-sndcard", .data = &sc8280xp_priv_data }, { .compatible = "qcom,shikra-cqm-sndcard", .data = &shikra_cqm_priv_data }, + { .compatible = "qcom,shikra-cqs-sndcard", .data = &shikra_cqs_priv_data }, { .compatible = "qcom,sm8450-sndcard", .data = &sm8450_priv_data }, { .compatible = "qcom,sm8475-sndcard", .data = &sm8475_priv_data }, { .compatible = "qcom,sm8550-sndcard", .data = &sm8550_priv_data }, From 899f8d4437cf75ace3e395590973798ee0c8e4c8 Mon Sep 17 00:00:00 2001 From: Ajay Kumar Nandam Date: Tue, 1 Dec 2026 03:00:38 +0530 Subject: [PATCH 2082/2102] ASoC: qcom: sc8280xp: Add shikra-iqs-evk compatible support Add machine driver support for the Qualcomm Shikra IQS EVK board. The Shikra IQS platform uses a third-party MAX98091 codec with modem-DSP support. IQS requires board-level DAPM widgets and pin-switch kcontrols because the MAX98091 codec driver does not expose its own endpoint topology, unlike the Qualcomm WSA885x/Rouleur codecs used on the CQM/CQS variants. Signed-off-by: Ajay Kumar Nandam Signed-off-by: Mohammad Rafi Shaik Reviewed-by: Ravi Hothi Tested-by: Ravi Hothi Link: https://patch.msgid.link/20261201-shikra-machine-v4-5-5c7261806dae@oss.qualcomm.com Signed-off-by: Mark Brown --- sound/soc/qcom/sc8280xp.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/sound/soc/qcom/sc8280xp.c b/sound/soc/qcom/sc8280xp.c index 43e6c3e882aac2..1920033314a38c 100644 --- a/sound/soc/qcom/sc8280xp.c +++ b/sound/soc/qcom/sc8280xp.c @@ -45,6 +45,7 @@ static struct snd_soc_dapm_widget sc8280xp_dapm_widgets[] = { static const struct snd_kcontrol_new max98090_controls[] = { SOC_DAPM_PIN_SWITCH("Headset Mic12"), SOC_DAPM_PIN_SWITCH("Headphone"), + SOC_DAPM_PIN_SWITCH("Headset Mic34"), SOC_DAPM_PIN_SWITCH("Headset Mic56"), SOC_DAPM_PIN_SWITCH("Speaker"), SOC_DAPM_PIN_SWITCH("Receiver"), @@ -56,6 +57,7 @@ static const struct snd_soc_dapm_widget max98090_dapm_widgets[] = { SND_SOC_DAPM_MIC("Mic Jack", NULL), SND_SOC_DAPM_HP("Headphone", NULL), SND_SOC_DAPM_MIC("Headset Mic12", NULL), + SND_SOC_DAPM_MIC("Headset Mic34", NULL), SND_SOC_DAPM_MIC("Headset Mic56", NULL), SND_SOC_DAPM_MIC("Int Mic", NULL), SND_SOC_DAPM_SPK("Receiver", NULL), @@ -761,6 +763,26 @@ static const struct qcom_snd_soc_common shikra_cqs_priv_data = { ), }; +static const struct qcom_snd_soc_common shikra_iqs_priv_data = { + .driver_name = "shikra", + .dapm_widgets = max98090_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(max98090_dapm_widgets), + .controls = max98090_controls, + .num_controls = ARRAY_SIZE(max98090_controls), + .codec_dai_fmt = SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_BC_FC, + SC8280XP_DAI_DATA({ + .id = AIF_MI2S_RX_0, + .codec_sysclk_set = true, + .mi2s_bclk_enable = true, + .jack_setup = SC8280XP_JACK_SETUP_CODEC, + }, { + .id = AIF_MI2S_TX_0, + .codec_sysclk_set = true, + .mi2s_bclk_enable = true, + } + ), +}; + static const struct qcom_snd_soc_common sm8450_priv_data = { .driver_name = "sm8450", .dapm_widgets = sc8280xp_dapm_widgets, @@ -832,6 +854,7 @@ static const struct of_device_id snd_sc8280xp_dt_match[] = { { .compatible = "qcom,sc8280xp-sndcard", .data = &sc8280xp_priv_data }, { .compatible = "qcom,shikra-cqm-sndcard", .data = &shikra_cqm_priv_data }, { .compatible = "qcom,shikra-cqs-sndcard", .data = &shikra_cqs_priv_data }, + { .compatible = "qcom,shikra-iqs-sndcard", .data = &shikra_iqs_priv_data }, { .compatible = "qcom,sm8450-sndcard", .data = &sm8450_priv_data }, { .compatible = "qcom,sm8475-sndcard", .data = &sm8475_priv_data }, { .compatible = "qcom,sm8550-sndcard", .data = &sm8550_priv_data }, From 1c25e5d16a8aebab9e201ca46376db2fc4148b73 Mon Sep 17 00:00:00 2001 From: Manuel Ebner Date: Mon, 30 Nov 2026 19:41:24 +0100 Subject: [PATCH 2083/2102] ASoC: fsl_aud2htx: Fix kernel-doc Add 'struct' to kernel-doc, fixing: $ ./scripts/kernel-doc --none sound/soc/fsl/fsl_aud2htx.h Warning: sound/soc/fsl/fsl_aud2htx.h:58 cannot understand function prototype: 'struct fsl_aud2htx' Signed-off-by: Manuel Ebner Reviewed-by: Shengjiu Wang Link: https://patch.msgid.link/20261130184125.1824415-1-manuelebnerli@mailbox.org Signed-off-by: Mark Brown --- sound/soc/fsl/fsl_aud2htx.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/fsl/fsl_aud2htx.h b/sound/soc/fsl/fsl_aud2htx.h index cf292e3ccc0209..51e48ae603c767 100644 --- a/sound/soc/fsl/fsl_aud2htx.h +++ b/sound/soc/fsl/fsl_aud2htx.h @@ -48,7 +48,7 @@ #define AUD2HTX_MAXBURST 0x10 /** - * fsl_aud2htx: AUD2HTX private data + * struct fsl_aud2htx: AUD2HTX private data * * @pdev: platform device pointer * @regmap: regmap handler From 27251dbed89574e761a204d15776d479e746d68a Mon Sep 17 00:00:00 2001 From: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Date: Tue, 1 Dec 2026 19:35:40 +0800 Subject: [PATCH 2084/2102] ALSA: 6fire: Don't resubmit an active MIDI URB The MIDI output keeps the transmission state in rt->out and submits rt->out_urb from the rawmidi trigger callback. Stopping the stream, for example through the SNDRV_RAWMIDI_IOCTL_DROP ioctl, only clears rt->out; the URB itself stays queued until the device has accepted the pending data, which can take a while when the device delays the transfer. If the stream is started again before that happens, the trigger callback passes the still-active URB to usb_submit_urb() a second time. The USB core rejects it and the new data is not sent: URB 00000000c6cd6557 submitted while active WARNING: drivers/usb/core/urb.c:379 at usb_submit_urb ... usb6fire_midi_out_trigger snd_rawmidi_kernel_write1 ... usb 1-1: midi out urb submit failed: -16 Track whether the URB is queued separately from the substream that owns it, and let the completion handler send the data queued by a restart while the URB is still in flight. Clear rt->out when the resubmission fails there as well, like the trigger callback already does, so that a later write restarts the transfer instead of returning early forever. Fixes: c6d43ba816d1 ("ALSA: usb/6fire - Driver for TerraTec DMX 6Fire USB") Co-developed-by: Bin Yu Signed-off-by: Bin Yu Co-developed-by: Cheng Wen Signed-off-by: Cheng Wen Signed-off-by: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261201113541.6237-2-25031212351@stu.xidian.edu.cn --- sound/usb/6fire/midi.c | 24 +++++++++++++++++++----- sound/usb/6fire/midi.h | 1 + 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/sound/usb/6fire/midi.c b/sound/usb/6fire/midi.c index 279b449936e75d..407f5d73b07dec 100644 --- a/sound/usb/6fire/midi.c +++ b/sound/usb/6fire/midi.c @@ -25,6 +25,7 @@ static void usb6fire_midi_out_handler(struct urb *urb) int ret; guard(spinlock_irqsave)(&rt->out_lock); + rt->out_urb_active = false; if (rt->out) { ret = snd_rawmidi_transmit(rt->out, rt->out_buffer + 4, @@ -35,10 +36,13 @@ static void usb6fire_midi_out_handler(struct urb *urb) urb->transfer_buffer_length = ret + 4; ret = usb_submit_urb(urb, GFP_ATOMIC); - if (ret < 0) + if (ret < 0) { + rt->out = NULL; dev_err(&urb->dev->dev, "midi out urb submit failed: %d\n", ret); + } else + rt->out_urb_active = true; } else /* no more data to transmit */ rt->out = NULL; } @@ -74,6 +78,14 @@ static void usb6fire_midi_out_trigger( if (rt->out) /* we are already transmitting so just return */ return; + rt->out = alsa_sub; + /* + * The urb is still in flight from the previous transmission; + * the completion handler sends the queued data instead. + */ + if (rt->out_urb_active) + return; + ret = snd_rawmidi_transmit(alsa_sub, rt->out_buffer + 4, MIDI_BUFSIZE - 4); if (ret > 0) { @@ -82,13 +94,15 @@ static void usb6fire_midi_out_trigger( urb->transfer_buffer_length = ret + 4; ret = usb_submit_urb(urb, GFP_ATOMIC); - if (ret < 0) + if (ret < 0) { + rt->out = NULL; dev_err(&urb->dev->dev, "midi out urb submit failed: %d\n", ret); - else - rt->out = alsa_sub; - } + } else + rt->out_urb_active = true; + } else + rt->out = NULL; } else if (rt->out == alsa_sub) rt->out = NULL; } diff --git a/sound/usb/6fire/midi.h b/sound/usb/6fire/midi.h index 8716ab8a863ae9..2213614424357c 100644 --- a/sound/usb/6fire/midi.h +++ b/sound/usb/6fire/midi.h @@ -23,6 +23,7 @@ struct midi_runtime { spinlock_t out_lock; struct snd_rawmidi_substream *out; struct urb *out_urb; + bool out_urb_active; /* out urb is still queued in the HCD */ u8 out_serial; /* serial number of out packet */ u8 *out_buffer; int buffer_offset; From 6a0f0a151210ed20e3ad84f197cd92438739e1fb Mon Sep 17 00:00:00 2001 From: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Date: Tue, 1 Dec 2026 19:35:41 +0800 Subject: [PATCH 2085/2102] ALSA: 6fire: Don't resubmit an active PCM out URB usb6fire_pcm_in_urb_handler() refills the playback URB paired with the capture URB that has just completed and submits it unconditionally, although the comment right above expects "a free out urb was found". Both URBs carry the same number of isochronous packets and are rearmed at the same time, so the playback URB can still be queued when the next capture completion arrives. The handler then rewrites a transfer buffer that is still owned by the host controller and submits the active URB again: URB 000000003ec29e65 submitted while active WARNING: drivers/usb/core/urb.c:379 at usb_submit_urb ... usb6fire_pcm_in_urb_handler __usb_hcd_giveback_urb ... The resubmission fails and the playback data of that period is lost. This is observed when the completion of the playback URB is delayed, for example by missed isochronous services on the host controller. Check whether the out URB has completed and skip it for the period otherwise; the next capture completion retries. Fixes: c6d43ba816d1 ("ALSA: usb/6fire - Driver for TerraTec DMX 6Fire USB") Co-developed-by: Bin Yu Signed-off-by: Bin Yu Co-developed-by: Cheng Wen Signed-off-by: Cheng Wen Signed-off-by: YuanZhe Liu <25031212351@stu.xidian.edu.cn> Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261201113541.6237-3-25031212351@stu.xidian.edu.cn --- sound/usb/6fire/pcm.c | 16 +++++++++++++++- sound/usb/6fire/pcm.h | 2 ++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/sound/usb/6fire/pcm.c b/sound/usb/6fire/pcm.c index f5dfb8c3096adf..d6ef8ffa97a9b5 100644 --- a/sound/usb/6fire/pcm.c +++ b/sound/usb/6fire/pcm.c @@ -460,6 +460,15 @@ static void usb6fire_pcm_in_urb_handler(struct urb *usb_urb) if (period_elapsed) snd_pcm_period_elapsed(sub->instance); + /* + * The out urb is submitted again from here, but the previous one may + * still be queued in the HCD. Its transfer buffer is owned by the + * HCD until it completes, so skip it for this period and retry at + * the next capture completion. + */ + if (atomic_xchg(&out_urb->active, 1)) + goto submit_in; + /* setup out urb structure */ for (i = 0; i < PCM_N_PACKETS_PER_URB; i++) { unsigned int frames = 0; @@ -525,8 +534,11 @@ static void usb6fire_pcm_in_urb_handler(struct urb *usb_urb) * the frames of an out urb that was not submitted never reach the * transmitter; the next urb continues the block at the same position */ - if (usb_submit_urb(out_urb->instance, GFP_ATOMIC) < 0) + if (usb_submit_urb(out_urb->instance, GFP_ATOMIC) < 0) { rt->spdif_frame = spdif_frame; + atomic_set(&out_urb->active, 0); + } +submit_in: usb_submit_urb(in_urb->instance, GFP_ATOMIC); } @@ -535,6 +547,8 @@ static void usb6fire_pcm_out_urb_handler(struct urb *usb_urb) struct pcm_urb *urb = usb_urb->context; struct pcm_runtime *rt = urb->chip->pcm; + atomic_set(&urb->active, 0); + if (rt->stream_state == STREAM_STARTING) { rt->stream_wait_cond = true; wake_up(&rt->stream_wait_queue); diff --git a/sound/usb/6fire/pcm.h b/sound/usb/6fire/pcm.h index f1b867b9c46864..b5d1f5106d2c09 100644 --- a/sound/usb/6fire/pcm.h +++ b/sound/usb/6fire/pcm.h @@ -28,6 +28,8 @@ struct pcm_urb { u8 *buffer; struct pcm_urb *peer; + + atomic_t active; /* urb is queued in the HCD */ }; struct pcm_substream { From a51ae1b30bca04c9103851e3ff0792afd96ca20c Mon Sep 17 00:00:00 2001 From: Hanxiang Xu Date: Wed, 2 Dec 2026 02:20:39 +0800 Subject: [PATCH 2086/2102] ALSA: emu8000: sync the PCM emulation timer before freeing snd_emu8k_pcm (uaf from the in-flight softirq callback) The emu8000 PCM emulation drives its period handling from a timer that re-arms itself every jiffie (emu8k_pcm_timer_func() -> mod_timer() inside the rec->timer_lock section). Stopping the stream uses the non-synchronizing timer_delete() (stop_voice()), which cannot affect a callback instance that is already executing in softirq context, and emu8k_pcm_close() then kfree()s rec with no timer_delete_sync() and nothing stops a running instance from re-arming. An in-flight emu8k_pcm_timer_func() therefore continues on freed memory: it dereferences rec->emu, locks the freed rec->timer_lock, writes rec->period_pos, re-arms the freed timer (a ghost timer firing every tick), and reads rec->substream for snd_pcm_period_elapsed(). stop_voice() runs under the stream spinlock, so the sync cannot be added there - but close() is process context. Gate the re-arm on rec->timer_running (under the rec->timer_lock that stop_voice() already clears) and wait for an in-flight callback with timer_delete_sync() before kfree(rec) in emu8k_pcm_close(). Cc: Signed-off-by: Hanxiang Xu Link: https://patch.msgid.link/20261202022039.1-1-xuhx@hust.edu.cn Signed-off-by: Takashi Iwai --- sound/isa/sb/emu8000_pcm.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sound/isa/sb/emu8000_pcm.c b/sound/isa/sb/emu8000_pcm.c index d2ca70aad1621e..ec26705808d11b 100644 --- a/sound/isa/sb/emu8000_pcm.c +++ b/sound/isa/sb/emu8000_pcm.c @@ -187,6 +187,8 @@ static void emu8k_pcm_timer_func(struct timer_list *t) bool period_elapsed = false; scoped_guard(spinlock, &rec->timer_lock) { + if (!rec->timer_running) + return; /* update the current pointer */ ptr = emu8k_get_curpos(rec, 0); if (ptr < rec->last_ptr) @@ -246,6 +248,8 @@ static int emu8k_pcm_open(struct snd_pcm_substream *subs) static int emu8k_pcm_close(struct snd_pcm_substream *subs) { struct snd_emu8k_pcm *rec = subs->runtime->private_data; + + timer_delete_sync(&rec->timer); kfree(rec); subs->runtime->private_data = NULL; return 0; From 45ad0951a8d46d6b254169f8c519059fa13af2e3 Mon Sep 17 00:00:00 2001 From: Hanxiang Xu Date: Wed, 2 Dec 2026 10:13:02 +0800 Subject: [PATCH 2087/2102] ALSA: emux: expose the hwdep device only after ports are initialized snd_emux_register() creates and registers the hwdep device (snd_emux_init_hwdep() -> snd_card_register()) before snd_emux_init_seq() fills emu->portptrs[], and ignores the init_seq() return value. A SNDRV_EMUX_IOCTL_MISC_MODE ioctl arriving inside that window walks emu->portptrs[i]->ctrls[] with portptrs[i] == NULL and causes a near-NULL kernel write (dynamically confirmed on v7.4-rc5); a failed sequencer setup additionally leaves the already-registered hwdep behind for the probe error path to free with possibly-open fds. Initialize the ports (and OSS/virmidi) first and create the hwdep device last, so the device only becomes visible to userspace after everything its ioctls touch is initialized, and propagate the snd_emux_init_seq() error. Cc: Signed-off-by: Hanxiang Xu Link: https://patch.msgid.link/20261202101302.1-1-xuhx@hust.edu.cn Signed-off-by: Takashi Iwai --- sound/synth/emux/emux.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/sound/synth/emux/emux.c b/sound/synth/emux/emux.c index 2a42d041e1da0b..c2ee40735bf202 100644 --- a/sound/synth/emux/emux.c +++ b/sound/synth/emux/emux.c @@ -105,18 +105,19 @@ int snd_emux_register(struct snd_emux *emu, struct snd_card *card, int index, ch if (emu->sflist == NULL) return -ENOMEM; - err = snd_emux_init_hwdep(emu); - if (err < 0) - return err; - snd_emux_init_voices(emu); - snd_emux_init_seq(emu, card, index); + if (snd_emux_init_seq(emu, card, index) < 0) + return -ENODEV; #if IS_ENABLED(CONFIG_SND_SEQUENCER_OSS) snd_emux_init_seq_oss(emu); #endif snd_emux_init_virmidi(emu, card); + err = snd_emux_init_hwdep(emu); + if (err < 0) + return err; + snd_emux_proc_init(emu, card, index); return 0; } From db0e79a82f02c4f6154d6893c9dbfd07ab4a5867 Mon Sep 17 00:00:00 2001 From: Igor Velkov Date: Sat, 28 Nov 2026 03:06:46 +0200 Subject: [PATCH 2088/2102] ASoC: rk817: Do not free the regmap of the parent PMIC The codec uses the regmap of its RK817/RK809 PMIC parent, which the PMIC core, RTC and regulator drivers use too. rk817_remove() calls snd_soc_component_exit_regmap(), so removing the component, on a card unbind or a failed bind, runs regmap_exit() on that shared regmap. The other users are left with a freed regmap, and devm runs regmap_exit() on it again when the PMIC goes away. Clear the pointer instead, as commit 6d66c5ccf5cb ("ASoC: mediatek: mt6359: Fix unexpected error in bind/unbind flow") does for mt6359. On an ODROID-M1 (RK3568, RK809) the PMIC regmap (3-0020) disappears from debugfs after unbinding the card, and a later hybrid sleep oopsed in regmap_update_bits_base() called from rk808_rtc_readtime(). With this change the regmap stays, the RTC reads and binding the card again works. Fixes: 0d6a04da9b25 ("ASoC: Add Rockchip rk817 audio CODEC support") Signed-off-by: Igor Velkov Link: https://patch.msgid.link/20261128-rk817-keep-parent-regmap-v1-1-de515c2899ed@iav.lv Signed-off-by: Mark Brown --- sound/soc/codecs/rk817_codec.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/codecs/rk817_codec.c b/sound/soc/codecs/rk817_codec.c index 2c0fe1dfd842c6..c7804b2b559c72 100644 --- a/sound/soc/codecs/rk817_codec.c +++ b/sound/soc/codecs/rk817_codec.c @@ -434,7 +434,7 @@ static int rk817_probe(struct snd_soc_component *component) static void rk817_remove(struct snd_soc_component *component) { - snd_soc_component_exit_regmap(component); + component->regmap = NULL; } static const struct snd_soc_component_driver soc_codec_dev_rk817 = { From d8d4f9e00b063e8c18af8ad03cba75fe2ac73ebc Mon Sep 17 00:00:00 2001 From: Richard Fitzgerald Date: Wed, 2 Dec 2026 11:43:33 +0000 Subject: [PATCH 2089/2102] ASoC: cs35l56: Add module parameter to allow factory calibration Always build the calibration debugfs support into the driver, but only create the debugfs files if the new module parameter 'allow_factory_cal' is true, or the existing CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS Kconfig is enabled. This allows manufacturers to perform factory calibration on the production line without the need to build and install a custom kernel. If the kernel has been built with CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS, the module parameter can be forced to 0 to disable calibration. A small change is needed to the Kconfig for the HDA driver to delete the select of SND_SOC_CS35L56_CAL_DEBUGFS_COMMON, as that Kconfig symbol is now removed. The CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS Kconfig is retained to prevent changing the behaviour of existing downstream products that depend on it enabling the debugfs. Factory calibration is disabled by default to prevent accidental use of this feature in non-factory conditions, which could result in the speakers being under-protected. Signed-off-by: Richard Fitzgerald Link: https://patch.msgid.link/20261202114333.816138-1-rf@opensource.cirrus.com Signed-off-by: Mark Brown --- sound/hda/codecs/side-codecs/Kconfig | 1 - sound/soc/codecs/Kconfig | 6 ------ sound/soc/codecs/cs35l56-shared.c | 15 --------------- sound/soc/codecs/cs35l56.c | 6 +++++- 4 files changed, 5 insertions(+), 23 deletions(-) diff --git a/sound/hda/codecs/side-codecs/Kconfig b/sound/hda/codecs/side-codecs/Kconfig index b7e2a6fa425881..3c36c82fe0a732 100644 --- a/sound/hda/codecs/side-codecs/Kconfig +++ b/sound/hda/codecs/side-codecs/Kconfig @@ -116,7 +116,6 @@ menu "CS35L56 driver options" config SND_HDA_SCODEC_CS35L56_CAL_DEBUGFS bool "CS35L56 create debugfs for factory calibration" depends on DEBUG_FS - select SND_SOC_CS35L56_CAL_DEBUGFS_COMMON help Create debugfs entries used during factory-line manufacture for factory calibration. diff --git a/sound/soc/codecs/Kconfig b/sound/soc/codecs/Kconfig index c353c54465d3f0..169427d43898fb 100644 --- a/sound/soc/codecs/Kconfig +++ b/sound/soc/codecs/Kconfig @@ -911,16 +911,12 @@ config SND_SOC_CS35L56_SDW help Enable support for Cirrus Logic CS35L56 boosted amplifier with SoundWire control -config SND_SOC_CS35L56_CAL_DEBUGFS_COMMON - bool - menu "CS35L56 driver options" depends on SND_SOC_CS35L56 config SND_SOC_CS35L56_CAL_DEBUGFS bool "CS35L56 create debugfs for factory calibration" depends on DEBUG_FS - select SND_SOC_CS35L56_CAL_DEBUGFS_COMMON help Create debugfs entries used during factory-line manufacture for factory calibration. @@ -929,7 +925,6 @@ config SND_SOC_CS35L56_CAL_DEBUGFS config SND_SOC_CS35L56_CAL_SET_CTRL bool "CS35L56 ALSA control to restore factory calibration" - select SND_SOC_CS35L56_CAL_DEBUGFS_COMMON help Allow restoring factory calibration data through an ALSA control. This is only needed on platforms without UEFI or @@ -942,7 +937,6 @@ config SND_SOC_CS35L56_CAL_SET_CTRL config SND_SOC_CS35L56_CAL_PERFORM_CTRL bool "CS35L56 ALSA control to perform factory calibration" - select SND_SOC_CS35L56_CAL_DEBUGFS_COMMON help Allow performing factory calibration data through an ALSA control. It is recommended to use the debugfs method instead diff --git a/sound/soc/codecs/cs35l56-shared.c b/sound/soc/codecs/cs35l56-shared.c index 329351de32b167..f7374afb709781 100644 --- a/sound/soc/codecs/cs35l56-shared.c +++ b/sound/soc/codecs/cs35l56-shared.c @@ -1084,9 +1084,6 @@ ssize_t cs35l56_calibrate_debugfs_write(struct cs35l56_base *cs35l56_base, char buf[11] = { 0 }; int num_amps, ret; - if (!IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS_COMMON)) - return -ENXIO; - if (*ppos) return -EINVAL; @@ -1139,9 +1136,6 @@ ssize_t cs35l56_cal_ambient_debugfs_write(struct cs35l56_base *cs35l56_base, unsigned long val; int ret; - if (!IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS_COMMON)) - return -ENXIO; - if (*ppos) return -EINVAL; @@ -1170,9 +1164,6 @@ ssize_t cs35l56_cal_data_debugfs_read(struct cs35l56_base *cs35l56_base, char __user *to, size_t count, loff_t *ppos) { - if (!IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS_COMMON)) - return -ENXIO; - if (!cs35l56_base->cal_data_valid) return 0; @@ -1188,9 +1179,6 @@ ssize_t cs35l56_cal_data_debugfs_write(struct cs35l56_base *cs35l56_base, struct cirrus_amp_cal_data cal_data; int ret; - if (!IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS_COMMON)) - return -ENXIO; - /* Only allow a full blob to be written */ if (*ppos || (count != sizeof(cal_data))) return -EMSGSIZE; @@ -1210,9 +1198,6 @@ EXPORT_SYMBOL_NS_GPL(cs35l56_cal_data_debugfs_write, "SND_SOC_CS35L56_SHARED"); void cs35l56_create_cal_debugfs(struct cs35l56_base *cs35l56_base, const struct cs35l56_cal_debugfs_fops *fops) { - if (!IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS_COMMON)) - return; - cs35l56_base->debugfs = cs_amp_create_debugfs(cs35l56_base->dev); debugfs_create_file("calibrate", diff --git a/sound/soc/codecs/cs35l56.c b/sound/soc/codecs/cs35l56.c index 0ea8c69d93fc11..34588245a8f31e 100644 --- a/sound/soc/codecs/cs35l56.c +++ b/sound/soc/codecs/cs35l56.c @@ -43,6 +43,10 @@ #include "wm_adsp.h" #include "cs35l56.h" +static bool cs35l56_allow_factory_cal = IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS); +module_param_named(allow_factory_cal, cs35l56_allow_factory_cal, bool, 0444); +MODULE_PARM_DESC(allow_factory_cal, "Enable support for factory calibration"); + /* * snd_soc_register_component() can call component_probe() on all instances * in a card, so deferred registration must be protected across all instances. @@ -1532,7 +1536,7 @@ static int _cs35l56_component_probe(struct snd_soc_component *component) if (ret) return ret; - if (IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS)) + if (cs35l56_allow_factory_cal) cs35l56_create_cal_debugfs(&cs35l56->base, &cs35l56_cal_debugfs_fops); queue_work(cs35l56->dsp_wq, &cs35l56->dsp_work); From 003beae76817f704dfb5322b95405a425d82ee6d Mon Sep 17 00:00:00 2001 From: Arina Kharlamova Date: Tue, 1 Dec 2026 02:57:10 +0400 Subject: [PATCH 2090/2102] ASoC: wm8993: Fix unbalanced regulator disables on remove The supplies are enabled during probe only to identify and reset the device, and disabled again before the component is registered. After that they are owned by wm8993_set_bias_level(), which enables them on the OFF to STANDBY transition and disables them again in OFF. wm8993_i2c_remove() still calls regulator_bulk_disable() on top of this. With no card bound the supplies are already off, so the regulator core warns about unbalanced disables on every unbind. With a card bound and the codec in STANDBY it cuts the supplies while the component is still registered, and the later OFF transition, run when devres unregisters the component, then warns. The error path after a failed component registration disables them a second time in the same way. Drop the disable from remove() and from that error path. Fixes: bfea3abb804f ("ASoC: Move WM8993 resource acquisition and device reset to bus probe") Signed-off-by: Arina Kharlamova Reviewed-by: Charles Keepax Link: https://patch.msgid.link/20261201-s2p-d101-v1-1-84a6b2587e74@mbzuai.ac.ae Signed-off-by: Mark Brown --- sound/soc/codecs/wm8993.c | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/sound/soc/codecs/wm8993.c b/sound/soc/codecs/wm8993.c index fbadbb33b6079d..f84736bb5d26f6 100644 --- a/sound/soc/codecs/wm8993.c +++ b/sound/soc/codecs/wm8993.c @@ -1729,14 +1729,13 @@ static int wm8993_i2c_probe(struct i2c_client *i2c) &soc_component_dev_wm8993, &wm8993_dai, 1); if (ret != 0) { dev_err(&i2c->dev, "Failed to register CODEC: %d\n", ret); - goto err_irq; + if (i2c->irq) + free_irq(i2c->irq, wm8993); + return ret; } return 0; -err_irq: - if (i2c->irq) - free_irq(i2c->irq, wm8993); err_enable: regulator_bulk_disable(ARRAY_SIZE(wm8993->supplies), wm8993->supplies); return ret; @@ -1748,7 +1747,6 @@ static void wm8993_i2c_remove(struct i2c_client *i2c) if (i2c->irq) free_irq(i2c->irq, wm8993); - regulator_bulk_disable(ARRAY_SIZE(wm8993->supplies), wm8993->supplies); } static const struct i2c_device_id wm8993_i2c_id[] = { From c187d0ead70a82ee0194dc7602ec216e25753164 Mon Sep 17 00:00:00 2001 From: Arina Kharlamova Date: Tue, 1 Dec 2026 02:56:00 +0400 Subject: [PATCH 2091/2102] ASoC: rockchip: rockchip_sai: Fix hclk and runtime PM handling in probe Probe powers the device up by calling rockchip_sai_runtime_resume() directly, but runtime PM is not told about it and the status stays suspended. The pm_runtime_put() at the end of probe then does nothing, so the mclk and hclk enables taken by that call are never dropped: both clocks stay on while the device is idle, and mclk stays on after unbind. hclk is also got with devm_clk_get_enabled(), although probe drops its own enable with clk_disable_unprepare() once the device is registered, so devres disables it a second time at unbind. With CONFIG_PM the two bugs cancel out for hclk; without it hclk is disabled once too often. Get hclk with devm_clk_get() and enable it by hand, as before the conversion, and disable it on the probe error paths. Resume the device first, mark it active and only then enable runtime PM. Use pm_runtime_put_sync() on the error path, so the device is suspended before devres disables runtime PM. The two fixes go together: either one alone leaves hclk unbalanced. Fixes: cc78d1eaabad ("ASoC: rockchip: add Serial Audio Interface (SAI) driver") Fixes: 03b778d19948 ("ASOC: rockchip: Use helper function devm_clk_get_enabled()") Signed-off-by: Arina Kharlamova Reviewed-by: bui duc phuc Link: https://patch.msgid.link/20261201-s2p-d08-v1-1-e6905d3dc4e7@mbzuai.ac.ae Signed-off-by: Mark Brown --- sound/soc/rockchip/rockchip_sai.c | 34 +++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/sound/soc/rockchip/rockchip_sai.c b/sound/soc/rockchip/rockchip_sai.c index b625d69f76c814..866b68cc706c13 100644 --- a/sound/soc/rockchip/rockchip_sai.c +++ b/sound/soc/rockchip/rockchip_sai.c @@ -1459,20 +1459,30 @@ static int rockchip_sai_probe(struct platform_device *pdev) return dev_err_probe(&pdev->dev, PTR_ERR(sai->mclk), "Failed to get mclk\n"); - sai->hclk = devm_clk_get_enabled(&pdev->dev, "hclk"); + sai->hclk = devm_clk_get(&pdev->dev, "hclk"); if (IS_ERR(sai->hclk)) return dev_err_probe(&pdev->dev, PTR_ERR(sai->hclk), "Failed to get hclk\n"); + /* + * hclk is only needed until runtime PM takes over below, so it is + * enabled by hand and not with devm_clk_get_enabled(). + */ + ret = clk_prepare_enable(sai->hclk); + if (ret) + return dev_err_probe(&pdev->dev, ret, "Failed to enable hclk\n"); + regmap_read(sai->regmap, SAI_VERSION, &sai->version); ret = rockchip_sai_init_dai(sai, res, &dai); - if (ret) - return dev_err_probe(&pdev->dev, ret, "Failed to initialize DAI\n"); + if (ret) { + dev_err_probe(&pdev->dev, ret, "Failed to initialize DAI\n"); + goto err_disable_hclk; + } ret = rockchip_sai_parse_paths(sai, node); if (ret) - return ret; + goto err_disable_hclk; /* * From here on, all register accesses need to be wrapped in @@ -1480,11 +1490,15 @@ static int rockchip_sai_probe(struct platform_device *pdev) * * NB: we don't rely on _resume_and_get in case of !CONFIG_PM */ - devm_pm_runtime_enable(&pdev->dev); - pm_runtime_get_noresume(&pdev->dev); ret = rockchip_sai_runtime_resume(&pdev->dev); - if (ret) - return dev_err_probe(&pdev->dev, ret, "Failed to resume device\n"); + if (ret) { + dev_err_probe(&pdev->dev, ret, "Failed to resume device\n"); + goto err_disable_hclk; + } + + pm_runtime_set_active(&pdev->dev); + pm_runtime_get_noresume(&pdev->dev); + devm_pm_runtime_enable(&pdev->dev); ret = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (ret) @@ -1505,9 +1519,11 @@ static int rockchip_sai_probe(struct platform_device *pdev) err_runtime_suspend: if (IS_ENABLED(CONFIG_PM)) - pm_runtime_put(&pdev->dev); + pm_runtime_put_sync(&pdev->dev); else rockchip_sai_runtime_suspend(&pdev->dev); +err_disable_hclk: + clk_disable_unprepare(sai->hclk); return ret; } From e648012fd3211f6a07c43fa96bda6f89ad6efbc1 Mon Sep 17 00:00:00 2001 From: Arun Iyengar Date: Mon, 30 Nov 2026 20:21:21 +0000 Subject: [PATCH 2092/2102] regmap: Don't free the bus context when devm init fails Since the devres is added after __regmap_init(), a failure to add it runs regmap_exit(), which frees the bus context. Callers that free their context when __devm_regmap_init() fails (spi-avmm, sch56xx) then free it twice. Allocate the devres before __regmap_init() again. Fixes: b1ef855c6260 ("regmap: Simplify devres handling") Signed-off-by: Arun Iyengar Reviewed-by: Peng Fan Link: https://patch.msgid.link/20261130-regmap-devm-ctx-v1-1-cfabbeaadee8@gmail.com Signed-off-by: Mark Brown --- drivers/base/regmap/regmap.c | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/drivers/base/regmap/regmap.c b/drivers/base/regmap/regmap.c index 83f1f59421356f..d0bde9bcaffbde 100644 --- a/drivers/base/regmap/regmap.c +++ b/drivers/base/regmap/regmap.c @@ -1181,9 +1181,9 @@ struct regmap *__regmap_init(struct device *dev, } EXPORT_SYMBOL_GPL(__regmap_init); -static void devm_regmap_release(void *regmap) +static void devm_regmap_release(struct device *dev, void *res) { - regmap_exit(regmap); + regmap_exit(*(struct regmap **)res); } struct regmap *__devm_regmap_init(struct device *dev, @@ -1193,17 +1193,21 @@ struct regmap *__devm_regmap_init(struct device *dev, struct lock_class_key *lock_key, const char *lock_name) { - struct regmap *regmap; - int ret; + struct regmap **ptr, *regmap; + + ptr = devres_alloc(devm_regmap_release, sizeof(*ptr), GFP_KERNEL); + if (!ptr) + return ERR_PTR(-ENOMEM); regmap = __regmap_init(dev, bus, bus_context, config, lock_key, lock_name); - if (IS_ERR(regmap)) + if (IS_ERR(regmap)) { + devres_free(ptr); return regmap; + } - ret = devm_add_action_or_reset(dev, devm_regmap_release, regmap); - if (ret) - return ERR_PTR(ret); + *ptr = regmap; + devres_add(dev, ptr); return regmap; } From a0ca2536454a1b4af16d388993e3278ed7089f04 Mon Sep 17 00:00:00 2001 From: Arun Iyengar Date: Mon, 30 Nov 2026 20:21:22 +0000 Subject: [PATCH 2093/2102] regmap: mmio: Free the context if regmap init fails The MMIO context is freed only by regmap_exit(), so it leaks, together with its prepared clock, when __regmap_init() or __devm_regmap_init() fails. Free it on that error. The devm part needs the previous patch: without it a failed devres add has already freed the context. Fixes: 45f5ff8107a8 ("regmap: add MMIO bus support") Signed-off-by: Arun Iyengar Reviewed-by: Peng Fan Link: https://patch.msgid.link/20261130-regmap-devm-ctx-v1-2-cfabbeaadee8@gmail.com Signed-off-by: Mark Brown --- drivers/base/regmap/regmap-mmio.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/drivers/base/regmap/regmap-mmio.c b/drivers/base/regmap/regmap-mmio.c index 1de2278fa572d2..e696a9bce8212a 100644 --- a/drivers/base/regmap/regmap-mmio.c +++ b/drivers/base/regmap/regmap-mmio.c @@ -559,13 +559,18 @@ struct regmap *__regmap_init_mmio_clk(struct device *dev, const char *clk_id, const char *lock_name) { struct regmap_mmio_context *ctx; + struct regmap *map; ctx = regmap_mmio_gen_context(dev, clk_id, regs, config); if (IS_ERR(ctx)) return ERR_CAST(ctx); - return __regmap_init(dev, ®map_mmio, ctx, config, - lock_key, lock_name); + map = __regmap_init(dev, ®map_mmio, ctx, config, + lock_key, lock_name); + if (IS_ERR(map)) + regmap_mmio_free_context(ctx); + + return map; } EXPORT_SYMBOL_GPL(__regmap_init_mmio_clk); @@ -577,13 +582,18 @@ struct regmap *__devm_regmap_init_mmio_clk(struct device *dev, const char *lock_name) { struct regmap_mmio_context *ctx; + struct regmap *map; ctx = regmap_mmio_gen_context(dev, clk_id, regs, config); if (IS_ERR(ctx)) return ERR_CAST(ctx); - return __devm_regmap_init(dev, ®map_mmio, ctx, config, - lock_key, lock_name); + map = __devm_regmap_init(dev, ®map_mmio, ctx, config, + lock_key, lock_name); + if (IS_ERR(map)) + regmap_mmio_free_context(ctx); + + return map; } EXPORT_SYMBOL_GPL(__devm_regmap_init_mmio_clk); From 21da9972e6056d9b194829c4218cd92972ca1797 Mon Sep 17 00:00:00 2001 From: HyeongJun An Date: Mon, 30 Nov 2026 17:54:14 +0900 Subject: [PATCH 2094/2102] selftests/alsa: Check that dB scaled controls are named Volume control-names.rst gives Volume as the function of a control that sets a gain, and new drivers keep naming such controls "... Gain" or similar. mixer-test only checks the Switch suffix, so it does not report them. Fail the name test for a writeable integer control that has a dB scale but does not end in " Volume". Read-only controls such as meters are left alone. Signed-off-by: HyeongJun An Link: https://patch.msgid.link/20261130085414.1348615-1-sammiee5311@gmail.com Signed-off-by: Takashi Iwai --- tools/testing/selftests/alsa/mixer-test.c | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tools/testing/selftests/alsa/mixer-test.c b/tools/testing/selftests/alsa/mixer-test.c index 966ef83354b979..eabbe8dfd1c9fa 100644 --- a/tools/testing/selftests/alsa/mixer-test.c +++ b/tools/testing/selftests/alsa/mixer-test.c @@ -490,6 +490,21 @@ static bool strend(const char *haystack, const char *needle) return strcmp(haystack + haystack_len - needle_len, needle) == 0; } +static bool ctl_has_db_scale(struct ctl_data *ctl) +{ + unsigned int tlv[256]; + long min, max; + + if (!snd_ctl_elem_info_is_tlv_readable(ctl->info)) + return false; + if (snd_ctl_elem_tlv_read(ctl->card->handle, ctl->id, tlv, sizeof(tlv)) < 0) + return false; + + min = snd_ctl_elem_info_get_min(ctl->info); + max = snd_ctl_elem_info_get_max(ctl->info); + return snd_tlv_get_dB_range(tlv, min, max, &min, &max) == 0; +} + static void test_ctl_name(struct ctl_data *ctl) { bool name_ok = true; @@ -516,6 +531,16 @@ static void test_ctl_name(struct ctl_data *ctl) } } + /* Writeable integer controls with a dB scale should end in Volume */ + if (snd_ctl_elem_info_get_type(ctl->info) == SND_CTL_ELEM_TYPE_INTEGER && + snd_ctl_elem_info_is_writable(ctl->info) && ctl_has_db_scale(ctl)) { + if (!strend(ctl->name, " Volume")) { + ksft_print_msg("%d.%d %s has a dB scale but is not a Volume\n", + ctl->card->card, ctl->elem, ctl->name); + name_ok = false; + } + } + ksft_test_result(name_ok, "name.%s.%d\n", ctl->card->card_name, ctl->elem); } From 6c48bef573afe93d1d832ba31c348777388cd795 Mon Sep 17 00:00:00 2001 From: Eric Curtin Date: Mon, 30 Nov 2026 12:44:33 +0000 Subject: [PATCH 2095/2102] ALSA: virtio: report device xruns from the pointer callbacks The pointer callbacks stopped checking xfer_xrun when the ack callback was introduced, so an xrun event from the device was never reported. Return SNDRV_PCM_POS_XRUN when it is set. Fixes: fe981e67568c ("ALSA: virtio: use ack callback") Signed-off-by: Eric Curtin Link: https://patch.msgid.link/20261130124434.474178-1-ericcurtin17@gmail.com Signed-off-by: Takashi Iwai --- sound/virtio/virtio_pcm_ops.c | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/sound/virtio/virtio_pcm_ops.c b/sound/virtio/virtio_pcm_ops.c index 1091100a4c982b..a4b944a8a48482 100644 --- a/sound/virtio/virtio_pcm_ops.c +++ b/sound/virtio/virtio_pcm_ops.c @@ -435,17 +435,26 @@ static int virtsnd_pcm_sync_stop(struct snd_pcm_substream *substream) * substream for playback. * @substream: Kernel ALSA substream. * - * Context: Any context. - * Return: Hardware position in frames inside [0 ... buffer_size) range. + * Context: Any context. Takes and releases the VirtIO substream spinlock. + * Return: Hardware position in frames inside [0 ... buffer_size) range, or + * SNDRV_PCM_POS_XRUN if the device reported an xrun. */ static snd_pcm_uframes_t virtsnd_pcm_pb_pointer(struct snd_pcm_substream *substream) { struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream); + size_t hw_ptr; + + scoped_guard(spinlock_irqsave, &vss->lock) { + if (vss->xfer_xrun) + return SNDRV_PCM_POS_XRUN; + + hw_ptr = vss->hw_ptr; + } return snd_pcm_indirect_playback_pointer(substream, &vss->pcm_indirect, - vss->hw_ptr); + hw_ptr); } /** @@ -453,17 +462,26 @@ virtsnd_pcm_pb_pointer(struct snd_pcm_substream *substream) * substream for capture. * @substream: Kernel ALSA substream. * - * Context: Any context. - * Return: Hardware position in frames inside [0 ... buffer_size) range. + * Context: Any context. Takes and releases the VirtIO substream spinlock. + * Return: Hardware position in frames inside [0 ... buffer_size) range, or + * SNDRV_PCM_POS_XRUN if the device reported an xrun. */ static snd_pcm_uframes_t virtsnd_pcm_cp_pointer(struct snd_pcm_substream *substream) { struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream); + size_t hw_ptr; + + scoped_guard(spinlock_irqsave, &vss->lock) { + if (vss->xfer_xrun) + return SNDRV_PCM_POS_XRUN; + + hw_ptr = vss->hw_ptr; + } return snd_pcm_indirect_capture_pointer(substream, &vss->pcm_indirect, - vss->hw_ptr); + hw_ptr); } static void virtsnd_pcm_trans_copy(struct snd_pcm_substream *substream, From a24cf91bbe74211875a4c05723dba1ffafcc44ed Mon Sep 17 00:00:00 2001 From: HyeongJun An Date: Wed, 2 Dec 2026 16:32:12 +0900 Subject: [PATCH 2096/2102] ALSA: seq: ump: Don't leave the bank LSB in a MIDI 1.0 program change The cvt_ump_midi2_to_midi1() sends a MIDI 2.0 program change with a valid bank as two bank select CCs and a program change, all built in the same packet. The CC data byte is the reserved byte of a MIDI 1.0 program change, so the program change keeps the bank LSB there: MIDI 2.0: 0x40c00001 0x05000102 (program 5, bank 1/2) MIDI 1.0: 0x20b00001, 0x20b02002, 0x20c00502 A UMP MIDI 1.0 client then gets a program change with a non-zero reserved byte. Clear it before the program change is sent. Fixes: 8a42886cae30 ("ALSA: seq: Fix missing bank setup between MIDI1/MIDI2 UMP conversion") Signed-off-by: HyeongJun An Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261202073215.2588603-2-sammiee5311@gmail.com --- sound/core/seq/seq_ump_convert.c | 1 + 1 file changed, 1 insertion(+) diff --git a/sound/core/seq/seq_ump_convert.c b/sound/core/seq/seq_ump_convert.c index e76fdb54df175a..602afb5a0f285e 100644 --- a/sound/core/seq/seq_ump_convert.c +++ b/sound/core/seq/seq_ump_convert.c @@ -520,6 +520,7 @@ static int cvt_ump_midi2_to_midi1(struct snd_seq_client *dest, if (err < 0) return err; midi1->note.status = midi2->note.status; + midi1->cc.data = 0; } midi1->pg.program = midi2->pg.program; break; From 36bb3c7cb020fc1c4095246c104556ceaba0401f Mon Sep 17 00:00:00 2001 From: HyeongJun An Date: Wed, 2 Dec 2026 16:32:13 +0900 Subject: [PATCH 2097/2102] selftests/alsa: Test the sequencer UMP bank and program change conversion Check that a bank select from a legacy client goes to a UMP MIDI 2.0 client with the next program change, sent as CCs and as CONTROL14. For the CCs, also check that the program change after that has no bank, and that a later bank select LSB keeps the MSB. The latter was fixed by commit a200df7deb31 ("ALSA: seq: Don't clear bank selection at event -> UMP MIDI2 conversion"). Also check the bank of a program change between UMP MIDI 1.0 and MIDI 2.0 clients. ump_midi2_to_midi1_program fails without "ALSA: seq: ump: Don't leave the bank LSB in a MIDI 1.0 program change". Signed-off-by: HyeongJun An Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261202073215.2588603-3-sammiee5311@gmail.com --- tools/testing/selftests/alsa/seq-ump-test.c | 64 ++++++++++++++++++++- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/tools/testing/selftests/alsa/seq-ump-test.c b/tools/testing/selftests/alsa/seq-ump-test.c index 7030d061dfae89..f2051777a9dc54 100644 --- a/tools/testing/selftests/alsa/seq-ump-test.c +++ b/tools/testing/selftests/alsa/seq-ump-test.c @@ -4,8 +4,8 @@ * packets between MIDI 1.0 and MIDI 2.0 clients. * * A client sends events to a UMP client, and the test checks the packets - * that the UMP client receives. The converter keeps its RPN/NRPN state - * per destination port and channel, so each test uses new clients. + * that the UMP client receives. The converter keeps its RPN/NRPN and bank + * state per destination port and channel, so each test uses new clients. */ #include #include @@ -232,6 +232,8 @@ struct event { { SNDRV_SEQ_EVENT_CONTROLLER, ch, param, value } #define C14(ch, param, value) \ { SNDRV_SEQ_EVENT_CONTROL14, ch, param, value } +#define PGM(ch, value) \ + { SNDRV_SEQ_EVENT_PGMCHANGE, ch, 0, value } static int send_events(struct seq_client *src, struct seq_client *dst, const struct event *ev, int n) @@ -482,6 +484,26 @@ TEST_F(seq_ump, key_pressure) EXPECT_PACKETS({ 0x40a24000, 0 }); } +/* + * A bank select goes with the next program change only, and a later + * bank select LSB keeps the MSB + */ +TEST_F(seq_ump, program_bank) +{ + SEND(CC(0, 0, 1), CC(0, 32, 2), PGM(0, 5)); + SEND(CC(0, 32, 3), PGM(0, 6), PGM(0, 7)); + EXPECT_PACKETS({ 0x40c00001, 0x05000102 }, + { 0x40c00001, 0x06000103 }, + { 0x40c00000, 0x07000000 }); +} + +/* the same with the bank select sent as CONTROL14 */ +TEST_F(seq_ump, c14_program_bank) +{ + SEND(C14(7, 0, (3 << 7) | 4), PGM(7, 9)); + EXPECT_PACKETS({ 0x40c70001, 0x09000304 }); +} + /* a UMP MIDI 1.0 client gets the CCs as they are, RPN selection included */ TEST(midi1_passthrough) { @@ -640,4 +662,42 @@ TEST_F(seq_pair, ump_midi2_to_midi1_rpn) { 0x20b10609, 0 }, { 0x20b1260d, 0 }); } +/* UMP MIDI 1.0 to MIDI 2.0: the bank select CCs go into the program change */ +TEST_F(seq_pair, ump_midi1_to_midi2_program) +{ + int skip = 0; + int err; + + err = open_pair(&self->dst, SNDRV_SEQ_CLIENT_UMP_MIDI_2_0, + &self->src, SNDRV_SEQ_CLIENT_UMP_MIDI_1_0, &skip); + if (skip) + SKIP(return, "UMP sequencer client unavailable: %s", + strerror(-err)); + ASSERT_EQ(0, err); + + SEND_UMP(0x20b00001, 0); + SEND_UMP(0x20b02002, 0); + SEND_UMP(0x20c00500, 0); + EXPECT_PACKETS({ 0x40c00001, 0x05000102 }); +} + +/* UMP MIDI 2.0 to MIDI 1.0: a program change with a bank is three messages */ +TEST_F(seq_pair, ump_midi2_to_midi1_program) +{ + int skip = 0; + int err; + + err = open_pair(&self->dst, SNDRV_SEQ_CLIENT_UMP_MIDI_1_0, + &self->src, SNDRV_SEQ_CLIENT_UMP_MIDI_2_0, &skip); + if (skip) + SKIP(return, "UMP sequencer client unavailable: %s", + strerror(-err)); + ASSERT_EQ(0, err); + + SEND_UMP(0x40c00001, 0x05000102); + SEND_UMP(0x40c00000, 0x06000000); + EXPECT_MT_PACKETS(2, { 0x20b00001, 0 }, { 0x20b02002, 0 }, + { 0x20c00500, 0 }, { 0x20c00600, 0 }); +} + TEST_HARNESS_MAIN From 35392688dbe802de09b4d2ec38feef4342e275f9 Mon Sep 17 00:00:00 2001 From: HyeongJun An Date: Wed, 2 Dec 2026 16:32:14 +0900 Subject: [PATCH 2098/2102] selftests/alsa: Test the sequencer UMP SysEx conversion Check that a SysEx event from a legacy client reaches a UMP client as one packet with up to six data bytes, and as start, continue and end packets when it is longer. Also check that a SysEx split over two events continues in the second one. The six data bytes in the first packet come from commit 952b13c21523 ("ALSA: seq: ump: Optimize conversions from SysEx to UMP"). Signed-off-by: HyeongJun An Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261202073215.2588603-4-sammiee5311@gmail.com --- tools/testing/selftests/alsa/seq-ump-test.c | 67 +++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/tools/testing/selftests/alsa/seq-ump-test.c b/tools/testing/selftests/alsa/seq-ump-test.c index f2051777a9dc54..a0855dd451c2a1 100644 --- a/tools/testing/selftests/alsa/seq-ump-test.c +++ b/tools/testing/selftests/alsa/seq-ump-test.c @@ -145,6 +145,34 @@ static int send_note(struct seq_client *src, struct seq_client *dst, return 0; } +/* send a SYSEX event, with the data after the event in the same write */ +static int send_sysex(struct seq_client *src, struct seq_client *dst, + const unsigned char *data, int len) +{ + struct { + struct snd_seq_event ev; + unsigned char data[32]; + } buf; + int size = sizeof(buf.ev) + len; + + if (len > (int)sizeof(buf.data)) + return -EINVAL; + memset(&buf, 0, sizeof(buf)); + buf.ev.type = SNDRV_SEQ_EVENT_SYSEX; + buf.ev.flags = SNDRV_SEQ_TIME_STAMP_TICK | + SNDRV_SEQ_EVENT_LENGTH_VARIABLE; + buf.ev.queue = SNDRV_SEQ_QUEUE_DIRECT; + buf.ev.source.client = src->id; + buf.ev.source.port = src->port; + buf.ev.dest.client = dst->id; + buf.ev.dest.port = dst->port; + buf.ev.data.ext.len = len; + memcpy(buf.data, data, len); + if (write(src->fd, &buf, size) != size) + return -errno; + return 0; +} + /* send a UMP packet from a UMP client */ static int send_ump(struct seq_client *src, struct seq_client *dst, unsigned int w0, unsigned int w1) @@ -286,6 +314,13 @@ static int send_events(struct seq_client *src, struct seq_client *dst, #define SEND_UMP(w0, w1) \ ASSERT_EQ(0, send_ump(&self->src, &self->dst, w0, w1)) +#define SEND_SYSEX(...) do { \ + const unsigned char data[] = { __VA_ARGS__ }; \ + \ + ASSERT_EQ(0, send_sysex(&self->src, &self->dst, data, \ + sizeof(data))); \ +} while (0) + /* RPN 0/1 with Data Entry */ TEST_F(seq_ump, rpn) { @@ -504,6 +539,38 @@ TEST_F(seq_ump, c14_program_bank) EXPECT_PACKETS({ 0x40c70001, 0x09000304 }); } +/* SysEx of up to six data bytes goes in one packet */ +TEST_F(seq_ump, sysex_short) +{ + SEND_SYSEX(0xf0, 0x01, 0x02, 0x03, 0xf7); + SEND_SYSEX(0xf0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xf7); + EXPECT_MT_PACKETS(3, { 0x30030102, 0x03000000 }, + { 0x30060102, 0x03040506 }); +} + +/* longer SysEx goes in start, continue and end packets of six data bytes */ +TEST_F(seq_ump, sysex_long) +{ + SEND_SYSEX(0xf0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xf7); + SEND_SYSEX(0xf0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0xf7); + EXPECT_MT_PACKETS(3, { 0x30160102, 0x03040506 }, + { 0x30310700, 0 }, + { 0x30160102, 0x03040506 }, + { 0x30260708, 0x090a0b0c }, + { 0x30310d00, 0 }); +} + +/* SysEx sent in two events continues in the second one */ +TEST_F(seq_ump, sysex_split) +{ + SEND_SYSEX(0xf0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08); + SEND_SYSEX(0x09, 0x0a, 0xf7); + EXPECT_MT_PACKETS(3, { 0x30160102, 0x03040506 }, + { 0x30220708, 0 }, + { 0x3032090a, 0 }); +} + /* a UMP MIDI 1.0 client gets the CCs as they are, RPN selection included */ TEST(midi1_passthrough) { From c8671035affa867c5831f344371731fd3a4c426c Mon Sep 17 00:00:00 2001 From: HyeongJun An Date: Wed, 2 Dec 2026 16:32:15 +0900 Subject: [PATCH 2099/2102] selftests/alsa: Test the sequencer UMP system message conversion Check that a song position, a song select and a system reset from a legacy client reach UMP MIDI 1.0 and MIDI 2.0 clients as UMP system packets, with the song position LSB first and both of its bytes. These were fixed by commit edb32776196a ("ALSA: seq: Fix incorrect UMP type for system messages"), commit 700fe6fd093d ("ALSA: seq: Fix yet another spot for system message conversion"), commit 310fa3ec2859 ("ALSA: seq: ump: Fix swapped song position pointer data"), commit 9d65ab6050d2 ("ALSA: seq: Fix missing MSB in MIDI2 SPP conversion") for the MIDI 2.0 client, and commit 55fac50ea46f ("ALSA: seq: ump: Fix missing System Reset message handling"). Signed-off-by: HyeongJun An Signed-off-by: Takashi Iwai Link: https://patch.msgid.link/20261202073215.2588603-5-sammiee5311@gmail.com --- tools/testing/selftests/alsa/seq-ump-test.c | 28 +++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tools/testing/selftests/alsa/seq-ump-test.c b/tools/testing/selftests/alsa/seq-ump-test.c index a0855dd451c2a1..5745cfd522972f 100644 --- a/tools/testing/selftests/alsa/seq-ump-test.c +++ b/tools/testing/selftests/alsa/seq-ump-test.c @@ -262,6 +262,8 @@ struct event { { SNDRV_SEQ_EVENT_CONTROL14, ch, param, value } #define PGM(ch, value) \ { SNDRV_SEQ_EVENT_PGMCHANGE, ch, 0, value } +#define SYS(type, value) \ + { SNDRV_SEQ_EVENT_##type, 0, 0, value } static int send_events(struct seq_client *src, struct seq_client *dst, const struct event *ev, int n) @@ -571,6 +573,14 @@ TEST_F(seq_ump, sysex_split) { 0x3032090a, 0 }); } +/* system messages are UMP system packets, with both song position bytes */ +TEST_F(seq_ump, system) +{ + SEND(SYS(SONGPOS, 0x1234), SYS(SONGSEL, 5), SYS(RESET, 0)); + EXPECT_MT_PACKETS(1, { 0x10f23424, 0 }, { 0x10f30500, 0 }, + { 0x10ff0000, 0 }); +} + /* a UMP MIDI 1.0 client gets the CCs as they are, RPN selection included */ TEST(midi1_passthrough) { @@ -729,6 +739,24 @@ TEST_F(seq_pair, ump_midi2_to_midi1_rpn) { 0x20b10609, 0 }, { 0x20b1260d, 0 }); } +/* the same system messages to a UMP MIDI 1.0 client */ +TEST_F(seq_pair, midi1_system) +{ + int skip = 0; + int err; + + err = open_pair(&self->dst, SNDRV_SEQ_CLIENT_UMP_MIDI_1_0, + &self->src, 0, &skip); + if (skip) + SKIP(return, "UMP sequencer client unavailable: %s", + strerror(-err)); + ASSERT_EQ(0, err); + + SEND(SYS(SONGPOS, 0x1234), SYS(SONGSEL, 5), SYS(RESET, 0)); + EXPECT_MT_PACKETS(1, { 0x10f23424, 0 }, { 0x10f30500, 0 }, + { 0x10ff0000, 0 }); +} + /* UMP MIDI 1.0 to MIDI 2.0: the bank select CCs go into the program change */ TEST_F(seq_pair, ump_midi1_to_midi2_program) { From e9be4c8cd79850b70a8fc35c0cb52c837fb4ddfd Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Wed, 2 Dec 2026 08:39:16 +0000 Subject: [PATCH 2100/2102] ALSA: hda: Fix shortname truncation warning The shortname truncation check uses '>' instead of '>='. As a result, the warning is skipped when the source string length exactly matches the destination buffer size. Use '>=' to correctly detect this truncation case. Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261202083916.3399-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/controllers/acpi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/hda/controllers/acpi.c b/sound/hda/controllers/acpi.c index bad32a5c1ae924..91dd9a9a08bd38 100644 --- a/sound/hda/controllers/acpi.c +++ b/sound/hda/controllers/acpi.c @@ -136,7 +136,7 @@ static int hda_acpi_init(struct hda_acpi *hda) sname = hda->data->short_name ? hda->data->short_name : KBUILD_MODNAME; - if (strlen(sname) > sizeof(card->shortname)) + if (strlen(sname) >= sizeof(card->shortname)) dev_info(dev, "truncating shortname for card %s\n", sname); strscpy(card->shortname, sname); From ba80fcd7bf489ef6b854c0f3623fb4df4986e72f Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Wed, 2 Dec 2026 13:40:28 +0000 Subject: [PATCH 2101/2102] ALSA: hda: cix-ipbloq: Fix shortname truncation warning The shortname truncation check uses '>' instead of '>='. When the source string length exactly matches the destination buffer size, strscpy() truncates the string, but the warning is not printed. Use '>=' to correctly detect this truncation case. Fixes: d91e9bd10125 ("ALSA: hda: add CIX IPBLOQ HDA controller support") Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261202134028.3369-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/controllers/cix-ipbloq.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/hda/controllers/cix-ipbloq.c b/sound/hda/controllers/cix-ipbloq.c index c07098fc13403c..6983957d17c7ce 100644 --- a/sound/hda/controllers/cix-ipbloq.c +++ b/sound/hda/controllers/cix-ipbloq.c @@ -163,7 +163,7 @@ static int cix_ipbloq_hda_init(struct cix_ipbloq_hda *hda, sname = of_get_property(pdev->dev.of_node, "model", NULL); if (!sname) sname = drv_name; - if (strlen(sname) > sizeof(card->shortname)) + if (strlen(sname) >= sizeof(card->shortname)) dev_dbg(card->dev, "truncating shortname for card\n"); strscpy(card->shortname, sname, sizeof(card->shortname)); From a7d48fc278c3b77264b1e4acebac93dbd34b0ecf Mon Sep 17 00:00:00 2001 From: Sreeraj S Kurup Date: Wed, 2 Dec 2026 13:55:12 +0000 Subject: [PATCH 2102/2102] ALSA: hda: tegra: Fix shortname truncation warning The shortname truncation check uses '>' instead of '>='. When the source string length exactly matches the destination buffer size, strscpy() truncates the string, but the warning is not printed. Use '>=' to correctly detect this truncation case. Signed-off-by: Sreeraj S Kurup Link: https://patch.msgid.link/20261202135512.3768-1-sreekuttan2156239@gmail.com Signed-off-by: Takashi Iwai --- sound/hda/controllers/tegra.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/hda/controllers/tegra.c b/sound/hda/controllers/tegra.c index a765307c08f958..c1d8bcbfedf7e9 100644 --- a/sound/hda/controllers/tegra.c +++ b/sound/hda/controllers/tegra.c @@ -390,7 +390,7 @@ static int hda_tegra_first_init(struct azx *chip, struct platform_device *pdev) sname = of_get_property(np, "nvidia,model", NULL); if (!sname) sname = drv_name; - if (strlen(sname) > sizeof(card->shortname)) + if (strlen(sname) >= sizeof(card->shortname)) dev_info(card->dev, "truncating shortname for card\n"); strscpy(card->shortname, sname);